Skip to content

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

fix(switch): name the branch a failed worktree add leaves behind (#4109)

Worktrunk Bot07c9160db894
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index e37aa0194..3c696d038 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -882,7 +882,11 @@ fn setup_fork_branch(
branch: branch.to_string(),
conflicting,
},
- None => worktree_creation_error(&e, branch.to_string(), None),
+ // No leftover-branch hint on this path: `wt switch pr:N` is the
+ // re-run, and it adopts or prefixes the branch on its own terms
+ // (see this function's docstring), so naming the ref would point at
+ // a recovery that isn't the one to take.
+ None => worktree_creation_error(&e, branch.to_string(), None, false),
}
})?;
@@ -1178,10 +1182,12 @@ fn execute_switch(
}
.into());
}
+ let leftover = *create_branch && failed_add_left_branch(repo, &branch);
return Err(worktree_creation_error(
&e,
branch.clone(),
base_branch.clone(),
+ leftover,
)
.into());
}
@@ -1356,10 +1362,14 @@ fn detect_branch_namespace_conflict(repo: &Repository, branch: &str) -> Option<S
/// Build a `GitError::WorktreeCreationFailed` from a failed `git worktree add`,
/// extracting the underlying command output for the error message.
+///
+/// `leftover_branch` says whether the failed add left its `-b` branch behind
+/// (see [`failed_add_left_branch`]); it only adds a hint naming the branch.
fn worktree_creation_error(
err: &anyhow::Error,
branch: String,
base_branch: Option<String>,
+ leftover_branch: bool,
) -> GitError {
let (output, command) = Repository::extract_failed_command(err);
GitError::WorktreeCreationFailed {
@@ -1367,9 +1377,37 @@ fn worktree_creation_error(
base_branch,
error: output,
command,
+ leftover_branch,
}
}
+/// Whether a failed `git worktree add -b <branch>` left the branch behind.
+///
+/// Git writes the ref before it populates the worktree and unwinds only what it
+/// registered, so a failure in between — an index it can't write, a path whose
+/// leading directories it can't create — ends with the branch present and
+/// nothing checked out on it. The next `wt switch --create <branch>` then
+/// reports `Branch … already exists`, which reads as a fresh name collision
+/// rather than as fallout from the first failure (issue #4108).
+///
+/// Read-only on purpose: `wt` names the leftover, it never deletes it. A branch
+/// is the user's, and the rollback this would otherwise be is the one #3984
+/// removed — its did-we-create-it reasoning force-deleted a branch `wt` had not
+/// created. A hint costs nothing and leaves the choice where it belongs.
+///
+/// Only the `--create` path asks. Without `--create` the leftover branch is
+/// what a re-run wants anyway, so there is nothing to explain.
+///
+/// The worktree lookup goes through a fresh [`Repository`]: the failed add may
+/// still have registered one, and `repo` cached its inventory before the
+/// command ran (see the caching contract in `git/repository/mod.rs`).
+fn failed_add_left_branch(repo: &Repository, branch: &str) -> bool {
+ repo.branch(branch).exists_locally().unwrap_or(false)
+ && Repository::at(repo.discovery_path())
+ .and_then(|fresh| fresh.worktree_for_branch(branch))
+ .is_ok_and(|worktree| worktree.is_none())
+}
+
/// Format the last fetch time as a self-contained phrase for error hint parentheticals.
///
/// Returns e.g. "last fetched 3h ago" or "last fetched just now".
diff --git a/src/git/error.rs b/src/git/error.rs
index 1475158c4..18c0617fd 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -503,6 +503,11 @@ pub enum GitError {
error: String,
/// The git command that failed, shown separately from git output
command: Option<FailedCommand>,
+ /// `git worktree add -b <branch>` created the ref and then failed, so
+ /// the branch is present with nothing checked out on it. Adds a hint
+ /// naming the leftover; see `failed_add_left_branch` in
+ /// `commands/worktree/switch.rs` for why nothing deletes it.
+ leftover_branch: bool,
},
/// A new branch can't be created because its name collides with the
/// directory namespace of an existing branch. Git stores refs as file
@@ -1200,7 +1205,13 @@ impl GitError {
)
}
- GitError::WorktreeCreationFailed { error, command, .. } => {
+ GitError::WorktreeCreationFailed {
+ branch,
+ error,
+ command,
+ leftover_branch,
+ ..
+ } => {
let title = self.title();
write!(f, "{}", format_error_block(error_message(&title), error))?;
if let Some(cmd) = command {
@@ -1211,7 +1222,22 @@ impl GitError {
format_bash_with_gutter(&cmd.command)
)?;
}
- Ok(())
+ if !*leftover_branch {
+ return Ok(());
+ }
+ // `git worktree add -b` writes the ref before it populates the
+ // worktree, so the branch outlives a failure in between. Naming
+ // it here is what keeps the next `--create` run's `Branch …
+ // already exists` from reading as a fresh name collision.
+ let escaped = escape(Cow::Borrowed(branch.as_str()));
+ let switch_cmd = suggest_command("switch", &[branch], &[]);
+ write!(
+ f,
+ "\n{}",
+ hint_message(cformat!(
+ "Branch <underline>{branch}</> was created before the failure, with no worktree; to delete it, run <underline>git branch -d -- {escaped}</>; to use it, run <underline>{switch_cmd}</>"
+ ))
+ )
}
GitError::BranchNamespaceConflict {
@@ -2407,6 +2433,7 @@ mod tests {
base_branch: Some("main".into()),
error: "git error".into(),
command: None,
+ leftover_branch: false,
};
assert_snapshot!(err.render(), @"
✗ Failed to create worktree for feature from base main
@@ -2418,6 +2445,7 @@ mod tests {
base_branch: None,
error: "git error".into(),
command: None,
+ leftover_branch: false,
};
assert_snapshot!(err.render(), @"
✗ Failed to create worktree for feature
@@ -2432,6 +2460,7 @@ mod tests {
command: "git worktree add /path -b feature main".into(),
exit_info: "exit code 128".into(),
}),
+ leftover_branch: false,
};
assert_snapshot!(err.render(), @"
✗ Failed to create worktree for feature from base main
@@ -2441,6 +2470,25 @@ mod tests {
");
}
+ #[test]
+ fn snapshot_worktree_creation_failed_leftover_branch() {
+ // `git worktree add -b` wrote the ref and then failed, so the branch
+ // outlives the command with nothing checked out on it. The hint names
+ // it so the next `--create` run's "already exists" reads as fallout.
+ let err = GitError::WorktreeCreationFailed {
+ branch: "feature/auth".into(),
+ base_branch: Some("main".into()),
+ error: "fatal: could not create leading directories".into(),
+ command: None,
+ leftover_branch: true,
+ };
+ assert_snapshot!(err.render(), @"
+ ✗ Failed to create worktree for feature/auth from base main
+   fatal: could not create leading directories
+ ↳ Branch feature/auth was created before the failure, with no worktree; to delete it, run git branch -d -- feature/auth; to use it, run wt switch feature/auth
+ ");
+ }
+
#[test]
fn snapshot_worktree_locked() {
let err = GitError::WorktreeLocked {
diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rs
index 8438fa624..765e22ca9 100644
--- a/tests/integration_tests/git_error_display.rs
+++ b/tests/integration_tests/git_error_display.rs
@@ -89,6 +89,7 @@ fn worktree_errors_render() {
base_branch: Some("main".into()),
error: "fatal: '/tmp/repo.feature-y' already exists".into(),
command: None,
+ leftover_branch: false,
}
.render(),
),
@@ -104,6 +105,7 @@ fn worktree_errors_render() {
command: "git worktree add /tmp/repo.fix -b fix main".into(),
exit_info: "exit code 128".into(),
}),
+ leftover_branch: false,
}
.render(),
),
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 06376d648..5b6546766 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -8398,3 +8398,51 @@ fn switch_base_accepts_worktree_path(mut repo: TestRepo) {
"--base should resolve the worktree path to its branch: {stderr}"
);
}
+
+#[rstest]
+fn test_switch_create_names_branch_left_by_failed_worktree_add(repo: TestRepo) {
+ // `git worktree add -b` writes the branch ref before it populates the
+ // worktree, so a failure in between leaves the branch with nothing checked
+ // out on it (issue #4108). A regular file where the worktree's leading
+ // directories would go is the portable way to fail git exactly there.
+ repo.write_test_config(r#"worktree-path = "blocked/{{ branch | sanitize }}""#);
+ fs::write(repo.root_path().join("blocked"), "not a directory").unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["switch", "--create", "stranded"])
+ .output()
+ .unwrap();
+ assert!(
+ !output.status.success(),
+ "switch --create should fail when git cannot create the worktree"
+ );
+
+ // The branch git left behind is what makes a retry with --create report
+ // "already exists"; the first failure has to name it.
+ let branches = repo.git_output(&["branch", "--list", "stranded"]);
+ assert!(
+ branches.contains("stranded"),
+ "expected git to leave the branch behind, got: {branches:?}"
+ );
+ let worktrees = repo.git_output(&["worktree", "list", "--porcelain"]);
+ assert!(
+ !worktrees.contains("refs/heads/stranded"),
+ "expected no worktree on the leftover branch, got: {worktrees:?}"
+ );
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let stderr = stderr.ansi_strip();
+ assert!(
+ stderr.contains("Branch stranded was created before the failure, with no worktree"),
+ "expected the failure to name the leftover branch, got: {stderr}"
+ );
+ assert!(
+ stderr.contains("git branch -d -- stranded"),
+ "expected a delete suggestion for the leftover branch, got: {stderr}"
+ );
+ assert!(
+ stderr.contains("wt switch stranded"),
+ "expected a recovery suggestion for the leftover branch, got: {stderr}"
+ );
+}