diff --git a/Cargo.toml b/Cargo.toml index b8442b2..90e59bf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,7 +29,6 @@ serde_json = "1.0" serde_yaml = "0.9" chrono = { version = "0.4", features = ["serde"] } indicatif = "0.17" -dialoguer = "0.11" console = "0.15" log = "0.4" colored = "2" diff --git a/src/clone.rs b/src/clone.rs index c29e4ad..864ad5b 100644 --- a/src/clone.rs +++ b/src/clone.rs @@ -190,6 +190,9 @@ pub(crate) fn execute_git_clone( // Use the queue-based cloning system clone_with_queue(Arc::clone(&queue), parallel, &mp, ssh_cmd.as_deref())?; + if let Some(error) = crate::clone_worker::report_failures(&queue) { + return Ok(CommandResult::Error(error)); + } let (completed, total) = queue.get_counts(); if total > initial_count { diff --git a/src/clone_worker.rs b/src/clone_worker.rs index 48abc02..9e37db4 100644 --- a/src/clone_worker.rs +++ b/src/clone_worker.rs @@ -101,6 +101,36 @@ pub(crate) fn clone_with_queue( Ok(()) } +/// Print each failed clone with git's error to stderr, and return the +/// command's error, or `None` when every clone succeeded. +pub(crate) fn report_failures(queue: &CloneQueue) -> Option { + let failures = queue.failures(); + if failures.is_empty() { + return None; + } + for failure in &failures { + eprintln!( + "{} {} ({})", + style("Failed to clone").red().bold(), + failure.name, + failure.url + ); + for line in failure.error.lines() { + eprintln!(" {line}"); + } + } + let (finished, _) = queue.get_counts(); + Some(format!( + "{} of {finished} repositories failed to clone: {}", + failures.len(), + failures + .iter() + .map(|f| f.name.as_str()) + .collect::>() + .join(", ") + )) +} + /// Clone a single repository and handle .meta discovery fn clone_single_repo( task: &CloneTask, @@ -144,21 +174,16 @@ fn clone_single_repo( .spawn() { Ok(mut child) => { - // Stream stderr for progress updates - let stderr = child.stderr.take(); + // Stream stderr for progress updates, and keep its last lines for + // the failure report (the progress bar is hidden off a terminal). let pb_clone = pb.clone(); let task_name = task.name.clone(); - if let Some(stderr) = stderr { - std::thread::spawn(move || { - use std::io::{BufRead, BufReader}; - let reader = BufReader::new(stderr); - for line in reader.lines().map_while(Result::ok) { - pb_clone.set_message(format!("{task_name}: {line}")); - } - }); - } + let tail = StderrTail::spawn(child.stderr.take(), move |line| { + pb_clone.set_message(format!("{task_name}: {line}")) + }); - match child.wait() { + let status = child.wait(); + match status { Ok(status) if status.success() => { // Check for nested .meta and report new discoveries match queue.mark_completed(task) { @@ -189,8 +214,21 @@ fn clone_single_repo( } } } - _ => { - queue.mark_failed(task); + Ok(status) => { + let stderr_text = tail.text(); + let error = if stderr_text.trim().is_empty() { + format!("git clone exited with {status}") + } else { + stderr_text + }; + queue.mark_failed(task, error); + pb.finish_with_message(format!( + "{}", + style(format!("Failed to clone {}", task.name)).red() + )); + } + Err(e) => { + queue.mark_failed(task, format!("Failed to wait for git: {e}")); pb.finish_with_message(format!( "{}", style(format!("Failed to clone {}", task.name)).red() @@ -198,8 +236,8 @@ fn clone_single_repo( } } } - Err(_) => { - queue.mark_failed(task); + Err(e) => { + queue.mark_failed(task, format!("Failed to run git: {e}")); pb.finish_with_message(format!( "{}", style(format!("Failed to spawn git for {}", task.name)).red() @@ -207,3 +245,85 @@ fn clone_single_repo( } } } + +/// The last lines a process writes to stderr, kept by a reader thread that +/// drains the pipe and holds at most [`StderrTail::KEPT_LINES`]. +struct StderrTail { + lines: Arc>>, + done: std::sync::mpsc::Receiver<()>, +} + +impl StderrTail { + const KEPT_LINES: usize = 20; + const LINE_BYTES: u64 = 4096; + + fn spawn( + stderr: Option, + on_line: impl Fn(&str) + Send + 'static, + ) -> Self { + let lines = Arc::new(Mutex::new(std::collections::VecDeque::new())); + let (done_tx, done) = std::sync::mpsc::channel(); + if let Some(stderr) = stderr { + let kept = Arc::clone(&lines); + std::thread::spawn(move || { + use std::io::{BufRead, BufReader, Read}; + let mut reader = BufReader::new(stderr); + let mut buf = Vec::new(); + // Reads at most LINE_BYTES at a time, so one huge line can't + // grow memory; a longer line is kept in pieces. + while (&mut reader) + .take(Self::LINE_BYTES) + .read_until(b'\n', &mut buf) + .is_ok_and(|n| n > 0) + { + let line = String::from_utf8_lossy(&buf).trim_end().to_string(); + buf.clear(); + on_line(&line); + let mut kept = kept.lock().unwrap_or_else(|e| e.into_inner()); + if kept.len() == Self::KEPT_LINES { + kept.pop_front(); + } + kept.push_back(line); + } + drop(done_tx); + }); + } + Self { lines, done } + } + + /// The kept lines. Waits briefly for the reader to finish, but not for a + /// background process (an ssh master, say) that still holds the pipe. + fn text(&self) -> String { + let _ = self.done.recv_timeout(Duration::from_secs(2)); + let lines = self.lines.lock().unwrap_or_else(|e| e.into_inner()); + Vec::from(lines.clone()).join("\n") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stderr_tail_drains_everything_and_keeps_only_the_last_lines() { + let output: String = (0..100_000).map(|i| format!("line {i}\n")).collect(); + let seen = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&seen); + let tail = StderrTail::spawn(Some(std::io::Cursor::new(output)), move |_| { + counter.fetch_add(1, Ordering::SeqCst); + }); + + let text = tail.text(); + assert_eq!(seen.load(Ordering::SeqCst), 100_000); + assert_eq!(text.lines().count(), StderrTail::KEPT_LINES); + assert!(text.ends_with("line 99999")); + } + + #[test] + fn stderr_tail_bounds_a_single_huge_line() { + let output = "x".repeat(10_000_000); + let tail = StderrTail::spawn(Some(std::io::Cursor::new(output)), |_| {}); + let text = tail.text(); + assert!(text.len() <= StderrTail::KEPT_LINES * (StderrTail::LINE_BYTES as usize + 1)); + } +} diff --git a/src/commands/worktree/add.rs b/src/commands/worktree/add.rs index 780fd34..7969a5c 100644 --- a/src/commands/worktree/add.rs +++ b/src/commands/worktree/add.rs @@ -64,7 +64,7 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool, strict: bool) ); } - let created_branch = git_worktree_add(&source, &dest, &branch, None)?; + let created_branch = git_worktree_add(&source, &dest, &branch, None)?.is_some(); added.push(CreateRepoEntry { alias: spec.alias.clone(), path: dest.display().to_string(), diff --git a/src/commands/worktree/create.rs b/src/commands/worktree/create.rs index e4fd651..ced5d31 100644 --- a/src/commands/worktree/create.rs +++ b/src/commands/worktree/create.rs @@ -1,4 +1,4 @@ -use anyhow::Result; +use anyhow::{Context, Result}; use chrono::Utc; use colored::*; use std::collections::{HashMap, HashSet}; @@ -7,6 +7,7 @@ use meta_cli::dependency_graph::{DependencyGraph, ProjectDependencies}; use meta_git_lib::worktree::git_ops::*; use meta_git_lib::worktree::helpers::*; use meta_git_lib::worktree::hooks::fire_post_create; +use meta_git_lib::worktree::safety::{check_worktree_removal, delete_checked_set}; use meta_git_lib::worktree::store::store_add; use meta_git_lib::worktree::types::{ CreateOutput, CreateRepoEntry, StoreRepoEntry, WorktreeStoreEntry, @@ -162,138 +163,137 @@ pub(crate) fn handle_create( let mut repos_to_create = repos_to_create; let from_pr_info = from_pr_spec.map(resolve_from_pr).transpose()?; if let Some((ref pr_repo_spec, _pr_num, ref pr_branch)) = from_pr_info { - let mut matched = false; - for (alias, source, branch) in repos_to_create.iter_mut() { - if *alias != "." && repo_matches_spec(source, pr_repo_spec) { - // Fetch the PR branch - if let Err(e) = git_fetch_branch(source, pr_branch) { - super::warn_or_bail( - strict, - format!("Failed to fetch PR branch '{pr_branch}': {e}"), - )?; - } - *branch = pr_branch.clone(); - matched = true; - break; - } - } - if !matched { - super::warn_or_bail( - strict, - format!("No repo matches '{pr_repo_spec}'. PR branch '{pr_branch}' not applied."), - )?; - } + let (alias, source, branch) = repos_to_create + .iter_mut() + .find(|(alias, source, _)| alias != "." && repo_matches_spec(source, pr_repo_spec)) + .ok_or_else(|| { + anyhow::anyhow!( + "No selected repo has origin '{pr_repo_spec}', so PR branch '{pr_branch}' can't be applied" + ) + })?; + git_fetch_branch(source, pr_branch) + .map_err(|e| e.context(format!("Cannot fetch the PR branch into '{alias}'")))?; + *branch = pr_branch.clone(); } - let dot_included = repos_to_create.iter().any(|(a, _, _)| a == "."); - let mut created_repos = Vec::new(); - - // If "." is included, create it first (it becomes the worktree root). - // git worktree add creates the target dir, so we skip create_dir_all. - let mut dot_created = false; - if dot_included { - let (_, source, branch) = repos_to_create.iter().find(|(a, _, _)| a == ".").unwrap(); - - if verbose { - eprintln!( - "Creating meta repo worktree at {} (branch: {})", - wt_dir.display(), - branch - ); - } - - // Ensure parent exists (git worktree add creates the leaf dir) - if let Some(parent) = wt_dir.parent() { - std::fs::create_dir_all(parent)?; + // Claim the set directory atomically: if another create claimed it first, + // this fails and nothing of theirs is touched. Everything in it from here + // on was made by this call. + if let Some(parent) = wt_dir.parent() { + std::fs::create_dir_all(parent)?; + } + if let Err(e) = std::fs::create_dir(&wt_dir) { + if e.kind() == std::io::ErrorKind::AlreadyExists { + anyhow::bail!("Worktree '{name}' already exists at {}", wt_dir.display()); } + return Err(e).with_context(|| format!("Cannot create {}", wt_dir.display())); + } - match git_worktree_add(source, &wt_dir, branch, from_ref) { - Ok(created_branch) => { + // Anything that fails from here rolls back what this call created. + let mut created_repos = Vec::new(); + let mut new_branches = Vec::new(); + let built = (|| -> Result<()> { + // If "." is included, create it first (it becomes the worktree root; + // git accepts the empty directory claimed above). + if let Some((_, source, branch)) = repos_to_create.iter().find(|(a, _, _)| a == ".") { + if let Some(r) = missing_ref(source, from_ref)? { + // --from-ref: skip root repo if ref doesn't exist (same as child repos) + super::warn_or_bail(strict, format!("Skipping '.': ref '{r}' not found"))?; + } else { + if verbose { + eprintln!( + "Creating meta repo worktree at {} (branch: {})", + wt_dir.display(), + branch + ); + } + let created_branch = journal_new_branch(source, branch, &mut new_branches, || { + git_worktree_add(source, &wt_dir, branch, from_ref) + })?; created_repos.push(CreateRepoEntry { alias: ".".to_string(), path: wt_dir.display().to_string(), branch: branch.clone(), created_branch, }); - dot_created = true; - } - Err(e) if from_ref.is_some() => { - // --from-ref: skip root repo if ref doesn't exist (same as child repos) - super::warn_or_bail(strict, format!("Skipping '.': {e}"))?; } - Err(e) => return Err(e), } - } - // Ensure wt_dir exists for child repos (when "." isn't included or was skipped, it wasn't created by git) - if !dot_created { - std::fs::create_dir_all(&wt_dir)?; - } + // Create child repo worktrees + for (alias, source, branch) in &repos_to_create { + if alias == "." { + continue; + } + if let Some(r) = missing_ref(source, from_ref)? { + // --from-ref: skip repos where ref doesn't exist + super::warn_or_bail(strict, format!("Skipping '{alias}': ref '{r}' not found"))?; + continue; + } - // Create child repo worktrees - for (alias, source, branch) in &repos_to_create { - if alias == "." { - continue; - } + // Preserve the full alias as the destination path so that relative + // references (e.g., Cargo.toml workspace members) remain valid. + // "vendor/tree-sitter-markdown" -> "vendor/tree-sitter-markdown" + // Simple aliases are unchanged: "core" -> "core" + let dest = wt_dir.join(alias); - // Preserve the full alias as the destination path so that relative - // references (e.g., Cargo.toml workspace members) remain valid. - // "vendor/tree-sitter-markdown" -> "vendor/tree-sitter-markdown" - // Simple aliases are unchanged: "core" -> "core" - let dest = wt_dir.join(alias); + // Ensure parent directories exist for nested paths (e.g., "vendor/") + if let Some(parent) = dest.parent() { + if parent != wt_dir { + std::fs::create_dir_all(parent)?; + } + } - // Ensure parent directories exist for nested paths (e.g., "vendor/") - if let Some(parent) = dest.parent() { - if parent != wt_dir { - std::fs::create_dir_all(parent)?; + if verbose { + eprintln!( + "Creating worktree for '{}' at {} (branch: {})", + alias, + dest.display(), + branch + ); } - } - if verbose { - eprintln!( - "Creating worktree for '{}' at {} (branch: {})", - alias, - dest.display(), - branch - ); + // Any failure other than a missing ref is a failed create. + let created_branch = journal_new_branch(source, branch, &mut new_branches, || { + git_worktree_add(source, &dest, branch, from_ref) + })?; + created_repos.push(CreateRepoEntry { + alias: alias.clone(), + path: dest.display().to_string(), + branch: branch.clone(), + created_branch, + }); } - match git_worktree_add(source, &dest, branch, from_ref) { - Ok(created_branch) => { - created_repos.push(CreateRepoEntry { - alias: alias.clone(), - path: dest.display().to_string(), - branch: branch.clone(), - created_branch, - }); + if created_repos.is_empty() { + // Every repo was skipped because none has the ref. + match from_ref { + Some(r) => anyhow::bail!("No selected repo has ref '{r}'; no worktree was created"), + None => anyhow::bail!("No repos selected; no worktree was created"), } - Err(e) if from_ref.is_some() => { - // --from-ref: skip repos where ref doesn't exist - super::warn_or_bail(strict, format!("Skipping '{alias}': {e}"))?; - continue; - } - Err(e) => return Err(e), } - } - // Ensure .worktrees/ is in .gitignore - let dirname = worktree_root - .file_name() - .and_then(|n| n.to_str()) - .unwrap_or(".worktrees"); - ensure_worktrees_in_gitignore(&meta_dir, dirname, json)?; + // Ensure .worktrees/ is in .gitignore + let dirname = worktree_root + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or(".worktrees"); + ensure_worktrees_in_gitignore(&meta_dir, dirname, json)?; - // Add to centralized store - let store_entry = WorktreeStoreEntry { - name: name.to_string(), - project: meta_dir.to_string_lossy().to_string(), - created_at: Utc::now().to_rfc3339(), - ephemeral, - ttl_seconds, - repos: created_repos.iter().map(StoreRepoEntry::from).collect(), - custom: custom_meta.clone(), - }; - super::warn_store_error(store_add(&wt_dir, store_entry), strict)?; + // Add to centralized store + let store_entry = WorktreeStoreEntry { + name: name.to_string(), + project: meta_dir.to_string_lossy().to_string(), + created_at: Utc::now().to_rfc3339(), + ephemeral, + ttl_seconds, + repos: created_repos.iter().map(StoreRepoEntry::from).collect(), + custom: custom_meta.clone(), + }; + // `remove` and `prune` delete only recorded worktrees, so an unrecorded one + // would be stranded: failing to record is a failed create. + store_add(&wt_dir, store_entry).context("Cannot record the new worktree") + })(); + built.map_err(|e| roll_back(&wt_dir, &new_branches, e))?; // Fire post-create hook fire_post_create( @@ -342,6 +342,86 @@ pub(crate) fn handle_create( Ok(()) } +/// The `--from-ref` a repo doesn't have, if any: such repos are skipped. A +/// repo git can't read is an error, not a missing ref. +fn missing_ref<'a>(repo: &std::path::Path, from_ref: Option<&'a str>) -> Result> { + match from_ref { + Some(r) if git_rev_parse(repo, &format!("{r}^{{commit}}"))?.is_none() => Ok(Some(r)), + _ => Ok(None), + } +} + +/// Run a `git worktree add` and note the branch it created, with the commit +/// it was created at, so a rollback deletes only branches this call made and +/// only while they still point there (a post-checkout hook may have committed +/// on one). A branch that appears although the add failed may belong to +/// someone else: it is kept and named in the error. +fn journal_new_branch( + repo: &std::path::Path, + branch: &str, + journal: &mut Vec<(std::path::PathBuf, String, String)>, + add: impl FnOnce() -> Result>, +) -> Result { + let branch_ref = format!("refs/heads/{branch}"); + let existed = git_rev_parse(repo, &branch_ref)?.is_some(); + match add() { + Ok(Some(start)) => { + journal.push((repo.to_path_buf(), branch.to_string(), start)); + Ok(true) + } + Ok(None) => Ok(false), + Err(e) if !existed && matches!(git_rev_parse(repo, &branch_ref), Ok(Some(_))) => Err(e + .context(format!( + "branch '{branch}' now exists in {} and was kept: meta can't tell whether this \ + create made it", + repo.display() + ))), + Err(e) => Err(e), + } +} + +/// Undo a failed create: delete the set this call claimed, if the removal +/// check finds nothing to lose, and the branches it created, if they still +/// point where it left them. Returns the error to report. +fn roll_back( + wt_dir: &std::path::Path, + new_branches: &[(std::path::PathBuf, String, String)], + error: anyhow::Error, +) -> anyhow::Error { + let undone = check_worktree_removal(wt_dir).and_then(|check| { + let problems = [check.blockers.clone(), check.unsaved.clone()].concat(); + anyhow::ensure!(problems.is_empty(), "{}", problems.join("; ")); + delete_checked_set(wt_dir, &check, false, false) + }); + if let Err(undo) = undone { + let branches: Vec<&str> = new_branches.iter().map(|(_, b, _)| b.as_str()).collect(); + return anyhow::anyhow!( + "{error:#}\nThe partly created worktree at {} was left in place ({undo:#}); \ + delete it yourself and run 'git worktree prune' in its repositories. \ + Branches this create made: {}", + wt_dir.display(), + if branches.is_empty() { + "none".to_string() + } else { + branches.join(", ") + } + ); + } + let kept: Vec = new_branches + .iter() + .filter_map(|(repo, branch, tip)| git_delete_branch_at(repo, branch, tip).err()) + .map(|e| format!("{e:#}")) + .collect(); + if kept.is_empty() { + error + } else { + anyhow::anyhow!( + "{error:#}\nRolled back, but kept branches: {}", + kept.join("; ") + ) + } +} + struct CreateDryRunPlan<'a> { name: &'a str, wt_dir: &'a std::path::Path, @@ -724,3 +804,52 @@ fn ensure_intermediate_parents( Ok(result) } + +#[cfg(test)] +mod tests { + use super::*; + use std::process::Command; + + fn git(dir: &std::path::Path, args: &[&str]) { + let out = Command::new("git") + .arg("-C") + .arg(dir) + .args(["-c", "user.name=t", "-c", "user.email=t@example.com"]) + .args(args) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + } + + #[test] + fn journal_keeps_only_branches_this_call_created() { + let tmp = tempfile::tempdir().unwrap(); + git(tmp.path(), &["init", "-q"]); + git(tmp.path(), &["commit", "-q", "--allow-empty", "-m", "init"]); + let mut journal = Vec::new(); + + // Our add created the branch: journaled. + let created = journal_new_branch(tmp.path(), "ours", &mut journal, || { + git(tmp.path(), &["branch", "ours"]); + Ok(Some("start".to_string())) + }); + assert!(created.unwrap()); + assert_eq!(journal.len(), 1); + + // Another process created the branch while our add failed: kept and named. + let err = journal_new_branch(tmp.path(), "theirs", &mut journal, || { + git(tmp.path(), &["branch", "theirs"]); + anyhow::bail!("branch already exists") + }) + .unwrap_err(); + assert!( + format!("{err:#}").contains("'theirs' now exists"), + "{err:#}" + ); + assert_eq!(journal.len(), 1); + } +} diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rs index a0dd4b3..6dd8d71 100644 --- a/src/commands/worktree/mod.rs +++ b/src/commands/worktree/mod.rs @@ -92,7 +92,7 @@ pub fn execute_worktree_command( cwd, ) { Ok(()) => CommandResult::Message(String::new()), - Err(e) => CommandResult::Error(format!("{e}")), + Err(e) => CommandResult::Error(format!("{e:#}")), }, Err(e) => { // Clap treats --help and --version as "errors" with special ErrorKind diff --git a/src/commands/worktree/prune.rs b/src/commands/worktree/prune.rs index 5c1d077..1e120f7 100644 --- a/src/commands/worktree/prune.rs +++ b/src/commands/worktree/prune.rs @@ -3,10 +3,9 @@ use chrono::Utc; use colored::*; use std::path::Path; -use meta_cli::worktree::discover_worktree_repos; -use meta_git_lib::worktree::git_ops::remove_worktree_repos; -use meta_git_lib::worktree::helpers::find_meta_dir; +use meta_git_lib::worktree::helpers::{find_meta_dir, lookup_nested_project}; use meta_git_lib::worktree::hooks::fire_post_prune; +use meta_git_lib::worktree::safety::{check_worktree_removal, delete_checked_set}; use meta_git_lib::worktree::store::{entry_ttl_remaining, store_list, store_remove_batch}; use meta_git_lib::worktree::types::*; @@ -52,10 +51,19 @@ fn check_repo_orphaned( return None; // Can't check without config }; + // "." is the project's own repo and always exists, so a set holding it is + // never orphaned. Nested aliases ("sub/leaf") live in child .meta files, + // not the top-level project list. let missing_count = entry .repos .iter() - .filter(|store_repo| !projects.iter().any(|p| p.name == store_repo.alias)) + .map(|r| r.alias.as_str()) + .filter(|alias| { + *alias != "." + && !projects.iter().any(|p| p.name == *alias) + && !(alias.contains('/') + && lookup_nested_project(Path::new(&entry.project), alias).is_ok()) + }) .count(); if missing_count > 0 && missing_count == entry.repos.len() { @@ -65,6 +73,13 @@ fn check_repo_orphaned( } } +/// Only a path that is really gone counts as missing. A dangling link or a +/// path prune can't inspect (permission denied) exists, so it gets checked +/// and kept, never forgotten. +fn is_missing(path: &Path) -> bool { + matches!(path.symlink_metadata(), Err(e) if e.kind() == std::io::ErrorKind::NotFound) +} + pub(crate) fn handle_prune( args: PruneArgs, _verbose: bool, @@ -80,6 +95,7 @@ pub(crate) fn handle_prune( "{}", serde_json::to_string_pretty(&PruneOutput { removed: vec![], + kept: vec![], dry_run, })? ); @@ -100,7 +116,7 @@ pub(crate) fn handle_prune( let wt_path = Path::new(path_key); // Check if path exists (orphaned detection) - if !wt_path.exists() { + if is_missing(wt_path) { to_remove.push(create_prune_entry( entry.name.clone(), path_key.clone(), @@ -137,8 +153,8 @@ pub(crate) fn handle_prune( if let Some(remaining) = entry_ttl_remaining(entry, now) { if remaining <= 0 { // Total age = configured TTL + seconds past expiry - let overdue = (-remaining) as u64; - let age = entry.ttl_seconds.unwrap() + overdue; + let overdue = remaining.unsigned_abs(); + let age = entry.ttl_seconds.unwrap_or(0).saturating_add(overdue); to_remove.push(create_prune_entry( entry.name.clone(), path_key.clone(), @@ -149,68 +165,114 @@ pub(crate) fn handle_prune( } } - if to_remove.is_empty() { - if json { - println!( - "{}", - serde_json::to_string_pretty(&PruneOutput { - removed: vec![], - dry_run, - })? - ); - } else { - println!("Nothing to prune."); + // Prune never discards work: a candidate whose directory holds anything + // that deleting it would lose is kept, with the reason. + let mut kept = Vec::new(); + let mut candidates = Vec::new(); + for entry in to_remove { + let wt_path = Path::new(&entry.path); + if is_missing(wt_path) { + candidates.push((entry, None)); + continue; } - return Ok(()); + // Deleting a set would delete any recorded set inside it. + let nested: Vec<&str> = store + .worktrees + .keys() + .map(String::as_str) + .filter(|k| Path::new(k) != wt_path && Path::new(k).starts_with(wt_path)) + .collect(); + let problems = match check_worktree_removal(wt_path) { + _ if !nested.is_empty() => { + format!("it holds other worktree sets: {}", nested.join(", ")) + } + Ok(check) if check.is_clear() => { + candidates.push((entry, Some(check))); + continue; + } + Ok(check) => [check.blockers, check.unsaved].concat().join("; "), + Err(e) => format!("cannot inspect it: {e:#}"), + }; + kept.push(create_prune_entry( + entry.name, + entry.path, + format!("{}, but {problems}", entry.reason), + entry.age_seconds, + )); } - if dry_run { + if dry_run || candidates.is_empty() { + let would_remove: Vec = candidates.into_iter().map(|(e, _)| e).collect(); if json { println!( "{}", serde_json::to_string_pretty(&PruneOutput { - removed: to_remove, - dry_run: true, + removed: would_remove, + kept: kept.clone(), + dry_run, })? ); } else { - println!("Would prune {} worktree(s):", to_remove.len()); - for entry in &to_remove { - println!(" {} ({}) — {}", entry.name, entry.reason, entry.path); + if would_remove.is_empty() { + println!("Nothing to prune."); + } else { + println!("Would prune {} worktree(s):", would_remove.len()); + for entry in &would_remove { + println!(" {} ({}) — {}", entry.name, entry.reason, entry.path); + } } + print_kept(&kept); + } + if !dry_run { + warn_kept(&kept, strict)?; } return Ok(()); } // Actually remove: physical cleanup first, then batch store update. let mut removed = Vec::new(); - for prune_entry in &to_remove { + let mut failed = Vec::new(); + for (prune_entry, check) in candidates { let wt_path = Path::new(&prune_entry.path); - - if wt_path.exists() { - // Try to properly remove via git worktree remove - let repos = discover_worktree_repos(wt_path).unwrap_or_default(); - let _ = remove_worktree_repos(&repos, true, false); - - // Clean up directory - let _ = std::fs::remove_dir_all(wt_path); - - // Only record as removed if directory is actually gone - if wt_path.exists() { - super::warn_or_bail( - strict, - format!("Failed to remove directory: {}", wt_path.display()), - )?; + let removal = match &check { + Some(check) => delete_checked_set(wt_path, check, false, false), + // A missing directory only loses its record. One that has + // reappeared since was never checked: keep it, nothing failed. + None if !is_missing(wt_path) => { + kept.push(create_prune_entry( + prune_entry.name, + prune_entry.path, + format!("{}, but it reappeared", prune_entry.reason), + prune_entry.age_seconds, + )); continue; } + None => Ok(()), + }; + match removal { + Ok(()) => removed.push(prune_entry), + Err(e) => { + failed.push(prune_entry.name.clone()); + kept.push(create_prune_entry( + prune_entry.name, + prune_entry.path, + format!("{}, but removing it failed: {e:#}", prune_entry.reason), + prune_entry.age_seconds, + )); + } } - - removed.push(prune_entry.clone()); } - // Batch-remove all pruned entries from store in a single lock cycle - let keys_to_remove: Vec = removed.iter().map(|e| e.path.clone()).collect(); - super::warn_store_error(store_remove_batch(&keys_to_remove), strict)?; + // Batch-remove the pruned records in a single lock cycle, each only if it + // is still the record this run read. + let records: Vec<(String, String)> = removed + .iter() + .filter_map(|e| { + let entry = store.worktrees.get(&e.path)?; + Some((e.path.clone(), entry.created_at.clone())) + }) + .collect(); + super::warn_store_error(store_remove_batch(&records), strict)?; // Fire post-prune hook let meta_dir = find_meta_dir(); @@ -221,6 +283,7 @@ pub(crate) fn handle_prune( "{}", serde_json::to_string_pretty(&PruneOutput { removed, + kept: kept.clone(), dry_run: false, })? ); @@ -229,9 +292,32 @@ pub(crate) fn handle_prune( for entry in &removed { println!(" {} ({}) — {}", entry.name, entry.reason, entry.path); } + print_kept(&kept); } - Ok(()) + if !failed.is_empty() { + anyhow::bail!("Failed to prune: {}", failed.join(", ")); + } + warn_kept(&kept, strict) +} + +fn print_kept(kept: &[PruneEntry]) { + if kept.is_empty() { + return; + } + println!("Kept {} worktree(s):", kept.len()); + for entry in kept { + println!(" {} ({}) — {}", entry.name, entry.reason, entry.path); + } +} + +/// Kept worktrees are a warning, and an error in strict mode. +fn warn_kept(kept: &[PruneEntry], strict: bool) -> Result<()> { + if kept.is_empty() { + return Ok(()); + } + let names: Vec<&str> = kept.iter().map(|e| e.name.as_str()).collect(); + super::warn_or_bail(strict, format!("Kept worktrees: {}", names.join(", "))) } #[cfg(test)] @@ -368,6 +454,42 @@ mod tests { assert!(result.is_none()); } + #[test] + fn check_repo_orphaned_never_counts_the_root_repo_as_missing() { + let temp_dir = TempDir::new().unwrap(); + let project_path = temp_dir.path(); + let meta_config = r#"{"projects":{"repo3":"git@github.com:org/repo3.git"}}"#; + std::fs::write(project_path.join(".meta"), meta_config).unwrap(); + let project = project_path.to_str().unwrap(); + let mut cache = HashMap::new(); + + let root_only = make_store_entry("root-only", project, vec![(".", "main")]); + assert!(check_repo_orphaned(&root_only, &mut cache).is_none()); + + let root_and_removed = + make_store_entry("removed", project, vec![(".", "main"), ("repo1", "main")]); + assert!(check_repo_orphaned(&root_and_removed, &mut cache).is_none()); + } + + #[test] + fn check_repo_orphaned_finds_nested_aliases() { + let temp_dir = TempDir::new().unwrap(); + let project_path = temp_dir.path(); + let meta_config = + r#"{"projects":{"sub":{"repo":"git@github.com:org/sub.git","meta":true}}}"#; + std::fs::write(project_path.join(".meta"), meta_config).unwrap(); + std::fs::create_dir(project_path.join("sub")).unwrap(); + let sub_config = r#"{"projects":{"leaf":"git@github.com:org/leaf.git"}}"#; + std::fs::write(project_path.join("sub/.meta"), sub_config).unwrap(); + + let entry = make_store_entry( + "nested", + project_path.to_str().unwrap(), + vec![("sub/leaf", "main")], + ); + assert!(check_repo_orphaned(&entry, &mut HashMap::new()).is_none()); + } + #[test] fn check_repo_orphaned_returns_none_when_no_config() { let temp_dir = TempDir::new().unwrap(); diff --git a/src/commands/worktree/remove.rs b/src/commands/worktree/remove.rs index 4a0bef9..b0824f5 100644 --- a/src/commands/worktree/remove.rs +++ b/src/commands/worktree/remove.rs @@ -1,11 +1,10 @@ use anyhow::Result; use colored::*; -use meta_cli::worktree::discover_worktree_repos; -use meta_git_lib::worktree::git_ops::*; use meta_git_lib::worktree::helpers::*; use meta_git_lib::worktree::hooks::fire_post_destroy; -use meta_git_lib::worktree::store::store_remove; +use meta_git_lib::worktree::safety::{check_worktree_removal, delete_checked_set}; +use meta_git_lib::worktree::store::{store_get, store_remove_batch, store_sets_inside}; use meta_git_lib::worktree::types::*; use super::cli_types::DestroyArgs; @@ -28,39 +27,56 @@ pub(crate) fn handle_remove( anyhow::bail!("Worktree '{}' not found at {}", name, wt_dir.display()); } - let repos = discover_worktree_repos(&wt_dir)?; + // Only delete what meta created: the store records every worktree set it made. + let Some((record_key, record)) = store_get(&wt_dir)? else { + anyhow::bail!( + "Refusing to remove {}: meta has no record of creating a worktree there.\n\ + If it is a worktree whose record was lost, delete it yourself and run \ + 'git worktree prune' in its repositories.", + wt_dir.display() + ); + }; - // Check for dirty repos (unless --force) - if !force { - let dirty_repos: Vec<&str> = repos - .iter() - .filter(|r| { - git_status_summary(&r.path) - .map(|s| s.dirty) - .unwrap_or(false) - }) - .map(|r| r.alias.as_str()) - .collect(); - - if !dirty_repos.is_empty() { + let check = check_worktree_removal(&wt_dir)?; + let nested = store_sets_inside(&wt_dir)?; + let blockers: Vec = check + .blockers + .iter() + .cloned() + .chain( + nested + .iter() + .map(|k| format!("{k}: another worktree set; remove it first")), + ) + .collect(); + if !blockers.is_empty() { + anyhow::bail!( + "Refusing to remove worktree '{name}':\n {}\n\ + meta only deletes linked worktrees it can check; move or delete these yourself first.", + blockers.join("\n ") + ); + } + if !check.unsaved.is_empty() { + let found = check.unsaved.join("\n "); + if !force { anyhow::bail!( - "Worktree '{}' has uncommitted changes in: {}.\nUse --force to remove anyway.", - name, - dirty_repos.join(", ") + "Worktree '{name}' has work that removing it would lose:\n {found}\n\ + Commit and push it, or use --force to discard it." ); } + eprintln!( + "{} discarding work in worktree '{name}':\n {found}", + "warning:".yellow().bold() + ); } - // Remove worktrees in correct order (children first, "." last) - remove_worktree_repos(&repos, force, verbose)?; - - // Clean up directory if it still exists - if wt_dir.exists() { - std::fs::remove_dir_all(&wt_dir).ok(); - } + // Remove exactly what was checked, nested worktrees first + delete_checked_set(&wt_dir, &check, force, verbose)?; // Remove from centralized store - super::warn_store_error(store_remove(&wt_dir), strict)?; + // By the key read before deleting: the deleted path can't be resolved again. + let record = [(record_key, record.created_at)]; + super::warn_store_error(store_remove_batch(&record), strict)?; // Fire post-destroy hook fire_post_destroy(name, &wt_dir, force, meta_dir.as_deref()); @@ -69,7 +85,7 @@ pub(crate) fn handle_remove( let output = DestroyOutput { name: name.to_string(), path: wt_dir.display().to_string(), - repos_removed: repos.len(), + repos_removed: check.members.len(), }; println!("{}", serde_json::to_string_pretty(&output)?); } else { diff --git a/src/helpers.rs b/src/helpers.rs index 5819f94..f83231a 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -26,21 +26,3 @@ pub(crate) fn get_project_directories(cwd: &Path) -> anyhow::Result> dirs.extend(paths); Ok(dirs) } - -/// Get all repository directories for snapshot operations (recursive by default) -pub(crate) fn get_all_repo_directories( - projects: &[String], - cwd: &Path, -) -> anyhow::Result> { - if !projects.is_empty() { - return Ok(projects.to_vec()); - } - - let tree = match config::walk_meta_tree(cwd, None) { - Ok(t) => t, - Err(_) => return Ok(vec![".".to_string()]), - }; - let mut dirs = vec![".".to_string()]; - dirs.extend(config::flatten_meta_tree(&tree)); - Ok(dirs) -} diff --git a/src/lib.rs b/src/lib.rs index e44defa..b254232 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,7 +7,6 @@ mod clone_worker; mod commit; mod git_env; mod helpers; -mod snapshot; mod ssh; mod ssh_setup; mod status; @@ -56,10 +55,6 @@ pub fn execute_command( return commands::worktree::execute_worktree_command(command, args, options, cwd); } - if command.starts_with("git snapshot") && help_requested { - return snapshot::execute_snapshot_command_help(command); - } - if help_requested { if let Some(help) = build_passthrough_git_help(command, args, projects, cwd) { return CommandResult::Message(help); @@ -69,25 +64,17 @@ pub fn execute_command( let result = match command { // These act on repos they find themselves, not on the selected ones - "git snapshot restore" | "git update" | "git clone" + "git update" | "git clone" if options.include_filters.is_some() || options.exclude_filters.is_some() => { Err(anyhow::anyhow!( - "meta {command} finds its repos itself (in the snapshot or the .meta files); it does not take --include/--exclude" + "meta {command} finds its repos itself (in the .meta files); it does not take --include/--exclude" )) } "git status" => status::execute_git_status(projects, options, cwd), "git clone" => clone::execute_git_clone(args, options, cwd), "git update" => update::execute_git_update(projects, options.dry_run, cwd), "git commit" => commit::execute_git_commit(args, projects, options, cwd), - "git snapshot" => snapshot::execute_snapshot_help(), - "git snapshot create" => snapshot::execute_snapshot_create(args, projects, cwd), - "git snapshot list" => snapshot::execute_snapshot_list(cwd), - "git snapshot show" => snapshot::execute_snapshot_show(args, cwd), - "git snapshot restore" => { - snapshot::execute_snapshot_restore(args, projects, options.dry_run, cwd) - } - "git snapshot delete" => snapshot::execute_snapshot_delete(args, cwd), // Fallback: run raw git command across all repos _ => return execute_raw_git_command(command, args, projects, options, cwd), }; @@ -132,9 +119,7 @@ fn build_passthrough_git_help( return None; } - let adapted_commands = [ - "clone", "status", "update", "commit", "snapshot", "worktree", - ]; + let adapted_commands = ["clone", "status", "update", "commit", "worktree"]; let git_args: Vec = command_words .iter() .skip(1) @@ -310,27 +295,6 @@ SPECIAL COMMANDS: meta git commit --edit Opens an editor to create different commit messages for each repo. -SNAPSHOT COMMANDS (EXPERIMENTAL - file format subject to change): - Capture and restore workspace state for safe batch operations: - - meta git snapshot create - Record the current git state (SHA, branch, dirty status) of ALL repos. - Snapshots are recursive by default - they capture the entire workspace. - - meta git snapshot list - List all available snapshots with creation date and repo count. - - meta git snapshot show - Display details of a snapshot including per-repo state. - - meta git snapshot restore [--force] [--dry-run] - Restore all repos to the recorded snapshot state. Prompts for confirmation. - Dirty repos are automatically stashed before restore. - Use --force to skip confirmation, --dry-run to preview changes. - - meta git snapshot delete - Delete a snapshot file. - PASS-THROUGH COMMANDS: All other git commands are passed through to each repository: @@ -355,8 +319,6 @@ Examples: meta git pull --tag backend meta git commit --edit meta git checkout -b feature/new --include-only api,frontend - meta git snapshot create before-upgrade - meta git snapshot restore before-upgrade "# } diff --git a/src/main.rs b/src/main.rs index 6d855d8..52eb9ec 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,10 +27,6 @@ fn main() { "update".to_string(), "Pull existing repos and clone any missing repos".to_string(), ); - adapted.insert( - "snapshot".to_string(), - "Save and restore workspace state across all repos".to_string(), - ); adapted.insert( "worktree".to_string(), "Create isolated worktree sets for multi-repo branches".to_string(), @@ -60,12 +56,6 @@ fn main() { "git status".to_string(), "git update".to_string(), "git commit".to_string(), - "git snapshot".to_string(), - "git snapshot create".to_string(), - "git snapshot list".to_string(), - "git snapshot show".to_string(), - "git snapshot restore".to_string(), - "git snapshot delete".to_string(), "git worktree".to_string(), "git worktree create".to_string(), "git worktree add".to_string(), @@ -87,8 +77,6 @@ fn main() { "meta git status".to_string(), "meta git commit -m \"Update all repos\"".to_string(), "meta git commit --edit # Per-repo messages".to_string(), - "meta git snapshot create before-refactor".to_string(), - "meta git snapshot restore before-refactor".to_string(), "meta git worktree create feature-x --repo api --repo web".to_string(), ], note: Some( diff --git a/src/snapshot.rs b/src/snapshot.rs deleted file mode 100644 index eb040dd..0000000 --- a/src/snapshot.rs +++ /dev/null @@ -1,462 +0,0 @@ -use crate::helpers::get_all_repo_directories; -use chrono::Utc; -use console::style; -use dialoguer::Confirm; -use meta_git_lib::snapshot::{self, RepoState, Snapshot}; -use meta_plugin_protocol::CommandResult; -use rayon::prelude::*; -use std::collections::HashMap; -use std::path::Path; - -/// Show snapshot help text -pub(crate) fn execute_snapshot_help() -> anyhow::Result { - println!( - r#"{} - -{} - -Usage: meta git snapshot [args] - -Commands: - {} Create a snapshot of all repos' git state - {} List all available snapshots - {} Show details of a snapshot - {} Restore all repos to a snapshot state - {} Delete a snapshot - -Examples: - meta git snapshot create before-upgrade - meta git snapshot list - meta git snapshot show before-upgrade - meta git snapshot restore before-upgrade --dry-run - meta git snapshot restore before-upgrade --force - meta git snapshot delete before-upgrade - -Snapshots capture the entire workspace state (recursive by default). -Use --force to skip confirmation on restore, --dry-run to preview."#, - style("meta git snapshot - Workspace State Management").bold(), - style("[EXPERIMENTAL] File format is subject to change.").yellow(), - style("create ").cyan(), - style("list").cyan(), - style("show ").cyan(), - style("restore ").cyan(), - style("delete ").cyan(), - ); - Ok(CommandResult::Message(String::new())) -} - -pub(crate) fn execute_snapshot_command_help(command: &str) -> CommandResult { - let subcommand = command - .split_whitespace() - .filter(|word| *word != "--help" && *word != "-h") - .nth(2); - - let Some(subcommand) = subcommand else { - return execute_snapshot_help().unwrap_or_else(|e| { - CommandResult::Error(format!("Failed to show snapshot help: {e}")) - }); - }; - - let help = match subcommand { - "create" => { - r#"meta git snapshot create - Save workspace git state - -Usage: meta git snapshot create - -Records each repo's current SHA, branch, and dirty status. - -Examples: - meta git snapshot create before-refactor - meta git snapshot create before-upgrade"# - } - "list" => { - r#"meta git snapshot list - List saved workspace snapshots - -Usage: meta git snapshot list - -Shows snapshot names, creation times, repo counts, and dirty repo counts. - -Examples: - meta git snapshot list"# - } - "show" => { - r#"meta git snapshot show - Display one snapshot - -Usage: meta git snapshot show - -Shows per-repo branch, SHA, and dirty state recorded in a snapshot. - -Examples: - meta git snapshot show before-refactor"# - } - "restore" => { - r#"meta git snapshot restore - Restore workspace git state - -Usage: meta git snapshot restore [--force] [--dry-run] - -Restores repos to the recorded branches/SHAs. Dirty repos are stashed before restore. - -Options: - --force Skip confirmation - --dry-run Preview restore actions without changing repos - -Examples: - meta git snapshot restore before-refactor --dry-run - meta git snapshot restore before-refactor --force"# - } - "delete" => { - r#"meta git snapshot delete - Delete a saved snapshot - -Usage: meta git snapshot delete - -Examples: - meta git snapshot delete before-refactor"# - } - _ => { - return CommandResult::ShowHelp(Some(format!( - "unknown snapshot command '{subcommand}'" - ))); - } - }; - - CommandResult::Message(help.to_string()) -} - -/// Create a snapshot of the current workspace state -pub(crate) fn execute_snapshot_create( - args: &[String], - projects: &[String], - cwd: &Path, -) -> anyhow::Result { - // Parse snapshot name from args - let name = args - .iter() - .find(|a| !a.starts_with('-')) - .ok_or_else(|| anyhow::anyhow!("Usage: meta git snapshot create "))?; - - // Get all repos (recursive by default) - let dirs = get_all_repo_directories(projects, cwd)?; - - println!( - "Creating snapshot '{}' of {} repos...", - style(name).cyan(), - dirs.len() - ); - - // Capture repo states in parallel - let results: Vec<_> = dirs - .par_iter() - .map(|dir| { - let path = if dir == "." { - cwd.to_path_buf() - } else { - cwd.join(dir) - }; - - if !path.exists() || !snapshot::is_git_repo(&path) { - return (dir.clone(), None); - } - - let state = snapshot::capture_repo_state(&path); - (dir.clone(), Some(state)) - }) - .collect(); - - // Process results sequentially for display - let mut repos = HashMap::new(); - let mut dirty_count = 0; - - for (dir, result) in &results { - match result { - None => { - println!( - " {} {} (not a git repo, skipping)", - style("⚠").yellow(), - dir - ); - } - Some(Ok(state)) => { - if state.dirty { - dirty_count += 1; - println!(" {} {} (dirty)", style("○").yellow(), dir); - } else { - println!(" {} {}", style("✓").green(), dir); - } - repos.insert(dir.clone(), state.clone()); - } - Some(Err(e)) => { - println!(" {} {} (error: {})", style("✗").red(), dir, e); - } - } - } - - if repos.is_empty() { - anyhow::bail!("No repos captured"); - } - - let snap = Snapshot { - name: name.clone(), - created: Utc::now(), - repos, - }; - - snapshot::save_snapshot(cwd, &snap)?; - - println!(); - println!( - "{} Captured state of {} repos", - style("✓").green(), - snap.repos.len() - ); - if dirty_count > 0 { - println!( - "{} {} repo(s) have uncommitted changes (recorded as dirty)", - style("⚠").yellow(), - dirty_count - ); - } - println!( - "Snapshot saved: {}", - style(format!(".meta-snapshots/{name}.json")).dim() - ); - - Ok(CommandResult::Message(String::new())) -} - -/// List all snapshots -pub(crate) fn execute_snapshot_list(cwd: &Path) -> anyhow::Result { - let snapshots = snapshot::list_snapshots(cwd)?; - - if snapshots.is_empty() { - println!("No snapshots found."); - println!( - "Create one with: {}", - style("meta git snapshot create ").cyan() - ); - return Ok(CommandResult::Message(String::new())); - } - - println!("Snapshots:\n"); - for info in snapshots { - let dirty_note = if info.dirty_count > 0 { - format!(" ({} dirty)", info.dirty_count) - } else { - String::new() - }; - println!( - " {} - {} repos{} - {}", - style(&info.name).cyan().bold(), - info.repo_count, - style(dirty_note).yellow(), - style(info.created.format("%Y-%m-%d %H:%M:%S")).dim() - ); - } - println!(); - - Ok(CommandResult::Message(String::new())) -} - -/// Show details of a snapshot -pub(crate) fn execute_snapshot_show(args: &[String], cwd: &Path) -> anyhow::Result { - let name = args - .iter() - .find(|a| !a.starts_with('-')) - .ok_or_else(|| anyhow::anyhow!("Usage: meta git snapshot show "))?; - - let snap = snapshot::load_snapshot(cwd, name)?; - - println!("Snapshot: {}", style(&snap.name).cyan().bold()); - println!("Created: {}", snap.created.format("%Y-%m-%d %H:%M:%S UTC")); - println!("Repos: {}", snap.repos.len()); - println!(); - - // Sort repos by name for consistent output - let mut repos: Vec<_> = snap.repos.iter().collect(); - repos.sort_by(|a, b| a.0.cmp(b.0)); - - for (name, state) in repos { - let branch_info = state - .branch - .as_ref() - .map(|b| format!(" -> {b}")) - .unwrap_or_else(|| " (detached)".to_string()); - - let dirty_marker = if state.dirty { - format!(" {}", style("(dirty)").yellow()) - } else { - String::new() - }; - - println!( - " {} {}{}{}", - style(&state.sha[..8]).dim(), - name, - style(branch_info).cyan(), - dirty_marker - ); - } - - Ok(CommandResult::Message(String::new())) -} - -/// Restore workspace to a snapshot state -pub(crate) fn execute_snapshot_restore( - args: &[String], - _projects: &[String], - dry_run: bool, - cwd: &Path, -) -> anyhow::Result { - // Parse args - let mut name: Option<&str> = None; - let mut force = false; - let mut dry_run = dry_run; - - for arg in args { - match arg.as_str() { - "--force" | "-f" => force = true, - "--dry-run" => dry_run = true, - s if !s.starts_with('-') => name = Some(s), - _ => {} - } - } - - let name = name.ok_or_else(|| { - anyhow::anyhow!("Usage: meta git snapshot restore [--force] [--dry-run]") - })?; - - let snap = snapshot::load_snapshot(cwd, name)?; - - // Analyze what would change - let mut repos_to_restore: Vec<(&str, &RepoState, bool)> = Vec::new(); - let mut missing_repos = Vec::new(); - - for (repo_name, state) in &snap.repos { - let path = if repo_name == "." { - cwd.to_path_buf() - } else { - cwd.join(repo_name) - }; - - if !path.exists() || !snapshot::is_git_repo(&path) { - missing_repos.push(repo_name.as_str()); - continue; - } - - // Check if current state is dirty - let current_state = snapshot::capture_repo_state(&path)?; - repos_to_restore.push((repo_name, state, current_state.dirty)); - } - - let dirty_count = repos_to_restore.iter().filter(|(_, _, d)| *d).count(); - - // Show preview - println!( - "Restore {} repos to snapshot '{}':", - repos_to_restore.len(), - style(name).cyan() - ); - println!( - " - {} repos will checkout to their recorded SHA", - repos_to_restore.len() - dirty_count - ); - if dirty_count > 0 { - println!( - " - {} repos have uncommitted changes (will be stashed)", - style(dirty_count).yellow() - ); - } - if !missing_repos.is_empty() { - println!( - " - {} repos missing (will be skipped): {}", - style(missing_repos.len()).red(), - missing_repos.join(", ") - ); - } - println!(); - - if dry_run { - println!("{} Dry run - no changes made", style("[DRY RUN]").cyan()); - return Ok(CommandResult::Message(String::new())); - } - - // Confirm unless --force - if !force { - let proceed = Confirm::new() - .with_prompt("Proceed?") - .default(false) - .interact()?; - - if !proceed { - println!("Aborted."); - return Ok(CommandResult::Message(String::new())); - } - } - - // Execute restore - println!("Restoring..."); - let mut success_count = 0; - let mut fail_count = 0; - - for (repo_name, state, _is_dirty) in &repos_to_restore { - let path = if *repo_name == "." { - cwd.to_path_buf() - } else { - cwd.join(repo_name) - }; - - let result = snapshot::restore_repo_state(&path, state, force)?; - - if result.success { - let stash_note = if result.stashed { - format!(" {}", style("(stashed changes)").yellow()) - } else { - String::new() - }; - println!( - " {} {} {}{}", - style("✓").green(), - repo_name, - result.message, - stash_note - ); - success_count += 1; - } else { - println!(" {} {} {}", style("✗").red(), repo_name, result.message); - fail_count += 1; - } - } - - println!(); - if fail_count > 0 { - println!( - "Restored {} repo(s), {} failed", - style(success_count).green(), - style(fail_count).red() - ); - } else { - println!("{} Restored {} repo(s)", style("✓").green(), success_count); - } - - Ok(CommandResult::Message(String::new())) -} - -/// Delete a snapshot -pub(crate) fn execute_snapshot_delete( - args: &[String], - cwd: &Path, -) -> anyhow::Result { - let name = args - .iter() - .find(|a| !a.starts_with('-')) - .ok_or_else(|| anyhow::anyhow!("Usage: meta git snapshot delete "))?; - - snapshot::delete_snapshot(cwd, name)?; - - println!( - "{} Deleted snapshot '{}'", - style("✓").green(), - style(name).cyan() - ); - - Ok(CommandResult::Message(String::new())) -} diff --git a/src/update.rs b/src/update.rs index 7ba0998..73b9170 100644 --- a/src/update.rs +++ b/src/update.rs @@ -139,6 +139,9 @@ pub(crate) fn execute_git_update( let mp = MultiProgress::new(); clone_with_queue(Arc::clone(&queue), parallel, &mp, ssh_cmd.as_deref())?; + if let Some(error) = crate::clone_worker::report_failures(&queue) { + return Ok(CommandResult::Error(error)); + } let (completed, total) = queue.get_counts(); if total > initial_count { diff --git a/tests/safety.rs b/tests/safety.rs new file mode 100644 index 0000000..d32b960 --- /dev/null +++ b/tests/safety.rs @@ -0,0 +1,731 @@ +//! Commands that delete or report must check what they act on. + +use serde_json::{json, Value}; +use std::{ + fs, + io::Write, + path::Path, + process::{Command, Output, Stdio}, +}; + +/// Run a Git fixture command and surface diagnostics on failure. +fn git(path: &Path, args: &[&str]) { + let out = Command::new("git") + .arg("-C") + .arg(path) + .args(["-c", "user.name=Test", "-c", "user.email=test@example.com"]) + .args(args) + .output() + .unwrap(); + assert!( + out.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); +} + +/// A bare repo at `path` with one commit on `main`. +fn upstream(path: &Path) { + let seed = path.with_extension("seed"); + fs::create_dir_all(&seed).unwrap(); + git(&seed, &["init", "-q", "-b", "main"]); + fs::write(seed.join("README"), "hello\n").unwrap(); + git(&seed, &["add", "README"]); + git(&seed, &["commit", "-qm", "init"]); + git( + &seed, + &["clone", "-q", "--bare", ".", path.to_str().unwrap()], + ); +} + +/// A meta project at `root/ws` (itself a repo) with the given projects cloned. +fn workspace(root: &Path, projects: &[&str]) -> std::path::PathBuf { + let ws = root.join("ws"); + fs::create_dir_all(&ws).unwrap(); + git(&ws, &["init", "-q", "-b", "main"]); + let mut config = serde_json::Map::new(); + for name in projects { + let url = root.join("up").join(format!("{name}.git")); + upstream(&url); + git(&ws, &["clone", "-q", url.to_str().unwrap(), name]); + config.insert(name.to_string(), json!(url)); + } + fs::write(ws.join(".meta"), json!({ "projects": config }).to_string()).unwrap(); + fs::write( + ws.join(".gitignore"), + format!("{}\n.worktrees/\n", projects.join("\n")), + ) + .unwrap(); + git(&ws, &["add", "."]); + git(&ws, &["commit", "-qm", "meta"]); + ws +} + +/// Invoke the plugin protocol in `cwd` with an isolated store under `root/data`. +fn meta_git(root: &Path, cwd: &Path, command: &str, args: &[&str], options: Value) -> Output { + let request = json!({"command": command, "args": args, "cwd": cwd, "options": options}); + let mut cmd = Command::new(env!("CARGO_BIN_EXE_meta-git")); + if root.join("bin").is_dir() { + let path = std::env::var_os("PATH").unwrap_or_default(); + let paths = std::iter::once(root.join("bin")).chain(std::env::split_paths(&path)); + cmd.env("PATH", std::env::join_paths(paths).unwrap()); + } + let mut child = cmd + .arg("--meta-plugin-exec") + .current_dir(cwd) + .env("META_DATA_DIR", root.join("data")) + .env_remove("META_WORKTREES") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(request.to_string().as_bytes()) + .unwrap(); + child.wait_with_output().unwrap() +} + +fn worktree(root: &Path, ws: &Path, args: &[&str]) -> Output { + let (sub, rest) = args.split_first().unwrap(); + meta_git(root, ws, &format!("git worktree {sub}"), rest, json!({})) +} + +fn stderr(out: &Output) -> String { + String::from_utf8_lossy(&out.stderr).into_owned() +} + +#[test] +fn remove_refuses_directories_meta_did_not_create() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let ws = workspace(root, &["a"]); + + // A plain directory where a worktree would be. + fs::create_dir_all(ws.join(".worktrees/notawt")).unwrap(); + fs::write(ws.join(".worktrees/notawt/data"), "keep").unwrap(); + let out = worktree(root, &ws, &["remove", "notawt", "--force"]); + assert!(!out.status.success()); + assert!(stderr(&out).contains("no record"), "{}", stderr(&out)); + assert!(ws.join(".worktrees/notawt/data").exists()); + + // worktrees_dir "." makes the primary clone `a` look like a worktree. Even + // with a forged store record, a primary checkout is never deleted. + let config = json!({"worktrees_dir": ".", "projects": {"a": "unused"}}); + fs::write(ws.join(".meta"), config.to_string()).unwrap(); + let key = ws.join("a").canonicalize().unwrap(); + let store = json!({"worktrees": {key.to_str().unwrap(): { + "name": "a", "project": ws, "created_at": "2026-01-01T00:00:00Z", + "ephemeral": false, "ttl_seconds": null, "repos": [], "custom": {}}}}); + fs::create_dir_all(root.join("data")).unwrap(); + fs::write(root.join("data/worktree.json"), store.to_string()).unwrap(); + let out = worktree(root, &ws, &["remove", "a", "--force"]); + assert!(!out.status.success()); + assert!( + stderr(&out).contains("not a linked worktree"), + "{}", + stderr(&out) + ); + assert!(ws.join("a/README").exists()); +} + +#[test] +fn remove_checks_repos_nested_in_other_repos() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + // ws -> sub (a nested meta repo) -> leaf + let up = root.join("up"); + for name in ["sub", "leaf"] { + upstream(&up.join(format!("{name}.git"))); + } + let ws = workspace(root, &[]); + git( + &ws, + &["clone", "-q", up.join("sub.git").to_str().unwrap(), "sub"], + ); + let sub = ws.join("sub"); + git( + &sub, + &["clone", "-q", up.join("leaf.git").to_str().unwrap(), "leaf"], + ); + let leaf_url = up.join("leaf.git"); + fs::write( + sub.join(".meta"), + json!({"projects": {"leaf": leaf_url}}).to_string(), + ) + .unwrap(); + fs::write(sub.join(".gitignore"), "leaf/\n").unwrap(); + git(&sub, &["add", "."]); + git(&sub, &["commit", "-qm", "meta"]); + let config = json!({"projects": {"sub": {"repo": up.join("sub.git"), "meta": true}}}); + fs::write(ws.join(".meta"), config.to_string()).unwrap(); + fs::write(ws.join(".gitignore"), "sub/\n.worktrees/\n").unwrap(); + git(&ws, &["commit", "-qam", "sub"]); + + let out = meta_git( + root, + &ws, + "git worktree create", + &["t1", "--repo", "sub/leaf"], + json!({"recursive": true}), + ); + assert!(out.status.success(), "{}", stderr(&out)); + let work = ws.join(".worktrees/t1/sub/leaf/NEW_WORK.txt"); + fs::write(&work, "precious").unwrap(); + + let out = worktree(root, &ws, &["remove", "t1"]); + assert!(!out.status.success()); + let message = stderr(&out).replace('\\', "/"); + assert!( + message.contains("sub/leaf: 1 file untracked: NEW_WORK.txt"), + "{message}" + ); + assert!(work.exists()); + + // --force discards the work, but never deletes what git still has registered. + let leaf_wt = ws.join(".worktrees/t1/sub/leaf"); + git( + &sub.join("leaf"), + &["worktree", "lock", leaf_wt.to_str().unwrap()], + ); + let out = worktree(root, &ws, &["remove", "t1", "--force"]); + assert!(!out.status.success()); + assert!(stderr(&out).contains("locked"), "{}", stderr(&out)); + assert!(work.exists()); + git( + &sub.join("leaf"), + &["worktree", "unlock", leaf_wt.to_str().unwrap()], + ); + + fs::remove_file(&work).unwrap(); + let out = worktree(root, &ws, &["remove", "t1"]); + assert!(out.status.success(), "{}", stderr(&out)); + assert!(!ws.join(".worktrees/t1").exists()); + // The nested repo's worktree was unregistered, not just deleted. + let list = Command::new("git") + .args(["worktree", "list", "--porcelain"]) + .current_dir(sub.join("leaf")) + .output() + .unwrap(); + assert_eq!( + String::from_utf8_lossy(&list.stdout) + .matches("worktree ") + .count(), + 1 + ); +} + +#[test] +fn prune_keeps_worktrees_that_hold_work() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let ws = workspace(root, &["a"]); + + // A root-only worktree is not "orphaned": "." is never in the project list. + let out = worktree( + root, + &ws, + &["create", "rootonly", "--repo", ".", "--no-deps"], + ); + assert!(out.status.success(), "{}", stderr(&out)); + fs::write(ws.join(".worktrees/rootonly/NOTES.md"), "notes").unwrap(); + // An expired worktree with uncommitted work is kept too. + let out = worktree( + root, + &ws, + &[ + "create", + "expired", + "--repo", + "a", + "--no-deps", + "--ttl", + "0", + ], + ); + assert!(out.status.success(), "{}", stderr(&out)); + fs::write(ws.join(".worktrees/expired/a/README"), "edited").unwrap(); + // Expired clean ones are pruned, unless removing one fails. + for name in ["clean", "locked"] { + let out = worktree( + root, + &ws, + &["create", name, "--repo", "a", "--no-deps", "--ttl", "0"], + ); + assert!(out.status.success(), "{}", stderr(&out)); + } + let locked = ws.join(".worktrees/locked/a"); + git( + &ws.join("a"), + &["worktree", "lock", locked.to_str().unwrap()], + ); + + let out = meta_git( + root, + &ws, + "git worktree prune", + &[], + json!({"json_output": true}), + ); + assert!(!out.status.success()); + assert!( + stderr(&out).contains("Failed to prune: locked"), + "{}", + stderr(&out) + ); + let report: Value = serde_json::from_slice(&out.stdout).unwrap(); + let names = |key: &str| -> Vec { + let mut names: Vec = report[key] + .as_array() + .unwrap() + .iter() + .map(|e| e["name"].as_str().unwrap().to_string()) + .collect(); + names.sort(); + names + }; + assert_eq!(names("removed"), ["clean"]); + assert_eq!(names("kept"), ["expired", "locked"]); + assert!(locked.exists()); + assert!(ws.join(".worktrees/rootonly/NOTES.md").exists()); + assert!(ws.join(".worktrees/expired/a/README").exists()); + assert!(!ws.join(".worktrees/clean").exists()); +} + +#[cfg(unix)] +#[test] +fn hook_with_large_stderr_output_does_not_hang_create() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let ws = workspace(root, &["a"]); + // More than any pipe buffer (64 KiB by default, 1 MiB at most). + let hook = "head -c 4000000 /dev/zero >&2"; + let config = json!({"projects": {"a": "unused"}, "worktree": {"hooks": {"post-create": hook}}}); + fs::write(ws.join(".meta"), config.to_string()).unwrap(); + + let (tx, rx) = std::sync::mpsc::channel(); + let (root_path, ws_path) = (root.to_path_buf(), ws.clone()); + std::thread::spawn(move || { + let _ = tx.send(worktree( + &root_path, + &ws_path, + &["create", "w", "--repo", "a", "--no-deps"], + )); + }); + let out = rx + .recv_timeout(std::time::Duration::from_secs(120)) + .expect("worktree create hung on a hook's stderr output"); + let head = out.stderr.get(..200).unwrap_or(&out.stderr); + assert!(out.status.success(), "{}", String::from_utf8_lossy(head)); + assert!(out.stderr.len() >= 4_000_000); +} + +#[test] +fn from_ref_that_no_repo_has_creates_nothing() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let ws = workspace(root, &["a"]); + + let out = worktree( + root, + &ws, + &["create", "r1", "--repo", "a", "--no-deps", "no-such-ref"], + ); + assert!(!out.status.success()); + assert!( + stderr(&out).contains("no worktree was created"), + "{}", + stderr(&out) + ); + assert!(!ws.join(".worktrees/r1").exists()); +} + +#[cfg(unix)] +#[test] +fn from_pr_applies_only_to_the_exact_repo() { + use std::os::unix::fs::PermissionsExt; + + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + // Remotes end in org/api and org/api-legacy, as GitHub URLs would. + let up = root.join("up/org"); + let ws = root.join("ws"); + fs::create_dir_all(&ws).unwrap(); + git(&ws, &["init", "-q", "-b", "main"]); + for (alias, repo) in [("legacy", "api-legacy"), ("service", "api")] { + let url = up.join(format!("{repo}.git")); + upstream(&url); + git(&ws, &["clone", "-q", url.to_str().unwrap(), alias]); + } + git( + &ws.join("service"), + &["push", "-q", "origin", "main:feature-x"], + ); + let config = + json!({"projects": {"legacy": up.join("api-legacy.git"), "service": up.join("api.git")}}); + fs::write(ws.join(".meta"), config.to_string()).unwrap(); + fs::write(ws.join(".gitignore"), "legacy\nservice\n.worktrees/\n").unwrap(); + git(&ws, &["add", "."]); + git(&ws, &["commit", "-qm", "meta"]); + // A stand-in `gh` that reports the PR's head branch. + fs::create_dir(root.join("bin")).unwrap(); + fs::write(root.join("bin/gh"), "#!/bin/sh\necho feature-x\n").unwrap(); + fs::set_permissions(root.join("bin/gh"), fs::Permissions::from_mode(0o755)).unwrap(); + + let out = meta_git( + root, + &ws, + "git worktree create", + &["pr1", "--from-pr", "org/api#5", "--all"], + json!({"json_output": true}), + ); + assert!(out.status.success(), "{}", stderr(&out)); + let created: Value = serde_json::from_slice(&out.stdout).unwrap(); + let branch_of = |alias: &str| { + created["repos"] + .as_array() + .unwrap() + .iter() + .find(|r| r["alias"] == alias) + .map(|r| r["branch"].as_str().unwrap().to_string()) + }; + assert_eq!(branch_of("service").as_deref(), Some("feature-x")); + assert_eq!(branch_of("legacy").as_deref(), Some("pr1")); + + // A PR whose repo isn't selected is an error, not a silent no-op. + let out = worktree( + root, + &ws, + &[ + "create", + "pr2", + "--from-pr", + "org/api#5", + "--repo", + "legacy", + "--no-deps", + ], + ); + assert!(!out.status.success()); + assert!( + stderr(&out).contains("No selected repo has origin 'org/api'"), + "{}", + stderr(&out) + ); + assert!(!ws.join(".worktrees/pr2").exists()); +} + +#[test] +fn update_reports_failed_clones_and_exits_nonzero() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let ws = root.join("ws"); + fs::create_dir_all(&ws).unwrap(); + upstream(&root.join("good.git")); + let config = json!({"projects": { + "good": root.join("good.git"), + "missing": root.join("does-not-exist.git"), + }}); + fs::write(ws.join(".meta"), config.to_string()).unwrap(); + + let out = meta_git(root, &ws, "git update", &[], json!({})); + assert!(!out.status.success()); + let message = stderr(&out); + assert!( + message.contains("1 of 2 repositories failed to clone: missing"), + "{message}" + ); + assert!(message.contains("does-not-exist.git"), "{message}"); + assert!(ws.join("good/README").exists()); +} + +#[test] +fn failed_create_rolls_back_what_it_created() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let ws = workspace(root, &["a", "b"]); + // a only has `origin/t`, so creating `t` makes a local tracking branch. + git(&ws.join("a"), &["push", "-q", "origin", "main:t"]); + git(&ws.join("a"), &["fetch", "-q"]); + // b's branch `t` is checked out elsewhere, so creating `t` fails at b. + git(&ws.join("b"), &["branch", "t"]); + let elsewhere = root.join("elsewhere"); + git( + &ws.join("b"), + &["worktree", "add", "-q", elsewhere.to_str().unwrap(), "t"], + ); + + let args = ["create", "t", "--repo", "a", "--repo", "b", "--no-deps"]; + let out = worktree(root, &ws, &args); + assert!(!out.status.success()); + assert!(!ws.join(".worktrees/t").exists(), "{}", stderr(&out)); + let list = Command::new("git") + .args(["worktree", "list", "--porcelain"]) + .current_dir(ws.join("a")) + .output() + .unwrap(); + assert_eq!( + String::from_utf8_lossy(&list.stdout) + .matches("worktree ") + .count(), + 1 + ); + + // The branch this call created in a is gone too. + let branch = Command::new("git") + .args(["rev-parse", "--verify", "--quiet", "refs/heads/t"]) + .current_dir(ws.join("a")) + .output() + .unwrap(); + assert!(!branch.status.success()); + + // Nothing is stranded: the same command from a ref can be run again. + git(&ws.join("a"), &["tag", "v1"]); + let args = [ + "create", + "t", + "v1", + "--repo", + "a", + "--repo", + "b", + "--no-deps", + "--strict", + ]; + let out = worktree(root, &ws, &args); + assert!(!out.status.success(), "b has no v1, so --strict fails"); + assert!(!ws.join(".worktrees/t").exists(), "{}", stderr(&out)); + let out = worktree( + root, + &ws, + &["create", "t", "v1", "--repo", "a", "--no-deps"], + ); + assert!(out.status.success(), "{}", stderr(&out)); +} + +#[test] +fn from_ref_create_fails_on_anything_but_a_missing_ref() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let ws = workspace(root, &["a", "b"]); + git(&ws.join("a"), &["tag", "v1"]); + git(&ws.join("b"), &["tag", "v1"]); + // b has the ref, but its branch `t` already exists, so `-b t` fails there. + git(&ws.join("b"), &["branch", "t"]); + + let args = [ + "create", + "t", + "v1", + "--repo", + "a", + "--repo", + "b", + "--no-deps", + ]; + let out = worktree(root, &ws, &args); + assert!( + !out.status.success(), + "a real failure is not a skipped repo" + ); + assert!(!ws.join(".worktrees/t").exists(), "{}", stderr(&out)); + let branch = Command::new("git") + .args(["rev-parse", "--verify", "--quiet", "refs/heads/t"]) + .current_dir(ws.join("a")) + .output() + .unwrap(); + assert!(!branch.status.success(), "a's new branch was rolled back"); +} + +#[test] +fn from_ref_create_fails_when_a_repo_cannot_be_read() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let ws = workspace(root, &["a", "b"]); + git(&ws.join("a"), &["tag", "v1"]); + git(&ws.join("b"), &["tag", "v1"]); + let config = ws.join("b/.git/config"); + let mut broken = fs::read_to_string(&config).unwrap(); + broken.push_str("[broken\n"); + fs::write(&config, broken).unwrap(); + + let args = [ + "create", + "t", + "v1", + "--repo", + "a", + "--repo", + "b", + "--no-deps", + ]; + let out = worktree(root, &ws, &args); + assert!( + !out.status.success(), + "an unreadable repo is not a missing ref" + ); + assert!(stderr(&out).contains("config"), "{}", stderr(&out)); + assert!(!ws.join(".worktrees/t").exists()); +} + +#[test] +fn a_set_holding_another_recorded_set_is_not_deleted() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let ws = workspace(root, &["a"]); + let out = worktree(root, &ws, &["create", "outer", "--repo", ".", "--no-deps"]); + assert!(out.status.success(), "{}", stderr(&out)); + // A set created from inside the outer one lands in its .worktrees. + let outer = ws.join(".worktrees/outer"); + let out = worktree( + root, + &outer, + &["create", "inner", "--repo", ".", "--no-deps"], + ); + assert!(out.status.success(), "{}", stderr(&out)); + assert!(outer.join(".worktrees/inner").exists()); + + let out = worktree(root, &ws, &["remove", "outer", "--force"]); + assert!(!out.status.success()); + assert!( + stderr(&out).contains("another worktree set"), + "{}", + stderr(&out) + ); + assert!(outer.join(".worktrees/inner/.git").exists()); +} + +#[cfg(unix)] +#[test] +fn prune_keeps_a_dangling_link_at_a_recorded_path() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let ws = workspace(root, &["a"]); + let out = worktree( + root, + &ws, + &["create", "gone", "--repo", "a", "--no-deps", "--ttl", "0"], + ); + assert!(out.status.success(), "{}", stderr(&out)); + // Replace the set with a link to storage that has since disappeared. + let set = ws.join(".worktrees/gone"); + let check = std::fs::canonicalize(&set).unwrap(); + git( + &ws.join("a"), + &["worktree", "remove", set.join("a").to_str().unwrap()], + ); + fs::remove_dir_all(&set).unwrap(); + std::os::unix::fs::symlink(root.join("vanished"), &set).unwrap(); + assert_eq!(check, ws.canonicalize().unwrap().join(".worktrees/gone")); + + let out = meta_git( + root, + &ws, + "git worktree prune", + &[], + json!({"json_output": true}), + ); + assert!(out.status.success(), "{}", stderr(&out)); + let report: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(report["kept"][0]["name"], "gone", "{report}"); + assert!(set.symlink_metadata().is_ok()); +} + +#[cfg(unix)] +#[test] +fn remove_drops_the_record_when_the_worktrees_dir_is_a_link() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let ws = workspace(root, &["a"]); + fs::create_dir(root.join("real")).unwrap(); + std::os::unix::fs::symlink(root.join("real"), root.join("link")).unwrap(); + let config = json!({"worktrees_dir": "../link", "projects": {"a": "unused"}}); + fs::write(ws.join(".meta"), config.to_string()).unwrap(); + + let out = worktree(root, &ws, &["create", "t", "--repo", "a", "--no-deps"]); + assert!(out.status.success(), "{}", stderr(&out)); + let out = worktree(root, &ws, &["remove", "t"]); + assert!(out.status.success(), "{}", stderr(&out)); + let store: Value = + serde_json::from_str(&fs::read_to_string(root.join("data/worktree.json")).unwrap()) + .unwrap(); + assert_eq!(store["worktrees"], json!({}), "the record is gone"); +} + +#[cfg(unix)] +#[test] +fn prune_keeps_a_worktree_it_cannot_inspect() { + use std::os::unix::fs::PermissionsExt; + + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let ws = workspace(root, &["a"]); + let out = worktree( + root, + &ws, + &["create", "x", "--repo", "a", "--no-deps", "--ttl", "0"], + ); + assert!(out.status.success(), "{}", stderr(&out)); + let parent = ws.join(".worktrees"); + fs::set_permissions(&parent, fs::Permissions::from_mode(0o000)).unwrap(); + if fs::read_dir(&parent).is_ok() { + // Running as root: permissions don't apply. + fs::set_permissions(&parent, fs::Permissions::from_mode(0o755)).unwrap(); + return; + } + + let out = meta_git( + root, + &ws, + "git worktree prune", + &[], + json!({"json_output": true}), + ); + fs::set_permissions(&parent, fs::Permissions::from_mode(0o755)).unwrap(); + assert!(out.status.success(), "{}", stderr(&out)); + let report: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(report["removed"], json!([]), "{report}"); + assert_eq!(report["kept"][0]["name"], "x", "{report}"); + assert!(ws.join(".worktrees/x/a/README").exists()); +} + +#[cfg(unix)] +#[test] +fn rollback_keeps_a_branch_a_checkout_hook_committed_on() { + use std::os::unix::fs::PermissionsExt; + + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let ws = workspace(root, &["a", "b"]); + // Use this repo's hooks dir whatever the global git config says. + git(&ws.join("a"), &["config", "core.hooksPath", ".git/hooks"]); + fs::create_dir_all(ws.join("a/.git/hooks")).unwrap(); + let hook = ws.join("a/.git/hooks/post-checkout"); + fs::write( + &hook, + "#!/bin/sh\ngit -c user.name=h -c user.email=h@example.com commit -q --allow-empty -m hook\n", + ) + .unwrap(); + fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).unwrap(); + git(&ws.join("b"), &["branch", "t"]); + let elsewhere = root.join("elsewhere"); + git( + &ws.join("b"), + &["worktree", "add", "-q", elsewhere.to_str().unwrap(), "t"], + ); + + let args = ["create", "t", "--repo", "a", "--repo", "b", "--no-deps"]; + let out = worktree(root, &ws, &args); + assert!(!out.status.success()); + assert!(stderr(&out).contains("kept branches"), "{}", stderr(&out)); + // The hook's commit is still on a's branch t. + let log = Command::new("git") + .args(["log", "-1", "--format=%s", "refs/heads/t"]) + .current_dir(ws.join("a")) + .output() + .unwrap(); + assert_eq!(String::from_utf8_lossy(&log.stdout).trim(), "hook"); +}