Skip to main content

dev_prune/adapters/
mod.rs

1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4// Package manager adapter trait and registry.
5//
6// This module defines the [`PackageManager`] trait that all ecosystem adapters
7// must implement. It also provides helper functions for adapter detection and
8// directory size calculation.
9//
10// ## Adding a New Adapter
11//
12// 1. Create a new file in `src/adapters/` (e.g., `maven.rs`)
13// 2. Implement the [`PackageManager`] trait
14// 3. Register it in [`get_all_adapters()`]
15// 4. Add tests
16//
17// See [../../docs/ADDING_ADAPTERS.md] for a detailed guide.
18
19pub mod bun;
20pub mod bundler;
21pub mod cargo_adapter;
22pub mod cocoapods;
23pub mod composer;
24pub mod go;
25pub mod gradle;
26pub mod maven;
27pub mod mix;
28pub mod npm;
29pub mod pdm;
30pub mod pipenv;
31pub mod pnpm;
32pub mod poetry;
33pub mod swift;
34pub mod uv;
35pub mod venv;
36pub mod yarn;
37
38use std::collections::HashMap;
39use std::fmt;
40use std::path::{Path, PathBuf};
41use std::sync::{Mutex, OnceLock};
42
43use anyhow::{Context as _, Result};
44use walkdir::WalkDir;
45
46/// Information about a bloat directory that can be pruned.
47#[derive(Debug, Clone)]
48pub struct BloatDir {
49    /// Human-readable name (e.g., "node_modules").
50    pub name: String,
51    /// Full path to the bloat directory.
52    pub path: PathBuf,
53    /// Bytes that deleting this directory actually gives back to the disk.
54    pub size_bytes: u64,
55    /// Bytes reachable through hardlinks from outside this directory — pnpm's and
56    /// bun's store links. Deleting the directory does not free these; the store
57    /// keeps them. Zero for managers that copy instead of link.
58    pub shared_bytes: u64,
59}
60
61impl fmt::Display for BloatDir {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        write!(f, "{} ({})", self.name, self.path.display())
64    }
65}
66
67/// Packages sitting in a manager's environment directory that its lockfile does not
68/// record — installs a post-prune restore would not bring back.
69#[derive(Debug, Clone)]
70pub struct DriftReport {
71    /// The environment directory that drifted (e.g. `.venv`, `node_modules`).
72    pub directory: String,
73    /// The unrecorded package names, sorted.
74    pub unrecorded: Vec<String>,
75    /// The command that writes them into the lockfile.
76    pub record_command: &'static str,
77}
78
79/// The core trait that every package manager adapter must implement.
80///
81/// Each adapter is responsible for:
82/// - **Detecting** whether it applies to a given project directory
83/// - **Listing** the bloat directories it manages
84/// - **Enforcing** lockfile consistency before deletion
85/// - **Restoring** dependencies from lockfiles
86pub trait PackageManager: Send + Sync {
87    /// Human-readable name for this adapter (e.g., "npm", "pnpm", "uv").
88    fn name(&self) -> &'static str;
89
90    /// Check if this adapter applies to the given project directory.
91    ///
92    /// Typically checks for the presence of a specific lockfile or config file.
93    fn detect(&self, project_path: &Path) -> bool;
94
95    /// List all bloat directories this adapter manages in the given project.
96    ///
97    /// Only returns directories that actually exist on disk.
98    fn bloat_dirs(&self, project_path: &Path) -> Vec<BloatDir>;
99
100    /// Prove the lockfile can rebuild what is about to be deleted.
101    ///
102    /// This is a **safety-critical** method. It MUST succeed before any bloat
103    /// directory is deleted. If this fails, deletion for this adapter is aborted.
104    ///
105    /// See [`EnforcePolicy`] for the one rule every adapter follows.
106    fn enforce_lockfile(&self, project_path: &Path, policy: EnforcePolicy) -> Result<()>;
107
108    /// Restore dependencies from the lockfile (for `dev-prune restore`).
109    ///
110    /// `timeout` is threaded explicitly for the same reason [`EnforcePolicy`] is: the
111    /// restore path used to burn the compiled-in default regardless of
112    /// `command_timeout_secs`, and a full `npm ci` on a large tree needs the raised
113    /// timeout far more often than a verify does.
114    fn restore(&self, project_path: &Path, timeout: std::time::Duration) -> Result<()>;
115
116    /// [`PackageManager::restore`], told the name the pruned directory had.
117    ///
118    /// Most managers have exactly one possible directory name and ignore this. venv does
119    /// not: it prunes any folder carrying a `pyvenv.cfg` — `venv`, `env`, `my_env` — and
120    /// without the recorded name it would rebuild the environment as `.venv`, leaving
121    /// every activate script, IDE interpreter path and Makefile pointing at nothing.
122    /// `runtime` is the interpreter tag recorded when the directory was deleted (see
123    /// [`crate::config::PrunedDir::runtime`]). `None` means nothing was recorded, or the
124    /// caller has decided this machine cannot honour it; either way the manager should
125    /// fall back to whatever it would have used before.
126    fn restore_named(
127        &self,
128        project_path: &Path,
129        dir_name: &str,
130        runtime: Option<&str>,
131        timeout: std::time::Duration,
132    ) -> Result<()> {
133        let _ = (dir_name, runtime);
134        self.restore(project_path, timeout)
135    }
136
137    /// The language runtime a bloat directory is built against, recorded at prune time.
138    ///
139    /// Only the Python managers answer this. A `node_modules` is rebuilt by the same
140    /// `npm ci` whichever Node is installed, and cargo and go pin their toolchains in
141    /// files that are already in the repository — but a virtual environment is a
142    /// *copy* of one specific interpreter, and rebuilding it on a different one silently
143    /// changes which wheels resolve.
144    ///
145    /// `dir_name` is the directory about to be deleted, relative to `project_path`.
146    fn runtime_tag(&self, project_path: &Path, dir_name: &str) -> Option<String> {
147        let _ = (project_path, dir_name);
148        None
149    }
150
151    /// The file this manager rebuilds its bloat directory from.
152    ///
153    /// Two callers. Conflict resolution breaks ties between managers that share a bloat
154    /// directory — npm, pnpm, yarn and bun all own the same `node_modules` — by comparing
155    /// these files' timestamps. `devp doctor` names them, because a missing one is the
156    /// most common reason a project is not pruneable.
157    ///
158    /// More than one entry means the manager accepts any of them (bun's binary and text
159    /// lockfiles). An empty slice means the manager has no single file to point at.
160    fn lockfiles(&self) -> &'static [&'static str] {
161        &[]
162    }
163
164    /// Installed-but-unrecorded packages, as data instead of a refusal.
165    ///
166    /// The same comparison [`PackageManager::enforce_lockfile`] refuses a prune on,
167    /// surfaced early so `devp status --drift` can point at the problem before a prune
168    /// is ever attempted. Runs nothing and writes nothing. An empty answer means
169    /// "nothing detected", not "proven clean" — most managers have no cheap way to
170    /// compare and say nothing here.
171    fn drift(&self, project_path: &Path) -> Vec<DriftReport> {
172        let _ = project_path;
173        Vec::new()
174    }
175
176    /// Whether this adapter is inert until the user enables it in settings.
177    ///
178    /// Build-tool adapters (gradle, maven) answer `true`: their directories come back
179    /// by recompiling the project, which costs far more than a dependency reinstall,
180    /// so nobody should find them deleted without having asked. The engine also holds
181    /// them to the longer `build_idle_days` idle window.
182    fn opt_in(&self) -> bool {
183        false
184    }
185}
186
187/// Adapters that all manage `node_modules` and therefore cannot coexist.
188const JS_MANAGERS: [&str; 4] = ["npm", "pnpm", "yarn", "bun"];
189
190/// Bookkeeping files that each JavaScript manager writes into `node_modules` when it
191/// installs. Finding one identifies the manager that actually produced the tree on
192/// disk, which is stronger evidence than a lockfile's timestamp.
193///
194/// pnpm and yarn are checked before npm: a project migrated away from npm can still
195/// carry npm's `.package-lock.json` inside a tree the new manager rebuilt around it.
196/// Bun has no marker we rely on, so a bun conflict falls through to the later rules.
197const JS_INSTALL_MARKERS: [(&str, &[&str]); 3] = [
198    ("pnpm", &[".pnpm", ".modules.yaml"]),
199    ("yarn", &[".yarn-state.yml", ".yarn-integrity"]),
200    ("npm", &[".package-lock.json"]),
201];
202
203/// Returns all registered package manager adapters.
204///
205/// To add a new adapter, create your struct and add it to this list.
206pub fn get_all_adapters() -> Vec<Box<dyn PackageManager>> {
207    vec![
208        Box::new(npm::Npm),
209        Box::new(pnpm::Pnpm),
210        Box::new(yarn::Yarn),
211        Box::new(bun::Bun),
212        Box::new(uv::Uv),
213        Box::new(poetry::Poetry),
214        Box::new(pdm::Pdm),
215        Box::new(pipenv::Pipenv),
216        Box::new(venv::Venv),
217        Box::new(cargo_adapter::Cargo),
218        Box::new(go::Go),
219        Box::new(composer::Composer),
220        Box::new(bundler::Bundler),
221        Box::new(cocoapods::CocoaPods),
222        Box::new(mix::Mix),
223        Box::new(gradle::Gradle),
224        Box::new(maven::Maven),
225        Box::new(swift::Swift),
226    ]
227}
228
229/// The names of the opt-in adapters the user has switched on, resolved once per
230/// process from the registry settings.
231///
232/// Resolved here rather than threaded through every caller because `detect_adapters`
233/// is the single funnel every command discovers projects through — gating detection
234/// makes a disabled adapter invisible everywhere at once (status, stats, run, doctor),
235/// instead of visible in one view and inert in another.
236fn opt_in_enabled() -> &'static [String] {
237    static ENABLED: OnceLock<Vec<String>> = OnceLock::new();
238    ENABLED.get_or_init(|| {
239        crate::config::Registry::load()
240            .map(|r| {
241                let mut names = Vec::new();
242                if r.settings.enable_gradle {
243                    names.push("gradle".to_string());
244                }
245                if r.settings.enable_maven {
246                    names.push("maven".to_string());
247                }
248                if r.settings.enable_swift {
249                    names.push("swift".to_string());
250                }
251                names
252            })
253            .unwrap_or_default()
254    })
255}
256
257/// The adapters switched off by name in `disabled_adapters`, resolved once per process.
258///
259/// The mirror image of [`opt_in_enabled`], and read at the same single funnel for the
260/// same reason: an adapter someone has turned off should not appear in `status`, be
261/// counted by `stats`, or be probed for by `doctor` — "off" that still shows up
262/// everywhere is not off.
263fn user_disabled() -> &'static [String] {
264    static DISABLED: OnceLock<Vec<String>> = OnceLock::new();
265    DISABLED.get_or_init(|| {
266        crate::config::Registry::load()
267            .map(|r| {
268                r.settings
269                    .disabled_adapters
270                    .iter()
271                    .map(|n| n.trim().to_ascii_lowercase())
272                    .filter(|n| !n.is_empty())
273                    .collect()
274            })
275            .unwrap_or_default()
276    })
277}
278
279/// Whether `name` is a real adapter name, for validating what the user typed.
280pub fn is_adapter_name(name: &str) -> bool {
281    get_all_adapters().iter().any(|a| a.name() == name)
282}
283
284/// Every adapter name, in registry order, for error messages and pickers.
285pub fn all_adapter_names() -> Vec<&'static str> {
286    get_all_adapters().iter().map(|a| a.name()).collect()
287}
288
289/// The adapters that need their own `enable_*` switch as well as not being disabled.
290///
291/// Two switches govern these, and a picker that ticks one without saying so leaves the
292/// user watching nothing happen.
293pub fn opt_in_adapter_names() -> Vec<&'static str> {
294    get_all_adapters()
295        .iter()
296        .filter(|a| a.opt_in())
297        .map(|a| a.name())
298        .collect()
299}
300
301/// Detect which adapters apply to a given project directory.
302///
303/// Several adapters detecting at once is normal and supported — a directory holding
304/// `package-lock.json`, `uv.lock` and `Cargo.toml` legitimately has three managers,
305/// each owning a different bloat directory. Adapters that would fight over the *same*
306/// directory are reduced to one first; see [`resolve_conflicts`].
307pub fn detect_adapters(project_path: &Path) -> Vec<Box<dyn PackageManager>> {
308    let mut detected: Vec<Box<dyn PackageManager>> = get_all_adapters()
309        .into_iter()
310        .filter(|adapter| !adapter.opt_in() || opt_in_enabled().iter().any(|n| n == adapter.name()))
311        .filter(|adapter| !user_disabled().iter().any(|n| n == adapter.name()))
312        .filter(|adapter| adapter.detect(project_path))
313        .collect();
314    resolve_conflicts(project_path, &mut detected);
315    detected
316}
317
318/// Reduce every set of adapters that shares a bloat directory down to a single owner.
319fn resolve_conflicts(project_path: &Path, detected: &mut Vec<Box<dyn PackageManager>>) {
320    resolve_js_conflict(project_path, detected);
321    resolve_python_conflict(project_path, detected);
322}
323
324/// Reduce several JavaScript managers claiming the same `node_modules` down to one.
325///
326/// A directory carrying more than one JS lockfile is usually a half-finished migration
327/// or a stray file nobody deleted. Running the wrong manager's `enforce_lockfile` would
328/// rewrite a lockfile the project does not use, so pick deliberately, strongest signal
329/// first:
330///
331/// 1. The `packageManager` field of `package.json` — the maintainers said so outright.
332/// 2. The bookkeeping files inside `node_modules` — whoever built the tree we are about
333///    to delete is the manager whose lockfile has to be able to rebuild it.
334/// 3. The most recently written lockfile — a last resort when nothing else distinguishes
335///    them.
336fn resolve_js_conflict(project_path: &Path, detected: &mut Vec<Box<dyn PackageManager>>) {
337    if detected
338        .iter()
339        .filter(|a| JS_MANAGERS.contains(&a.name()))
340        .count()
341        < 2
342    {
343        return;
344    }
345
346    let winner = declared_package_manager(project_path)
347        .filter(|name| detected.iter().any(|a| a.name() == name))
348        .or_else(|| installed_manager(project_path, detected))
349        .or_else(|| newest_lockfile_owner(project_path, detected));
350
351    let Some(winner) = winner else { return };
352    detected.retain(|a| !JS_MANAGERS.contains(&a.name()) || a.name() == winner);
353}
354
355/// Give one lockfile-backed Python manager sole ownership of the environment directory.
356///
357/// uv, poetry, pdm and pipenv all point at the same in-project `.venv`, and so does the
358/// plain-venv adapter. Running the wrong one's `enforce_lockfile` would sync a lockfile
359/// the project does not use, so pick deliberately:
360///
361/// 1. Any of the four displaces `venv`. They have real lockfiles and rebuild the
362///    environment exactly; `requirements.txt` cannot promise that, so it is the
363///    fallback for projects none of them recognises.
364/// 2. Between themselves — usually a half-finished migration — the one whose lockfile
365///    is actually on disk built the tree we are about to delete. With several or none
366///    present, the tie goes to whichever comes first in [`get_all_adapters()`].
367const PYTHON_ENV_MANAGERS: [(&str, &str); 4] = [
368    ("uv", "uv.lock"),
369    ("poetry", "poetry.lock"),
370    ("pdm", "pdm.lock"),
371    ("pipenv", "Pipfile.lock"),
372];
373
374fn resolve_python_conflict(project_path: &Path, detected: &mut Vec<Box<dyn PackageManager>>) {
375    let claimants: Vec<(&str, &str)> = PYTHON_ENV_MANAGERS
376        .iter()
377        .copied()
378        .filter(|(name, _)| detected.iter().any(|a| a.name() == *name))
379        .collect();
380    let Some(&(first, _)) = claimants.first() else {
381        return;
382    };
383    detected.retain(|a| a.name() != "venv");
384    if claimants.len() < 2 {
385        return;
386    }
387    let winner = claimants
388        .iter()
389        .find(|(_, lockfile)| project_path.join(lockfile).exists())
390        .map_or(first, |(name, _)| *name);
391    detected.retain(|a| {
392        a.name() == winner
393            || !PYTHON_ENV_MANAGERS
394                .iter()
395                .any(|(name, _)| *name == a.name())
396    });
397}
398
399/// The manager that actually installed the `node_modules` tree currently on disk.
400fn installed_manager(project_path: &Path, detected: &[Box<dyn PackageManager>]) -> Option<String> {
401    let node_modules = project_path.join("node_modules");
402    if !node_modules.is_dir() {
403        return None;
404    }
405
406    JS_INSTALL_MARKERS
407        .iter()
408        .find(|(name, markers)| {
409            detected.iter().any(|a| a.name() == *name)
410                && markers.iter().any(|m| node_modules.join(m).exists())
411        })
412        .map(|(name, _)| (*name).to_string())
413}
414
415/// Read the Corepack `packageManager` field (e.g. `"pnpm@9.1.0"`) from `package.json`.
416fn declared_package_manager(project_path: &Path) -> Option<String> {
417    let raw = std::fs::read_to_string(project_path.join("package.json")).ok()?;
418    let json: serde_json::Value = serde_json::from_str(&raw).ok()?;
419    let declared = json.get("packageManager")?.as_str()?;
420    let name = declared.split('@').next().unwrap_or_default();
421    JS_MANAGERS
422        .iter()
423        .find(|m| **m == name)
424        .map(|m| (*m).to_string())
425}
426
427/// The detected JS manager whose lockfile has the most recent modification time.
428fn newest_lockfile_owner(
429    project_path: &Path,
430    detected: &[Box<dyn PackageManager>],
431) -> Option<String> {
432    detected
433        .iter()
434        .filter(|a| JS_MANAGERS.contains(&a.name()))
435        .filter_map(|a| {
436            let newest = a
437                .lockfiles()
438                .iter()
439                .filter_map(|f| std::fs::metadata(project_path.join(f)).ok()?.modified().ok())
440                .max()?;
441            Some((newest, a.name().to_string()))
442        })
443        // Ties keep the earlier adapter in `get_all_adapters()` order, so the choice is
444        // deterministic when two lockfiles share a timestamp.
445        .fold(None::<(std::time::SystemTime, String)>, |best, cur| {
446            match best {
447                Some(b) if b.0 >= cur.0 => Some(b),
448                _ => Some(cur),
449            }
450        })
451        .map(|(_, name)| name)
452}
453
454/// Calculate the total size of a directory recursively (in bytes).
455pub fn dir_size(path: &Path) -> u64 {
456    if !path.exists() {
457        return 0;
458    }
459    WalkDir::new(path)
460        .follow_links(false)
461        .into_iter()
462        .flatten()
463        .filter_map(|entry| entry.metadata().ok())
464        .filter(|meta| meta.is_file())
465        .map(|meta| meta.len())
466        .sum()
467}
468
469/// A directory's size split by what deleting it would actually free.
470#[derive(Debug, Clone, Copy, Default)]
471pub struct DirSizeBreakdown {
472    /// Bytes `remove_dir_all` gives back to the disk.
473    pub freed_bytes: u64,
474    /// Bytes that survive the deletion because a hardlink outside the directory —
475    /// for pnpm and bun, the global store — still points at them.
476    pub shared_bytes: u64,
477}
478
479/// [`dir_size`], but hardlink-aware.
480///
481/// pnpm and bun do not copy packages into `node_modules`; they hardlink them from a
482/// machine-wide store, so summing file sizes counts bytes the store keeps after the
483/// delete and promises space a prune cannot deliver. Here a physical file is counted
484/// once no matter how many names it has inside the tree, and counts as freed only
485/// when every one of its links is inside the tree. A store that fell back to copying
486/// — a different volume, a filesystem without hardlinks — leaves the link count at
487/// one, so copied installs still count in full. A file whose link count cannot be
488/// read is counted as freed, which errs toward the plain [`dir_size`] figure.
489pub fn dir_size_with_hardlinks(path: &Path) -> DirSizeBreakdown {
490    let mut out = DirSizeBreakdown::default();
491    if !path.exists() {
492        return out;
493    }
494    // (volume, file id) → (bytes, links on disk, links seen inside this walk)
495    let mut linked: HashMap<(u64, u64), (u64, u64, u64)> = HashMap::new();
496    for entry in WalkDir::new(path).follow_links(false).into_iter().flatten() {
497        let Ok(meta) = entry.metadata() else { continue };
498        if !meta.is_file() {
499            continue;
500        }
501        match file_link_identity(entry.path(), &meta) {
502            Some((dev, ino, nlink)) if nlink > 1 => {
503                linked.entry((dev, ino)).or_insert((meta.len(), nlink, 0)).2 += 1;
504            }
505            _ => out.freed_bytes += meta.len(),
506        }
507    }
508    for (bytes, nlink, seen) in linked.into_values() {
509        if seen >= nlink {
510            out.freed_bytes += bytes;
511        } else {
512            out.shared_bytes += bytes;
513        }
514    }
515    out
516}
517
518/// (volume, file id, hardlink count) for one file, where the platform can say.
519#[cfg(unix)]
520fn file_link_identity(_path: &Path, meta: &std::fs::Metadata) -> Option<(u64, u64, u64)> {
521    use std::os::unix::fs::MetadataExt as _;
522    Some((meta.dev(), meta.ino(), meta.nlink()))
523}
524
525/// Windows keeps the link count behind an opened handle, not in the directory entry
526/// (std exposes it only on an unstable feature), so this costs one metadata-only open
527/// per file. Only the adapters that actually hardlink — pnpm and bun — pay it.
528#[cfg(windows)]
529fn file_link_identity(path: &Path, _meta: &std::fs::Metadata) -> Option<(u64, u64, u64)> {
530    use std::os::windows::fs::OpenOptionsExt as _;
531    use std::os::windows::io::AsRawHandle as _;
532    use windows_sys::Win32::Storage::FileSystem::{
533        BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
534    };
535
536    // access_mode(0) asks for attribute access only, so a file another process holds
537    // open without read sharing — an antivirus scan, an editor — does not fail here.
538    let file = std::fs::OpenOptions::new().access_mode(0).open(path).ok()?;
539    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
540    // SAFETY: `file` keeps the handle open for the whole call, and `info` is a
541    // plain-data out-parameter the API fills before returning.
542    if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 {
543        return None;
544    }
545    Some((
546        u64::from(info.dwVolumeSerialNumber),
547        (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
548        u64::from(info.nNumberOfLinks),
549    ))
550}
551
552#[cfg(not(any(unix, windows)))]
553fn file_link_identity(_path: &Path, _meta: &std::fs::Metadata) -> Option<(u64, u64, u64)> {
554    None
555}
556
557/// Resolve a program name into something `Command::new` can actually spawn.
558///
559/// On Windows the JS package managers (`npm`, `pnpm`, `yarn`, `bun`) are shipped as
560/// `.cmd` shims. `CreateProcess` only ever appends `.exe`, so `Command::new("npm")`
561/// fails with `NotFound` even when npm is installed and on `PATH`. Search `PATH`
562/// ourselves for the shim extensions and hand back the full path.
563///
564/// Names that already contain a path separator (e.g. `.venv\Scripts\python.exe`)
565/// are returned unchanged, as are all names on non-Windows platforms.
566pub fn resolve_program(program: &str) -> String {
567    #[cfg(windows)]
568    {
569        if Path::new(program).components().count() > 1 {
570            return program.to_string();
571        }
572        let Some(path_var) = std::env::var_os("PATH") else {
573            return program.to_string();
574        };
575        for dir in std::env::split_paths(&path_var) {
576            for ext in ["exe", "cmd", "bat"] {
577                let candidate = dir.join(format!("{program}.{ext}"));
578                if candidate.is_file() {
579                    return candidate.to_string_lossy().into_owned();
580                }
581            }
582        }
583    }
584    program.to_string()
585}
586
587/// Check whether a package manager binary is present and runnable.
588///
589/// Answers are cached for the life of the process. Every adapter asks this before it
590/// enforces a lockfile, so a monorepo with ten projects on the same manager otherwise
591/// pays for ten `npm --version` process spawns — around half a second each on Windows —
592/// to learn the same fact ten times. A run is short-lived, so nothing installed or
593/// removed mid-run can be missed for long.
594pub fn binary_available(program: &str) -> bool {
595    static CACHE: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();
596    let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
597
598    // Held across the probe on purpose: two threads asking about the same missing
599    // binary should spawn one process, not two. Nothing else takes this lock.
600    let mut guard = match cache.lock() {
601        Ok(g) => g,
602        // A poisoned lock only means some other thread panicked mid-probe; the answer
603        // is still worth having, so fall back to probing without the cache.
604        Err(_) => return probe_binary(program),
605    };
606    if let Some(known) = guard.get(program) {
607        return *known;
608    }
609    let available = probe_binary(program);
610    guard.insert(program.to_string(), available);
611    available
612}
613
614/// Programs that do not answer `--version`, and what to ask them instead.
615///
616/// `go --version` is not a typo for `go version`: the Go toolchain parses everything
617/// after `go` as a subcommand, rejects the flag with `flag provided but not defined:
618/// -version` and exits 2. A probe reading that as "not installed" is wrong on every
619/// machine with Go on it, and wrong in a way that silently weakens things — the Go
620/// adapter skips `go mod download` verification when it believes `go` is absent.
621const VERSION_PROBE_ARGS: [(&str, &[&str]); 1] = [("go", &["version"])];
622
623/// The arguments that make `program` print its version and exit `0`.
624fn version_probe_args(program: &str) -> &'static [&'static str] {
625    VERSION_PROBE_ARGS
626        .iter()
627        .find(|(name, _)| *name == program)
628        .map_or(&["--version"], |(_, args)| *args)
629}
630
631/// The actual version-probe spawn behind [`binary_available`].
632fn probe_binary(program: &str) -> bool {
633    crate::spawn::command(resolve_program(program))
634        .args(version_probe_args(program))
635        .stdin(std::process::Stdio::null())
636        .output()
637        .map(|o| o.status.success())
638        .unwrap_or(false)
639}
640
641/// The exit status and drained pipes of a finished command.
642struct CommandOutput {
643    status: std::process::ExitStatus,
644    stdout: String,
645    stderr: String,
646}
647
648/// Spawn a command, drain both of its pipes and wait for it, bounded by `timeout`.
649///
650/// Shared by the two public wrappers below. `devp caches` needs a command's *output* —
651/// `npm config get cache` answers a question rather than performing an action — and a
652/// second copy of the draining and polling below would be a second place for the
653/// deadlock it exists to prevent to come back.
654fn spawn_capture(
655    program: &str,
656    args: &[&str],
657    cwd: &Path,
658    timeout: std::time::Duration,
659) -> Result<CommandOutput> {
660    use std::io::Read;
661    use std::process::Stdio;
662    use std::thread;
663    use std::time::Instant;
664
665    let resolved = resolve_program(program);
666    let mut child = crate::spawn::command(&resolved)
667        .args(args)
668        .current_dir(cwd)
669        .stdin(Stdio::null())
670        .stdout(Stdio::piped())
671        .stderr(Stdio::piped())
672        .spawn()
673        .with_context(|| format!("Failed to execute: {program} {}", args.join(" ")))?;
674
675    // Drain both pipes on their own threads. A package manager easily emits more
676    // than the ~64 KiB OS pipe buffer; if nobody reads it the child blocks on write
677    // and never exits, which would turn every large install into a timeout kill.
678    let mut stdout_pipe = child.stdout.take();
679    let mut stderr_pipe = child.stderr.take();
680    let stdout_reader = thread::spawn(move || {
681        let mut buf = Vec::new();
682        if let Some(pipe) = stdout_pipe.as_mut() {
683            let _ = pipe.read_to_end(&mut buf);
684        }
685        buf
686    });
687    let stderr_reader = thread::spawn(move || {
688        let mut buf = Vec::new();
689        if let Some(pipe) = stderr_pipe.as_mut() {
690            let _ = pipe.read_to_end(&mut buf);
691        }
692        buf
693    });
694
695    let start = Instant::now();
696    let status = loop {
697        match child.try_wait()? {
698            Some(status) => break status,
699            None => {
700                if start.elapsed() >= timeout {
701                    let _ = child.kill();
702                    let _ = child.wait();
703                    anyhow::bail!(
704                        "Command timed out after {}s: {} {}\n\
705                         To increase the timeout, run: `devp config set command_timeout_secs <seconds>`",
706                        timeout.as_secs(),
707                        program,
708                        args.join(" ")
709                    );
710                }
711                thread::sleep(std::time::Duration::from_millis(100));
712            }
713        }
714    };
715
716    let stderr = stderr_reader
717        .join()
718        .map(|b| String::from_utf8_lossy(&b).into_owned())
719        .unwrap_or_default();
720    let stdout = stdout_reader
721        .join()
722        .map(|b| String::from_utf8_lossy(&b).into_owned())
723        .unwrap_or_default();
724
725    Ok(CommandOutput {
726        status,
727        stdout,
728        stderr,
729    })
730}
731
732/// Helper: run a command with a configurable timeout.
733pub fn run_command_with_timeout(
734    program: &str,
735    args: &[&str],
736    cwd: &Path,
737    timeout: std::time::Duration,
738) -> Result<()> {
739    let out = spawn_capture(program, args, cwd, timeout)?;
740    if out.status.success() {
741        Ok(())
742    } else {
743        anyhow::bail!(
744            "{} {} failed (exit code {:?}):\n{}",
745            program,
746            args.join(" "),
747            out.status.code(),
748            crate::output::condense_tool_output(
749                &out.stderr,
750                crate::constants::TOOL_OUTPUT_MAX_LINES
751            )
752        )
753    }
754}
755
756/// Run a command and hand back what it printed on stdout, bounded by `timeout`.
757///
758/// For commands that answer a question instead of doing work. A non-zero exit is an
759/// error like anywhere else, so a caller never mistakes an error message on stderr for
760/// the answer it asked for.
761pub fn capture_command_with_timeout(
762    program: &str,
763    args: &[&str],
764    cwd: &Path,
765    timeout: std::time::Duration,
766) -> Result<String> {
767    let out = spawn_capture(program, args, cwd, timeout)?;
768    if out.status.success() {
769        Ok(out.stdout)
770    } else {
771        anyhow::bail!(
772            "{} {} failed (exit code {:?}):\n{}",
773            program,
774            args.join(" "),
775            out.status.code(),
776            crate::output::condense_tool_output(
777                &out.stderr,
778                crate::constants::TOOL_OUTPUT_MAX_LINES
779            )
780        )
781    }
782}
783
784/// Helper: attempt a command but return `true`/`false` instead of `Err`.
785pub fn try_run_command(program: &str, args: &[&str], cwd: &Path) -> bool {
786    crate::spawn::command(resolve_program(program))
787        .args(args)
788        .current_dir(cwd)
789        .stdin(std::process::Stdio::null())
790        .output()
791        .map(|o| o.status.success())
792        .unwrap_or(false)
793}
794
795/// How much newer the manifest must be than the lockfile before
796/// [`refuse_if_manifest_newer`] calls it drift.
797///
798/// A clone or checkout writes both files within moments of each other, in whichever
799/// order the tree walk happens to visit them — a strict comparison would refuse half of
800/// all fresh clones. A hand edit that never got a lockfile sync is separated by minutes
801/// or days, which a minute of tolerance still catches.
802const MANIFEST_MTIME_TOLERANCE: std::time::Duration = std::time::Duration::from_secs(60);
803
804/// When the package manager is missing, a lockfile is only proof if the manifest has
805/// not been edited since it was written.
806///
807/// With the binary present the verify command answers this properly; without it, mtimes
808/// are the only signal there is. The manifest is inferred from the lockfile's file
809/// name; an unrecognised name changes nothing.
810fn refuse_if_manifest_newer(lockfile: &Path, program: &str, cwd: &Path) -> Result<()> {
811    let manifest_name = match lockfile.file_name().and_then(|n| n.to_str()) {
812        Some("Cargo.lock") => "Cargo.toml",
813        Some("package-lock.json")
814        | Some("yarn.lock")
815        | Some("pnpm-lock.yaml")
816        | Some("bun.lockb")
817        | Some("bun.lock") => "package.json",
818        Some("uv.lock") | Some("poetry.lock") | Some("pdm.lock") => "pyproject.toml",
819        Some("go.sum") => "go.mod",
820        Some("composer.lock") => "composer.json",
821        Some("Gemfile.lock") => "Gemfile",
822        Some("Pipfile.lock") => "Pipfile",
823        _ => return Ok(()),
824    };
825    let manifest = cwd.join(manifest_name);
826    let (Ok(manifest_meta), Ok(lock_meta)) =
827        (std::fs::metadata(&manifest), std::fs::metadata(lockfile))
828    else {
829        return Ok(());
830    };
831    if let (Ok(manifest_mtime), Ok(lock_mtime)) = (manifest_meta.modified(), lock_meta.modified())
832        && manifest_mtime > lock_mtime + MANIFEST_MTIME_TOLERANCE
833    {
834        anyhow::bail!(
835            "`{program}` is not available, and `{manifest_name}` has been edited more \
836                 recently than `{}` — the lockfile may no longer record the current \
837                 dependencies, and without `{program}` that cannot be verified. Install \
838                 {program} and run its lockfile sync, then prune again.",
839            lockfile.display()
840        );
841    }
842    Ok(())
843}
844
845/// The lockfile-freshness proof for managers that have no read-only check of their own.
846///
847/// CocoaPods, Mix and SwiftPM all rebuild from a lockfile, and not one of them offers a
848/// command that compares the lockfile to the manifest without also resolving over the
849/// network — `pod install`, `mix deps.get` and `swift package resolve` all *fix* the
850/// drift rather than reporting it, which is a write in the middle of a delete pass. The
851/// timestamps are the only offline evidence there is, so they are the evidence used: a
852/// manifest edited after its lockfile means the lockfile may no longer describe the
853/// dependency set, and a directory only a stale lockfile can rebuild is not recoverable
854/// in the sense this tool promises.
855pub fn refuse_if_manifest_stale(
856    manifest: &Path,
857    lockfile: &Path,
858    sync_command: &str,
859) -> Result<()> {
860    let (Ok(manifest_meta), Ok(lock_meta)) =
861        (std::fs::metadata(manifest), std::fs::metadata(lockfile))
862    else {
863        return Ok(());
864    };
865    if let (Ok(manifest_mtime), Ok(lock_mtime)) = (manifest_meta.modified(), lock_meta.modified())
866        && manifest_mtime > lock_mtime + MANIFEST_MTIME_TOLERANCE
867    {
868        anyhow::bail!(
869            "`{}` has been edited more recently than `{}` — the lockfile may no longer \
870             record the current dependencies. Run `{sync_command}` and prune again.",
871            manifest.display(),
872            lockfile.display()
873        );
874    }
875    Ok(())
876}
877
878/// Two-tier lockfile enforcement with configurable timeout.
879pub fn lock_sync_or_verify_with_timeout(
880    lockfile: &Path,
881    program: &str,
882    sync_args: &[&str],
883    cwd: &Path,
884    timeout: std::time::Duration,
885) -> Result<()> {
886    let lockfile_exists = lockfile.exists();
887
888    if !binary_available(program) {
889        if lockfile_exists {
890            refuse_if_manifest_newer(lockfile, program, cwd)?;
891            return Ok(());
892        } else {
893            anyhow::bail!(
894                "`{program}` is not available and no lockfile was found at `{}`. \
895                 Cannot safely delete dependencies — install {program} first, \
896                 or commit a lockfile.",
897                lockfile.display()
898            );
899        }
900    }
901
902    // Binary is available — run the sync with timeout.
903    run_command_with_timeout(program, sync_args, cwd, timeout)
904}
905
906/// What an adapter is allowed to do while enforcing a lockfile on this pass.
907///
908/// The two things that used to be hardcoded per adapter, and were wrong in both places:
909/// every adapter burned the compiled-in timeout regardless of `command_timeout_secs`,
910/// and only cargo and go consulted `allow_manifest_rewrite`.
911#[derive(Debug, Clone, Copy)]
912pub struct EnforcePolicy {
913    /// Whether a sync command that writes files Git tracks may run anyway.
914    ///
915    /// The user's `allow_manifest_rewrite`. Off by default: a prune pass can come from
916    /// the scheduler, and a background process that leaves a dirty working tree behind
917    /// is a surprise no matter which file it wrote.
918    pub allow_rewrite: bool,
919    /// Ceiling on any one package-manager command — the user's `command_timeout_secs`.
920    pub timeout: std::time::Duration,
921}
922
923impl Default for EnforcePolicy {
924    fn default() -> Self {
925        Self {
926            allow_rewrite: crate::constants::DEFAULT_ALLOW_MANIFEST_REWRITE,
927            timeout: std::time::Duration::from_secs(crate::constants::DEFAULT_COMMAND_TIMEOUT_SECS),
928        }
929    }
930}
931
932impl EnforcePolicy {
933    /// A policy from the user's own settings.
934    pub fn from_settings(settings: &crate::config::Settings) -> Self {
935        Self {
936            allow_rewrite: settings.allow_manifest_rewrite,
937            timeout: std::time::Duration::from_secs(settings.command_timeout_secs),
938        }
939    }
940}
941
942/// The one rule every adapter enforces, given the manager's two spellings of the check.
943///
944/// - lockfile present → `verify_args`, which resolves the graph against the lockfile and
945///   **fails** rather than writing when the two have drifted apart
946/// - lockfile absent → `write_args`, because `restore` needs a lockfile to exist at all
947///   and there is nothing there to preserve
948/// - `allow_rewrite` → `write_args` either way: the informed opt-in, for the user who
949///   would rather have a stale lockfile refreshed than have the prune refused
950///
951/// This used to be the cargo/go rule only. Every other adapter ran its writing sync
952/// unconditionally — `npm install --package-lock-only`, `pnpm install --lockfile-only`,
953/// `uv lock` and `yarn install --mode update-lockfile` all rewrite a lockfile Git tracks
954/// when it has drifted from the manifest. That is a smaller edit than `go mod tidy`
955/// makes, but it is still an unattended pass modifying a tracked file, and it made
956/// `allow_manifest_rewrite` mean two different things depending on the ecosystem.
957pub fn enforce_two_tier(
958    lockfile: &Path,
959    program: &str,
960    verify_args: &[&str],
961    write_args: &[&str],
962    cwd: &Path,
963    policy: EnforcePolicy,
964) -> Result<()> {
965    if policy.allow_rewrite {
966        return lock_sync_or_verify_with_timeout(
967            lockfile,
968            program,
969            write_args,
970            cwd,
971            policy.timeout,
972        );
973    }
974    lock_verify_or_generate(
975        lockfile,
976        program,
977        verify_args,
978        write_args,
979        cwd,
980        policy.timeout,
981    )
982}
983
984/// Lockfile enforcement for ecosystems whose "sync" command rewrites source manifests.
985///
986/// `cargo generate-lockfile` re-resolves every dependency and overwrites `Cargo.lock`;
987/// `go mod tidy` edits both `go.mod` and `go.sum` and can drop requirements. Running
988/// either as a precondition for deletion would silently modify tracked source files,
989/// which contradicts the lockfile-safety guarantee. So:
990///
991/// - lockfile present → run the read-only `verify_args` (never writes)
992/// - lockfile absent  → run `generate_args`, since a lockfile must exist for `restore`
993pub fn lock_verify_or_generate(
994    lockfile: &Path,
995    program: &str,
996    verify_args: &[&str],
997    generate_args: &[&str],
998    cwd: &Path,
999    timeout: std::time::Duration,
1000) -> Result<()> {
1001    let lockfile_exists = lockfile.exists();
1002
1003    if !binary_available(program) {
1004        if lockfile_exists {
1005            refuse_if_manifest_newer(lockfile, program, cwd)?;
1006            return Ok(());
1007        }
1008        anyhow::bail!(
1009            "`{program}` is not available and no lockfile was found at `{}`. \
1010             Cannot safely delete dependencies — install {program} first, \
1011             or commit a lockfile.",
1012            lockfile.display()
1013        );
1014    }
1015
1016    if lockfile_exists {
1017        run_command_with_timeout(program, verify_args, cwd, timeout)
1018    } else {
1019        run_command_with_timeout(program, generate_args, cwd, timeout)
1020    }
1021}
1022
1023/// Two-tier lockfile enforcement using default timeout.
1024pub fn lock_sync_or_verify(
1025    lockfile: &Path,
1026    program: &str,
1027    sync_args: &[&str],
1028    cwd: &Path,
1029) -> Result<()> {
1030    lock_sync_or_verify_with_timeout(
1031        lockfile,
1032        program,
1033        sync_args,
1034        cwd,
1035        std::time::Duration::from_secs(crate::constants::DEFAULT_COMMAND_TIMEOUT_SECS),
1036    )
1037}
1038
1039/// Adapters with no binary worth probing before a restore: venv rebuilds through
1040/// whichever `python` the user has, and the build-tool adapters restore by the project's
1041/// next compile rather than by a command dev-prune runs.
1042/// Filename every virtual environment carries, and the only reliable record of which
1043/// interpreter built it.
1044const PYVENV_CFG: &str = "pyvenv.cfg";
1045
1046/// The `major.minor` a virtual environment was built with, as `"3.12"`.
1047///
1048/// Read from the environment's own `pyvenv.cfg`, which CPython writes at creation time
1049/// and never updates — which is exactly what makes it a record of the *original*
1050/// interpreter rather than of whatever is on `PATH` now. `None` when the directory is
1051/// not a virtual environment, or is one written by something that omitted the key.
1052pub(crate) fn venv_runtime_tag(venv: &Path) -> Option<String> {
1053    let cfg = std::fs::read_to_string(venv.join(PYVENV_CFG)).ok()?;
1054    for line in cfg.lines() {
1055        let Some((key, value)) = line.split_once('=') else {
1056            continue;
1057        };
1058        if matches!(key.trim(), "version" | "version_info") {
1059            let mut parts = value.trim().split('.');
1060            let major: u64 = parts.next()?.parse().ok()?;
1061            let minor: u64 = parts.next()?.parse().ok()?;
1062            return Some(format!("{major}.{minor}"));
1063        }
1064    }
1065    None
1066}
1067
1068/// A runtime tag is spliced into a command line, so it has to be proved to be a version
1069/// number before it gets there. The registry is a file on disk; a hand-edited or
1070/// corrupted entry must not be able to turn a restore into `python --version; rm -rf /`.
1071pub(crate) fn is_valid_runtime_tag(tag: &str) -> bool {
1072    let mut parts = tag.split('.');
1073    let (Some(major), Some(minor), None) = (parts.next(), parts.next(), parts.next()) else {
1074        return false;
1075    };
1076    !major.is_empty()
1077        && !minor.is_empty()
1078        && major.len() <= 2
1079        && minor.len() <= 3
1080        && major.bytes().all(|b| b.is_ascii_digit())
1081        && minor.bytes().all(|b| b.is_ascii_digit())
1082}
1083
1084/// How to invoke one specific Python `major.minor`: the program, and the arguments that
1085/// must come before anything else.
1086///
1087/// Windows ships the `py` launcher, which knows about every interpreter the machine has
1088/// registered and takes the version as a flag. Everywhere else the convention is a
1089/// separate `python3.12` binary on `PATH`. Returns `None` for a tag that is not a plain
1090/// version number.
1091pub(crate) fn python_launcher(tag: &str) -> Option<(String, Vec<String>)> {
1092    if !is_valid_runtime_tag(tag) {
1093        return None;
1094    }
1095    #[cfg(windows)]
1096    {
1097        Some(("py".to_string(), vec![format!("-{tag}")]))
1098    }
1099    #[cfg(not(windows))]
1100    {
1101        Some((format!("python{tag}"), Vec::new()))
1102    }
1103}
1104
1105/// The absolute path of one specific Python `major.minor`, asked of the interpreter
1106/// itself.
1107///
1108/// The launcher form is enough to *run* an interpreter, but not to name one to a tool
1109/// that wants a path — `poetry env use` is the case in hand, and `poetry env use py` is
1110/// not a thing. Returns `None` when that version is not installed, which makes this an
1111/// availability check as well.
1112pub(crate) fn python_executable(tag: &str) -> Option<String> {
1113    let (program, prefix) = python_launcher(tag)?;
1114    let out = crate::spawn::command(resolve_program(&program))
1115        .args(&prefix)
1116        .args(["-c", "import sys; print(sys.executable)"])
1117        .stdin(std::process::Stdio::null())
1118        .stderr(std::process::Stdio::null())
1119        .output()
1120        .ok()?;
1121    if !out.status.success() {
1122        return None;
1123    }
1124    let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
1125    (!path.is_empty()).then_some(path)
1126}
1127
1128/// Whether this machine can actually run that interpreter.
1129///
1130/// Asked before a restore commits to it, because the recorded version is a fact about
1131/// the machine the prune ran on, and the restore may well be happening somewhere else.
1132pub(crate) fn python_runtime_available(tag: &str) -> bool {
1133    let Some((program, prefix)) = python_launcher(tag) else {
1134        return false;
1135    };
1136    crate::spawn::command(resolve_program(&program))
1137        .args(&prefix)
1138        .arg("--version")
1139        .stdin(std::process::Stdio::null())
1140        .stdout(std::process::Stdio::null())
1141        .stderr(std::process::Stdio::null())
1142        .status()
1143        .is_ok_and(|s| s.success())
1144}
1145
1146const NO_RESTORE_BINARY: [&str; 4] = ["venv", "gradle", "maven", "swift"];
1147
1148/// Adapters whose executable is not called what the adapter is called.
1149const ADAPTER_BINARIES: [(&str, &str); 2] = [("bundler", "bundle"), ("cocoapods", "pod")];
1150
1151/// The executable that restores for a given adapter.
1152pub fn adapter_binary(adapter: &str) -> &str {
1153    ADAPTER_BINARIES
1154        .iter()
1155        .find(|(name, _)| *name == adapter)
1156        .map_or(adapter, |(_, binary)| *binary)
1157}
1158
1159/// Where to get each package manager, for the one report that has to say so.
1160///
1161/// `devp doctor` naming a missing manager without saying how to get it is a finding the
1162/// reader has to go and research; every other finding it prints carries its own repair.
1163const INSTALL_HINTS: [(&str, &str); 14] = [
1164    ("npm", "ships with Node.js — https://nodejs.org"),
1165    (
1166        "pnpm",
1167        "`npm install -g pnpm` — https://pnpm.io/installation",
1168    ),
1169    (
1170        "yarn",
1171        "`corepack enable` — https://yarnpkg.com/getting-started/install",
1172    ),
1173    ("bun", "https://bun.sh/docs/installation"),
1174    (
1175        "uv",
1176        "https://docs.astral.sh/uv/getting-started/installation/",
1177    ),
1178    ("poetry", "https://python-poetry.org/docs/#installation"),
1179    (
1180        "pdm",
1181        "`uv tool install pdm` — https://pdm-project.org/en/latest/#installation",
1182    ),
1183    (
1184        "pipenv",
1185        "`uv tool install pipenv` — https://pipenv.pypa.io/en/latest/installation.html",
1186    ),
1187    ("cargo", "ships with Rust — https://rustup.rs"),
1188    ("go", "https://go.dev/dl/"),
1189    ("composer", "https://getcomposer.org/download/"),
1190    ("bundler", "`gem install bundler` — https://bundler.io"),
1191    (
1192        "cocoapods",
1193        "`gem install cocoapods` — https://cocoapods.org",
1194    ),
1195    (
1196        "mix",
1197        "ships with Elixir — https://elixir-lang.org/install.html",
1198    ),
1199];
1200
1201/// How to install the manager behind `adapter`, if there is a one-line answer.
1202pub fn install_hint(adapter: &str) -> Option<&'static str> {
1203    INSTALL_HINTS
1204        .iter()
1205        .find(|(name, _)| *name == adapter)
1206        .map(|(_, hint)| *hint)
1207}
1208
1209/// Information describing status of a required package manager binary.
1210#[derive(Debug, Clone)]
1211pub struct BinaryCheckStatus {
1212    pub name: String,
1213    pub available: bool,
1214    pub version: Option<String>,
1215}
1216
1217/// Scan only the package manager binaries needed by candidate repos.
1218pub fn scan_required_binaries(adapter_names: &[String]) -> Vec<BinaryCheckStatus> {
1219    let mut unique: Vec<String> = adapter_names
1220        .iter()
1221        // venv restores through python, and the build-tool adapters restore by the
1222        // next compile — none of them has a binary named after the adapter to probe.
1223        .filter(|&n| !NO_RESTORE_BINARY.contains(&n.as_str()) && n != "-")
1224        .cloned()
1225        .collect();
1226    unique.sort();
1227    unique.dedup();
1228
1229    unique
1230        .into_iter()
1231        .map(|name| {
1232            let binary = adapter_binary(&name);
1233            let output = crate::spawn::command(resolve_program(binary))
1234                .args(version_probe_args(binary))
1235                .stdin(std::process::Stdio::null())
1236                .output();
1237            match output {
1238                Ok(out) if out.status.success() => {
1239                    let ver = String::from_utf8_lossy(&out.stdout).trim().to_string();
1240                    let first_line = ver.lines().next().unwrap_or(&ver).to_string();
1241                    BinaryCheckStatus {
1242                        name,
1243                        available: true,
1244                        version: if first_line.is_empty() {
1245                            None
1246                        } else {
1247                            Some(first_line)
1248                        },
1249                    }
1250                }
1251                _ => BinaryCheckStatus {
1252                    name,
1253                    available: false,
1254                    version: None,
1255                },
1256            }
1257        })
1258        .collect()
1259}
1260
1261#[cfg(test)]
1262mod tests {
1263    use super::*;
1264    use std::fs;
1265    use tempfile::TempDir;
1266
1267    #[test]
1268    fn go_is_probed_with_the_subcommand_it_actually_accepts() {
1269        // `go --version` exits 2 with "flag provided but not defined: -version". The
1270        // probe reading that as "go is not installed" made `devp doctor` warn on every
1271        // machine with Go on it, and made the Go adapter fall back from `go mod
1272        // download` to the weaker manifest-age check before deleting anything.
1273        assert_eq!(version_probe_args("go"), &["version"]);
1274        assert_eq!(version_probe_args("npm"), &["--version"]);
1275    }
1276
1277    #[test]
1278    fn every_probed_adapter_binary_has_somewhere_to_get_it() {
1279        // A `doctor` warning that names a manager and not how to install it is research
1280        // homework. The adapters excluded from the probe have no binary to install.
1281        for adapter in get_all_adapters() {
1282            let name = adapter.name();
1283            if NO_RESTORE_BINARY.contains(&name) {
1284                continue;
1285            }
1286            assert!(
1287                install_hint(name).is_some(),
1288                "adapter `{name}` has no install hint"
1289            );
1290        }
1291    }
1292
1293    #[test]
1294    fn test_bloat_dir_display() {
1295        let bd = BloatDir {
1296            name: "node_modules".to_string(),
1297            path: PathBuf::from("/test/node_modules"),
1298            size_bytes: 1024,
1299            shared_bytes: 0,
1300        };
1301        assert!(bd.to_string().contains("node_modules"));
1302    }
1303
1304    #[test]
1305    fn test_hardlink_size_counts_a_plain_file_in_full() {
1306        let tmp = TempDir::new().unwrap();
1307        let tree = tmp.path().join("tree");
1308        fs::create_dir(&tree).unwrap();
1309        fs::write(tree.join("copied.txt"), "12345").unwrap();
1310        let size = dir_size_with_hardlinks(&tree);
1311        assert_eq!(size.freed_bytes, 5);
1312        assert_eq!(size.shared_bytes, 0);
1313    }
1314
1315    #[test]
1316    fn test_hardlink_size_excludes_a_file_the_store_keeps() {
1317        // The pnpm shape: the store's copy lives outside the tree being deleted, so
1318        // deleting the tree frees nothing for this file.
1319        let tmp = TempDir::new().unwrap();
1320        let store = tmp.path().join("store");
1321        let tree = tmp.path().join("tree");
1322        fs::create_dir(&store).unwrap();
1323        fs::create_dir(&tree).unwrap();
1324        fs::write(store.join("pkg.js"), "0123456789").unwrap();
1325        fs::hard_link(store.join("pkg.js"), tree.join("pkg.js")).unwrap();
1326        let size = dir_size_with_hardlinks(&tree);
1327        assert_eq!(size.freed_bytes, 0);
1328        assert_eq!(size.shared_bytes, 10);
1329    }
1330
1331    #[test]
1332    fn test_hardlink_size_counts_an_internal_pair_once() {
1333        // Both names live inside the tree, so the delete removes the last link and
1334        // the bytes really are freed — but only once, not per name.
1335        let tmp = TempDir::new().unwrap();
1336        let tree = tmp.path().join("tree");
1337        fs::create_dir(&tree).unwrap();
1338        fs::write(tree.join("a.js"), "abcdefg").unwrap();
1339        fs::hard_link(tree.join("a.js"), tree.join("b.js")).unwrap();
1340        let size = dir_size_with_hardlinks(&tree);
1341        assert_eq!(size.freed_bytes, 7);
1342        assert_eq!(size.shared_bytes, 0);
1343    }
1344
1345    #[test]
1346    fn test_dir_size_empty() {
1347        let tmp = TempDir::new().unwrap();
1348        assert_eq!(dir_size(tmp.path()), 0);
1349    }
1350
1351    #[test]
1352    fn test_dir_size_with_files() {
1353        let tmp = TempDir::new().unwrap();
1354        fs::write(tmp.path().join("file1.txt"), "hello").unwrap();
1355        fs::write(tmp.path().join("file2.txt"), "world!").unwrap();
1356        assert_eq!(dir_size(tmp.path()), 11); // 5 + 6
1357    }
1358
1359    #[test]
1360    fn test_dir_size_nonexistent() {
1361        assert_eq!(dir_size(Path::new("/nonexistent/path")), 0);
1362    }
1363
1364    #[test]
1365    fn test_get_all_adapters_not_empty() {
1366        let adapters = get_all_adapters();
1367        assert!(adapters.len() >= 6);
1368    }
1369
1370    #[test]
1371    fn test_detect_adapters_npm() {
1372        let tmp = TempDir::new().unwrap();
1373        fs::write(tmp.path().join("package.json"), "{}").unwrap();
1374        fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
1375        let adapters = detect_adapters(tmp.path());
1376        let names: Vec<&str> = adapters.iter().map(|a| a.name()).collect();
1377        assert!(names.contains(&"npm"));
1378    }
1379
1380    #[test]
1381    fn test_detect_adapters_empty_dir() {
1382        let tmp = TempDir::new().unwrap();
1383        let adapters = detect_adapters(tmp.path());
1384        assert!(adapters.is_empty());
1385    }
1386
1387    /// Names of the adapters that detect in `dir`, sorted.
1388    fn detected_names(dir: &Path) -> Vec<&'static str> {
1389        let mut names: Vec<&'static str> = detect_adapters(dir).iter().map(|a| a.name()).collect();
1390        names.sort_unstable();
1391        names
1392    }
1393
1394    #[test]
1395    fn test_detect_adapters_multiple_ecosystems_coexist() {
1396        // Different managers owning different directories must all survive detection.
1397        let tmp = TempDir::new().unwrap();
1398        fs::write(tmp.path().join("package.json"), "{}").unwrap();
1399        fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
1400        fs::write(tmp.path().join("uv.lock"), "").unwrap();
1401        fs::write(tmp.path().join("Cargo.toml"), "[package]").unwrap();
1402        fs::write(tmp.path().join("go.mod"), "module x").unwrap();
1403
1404        assert_eq!(detected_names(tmp.path()), vec!["cargo", "go", "npm", "uv"]);
1405    }
1406
1407    #[test]
1408    fn test_js_conflict_resolved_by_package_manager_field() {
1409        let tmp = TempDir::new().unwrap();
1410        fs::write(
1411            tmp.path().join("package.json"),
1412            r#"{"packageManager":"yarn@4.1.0"}"#,
1413        )
1414        .unwrap();
1415        fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
1416        fs::write(tmp.path().join("pnpm-lock.yaml"), "").unwrap();
1417        fs::write(tmp.path().join("yarn.lock"), "").unwrap();
1418
1419        assert_eq!(detected_names(tmp.path()), vec!["yarn"]);
1420    }
1421
1422    #[test]
1423    fn test_js_conflict_resolved_by_what_installed_node_modules() {
1424        // npm's lockfile is written last, but the tree on disk was built by pnpm — and
1425        // that tree is what is about to be deleted.
1426        let tmp = TempDir::new().unwrap();
1427        fs::write(tmp.path().join("package.json"), "{}").unwrap();
1428        fs::write(tmp.path().join("pnpm-lock.yaml"), "").unwrap();
1429        fs::create_dir_all(tmp.path().join("node_modules/.pnpm")).unwrap();
1430        std::thread::sleep(std::time::Duration::from_millis(20));
1431        fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
1432
1433        assert_eq!(detected_names(tmp.path()), vec!["pnpm"]);
1434    }
1435
1436    #[test]
1437    fn test_js_conflict_prefers_yarn_state_over_leftover_npm_bookkeeping() {
1438        // A repo migrated npm → yarn keeps npm's hidden lockfile inside node_modules.
1439        let tmp = TempDir::new().unwrap();
1440        fs::write(tmp.path().join("package.json"), "{}").unwrap();
1441        fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
1442        fs::write(tmp.path().join("yarn.lock"), "").unwrap();
1443        let nm = tmp.path().join("node_modules");
1444        fs::create_dir_all(&nm).unwrap();
1445        fs::write(nm.join(".package-lock.json"), "{}").unwrap();
1446        fs::write(nm.join(".yarn-state.yml"), "").unwrap();
1447
1448        assert_eq!(detected_names(tmp.path()), vec!["yarn"]);
1449    }
1450
1451    #[test]
1452    fn test_declared_package_manager_outranks_what_is_installed() {
1453        // Corepack pins the project to pnpm; the npm tree on disk is the accident.
1454        let tmp = TempDir::new().unwrap();
1455        fs::write(
1456            tmp.path().join("package.json"),
1457            r#"{"packageManager":"pnpm@9.1.0"}"#,
1458        )
1459        .unwrap();
1460        fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
1461        fs::write(tmp.path().join("pnpm-lock.yaml"), "").unwrap();
1462        let nm = tmp.path().join("node_modules");
1463        fs::create_dir_all(&nm).unwrap();
1464        fs::write(nm.join(".package-lock.json"), "{}").unwrap();
1465
1466        assert_eq!(detected_names(tmp.path()), vec!["pnpm"]);
1467    }
1468
1469    #[test]
1470    fn test_uv_takes_precedence_over_plain_venv() {
1471        // A uv project declared through `[tool.uv]` alone, with a requirements.txt and a
1472        // virtual environment left over from before the migration.
1473        let tmp = TempDir::new().unwrap();
1474        fs::write(
1475            tmp.path().join("pyproject.toml"),
1476            "[project]\nname = \"x\"\n\n[tool.uv]\n",
1477        )
1478        .unwrap();
1479        fs::write(tmp.path().join("requirements.txt"), "requests\n").unwrap();
1480        let venv = tmp.path().join(".venv");
1481        fs::create_dir_all(&venv).unwrap();
1482        fs::write(venv.join("pyvenv.cfg"), "home = /usr\n").unwrap();
1483
1484        assert_eq!(detected_names(tmp.path()), vec!["uv"]);
1485    }
1486
1487    #[test]
1488    fn test_plain_venv_handles_projects_uv_does_not_claim() {
1489        let tmp = TempDir::new().unwrap();
1490        fs::write(tmp.path().join("requirements.txt"), "requests\n").unwrap();
1491        let venv = tmp.path().join("venv");
1492        fs::create_dir_all(&venv).unwrap();
1493        fs::write(venv.join("pyvenv.cfg"), "home = /usr\n").unwrap();
1494
1495        assert_eq!(detected_names(tmp.path()), vec!["venv"]);
1496    }
1497
1498    #[test]
1499    fn test_js_conflict_falls_back_to_newest_lockfile() {
1500        let tmp = TempDir::new().unwrap();
1501        fs::write(tmp.path().join("package.json"), "{}").unwrap();
1502        fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
1503        // Written second, and touched again, so pnpm is unambiguously the newer of the
1504        // two even on filesystems with coarse timestamp granularity.
1505        std::thread::sleep(std::time::Duration::from_millis(20));
1506        fs::write(tmp.path().join("pnpm-lock.yaml"), "").unwrap();
1507
1508        assert_eq!(detected_names(tmp.path()), vec!["pnpm"]);
1509    }
1510
1511    #[test]
1512    fn test_js_conflict_ignores_an_unrecognised_package_manager_field() {
1513        // A `packageManager` naming something we have no adapter for must not wipe out
1514        // the detection entirely — fall through to the lockfile timestamps.
1515        let tmp = TempDir::new().unwrap();
1516        fs::write(
1517            tmp.path().join("package.json"),
1518            r#"{"packageManager":"deno@2.0.0"}"#,
1519        )
1520        .unwrap();
1521        fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
1522        std::thread::sleep(std::time::Duration::from_millis(20));
1523        fs::write(tmp.path().join("yarn.lock"), "").unwrap();
1524
1525        assert_eq!(detected_names(tmp.path()), vec!["yarn"]);
1526    }
1527
1528    #[test]
1529    fn test_js_conflict_does_not_disturb_a_single_manager() {
1530        let tmp = TempDir::new().unwrap();
1531        fs::write(tmp.path().join("package.json"), "{}").unwrap();
1532        fs::write(tmp.path().join("pnpm-lock.yaml"), "").unwrap();
1533        assert_eq!(detected_names(tmp.path()), vec!["pnpm"]);
1534    }
1535
1536    #[test]
1537    fn test_js_adapters_declare_their_lockfiles() {
1538        for adapter in get_all_adapters() {
1539            if JS_MANAGERS.contains(&adapter.name()) {
1540                assert!(
1541                    !adapter.lockfiles().is_empty(),
1542                    "{} shares node_modules and must declare its lockfiles for \
1543                     conflict resolution",
1544                    adapter.name()
1545                );
1546            }
1547        }
1548    }
1549
1550    #[test]
1551    fn test_adapter_names_unique() {
1552        let adapters = get_all_adapters();
1553        let names: Vec<&str> = adapters.iter().map(|a| a.name()).collect();
1554        let mut unique = names.clone();
1555        unique.sort();
1556        unique.dedup();
1557        assert_eq!(names.len(), unique.len(), "Adapter names must be unique");
1558    }
1559
1560    #[test]
1561    fn a_runtime_tag_is_a_version_number_and_nothing_else() {
1562        // This is spliced into a command line, and the registry it comes from is a file
1563        // on disk. A hand-edited or corrupted entry must not reach a shell.
1564        assert!(is_valid_runtime_tag("3.12"));
1565        assert!(is_valid_runtime_tag("3.9"));
1566        for bad in [
1567            "",
1568            "3",
1569            "3.12.1",
1570            "3.x",
1571            "3.12; rm -rf /",
1572            "-3.12",
1573            "../python",
1574            "3.1234",
1575            "300.1",
1576        ] {
1577            assert!(!is_valid_runtime_tag(bad), "{bad} must be refused");
1578        }
1579    }
1580
1581    #[test]
1582    fn the_interpreter_is_read_from_the_environments_own_pyvenv_cfg() {
1583        let tmp = tempfile::tempdir().unwrap();
1584        let venv = tmp.path().join(".venv");
1585        std::fs::create_dir_all(&venv).unwrap();
1586        std::fs::write(
1587            venv.join("pyvenv.cfg"),
1588            "home = /usr/bin\nversion = 3.12.4\ninclude-system-site-packages = false\n",
1589        )
1590        .unwrap();
1591        assert_eq!(venv_runtime_tag(&venv), Some("3.12".to_string()));
1592    }
1593
1594    #[test]
1595    fn a_directory_that_is_not_an_environment_records_no_interpreter() {
1596        let tmp = tempfile::tempdir().unwrap();
1597        assert_eq!(venv_runtime_tag(tmp.path()), None);
1598    }
1599}