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