dev_prune/config.rs
1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4// Configuration and registry management for dev-prune.
5//
6// This module handles persistent storage of:
7// - Global settings (idle threshold, check interval, daemon toggle)
8// - Registered repository paths and their metadata
9//
10// All data is stored in `~/.config/dev-prune/registry.json`.
11
12use std::collections::{BTreeMap, HashMap, HashSet};
13use std::fs;
14use std::io::Write as _;
15use std::path::{Path, PathBuf};
16
17use anyhow::{Context, Result};
18use chrono::{DateTime, Utc};
19use serde::{Deserialize, Serialize};
20
21use crate::constants;
22
23/// Global settings that control prune behavior.
24#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
25pub struct Settings {
26 /// Number of inactive days before a repo is eligible for pruning.
27 pub idle_days: u64,
28 /// Interval in days between automated daemon checks.
29 pub check_interval_days: u64,
30 /// Whether the setup pass installs the OS scheduler. On by default.
31 pub auto_daemon: bool,
32 /// Whether the setup pass installs the global Git hooks. On by default.
33 #[serde(default = "default_auto_hooks")]
34 pub auto_hooks: bool,
35 /// Whether dev-prune installs its own missing integrations. On by default.
36 #[serde(default = "default_auto_setup")]
37 pub auto_setup: bool,
38 /// Whether `link` and `init` write a default `.devprune.json` into repositories
39 /// they register. Off by default; see [`constants::DEFAULT_AUTO_CONFIG`].
40 #[serde(default = "default_auto_config")]
41 pub auto_config: bool,
42 /// Whether interactive confirmation is required before pruning.
43 #[serde(default = "default_require_confirmation")]
44 pub require_confirmation: bool,
45 /// Timeout in seconds for lockfile enforcement / CLI commands (default 600s = 10m).
46 #[serde(default = "default_command_timeout_secs")]
47 pub command_timeout_secs: u64,
48 /// Smallest bloat directory worth deleting, in MiB. `0` disables the floor.
49 ///
50 /// Below this size the reinstall costs more than the space is worth, so the
51 /// directory is not offered as a candidate at all.
52 #[serde(default = "default_min_size_mb")]
53 pub min_size_mb: u64,
54 /// Whether dev-prune asks GitHub for the latest release from time to time.
55 ///
56 /// On by default, and opt-*out* rather than opt-in: an out-of-date cleanup tool is a
57 /// tool whose safety fixes you do not have. The request sends nothing but itself —
58 /// no identifier, no configuration, no usage data. Turn it off with
59 /// `devp config set update_check false`.
60 #[serde(default = "default_update_check")]
61 pub update_check: bool,
62 /// How many directory levels below a repository root discovery descends.
63 ///
64 /// Six by default. A flat repository never notices; a monorepo that nests projects
65 /// under `packages/@scope/name/app` does. Raise it when `devp status` does not list
66 /// a project you know is there, and remember that the walk gets more expensive with
67 /// every level. Clamped to [`constants::MAX_SCAN_DEPTH_LIMIT`].
68 #[serde(default = "default_scan_depth")]
69 pub scan_depth: usize,
70 /// Whether cargo and go may run the sync command that rewrites tracked manifests.
71 ///
72 /// Off. See [`constants::DEFAULT_ALLOW_MANIFEST_REWRITE`] — with this off, both are
73 /// verified read-only and a project with no lockfile at all is simply not pruned.
74 #[serde(default = "default_allow_manifest_rewrite")]
75 pub allow_manifest_rewrite: bool,
76 /// Days between automatic release checks.
77 ///
78 /// Only the *automatic* check honours this; `devp update` always asks, because you
79 /// are standing there waiting for the answer.
80 #[serde(default = "default_update_check_interval_days")]
81 pub update_check_interval_days: i64,
82 /// How long the release check waits for GitHub before giving up, in seconds.
83 ///
84 /// Five is right on a normal connection and too short behind some corporate proxies,
85 /// which is the whole reason this is a setting rather than a constant.
86 #[serde(default = "default_update_check_timeout_secs")]
87 pub update_check_timeout_secs: u64,
88 /// Whether the setup pass may install the Git hooks *in front of* another tool's.
89 ///
90 /// Off. With it on, a `core.hooksPath` that belongs to husky is not a reason to skip:
91 /// dev-prune takes the slot and forwards every hook back to the directory it
92 /// displaced. Behaviour-preserving, but it is still someone else's setup, so it is
93 /// asked for rather than assumed. Same thing as `devp hook install --chain`.
94 #[serde(default = "default_auto_hooks_chain")]
95 pub auto_hooks_chain: bool,
96 /// Whether the opt-in Cargo adapter is active. Off by default, and the reason is
97 /// the same one that keeps `enable_gradle` off: Rust's `target/` is compiler
98 /// output. `cargo metadata --locked` proves the *crates* come back from
99 /// `Cargo.lock`, but nothing downloads a compiled artefact — the directory returns
100 /// only by rebuilding, which on a large workspace is minutes rather than the
101 /// seconds a dependency reinstall costs. See [`crate::adapters::cargo_adapter`].
102 #[serde(default)]
103 pub enable_cargo: bool,
104 /// Whether the opt-in Gradle build-tool adapter is active. Off by default:
105 /// `build/` comes back by recompiling the project, so nobody should find it
106 /// deleted without having asked. See [`crate::adapters::gradle`].
107 #[serde(default)]
108 pub enable_gradle: bool,
109 /// Whether the opt-in Maven build-tool adapter is active. Off by default, for the
110 /// same reason as `enable_gradle`. See [`crate::adapters::maven`].
111 #[serde(default)]
112 pub enable_maven: bool,
113 /// Whether the opt-in Swift Package Manager adapter is active. Off by default, for
114 /// the same reason as `enable_gradle`: `.build/` holds compiled modules and comes
115 /// back through `swift build`. See [`crate::adapters::swift`].
116 #[serde(default)]
117 pub enable_swift: bool,
118 /// Whether the opt-in Dart and Flutter adapter is active. Off by default: the pub
119 /// metadata in `.dart_tool/` is a second's work to restore, but the `build_runner`
120 /// and `flutter_build` caches beside it are compiler output and come back only by
121 /// recompiling. See [`crate::adapters::dart`].
122 #[serde(default)]
123 pub enable_dart: bool,
124 /// Whether the opt-in Mix build-tree adapter is active. Off by default, and separate
125 /// from the always-on `mix` adapter: that one deletes `deps/`, which comes back by
126 /// downloading, while `_build/` comes back only by recompiling the project and every
127 /// dependency in it. See [`crate::adapters::mix_build`].
128 #[serde(default)]
129 pub enable_mix_build: bool,
130 /// Idle days required before *build-tree* directories (cargo, gradle, maven,
131 /// swift) are pruned.
132 ///
133 /// Separate from `idle_days` because the cost of being wrong is different: a
134 /// deleted `node_modules` is one `npm ci` away, a deleted Android `build/` is a
135 /// long recompile. Applied as `max(build_idle_days, idle_days)`.
136 #[serde(default = "default_build_idle_days")]
137 pub build_idle_days: u64,
138 /// Whether a newer release installs itself at the end of a prune pass, once the
139 /// periodic check has found one.
140 ///
141 /// On by default. A pruner that runs on a schedule is exactly the kind of tool
142 /// nobody thinks to upgrade, and an old one keeps whatever bug it shipped with
143 /// forever. What runs here is the download-and-replace half only: see
144 /// [`crate::commands::update::maybe_auto_update`], which never hands the machine to
145 /// a package manager unattended and stands aside entirely on WinGet, Scoop and
146 /// Homebrew, where the manager owns the upgrade.
147 #[serde(default = "default_auto_update")]
148 pub auto_update: bool,
149 /// Adapters switched off by name, whatever their lockfiles say.
150 ///
151 /// A deny-list rather than twenty `enable_*` booleans, because the answer for
152 /// almost everyone is "none of them" and a list of exceptions says that in one
153 /// place. It is a *preference*, and the opposite of `enable_gradle` and friends:
154 /// those are off until asked for because deleting a build tree is expensive to
155 /// undo, whereas `node_modules` is safe to prune and merely something a particular
156 /// person may not want touched.
157 ///
158 /// Names are the adapter names `--only`/`--skip` take. Applied in
159 /// [`crate::adapters::detect_adapters`], so a disabled adapter is invisible to
160 /// every command at once rather than listed by `status` and skipped by `run`.
161 #[serde(default)]
162 pub disabled_adapters: Vec<String>,
163 /// Per-adapter idle windows, in days, keyed by adapter name.
164 ///
165 /// The one dial that is neither global nor per-repository: "wait longer before
166 /// touching Rust" is a statement about a *toolchain*, not about one checkout, and
167 /// before this it could only be said by moving the global window for everything.
168 ///
169 /// **A floor, never a bypass.** The value is applied as
170 /// `max(idle_days, adapter_idle_days[name])`, so it can only make an adapter wait
171 /// longer than the repository-level check already requires. A smaller number is
172 /// accepted and simply has no effect — the repository gate runs first and is the
173 /// same gate for every adapter, and letting one adapter lower it would be a
174 /// bypass of the idle check rather than a preference.
175 ///
176 /// `BTreeMap` rather than `HashMap` so the JSON round-trips in a stable order and
177 /// a diff of the registry file shows what actually changed.
178 #[serde(default)]
179 pub adapter_idle_days: BTreeMap<String, u64>,
180}
181
182fn default_build_idle_days() -> u64 {
183 constants::DEFAULT_BUILD_IDLE_DAYS
184}
185
186fn default_require_confirmation() -> bool {
187 constants::DEFAULT_REQUIRE_CONFIRMATION
188}
189
190fn default_command_timeout_secs() -> u64 {
191 constants::DEFAULT_COMMAND_TIMEOUT_SECS
192}
193
194fn default_auto_hooks() -> bool {
195 constants::DEFAULT_AUTO_HOOKS
196}
197
198fn default_auto_setup() -> bool {
199 constants::DEFAULT_AUTO_SETUP
200}
201
202fn default_auto_config() -> bool {
203 constants::DEFAULT_AUTO_CONFIG
204}
205
206fn default_update_check() -> bool {
207 constants::DEFAULT_UPDATE_CHECK
208}
209
210fn default_auto_update() -> bool {
211 constants::DEFAULT_AUTO_UPDATE
212}
213
214fn default_min_size_mb() -> u64 {
215 constants::DEFAULT_MIN_SIZE_MB
216}
217
218fn default_scan_depth() -> usize {
219 constants::DEFAULT_SCAN_DEPTH
220}
221
222fn default_allow_manifest_rewrite() -> bool {
223 constants::DEFAULT_ALLOW_MANIFEST_REWRITE
224}
225
226fn default_update_check_interval_days() -> i64 {
227 constants::UPDATE_CHECK_INTERVAL_DAYS
228}
229
230fn default_update_check_timeout_secs() -> u64 {
231 constants::UPDATE_CHECK_TIMEOUT_SECS
232}
233
234fn default_auto_hooks_chain() -> bool {
235 constants::DEFAULT_AUTO_HOOKS_CHAIN
236}
237
238impl Default for Settings {
239 fn default() -> Self {
240 Self {
241 idle_days: constants::DEFAULT_IDLE_DAYS,
242 check_interval_days: constants::DEFAULT_CHECK_INTERVAL_DAYS,
243 auto_daemon: constants::DEFAULT_AUTO_DAEMON,
244 auto_hooks: constants::DEFAULT_AUTO_HOOKS,
245 auto_setup: constants::DEFAULT_AUTO_SETUP,
246 auto_config: constants::DEFAULT_AUTO_CONFIG,
247 require_confirmation: constants::DEFAULT_REQUIRE_CONFIRMATION,
248 command_timeout_secs: constants::DEFAULT_COMMAND_TIMEOUT_SECS,
249 min_size_mb: constants::DEFAULT_MIN_SIZE_MB,
250 update_check: constants::DEFAULT_UPDATE_CHECK,
251 scan_depth: constants::DEFAULT_SCAN_DEPTH,
252 allow_manifest_rewrite: constants::DEFAULT_ALLOW_MANIFEST_REWRITE,
253 update_check_interval_days: constants::UPDATE_CHECK_INTERVAL_DAYS,
254 update_check_timeout_secs: constants::UPDATE_CHECK_TIMEOUT_SECS,
255 auto_hooks_chain: constants::DEFAULT_AUTO_HOOKS_CHAIN,
256 enable_cargo: false,
257 enable_gradle: false,
258 enable_maven: false,
259 enable_swift: false,
260 enable_dart: false,
261 enable_mix_build: false,
262 build_idle_days: constants::DEFAULT_BUILD_IDLE_DAYS,
263 auto_update: constants::DEFAULT_AUTO_UPDATE,
264 disabled_adapters: Vec::new(),
265 adapter_idle_days: BTreeMap::new(),
266 }
267 }
268}
269
270/// Outcome of recording a repository's identity when it was registered.
271///
272/// Reported rather than silent: a registration that quietly absorbed another entry's
273/// prune history would be indistinguishable from one that lost it.
274#[derive(Debug, Clone, PartialEq, Eq)]
275pub enum Adoption {
276 /// No dead entry claimed this identity.
277 Nothing,
278 /// This registration took over the history of a path that no longer exists.
279 Moved(PathBuf),
280 /// More than one dead entry claims the identity, so none was chosen.
281 Ambiguous,
282}
283
284/// Metadata for a single registered repository.
285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
286pub struct RepoEntry {
287 /// Timestamp when the repo was added to the registry.
288 pub added_at: DateTime<Utc>,
289 /// Timestamp of the last successful prune, if any.
290 pub last_pruned_at: Option<DateTime<Utc>>,
291 /// Per-repo override for idle days (overrides global setting).
292 pub override_idle_days: Option<u64>,
293 /// Whether this repo is enabled for pruning.
294 pub enabled: bool,
295 /// Cumulative bytes reclaimed from this repository.
296 ///
297 /// Recorded from 1.1.0 onward. Registries written by 1.0.0 have no such figure and
298 /// deserialize to zero, so `devp stats` says where the number starts rather than
299 /// implying a repository pruned last March never freed anything.
300 #[serde(default)]
301 pub total_freed_bytes: u64,
302 /// The repository's root commit, recorded when it was registered.
303 ///
304 /// A repository that is moved keeps this; its path does not. Without it a moved
305 /// workspace registers as a brand new repository and its prune history is stranded
306 /// on a path that will never exist again. Registries written before 1.4.0 have none,
307 /// and re-registering the repository is what fills it in.
308 #[serde(default, skip_serializing_if = "Option::is_none")]
309 pub identity: Option<String>,
310}
311
312impl RepoEntry {
313 /// Creates a new `RepoEntry` with the current timestamp.
314 pub fn new() -> Self {
315 Self {
316 added_at: Utc::now(),
317 last_pruned_at: None,
318 override_idle_days: None,
319 enabled: true,
320 total_freed_bytes: 0,
321 identity: None,
322 }
323 }
324}
325
326impl Default for RepoEntry {
327 fn default() -> Self {
328 Self::new()
329 }
330}
331
332/// Resolve where a repository's shared git directory actually lives.
333///
334/// `.git` is a directory in an ordinary clone, but in worktrees and submodules it is a
335/// one-line `gitdir: <path>` pointer file — and a worktree's private gitdir in turn
336/// holds a `commondir` file pointing at the shared one, which is where `info/exclude`
337/// lives. Returns `None` when the path is not inside a git repository at all.
338fn git_common_dir(repo_path: &Path) -> Option<PathBuf> {
339 let dot_git = repo_path.join(".git");
340 let git_dir = if dot_git.is_dir() {
341 dot_git
342 } else {
343 let pointer = fs::read_to_string(&dot_git).ok()?;
344 let target = pointer.strip_prefix("gitdir:")?.trim();
345 let target = Path::new(target);
346 if target.is_absolute() {
347 target.to_path_buf()
348 } else {
349 repo_path.join(target)
350 }
351 };
352 if let Ok(common) = fs::read_to_string(git_dir.join("commondir")) {
353 let target = Path::new(common.trim());
354 if target.is_absolute() {
355 return Some(target.to_path_buf());
356 }
357 return Some(git_dir.join(target));
358 }
359 Some(git_dir)
360}
361
362/// Ensure an entry (e.g. ".devprune.json") is in the repository's `.git/info/exclude`.
363///
364/// The exclude file, not `.gitignore`: the config records one machine's preferences,
365/// and `.gitignore` is a tracked file shared by everyone who clones the repository —
366/// appending to it silently puts an uncommitted change in the user's diff. The exclude
367/// file gives the same "never shows up in `git status`" result without touching
368/// anything the repository tracks.
369pub fn ensure_in_git_exclude(repo_path: &Path, entry: &str) -> Result<()> {
370 let Some(git_dir) = git_common_dir(repo_path) else {
371 return Ok(());
372 };
373 let info_dir = git_dir.join("info");
374 fs::create_dir_all(&info_dir)?;
375 let exclude_path = info_dir.join("exclude");
376 if exclude_path.exists() {
377 let content = fs::read_to_string(&exclude_path)?;
378 if !content.lines().any(|line| line.trim() == entry) {
379 let mut file = fs::OpenOptions::new().append(true).open(&exclude_path)?;
380 let prefix = if content.ends_with('\n') || content.is_empty() {
381 ""
382 } else {
383 "\n"
384 };
385 writeln!(file, "{prefix}{entry}")?;
386 }
387 } else {
388 fs::write(&exclude_path, format!("{entry}\n"))?;
389 }
390 Ok(())
391}
392
393/// Normalise a repository path into the form used as a registry key.
394///
395/// Falls back to the path as given when it cannot be canonicalised (e.g. it no longer
396/// exists), so entries for deleted repos stay addressable.
397pub fn canonical_key(path: &Path) -> PathBuf {
398 path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
399}
400
401/// Resolve `.` and `..` segments and anchor a relative path to the working directory,
402/// for paths that no longer exist and so cannot be canonicalised whole. The deepest
403/// ancestor that still exists is canonicalised and the missing tail re-appended:
404/// registry keys are canonical, and a deleted repo named through a symlinked parent —
405/// macOS's `/var` → `/private/var` temp tree being the everyday case — would otherwise
406/// spell the same directory through a different root and never compare equal.
407fn lexical_absolute(path: &Path) -> PathBuf {
408 use std::path::Component;
409 let mut out = if path.is_absolute() {
410 PathBuf::new()
411 } else {
412 std::env::current_dir().unwrap_or_default()
413 };
414 for comp in path.components() {
415 match comp {
416 Component::CurDir => {}
417 Component::ParentDir => {
418 out.pop();
419 }
420 other => out.push(other.as_os_str()),
421 }
422 }
423 let mut prefix = out.as_path();
424 while !prefix.as_os_str().is_empty() {
425 if let Ok(real) = prefix.canonicalize() {
426 if let Ok(tail) = out.strip_prefix(prefix) {
427 return real.join(tail);
428 }
429 break;
430 }
431 match prefix.parent() {
432 Some(parent) => prefix = parent,
433 None => break,
434 }
435 }
436 out
437}
438
439/// Whether two paths name the same directory, tolerating the differences
440/// canonicalisation normally absorbs: the Windows `\\?\` prefix, separator style,
441/// trailing separators, and case on Windows.
442fn loose_path_eq(a: &Path, b: &Path) -> bool {
443 let norm = |p: &Path| {
444 let s = p.to_string_lossy().replace('\\', "/");
445 let s = s.strip_prefix("//?/").unwrap_or(&s);
446 let s = s.trim_end_matches('/').to_string();
447 if cfg!(windows) { s.to_lowercase() } else { s }
448 };
449 norm(a) == norm(b)
450}
451
452/// Expand a leading `~` to the user's home directory.
453///
454/// POSIX shells do this before the argument ever reaches a program, so on Linux and
455/// macOS it is usually a no-op. PowerShell and cmd do not: they hand a native
456/// executable the literal three characters `~/C`, and `devp init ~/Code` — the exact
457/// line in the README and on the landing page — would register a directory called `~`
458/// sitting in the current working directory. Quoting defeats the expansion in *every*
459/// shell, so `devp init "~/Code"` needs this too.
460///
461/// Only a bare `~` or a `~` followed by a separator is expanded. `~alice` means "some
462/// other user's home" in shell syntax and cannot be resolved portably, and `~backup` is
463/// a perfectly ordinary directory name.
464pub fn expand_tilde(raw: &str) -> String {
465 let Some(rest) = raw.strip_prefix('~') else {
466 return raw.to_string();
467 };
468 if !(rest.is_empty() || rest.starts_with('/') || rest.starts_with('\\')) {
469 return raw.to_string();
470 }
471 let Some(home) = dirs::home_dir() else {
472 // No home directory to expand to. Handing back the literal `~` lets the caller
473 // fail with "no such directory", which is a better error than a silent guess.
474 return raw.to_string();
475 };
476 if rest.is_empty() {
477 return home.to_string_lossy().into_owned();
478 }
479 home.join(rest.trim_start_matches(['/', '\\']))
480 .to_string_lossy()
481 .into_owned()
482}
483
484/// Structured per-repository configuration file stored inside repo roots as `.devprune.json`.
485#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
486pub struct PerRepoConfig {
487 /// JSON Schema reference URL for IDE IntelliSense and validation.
488 #[serde(rename = "$schema", default = "default_schema_url")]
489 pub schema: String,
490 /// Custom display name for this project in TUI and CLI status views.
491 #[serde(default)]
492 pub project_name: Option<String>,
493 /// Whether this repository is ignored/excluded from pruning.
494 #[serde(default)]
495 pub ignore: bool,
496 /// Disable global Git auto-registration hooks for this specific workspace.
497 #[serde(default)]
498 pub disable_hooks: bool,
499 /// Disable background daemon automated pruning pass for this specific workspace.
500 #[serde(default)]
501 pub disable_daemon: bool,
502 /// Custom override for idle days threshold (overrides global settings).
503 #[serde(default)]
504 pub override_idle_days: Option<u64>,
505 /// Custom override for the size floor, in MiB (overrides global `min_size_mb`).
506 ///
507 /// `Some(0)` is a meaningful value: it turns the floor off for this repository even
508 /// when a global floor is set.
509 #[serde(default)]
510 pub min_size_mb: Option<u64>,
511 /// Custom override for how deep discovery walks this repository.
512 ///
513 /// The setting that most often needs to differ per repository rather than globally:
514 /// one deeply-nested monorepo should not make every other repository pay for a
515 /// deeper walk. Clamped to [`constants::MAX_SCAN_DEPTH_LIMIT`] like the global one.
516 #[serde(default)]
517 pub scan_depth: Option<usize>,
518}
519
520// Deliberately absent: `allow_manifest_rewrite`.
521//
522// Only the settings whose right value depends on the *project* have a per-repository
523// form. `allow_manifest_rewrite` is a permission the user grants their own machine, and
524// — exactly as with `post_prune_command` below — nothing stops a project from committing
525// its `.devprune.json`: the `.git/info/exclude` entry [`PerRepoConfig::save_to_repo`]
526// writes is local to one clone and excludes nothing already tracked. A
527// per-repository form would therefore let a repository nobody has read grant itself the
528// right to have `cargo generate-lockfile` / `go mod tidy` rewrite its tracked manifests
529// during an unattended pass. The `auto_*` and `update_check*` settings describe the
530// machine rather than a project and would mean nothing here either.
531
532// Removed: `custom_bloat_dirs` and `post_prune_command`.
533//
534// Both were serialized, schema'd and documented but never read by any code path, so
535// setting them did nothing. `post_prune_command` is also not a feature that should be
536// reintroduced casually: nothing stops a project from committing its `.devprune.json`,
537// so honouring it would mean cloning an untrusted repository and running `devp` hands
538// that repository arbitrary code execution on the user's machine.
539
540fn default_schema_url() -> String {
541 if let Ok(config_dir) = Registry::config_dir() {
542 let local_schema = config_dir.join("bin").join("devprune.schema.json");
543 if local_schema.exists() {
544 // `file://` + `/` + an absolute path. Unix paths already start with a
545 // separator, so pasting them in unconditionally produced `file:////home/...`
546 // — four slashes, which editors reject, leaving the `$schema` link dead and
547 // no IntelliSense at all on the platform where most of them run.
548 return file_uri(&crate::output::clean_path(&local_schema));
549 }
550 }
551 constants::JSON_SCHEMA_URL.to_string()
552}
553
554/// A `file://` URI for an absolute path.
555///
556/// `file://` + `/` + the path. Unix paths already start with a separator, so pasting one
557/// in unconditionally produced `file:////home/...` — four slashes, which editors reject,
558/// leaving the `$schema` link dead and no IntelliSense at all on the platform where most
559/// of them run.
560fn file_uri(clean_path: &str) -> String {
561 format!("file:///{}", clean_path.trim_start_matches('/'))
562}
563
564impl Default for PerRepoConfig {
565 fn default() -> Self {
566 Self {
567 schema: default_schema_url(),
568 project_name: None,
569 ignore: false,
570 disable_hooks: false,
571 disable_daemon: false,
572 override_idle_days: None,
573 min_size_mb: None,
574 scan_depth: None,
575 }
576 }
577}
578
579impl PerRepoConfig {
580 /// Load per-repo config from `.devprune.json`, or `None` when there is no such file.
581 ///
582 /// This is the only loader. There used to be a second one that returned `None` for a
583 /// file that failed to parse as well as for one that was absent, and every caller of
584 /// it then went on to act as though the repository had no configuration: the prune
585 /// pass ignored an `"ignore": true` it could not read, and the two workspace toggles
586 /// wrote a fresh default file straight over the user's broken one, taking every
587 /// override in it with them. A caller that genuinely does not care — the display-name
588 /// lookup — says so with `.ok().flatten()`.
589 pub fn load_with_diagnostics(repo_path: &Path) -> Result<Option<Self>, String> {
590 let config_file = repo_path.join(constants::PER_REPO_CONFIG_FILE);
591 if !config_file.exists() {
592 return Ok(None);
593 }
594 let content =
595 fs::read_to_string(&config_file).map_err(|e| format!("Failed to read file: {e}"))?;
596 match serde_json::from_str::<Self>(&content) {
597 Ok(cfg) => Ok(Some(cfg)),
598 // `clean_path`, like every other path this tool shows. `Display` on a
599 // canonicalised Windows path leaks the `\\?\` extended-length prefix into an
600 // error message the user is being asked to act on.
601 Err(e) => Err(format!(
602 "Syntax error in `{}`: {e}",
603 crate::output::clean_path(&config_file)
604 )),
605 }
606 }
607
608 /// Save per-repo config to `.devprune.json` in the repo root, and record it in the
609 /// repository's `.git/info/exclude` so it never shows up in `git status`.
610 pub fn save_to_repo(&self, repo_path: &Path) -> Result<()> {
611 let config_file = repo_path.join(constants::PER_REPO_CONFIG_FILE);
612 let content = serde_json::to_string_pretty(self)?;
613 fs::write(&config_file, content)?;
614 let _ = ensure_in_git_exclude(repo_path, constants::PER_REPO_CONFIG_FILE);
615 let _ = ensure_in_git_exclude(repo_path, constants::DEVPRUNE_IGNORE_FILE);
616 Ok(())
617 }
618}
619
620/// One directory a prune pass deleted.
621///
622/// Enough to put it back and nothing more: which repository it belonged to, which
623/// project inside that repository owned it, and who verified it. No file list — the
624/// lockfile is the record of the contents, which is the whole premise of the tool.
625#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
626pub struct PrunedDir {
627 /// Repository root the directory belonged to.
628 pub repo_path: PathBuf,
629 /// Repository-relative label, `/`-separated: `node_modules`, `frontend/node_modules`.
630 pub bloat_dir: String,
631 /// Adapter that verified and deleted it.
632 pub adapter: String,
633 /// Bytes reclaimed.
634 pub size_freed: u64,
635 /// The language runtime the deleted directory was built against — `"3.12"` for a
636 /// virtual environment created by Python 3.12 — so a restore can rebuild on that
637 /// interpreter instead of on whatever happens to be first on `PATH` today.
638 ///
639 /// `None` for every manager that pins its own toolchain in the lockfile (cargo, npm,
640 /// go) and for anything pruned before 1.4.0. Optional rather than required for that
641 /// second reason: a `registry.json` written by an older version has to keep loading.
642 #[serde(default, skip_serializing_if = "Option::is_none")]
643 pub runtime: Option<String>,
644}
645
646/// What the most recent prune pass deleted, for `devp restore --last-run`.
647///
648/// Only passes that actually deleted something are recorded. A later run that frees
649/// nothing — everything was active, everything was already clean — leaves this alone,
650/// because "put back what you just took" should still mean the pass that took something.
651#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
652pub struct LastPrune {
653 /// When the pass ran.
654 pub at: DateTime<Utc>,
655 /// Every directory it removed.
656 pub dirs: Vec<PrunedDir>,
657}
658
659/// A one-line summary of a completed prune pass, for `devp stats`.
660///
661/// Deliberately not a second copy of [`LastPrune`]. That one exists so
662/// `devp restore --last-run` can put files back, so it carries the full directory list
663/// and only ever describes the most recent pass. This one is a trend line — four numbers
664/// per pass, bounded by [`constants::PRUNE_HISTORY_LIMIT`] — and could not restore
665/// anything if it wanted to.
666#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
667pub struct PruneRunSummary {
668 /// When the pass ran.
669 pub at: DateTime<Utc>,
670 /// Bytes reclaimed by the pass.
671 pub bytes_freed: u64,
672 /// How many directories it removed.
673 pub dirs_removed: usize,
674 /// How many distinct repositories it touched.
675 pub repos_touched: usize,
676}
677
678/// The top-level registry structure persisted to disk.
679#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
680pub struct Registry {
681 /// Schema version for forward compatibility.
682 pub version: String,
683 /// Global settings.
684 pub settings: Settings,
685 /// Map of canonical repo paths to their metadata.
686 pub repositories: HashMap<PathBuf, RepoEntry>,
687 /// Total cumulative bytes freed historically across all prune passes.
688 #[serde(default)]
689 pub total_freed_bytes: u64,
690 /// How many prune passes have deleted something, ever.
691 ///
692 /// One per *pass*, not per repository and not per directory — a `devp run` that
693 /// cleared eleven directories across four repositories counts once. Incremented in
694 /// exactly one place, [`Registry::record_prune`], which is also where the pass is
695 /// recorded for `devp restore --last-run`; keeping the two together is what stops
696 /// them meaning different things depending on which command did the pruning.
697 #[serde(default)]
698 pub total_pruned_count: u64,
699 /// List of repository paths added in the most recent init/link action (for devp undo).
700 #[serde(default)]
701 pub last_added_repos: Vec<PathBuf>,
702 /// What the most recent prune pass deleted (for `devp restore --last-run`).
703 #[serde(default)]
704 pub last_prune: Option<LastPrune>,
705 /// Summaries of recent prune passes, oldest first, for `devp stats`.
706 ///
707 /// Capped at [`constants::PRUNE_HISTORY_LIMIT`]. Recorded from 1.1.0 onward.
708 #[serde(default)]
709 pub prune_history: Vec<PruneRunSummary>,
710 /// When the release check last ran, so it runs at most once every
711 /// `UPDATE_CHECK_INTERVAL_DAYS` instead of on every command.
712 #[serde(default)]
713 pub last_update_check: Option<DateTime<Utc>>,
714 /// The newest release seen by the last check, so the reminder survives until the
715 /// user actually upgrades without needing the network again.
716 #[serde(default)]
717 pub latest_known_version: Option<String>,
718 /// How fast each adapter has actually restored on this machine.
719 ///
720 /// Measured by `devp restore --last-run`, which is the one command that knows both
721 /// how long a restore took and how many bytes it put back. Local only: nothing here
722 /// is uploaded, compared against anyone else's machine, or used for anything except
723 /// the estimate `devp status` prints. See `docs/PRIVACY.md`.
724 #[serde(default)]
725 pub restore_rates: BTreeMap<String, RestoreRate>,
726}
727
728/// One adapter's observed restore throughput on this machine.
729///
730/// Totals rather than a stored average, because that is what lets a new measurement be
731/// folded in without keeping the individual samples — and the individual samples are
732/// per-repository, which is exactly the shape of data this tool has no business keeping.
733#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
734pub struct RestoreRate {
735 /// How many restores this average is made of.
736 pub samples: u32,
737 /// Bytes those restores put back.
738 pub bytes: u64,
739 /// Milliseconds they took.
740 pub millis: u64,
741}
742
743impl RestoreRate {
744 /// Bytes per second, or `None` when the record cannot support the division.
745 pub fn bytes_per_sec(&self) -> Option<f64> {
746 (self.samples > 0 && self.millis > 0 && self.bytes > 0)
747 .then(|| self.bytes as f64 * 1000.0 / self.millis as f64)
748 }
749}
750
751impl Default for Registry {
752 fn default() -> Self {
753 Self {
754 version: "1.0".to_string(),
755 settings: Settings::default(),
756 repositories: HashMap::new(),
757 total_freed_bytes: 0,
758 total_pruned_count: 0,
759 last_added_repos: Vec::new(),
760 last_prune: None,
761 prune_history: Vec::new(),
762 last_update_check: None,
763 latest_known_version: None,
764 restore_rates: BTreeMap::new(),
765 }
766 }
767}
768
769impl Registry {
770 /// Returns the path to the config directory (`~/.config/dev-prune/`).
771 ///
772 /// Uses the `dirs` crate to resolve the platform-specific config location:
773 /// - Linux/macOS: `~/.config/dev-prune/`
774 /// - Windows: `C:\Users\<user>\AppData\Roaming\dev-prune\` (or `~/.config/dev-prune/`)
775 pub fn config_dir() -> Result<PathBuf> {
776 if let Ok(override_dir) = std::env::var(constants::ENV_CONFIG_DIR_OVERRIDE) {
777 return Ok(PathBuf::from(override_dir));
778 }
779 let base = dirs::config_dir().context("Could not determine config directory")?;
780 Ok(base.join(constants::CONFIG_DIR_NAME))
781 }
782
783 /// Returns the full path to the registry file.
784 pub fn registry_path() -> Result<PathBuf> {
785 Ok(Self::config_dir()?.join(constants::REGISTRY_FILENAME))
786 }
787
788 /// Loads the registry from disk, or the defaults when there is nothing to load.
789 ///
790 /// Reading does not write. This used to persist the default registry on the way
791 /// out, which made `devp --dry-run init` create the very file it had just promised
792 /// not to write and gave `devp status --json` — documented as a pure read — a side
793 /// effect on first use. Every command that actually changes something calls
794 /// [`Registry::save`], and that creates the directory as needed.
795 pub fn load() -> Result<Self> {
796 Self::load_from(&Self::registry_path()?)
797 }
798
799 /// Loads the registry from a specific path (for testing or custom locations).
800 ///
801 /// Non-persisting, exactly like [`Registry::load`], which is implemented on top of
802 /// it. The two used to disagree — this one wrote the defaults out when the file was
803 /// missing — which is the sort of difference that makes a test pass while the
804 /// behaviour it stands in for is broken.
805 pub fn load_from(path: &Path) -> Result<Self> {
806 if !path.exists() {
807 return Ok(Registry::default());
808 }
809 let contents = fs::read_to_string(path)
810 .with_context(|| format!("Failed to read registry at {}", path.display()))?;
811 serde_json::from_str(&contents)
812 .with_context(|| format!("Failed to parse registry at {}", path.display()))
813 }
814
815 /// Saves the registry to disk atomically (write to temp, then rename).
816 pub fn save(&self) -> Result<()> {
817 let path = Self::registry_path()?;
818 self.save_to(&path)
819 }
820
821 /// Saves the registry to a specific path (for testing or custom locations).
822 pub fn save_to(&self, path: &Path) -> Result<()> {
823 if let Some(parent) = path.parent() {
824 fs::create_dir_all(parent)
825 .with_context(|| format!("Failed to create config dir {}", parent.display()))?;
826 }
827 // Unique per process. A manual run and the scheduled daemon pass can save at the
828 // same moment; with a shared `registry.json.tmp`, one process could rename the
829 // other's half-written file into place as a torn, unparseable registry.
830 let tmp_path = path.with_extension(format!("json.{}.tmp", std::process::id()));
831 let contents =
832 serde_json::to_string_pretty(self).context("Failed to serialize registry")?;
833 {
834 // `sync_all` before the rename, or the atomicity is only apparent: after a
835 // power cut the rename can survive while the data does not, leaving the
836 // registry as zero bytes — the one outcome this dance exists to prevent.
837 use std::io::Write;
838 let mut file = fs::File::create(&tmp_path)
839 .with_context(|| format!("Failed to write temp registry {}", tmp_path.display()))?;
840 file.write_all(contents.as_bytes())
841 .with_context(|| format!("Failed to write temp registry {}", tmp_path.display()))?;
842 file.sync_all()
843 .with_context(|| format!("Failed to flush temp registry {}", tmp_path.display()))?;
844 }
845 fs::rename(&tmp_path, path)
846 .with_context(|| format!("Failed to rename temp registry to {}", path.display()))?;
847
848 // A crash between write and rename strands that process's `.<pid>.tmp` forever.
849 // Sweep siblings old enough that no live save can still own them.
850 if let (Some(parent), Some(name)) = (path.parent(), path.file_name()) {
851 let prefix = format!("{}.", name.to_string_lossy());
852 if let Ok(entries) = fs::read_dir(parent) {
853 for entry in entries.flatten() {
854 let file_name = entry.file_name();
855 let file_name = file_name.to_string_lossy();
856 if file_name.starts_with(&prefix)
857 && file_name.ends_with(".tmp")
858 && entry
859 .metadata()
860 .and_then(|m| m.modified())
861 .ok()
862 .and_then(|t| t.elapsed().ok())
863 .is_some_and(|age| age.as_secs() > 3600)
864 {
865 let _ = fs::remove_file(entry.path());
866 }
867 }
868 }
869 }
870 Ok(())
871 }
872
873 /// Adds a repository to the registry. Returns `true` if newly added, `false` if already present.
874 pub fn add_repo(&mut self, path: PathBuf) -> bool {
875 // The registry is keyed by path, so `./foo`, `foo/`, and the absolute form
876 // would otherwise register as three separate repositories.
877 let path = canonical_key(&path);
878 if self.repositories.contains_key(&path) {
879 return false;
880 }
881 self.repositories.insert(path, RepoEntry::new());
882 true
883 }
884
885 /// Record `identity` against a registered repository, and hand it the history of the
886 /// entry it moved away from.
887 ///
888 /// Called after `add_repo` from both `link` and `init`. When exactly one registered
889 /// path no longer exists on disk and carries the same root commit, that entry is the
890 /// same repository at its old location: its `added_at`, prune history and settings
891 /// move across and the dead row is removed. Two dead entries claiming one identity
892 /// is a clone, not a move, so nothing is guessed — the caller says so instead.
893 ///
894 /// Also the backfill path. Entries registered before 1.4.0 have no identity, so
895 /// nothing they do can be recognised as a move; re-registering them records one, and
896 /// a single `devp init ~/code` backfills the whole registry.
897 pub fn adopt_moved_entry(&mut self, path: &Path, identity: Option<String>) -> Adoption {
898 let key = canonical_key(path);
899 let Some(identity) = identity else {
900 return Adoption::Nothing;
901 };
902
903 let mut claimants: Vec<PathBuf> = self
904 .repositories
905 .iter()
906 .filter(|(p, e)| {
907 **p != key && e.identity.as_deref() == Some(identity.as_str()) && !p.exists()
908 })
909 .map(|(p, _)| p.clone())
910 .collect();
911 // Deterministic: two dead entries with one identity is a report, not a coin toss,
912 // and the report must read the same twice.
913 claimants.sort();
914
915 let adopted = match claimants.len() {
916 0 => Adoption::Nothing,
917 1 => Adoption::Moved(claimants.remove(0)),
918 _ => Adoption::Ambiguous,
919 };
920
921 if let Adoption::Moved(ref old) = adopted
922 && let Some(previous) = self.repositories.remove(old)
923 {
924 if let Some(entry) = self.repositories.get_mut(&key) {
925 // Everything the old path had earned. `enabled` and the idle override
926 // come across too: a repository the user had switched off did not switch
927 // itself back on by being moved.
928 entry.added_at = previous.added_at;
929 entry.last_pruned_at = previous.last_pruned_at;
930 entry.override_idle_days = previous.override_idle_days;
931 entry.enabled = previous.enabled;
932 entry.total_freed_bytes = previous.total_freed_bytes;
933 }
934 self.last_added_repos.retain(|p| p != old);
935 }
936
937 if let Some(entry) = self.repositories.get_mut(&key) {
938 entry.identity = Some(identity);
939 }
940 adopted
941 }
942
943 /// Whether a registered repository still has no recorded identity.
944 ///
945 /// The global Git hook runs `devp link --quiet` on every commit, and backfilling
946 /// unconditionally would shell out to git and rewrite the registry once per commit
947 /// forever. This makes it once per repository.
948 pub fn needs_identity(&self, path: &Path) -> bool {
949 self.repositories
950 .get(&canonical_key(path))
951 .is_some_and(|e| e.identity.is_none())
952 }
953
954 /// Removes a repository from the registry. Returns `true` if it was present.
955 ///
956 /// A repository that has been deleted from disk cannot be canonicalised any more,
957 /// so `canonical_key` falls back to the path as typed — which never equals the
958 /// canonical key it was registered under (on Windows those carry the `\\?\`
959 /// prefix). Unlinking a deleted repository is the most ordinary reason to unlink
960 /// at all, so a direct miss falls back to a lexical comparison.
961 pub fn remove_repo(&mut self, path: &Path) -> bool {
962 let target = lexical_absolute(path);
963 let removed = if self.repositories.remove(&canonical_key(path)).is_some() {
964 true
965 } else {
966 let found = self
967 .repositories
968 .keys()
969 .find(|k| loose_path_eq(k, &target))
970 .cloned();
971 found.is_some_and(|k| self.repositories.remove(&k).is_some())
972 };
973 if removed {
974 // The undo list stores the canonical `\\?\`-prefixed spelling, while a
975 // deleted directory can only be named lexically — strict equality misses,
976 // and the next `devp undo` "reverts" by removing nothing.
977 self.last_added_repos.retain(|p| !loose_path_eq(p, &target));
978 }
979 removed
980 }
981
982 // Removed: `repo_paths` and `effective_idle_days`.
983 //
984 // Neither had a caller outside this file's own tests. `effective_idle_days` had also
985 // drifted from the rule the engine actually applies: it looked the repository up by
986 // the path as given, where every write to `repositories` goes through
987 // `canonical_key`, so `devp`'s own relative paths would have missed the entry and
988 // silently returned the global threshold instead of the repository's override.
989
990 /// Credit `bytes_freed` to one repository, and to the machine-wide total.
991 ///
992 /// Safe to call once per repository or once per directory — every figure it touches
993 /// is either a sum or a timestamp, so the two styles agree. Counting *passes* is
994 /// deliberately not done here for exactly that reason; that lives in
995 /// [`Registry::record_prune`], which is called once per pass.
996 pub fn mark_pruned(&mut self, path: &Path, bytes_freed: u64) {
997 // Same rule as every other accessor: the map is keyed by `canonical_key`, so a
998 // raw lookup would silently skip the per-repo credit for a relative or
999 // differently-spelled path while still growing the machine-wide total.
1000 if let Some(entry) = self.repositories.get_mut(&canonical_key(path)) {
1001 entry.last_pruned_at = Some(Utc::now());
1002 entry.total_freed_bytes += bytes_freed;
1003 }
1004 self.total_freed_bytes += bytes_freed;
1005 }
1006
1007 /// Record what a prune pass deleted, replacing any earlier record.
1008 ///
1009 /// A pass that deleted nothing is not a pass worth remembering, so an empty list is
1010 /// ignored rather than stored — otherwise `devp run` on an already-clean machine
1011 /// would quietly throw away the record of the run the user actually wants back.
1012 ///
1013 /// This is the one place a prune pass is counted. It sets [`Registry::last_prune`],
1014 /// appends a [`PruneRunSummary`] to [`Registry::prune_history`] and bumps
1015 /// [`Registry::total_pruned_count`], because "a pass happened and it deleted things"
1016 /// is exactly the condition all three describe. Splitting them across call sites is
1017 /// how the counter previously came to mean repositories in `devp run` and directories
1018 /// in the `devp status` dashboard.
1019 /// Fold one measured restore into an adapter's running average.
1020 ///
1021 /// Ignores anything too quick to have been real work — see
1022 /// [`constants::RESTORE_RATE_MIN_MILLIS`] — because a manager that found everything
1023 /// still in its cache returns in a moment and would teach a throughput no cold
1024 /// restore can reach. That is the difference between an estimate that is optimistic
1025 /// and one that is wrong.
1026 pub fn record_restore(&mut self, adapter: &str, bytes: u64, millis: u64) {
1027 if bytes == 0 || millis < constants::RESTORE_RATE_MIN_MILLIS {
1028 return;
1029 }
1030 let rate = self.restore_rates.entry(adapter.to_string()).or_default();
1031 if rate.samples >= constants::RESTORE_RATE_SAMPLE_CAP {
1032 rate.samples /= 2;
1033 rate.bytes /= 2;
1034 rate.millis /= 2;
1035 }
1036 rate.samples += 1;
1037 rate.bytes = rate.bytes.saturating_add(bytes);
1038 rate.millis = rate.millis.saturating_add(millis);
1039 }
1040
1041 /// How long putting back `by_adapter` would take, from what this machine has
1042 /// measured.
1043 ///
1044 /// Returns the seconds and the bytes those seconds account for. Anything from an
1045 /// adapter that has never been timed here is left out of both, so a caller can say
1046 /// how much of the estimate is actually covered rather than quietly quoting a
1047 /// number for half the work. `None` when nothing is covered at all — an estimate
1048 /// with no measurement behind it is a guess, and this command does not print
1049 /// guesses.
1050 pub fn estimate_restore(&self, by_adapter: &[(String, u64)]) -> Option<(f64, u64)> {
1051 let mut secs = 0.0;
1052 let mut covered = 0u64;
1053 for (adapter, bytes) in by_adapter {
1054 let Some(rate) = self
1055 .restore_rates
1056 .get(adapter)
1057 .and_then(|r| r.bytes_per_sec())
1058 else {
1059 continue;
1060 };
1061 secs += *bytes as f64 / rate;
1062 covered = covered.saturating_add(*bytes);
1063 }
1064 (covered > 0).then_some((secs, covered))
1065 }
1066
1067 pub fn record_prune(&mut self, dirs: Vec<PrunedDir>) {
1068 self.record_prune_progress(Utc::now(), dirs);
1069 }
1070
1071 /// Record a pass's progress mid-flight, superseding this same pass's earlier record.
1072 ///
1073 /// `at` identifies the pass: a repeated call with the same timestamp replaces the
1074 /// history entry and `last_prune` it wrote before, rather than counting a second
1075 /// pass. This exists so a long pass can persist after every repository — a crash
1076 /// half-way through used to leave `devp restore --last-run` pointing at the
1077 /// *previous* pass, offering to reinstall directories that were never deleted while
1078 /// saying nothing about the ones that were.
1079 pub fn record_prune_progress(&mut self, at: DateTime<Utc>, dirs: Vec<PrunedDir>) {
1080 if dirs.is_empty() {
1081 return;
1082 }
1083 if self.prune_history.last().map(|s| s.at) == Some(at) {
1084 self.prune_history.pop();
1085 } else {
1086 self.total_pruned_count += 1;
1087 }
1088
1089 self.prune_history.push(PruneRunSummary {
1090 at,
1091 bytes_freed: dirs.iter().map(|d| d.size_freed).sum(),
1092 dirs_removed: dirs.len(),
1093 repos_touched: dirs
1094 .iter()
1095 .map(|d| &d.repo_path)
1096 .collect::<HashSet<_>>()
1097 .len(),
1098 });
1099 // Oldest first, so the overflow comes off the front.
1100 if self.prune_history.len() > constants::PRUNE_HISTORY_LIMIT {
1101 let excess = self.prune_history.len() - constants::PRUNE_HISTORY_LIMIT;
1102 self.prune_history.drain(..excess);
1103 }
1104
1105 self.last_prune = Some(LastPrune { at, dirs });
1106 }
1107
1108 /// Returns the number of registered repositories.
1109 pub fn repo_count(&self) -> usize {
1110 self.repositories.len()
1111 }
1112}
1113
1114#[cfg(test)]
1115mod tests {
1116 use super::*;
1117 use tempfile::TempDir;
1118
1119 fn test_registry_path(dir: &TempDir) -> PathBuf {
1120 dir.path().join("dev-prune").join("registry.json")
1121 }
1122
1123 fn a_pruned_dir(label: &str) -> PrunedDir {
1124 PrunedDir {
1125 repo_path: PathBuf::from("/repo"),
1126 bloat_dir: label.to_string(),
1127 adapter: "npm".to_string(),
1128 size_freed: 42,
1129 runtime: None,
1130 }
1131 }
1132
1133 #[test]
1134 fn a_prune_that_deleted_nothing_does_not_erase_the_last_one() {
1135 // Otherwise a second `devp run` on an already-clean machine throws away the
1136 // record of the pass the user actually wants to undo.
1137 let mut registry = Registry::default();
1138 registry.record_prune(vec![a_pruned_dir("node_modules")]);
1139 let recorded = registry.last_prune.clone().expect("first pass recorded");
1140
1141 registry.record_prune(Vec::new());
1142
1143 assert_eq!(registry.last_prune, Some(recorded));
1144 }
1145
1146 #[test]
1147 fn a_later_prune_replaces_the_record() {
1148 let mut registry = Registry::default();
1149 registry.record_prune(vec![a_pruned_dir("node_modules")]);
1150 registry.record_prune(vec![a_pruned_dir("frontend/node_modules")]);
1151
1152 let dirs = registry.last_prune.unwrap().dirs;
1153 assert_eq!(dirs.len(), 1);
1154 assert_eq!(dirs[0].bloat_dir, "frontend/node_modules");
1155 }
1156
1157 #[test]
1158 fn the_last_prune_record_survives_a_save_and_load() {
1159 // `restore --last-run` reads it out of a file written by a process that has
1160 // already exited, so the round trip is the whole feature.
1161 let dir = TempDir::new().unwrap();
1162 let path = test_registry_path(&dir);
1163
1164 let mut registry = Registry::default();
1165 registry.record_prune(vec![a_pruned_dir("frontend/node_modules")]);
1166 registry.save_to(&path).unwrap();
1167
1168 let loaded = Registry::load_from(&path).unwrap();
1169 assert_eq!(loaded.last_prune, registry.last_prune);
1170 }
1171
1172 #[test]
1173 fn a_registry_written_before_the_field_existed_still_loads() {
1174 // The registry on disk predates `last_prune`; a missing key means "no pass
1175 // recorded", not a parse failure that would lock the user out of their config.
1176 let dir = TempDir::new().unwrap();
1177 let path = test_registry_path(&dir);
1178 fs::create_dir_all(path.parent().unwrap()).unwrap();
1179 fs::write(
1180 &path,
1181 r#"{"version":"1.0","settings":{"idle_days":15,"check_interval_days":2,
1182 "auto_daemon":true},"repositories":{}}"#,
1183 )
1184 .unwrap();
1185
1186 let loaded = Registry::load_from(&path).unwrap();
1187 assert_eq!(loaded.last_prune, None);
1188 }
1189
1190 #[test]
1191 fn a_leading_tilde_becomes_the_home_directory() {
1192 // The whole reason this exists: PowerShell hands `devp init ~/Code` straight
1193 // through, so without expansion the registry gains a repository at `.\~\Code`.
1194 let home = dirs::home_dir().expect("test host has a home directory");
1195
1196 assert_eq!(expand_tilde("~"), home.to_string_lossy());
1197 assert_eq!(
1198 expand_tilde("~/Code"),
1199 home.join("Code").to_string_lossy(),
1200 "forward slash, as typed in every shell"
1201 );
1202 assert_eq!(
1203 expand_tilde("~\\Code"),
1204 home.join("Code").to_string_lossy(),
1205 "backslash, as typed in PowerShell"
1206 );
1207 }
1208
1209 #[test]
1210 fn a_tilde_that_is_not_a_home_reference_is_left_alone() {
1211 // `~alice` is another user's home in shell syntax and cannot be resolved
1212 // portably; `~backup` and `./~tmp` are ordinary directory names. Rewriting any
1213 // of them would silently point the user at the wrong directory.
1214 for raw in ["~alice/Code", "~backup", "./~tmp", "Code~", "", "."] {
1215 assert_eq!(expand_tilde(raw), raw, "{raw} must survive untouched");
1216 }
1217 }
1218
1219 #[test]
1220 fn test_default_settings() {
1221 let settings = Settings::default();
1222 assert_eq!(settings.idle_days, 15);
1223 assert_eq!(settings.check_interval_days, 2);
1224 // On by default: dev-prune installs its own integrations, once per version,
1225 // and only the ones it finds missing.
1226 assert!(settings.auto_daemon);
1227 assert!(settings.auto_hooks);
1228 assert!(settings.auto_setup);
1229 }
1230
1231 #[test]
1232 fn settings_written_before_the_automation_toggles_existed_still_load() {
1233 // Real registries on disk predate `auto_hooks` / `auto_setup`; an upgrade must
1234 // read them rather than fail to parse and lose every registered repository.
1235 let json = r#"{
1236 "idle_days": 30,
1237 "check_interval_days": 2,
1238 "auto_daemon": false
1239 }"#;
1240 let settings: Settings = serde_json::from_str(json).unwrap();
1241 assert_eq!(settings.idle_days, 30);
1242 assert!(!settings.auto_daemon, "an explicit opt-out is preserved");
1243 assert!(settings.auto_hooks, "a missing key takes the default");
1244 assert!(settings.auto_setup);
1245 }
1246
1247 #[test]
1248 fn test_default_registry() {
1249 let registry = Registry::default();
1250 assert_eq!(registry.version, "1.0");
1251 assert_eq!(registry.settings, Settings::default());
1252 assert!(registry.repositories.is_empty());
1253 }
1254
1255 #[test]
1256 fn test_repo_entry_new() {
1257 let entry = RepoEntry::new();
1258 assert!(entry.enabled);
1259 assert!(entry.last_pruned_at.is_none());
1260 assert!(entry.override_idle_days.is_none());
1261 }
1262
1263 #[test]
1264 fn test_save_and_load() {
1265 let tmp = TempDir::new().unwrap();
1266 let path = test_registry_path(&tmp);
1267
1268 let mut registry = Registry::default();
1269 registry.add_repo(PathBuf::from("/test/repo"));
1270 registry.save_to(&path).unwrap();
1271
1272 let loaded = Registry::load_from(&path).unwrap();
1273 assert_eq!(loaded.repo_count(), 1);
1274 assert!(
1275 loaded
1276 .repositories
1277 .contains_key(&PathBuf::from("/test/repo"))
1278 );
1279 }
1280
1281 #[test]
1282 fn loading_a_missing_registry_yields_the_defaults_and_writes_nothing() {
1283 let tmp = TempDir::new().unwrap();
1284 let path = test_registry_path(&tmp);
1285
1286 let loaded = Registry::load_from(&path).unwrap();
1287 assert_eq!(loaded, Registry::default());
1288 // Reading is not writing. `devp --dry-run` and `devp status --json` both promise
1289 // to leave the disk alone, and both start by loading the registry.
1290 assert!(!path.exists(), "loading the registry created it");
1291 }
1292
1293 #[test]
1294 fn test_add_repo_returns_true_for_new() {
1295 let mut registry = Registry::default();
1296 assert!(registry.add_repo(PathBuf::from("/test/repo")));
1297 }
1298
1299 #[test]
1300 fn test_add_repo_returns_false_for_duplicate() {
1301 let mut registry = Registry::default();
1302 registry.add_repo(PathBuf::from("/test/repo"));
1303 assert!(!registry.add_repo(PathBuf::from("/test/repo")));
1304 }
1305
1306 #[test]
1307 fn test_remove_repo() {
1308 let mut registry = Registry::default();
1309 registry.add_repo(PathBuf::from("/test/repo"));
1310 assert!(registry.remove_repo(Path::new("/test/repo")));
1311 assert!(!registry.remove_repo(Path::new("/test/repo")));
1312 assert_eq!(registry.repo_count(), 0);
1313 }
1314
1315 /// macOS puts temp trees behind `/var` → `/private/var`, so a repo registered
1316 /// through the symlink is keyed under the real path — and once deleted, the
1317 /// symlinked spelling cannot be canonicalised whole. The lexical fallback must
1318 /// resolve the surviving parent, or unlink reports "not registered" for a
1319 /// directory the user is looking at in their own prompt.
1320 #[cfg(unix)]
1321 #[test]
1322 fn a_deleted_repo_named_through_a_symlinked_parent_still_unlinks() {
1323 let tmp = TempDir::new().unwrap();
1324 let real_parent = tmp.path().join("real");
1325 std::fs::create_dir(&real_parent).unwrap();
1326 let alias = tmp.path().join("alias");
1327 std::os::unix::fs::symlink(&real_parent, &alias).unwrap();
1328
1329 let repo = real_parent.join("repo");
1330 std::fs::create_dir(&repo).unwrap();
1331 let mut registry = Registry::default();
1332 registry.add_repo(alias.join("repo"));
1333 std::fs::remove_dir(&repo).unwrap();
1334
1335 assert!(registry.remove_repo(&alias.join("repo")));
1336 assert_eq!(registry.repo_count(), 0);
1337 }
1338
1339 #[test]
1340 fn test_mark_pruned() {
1341 let mut registry = Registry::default();
1342 registry.add_repo(PathBuf::from("/test/repo"));
1343 assert!(
1344 registry.repositories[&PathBuf::from("/test/repo")]
1345 .last_pruned_at
1346 .is_none()
1347 );
1348 registry.mark_pruned(Path::new("/test/repo"), 1024);
1349 assert!(
1350 registry.repositories[&PathBuf::from("/test/repo")]
1351 .last_pruned_at
1352 .is_some()
1353 );
1354 assert_eq!(registry.total_freed_bytes, 1024);
1355 // Not the pass counter — that is `record_prune`'s job, once per pass.
1356 assert_eq!(registry.total_pruned_count, 0);
1357 }
1358
1359 #[test]
1360 fn a_pass_is_counted_once_however_much_it_deleted() {
1361 // The counter is published as `prune_passes`, and it used to be incremented once
1362 // per repository by `devp run` and once per *directory* by the status dashboard,
1363 // so the same work produced a different number depending on where it started.
1364 let mut registry = Registry::default();
1365 registry.add_repo(PathBuf::from("/repo"));
1366
1367 registry.mark_pruned(Path::new("/repo"), 1024);
1368 registry.mark_pruned(Path::new("/repo"), 1024);
1369 registry.record_prune(vec![
1370 a_pruned_dir("node_modules"),
1371 a_pruned_dir("frontend/node_modules"),
1372 ]);
1373
1374 assert_eq!(registry.total_pruned_count, 1);
1375
1376 registry.record_prune(vec![a_pruned_dir("target")]);
1377 assert_eq!(registry.total_pruned_count, 2);
1378
1379 // A pass that deleted nothing is not a pass.
1380 registry.record_prune(Vec::new());
1381 assert_eq!(registry.total_pruned_count, 2);
1382 }
1383
1384 #[test]
1385 fn mark_pruned_credits_the_repo_under_its_canonical_key() {
1386 // On Windows, `canonicalize` yields a `\\?\`-prefixed path, so a registry keyed
1387 // by the canonical form and a `mark_pruned` looking up the raw form would miss —
1388 // growing the machine-wide total while the repository's own figure stayed zero.
1389 let tmp = TempDir::new().unwrap();
1390 let raw = tmp.path().to_path_buf();
1391
1392 let mut registry = Registry::default();
1393 registry.add_repo(raw.clone());
1394 registry.mark_pruned(&raw, 1024);
1395
1396 let entry = ®istry.repositories[&canonical_key(&raw)];
1397 assert_eq!(entry.total_freed_bytes, 1024);
1398 assert!(entry.last_pruned_at.is_some());
1399 assert_eq!(registry.total_freed_bytes, 1024);
1400 }
1401
1402 #[test]
1403 fn each_repository_accumulates_its_own_total() {
1404 // `devp stats` ranks repositories against each other, so the per-repo figure has
1405 // to be a running total and not the size of the most recent pass.
1406 let mut registry = Registry::default();
1407 registry.add_repo(PathBuf::from("/test/repo"));
1408 registry.add_repo(PathBuf::from("/test/other"));
1409
1410 registry.mark_pruned(Path::new("/test/repo"), 1024);
1411 registry.mark_pruned(Path::new("/test/repo"), 2048);
1412 registry.mark_pruned(Path::new("/test/other"), 512);
1413
1414 assert_eq!(
1415 registry.repositories[&PathBuf::from("/test/repo")].total_freed_bytes,
1416 3072
1417 );
1418 assert_eq!(
1419 registry.repositories[&PathBuf::from("/test/other")].total_freed_bytes,
1420 512
1421 );
1422 assert_eq!(registry.total_freed_bytes, 3584);
1423 }
1424
1425 #[test]
1426 fn the_prune_history_summarises_the_pass() {
1427 let mut registry = Registry::default();
1428 registry.record_prune(vec![
1429 a_pruned_dir("node_modules"),
1430 a_pruned_dir("frontend/node_modules"),
1431 ]);
1432
1433 let summary = registry.prune_history.last().expect("pass summarised");
1434 assert_eq!(summary.bytes_freed, 84);
1435 assert_eq!(summary.dirs_removed, 2);
1436 // Both fixtures live under `/repo`, so this is one repository, not two.
1437 assert_eq!(summary.repos_touched, 1);
1438 }
1439
1440 #[test]
1441 fn the_prune_history_is_capped_and_drops_the_oldest() {
1442 // The registry is rewritten in full on every save, so an uncapped list would grow
1443 // the file forever on a machine running the scheduled pass.
1444 let mut registry = Registry::default();
1445 for _ in 0..constants::PRUNE_HISTORY_LIMIT + 5 {
1446 registry.record_prune(vec![a_pruned_dir("node_modules")]);
1447 }
1448
1449 assert_eq!(registry.prune_history.len(), constants::PRUNE_HISTORY_LIMIT);
1450 let first = registry.prune_history.first().unwrap().at;
1451 let last = registry.prune_history.last().unwrap().at;
1452 assert!(first <= last, "oldest first");
1453 }
1454
1455 #[test]
1456 fn test_repo_count() {
1457 let mut registry = Registry::default();
1458 assert_eq!(registry.repo_count(), 0);
1459 registry.add_repo(PathBuf::from("/a"));
1460 registry.add_repo(PathBuf::from("/b"));
1461 assert_eq!(registry.repo_count(), 2);
1462 }
1463
1464 #[test]
1465 fn a_local_schema_uri_has_exactly_three_slashes_on_either_platform() {
1466 assert_eq!(
1467 file_uri("/home/dev/.config/dev-prune/bin/devprune.schema.json"),
1468 "file:///home/dev/.config/dev-prune/bin/devprune.schema.json"
1469 );
1470 assert_eq!(
1471 file_uri("C:/Users/dev/AppData/Roaming/dev-prune/bin/devprune.schema.json"),
1472 "file:///C:/Users/dev/AppData/Roaming/dev-prune/bin/devprune.schema.json"
1473 );
1474 }
1475
1476 #[test]
1477 fn a_broken_per_repo_config_is_an_error_rather_than_an_absent_one() {
1478 // The distinction the whole tool leans on: "no config" means take the defaults,
1479 // "unreadable config" means refuse — never overwrite, never prune on a guess.
1480 let tmp = TempDir::new().unwrap();
1481 let repo = tmp.path();
1482 assert_eq!(PerRepoConfig::load_with_diagnostics(repo), Ok(None));
1483
1484 fs::write(
1485 repo.join(constants::PER_REPO_CONFIG_FILE),
1486 r#"{ "ignore": true, }"#,
1487 )
1488 .unwrap();
1489 let err = PerRepoConfig::load_with_diagnostics(repo).unwrap_err();
1490 assert!(err.contains("Syntax error"), "{err}");
1491
1492 fs::write(
1493 repo.join(constants::PER_REPO_CONFIG_FILE),
1494 r#"{ "ignore": true }"#,
1495 )
1496 .unwrap();
1497 assert!(
1498 PerRepoConfig::load_with_diagnostics(repo)
1499 .unwrap()
1500 .unwrap()
1501 .ignore
1502 );
1503 }
1504
1505 #[test]
1506 fn test_serialization_roundtrip() {
1507 let mut registry = Registry::default();
1508 registry.settings.idle_days = 30;
1509 registry.add_repo(PathBuf::from("/test/repo"));
1510
1511 let json = serde_json::to_string_pretty(®istry).unwrap();
1512 let deserialized: Registry = serde_json::from_str(&json).unwrap();
1513 assert_eq!(registry.settings.idle_days, deserialized.settings.idle_days);
1514 assert_eq!(registry.repo_count(), deserialized.repo_count());
1515 }
1516
1517 #[test]
1518 fn test_atomic_save_leaves_no_tmp() {
1519 let tmp = TempDir::new().unwrap();
1520 let path = test_registry_path(&tmp);
1521
1522 let registry = Registry::default();
1523 registry.save_to(&path).unwrap();
1524
1525 assert!(path.exists());
1526 // Nothing but the registry itself may remain — a leftover `*.tmp` would mean the
1527 // rename never happened.
1528 let leftovers: Vec<_> = fs::read_dir(path.parent().unwrap())
1529 .unwrap()
1530 .flatten()
1531 .filter(|e| e.path() != path)
1532 .collect();
1533 assert!(leftovers.is_empty(), "leftover files: {leftovers:?}");
1534 }
1535
1536 #[test]
1537 fn exclude_entry_lands_in_git_info_exclude_not_gitignore() {
1538 let tmp = TempDir::new().unwrap();
1539 let repo = tmp.path();
1540 fs::create_dir(repo.join(".git")).unwrap();
1541
1542 ensure_in_git_exclude(repo, ".devprune.json").unwrap();
1543
1544 let exclude = fs::read_to_string(repo.join(".git/info/exclude")).unwrap();
1545 assert!(exclude.lines().any(|l| l == ".devprune.json"));
1546 // The whole point of using the exclude file: the shared, tracked `.gitignore`
1547 // must never be created or touched.
1548 assert!(!repo.join(".gitignore").exists());
1549 }
1550
1551 #[test]
1552 fn exclude_entry_is_appended_once_and_preserves_existing_lines() {
1553 let tmp = TempDir::new().unwrap();
1554 let repo = tmp.path();
1555 fs::create_dir_all(repo.join(".git/info")).unwrap();
1556 // No trailing newline, deliberately — the append must not glue two entries
1557 // onto one line.
1558 fs::write(repo.join(".git/info/exclude"), "*.log").unwrap();
1559
1560 ensure_in_git_exclude(repo, ".devprune.json").unwrap();
1561 ensure_in_git_exclude(repo, ".devprune.json").unwrap();
1562
1563 let exclude = fs::read_to_string(repo.join(".git/info/exclude")).unwrap();
1564 let lines: Vec<_> = exclude.lines().collect();
1565 assert_eq!(lines, vec!["*.log", ".devprune.json"]);
1566 }
1567
1568 #[test]
1569 fn exclude_follows_a_gitdir_pointer_file() {
1570 // Worktrees and submodules have a one-line `.git` *file*, and a worktree's
1571 // private gitdir points at the shared one via `commondir` — where the real
1572 // `info/exclude` lives.
1573 let tmp = TempDir::new().unwrap();
1574 let shared = tmp.path().join("main-clone/.git");
1575 let worktree_gitdir = shared.join("worktrees/wt");
1576 fs::create_dir_all(&worktree_gitdir).unwrap();
1577 fs::write(worktree_gitdir.join("commondir"), "../..\n").unwrap();
1578
1579 let wt = tmp.path().join("wt");
1580 fs::create_dir(&wt).unwrap();
1581 fs::write(
1582 wt.join(".git"),
1583 format!("gitdir: {}\n", worktree_gitdir.display()),
1584 )
1585 .unwrap();
1586
1587 ensure_in_git_exclude(&wt, ".devprune.json").unwrap();
1588
1589 let exclude = fs::read_to_string(shared.join("info/exclude")).unwrap();
1590 assert!(exclude.lines().any(|l| l == ".devprune.json"));
1591 }
1592
1593 #[test]
1594 fn exclude_is_a_no_op_outside_a_git_repository() {
1595 let tmp = TempDir::new().unwrap();
1596
1597 ensure_in_git_exclude(tmp.path(), ".devprune.json").unwrap();
1598
1599 assert!(!tmp.path().join(".git").exists());
1600 assert!(!tmp.path().join(".gitignore").exists());
1601 }
1602 /// A repository that moved is recognised, and arrives with everything it had earned.
1603 #[test]
1604 fn adopt_moved_entry_transfers_history() {
1605 let mut reg = Registry::default();
1606 let old = PathBuf::from("/nowhere/old-home/project");
1607 let mut entry = RepoEntry::new();
1608 entry.identity = Some("abc1234def".into());
1609 entry.total_freed_bytes = 4096;
1610 entry.enabled = false;
1611 entry.override_idle_days = Some(90);
1612 reg.repositories.insert(old.clone(), entry);
1613
1614 let new = std::env::temp_dir().join("devprune-adopt-live");
1615 reg.repositories.insert(new.clone(), RepoEntry::new());
1616
1617 let outcome = reg.adopt_moved_entry(&new, Some("abc1234def".into()));
1618 assert_eq!(outcome, Adoption::Moved(old.clone()));
1619 assert!(!reg.repositories.contains_key(&old));
1620
1621 let moved = ®.repositories[&canonical_key(&new)];
1622 assert_eq!(moved.total_freed_bytes, 4096);
1623 // A repository the user had switched off did not switch itself back on by
1624 // being moved.
1625 assert!(!moved.enabled);
1626 assert_eq!(moved.override_idle_days, Some(90));
1627 assert_eq!(moved.identity.as_deref(), Some("abc1234def"));
1628 }
1629
1630 /// Two dead entries with one root commit are clones, not a move. Nothing is guessed.
1631 #[test]
1632 fn adopt_moved_entry_refuses_to_guess_between_two() {
1633 let mut reg = Registry::default();
1634 for name in ["/nowhere/a", "/nowhere/b"] {
1635 let mut entry = RepoEntry::new();
1636 entry.identity = Some("shared".into());
1637 reg.repositories.insert(PathBuf::from(name), entry);
1638 }
1639 let new = std::env::temp_dir().join("devprune-adopt-ambiguous");
1640 reg.repositories.insert(new.clone(), RepoEntry::new());
1641
1642 assert_eq!(
1643 reg.adopt_moved_entry(&new, Some("shared".into())),
1644 Adoption::Ambiguous
1645 );
1646 assert_eq!(reg.repositories.len(), 3);
1647 // The identity is still recorded, so the next registration can recognise it
1648 // once the duplicates are cleared.
1649 assert_eq!(
1650 reg.repositories[&canonical_key(&new)].identity.as_deref(),
1651 Some("shared")
1652 );
1653 }
1654
1655 /// An entry whose path still exists is not a move, however matching its history.
1656 #[test]
1657 fn adopt_moved_entry_never_takes_from_a_live_path() {
1658 let dir = tempfile::tempdir().unwrap();
1659 let live = dir.path().join("live");
1660 std::fs::create_dir(&live).unwrap();
1661
1662 let mut reg = Registry::default();
1663 let mut entry = RepoEntry::new();
1664 entry.identity = Some("same".into());
1665 entry.total_freed_bytes = 999;
1666 reg.repositories.insert(canonical_key(&live), entry);
1667
1668 let other = dir.path().join("other");
1669 std::fs::create_dir(&other).unwrap();
1670 reg.repositories
1671 .insert(canonical_key(&other), RepoEntry::new());
1672
1673 assert_eq!(
1674 reg.adopt_moved_entry(&other, Some("same".into())),
1675 Adoption::Nothing
1676 );
1677 assert_eq!(
1678 reg.repositories[&canonical_key(&live)].total_freed_bytes,
1679 999
1680 );
1681 }
1682
1683 /// A repository with no commits has no identity, so nothing is adopted and nothing
1684 /// is recorded — a guess would be worse than the dead entry it replaced.
1685 #[test]
1686 fn adopt_moved_entry_ignores_a_missing_identity() {
1687 let mut reg = Registry::default();
1688 let mut entry = RepoEntry::new();
1689 entry.identity = Some("orphan".into());
1690 reg.repositories
1691 .insert(PathBuf::from("/nowhere/gone"), entry);
1692 let new = std::env::temp_dir().join("devprune-adopt-unborn");
1693 reg.repositories.insert(new.clone(), RepoEntry::new());
1694
1695 assert_eq!(reg.adopt_moved_entry(&new, None), Adoption::Nothing);
1696 assert_eq!(reg.repositories.len(), 2);
1697 assert!(reg.needs_identity(&new));
1698 }
1699
1700 #[test]
1701 fn a_restore_too_quick_to_be_real_teaches_nothing() {
1702 // A manager that found everything still in its cache returns in a moment. Folding
1703 // that into the average would claim a throughput no cold restore can reach, and
1704 // the estimate exists precisely to describe a cold one.
1705 let mut reg = Registry::default();
1706 reg.record_restore("npm", 500_000_000, 10);
1707 reg.record_restore("npm", 0, 60_000);
1708 assert!(reg.restore_rates.is_empty(), "{:?}", reg.restore_rates);
1709
1710 reg.record_restore("npm", 500_000_000, 60_000);
1711 assert_eq!(reg.restore_rates["npm"].samples, 1);
1712 }
1713
1714 #[test]
1715 fn the_average_forgets_the_disk_the_machine_no_longer_has() {
1716 let mut reg = Registry::default();
1717 for _ in 0..constants::RESTORE_RATE_SAMPLE_CAP {
1718 reg.record_restore("npm", 1_000_000, 1_000);
1719 }
1720 assert_eq!(
1721 reg.restore_rates["npm"].samples,
1722 constants::RESTORE_RATE_SAMPLE_CAP
1723 );
1724
1725 // The cap is a halving, not a ceiling: the next sample still lands, on top of
1726 // half of what came before.
1727 reg.record_restore("npm", 1_000_000, 1_000);
1728 let rate = ®.restore_rates["npm"];
1729 assert_eq!(rate.samples, constants::RESTORE_RATE_SAMPLE_CAP / 2 + 1);
1730 assert!(rate.bytes_per_sec().is_some());
1731 }
1732
1733 #[test]
1734 fn an_estimate_with_nothing_measured_is_not_offered() {
1735 // Never a zero and never a guess: a machine that has not restored anything yet
1736 // has no honest answer to "how long is this to undo", so it does not print one.
1737 let reg = Registry::default();
1738 assert!(reg.estimate_restore(&[("npm".into(), 1_000_000)]).is_none());
1739 }
1740
1741 #[test]
1742 fn an_untimed_adapter_is_left_out_of_the_coverage() {
1743 // Half an answer, reported as half. Counting cargo's bytes at npm's speed would
1744 // be the one thing worse than saying nothing.
1745 let mut reg = Registry::default();
1746 reg.record_restore("npm", 10_000_000, 10_000);
1747 let (secs, covered) = reg
1748 .estimate_restore(&[("npm".into(), 10_000_000), ("cargo".into(), 90_000_000)])
1749 .expect("npm alone is enough to answer for npm");
1750 assert_eq!(covered, 10_000_000, "cargo has never been timed here");
1751 assert!((secs - 10.0).abs() < 0.01, "{secs}");
1752 }
1753}