use crate::names::BIN;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Stdio};
use crate::ui::{highlight, warning_sign};
const CARRY: &str = "greengate.snapshotCarry";
const DEPS: &str = "greengate.snapshotDeps";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DepsMode {
Install,
Reuse,
Off,
}
pub fn deps_mode(settings: &crate::config::Settings) -> DepsMode {
match crate::config::enumerated_or(settings, DEPS, &["install", "reuse", "off"], "install") {
"reuse" => DepsMode::Reuse,
"off" => DepsMode::Off,
_ => DepsMode::Install,
}
}
pub fn carry_list(settings: &crate::config::Settings) -> Vec<String> {
crate::config::string_value(settings, CARRY)
.map(|v| {
v.split(|c: char| c.is_whitespace() || c == ',')
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect()
})
.unwrap_or_default()
}
pub fn snapshot_files(snapshot: &Path) -> Result<Vec<String>, String> {
let mut cmd = Command::new("git");
cmd.arg("-C")
.arg(snapshot)
.args(["ls-files", "-z"])
.stdin(Stdio::null())
.stderr(Stdio::null());
crate::hooks::common::strip_git_env(&mut cmd);
let out = cmd
.output()
.map_err(|e| format!("could not list the snapshot's files: {e}"))?;
if !out.status.success() {
return Err("could not list the snapshot's files".to_string());
}
Ok(crate::git::split_nul_paths(&out.stdout))
}
struct Carried {
entry: String,
src: PathBuf,
dst: PathBuf,
}
fn lexical_problem(entry: &str) -> Option<&'static str> {
if entry.is_empty() {
return Some("empty");
}
let bytes = entry.as_bytes();
if entry.starts_with('/') || entry.starts_with('\\') || (bytes.len() >= 2 && bytes[1] == b':') {
return Some("not a repo-relative path");
}
for part in entry.split(['/', '\\']) {
if part.is_empty() {
return Some("has an empty path component");
}
if part == "." || part == ".." {
return Some("has a `.` or `..` component");
}
if part.eq_ignore_ascii_case(".git") {
return Some("is inside .git");
}
}
None
}
fn tracked_collision(entry: &str, files: &[String]) -> Option<String> {
let inside = format!("{entry}/");
files
.iter()
.find(|f| {
f.as_str() == entry || f.starts_with(&inside) || entry.starts_with(&format!("{f}/"))
})
.cloned()
}
fn is_symlink(p: &Path) -> bool {
std::fs::symlink_metadata(p)
.map(|m| m.file_type().is_symlink())
.unwrap_or(false)
}
fn symlinked_ancestor(root: &Path, rel: &Path) -> Option<PathBuf> {
let mut at = root.to_path_buf();
let parts: Vec<_> = rel.components().collect();
for part in parts.iter().take(parts.len().saturating_sub(1)) {
at.push(part.as_os_str());
if is_symlink(&at) {
return Some(at);
}
}
None
}
fn symlink_inside(dir: &Path) -> std::io::Result<Option<PathBuf>> {
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let kind = entry.file_type()?;
if kind.is_symlink() {
return Ok(Some(entry.path()));
}
if kind.is_dir() {
if let Some(found) = symlink_inside(&entry.path())? {
return Ok(Some(found));
}
}
}
Ok(None)
}
fn copy_tree(src: &Path, dst: &Path) -> std::io::Result<()> {
let meta = std::fs::symlink_metadata(src)?;
if meta.is_dir() {
std::fs::create_dir(dst)?;
for entry in std::fs::read_dir(src)? {
let entry = entry?;
copy_tree(&entry.path(), &dst.join(entry.file_name()))?;
}
Ok(())
} else {
std::fs::copy(src, dst).map(|_| ())
}
}
pub fn carry(
entries: &[String],
source: &Path,
snapshot: &Path,
files: &[String],
) -> Result<(), String> {
let mut refused: Vec<String> = Vec::new();
let mut missing: Vec<&str> = Vec::new();
let mut plan: Vec<Carried> = Vec::new();
for entry in entries {
let norm = entry.replace('\\', "/");
let norm = norm.trim_end_matches('/').to_string();
if let Some(why) = lexical_problem(&norm) {
refused.push(format!("{entry}: {why}"));
continue;
}
if let Some(f) = tracked_collision(&norm, files) {
refused.push(format!(
"{entry}: tracked content ({f}) — only untracked files can be carried"
));
continue;
}
let rel = PathBuf::from(&norm);
let src = source.join(&rel);
let dst = snapshot.join(&rel);
if let Some(link) = symlinked_ancestor(source, &rel) {
refused.push(format!(
"{entry}: {} is a symlink in the working tree",
link.display()
));
continue;
}
if let Some(link) = symlinked_ancestor(snapshot, &rel) {
refused.push(format!(
"{entry}: {} is a symlink in the snapshot",
link.display()
));
continue;
}
let meta = match std::fs::symlink_metadata(&src) {
Ok(m) => m,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
missing.push(entry);
continue;
}
Err(e) => {
refused.push(format!("{entry}: cannot be read: {e}"));
continue;
}
};
if meta.file_type().is_symlink() {
refused.push(format!("{entry}: is a symlink"));
continue;
}
if meta.is_dir() {
match symlink_inside(&src) {
Ok(Some(link)) => {
refused.push(format!("{entry}: holds a symlink ({})", link.display()));
continue;
}
Ok(None) => {}
Err(e) => {
refused.push(format!("{entry}: cannot be read: {e}"));
continue;
}
}
}
if std::fs::symlink_metadata(&dst).is_ok() {
refused.push(format!("{entry}: already exists in the snapshot"));
continue;
}
plan.push(Carried {
entry: entry.clone(),
src,
dst,
});
}
if !refused.is_empty() {
return Err(format!(
"{CARRY} refused {}: {}",
if refused.len() == 1 {
"an entry".to_string()
} else {
format!("{} entries", refused.len())
},
refused.join("; ")
));
}
if !missing.is_empty() {
println!(
"snapshot: not carrying {} — not in the working tree",
missing.join(", ")
);
}
for c in &plan {
if let Some(parent) = c.dst.parent() {
std::fs::create_dir_all(parent).map_err(|e| format!("{CARRY}: {}: {e}", c.entry))?;
}
copy_tree(&c.src, &c.dst)
.map_err(|e| format!("{CARRY}: {} could not be copied: {e}", c.entry))?;
}
if !plan.is_empty() {
let names: Vec<&str> = plan.iter().map(|c| c.entry.as_str()).collect();
println!("snapshot: carried {}", names.join(", "));
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Manager {
Npm,
Pnpm,
Yarn,
Bun,
}
impl Manager {
const ALL: [Manager; 4] = [Manager::Npm, Manager::Pnpm, Manager::Yarn, Manager::Bun];
fn lockfiles(self) -> &'static [&'static str] {
match self {
Manager::Npm => &["package-lock.json"],
Manager::Pnpm => &["pnpm-lock.yaml"],
Manager::Yarn => &["yarn.lock"],
Manager::Bun => &["bun.lock", "bun.lockb"],
}
}
pub(crate) fn tool(self) -> &'static str {
match self {
Manager::Npm => "npm",
Manager::Pnpm => "pnpm",
Manager::Yarn => "yarn",
Manager::Bun => "bun",
}
}
pub(crate) fn from_root_lockfile(root: &Path) -> Option<Manager> {
let mut found = Manager::ALL
.into_iter()
.filter(|m| m.lockfiles().iter().any(|l| root.join(l).is_file()));
let one = found.next()?;
found.next().is_none().then_some(one)
}
pub(crate) fn add_dev_command(self, spec: &str) -> String {
match self {
Manager::Npm => format!("npm install --save-dev --save-exact {spec}"),
Manager::Pnpm => format!("pnpm add -D --save-exact {spec}"),
Manager::Yarn => format!("yarn add -D --exact {spec}"),
Manager::Bun => format!("bun add -d --exact {spec}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unit {
pub dir: String,
pub manager: Manager,
pub lockfile: &'static str,
pub standalone: bool,
pub berry: bool,
}
pub fn is_berry_lock(text: &str) -> bool {
text.lines().any(|l| l.starts_with("__metadata:"))
}
pub fn lockfile_dirs_in(files: &[String], name: &str) -> Vec<String> {
let mut dirs: Vec<String> = files
.iter()
.filter(|p| p.rsplit('/').next().unwrap_or(p) == name)
.map(|p| {
p.rsplit_once('/')
.map(|(d, _)| d.to_string())
.unwrap_or_default()
})
.collect();
dirs.sort();
dirs.dedup();
dirs
}
fn join_rel(dir: &str, name: &str) -> String {
if dir.is_empty() {
name.to_string()
} else {
format!("{dir}/{name}")
}
}
pub fn declared_manager(package_json: &str) -> Option<Manager> {
let key = "\"packageManager\"";
let mut hits = package_json.match_indices(key);
let (at, _) = hits.next()?;
if hits.next().is_some() {
return None;
}
let rest = package_json[at + key.len()..].trim_start();
let rest = rest.strip_prefix(':')?.trim_start();
let rest = rest.strip_prefix('"')?;
let value = &rest[..rest.find('"')?];
let name = value.split('@').next().unwrap_or(value);
Manager::ALL.into_iter().find(|m| m.tool() == name)
}
pub fn units(files: &[String], snapshot: &Path) -> Result<Vec<Unit>, String> {
let mut found: Vec<(String, Manager, &'static str)> = Vec::new();
for m in Manager::ALL {
for lock in m.lockfiles() {
found.extend(
lockfile_dirs_in(files, lock)
.into_iter()
.map(|dir| (dir, m, *lock)),
);
}
}
let mut dirs: Vec<String> = found.iter().map(|f| f.0.clone()).collect();
dirs.sort();
dirs.dedup();
let mut out = Vec::new();
for dir in dirs {
let here: Vec<&(String, Manager, &'static str)> =
found.iter().filter(|f| f.0 == dir).collect();
let (manager, lockfile) = if here.iter().all(|f| f.1 == here[0].1) {
(here[0].1, here[0].2)
} else {
let manifest = snapshot.join(join_rel(&dir, "package.json"));
let body = std::fs::read_to_string(&manifest).unwrap_or_default();
declared_manager(&body)
.and_then(|m| here.iter().find(|f| f.1 == m))
.map(|f| (f.1, f.2))
.ok_or_else(|| {
let names: Vec<&str> = here.iter().map(|f| f.2).collect();
format!(
"both {} in {} and no `packageManager` to choose — set \
greengate.snapshotPrepare",
names.join(" and "),
if dir.is_empty() { "the root" } else { &dir }
)
})?
};
let standalone =
manager == Manager::Pnpm && !files.contains(&join_rel(&dir, "pnpm-workspace.yaml"));
let berry = manager == Manager::Yarn
&& std::fs::read_to_string(snapshot.join(join_rel(&dir, lockfile)))
.map(|t| is_berry_lock(&t))
.unwrap_or(false);
out.push(Unit {
dir,
manager,
lockfile,
standalone,
berry,
});
}
Ok(out)
}
fn bun_refusal(u: &Unit) -> String {
format!(
"{} in {}: {BIN} cannot install bun dependencies — set greengate.snapshotPrepare \
to the install command, or greengate.snapshotDeps off",
u.lockfile,
unit_label(u)
)
}
fn unit_label(u: &Unit) -> String {
if u.dir.is_empty() {
"the root".to_string()
} else {
format!("{}/", u.dir)
}
}
fn manager_cmd(u: &Unit, at: &Path, args: &[&str]) -> Command {
let mut cmd = Command::new(crate::hooks::common::program(u.manager.tool()));
cmd.args(args).current_dir(at).stdin(Stdio::null());
if u.manager == Manager::Pnpm {
cmd.arg("--config.confirmModulesPurge=false");
if u.standalone {
cmd.arg("--ignore-workspace");
}
}
crate::hooks::common::strip_git_env(&mut cmd);
cmd.env(crate::pushed_tree::SNAPSHOT_ENV, "1");
cmd
}
fn quiet(settings: &crate::config::Settings, mut cmd: Command) -> Result<String, String> {
match crate::hooks::common::capture_within(settings, &mut cmd) {
Some((crate::hooks::common::Ran::Status(s), text)) if s.success() => Ok(text),
Some((_, text)) => Err(text),
None => Err("could not start".to_string()),
}
}
fn last_line(text: &str) -> String {
text.lines()
.map(str::trim)
.rfind(|l| !l.is_empty())
.unwrap_or("no output")
.chars()
.take(200)
.collect()
}
fn install(settings: &crate::config::Settings, u: &Unit, at: &Path) -> Result<(), String> {
let args: &[&str] = match u.manager {
Manager::Npm => &["ci", "--no-audit", "--no-fund", "--prefer-offline"],
Manager::Pnpm => &["install", "--frozen-lockfile", "--prefer-offline"],
Manager::Yarn if u.berry => &["install", "--immutable"],
Manager::Yarn => &[
"install",
"--frozen-lockfile",
"--non-interactive",
"--prefer-offline",
],
Manager::Bun => return Err(bun_refusal(u)),
};
let mut cmd = manager_cmd(u, at, args);
let what = format!("{} {}", u.manager.tool(), args[0]);
if crate::hooks::common::bounded_success(settings, &mut cmd, &what) {
Ok(())
} else {
Err(format!("{what} failed in {}", unit_label(u)))
}
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
const CROSS_VOLUME_HINT: &str = "the snapshot's temp dir is on another volume than the working \
tree; set TMPDIR to a directory on that volume";
#[cfg(any(target_os = "macos", target_os = "linux"))]
const NO_CLONE_HINT: &str = "this filesystem cannot clone; \
`git config greengate.snapshotDeps install` skips the attempt";
fn clone_dir(src: &Path, dst: &Path) -> Result<(), String> {
use std::io::ErrorKind;
let (ours, outcome) = match std::fs::symlink_metadata(dst) {
Ok(_) => (false, Err(std::io::Error::from(ErrorKind::AlreadyExists))),
Err(e) if e.kind() == ErrorKind::NotFound => (true, clone_tree(src, dst)),
Err(e) => (false, Err(e)),
};
match outcome {
Ok(()) => Ok(()),
Err(e) => {
let mut why = e.to_string();
if ours && e.kind() != ErrorKind::AlreadyExists {
if let Err(rm) = std::fs::remove_dir_all(dst) {
if rm.kind() != ErrorKind::NotFound {
why.push_str(&format!(
", and the partial clone could not be removed: {rm}"
));
}
}
}
Err(format!(
"no copy-on-write clone of {} ({why})",
src.display()
))
}
}
}
#[cfg(target_os = "macos")]
fn clone_tree(src: &Path, dst: &Path) -> std::io::Result<()> {
use std::ffi::CString;
use std::os::unix::ffi::OsStrExt;
const CLONE_NOFOLLOW: u32 = 0x0001;
const EXDEV: i32 = 18;
const ENOTSUP: i32 = 45;
extern "C" {
fn clonefile(
src: *const std::os::raw::c_char,
dst: *const std::os::raw::c_char,
flags: u32,
) -> std::os::raw::c_int;
}
let to_c = |p: &Path| {
CString::new(p.as_os_str().as_bytes()).map_err(|_| {
std::io::Error::new(std::io::ErrorKind::InvalidInput, "path contains a NUL byte")
})
};
let (from, to) = (to_c(src)?, to_c(dst)?);
let rc = unsafe { clonefile(from.as_ptr(), to.as_ptr(), CLONE_NOFOLLOW) };
if rc == 0 {
return Ok(());
}
let err = std::io::Error::last_os_error();
Err(match err.raw_os_error() {
Some(EXDEV) => std::io::Error::other(CROSS_VOLUME_HINT),
Some(ENOTSUP) => std::io::Error::other(NO_CLONE_HINT),
_ => err,
})
}
#[cfg(target_os = "linux")]
fn clone_tree(src: &Path, dst: &Path) -> std::io::Result<()> {
let cp = ["/bin/cp", "/usr/bin/cp"]
.into_iter()
.find(|p| Path::new(p).exists())
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no cp found"))?;
std::fs::create_dir(dst).map_err(|err| {
std::io::Error::new(
err.kind(),
format!("cannot create {}: {err}", dst.display()),
)
})?;
let out = Command::new(cp)
.args([
"-R",
"-T",
"--reflink=always",
"--preserve=mode,timestamps",
"--no-dereference",
])
.arg(src)
.arg(dst)
.env("LC_ALL", "C")
.stdin(Stdio::null())
.stdout(Stdio::null())
.output()?;
if out.status.success() {
return Ok(());
}
let stderr = String::from_utf8_lossy(&out.stderr);
let mut lines = stderr.lines().map(str::trim).filter(|l| !l.is_empty());
let first = lines.next().unwrap_or("cp failed with no output");
let more = lines.count();
let lower = first.to_lowercase();
Err(std::io::Error::other(if lower.contains("cross-device") {
CROSS_VOLUME_HINT.to_string()
} else if lower.contains("not supported") || lower.contains("inappropriate ioctl") {
NO_CLONE_HINT.to_string()
} else if more == 0 {
first.to_string()
} else {
format!("{first} (and {more} more)")
}))
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn clone_tree(_src: &Path, _dst: &Path) -> std::io::Result<()> {
Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
}
fn normalize(p: &Path) -> PathBuf {
let mut out = PathBuf::new();
for c in p.components() {
match c {
Component::ParentDir => {
out.pop();
}
Component::CurDir => {}
other => out.push(other.as_os_str()),
}
}
out
}
fn first_link(dir: &Path, bad: &dyn Fn(&Path, &Path) -> bool) -> std::io::Result<Option<PathBuf>> {
let mut stack = vec![dir.to_path_buf()];
while let Some(at) = stack.pop() {
for entry in std::fs::read_dir(&at)? {
let entry = entry?;
let kind = entry.file_type()?;
let path = entry.path();
if kind.is_symlink() {
let target = std::fs::read_link(&path)?;
let resolved = if target.is_absolute() {
normalize(&target)
} else {
normalize(&at.join(target))
};
if bad(&path, &resolved) {
return Ok(Some(path));
}
} else if kind.is_dir() {
stack.push(path);
}
}
}
Ok(None)
}
fn link_into(dir: &Path, sources: &[PathBuf]) -> std::io::Result<Option<PathBuf>> {
first_link(dir, &|path, resolved| {
let real = path.canonicalize().ok();
sources
.iter()
.any(|s| resolved.starts_with(s) || real.as_ref().is_some_and(|r| r.starts_with(s)))
})
}
fn link_outside(dir: &Path, roots: &[PathBuf]) -> std::io::Result<Option<PathBuf>> {
first_link(dir, &|_, resolved| {
!roots.iter().any(|root| resolved.starts_with(root))
})
}
fn skipped_file(skip: &[&str], root: &Path, parent: &Path, name: &str) -> bool {
skip.iter().any(|pattern| {
if let Some(top) = pattern.strip_prefix("./") {
parent == root && name == top
} else if let Some(prefix) = pattern.strip_suffix('*') {
name.starts_with(prefix)
} else if let Some((dir, file)) = pattern.split_once('/') {
name == file && parent.file_name().is_some_and(|d| d == dir)
} else {
name == *pattern
}
})
}
fn newer_than(
nm: &Path,
record: std::time::SystemTime,
skip_files: &[&str],
) -> std::io::Result<Option<PathBuf>> {
if !nm.is_dir() {
return Ok(None);
}
let mut stack = vec![nm.to_path_buf()];
while let Some(at) = stack.pop() {
for entry in std::fs::read_dir(&at)? {
let entry = entry?;
let name = entry.file_name();
let name = name.to_string_lossy();
let kind = entry.file_type()?;
if kind.is_dir() {
if name == ".bin" || name == ".cache" || name.starts_with(".vite") {
continue;
}
stack.push(entry.path());
} else if kind.is_file() {
if skipped_file(skip_files, nm, &at, &name) {
continue;
}
if entry.metadata()?.modified()? > record {
return Ok(Some(entry.path()));
}
}
}
}
Ok(None)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Voucher {
Pnpm,
Npm,
}
impl Voucher {
fn of(u: &Unit) -> Result<Voucher, String> {
match u.manager {
Manager::Pnpm => Ok(Voucher::Pnpm),
Manager::Npm => Ok(Voucher::Npm),
Manager::Yarn if u.berry => Err("yarn cannot check an installed tree against its \
lockfile, so yarn snapshots always install"
.to_string()),
Manager::Yarn => Err(
"yarn's own checks accept a tree with a package missing, so \
yarn snapshots always install"
.to_string(),
),
Manager::Bun => Err(bun_refusal(u)),
}
}
fn tool(self) -> &'static str {
match self {
Voucher::Pnpm => "pnpm",
Voucher::Npm => "npm",
}
}
fn record(self) -> &'static str {
match self {
Voucher::Pnpm => ".modules.yaml",
Voucher::Npm => ".package-lock.json",
}
}
fn skip_files(self, scope: Scope) -> &'static [&'static str] {
match (self, scope) {
(Voucher::Pnpm, _) => &[".modules.yaml", ".pnpm-workspace-state*", ".pnpm/lock.yaml"],
(Voucher::Npm, Scope::Root) => &["./.package-lock.json"],
(Voucher::Npm, Scope::Member) => &[],
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Scope {
Root,
Member,
}
impl Scope {
fn of(m: &str) -> Scope {
if m.is_empty() {
Scope::Root
} else {
Scope::Member
}
}
}
struct Captured {
status: std::process::ExitStatus,
stdout: String,
stderr: String,
}
enum CaptureFailure {
TimedOut,
Spawn(std::io::Error),
}
impl CaptureFailure {
fn describe(&self, what: &str) -> String {
match self {
CaptureFailure::TimedOut => format!("{what} timed out"),
CaptureFailure::Spawn(e) => format!("{what} could not start: {e}"),
}
}
}
fn capture_apart(
settings: &crate::config::Settings,
cmd: &mut Command,
) -> Result<Captured, CaptureFailure> {
let out = crate::hooks::common::capture_stdout_within(settings, cmd)
.map_err(CaptureFailure::Spawn)?;
match out.ran {
crate::hooks::common::Ran::Status(status) => Ok(Captured {
status,
stdout: out.stdout,
stderr: out.stderr,
}),
crate::hooks::common::Ran::TimedOut(_) => Err(CaptureFailure::TimedOut),
}
}
fn unlinked_file(text: &str) -> std::io::Result<std::fs::File> {
use std::io::{Seek, Write};
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let path = std::env::temp_dir().join(format!(
"greengate-npm-{}-{}-{nanos}.json",
std::process::id(),
COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
let mut options = std::fs::OpenOptions::new();
options.read(true).write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
let mut file = options.open(&path)?;
let written = file.write_all(text.as_bytes()).and_then(|()| file.rewind());
let removed = std::fs::remove_file(&path);
written?;
removed?;
Ok(file)
}
fn parse_counts(text: &str) -> Option<[usize; 3]> {
let mut lines = text.lines().filter_map(|l| l.strip_prefix("counts="));
let line = lines.next()?;
if lines.next().is_some() {
return None;
}
let numbers: Vec<usize> = line
.split_whitespace()
.map(|n| n.parse().ok())
.collect::<Option<_>>()?;
numbers.try_into().ok()
}
fn node_reads(
settings: &crate::config::Settings,
u: &Unit,
json: &str,
script: &str,
) -> Result<String, String> {
let tool = u.manager.tool();
let file = unlinked_file(json)
.map_err(|e| format!("could not write {tool}'s output for node: {e}"))?;
let mut cmd = Command::new(crate::hooks::common::program("node"));
cmd.arg("-e")
.arg(script)
.current_dir(std::env::temp_dir())
.env_remove("NODE_OPTIONS")
.stdin(Stdio::from(file));
crate::hooks::common::strip_git_env(&mut cmd);
let out = match capture_apart(settings, &mut cmd) {
Ok(out) => out,
Err(CaptureFailure::Spawn(e)) if e.kind() == std::io::ErrorKind::NotFound => {
return Err(format!(
"node not found on PATH (needed to read {tool}'s output); put node on PATH, \
or git config greengate.snapshotDeps install"
));
}
Err(CaptureFailure::Spawn(e)) => {
return Err(format!("could not start node to read {tool}'s output: {e}"));
}
Err(CaptureFailure::TimedOut) => {
return Err(format!("node timed out reading {tool}'s output"));
}
};
if !out.status.success() {
let exited = out
.status
.code()
.map_or_else(|| "on a signal".to_string(), |c| c.to_string());
return Err(format!(
"could not read {tool}'s output (node exited {exited}): {}",
last_line(&out.stderr)
));
}
Ok(out.stdout)
}
const NPM_QUERY_SCRIPT: &str = r#"
const text = require('fs').readFileSync(0, 'utf8');
const start = text.indexOf('[');
if (start < 0) throw new Error('no JSON array in npm query output');
const found = JSON.parse(text.slice(start));
if (!Array.isArray(found)) throw new Error('npm query did not print an array');
for (const workspace of found) console.log(String(workspace.location));
"#;
const NPM_DRY_RUN_SCRIPT: &str = r#"
const text = require('fs').readFileSync(0, 'utf8');
const start = text.indexOf('{');
if (start < 0) throw new Error('no JSON object in npm output');
const report = JSON.parse(text.slice(start));
if (report.error) {
const why = report.error.summary || report.error.code || 'unknown error';
console.log('error=' + String(why).replace(/\s+/g, ' '));
} else {
for (const key of ['add', 'remove', 'change']) {
if (!Array.isArray(report[key])) throw new Error('npm printed no ' + key + ' list');
}
const named = (entry) => {
const pkg = (entry && (entry.to || entry.from || entry)) || {};
return (pkg.name || '?') + '@' + (pkg.version || '?');
};
console.log('counts=' + report.add.length + ' ' + report.remove.length + ' ' + report.change.length);
const first = [...report.add, ...report.remove, ...report.change][0];
if (first) console.log('first=' + named(first));
}
"#;
fn members(
settings: &crate::config::Settings,
u: &Unit,
at: &Path,
voucher: Voucher,
) -> Result<Vec<String>, String> {
match voucher {
Voucher::Pnpm => {
if u.standalone {
return Ok(Vec::new());
}
let text = quiet(
settings,
manager_cmd(u, at, &["ls", "-r", "--depth", "-1", "--parseable"]),
)
.map_err(|t| format!("pnpm could not list the workspace: {}", last_line(&t)))?;
let root = normalize(at);
let canon = at.canonicalize().unwrap_or_else(|_| root.clone());
Ok(text
.lines()
.filter_map(|l| {
let p = PathBuf::from(l.trim());
let rel = p
.strip_prefix(&root)
.or_else(|_| p.strip_prefix(&canon))
.ok()?;
let rel = rel.to_string_lossy().replace('\\', "/");
(!rel.is_empty()).then_some(rel)
})
.collect())
}
Voucher::Npm => {
let what = "npm query .workspace";
let out = capture_apart(
settings,
&mut manager_cmd(
u,
at,
&["query", ".workspace", "--offline", "--no-update-notifier"],
),
)
.map_err(|e| e.describe(what))?;
if !out.status.success() {
return Err(format!(
"npm could not list the workspace ({}): {}",
out.status,
last_line(&out.stderr)
));
}
if out.stdout.trim().is_empty() {
return Err(format!(
"npm could not list the workspace: {what} printed nothing ({})",
last_line(&out.stderr)
));
}
let lines = node_reads(settings, u, &out.stdout, NPM_QUERY_SCRIPT)?;
let mut found = Vec::new();
for line in lines.lines().map(|l| l.trim().replace('\\', "/")) {
let outside = Path::new(&line).is_absolute()
|| Path::new(&line)
.components()
.any(|c| matches!(c, Component::ParentDir));
if outside {
return Err(format!("npm listed a workspace outside the unit: {line}"));
}
if !line.is_empty() && line != "." {
found.push(line);
}
}
Ok(found)
}
}
}
fn pnpm_layout_problem(nm: &Path, is_root: bool) -> Option<String> {
if is_root {
let modules = std::fs::read_to_string(nm.join(".modules.yaml")).unwrap_or_default();
let isolated = modules
.lines()
.any(|l| l.contains("nodeLinker") && l.contains("isolated"));
if !isolated {
return Some("not installed with pnpm's isolated linker".to_string());
}
}
let entries = std::fs::read_dir(nm).ok()?;
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
if name.starts_with('.') {
continue;
}
let kind = e.file_type().ok()?;
if kind.is_symlink() {
continue;
}
if name.starts_with('@') && kind.is_dir() {
for inner in std::fs::read_dir(e.path()).ok()?.flatten() {
if !inner.file_type().map(|k| k.is_symlink()).unwrap_or(false) {
return Some(format!(
"{} is not a link pnpm made",
inner.path().display()
));
}
}
continue;
}
return Some(format!("{} is not a link pnpm made", e.path().display()));
}
None
}
fn npm_vouch(
settings: &crate::config::Settings,
u: &Unit,
snap_dir: &Path,
members: &[String],
) -> Result<(), String> {
for member in members {
let hidden = snap_dir
.join(member)
.join("node_modules")
.join(".package-lock.json");
match std::fs::remove_file(&hidden) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(format!("could not remove {}: {e}", hidden.display())),
}
}
let lock_path = snap_dir.join(u.lockfile);
let before = std::fs::read(&lock_path).map_err(|e| format!("{}: {e}", u.lockfile))?;
let what = "npm install --dry-run";
let mut cmd = manager_cmd(
u,
snap_dir,
&[
"install",
"--dry-run",
"--offline",
"--ignore-scripts",
"--json",
"--no-audit",
"--no-fund",
"--no-update-notifier",
],
);
let captured = capture_apart(settings, &mut cmd);
if std::fs::read(&lock_path).ok().as_deref() != Some(before.as_slice()) {
let restored = match std::fs::write(&lock_path, &before) {
Ok(()) => String::new(),
Err(e) => format!(" (and {} could not be restored: {e})", u.lockfile),
};
return Err(format!("{} would change{restored}", u.lockfile));
}
let out = captured.map_err(|e| e.describe(what))?;
npm_verdict(settings, u, &out, what)
}
fn npm_verdict(
settings: &crate::config::Settings,
u: &Unit,
out: &Captured,
what: &str,
) -> Result<(), String> {
let read = |json: &str| node_reads(settings, u, json, NPM_DRY_RUN_SCRIPT);
if !out.status.success() {
if out.stdout.contains('{') {
if let Ok(text) = read(&out.stdout) {
if let Some(summary) = text.lines().find_map(|l| l.strip_prefix("error=")) {
return Err(format!("npm failed: {summary}"));
}
}
}
let code = out
.status
.code()
.map_or_else(|| out.status.to_string(), |c| c.to_string());
return Err(format!("{what} exited {code}: {}", last_line(&out.stderr)));
}
if out.stdout.trim().is_empty() {
return Err(format!(
"{what} printed nothing on stdout ({})",
last_line(&out.stderr)
));
}
let text = read(&out.stdout)?;
if let Some(summary) = text.lines().find_map(|l| l.strip_prefix("error=")) {
return Err(format!("npm failed: {summary}"));
}
let Some([add, remove, change]) = parse_counts(&text) else {
return Err(format!("{what} printed no add/remove/change counts"));
};
if add + remove + change > 0 {
let first = text
.lines()
.find_map(|l| l.strip_prefix("first="))
.unwrap_or("?");
return Err(format!(
"npm would add {add}, remove {remove}, change {change}: {first}"
));
}
Ok(())
}
fn reuse(
settings: &crate::config::Settings,
u: &Unit,
source: &Path,
snapshot: &Path,
unit_dirs: &[String],
) -> Result<(), String> {
let voucher = Voucher::of(u)?;
let tool = voucher.tool();
let src_dir = source.join(&u.dir);
let snap_dir = snapshot.join(&u.dir);
let lock = u.lockfile;
let src_lock = std::fs::read(src_dir.join(lock))
.map_err(|_| "no lockfile in the working tree".to_string())?;
let snap_lock = std::fs::read(snap_dir.join(lock)).map_err(|e| format!("{lock}: {e}"))?;
if src_lock != snap_lock {
return Err("the working tree's lockfile differs from the commit's".to_string());
}
if !src_dir.join("node_modules").is_dir() {
return Err("nothing installed in the working tree".to_string());
}
let mut set = vec![String::new()];
for m in members(settings, u, &snap_dir, voucher)? {
let repo_rel = join_rel(&u.dir, &m);
if unit_dirs.contains(&repo_rel) {
continue;
}
if src_dir.join(&m).join("node_modules").is_dir() {
set.push(m);
}
}
let record_path = format!("node_modules/{}", voucher.record());
let record = std::fs::metadata(src_dir.join(&record_path))
.and_then(|m| m.modified())
.map_err(|_| format!("no {tool} install record ({record_path})"))?;
for m in &set {
match newer_than(
&src_dir.join(m).join("node_modules"),
record,
voucher.skip_files(Scope::of(m)),
) {
Ok(None) => {}
Ok(Some(f)) => {
let shown = f.strip_prefix(source).unwrap_or(&f);
return Err(format!(
"{} changed after the install — an in-place edit {tool} does not check",
shown.display()
));
}
Err(e) => return Err(format!("could not inspect the working tree's install: {e}")),
}
}
let mut cloned: Vec<PathBuf> = Vec::new();
let rollback = |cloned: &[PathBuf]| -> String {
let mut left = Vec::new();
for dir in cloned {
if let Err(err) = std::fs::remove_dir_all(dir) {
if err.kind() != std::io::ErrorKind::NotFound {
left.push(format!("{}: {err}", dir.display()));
}
}
}
if left.is_empty() {
String::new()
} else {
format!(
"; could not remove the clone, so the install may run over it (remove it by hand): {}",
left.join(", ")
)
}
};
let sources = [
normalize(source),
source.canonicalize().unwrap_or_else(|_| normalize(source)),
];
let roots = [
normalize(snapshot),
snapshot
.canonicalize()
.unwrap_or_else(|_| normalize(snapshot)),
];
for m in &set {
let from = src_dir.join(m).join("node_modules");
let to = snap_dir.join(m).join("node_modules");
if std::fs::symlink_metadata(&to).is_ok() {
let left = rollback(&cloned);
return Err(format!(
"{} already exists in the snapshot{left}",
to.display()
));
}
if let Err(e) = clone_dir(&from, &to) {
let left = rollback(&cloned);
return Err(format!("{e}{left}"));
}
cloned.push(to.clone());
let problem = match link_into(&to, &sources) {
Ok(Some(link)) => Some(format!(
"{} links back into the working tree",
link.display()
)),
Ok(None) => match voucher {
Voucher::Pnpm => pnpm_layout_problem(&to, m.is_empty()),
Voucher::Npm => match link_outside(&to, &roots) {
Ok(Some(link)) => {
Some(format!("{} links outside the snapshot", link.display()))
}
Ok(None) => None,
Err(e) => Some(format!("could not inspect the clone: {e}")),
},
},
Err(e) => Some(format!("could not inspect the clone: {e}")),
};
if let Some(why) = problem {
let left = rollback(&cloned);
return Err(format!("{why}{left}"));
}
}
let vouched = match voucher {
Voucher::Pnpm => pnpm_vouch(settings, u, &snap_dir),
Voucher::Npm => {
println!(
"snapshot: checking node_modules in {} with npm",
unit_label(u)
);
npm_vouch(settings, u, &snap_dir, &set)
}
};
if let Err(why) = vouched {
let left = rollback(&cloned);
return Err(format!("{why}{left}"));
}
Ok(())
}
fn pnpm_vouch(settings: &crate::config::Settings, u: &Unit, snap_dir: &Path) -> Result<(), String> {
if let Ok(rd) = std::fs::read_dir(snap_dir.join("node_modules")) {
for e in rd.flatten() {
if e.file_name()
.to_string_lossy()
.starts_with(".pnpm-workspace-state")
{
let _ = std::fs::remove_file(e.path());
}
}
}
quiet(
settings,
manager_cmd(u, snap_dir, &["install", "--frozen-lockfile", "--offline"]),
)
.map(|_| ())
.map_err(|text| format!("pnpm did not accept the clone ({})", last_line(&text)))
}
pub fn changed_since_upstream(source: &Path, tip: &str) -> Option<Vec<String>> {
let git = |args: &[&str]| -> Option<Vec<u8>> {
let mut cmd = Command::new("git");
cmd.arg("-C")
.arg(source)
.args(args)
.stdin(Stdio::null())
.stderr(Stdio::null());
crate::hooks::common::strip_git_env(&mut cmd);
let out = cmd.output().ok()?;
out.status.success().then_some(out.stdout)
};
let base = git(&["merge-base", tip, "@{upstream}"])?;
let base = String::from_utf8_lossy(&base).trim().to_string();
if base.is_empty() {
return None;
}
let raw = git(&["diff", "--name-only", "-z", &base, tip])?;
Some(crate::git::split_nul_paths(&raw))
}
pub fn select_units(units: Vec<Unit>, changed: Option<&[String]>) -> (Vec<Unit>, Vec<Unit>) {
let Some(changed) = changed else {
return (units, Vec::new());
};
let nearest = |f: &str| -> Option<&str> {
units
.iter()
.map(|u| u.dir.as_str())
.filter(|d| d.is_empty() || f.starts_with(&format!("{d}/")))
.max_by_key(|d| d.len())
};
let touched: Vec<&str> = changed.iter().filter_map(|f| nearest(f)).collect();
let (kept, skipped): (Vec<Unit>, Vec<Unit>) = units
.clone()
.into_iter()
.partition(|u| u.dir.is_empty() || touched.contains(&u.dir.as_str()));
(kept, skipped)
}
pub fn deps(
settings: &crate::config::Settings,
mode: DepsMode,
source: &Path,
snapshot: &Path,
files: &[String],
changed: Option<&[String]>,
) -> Result<(), String> {
if mode == DepsMode::Off {
return Ok(());
}
let all = units(files, snapshot)?;
let unit_dirs: Vec<String> = all.iter().map(|u| u.dir.clone()).collect();
let (units, skipped) = select_units(all, changed);
if !skipped.is_empty() {
let names: Vec<String> = skipped.iter().map(unit_label).collect();
println!(
"snapshot: not preparing {} — the push changes nothing there",
names.join(", ")
);
}
for u in &units {
let at = snapshot.join(&u.dir);
let label = unit_label(u);
if u.manager == Manager::Bun {
return Err(bun_refusal(u));
}
if mode == DepsMode::Reuse {
match reuse(settings, u, source, snapshot, &unit_dirs) {
Ok(()) => {
println!(
"snapshot: node_modules in {label} reused from the working tree — {} \
accepted it against the lockfile \
(copy-on-write clone, shares disk with the working tree)",
u.manager.tool()
);
continue;
}
Err(why) => println!(
"snapshot: {} in {label} — not reusing the working tree's install: {why}",
highlight(&format!("{} {}", u.manager.tool(), install_verb(u)))
),
}
} else {
println!(
"snapshot: {} in {label}",
highlight(&format!("{} {}", u.manager.tool(), install_verb(u)))
);
}
install(settings, u, &at)?;
}
Ok(())
}
fn install_verb(u: &Unit) -> &'static str {
match u.manager {
Manager::Npm => "ci",
Manager::Pnpm => "install --frozen-lockfile",
Manager::Yarn if u.berry => "install --immutable",
Manager::Yarn => "install --frozen-lockfile",
Manager::Bun => "install",
}
}
pub fn run(
settings: &crate::config::Settings,
source: &Path,
snapshot: &Path,
tip: &str,
command_owns_deps: bool,
) -> Result<(), String> {
let entries = carry_list(settings);
let mode = if command_owns_deps {
DepsMode::Off
} else {
deps_mode(settings)
};
if entries.is_empty() && mode == DepsMode::Off {
return Ok(());
}
let files = snapshot_files(snapshot)?;
if !entries.is_empty() {
carry(&entries, source, snapshot, &files)?;
}
let changed = if mode == DepsMode::Off {
None
} else {
changed_since_upstream(source, tip)
};
deps(settings, mode, source, snapshot, &files, changed.as_deref()).map_err(|e| {
println!("{} {e}", warning_sign());
e
})
}
#[cfg(test)]
mod tests {
use super::*;
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
#[test]
fn clone_dir_refuses_an_existing_destination() {
let scratch = std::env::temp_dir().join(format!("clone-exist-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&scratch); std::fs::create_dir_all(scratch.join("src")).unwrap();
std::fs::create_dir_all(scratch.join("dst")).unwrap();
std::fs::write(scratch.join("dst/keep"), "mine").unwrap();
let err = clone_dir(&scratch.join("src"), &scratch.join("dst")).unwrap_err();
assert!(err.starts_with("no copy-on-write clone of "), "{err}");
assert_eq!(
std::fs::read_to_string(scratch.join("dst/keep")).unwrap(),
"mine"
);
assert_eq!(std::fs::read_dir(scratch.join("dst")).unwrap().count(), 1);
let _ = std::fs::remove_dir_all(&scratch); }
#[cfg(target_os = "macos")]
#[test]
fn clone_dir_keeps_odd_names_and_relative_symlinks() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
const EILSEQ: i32 = 92;
let scratch = std::env::temp_dir().join(format!("clone-tree-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&scratch); std::fs::create_dir_all(scratch.join("src/sub")).unwrap();
let mut odd = OsStr::from_bytes(b"caf\xe9");
match std::fs::write(scratch.join("src/sub").join(odd), "odd") {
Ok(()) => eprintln!("clone test: a non-UTF-8 file name"),
Err(e) if e.raw_os_error() == Some(EILSEQ) => {
eprintln!("clone test: this volume refuses non-UTF-8 names; non-ASCII UTF-8 used");
odd = OsStr::new("caf\u{e9}");
std::fs::write(scratch.join("src/sub").join(odd), "odd").unwrap();
}
Err(e) => panic!("fixture could not be written: {e}"),
}
std::os::unix::fs::symlink("sub", scratch.join("src/link")).unwrap();
clone_dir(&scratch.join("src"), &scratch.join("dst")).unwrap();
assert_eq!(
std::fs::read(scratch.join("dst/sub").join(odd)).unwrap(),
b"odd"
);
assert_eq!(
std::fs::read_link(scratch.join("dst/link")).unwrap(),
Path::new("sub")
);
let _ = std::fs::remove_dir_all(&scratch); }
#[cfg(target_os = "linux")]
#[test]
fn clone_dir_refuses_a_filesystem_without_reflinks() {
let shm = Path::new("/dev/shm");
if !shm.is_dir() {
assert!(
std::env::var_os("CI").is_none(),
"no /dev/shm on a CI runner: the refusal has no tmpfs to be proven on"
);
eprintln!("no /dev/shm here: the refusal test has no tmpfs to run on");
return;
}
let scratch = shm.join(format!("clone-tmpfs-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&scratch); std::fs::create_dir_all(scratch.join("src")).unwrap();
for i in 0..20 {
std::fs::write(scratch.join(format!("src/f{i}")), "data").unwrap();
}
let err = clone_dir(&scratch.join("src"), &scratch.join("dst")).unwrap_err();
assert!(err.starts_with("no copy-on-write clone of "), "{err}");
assert!(
!err.contains('\n'),
"one line, not cp's whole stderr: {err}"
);
assert!(
!scratch.join("dst").exists(),
"a refused clone left a destination"
);
let _ = std::fs::remove_dir_all(&scratch); }
#[test]
fn lexical_refusals() {
for bad in [
"",
"/etc/hosts",
"\\x",
"C:/x",
"a//b",
".",
"..",
"a/../b",
".git/config",
"x/.GIT/y",
] {
assert!(lexical_problem(bad).is_some(), "{bad:?} must be refused");
}
for good in [".env", "config/local.json", ".npmrc", "a.b/c"] {
assert!(lexical_problem(good).is_none(), "{good:?} must pass");
}
}
#[test]
fn a_tracked_path_inside_above_or_equal_collides() {
let files = s(&["src/a.ts", "vendor", "README.md"]);
assert!(tracked_collision("src", &files).is_some());
assert!(tracked_collision("src/a.ts", &files).is_some());
assert!(tracked_collision("vendor/x", &files).is_some());
assert!(tracked_collision(".env", &files).is_none());
assert!(tracked_collision("sr", &files).is_none());
}
#[test]
fn lockfile_dirs_come_from_the_list_given() {
let files = s(&[
"package-lock.json",
"web/package-lock.json",
"web/x/pnpm-lock.yaml",
"notpackage-lock.json",
]);
assert_eq!(
lockfile_dirs_in(&files, "package-lock.json"),
s(&["", "web"])
);
assert_eq!(lockfile_dirs_in(&files, "pnpm-lock.yaml"), s(&["web/x"]));
}
#[test]
fn package_manager_field_is_read_narrowly() {
assert_eq!(
declared_manager(r#"{"packageManager": "pnpm@10.1.0"}"#),
Some(Manager::Pnpm)
);
assert_eq!(
declared_manager(r#"{"packageManager":"npm@11"}"#),
Some(Manager::Npm)
);
assert_eq!(
declared_manager(r#"{"packageManager":"yarn@4"}"#),
Some(Manager::Yarn)
);
assert_eq!(
declared_manager(r#"{"packageManager":"bun@1.2.0"}"#),
Some(Manager::Bun)
);
assert_eq!(
declared_manager(r#"{"packageManager":"yarnpkg@1"}"#),
None,
"a name, not a prefix"
);
assert_eq!(declared_manager(r#"{"name":"x"}"#), None);
assert_eq!(
declared_manager(r#"{"packageManager":"npm@1","x":{"packageManager":"pnpm@1"}}"#),
None,
"two answers is no answer"
);
}
fn unit(dir: &str) -> Unit {
Unit {
dir: dir.to_string(),
manager: Manager::Pnpm,
lockfile: "pnpm-lock.yaml",
standalone: !dir.is_empty(),
berry: false,
}
}
#[test]
fn a_berry_lockfile_is_told_by_its_metadata_block() {
assert!(is_berry_lock(
"# This file is generated by running \"yarn install\" inside your project.\n\n__metadata:\n version: 8\n"
));
assert!(!is_berry_lock(
"# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n# yarn lockfile v1\n\n"
));
assert!(!is_berry_lock(""));
}
#[test]
fn every_manager_lockfile_is_a_unit_and_a_mixed_directory_needs_the_field() {
let d = std::env::temp_dir().join(format!("units-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(d.join("berry")).unwrap();
std::fs::write(d.join("yarn.lock"), "# yarn lockfile v1\n").unwrap();
std::fs::write(d.join("berry/yarn.lock"), "__metadata:\n version: 8\n").unwrap();
let files = s(&[
"yarn.lock",
"berry/yarn.lock",
"old/bun.lockb",
"new/bun.lock",
"mixed/package-lock.json",
"mixed/yarn.lock",
]);
let err = units(&files, &d).unwrap_err();
assert!(
err.contains("both package-lock.json and yarn.lock in mixed"),
"{err}"
);
std::fs::create_dir_all(d.join("mixed")).unwrap();
std::fs::write(
d.join("mixed/package.json"),
r#"{"packageManager":"yarn@1.22.22"}"#,
)
.unwrap();
let got = units(&files, &d).unwrap();
let brief: Vec<(&str, Manager, &str, bool)> = got
.iter()
.map(|u| (u.dir.as_str(), u.manager, u.lockfile, u.berry))
.collect();
assert_eq!(
brief,
vec![
("", Manager::Yarn, "yarn.lock", false),
("berry", Manager::Yarn, "yarn.lock", true),
("mixed", Manager::Yarn, "yarn.lock", false),
("new", Manager::Bun, "bun.lock", false),
("old", Manager::Bun, "bun.lockb", false),
]
);
std::fs::write(
d.join("mixed/package.json"),
r#"{"packageManager":"pnpm@10"}"#,
)
.unwrap();
let err = units(&files, &d).unwrap_err();
assert!(
err.contains("no `packageManager` to choose"),
"a field naming an absent lockfile chooses nothing: {err}"
);
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn only_the_root_and_the_touched_units_are_kept() {
let all = vec![unit(""), unit("spikes/a"), unit("spikes/b"), unit("tools")];
let changed = s(&["src/x.ts", "spikes/b/index.ts", "spikes/bb/y.ts"]);
let (kept, skipped) = select_units(all.clone(), Some(&changed));
let dirs = |v: &[Unit]| v.iter().map(|u| u.dir.clone()).collect::<Vec<_>>();
assert_eq!(
dirs(&kept),
s(&["", "spikes/b"]),
"spikes/bb is not spikes/b"
);
assert_eq!(dirs(&skipped), s(&["spikes/a", "tools"]));
let (kept, skipped) = select_units(all.clone(), None);
assert_eq!(kept.len(), 4, "an unknown range keeps everything");
assert!(skipped.is_empty());
}
#[test]
fn a_nested_unit_claims_its_files_from_the_outer_one() {
let all = vec![unit("web"), unit("web/nested")];
let changed = s(&["web/nested/a.ts"]);
let (kept, _) = select_units(all, Some(&changed));
assert_eq!(kept.len(), 1);
assert_eq!(kept[0].dir, "web/nested");
}
const PNPM_SKIPS: &[&str] = &[".modules.yaml", ".pnpm-workspace-state*", ".pnpm/lock.yaml"];
#[test]
fn a_file_newer_than_the_install_record_is_found() {
let d = std::env::temp_dir().join(format!("newer-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
let pkg = d.join(".pnpm/a@1/node_modules/a");
std::fs::create_dir_all(&pkg).unwrap();
std::fs::create_dir_all(d.join(".bin")).unwrap();
std::fs::create_dir_all(d.join(".cache")).unwrap();
std::fs::write(pkg.join("index.js"), "old").unwrap();
let record = std::time::SystemTime::now();
std::thread::sleep(std::time::Duration::from_millis(20));
for skipped in [".bin/tsc", ".cache/x", ".pnpm/lock.yaml", ".modules.yaml"] {
std::fs::write(d.join(skipped), "new").unwrap();
}
assert_eq!(
newer_than(&d, record, PNPM_SKIPS).unwrap(),
None,
"the install's own writes"
);
std::fs::write(pkg.join("index.js"), "edited").unwrap();
assert_eq!(
newer_than(&d, record, PNPM_SKIPS).unwrap(),
Some(pkg.join("index.js"))
);
let _ = std::fs::remove_dir_all(&d);
}
#[cfg(unix)]
#[test]
fn a_link_outside_the_snapshot_is_refused_and_a_workspace_link_is_not() {
let scratch = std::env::temp_dir().join(format!("outside-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&scratch); let snapshot = scratch.join("snap");
let nm = snapshot.join("node_modules");
std::fs::create_dir_all(snapshot.join("packages/a")).unwrap();
std::fs::create_dir_all(nm.join(".bin")).unwrap();
std::fs::create_dir_all(nm.join("typescript/bin")).unwrap();
let roots = [normalize(&snapshot)];
std::os::unix::fs::symlink("../packages/a", nm.join("a")).unwrap();
std::os::unix::fs::symlink("../typescript/bin/tsc", nm.join(".bin/tsc")).unwrap();
assert_eq!(
link_outside(&nm, &roots).unwrap(),
None,
"relative links that stay inside the snapshot"
);
std::os::unix::fs::symlink("/usr/bin/env", nm.join(".bin/evil")).unwrap();
assert_eq!(
link_outside(&nm, &roots).unwrap(),
Some(nm.join(".bin/evil")),
"an absolute link out, .bin included"
);
std::fs::remove_file(nm.join(".bin/evil")).unwrap();
std::os::unix::fs::symlink("../../outside", nm.join("up")).unwrap();
assert_eq!(link_outside(&nm, &roots).unwrap(), Some(nm.join("up")));
let _ = std::fs::remove_dir_all(&scratch); }
#[test]
fn npms_hidden_lockfile_is_skipped_in_the_root_node_modules_only() {
let scratch = std::env::temp_dir().join(format!("hidden-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&scratch); let nested = scratch.join("a/node_modules");
std::fs::create_dir_all(&nested).unwrap();
let record = std::time::SystemTime::now() - std::time::Duration::from_secs(60);
std::fs::write(scratch.join(".package-lock.json"), "new").unwrap();
let skips = Voucher::Npm.skip_files(Scope::Root);
assert_eq!(newer_than(&scratch, record, skips).unwrap(), None);
std::fs::write(nested.join(".package-lock.json"), "new").unwrap();
assert_eq!(
newer_than(&scratch, record, skips).unwrap(),
Some(nested.join(".package-lock.json"))
);
let _ = std::fs::remove_dir_all(&scratch); }
#[test]
fn counts_are_one_line_of_three_numbers() {
assert_eq!(parse_counts("counts=0 1 2\nfirst=a@1"), Some([0, 1, 2]));
assert_eq!(parse_counts(""), None);
assert_eq!(parse_counts("counts=0 1"), None);
assert_eq!(parse_counts("counts=0 1 2 3"), None);
assert_eq!(parse_counts("counts=0 x 2"), None);
assert_eq!(parse_counts("counts=0 0 0\ncounts=0 0 0"), None);
}
#[test]
fn normalize_folds_dots_lexically() {
assert_eq!(
normalize(Path::new("/a/b/../c/./d")),
PathBuf::from("/a/c/d")
);
}
}