diff --git a/src/clone_queue.rs b/src/clone_queue.rs index bc55ccd..2983ff8 100644 --- a/src/clone_queue.rs +++ b/src/clone_queue.rs @@ -20,17 +20,25 @@ pub struct CloneTask { pub is_meta: bool, } +/// A clone that failed, with git's own error output. +#[derive(Debug, Clone)] +pub struct CloneFailure { + pub name: String, + pub url: String, + pub error: String, +} + /// Thread-safe queue for managing clone tasks with dynamic discovery pub struct CloneQueue { /// Pending tasks to process pending: Mutex>, /// Completed task paths (to avoid duplicates) completed: Mutex>, - /// Failed task paths - failed: Mutex>, + /// Failed clones, in the order they failed + failures: Mutex>, /// Total tasks discovered (for progress display) total_discovered: AtomicUsize, - /// Total tasks completed + /// Total tasks finished, failed ones included (for progress display) total_completed: AtomicUsize, /// Git depth argument (if any) git_depth: Option, @@ -43,7 +51,7 @@ impl CloneQueue { Self { pending: Mutex::new(Vec::new()), completed: Mutex::new(HashSet::new()), - failed: Mutex::new(HashSet::new()), + failures: Mutex::new(Vec::new()), total_discovered: AtomicUsize::new(0), total_completed: AtomicUsize::new(0), git_depth, @@ -216,12 +224,24 @@ impl CloneQueue { pending.iter().map(|t| t.url.clone()).collect() } - /// Mark a task as failed - pub fn mark_failed(&self, task: &CloneTask) { + /// Mark a task as failed, keeping git's error output for the final report + pub fn mark_failed(&self, task: &CloneTask, error: String) { self.total_completed.fetch_add(1, Ordering::SeqCst); - let mut failed = self.failed.lock().unwrap_or_else(|e| e.into_inner()); - failed.insert(task.target_path.clone()); + let mut failures = self.failures.lock().unwrap_or_else(|e| e.into_inner()); + failures.push(CloneFailure { + name: task.name.clone(), + url: task.url.clone(), + error, + }); + } + + /// Clones that failed so far + pub fn failures(&self) -> Vec { + self.failures + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() } } @@ -492,6 +512,22 @@ mod tests { assert_eq!(completed, 0); } + #[test] + fn failed_clones_are_reported_with_their_error() { + let dir = tempfile::tempdir().unwrap(); + let queue = CloneQueue::new(None, None); + let task = make_task("missing", &dir.path().join("missing")); + queue.push(task.clone()); + + queue.mark_failed(&task, "fatal: repository not found".to_string()); + + let failures = queue.failures(); + assert_eq!(failures.len(), 1); + assert_eq!(failures[0].name, "missing"); + assert_eq!(failures[0].url, task.url); + assert_eq!(failures[0].error, "fatal: repository not found"); + } + // ── drain_all ───────────────────────────────────────────── #[test] diff --git a/src/lib.rs b/src/lib.rs index 52deb59..b5fba76 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,7 +4,6 @@ use std::path::Path; use std::process::{Command, Stdio}; pub mod clone_queue; pub mod missing; -pub mod snapshot; pub mod ssh_multiplexing; pub mod worktree; use console::style; diff --git a/src/snapshot.rs b/src/snapshot.rs deleted file mode 100644 index b977917..0000000 --- a/src/snapshot.rs +++ /dev/null @@ -1,414 +0,0 @@ -//! Workspace snapshot functionality for meta repositories. -//! -//! Captures and restores the git state of all repos in a meta workspace, -//! enabling safe batch operations with rollback capability. - -use anyhow::{Context, Result}; -use chrono::{DateTime, Utc}; -use meta_cli::git_utils; -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::fs; -use std::path::Path; -use std::process::{Command, Stdio}; - -const SNAPSHOTS_DIR: &str = ".meta-snapshots"; - -/// State of a single repository at snapshot time -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RepoState { - /// The commit SHA at snapshot time - pub sha: String, - /// The branch name (None if detached HEAD) - pub branch: Option, - /// Whether the repo had uncommitted changes - pub dirty: bool, - /// Whether a stash was created during restore (only set after restore) - #[serde(default, skip_serializing_if = "std::ops::Not::not")] - pub stash_created: bool, -} - -/// A complete workspace snapshot -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Snapshot { - /// Name of the snapshot - pub name: String, - /// When the snapshot was created - pub created: DateTime, - /// State of each repository (key is relative path from meta root) - pub repos: HashMap, -} - -/// Summary info about a snapshot (for listing) -#[derive(Debug, Clone, Serialize)] -pub struct SnapshotInfo { - pub name: String, - pub created: DateTime, - pub repo_count: usize, - pub dirty_count: usize, -} - -/// Result of a restore operation for a single repo -#[derive(Debug, Clone, Serialize)] -pub struct RestoreResult { - pub repo: String, - pub success: bool, - pub stashed: bool, - pub message: String, -} - -/// Capture the current git state of a repository -pub fn capture_repo_state(repo_path: &Path) -> Result { - // Get current SHA - let sha_output = Command::new("git") - .args(["rev-parse", "HEAD"]) - .current_dir(repo_path) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .context("Failed to run git rev-parse HEAD")?; - - if !sha_output.status.success() { - anyhow::bail!( - "git rev-parse HEAD failed: {}", - String::from_utf8_lossy(&sha_output.stderr) - ); - } - - let sha = String::from_utf8_lossy(&sha_output.stdout) - .trim() - .to_string(); - - let branch = git_utils::current_branch(repo_path); - - let dirty = git_utils::is_dirty(repo_path).unwrap_or(false); - - Ok(RepoState { - sha, - branch, - dirty, - stash_created: false, - }) -} - -/// Restore a repository to a snapshot state -pub fn restore_repo_state( - repo_path: &Path, - state: &RepoState, - force: bool, -) -> Result { - let repo_name = repo_path - .file_name() - .map(|n| n.to_string_lossy().to_string()) - .unwrap_or_else(|| ".".to_string()); - - // Check if repo is dirty and needs stashing - let is_dirty = git_utils::is_dirty(repo_path).unwrap_or(false); - - let mut stashed = false; - - // If dirty, stash changes first - if is_dirty { - if !force { - // In non-force mode, we've already confirmed with user - } - - let stash_output = Command::new("git") - .args(["stash", "push", "-m", "meta-snapshot-auto-stash"]) - .current_dir(repo_path) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .context("Failed to stash changes")?; - - if !stash_output.status.success() { - return Ok(RestoreResult { - repo: repo_name, - success: false, - stashed: false, - message: format!( - "Failed to stash: {}", - String::from_utf8_lossy(&stash_output.stderr) - ), - }); - } - stashed = true; - } - - // Checkout to the snapshot SHA - let checkout_output = Command::new("git") - .args(["checkout", &state.sha]) - .current_dir(repo_path) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .context("Failed to checkout SHA")?; - - if !checkout_output.status.success() { - let stderr = String::from_utf8_lossy(&checkout_output.stderr); - // Check if SHA doesn't exist (likely garbage collected) - if stderr.contains("did not match any") || stderr.contains("not a commit") { - return Ok(RestoreResult { - repo: repo_name, - success: false, - stashed, - message: format!( - "SHA {} no longer exists. Check git reflog for recovery options.", - &state.sha[..8] - ), - }); - } - return Ok(RestoreResult { - repo: repo_name, - success: false, - stashed, - message: format!("Failed to checkout: {stderr}"), - }); - } - - // If was on a branch, restore branch pointer - if let Some(ref branch) = state.branch { - let branch_output = Command::new("git") - .args(["checkout", "-B", branch, &state.sha]) - .current_dir(repo_path) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .context("Failed to restore branch")?; - - if !branch_output.status.success() { - // Non-fatal: we're at the right SHA, just not on the branch - return Ok(RestoreResult { - repo: repo_name, - success: true, - stashed, - message: format!( - "Restored to {} (couldn't restore branch '{}')", - &state.sha[..8], - branch - ), - }); - } - - Ok(RestoreResult { - repo: repo_name, - success: true, - stashed, - message: format!("{} -> {}", &state.sha[..8], branch), - }) - } else { - Ok(RestoreResult { - repo: repo_name, - success: true, - stashed, - message: format!("{} (detached)", &state.sha[..8]), - }) - } -} - -/// Save a snapshot to disk -pub fn save_snapshot(meta_root: &Path, snapshot: &Snapshot) -> Result<()> { - let snapshots_dir = meta_root.join(SNAPSHOTS_DIR); - fs::create_dir_all(&snapshots_dir).context("Failed to create snapshots directory")?; - - let snapshot_path = snapshots_dir.join(format!("{}.json", snapshot.name)); - let json = serde_json::to_string_pretty(snapshot).context("Failed to serialize snapshot")?; - - fs::write(&snapshot_path, json).context("Failed to write snapshot file")?; - - Ok(()) -} - -/// Load a snapshot from disk -pub fn load_snapshot(meta_root: &Path, name: &str) -> Result { - let snapshot_path = meta_root.join(SNAPSHOTS_DIR).join(format!("{name}.json")); - - if !snapshot_path.exists() { - anyhow::bail!("Snapshot '{name}' not found"); - } - - let json = fs::read_to_string(&snapshot_path).context("Failed to read snapshot file")?; - let snapshot: Snapshot = serde_json::from_str(&json).context("Failed to parse snapshot")?; - - Ok(snapshot) -} - -/// List all snapshots in a meta root -pub fn list_snapshots(meta_root: &Path) -> Result> { - let snapshots_dir = meta_root.join(SNAPSHOTS_DIR); - - if !snapshots_dir.exists() { - return Ok(Vec::new()); - } - - let mut snapshots = Vec::new(); - - for entry in fs::read_dir(&snapshots_dir).context("Failed to read snapshots directory")? { - let entry = entry?; - let path = entry.path(); - - if path.extension().map(|e| e == "json").unwrap_or(false) { - if let Ok(json) = fs::read_to_string(&path) { - if let Ok(snapshot) = serde_json::from_str::(&json) { - let dirty_count = snapshot.repos.values().filter(|r| r.dirty).count(); - snapshots.push(SnapshotInfo { - name: snapshot.name, - created: snapshot.created, - repo_count: snapshot.repos.len(), - dirty_count, - }); - } - } - } - } - - // Sort by creation time, newest first - snapshots.sort_by_key(|s| std::cmp::Reverse(s.created)); - - Ok(snapshots) -} - -/// Delete a snapshot -pub fn delete_snapshot(meta_root: &Path, name: &str) -> Result<()> { - let snapshot_path = meta_root.join(SNAPSHOTS_DIR).join(format!("{name}.json")); - - if !snapshot_path.exists() { - anyhow::bail!("Snapshot '{name}' not found"); - } - - fs::remove_file(&snapshot_path).context("Failed to delete snapshot file")?; - - Ok(()) -} - -/// Check if a path is a git repository -pub fn is_git_repo(path: &Path) -> bool { - path.join(".git").exists() || path.join(".git").is_file() -} - -#[cfg(test)] -mod tests { - use super::*; - use std::fs; - use tempfile::TempDir; - - fn create_test_repo(dir: &Path) -> Result<()> { - Command::new("git") - .args(["init"]) - .current_dir(dir) - .output()?; - Command::new("git") - .args(["config", "user.email", "test@test.com"]) - .current_dir(dir) - .output()?; - Command::new("git") - .args(["config", "user.name", "Test"]) - .current_dir(dir) - .output()?; - fs::write(dir.join("README.md"), "# Test")?; - Command::new("git") - .args(["add", "."]) - .current_dir(dir) - .output()?; - Command::new("git") - .args(["commit", "-m", "Initial commit"]) - .current_dir(dir) - .output()?; - Ok(()) - } - - #[test] - fn test_capture_clean_repo() { - let temp = TempDir::new().unwrap(); - create_test_repo(temp.path()).unwrap(); - - let state = capture_repo_state(temp.path()).unwrap(); - assert!(!state.sha.is_empty()); - assert!(!state.dirty); - // Default branch could be main or master - assert!(state.branch.is_some()); - } - - #[test] - fn test_capture_dirty_repo() { - let temp = TempDir::new().unwrap(); - create_test_repo(temp.path()).unwrap(); - - // Make it dirty - fs::write(temp.path().join("new_file.txt"), "dirty").unwrap(); - - let state = capture_repo_state(temp.path()).unwrap(); - assert!(state.dirty); - } - - #[test] - fn test_save_and_load_snapshot() { - let temp = TempDir::new().unwrap(); - - let snapshot = Snapshot { - name: "test-snapshot".to_string(), - created: Utc::now(), - repos: HashMap::from([( - ".".to_string(), - RepoState { - sha: "abc123".to_string(), - branch: Some("main".to_string()), - dirty: false, - stash_created: false, - }, - )]), - }; - - save_snapshot(temp.path(), &snapshot).unwrap(); - let loaded = load_snapshot(temp.path(), "test-snapshot").unwrap(); - - assert_eq!(loaded.name, "test-snapshot"); - assert_eq!(loaded.repos.len(), 1); - assert_eq!(loaded.repos["."].sha, "abc123"); - } - - #[test] - fn test_list_snapshots() { - let temp = TempDir::new().unwrap(); - - // Create two snapshots - for name in ["snap1", "snap2"] { - let snapshot = Snapshot { - name: name.to_string(), - created: Utc::now(), - repos: HashMap::new(), - }; - save_snapshot(temp.path(), &snapshot).unwrap(); - } - - let list = list_snapshots(temp.path()).unwrap(); - assert_eq!(list.len(), 2); - } - - #[test] - fn test_delete_snapshot() { - let temp = TempDir::new().unwrap(); - - let snapshot = Snapshot { - name: "to-delete".to_string(), - created: Utc::now(), - repos: HashMap::new(), - }; - save_snapshot(temp.path(), &snapshot).unwrap(); - - assert!(load_snapshot(temp.path(), "to-delete").is_ok()); - - delete_snapshot(temp.path(), "to-delete").unwrap(); - - assert!(load_snapshot(temp.path(), "to-delete").is_err()); - } - - #[test] - fn test_is_git_repo() { - let temp = TempDir::new().unwrap(); - assert!(!is_git_repo(temp.path())); - - create_test_repo(temp.path()).unwrap(); - assert!(is_git_repo(temp.path())); - } -} diff --git a/src/worktree/git_ops.rs b/src/worktree/git_ops.rs index d0d2d11..a34a913 100644 --- a/src/worktree/git_ops.rs +++ b/src/worktree/git_ops.rs @@ -31,7 +31,7 @@ fn clear_git_local_env(command: &mut Command) { } } -fn git_command(repo_path: &Path) -> Command { +pub(crate) fn git_command(repo_path: &Path) -> Command { let mut command = Command::new("git"); command.current_dir(repo_path); clear_git_local_env(&mut command); @@ -79,36 +79,25 @@ pub fn git_worktree_add( worktree_dest: &Path, branch: &str, from_ref: Option<&str>, -) -> Result { +) -> Result> { ensure_checkout_config_is_not_bare(repo_path)?; + let dest_str = worktree_dest.to_string_lossy(); - // If from_ref is specified, verify it exists in this repo + // If from_ref is specified, create the branch at the commit it names if let Some(ref_name) = from_ref { - let ref_exists = git_command(repo_path) - .args(["rev-parse", "--verify", ref_name]) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status()? - .success(); - - if !ref_exists { - anyhow::bail!( - "Ref '{}' not found in repo '{}'", - ref_name, - repo_path.display() - ); - } - - // Create branch from the specified ref + let start = + git_rev_parse(repo_path, &format!("{ref_name}^{{commit}}"))?.ok_or_else(|| { + anyhow::anyhow!( + "Ref '{}' not found in repo '{}'", + ref_name, + repo_path.display() + ) + })?; + // Pass the name, not the commit: a remote-tracking ref still sets the + // branch's upstream. If it moved meanwhile, the branch isn't at + // `start` and a rollback keeps it. let output = git_command(repo_path) - .args([ - "worktree", - "add", - "-b", - branch, - &worktree_dest.to_string_lossy(), - ref_name, - ]) + .args(["worktree", "add", "-b", branch, &dest_str, ref_name]) .output()?; if !output.status.success() { @@ -121,42 +110,23 @@ pub fn git_worktree_add( stderr.trim() ); } - return Ok(true); // Always creates a new branch from ref + return Ok(Some(start)); // Always creates a new branch from ref } - // Check if branch exists locally - let branch_exists = git_command(repo_path) - .args(["rev-parse", "--verify", &format!("refs/heads/{branch}")]) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status()? - .success(); - - // Also check if branch exists on remote - let remote_branch_exists = if !branch_exists { - git_command(repo_path) - .args([ - "rev-parse", - "--verify", - &format!("refs/remotes/origin/{branch}"), - ]) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status()? - .success() + let branch_exists = git_rev_parse(repo_path, &format!("refs/heads/{branch}"))?.is_some(); + let remote_ref = format!("origin/{branch}"); + let remote_start = if branch_exists { + None } else { - false + git_rev_parse(repo_path, &format!("refs/remotes/{remote_ref}"))? }; - let dest_str = worktree_dest.to_string_lossy(); - let remote_ref = format!("origin/{branch}"); - - let wt_args: Vec<&str> = if branch_exists { + let (wt_args, start): (Vec<&str>, Option) = if branch_exists { // Use existing local branch - vec!["worktree", "add", &dest_str, branch] - } else if remote_branch_exists { + (vec!["worktree", "add", &dest_str, branch], None) + } else if let Some(start) = remote_start { // Create local tracking branch from remote - vec![ + let args = vec![ "worktree", "add", "--track", @@ -164,10 +134,17 @@ pub fn git_worktree_add( branch, &dest_str, &remote_ref, - ] + ]; + (args, Some(start)) } else { // Create new branch from HEAD - vec!["worktree", "add", "-b", branch, &dest_str] + let start = git_rev_parse(repo_path, "HEAD")?.ok_or_else(|| { + anyhow::anyhow!("{} has no commit to branch from", repo_path.display()) + })?; + ( + vec!["worktree", "add", "-b", branch, &dest_str], + Some(start), + ) }; let output = git_command(repo_path).args(&wt_args).output()?; @@ -182,9 +159,9 @@ pub fn git_worktree_add( ); } - // Return whether we created a new branch - let created_branch = !branch_exists && !remote_branch_exists; - Ok(created_branch) + // The commit the branch was created at (`-b` refuses an existing branch, + // so success proves this call made it), or None for an existing branch. + Ok(start) } pub fn git_worktree_remove(repo_path: &Path, worktree_path: &Path, force: bool) -> Result<()> { @@ -320,52 +297,183 @@ pub fn git_diff_stat( Ok((files_changed, insertions, deletions, files)) } -/// Remove all worktree repos in correct order (children first, "." last). -/// In force mode, continues past failures and prints warnings. -/// Returns the number of repos that failed to remove (always 0 in non-force mode, -/// since non-force mode returns on first error). +/// Unregister and delete the checked worktrees of a set, deepest first +/// (nested checkouts before the checkouts that contain them). +/// Stops at the first failure, so the caller never deletes a set that git +/// still has registered (a locked worktree, say). pub fn remove_worktree_repos( - repos: &[meta_cli::worktree::WorktreeRepoInfo], + members: &[super::safety::Member], force: bool, verbose: bool, -) -> Result { - let mut failures = 0; +) -> Result<()> { + let mut ordered: Vec<_> = members.iter().collect(); + ordered.sort_by_key(|m| std::cmp::Reverse(m.path.components().count())); - // Remove child repos first - for r in repos.iter().filter(|r| r.alias != ".") { + for m in ordered { if verbose { - eprintln!( - "Removing worktree for '{}' at {}", - r.alias, - r.path.display() - ); + eprintln!("Removing worktree at {}", m.path.display()); } - if let Err(e) = git_worktree_remove(&r.source_path, &r.path, force) { - if force { - failures += 1; - log::warn!("Failed to remove worktree for '{}': {e}", r.alias); - } else { - return Err(e); + git_worktree_remove(&m.repo_git_dir, &m.path, force) + .map_err(|e| e.context(format!("Cannot remove {}", m.path.display())))?; + } + Ok(()) +} + +/// The commit `rev` names in `repo_path`, or `None` if git says no such name +/// exists. Any other failure (a broken repository, say) is an error with +/// git's message, never mistaken for a missing name. +pub fn git_rev_parse(repo_path: &Path, rev: &str) -> Result> { + let output = git_command(repo_path) + .args(["rev-parse", "--verify", "--quiet", rev]) + .output()?; + if output.status.success() { + return Ok(Some( + String::from_utf8_lossy(&output.stdout).trim().to_string(), + )); + } + let stderr = String::from_utf8_lossy(&output.stderr); + if output.status.code() == Some(1) && stderr.trim().is_empty() { + return Ok(None); + } + anyhow::bail!( + "git rev-parse {rev} failed in {}: {}", + repo_path.display(), + stderr.trim() + ) +} + +/// Fail if any worktree of the repository has `branch` checked out, or is +/// rebasing or bisecting it: the reservations git itself enforces. Checked-out +/// branches come from `git worktree list` (git resolves each HEAD through its +/// ref store, files or reftable); rebase and bisect state comes from each +/// worktree's state files (`rebase-merge/head-name`, `rebase-apply/head-name`, +/// `rebase-merge/update-refs`, `BISECT_START`). Changes nothing; anything it +/// can't read is an error, not "free". +pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { + let full = format!("refs/heads/{branch}"); + let in_use = |by: &str| anyhow::anyhow!("'{branch}' is {by}"); + + // A symbolic branch would carry a ref transaction to the branch it points + // at, which this check never looked at. + let symbolic = git_command(repo_path) + .args(["symbolic-ref", "-q", &full]) + .output()?; + match symbolic.status.code() { + Some(1) => {} + Some(0) => return Err(in_use("a symbolic ref; meta only moves plain branches")), + _ => anyhow::bail!( + "Cannot inspect '{branch}': {}", + String::from_utf8_lossy(&symbolic.stderr).trim() + ), + } + + let list = git_command(repo_path) + .args(["worktree", "list", "--porcelain"]) + .output()?; + anyhow::ensure!( + list.status.success(), + "Cannot list the worktrees of {}: {}", + repo_path.display(), + String::from_utf8_lossy(&list.stderr).trim() + ); + let wanted = format!("branch {full}"); + if String::from_utf8_lossy(&list.stdout) + .lines() + .any(|line| line == wanted) + { + return Err(in_use("checked out in a worktree")); + } + + let output = git_command(repo_path) + .args(["rev-parse", "--git-common-dir"]) + .output()?; + anyhow::ensure!( + output.status.success(), + "Cannot find the git directory of {}: {}", + repo_path.display(), + String::from_utf8_lossy(&output.stderr).trim() + ); + // Relative output is relative to the repository, where git ran. + let common = + repo_path.join(String::from_utf8_lossy(&output.stdout).trim_end_matches(['\n', '\r'])); + anyhow::ensure!( + common.is_dir(), + "Cannot find the git directory of {} (got {})", + repo_path.display(), + common.display() + ); + let mut admin_dirs = vec![common.clone()]; + match std::fs::read_dir(common.join("worktrees")) { + Ok(entries) => { + for entry in entries { + admin_dirs.push(entry?.path()); } } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e.into()), } - // Remove "." last (children live inside it) - if let Some(r) = repos.iter().find(|r| r.alias == ".") { - if verbose { - eprintln!("Removing meta repo worktree at {}", r.path.display()); - } - if let Err(e) = git_worktree_remove(&r.source_path, &r.path, force) { - if force { - failures += 1; - log::warn!("Failed to remove meta repo worktree: {e}"); - } else { - return Err(e); + let read = |path: std::path::PathBuf| -> Result { + match std::fs::read_to_string(&path) { + Ok(text) => Ok(text), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()), + Err(e) => { + Err(anyhow::Error::from(e).context(format!("Cannot read {}", path.display()))) } } + }; + for dir in admin_dirs { + let rebasing = [ + read(dir.join("rebase-merge/head-name"))?, + read(dir.join("rebase-apply/head-name"))?, + ]; + let updating = read(dir.join("rebase-merge/update-refs"))?; + if rebasing.iter().any(|name| name.trim() == full) + || updating.lines().any(|line| line.trim() == full) + { + return Err(in_use(&format!( + "being rebased by the worktree whose git dir is {}", + dir.display() + ))); + } + let bisect = read(dir.join("BISECT_START"))?; + if [branch, full.as_str()].contains(&bisect.trim()) { + return Err(in_use(&format!( + "being bisected by the worktree whose git dir is {}", + dir.display() + ))); + } } + Ok(()) +} - Ok(failures) +/// Delete a branch, but only if git would let it go (see +/// [`git_branch_is_free`]) and it still points at `expected`, atomically +/// through git's ref transaction. +pub fn git_delete_branch_at(repo_path: &Path, branch: &str, expected: &str) -> Result<()> { + git_branch_is_free(repo_path, branch) + .map_err(|e| anyhow::anyhow!("Branch '{branch}' is in use; kept ({e})"))?; + let output = git_command(repo_path) + .args([ + "update-ref", + "--no-deref", + "-d", + &format!("refs/heads/{branch}"), + expected, + ]) + .output()?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + anyhow::bail!( + "Branch '{branch}' no longer points where it was created; kept ({})", + stderr.trim() + ); + } + // Upstream settings of a deleted branch; there may be none. + let _ = git_command(repo_path) + .args(["config", "--remove-section", &format!("branch.{branch}")]) + .output(); + Ok(()) } /// Fetch a branch from origin if not locally available. @@ -422,6 +530,132 @@ mod tests { .unwrap(); } + // ── git_delete_branch_at ──────────────────────────────── + + #[test] + fn delete_branch_keeps_a_branch_that_moved() { + let tmp = init_git_repo(); + make_initial_commit(tmp.path()); + let start = git_rev_parse(tmp.path(), "HEAD").unwrap().unwrap(); + git_command(tmp.path()) + .args(["branch", "t"]) + .status() + .unwrap(); + std::fs::write(tmp.path().join("more"), "x").unwrap(); + git_command(tmp.path()) + .args(["add", "more"]) + .status() + .unwrap(); + git_command(tmp.path()) + .args(["commit", "-q", "-m", "more"]) + .status() + .unwrap(); + let moved = git_rev_parse(tmp.path(), "HEAD").unwrap().unwrap(); + git_command(tmp.path()) + .args(["update-ref", "refs/heads/t", &moved]) + .status() + .unwrap(); + + assert!(git_delete_branch_at(tmp.path(), "t", &start).is_err()); + assert_eq!( + git_rev_parse(tmp.path(), "refs/heads/t").unwrap(), + Some(moved.clone()) + ); + git_delete_branch_at(tmp.path(), "t", &moved).unwrap(); + assert_eq!(git_rev_parse(tmp.path(), "refs/heads/t").unwrap(), None); + } + + #[test] + fn branch_is_free_reads_reservations_and_changes_nothing() { + let tmp = init_git_repo(); + make_initial_commit(tmp.path()); + git_command(tmp.path()) + .args(["branch", "t"]) + .status() + .unwrap(); + git_command(tmp.path()) + .args(["config", "branch.autoSetupMerge", "always"]) + .status() + .unwrap(); + git_command(tmp.path()) + .args(["config", "branch.t.remote", "origin"]) + .status() + .unwrap(); + git_branch_is_free(tmp.path(), "t").unwrap(); + let remote = git_command(tmp.path()) + .args(["config", "branch.t.remote"]) + .output() + .unwrap(); + assert_eq!(String::from_utf8_lossy(&remote.stdout).trim(), "origin"); + + // Checked out in another worktree. + let other = tmp.path().join("other"); + git_command(tmp.path()) + .args(["worktree", "add", "-q", other.to_str().unwrap(), "t"]) + .status() + .unwrap(); + assert!(git_branch_is_free(tmp.path(), "t").is_err()); + // Bisected there instead: HEAD detached, branch still reserved. + git_command(&other) + .args(["checkout", "-q", "--detach"]) + .status() + .unwrap(); + git_branch_is_free(tmp.path(), "t").unwrap(); + let admin = tmp.path().join(".git/worktrees/other"); + std::fs::write(admin.join("BISECT_START"), "t\n").unwrap(); + assert!(git_branch_is_free(tmp.path(), "t").is_err()); + } + + #[test] + fn branch_is_free_sees_checkouts_in_a_reftable_repository() { + let tmp = tempfile::tempdir().unwrap(); + let repo = tmp.path().join("repo"); + let init = git_command(tmp.path()) + .args(["init", "-q", "--ref-format=reftable"]) + .arg(&repo) + .output() + .unwrap(); + if !init.status.success() { + return; // git older than 2.45 has no reftable support + } + for (key, value) in [("user.name", "Test"), ("user.email", "test@test.com")] { + git_command(&repo) + .args(["config", key, value]) + .status() + .unwrap(); + } + make_initial_commit(&repo); + assert!(git_rev_parse(&repo, "HEAD").unwrap().is_some()); + git_command(&repo).args(["branch", "t"]).status().unwrap(); + git_branch_is_free(&repo, "t").unwrap(); + let other = tmp.path().join("other"); + git_command(&repo) + .args(["worktree", "add", "-q", other.to_str().unwrap(), "t"]) + .status() + .unwrap(); + assert!(git_branch_is_free(&repo, "t").is_err()); + } + + #[test] + fn a_symbolic_branch_is_never_moved_or_deleted() { + let tmp = init_git_repo(); + make_initial_commit(tmp.path()); + let main = git_rev_parse(tmp.path(), "HEAD").unwrap().unwrap(); + let current = git_command(tmp.path()) + .args(["symbolic-ref", "HEAD"]) + .output() + .unwrap(); + let current = String::from_utf8_lossy(¤t.stdout).trim().to_string(); + git_command(tmp.path()) + .args(["symbolic-ref", "refs/heads/t", ¤t]) + .status() + .unwrap(); + + assert!(git_branch_is_free(tmp.path(), "t").is_err()); + assert!(git_delete_branch_at(tmp.path(), "t", &main).is_err()); + assert_eq!(git_rev_parse(tmp.path(), ¤t).unwrap(), Some(main)); + } + // ── git_status_summary ────────────────────────────────── #[test] @@ -608,70 +842,4 @@ mod tests { assert_eq!(ahead, 0); assert_eq!(behind, 0); } - - // ── remove_worktree_repos ordering ────────────────────── - // These tests verify the ordering logic without actual git operations. - // We construct WorktreeRepoInfo values and check that "." is processed last. - - #[test] - fn removal_ordering_children_before_root() { - // Verify via the filter logic that children come before "." - let repos = [ - meta_cli::worktree::WorktreeRepoInfo { - alias: ".".to_string(), - branch: "main".to_string(), - path: std::path::PathBuf::from("/tmp/wt"), - source_path: std::path::PathBuf::from("/tmp/src"), - created_branch: None, - }, - meta_cli::worktree::WorktreeRepoInfo { - alias: "lib".to_string(), - branch: "main".to_string(), - path: std::path::PathBuf::from("/tmp/wt/lib"), - source_path: std::path::PathBuf::from("/tmp/src/lib"), - created_branch: None, - }, - meta_cli::worktree::WorktreeRepoInfo { - alias: "cli".to_string(), - branch: "main".to_string(), - path: std::path::PathBuf::from("/tmp/wt/cli"), - source_path: std::path::PathBuf::from("/tmp/src/cli"), - created_branch: None, - }, - ]; - - // Verify ordering: children (non-".") are iterated first - let children: Vec<&str> = repos - .iter() - .filter(|r| r.alias != ".") - .map(|r| r.alias.as_str()) - .collect(); - assert_eq!(children, vec!["lib", "cli"]); - - // Root comes last - let root = repos.iter().find(|r| r.alias == "."); - assert!(root.is_some()); - } - - #[test] - fn removal_ordering_no_root_repo() { - // When there's no "." repo, all repos are children - let repos = [meta_cli::worktree::WorktreeRepoInfo { - alias: "lib".to_string(), - branch: "main".to_string(), - path: std::path::PathBuf::from("/tmp/wt/lib"), - source_path: std::path::PathBuf::from("/tmp/src/lib"), - created_branch: None, - }]; - - let root = repos.iter().find(|r| r.alias == "."); - assert!(root.is_none()); - - let children: Vec<&str> = repos - .iter() - .filter(|r| r.alias != ".") - .map(|r| r.alias.as_str()) - .collect(); - assert_eq!(children, vec!["lib"]); - } } diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 1827f89..97ed98c 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -232,7 +232,8 @@ pub fn resolve_branch( } /// Parse a human-friendly duration string to seconds. -/// Supported formats: "30s", "5m", "1h", "2d", "1w", or bare seconds "300" +/// Supported formats: "30s", "5m", "1h", "2d", "1w", or bare seconds "300". +/// The result always fits in an `i64`, so timestamp arithmetic can't wrap. pub fn parse_duration(s: &str) -> Result { let s = s.trim(); if s.is_empty() { @@ -240,29 +241,30 @@ pub fn parse_duration(s: &str) -> Result { } // Bare number: treat as seconds - if s.chars().all(|c| c.is_ascii_digit()) { - return s - .parse::() - .with_context(|| format!("Invalid duration: '{s}'")); - } - - let (num_str, suffix) = s.split_at(s.len() - 1); + let (num_str, multiplier) = if s.chars().all(|c| c.is_ascii_digit()) { + (s, 1) + } else { + let suffix_at = s.len() - s.chars().last().map_or(0, char::len_utf8); + let (num_str, suffix) = s.split_at(suffix_at); + let multiplier = match suffix { + "s" => 1, + "m" => 60, + "h" => 3600, + "d" => 86400, + "w" => 604800, + _ => anyhow::bail!( + "Invalid duration suffix '{suffix}'. Use s (seconds), m (minutes), h (hours), d (days), or w (weeks)" + ), + }; + (num_str, multiplier) + }; let num: u64 = num_str .parse() .with_context(|| format!("Invalid duration number: '{num_str}'"))?; - let multiplier = match suffix { - "s" => 1, - "m" => 60, - "h" => 3600, - "d" => 86400, - "w" => 604800, - _ => anyhow::bail!( - "Invalid duration suffix '{suffix}'. Use s (seconds), m (minutes), h (hours), d (days), or w (weeks)" - ), - }; - - Ok(num * multiplier) + num.checked_mul(multiplier) + .filter(|secs| i64::try_from(*secs).is_ok()) + .ok_or_else(|| anyhow::anyhow!("Duration '{s}' is too large")) } /// Format seconds into a human-friendly duration string. @@ -341,7 +343,7 @@ pub fn resolve_from_pr(from_pr: &str) -> Result<(String, u32, String)> { Ok((repo_spec.to_string(), pr_num, branch)) } -/// Check if a repo's remote URL matches the given owner/repo spec. +/// Check if a repo's `origin` remote is exactly the given owner/repo. pub fn repo_matches_spec(repo_path: &Path, spec: &str) -> bool { use std::process::Command; @@ -351,15 +353,23 @@ pub fn repo_matches_spec(repo_path: &Path, spec: &str) -> bool { .output(); match output { - Ok(o) if o.status.success() => { - let url = String::from_utf8_lossy(&o.stdout).trim().to_string(); - // Match against github.com:owner/repo or github.com/owner/repo - url.contains(spec) || url.contains(&spec.replace('/', ":")) - } + Ok(o) if o.status.success() => remote_owner_repo(&String::from_utf8_lossy(&o.stdout)) + .is_some_and(|owner_repo| owner_repo.eq_ignore_ascii_case(spec)), _ => false, } } +/// The trailing `owner/repo` of a remote URL such as `git@github.com:owner/repo.git`, +/// `https://github.com/owner/repo`, `ssh://git@host/owner/repo.git` or a local path. +fn remote_owner_repo(url: &str) -> Option { + let path = url.trim().trim_end_matches('/'); + let path = path.strip_suffix(".git").unwrap_or(path); + let mut parts = path.rsplit(['/', ':', '\\']); + let repo = parts.next().filter(|p| !p.is_empty())?; + let owner = parts.next().filter(|p| !p.is_empty())?; + Some(format!("{owner}/{repo}")) +} + pub fn ensure_worktrees_in_gitignore( meta_dir: &Path, worktrees_dirname: &str, @@ -495,6 +505,65 @@ mod tests { #[test] fn parse_duration_rejects_non_numeric() { assert!(parse_duration("abcs").is_err()); + assert!(parse_duration("5é").is_err()); + } + + #[test] + fn parse_duration_rejects_values_that_overflow() { + for input in [ + "18446744073709551615", + "30500000000000w", + "9223372036854775808", + ] { + let err = parse_duration(input).unwrap_err(); + assert!(err.to_string().contains("too large"), "{input}: {err}"); + } + assert_eq!( + parse_duration("9223372036854775807").unwrap(), + i64::MAX as u64 + ); + } + + // ── remote_owner_repo ─────────────────────────────────── + + #[test] + fn remote_owner_repo_parses_common_url_forms() { + for url in [ + "git@github.com:org/api.git", + "https://github.com/org/api", + "https://github.com/org/api.git/\n", + "ssh://git@github.example.com:22/org/api.git", + "C:\\remotes\\org\\api.git", + ] { + assert_eq!(remote_owner_repo(url).as_deref(), Some("org/api"), "{url}"); + } + assert_eq!( + remote_owner_repo("git@github.com:org/api-legacy.git").as_deref(), + Some("org/api-legacy") + ); + assert_eq!(remote_owner_repo("api"), None); + } + + #[test] + fn repo_matches_spec_requires_the_exact_repo() { + let tmp = tempfile::tempdir().unwrap(); + let run = |args: &[&str]| { + std::process::Command::new("git") + .args(args) + .current_dir(tmp.path()) + .output() + .unwrap() + }; + run(&["init", "-q"]); + run(&[ + "remote", + "add", + "origin", + "git@github.com:Org/api-legacy.git", + ]); + assert!(!repo_matches_spec(tmp.path(), "org/api")); + assert!(!repo_matches_spec(tmp.path(), "api-legacy")); + assert!(repo_matches_spec(tmp.path(), "org/api-legacy")); } // ── format_duration ───────────────────────────────────── diff --git a/src/worktree/hooks.rs b/src/worktree/hooks.rs index 2731513..23b6cf8 100644 --- a/src/worktree/hooks.rs +++ b/src/worktree/hooks.rs @@ -11,6 +11,8 @@ use super::types::{CreateRepoEntry, PruneEntry}; /// /// Reads the `.meta` config for `worktree.hooks.`. /// If configured, spawns the command and pipes `payload` JSON to stdin. +/// The hook's stderr goes to meta's stderr, as git does for its hooks; a +/// pipe that nobody reads would block a verbose hook forever. /// Hook failure prints a warning but doesn't block the operation. pub fn fire_worktree_hook(hook_name: &str, payload: &serde_json::Value, meta_dir: Option<&Path>) { let dir = match meta_dir { @@ -43,7 +45,7 @@ pub fn fire_worktree_hook(hook_name: &str, payload: &serde_json::Value, meta_dir .args(["-c", cmd_str]) .stdin(Stdio::piped()) .stdout(Stdio::null()) - .stderr(Stdio::piped()) + .stderr(Stdio::inherit()) .spawn() .and_then(|mut child| { // Write payload then drop stdin to signal EOF before waiting diff --git a/src/worktree/mod.rs b/src/worktree/mod.rs index c7685fa..cad1de6 100644 --- a/src/worktree/mod.rs +++ b/src/worktree/mod.rs @@ -6,6 +6,7 @@ pub mod git_ops; pub mod helpers; pub mod hooks; +pub mod safety; pub mod store; pub mod types; diff --git a/src/worktree/safety.rs b/src/worktree/safety.rs new file mode 100644 index 0000000..7116627 --- /dev/null +++ b/src/worktree/safety.rs @@ -0,0 +1,882 @@ +//! Checks that must pass before meta deletes a worktree set. +//! +//! Removal deletes the whole set directory, so every repository inside it is +//! inspected, nested ones included, and so is anything outside a repository. + +use anyhow::{Context, Result}; +use std::path::{Path, PathBuf}; + +use super::git_ops::{git_command, remove_worktree_repos}; + +/// A linked worktree checkout inside a set, and the git directory of the +/// repository it belongs to (where `git worktree remove` runs). +#[derive(Debug, Clone, PartialEq)] +pub struct Member { + pub path: PathBuf, + pub repo_git_dir: PathBuf, +} + +/// What deleting a worktree set would destroy. +#[derive(Debug, Default, PartialEq)] +pub struct RemovalCheck { + /// Every linked worktree in the set, nested and hidden ones included. + pub members: Vec, + /// Repositories that aren't linked worktrees, and checkouts git can't + /// inspect. No flag overrides these. + pub blockers: Vec, + /// Work that deleting the set would lose. `--force` may discard it. + pub unsaved: Vec, + /// Files outside every repository (part of `unsaved`). + pub loose: Vec, + /// Each checkout's complete git status, stranded commit ids, and the size + /// and modification time of every file `unsaved` lists, so a re-check + /// sees changes the abbreviated lines would hide, rewrites included. + exact: Vec, +} + +impl RemovalCheck { + pub fn is_clear(&self) -> bool { + self.blockers.is_empty() && self.unsaved.is_empty() + } +} + +/// Inspect a worktree set before deleting it. +/// +/// Blocks on repositories that aren't linked worktrees (a `.git` directory or +/// link, a bare repository, or a `.git` file that doesn't name a linked +/// worktree of its repository) and on checkouts git cannot inspect. Reports +/// as unsaved: uncommitted or untracked changes, commits that no branch, tag +/// or remote ref holds, and files that no repository holds. Ignored files count as disposable, as +/// they do for `git worktree remove`. +pub fn check_worktree_removal(wt_dir: &Path) -> Result { + let mut check = RemovalCheck::default(); + if wt_dir.symlink_metadata().is_ok_and(|m| m.is_symlink()) { + check.blockers.push(format!( + "{} is a symbolic link; meta doesn't delete through links", + wt_dir.display() + )); + return Ok(check); + } + let root_owned = match git_entry(wt_dir)? { + GitEntry::Worktree(repo_git_dir) => { + check.members.push(Member { + path: wt_dir.to_path_buf(), + repo_git_dir, + }); + true + } + GitEntry::Repository(why) => { + check.blockers.push(format!("{}: {why}", wt_dir.display())); + return Ok(check); + } + GitEntry::None => false, + }; + let mut loose = Vec::new(); + scan(wt_dir, root_owned, &mut loose, &mut check)?; + // A stable order, so two checks of an unchanged set compare equal. + check.members.sort_by(|a, b| a.path.cmp(&b.path)); + check.blockers.sort(); + loose.sort(); + + let paths: Vec = check.members.iter().map(|m| m.path.clone()).collect(); + for member in &paths { + let label = relative_label(wt_dir, member); + match unsaved_work(member, &paths) { + Ok((found, exact)) => { + check + .unsaved + .extend(found.into_iter().map(|what| format!("{label}: {what}"))); + check.exact.push(exact); + } + // What meta can't inspect it doesn't delete, even with --force. + Err(e) => check + .blockers + .push(format!("{label}: cannot verify ({e:#})")), + } + } + if !loose.is_empty() { + check.unsaved.push(format!( + "{} not inside any repository: {}", + plural(loose.len(), "file"), + sample(&loose, |p| relative_label(wt_dir, p)) + )); + } + check + .exact + .extend(loose.iter().map(|path| file_fingerprint(path))); + check.loose = loose; + Ok(check) +} + +/// A file's path, size and modification time: enough to notice a rewrite. +fn file_fingerprint(path: &Path) -> String { + match path.symlink_metadata() { + Ok(meta) => format!( + "{}\t{}\t{:?}", + path.display(), + meta.len(), + meta.modified().ok() + ), + Err(e) => format!("{}\t{}", path.display(), e.kind()), + } +} + +/// Delete a set that [`check_worktree_removal`] inspected, and nothing else. +/// +/// Checks the set again first and refuses if anything changed since `check` +/// (prune checks many sets before deleting any). Then unregisters the checked +/// worktrees (stopping at the first failure), deletes the files outside every +/// repository only if `force`, and removes the directories left empty. +/// Anything outside the checked worktrees that is still there is reported +/// and left in place. meta doesn't lock out other processes, so a write into +/// the set during the deletion itself can still be lost. +pub fn delete_checked_set( + wt_dir: &Path, + check: &RemovalCheck, + force: bool, + verbose: bool, +) -> Result<()> { + if check_worktree_removal(wt_dir)? != *check { + anyhow::bail!( + "{} changed after it was checked; left in place, check it again", + wt_dir.display() + ); + } + remove_worktree_repos(&check.members, force, verbose)?; + if force { + for path in &check.loose { + remove_entry(path).with_context(|| format!("Cannot delete {}", path.display()))?; + } + } + remove_empty_dirs(wt_dir)?; + if wt_dir.symlink_metadata().is_ok() { + let left: Vec = std::fs::read_dir(wt_dir) + .map(|entries| entries.flatten().map(|e| e.path()).collect()) + .unwrap_or_default(); + anyhow::bail!( + "{} could not be deleted completely (left in place: {}); new files may have \ + appeared in it, or some couldn't be removed", + wt_dir.display(), + sample(&left, |p| relative_label(wt_dir, p)) + ); + } + Ok(()) +} + +/// Delete a file or link. On Windows a link to a directory needs `remove_dir`. +fn remove_entry(path: &Path) -> std::io::Result<()> { + match std::fs::remove_file(path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) if path.symlink_metadata().is_ok_and(|m| m.is_symlink()) => { + std::fs::remove_dir(path).map_err(|_| e) + } + other => other, + } +} + +/// Remove `dir` and its subdirectories that hold nothing. Links aren't followed. +fn remove_empty_dirs(dir: &Path) -> Result<()> { + let entries = match std::fs::read_dir(dir) { + Ok(entries) => entries, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(e).with_context(|| format!("Cannot read {}", dir.display())), + }; + for entry in entries { + let entry = entry.with_context(|| format!("Cannot read {}", dir.display()))?; + if entry.file_type().is_ok_and(|t| t.is_dir()) { + remove_empty_dirs(&entry.path())?; + } + } + // Fails harmlessly when something is left; the caller reports it. + let _ = std::fs::remove_dir(dir); + Ok(()) +} + +enum GitEntry { + /// A linked worktree, with its repository's git directory. + Worktree(PathBuf), + /// A repository of its own, or a checkout meta can't attribute to one. + Repository(String), + None, +} + +fn git_entry(dir: &Path) -> Result { + let git = dir.join(".git"); + match git.symlink_metadata() { + Ok(meta) if meta.is_file() => Ok(match linked_worktree_git_dir(dir) { + Ok(repo_git_dir) => GitEntry::Worktree(repo_git_dir), + Err(e) => GitEntry::Repository(format!("not a linked worktree ({e:#})")), + }), + Ok(_) => Ok(GitEntry::Repository( + "a git repository, not a linked worktree".to_string(), + )), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + let bare = dir.join("HEAD").is_file() + && dir.join("objects").is_dir() + && dir.join("refs").is_dir(); + Ok(if bare { + GitEntry::Repository("a bare git repository".to_string()) + } else { + GitEntry::None + }) + } + Err(e) => Err(e).with_context(|| format!("Cannot inspect {}", git.display())), + } +} + +/// Follow a checkout's `.git` file to its repository's git directory, +/// requiring the linked-worktree layout: an admin directory with a +/// `commondir` and a `gitdir` that points back at this checkout. A +/// `--separate-git-dir` checkout or a submodule fails this. +fn linked_worktree_git_dir(checkout: &Path) -> Result { + let git_file = checkout.join(".git"); + let content = std::fs::read_to_string(&git_file).context("cannot read .git")?; + let admin = content + .trim() + .strip_prefix("gitdir:") + .map(|target| checkout.join(target.trim())) + .context(".git has no gitdir line")?; + anyhow::ensure!( + admin.exists(), + "its git metadata {} is missing; was the repository moved or deleted?", + admin.display() + ); + let common = std::fs::read_to_string(admin.join("commondir")).with_context(|| { + if admin.components().any(|c| c.as_os_str() == "modules") { + format!( + "{} looks like a submodule; meta can't remove sets that contain submodules", + admin.display() + ) + } else { + format!("{} has no commondir", admin.display()) + } + })?; + let backlink = std::fs::read_to_string(admin.join("gitdir")) + .with_context(|| format!("{} has no gitdir", admin.display()))?; + let points_back = admin + .join(backlink.trim()) + .canonicalize() + .ok() + .is_some_and(|target| git_file.canonicalize().ok() == Some(target)); + anyhow::ensure!( + points_back, + "{} belongs to another checkout (if this set was moved, run \ + 'git worktree repair' in its repository)", + admin.display() + ); + Ok(admin.join(common.trim())) +} + +/// Walk the set without following links. `owned` means a repository above +/// `dir` accounts for its files. +fn scan(dir: &Path, owned: bool, loose: &mut Vec, check: &mut RemovalCheck) -> Result<()> { + let entries = + std::fs::read_dir(dir).with_context(|| format!("Cannot read {}", dir.display()))?; + for entry in entries { + let entry = entry.with_context(|| format!("Cannot read {}", dir.display()))?; + let path = entry.path(); + if entry.file_name() == ".git" { + continue; + } + let file_type = entry + .file_type() + .with_context(|| format!("Cannot inspect {}", path.display()))?; + if !file_type.is_dir() { + if !owned { + loose.push(path); + } + continue; + } + match git_entry(&path)? { + GitEntry::Repository(why) => check.blockers.push(format!("{}: {why}", path.display())), + GitEntry::Worktree(repo_git_dir) => { + check.members.push(Member { + path: path.clone(), + repo_git_dir, + }); + scan(&path, true, loose, check)?; + } + GitEntry::None => scan(&path, owned, loose, check)?, + } + } + Ok(()) +} + +/// Describe the work in one checkout that deleting it would lose, and return +/// git's complete output alongside for exact comparison. +fn unsaved_work(repo: &Path, members: &[PathBuf]) -> Result<(Vec, String)> { + let output = git_command(repo) + .args(["status", "--porcelain", "-z", "--untracked-files=all"]) + .output() + .context("cannot run git status")?; + anyhow::ensure!( + output.status.success(), + "git status failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + // Exact, for the re-check: raw bytes, not a lossy decoding. + let text = format!("{:?}", output.stdout); + // Paths stay raw bytes, so a file with any name is found again on disk. + let mut modified: Vec<(String, PathBuf)> = Vec::new(); + let mut untracked: Vec<(String, PathBuf)> = Vec::new(); + let mut entries = output.stdout.split(|b| *b == 0).filter(|e| !e.is_empty()); + while let Some(entry) = entries.next() { + let (Some(code), Some(path)) = (entry.get(..2), entry.get(3..)) else { + continue; + }; + if code.contains(&b'R') || code.contains(&b'C') { + entries.next(); // the rename source + } + let shown = String::from_utf8_lossy(path).into_owned(); + let full = repo.join(path_from_bytes(path.strip_suffix(b"/").unwrap_or(path))?); + if code != b"??" { + modified.push((shown, full)); + } else if !members.contains(&full) { + // Nested checkouts show up as untracked; they are checked separately. + untracked.push((shown, full)); + } + } + let hidden = hidden_files(repo)?; + + let mut found = Vec::new(); + for (files, what) in [ + (&modified, "with uncommitted changes"), + (&untracked, "untracked"), + ( + &hidden, + "git is told not to check (assume-unchanged or skip-worktree)", + ), + ] { + if !files.is_empty() { + found.push(format!( + "{} {what}: {}", + plural(files.len(), "file"), + sample(files, |(shown, _)| shown.clone()) + )); + } + } + let operation = operation_in_progress(repo)?; + if let Some(op) = operation { + found.push(format!( + "a {op} is in progress (its state, such as an autostash, would be lost)" + )); + } + + let output = git_command(repo) + .args([ + "rev-list", + "HEAD", + "--not", + "--branches", + "--tags", + "--remotes", + ]) + .output() + .context("cannot run git rev-list")?; + anyhow::ensure!( + output.status.success(), + "git rev-list failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + let commits = String::from_utf8_lossy(&output.stdout).into_owned(); + let stranded = commits.lines().count(); + if stranded > 0 { + found.push(format!( + "{} not on any branch, tag or remote", + plural(stranded, "commit") + )); + } + // Staged content, which the status codes alone don't show. + let staged = git_command(repo) + .args(["diff", "--cached", "--raw", "-z", "--no-renames"]) + .output() + .context("cannot run git diff --cached")?; + anyhow::ensure!( + staged.status.success(), + "git diff --cached failed: {}", + String::from_utf8_lossy(&staged.stderr).trim() + ); + let staged = String::from_utf8_lossy(&staged.stdout).into_owned(); + let files: Vec = modified + .iter() + .chain(&untracked) + .chain(&hidden) + .map(|(_, path)| file_fingerprint(path)) + .collect(); + Ok(( + found, + format!( + "{}\0{text}\0{commits}\0{staged}\0{}\0{operation:?}", + repo.display(), + files.join("\n") + ), + )) +} + +/// Tracked files git is told not to look at (assume-unchanged or +/// skip-worktree) that are on disk: `git status` can't see changes to them, +/// so meta counts them as unsaved instead of guessing. Files absent from +/// disk (a sparse checkout) hold nothing. +fn hidden_files(repo: &Path) -> Result> { + let output = git_command(repo) + .args(["ls-files", "-v", "-z"]) + .output() + .context("cannot run git ls-files")?; + anyhow::ensure!( + output.status.success(), + "git ls-files failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + // Entries are " "; a lowercase tag means assume-unchanged, + // "S" skip-worktree. + let mut hidden = Vec::new(); + for entry in output.stdout.split(|b| *b == 0) { + let Some((tag, rest)) = entry.split_first() else { + continue; + }; + let Some(path) = rest.strip_prefix(b" ") else { + continue; + }; + if tag.is_ascii_lowercase() || *tag == b'S' { + let full = repo.join(path_from_bytes(path)?); + if full.symlink_metadata().is_ok() { + hidden.push((String::from_utf8_lossy(path).into_owned(), full)); + } + } + } + Ok(hidden) +} + +/// A path git printed as raw bytes. Outside Unix, git writes UTF-8. +fn path_from_bytes(bytes: &[u8]) -> Result { + #[cfg(unix)] + { + use std::os::unix::ffi::OsStrExt; + Ok(PathBuf::from(std::ffi::OsStr::from_bytes(bytes))) + } + #[cfg(not(unix))] + { + std::str::from_utf8(bytes) + .map(PathBuf::from) + .context("git printed a path that isn't UTF-8") + } +} + +/// The operation in progress in a checkout, if any. Its state (a rebase's +/// autostash, say) lives in the worktree's git directory, which removal +/// deletes. +fn operation_in_progress(repo: &Path) -> Result> { + let output = git_command(repo) + .args(["rev-parse", "--git-dir"]) + .output() + .context("cannot run git rev-parse")?; + anyhow::ensure!( + output.status.success(), + "git rev-parse --git-dir failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + let git_dir = repo.join(String::from_utf8_lossy(&output.stdout).trim_end_matches(['\n', '\r'])); + let markers = [ + ("rebase-merge", "rebase"), + ("rebase-apply", "rebase or am"), + ("MERGE_HEAD", "merge"), + ("CHERRY_PICK_HEAD", "cherry-pick"), + ("REVERT_HEAD", "revert"), + ("sequencer", "cherry-pick or revert"), + ("BISECT_START", "bisect"), + ]; + Ok(markers + .into_iter() + .find(|(marker, _)| git_dir.join(marker).symlink_metadata().is_ok()) + .map(|(_, name)| name)) +} + +fn relative_label(root: &Path, path: &Path) -> String { + match path.strip_prefix(root) { + Ok(rel) if rel.as_os_str().is_empty() => ".".to_string(), + Ok(rel) => rel.display().to_string(), + Err(_) => path.display().to_string(), + } +} + +fn plural(count: usize, noun: &str) -> String { + if count == 1 { + format!("1 {noun}") + } else { + format!("{count} {noun}s") + } +} + +/// The first few items, so a huge list stays readable. +fn sample(items: &[T], show: impl Fn(&T) -> String) -> String { + const SHOWN: usize = 3; + let mut text = items + .iter() + .take(SHOWN) + .map(show) + .collect::>() + .join(", "); + if items.len() > SHOWN { + text.push_str(&format!(", and {} more", items.len() - SHOWN)); + } + text +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::Command; + + fn git(dir: &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) + ); + } + + /// A source repo with one commit and a linked worktree of it at `wt`. + fn repo_with_worktree(root: &Path, name: &str, wt: &Path) { + let source = root.join(name); + std::fs::create_dir_all(&source).unwrap(); + git(&source, &["init", "-q"]); + git(&source, &["commit", "-q", "--allow-empty", "-m", "init"]); + std::fs::create_dir_all(wt.parent().unwrap()).unwrap(); + git( + &source, + &["worktree", "add", "-q", "-b", name, wt.to_str().unwrap()], + ); + } + + #[test] + fn clean_nested_set_is_clear() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "root", &set); + repo_with_worktree(tmp.path(), "leaf", &set.join("sub/leaf")); + repo_with_worktree(tmp.path(), "hidden", &set.join(".scratch/leaf")); + + let check = check_worktree_removal(&set).unwrap(); + assert!(check.is_clear(), "{check:?}"); + let mut members: Vec<_> = check.members.iter().map(|m| m.path.clone()).collect(); + members.sort(); + assert_eq!( + members, + [ + set.clone(), + set.join(".scratch").join("leaf"), + set.join("sub").join("leaf") + ] + ); + } + + #[test] + fn reports_dirty_nested_repo_loose_files_and_primary_checkouts() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "leaf", &set.join("sub/leaf")); + std::fs::write(set.join("sub/leaf/new.txt"), "work").unwrap(); + std::fs::write(set.join("notes.txt"), "work").unwrap(); + std::fs::create_dir_all(set.join("clone")).unwrap(); + git(&set.join("clone"), &["init", "-q"]); + git(&set, &["init", "-q", "--bare", "mirror.git"]); + + let check = check_worktree_removal(&set).unwrap(); + let blockers = check.blockers.join("\n"); + assert_eq!(check.blockers.len(), 2, "{blockers}"); + assert!(blockers.contains("clone") && blockers.contains("mirror.git")); + let unsaved = check.unsaved.join("\n").replace('\\', "/"); + assert!( + unsaved.contains("sub/leaf: 1 file untracked: new.txt"), + "{unsaved}" + ); + assert!( + unsaved.contains("not inside any repository: notes.txt"), + "{unsaved}" + ); + } + + #[test] + fn reports_commits_only_a_detached_head_holds() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "root", &set); + git(&set, &["checkout", "-q", "--detach"]); + git( + &set, + &["commit", "-q", "--allow-empty", "-m", "detached work"], + ); + + let check = check_worktree_removal(&set).unwrap(); + assert_eq!( + check.unsaved, + [".: 1 commit not on any branch, tag or remote"] + ); + } + + #[test] + fn delete_checked_set_refuses_files_that_appeared_after_the_check() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "leaf", &set.join("sub/leaf")); + std::fs::write(set.join("notes.txt"), "work").unwrap(); + let check = check_worktree_removal(&set).unwrap(); + std::fs::write(set.join("sub/late.txt"), "written after the check").unwrap(); + + let err = delete_checked_set(&set, &check, true, false).unwrap_err(); + assert!( + err.to_string().contains("changed after it was checked"), + "{err}" + ); + for kept in ["sub/late.txt", "notes.txt", "sub/leaf/.git"] { + assert!(set.join(kept).exists(), "{kept}"); + } + + std::fs::remove_file(set.join("sub/late.txt")).unwrap(); + let check = check_worktree_removal(&set).unwrap(); + assert_eq!(check.loose, [set.join("notes.txt")]); + delete_checked_set(&set, &check, true, false).unwrap(); + assert!(!set.exists(), "--force discards the checked loose file"); + } + + #[test] + fn recheck_sees_changes_the_summary_hides() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "root", &set); + for name in ["a", "b", "c", "d"] { + std::fs::write(set.join(name), "x").unwrap(); + } + let before = check_worktree_removal(&set).unwrap(); + std::fs::rename(set.join("d"), set.join("e")).unwrap(); + let after = check_worktree_removal(&set).unwrap(); + assert_eq!(before.unsaved, after.unsaved, "the summary looks the same"); + assert_ne!(before, after); + } + + #[test] + fn a_worktree_of_a_bare_repository_is_clear() { + let tmp = tempfile::tempdir().unwrap(); + let seed = tmp.path().join("seed"); + std::fs::create_dir(&seed).unwrap(); + git(&seed, &["init", "-q"]); + git(&seed, &["commit", "-q", "--allow-empty", "-m", "init"]); + let bare = tmp.path().join("bare.git"); + git( + &seed, + &["clone", "-q", "--bare", ".", bare.to_str().unwrap()], + ); + let set = tmp.path().join("set"); + std::fs::create_dir(&set).unwrap(); + git( + &bare, + &[ + "worktree", + "add", + "-q", + "-b", + "t", + set.join("a").to_str().unwrap(), + ], + ); + + let check = check_worktree_removal(&set).unwrap(); + assert!(check.is_clear(), "{check:?}"); + delete_checked_set(&set, &check, false, false).unwrap(); + assert!(!set.exists()); + } + + #[test] + fn reports_files_hidden_by_index_flags_and_operations_in_progress() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "root", &set); + std::fs::write(set.join("config"), "original").unwrap(); + git(&set, &["add", "config"]); + git(&set, &["commit", "-q", "-m", "config"]); + git(&set, &["update-index", "--assume-unchanged", "config"]); + let check = check_worktree_removal(&set).unwrap(); + assert_eq!( + check.unsaved, + [".: 1 file git is told not to check (assume-unchanged or skip-worktree): config"] + ); + + git(&set, &["update-index", "--no-assume-unchanged", "config"]); + let admin = tmp.path().join("root/.git/worktrees/set"); + std::fs::create_dir(admin.join("rebase-merge")).unwrap(); + let check = check_worktree_removal(&set).unwrap(); + assert!( + check.unsaved[0].contains("a rebase is in progress"), + "{check:?}" + ); + } + + #[cfg(target_os = "linux")] + #[test] + fn files_with_non_utf8_names_are_tracked_exactly() { + use std::os::unix::ffi::OsStrExt; + + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "root", &set); + let name = std::ffi::OsStr::from_bytes(b"caf\xff"); + std::fs::write(set.join(name), "draft").unwrap(); + let before = check_worktree_removal(&set).unwrap(); + std::fs::write(set.join(name), "new work, longer than the draft").unwrap(); + let err = delete_checked_set(&set, &before, true, false).unwrap_err(); + assert!( + err.to_string().contains("changed after it was checked"), + "{err}" + ); + assert!(set.join(name).exists()); + } + + #[test] + fn a_checkout_git_cannot_inspect_is_a_blocker() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "root", &set); + std::fs::write(set.join("file"), "x").unwrap(); + git(&set, &["add", "file"]); + let index = tmp.path().join("root/.git/worktrees/set/index"); + std::fs::write(&index, "not an index").unwrap(); + + let check = check_worktree_removal(&set).unwrap(); + assert!(check.unsaved.is_empty(), "{check:?}"); + assert!(check.blockers[0].contains("cannot verify"), "{check:?}"); + } + + #[test] + fn recheck_sees_a_rewritten_file() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "leaf", &set.join("leaf")); + std::fs::write(set.join("leaf/notes.txt"), "old draft").unwrap(); + std::fs::write(set.join("loose.txt"), "old").unwrap(); + let before = check_worktree_removal(&set).unwrap(); + + std::fs::write( + set.join("leaf/notes.txt"), + "new work, longer than the draft", + ) + .unwrap(); + let after = check_worktree_removal(&set).unwrap(); + assert_eq!(before.unsaved, after.unsaved, "the summary looks the same"); + assert_ne!(before, after); + let err = delete_checked_set(&set, &before, true, false).unwrap_err(); + assert!( + err.to_string().contains("changed after it was checked"), + "{err}" + ); + + std::fs::write(set.join("loose.txt"), "newer").unwrap(); + assert_ne!(after, check_worktree_removal(&set).unwrap()); + } + + #[test] + fn recheck_sees_a_change_only_in_the_index() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "root", &set); + std::fs::write(set.join("f"), "staged").unwrap(); + git(&set, &["add", "f"]); + std::fs::write(set.join("f"), "working copy").unwrap(); + let before = check_worktree_removal(&set).unwrap(); + + // Replace the staged blob only; status stays the same, the file too. + std::fs::write(tmp.path().join("other"), "other staged").unwrap(); + let blob = Command::new("git") + .args(["hash-object", "-w"]) + .arg(tmp.path().join("other")) + .current_dir(&set) + .output() + .unwrap(); + let blob = String::from_utf8_lossy(&blob.stdout).trim().to_string(); + git( + &set, + &["update-index", "--cacheinfo", &format!("100644,{blob},f")], + ); + + let after = check_worktree_removal(&set).unwrap(); + assert_eq!(before.unsaved, after.unsaved); + assert_ne!(before, after); + } + + #[test] + fn delete_checked_set_refuses_a_set_that_changed_inside_a_worktree() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "root", &set); + std::fs::write(set.join(".gitignore"), "ignored/\n").unwrap(); + git(&set, &["add", ".gitignore"]); + git(&set, &["commit", "-q", "-m", "ignore"]); + let check = check_worktree_removal(&set).unwrap(); + assert!(check.is_clear(), "{check:?}"); + // A repository appears in an ignored directory after the check. + std::fs::create_dir_all(set.join("ignored/repo")).unwrap(); + git(&set.join("ignored/repo"), &["init", "-q"]); + + let err = delete_checked_set(&set, &check, true, false).unwrap_err(); + assert!( + err.to_string().contains("changed after it was checked"), + "{err}" + ); + assert!(set.join("ignored/repo/.git").exists()); + } + + #[test] + fn symlinked_set_root_is_blocked() { + let tmp = tempfile::tempdir().unwrap(); + let target = tmp.path().join("target"); + repo_with_worktree(tmp.path(), "root", &target); + let link = tmp.path().join("link"); + #[cfg(unix)] + std::os::unix::fs::symlink(&target, &link).unwrap(); + #[cfg(windows)] + if std::os::windows::fs::symlink_dir(&target, &link).is_err() { + return; // creating links needs a privilege Windows CI may not have + } + let check = check_worktree_removal(&link).unwrap(); + assert!(check.blockers[0].contains("symbolic link"), "{check:?}"); + } + + #[test] + fn separate_git_dir_checkout_is_not_a_worktree() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + std::fs::create_dir_all(set.join("repo")).unwrap(); + let git_dir = tmp.path().join("repo.git"); + git( + &set.join("repo"), + &[ + "init", + "-q", + "--separate-git-dir", + git_dir.to_str().unwrap(), + ], + ); + + let check = check_worktree_removal(&set).unwrap(); + assert!(check.members.is_empty()); + assert_eq!(check.blockers.len(), 1, "{check:?}"); + assert!( + check.blockers[0].contains("not a linked worktree"), + "{check:?}" + ); + } + + #[test] + fn set_root_that_is_a_primary_checkout_is_blocked() { + let tmp = tempfile::tempdir().unwrap(); + git(tmp.path(), &["init", "-q"]); + let check = check_worktree_removal(tmp.path()).unwrap(); + assert_eq!(check.blockers.len(), 1); + } +} diff --git a/src/worktree/store.rs b/src/worktree/store.rs index 3444c8a..e14c822 100644 --- a/src/worktree/store.rs +++ b/src/worktree/store.rs @@ -55,24 +55,34 @@ pub fn store_add(worktree_path: &Path, entry: WorktreeStoreEntry) -> Result<()> }) } -/// Remove a worktree entry from the centralized store. -pub fn store_remove(worktree_path: &Path) -> Result<()> { - let (data_path, lock_path) = store_paths(); - if !data_path.exists() { - return Ok(()); - } - let key = store_key(worktree_path); - - meta_core::store::update::(&data_path, &lock_path, |store| { - store.worktrees.remove(&key); - }) -} - /// Get all entries from the store. pub fn store_list() -> Result { meta_core::store::read(&store_path()) } +/// Get the store key and entry for an existing worktree path, if meta +/// recorded creating it. Keep the key: once the path is deleted it can no +/// longer be resolved to the same key. +pub fn store_get(worktree_path: &Path) -> Result> { + let key = store_key(worktree_path); + Ok(store_list()? + .worktrees + .remove(&key) + .map(|entry| (key, entry))) +} + +/// Recorded worktree sets inside `worktree_path`, not counting itself. +/// Deleting `worktree_path` would delete those sets too. +pub fn store_sets_inside(worktree_path: &Path) -> Result> { + let key = store_key(worktree_path); + let root = Path::new(&key); + Ok(store_list()? + .worktrees + .into_keys() + .filter(|k| Path::new(k) != root && Path::new(k).starts_with(root)) + .collect()) +} + /// Add repos to an existing worktree entry in the store. pub fn store_extend_repos(worktree_path: &Path, repos: Vec) -> Result<()> { let (data_path, lock_path) = store_paths(); @@ -86,15 +96,23 @@ pub fn store_extend_repos(worktree_path: &Path, repos: Vec) -> R } /// Remove multiple worktree entries from the store in a single lock cycle. -pub fn store_remove_batch(keys: &[String]) -> Result<()> { +/// Each `(key, created_at)` pair removes the entry only if it is still the +/// one that was read, so a worktree recreated at the same path keeps its record. +pub fn store_remove_batch(entries: &[(String, String)]) -> Result<()> { let (data_path, lock_path) = store_paths(); if !data_path.exists() { return Ok(()); } meta_core::store::update::(&data_path, &lock_path, |store| { - for key in keys { - store.worktrees.remove(key); + for (key, created_at) in entries { + if store + .worktrees + .get(key) + .is_some_and(|e| e.created_at == *created_at) + { + store.worktrees.remove(key); + } } }) } @@ -116,7 +134,8 @@ pub fn entry_ttl_remaining(entry: &WorktreeStoreEntry, now_epoch: i64) -> Option return i64::MAX; } }; - created + ttl as i64 - now_epoch + let ttl = i64::try_from(ttl).unwrap_or(i64::MAX); + created.saturating_add(ttl).saturating_sub(now_epoch) }) } @@ -250,6 +269,13 @@ mod tests { assert_eq!(remaining, 0); } + #[test] + fn ttl_remaining_huge_ttl_never_expires() { + let entry = make_entry("2025-01-01T00:00:00Z", Some(u64::MAX)); + let remaining = entry_ttl_remaining(&entry, 1_800_000_000).unwrap(); + assert_eq!(remaining, i64::MAX - 1_800_000_000); + } + #[test] fn ttl_remaining_malformed_date_returns_max() { let entry = make_entry("not-a-date", Some(3600)); @@ -283,7 +309,7 @@ mod tests { assert!(data.worktrees.contains_key(&key)); // Remove entry - store_remove(&wt_path).unwrap(); + store_remove_batch(&[(key.clone(), "2025-01-01T00:00:00Z".to_string())]).unwrap(); // Verify it was removed let data = store_list().unwrap(); @@ -315,9 +341,16 @@ mod tests { store_add(&wt3, make_entry("2025-01-01T00:00:00Z", None)).unwrap(); // Remove two in batch - let keys_to_remove = vec![store_key(&wt1), store_key(&wt2)]; + let keys_to_remove = vec![ + (store_key(&wt1), "2025-01-01T00:00:00Z".to_string()), + (store_key(&wt2), "2025-01-01T00:00:00Z".to_string()), + ]; store_remove_batch(&keys_to_remove).unwrap(); + // An entry recreated since it was read keeps its record + store_add(&wt3, make_entry("2026-01-01T00:00:00Z", None)).unwrap(); + store_remove_batch(&[(store_key(&wt3), "2025-01-01T00:00:00Z".to_string())]).unwrap(); + // Verify only wt3 remains let data = store_list().unwrap(); assert!(!data.worktrees.contains_key(&store_key(&wt1))); @@ -325,7 +358,7 @@ mod tests { assert!(data.worktrees.contains_key(&store_key(&wt3))); // Cleanup - store_remove(&wt3).unwrap(); + store_remove_batch(&[(store_key(&wt3), "2026-01-01T00:00:00Z".to_string())]).unwrap(); std::env::remove_var("META_DATA_DIR"); } @@ -370,7 +403,7 @@ mod tests { assert!(stored_entry.repos.iter().any(|r| r.alias == "repo2")); // Cleanup - store_remove(&wt_path).unwrap(); + store_remove_batch(&[(store_key(&wt_path), "2025-01-01T00:00:00Z".to_string())]).unwrap(); std::env::remove_var("META_DATA_DIR"); } @@ -389,7 +422,10 @@ mod tests { // Remove on non-existent worktree should succeed let wt_path = temp_dir.path().join("nonexistent-wt"); - assert!(store_remove(&wt_path).is_ok()); + assert!( + store_remove_batch(&[(store_key(&wt_path), "2025-01-01T00:00:00Z".to_string())]) + .is_ok() + ); std::env::remove_var("META_DATA_DIR"); } @@ -436,7 +472,11 @@ mod tests { // Cleanup - batch remove for efficiency let keys: Vec = paths.iter().map(|p| store_key(p)).collect(); - store_remove_batch(&keys).unwrap(); + let entries: Vec<_> = keys + .iter() + .map(|k| (k.clone(), "2025-01-01T00:00:00Z".to_string())) + .collect(); + store_remove_batch(&entries).unwrap(); // Verify cleanup worked let data_after = store_list().unwrap(); @@ -485,7 +525,11 @@ mod tests { let end = std::cmp::min(start + 4, paths.len()); let keys: Vec = paths[start..end].iter().map(|p| store_key(p)).collect(); - store_remove_batch(&keys).unwrap(); + let entries: Vec<_> = keys + .into_iter() + .map(|k| (k, "2025-01-01T00:00:00Z".to_string())) + .collect(); + store_remove_batch(&entries).unwrap(); }) }) .collect(); diff --git a/src/worktree/types.rs b/src/worktree/types.rs index 58fb12f..93908d0 100644 --- a/src/worktree/types.rs +++ b/src/worktree/types.rs @@ -200,6 +200,8 @@ pub struct DiffTotals { #[derive(Debug, Serialize)] pub struct PruneOutput { pub removed: Vec, + /// Candidates kept because deleting them would lose work. + pub kept: Vec, pub dry_run: bool, }