Skip to content

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

feat(remove): instant worktree removal via move-then-delete (#773)

Maximilian Roos298a961a54b8
diff --git a/src/commands/process.rs b/src/commands/process.rs
index bcdd4a6f5..a0ae5f71a 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -9,6 +9,7 @@ use std::str::FromStr;
use strum::IntoEnumIterator;
use worktrunk::git::{HookType, Repository};
use worktrunk::path::{format_path_for_display, sanitize_for_filename};
+use worktrunk::utils::get_now;
use crate::commands::hook_filter::HookSource;
@@ -369,7 +370,57 @@ fn spawn_detached_windows(
Ok(())
}
-/// Build shell command for background worktree removal
+/// Generate a staging path for worktree removal.
+///
+/// Creates a sibling path with a unique suffix to enable instant rename-based removal.
+/// The path is guaranteed to be on the same filesystem as the original worktree
+/// (sibling paths share the same parent directory).
+///
+/// Format: `<path>.wt-removing-<timestamp>`
+pub fn generate_removing_path(worktree_path: &Path) -> PathBuf {
+ let timestamp = get_now();
+ let name = worktree_path
+ .file_name()
+ .map(|n| n.to_string_lossy())
+ .unwrap_or_default();
+ worktree_path.with_file_name(format!("{}.wt-removing-{}", name, timestamp))
+}
+
+/// 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.
+///
+/// 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 {
+ 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),
+ }
+}
+
+/// Build shell command for background worktree removal (legacy path).
+///
+/// This is the fallback for when rename-based removal fails (e.g., cross-filesystem)
+/// or for foreground mode where `git worktree remove` provides better error messages.
///
/// `branch_to_delete` is the branch to delete after removing the worktree.
/// Pass `None` for detached HEAD or when branch should be retained.
@@ -526,6 +577,60 @@ mod tests {
assert!(cmd.contains("worktree remove"));
}
+ #[test]
+ fn test_generate_removing_path() {
+ let path = PathBuf::from("/tmp/my-project.feature");
+ let removing_path = generate_removing_path(&path);
+
+ // Should be a sibling path (same parent)
+ assert_eq!(removing_path.parent(), path.parent());
+
+ // Should have the expected prefix
+ let name = removing_path.file_name().unwrap().to_string_lossy();
+ assert!(
+ name.starts_with("my-project.feature.wt-removing-"),
+ "got: {}",
+ name
+ );
+
+ // Should have a timestamp suffix (digits only after the prefix)
+ let timestamp_part = name.trim_start_matches("my-project.feature.wt-removing-");
+ assert!(
+ timestamp_part.chars().all(|c| c.is_ascii_digit()),
+ "timestamp part should be numeric: {}",
+ timestamp_part
+ );
+ }
+
+ #[test]
+ 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);
+ assert!(cmd.starts_with("rm -rf -- ")); // -- prevents option parsing
+ assert!(cmd.contains("wt-removing-1234567890"));
+ assert!(!cmd.contains("branch -D"));
+ assert!(!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 characters
+ let special_path = PathBuf::from("/tmp/test worktree.wt-removing-123");
+ let cmd = build_remove_command_staged(&special_path, Some("feature/branch"));
+ assert!(cmd.contains("rm -rf "));
+ // Verify the path is escaped (single-quoted for shell safety)
+ assert!(
+ cmd.contains("'/tmp/test worktree.wt-removing-123'"),
+ "path should be escaped: {}",
+ cmd
+ );
+ }
+
#[test]
fn test_hook_log_hook_suffix() {
use worktrunk::git::HookType;
diff --git a/src/output/global.rs b/src/output/global.rs
index ec9bb5ebc..f6cdbb3f7 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -398,7 +398,11 @@ pub fn compute_hooks_display_path<'a>(
pub fn pre_hook_display_path(hooks_run_at: &std::path::Path) -> Option<&std::path::Path> {
let cwd = match std::env::current_dir() {
Ok(cwd) => cwd,
- Err(_) => return None, // Can't determine cwd, don't show path
+ Err(_) => {
+ // Can't determine cwd (directory deleted/renamed) - show the path
+ // since we can't know if user is there or not
+ return Some(hooks_run_at);
+ }
};
compute_hooks_display_path(hooks_run_at, &cwd)
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 6602504c6..7bfd599ce 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -15,7 +15,10 @@ use crate::commands::command_executor::CommandContext;
use crate::commands::hooks::{
HookFailureStrategy, execute_hook, prepare_background_hooks, spawn_background_hooks,
};
-use crate::commands::process::{HookLog, InternalOp, build_remove_command, spawn_detached};
+use crate::commands::process::{
+ HookLog, InternalOp, build_remove_command, build_remove_command_staged, generate_removing_path,
+ spawn_detached,
+};
use crate::commands::worktree::{BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult};
use worktrunk::config::UserConfig;
use worktrunk::git::GitError;
@@ -33,6 +36,51 @@ use super::shell_integration::{
shell_integration_hint, should_show_explicit_path_hint,
};
+// ============================================================================
+// Background Removal Helper
+// ============================================================================
+
+/// 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.
+/// If rename fails (cross-filesystem, permissions, Windows file locking), returns the legacy
+/// `git worktree remove` command instead.
+///
+/// The caller is responsible for spawning the returned command in the background.
+fn execute_instant_removal_or_fallback(
+ repo: &Repository,
+ worktree_path: &Path,
+ branch_to_delete: Option<&str>,
+ force_worktree: bool,
+) -> String {
+ // Fast path: instant removal via rename-then-prune.
+ // Rename worktree to staging path (instant on same filesystem), then prune
+ // git metadata. Background process just does `rm -rf` on the staged directory.
+ let staged_path = generate_removing_path(worktree_path);
+ match std::fs::rename(worktree_path, &staged_path) {
+ Ok(()) => {
+ // Fast path succeeded - prune git metadata synchronously.
+ // If prune fails, log and continue - the staged directory will still be deleted,
+ // and stale metadata is harmless (cleaned up by git gc or our next worktree operation).
+ 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)
+ }
+ Err(e) => {
+ // Fallback: cross-filesystem, permissions, Windows file locking, etc.
+ // Use legacy git worktree remove which handles these cases.
+ log::debug!("Instant removal unavailable, using legacy: {}", e);
+ build_remove_command(worktree_path, branch_to_delete, force_worktree)
+ }
+ }
+}
+
+// ============================================================================
+// Switch Output Handlers
+// ============================================================================
+
/// Format a switch message based on what was created
///
/// # Message formats
@@ -953,7 +1001,15 @@ fn handle_removed_worktree_output(
"Removing worktree in background (detached HEAD, no branch to delete)",
)
);
- let remove_command = build_remove_command(worktree_path, None, force_worktree);
+
+ // Stop fsmonitor daemon BEFORE rename (must happen while path still exists)
+ let _ = repo
+ .worktree_at(worktree_path)
+ .run_command(&["fsmonitor--daemon", "stop"]);
+
+ let remove_command =
+ execute_instant_removal_or_fallback(&repo, worktree_path, None, force_worktree);
+
spawn_detached(
&repo,
main_path,
@@ -1015,8 +1071,14 @@ fn handle_removed_worktree_output(
display_info.print_hints(branch_name, deletion_mode, pre_computed_integration)?;
print_switch_message_if_changed(changed_directory, main_path)?;
- // Build command with the decision we already made
- let remove_command = build_remove_command(
+ // Stop fsmonitor daemon BEFORE rename (must happen while path still exists).
+ // Best effort - ignore errors. This prevents zombie daemons from accumulating.
+ let _ = repo
+ .worktree_at(worktree_path)
+ .run_command(&["fsmonitor--daemon", "stop"]);
+
+ let remove_command = execute_instant_removal_or_fallback(
+ &repo,
worktree_path,
display_info.branch_deleted().then_some(branch_name),
force_worktree,
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 42085ebe7..85bcd97db 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1804,3 +1804,298 @@ fn test_remove_pruned_worktree_keep_branch(mut repo: TestRepo) {
"Branch should still exist"
);
}
+
+// ============================================================================
+// Instant Removal Tests (move-then-delete optimization)
+// ============================================================================
+
+/// Background removal should make the original worktree path unavailable immediately.
+///
+/// This tests the move-then-delete optimization: the worktree directory is renamed
+/// to a staging path synchronously, so the original path is gone before wt returns.
+/// The actual deletion (rm -rf) happens in the background.
+#[rstest]
+fn test_remove_background_path_gone_immediately(mut repo: TestRepo) {
+ // Create a worktree
+ let worktree_path = repo.add_worktree("feature-instant");
+
+ // Verify the worktree exists
+ assert!(worktree_path.exists(), "Worktree should exist initially");
+
+ // Remove in background mode (default) - NOT using snapshot since we need to check state after
+ let output = repo
+ .wt_command()
+ .args(["remove", "feature-instant"])
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "wt remove should succeed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // The original worktree path should be gone IMMEDIATELY (before background rm completes)
+ // This is the key behavior of the move-then-delete optimization
+ assert!(
+ !worktree_path.exists(),
+ "Worktree path should be gone immediately after wt remove returns"
+ );
+
+ // Note: The staging directory (.wt-removing-*) might already be deleted by the
+ // background process, or it might still exist. Both are valid outcomes.
+ // The key assertion above is that the original path is gone immediately.
+}
+
+/// Background removal should prune git worktree metadata synchronously.
+///
+/// After removal, `git worktree list` should NOT show the removed worktree,
+/// even before the background rm -rf completes.
+#[rstest]
+fn test_remove_background_git_metadata_pruned(mut repo: TestRepo) {
+ // Create a worktree
+ let _worktree_path = repo.add_worktree("feature-prune-test");
+
+ // Verify git knows about the worktree
+ let list_before = repo
+ .git_command()
+ .args(["worktree", "list", "--porcelain"])
+ .output()
+ .unwrap();
+ assert!(
+ String::from_utf8_lossy(&list_before.stdout).contains("feature-prune-test"),
+ "Git should list the worktree before removal"
+ );
+
+ // Remove in background mode
+ let output = repo
+ .wt_command()
+ .args(["remove", "feature-prune-test"])
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "wt remove should succeed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Git worktree metadata should be pruned IMMEDIATELY
+ let list_after = repo
+ .git_command()
+ .args(["worktree", "list", "--porcelain"])
+ .output()
+ .unwrap();
+ assert!(
+ !String::from_utf8_lossy(&list_after.stdout).contains("feature-prune-test"),
+ "Git should NOT list the worktree after removal (metadata should be pruned)"
+ );
+}
+
+/// Background removal should delete the branch 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).
+#[rstest]
+fn test_remove_background_deletes_merged_branch(mut repo: TestRepo) {
+ // Create a worktree with the branch already merged to main (same commit)
+ let _worktree_path = repo.add_worktree("feature-merged");
+
+ // Verify branch exists before removal
+ let branches_before = repo
+ .git_command()
+ .args(["branch", "--list", "feature-merged"])
+ .output()
+ .unwrap();
+ assert!(
+ !String::from_utf8_lossy(&branches_before.stdout)
+ .trim()
+ .is_empty(),
+ "Branch should exist before removal"
+ );
+
+ // Remove in background mode (default)
+ let output = repo
+ .wt_command()
+ .args(["remove", "feature-merged"])
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "wt remove should succeed: {}",
+ 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()
+ });
+}
+
+/// Test that worktree paths containing special characters are handled correctly.
+///
+/// This tests that the `rm -rf -- <path>` command correctly handles paths
+/// that might be misinterpreted as options.
+#[rstest]
+fn test_remove_worktree_with_special_path_chars(mut repo: TestRepo) {
+ // Create a worktree with special characters in the branch name
+ // (which becomes part of the path)
+ let _worktree_path = repo.add_worktree("feature--double-dash");
+
+ // Verify worktree exists
+ let list_before = repo
+ .git_command()
+ .args(["worktree", "list", "--porcelain"])
+ .output()
+ .unwrap();
+ assert!(
+ String::from_utf8_lossy(&list_before.stdout).contains("feature--double-dash"),
+ "Worktree should exist before removal"
+ );
+
+ // Remove the worktree
+ let output = repo
+ .wt_command()
+ .args(["remove", "feature--double-dash"])
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "wt remove should succeed for path with special chars: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Poll for background worktree removal
+ crate::common::wait_for("worktree with special chars removed", || {
+ let list = repo
+ .git_command()
+ .args(["worktree", "list", "--porcelain"])
+ .output()
+ .unwrap();
+ !String::from_utf8_lossy(&list.stdout).contains("feature--double-dash")
+ });
+}
+
+/// Test that background removal falls back to legacy git worktree remove
+/// when the instant rename fails.
+///
+/// This tests the fallback path: when std::fs::rename() fails (e.g., cross-filesystem,
+/// permissions, or in this case a blocking file), we fall back to the legacy
+/// `git worktree remove` command which handles cleanup properly.
+#[rstest]
+fn test_remove_background_fallback_on_rename_failure(mut repo: TestRepo) {
+ // Create a worktree
+ let worktree_path = repo.add_worktree("feature-fallback");
+
+ // Calculate the expected staged path that the rename would use.
+ // The path is: <worktree>.wt-removing-<TEST_EPOCH>
+ // Since WT_TEST_EPOCH is set by the test harness, the timestamp is deterministic.
+ let staged_path = worktree_path.with_file_name(format!(
+ "{}.wt-removing-{}",
+ worktree_path.file_name().unwrap().to_string_lossy(),
+ crate::common::TEST_EPOCH
+ ));
+
+ // Create a regular file at the staged path to block the rename.
+ // On POSIX systems, you cannot rename a directory to an existing file.
+ std::fs::write(&staged_path, "blocking file").unwrap();
+
+ // Verify worktree exists before removal
+ assert!(
+ worktree_path.exists(),
+ "Worktree should exist before removal"
+ );
+
+ // Remove in background mode - should fall back to legacy removal
+ let output = repo
+ .wt_command()
+ .args(["remove", "feature-fallback"])
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "wt remove should succeed even when instant rename fails: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Poll for legacy background removal (includes 1-second sleep before git worktree remove)
+ crate::common::wait_for("worktree removed by legacy fallback", || {
+ !worktree_path.exists()
+ });
+
+ // Poll for branch deletion (happens after worktree removal in background command)
+ crate::common::wait_for("branch deleted by legacy fallback", || {
+ let branches = repo
+ .git_command()
+ .args(["branch", "--list", "feature-fallback"])
+ .output()
+ .unwrap();
+ String::from_utf8_lossy(&branches.stdout).trim().is_empty()
+ });
+
+ // Clean up the blocking file
+ let _ = std::fs::remove_file(&staged_path);
+}
+
+/// Stale `.wt-removing-*` directories from crashed removals accumulate on disk.
+///
+/// If `wt remove` is killed after `fs::rename()` succeeds but before the background
+/// `rm -rf` spawns, the staging directory is left behind. When the same worktree is
+/// re-created and removed again, the staging path collides (non-empty directory),
+/// forcing a fallback to legacy removal. The stale directory is never cleaned up.
+#[rstest]
+fn test_remove_stale_staging_dir_from_crashed_removal(mut repo: TestRepo) {
+ let worktree_path = repo.add_worktree("feature-crash");
+
+ // Calculate the deterministic staging path (TEST_EPOCH is fixed in tests)
+ let staged_path = worktree_path.with_file_name(format!(
+ "{}.wt-removing-{}",
+ worktree_path.file_name().unwrap().to_string_lossy(),
+ crate::common::TEST_EPOCH
+ ));
+
+ // Simulate a crashed removal: rename the worktree to the staging path manually,
+ // then prune git metadata — but never run the background rm -rf.
+ std::fs::rename(&worktree_path, &staged_path).unwrap();
+ repo.run_git(&["worktree", "prune"]);
+
+ // Verify the crash state: original path gone, stale staging dir remains
+ assert!(!worktree_path.exists());
+ assert!(staged_path.exists());
+
+ // Re-create the same worktree (branch was deleted by prune, so create fresh)
+ let _ = repo.add_worktree("feature-crash");
+
+ // Remove it again — staging path collides with stale dir, falls back to legacy
+ let output = repo
+ .wt_command()
+ .args(["remove", "feature-crash"])
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "wt remove should succeed despite stale staging dir: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Poll for legacy background removal (includes 1-second sleep before git worktree remove)
+ crate::common::wait_for("re-created worktree removed by fallback", || {
+ !worktree_path.exists()
+ });
+
+ // But the stale staging directory from the first crash is STILL there —
+ // nothing cleans it up. This is the accumulation risk.
+ assert!(
+ staged_path.exists(),
+ "Stale staging directory from crashed removal is never cleaned up"
+ );
+}