Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: delete branch synchronously on fast-path remove (#1216)
Maximilian Roos0bee6af00b2d
diff --git a/src/commands/process.rs b/src/commands/process.rsindex a0ae5f71a..ac209b972 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -388,33 +388,21 @@ pub fn generate_removing_path(worktree_path: &Path) -> PathBuf {/// Build shell command for background removal of a staged (renamed) worktree.///-/// This is used after the worktree has been renamed to a staging path and-/// git metadata has been pruned. The command just does `rm -rf` on the-/// staged directory, optionally followed by branch deletion.+/// This is used after the worktree has been renamed to a staging path,+/// git metadata has been pruned, and the branch has been deleted synchronously.+/// The command just does `rm -rf` on the staged directory.////// No sleep is needed because:/// 1. The shell cd happens before the rename (directive file is written first)/// 2. The original worktree path no longer exists immediately after rename-pub fn build_remove_command_staged(- staged_path: &std::path::Path,- branch_to_delete: Option<&str>,-) -> String {+pub fn build_remove_command_staged(staged_path: &std::path::Path) -> String {use shell_escape::escape;let staged_path_str = staged_path.to_string_lossy();let staged_escaped = escape(staged_path_str.as_ref().into());- // Use -- to prevent option parsing for paths/branches starting with -- match branch_to_delete {- Some(branch_name) => {- let branch_escaped = escape(branch_name.into());- format!(- "rm -rf -- {} && git branch -D -- {}",- staged_escaped, branch_escaped- )- }- None => format!("rm -rf -- {}", staged_escaped),- }+ // Use -- to prevent option parsing for paths starting with -+ format!("rm -rf -- {}", staged_escaped)}/// Build shell command for background worktree removal (legacy path).@@ -606,22 +594,15 @@ mod tests {fn test_build_remove_command_staged() {let staged_path = PathBuf::from("/tmp/my-project.feature.wt-removing-1234567890");- // Without branch deletion- let cmd = build_remove_command_staged(&staged_path, None);+ let cmd = build_remove_command_staged(&staged_path);assert!(cmd.starts_with("rm -rf -- ")); // -- prevents option parsingassert!(cmd.contains("wt-removing-1234567890"));- assert!(!cmd.contains("branch -D"));+ assert!(!cmd.contains("branch -D")); // Branch deleted synchronously, not in backgroundassert!(!cmd.contains("sleep")); // No sleep in staged removal- // With branch deletion- let cmd = build_remove_command_staged(&staged_path, Some("feature-branch"));- assert!(cmd.contains("rm -rf -- ")); // -- prevents option parsing- assert!(cmd.contains("git branch -D -- ")); // -- prevents option parsing- assert!(cmd.contains("feature-branch"));-// Shell escaping for special characterslet special_path = PathBuf::from("/tmp/test worktree.wt-removing-123");- let cmd = build_remove_command_staged(&special_path, Some("feature/branch"));+ let cmd = build_remove_command_staged(&special_path);assert!(cmd.contains("rm -rf "));// Verify the path is escaped (single-quoted for shell safety)assert!(diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 153a8ff65..6ea9d25fc 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -43,9 +43,10 @@ use super::shell_integration::{/// Execute instant worktree removal via rename-then-prune, returning the background command.////// This function has side effects: it renames the worktree directory and prunes git metadata.-/// If successful, returns a simple `rm -rf` command for the staged directory.+/// On the fast path, the branch is also deleted synchronously (since after prune, the branch+/// is no longer checked out in any worktree), and the background command is just `rm -rf`./// If rename fails (cross-filesystem, permissions, Windows file locking), returns the legacy-/// `git worktree remove` command instead.+/// `git worktree remove` command with branch deletion deferred to the background.////// The caller is responsible for spawning the returned command in the background.fn execute_instant_removal_or_fallback(@@ -66,11 +67,22 @@ fn execute_instant_removal_or_fallback(if let Err(e) = repo.prune_worktrees() {log::debug!("Failed to prune worktrees after rename: {}", e);}- build_remove_command_staged(&staged_path, branch_to_delete)+ // Delete branch synchronously now that prune has removed the worktree metadata.+ // The branch is no longer checked out, so `git branch -D` will succeed.+ // This avoids a race where the user creates a new worktree with the same branch+ // name before the background `rm -rf` completes.+ if let Some(branch) = branch_to_delete+ && let Err(e) = repo.run_command(&["branch", "-D", branch])+ {+ log::debug!("Failed to delete branch {} synchronously: {}", branch, e);+ }+ build_remove_command_staged(&staged_path)}Err(e) => {// Fallback: cross-filesystem, permissions, Windows file locking, etc.// Use legacy git worktree remove which handles these cases.+ // Branch deletion stays in the background command since the worktree+ // still references the branch until `git worktree remove` runs.log::debug!("Instant removal unavailable, using legacy: {}", e);// Git refuses to remove worktrees with initialized submodules without// --force. We preemptively set --force when .gitmodules exists — broaderdiff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex b4d85a170..8dec394d7 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -1934,10 +1934,12 @@ fn test_remove_background_git_metadata_pruned(mut repo: TestRepo) {);}-/// Background removal should delete the branch when it's merged.+/// Background removal should delete the branch synchronously when it's merged.///-/// This verifies that branch deletion works correctly with the instant removal path-/// (the branch is deleted in the background after the worktree is renamed).+/// On the fast path (rename-then-prune), the branch is deleted synchronously+/// after pruning git metadata, before the background `rm -rf` runs.+/// This prevents races where the user creates a new worktree with the same+/// branch name before the background process completes.#[rstest]fn test_remove_background_deletes_merged_branch(mut repo: TestRepo) {// Create a worktree with the branch already merged to main (same commit)@@ -1969,15 +1971,18 @@ fn test_remove_background_deletes_merged_branch(mut repo: TestRepo) {String::from_utf8_lossy(&output.stderr));- // Poll for background branch deletion (happens after rm -rf in background command)- crate::common::wait_for("merged branch deleted by background removal", || {- let branches = repo- .git_command()- .args(["branch", "--list", "feature-merged"])- .output()- .unwrap();- String::from_utf8_lossy(&branches.stdout).trim().is_empty()- });+ // Branch should be deleted IMMEDIATELY (synchronously, not in background)+ let branches_after = repo+ .git_command()+ .args(["branch", "--list", "feature-merged"])+ .output()+ .unwrap();+ assert!(+ String::from_utf8_lossy(&branches_after.stdout)+ .trim()+ .is_empty(),+ "Branch should be deleted synchronously after wt remove returns"+ );}/// Test that worktree paths containing special characters are handled correctly.