1use 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 = "amont.snapshotCarry";
44const DEPS: &str = "amont.snapshotDeps";
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum DepsMode {
49 Install,
52 Reuse,
54 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
66pub 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
78pub 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
99struct Carried {
105 entry: String,
106 src: PathBuf,
107 dst: PathBuf,
108}
109
110fn 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
134fn 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
153fn 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
167fn 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
198pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321pub enum Manager {
322 Npm,
323 Pnpm,
324 Yarn,
325 Bun,
329}
330
331impl Manager {
332 const ALL: [Manager; 4] = [Manager::Npm, Manager::Pnpm, Manager::Yarn, Manager::Bun];
333
334 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
376pub struct Unit {
377 pub dir: String,
379 pub manager: Manager,
380 pub lockfile: &'static str,
382 pub standalone: bool,
385 pub berry: bool,
389}
390
391pub fn is_berry_lock(text: &str) -> bool {
395 text.lines().any(|l| l.starts_with("__metadata:"))
396}
397
398pub 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
424pub 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
442pub fn units(files: &[String], snapshot: &Path) -> Result<Vec<Unit>, String> {
446 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 amont.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
499fn bun_refusal(u: &Unit) -> String {
505 format!(
506 "{} in {}: {BIN} cannot install bun dependencies — set amont.snapshotPrepare \
507 to the install command, or amont.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 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 cmd.env(crate::pushed_tree::SNAPSHOT_ENV, "1");
535 cmd
536}
537
538fn 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
548fn 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 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
584fn clone_dir(src: &Path, dst: &Path) -> Result<(), String> {
589 #[cfg(target_os = "macos")]
590 let attempts: &[&[&str]] = &[&["/bin/cp", "-cR"], &["/bin/cp", "-R"]];
591 #[cfg(all(unix, not(target_os = "macos")))]
592 let attempts: &[&[&str]] = &[
593 &["/bin/cp", "-R", "--reflink=auto"],
594 &["/usr/bin/cp", "-R", "--reflink=auto"],
595 ];
596 #[cfg(not(unix))]
597 let attempts: &[&[&str]] = &[];
598 for argv in attempts {
599 if !Path::new(argv[0]).exists() {
600 continue;
601 }
602 let ok = Command::new(argv[0])
603 .args(&argv[1..])
604 .arg(src)
605 .arg(dst)
606 .stdin(Stdio::null())
607 .stdout(Stdio::null())
608 .stderr(Stdio::null())
609 .status()
610 .map(|s| s.success())
611 .unwrap_or(false);
612 if ok {
613 return Ok(());
614 }
615 let _ = std::fs::remove_dir_all(dst);
616 }
617 Err(format!("could not clone {}", src.display()))
618}
619
620fn normalize(p: &Path) -> PathBuf {
622 let mut out = PathBuf::new();
623 for c in p.components() {
624 match c {
625 Component::ParentDir => {
626 out.pop();
627 }
628 Component::CurDir => {}
629 other => out.push(other.as_os_str()),
630 }
631 }
632 out
633}
634
635fn link_into(dir: &Path, sources: &[PathBuf]) -> std::io::Result<Option<PathBuf>> {
639 let mut stack = vec![dir.to_path_buf()];
640 while let Some(at) = stack.pop() {
641 for entry in std::fs::read_dir(&at)? {
642 let entry = entry?;
643 let kind = entry.file_type()?;
644 let path = entry.path();
645 if kind.is_symlink() {
646 let target = std::fs::read_link(&path)?;
647 let resolved = if target.is_absolute() {
648 normalize(&target)
649 } else {
650 normalize(&at.join(target))
651 };
652 let real = path.canonicalize().ok();
656 if sources.iter().any(|s| {
657 resolved.starts_with(s) || real.as_ref().is_some_and(|r| r.starts_with(s))
658 }) {
659 return Ok(Some(path));
660 }
661 } else if kind.is_dir() {
662 stack.push(path);
663 }
664 }
665 }
666 Ok(None)
667}
668
669fn newer_than(nm: &Path, record: std::time::SystemTime) -> std::io::Result<Option<PathBuf>> {
678 if !nm.is_dir() {
679 return Ok(None);
680 }
681 let mut stack = vec![nm.to_path_buf()];
682 while let Some(at) = stack.pop() {
683 for entry in std::fs::read_dir(&at)? {
684 let entry = entry?;
685 let name = entry.file_name();
686 let name = name.to_string_lossy();
687 let kind = entry.file_type()?;
688 if kind.is_dir() {
689 if name == ".bin" || name == ".cache" || name.starts_with(".vite") {
690 continue;
691 }
692 stack.push(entry.path());
693 } else if kind.is_file() {
694 if name == ".modules.yaml"
695 || name.starts_with(".pnpm-workspace-state")
696 || (name == "lock.yaml" && at.file_name().is_some_and(|d| d == ".pnpm"))
697 {
698 continue;
699 }
700 if entry.metadata()?.modified()? > record {
701 return Ok(Some(entry.path()));
702 }
703 }
704 }
705 }
706 Ok(None)
707}
708
709fn members(settings: &crate::config::Settings, u: &Unit, at: &Path) -> Result<Vec<String>, String> {
712 if u.standalone {
713 return Ok(Vec::new());
714 }
715 let text = quiet(
716 settings,
717 manager_cmd(u, at, &["ls", "-r", "--depth", "-1", "--parseable"]),
718 )
719 .map_err(|t| format!("pnpm could not list the workspace: {}", last_line(&t)))?;
720 let root = normalize(at);
721 let canon = at.canonicalize().unwrap_or_else(|_| root.clone());
722 Ok(text
723 .lines()
724 .filter_map(|l| {
725 let p = PathBuf::from(l.trim());
726 let rel = p
727 .strip_prefix(&root)
728 .or_else(|_| p.strip_prefix(&canon))
729 .ok()?;
730 let rel = rel.to_string_lossy().replace('\\', "/");
731 (!rel.is_empty()).then_some(rel)
732 })
733 .collect())
734}
735
736fn pnpm_layout_problem(nm: &Path, is_root: bool) -> Option<String> {
741 if is_root {
742 let modules = std::fs::read_to_string(nm.join(".modules.yaml")).unwrap_or_default();
743 let isolated = modules
744 .lines()
745 .any(|l| l.contains("nodeLinker") && l.contains("isolated"));
746 if !isolated {
747 return Some("not installed with pnpm's isolated linker".to_string());
748 }
749 }
750 let entries = std::fs::read_dir(nm).ok()?;
751 for e in entries.flatten() {
752 let name = e.file_name().to_string_lossy().into_owned();
753 if name.starts_with('.') {
754 continue;
755 }
756 let kind = e.file_type().ok()?;
757 if kind.is_symlink() {
758 continue;
759 }
760 if name.starts_with('@') && kind.is_dir() {
761 for inner in std::fs::read_dir(e.path()).ok()?.flatten() {
762 if !inner.file_type().map(|k| k.is_symlink()).unwrap_or(false) {
763 return Some(format!(
764 "{} is not a link pnpm made",
765 inner.path().display()
766 ));
767 }
768 }
769 continue;
770 }
771 return Some(format!("{} is not a link pnpm made", e.path().display()));
772 }
773 None
774}
775
776fn reuse(
792 settings: &crate::config::Settings,
793 u: &Unit,
794 source: &Path,
795 snapshot: &Path,
796 unit_dirs: &[String],
797) -> Result<(), String> {
798 match u.manager {
799 Manager::Npm => {
800 return Err(
801 "npm cannot check an installed tree against its lockfile, so npm \
802 snapshots always install"
803 .to_string(),
804 )
805 }
806 Manager::Yarn => {
807 return Err(
808 "yarn cannot check an installed tree against its lockfile, so yarn \
809 snapshots always install"
810 .to_string(),
811 )
812 }
813 Manager::Bun => return Err(bun_refusal(u)),
814 Manager::Pnpm => {}
815 }
816 let src_dir = source.join(&u.dir);
817 let snap_dir = snapshot.join(&u.dir);
818 let lock = u.lockfile;
819 let src_lock = std::fs::read(src_dir.join(lock))
820 .map_err(|_| "no lockfile in the working tree".to_string())?;
821 let snap_lock = std::fs::read(snap_dir.join(lock)).map_err(|e| format!("{lock}: {e}"))?;
822 if src_lock != snap_lock {
823 return Err("the working tree's lockfile differs from the commit's".to_string());
824 }
825 if !src_dir.join("node_modules").is_dir() {
826 return Err("nothing installed in the working tree".to_string());
827 }
828 let mut set = vec![String::new()];
829 for m in members(settings, u, &snap_dir)? {
830 let repo_rel = join_rel(&u.dir, &m);
831 if unit_dirs.contains(&repo_rel) {
833 continue;
834 }
835 if src_dir.join(&m).join("node_modules").is_dir() {
836 set.push(m);
837 }
838 }
839 let record = std::fs::metadata(src_dir.join("node_modules/.modules.yaml"))
843 .and_then(|m| m.modified())
844 .map_err(|_| "no pnpm install record (node_modules/.modules.yaml)".to_string())?;
845 for m in &set {
846 match newer_than(&src_dir.join(m).join("node_modules"), record) {
847 Ok(None) => {}
848 Ok(Some(f)) => {
849 let shown = f.strip_prefix(source).unwrap_or(&f);
850 return Err(format!(
851 "{} changed after the install — an in-place edit pnpm does not check",
852 shown.display()
853 ));
854 }
855 Err(e) => return Err(format!("could not inspect the working tree's install: {e}")),
856 }
857 }
858 let mut cloned: Vec<PathBuf> = Vec::new();
859 let rollback = |cloned: &[PathBuf]| {
860 for d in cloned {
861 let _ = std::fs::remove_dir_all(d);
862 }
863 };
864 let sources = [
865 normalize(source),
866 source.canonicalize().unwrap_or_else(|_| normalize(source)),
867 ];
868 for m in &set {
869 let from = src_dir.join(m).join("node_modules");
870 let to = snap_dir.join(m).join("node_modules");
871 if std::fs::symlink_metadata(&to).is_ok() {
872 rollback(&cloned);
873 return Err(format!("{} already exists in the snapshot", to.display()));
874 }
875 if let Err(e) = clone_dir(&from, &to) {
876 rollback(&cloned);
877 return Err(e);
878 }
879 cloned.push(to.clone());
880 let problem = match link_into(&to, &sources) {
881 Ok(Some(link)) => Some(format!(
882 "{} links back into the working tree",
883 link.display()
884 )),
885 Ok(None) => pnpm_layout_problem(&to, m.is_empty()),
886 Err(e) => Some(format!("could not inspect the clone: {e}")),
887 };
888 if let Some(why) = problem {
889 rollback(&cloned);
890 return Err(why);
891 }
892 }
893 if let Ok(rd) = std::fs::read_dir(snap_dir.join("node_modules")) {
896 for e in rd.flatten() {
897 if e.file_name()
898 .to_string_lossy()
899 .starts_with(".pnpm-workspace-state")
900 {
901 let _ = std::fs::remove_file(e.path());
902 }
903 }
904 }
905 if let Err(text) = quiet(
909 settings,
910 manager_cmd(u, &snap_dir, &["install", "--frozen-lockfile", "--offline"]),
911 ) {
912 rollback(&cloned);
913 return Err(format!(
914 "pnpm did not accept the clone ({})",
915 last_line(&text)
916 ));
917 }
918 Ok(())
919}
920
921pub fn changed_since_upstream(source: &Path, tip: &str) -> Option<Vec<String>> {
925 let git = |args: &[&str]| -> Option<Vec<u8>> {
926 let mut cmd = Command::new("git");
927 cmd.arg("-C")
928 .arg(source)
929 .args(args)
930 .stdin(Stdio::null())
931 .stderr(Stdio::null());
932 crate::hooks::common::strip_git_env(&mut cmd);
933 let out = cmd.output().ok()?;
934 out.status.success().then_some(out.stdout)
935 };
936 let base = git(&["merge-base", tip, "@{upstream}"])?;
937 let base = String::from_utf8_lossy(&base).trim().to_string();
938 if base.is_empty() {
939 return None;
940 }
941 let raw = git(&["diff", "--name-only", "-z", &base, tip])?;
942 Some(crate::git::split_nul_paths(&raw))
943}
944
945pub fn select_units(units: Vec<Unit>, changed: Option<&[String]>) -> (Vec<Unit>, Vec<Unit>) {
954 let Some(changed) = changed else {
955 return (units, Vec::new());
956 };
957 let nearest = |f: &str| -> Option<&str> {
958 units
959 .iter()
960 .map(|u| u.dir.as_str())
961 .filter(|d| d.is_empty() || f.starts_with(&format!("{d}/")))
962 .max_by_key(|d| d.len())
963 };
964 let touched: Vec<&str> = changed.iter().filter_map(|f| nearest(f)).collect();
965 let (kept, skipped): (Vec<Unit>, Vec<Unit>) = units
966 .clone()
967 .into_iter()
968 .partition(|u| u.dir.is_empty() || touched.contains(&u.dir.as_str()));
969 (kept, skipped)
970}
971
972pub fn deps(
974 settings: &crate::config::Settings,
975 mode: DepsMode,
976 source: &Path,
977 snapshot: &Path,
978 files: &[String],
979 changed: Option<&[String]>,
980) -> Result<(), String> {
981 if mode == DepsMode::Off {
982 return Ok(());
983 }
984 let all = units(files, snapshot)?;
985 let unit_dirs: Vec<String> = all.iter().map(|u| u.dir.clone()).collect();
986 let (units, skipped) = select_units(all, changed);
987 if !skipped.is_empty() {
988 let names: Vec<String> = skipped.iter().map(unit_label).collect();
989 println!(
990 "snapshot: not preparing {} — the push changes nothing there",
991 names.join(", ")
992 );
993 }
994 for u in &units {
995 let at = snapshot.join(&u.dir);
996 let label = unit_label(u);
997 if u.manager == Manager::Bun {
998 return Err(bun_refusal(u));
1001 }
1002 if mode == DepsMode::Reuse {
1003 match reuse(settings, u, source, snapshot, &unit_dirs) {
1006 Ok(()) => {
1007 println!(
1008 "snapshot: node_modules in {label} reused from the working tree — {} \
1009 accepted it against the lockfile",
1010 u.manager.tool()
1011 );
1012 continue;
1013 }
1014 Err(why) => println!(
1015 "snapshot: {} in {label} — not reusing the working tree's install: {why}",
1016 highlight(&format!("{} {}", u.manager.tool(), install_verb(u)))
1017 ),
1018 }
1019 } else {
1020 println!(
1021 "snapshot: {} in {label}",
1022 highlight(&format!("{} {}", u.manager.tool(), install_verb(u)))
1023 );
1024 }
1025 install(settings, u, &at)?;
1026 }
1027 Ok(())
1028}
1029
1030fn install_verb(u: &Unit) -> &'static str {
1031 match u.manager {
1032 Manager::Npm => "ci",
1033 Manager::Pnpm => "install --frozen-lockfile",
1034 Manager::Yarn if u.berry => "install --immutable",
1035 Manager::Yarn => "install --frozen-lockfile",
1036 Manager::Bun => "install",
1037 }
1038}
1039
1040pub fn run(
1044 settings: &crate::config::Settings,
1045 source: &Path,
1046 snapshot: &Path,
1047 tip: &str,
1048 command_owns_deps: bool,
1049) -> Result<(), String> {
1050 let entries = carry_list(settings);
1051 let mode = if command_owns_deps {
1052 DepsMode::Off
1053 } else {
1054 deps_mode(settings)
1055 };
1056 if entries.is_empty() && mode == DepsMode::Off {
1057 return Ok(());
1058 }
1059 let files = snapshot_files(snapshot)?;
1060 if !entries.is_empty() {
1061 carry(&entries, source, snapshot, &files)?;
1062 }
1063 let changed = if mode == DepsMode::Off {
1064 None
1065 } else {
1066 changed_since_upstream(source, tip)
1067 };
1068 deps(settings, mode, source, snapshot, &files, changed.as_deref()).map_err(|e| {
1069 println!("{} {e}", warning_sign());
1070 e
1071 })
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076 use super::*;
1077
1078 fn s(v: &[&str]) -> Vec<String> {
1079 v.iter().map(|x| x.to_string()).collect()
1080 }
1081
1082 #[test]
1083 fn lexical_refusals() {
1084 for bad in [
1085 "",
1086 "/etc/hosts",
1087 "\\x",
1088 "C:/x",
1089 "a//b",
1090 ".",
1091 "..",
1092 "a/../b",
1093 ".git/config",
1094 "x/.GIT/y",
1095 ] {
1096 assert!(lexical_problem(bad).is_some(), "{bad:?} must be refused");
1097 }
1098 for good in [".env", "config/local.json", ".npmrc", "a.b/c"] {
1099 assert!(lexical_problem(good).is_none(), "{good:?} must pass");
1100 }
1101 }
1102
1103 #[test]
1104 fn a_tracked_path_inside_above_or_equal_collides() {
1105 let files = s(&["src/a.ts", "vendor", "README.md"]);
1106 assert!(tracked_collision("src", &files).is_some());
1107 assert!(tracked_collision("src/a.ts", &files).is_some());
1108 assert!(tracked_collision("vendor/x", &files).is_some());
1109 assert!(tracked_collision(".env", &files).is_none());
1110 assert!(tracked_collision("sr", &files).is_none());
1111 }
1112
1113 #[test]
1114 fn lockfile_dirs_come_from_the_list_given() {
1115 let files = s(&[
1116 "package-lock.json",
1117 "web/package-lock.json",
1118 "web/x/pnpm-lock.yaml",
1119 "notpackage-lock.json",
1120 ]);
1121 assert_eq!(
1122 lockfile_dirs_in(&files, "package-lock.json"),
1123 s(&["", "web"])
1124 );
1125 assert_eq!(lockfile_dirs_in(&files, "pnpm-lock.yaml"), s(&["web/x"]));
1126 }
1127
1128 #[test]
1129 fn package_manager_field_is_read_narrowly() {
1130 assert_eq!(
1131 declared_manager(r#"{"packageManager": "pnpm@10.1.0"}"#),
1132 Some(Manager::Pnpm)
1133 );
1134 assert_eq!(
1135 declared_manager(r#"{"packageManager":"npm@11"}"#),
1136 Some(Manager::Npm)
1137 );
1138 assert_eq!(
1139 declared_manager(r#"{"packageManager":"yarn@4"}"#),
1140 Some(Manager::Yarn)
1141 );
1142 assert_eq!(
1143 declared_manager(r#"{"packageManager":"bun@1.2.0"}"#),
1144 Some(Manager::Bun)
1145 );
1146 assert_eq!(
1147 declared_manager(r#"{"packageManager":"yarnpkg@1"}"#),
1148 None,
1149 "a name, not a prefix"
1150 );
1151 assert_eq!(declared_manager(r#"{"name":"x"}"#), None);
1152 assert_eq!(
1153 declared_manager(r#"{"packageManager":"npm@1","x":{"packageManager":"pnpm@1"}}"#),
1154 None,
1155 "two answers is no answer"
1156 );
1157 }
1158
1159 fn unit(dir: &str) -> Unit {
1160 Unit {
1161 dir: dir.to_string(),
1162 manager: Manager::Pnpm,
1163 lockfile: "pnpm-lock.yaml",
1164 standalone: !dir.is_empty(),
1165 berry: false,
1166 }
1167 }
1168
1169 #[test]
1170 fn a_berry_lockfile_is_told_by_its_metadata_block() {
1171 assert!(is_berry_lock(
1172 "# This file is generated by running \"yarn install\" inside your project.\n\n__metadata:\n version: 8\n"
1173 ));
1174 assert!(!is_berry_lock(
1175 "# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n# yarn lockfile v1\n\n"
1176 ));
1177 assert!(!is_berry_lock(""));
1178 }
1179
1180 #[test]
1181 fn every_manager_lockfile_is_a_unit_and_a_mixed_directory_needs_the_field() {
1182 let d = std::env::temp_dir().join(format!("units-{}", std::process::id()));
1183 let _ = std::fs::remove_dir_all(&d);
1184 std::fs::create_dir_all(d.join("berry")).unwrap();
1185 std::fs::write(d.join("yarn.lock"), "# yarn lockfile v1\n").unwrap();
1186 std::fs::write(d.join("berry/yarn.lock"), "__metadata:\n version: 8\n").unwrap();
1187 let files = s(&[
1188 "yarn.lock",
1189 "berry/yarn.lock",
1190 "old/bun.lockb",
1191 "new/bun.lock",
1192 "mixed/package-lock.json",
1193 "mixed/yarn.lock",
1194 ]);
1195 let err = units(&files, &d).unwrap_err();
1196 assert!(
1197 err.contains("both package-lock.json and yarn.lock in mixed"),
1198 "{err}"
1199 );
1200 std::fs::create_dir_all(d.join("mixed")).unwrap();
1201 std::fs::write(
1202 d.join("mixed/package.json"),
1203 r#"{"packageManager":"yarn@1.22.22"}"#,
1204 )
1205 .unwrap();
1206 let got = units(&files, &d).unwrap();
1207 let brief: Vec<(&str, Manager, &str, bool)> = got
1208 .iter()
1209 .map(|u| (u.dir.as_str(), u.manager, u.lockfile, u.berry))
1210 .collect();
1211 assert_eq!(
1212 brief,
1213 vec![
1214 ("", Manager::Yarn, "yarn.lock", false),
1215 ("berry", Manager::Yarn, "yarn.lock", true),
1216 ("mixed", Manager::Yarn, "yarn.lock", false),
1217 ("new", Manager::Bun, "bun.lock", false),
1218 ("old", Manager::Bun, "bun.lockb", false),
1219 ]
1220 );
1221 std::fs::write(
1222 d.join("mixed/package.json"),
1223 r#"{"packageManager":"pnpm@10"}"#,
1224 )
1225 .unwrap();
1226 let err = units(&files, &d).unwrap_err();
1227 assert!(
1228 err.contains("no `packageManager` to choose"),
1229 "a field naming an absent lockfile chooses nothing: {err}"
1230 );
1231 let _ = std::fs::remove_dir_all(&d);
1232 }
1233
1234 #[test]
1235 fn only_the_root_and_the_touched_units_are_kept() {
1236 let all = vec![unit(""), unit("spikes/a"), unit("spikes/b"), unit("tools")];
1237 let changed = s(&["src/x.ts", "spikes/b/index.ts", "spikes/bb/y.ts"]);
1238 let (kept, skipped) = select_units(all.clone(), Some(&changed));
1239 let dirs = |v: &[Unit]| v.iter().map(|u| u.dir.clone()).collect::<Vec<_>>();
1240 assert_eq!(
1241 dirs(&kept),
1242 s(&["", "spikes/b"]),
1243 "spikes/bb is not spikes/b"
1244 );
1245 assert_eq!(dirs(&skipped), s(&["spikes/a", "tools"]));
1246 let (kept, skipped) = select_units(all.clone(), None);
1247 assert_eq!(kept.len(), 4, "an unknown range keeps everything");
1248 assert!(skipped.is_empty());
1249 }
1250
1251 #[test]
1252 fn a_nested_unit_claims_its_files_from_the_outer_one() {
1253 let all = vec![unit("web"), unit("web/nested")];
1254 let changed = s(&["web/nested/a.ts"]);
1255 let (kept, _) = select_units(all, Some(&changed));
1256 assert_eq!(kept.len(), 1);
1257 assert_eq!(kept[0].dir, "web/nested");
1258 }
1259
1260 #[test]
1261 fn a_file_newer_than_the_install_record_is_found() {
1262 let d = std::env::temp_dir().join(format!("newer-{}", std::process::id()));
1263 let _ = std::fs::remove_dir_all(&d);
1264 let pkg = d.join(".pnpm/a@1/node_modules/a");
1265 std::fs::create_dir_all(&pkg).unwrap();
1266 std::fs::create_dir_all(d.join(".bin")).unwrap();
1267 std::fs::create_dir_all(d.join(".cache")).unwrap();
1268 std::fs::write(pkg.join("index.js"), "old").unwrap();
1269 let record = std::time::SystemTime::now();
1270 std::thread::sleep(std::time::Duration::from_millis(20));
1271 for skipped in [".bin/tsc", ".cache/x", ".pnpm/lock.yaml", ".modules.yaml"] {
1272 std::fs::write(d.join(skipped), "new").unwrap();
1273 }
1274 assert_eq!(
1275 newer_than(&d, record).unwrap(),
1276 None,
1277 "the install's own writes"
1278 );
1279 std::fs::write(pkg.join("index.js"), "edited").unwrap();
1280 assert_eq!(newer_than(&d, record).unwrap(), Some(pkg.join("index.js")));
1281 let _ = std::fs::remove_dir_all(&d);
1282 }
1283
1284 #[test]
1285 fn normalize_folds_dots_lexically() {
1286 assert_eq!(
1287 normalize(Path::new("/a/b/../c/./d")),
1288 PathBuf::from("/a/c/d")
1289 );
1290 }
1291}