Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(remove): plan no branch deletion for an orphan worktree's unborn branch (#4233)

Maximilian Roos2a4aa28c2692
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index f05736902..43672efdc 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -282,6 +282,10 @@ impl RepositoryCliExt for Repository {
if let Some(branch) = branch_name {
check_not_default_branch(self, branch, &deletion_mode)?;
}
+ // An orphan worktree's branch is unborn until its first commit: it has
+ // no ref, so there is nothing for the removal to delete.
+ let branch_unborn =
+ branch_name.is_some_and(|branch| snapshot.local_branch(branch).is_none());
// Phase 4: Return BranchOnly early (after validation), or continue to
// worktree-level checks. Branch-only removals have no pre-remove hook,
@@ -298,14 +302,17 @@ impl RepositoryCliExt for Repository {
live_sibling_checkout(worktrees, &branch, target)
.map(|sibling| SharedBranchCheckout::new(&sibling.path, &deletion_mode))
});
- if let Some(shared) = shared {
+ // A shared branch stays for its sibling, and an unborn one has
+ // no ref to delete, so either way pruning the entry is the whole
+ // removal.
+ if shared.is_some() || branch_unborn {
return Ok(RemovalPlan::BranchOnly {
branch_name: branch,
deletion_mode: BranchDeletionMode::Keep,
prune_entry: pruned_from,
target_branch: None,
integration_reason: None,
- branch_checked_out_at: Some(shared),
+ branch_checked_out_at: shared,
});
}
let default_branch = self.default_branch();
@@ -376,32 +383,32 @@ impl RepositoryCliExt for Repository {
// retention prediction. The actual branch deletion re-decides against
// fresh refs (`delete_branch_if_safe`'s CAS), so this is display-only.
//
- // A retained shared branch skips all of it: forcing `Keep` — the single
- // chokepoint every deletion path honors — settles the outcome, so an
- // integration verdict would only be computed to be ignored, and
- // reporting one alongside a branch that survives reads as a
- // contradiction.
- let (deletion_mode, target_branch, integration_reason) = if branch_checked_out_at.is_some()
- {
- (BranchDeletionMode::Keep, None, None)
- } else {
- let default_branch = self.default_branch();
- let target_branch = match (&default_branch, &branch_name) {
- (Some(db), Some(bn)) if db == bn => None,
- _ => default_branch,
- };
- let (integration_reason, target_branch) = match compute_integration_reason(
- self,
- snapshot,
- branch_name.as_deref(),
- target_branch.as_deref(),
- deletion_mode,
- ) {
- (reason, Some(effective_target)) => (reason, Some(effective_target)),
- (reason, None) => (reason, target_branch),
+ // A shared branch, retained for its sibling, skips all of it, as does
+ // an unborn one, which has nothing to delete. Forcing `Keep` — the
+ // single chokepoint every deletion path honors — settles the outcome,
+ // so an integration verdict would only be computed to be ignored, and
+ // beside a branch that survives it reads as a contradiction.
+ let (deletion_mode, target_branch, integration_reason) =
+ if branch_checked_out_at.is_some() || branch_unborn {
+ (BranchDeletionMode::Keep, None, None)
+ } else {
+ let default_branch = self.default_branch();
+ let target_branch = match (&default_branch, &branch_name) {
+ (Some(db), Some(bn)) if db == bn => None,
+ _ => default_branch,
+ };
+ let (integration_reason, target_branch) = match compute_integration_reason(
+ self,
+ snapshot,
+ branch_name.as_deref(),
+ target_branch.as_deref(),
+ deletion_mode,
+ ) {
+ (reason, Some(effective_target)) => (reason, Some(effective_target)),
+ (reason, None) => (reason, target_branch),
+ };
+ (deletion_mode, target_branch, integration_reason)
};
- (deletion_mode, target_branch, integration_reason)
- };
// Capture commit SHA before removal for post-remove hook template variables.
// This ensures {{ commit }} references the removed worktree's state.
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index 8bdee26cb..7a9ac17d6 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -196,8 +196,8 @@ impl SharedBranchCheckout {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BranchFate {
/// No deletion was attempted: the plan had no branch (detached worktree)
- /// or retained it (`deletion_mode` Keep — shared checkout, or
- /// `--no-delete-branch`).
+ /// or retained it (`deletion_mode` Keep — a shared checkout, an unborn
+ /// branch with no ref to delete, or `--no-delete-branch`).
NotAttempted,
/// The deletion ran and the branch is gone.
Deleted,
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 7118fb00f..7231d93d9 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -87,7 +87,7 @@ struct BackgroundRemoval<'a> {
force_worktree: bool,
changed_directory: bool,
/// `true` when the planner already decided the branch would be retained
- /// (unmerged, or `--no-delete-branch`) — `print_hints` has explained why,
+ /// (unmerged, or a `Keep` plan) — `print_hints` has explained why,
/// so [`warn_if_branch_retained`] stays silent on the expected
/// `NotDeleted` outcome and only fires when the deletion command errors.
/// `false` means the planner predicted deletion; a `NotDeleted` here is a
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 6cc612f23..e142520cf 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -572,6 +572,60 @@ fn test_remove_stale_worktree_holding_staged_changes(mut repo: TestRepo) {
);
}
+/// An orphan worktree's branch is unborn, so there is no local branch to
+/// delete or retain, even with a remote branch of that name: removing the
+/// worktree, or pruning a stale one, is the whole removal.
+#[rstest]
+fn test_remove_orphan_worktree(#[from(repo_with_remote)] repo: TestRepo) {
+ let remove = |branch: &str| {
+ repo.run_git(&[
+ "update-ref",
+ &format!("refs/remotes/origin/{branch}"),
+ "HEAD",
+ ]);
+ let wt_path = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join(format!("repo.{branch}"));
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "--orphan",
+ "-b",
+ branch,
+ wt_path.to_str().unwrap(),
+ ]);
+ if branch == "stale" {
+ std::fs::remove_dir_all(&wt_path).unwrap();
+ }
+ let output = repo
+ .wt_command()
+ .args(["remove", branch, "--yes", "--foreground"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ String::from_utf8_lossy(&output.stderr)
+ .ansi_strip()
+ .to_string()
+ };
+
+ assert_snapshot!(remove("live"), @"
+ ◎ Removing live worktree...
+ ✓ Removed live worktree (1 file · [BYTES] B)
+ ");
+ assert_snapshot!(remove("stale"), @"✓ Pruned stale worktree for stale");
+ let list = repo.git_output(&["worktree", "list", "--porcelain"]);
+ assert!(
+ !list.contains("repo.live") && !list.contains("repo.stale"),
+ "worktrees:\n{list}"
+ );
+}
+
/// A detached stale entry has no branch for the removal to fall back to, so
/// `wt remove` reports it rather than removing it; `wt step prune` is what
/// unregisters one.