Skip to content

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

fix: only create placeholder directory when removing current worktree (#1868)

Maximilian Roos0d37405b3884
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 3e7b36a06..29a7cb639 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -406,33 +406,43 @@ pub fn generate_removing_path(trash_dir: &Path, worktree_path: &Path) -> PathBuf
/// 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 delay mirrors `build_remove_command`'s `sleep 1`. After the rename,
-/// a placeholder directory is created at `original_path` so the shell's
+/// The delay mirrors `build_remove_command`'s `sleep 1`.
+///
+/// When `changed_directory` is true — the shell is cd-ing away from the removed
+/// worktree — a placeholder directory is created at `original_path` so the shell's
/// working directory remains valid until the wrapper has processed the `cd`
/// directive. Without this, shells that validate `$env.PWD` (notably Nushell)
-/// emit errors between binary exit and the `cd`.
+/// emit errors between binary exit and the `cd`. The background command then
+/// waits for the shell wrapper before cleaning up the placeholder.
///
-/// The background command removes both the placeholder and the staged directory.
+/// When `changed_directory` is false, no placeholder exists, so the background
+/// command just removes the staged directory directly.
pub fn build_remove_command_staged(
staged_path: &std::path::Path,
original_path: &std::path::Path,
+ changed_directory: bool,
) -> String {
use shell_escape::escape;
let staged_path_str = staged_path.to_string_lossy();
let staged_escaped = escape(staged_path_str.as_ref().into());
- let original_path_str = original_path.to_string_lossy();
- let original_escaped = escape(original_path_str.as_ref().into());
-
- // sleep 1: give the shell wrapper time to cd away before removing the placeholder.
- // rmdir: remove the empty placeholder (safe — only removes empty directories).
- // rm -rf: remove the staged worktree contents.
- // Use -- to prevent option parsing for paths starting with -
- format!(
- "sleep 1 && rmdir -- {} 2>/dev/null; rm -rf -- {}",
- original_escaped, staged_escaped
- )
+ if changed_directory {
+ let original_path_str = original_path.to_string_lossy();
+ let original_escaped = escape(original_path_str.as_ref().into());
+
+ // sleep 1: give the shell wrapper time to cd away before removing the placeholder.
+ // rmdir: remove the empty placeholder (safe — only removes empty directories).
+ // rm -rf: remove the staged worktree contents.
+ // Use -- to prevent option parsing for paths starting with -
+ format!(
+ "sleep 1 && rmdir -- {} 2>/dev/null; rm -rf -- {}",
+ original_escaped, staged_escaped
+ )
+ } else {
+ // No placeholder to clean up — just remove the staged directory.
+ format!("rm -rf -- {}", staged_escaped)
+ }
}
/// Build shell command for background worktree removal (legacy path).
@@ -623,12 +633,17 @@ mod tests {
fn test_build_remove_command_staged() {
let staged_path = PathBuf::from("/tmp/repo/.git/wt/trash/my-project.feature-1234567890");
let original_path = PathBuf::from("/tmp/my-project.feature");
- assert_snapshot!(build_remove_command_staged(&staged_path, &original_path), @"sleep 1 && rmdir -- /tmp/my-project.feature 2>/dev/null; rm -rf -- /tmp/repo/.git/wt/trash/my-project.feature-1234567890");
+
+ // changed_directory=true: placeholder cleanup before rm -rf
+ assert_snapshot!(build_remove_command_staged(&staged_path, &original_path, true), @"sleep 1 && rmdir -- /tmp/my-project.feature 2>/dev/null; rm -rf -- /tmp/repo/.git/wt/trash/my-project.feature-1234567890");
+
+ // changed_directory=false: just rm -rf, no placeholder
+ assert_snapshot!(build_remove_command_staged(&staged_path, &original_path, false), @"rm -rf -- /tmp/repo/.git/wt/trash/my-project.feature-1234567890");
// Shell escaping for special characters (space in path)
let special_path = PathBuf::from("/tmp/repo/.git/wt/trash/test worktree-123");
let special_original = PathBuf::from("/tmp/test worktree");
- assert_snapshot!(build_remove_command_staged(&special_path, &special_original), @"sleep 1 && rmdir -- '/tmp/test worktree' 2>/dev/null; rm -rf -- '/tmp/repo/.git/wt/trash/test worktree-123'");
+ assert_snapshot!(build_remove_command_staged(&special_path, &special_original, true), @"sleep 1 && rmdir -- '/tmp/test worktree' 2>/dev/null; rm -rf -- '/tmp/repo/.git/wt/trash/test worktree-123'");
}
#[test]
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 60f244259..755067e17 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -55,6 +55,7 @@ fn spawn_background_removal(
branch_to_delete: Option<&str>,
force_worktree: bool,
log_label: &str,
+ changed_directory: bool,
) -> anyhow::Result<()> {
// Stop fsmonitor daemon BEFORE rename (must happen while path still exists).
// Best effort — prevents zombie daemons from accumulating.
@@ -62,8 +63,13 @@ fn spawn_background_removal(
.worktree_at(worktree_path)
.run_command(&["fsmonitor--daemon", "stop"]);
- let remove_command =
- execute_instant_removal_or_fallback(repo, worktree_path, branch_to_delete, force_worktree);
+ let remove_command = execute_instant_removal_or_fallback(
+ repo,
+ worktree_path,
+ branch_to_delete,
+ force_worktree,
+ changed_directory,
+ );
spawn_detached(
repo,
@@ -91,6 +97,7 @@ fn execute_instant_removal_or_fallback(
worktree_path: &Path,
branch_to_delete: Option<&str>,
force_worktree: bool,
+ changed_directory: bool,
) -> String {
// Fast path: rename worktree into .git/wt/trash/ (instant on same filesystem),
// prune git metadata, then background process just does `rm -rf`.
@@ -104,14 +111,16 @@ fn execute_instant_removal_or_fallback(
{
log::debug!("Failed to delete branch {} synchronously: {}", branch, e);
}
- // Create an empty placeholder at the original path so the shell's working
- // directory ($env.PWD) remains valid until the wrapper has cd'd away.
- // Without this, shells that validate PWD (notably Nushell) emit errors
- // between binary exit and the cd directive executing.
- // Best-effort: if create_dir fails (permissions, race), the only effect
- // is that Nushell may still emit PWD errors — not a correctness issue.
- let _ = std::fs::create_dir(worktree_path);
- build_remove_command_staged(&staged_path, worktree_path)
+ if changed_directory {
+ // Create an empty placeholder at the original path so the shell's working
+ // directory ($env.PWD) remains valid until the wrapper has cd'd away.
+ // Without this, shells that validate PWD (notably Nushell) emit errors
+ // between binary exit and the cd directive executing.
+ // Best-effort: if create_dir fails (permissions, race), the only effect
+ // is that Nushell may still emit PWD errors — not a correctness issue.
+ let _ = std::fs::create_dir(worktree_path);
+ }
+ build_remove_command_staged(&staged_path, worktree_path, changed_directory)
} else {
// Fallback: cross-filesystem, permissions, Windows file locking, etc.
// Use legacy git worktree remove which handles these cases.
@@ -1184,6 +1193,7 @@ fn handle_detached_removed_worktree_output(
None,
ctx.force_worktree,
"detached",
+ ctx.changed_directory,
)?;
}
@@ -1291,6 +1301,7 @@ fn handle_named_removed_worktree_background(
display_info.branch_deleted().then_some(branch_name),
ctx.force_worktree,
branch_name,
+ ctx.changed_directory,
)?;
spawn_hooks_after_remove(
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 30d379496..09c5eec9b 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -2172,8 +2172,8 @@ fn test_remove_background_path_gone_immediately(mut repo: TestRepo) {
);
// The worktree contents should be gone IMMEDIATELY (moved to .git/wt/trash/).
- // An empty placeholder directory may remain briefly (for shell PWD validity).
- crate::common::assert_worktree_removed(&worktree_path);
+ // No placeholder created because this is a non-current worktree removal.
+ assert!(!worktree_path.exists(), "Worktree should be fully removed");
}
/// Background removal should prune git worktree metadata synchronously.
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index 946e74ac7..d1c06f194 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -67,13 +67,13 @@ fn test_prune_removes_merged(mut repo: TestRepo) {
None
));
- // Verify worktree was removed
+ // Verify worktree was removed (non-current removal — no placeholder created)
let worktree_path = repo
.root_path()
.parent()
.unwrap()
.join("repo.merged-branch");
- crate::common::assert_worktree_removed(&worktree_path);
+ assert!(!worktree_path.exists(), "Worktree should be fully removed");
}
/// Prune skips worktrees with unique commits (not merged)
@@ -94,9 +94,12 @@ fn test_prune_skips_unmerged(mut repo: TestRepo) {
None
));
- // Merged worktree removed
+ // Merged worktree removed (non-current — no placeholder)
let merged_path = repo.root_path().parent().unwrap().join("repo.merged-one");
- crate::common::assert_worktree_removed(&merged_path);
+ assert!(
+ !merged_path.exists(),
+ "Merged worktree should be fully removed"
+ );
// Unmerged worktree still exists
let unmerged_path = repo.root_path().parent().unwrap().join("repo.unmerged");
@@ -144,11 +147,20 @@ fn test_prune_multiple(mut repo: TestRepo) {
None
));
- // All merged worktrees removed
+ // All merged worktrees removed (non-current — no placeholders)
let parent = repo.root_path().parent().unwrap();
- crate::common::assert_worktree_removed(&parent.join("repo.merged-a"));
- crate::common::assert_worktree_removed(&parent.join("repo.merged-b"));
- crate::common::assert_worktree_removed(&parent.join("repo.merged-c"));
+ assert!(
+ !parent.join("repo.merged-a").exists(),
+ "merged-a should be fully removed"
+ );
+ assert!(
+ !parent.join("repo.merged-b").exists(),
+ "merged-b should be fully removed"
+ );
+ assert!(
+ !parent.join("repo.merged-c").exists(),
+ "merged-c should be fully removed"
+ );
}
/// Prune skips unmerged detached HEAD worktrees
@@ -192,9 +204,12 @@ fn test_prune_removes_integrated_detached(mut repo: TestRepo) {
None
));
- // Worktree was removed
+ // Worktree was removed (non-current — no placeholder)
let parent = repo.root_path().parent().unwrap();
- crate::common::assert_worktree_removed(&parent.join("repo.detached-integrated"));
+ assert!(
+ !parent.join("repo.detached-integrated").exists(),
+ "Worktree should be fully removed"
+ );
}
/// Prune removes multiple integrated detached HEAD worktrees (exercises plural "worktrees")
@@ -216,8 +231,14 @@ fn test_prune_removes_multiple_detached(mut repo: TestRepo) {
));
let parent = repo.root_path().parent().unwrap();
- crate::common::assert_worktree_removed(&parent.join("repo.detached-a"));
- crate::common::assert_worktree_removed(&parent.join("repo.detached-b"));
+ assert!(
+ !parent.join("repo.detached-a").exists(),
+ "detached-a should be fully removed"
+ );
+ assert!(
+ !parent.join("repo.detached-b").exists(),
+ "detached-b should be fully removed"
+ );
}
/// Prune skips locked worktrees
@@ -239,9 +260,12 @@ fn test_prune_skips_locked(mut repo: TestRepo) {
None
));
- // Merged removed, locked remains
+ // Merged removed (non-current — no placeholder), locked remains
let parent = repo.root_path().parent().unwrap();
- crate::common::assert_worktree_removed(&parent.join("repo.merged-branch"));
+ assert!(
+ !parent.join("repo.merged-branch").exists(),
+ "Merged worktree should be fully removed"
+ );
assert!(
parent.join("repo.locked-branch").exists(),
"Locked worktree should be skipped"
@@ -309,7 +333,10 @@ fn test_prune_mixed_worktree_and_orphan_branch(mut repo: TestRepo) {
));
let parent = repo.root_path().parent().unwrap();
- crate::common::assert_worktree_removed(&parent.join("repo.merged-mixed"));
+ assert!(
+ !parent.join("repo.merged-mixed").exists(),
+ "Worktree should be fully removed"
+ );
}
/// Prune from a merged worktree removes it last (CandidateKind::Current).
@@ -392,9 +419,12 @@ fn test_prune_skips_dirty(mut repo: TestRepo) {
// Dirty worktree still exists
assert!(wt_path.exists(), "Dirty worktree should be skipped");
- // Clean worktree removed
+ // Clean worktree removed (non-current — no placeholder)
let clean_path = repo.root_path().parent().unwrap().join("repo.clean-merged");
- crate::common::assert_worktree_removed(&clean_path);
+ assert!(
+ !clean_path.exists(),
+ "Clean worktree should be fully removed"
+ );
}
/// Dry-run with mixed worktrees + orphan branches shows both counts.