Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(prune, remove, ci): count what a removal took, not what it selected (#3633)
Maximilian Roos4c845597b228
diff --git a/.gitattributes b/.gitattributesindex 6968f82b1..69188f905 100644--- a/.gitattributes+++ b/.gitattributes@@ -15,3 +15,11 @@ docs/static/.well-known/agent-skills/index.json linguist-generated=true# Shell templates are embedded into the binary at compile time (askama); a# CRLF checkout would leak \r into the shell code Windows-built binaries emit.templates/* text eol=lf+# A fixture's object store and index are git's own binary formats, but git only+# calls a file binary when it finds a NUL in the first 8000 bytes, and a small+# enough zlib object may have none. Those diff as text, so `git diff` writes raw+# deflate into its output and any tool that decodes that output as a string+# fails on it — which is how `cargo affected` came to abort before running a+# test. The rest of `_git/` (HEAD, config, refs) is text worth reading.+tests/fixtures/*/_git/objects/** binary+tests/fixtures/*/_git/index binarydiff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 6f9aeeb13..a5a9f1498 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -2930,6 +2930,34 @@ pub mod tests {);}+ /// A branch-only row whose branch has since acquired a worktree — someone+ /// ran `wt switch` elsewhere while the picker sat open. The row's signal+ /// still decodes to `Branch`, and removing it would take out a worktree+ /// nobody selected, so validation refuses.+ #[test]+ fn test_prepare_removal_refuses_branch_that_gained_a_worktree() {+ let mut test = worktrunk::testing::TestRepo::with_initial_commit();+ let worktree_path = test.add_worktree("feature");+ let repo = worktrunk::git::Repository::at(test.path()).unwrap();++ let remover = test_remover(Arc::new(Mutex::new(Vec::new())), repo);++ let target = PickerRemovalTarget::from_signal("feature").unwrap();+ let err = remover+ .prepare_removal(&target)+ .map(|_| ())+ .expect_err("a branch with a worktree should not delete as branch-only");+ let rendered = err.to_string();+ assert!(+ rendered.contains("feature") && rendered.contains("wt remove"),+ "error should name the branch and the command that removes its worktree: {err:#}"+ );+ assert!(+ worktree_path.exists(),+ "the worktree nobody selected should survive"+ );+ }+/// A selection that names neither a worktree nor a local branch fails the/// `prepare_worktree_removal` validation, so `prepare_removal` returns the/// error rather than touching the picker list.diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 4128c8560..b18ea6363 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -10,12 +10,21 @@ use worktrunk::git::{parse_porcelain_z, parse_untracked_files,};use worktrunk::path::format_path_for_display;-use worktrunk::styling::{eprintln, format_with_gutter, progress_message, warning_message};+use worktrunk::styling::{+ eprintln, format_with_gutter, progress_message, suggest_command, warning_message,+};/// Target for worktree removal.#[derive(Debug)]pub enum RemoveTarget<'a> {- /// Remove worktree by branch name+ /// Delete a branch that has no worktree.+ ///+ /// A branch names a worktree only while it has exactly one: let it name+ /// two, which `git worktree add --force` allows, and the lookup silently+ /// picks git's first-listed checkout. So callers resolve first and pass+ /// [`Path`](Self::Path) for anything that has a worktree, and this variant+ /// carries only the branch-only case. One that has since acquired a+ /// worktree lost the race and errors rather than removing it unasked.Branch(&'a str),/// Remove the current worktree (supports detached HEAD)Current,@@ -29,7 +38,8 @@ pub trait RepositoryCliExt {/// Warn about untracked files being auto-staged.fn warn_if_auto_staging_untracked(&self) -> anyhow::Result<()>;- /// Prepare a worktree removal by branch name or current worktree.+ /// Prepare the removal of whichever worktree or branch [`RemoveTarget`]+ /// names.////// Returns a `RemoveResult` describing what will be removed. The actual/// removal is performed by the output handler.@@ -133,10 +143,10 @@ impl RepositoryCliExt for Repository {},BranchOnly {/// Path of the stale worktree entry this fell back from, when- /// the fallback was a prune. `None` when the branch never had a- /// worktree, which is also the only case with no sibling to- /// check — a branch whose worktree exists resolves to- /// `Worktree` above.+ /// the fallback was a prune. `None` when the branch has no+ /// worktree entry at all, which is also the only case with no+ /// sibling to check — a branch that has one resolves to+ /// `Worktree` above, or, named as a `Branch` target, errors.pruned_from: Option<PathBuf>,branch: String,},@@ -144,59 +154,44 @@ impl RepositoryCliExt for Repository {let resolved = match target {RemoveTarget::Branch(branch) => {- match worktrees+ // The caller established there was no worktree, so one here+ // appeared in between. Falling through would remove it — the+ // wrong operation, and on a worktree nobody named — so the+ // race surfaces instead. `wt remove <path>` is the spelling+ // that does mean "remove that worktree".+ if let Some(wt) = worktrees.iter().find(|wt| wt.branch.as_deref() == Some(branch)){- Some(wt) => {- if !wt.path.exists() {- // Directory missing - prune and continue- self.prune_worktrees()?;- Resolved::BranchOnly {- pruned_from: Some(wt.path.clone()),- branch: branch.to_string(),- }- } else if wt.locked.is_some() {- return Err(GitError::WorktreeLocked {- branch: branch.into(),- path: wt.path.clone(),- reason: wt.locked.clone(),- }- .into());- } else {- let is_current = current_path == wt.path;- Resolved::Worktree {- path: wt.path.clone(),- branch: Some(branch.to_string()),- is_current,- }+ let path = format_path_for_display(&wt.path);+ bail!(cformat!(+ "Branch <bold>{branch}</> gained a worktree @ <bold>{path}</> since it was selected; to remove that worktree, run <bold>{}</>",+ suggest_command("remove", &[&path], &[])+ ));+ }+ // Check the branch exists locally, so a typo or a remote-only+ // name reports itself rather than deleting nothing.+ let branch_handle = self.branch(branch);+ if !branch_handle.exists_locally()? {+ let remotes = branch_handle.remotes()?;+ if !remotes.is_empty() {+ return Err(GitError::RemoteOnlyBranch {+ branch: branch.into(),+ remote: remotes[0].clone(),}+ .into());}- None => {- // No worktree found - check if the branch exists locally- let branch_handle = self.branch(branch);- if !branch_handle.exists_locally()? {- let remotes = branch_handle.remotes()?;- if !remotes.is_empty() {- return Err(GitError::RemoteOnlyBranch {- branch: branch.into(),- remote: remotes[0].clone(),- }- .into());- }- return Err(GitError::BranchNotFound {- branch: branch.into(),- show_create_hint: false,- last_fetch_ago: None,- pr_mr_platform: None,- }- .into());- }- Resolved::BranchOnly {- pruned_from: None,- branch: branch.to_string(),- }+ return Err(GitError::BranchNotFound {+ branch: branch.into(),+ show_create_hint: false,+ last_fetch_ago: None,+ pr_mr_platform: None,}+ .into());+ }+ Resolved::BranchOnly {+ pruned_from: None,+ branch: branch.to_string(),}}RemoveTarget::Current | RemoveTarget::Path(_) => {@@ -567,10 +562,6 @@ pub(crate) fn compute_integration_reason(}}-/// Reject removing the default branch unless force-delete is set.-///-/// The default branch is the integration target — checking it against itself is-/// tautological (same logic as `wt list`'s `is_main` guard in `check_integration_state`)./// The worktree, other than the one being removed, whose checkout of `branch`/// deleting the ref would orphan.///@@ -598,6 +589,11 @@ pub(crate) fn live_sibling_checkout<'a>(})}+/// Reject removing the default branch unless force-delete is set.+///+/// The default branch is the integration target — checking it against itself is+/// tautological (same logic as `wt list`'s `is_main` guard in+/// `check_integration_state`).pub(crate) fn check_not_default_branch(repo: &Repository,branch: &str,diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex 2d60129a1..b943eeafa 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -23,7 +23,7 @@ use worktrunk::trace::Span;use super::super::hook_plan::{ApprovedHookPlan, HookPlan, HookPlanBuilder};use super::super::hooks::HookAnnouncer;-use super::super::repository_ext::{RemoveTarget, RepositoryCliExt};+use super::super::repository_ext::{RemoveTarget, RepositoryCliExt, live_sibling_checkout};use super::super::worktree::RemoveResult;use crate::output::{BackgroundFallbackMode, handle_remove_output};@@ -40,6 +40,13 @@ struct Candidate {path: Option<PathBuf>,/// Current worktree, other worktree, branch-only, or stale detached metadatakind: CandidateKind,+ /// Whether the removal deletes `branch`, from+ /// [`RemoveResult::deletes_branch`]. The kind is a plan, not an outcome: a+ /// branch a sibling worktree still has checked out is retained, so a+ /// worktree candidate can take the worktree and leave the branch standing.+ /// The summary counts this rather than the kind, so it never reports a+ /// branch the run deliberately kept.+ deletes_branch: bool,}impl Candidate {@@ -129,20 +136,30 @@ struct DryRunInfo {////// Worktree + branch is the default pair (matching progress messages'/// "worktree & branch" pattern). Unpaired items listed separately.+///+/// Counts what each removal took, not what its kind selected — see+/// [`Candidate::deletes_branch`]. A branch a sibling checkout retained leaves+/// only its worktree, and a retained branch whose worktree was stale metadata+/// leaves only the pruned entry, which reads the same as any other stale+/// entry ("Pruned 1 worktree", matching the `pruned` line above it).fn prune_summary(candidates: &[Candidate]) -> String {let mut worktree_with_branch = 0usize;- let mut detached_worktree = 0usize;+ let mut worktree_only = 0usize;let mut branch_only = 0usize;for c in candidates {match &c.kind {- CandidateKind::BranchOnly => branch_only += 1,+ CandidateKind::BranchOnly if c.deletes_branch => branch_only += 1,+ // Nothing but the stale worktree entry went. An orphan branch+ // never reaches here — it has no worktree entry, so no sibling+ // checkout exists to retain it.+ CandidateKind::BranchOnly => worktree_only += 1,// A stale detached worktree never has a branch.- CandidateKind::StaleDetached => detached_worktree += 1,+ CandidateKind::StaleDetached => worktree_only += 1,CandidateKind::Current | CandidateKind::Other => {- if c.branch.is_some() {+ if c.deletes_branch {worktree_with_branch += 1;} else {- detached_worktree += 1;+ worktree_only += 1;}}}@@ -156,13 +173,13 @@ fn prune_summary(candidates: &[Candidate]) -> String {};parts.push(format!("{worktree_with_branch} {noun}"));}- if detached_worktree > 0 {- let noun = if detached_worktree == 1 {+ if worktree_only > 0 {+ let noun = if worktree_only == 1 {"worktree"} else {"worktrees"};- parts.push(format!("{detached_worktree} {noun}"));+ parts.push(format!("{worktree_only} {noun}"));}if branch_only > 0 {let noun = if branch_only == 1 {@@ -284,6 +301,8 @@ struct CheckOutcome {plan: Option<RemoveResult>,/// Whether the item passed the removability gate (see `plan`).removable: bool,+ /// What the removal takes, carried onto [`Candidate::deletes_branch`].+ deletes_branch: bool,/// `Some(_)` if `min_age` is set and the age could be resolved; the/// caller compares against `min_age_duration` to decide on the skip.age: Option<Duration>,@@ -311,6 +330,7 @@ fn check_one(reason,plan: None,removable: false,+ deletes_branch: false,age: None,});}@@ -346,6 +366,22 @@ fn check_one(CheckSource::Prunable { .. } => true,CheckSource::Orphan | CheckSource::Linked { .. } => plan.is_some(),};+ let deletes_branch = match &plan {+ Some(plan) => plan.deletes_branch(),+ // A `Prunable` item has no plan until `try_remove` prunes its stale+ // entry, so ask the predicate that plan would: a live sibling+ // checkout of the same branch retains it. `Linked` and `Orphan`+ // arrive here only when the gate refused them, and nothing is+ // removed.+ None => match &item.source {+ CheckSource::Prunable { wt_idx } => {+ let wt = &worktrees[*wt_idx];+ wt.branch.is_some()+ && live_sibling_checkout(worktrees, &item.integration_ref, &wt.path).is_none()+ }+ CheckSource::Linked { .. } | CheckSource::Orphan => false,+ },+ };let age = if min_age_duration > Duration::ZERO {match &item.source {CheckSource::Linked { wt_idx } => worktree_age(repo, &worktrees[*wt_idx], now_secs)?,@@ -360,6 +396,7 @@ fn check_one(reason,plan,removable,+ deletes_branch,age,})}@@ -581,6 +618,7 @@ fn render_dry_run("branch": c.branch,"path": c.path,"kind": c.kind.as_str(),+ "branch_deleted": c.deletes_branch,"reason": info.reason_desc,"target": info.effective_target,})@@ -814,6 +852,7 @@ pub fn step_prune(label,path,kind,+ deletes_branch: outcome.deletes_branch,},DryRunInfo {reason_desc: reason.description().to_string(),@@ -1014,6 +1053,7 @@ pub fn step_prune(branch,path,kind,+ deletes_branch: outcome.deletes_branch,};if matches!(candidate.kind, CandidateKind::Current) {deferred_current = Some((candidate, outcome.plan));@@ -1044,6 +1084,7 @@ pub fn step_prune("branch": c.branch,"path": c.path,"kind": c.kind.as_str(),+ "branch_deleted": c.deletes_branch,})}).collect();@@ -1148,6 +1189,7 @@ mod tests {label: label.to_string(),path: None,kind,+ deletes_branch: !matches!(kind, CandidateKind::StaleDetached),}}@@ -1261,6 +1303,7 @@ mod tests {fn prune_summary_counts_each_candidate_kind() {let mut detached = candidate(CandidateKind::Other, "det");detached.branch = None;+ detached.deletes_branch = false;let candidates = [candidate(CandidateKind::Other, "feat-a"),candidate(CandidateKind::Other, "feat-b"),@@ -1274,4 +1317,18 @@ mod tests {"2 worktrees & branches, 2 worktrees, 1 branch");}++ /// A branch a sibling worktree still has checked out is retained, so the+ /// removal takes only the worktree — a live one for `Other`, a stale entry+ /// for `BranchOnly`. Counting the kind instead would report branches that+ /// are still there.+ #[test]+ fn prune_summary_counts_a_retained_branch_as_worktree_only() {+ let mut shared_worktree = candidate(CandidateKind::Other, "shared");+ shared_worktree.deletes_branch = false;+ let mut shared_stale = candidate(CandidateKind::BranchOnly, "shared-stale");+ shared_stale.deletes_branch = false;+ assert_eq!(prune_summary(&[shared_worktree]), "1 worktree");+ assert_eq!(prune_summary(&[shared_stale]), "1 worktree");+ }}diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex 364d5a7b8..d8b2a1733 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -262,25 +262,43 @@ impl RemoveResult {}}+ /// Whether this removal deletes a branch.+ ///+ /// False for a detached worktree, which has none, and false whenever a+ /// sibling checkout forced `deletion_mode` to [`BranchDeletionMode::Keep`]+ /// (see [`SharedBranchCheckout`]). What the plan intends, not what the+ /// delete returned: a `SafeDelete` still re-decides against fresh refs, and+ /// a background removal hasn't run yet — so this answers the same question+ /// the removal message answers when it says "worktree" rather than+ /// "worktree & branch".+ pub fn deletes_branch(&self) -> bool {+ match self {+ RemoveResult::RemovedWorktree {+ branch_name,+ deletion_mode,+ ..+ } => branch_name.is_some() && !deletion_mode.should_keep(),+ RemoveResult::BranchOnly { deletion_mode, .. } => !deletion_mode.should_keep(),+ }+ }+/// Convert to a JSON value for structured output.pub fn to_json(&self) -> serde_json::Value {match self {RemoveResult::RemovedWorktree {worktree_path,branch_name,- deletion_mode,branch_checked_out_at,..} => serde_json::json!({"kind": "worktree","branch": branch_name,"path": worktree_path,- "branch_deleted": !deletion_mode.should_keep(),+ "branch_deleted": self.deletes_branch(),"branch_checked_out_at": branch_checked_out_at.as_ref().map(|c| &c.path),}),RemoveResult::BranchOnly {branch_name,- deletion_mode,pruned,branch_checked_out_at,..@@ -288,7 +306,7 @@ impl RemoveResult {"kind": "branch_only","branch": branch_name,"pruned": pruned,- "branch_deleted": !deletion_mode.should_keep(),+ "branch_deleted": self.deletes_branch(),"branch_checked_out_at": branch_checked_out_at.as_ref().map(|c| &c.path),}),}diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rsindex c70b828e5..963363902 100644--- a/tests/integration_tests/step_prune.rs+++ b/tests/integration_tests/step_prune.rs@@ -1638,4 +1638,12 @@ fn test_prune_retains_branch_checked_out_in_another_worktree(mut repo: TestRepo).success(),"survivor must resolve HEAD to a commit, not a deleted branch:\n{stderr}",);++ // All the run took is the stale worktree entry, so that is what the summary+ // counts. Counting the candidate's kind instead would announce a branch the+ // run deliberately kept, contradicting the retention line above it.+ assert!(+ stderr.contains("Pruned 1 worktree") && !stderr.contains("Pruned 1 branch"),+ "summary must count the pruned entry, not the retained branch:\n{stderr}",+ );}diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json.snapindex 5c74e0ce1..28ad8dbba 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json.snap@@ -5,6 +5,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"[{"branch": "merged-a",+ "branch_deleted": true,"kind": "worktree","path": "<PATH>","reason": "same commit as",diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_current_worktree.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_current_worktree.snapindex 1965321e1..8964fa9e0 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_current_worktree.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_current_worktree.snap@@ -5,6 +5,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"[{"branch": "current-merged",+ "branch_deleted": true,"kind": "current","path": "<PATH>","reason": "same commit as",diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_orphan_branch.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_orphan_branch.snapindex 15200150a..f30ab3239 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_orphan_branch.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_orphan_branch.snap@@ -5,6 +5,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"[{"branch": "orphan-integrated",+ "branch_deleted": true,"kind": "branch_only","path": null,"reason": "same commit as",diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_json_actual_removal.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_json_actual_removal.snapindex 1feec03df..f9238f141 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_json_actual_removal.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_json_actual_removal.snap@@ -5,6 +5,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"[{"branch": "merged-a",+ "branch_deleted": true,"kind": "worktree","path": "<PATH>"}diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_json_current_worktree.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_json_current_worktree.snapindex 45c22910b..b8da16d58 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_json_current_worktree.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_json_current_worktree.snap@@ -5,6 +5,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"[{"branch": "current-merged",+ "branch_deleted": true,"kind": "current","path": "<PATH>"}diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_json_orphan_branch.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_json_orphan_branch.snapindex c6be38604..9dd6fc097 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_json_orphan_branch.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_json_orphan_branch.snap@@ -5,6 +5,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"[{"branch": "orphan-integrated",+ "branch_deleted": true,"kind": "branch_only","path": null}