Skip to content

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

Merge: Defer worktree removal until after primary worktree switch

Maximilian Roos3dc228f27980
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 87d610e05..d81ad14ef 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -116,16 +116,10 @@ pub fn handle_merge(
// Finish worktree unless --keep was specified
if !keep {
- crate::output::progress(format!("πŸ”„ {CYAN}Cleaning up worktree...{CYAN:#}"))?;
-
- let result = handle_remove(None)?;
-
- // Set directory for shell integration (but don't print separate success message)
- if let super::worktree::RemoveResult::RemovedWorktree { primary_path } = &result {
- crate::output::change_directory(primary_path)?;
- }
+ // STEP 1: Emit CD directive (just sets intent, doesn't actually change CWD)
+ crate::output::change_directory(&primary_worktree_dir)?;
- // Check if we need to switch to target branch
+ // STEP 2: Switch to target branch in primary worktree (fails safely if there's an issue)
let primary_repo = Repository::at(&primary_worktree_dir);
let new_branch = primary_repo.current_branch()?;
if new_branch.as_deref() != Some(&target_branch) {
@@ -137,6 +131,10 @@ pub fn handle_merge(
.git_context(&format!("Failed to switch to '{}'", target_branch))?;
}
+ // STEP 3: Only NOW remove the worktree (after everything else succeeded)
+ crate::output::progress(format!("πŸ”„ {CYAN}Cleaning up worktree...{CYAN:#}"))?;
+ handle_remove(None)?;
+
// Print comprehensive summary
crate::output::progress("")?;
handle_merge_summary_output(Some(&primary_worktree_dir))?;
diff --git a/tests/snapshots/integration__integration_tests__directives__merge_internal_remove.snap b/tests/snapshots/integration__integration_tests__directives__merge_internal_remove.snap
index 8f4b1482a..a4620d677 100644
Binary files a/tests/snapshots/integration__integration_tests__directives__merge_internal_remove.snap and b/tests/snapshots/integration__integration_tests__directives__merge_internal_remove.snap differ