Skip to main content

greengate_runtime/
snapshot_prep.rs

1//! Make a fresh snapshot runnable: carry the untracked files a suite needs,
2//! then prepare its JavaScript dependencies.
3//!
4//! A snapshot is a checkout, not a workspace — no `node_modules`, no `.env` —
5//! and a gate started there fails having tested nothing. Both steps run in
6//! [`crate::pushed_tree::PushedTree::prepare`], before `greengate.snapshotPrepare`
7//! (the escape hatch), and a failure in either is the snapshot's failure: no
8//! suite runs, nothing is stamped.
9//!
10//! ## What a stamp may rest on
11//!
12//! A stamp claims the gate passed on the COMMITTED content. So nothing here
13//! may put content from the developer's tree where committed content lives:
14//! a carried path must be untracked in the snapshot's own index, and the
15//! dependencies must be the ones the committed lockfile describes.
16//!
17//! The default, `install`, is what CI does: `npm ci`, `pnpm install
18//! --frozen-lockfile`, `yarn install --frozen-lockfile` (yarn 1) or
19//! `--immutable` (berry, told apart by the lockfile's `__metadata:` block).
20//! A bun lockfile is recognised and refused with the fix named, never
21//! installed: a gate run over no dependencies fails every workspace at once
22//! and reads like a broken branch. `reuse` (pnpm and npm; yarn and bun always
23//! install, see `voucher`) clones the working tree's `node_modules` and keeps
24//! the clone only when the manager vouches for it: pnpm by its isolated layout
25//! and a frozen offline install, npm by a dry-run install that would add,
26//! remove and change nothing. Both catch a missing or wrong-version package, a
27//! stray directory, and a manifest the lockfile does not satisfy; npm also
28//! catches a version raised in place with its timestamps set back. NEITHER
29//! catches a file edited in place without a version change: the mtime scan
30//! covers that only while the edit is newer than the install. That limit is
31//! why reuse is opt-in.
32//!
33//! Every question about a manifest goes to the package manager, through exit
34//! codes and parseable output: this crate is dependency-free and has no JSON
35//! or YAML parser, and a hand-rolled one reading `workspaces` would be a
36//! second, divergent answer to a question npm already answers.
37
38use crate::names::BIN;
39use std::path::{Component, Path, PathBuf};
40use std::process::{Command, Stdio};
41
42use crate::ui::{highlight, warning_sign};
43
44const CARRY: &str = "greengate.snapshotCarry";
45const DEPS: &str = "greengate.snapshotDeps";
46
47/// `greengate.snapshotDeps`.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum DepsMode {
50    /// `npm ci` / `pnpm install --frozen-lockfile` / `yarn install
51    /// --frozen-lockfile` (`--immutable` for berry) in the snapshot.
52    Install,
53    /// Clone the working tree's install, keep it only if the manager accepts it.
54    Reuse,
55    /// Prepare nothing.
56    Off,
57}
58
59pub fn deps_mode(settings: &crate::config::Settings) -> DepsMode {
60    match crate::config::enumerated_or(settings, DEPS, &["install", "reuse", "off"], "install") {
61        "reuse" => DepsMode::Reuse,
62        "off" => DepsMode::Off,
63        _ => DepsMode::Install,
64    }
65}
66
67/// `greengate.snapshotCarry`, split on whitespace and commas.
68pub fn carry_list(settings: &crate::config::Settings) -> Vec<String> {
69    crate::config::string_value(settings, CARRY)
70        .map(|v| {
71            v.split(|c: char| c.is_whitespace() || c == ',')
72                .filter(|s| !s.is_empty())
73                .map(str::to_string)
74                .collect()
75        })
76        .unwrap_or_default()
77}
78
79/// The snapshot's own tracked files, `-z`, with git's environment stripped:
80/// a hook's `GIT_DIR`/`GIT_INDEX_FILE` would otherwise answer for the
81/// developer's repository, and the pushed tip — not HEAD, not the index the
82/// developer is staging into — decides what the snapshot holds.
83pub fn snapshot_files(snapshot: &Path) -> Result<Vec<String>, String> {
84    let mut cmd = Command::new("git");
85    cmd.arg("-C")
86        .arg(snapshot)
87        .args(["ls-files", "-z"])
88        .stdin(Stdio::null())
89        .stderr(Stdio::null());
90    crate::hooks::common::strip_git_env(&mut cmd);
91    let out = cmd
92        .output()
93        .map_err(|e| format!("could not list the snapshot's files: {e}"))?;
94    if !out.status.success() {
95        return Err("could not list the snapshot's files".to_string());
96    }
97    Ok(crate::git::split_nul_paths(&out.stdout))
98}
99
100// ---------------------------------------------------------------------------
101// carry
102// ---------------------------------------------------------------------------
103
104/// One validated carry entry.
105struct Carried {
106    entry: String,
107    src: PathBuf,
108    dst: PathBuf,
109}
110
111/// Why one carry entry is refused, or `None` when it is lexically a
112/// repo-relative path with nothing to climb out through.
113fn lexical_problem(entry: &str) -> Option<&'static str> {
114    if entry.is_empty() {
115        return Some("empty");
116    }
117    let bytes = entry.as_bytes();
118    if entry.starts_with('/') || entry.starts_with('\\') || (bytes.len() >= 2 && bytes[1] == b':') {
119        return Some("not a repo-relative path");
120    }
121    for part in entry.split(['/', '\\']) {
122        if part.is_empty() {
123            return Some("has an empty path component");
124        }
125        if part == "." || part == ".." {
126            return Some("has a `.` or `..` component");
127        }
128        if part.eq_ignore_ascii_case(".git") {
129            return Some("is inside .git");
130        }
131    }
132    None
133}
134
135/// Is `entry` — or anything inside it, or any directory above it — tracked in
136/// the snapshot? Carrying it would put the developer's copy over committed
137/// content, and the stamp would vouch for a tree nobody committed.
138fn tracked_collision(entry: &str, files: &[String]) -> Option<String> {
139    let inside = format!("{entry}/");
140    files
141        .iter()
142        .find(|f| {
143            f.as_str() == entry || f.starts_with(&inside) || entry.starts_with(&format!("{f}/"))
144        })
145        .cloned()
146}
147
148fn is_symlink(p: &Path) -> bool {
149    std::fs::symlink_metadata(p)
150        .map(|m| m.file_type().is_symlink())
151        .unwrap_or(false)
152}
153
154/// A symlinked directory between `root` and `rel`'s last component — which
155/// would take a read, or a write, somewhere outside the tree it names.
156fn symlinked_ancestor(root: &Path, rel: &Path) -> Option<PathBuf> {
157    let mut at = root.to_path_buf();
158    let parts: Vec<_> = rel.components().collect();
159    for part in parts.iter().take(parts.len().saturating_sub(1)) {
160        at.push(part.as_os_str());
161        if is_symlink(&at) {
162            return Some(at);
163        }
164    }
165    None
166}
167
168/// A symlink anywhere inside `dir`, not followed.
169fn symlink_inside(dir: &Path) -> std::io::Result<Option<PathBuf>> {
170    for entry in std::fs::read_dir(dir)? {
171        let entry = entry?;
172        let kind = entry.file_type()?;
173        if kind.is_symlink() {
174            return Ok(Some(entry.path()));
175        }
176        if kind.is_dir() {
177            if let Some(found) = symlink_inside(&entry.path())? {
178                return Ok(Some(found));
179            }
180        }
181    }
182    Ok(None)
183}
184
185fn copy_tree(src: &Path, dst: &Path) -> std::io::Result<()> {
186    let meta = std::fs::symlink_metadata(src)?;
187    if meta.is_dir() {
188        std::fs::create_dir(dst)?;
189        for entry in std::fs::read_dir(src)? {
190            let entry = entry?;
191            copy_tree(&entry.path(), &dst.join(entry.file_name()))?;
192        }
193        Ok(())
194    } else {
195        std::fs::copy(src, dst).map(|_| ())
196    }
197}
198
199/// Copy the untracked files `greengate.snapshotCarry` names from `source` into
200/// `snapshot`.
201///
202/// Every entry is validated before anything is copied, and every refusal is
203/// reported in ONE message — `config::complain` says a key once, which would
204/// hide all but the first bad entry. Any refusal fails preparation: a carry
205/// the author got wrong must be loud, never a silently thinner snapshot that
206/// still earns a stamp. An entry that is simply absent is skipped (a `.env`
207/// exists on a laptop and not in CI); one that is present and cannot be
208/// copied fails.
209pub fn carry(
210    entries: &[String],
211    source: &Path,
212    snapshot: &Path,
213    files: &[String],
214) -> Result<(), String> {
215    let mut refused: Vec<String> = Vec::new();
216    let mut missing: Vec<&str> = Vec::new();
217    let mut plan: Vec<Carried> = Vec::new();
218    for entry in entries {
219        let norm = entry.replace('\\', "/");
220        let norm = norm.trim_end_matches('/').to_string();
221        if let Some(why) = lexical_problem(&norm) {
222            refused.push(format!("{entry}: {why}"));
223            continue;
224        }
225        if let Some(f) = tracked_collision(&norm, files) {
226            refused.push(format!(
227                "{entry}: tracked content ({f}) — only untracked files can be carried"
228            ));
229            continue;
230        }
231        let rel = PathBuf::from(&norm);
232        let src = source.join(&rel);
233        let dst = snapshot.join(&rel);
234        if let Some(link) = symlinked_ancestor(source, &rel) {
235            refused.push(format!(
236                "{entry}: {} is a symlink in the working tree",
237                link.display()
238            ));
239            continue;
240        }
241        if let Some(link) = symlinked_ancestor(snapshot, &rel) {
242            refused.push(format!(
243                "{entry}: {} is a symlink in the snapshot",
244                link.display()
245            ));
246            continue;
247        }
248        let meta = match std::fs::symlink_metadata(&src) {
249            Ok(m) => m,
250            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
251                missing.push(entry);
252                continue;
253            }
254            Err(e) => {
255                refused.push(format!("{entry}: cannot be read: {e}"));
256                continue;
257            }
258        };
259        if meta.file_type().is_symlink() {
260            refused.push(format!("{entry}: is a symlink"));
261            continue;
262        }
263        if meta.is_dir() {
264            match symlink_inside(&src) {
265                Ok(Some(link)) => {
266                    refused.push(format!("{entry}: holds a symlink ({})", link.display()));
267                    continue;
268                }
269                Ok(None) => {}
270                Err(e) => {
271                    refused.push(format!("{entry}: cannot be read: {e}"));
272                    continue;
273                }
274            }
275        }
276        if std::fs::symlink_metadata(&dst).is_ok() {
277            refused.push(format!("{entry}: already exists in the snapshot"));
278            continue;
279        }
280        plan.push(Carried {
281            entry: entry.clone(),
282            src,
283            dst,
284        });
285    }
286    if !refused.is_empty() {
287        return Err(format!(
288            "{CARRY} refused {}: {}",
289            if refused.len() == 1 {
290                "an entry".to_string()
291            } else {
292                format!("{} entries", refused.len())
293            },
294            refused.join("; ")
295        ));
296    }
297    if !missing.is_empty() {
298        println!(
299            "snapshot: not carrying {} — not in the working tree",
300            missing.join(", ")
301        );
302    }
303    for c in &plan {
304        if let Some(parent) = c.dst.parent() {
305            std::fs::create_dir_all(parent).map_err(|e| format!("{CARRY}: {}: {e}", c.entry))?;
306        }
307        copy_tree(&c.src, &c.dst)
308            .map_err(|e| format!("{CARRY}: {} could not be copied: {e}", c.entry))?;
309    }
310    if !plan.is_empty() {
311        let names: Vec<&str> = plan.iter().map(|c| c.entry.as_str()).collect();
312        println!("snapshot: carried {}", names.join(", "));
313    }
314    Ok(())
315}
316
317// ---------------------------------------------------------------------------
318// dependencies
319// ---------------------------------------------------------------------------
320
321#[derive(Debug, Clone, Copy, PartialEq, Eq)]
322pub enum Manager {
323    Npm,
324    Pnpm,
325    Yarn,
326    /// Recognised so that its lockfile is a unit — skipped when the push
327    /// does not touch it, refused with the fix named when it does — never
328    /// installed: see `bun_refusal`.
329    Bun,
330}
331
332impl Manager {
333    const ALL: [Manager; 4] = [Manager::Npm, Manager::Pnpm, Manager::Yarn, Manager::Bun];
334
335    /// The lockfiles that make a directory a unit of this manager. bun has
336    /// two: the binary `bun.lockb`, and the text `bun.lock` since bun 1.2.
337    fn lockfiles(self) -> &'static [&'static str] {
338        match self {
339            Manager::Npm => &["package-lock.json"],
340            Manager::Pnpm => &["pnpm-lock.yaml"],
341            Manager::Yarn => &["yarn.lock"],
342            Manager::Bun => &["bun.lock", "bun.lockb"],
343        }
344    }
345    pub(crate) fn tool(self) -> &'static str {
346        match self {
347            Manager::Npm => "npm",
348            Manager::Pnpm => "pnpm",
349            Manager::Yarn => "yarn",
350            Manager::Bun => "bun",
351        }
352    }
353
354    /// The manager whose lockfile sits in `root`, when exactly one does.
355    pub(crate) fn from_root_lockfile(root: &Path) -> Option<Manager> {
356        let mut found = Manager::ALL
357            .into_iter()
358            .filter(|m| m.lockfiles().iter().any(|l| root.join(l).is_file()));
359        let one = found.next()?;
360        found.next().is_none().then_some(one)
361    }
362
363    /// The command that adds `spec` (`prettier@3.9.10`) as a dev dependency.
364    pub(crate) fn add_dev_command(self, spec: &str) -> String {
365        match self {
366            Manager::Npm => format!("npm install --save-dev --save-exact {spec}"),
367            Manager::Pnpm => format!("pnpm add -D --save-exact {spec}"),
368            Manager::Yarn => format!("yarn add -D --exact {spec}"),
369            Manager::Bun => format!("bun add -d --exact {spec}"),
370        }
371    }
372}
373
374/// One installation unit: a directory holding a tracked lockfile, and the
375/// manager that reads it.
376#[derive(Debug, Clone, PartialEq, Eq)]
377pub struct Unit {
378    /// Repo-relative, `""` for the root.
379    pub dir: String,
380    pub manager: Manager,
381    /// The tracked lockfile's basename.
382    pub lockfile: &'static str,
383    /// pnpm only: a lockfile with no `pnpm-workspace.yaml` beside it is a
384    /// standalone project, even inside a workspace (see `audit::pnpm_args`).
385    pub standalone: bool,
386    /// yarn only: the lockfile is yarn 2+'s ("berry"), whose install is
387    /// `--immutable`; a classic (yarn 1) lockfile installs with
388    /// `--frozen-lockfile`.
389    pub berry: bool,
390}
391
392/// Is this `yarn.lock` yarn 2+'s? Berry writes a `__metadata:` block at the
393/// top of every lockfile; yarn 1 writes `# yarn lockfile v1` and never that
394/// key. Read from the SNAPSHOT's lockfile, so the pushed commit decides.
395pub fn is_berry_lock(text: &str) -> bool {
396    text.lines().any(|l| l.starts_with("__metadata:"))
397}
398
399/// The directories of `files` named exactly `name`, repo-relative (`""` for
400/// the root), sorted and deduplicated. Pure: the caller decides WHICH index
401/// the list comes from — the snapshot's, for a snapshot.
402pub fn lockfile_dirs_in(files: &[String], name: &str) -> Vec<String> {
403    let mut dirs: Vec<String> = files
404        .iter()
405        .filter(|p| p.rsplit('/').next().unwrap_or(p) == name)
406        .map(|p| {
407            p.rsplit_once('/')
408                .map(|(d, _)| d.to_string())
409                .unwrap_or_default()
410        })
411        .collect();
412    dirs.sort();
413    dirs.dedup();
414    dirs
415}
416
417fn join_rel(dir: &str, name: &str) -> String {
418    if dir.is_empty() {
419        name.to_string()
420    } else {
421        format!("{dir}/{name}")
422    }
423}
424
425/// The `packageManager` field of a package.json, by a targeted scan of that
426/// one key — the manager it names (`npm@…`, `pnpm@…`, `yarn@…`, `bun@…`)
427/// when it names one without ambiguity, `None` otherwise.
428pub fn declared_manager(package_json: &str) -> Option<Manager> {
429    let key = "\"packageManager\"";
430    let mut hits = package_json.match_indices(key);
431    let (at, _) = hits.next()?;
432    if hits.next().is_some() {
433        return None;
434    }
435    let rest = package_json[at + key.len()..].trim_start();
436    let rest = rest.strip_prefix(':')?.trim_start();
437    let rest = rest.strip_prefix('"')?;
438    let value = &rest[..rest.find('"')?];
439    let name = value.split('@').next().unwrap_or(value);
440    Manager::ALL.into_iter().find(|m| m.tool() == name)
441}
442
443/// Every installation unit in `files`. A directory holding MORE THAN ONE
444/// manager's lockfile is settled by `packageManager`, or refused: guessing
445/// would install the wrong tree and test it as if it were the right one.
446pub fn units(files: &[String], snapshot: &Path) -> Result<Vec<Unit>, String> {
447    // Every tracked lockfile: (directory, manager, basename).
448    let mut found: Vec<(String, Manager, &'static str)> = Vec::new();
449    for m in Manager::ALL {
450        for lock in m.lockfiles() {
451            found.extend(
452                lockfile_dirs_in(files, lock)
453                    .into_iter()
454                    .map(|dir| (dir, m, *lock)),
455            );
456        }
457    }
458    let mut dirs: Vec<String> = found.iter().map(|f| f.0.clone()).collect();
459    dirs.sort();
460    dirs.dedup();
461    let mut out = Vec::new();
462    for dir in dirs {
463        let here: Vec<&(String, Manager, &'static str)> =
464            found.iter().filter(|f| f.0 == dir).collect();
465        let (manager, lockfile) = if here.iter().all(|f| f.1 == here[0].1) {
466            (here[0].1, here[0].2)
467        } else {
468            let manifest = snapshot.join(join_rel(&dir, "package.json"));
469            let body = std::fs::read_to_string(&manifest).unwrap_or_default();
470            declared_manager(&body)
471                .and_then(|m| here.iter().find(|f| f.1 == m))
472                .map(|f| (f.1, f.2))
473                .ok_or_else(|| {
474                    let names: Vec<&str> = here.iter().map(|f| f.2).collect();
475                    format!(
476                        "both {} in {} and no `packageManager` to choose — set \
477                         greengate.snapshotPrepare",
478                        names.join(" and "),
479                        if dir.is_empty() { "the root" } else { &dir }
480                    )
481                })?
482        };
483        let standalone =
484            manager == Manager::Pnpm && !files.contains(&join_rel(&dir, "pnpm-workspace.yaml"));
485        let berry = manager == Manager::Yarn
486            && std::fs::read_to_string(snapshot.join(join_rel(&dir, lockfile)))
487                .map(|t| is_berry_lock(&t))
488                .unwrap_or(false);
489        out.push(Unit {
490            dir,
491            manager,
492            lockfile,
493            standalone,
494            berry,
495        });
496    }
497    Ok(out)
498}
499
500/// Why a bun unit is never installed, with the fix: bun's `--frozen-lockfile`
501/// and its lockfile formats have not been exercised here, and running the
502/// gate in a checkout with no dependencies fails every workspace at once
503/// and reads like a broken branch (#308). The snapshot's owner names the
504/// install command, or turns the preparation off.
505fn bun_refusal(u: &Unit) -> String {
506    format!(
507        "{} in {}: {BIN} cannot install bun dependencies — set greengate.snapshotPrepare \
508         to the install command, or greengate.snapshotDeps off",
509        u.lockfile,
510        unit_label(u)
511    )
512}
513
514fn unit_label(u: &Unit) -> String {
515    if u.dir.is_empty() {
516        "the root".to_string()
517    } else {
518        format!("{}/", u.dir)
519    }
520}
521
522fn manager_cmd(u: &Unit, at: &Path, args: &[&str]) -> Command {
523    let mut cmd = Command::new(crate::hooks::common::program(u.manager.tool()));
524    cmd.args(args).current_dir(at).stdin(Stdio::null());
525    if u.manager == Manager::Pnpm {
526        // A purge prompt cannot be answered from a hook, and aborts.
527        cmd.arg("--config.confirmModulesPurge=false");
528        if u.standalone {
529            cmd.arg("--ignore-workspace");
530        }
531    }
532    crate::hooks::common::strip_git_env(&mut cmd);
533    // For a `prepare` script that wants to know; the guard itself is the
534    // marker in the snapshot's git dir (`pushed_tree::MARKER`).
535    cmd.env(crate::pushed_tree::SNAPSHOT_ENV, "1");
536    cmd
537}
538
539/// Run a manager command quietly; `Ok(output)` on exit 0, `Err(output)`
540/// otherwise — the output is what the caller quotes when it says why.
541fn quiet(settings: &crate::config::Settings, mut cmd: Command) -> Result<String, String> {
542    match crate::hooks::common::capture_within(settings, &mut cmd) {
543        Some((crate::hooks::common::Ran::Status(s), text)) if s.success() => Ok(text),
544        Some((_, text)) => Err(text),
545        None => Err("could not start".to_string()),
546    }
547}
548
549/// The last meaningful line of a tool's output, for a one-line reason.
550fn last_line(text: &str) -> String {
551    text.lines()
552        .map(str::trim)
553        .rfind(|l| !l.is_empty())
554        .unwrap_or("no output")
555        .chars()
556        .take(200)
557        .collect()
558}
559
560fn install(settings: &crate::config::Settings, u: &Unit, at: &Path) -> Result<(), String> {
561    let args: &[&str] = match u.manager {
562        Manager::Npm => &["ci", "--no-audit", "--no-fund", "--prefer-offline"],
563        Manager::Pnpm => &["install", "--frozen-lockfile", "--prefer-offline"],
564        // Berry accepts `--frozen-lockfile` only as a deprecated alias and
565        // warns on `--prefer-offline`; yarn 1 ignores `--immutable`. Each
566        // flavour gets its own spelling.
567        Manager::Yarn if u.berry => &["install", "--immutable"],
568        Manager::Yarn => &[
569            "install",
570            "--frozen-lockfile",
571            "--non-interactive",
572            "--prefer-offline",
573        ],
574        Manager::Bun => return Err(bun_refusal(u)),
575    };
576    let mut cmd = manager_cmd(u, at, args);
577    let what = format!("{} {}", u.manager.tool(), args[0]);
578    if crate::hooks::common::bounded_success(settings, &mut cmd, &what) {
579        Ok(())
580    } else {
581        Err(format!("{what} failed in {}", unit_label(u)))
582    }
583}
584
585#[cfg(any(target_os = "macos", target_os = "linux"))]
586const CROSS_VOLUME_HINT: &str = "the snapshot's temp dir is on another volume than the working \
587     tree; set TMPDIR to a directory on that volume";
588#[cfg(any(target_os = "macos", target_os = "linux"))]
589const NO_CLONE_HINT: &str = "this filesystem cannot clone; \
590     `git config greengate.snapshotDeps install` skips the attempt";
591
592/// Clone a directory copy-on-write or refuse. macOS calls `clonefile(2)` with
593/// `CLONE_NOFOLLOW`, so symlinks are cloned as symlinks; Linux runs GNU
594/// `cp -R -T --reflink=always` by absolute path. There is no plain-copy
595/// fallback: a copy would cost the disk the clone exists to save. An existing
596/// destination is refused and left untouched, and so is one that cannot be
597/// statted: only a path that is certainly absent is ours to clear after a
598/// failed clone, and never after `AlreadyExists`, which means someone else
599/// made it first.
600fn clone_dir(src: &Path, dst: &Path) -> Result<(), String> {
601    use std::io::ErrorKind;
602    let (ours, outcome) = match std::fs::symlink_metadata(dst) {
603        Ok(_) => (false, Err(std::io::Error::from(ErrorKind::AlreadyExists))),
604        Err(e) if e.kind() == ErrorKind::NotFound => (true, clone_tree(src, dst)),
605        Err(e) => (false, Err(e)),
606    };
607    match outcome {
608        Ok(()) => Ok(()),
609        Err(e) => {
610            let mut why = e.to_string();
611            if ours && e.kind() != ErrorKind::AlreadyExists {
612                if let Err(rm) = std::fs::remove_dir_all(dst) {
613                    if rm.kind() != ErrorKind::NotFound {
614                        why.push_str(&format!(
615                            ", and the partial clone could not be removed: {rm}"
616                        ));
617                    }
618                }
619            }
620            Err(format!(
621                "no copy-on-write clone of {} ({why})",
622                src.display()
623            ))
624        }
625    }
626}
627
628#[cfg(target_os = "macos")]
629fn clone_tree(src: &Path, dst: &Path) -> std::io::Result<()> {
630    use std::ffi::CString;
631    use std::os::unix::ffi::OsStrExt;
632
633    const CLONE_NOFOLLOW: u32 = 0x0001;
634    // errno values on macOS: another volume, and a filesystem without clones.
635    const EXDEV: i32 = 18;
636    const ENOTSUP: i32 = 45;
637    extern "C" {
638        fn clonefile(
639            src: *const std::os::raw::c_char,
640            dst: *const std::os::raw::c_char,
641            flags: u32,
642        ) -> std::os::raw::c_int;
643    }
644    let to_c = |p: &Path| {
645        CString::new(p.as_os_str().as_bytes()).map_err(|_| {
646            std::io::Error::new(std::io::ErrorKind::InvalidInput, "path contains a NUL byte")
647        })
648    };
649    let (from, to) = (to_c(src)?, to_c(dst)?);
650    // SAFETY: both pointers are NUL-terminated and outlive the call.
651    let rc = unsafe { clonefile(from.as_ptr(), to.as_ptr(), CLONE_NOFOLLOW) };
652    if rc == 0 {
653        return Ok(());
654    }
655    let err = std::io::Error::last_os_error();
656    Err(match err.raw_os_error() {
657        Some(EXDEV) => std::io::Error::other(CROSS_VOLUME_HINT),
658        Some(ENOTSUP) => std::io::Error::other(NO_CLONE_HINT),
659        _ => err,
660    })
661}
662
663#[cfg(target_os = "linux")]
664fn clone_tree(src: &Path, dst: &Path) -> std::io::Result<()> {
665    let cp = ["/bin/cp", "/usr/bin/cp"]
666        .into_iter()
667        .find(|p| Path::new(p).exists())
668        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no cp found"))?;
669    // `dst` is created here, atomically, so it is ours: a path that appeared
670    // since the caller's stat is `AlreadyExists` and is left alone. -T then
671    // copies INTO it rather than nesting `src` inside. --preserve keeps the
672    // modes and mtimes `clonefile` keeps, which the install-record scans read.
673    std::fs::create_dir(dst).map_err(|err| {
674        std::io::Error::new(
675            err.kind(),
676            format!("cannot create {}: {err}", dst.display()),
677        )
678    })?;
679    let out = Command::new(cp)
680        .args([
681            "-R",
682            "-T",
683            "--reflink=always",
684            "--preserve=mode,timestamps",
685            "--no-dereference",
686        ])
687        .arg(src)
688        .arg(dst)
689        // English messages, so the hints below match under any locale.
690        .env("LC_ALL", "C")
691        .stdin(Stdio::null())
692        .stdout(Stdio::null())
693        .output()?;
694    if out.status.success() {
695        return Ok(());
696    }
697    // `cp` prints one error per file it could not clone: a tree of 74k files
698    // on a filesystem without reflinks would bury the reason, so keep the first.
699    let stderr = String::from_utf8_lossy(&out.stderr);
700    let mut lines = stderr.lines().map(str::trim).filter(|l| !l.is_empty());
701    let first = lines.next().unwrap_or("cp failed with no output");
702    let more = lines.count();
703    let lower = first.to_lowercase();
704    Err(std::io::Error::other(if lower.contains("cross-device") {
705        CROSS_VOLUME_HINT.to_string()
706    } else if lower.contains("not supported") || lower.contains("inappropriate ioctl") {
707        NO_CLONE_HINT.to_string()
708    } else if more == 0 {
709        first.to_string()
710    } else {
711        format!("{first} (and {more} more)")
712    }))
713}
714
715#[cfg(not(any(target_os = "macos", target_os = "linux")))]
716fn clone_tree(_src: &Path, _dst: &Path) -> std::io::Result<()> {
717    Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
718}
719
720/// Lexically resolve `p` — `.` and `..` folded, nothing touched on disk.
721fn normalize(p: &Path) -> PathBuf {
722    let mut out = PathBuf::new();
723    for c in p.components() {
724        match c {
725            Component::ParentDir => {
726                out.pop();
727            }
728            Component::CurDir => {}
729            other => out.push(other.as_os_str()),
730        }
731    }
732    out
733}
734
735/// The first symlink under `dir` for which `bad(link, resolved)` holds,
736/// where `resolved` is its target folded lexically (relative targets against
737/// the directory holding the link). Nothing is followed.
738fn first_link(dir: &Path, bad: &dyn Fn(&Path, &Path) -> bool) -> std::io::Result<Option<PathBuf>> {
739    let mut stack = vec![dir.to_path_buf()];
740    while let Some(at) = stack.pop() {
741        for entry in std::fs::read_dir(&at)? {
742            let entry = entry?;
743            let kind = entry.file_type()?;
744            let path = entry.path();
745            if kind.is_symlink() {
746                let target = std::fs::read_link(&path)?;
747                let resolved = if target.is_absolute() {
748                    normalize(&target)
749                } else {
750                    normalize(&at.join(target))
751                };
752                if bad(&path, &resolved) {
753                    return Ok(Some(path));
754                }
755            } else if kind.is_dir() {
756                stack.push(path);
757            }
758        }
759    }
760    Ok(None)
761}
762
763/// The first symlink under `dir` that resolves into `source` — a clone
764/// still reading the developer's tree through a link is not isolated,
765/// whatever else it preserved.
766fn link_into(dir: &Path, sources: &[PathBuf]) -> std::io::Result<Option<PathBuf>> {
767    first_link(dir, &|path, resolved| {
768        // Lexically AND through every link: `/var` is itself a symlink on
769        // macOS, so the two spellings of one directory must both be caught.
770        let real = path.canonicalize().ok();
771        sources
772            .iter()
773            .any(|s| resolved.starts_with(s) || real.as_ref().is_some_and(|r| r.starts_with(s)))
774    })
775}
776
777/// The first symlink under `dir` that resolves outside every one of `roots`
778/// (the snapshot, spelled each way it can be): `npm link`, an absolute link,
779/// a `.bin` entry pointing elsewhere. A relative workspace link such as
780/// `../packages/a`, which stays inside the snapshot, is accepted.
781fn link_outside(dir: &Path, roots: &[PathBuf]) -> std::io::Result<Option<PathBuf>> {
782    first_link(dir, &|_, resolved| {
783        !roots.iter().any(|root| resolved.starts_with(root))
784    })
785}
786
787/// Does `skip` name this file? A pattern starting with `./` is a name directly
788/// under `root` (the `node_modules` being scanned), one ending in `*` is a name
789/// prefix, one holding a `/` is `<parent dir>/<name>`, any other is a name.
790fn skipped_file(skip: &[&str], root: &Path, parent: &Path, name: &str) -> bool {
791    skip.iter().any(|pattern| {
792        if let Some(top) = pattern.strip_prefix("./") {
793            parent == root && name == top
794        } else if let Some(prefix) = pattern.strip_suffix('*') {
795            name.starts_with(prefix)
796        } else if let Some((dir, file)) = pattern.split_once('/') {
797            name == file && parent.file_name().is_some_and(|d| d == dir)
798        } else {
799            name == *pattern
800        }
801    })
802}
803
804/// The first regular file under `nm` modified after `record`, the manager's
805/// install record, rewritten as an install finishes.
806///
807/// Skipped, because an install or the tools legitimately write them after
808/// the record: every `.bin/` (relinked last), `.cache/` and `.vite*/` (tool
809/// caches), and the files in `skip_files` (the voucher's own bookkeeping,
810/// the record included). Symlinks are not followed — under pnpm a top-level
811/// package is a link into `.pnpm`, which is walked itself.
812fn newer_than(
813    nm: &Path,
814    record: std::time::SystemTime,
815    skip_files: &[&str],
816) -> std::io::Result<Option<PathBuf>> {
817    if !nm.is_dir() {
818        return Ok(None);
819    }
820    let mut stack = vec![nm.to_path_buf()];
821    while let Some(at) = stack.pop() {
822        for entry in std::fs::read_dir(&at)? {
823            let entry = entry?;
824            let name = entry.file_name();
825            let name = name.to_string_lossy();
826            let kind = entry.file_type()?;
827            if kind.is_dir() {
828                if name == ".bin" || name == ".cache" || name.starts_with(".vite") {
829                    continue;
830                }
831                stack.push(entry.path());
832            } else if kind.is_file() {
833                if skipped_file(skip_files, nm, &at, &name) {
834                    continue;
835                }
836                if entry.metadata()?.modified()? > record {
837                    return Ok(Some(entry.path()));
838                }
839            }
840        }
841    }
842    Ok(None)
843}
844
845/// What `reuse` needs from a package manager; the rest of it is shared.
846#[derive(Debug, Clone, Copy, PartialEq, Eq)]
847enum Voucher {
848    /// A layout check, then a frozen offline install.
849    Pnpm,
850    /// A dry-run install, which reads the tree and the lockfile.
851    Npm,
852}
853
854impl Voucher {
855    /// The voucher of a unit's manager, or why that manager always installs.
856    fn of(u: &Unit) -> Result<Voucher, String> {
857        match u.manager {
858            Manager::Pnpm => Ok(Voucher::Pnpm),
859            Manager::Npm => Ok(Voucher::Npm),
860            Manager::Yarn if u.berry => Err("yarn cannot check an installed tree against its \
861                 lockfile, so yarn snapshots always install"
862                .to_string()),
863            Manager::Yarn => Err(
864                "yarn's own checks accept a tree with a package missing, so \
865                 yarn snapshots always install"
866                    .to_string(),
867            ),
868            Manager::Bun => Err(bun_refusal(u)),
869        }
870    }
871
872    /// The name every refusal carries.
873    fn tool(self) -> &'static str {
874        match self {
875            Voucher::Pnpm => "pnpm",
876            Voucher::Npm => "npm",
877        }
878    }
879
880    /// The install record, under `node_modules`, whose mtime marks the end of
881    /// the install.
882    fn record(self) -> &'static str {
883        match self {
884            Voucher::Pnpm => ".modules.yaml",
885            Voucher::Npm => ".package-lock.json",
886        }
887    }
888
889    /// Files an install writes after the record (see [`skipped_file`]). npm's
890    /// hidden lockfile is skipped in the root `node_modules` only.
891    fn skip_files(self, scope: Scope) -> &'static [&'static str] {
892        match (self, scope) {
893            (Voucher::Pnpm, _) => &[".modules.yaml", ".pnpm-workspace-state*", ".pnpm/lock.yaml"],
894            (Voucher::Npm, Scope::Root) => &["./.package-lock.json"],
895            (Voucher::Npm, Scope::Member) => &[],
896        }
897    }
898}
899
900/// Which `node_modules` of a unit: its root's, or a workspace member's.
901#[derive(Debug, Clone, Copy, PartialEq, Eq)]
902enum Scope {
903    Root,
904    Member,
905}
906
907impl Scope {
908    /// `m` is a member's path relative to the unit, `""` for the root.
909    fn of(m: &str) -> Scope {
910        if m.is_empty() {
911            Scope::Root
912        } else {
913            Scope::Member
914        }
915    }
916}
917
918/// A command run to the end with stdout and stderr apart.
919struct Captured {
920    status: std::process::ExitStatus,
921    stdout: String,
922    stderr: String,
923}
924
925/// Why [`capture_apart`] has no [`Captured`].
926enum CaptureFailure {
927    TimedOut,
928    Spawn(std::io::Error),
929}
930
931impl CaptureFailure {
932    fn describe(&self, what: &str) -> String {
933        match self {
934            CaptureFailure::TimedOut => format!("{what} timed out"),
935            CaptureFailure::Spawn(e) => format!("{what} could not start: {e}"),
936        }
937    }
938}
939
940/// Run `cmd` under the deadline and the host slots, keeping the streams
941/// apart. `Err` when it cannot start or is killed by a clock; a non-zero exit
942/// is the caller's to read.
943fn capture_apart(
944    settings: &crate::config::Settings,
945    cmd: &mut Command,
946) -> Result<Captured, CaptureFailure> {
947    let out = crate::hooks::common::capture_stdout_within(settings, cmd)
948        .map_err(CaptureFailure::Spawn)?;
949    match out.ran {
950        crate::hooks::common::Ran::Status(status) => Ok(Captured {
951            status,
952            stdout: out.stdout,
953            stderr: out.stderr,
954        }),
955        crate::hooks::common::Ran::TimedOut(_) => Err(CaptureFailure::TimedOut),
956    }
957}
958
959/// `text` in an open, already-deleted file, rewound to its start: node reads
960/// it as its stdin. Nothing is written to a pipe, so an early node exit cannot
961/// raise SIGPIPE (greengate restores its default action), and nothing is left
962/// on disk after any kill. The name holds the pid, a counter and the time, so a
963/// file a killed run left behind under the same pid cannot collide; it is
964/// created owner-only, never inside the snapshot, whose tree the stamp covers.
965fn unlinked_file(text: &str) -> std::io::Result<std::fs::File> {
966    use std::io::{Seek, Write};
967    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
968    let nanos = std::time::SystemTime::now()
969        .duration_since(std::time::UNIX_EPOCH)
970        .map(|d| d.as_nanos())
971        .unwrap_or(0);
972    let path = std::env::temp_dir().join(format!(
973        "greengate-npm-{}-{}-{nanos}.json",
974        std::process::id(),
975        COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
976    ));
977    let mut options = std::fs::OpenOptions::new();
978    options.read(true).write(true).create_new(true);
979    #[cfg(unix)]
980    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
981    let mut file = options.open(&path)?;
982    let written = file.write_all(text.as_bytes()).and_then(|()| file.rewind());
983    let removed = std::fs::remove_file(&path);
984    written?;
985    removed?;
986    Ok(file)
987}
988
989/// The `counts=` line of the dry-run helper: exactly one line holding exactly
990/// three numbers. Anything else is `None`.
991fn parse_counts(text: &str) -> Option<[usize; 3]> {
992    let mut lines = text.lines().filter_map(|l| l.strip_prefix("counts="));
993    let line = lines.next()?;
994    if lines.next().is_some() {
995        return None;
996    }
997    let numbers: Vec<usize> = line
998        .split_whitespace()
999        .map(|n| n.parse().ok())
1000        .collect::<Option<_>>()?;
1001    numbers.try_into().ok()
1002}
1003
1004/// Reduce JSON the manager printed to plain lines with `node -e script`, the
1005/// JSON on node's stdin from an already-deleted file: this crate has no JSON
1006/// parser, and the answer is npm's own. node's exit status decides; a missing
1007/// node is a refusal that says so.
1008fn node_reads(
1009    settings: &crate::config::Settings,
1010    u: &Unit,
1011    json: &str,
1012    script: &str,
1013) -> Result<String, String> {
1014    let tool = u.manager.tool();
1015    let file = unlinked_file(json)
1016        .map_err(|e| format!("could not write {tool}'s output for node: {e}"))?;
1017    let mut cmd = Command::new(crate::hooks::common::program("node"));
1018    cmd.arg("-e")
1019        .arg(script)
1020        .current_dir(std::env::temp_dir())
1021        .env_remove("NODE_OPTIONS")
1022        .stdin(Stdio::from(file));
1023    crate::hooks::common::strip_git_env(&mut cmd);
1024    let out = match capture_apart(settings, &mut cmd) {
1025        Ok(out) => out,
1026        Err(CaptureFailure::Spawn(e)) if e.kind() == std::io::ErrorKind::NotFound => {
1027            return Err(format!(
1028                "node not found on PATH (needed to read {tool}'s output); put node on PATH, \
1029                 or git config greengate.snapshotDeps install"
1030            ));
1031        }
1032        Err(CaptureFailure::Spawn(e)) => {
1033            return Err(format!("could not start node to read {tool}'s output: {e}"));
1034        }
1035        Err(CaptureFailure::TimedOut) => {
1036            return Err(format!("node timed out reading {tool}'s output"));
1037        }
1038    };
1039    if !out.status.success() {
1040        let exited = out
1041            .status
1042            .code()
1043            .map_or_else(|| "on a signal".to_string(), |c| c.to_string());
1044        return Err(format!(
1045            "could not read {tool}'s output (node exited {exited}): {}",
1046            last_line(&out.stderr)
1047        ));
1048    }
1049    Ok(out.stdout)
1050}
1051
1052/// `npm query .workspace`: the `location` of each workspace, one per line.
1053const NPM_QUERY_SCRIPT: &str = r#"
1054const text = require('fs').readFileSync(0, 'utf8');
1055const start = text.indexOf('[');
1056if (start < 0) throw new Error('no JSON array in npm query output');
1057const found = JSON.parse(text.slice(start));
1058if (!Array.isArray(found)) throw new Error('npm query did not print an array');
1059for (const workspace of found) console.log(String(workspace.location));
1060"#;
1061
1062/// `npm install --dry-run --json`: its plain-text lines come BEFORE the JSON,
1063/// so parsing starts at the first `{`. Prints `error=<summary>`, or
1064/// `counts=<add> <remove> <change>` and `first=<name@version>`.
1065const NPM_DRY_RUN_SCRIPT: &str = r#"
1066const text = require('fs').readFileSync(0, 'utf8');
1067const start = text.indexOf('{');
1068if (start < 0) throw new Error('no JSON object in npm output');
1069const report = JSON.parse(text.slice(start));
1070if (report.error) {
1071  const why = report.error.summary || report.error.code || 'unknown error';
1072  console.log('error=' + String(why).replace(/\s+/g, ' '));
1073} else {
1074  for (const key of ['add', 'remove', 'change']) {
1075    if (!Array.isArray(report[key])) throw new Error('npm printed no ' + key + ' list');
1076  }
1077  const named = (entry) => {
1078    const pkg = (entry && (entry.to || entry.from || entry)) || {};
1079    return (pkg.name || '?') + '@' + (pkg.version || '?');
1080  };
1081  console.log('counts=' + report.add.length + ' ' + report.remove.length + ' ' + report.change.length);
1082  const first = [...report.add, ...report.remove, ...report.change][0];
1083  if (first) console.log('first=' + named(first));
1084}
1085"#;
1086
1087/// Workspace members of a unit, as its manager lists them, relative to the
1088/// unit dir. Asked in the SNAPSHOT: the committed manifests decide.
1089fn members(
1090    settings: &crate::config::Settings,
1091    u: &Unit,
1092    at: &Path,
1093    voucher: Voucher,
1094) -> Result<Vec<String>, String> {
1095    match voucher {
1096        Voucher::Pnpm => {
1097            if u.standalone {
1098                return Ok(Vec::new());
1099            }
1100            let text = quiet(
1101                settings,
1102                manager_cmd(u, at, &["ls", "-r", "--depth", "-1", "--parseable"]),
1103            )
1104            .map_err(|t| format!("pnpm could not list the workspace: {}", last_line(&t)))?;
1105            let root = normalize(at);
1106            let canon = at.canonicalize().unwrap_or_else(|_| root.clone());
1107            Ok(text
1108                .lines()
1109                .filter_map(|l| {
1110                    let p = PathBuf::from(l.trim());
1111                    let rel = p
1112                        .strip_prefix(&root)
1113                        .or_else(|_| p.strip_prefix(&canon))
1114                        .ok()?;
1115                    let rel = rel.to_string_lossy().replace('\\', "/");
1116                    (!rel.is_empty()).then_some(rel)
1117                })
1118                .collect())
1119        }
1120        Voucher::Npm => {
1121            let what = "npm query .workspace";
1122            let out = capture_apart(
1123                settings,
1124                &mut manager_cmd(
1125                    u,
1126                    at,
1127                    &["query", ".workspace", "--offline", "--no-update-notifier"],
1128                ),
1129            )
1130            .map_err(|e| e.describe(what))?;
1131            if !out.status.success() {
1132                return Err(format!(
1133                    "npm could not list the workspace ({}): {}",
1134                    out.status,
1135                    last_line(&out.stderr)
1136                ));
1137            }
1138            if out.stdout.trim().is_empty() {
1139                return Err(format!(
1140                    "npm could not list the workspace: {what} printed nothing ({})",
1141                    last_line(&out.stderr)
1142                ));
1143            }
1144            let lines = node_reads(settings, u, &out.stdout, NPM_QUERY_SCRIPT)?;
1145            let mut found = Vec::new();
1146            for line in lines.lines().map(|l| l.trim().replace('\\', "/")) {
1147                let outside = Path::new(&line).is_absolute()
1148                    || Path::new(&line)
1149                        .components()
1150                        .any(|c| matches!(c, Component::ParentDir));
1151                if outside {
1152                    return Err(format!("npm listed a workspace outside the unit: {line}"));
1153                }
1154                if !line.is_empty() && line != "." {
1155                    found.push(line);
1156                }
1157            }
1158            Ok(found)
1159        }
1160    }
1161}
1162
1163/// Is `nm` laid out the way pnpm's default (`isolated`) linker lays it out —
1164/// every package a link, `@scope` directories holding only links? pnpm's own
1165/// check does not look at a directory it did not create, and a stray one
1166/// here is importable by the suite; so anything else is not reused.
1167fn pnpm_layout_problem(nm: &Path, is_root: bool) -> Option<String> {
1168    if is_root {
1169        let modules = std::fs::read_to_string(nm.join(".modules.yaml")).unwrap_or_default();
1170        let isolated = modules
1171            .lines()
1172            .any(|l| l.contains("nodeLinker") && l.contains("isolated"));
1173        if !isolated {
1174            return Some("not installed with pnpm's isolated linker".to_string());
1175        }
1176    }
1177    let entries = std::fs::read_dir(nm).ok()?;
1178    for e in entries.flatten() {
1179        let name = e.file_name().to_string_lossy().into_owned();
1180        if name.starts_with('.') {
1181            continue;
1182        }
1183        let kind = e.file_type().ok()?;
1184        if kind.is_symlink() {
1185            continue;
1186        }
1187        if name.starts_with('@') && kind.is_dir() {
1188            for inner in std::fs::read_dir(e.path()).ok()?.flatten() {
1189                if !inner.file_type().map(|k| k.is_symlink()).unwrap_or(false) {
1190                    return Some(format!(
1191                        "{} is not a link pnpm made",
1192                        inner.path().display()
1193                    ));
1194                }
1195            }
1196            continue;
1197        }
1198        return Some(format!("{} is not a link pnpm made", e.path().display()));
1199    }
1200    None
1201}
1202
1203/// Ask npm whether the clone in `snap_dir` is what the lockfile describes: a
1204/// dry-run install that must add, remove and change nothing and leave
1205/// `package-lock.json` byte-identical. Exit 0 alone decides nothing (npm
1206/// exits 0 for a tree it would change), so the JSON does; a non-zero exit,
1207/// empty or unparseable output is a refusal, never "no changes".
1208fn npm_vouch(
1209    settings: &crate::config::Settings,
1210    u: &Unit,
1211    snap_dir: &Path,
1212    members: &[String],
1213) -> Result<(), String> {
1214    // npm trusts `node_modules/.package-lock.json` when it is newer than the
1215    // tree; with it gone npm must read the tree itself.
1216    for member in members {
1217        let hidden = snap_dir
1218            .join(member)
1219            .join("node_modules")
1220            .join(".package-lock.json");
1221        match std::fs::remove_file(&hidden) {
1222            Ok(()) => {}
1223            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1224            Err(e) => return Err(format!("could not remove {}: {e}", hidden.display())),
1225        }
1226    }
1227    let lock_path = snap_dir.join(u.lockfile);
1228    let before = std::fs::read(&lock_path).map_err(|e| format!("{}: {e}", u.lockfile))?;
1229    let what = "npm install --dry-run";
1230    let mut cmd = manager_cmd(
1231        u,
1232        snap_dir,
1233        &[
1234            "install",
1235            "--dry-run",
1236            "--offline",
1237            "--ignore-scripts",
1238            "--json",
1239            "--no-audit",
1240            "--no-fund",
1241            "--no-update-notifier",
1242        ],
1243    );
1244    let captured = capture_apart(settings, &mut cmd);
1245    // A dry-run must not write; if it did, put the committed bytes back
1246    // before anything installs over them, whether or not it finished.
1247    if std::fs::read(&lock_path).ok().as_deref() != Some(before.as_slice()) {
1248        let restored = match std::fs::write(&lock_path, &before) {
1249            Ok(()) => String::new(),
1250            Err(e) => format!(" (and {} could not be restored: {e})", u.lockfile),
1251        };
1252        return Err(format!("{} would change{restored}", u.lockfile));
1253    }
1254    let out = captured.map_err(|e| e.describe(what))?;
1255    npm_verdict(settings, u, &out, what)
1256}
1257
1258/// What npm's dry-run said, as `Ok` for "nothing to do" and otherwise the
1259/// reason, read from the parsed JSON and never from its last line.
1260fn npm_verdict(
1261    settings: &crate::config::Settings,
1262    u: &Unit,
1263    out: &Captured,
1264    what: &str,
1265) -> Result<(), String> {
1266    let read = |json: &str| node_reads(settings, u, json, NPM_DRY_RUN_SCRIPT);
1267    if !out.status.success() {
1268        // npm prints `{"error": {...}}` on stdout for a manifest it cannot
1269        // satisfy; quote its summary when there is one.
1270        if out.stdout.contains('{') {
1271            if let Ok(text) = read(&out.stdout) {
1272                if let Some(summary) = text.lines().find_map(|l| l.strip_prefix("error=")) {
1273                    return Err(format!("npm failed: {summary}"));
1274                }
1275            }
1276        }
1277        let code = out
1278            .status
1279            .code()
1280            .map_or_else(|| out.status.to_string(), |c| c.to_string());
1281        return Err(format!("{what} exited {code}: {}", last_line(&out.stderr)));
1282    }
1283    if out.stdout.trim().is_empty() {
1284        return Err(format!(
1285            "{what} printed nothing on stdout ({})",
1286            last_line(&out.stderr)
1287        ));
1288    }
1289    let text = read(&out.stdout)?;
1290    if let Some(summary) = text.lines().find_map(|l| l.strip_prefix("error=")) {
1291        return Err(format!("npm failed: {summary}"));
1292    }
1293    let Some([add, remove, change]) = parse_counts(&text) else {
1294        return Err(format!("{what} printed no add/remove/change counts"));
1295    };
1296    if add + remove + change > 0 {
1297        let first = text
1298            .lines()
1299            .find_map(|l| l.strip_prefix("first="))
1300            .unwrap_or("?");
1301        return Err(format!(
1302            "npm would add {add}, remove {remove}, change {change}: {first}"
1303        ));
1304    }
1305    Ok(())
1306}
1307
1308/// Try to reuse the working tree's install for one unit. `Ok(())` when the
1309/// clone is in place and its manager vouched for it; `Err(reason)` — with the
1310/// snapshot left exactly as it was — when it cannot be.
1311///
1312/// Each manager is a [`Voucher`]: pnpm's is a layout check and a frozen
1313/// offline install; npm's is a dry-run install, which reads the installed
1314/// tree itself (`npm ls` cannot do that: it fails on peer-range conflicts
1315/// `npm ci` accepts). yarn 1 is never reused: its checks accept a tree with
1316/// a package missing (a deletion leaves no newer file for the timestamp scan
1317/// either), and yarn berry and bun have no voucher.
1318fn reuse(
1319    settings: &crate::config::Settings,
1320    u: &Unit,
1321    source: &Path,
1322    snapshot: &Path,
1323    unit_dirs: &[String],
1324) -> Result<(), String> {
1325    let voucher = Voucher::of(u)?;
1326    let tool = voucher.tool();
1327    let src_dir = source.join(&u.dir);
1328    let snap_dir = snapshot.join(&u.dir);
1329    let lock = u.lockfile;
1330    let src_lock = std::fs::read(src_dir.join(lock))
1331        .map_err(|_| "no lockfile in the working tree".to_string())?;
1332    let snap_lock = std::fs::read(snap_dir.join(lock)).map_err(|e| format!("{lock}: {e}"))?;
1333    if src_lock != snap_lock {
1334        return Err("the working tree's lockfile differs from the commit's".to_string());
1335    }
1336    if !src_dir.join("node_modules").is_dir() {
1337        return Err("nothing installed in the working tree".to_string());
1338    }
1339    let mut set = vec![String::new()];
1340    for m in members(settings, u, &snap_dir, voucher)? {
1341        let repo_rel = join_rel(&u.dir, &m);
1342        // A member with a lockfile of its own is its own unit.
1343        if unit_dirs.contains(&repo_rel) {
1344            continue;
1345        }
1346        if src_dir.join(&m).join("node_modules").is_dir() {
1347            set.push(m);
1348        }
1349    }
1350    // Checked on the SOURCE, before anything is copied: a file changed
1351    // since the manager finished installing is an edit its own check may not
1352    // see, and a clone would carry it into a stamped snapshot.
1353    let record_path = format!("node_modules/{}", voucher.record());
1354    let record = std::fs::metadata(src_dir.join(&record_path))
1355        .and_then(|m| m.modified())
1356        .map_err(|_| format!("no {tool} install record ({record_path})"))?;
1357    for m in &set {
1358        match newer_than(
1359            &src_dir.join(m).join("node_modules"),
1360            record,
1361            voucher.skip_files(Scope::of(m)),
1362        ) {
1363            Ok(None) => {}
1364            Ok(Some(f)) => {
1365                let shown = f.strip_prefix(source).unwrap_or(&f);
1366                return Err(format!(
1367                    "{} changed after the install — an in-place edit {tool} does not check",
1368                    shown.display()
1369                ));
1370            }
1371            Err(e) => return Err(format!("could not inspect the working tree's install: {e}")),
1372        }
1373    }
1374    let mut cloned: Vec<PathBuf> = Vec::new();
1375    // What it could not remove goes into the refusal: an install over a
1376    // clone left behind is the one outcome this function must never hide.
1377    let rollback = |cloned: &[PathBuf]| -> String {
1378        let mut left = Vec::new();
1379        for dir in cloned {
1380            if let Err(err) = std::fs::remove_dir_all(dir) {
1381                if err.kind() != std::io::ErrorKind::NotFound {
1382                    left.push(format!("{}: {err}", dir.display()));
1383                }
1384            }
1385        }
1386        if left.is_empty() {
1387            String::new()
1388        } else {
1389            format!(
1390                "; could not remove the clone, so the install may run over it (remove it by hand): {}",
1391                left.join(", ")
1392            )
1393        }
1394    };
1395    let sources = [
1396        normalize(source),
1397        source.canonicalize().unwrap_or_else(|_| normalize(source)),
1398    ];
1399    let roots = [
1400        normalize(snapshot),
1401        snapshot
1402            .canonicalize()
1403            .unwrap_or_else(|_| normalize(snapshot)),
1404    ];
1405    for m in &set {
1406        let from = src_dir.join(m).join("node_modules");
1407        let to = snap_dir.join(m).join("node_modules");
1408        if std::fs::symlink_metadata(&to).is_ok() {
1409            let left = rollback(&cloned);
1410            return Err(format!(
1411                "{} already exists in the snapshot{left}",
1412                to.display()
1413            ));
1414        }
1415        if let Err(e) = clone_dir(&from, &to) {
1416            let left = rollback(&cloned);
1417            return Err(format!("{e}{left}"));
1418        }
1419        cloned.push(to.clone());
1420        let problem = match link_into(&to, &sources) {
1421            Ok(Some(link)) => Some(format!(
1422                "{} links back into the working tree",
1423                link.display()
1424            )),
1425            Ok(None) => match voucher {
1426                Voucher::Pnpm => pnpm_layout_problem(&to, m.is_empty()),
1427                Voucher::Npm => match link_outside(&to, &roots) {
1428                    Ok(Some(link)) => {
1429                        Some(format!("{} links outside the snapshot", link.display()))
1430                    }
1431                    Ok(None) => None,
1432                    Err(e) => Some(format!("could not inspect the clone: {e}")),
1433                },
1434            },
1435            Err(e) => Some(format!("could not inspect the clone: {e}")),
1436        };
1437        if let Some(why) = problem {
1438            let left = rollback(&cloned);
1439            return Err(format!("{why}{left}"));
1440        }
1441    }
1442    let vouched = match voucher {
1443        Voucher::Pnpm => pnpm_vouch(settings, u, &snap_dir),
1444        Voucher::Npm => {
1445            println!(
1446                "snapshot: checking node_modules in {} with npm",
1447                unit_label(u)
1448            );
1449            npm_vouch(settings, u, &snap_dir, &set)
1450        }
1451    };
1452    if let Err(why) = vouched {
1453        let left = rollback(&cloned);
1454        return Err(format!("{why}{left}"));
1455    }
1456    Ok(())
1457}
1458
1459/// pnpm records the absolute paths of the tree it installed; the clone must
1460/// not carry the source's. Then a frozen OFFLINE install is both the check
1461/// and the repair: it fails on a manifest the lockfile does not satisfy,
1462/// relinks drift from the store, and says "Already up to date" for a
1463/// faithful clone.
1464fn pnpm_vouch(settings: &crate::config::Settings, u: &Unit, snap_dir: &Path) -> Result<(), String> {
1465    if let Ok(rd) = std::fs::read_dir(snap_dir.join("node_modules")) {
1466        for e in rd.flatten() {
1467            if e.file_name()
1468                .to_string_lossy()
1469                .starts_with(".pnpm-workspace-state")
1470            {
1471                // best effort: pnpm's frozen install below rewrites or rejects the state
1472                let _ = std::fs::remove_file(e.path());
1473            }
1474        }
1475    }
1476    quiet(
1477        settings,
1478        manager_cmd(u, snap_dir, &["install", "--frozen-lockfile", "--offline"]),
1479    )
1480    .map(|_| ())
1481    .map_err(|text| format!("pnpm did not accept the clone ({})", last_line(&text)))
1482}
1483
1484/// The files `tip` changes relative to where it forked from its upstream —
1485/// what the push is about. `None` when git cannot say (no upstream, a tip
1486/// it does not know): the caller then prepares everything.
1487pub fn changed_since_upstream(source: &Path, tip: &str) -> Option<Vec<String>> {
1488    let git = |args: &[&str]| -> Option<Vec<u8>> {
1489        let mut cmd = Command::new("git");
1490        cmd.arg("-C")
1491            .arg(source)
1492            .args(args)
1493            .stdin(Stdio::null())
1494            .stderr(Stdio::null());
1495        crate::hooks::common::strip_git_env(&mut cmd);
1496        let out = cmd.output().ok()?;
1497        out.status.success().then_some(out.stdout)
1498    };
1499    let base = git(&["merge-base", tip, "@{upstream}"])?;
1500    let base = String::from_utf8_lossy(&base).trim().to_string();
1501    if base.is_empty() {
1502        return None;
1503    }
1504    let raw = git(&["diff", "--name-only", "-z", &base, tip])?;
1505    Some(crate::git::split_nul_paths(&raw))
1506}
1507
1508/// Which units a snapshot needs: the root one, and every unit that is the
1509/// NEAREST enclosing unit of a changed file. A unit the push does not touch
1510/// cannot hold a failure the push introduced — and nothing the gates run for
1511/// this push reads it — so installing it is pure cost (website-builder: seven
1512/// spikes, an install each, on every snapshot). `changed` is `None` when the
1513/// range is unknown, and then every unit is kept.
1514///
1515/// Returns `(kept, skipped)`.
1516pub fn select_units(units: Vec<Unit>, changed: Option<&[String]>) -> (Vec<Unit>, Vec<Unit>) {
1517    let Some(changed) = changed else {
1518        return (units, Vec::new());
1519    };
1520    let nearest = |f: &str| -> Option<&str> {
1521        units
1522            .iter()
1523            .map(|u| u.dir.as_str())
1524            .filter(|d| d.is_empty() || f.starts_with(&format!("{d}/")))
1525            .max_by_key(|d| d.len())
1526    };
1527    let touched: Vec<&str> = changed.iter().filter_map(|f| nearest(f)).collect();
1528    let (kept, skipped): (Vec<Unit>, Vec<Unit>) = units
1529        .clone()
1530        .into_iter()
1531        .partition(|u| u.dir.is_empty() || touched.contains(&u.dir.as_str()));
1532    (kept, skipped)
1533}
1534
1535/// Prepare the dependencies of every unit the push needs in `snapshot`.
1536pub fn deps(
1537    settings: &crate::config::Settings,
1538    mode: DepsMode,
1539    source: &Path,
1540    snapshot: &Path,
1541    files: &[String],
1542    changed: Option<&[String]>,
1543) -> Result<(), String> {
1544    if mode == DepsMode::Off {
1545        return Ok(());
1546    }
1547    let all = units(files, snapshot)?;
1548    let unit_dirs: Vec<String> = all.iter().map(|u| u.dir.clone()).collect();
1549    let (units, skipped) = select_units(all, changed);
1550    if !skipped.is_empty() {
1551        let names: Vec<String> = skipped.iter().map(unit_label).collect();
1552        println!(
1553            "snapshot: not preparing {} — the push changes nothing there",
1554            names.join(", ")
1555        );
1556    }
1557    for u in &units {
1558        let at = snapshot.join(&u.dir);
1559        let label = unit_label(u);
1560        if u.manager == Manager::Bun {
1561            // Refused before anything is printed or cloned: the message IS
1562            // the preparation's result for this unit.
1563            return Err(bun_refusal(u));
1564        }
1565        if mode == DepsMode::Reuse {
1566            // No clone tool on Windows: `clone_dir` says so and this falls
1567            // through to the install, like any other refusal.
1568            match reuse(settings, u, source, snapshot, &unit_dirs) {
1569                Ok(()) => {
1570                    println!(
1571                        "snapshot: node_modules in {label} reused from the working tree — {} \
1572                         accepted it against the lockfile \
1573                         (copy-on-write clone, shares disk with the working tree)",
1574                        u.manager.tool()
1575                    );
1576                    continue;
1577                }
1578                Err(why) => println!(
1579                    "snapshot: {} in {label} — not reusing the working tree's install: {why}",
1580                    highlight(&format!("{} {}", u.manager.tool(), install_verb(u)))
1581                ),
1582            }
1583        } else {
1584            println!(
1585                "snapshot: {} in {label}",
1586                highlight(&format!("{} {}", u.manager.tool(), install_verb(u)))
1587            );
1588        }
1589        install(settings, u, &at)?;
1590    }
1591    Ok(())
1592}
1593
1594fn install_verb(u: &Unit) -> &'static str {
1595    match u.manager {
1596        Manager::Npm => "ci",
1597        Manager::Pnpm => "install --frozen-lockfile",
1598        Manager::Yarn if u.berry => "install --immutable",
1599        Manager::Yarn => "install --frozen-lockfile",
1600        Manager::Bun => "install",
1601    }
1602}
1603
1604/// Carry → dependencies → nothing else; `snapshotPrepare` runs after this,
1605/// in `PushedTree::prepare`. Dependencies are skipped when a
1606/// `snapshotPrepare` command exists: that command owns them.
1607pub fn run(
1608    settings: &crate::config::Settings,
1609    source: &Path,
1610    snapshot: &Path,
1611    tip: &str,
1612    command_owns_deps: bool,
1613) -> Result<(), String> {
1614    let entries = carry_list(settings);
1615    let mode = if command_owns_deps {
1616        DepsMode::Off
1617    } else {
1618        deps_mode(settings)
1619    };
1620    if entries.is_empty() && mode == DepsMode::Off {
1621        return Ok(());
1622    }
1623    let files = snapshot_files(snapshot)?;
1624    if !entries.is_empty() {
1625        carry(&entries, source, snapshot, &files)?;
1626    }
1627    let changed = if mode == DepsMode::Off {
1628        None
1629    } else {
1630        changed_since_upstream(source, tip)
1631    };
1632    deps(settings, mode, source, snapshot, &files, changed.as_deref()).map_err(|e| {
1633        println!("{} {e}", warning_sign());
1634        e
1635    })
1636}
1637
1638#[cfg(test)]
1639mod tests {
1640    use super::*;
1641
1642    fn s(v: &[&str]) -> Vec<String> {
1643        v.iter().map(|x| x.to_string()).collect()
1644    }
1645
1646    #[test]
1647    fn clone_dir_refuses_an_existing_destination() {
1648        let scratch = std::env::temp_dir().join(format!("clone-exist-{}", std::process::id()));
1649        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1650        std::fs::create_dir_all(scratch.join("src")).unwrap();
1651        std::fs::create_dir_all(scratch.join("dst")).unwrap();
1652        std::fs::write(scratch.join("dst/keep"), "mine").unwrap();
1653        let err = clone_dir(&scratch.join("src"), &scratch.join("dst")).unwrap_err();
1654        assert!(err.starts_with("no copy-on-write clone of "), "{err}");
1655        assert_eq!(
1656            std::fs::read_to_string(scratch.join("dst/keep")).unwrap(),
1657            "mine"
1658        );
1659        assert_eq!(std::fs::read_dir(scratch.join("dst")).unwrap().count(), 1);
1660        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1661    }
1662
1663    #[cfg(target_os = "macos")]
1664    #[test]
1665    fn clone_dir_keeps_odd_names_and_relative_symlinks() {
1666        use std::ffi::OsStr;
1667        use std::os::unix::ffi::OsStrExt;
1668        // APFS refuses a name that is not valid UTF-8 (EILSEQ, 92), so there
1669        // the fixture holds a non-ASCII UTF-8 name instead; the line printed
1670        // says which of the two this run proved.
1671        const EILSEQ: i32 = 92;
1672        let scratch = std::env::temp_dir().join(format!("clone-tree-{}", std::process::id()));
1673        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1674        std::fs::create_dir_all(scratch.join("src/sub")).unwrap();
1675        let mut odd = OsStr::from_bytes(b"caf\xe9");
1676        match std::fs::write(scratch.join("src/sub").join(odd), "odd") {
1677            Ok(()) => eprintln!("clone test: a non-UTF-8 file name"),
1678            Err(e) if e.raw_os_error() == Some(EILSEQ) => {
1679                eprintln!("clone test: this volume refuses non-UTF-8 names; non-ASCII UTF-8 used");
1680                odd = OsStr::new("caf\u{e9}");
1681                std::fs::write(scratch.join("src/sub").join(odd), "odd").unwrap();
1682            }
1683            Err(e) => panic!("fixture could not be written: {e}"),
1684        }
1685        std::os::unix::fs::symlink("sub", scratch.join("src/link")).unwrap();
1686        clone_dir(&scratch.join("src"), &scratch.join("dst")).unwrap();
1687        assert_eq!(
1688            std::fs::read(scratch.join("dst/sub").join(odd)).unwrap(),
1689            b"odd"
1690        );
1691        assert_eq!(
1692            std::fs::read_link(scratch.join("dst/link")).unwrap(),
1693            Path::new("sub")
1694        );
1695        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1696    }
1697
1698    /// tmpfs cannot clone: the refusal names the clone in ONE line, leaves no
1699    /// destination behind and never falls back to a copy. CI's other Linux
1700    /// tests run on an XFS image with reflinks (`.github/workflows/ci.yaml`),
1701    /// so this is the one that proves the refusal there; where `CI` is set a
1702    /// runner without tmpfs fails it instead of passing without a check.
1703    #[cfg(target_os = "linux")]
1704    #[test]
1705    fn clone_dir_refuses_a_filesystem_without_reflinks() {
1706        let shm = Path::new("/dev/shm");
1707        if !shm.is_dir() {
1708            assert!(
1709                std::env::var_os("CI").is_none(),
1710                "no /dev/shm on a CI runner: the refusal has no tmpfs to be proven on"
1711            );
1712            eprintln!("no /dev/shm here: the refusal test has no tmpfs to run on");
1713            return;
1714        }
1715        let scratch = shm.join(format!("clone-tmpfs-{}", std::process::id()));
1716        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1717        std::fs::create_dir_all(scratch.join("src")).unwrap();
1718        for i in 0..20 {
1719            std::fs::write(scratch.join(format!("src/f{i}")), "data").unwrap();
1720        }
1721        let err = clone_dir(&scratch.join("src"), &scratch.join("dst")).unwrap_err();
1722        assert!(err.starts_with("no copy-on-write clone of "), "{err}");
1723        assert!(
1724            !err.contains('\n'),
1725            "one line, not cp's whole stderr: {err}"
1726        );
1727        assert!(
1728            !scratch.join("dst").exists(),
1729            "a refused clone left a destination"
1730        );
1731        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1732    }
1733
1734    #[test]
1735    fn lexical_refusals() {
1736        for bad in [
1737            "",
1738            "/etc/hosts",
1739            "\\x",
1740            "C:/x",
1741            "a//b",
1742            ".",
1743            "..",
1744            "a/../b",
1745            ".git/config",
1746            "x/.GIT/y",
1747        ] {
1748            assert!(lexical_problem(bad).is_some(), "{bad:?} must be refused");
1749        }
1750        for good in [".env", "config/local.json", ".npmrc", "a.b/c"] {
1751            assert!(lexical_problem(good).is_none(), "{good:?} must pass");
1752        }
1753    }
1754
1755    #[test]
1756    fn a_tracked_path_inside_above_or_equal_collides() {
1757        let files = s(&["src/a.ts", "vendor", "README.md"]);
1758        assert!(tracked_collision("src", &files).is_some());
1759        assert!(tracked_collision("src/a.ts", &files).is_some());
1760        assert!(tracked_collision("vendor/x", &files).is_some());
1761        assert!(tracked_collision(".env", &files).is_none());
1762        assert!(tracked_collision("sr", &files).is_none());
1763    }
1764
1765    #[test]
1766    fn lockfile_dirs_come_from_the_list_given() {
1767        let files = s(&[
1768            "package-lock.json",
1769            "web/package-lock.json",
1770            "web/x/pnpm-lock.yaml",
1771            "notpackage-lock.json",
1772        ]);
1773        assert_eq!(
1774            lockfile_dirs_in(&files, "package-lock.json"),
1775            s(&["", "web"])
1776        );
1777        assert_eq!(lockfile_dirs_in(&files, "pnpm-lock.yaml"), s(&["web/x"]));
1778    }
1779
1780    #[test]
1781    fn package_manager_field_is_read_narrowly() {
1782        assert_eq!(
1783            declared_manager(r#"{"packageManager": "pnpm@10.1.0"}"#),
1784            Some(Manager::Pnpm)
1785        );
1786        assert_eq!(
1787            declared_manager(r#"{"packageManager":"npm@11"}"#),
1788            Some(Manager::Npm)
1789        );
1790        assert_eq!(
1791            declared_manager(r#"{"packageManager":"yarn@4"}"#),
1792            Some(Manager::Yarn)
1793        );
1794        assert_eq!(
1795            declared_manager(r#"{"packageManager":"bun@1.2.0"}"#),
1796            Some(Manager::Bun)
1797        );
1798        assert_eq!(
1799            declared_manager(r#"{"packageManager":"yarnpkg@1"}"#),
1800            None,
1801            "a name, not a prefix"
1802        );
1803        assert_eq!(declared_manager(r#"{"name":"x"}"#), None);
1804        assert_eq!(
1805            declared_manager(r#"{"packageManager":"npm@1","x":{"packageManager":"pnpm@1"}}"#),
1806            None,
1807            "two answers is no answer"
1808        );
1809    }
1810
1811    fn unit(dir: &str) -> Unit {
1812        Unit {
1813            dir: dir.to_string(),
1814            manager: Manager::Pnpm,
1815            lockfile: "pnpm-lock.yaml",
1816            standalone: !dir.is_empty(),
1817            berry: false,
1818        }
1819    }
1820
1821    #[test]
1822    fn a_berry_lockfile_is_told_by_its_metadata_block() {
1823        assert!(is_berry_lock(
1824            "# This file is generated by running \"yarn install\" inside your project.\n\n__metadata:\n  version: 8\n"
1825        ));
1826        assert!(!is_berry_lock(
1827            "# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n# yarn lockfile v1\n\n"
1828        ));
1829        assert!(!is_berry_lock(""));
1830    }
1831
1832    #[test]
1833    fn every_manager_lockfile_is_a_unit_and_a_mixed_directory_needs_the_field() {
1834        let d = std::env::temp_dir().join(format!("units-{}", std::process::id()));
1835        let _ = std::fs::remove_dir_all(&d);
1836        std::fs::create_dir_all(d.join("berry")).unwrap();
1837        std::fs::write(d.join("yarn.lock"), "# yarn lockfile v1\n").unwrap();
1838        std::fs::write(d.join("berry/yarn.lock"), "__metadata:\n  version: 8\n").unwrap();
1839        let files = s(&[
1840            "yarn.lock",
1841            "berry/yarn.lock",
1842            "old/bun.lockb",
1843            "new/bun.lock",
1844            "mixed/package-lock.json",
1845            "mixed/yarn.lock",
1846        ]);
1847        let err = units(&files, &d).unwrap_err();
1848        assert!(
1849            err.contains("both package-lock.json and yarn.lock in mixed"),
1850            "{err}"
1851        );
1852        std::fs::create_dir_all(d.join("mixed")).unwrap();
1853        std::fs::write(
1854            d.join("mixed/package.json"),
1855            r#"{"packageManager":"yarn@1.22.22"}"#,
1856        )
1857        .unwrap();
1858        let got = units(&files, &d).unwrap();
1859        let brief: Vec<(&str, Manager, &str, bool)> = got
1860            .iter()
1861            .map(|u| (u.dir.as_str(), u.manager, u.lockfile, u.berry))
1862            .collect();
1863        assert_eq!(
1864            brief,
1865            vec![
1866                ("", Manager::Yarn, "yarn.lock", false),
1867                ("berry", Manager::Yarn, "yarn.lock", true),
1868                ("mixed", Manager::Yarn, "yarn.lock", false),
1869                ("new", Manager::Bun, "bun.lock", false),
1870                ("old", Manager::Bun, "bun.lockb", false),
1871            ]
1872        );
1873        std::fs::write(
1874            d.join("mixed/package.json"),
1875            r#"{"packageManager":"pnpm@10"}"#,
1876        )
1877        .unwrap();
1878        let err = units(&files, &d).unwrap_err();
1879        assert!(
1880            err.contains("no `packageManager` to choose"),
1881            "a field naming an absent lockfile chooses nothing: {err}"
1882        );
1883        let _ = std::fs::remove_dir_all(&d);
1884    }
1885
1886    #[test]
1887    fn only_the_root_and_the_touched_units_are_kept() {
1888        let all = vec![unit(""), unit("spikes/a"), unit("spikes/b"), unit("tools")];
1889        let changed = s(&["src/x.ts", "spikes/b/index.ts", "spikes/bb/y.ts"]);
1890        let (kept, skipped) = select_units(all.clone(), Some(&changed));
1891        let dirs = |v: &[Unit]| v.iter().map(|u| u.dir.clone()).collect::<Vec<_>>();
1892        assert_eq!(
1893            dirs(&kept),
1894            s(&["", "spikes/b"]),
1895            "spikes/bb is not spikes/b"
1896        );
1897        assert_eq!(dirs(&skipped), s(&["spikes/a", "tools"]));
1898        let (kept, skipped) = select_units(all.clone(), None);
1899        assert_eq!(kept.len(), 4, "an unknown range keeps everything");
1900        assert!(skipped.is_empty());
1901    }
1902
1903    #[test]
1904    fn a_nested_unit_claims_its_files_from_the_outer_one() {
1905        let all = vec![unit("web"), unit("web/nested")];
1906        let changed = s(&["web/nested/a.ts"]);
1907        let (kept, _) = select_units(all, Some(&changed));
1908        assert_eq!(kept.len(), 1);
1909        assert_eq!(kept[0].dir, "web/nested");
1910    }
1911
1912    const PNPM_SKIPS: &[&str] = &[".modules.yaml", ".pnpm-workspace-state*", ".pnpm/lock.yaml"];
1913
1914    #[test]
1915    fn a_file_newer_than_the_install_record_is_found() {
1916        let d = std::env::temp_dir().join(format!("newer-{}", std::process::id()));
1917        let _ = std::fs::remove_dir_all(&d);
1918        let pkg = d.join(".pnpm/a@1/node_modules/a");
1919        std::fs::create_dir_all(&pkg).unwrap();
1920        std::fs::create_dir_all(d.join(".bin")).unwrap();
1921        std::fs::create_dir_all(d.join(".cache")).unwrap();
1922        std::fs::write(pkg.join("index.js"), "old").unwrap();
1923        let record = std::time::SystemTime::now();
1924        std::thread::sleep(std::time::Duration::from_millis(20));
1925        for skipped in [".bin/tsc", ".cache/x", ".pnpm/lock.yaml", ".modules.yaml"] {
1926            std::fs::write(d.join(skipped), "new").unwrap();
1927        }
1928        assert_eq!(
1929            newer_than(&d, record, PNPM_SKIPS).unwrap(),
1930            None,
1931            "the install's own writes"
1932        );
1933        std::fs::write(pkg.join("index.js"), "edited").unwrap();
1934        assert_eq!(
1935            newer_than(&d, record, PNPM_SKIPS).unwrap(),
1936            Some(pkg.join("index.js"))
1937        );
1938        let _ = std::fs::remove_dir_all(&d);
1939    }
1940
1941    #[cfg(unix)]
1942    #[test]
1943    fn a_link_outside_the_snapshot_is_refused_and_a_workspace_link_is_not() {
1944        let scratch = std::env::temp_dir().join(format!("outside-{}", std::process::id()));
1945        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1946        let snapshot = scratch.join("snap");
1947        let nm = snapshot.join("node_modules");
1948        std::fs::create_dir_all(snapshot.join("packages/a")).unwrap();
1949        std::fs::create_dir_all(nm.join(".bin")).unwrap();
1950        std::fs::create_dir_all(nm.join("typescript/bin")).unwrap();
1951        let roots = [normalize(&snapshot)];
1952        std::os::unix::fs::symlink("../packages/a", nm.join("a")).unwrap();
1953        std::os::unix::fs::symlink("../typescript/bin/tsc", nm.join(".bin/tsc")).unwrap();
1954        assert_eq!(
1955            link_outside(&nm, &roots).unwrap(),
1956            None,
1957            "relative links that stay inside the snapshot"
1958        );
1959        std::os::unix::fs::symlink("/usr/bin/env", nm.join(".bin/evil")).unwrap();
1960        assert_eq!(
1961            link_outside(&nm, &roots).unwrap(),
1962            Some(nm.join(".bin/evil")),
1963            "an absolute link out, .bin included"
1964        );
1965        std::fs::remove_file(nm.join(".bin/evil")).unwrap();
1966        std::os::unix::fs::symlink("../../outside", nm.join("up")).unwrap();
1967        assert_eq!(link_outside(&nm, &roots).unwrap(), Some(nm.join("up")));
1968        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1969    }
1970
1971    #[test]
1972    fn npms_hidden_lockfile_is_skipped_in_the_root_node_modules_only() {
1973        let scratch = std::env::temp_dir().join(format!("hidden-{}", std::process::id()));
1974        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1975        let nested = scratch.join("a/node_modules");
1976        std::fs::create_dir_all(&nested).unwrap();
1977        let record = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
1978        std::fs::write(scratch.join(".package-lock.json"), "new").unwrap();
1979        let skips = Voucher::Npm.skip_files(Scope::Root);
1980        assert_eq!(newer_than(&scratch, record, skips).unwrap(), None);
1981        std::fs::write(nested.join(".package-lock.json"), "new").unwrap();
1982        assert_eq!(
1983            newer_than(&scratch, record, skips).unwrap(),
1984            Some(nested.join(".package-lock.json"))
1985        );
1986        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1987    }
1988
1989    #[test]
1990    fn counts_are_one_line_of_three_numbers() {
1991        assert_eq!(parse_counts("counts=0 1 2\nfirst=a@1"), Some([0, 1, 2]));
1992        assert_eq!(parse_counts(""), None);
1993        assert_eq!(parse_counts("counts=0 1"), None);
1994        assert_eq!(parse_counts("counts=0 1 2 3"), None);
1995        assert_eq!(parse_counts("counts=0 x 2"), None);
1996        assert_eq!(parse_counts("counts=0 0 0\ncounts=0 0 0"), None);
1997    }
1998
1999    #[test]
2000    fn normalize_folds_dots_lexically() {
2001        assert_eq!(
2002            normalize(Path::new("/a/b/../c/./d")),
2003            PathBuf::from("/a/c/d")
2004        );
2005    }
2006}