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 only; see `reuse` for why
23//! npm and yarn are not reusable) clones the working tree's `node_modules`
24//! and keeps the clone
25//! only when it has pnpm's isolated layout and a frozen offline install
26//! accepts it against the snapshot's manifests and lockfile — which catches
27//! a missing or wrong-version package, a stray directory, and a manifest the
28//! lockfile does not satisfy, and does NOT catch a package whose files were
29//! edited in place without a version change. That limit is why reuse is
30//! opt-in.
31//!
32//! Every question about a manifest goes to the package manager, through exit
33//! codes and parseable output: this crate is dependency-free and has no JSON
34//! or YAML parser, and a hand-rolled one reading `workspaces` would be a
35//! second, divergent answer to a question npm already answers.
36
37use crate::names::BIN;
38use std::path::{Component, Path, PathBuf};
39use std::process::{Command, Stdio};
40
41use crate::ui::{highlight, warning_sign};
42
43const CARRY: &str = "greengate.snapshotCarry";
44const DEPS: &str = "greengate.snapshotDeps";
45
46/// `greengate.snapshotDeps`.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum DepsMode {
49    /// `npm ci` / `pnpm install --frozen-lockfile` / `yarn install
50    /// --frozen-lockfile` (`--immutable` for berry) in the snapshot.
51    Install,
52    /// Clone the working tree's install, keep it only if the manager accepts it.
53    Reuse,
54    /// Prepare nothing.
55    Off,
56}
57
58pub fn deps_mode(settings: &crate::config::Settings) -> DepsMode {
59    match crate::config::enumerated_or(settings, DEPS, &["install", "reuse", "off"], "install") {
60        "reuse" => DepsMode::Reuse,
61        "off" => DepsMode::Off,
62        _ => DepsMode::Install,
63    }
64}
65
66/// `greengate.snapshotCarry`, split on whitespace and commas.
67pub fn carry_list(settings: &crate::config::Settings) -> Vec<String> {
68    crate::config::string_value(settings, CARRY)
69        .map(|v| {
70            v.split(|c: char| c.is_whitespace() || c == ',')
71                .filter(|s| !s.is_empty())
72                .map(str::to_string)
73                .collect()
74        })
75        .unwrap_or_default()
76}
77
78/// The snapshot's own tracked files, `-z`, with git's environment stripped:
79/// a hook's `GIT_DIR`/`GIT_INDEX_FILE` would otherwise answer for the
80/// developer's repository, and the pushed tip — not HEAD, not the index the
81/// developer is staging into — decides what the snapshot holds.
82pub fn snapshot_files(snapshot: &Path) -> Result<Vec<String>, String> {
83    let mut cmd = Command::new("git");
84    cmd.arg("-C")
85        .arg(snapshot)
86        .args(["ls-files", "-z"])
87        .stdin(Stdio::null())
88        .stderr(Stdio::null());
89    crate::hooks::common::strip_git_env(&mut cmd);
90    let out = cmd
91        .output()
92        .map_err(|e| format!("could not list the snapshot's files: {e}"))?;
93    if !out.status.success() {
94        return Err("could not list the snapshot's files".to_string());
95    }
96    Ok(crate::git::split_nul_paths(&out.stdout))
97}
98
99// ---------------------------------------------------------------------------
100// carry
101// ---------------------------------------------------------------------------
102
103/// One validated carry entry.
104struct Carried {
105    entry: String,
106    src: PathBuf,
107    dst: PathBuf,
108}
109
110/// Why one carry entry is refused, or `None` when it is lexically a
111/// repo-relative path with nothing to climb out through.
112fn lexical_problem(entry: &str) -> Option<&'static str> {
113    if entry.is_empty() {
114        return Some("empty");
115    }
116    let bytes = entry.as_bytes();
117    if entry.starts_with('/') || entry.starts_with('\\') || (bytes.len() >= 2 && bytes[1] == b':') {
118        return Some("not a repo-relative path");
119    }
120    for part in entry.split(['/', '\\']) {
121        if part.is_empty() {
122            return Some("has an empty path component");
123        }
124        if part == "." || part == ".." {
125            return Some("has a `.` or `..` component");
126        }
127        if part.eq_ignore_ascii_case(".git") {
128            return Some("is inside .git");
129        }
130    }
131    None
132}
133
134/// Is `entry` — or anything inside it, or any directory above it — tracked in
135/// the snapshot? Carrying it would put the developer's copy over committed
136/// content, and the stamp would vouch for a tree nobody committed.
137fn tracked_collision(entry: &str, files: &[String]) -> Option<String> {
138    let inside = format!("{entry}/");
139    files
140        .iter()
141        .find(|f| {
142            f.as_str() == entry || f.starts_with(&inside) || entry.starts_with(&format!("{f}/"))
143        })
144        .cloned()
145}
146
147fn is_symlink(p: &Path) -> bool {
148    std::fs::symlink_metadata(p)
149        .map(|m| m.file_type().is_symlink())
150        .unwrap_or(false)
151}
152
153/// A symlinked directory between `root` and `rel`'s last component — which
154/// would take a read, or a write, somewhere outside the tree it names.
155fn symlinked_ancestor(root: &Path, rel: &Path) -> Option<PathBuf> {
156    let mut at = root.to_path_buf();
157    let parts: Vec<_> = rel.components().collect();
158    for part in parts.iter().take(parts.len().saturating_sub(1)) {
159        at.push(part.as_os_str());
160        if is_symlink(&at) {
161            return Some(at);
162        }
163    }
164    None
165}
166
167/// A symlink anywhere inside `dir`, not followed.
168fn symlink_inside(dir: &Path) -> std::io::Result<Option<PathBuf>> {
169    for entry in std::fs::read_dir(dir)? {
170        let entry = entry?;
171        let kind = entry.file_type()?;
172        if kind.is_symlink() {
173            return Ok(Some(entry.path()));
174        }
175        if kind.is_dir() {
176            if let Some(found) = symlink_inside(&entry.path())? {
177                return Ok(Some(found));
178            }
179        }
180    }
181    Ok(None)
182}
183
184fn copy_tree(src: &Path, dst: &Path) -> std::io::Result<()> {
185    let meta = std::fs::symlink_metadata(src)?;
186    if meta.is_dir() {
187        std::fs::create_dir(dst)?;
188        for entry in std::fs::read_dir(src)? {
189            let entry = entry?;
190            copy_tree(&entry.path(), &dst.join(entry.file_name()))?;
191        }
192        Ok(())
193    } else {
194        std::fs::copy(src, dst).map(|_| ())
195    }
196}
197
198/// Copy the untracked files `greengate.snapshotCarry` names from `source` into
199/// `snapshot`.
200///
201/// Every entry is validated before anything is copied, and every refusal is
202/// reported in ONE message — `config::complain` says a key once, which would
203/// hide all but the first bad entry. Any refusal fails preparation: a carry
204/// the author got wrong must be loud, never a silently thinner snapshot that
205/// still earns a stamp. An entry that is simply absent is skipped (a `.env`
206/// exists on a laptop and not in CI); one that is present and cannot be
207/// copied fails.
208pub fn carry(
209    entries: &[String],
210    source: &Path,
211    snapshot: &Path,
212    files: &[String],
213) -> Result<(), String> {
214    let mut refused: Vec<String> = Vec::new();
215    let mut missing: Vec<&str> = Vec::new();
216    let mut plan: Vec<Carried> = Vec::new();
217    for entry in entries {
218        let norm = entry.replace('\\', "/");
219        let norm = norm.trim_end_matches('/').to_string();
220        if let Some(why) = lexical_problem(&norm) {
221            refused.push(format!("{entry}: {why}"));
222            continue;
223        }
224        if let Some(f) = tracked_collision(&norm, files) {
225            refused.push(format!(
226                "{entry}: tracked content ({f}) — only untracked files can be carried"
227            ));
228            continue;
229        }
230        let rel = PathBuf::from(&norm);
231        let src = source.join(&rel);
232        let dst = snapshot.join(&rel);
233        if let Some(link) = symlinked_ancestor(source, &rel) {
234            refused.push(format!(
235                "{entry}: {} is a symlink in the working tree",
236                link.display()
237            ));
238            continue;
239        }
240        if let Some(link) = symlinked_ancestor(snapshot, &rel) {
241            refused.push(format!(
242                "{entry}: {} is a symlink in the snapshot",
243                link.display()
244            ));
245            continue;
246        }
247        let meta = match std::fs::symlink_metadata(&src) {
248            Ok(m) => m,
249            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
250                missing.push(entry);
251                continue;
252            }
253            Err(e) => {
254                refused.push(format!("{entry}: cannot be read: {e}"));
255                continue;
256            }
257        };
258        if meta.file_type().is_symlink() {
259            refused.push(format!("{entry}: is a symlink"));
260            continue;
261        }
262        if meta.is_dir() {
263            match symlink_inside(&src) {
264                Ok(Some(link)) => {
265                    refused.push(format!("{entry}: holds a symlink ({})", link.display()));
266                    continue;
267                }
268                Ok(None) => {}
269                Err(e) => {
270                    refused.push(format!("{entry}: cannot be read: {e}"));
271                    continue;
272                }
273            }
274        }
275        if std::fs::symlink_metadata(&dst).is_ok() {
276            refused.push(format!("{entry}: already exists in the snapshot"));
277            continue;
278        }
279        plan.push(Carried {
280            entry: entry.clone(),
281            src,
282            dst,
283        });
284    }
285    if !refused.is_empty() {
286        return Err(format!(
287            "{CARRY} refused {}: {}",
288            if refused.len() == 1 {
289                "an entry".to_string()
290            } else {
291                format!("{} entries", refused.len())
292            },
293            refused.join("; ")
294        ));
295    }
296    if !missing.is_empty() {
297        println!(
298            "snapshot: not carrying {} — not in the working tree",
299            missing.join(", ")
300        );
301    }
302    for c in &plan {
303        if let Some(parent) = c.dst.parent() {
304            std::fs::create_dir_all(parent).map_err(|e| format!("{CARRY}: {}: {e}", c.entry))?;
305        }
306        copy_tree(&c.src, &c.dst)
307            .map_err(|e| format!("{CARRY}: {} could not be copied: {e}", c.entry))?;
308    }
309    if !plan.is_empty() {
310        let names: Vec<&str> = plan.iter().map(|c| c.entry.as_str()).collect();
311        println!("snapshot: carried {}", names.join(", "));
312    }
313    Ok(())
314}
315
316// ---------------------------------------------------------------------------
317// dependencies
318// ---------------------------------------------------------------------------
319
320#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321pub enum Manager {
322    Npm,
323    Pnpm,
324    Yarn,
325    /// Recognised so that its lockfile is a unit — skipped when the push
326    /// does not touch it, refused with the fix named when it does — never
327    /// installed: see `bun_refusal`.
328    Bun,
329}
330
331impl Manager {
332    const ALL: [Manager; 4] = [Manager::Npm, Manager::Pnpm, Manager::Yarn, Manager::Bun];
333
334    /// The lockfiles that make a directory a unit of this manager. bun has
335    /// two: the binary `bun.lockb`, and the text `bun.lock` since bun 1.2.
336    fn lockfiles(self) -> &'static [&'static str] {
337        match self {
338            Manager::Npm => &["package-lock.json"],
339            Manager::Pnpm => &["pnpm-lock.yaml"],
340            Manager::Yarn => &["yarn.lock"],
341            Manager::Bun => &["bun.lock", "bun.lockb"],
342        }
343    }
344    pub(crate) fn tool(self) -> &'static str {
345        match self {
346            Manager::Npm => "npm",
347            Manager::Pnpm => "pnpm",
348            Manager::Yarn => "yarn",
349            Manager::Bun => "bun",
350        }
351    }
352
353    /// The manager whose lockfile sits in `root`, when exactly one does.
354    pub(crate) fn from_root_lockfile(root: &Path) -> Option<Manager> {
355        let mut found = Manager::ALL
356            .into_iter()
357            .filter(|m| m.lockfiles().iter().any(|l| root.join(l).is_file()));
358        let one = found.next()?;
359        found.next().is_none().then_some(one)
360    }
361
362    /// The command that adds `spec` (`prettier@3.9.10`) as a dev dependency.
363    pub(crate) fn add_dev_command(self, spec: &str) -> String {
364        match self {
365            Manager::Npm => format!("npm install --save-dev --save-exact {spec}"),
366            Manager::Pnpm => format!("pnpm add -D --save-exact {spec}"),
367            Manager::Yarn => format!("yarn add -D --exact {spec}"),
368            Manager::Bun => format!("bun add -d --exact {spec}"),
369        }
370    }
371}
372
373/// One installation unit: a directory holding a tracked lockfile, and the
374/// manager that reads it.
375#[derive(Debug, Clone, PartialEq, Eq)]
376pub struct Unit {
377    /// Repo-relative, `""` for the root.
378    pub dir: String,
379    pub manager: Manager,
380    /// The tracked lockfile's basename.
381    pub lockfile: &'static str,
382    /// pnpm only: a lockfile with no `pnpm-workspace.yaml` beside it is a
383    /// standalone project, even inside a workspace (see `audit::pnpm_args`).
384    pub standalone: bool,
385    /// yarn only: the lockfile is yarn 2+'s ("berry"), whose install is
386    /// `--immutable`; a classic (yarn 1) lockfile installs with
387    /// `--frozen-lockfile`.
388    pub berry: bool,
389}
390
391/// Is this `yarn.lock` yarn 2+'s? Berry writes a `__metadata:` block at the
392/// top of every lockfile; yarn 1 writes `# yarn lockfile v1` and never that
393/// key. Read from the SNAPSHOT's lockfile, so the pushed commit decides.
394pub fn is_berry_lock(text: &str) -> bool {
395    text.lines().any(|l| l.starts_with("__metadata:"))
396}
397
398/// The directories of `files` named exactly `name`, repo-relative (`""` for
399/// the root), sorted and deduplicated. Pure: the caller decides WHICH index
400/// the list comes from — the snapshot's, for a snapshot.
401pub fn lockfile_dirs_in(files: &[String], name: &str) -> Vec<String> {
402    let mut dirs: Vec<String> = files
403        .iter()
404        .filter(|p| p.rsplit('/').next().unwrap_or(p) == name)
405        .map(|p| {
406            p.rsplit_once('/')
407                .map(|(d, _)| d.to_string())
408                .unwrap_or_default()
409        })
410        .collect();
411    dirs.sort();
412    dirs.dedup();
413    dirs
414}
415
416fn join_rel(dir: &str, name: &str) -> String {
417    if dir.is_empty() {
418        name.to_string()
419    } else {
420        format!("{dir}/{name}")
421    }
422}
423
424/// The `packageManager` field of a package.json, by a targeted scan of that
425/// one key — the manager it names (`npm@…`, `pnpm@…`, `yarn@…`, `bun@…`)
426/// when it names one without ambiguity, `None` otherwise.
427pub fn declared_manager(package_json: &str) -> Option<Manager> {
428    let key = "\"packageManager\"";
429    let mut hits = package_json.match_indices(key);
430    let (at, _) = hits.next()?;
431    if hits.next().is_some() {
432        return None;
433    }
434    let rest = package_json[at + key.len()..].trim_start();
435    let rest = rest.strip_prefix(':')?.trim_start();
436    let rest = rest.strip_prefix('"')?;
437    let value = &rest[..rest.find('"')?];
438    let name = value.split('@').next().unwrap_or(value);
439    Manager::ALL.into_iter().find(|m| m.tool() == name)
440}
441
442/// Every installation unit in `files`. A directory holding MORE THAN ONE
443/// manager's lockfile is settled by `packageManager`, or refused: guessing
444/// would install the wrong tree and test it as if it were the right one.
445pub fn units(files: &[String], snapshot: &Path) -> Result<Vec<Unit>, String> {
446    // Every tracked lockfile: (directory, manager, basename).
447    let mut found: Vec<(String, Manager, &'static str)> = Vec::new();
448    for m in Manager::ALL {
449        for lock in m.lockfiles() {
450            found.extend(
451                lockfile_dirs_in(files, lock)
452                    .into_iter()
453                    .map(|dir| (dir, m, *lock)),
454            );
455        }
456    }
457    let mut dirs: Vec<String> = found.iter().map(|f| f.0.clone()).collect();
458    dirs.sort();
459    dirs.dedup();
460    let mut out = Vec::new();
461    for dir in dirs {
462        let here: Vec<&(String, Manager, &'static str)> =
463            found.iter().filter(|f| f.0 == dir).collect();
464        let (manager, lockfile) = if here.iter().all(|f| f.1 == here[0].1) {
465            (here[0].1, here[0].2)
466        } else {
467            let manifest = snapshot.join(join_rel(&dir, "package.json"));
468            let body = std::fs::read_to_string(&manifest).unwrap_or_default();
469            declared_manager(&body)
470                .and_then(|m| here.iter().find(|f| f.1 == m))
471                .map(|f| (f.1, f.2))
472                .ok_or_else(|| {
473                    let names: Vec<&str> = here.iter().map(|f| f.2).collect();
474                    format!(
475                        "both {} in {} and no `packageManager` to choose — set \
476                         greengate.snapshotPrepare",
477                        names.join(" and "),
478                        if dir.is_empty() { "the root" } else { &dir }
479                    )
480                })?
481        };
482        let standalone =
483            manager == Manager::Pnpm && !files.contains(&join_rel(&dir, "pnpm-workspace.yaml"));
484        let berry = manager == Manager::Yarn
485            && std::fs::read_to_string(snapshot.join(join_rel(&dir, lockfile)))
486                .map(|t| is_berry_lock(&t))
487                .unwrap_or(false);
488        out.push(Unit {
489            dir,
490            manager,
491            lockfile,
492            standalone,
493            berry,
494        });
495    }
496    Ok(out)
497}
498
499/// Why a bun unit is never installed, with the fix: bun's `--frozen-lockfile`
500/// and its lockfile formats have not been exercised here, and running the
501/// gate in a checkout with no dependencies fails every workspace at once
502/// and reads like a broken branch (#308). The snapshot's owner names the
503/// install command, or turns the preparation off.
504fn bun_refusal(u: &Unit) -> String {
505    format!(
506        "{} in {}: {BIN} cannot install bun dependencies — set greengate.snapshotPrepare \
507         to the install command, or greengate.snapshotDeps off",
508        u.lockfile,
509        unit_label(u)
510    )
511}
512
513fn unit_label(u: &Unit) -> String {
514    if u.dir.is_empty() {
515        "the root".to_string()
516    } else {
517        format!("{}/", u.dir)
518    }
519}
520
521fn manager_cmd(u: &Unit, at: &Path, args: &[&str]) -> Command {
522    let mut cmd = Command::new(crate::hooks::common::program(u.manager.tool()));
523    cmd.args(args).current_dir(at).stdin(Stdio::null());
524    if u.manager == Manager::Pnpm {
525        // A purge prompt cannot be answered from a hook, and aborts.
526        cmd.arg("--config.confirmModulesPurge=false");
527        if u.standalone {
528            cmd.arg("--ignore-workspace");
529        }
530    }
531    crate::hooks::common::strip_git_env(&mut cmd);
532    // For a `prepare` script that wants to know; the guard itself is the
533    // marker in the snapshot's git dir (`pushed_tree::MARKER`).
534    cmd.env(crate::pushed_tree::SNAPSHOT_ENV, "1");
535    cmd
536}
537
538/// Run a manager command quietly; `Ok(output)` on exit 0, `Err(output)`
539/// otherwise — the output is what the caller quotes when it says why.
540fn quiet(settings: &crate::config::Settings, mut cmd: Command) -> Result<String, String> {
541    match crate::hooks::common::capture_within(settings, &mut cmd) {
542        Some((crate::hooks::common::Ran::Status(s), text)) if s.success() => Ok(text),
543        Some((_, text)) => Err(text),
544        None => Err("could not start".to_string()),
545    }
546}
547
548/// The last meaningful line of a tool's output, for a one-line reason.
549fn last_line(text: &str) -> String {
550    text.lines()
551        .map(str::trim)
552        .rfind(|l| !l.is_empty())
553        .unwrap_or("no output")
554        .chars()
555        .take(200)
556        .collect()
557}
558
559fn install(settings: &crate::config::Settings, u: &Unit, at: &Path) -> Result<(), String> {
560    let args: &[&str] = match u.manager {
561        Manager::Npm => &["ci", "--no-audit", "--no-fund", "--prefer-offline"],
562        Manager::Pnpm => &["install", "--frozen-lockfile", "--prefer-offline"],
563        // Berry accepts `--frozen-lockfile` only as a deprecated alias and
564        // warns on `--prefer-offline`; yarn 1 ignores `--immutable`. Each
565        // flavour gets its own spelling.
566        Manager::Yarn if u.berry => &["install", "--immutable"],
567        Manager::Yarn => &[
568            "install",
569            "--frozen-lockfile",
570            "--non-interactive",
571            "--prefer-offline",
572        ],
573        Manager::Bun => return Err(bun_refusal(u)),
574    };
575    let mut cmd = manager_cmd(u, at, args);
576    let what = format!("{} {}", u.manager.tool(), args[0]);
577    if crate::hooks::common::bounded_success(settings, &mut cmd, &what) {
578        Ok(())
579    } else {
580        Err(format!("{what} failed in {}", unit_label(u)))
581    }
582}
583
584#[cfg(any(target_os = "macos", target_os = "linux"))]
585const CROSS_VOLUME_HINT: &str = "the snapshot's temp dir is on another volume than the working \
586     tree; set TMPDIR to a directory on that volume";
587#[cfg(any(target_os = "macos", target_os = "linux"))]
588const NO_CLONE_HINT: &str = "this filesystem cannot clone; \
589     `git config greengate.snapshotDeps install` skips the attempt";
590
591/// Clone a directory copy-on-write or refuse. macOS calls `clonefile(2)` with
592/// `CLONE_NOFOLLOW`, so symlinks are cloned as symlinks; Linux runs GNU
593/// `cp -R -T --reflink=always` by absolute path. There is no plain-copy
594/// fallback: a copy would cost the disk the clone exists to save. An existing
595/// destination is refused and left untouched, and so is one that cannot be
596/// statted: only a path that is certainly absent is ours to clear after a
597/// failed clone, and never after `AlreadyExists`, which means someone else
598/// made it first.
599fn clone_dir(src: &Path, dst: &Path) -> Result<(), String> {
600    use std::io::ErrorKind;
601    let (ours, outcome) = match std::fs::symlink_metadata(dst) {
602        Ok(_) => (false, Err(std::io::Error::from(ErrorKind::AlreadyExists))),
603        Err(e) if e.kind() == ErrorKind::NotFound => (true, clone_tree(src, dst)),
604        Err(e) => (false, Err(e)),
605    };
606    match outcome {
607        Ok(()) => Ok(()),
608        Err(e) => {
609            let mut why = e.to_string();
610            if ours && e.kind() != ErrorKind::AlreadyExists {
611                if let Err(rm) = std::fs::remove_dir_all(dst) {
612                    if rm.kind() != ErrorKind::NotFound {
613                        why.push_str(&format!(
614                            ", and the partial clone could not be removed: {rm}"
615                        ));
616                    }
617                }
618            }
619            Err(format!(
620                "no copy-on-write clone of {} ({why})",
621                src.display()
622            ))
623        }
624    }
625}
626
627#[cfg(target_os = "macos")]
628fn clone_tree(src: &Path, dst: &Path) -> std::io::Result<()> {
629    use std::ffi::CString;
630    use std::os::unix::ffi::OsStrExt;
631
632    const CLONE_NOFOLLOW: u32 = 0x0001;
633    // errno values on macOS: another volume, and a filesystem without clones.
634    const EXDEV: i32 = 18;
635    const ENOTSUP: i32 = 45;
636    extern "C" {
637        fn clonefile(
638            src: *const std::os::raw::c_char,
639            dst: *const std::os::raw::c_char,
640            flags: u32,
641        ) -> std::os::raw::c_int;
642    }
643    let to_c = |p: &Path| {
644        CString::new(p.as_os_str().as_bytes()).map_err(|_| {
645            std::io::Error::new(std::io::ErrorKind::InvalidInput, "path contains a NUL byte")
646        })
647    };
648    let (from, to) = (to_c(src)?, to_c(dst)?);
649    // SAFETY: both pointers are NUL-terminated and outlive the call.
650    let rc = unsafe { clonefile(from.as_ptr(), to.as_ptr(), CLONE_NOFOLLOW) };
651    if rc == 0 {
652        return Ok(());
653    }
654    let err = std::io::Error::last_os_error();
655    Err(match err.raw_os_error() {
656        Some(EXDEV) => std::io::Error::other(CROSS_VOLUME_HINT),
657        Some(ENOTSUP) => std::io::Error::other(NO_CLONE_HINT),
658        _ => err,
659    })
660}
661
662#[cfg(target_os = "linux")]
663fn clone_tree(src: &Path, dst: &Path) -> std::io::Result<()> {
664    let cp = ["/bin/cp", "/usr/bin/cp"]
665        .into_iter()
666        .find(|p| Path::new(p).exists())
667        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no cp found"))?;
668    // `dst` is created here, atomically, so it is ours: a path that appeared
669    // since the caller's stat is `AlreadyExists` and is left alone. -T then
670    // copies INTO it rather than nesting `src` inside. --preserve keeps the
671    // modes and mtimes `clonefile` keeps, which the install-record scans read.
672    std::fs::create_dir(dst).map_err(|err| {
673        std::io::Error::new(
674            err.kind(),
675            format!("cannot create {}: {err}", dst.display()),
676        )
677    })?;
678    let out = Command::new(cp)
679        .args([
680            "-R",
681            "-T",
682            "--reflink=always",
683            "--preserve=mode,timestamps",
684            "--no-dereference",
685        ])
686        .arg(src)
687        .arg(dst)
688        // English messages, so the hints below match under any locale.
689        .env("LC_ALL", "C")
690        .stdin(Stdio::null())
691        .stdout(Stdio::null())
692        .output()?;
693    if out.status.success() {
694        return Ok(());
695    }
696    // `cp` prints one error per file it could not clone: a tree of 74k files
697    // on a filesystem without reflinks would bury the reason, so keep the first.
698    let stderr = String::from_utf8_lossy(&out.stderr);
699    let mut lines = stderr.lines().map(str::trim).filter(|l| !l.is_empty());
700    let first = lines.next().unwrap_or("cp failed with no output");
701    let more = lines.count();
702    let lower = first.to_lowercase();
703    Err(std::io::Error::other(if lower.contains("cross-device") {
704        CROSS_VOLUME_HINT.to_string()
705    } else if lower.contains("not supported") || lower.contains("inappropriate ioctl") {
706        NO_CLONE_HINT.to_string()
707    } else if more == 0 {
708        first.to_string()
709    } else {
710        format!("{first} (and {more} more)")
711    }))
712}
713
714#[cfg(not(any(target_os = "macos", target_os = "linux")))]
715fn clone_tree(_src: &Path, _dst: &Path) -> std::io::Result<()> {
716    Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
717}
718
719/// Lexically resolve `p` — `.` and `..` folded, nothing touched on disk.
720fn normalize(p: &Path) -> PathBuf {
721    let mut out = PathBuf::new();
722    for c in p.components() {
723        match c {
724            Component::ParentDir => {
725                out.pop();
726            }
727            Component::CurDir => {}
728            other => out.push(other.as_os_str()),
729        }
730    }
731    out
732}
733
734/// The first symlink under `dir` that resolves into `source` — a clone
735/// still reading the developer's tree through a link is not isolated,
736/// whatever else it preserved.
737fn link_into(dir: &Path, sources: &[PathBuf]) -> std::io::Result<Option<PathBuf>> {
738    let mut stack = vec![dir.to_path_buf()];
739    while let Some(at) = stack.pop() {
740        for entry in std::fs::read_dir(&at)? {
741            let entry = entry?;
742            let kind = entry.file_type()?;
743            let path = entry.path();
744            if kind.is_symlink() {
745                let target = std::fs::read_link(&path)?;
746                let resolved = if target.is_absolute() {
747                    normalize(&target)
748                } else {
749                    normalize(&at.join(target))
750                };
751                // Lexically AND through every link: `/var` is itself a
752                // symlink on macOS, so the two spellings of one directory
753                // must both be caught.
754                let real = path.canonicalize().ok();
755                if sources.iter().any(|s| {
756                    resolved.starts_with(s) || real.as_ref().is_some_and(|r| r.starts_with(s))
757                }) {
758                    return Ok(Some(path));
759                }
760            } else if kind.is_dir() {
761                stack.push(path);
762            }
763        }
764    }
765    Ok(None)
766}
767
768/// The first regular file under `nm` modified after `record`, pnpm's
769/// install record (`.modules.yaml`, rewritten as an install finishes).
770///
771/// Skipped, because an install or the tools legitimately write them after
772/// the record: every `.bin/` (pnpm relinks it last), `.cache/` and
773/// `.vite*/` (tool caches), and pnpm's own `.pnpm/lock.yaml`,
774/// `.pnpm-workspace-state*` and `.modules.yaml`. Symlinks are not followed —
775/// a top-level package is a link into `.pnpm`, which is walked itself.
776fn newer_than(nm: &Path, record: std::time::SystemTime) -> std::io::Result<Option<PathBuf>> {
777    if !nm.is_dir() {
778        return Ok(None);
779    }
780    let mut stack = vec![nm.to_path_buf()];
781    while let Some(at) = stack.pop() {
782        for entry in std::fs::read_dir(&at)? {
783            let entry = entry?;
784            let name = entry.file_name();
785            let name = name.to_string_lossy();
786            let kind = entry.file_type()?;
787            if kind.is_dir() {
788                if name == ".bin" || name == ".cache" || name.starts_with(".vite") {
789                    continue;
790                }
791                stack.push(entry.path());
792            } else if kind.is_file() {
793                if name == ".modules.yaml"
794                    || name.starts_with(".pnpm-workspace-state")
795                    || (name == "lock.yaml" && at.file_name().is_some_and(|d| d == ".pnpm"))
796                {
797                    continue;
798                }
799                if entry.metadata()?.modified()? > record {
800                    return Ok(Some(entry.path()));
801                }
802            }
803        }
804    }
805    Ok(None)
806}
807
808/// Workspace members of a pnpm unit, as pnpm lists them, relative to the
809/// unit dir. Asked in the SNAPSHOT: the committed manifests decide.
810fn members(settings: &crate::config::Settings, u: &Unit, at: &Path) -> Result<Vec<String>, String> {
811    if u.standalone {
812        return Ok(Vec::new());
813    }
814    let text = quiet(
815        settings,
816        manager_cmd(u, at, &["ls", "-r", "--depth", "-1", "--parseable"]),
817    )
818    .map_err(|t| format!("pnpm could not list the workspace: {}", last_line(&t)))?;
819    let root = normalize(at);
820    let canon = at.canonicalize().unwrap_or_else(|_| root.clone());
821    Ok(text
822        .lines()
823        .filter_map(|l| {
824            let p = PathBuf::from(l.trim());
825            let rel = p
826                .strip_prefix(&root)
827                .or_else(|_| p.strip_prefix(&canon))
828                .ok()?;
829            let rel = rel.to_string_lossy().replace('\\', "/");
830            (!rel.is_empty()).then_some(rel)
831        })
832        .collect())
833}
834
835/// Is `nm` laid out the way pnpm's default (`isolated`) linker lays it out —
836/// every package a link, `@scope` directories holding only links? pnpm's own
837/// check does not look at a directory it did not create, and a stray one
838/// here is importable by the suite; so anything else is not reused.
839fn pnpm_layout_problem(nm: &Path, is_root: bool) -> Option<String> {
840    if is_root {
841        let modules = std::fs::read_to_string(nm.join(".modules.yaml")).unwrap_or_default();
842        let isolated = modules
843            .lines()
844            .any(|l| l.contains("nodeLinker") && l.contains("isolated"));
845        if !isolated {
846            return Some("not installed with pnpm's isolated linker".to_string());
847        }
848    }
849    let entries = std::fs::read_dir(nm).ok()?;
850    for e in entries.flatten() {
851        let name = e.file_name().to_string_lossy().into_owned();
852        if name.starts_with('.') {
853            continue;
854        }
855        let kind = e.file_type().ok()?;
856        if kind.is_symlink() {
857            continue;
858        }
859        if name.starts_with('@') && kind.is_dir() {
860            for inner in std::fs::read_dir(e.path()).ok()?.flatten() {
861                if !inner.file_type().map(|k| k.is_symlink()).unwrap_or(false) {
862                    return Some(format!(
863                        "{} is not a link pnpm made",
864                        inner.path().display()
865                    ));
866                }
867            }
868            continue;
869        }
870        return Some(format!("{} is not a link pnpm made", e.path().display()));
871    }
872    None
873}
874
875/// Try to reuse the working tree's install for one unit. `Ok(())` when the
876/// clone is in place and pnpm accepted it; `Err(reason)` — with the snapshot
877/// left exactly as it was — when it cannot be.
878///
879/// npm is never reused. `npm ls` answers "is this dependency graph valid",
880/// not "is this the tree the lockfile describes": a real repository with
881/// peer-range conflicts `npm ci` installs without complaint fails `npm ls`
882/// on a fresh install (application-landscape: 182 findings), so it can
883/// neither accept a correct clone nor be trusted to reject a wrong one.
884///
885/// yarn is never reused either: `yarn check` is gone from yarn 1 and berry
886/// alike, a frozen install checks the lockfile against the manifests and
887/// not the installed tree, and yarn 1's `--frozen-lockfile` is known to let
888/// some drift through (yarnpkg/yarn#5840) — so nothing yarn offers can
889/// vouch for a clone.
890fn reuse(
891    settings: &crate::config::Settings,
892    u: &Unit,
893    source: &Path,
894    snapshot: &Path,
895    unit_dirs: &[String],
896) -> Result<(), String> {
897    match u.manager {
898        Manager::Npm => {
899            return Err(
900                "npm cannot check an installed tree against its lockfile, so npm \
901                 snapshots always install"
902                    .to_string(),
903            )
904        }
905        Manager::Yarn => {
906            return Err(
907                "yarn cannot check an installed tree against its lockfile, so yarn \
908                 snapshots always install"
909                    .to_string(),
910            )
911        }
912        Manager::Bun => return Err(bun_refusal(u)),
913        Manager::Pnpm => {}
914    }
915    let src_dir = source.join(&u.dir);
916    let snap_dir = snapshot.join(&u.dir);
917    let lock = u.lockfile;
918    let src_lock = std::fs::read(src_dir.join(lock))
919        .map_err(|_| "no lockfile in the working tree".to_string())?;
920    let snap_lock = std::fs::read(snap_dir.join(lock)).map_err(|e| format!("{lock}: {e}"))?;
921    if src_lock != snap_lock {
922        return Err("the working tree's lockfile differs from the commit's".to_string());
923    }
924    if !src_dir.join("node_modules").is_dir() {
925        return Err("nothing installed in the working tree".to_string());
926    }
927    let mut set = vec![String::new()];
928    for m in members(settings, u, &snap_dir)? {
929        let repo_rel = join_rel(&u.dir, &m);
930        // A member with a lockfile of its own is its own unit.
931        if unit_dirs.contains(&repo_rel) {
932            continue;
933        }
934        if src_dir.join(&m).join("node_modules").is_dir() {
935            set.push(m);
936        }
937    }
938    // Checked on the SOURCE, before anything is copied: a file changed
939    // since pnpm finished installing is an edit pnpm's own check will not
940    // see, and a clone would carry it into a stamped snapshot.
941    let record = std::fs::metadata(src_dir.join("node_modules/.modules.yaml"))
942        .and_then(|m| m.modified())
943        .map_err(|_| "no pnpm install record (node_modules/.modules.yaml)".to_string())?;
944    for m in &set {
945        match newer_than(&src_dir.join(m).join("node_modules"), record) {
946            Ok(None) => {}
947            Ok(Some(f)) => {
948                let shown = f.strip_prefix(source).unwrap_or(&f);
949                return Err(format!(
950                    "{} changed after the install — an in-place edit pnpm does not check",
951                    shown.display()
952                ));
953            }
954            Err(e) => return Err(format!("could not inspect the working tree's install: {e}")),
955        }
956    }
957    let mut cloned: Vec<PathBuf> = Vec::new();
958    // What it could not remove goes into the refusal: an install over a
959    // clone left behind is the one outcome this function must never hide.
960    let rollback = |cloned: &[PathBuf]| -> String {
961        let mut left = Vec::new();
962        for dir in cloned {
963            if let Err(err) = std::fs::remove_dir_all(dir) {
964                if err.kind() != std::io::ErrorKind::NotFound {
965                    left.push(format!("{}: {err}", dir.display()));
966                }
967            }
968        }
969        if left.is_empty() {
970            String::new()
971        } else {
972            format!(
973                "; could not remove the clone, so the install may run over it (remove it by hand): {}",
974                left.join(", ")
975            )
976        }
977    };
978    let sources = [
979        normalize(source),
980        source.canonicalize().unwrap_or_else(|_| normalize(source)),
981    ];
982    for m in &set {
983        let from = src_dir.join(m).join("node_modules");
984        let to = snap_dir.join(m).join("node_modules");
985        if std::fs::symlink_metadata(&to).is_ok() {
986            let left = rollback(&cloned);
987            return Err(format!(
988                "{} already exists in the snapshot{left}",
989                to.display()
990            ));
991        }
992        if let Err(e) = clone_dir(&from, &to) {
993            let left = rollback(&cloned);
994            return Err(format!("{e}{left}"));
995        }
996        cloned.push(to.clone());
997        let problem = match link_into(&to, &sources) {
998            Ok(Some(link)) => Some(format!(
999                "{} links back into the working tree",
1000                link.display()
1001            )),
1002            Ok(None) => pnpm_layout_problem(&to, m.is_empty()),
1003            Err(e) => Some(format!("could not inspect the clone: {e}")),
1004        };
1005        if let Some(why) = problem {
1006            let left = rollback(&cloned);
1007            return Err(format!("{why}{left}"));
1008        }
1009    }
1010    // pnpm records the absolute paths of the tree it installed; the clone
1011    // must not carry the source's.
1012    if let Ok(rd) = std::fs::read_dir(snap_dir.join("node_modules")) {
1013        for e in rd.flatten() {
1014            if e.file_name()
1015                .to_string_lossy()
1016                .starts_with(".pnpm-workspace-state")
1017            {
1018                let _ = std::fs::remove_file(e.path());
1019            }
1020        }
1021    }
1022    // A frozen OFFLINE install is both the check and the repair: it fails on
1023    // a manifest the lockfile does not satisfy, relinks drift from the
1024    // store, and says "Already up to date" for a faithful clone.
1025    if let Err(text) = quiet(
1026        settings,
1027        manager_cmd(u, &snap_dir, &["install", "--frozen-lockfile", "--offline"]),
1028    ) {
1029        let left = rollback(&cloned);
1030        return Err(format!(
1031            "pnpm did not accept the clone ({}){left}",
1032            last_line(&text)
1033        ));
1034    }
1035    Ok(())
1036}
1037
1038/// The files `tip` changes relative to where it forked from its upstream —
1039/// what the push is about. `None` when git cannot say (no upstream, a tip
1040/// it does not know): the caller then prepares everything.
1041pub fn changed_since_upstream(source: &Path, tip: &str) -> Option<Vec<String>> {
1042    let git = |args: &[&str]| -> Option<Vec<u8>> {
1043        let mut cmd = Command::new("git");
1044        cmd.arg("-C")
1045            .arg(source)
1046            .args(args)
1047            .stdin(Stdio::null())
1048            .stderr(Stdio::null());
1049        crate::hooks::common::strip_git_env(&mut cmd);
1050        let out = cmd.output().ok()?;
1051        out.status.success().then_some(out.stdout)
1052    };
1053    let base = git(&["merge-base", tip, "@{upstream}"])?;
1054    let base = String::from_utf8_lossy(&base).trim().to_string();
1055    if base.is_empty() {
1056        return None;
1057    }
1058    let raw = git(&["diff", "--name-only", "-z", &base, tip])?;
1059    Some(crate::git::split_nul_paths(&raw))
1060}
1061
1062/// Which units a snapshot needs: the root one, and every unit that is the
1063/// NEAREST enclosing unit of a changed file. A unit the push does not touch
1064/// cannot hold a failure the push introduced — and nothing the gates run for
1065/// this push reads it — so installing it is pure cost (website-builder: seven
1066/// spikes, an install each, on every snapshot). `changed` is `None` when the
1067/// range is unknown, and then every unit is kept.
1068///
1069/// Returns `(kept, skipped)`.
1070pub fn select_units(units: Vec<Unit>, changed: Option<&[String]>) -> (Vec<Unit>, Vec<Unit>) {
1071    let Some(changed) = changed else {
1072        return (units, Vec::new());
1073    };
1074    let nearest = |f: &str| -> Option<&str> {
1075        units
1076            .iter()
1077            .map(|u| u.dir.as_str())
1078            .filter(|d| d.is_empty() || f.starts_with(&format!("{d}/")))
1079            .max_by_key(|d| d.len())
1080    };
1081    let touched: Vec<&str> = changed.iter().filter_map(|f| nearest(f)).collect();
1082    let (kept, skipped): (Vec<Unit>, Vec<Unit>) = units
1083        .clone()
1084        .into_iter()
1085        .partition(|u| u.dir.is_empty() || touched.contains(&u.dir.as_str()));
1086    (kept, skipped)
1087}
1088
1089/// Prepare the dependencies of every unit the push needs in `snapshot`.
1090pub fn deps(
1091    settings: &crate::config::Settings,
1092    mode: DepsMode,
1093    source: &Path,
1094    snapshot: &Path,
1095    files: &[String],
1096    changed: Option<&[String]>,
1097) -> Result<(), String> {
1098    if mode == DepsMode::Off {
1099        return Ok(());
1100    }
1101    let all = units(files, snapshot)?;
1102    let unit_dirs: Vec<String> = all.iter().map(|u| u.dir.clone()).collect();
1103    let (units, skipped) = select_units(all, changed);
1104    if !skipped.is_empty() {
1105        let names: Vec<String> = skipped.iter().map(unit_label).collect();
1106        println!(
1107            "snapshot: not preparing {} — the push changes nothing there",
1108            names.join(", ")
1109        );
1110    }
1111    for u in &units {
1112        let at = snapshot.join(&u.dir);
1113        let label = unit_label(u);
1114        if u.manager == Manager::Bun {
1115            // Refused before anything is printed or cloned: the message IS
1116            // the preparation's result for this unit.
1117            return Err(bun_refusal(u));
1118        }
1119        if mode == DepsMode::Reuse {
1120            // No clone tool on Windows: `clone_dir` says so and this falls
1121            // through to the install, like any other refusal.
1122            match reuse(settings, u, source, snapshot, &unit_dirs) {
1123                Ok(()) => {
1124                    println!(
1125                        "snapshot: node_modules in {label} reused from the working tree — {} \
1126                         accepted it against the lockfile \
1127                         (copy-on-write clone, shares disk with the working tree)",
1128                        u.manager.tool()
1129                    );
1130                    continue;
1131                }
1132                Err(why) => println!(
1133                    "snapshot: {} in {label} — not reusing the working tree's install: {why}",
1134                    highlight(&format!("{} {}", u.manager.tool(), install_verb(u)))
1135                ),
1136            }
1137        } else {
1138            println!(
1139                "snapshot: {} in {label}",
1140                highlight(&format!("{} {}", u.manager.tool(), install_verb(u)))
1141            );
1142        }
1143        install(settings, u, &at)?;
1144    }
1145    Ok(())
1146}
1147
1148fn install_verb(u: &Unit) -> &'static str {
1149    match u.manager {
1150        Manager::Npm => "ci",
1151        Manager::Pnpm => "install --frozen-lockfile",
1152        Manager::Yarn if u.berry => "install --immutable",
1153        Manager::Yarn => "install --frozen-lockfile",
1154        Manager::Bun => "install",
1155    }
1156}
1157
1158/// Carry → dependencies → nothing else; `snapshotPrepare` runs after this,
1159/// in `PushedTree::prepare`. Dependencies are skipped when a
1160/// `snapshotPrepare` command exists: that command owns them.
1161pub fn run(
1162    settings: &crate::config::Settings,
1163    source: &Path,
1164    snapshot: &Path,
1165    tip: &str,
1166    command_owns_deps: bool,
1167) -> Result<(), String> {
1168    let entries = carry_list(settings);
1169    let mode = if command_owns_deps {
1170        DepsMode::Off
1171    } else {
1172        deps_mode(settings)
1173    };
1174    if entries.is_empty() && mode == DepsMode::Off {
1175        return Ok(());
1176    }
1177    let files = snapshot_files(snapshot)?;
1178    if !entries.is_empty() {
1179        carry(&entries, source, snapshot, &files)?;
1180    }
1181    let changed = if mode == DepsMode::Off {
1182        None
1183    } else {
1184        changed_since_upstream(source, tip)
1185    };
1186    deps(settings, mode, source, snapshot, &files, changed.as_deref()).map_err(|e| {
1187        println!("{} {e}", warning_sign());
1188        e
1189    })
1190}
1191
1192#[cfg(test)]
1193mod tests {
1194    use super::*;
1195
1196    fn s(v: &[&str]) -> Vec<String> {
1197        v.iter().map(|x| x.to_string()).collect()
1198    }
1199
1200    #[test]
1201    fn clone_dir_refuses_an_existing_destination() {
1202        let scratch = std::env::temp_dir().join(format!("clone-exist-{}", std::process::id()));
1203        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1204        std::fs::create_dir_all(scratch.join("src")).unwrap();
1205        std::fs::create_dir_all(scratch.join("dst")).unwrap();
1206        std::fs::write(scratch.join("dst/keep"), "mine").unwrap();
1207        let err = clone_dir(&scratch.join("src"), &scratch.join("dst")).unwrap_err();
1208        assert!(err.starts_with("no copy-on-write clone of "), "{err}");
1209        assert_eq!(
1210            std::fs::read_to_string(scratch.join("dst/keep")).unwrap(),
1211            "mine"
1212        );
1213        assert_eq!(std::fs::read_dir(scratch.join("dst")).unwrap().count(), 1);
1214        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1215    }
1216
1217    #[cfg(target_os = "macos")]
1218    #[test]
1219    fn clone_dir_keeps_odd_names_and_relative_symlinks() {
1220        use std::ffi::OsStr;
1221        use std::os::unix::ffi::OsStrExt;
1222        // APFS refuses a name that is not valid UTF-8 (EILSEQ, 92), so there
1223        // the fixture holds a non-ASCII UTF-8 name instead; the line printed
1224        // says which of the two this run proved.
1225        const EILSEQ: i32 = 92;
1226        let scratch = std::env::temp_dir().join(format!("clone-tree-{}", std::process::id()));
1227        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1228        std::fs::create_dir_all(scratch.join("src/sub")).unwrap();
1229        let mut odd = OsStr::from_bytes(b"caf\xe9");
1230        match std::fs::write(scratch.join("src/sub").join(odd), "odd") {
1231            Ok(()) => eprintln!("clone test: a non-UTF-8 file name"),
1232            Err(e) if e.raw_os_error() == Some(EILSEQ) => {
1233                eprintln!("clone test: this volume refuses non-UTF-8 names; non-ASCII UTF-8 used");
1234                odd = OsStr::new("caf\u{e9}");
1235                std::fs::write(scratch.join("src/sub").join(odd), "odd").unwrap();
1236            }
1237            Err(e) => panic!("fixture could not be written: {e}"),
1238        }
1239        std::os::unix::fs::symlink("sub", scratch.join("src/link")).unwrap();
1240        clone_dir(&scratch.join("src"), &scratch.join("dst")).unwrap();
1241        assert_eq!(
1242            std::fs::read(scratch.join("dst/sub").join(odd)).unwrap(),
1243            b"odd"
1244        );
1245        assert_eq!(
1246            std::fs::read_link(scratch.join("dst/link")).unwrap(),
1247            Path::new("sub")
1248        );
1249        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1250    }
1251
1252    /// tmpfs cannot clone: the refusal names the clone in ONE line, leaves no
1253    /// destination behind and never falls back to a copy. CI's other Linux
1254    /// tests run on an XFS image with reflinks (`.github/workflows/ci.yaml`),
1255    /// so this is the one that proves the refusal there; where `CI` is set a
1256    /// runner without tmpfs fails it instead of passing without a check.
1257    #[cfg(target_os = "linux")]
1258    #[test]
1259    fn clone_dir_refuses_a_filesystem_without_reflinks() {
1260        let shm = Path::new("/dev/shm");
1261        if !shm.is_dir() {
1262            assert!(
1263                std::env::var_os("CI").is_none(),
1264                "no /dev/shm on a CI runner: the refusal has no tmpfs to be proven on"
1265            );
1266            eprintln!("no /dev/shm here: the refusal test has no tmpfs to run on");
1267            return;
1268        }
1269        let scratch = shm.join(format!("clone-tmpfs-{}", std::process::id()));
1270        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1271        std::fs::create_dir_all(scratch.join("src")).unwrap();
1272        for i in 0..20 {
1273            std::fs::write(scratch.join(format!("src/f{i}")), "data").unwrap();
1274        }
1275        let err = clone_dir(&scratch.join("src"), &scratch.join("dst")).unwrap_err();
1276        assert!(err.starts_with("no copy-on-write clone of "), "{err}");
1277        assert!(
1278            !err.contains('\n'),
1279            "one line, not cp's whole stderr: {err}"
1280        );
1281        assert!(
1282            !scratch.join("dst").exists(),
1283            "a refused clone left a destination"
1284        );
1285        let _ = std::fs::remove_dir_all(&scratch); // scratch dir: absent is fine
1286    }
1287
1288    #[test]
1289    fn lexical_refusals() {
1290        for bad in [
1291            "",
1292            "/etc/hosts",
1293            "\\x",
1294            "C:/x",
1295            "a//b",
1296            ".",
1297            "..",
1298            "a/../b",
1299            ".git/config",
1300            "x/.GIT/y",
1301        ] {
1302            assert!(lexical_problem(bad).is_some(), "{bad:?} must be refused");
1303        }
1304        for good in [".env", "config/local.json", ".npmrc", "a.b/c"] {
1305            assert!(lexical_problem(good).is_none(), "{good:?} must pass");
1306        }
1307    }
1308
1309    #[test]
1310    fn a_tracked_path_inside_above_or_equal_collides() {
1311        let files = s(&["src/a.ts", "vendor", "README.md"]);
1312        assert!(tracked_collision("src", &files).is_some());
1313        assert!(tracked_collision("src/a.ts", &files).is_some());
1314        assert!(tracked_collision("vendor/x", &files).is_some());
1315        assert!(tracked_collision(".env", &files).is_none());
1316        assert!(tracked_collision("sr", &files).is_none());
1317    }
1318
1319    #[test]
1320    fn lockfile_dirs_come_from_the_list_given() {
1321        let files = s(&[
1322            "package-lock.json",
1323            "web/package-lock.json",
1324            "web/x/pnpm-lock.yaml",
1325            "notpackage-lock.json",
1326        ]);
1327        assert_eq!(
1328            lockfile_dirs_in(&files, "package-lock.json"),
1329            s(&["", "web"])
1330        );
1331        assert_eq!(lockfile_dirs_in(&files, "pnpm-lock.yaml"), s(&["web/x"]));
1332    }
1333
1334    #[test]
1335    fn package_manager_field_is_read_narrowly() {
1336        assert_eq!(
1337            declared_manager(r#"{"packageManager": "pnpm@10.1.0"}"#),
1338            Some(Manager::Pnpm)
1339        );
1340        assert_eq!(
1341            declared_manager(r#"{"packageManager":"npm@11"}"#),
1342            Some(Manager::Npm)
1343        );
1344        assert_eq!(
1345            declared_manager(r#"{"packageManager":"yarn@4"}"#),
1346            Some(Manager::Yarn)
1347        );
1348        assert_eq!(
1349            declared_manager(r#"{"packageManager":"bun@1.2.0"}"#),
1350            Some(Manager::Bun)
1351        );
1352        assert_eq!(
1353            declared_manager(r#"{"packageManager":"yarnpkg@1"}"#),
1354            None,
1355            "a name, not a prefix"
1356        );
1357        assert_eq!(declared_manager(r#"{"name":"x"}"#), None);
1358        assert_eq!(
1359            declared_manager(r#"{"packageManager":"npm@1","x":{"packageManager":"pnpm@1"}}"#),
1360            None,
1361            "two answers is no answer"
1362        );
1363    }
1364
1365    fn unit(dir: &str) -> Unit {
1366        Unit {
1367            dir: dir.to_string(),
1368            manager: Manager::Pnpm,
1369            lockfile: "pnpm-lock.yaml",
1370            standalone: !dir.is_empty(),
1371            berry: false,
1372        }
1373    }
1374
1375    #[test]
1376    fn a_berry_lockfile_is_told_by_its_metadata_block() {
1377        assert!(is_berry_lock(
1378            "# This file is generated by running \"yarn install\" inside your project.\n\n__metadata:\n  version: 8\n"
1379        ));
1380        assert!(!is_berry_lock(
1381            "# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n# yarn lockfile v1\n\n"
1382        ));
1383        assert!(!is_berry_lock(""));
1384    }
1385
1386    #[test]
1387    fn every_manager_lockfile_is_a_unit_and_a_mixed_directory_needs_the_field() {
1388        let d = std::env::temp_dir().join(format!("units-{}", std::process::id()));
1389        let _ = std::fs::remove_dir_all(&d);
1390        std::fs::create_dir_all(d.join("berry")).unwrap();
1391        std::fs::write(d.join("yarn.lock"), "# yarn lockfile v1\n").unwrap();
1392        std::fs::write(d.join("berry/yarn.lock"), "__metadata:\n  version: 8\n").unwrap();
1393        let files = s(&[
1394            "yarn.lock",
1395            "berry/yarn.lock",
1396            "old/bun.lockb",
1397            "new/bun.lock",
1398            "mixed/package-lock.json",
1399            "mixed/yarn.lock",
1400        ]);
1401        let err = units(&files, &d).unwrap_err();
1402        assert!(
1403            err.contains("both package-lock.json and yarn.lock in mixed"),
1404            "{err}"
1405        );
1406        std::fs::create_dir_all(d.join("mixed")).unwrap();
1407        std::fs::write(
1408            d.join("mixed/package.json"),
1409            r#"{"packageManager":"yarn@1.22.22"}"#,
1410        )
1411        .unwrap();
1412        let got = units(&files, &d).unwrap();
1413        let brief: Vec<(&str, Manager, &str, bool)> = got
1414            .iter()
1415            .map(|u| (u.dir.as_str(), u.manager, u.lockfile, u.berry))
1416            .collect();
1417        assert_eq!(
1418            brief,
1419            vec![
1420                ("", Manager::Yarn, "yarn.lock", false),
1421                ("berry", Manager::Yarn, "yarn.lock", true),
1422                ("mixed", Manager::Yarn, "yarn.lock", false),
1423                ("new", Manager::Bun, "bun.lock", false),
1424                ("old", Manager::Bun, "bun.lockb", false),
1425            ]
1426        );
1427        std::fs::write(
1428            d.join("mixed/package.json"),
1429            r#"{"packageManager":"pnpm@10"}"#,
1430        )
1431        .unwrap();
1432        let err = units(&files, &d).unwrap_err();
1433        assert!(
1434            err.contains("no `packageManager` to choose"),
1435            "a field naming an absent lockfile chooses nothing: {err}"
1436        );
1437        let _ = std::fs::remove_dir_all(&d);
1438    }
1439
1440    #[test]
1441    fn only_the_root_and_the_touched_units_are_kept() {
1442        let all = vec![unit(""), unit("spikes/a"), unit("spikes/b"), unit("tools")];
1443        let changed = s(&["src/x.ts", "spikes/b/index.ts", "spikes/bb/y.ts"]);
1444        let (kept, skipped) = select_units(all.clone(), Some(&changed));
1445        let dirs = |v: &[Unit]| v.iter().map(|u| u.dir.clone()).collect::<Vec<_>>();
1446        assert_eq!(
1447            dirs(&kept),
1448            s(&["", "spikes/b"]),
1449            "spikes/bb is not spikes/b"
1450        );
1451        assert_eq!(dirs(&skipped), s(&["spikes/a", "tools"]));
1452        let (kept, skipped) = select_units(all.clone(), None);
1453        assert_eq!(kept.len(), 4, "an unknown range keeps everything");
1454        assert!(skipped.is_empty());
1455    }
1456
1457    #[test]
1458    fn a_nested_unit_claims_its_files_from_the_outer_one() {
1459        let all = vec![unit("web"), unit("web/nested")];
1460        let changed = s(&["web/nested/a.ts"]);
1461        let (kept, _) = select_units(all, Some(&changed));
1462        assert_eq!(kept.len(), 1);
1463        assert_eq!(kept[0].dir, "web/nested");
1464    }
1465
1466    #[test]
1467    fn a_file_newer_than_the_install_record_is_found() {
1468        let d = std::env::temp_dir().join(format!("newer-{}", std::process::id()));
1469        let _ = std::fs::remove_dir_all(&d);
1470        let pkg = d.join(".pnpm/a@1/node_modules/a");
1471        std::fs::create_dir_all(&pkg).unwrap();
1472        std::fs::create_dir_all(d.join(".bin")).unwrap();
1473        std::fs::create_dir_all(d.join(".cache")).unwrap();
1474        std::fs::write(pkg.join("index.js"), "old").unwrap();
1475        let record = std::time::SystemTime::now();
1476        std::thread::sleep(std::time::Duration::from_millis(20));
1477        for skipped in [".bin/tsc", ".cache/x", ".pnpm/lock.yaml", ".modules.yaml"] {
1478            std::fs::write(d.join(skipped), "new").unwrap();
1479        }
1480        assert_eq!(
1481            newer_than(&d, record).unwrap(),
1482            None,
1483            "the install's own writes"
1484        );
1485        std::fs::write(pkg.join("index.js"), "edited").unwrap();
1486        assert_eq!(newer_than(&d, record).unwrap(), Some(pkg.join("index.js")));
1487        let _ = std::fs::remove_dir_all(&d);
1488    }
1489
1490    #[test]
1491    fn normalize_folds_dots_lexically() {
1492        assert_eq!(
1493            normalize(Path::new("/a/b/../c/./d")),
1494            PathBuf::from("/a/c/d")
1495        );
1496    }
1497}