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 /// Whether the opt-in vcpkg adapter is active. Off by default: vcpkg builds every
131 /// port from source, so `vcpkg_installed/` comes back by compiling Boost or Qt
132 /// again rather than by downloading them. See [`crate::adapters::vcpkg`].
133 #[serde(default)]
134 pub enable_vcpkg: bool,
135
136 /// Whether the opt-in CMake build-tree adapter is active. Off by default: a build
137 /// tree is object files and linked binaries, and it comes back by compiling the
138 /// project again. See [`crate::adapters::cmake_build`].
139 #[serde(default)]
140 pub enable_cmake_build: bool,
141 /// Idle days required before *build-tree* directories — everything the opt-in
142 /// adapters claim — are pruned.
143 ///
144 /// Separate from `idle_days` because the cost of being wrong is different: a
145 /// deleted `node_modules` is one `npm ci` away, a deleted Android `build/` is a
146 /// long recompile. Applied as `max(build_idle_days, idle_days)`.
147 #[serde(default = "default_build_idle_days")]
148 pub build_idle_days: u64,
149 /// Whether a newer release installs itself at the end of a prune pass, once the
150 /// periodic check has found one.
151 ///
152 /// On by default. A pruner that runs on a schedule is exactly the kind of tool
153 /// nobody thinks to upgrade, and an old one keeps whatever bug it shipped with
154 /// forever. What runs here is the download-and-replace half only: see
155 /// [`crate::commands::update::maybe_auto_update`], which never hands the machine to
156 /// a package manager unattended and stands aside entirely on WinGet, Scoop and
157 /// Homebrew, where the manager owns the upgrade.
158 #[serde(default = "default_auto_update")]
159 pub auto_update: bool,
160 /// Whether this copy stays on the version it is, whatever else is configured.
161 ///
162 /// Off by default, and turned on only by a person typing
163 /// `devp config set version_lock true`. While it is on, `auto_update` does not run
164 /// however it is set, `devp update --install` refuses, `devp install --channel`
165 /// refuses because moving channels installs the latest release, and the install
166 /// scripts leave the binary exactly where they find it. There is no flag that
167 /// bypasses it: releasing the pin is the same kind of decision as setting it, and
168 /// belongs to the same person.
169 ///
170 /// It exists because `auto_update = false` was never the whole answer. That setting
171 /// stops one path; a machine that has to keep shipping the same tool for a year --
172 /// a CI image, a reproduction that stops reproducing the moment the tool changes
173 /// underneath it, a locked-down build box -- also has to survive someone re-running
174 /// the install one-liner out of habit.
175 #[serde(default)]
176 pub version_lock: bool,
177 /// Adapters switched off by name, whatever their lockfiles say.
178 ///
179 /// A deny-list rather than twenty `enable_*` booleans, because the answer for
180 /// almost everyone is "none of them" and a list of exceptions says that in one
181 /// place. It is a *preference*, and the opposite of `enable_gradle` and friends:
182 /// those are off until asked for because deleting a build tree is expensive to
183 /// undo, whereas `node_modules` is safe to prune and merely something a particular
184 /// person may not want touched.
185 ///
186 /// Names are the adapter names `--only`/`--skip` take. Applied in
187 /// [`crate::adapters::detect_adapters`], so a disabled adapter is invisible to
188 /// every command at once rather than listed by `status` and skipped by `run`.
189 #[serde(default)]
190 pub disabled_adapters: Vec<String>,
191 /// Per-adapter idle windows, in days, keyed by adapter name.
192 ///
193 /// The one dial that is neither global nor per-repository: "wait longer before
194 /// touching Rust" is a statement about a *toolchain*, not about one checkout, and
195 /// before this it could only be said by moving the global window for everything.
196 ///
197 /// **A floor, never a bypass.** The value is applied as
198 /// `max(idle_days, adapter_idle_days[name])`, so it can only make an adapter wait
199 /// longer than the repository-level check already requires. A smaller number is
200 /// accepted and simply has no effect — the repository gate runs first and is the
201 /// same gate for every adapter, and letting one adapter lower it would be a
202 /// bypass of the idle check rather than a preference.
203 ///
204 /// `BTreeMap` rather than `HashMap` so the JSON round-trips in a stable order and
205 /// a diff of the registry file shows what actually changed.
206 #[serde(default)]
207 pub adapter_idle_days: BTreeMap<String, u64>,
208 /// Per-manager cache size caps, in gibibytes, keyed by cache manager name.
209 ///
210 /// A download cache is a bet that re-downloading costs more than the disk it
211 /// occupies, and the bet stops paying somewhere: a `uv` cache past ten gigabytes is
212 /// keeping wheels for Python versions the machine no longer has, and no repository's
213 /// lockfile will ever say so. This is where that ceiling is written down.
214 ///
215 /// **It never deletes anything on its own.** `devp caches` marks a cache over its
216 /// cap and `devp caches clear --over-cap` empties exactly those; nothing dev-prune
217 /// runs on a schedule touches a cache, which is a promise `devp caches` prints in
218 /// so many words and a size cap is not a reason to break.
219 ///
220 /// Keyed by the names `devp caches clear <MANAGER>` takes, not by adapter name.
221 /// They mostly agree — `npm`, `uv`, `cargo`, `go` — but `pip`, `nuget`, `conan`,
222 /// `conda`, `vcpkg` and `hex` are caches with no adapter, and `venv`, `terraform`
223 /// and `dart` are adapters with no cache. Empty by default: no cache is too big
224 /// until someone says what too big is.
225 #[serde(default)]
226 pub cache_max_gb: BTreeMap<String, u64>,
227 /// Language for dev-prune's own headings and summary lines.
228 ///
229 /// English by default, and English wherever a translation has not reached a string
230 /// yet -- see [`crate::i18n`] for what is translated and, more importantly, what is
231 /// not: `--json`, exit codes, flag names, config keys and the sentences a refusal
232 /// prints stay in English in every language, because they are a contract or a
233 /// diagnosis rather than prose.
234 ///
235 /// `DEV_PRUNE_LANG` overrides this for one invocation. An unrecognised code falls
236 /// back to English rather than failing.
237 #[serde(default = "default_language")]
238 pub language: String,
239}
240
241fn default_build_idle_days() -> u64 {
242 constants::DEFAULT_BUILD_IDLE_DAYS
243}
244
245fn default_require_confirmation() -> bool {
246 constants::DEFAULT_REQUIRE_CONFIRMATION
247}
248
249fn default_command_timeout_secs() -> u64 {
250 constants::DEFAULT_COMMAND_TIMEOUT_SECS
251}
252
253fn default_auto_hooks() -> bool {
254 constants::DEFAULT_AUTO_HOOKS
255}
256
257fn default_auto_setup() -> bool {
258 constants::DEFAULT_AUTO_SETUP
259}
260
261fn default_auto_config() -> bool {
262 constants::DEFAULT_AUTO_CONFIG
263}
264
265fn default_update_check() -> bool {
266 constants::DEFAULT_UPDATE_CHECK
267}
268
269fn default_auto_update() -> bool {
270 constants::DEFAULT_AUTO_UPDATE
271}
272
273fn default_min_size_mb() -> u64 {
274 constants::DEFAULT_MIN_SIZE_MB
275}
276
277fn default_scan_depth() -> usize {
278 constants::DEFAULT_SCAN_DEPTH
279}
280
281fn default_allow_manifest_rewrite() -> bool {
282 constants::DEFAULT_ALLOW_MANIFEST_REWRITE
283}
284
285fn default_update_check_interval_days() -> i64 {
286 constants::UPDATE_CHECK_INTERVAL_DAYS
287}
288
289fn default_update_check_timeout_secs() -> u64 {
290 constants::UPDATE_CHECK_TIMEOUT_SECS
291}
292
293fn default_auto_hooks_chain() -> bool {
294 constants::DEFAULT_AUTO_HOOKS_CHAIN
295}
296
297fn default_language() -> String {
298 constants::DEFAULT_LANGUAGE.to_string()
299}
300
301impl Default for Settings {
302 fn default() -> Self {
303 Self {
304 idle_days: constants::DEFAULT_IDLE_DAYS,
305 check_interval_days: constants::DEFAULT_CHECK_INTERVAL_DAYS,
306 auto_daemon: constants::DEFAULT_AUTO_DAEMON,
307 auto_hooks: constants::DEFAULT_AUTO_HOOKS,
308 auto_setup: constants::DEFAULT_AUTO_SETUP,
309 auto_config: constants::DEFAULT_AUTO_CONFIG,
310 require_confirmation: constants::DEFAULT_REQUIRE_CONFIRMATION,
311 command_timeout_secs: constants::DEFAULT_COMMAND_TIMEOUT_SECS,
312 min_size_mb: constants::DEFAULT_MIN_SIZE_MB,
313 update_check: constants::DEFAULT_UPDATE_CHECK,
314 scan_depth: constants::DEFAULT_SCAN_DEPTH,
315 allow_manifest_rewrite: constants::DEFAULT_ALLOW_MANIFEST_REWRITE,
316 update_check_interval_days: constants::UPDATE_CHECK_INTERVAL_DAYS,
317 update_check_timeout_secs: constants::UPDATE_CHECK_TIMEOUT_SECS,
318 auto_hooks_chain: constants::DEFAULT_AUTO_HOOKS_CHAIN,
319 enable_cargo: false,
320 enable_gradle: false,
321 enable_maven: false,
322 enable_swift: false,
323 enable_dart: false,
324 enable_mix_build: false,
325 enable_vcpkg: false,
326 enable_cmake_build: false,
327 build_idle_days: constants::DEFAULT_BUILD_IDLE_DAYS,
328 auto_update: constants::DEFAULT_AUTO_UPDATE,
329 version_lock: constants::DEFAULT_VERSION_LOCK,
330 disabled_adapters: Vec::new(),
331 adapter_idle_days: BTreeMap::new(),
332 cache_max_gb: BTreeMap::new(),
333 language: constants::DEFAULT_LANGUAGE.to_string(),
334 }
335 }
336}
337
338/// Outcome of recording a repository's identity when it was registered.
339///
340/// Reported rather than silent: a registration that quietly absorbed another entry's
341/// prune history would be indistinguishable from one that lost it.
342#[derive(Debug, Clone, PartialEq, Eq)]
343pub enum Adoption {
344 /// No dead entry claimed this identity.
345 Nothing,
346 /// This registration took over the history of a path that no longer exists.
347 Moved(PathBuf),
348 /// More than one dead entry claims the identity, so none was chosen.
349 Ambiguous,
350}
351
352/// Metadata for a single registered repository.
353#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
354pub struct RepoEntry {
355 /// Timestamp when the repo was added to the registry.
356 pub added_at: DateTime<Utc>,
357 /// Timestamp of the last successful prune, if any.
358 pub last_pruned_at: Option<DateTime<Utc>>,
359 /// Per-repo override for idle days (overrides global setting).
360 pub override_idle_days: Option<u64>,
361 /// Whether this repo is enabled for pruning.
362 pub enabled: bool,
363 /// Cumulative bytes reclaimed from this repository.
364 ///
365 /// Recorded from 1.1.0 onward. Registries written by 1.0.0 have no such figure and
366 /// deserialize to zero, so `devp stats` says where the number starts rather than
367 /// implying a repository pruned last March never freed anything.
368 #[serde(default)]
369 pub total_freed_bytes: u64,
370 /// The repository's root commit, recorded when it was registered.
371 ///
372 /// A repository that is moved keeps this; its path does not. Without it a moved
373 /// workspace registers as a brand new repository and its prune history is stranded
374 /// on a path that will never exist again. Registries written before 1.4.0 have none,
375 /// and re-registering the repository is what fills it in.
376 #[serde(default, skip_serializing_if = "Option::is_none")]
377 pub identity: Option<String>,
378}
379
380impl RepoEntry {
381 /// Creates a new `RepoEntry` with the current timestamp.
382 pub fn new() -> Self {
383 Self {
384 added_at: Utc::now(),
385 last_pruned_at: None,
386 override_idle_days: None,
387 enabled: true,
388 total_freed_bytes: 0,
389 identity: None,
390 }
391 }
392}
393
394impl Default for RepoEntry {
395 fn default() -> Self {
396 Self::new()
397 }
398}
399
400/// Resolve where a repository's shared git directory actually lives.
401///
402/// `.git` is a directory in an ordinary clone, but in worktrees and submodules it is a
403/// one-line `gitdir: <path>` pointer file — and a worktree's private gitdir in turn
404/// holds a `commondir` file pointing at the shared one, which is where `info/exclude`
405/// lives. Returns `None` when the path is not inside a git repository at all.
406fn git_common_dir(repo_path: &Path) -> Option<PathBuf> {
407 let dot_git = repo_path.join(".git");
408 let git_dir = if dot_git.is_dir() {
409 dot_git
410 } else {
411 let pointer = fs::read_to_string(&dot_git).ok()?;
412 let target = pointer.strip_prefix("gitdir:")?.trim();
413 let target = Path::new(target);
414 if target.is_absolute() {
415 target.to_path_buf()
416 } else {
417 repo_path.join(target)
418 }
419 };
420 if let Ok(common) = fs::read_to_string(git_dir.join("commondir")) {
421 let target = Path::new(common.trim());
422 if target.is_absolute() {
423 return Some(target.to_path_buf());
424 }
425 return Some(git_dir.join(target));
426 }
427 Some(git_dir)
428}
429
430/// Ensure an entry (e.g. ".devprune.json") is in the repository's `.git/info/exclude`.
431///
432/// The exclude file, not `.gitignore`: the config records one machine's preferences,
433/// and `.gitignore` is a tracked file shared by everyone who clones the repository —
434/// appending to it silently puts an uncommitted change in the user's diff. The exclude
435/// file gives the same "never shows up in `git status`" result without touching
436/// anything the repository tracks.
437pub fn ensure_in_git_exclude(repo_path: &Path, entry: &str) -> Result<()> {
438 let Some(git_dir) = git_common_dir(repo_path) else {
439 return Ok(());
440 };
441 let info_dir = git_dir.join("info");
442 fs::create_dir_all(&info_dir)?;
443 let exclude_path = info_dir.join("exclude");
444 if exclude_path.exists() {
445 let content = fs::read_to_string(&exclude_path)?;
446 if !content.lines().any(|line| line.trim() == entry) {
447 let mut file = fs::OpenOptions::new().append(true).open(&exclude_path)?;
448 let prefix = if content.ends_with('\n') || content.is_empty() {
449 ""
450 } else {
451 "\n"
452 };
453 writeln!(file, "{prefix}{entry}")?;
454 }
455 } else {
456 fs::write(&exclude_path, format!("{entry}\n"))?;
457 }
458 Ok(())
459}
460
461/// Normalise a repository path into the form used as a registry key.
462///
463/// Falls back to the path as given when it cannot be canonicalised (e.g. it no longer
464/// exists), so entries for deleted repos stay addressable.
465pub fn canonical_key(path: &Path) -> PathBuf {
466 path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
467}
468
469/// Resolve `.` and `..` segments and anchor a relative path to the working directory,
470/// for paths that no longer exist and so cannot be canonicalised whole. The deepest
471/// ancestor that still exists is canonicalised and the missing tail re-appended:
472/// registry keys are canonical, and a deleted repo named through a symlinked parent —
473/// macOS's `/var` → `/private/var` temp tree being the everyday case — would otherwise
474/// spell the same directory through a different root and never compare equal.
475fn lexical_absolute(path: &Path) -> PathBuf {
476 use std::path::Component;
477 let mut out = if path.is_absolute() {
478 PathBuf::new()
479 } else {
480 std::env::current_dir().unwrap_or_default()
481 };
482 for comp in path.components() {
483 match comp {
484 Component::CurDir => {}
485 Component::ParentDir => {
486 out.pop();
487 }
488 other => out.push(other.as_os_str()),
489 }
490 }
491 let mut prefix = out.as_path();
492 while !prefix.as_os_str().is_empty() {
493 if let Ok(real) = prefix.canonicalize() {
494 if let Ok(tail) = out.strip_prefix(prefix) {
495 return real.join(tail);
496 }
497 break;
498 }
499 match prefix.parent() {
500 Some(parent) => prefix = parent,
501 None => break,
502 }
503 }
504 out
505}
506
507/// Whether two paths name the same directory, tolerating the differences
508/// canonicalisation normally absorbs: the Windows `\\?\` prefix, separator style,
509/// trailing separators, and case on Windows.
510fn loose_path_eq(a: &Path, b: &Path) -> bool {
511 let norm = |p: &Path| {
512 let s = p.to_string_lossy().replace('\\', "/");
513 let s = s.strip_prefix("//?/").unwrap_or(&s);
514 let s = s.trim_end_matches('/').to_string();
515 if cfg!(windows) { s.to_lowercase() } else { s }
516 };
517 norm(a) == norm(b)
518}
519
520/// Expand a leading `~` to the user's home directory.
521///
522/// POSIX shells do this before the argument ever reaches a program, so on Linux and
523/// macOS it is usually a no-op. PowerShell and cmd do not: they hand a native
524/// executable the literal three characters `~/C`, and `devp init ~/Code` — the exact
525/// line in the README and on the landing page — would register a directory called `~`
526/// sitting in the current working directory. Quoting defeats the expansion in *every*
527/// shell, so `devp init "~/Code"` needs this too.
528///
529/// Only a bare `~` or a `~` followed by a separator is expanded. `~alice` means "some
530/// other user's home" in shell syntax and cannot be resolved portably, and `~backup` is
531/// a perfectly ordinary directory name.
532pub fn expand_tilde(raw: &str) -> String {
533 let Some(rest) = raw.strip_prefix('~') else {
534 return raw.to_string();
535 };
536 if !(rest.is_empty() || rest.starts_with('/') || rest.starts_with('\\')) {
537 return raw.to_string();
538 }
539 let Some(home) = dirs::home_dir() else {
540 // No home directory to expand to. Handing back the literal `~` lets the caller
541 // fail with "no such directory", which is a better error than a silent guess.
542 return raw.to_string();
543 };
544 if rest.is_empty() {
545 return home.to_string_lossy().into_owned();
546 }
547 home.join(rest.trim_start_matches(['/', '\\']))
548 .to_string_lossy()
549 .into_owned()
550}
551
552/// Structured per-repository configuration file stored inside repo roots as `.devprune.json`.
553#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
554pub struct PerRepoConfig {
555 /// JSON Schema reference URL for IDE IntelliSense and validation.
556 #[serde(rename = "$schema", default = "default_schema_url")]
557 pub schema: String,
558 /// Custom display name for this project in TUI and CLI status views.
559 #[serde(default)]
560 pub project_name: Option<String>,
561 /// Whether this repository is ignored/excluded from pruning.
562 #[serde(default)]
563 pub ignore: bool,
564 /// Disable global Git auto-registration hooks for this specific workspace.
565 #[serde(default)]
566 pub disable_hooks: bool,
567 /// Disable background daemon automated pruning pass for this specific workspace.
568 #[serde(default)]
569 pub disable_daemon: bool,
570 /// Custom override for idle days threshold (overrides global settings).
571 #[serde(default)]
572 pub override_idle_days: Option<u64>,
573 /// Custom override for the size floor, in MiB (overrides global `min_size_mb`).
574 ///
575 /// `Some(0)` is a meaningful value: it turns the floor off for this repository even
576 /// when a global floor is set.
577 #[serde(default)]
578 pub min_size_mb: Option<u64>,
579 /// Custom override for how deep discovery walks this repository.
580 ///
581 /// The setting that most often needs to differ per repository rather than globally:
582 /// one deeply-nested monorepo should not make every other repository pay for a
583 /// deeper walk. Clamped to [`constants::MAX_SCAN_DEPTH_LIMIT`] like the global one.
584 #[serde(default)]
585 pub scan_depth: Option<usize>,
586 /// What this project declares prunable beyond what an adapter can recognise.
587 #[serde(default, skip_serializing_if = "Option::is_none")]
588 pub prunable: Option<Prunable>,
589}
590
591/// The nested half of a repository's config: what this project says is rebuildable.
592///
593/// A section rather than a top-level key, because the keys above it are the whole of
594/// what a repository could say in 1.0.0 and the list of things it might want to say is
595/// not finished. Everything that arrives later and describes *what to delete* belongs
596/// under this heading with `directories`, so the file grows a section at a time instead
597/// of a scatter of top-level names nobody can group by eye.
598#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
599pub struct Prunable {
600 /// Directories dev-prune would never find on its own, each with its way back.
601 #[serde(default, skip_serializing_if = "Vec::is_empty")]
602 pub directories: Vec<DeclaredDir>,
603 /// Declared paths to leave alone on this machine, whoever declared them.
604 ///
605 /// `project.devprune.json` is committed, so one person's `scratch` is everybody's
606 /// `scratch`, and the teammate whose copy is holding something had no way to say so
607 /// short of editing a file the whole team shares. Same spelling as a `path` in
608 /// `directories`; the entry it names is skipped entirely.
609 #[serde(default, skip_serializing_if = "Vec::is_empty")]
610 pub exclude: Vec<String>,
611}
612
613/// One directory a project declares prunable, and the command that puts it back.
614///
615/// Every adapter in this tool earns the right to delete a directory by finding a
616/// lockfile that can rebuild it. A declaration is the same bargain made by hand: the
617/// project states the directory, and states what rebuilds it, and dev-prune checks that
618/// the stated command is one this machine could actually run before it deletes anything.
619///
620/// `rebuild` is required, and required is the point. An optional one would have made
621/// "delete this, I have no idea how to get it back" the path of least resistance in a
622/// file that gets committed and cloned.
623#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
624pub struct DeclaredDir {
625 /// Repository-relative, `/`-separated. Never absolute, never `..`, never `.git`.
626 pub path: String,
627 /// The command that rebuilds it. Shown, never run — see [`crate::declared`].
628 pub rebuild: String,
629 /// Why this is safe to lose, in the project's own words. Printed beside the path.
630 #[serde(default, skip_serializing_if = "Option::is_none")]
631 pub why: Option<String>,
632}
633
634// Deliberately absent: `allow_manifest_rewrite`.
635//
636// Only the settings whose right value depends on the *project* have a per-repository
637// form. `allow_manifest_rewrite` is a permission the user grants their own machine, and
638// — exactly as with `post_prune_command` below — nothing stops a project from committing
639// its `.devprune.json`: the `.git/info/exclude` entry [`PerRepoConfig::save_to_repo`]
640// writes is local to one clone and excludes nothing already tracked. A
641// per-repository form would therefore let a repository nobody has read grant itself the
642// right to have `cargo generate-lockfile` / `go mod tidy` rewrite its tracked manifests
643// during an unattended pass. The `auto_*` and `update_check*` settings describe the
644// machine rather than a project and would mean nothing here either.
645
646// Removed: `custom_bloat_dirs` and `post_prune_command`.
647//
648// Both were serialized, schema'd and documented but never read by any code path, so
649// setting them did nothing. `post_prune_command` is also not a feature that should be
650// reintroduced casually: nothing stops a project from committing its `.devprune.json`,
651// so honouring it would mean cloning an untrusted repository and running `devp` hands
652// that repository arbitrary code execution on the user's machine.
653
654fn default_schema_url() -> String {
655 if let Ok(config_dir) = Registry::config_dir() {
656 let local_schema = config_dir.join("bin").join("devprune.schema.json");
657 if local_schema.exists() {
658 // `file://` + `/` + an absolute path. Unix paths already start with a
659 // separator, so pasting them in unconditionally produced `file:////home/...`
660 // — four slashes, which editors reject, leaving the `$schema` link dead and
661 // no IntelliSense at all on the platform where most of them run.
662 return file_uri(&crate::output::clean_path(&local_schema));
663 }
664 }
665 constants::JSON_SCHEMA_URL.to_string()
666}
667
668/// A `file://` URI for an absolute path.
669///
670/// `file://` + `/` + the path. Unix paths already start with a separator, so pasting one
671/// in unconditionally produced `file:////home/...` — four slashes, which editors reject,
672/// leaving the `$schema` link dead and no IntelliSense at all on the platform where most
673/// of them run.
674fn file_uri(clean_path: &str) -> String {
675 format!("file:///{}", clean_path.trim_start_matches('/'))
676}
677
678impl Default for PerRepoConfig {
679 fn default() -> Self {
680 Self {
681 schema: default_schema_url(),
682 project_name: None,
683 ignore: false,
684 disable_hooks: false,
685 disable_daemon: false,
686 override_idle_days: None,
687 min_size_mb: None,
688 scan_depth: None,
689 prunable: None,
690 }
691 }
692}
693
694impl PerRepoConfig {
695 /// Load per-repo config from `.devprune.json`, or `None` when there is no such file.
696 ///
697 /// This is the only loader. There used to be a second one that returned `None` for a
698 /// file that failed to parse as well as for one that was absent, and every caller of
699 /// it then went on to act as though the repository had no configuration: the prune
700 /// pass ignored an `"ignore": true` it could not read, and the two workspace toggles
701 /// wrote a fresh default file straight over the user's broken one, taking every
702 /// override in it with them. A caller that genuinely does not care — the display-name
703 /// lookup — says so with `.ok().flatten()`.
704 pub fn load_with_diagnostics(repo_path: &Path) -> Result<Option<Self>, String> {
705 Ok(RepoConfigLayers::load(repo_path)?.effective())
706 }
707
708 /// Save per-repo config to `.devprune.json` in the repo root, and record it in the
709 /// repository's `.git/info/exclude` so it never shows up in `git status`.
710 pub fn save_to_repo(&self, repo_path: &Path) -> Result<()> {
711 let config_file = repo_path.join(constants::PER_REPO_CONFIG_FILE);
712 let content = serde_json::to_string_pretty(self)?;
713 fs::write(&config_file, content)?;
714 let _ = ensure_in_git_exclude(repo_path, constants::PER_REPO_CONFIG_FILE);
715 let _ = ensure_in_git_exclude(repo_path, constants::DEVPRUNE_IGNORE_FILE);
716 Ok(())
717 }
718
719 /// Which of a repository's config files exist and do not parse, and why.
720 ///
721 /// [`load_with_diagnostics`](Self::load_with_diagnostics) collapses both into one
722 /// refusal, which is the right answer for every reader: a config that cannot be read
723 /// is a repository dev-prune will not touch, whichever file it was in. `devp doctor`
724 /// is the one caller that has to know which, because it repairs the personal file by
725 /// renaming it aside and must never do that to a file the user has committed.
726 pub fn broken_files(repo_path: &Path) -> Vec<(&'static str, String)> {
727 [
728 constants::PROJECT_REPO_CONFIG_FILE,
729 constants::PER_REPO_CONFIG_FILE,
730 ]
731 .into_iter()
732 .filter_map(|name| match read_layer(&repo_path.join(name)) {
733 Err(e) => Some((name, e)),
734 Ok(_) => None,
735 })
736 .collect()
737 }
738
739 /// Keys a repository config file spells out that dev-prune does not read.
740 ///
741 /// Unknown keys are tolerated on purpose — a file written by a newer dev-prune must
742 /// not stop an older one from reading the keys it does know — so
743 /// `deny_unknown_fields` is the one fix this must never become. The cost of that
744 /// tolerance is that a typo (`idle_days` for `override_idle_days`) silently does
745 /// nothing, and nothing on this machine ever tells its author why. This is the
746 /// diagnostic half: `devp doctor` names each stray key, and behaviour changes
747 /// nowhere.
748 pub fn unknown_keys(repo_path: &Path) -> Vec<(&'static str, String)> {
749 const KNOWN: &[&str] = &[
750 "$schema",
751 "project_name",
752 "ignore",
753 "disable_hooks",
754 "disable_daemon",
755 "override_idle_days",
756 "min_size_mb",
757 "scan_depth",
758 "prunable",
759 ];
760 const KNOWN_PRUNABLE: &[&str] = &["directories", "exclude"];
761 const KNOWN_DIRECTORY: &[&str] = &["path", "rebuild", "why"];
762
763 let mut out = Vec::new();
764 for name in [
765 constants::PROJECT_REPO_CONFIG_FILE,
766 constants::PER_REPO_CONFIG_FILE,
767 ] {
768 let Ok(content) = fs::read_to_string(repo_path.join(name)) else {
769 continue;
770 };
771 let Ok(serde_json::Value::Object(map)) = serde_json::from_str(&content) else {
772 continue;
773 };
774 for key in map.keys().filter(|k| !KNOWN.contains(&k.as_str())) {
775 out.push((name, key.clone()));
776 }
777 let Some(serde_json::Value::Object(prunable)) = map.get("prunable") else {
778 continue;
779 };
780 for key in prunable
781 .keys()
782 .filter(|k| !KNOWN_PRUNABLE.contains(&k.as_str()))
783 {
784 out.push((name, format!("prunable.{key}")));
785 }
786 if let Some(serde_json::Value::Array(dirs)) = prunable.get("directories") {
787 for entry in dirs.iter().filter_map(|d| d.as_object()) {
788 for key in entry
789 .keys()
790 .filter(|k| !KNOWN_DIRECTORY.contains(&k.as_str()))
791 {
792 out.push((name, format!("prunable.directories[].{key}")));
793 }
794 }
795 }
796 }
797 out
798 }
799
800 /// The personal `.devprune.json` alone, for a caller about to write it back.
801 ///
802 /// [`load_with_diagnostics`](Self::load_with_diagnostics) answers "what is in force
803 /// here", which is the merge of both files and the right answer for everything that
804 /// reads. It is the wrong answer for anything that writes: saving it copies the
805 /// project file's values into the personal one, and the next edit to the project
806 /// file leaves that copy behind, silently overriding the file it was copied from.
807 pub fn load_personal_for_write(repo_path: &Path) -> Result<Option<Self>, String> {
808 Ok(RepoConfigLayers::load(repo_path)?
809 .personal_config()
810 .cloned())
811 }
812}
813
814/// Write a starter `project.devprune.json`: a schema link, and the empty section.
815///
816/// Deliberately not a serialized [`PerRepoConfig::default`]. Every scalar key the
817/// project file names is a key it wins, so writing all of them out would have `--team`
818/// quietly take over every setting in the `.devprune.json` beside it — including the
819/// ones that file was created to hold. An empty team file decides nothing until the team
820/// decides something, and the `$schema` link is what makes deciding it a matter of
821/// autocomplete rather than of remembering the key names.
822///
823/// The one thing written out is the empty `prunable.directories`, which decides nothing
824/// either — an empty list adds no directories. It is there because a section nobody can
825/// see is a section nobody fills in, and this is the file a person or an agent is
826/// expected to fill in.
827///
828/// No `ensure_in_git_exclude`, and that omission is the entire point. [`PerRepoConfig::
829/// save_to_repo`] hides what it writes because one person's overrides are nobody else's
830/// business; hiding this one would leave it identical to the file beside it and useful
831/// to nobody.
832pub fn write_project_starter(repo_path: &Path) -> Result<()> {
833 let file = repo_path.join(constants::PROJECT_REPO_CONFIG_FILE);
834 let starter = serde_json::json!({
835 "$schema": default_schema_url(),
836 "prunable": { "directories": [] },
837 });
838 fs::write(&file, serde_json::to_string_pretty(&starter)?)?;
839 Ok(())
840}
841
842/// Which of a repository's two config files an effective value came from.
843#[derive(Debug, Clone, Copy, PartialEq, Eq)]
844pub enum ConfigSource {
845 /// Spelled out in the committed `project.devprune.json`.
846 Project,
847 /// Spelled out in the git-excluded `.devprune.json`.
848 Personal,
849 /// In neither file, so whatever the global setting or the built-in default says.
850 Default,
851}
852
853impl ConfigSource {
854 /// The file this answer came from, or where to look when it came from no file.
855 pub fn label(self) -> &'static str {
856 match self {
857 Self::Project => constants::PROJECT_REPO_CONFIG_FILE,
858 Self::Personal => constants::PER_REPO_CONFIG_FILE,
859 Self::Default => "global setting",
860 }
861 }
862}
863
864/// A repository's configuration as the two files that can contribute to it.
865///
866/// The project file wins every scalar key it names, and the personal file answers the
867/// rest. That is the inverse of the usual local-overrides-committed convention, and
868/// deliberately so: the settings here are the ones a *project* decides, and a team that
869/// has written down "this repository is not worth pruning" wants that to survive a
870/// teammate's stale personal file rather than lose to it.
871///
872/// "Names a key" means the key is literally in the file. A project file silent on
873/// `ignore` does not overrule the personal one with serde's `false`, because a default
874/// filled in by the deserializer is not something anybody wrote down.
875///
876/// `prunable.directories` is the one thing that unions instead of winning. It is a list
877/// of separate declarations rather than a single decided value, so there is nothing for
878/// one file to win: "the team says this cache is rebuildable" and "so is this one on my
879/// machine" are both true at once, and a rule that let the committed file silence the
880/// personal list would delete somebody's own declaration the day their team wrote their
881/// first one. `prunable.exclude` unions for the opposite reason: a veto only ever
882/// deletes less, so it is safe to honour from whichever file wrote it.
883///
884/// Nothing here widens what a repository can ask for. Both files deserialize into the
885/// same [`PerRepoConfig`], so the two settings the type deliberately does not carry —
886/// `allow_manifest_rewrite` and `post_prune_command` — are still absent from both, and
887/// every field that is present is either display-only or scope-shaping. A committed
888/// `.devprune.json` has had exactly this reach since 1.0.0, since the `.git/info/exclude`
889/// entry is local to one clone and excludes nothing already tracked; the shared file
890/// makes that reach a named, documented file instead of an accident.
891pub struct RepoConfigLayers {
892 /// The committed file and the keys it actually spells out.
893 project: Option<(PerRepoConfig, HashSet<String>)>,
894 /// The git-excluded file and the keys it actually spells out.
895 personal: Option<(PerRepoConfig, HashSet<String>)>,
896}
897
898impl RepoConfigLayers {
899 /// Read both files. `Err` if either exists and does not parse.
900 pub fn load(repo_path: &Path) -> Result<Self, String> {
901 Ok(Self {
902 project: read_layer(&repo_path.join(constants::PROJECT_REPO_CONFIG_FILE))?,
903 personal: read_layer(&repo_path.join(constants::PER_REPO_CONFIG_FILE))?,
904 })
905 }
906
907 /// The merged configuration, or `None` when the repository has neither file.
908 ///
909 /// `None` rather than the defaults, because every caller of this treats "no config"
910 /// and "a config that happens to match the defaults" as the same thing to act on but
911 /// not the same thing to report.
912 pub fn effective(&self) -> Option<PerRepoConfig> {
913 if self.project.is_none() && self.personal.is_none() {
914 return None;
915 }
916 let base = self
917 .personal
918 .as_ref()
919 .map(|(c, _)| c.clone())
920 .unwrap_or_default();
921 let Some((project, keys)) = &self.project else {
922 return Some(base);
923 };
924 let said = |k: &str| keys.contains(k);
925 let declared = merge_declarations(project.prunable.as_ref(), base.prunable);
926 Some(PerRepoConfig {
927 // Never taken from the project file. `$schema` points at a validator, and the
928 // one this clone should resolve is the one this machine has —
929 // `default_schema_url` prefers a local copy when there is one, which a
930 // teammate's committed absolute path would override with a file that does
931 // not exist here.
932 schema: base.schema,
933 project_name: pick(
934 said("project_name"),
935 &project.project_name,
936 base.project_name,
937 ),
938 ignore: pick(said("ignore"), &project.ignore, base.ignore),
939 disable_hooks: pick(
940 said("disable_hooks"),
941 &project.disable_hooks,
942 base.disable_hooks,
943 ),
944 disable_daemon: pick(
945 said("disable_daemon"),
946 &project.disable_daemon,
947 base.disable_daemon,
948 ),
949 override_idle_days: pick(
950 said("override_idle_days"),
951 &project.override_idle_days,
952 base.override_idle_days,
953 ),
954 min_size_mb: pick(said("min_size_mb"), &project.min_size_mb, base.min_size_mb),
955 scan_depth: pick(said("scan_depth"), &project.scan_depth, base.scan_depth),
956 prunable: declared,
957 })
958 }
959
960 /// The committed file as it stands, before the personal one fills any gaps in.
961 pub fn project_config(&self) -> Option<&PerRepoConfig> {
962 self.project.as_ref().map(|(c, _)| c)
963 }
964
965 /// The personal file as it stands, before the project one overrules any of it.
966 pub fn personal_config(&self) -> Option<&PerRepoConfig> {
967 self.personal.as_ref().map(|(c, _)| c)
968 }
969
970 /// Which file each setting's effective value came from.
971 ///
972 /// This is what gets shown instead of copying the project file's values into
973 /// `.devprune.json` as a visible "mirror". A second copy of a value is a second copy
974 /// free to drift from the first, and the question somebody actually has in front of
975 /// two config files is not "what does each say" but "which one won".
976 pub fn rows(&self) -> Vec<(&'static str, String, ConfigSource)> {
977 let cfg = self.effective().unwrap_or_default();
978 vec![
979 (
980 "project_name",
981 opt(&cfg.project_name),
982 self.source_of("project_name"),
983 ),
984 ("ignore", cfg.ignore.to_string(), self.source_of("ignore")),
985 (
986 "disable_hooks",
987 cfg.disable_hooks.to_string(),
988 self.source_of("disable_hooks"),
989 ),
990 (
991 "disable_daemon",
992 cfg.disable_daemon.to_string(),
993 self.source_of("disable_daemon"),
994 ),
995 (
996 "override_idle_days",
997 opt(&cfg.override_idle_days),
998 self.source_of("override_idle_days"),
999 ),
1000 (
1001 "min_size_mb",
1002 opt(&cfg.min_size_mb),
1003 self.source_of("min_size_mb"),
1004 ),
1005 (
1006 "scan_depth",
1007 opt(&cfg.scan_depth),
1008 self.source_of("scan_depth"),
1009 ),
1010 ]
1011 }
1012
1013 /// Which file spelled this key out, in precedence order.
1014 pub fn source_of(&self, key: &str) -> ConfigSource {
1015 if self.project.as_ref().is_some_and(|(_, k)| k.contains(key)) {
1016 ConfigSource::Project
1017 } else if self.personal.as_ref().is_some_and(|(_, k)| k.contains(key)) {
1018 ConfigSource::Personal
1019 } else {
1020 ConfigSource::Default
1021 }
1022 }
1023}
1024
1025/// `project` when the project file named this key, `personal` otherwise.
1026fn pick<T: Clone>(project_said_so: bool, project: &T, personal: T) -> T {
1027 if project_said_so {
1028 project.clone()
1029 } else {
1030 personal
1031 }
1032}
1033
1034/// Both files' declarations, the committed ones first, one entry per path.
1035///
1036/// Deduplicated by path rather than by whole entry: two files naming the same directory
1037/// with two different `rebuild` commands is one directory, and the committed one is the
1038/// answer — a teammate whose personal file still names last year's build script should
1039/// get the project's current one, not a second delete of the same path.
1040///
1041/// `exclude` unions the same way and from either file. It can only ever take a directory
1042/// out of play, so there is nothing for the committed file to protect by winning it —
1043/// and the person who needs one is by definition the person that file is wrong for.
1044fn merge_declarations(project: Option<&Prunable>, personal: Option<Prunable>) -> Option<Prunable> {
1045 let mut directories: Vec<DeclaredDir> =
1046 project.map(|p| p.directories.clone()).unwrap_or_default();
1047 let mut exclude: Vec<String> = project.map(|p| p.exclude.clone()).unwrap_or_default();
1048 let personal = personal.unwrap_or_default();
1049 for dir in personal.directories {
1050 if !directories.iter().any(|d| d.path == dir.path) {
1051 directories.push(dir);
1052 }
1053 }
1054 for path in personal.exclude {
1055 if !exclude.contains(&path) {
1056 exclude.push(path);
1057 }
1058 }
1059 if directories.is_empty() && exclude.is_empty() {
1060 None
1061 } else {
1062 Some(Prunable {
1063 directories,
1064 exclude,
1065 })
1066 }
1067}
1068
1069/// How an unset optional reads in the provenance table.
1070fn opt<T: std::fmt::Display>(value: &Option<T>) -> String {
1071 value
1072 .as_ref()
1073 .map_or_else(|| "not set".to_string(), ToString::to_string)
1074}
1075
1076/// Parse one config file into its values and the set of keys it actually spells out.
1077fn read_layer(path: &Path) -> Result<Option<(PerRepoConfig, HashSet<String>)>, String> {
1078 if !path.exists() {
1079 return Ok(None);
1080 }
1081 let content = fs::read_to_string(path).map_err(|e| format!("Failed to read file: {e}"))?;
1082 // `clean_path`, like every other path this tool shows. `Display` on a canonicalised
1083 // Windows path leaks the `\\?\` extended-length prefix into an error message the user
1084 // is being asked to act on.
1085 let cfg = serde_json::from_str::<PerRepoConfig>(&content)
1086 .map_err(|e| format!("Syntax error in `{}`: {e}", crate::output::clean_path(path)))?;
1087 // The same text just deserialized into a struct, so it is a JSON object and this
1088 // cannot fail; it is parsed a second time only because serde has by then thrown away
1089 // the difference between a key the file set and a key it defaulted.
1090 let keys = serde_json::from_str::<HashMap<String, serde_json::Value>>(&content)
1091 .map(|m| m.into_keys().collect())
1092 .unwrap_or_default();
1093 Ok(Some((cfg, keys)))
1094}
1095
1096/// One directory a prune pass deleted.
1097///
1098/// Enough to put it back and nothing more: which repository it belonged to, which
1099/// project inside that repository owned it, and who verified it. No file list — the
1100/// lockfile is the record of the contents, which is the whole premise of the tool.
1101#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1102pub struct PrunedDir {
1103 /// Repository root the directory belonged to.
1104 pub repo_path: PathBuf,
1105 /// Repository-relative label, `/`-separated: `node_modules`, `frontend/node_modules`.
1106 pub bloat_dir: String,
1107 /// Adapter that verified and deleted it.
1108 pub adapter: String,
1109 /// Bytes reclaimed.
1110 pub size_freed: u64,
1111 /// The language runtime the deleted directory was built against — `"3.12"` for a
1112 /// virtual environment created by Python 3.12 — so a restore can rebuild on that
1113 /// interpreter instead of on whatever happens to be first on `PATH` today.
1114 ///
1115 /// `None` for every manager that pins its own toolchain in the lockfile (cargo, npm,
1116 /// go) and for anything pruned before 1.4.0. Optional rather than required for that
1117 /// second reason: a `registry.json` written by an older version has to keep loading.
1118 #[serde(default, skip_serializing_if = "Option::is_none")]
1119 pub runtime: Option<String>,
1120}
1121
1122/// What the most recent prune pass deleted, for `devp restore --last-run`.
1123///
1124/// Only passes that actually deleted something are recorded. A later run that frees
1125/// nothing — everything was active, everything was already clean — leaves this alone,
1126/// because "put back what you just took" should still mean the pass that took something.
1127#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1128pub struct LastPrune {
1129 /// When the pass ran.
1130 pub at: DateTime<Utc>,
1131 /// Every directory it removed.
1132 pub dirs: Vec<PrunedDir>,
1133}
1134
1135/// A one-line summary of a completed prune pass, for `devp stats`.
1136///
1137/// Deliberately not a second copy of [`LastPrune`]. That one exists so
1138/// `devp restore --last-run` can put files back, so it carries the full directory list
1139/// and only ever describes the most recent pass. This one is a trend line — four numbers
1140/// per pass, bounded by [`constants::PRUNE_HISTORY_LIMIT`] — and could not restore
1141/// anything if it wanted to.
1142#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1143pub struct PruneRunSummary {
1144 /// When the pass ran.
1145 pub at: DateTime<Utc>,
1146 /// Bytes reclaimed by the pass.
1147 pub bytes_freed: u64,
1148 /// How many directories it removed.
1149 pub dirs_removed: usize,
1150 /// How many distinct repositories it touched.
1151 pub repos_touched: usize,
1152}
1153
1154/// The top-level registry structure persisted to disk.
1155#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1156pub struct Registry {
1157 /// Schema version for forward compatibility.
1158 pub version: String,
1159 /// Global settings.
1160 pub settings: Settings,
1161 /// Map of canonical repo paths to their metadata.
1162 pub repositories: HashMap<PathBuf, RepoEntry>,
1163 /// Total cumulative bytes freed historically across all prune passes.
1164 #[serde(default)]
1165 pub total_freed_bytes: u64,
1166 /// Total bytes given back by `devp caches clear`, ever, on this machine.
1167 ///
1168 /// Kept apart from `total_freed_bytes` rather than folded into it, because the two
1169 /// cost different things to undo. A prune deletes what a lockfile proves it can
1170 /// rebuild, and getting it back is one reinstall in one repository; emptying a shared
1171 /// cache costs a download in every project on the disk. Not keyed by repository for
1172 /// the same reason: a package manager's cache belongs to none of them.
1173 ///
1174 /// Recorded from 1.9.0 onward, so a registry written before then deserializes to
1175 /// zero and starts counting from the next clear.
1176 #[serde(default)]
1177 pub total_cache_freed_bytes: u64,
1178 /// How many prune passes have deleted something, ever.
1179 ///
1180 /// One per *pass*, not per repository and not per directory — a `devp run` that
1181 /// cleared eleven directories across four repositories counts once. Incremented in
1182 /// exactly one place, [`Registry::record_prune`], which is also where the pass is
1183 /// recorded for `devp restore --last-run`; keeping the two together is what stops
1184 /// them meaning different things depending on which command did the pruning.
1185 #[serde(default)]
1186 pub total_pruned_count: u64,
1187 /// List of repository paths added in the most recent init/link action (for devp undo).
1188 #[serde(default)]
1189 pub last_added_repos: Vec<PathBuf>,
1190 /// What the most recent prune pass deleted (for `devp restore --last-run`).
1191 #[serde(default)]
1192 pub last_prune: Option<LastPrune>,
1193 /// Summaries of recent prune passes, oldest first, for `devp stats`.
1194 ///
1195 /// Capped at [`constants::PRUNE_HISTORY_LIMIT`]. Recorded from 1.1.0 onward.
1196 #[serde(default)]
1197 pub prune_history: Vec<PruneRunSummary>,
1198 /// When the release check last ran, so it runs at most once every
1199 /// `UPDATE_CHECK_INTERVAL_DAYS` instead of on every command.
1200 #[serde(default)]
1201 pub last_update_check: Option<DateTime<Utc>>,
1202 /// The newest release seen by the last check, so the reminder survives until the
1203 /// user actually upgrades without needing the network again.
1204 #[serde(default)]
1205 pub latest_known_version: Option<String>,
1206 /// How fast each adapter has actually restored on this machine.
1207 ///
1208 /// Measured by `devp restore --last-run`, which is the one command that knows both
1209 /// how long a restore took and how many bytes it put back. Local only: nothing here
1210 /// is uploaded, compared against anyone else's machine, or used for anything except
1211 /// the estimate `devp status` prints. See `docs/PRIVACY.md`.
1212 #[serde(default)]
1213 pub restore_rates: BTreeMap<String, RestoreRate>,
1214}
1215
1216/// One adapter's observed restore throughput on this machine.
1217///
1218/// Totals rather than a stored average, because that is what lets a new measurement be
1219/// folded in without keeping the individual samples — and the individual samples are
1220/// per-repository, which is exactly the shape of data this tool has no business keeping.
1221#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1222pub struct RestoreRate {
1223 /// How many restores this average is made of.
1224 pub samples: u32,
1225 /// Bytes those restores put back.
1226 pub bytes: u64,
1227 /// Milliseconds they took.
1228 pub millis: u64,
1229}
1230
1231impl RestoreRate {
1232 /// Bytes per second, or `None` when the record cannot support the division.
1233 pub fn bytes_per_sec(&self) -> Option<f64> {
1234 (self.samples > 0 && self.millis > 0 && self.bytes > 0)
1235 .then(|| self.bytes as f64 * 1000.0 / self.millis as f64)
1236 }
1237}
1238
1239impl Default for Registry {
1240 fn default() -> Self {
1241 Self {
1242 version: "1.0".to_string(),
1243 settings: Settings::default(),
1244 repositories: HashMap::new(),
1245 total_freed_bytes: 0,
1246 total_cache_freed_bytes: 0,
1247 total_pruned_count: 0,
1248 last_added_repos: Vec::new(),
1249 last_prune: None,
1250 prune_history: Vec::new(),
1251 last_update_check: None,
1252 latest_known_version: None,
1253 restore_rates: BTreeMap::new(),
1254 }
1255 }
1256}
1257
1258impl Registry {
1259 /// Returns the path to the config directory (`~/.config/dev-prune/`).
1260 ///
1261 /// Uses the `dirs` crate to resolve the platform-specific config location:
1262 /// - Linux/macOS: `~/.config/dev-prune/`
1263 /// - Windows: `C:\Users\<user>\AppData\Roaming\dev-prune\` (or `~/.config/dev-prune/`)
1264 pub fn config_dir() -> Result<PathBuf> {
1265 if let Ok(override_dir) = std::env::var(constants::ENV_CONFIG_DIR_OVERRIDE) {
1266 return Ok(PathBuf::from(override_dir));
1267 }
1268 let base = dirs::config_dir().context("Could not determine config directory")?;
1269 Ok(base.join(constants::CONFIG_DIR_NAME))
1270 }
1271
1272 /// Returns the full path to the registry file.
1273 pub fn registry_path() -> Result<PathBuf> {
1274 Ok(Self::config_dir()?.join(constants::REGISTRY_FILENAME))
1275 }
1276
1277 /// Loads the registry from disk, or the defaults when there is nothing to load.
1278 ///
1279 /// Reading does not write. This used to persist the default registry on the way
1280 /// out, which made `devp --dry-run init` create the very file it had just promised
1281 /// not to write and gave `devp status --json` — documented as a pure read — a side
1282 /// effect on first use. Every command that actually changes something calls
1283 /// [`Registry::save`], and that creates the directory as needed.
1284 pub fn load() -> Result<Self> {
1285 Self::load_from(&Self::registry_path()?)
1286 }
1287
1288 /// Loads the registry from a specific path (for testing or custom locations).
1289 ///
1290 /// Non-persisting, exactly like [`Registry::load`], which is implemented on top of
1291 /// it. The two used to disagree — this one wrote the defaults out when the file was
1292 /// missing — which is the sort of difference that makes a test pass while the
1293 /// behaviour it stands in for is broken.
1294 pub fn load_from(path: &Path) -> Result<Self> {
1295 if !path.exists() {
1296 return Ok(Registry::default());
1297 }
1298 let contents = fs::read_to_string(path)
1299 .with_context(|| format!("Failed to read registry at {}", path.display()))?;
1300 serde_json::from_str(&contents)
1301 .with_context(|| format!("Failed to parse registry at {}", path.display()))
1302 }
1303
1304 /// Saves the registry to disk atomically (write to temp, then rename).
1305 pub fn save(&self) -> Result<()> {
1306 let path = Self::registry_path()?;
1307 self.save_to(&path)
1308 }
1309
1310 /// Saves the registry to a specific path (for testing or custom locations).
1311 pub fn save_to(&self, path: &Path) -> Result<()> {
1312 if let Some(parent) = path.parent() {
1313 fs::create_dir_all(parent)
1314 .with_context(|| format!("Failed to create config dir {}", parent.display()))?;
1315 }
1316 // Unique per process. A manual run and the scheduled daemon pass can save at the
1317 // same moment; with a shared `registry.json.tmp`, one process could rename the
1318 // other's half-written file into place as a torn, unparseable registry.
1319 let tmp_path = path.with_extension(format!("json.{}.tmp", std::process::id()));
1320 let contents =
1321 serde_json::to_string_pretty(self).context("Failed to serialize registry")?;
1322 {
1323 // `sync_all` before the rename, or the atomicity is only apparent: after a
1324 // power cut the rename can survive while the data does not, leaving the
1325 // registry as zero bytes — the one outcome this dance exists to prevent.
1326 use std::io::Write;
1327 let mut file = fs::File::create(&tmp_path)
1328 .with_context(|| format!("Failed to write temp registry {}", tmp_path.display()))?;
1329 file.write_all(contents.as_bytes())
1330 .with_context(|| format!("Failed to write temp registry {}", tmp_path.display()))?;
1331 file.sync_all()
1332 .with_context(|| format!("Failed to flush temp registry {}", tmp_path.display()))?;
1333 }
1334 fs::rename(&tmp_path, path)
1335 .with_context(|| format!("Failed to rename temp registry to {}", path.display()))?;
1336
1337 // A crash between write and rename strands that process's `.<pid>.tmp` forever.
1338 // Sweep siblings old enough that no live save can still own them.
1339 if let (Some(parent), Some(name)) = (path.parent(), path.file_name()) {
1340 let prefix = format!("{}.", name.to_string_lossy());
1341 if let Ok(entries) = fs::read_dir(parent) {
1342 for entry in entries.flatten() {
1343 let file_name = entry.file_name();
1344 let file_name = file_name.to_string_lossy();
1345 if file_name.starts_with(&prefix)
1346 && file_name.ends_with(".tmp")
1347 && entry
1348 .metadata()
1349 .and_then(|m| m.modified())
1350 .ok()
1351 .and_then(|t| t.elapsed().ok())
1352 .is_some_and(|age| age.as_secs() > 3600)
1353 {
1354 let _ = fs::remove_file(entry.path());
1355 }
1356 }
1357 }
1358 }
1359 Ok(())
1360 }
1361
1362 /// Adds a repository to the registry. Returns `true` if newly added, `false` if already present.
1363 pub fn add_repo(&mut self, path: PathBuf) -> bool {
1364 // The registry is keyed by path, so `./foo`, `foo/`, and the absolute form
1365 // would otherwise register as three separate repositories.
1366 let path = canonical_key(&path);
1367 if self.repositories.contains_key(&path) {
1368 return false;
1369 }
1370 self.repositories.insert(path, RepoEntry::new());
1371 true
1372 }
1373
1374 /// Record `identity` against a registered repository, and hand it the history of the
1375 /// entry it moved away from.
1376 ///
1377 /// Called after `add_repo` from both `link` and `init`. When exactly one registered
1378 /// path no longer exists on disk and carries the same root commit, that entry is the
1379 /// same repository at its old location: its `added_at`, prune history and settings
1380 /// move across and the dead row is removed. Two dead entries claiming one identity
1381 /// is a clone, not a move, so nothing is guessed — the caller says so instead.
1382 ///
1383 /// Also the backfill path. Entries registered before 1.4.0 have no identity, so
1384 /// nothing they do can be recognised as a move; re-registering them records one, and
1385 /// a single `devp init ~/code` backfills the whole registry.
1386 pub fn adopt_moved_entry(&mut self, path: &Path, identity: Option<String>) -> Adoption {
1387 let key = canonical_key(path);
1388 let Some(identity) = identity else {
1389 return Adoption::Nothing;
1390 };
1391
1392 let mut claimants: Vec<PathBuf> = self
1393 .repositories
1394 .iter()
1395 .filter(|(p, e)| {
1396 **p != key && e.identity.as_deref() == Some(identity.as_str()) && !p.exists()
1397 })
1398 .map(|(p, _)| p.clone())
1399 .collect();
1400 // Deterministic: two dead entries with one identity is a report, not a coin toss,
1401 // and the report must read the same twice.
1402 claimants.sort();
1403
1404 let adopted = match claimants.len() {
1405 0 => Adoption::Nothing,
1406 1 => Adoption::Moved(claimants.remove(0)),
1407 _ => Adoption::Ambiguous,
1408 };
1409
1410 if let Adoption::Moved(ref old) = adopted
1411 && let Some(previous) = self.repositories.remove(old)
1412 {
1413 if let Some(entry) = self.repositories.get_mut(&key) {
1414 // Everything the old path had earned. `enabled` and the idle override
1415 // come across too: a repository the user had switched off did not switch
1416 // itself back on by being moved.
1417 entry.added_at = previous.added_at;
1418 entry.last_pruned_at = previous.last_pruned_at;
1419 entry.override_idle_days = previous.override_idle_days;
1420 entry.enabled = previous.enabled;
1421 entry.total_freed_bytes = previous.total_freed_bytes;
1422 }
1423 self.last_added_repos.retain(|p| p != old);
1424 }
1425
1426 if let Some(entry) = self.repositories.get_mut(&key) {
1427 entry.identity = Some(identity);
1428 }
1429 adopted
1430 }
1431
1432 /// Whether a registered repository still has no recorded identity.
1433 ///
1434 /// The global Git hook runs `devp link --quiet` on every commit, and backfilling
1435 /// unconditionally would shell out to git and rewrite the registry once per commit
1436 /// forever. This makes it once per repository.
1437 pub fn needs_identity(&self, path: &Path) -> bool {
1438 self.repositories
1439 .get(&canonical_key(path))
1440 .is_some_and(|e| e.identity.is_none())
1441 }
1442
1443 /// Removes a repository from the registry. Returns `true` if it was present.
1444 ///
1445 /// A repository that has been deleted from disk cannot be canonicalised any more,
1446 /// so `canonical_key` falls back to the path as typed — which never equals the
1447 /// canonical key it was registered under (on Windows those carry the `\\?\`
1448 /// prefix). Unlinking a deleted repository is the most ordinary reason to unlink
1449 /// at all, so a direct miss falls back to a lexical comparison.
1450 pub fn remove_repo(&mut self, path: &Path) -> bool {
1451 let target = lexical_absolute(path);
1452 let removed = if self.repositories.remove(&canonical_key(path)).is_some() {
1453 true
1454 } else {
1455 let found = self
1456 .repositories
1457 .keys()
1458 .find(|k| loose_path_eq(k, &target))
1459 .cloned();
1460 found.is_some_and(|k| self.repositories.remove(&k).is_some())
1461 };
1462 if removed {
1463 // The undo list stores the canonical `\\?\`-prefixed spelling, while a
1464 // deleted directory can only be named lexically — strict equality misses,
1465 // and the next `devp undo` "reverts" by removing nothing.
1466 self.last_added_repos.retain(|p| !loose_path_eq(p, &target));
1467 }
1468 removed
1469 }
1470
1471 // Removed: `repo_paths` and `effective_idle_days`.
1472 //
1473 // Neither had a caller outside this file's own tests. `effective_idle_days` had also
1474 // drifted from the rule the engine actually applies: it looked the repository up by
1475 // the path as given, where every write to `repositories` goes through
1476 // `canonical_key`, so `devp`'s own relative paths would have missed the entry and
1477 // silently returned the global threshold instead of the repository's override.
1478
1479 /// Credit `bytes_freed` to one repository, and to the machine-wide total.
1480 ///
1481 /// Safe to call once per repository or once per directory — every figure it touches
1482 /// is either a sum or a timestamp, so the two styles agree. Counting *passes* is
1483 /// deliberately not done here for exactly that reason; that lives in
1484 /// [`Registry::record_prune`], which is called once per pass.
1485 pub fn mark_pruned(&mut self, path: &Path, bytes_freed: u64) {
1486 // Same rule as every other accessor: the map is keyed by `canonical_key`, so a
1487 // raw lookup would silently skip the per-repo credit for a relative or
1488 // differently-spelled path while still growing the machine-wide total.
1489 if let Some(entry) = self.repositories.get_mut(&canonical_key(path)) {
1490 entry.last_pruned_at = Some(Utc::now());
1491 entry.total_freed_bytes += bytes_freed;
1492 }
1493 self.total_freed_bytes += bytes_freed;
1494 }
1495
1496 /// Credit `bytes` to the machine's running cache-clear total.
1497 pub fn record_cache_clear(&mut self, bytes: u64) {
1498 self.total_cache_freed_bytes += bytes;
1499 }
1500
1501 /// Record what a prune pass deleted, replacing any earlier record.
1502 ///
1503 /// A pass that deleted nothing is not a pass worth remembering, so an empty list is
1504 /// ignored rather than stored — otherwise `devp run` on an already-clean machine
1505 /// would quietly throw away the record of the run the user actually wants back.
1506 ///
1507 /// This is the one place a prune pass is counted. It sets [`Registry::last_prune`],
1508 /// appends a [`PruneRunSummary`] to [`Registry::prune_history`] and bumps
1509 /// [`Registry::total_pruned_count`], because "a pass happened and it deleted things"
1510 /// is exactly the condition all three describe. Splitting them across call sites is
1511 /// how the counter previously came to mean repositories in `devp run` and directories
1512 /// in the `devp status` dashboard.
1513 /// Fold one measured restore into an adapter's running average.
1514 ///
1515 /// Ignores anything too quick to have been real work — see
1516 /// [`constants::RESTORE_RATE_MIN_MILLIS`] — because a manager that found everything
1517 /// still in its cache returns in a moment and would teach a throughput no cold
1518 /// restore can reach. That is the difference between an estimate that is optimistic
1519 /// and one that is wrong.
1520 pub fn record_restore(&mut self, adapter: &str, bytes: u64, millis: u64) {
1521 if bytes == 0 || millis < constants::RESTORE_RATE_MIN_MILLIS {
1522 return;
1523 }
1524 let rate = self.restore_rates.entry(adapter.to_string()).or_default();
1525 if rate.samples >= constants::RESTORE_RATE_SAMPLE_CAP {
1526 rate.samples /= 2;
1527 rate.bytes /= 2;
1528 rate.millis /= 2;
1529 }
1530 rate.samples += 1;
1531 rate.bytes = rate.bytes.saturating_add(bytes);
1532 rate.millis = rate.millis.saturating_add(millis);
1533 }
1534
1535 /// How long putting back `by_adapter` would take, from what this machine has
1536 /// measured.
1537 ///
1538 /// Returns the seconds and the bytes those seconds account for. Anything from an
1539 /// adapter that has never been timed here is left out of both, so a caller can say
1540 /// how much of the estimate is actually covered rather than quietly quoting a
1541 /// number for half the work. `None` when nothing is covered at all — an estimate
1542 /// with no measurement behind it is a guess, and this command does not print
1543 /// guesses.
1544 pub fn estimate_restore(&self, by_adapter: &[(String, u64)]) -> Option<(f64, u64)> {
1545 let mut secs = 0.0;
1546 let mut covered = 0u64;
1547 for (adapter, bytes) in by_adapter {
1548 let Some(rate) = self
1549 .restore_rates
1550 .get(adapter)
1551 .and_then(|r| r.bytes_per_sec())
1552 else {
1553 continue;
1554 };
1555 secs += *bytes as f64 / rate;
1556 covered = covered.saturating_add(*bytes);
1557 }
1558 (covered > 0).then_some((secs, covered))
1559 }
1560
1561 pub fn record_prune(&mut self, dirs: Vec<PrunedDir>) {
1562 self.record_prune_progress(Utc::now(), dirs);
1563 }
1564
1565 /// Record a pass's progress mid-flight, superseding this same pass's earlier record.
1566 ///
1567 /// `at` identifies the pass: a repeated call with the same timestamp replaces the
1568 /// history entry and `last_prune` it wrote before, rather than counting a second
1569 /// pass. This exists so a long pass can persist after every repository — a crash
1570 /// half-way through used to leave `devp restore --last-run` pointing at the
1571 /// *previous* pass, offering to reinstall directories that were never deleted while
1572 /// saying nothing about the ones that were.
1573 pub fn record_prune_progress(&mut self, at: DateTime<Utc>, dirs: Vec<PrunedDir>) {
1574 if dirs.is_empty() {
1575 return;
1576 }
1577 if self.prune_history.last().map(|s| s.at) == Some(at) {
1578 self.prune_history.pop();
1579 } else {
1580 self.total_pruned_count += 1;
1581 }
1582
1583 self.prune_history.push(PruneRunSummary {
1584 at,
1585 bytes_freed: dirs.iter().map(|d| d.size_freed).sum(),
1586 dirs_removed: dirs.len(),
1587 repos_touched: dirs
1588 .iter()
1589 .map(|d| &d.repo_path)
1590 .collect::<HashSet<_>>()
1591 .len(),
1592 });
1593 // Oldest first, so the overflow comes off the front.
1594 if self.prune_history.len() > constants::PRUNE_HISTORY_LIMIT {
1595 let excess = self.prune_history.len() - constants::PRUNE_HISTORY_LIMIT;
1596 self.prune_history.drain(..excess);
1597 }
1598
1599 self.last_prune = Some(LastPrune { at, dirs });
1600 }
1601
1602 /// Returns the number of registered repositories.
1603 pub fn repo_count(&self) -> usize {
1604 self.repositories.len()
1605 }
1606}
1607
1608#[cfg(test)]
1609mod tests {
1610 use super::*;
1611 use tempfile::TempDir;
1612
1613 fn test_registry_path(dir: &TempDir) -> PathBuf {
1614 dir.path().join("dev-prune").join("registry.json")
1615 }
1616
1617 fn a_pruned_dir(label: &str) -> PrunedDir {
1618 PrunedDir {
1619 repo_path: PathBuf::from("/repo"),
1620 bloat_dir: label.to_string(),
1621 adapter: "npm".to_string(),
1622 size_freed: 42,
1623 runtime: None,
1624 }
1625 }
1626
1627 #[test]
1628 fn cache_clears_accumulate_separately_from_prunes() {
1629 let dir = TempDir::new().expect("temp dir");
1630 let path = test_registry_path(&dir);
1631
1632 let mut registry = Registry::default();
1633 registry.mark_pruned(Path::new("/repo"), 42);
1634 registry.record_cache_clear(6_000_000_000);
1635 registry.record_cache_clear(2_000_000_000);
1636 registry.save_to(&path).expect("saved");
1637
1638 let reloaded = Registry::load_from(&path).expect("reloaded");
1639 assert_eq!(reloaded.total_cache_freed_bytes, 8_000_000_000);
1640 // The prune total is untouched by either clear. `devp stats` prints them as two
1641 // lines because emptying a shared cache is not the same promise as pruning one
1642 // repository, and one combined figure would answer neither question.
1643 assert_eq!(reloaded.total_freed_bytes, 42);
1644 }
1645
1646 #[test]
1647 fn a_registry_written_before_1_9_0_reads_the_cache_total_as_zero() {
1648 // The `#[serde(default)]`, exercised. Without it every registry on every machine
1649 // that upgraded would fail to parse, and `devp stats` would exit 1.
1650 let dir = TempDir::new().expect("temp dir");
1651 let path = test_registry_path(&dir);
1652 std::fs::create_dir_all(path.parent().expect("parent")).expect("config dir");
1653
1654 // Built by removing the one key 1.8.0 did not write, rather than hand-typed, so
1655 // this stays a test of the `default` and not of whichever unrelated field is
1656 // added to `Settings` next.
1657 let mut older = Registry {
1658 total_freed_bytes: 99,
1659 ..Default::default()
1660 };
1661 older.record_cache_clear(500);
1662 let mut document: serde_json::Value =
1663 serde_json::from_str(&serde_json::to_string(&older).expect("serialized"))
1664 .expect("re-parsed");
1665 assert!(
1666 document
1667 .as_object_mut()
1668 .expect("an object")
1669 .remove("total_cache_freed_bytes")
1670 .is_some(),
1671 "the field this test is about must be in the document to begin with"
1672 );
1673 std::fs::write(&path, document.to_string()).expect("wrote an older registry");
1674
1675 let registry = Registry::load_from(&path).expect("an older registry still parses");
1676 assert_eq!(registry.total_cache_freed_bytes, 0);
1677 assert_eq!(registry.total_freed_bytes, 99);
1678 }
1679
1680 #[test]
1681 fn a_prune_that_deleted_nothing_does_not_erase_the_last_one() {
1682 // Otherwise a second `devp run` on an already-clean machine throws away the
1683 // record of the pass the user actually wants to undo.
1684 let mut registry = Registry::default();
1685 registry.record_prune(vec![a_pruned_dir("node_modules")]);
1686 let recorded = registry.last_prune.clone().expect("first pass recorded");
1687
1688 registry.record_prune(Vec::new());
1689
1690 assert_eq!(registry.last_prune, Some(recorded));
1691 }
1692
1693 #[test]
1694 fn a_later_prune_replaces_the_record() {
1695 let mut registry = Registry::default();
1696 registry.record_prune(vec![a_pruned_dir("node_modules")]);
1697 registry.record_prune(vec![a_pruned_dir("frontend/node_modules")]);
1698
1699 let dirs = registry.last_prune.unwrap().dirs;
1700 assert_eq!(dirs.len(), 1);
1701 assert_eq!(dirs[0].bloat_dir, "frontend/node_modules");
1702 }
1703
1704 #[test]
1705 fn the_last_prune_record_survives_a_save_and_load() {
1706 // `restore --last-run` reads it out of a file written by a process that has
1707 // already exited, so the round trip is the whole feature.
1708 let dir = TempDir::new().unwrap();
1709 let path = test_registry_path(&dir);
1710
1711 let mut registry = Registry::default();
1712 registry.record_prune(vec![a_pruned_dir("frontend/node_modules")]);
1713 registry.save_to(&path).unwrap();
1714
1715 let loaded = Registry::load_from(&path).unwrap();
1716 assert_eq!(loaded.last_prune, registry.last_prune);
1717 }
1718
1719 #[test]
1720 fn a_registry_written_before_the_field_existed_still_loads() {
1721 // The registry on disk predates `last_prune`; a missing key means "no pass
1722 // recorded", not a parse failure that would lock the user out of their config.
1723 let dir = TempDir::new().unwrap();
1724 let path = test_registry_path(&dir);
1725 fs::create_dir_all(path.parent().unwrap()).unwrap();
1726 fs::write(
1727 &path,
1728 r#"{"version":"1.0","settings":{"idle_days":15,"check_interval_days":2,
1729 "auto_daemon":true},"repositories":{}}"#,
1730 )
1731 .unwrap();
1732
1733 let loaded = Registry::load_from(&path).unwrap();
1734 assert_eq!(loaded.last_prune, None);
1735 }
1736
1737 #[test]
1738 fn a_leading_tilde_becomes_the_home_directory() {
1739 // The whole reason this exists: PowerShell hands `devp init ~/Code` straight
1740 // through, so without expansion the registry gains a repository at `.\~\Code`.
1741 let home = dirs::home_dir().expect("test host has a home directory");
1742
1743 assert_eq!(expand_tilde("~"), home.to_string_lossy());
1744 assert_eq!(
1745 expand_tilde("~/Code"),
1746 home.join("Code").to_string_lossy(),
1747 "forward slash, as typed in every shell"
1748 );
1749 assert_eq!(
1750 expand_tilde("~\\Code"),
1751 home.join("Code").to_string_lossy(),
1752 "backslash, as typed in PowerShell"
1753 );
1754 }
1755
1756 #[test]
1757 fn a_tilde_that_is_not_a_home_reference_is_left_alone() {
1758 // `~alice` is another user's home in shell syntax and cannot be resolved
1759 // portably; `~backup` and `./~tmp` are ordinary directory names. Rewriting any
1760 // of them would silently point the user at the wrong directory.
1761 for raw in ["~alice/Code", "~backup", "./~tmp", "Code~", "", "."] {
1762 assert_eq!(expand_tilde(raw), raw, "{raw} must survive untouched");
1763 }
1764 }
1765
1766 #[test]
1767 fn test_default_settings() {
1768 let settings = Settings::default();
1769 assert_eq!(settings.idle_days, 15);
1770 assert_eq!(settings.check_interval_days, 2);
1771 // On by default: dev-prune installs its own integrations, once per version,
1772 // and only the ones it finds missing.
1773 assert!(settings.auto_daemon);
1774 assert!(settings.auto_hooks);
1775 assert!(settings.auto_setup);
1776 }
1777
1778 #[test]
1779 fn settings_written_before_the_automation_toggles_existed_still_load() {
1780 // Real registries on disk predate `auto_hooks` / `auto_setup`; an upgrade must
1781 // read them rather than fail to parse and lose every registered repository.
1782 let json = r#"{
1783 "idle_days": 30,
1784 "check_interval_days": 2,
1785 "auto_daemon": false
1786 }"#;
1787 let settings: Settings = serde_json::from_str(json).unwrap();
1788 assert_eq!(settings.idle_days, 30);
1789 assert!(!settings.auto_daemon, "an explicit opt-out is preserved");
1790 assert!(settings.auto_hooks, "a missing key takes the default");
1791 assert!(settings.auto_setup);
1792 }
1793
1794 #[test]
1795 fn test_default_registry() {
1796 let registry = Registry::default();
1797 assert_eq!(registry.version, "1.0");
1798 assert_eq!(registry.settings, Settings::default());
1799 assert!(registry.repositories.is_empty());
1800 }
1801
1802 #[test]
1803 fn test_repo_entry_new() {
1804 let entry = RepoEntry::new();
1805 assert!(entry.enabled);
1806 assert!(entry.last_pruned_at.is_none());
1807 assert!(entry.override_idle_days.is_none());
1808 }
1809
1810 #[test]
1811 fn test_save_and_load() {
1812 let tmp = TempDir::new().unwrap();
1813 let path = test_registry_path(&tmp);
1814
1815 let mut registry = Registry::default();
1816 registry.add_repo(PathBuf::from("/test/repo"));
1817 registry.save_to(&path).unwrap();
1818
1819 let loaded = Registry::load_from(&path).unwrap();
1820 assert_eq!(loaded.repo_count(), 1);
1821 assert!(
1822 loaded
1823 .repositories
1824 .contains_key(&PathBuf::from("/test/repo"))
1825 );
1826 }
1827
1828 #[test]
1829 fn loading_a_missing_registry_yields_the_defaults_and_writes_nothing() {
1830 let tmp = TempDir::new().unwrap();
1831 let path = test_registry_path(&tmp);
1832
1833 let loaded = Registry::load_from(&path).unwrap();
1834 assert_eq!(loaded, Registry::default());
1835 // Reading is not writing. `devp --dry-run` and `devp status --json` both promise
1836 // to leave the disk alone, and both start by loading the registry.
1837 assert!(!path.exists(), "loading the registry created it");
1838 }
1839
1840 #[test]
1841 fn test_add_repo_returns_true_for_new() {
1842 let mut registry = Registry::default();
1843 assert!(registry.add_repo(PathBuf::from("/test/repo")));
1844 }
1845
1846 #[test]
1847 fn test_add_repo_returns_false_for_duplicate() {
1848 let mut registry = Registry::default();
1849 registry.add_repo(PathBuf::from("/test/repo"));
1850 assert!(!registry.add_repo(PathBuf::from("/test/repo")));
1851 }
1852
1853 #[test]
1854 fn test_remove_repo() {
1855 let mut registry = Registry::default();
1856 registry.add_repo(PathBuf::from("/test/repo"));
1857 assert!(registry.remove_repo(Path::new("/test/repo")));
1858 assert!(!registry.remove_repo(Path::new("/test/repo")));
1859 assert_eq!(registry.repo_count(), 0);
1860 }
1861
1862 /// macOS puts temp trees behind `/var` → `/private/var`, so a repo registered
1863 /// through the symlink is keyed under the real path — and once deleted, the
1864 /// symlinked spelling cannot be canonicalised whole. The lexical fallback must
1865 /// resolve the surviving parent, or unlink reports "not registered" for a
1866 /// directory the user is looking at in their own prompt.
1867 #[cfg(unix)]
1868 #[test]
1869 fn a_deleted_repo_named_through_a_symlinked_parent_still_unlinks() {
1870 let tmp = TempDir::new().unwrap();
1871 let real_parent = tmp.path().join("real");
1872 std::fs::create_dir(&real_parent).unwrap();
1873 let alias = tmp.path().join("alias");
1874 std::os::unix::fs::symlink(&real_parent, &alias).unwrap();
1875
1876 let repo = real_parent.join("repo");
1877 std::fs::create_dir(&repo).unwrap();
1878 let mut registry = Registry::default();
1879 registry.add_repo(alias.join("repo"));
1880 std::fs::remove_dir(&repo).unwrap();
1881
1882 assert!(registry.remove_repo(&alias.join("repo")));
1883 assert_eq!(registry.repo_count(), 0);
1884 }
1885
1886 #[test]
1887 fn test_mark_pruned() {
1888 let mut registry = Registry::default();
1889 registry.add_repo(PathBuf::from("/test/repo"));
1890 assert!(
1891 registry.repositories[&PathBuf::from("/test/repo")]
1892 .last_pruned_at
1893 .is_none()
1894 );
1895 registry.mark_pruned(Path::new("/test/repo"), 1024);
1896 assert!(
1897 registry.repositories[&PathBuf::from("/test/repo")]
1898 .last_pruned_at
1899 .is_some()
1900 );
1901 assert_eq!(registry.total_freed_bytes, 1024);
1902 // Not the pass counter — that is `record_prune`'s job, once per pass.
1903 assert_eq!(registry.total_pruned_count, 0);
1904 }
1905
1906 #[test]
1907 fn a_pass_is_counted_once_however_much_it_deleted() {
1908 // The counter is published as `prune_passes`, and it used to be incremented once
1909 // per repository by `devp run` and once per *directory* by the status dashboard,
1910 // so the same work produced a different number depending on where it started.
1911 let mut registry = Registry::default();
1912 registry.add_repo(PathBuf::from("/repo"));
1913
1914 registry.mark_pruned(Path::new("/repo"), 1024);
1915 registry.mark_pruned(Path::new("/repo"), 1024);
1916 registry.record_prune(vec![
1917 a_pruned_dir("node_modules"),
1918 a_pruned_dir("frontend/node_modules"),
1919 ]);
1920
1921 assert_eq!(registry.total_pruned_count, 1);
1922
1923 registry.record_prune(vec![a_pruned_dir("target")]);
1924 assert_eq!(registry.total_pruned_count, 2);
1925
1926 // A pass that deleted nothing is not a pass.
1927 registry.record_prune(Vec::new());
1928 assert_eq!(registry.total_pruned_count, 2);
1929 }
1930
1931 #[test]
1932 fn mark_pruned_credits_the_repo_under_its_canonical_key() {
1933 // On Windows, `canonicalize` yields a `\\?\`-prefixed path, so a registry keyed
1934 // by the canonical form and a `mark_pruned` looking up the raw form would miss —
1935 // growing the machine-wide total while the repository's own figure stayed zero.
1936 let tmp = TempDir::new().unwrap();
1937 let raw = tmp.path().to_path_buf();
1938
1939 let mut registry = Registry::default();
1940 registry.add_repo(raw.clone());
1941 registry.mark_pruned(&raw, 1024);
1942
1943 let entry = ®istry.repositories[&canonical_key(&raw)];
1944 assert_eq!(entry.total_freed_bytes, 1024);
1945 assert!(entry.last_pruned_at.is_some());
1946 assert_eq!(registry.total_freed_bytes, 1024);
1947 }
1948
1949 #[test]
1950 fn each_repository_accumulates_its_own_total() {
1951 // `devp stats` ranks repositories against each other, so the per-repo figure has
1952 // to be a running total and not the size of the most recent pass.
1953 let mut registry = Registry::default();
1954 registry.add_repo(PathBuf::from("/test/repo"));
1955 registry.add_repo(PathBuf::from("/test/other"));
1956
1957 registry.mark_pruned(Path::new("/test/repo"), 1024);
1958 registry.mark_pruned(Path::new("/test/repo"), 2048);
1959 registry.mark_pruned(Path::new("/test/other"), 512);
1960
1961 assert_eq!(
1962 registry.repositories[&PathBuf::from("/test/repo")].total_freed_bytes,
1963 3072
1964 );
1965 assert_eq!(
1966 registry.repositories[&PathBuf::from("/test/other")].total_freed_bytes,
1967 512
1968 );
1969 assert_eq!(registry.total_freed_bytes, 3584);
1970 }
1971
1972 #[test]
1973 fn the_prune_history_summarises_the_pass() {
1974 let mut registry = Registry::default();
1975 registry.record_prune(vec![
1976 a_pruned_dir("node_modules"),
1977 a_pruned_dir("frontend/node_modules"),
1978 ]);
1979
1980 let summary = registry.prune_history.last().expect("pass summarised");
1981 assert_eq!(summary.bytes_freed, 84);
1982 assert_eq!(summary.dirs_removed, 2);
1983 // Both fixtures live under `/repo`, so this is one repository, not two.
1984 assert_eq!(summary.repos_touched, 1);
1985 }
1986
1987 #[test]
1988 fn the_prune_history_is_capped_and_drops_the_oldest() {
1989 // The registry is rewritten in full on every save, so an uncapped list would grow
1990 // the file forever on a machine running the scheduled pass.
1991 let mut registry = Registry::default();
1992 for _ in 0..constants::PRUNE_HISTORY_LIMIT + 5 {
1993 registry.record_prune(vec![a_pruned_dir("node_modules")]);
1994 }
1995
1996 assert_eq!(registry.prune_history.len(), constants::PRUNE_HISTORY_LIMIT);
1997 let first = registry.prune_history.first().unwrap().at;
1998 let last = registry.prune_history.last().unwrap().at;
1999 assert!(first <= last, "oldest first");
2000 }
2001
2002 #[test]
2003 fn test_repo_count() {
2004 let mut registry = Registry::default();
2005 assert_eq!(registry.repo_count(), 0);
2006 registry.add_repo(PathBuf::from("/a"));
2007 registry.add_repo(PathBuf::from("/b"));
2008 assert_eq!(registry.repo_count(), 2);
2009 }
2010
2011 #[test]
2012 fn a_local_schema_uri_has_exactly_three_slashes_on_either_platform() {
2013 assert_eq!(
2014 file_uri("/home/dev/.config/dev-prune/bin/devprune.schema.json"),
2015 "file:///home/dev/.config/dev-prune/bin/devprune.schema.json"
2016 );
2017 assert_eq!(
2018 file_uri("C:/Users/dev/AppData/Roaming/dev-prune/bin/devprune.schema.json"),
2019 "file:///C:/Users/dev/AppData/Roaming/dev-prune/bin/devprune.schema.json"
2020 );
2021 }
2022
2023 #[test]
2024 fn a_broken_per_repo_config_is_an_error_rather_than_an_absent_one() {
2025 // The distinction the whole tool leans on: "no config" means take the defaults,
2026 // "unreadable config" means refuse — never overwrite, never prune on a guess.
2027 let tmp = TempDir::new().unwrap();
2028 let repo = tmp.path();
2029 assert_eq!(PerRepoConfig::load_with_diagnostics(repo), Ok(None));
2030
2031 fs::write(
2032 repo.join(constants::PER_REPO_CONFIG_FILE),
2033 r#"{ "ignore": true, }"#,
2034 )
2035 .unwrap();
2036 let err = PerRepoConfig::load_with_diagnostics(repo).unwrap_err();
2037 assert!(err.contains("Syntax error"), "{err}");
2038
2039 fs::write(
2040 repo.join(constants::PER_REPO_CONFIG_FILE),
2041 r#"{ "ignore": true }"#,
2042 )
2043 .unwrap();
2044 assert!(
2045 PerRepoConfig::load_with_diagnostics(repo)
2046 .unwrap()
2047 .unwrap()
2048 .ignore
2049 );
2050 }
2051
2052 /// A typo'd key must be pointed out and must not refuse the file: the same
2053 /// tolerance that lets a newer dev-prune's file load in an older one is what makes
2054 /// the typo silent everywhere else.
2055 #[test]
2056 fn a_typo_key_is_reported_but_never_refused() {
2057 let tmp = TempDir::new().unwrap();
2058 let repo = tmp.path();
2059 fs::write(
2060 repo.join(constants::PER_REPO_CONFIG_FILE),
2061 r#"{ "ignore": true, "idle_days": 30, "prunable": { "directores": [] } }"#,
2062 )
2063 .unwrap();
2064
2065 let cfg = PerRepoConfig::load_with_diagnostics(repo).unwrap().unwrap();
2066 assert!(cfg.ignore, "the keys the file spells right still apply");
2067
2068 let unknown: Vec<String> = PerRepoConfig::unknown_keys(repo)
2069 .into_iter()
2070 .map(|(_, k)| k)
2071 .collect();
2072 assert_eq!(unknown, vec!["idle_days", "prunable.directores"]);
2073 }
2074
2075 /// Drift guard: a field added to [`PerRepoConfig`] without extending the known-key
2076 /// list would make doctor warn about a key the tool itself wrote.
2077 #[test]
2078 fn every_key_the_type_serializes_is_a_known_key() {
2079 let tmp = TempDir::new().unwrap();
2080 let repo = tmp.path();
2081 let full = PerRepoConfig {
2082 project_name: Some("x".into()),
2083 ignore: true,
2084 disable_hooks: true,
2085 disable_daemon: true,
2086 override_idle_days: Some(1),
2087 min_size_mb: Some(1),
2088 scan_depth: Some(1),
2089 prunable: Some(Prunable {
2090 directories: vec![DeclaredDir {
2091 path: "scratch".into(),
2092 rebuild: "echo not needed".into(),
2093 why: Some("scratch".into()),
2094 }],
2095 exclude: vec!["dist".into()],
2096 }),
2097 ..PerRepoConfig::default()
2098 };
2099 fs::write(
2100 repo.join(constants::PER_REPO_CONFIG_FILE),
2101 serde_json::to_string_pretty(&full).unwrap(),
2102 )
2103 .unwrap();
2104 assert_eq!(PerRepoConfig::unknown_keys(repo), Vec::new());
2105 }
2106
2107 #[test]
2108 fn the_project_file_wins_the_keys_it_names_and_no_others() {
2109 let tmp = TempDir::new().unwrap();
2110 let repo = tmp.path();
2111
2112 // A team file that says one thing, and a personal file that says three.
2113 fs::write(
2114 repo.join(constants::PROJECT_REPO_CONFIG_FILE),
2115 r#"{ "ignore": true }"#,
2116 )
2117 .unwrap();
2118 fs::write(
2119 repo.join(constants::PER_REPO_CONFIG_FILE),
2120 r#"{ "ignore": false, "scan_depth": 12, "project_name": "mine" }"#,
2121 )
2122 .unwrap();
2123
2124 let cfg = PerRepoConfig::load_with_diagnostics(repo).unwrap().unwrap();
2125 assert!(cfg.ignore, "the committed file decides the key it names");
2126 assert_eq!(
2127 cfg.scan_depth,
2128 Some(12),
2129 "and decides nothing about the keys it does not"
2130 );
2131 assert_eq!(cfg.project_name.as_deref(), Some("mine"));
2132
2133 let layers = RepoConfigLayers::load(repo).unwrap();
2134 assert_eq!(layers.source_of("ignore"), ConfigSource::Project);
2135 assert_eq!(layers.source_of("scan_depth"), ConfigSource::Personal);
2136 assert_eq!(layers.source_of("min_size_mb"), ConfigSource::Default);
2137 }
2138
2139 #[test]
2140 fn a_serde_default_is_not_a_project_decision() {
2141 // The whole reason the key set is carried around. Serde fills `ignore` in as
2142 // `false` for a file that never mentioned it, and a merge that could not tell
2143 // those apart would have every project file silently un-ignoring repositories
2144 // its author had said nothing about.
2145 let tmp = TempDir::new().unwrap();
2146 let repo = tmp.path();
2147 fs::write(
2148 repo.join(constants::PROJECT_REPO_CONFIG_FILE),
2149 r#"{ "scan_depth": 3 }"#,
2150 )
2151 .unwrap();
2152 fs::write(
2153 repo.join(constants::PER_REPO_CONFIG_FILE),
2154 r#"{ "ignore": true }"#,
2155 )
2156 .unwrap();
2157
2158 let cfg = PerRepoConfig::load_with_diagnostics(repo).unwrap().unwrap();
2159 assert!(cfg.ignore);
2160 assert_eq!(cfg.scan_depth, Some(3));
2161 }
2162
2163 #[test]
2164 fn a_broken_project_file_is_named_and_never_healed_in_place() {
2165 let tmp = TempDir::new().unwrap();
2166 let repo = tmp.path();
2167 fs::write(
2168 repo.join(constants::PROJECT_REPO_CONFIG_FILE),
2169 r#"{ "ignore": true, }"#,
2170 )
2171 .unwrap();
2172
2173 // Same refusal as a broken personal file: nothing reads a config it cannot
2174 // parse, whichever file it was in.
2175 assert!(
2176 PerRepoConfig::load_with_diagnostics(repo)
2177 .unwrap_err()
2178 .contains("Syntax error")
2179 );
2180
2181 // But the repair path has to know which file, because one of them is tracked.
2182 let broken = PerRepoConfig::broken_files(repo);
2183 assert_eq!(broken.len(), 1);
2184 assert_eq!(broken[0].0, constants::PROJECT_REPO_CONFIG_FILE);
2185 }
2186
2187 #[test]
2188 fn a_new_project_file_is_visible_to_git_and_decides_nothing() {
2189 let tmp = TempDir::new().unwrap();
2190 let repo = tmp.path();
2191 fs::create_dir_all(repo.join(".git").join("info")).unwrap();
2192 fs::write(
2193 repo.join(constants::PER_REPO_CONFIG_FILE),
2194 r#"{ "ignore": true, "scan_depth": 9 }"#,
2195 )
2196 .unwrap();
2197
2198 write_project_starter(repo).unwrap();
2199
2200 // `save_to_repo` hides what it writes; this one must not, or the file is a
2201 // per-machine file with a misleading name.
2202 let exclude = repo.join(".git").join("info").join("exclude");
2203 let listed = fs::read_to_string(&exclude).unwrap_or_default();
2204 assert!(
2205 !listed.contains(constants::PROJECT_REPO_CONFIG_FILE),
2206 "the committed file must never be excluded: {listed}"
2207 );
2208
2209 // And creating it must not have quietly taken over the file beside it. A
2210 // serialized `PerRepoConfig::default()` would name all seven keys and therefore
2211 // win all seven.
2212 let layers = RepoConfigLayers::load(repo).unwrap();
2213 assert_eq!(layers.source_of("ignore"), ConfigSource::Personal);
2214 let cfg = layers.effective().unwrap();
2215 assert!(cfg.ignore);
2216 assert_eq!(cfg.scan_depth, Some(9));
2217
2218 // The empty section is written so it can be seen and filled in, which means it
2219 // has to be inert until somebody fills it in.
2220 assert!(cfg.prunable.is_none(), "an empty list declares nothing");
2221 }
2222
2223 #[test]
2224 fn a_write_back_never_copies_the_project_answer_into_the_personal_file() {
2225 // The drift this feature would otherwise create: `devp config --update` and the
2226 // workspace toggles all read-modify-write `.devprune.json`, and a merged read
2227 // would bake the team's value into one person's file, where it outlives the
2228 // next edit to the file it came from.
2229 let tmp = TempDir::new().unwrap();
2230 let repo = tmp.path();
2231 fs::write(
2232 repo.join(constants::PROJECT_REPO_CONFIG_FILE),
2233 r#"{ "ignore": true }"#,
2234 )
2235 .unwrap();
2236 fs::write(
2237 repo.join(constants::PER_REPO_CONFIG_FILE),
2238 r#"{ "scan_depth": 4 }"#,
2239 )
2240 .unwrap();
2241
2242 let personal = PerRepoConfig::load_personal_for_write(repo)
2243 .unwrap()
2244 .unwrap();
2245 assert!(!personal.ignore, "the project answer must not travel");
2246 assert_eq!(personal.scan_depth, Some(4));
2247 }
2248
2249 #[test]
2250 fn a_personal_exclusion_vetoes_a_declaration_the_project_committed() {
2251 // The conflict the key exists for: the committed file says `scratch` is
2252 // rebuildable, and on this one machine `scratch` is holding something. The way
2253 // out must not be editing a file the whole team shares.
2254 let tmp = TempDir::new().unwrap();
2255 let repo = tmp.path();
2256 fs::write(
2257 repo.join(constants::PROJECT_REPO_CONFIG_FILE),
2258 r#"{ "prunable": { "directories": [
2259 { "path": "scratch", "rebuild": "make scratch" }
2260 ] } }"#,
2261 )
2262 .unwrap();
2263 fs::write(
2264 repo.join(constants::PER_REPO_CONFIG_FILE),
2265 r#"{ "prunable": { "exclude": ["scratch"] } }"#,
2266 )
2267 .unwrap();
2268
2269 let prunable = PerRepoConfig::load_with_diagnostics(repo)
2270 .unwrap()
2271 .unwrap()
2272 .prunable
2273 .unwrap();
2274
2275 // The declaration survives the merge and is vetoed when it is resolved, so
2276 // deleting the exclusion later puts the directory back in play without anyone
2277 // having to re-declare it.
2278 assert_eq!(prunable.directories.len(), 1);
2279 assert_eq!(prunable.exclude, ["scratch"]);
2280 }
2281
2282 #[test]
2283 fn declarations_from_both_files_add_up_rather_than_one_silencing_the_other() {
2284 let tmp = TempDir::new().unwrap();
2285 let repo = tmp.path();
2286 fs::write(
2287 repo.join(constants::PROJECT_REPO_CONFIG_FILE),
2288 r#"{ "prunable": { "directories": [
2289 { "path": "tools/vendor", "rebuild": "make vendor" },
2290 { "path": ".cache/shared", "rebuild": "make cache" }
2291 ] } }"#,
2292 )
2293 .unwrap();
2294 fs::write(
2295 repo.join(constants::PER_REPO_CONFIG_FILE),
2296 r#"{ "prunable": { "directories": [
2297 { "path": ".cache/shared", "rebuild": "an old script I wrote" },
2298 { "path": "scratch", "rebuild": "make scratch" }
2299 ] } }"#,
2300 )
2301 .unwrap();
2302
2303 let dirs = PerRepoConfig::load_with_diagnostics(repo)
2304 .unwrap()
2305 .unwrap()
2306 .prunable
2307 .unwrap()
2308 .directories;
2309
2310 // Every key above this one is decided by one file or the other. A list is not a
2311 // decision, so nobody's entry is dropped for having been written by the wrong
2312 // person.
2313 let paths: Vec<&str> = dirs.iter().map(|d| d.path.as_str()).collect();
2314 assert_eq!(paths, ["tools/vendor", ".cache/shared", "scratch"]);
2315
2316 // One path is still one directory, and the committed answer is the current one.
2317 assert_eq!(dirs[1].rebuild, "make cache");
2318 }
2319
2320 #[test]
2321 fn test_serialization_roundtrip() {
2322 let mut registry = Registry::default();
2323 registry.settings.idle_days = 30;
2324 registry.add_repo(PathBuf::from("/test/repo"));
2325
2326 let json = serde_json::to_string_pretty(®istry).unwrap();
2327 let deserialized: Registry = serde_json::from_str(&json).unwrap();
2328 assert_eq!(registry.settings.idle_days, deserialized.settings.idle_days);
2329 assert_eq!(registry.repo_count(), deserialized.repo_count());
2330 }
2331
2332 #[test]
2333 fn test_atomic_save_leaves_no_tmp() {
2334 let tmp = TempDir::new().unwrap();
2335 let path = test_registry_path(&tmp);
2336
2337 let registry = Registry::default();
2338 registry.save_to(&path).unwrap();
2339
2340 assert!(path.exists());
2341 // Nothing but the registry itself may remain — a leftover `*.tmp` would mean the
2342 // rename never happened.
2343 let leftovers: Vec<_> = fs::read_dir(path.parent().unwrap())
2344 .unwrap()
2345 .flatten()
2346 .filter(|e| e.path() != path)
2347 .collect();
2348 assert!(leftovers.is_empty(), "leftover files: {leftovers:?}");
2349 }
2350
2351 #[test]
2352 fn exclude_entry_lands_in_git_info_exclude_not_gitignore() {
2353 let tmp = TempDir::new().unwrap();
2354 let repo = tmp.path();
2355 fs::create_dir(repo.join(".git")).unwrap();
2356
2357 ensure_in_git_exclude(repo, ".devprune.json").unwrap();
2358
2359 let exclude = fs::read_to_string(repo.join(".git/info/exclude")).unwrap();
2360 assert!(exclude.lines().any(|l| l == ".devprune.json"));
2361 // The whole point of using the exclude file: the shared, tracked `.gitignore`
2362 // must never be created or touched.
2363 assert!(!repo.join(".gitignore").exists());
2364 }
2365
2366 #[test]
2367 fn exclude_entry_is_appended_once_and_preserves_existing_lines() {
2368 let tmp = TempDir::new().unwrap();
2369 let repo = tmp.path();
2370 fs::create_dir_all(repo.join(".git/info")).unwrap();
2371 // No trailing newline, deliberately — the append must not glue two entries
2372 // onto one line.
2373 fs::write(repo.join(".git/info/exclude"), "*.log").unwrap();
2374
2375 ensure_in_git_exclude(repo, ".devprune.json").unwrap();
2376 ensure_in_git_exclude(repo, ".devprune.json").unwrap();
2377
2378 let exclude = fs::read_to_string(repo.join(".git/info/exclude")).unwrap();
2379 let lines: Vec<_> = exclude.lines().collect();
2380 assert_eq!(lines, vec!["*.log", ".devprune.json"]);
2381 }
2382
2383 #[test]
2384 fn exclude_follows_a_gitdir_pointer_file() {
2385 // Worktrees and submodules have a one-line `.git` *file*, and a worktree's
2386 // private gitdir points at the shared one via `commondir` — where the real
2387 // `info/exclude` lives.
2388 let tmp = TempDir::new().unwrap();
2389 let shared = tmp.path().join("main-clone/.git");
2390 let worktree_gitdir = shared.join("worktrees/wt");
2391 fs::create_dir_all(&worktree_gitdir).unwrap();
2392 fs::write(worktree_gitdir.join("commondir"), "../..\n").unwrap();
2393
2394 let wt = tmp.path().join("wt");
2395 fs::create_dir(&wt).unwrap();
2396 fs::write(
2397 wt.join(".git"),
2398 format!("gitdir: {}\n", worktree_gitdir.display()),
2399 )
2400 .unwrap();
2401
2402 ensure_in_git_exclude(&wt, ".devprune.json").unwrap();
2403
2404 let exclude = fs::read_to_string(shared.join("info/exclude")).unwrap();
2405 assert!(exclude.lines().any(|l| l == ".devprune.json"));
2406 }
2407
2408 #[test]
2409 fn exclude_is_a_no_op_outside_a_git_repository() {
2410 let tmp = TempDir::new().unwrap();
2411
2412 ensure_in_git_exclude(tmp.path(), ".devprune.json").unwrap();
2413
2414 assert!(!tmp.path().join(".git").exists());
2415 assert!(!tmp.path().join(".gitignore").exists());
2416 }
2417 /// A repository that moved is recognised, and arrives with everything it had earned.
2418 #[test]
2419 fn adopt_moved_entry_transfers_history() {
2420 let mut reg = Registry::default();
2421 let old = PathBuf::from("/nowhere/old-home/project");
2422 let mut entry = RepoEntry::new();
2423 entry.identity = Some("abc1234def".into());
2424 entry.total_freed_bytes = 4096;
2425 entry.enabled = false;
2426 entry.override_idle_days = Some(90);
2427 reg.repositories.insert(old.clone(), entry);
2428
2429 let new = std::env::temp_dir().join("devprune-adopt-live");
2430 reg.repositories.insert(new.clone(), RepoEntry::new());
2431
2432 let outcome = reg.adopt_moved_entry(&new, Some("abc1234def".into()));
2433 assert_eq!(outcome, Adoption::Moved(old.clone()));
2434 assert!(!reg.repositories.contains_key(&old));
2435
2436 let moved = ®.repositories[&canonical_key(&new)];
2437 assert_eq!(moved.total_freed_bytes, 4096);
2438 // A repository the user had switched off did not switch itself back on by
2439 // being moved.
2440 assert!(!moved.enabled);
2441 assert_eq!(moved.override_idle_days, Some(90));
2442 assert_eq!(moved.identity.as_deref(), Some("abc1234def"));
2443 }
2444
2445 /// Two dead entries with one root commit are clones, not a move. Nothing is guessed.
2446 #[test]
2447 fn adopt_moved_entry_refuses_to_guess_between_two() {
2448 let mut reg = Registry::default();
2449 for name in ["/nowhere/a", "/nowhere/b"] {
2450 let mut entry = RepoEntry::new();
2451 entry.identity = Some("shared".into());
2452 reg.repositories.insert(PathBuf::from(name), entry);
2453 }
2454 let new = std::env::temp_dir().join("devprune-adopt-ambiguous");
2455 reg.repositories.insert(new.clone(), RepoEntry::new());
2456
2457 assert_eq!(
2458 reg.adopt_moved_entry(&new, Some("shared".into())),
2459 Adoption::Ambiguous
2460 );
2461 assert_eq!(reg.repositories.len(), 3);
2462 // The identity is still recorded, so the next registration can recognise it
2463 // once the duplicates are cleared.
2464 assert_eq!(
2465 reg.repositories[&canonical_key(&new)].identity.as_deref(),
2466 Some("shared")
2467 );
2468 }
2469
2470 /// An entry whose path still exists is not a move, however matching its history.
2471 #[test]
2472 fn adopt_moved_entry_never_takes_from_a_live_path() {
2473 let dir = tempfile::tempdir().unwrap();
2474 let live = dir.path().join("live");
2475 std::fs::create_dir(&live).unwrap();
2476
2477 let mut reg = Registry::default();
2478 let mut entry = RepoEntry::new();
2479 entry.identity = Some("same".into());
2480 entry.total_freed_bytes = 999;
2481 reg.repositories.insert(canonical_key(&live), entry);
2482
2483 let other = dir.path().join("other");
2484 std::fs::create_dir(&other).unwrap();
2485 reg.repositories
2486 .insert(canonical_key(&other), RepoEntry::new());
2487
2488 assert_eq!(
2489 reg.adopt_moved_entry(&other, Some("same".into())),
2490 Adoption::Nothing
2491 );
2492 assert_eq!(
2493 reg.repositories[&canonical_key(&live)].total_freed_bytes,
2494 999
2495 );
2496 }
2497
2498 /// A repository with no commits has no identity, so nothing is adopted and nothing
2499 /// is recorded — a guess would be worse than the dead entry it replaced.
2500 #[test]
2501 fn adopt_moved_entry_ignores_a_missing_identity() {
2502 let mut reg = Registry::default();
2503 let mut entry = RepoEntry::new();
2504 entry.identity = Some("orphan".into());
2505 reg.repositories
2506 .insert(PathBuf::from("/nowhere/gone"), entry);
2507 let new = std::env::temp_dir().join("devprune-adopt-unborn");
2508 reg.repositories.insert(new.clone(), RepoEntry::new());
2509
2510 assert_eq!(reg.adopt_moved_entry(&new, None), Adoption::Nothing);
2511 assert_eq!(reg.repositories.len(), 2);
2512 assert!(reg.needs_identity(&new));
2513 }
2514
2515 #[test]
2516 fn a_restore_too_quick_to_be_real_teaches_nothing() {
2517 // A manager that found everything still in its cache returns in a moment. Folding
2518 // that into the average would claim a throughput no cold restore can reach, and
2519 // the estimate exists precisely to describe a cold one.
2520 let mut reg = Registry::default();
2521 reg.record_restore("npm", 500_000_000, 10);
2522 reg.record_restore("npm", 0, 60_000);
2523 assert!(reg.restore_rates.is_empty(), "{:?}", reg.restore_rates);
2524
2525 reg.record_restore("npm", 500_000_000, 60_000);
2526 assert_eq!(reg.restore_rates["npm"].samples, 1);
2527 }
2528
2529 #[test]
2530 fn the_average_forgets_the_disk_the_machine_no_longer_has() {
2531 let mut reg = Registry::default();
2532 for _ in 0..constants::RESTORE_RATE_SAMPLE_CAP {
2533 reg.record_restore("npm", 1_000_000, 1_000);
2534 }
2535 assert_eq!(
2536 reg.restore_rates["npm"].samples,
2537 constants::RESTORE_RATE_SAMPLE_CAP
2538 );
2539
2540 // The cap is a halving, not a ceiling: the next sample still lands, on top of
2541 // half of what came before.
2542 reg.record_restore("npm", 1_000_000, 1_000);
2543 let rate = ®.restore_rates["npm"];
2544 assert_eq!(rate.samples, constants::RESTORE_RATE_SAMPLE_CAP / 2 + 1);
2545 assert!(rate.bytes_per_sec().is_some());
2546 }
2547
2548 #[test]
2549 fn an_estimate_with_nothing_measured_is_not_offered() {
2550 // Never a zero and never a guess: a machine that has not restored anything yet
2551 // has no honest answer to "how long is this to undo", so it does not print one.
2552 let reg = Registry::default();
2553 assert!(reg.estimate_restore(&[("npm".into(), 1_000_000)]).is_none());
2554 }
2555
2556 #[test]
2557 fn an_untimed_adapter_is_left_out_of_the_coverage() {
2558 // Half an answer, reported as half. Counting cargo's bytes at npm's speed would
2559 // be the one thing worse than saying nothing.
2560 let mut reg = Registry::default();
2561 reg.record_restore("npm", 10_000_000, 10_000);
2562 let (secs, covered) = reg
2563 .estimate_restore(&[("npm".into(), 10_000_000), ("cargo".into(), 90_000_000)])
2564 .expect("npm alone is enough to answer for npm");
2565 assert_eq!(covered, 10_000_000, "cargo has never been timed here");
2566 assert!((secs - 10.0).abs() < 0.01, "{secs}");
2567 }
2568}