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