Skip to main content

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