Skip to content

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

feat: prune worktree metadata when directory is missing during remove (#766)

Maximilian Roos55a33a6311ba
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index c4205347a..9cf4fd9ca 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -91,10 +91,13 @@ impl RepositoryCliExt for Repository {
{
Some(wt) => {
if !wt.path.exists() {
- return Err(GitError::WorktreeMissing {
- branch: branch.into(),
- }
- .into());
+ // Directory missing - prune and continue
+ self.prune_worktrees()?;
+ return Ok(RemoveResult::BranchOnly {
+ branch_name: branch.to_string(),
+ deletion_mode,
+ pruned: true,
+ });
}
if wt.locked.is_some() {
return Err(GitError::WorktreeLocked {
@@ -114,6 +117,7 @@ impl RepositoryCliExt for Repository {
return Ok(RemoveResult::BranchOnly {
branch_name: branch.to_string(),
deletion_mode,
+ pruned: false,
});
}
// Check if branch exists on a remote
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index 097cd4752..e0919e57f 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -197,10 +197,15 @@ pub enum RemoveResult {
/// from expected (path mismatch), `None` when path matches template.
expected_path: Option<PathBuf>,
},
- /// Branch exists but has no worktree - attempt branch deletion only
+ /// Branch exists but has no worktree - attempt branch deletion only.
+ ///
+ /// `pruned` indicates whether the worktree was pruned (directory was missing).
+ /// When true, shows an info message instead of a warning.
BranchOnly {
branch_name: String,
deletion_mode: BranchDeletionMode,
+ /// True if the worktree was pruned before returning this result.
+ pruned: bool,
},
}
@@ -357,15 +362,39 @@ mod tests {
let result = RemoveResult::BranchOnly {
branch_name: "stale-branch".to_string(),
deletion_mode: BranchDeletionMode::Keep,
+ pruned: false,
};
match result {
RemoveResult::BranchOnly {
branch_name,
deletion_mode,
+ pruned,
} => {
assert_eq!(branch_name, "stale-branch");
assert!(deletion_mode.should_keep());
assert!(!deletion_mode.is_force());
+ assert!(!pruned);
+ }
+ _ => panic!("Expected BranchOnly variant"),
+ }
+ }
+
+ #[test]
+ fn test_remove_result_branch_only_pruned() {
+ let result = RemoveResult::BranchOnly {
+ branch_name: "pruned-branch".to_string(),
+ deletion_mode: BranchDeletionMode::SafeDelete,
+ pruned: true,
+ };
+ match result {
+ RemoveResult::BranchOnly {
+ branch_name,
+ deletion_mode,
+ pruned,
+ } => {
+ assert_eq!(branch_name, "pruned-branch");
+ assert!(!deletion_mode.should_keep());
+ assert!(pruned);
}
_ => panic!("Expected BranchOnly variant"),
}
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index a10e461a9..d99111edf 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -92,6 +92,16 @@ impl Repository {
.map(|wt| (wt.path.clone(), wt.branch.clone())))
}
+ /// Prune worktree entries whose directories no longer exist.
+ ///
+ /// Git tracks worktrees in `.git/worktrees/`. If a worktree directory is deleted
+ /// externally (e.g., `rm -rf`), this method runs `git worktree prune` to clean
+ /// up the entries.
+ pub fn prune_worktrees(&self) -> anyhow::Result<()> {
+ self.run_command(&["worktree", "prune"])?;
+ Ok(())
+ }
+
/// Remove a worktree at the specified path.
///
/// When `force` is true, passes `--force` to `git worktree remove`,
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 6cd1e13d2..f9b3feae5 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -492,7 +492,8 @@ pub fn handle_remove_output(
RemoveResult::BranchOnly {
branch_name,
deletion_mode,
- } => handle_branch_only_output(branch_name, *deletion_mode),
+ pruned,
+ } => handle_branch_only_output(branch_name, *deletion_mode, *pruned),
}
}
@@ -500,11 +501,20 @@ pub fn handle_remove_output(
fn handle_branch_only_output(
branch_name: &str,
deletion_mode: BranchDeletionMode,
+ pruned: bool,
) -> anyhow::Result<()> {
- // Warn that no worktree was found (user asked to remove it)
- super::print(warning_message(cformat!(
- "No worktree found for branch <bold>{branch_name}</>"
- )))?;
+ // Different message depending on whether we pruned a stale worktree
+ if pruned {
+ // Worktree was pruned - informational, not a warning
+ super::print(info_message(cformat!(
+ "Worktree directory missing for <bold>{branch_name}</>; pruned"
+ )))?;
+ } else {
+ // No worktree at all - warn since user asked to remove something that doesn't exist
+ super::print(warning_message(cformat!(
+ "No worktree found for branch <bold>{branch_name}</>"
+ )))?;
+ }
// Attempt branch deletion (unless --no-delete-branch was specified)
if deletion_mode.should_keep() {
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index e2f5e15ad..3814f54f1 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1639,3 +1639,106 @@ fn test_remove_at_symbol_via_symlink(mut repo: TestRepo) {
Some(&symlink_path)
));
}
+
+// ============================================================================
+// Pruned Worktree Tests
+// ============================================================================
+
+/// When a worktree's directory is deleted externally (e.g., `rm -rf`), the git
+/// metadata becomes stale. `wt remove` should prune this stale metadata and
+/// proceed with branch deletion, rather than erroring.
+///
+/// This makes `wt remove` more idempotent - it puts the repository into the
+/// correct end state regardless of whether the directory exists.
+#[rstest]
+fn test_remove_pruned_worktree_directory_missing(mut repo: TestRepo) {
+ // Create a worktree
+ let worktree_path = repo.add_worktree("feature-pruned");
+
+ // Verify the worktree exists
+ assert!(worktree_path.exists(), "Worktree should exist initially");
+
+ // Externally delete the worktree directory (simulating user running `rm -rf`)
+ std::fs::remove_dir_all(&worktree_path).expect("Failed to remove worktree directory");
+ assert!(
+ !worktree_path.exists(),
+ "Worktree directory should be deleted"
+ );
+
+ // Verify git still thinks the worktree exists (stale metadata)
+ let list_output = repo
+ .git_command()
+ .args(["worktree", "list", "--porcelain"])
+ .output()
+ .unwrap();
+ let list_str = String::from_utf8_lossy(&list_output.stdout);
+ assert!(
+ list_str.contains("feature-pruned"),
+ "Git should still list the stale worktree"
+ );
+
+ // `wt remove feature-pruned` should prune the stale metadata and delete the branch
+ // The info message should say "Worktree directory missing for feature-pruned; pruned stale metadata"
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "remove",
+ &["feature-pruned"],
+ None
+ ));
+
+ // Verify the stale worktree metadata is cleaned up
+ let list_after = repo
+ .git_command()
+ .args(["worktree", "list", "--porcelain"])
+ .output()
+ .unwrap();
+ let list_after_str = String::from_utf8_lossy(&list_after.stdout);
+ assert!(
+ !list_after_str.contains("feature-pruned"),
+ "Stale worktree should be pruned"
+ );
+
+ // Verify the branch is deleted
+ let branch_exists = repo
+ .git_command()
+ .args(["branch", "--list", "feature-pruned"])
+ .output()
+ .unwrap();
+ assert!(
+ String::from_utf8_lossy(&branch_exists.stdout)
+ .trim()
+ .is_empty(),
+ "Branch should be deleted"
+ );
+}
+
+/// Test pruning with --no-delete-branch: should prune metadata but keep the branch
+#[rstest]
+fn test_remove_pruned_worktree_keep_branch(mut repo: TestRepo) {
+ // Create a worktree
+ let worktree_path = repo.add_worktree("feature-pruned-keep");
+
+ // Delete the worktree directory externally
+ std::fs::remove_dir_all(&worktree_path).expect("Failed to remove worktree directory");
+
+ // Remove with --no-delete-branch
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "remove",
+ &["--no-delete-branch", "feature-pruned-keep"],
+ None
+ ));
+
+ // Verify the branch still exists
+ let branch_exists = repo
+ .git_command()
+ .args(["branch", "--list", "feature-pruned-keep"])
+ .output()
+ .unwrap();
+ assert!(
+ !String::from_utf8_lossy(&branch_exists.stdout)
+ .trim()
+ .is_empty(),
+ "Branch should still exist"
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_pruned_worktree_directory_missing.snap b/tests/snapshots/integration__integration_tests__remove__remove_pruned_worktree_directory_missing.snap
new file mode 100644
index 000000000..46e6482c7
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_pruned_worktree_directory_missing.snap
@@ -0,0 +1,39 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - feature-pruned
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+○ Worktree directory missing for feature-pruned; pruned
+✓ Removed branch feature-pruned (same commit as main, _)
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_pruned_worktree_keep_branch.snap b/tests/snapshots/integration__integration_tests__remove__remove_pruned_worktree_keep_branch.snap
new file mode 100644
index 000000000..d6441c694
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_pruned_worktree_keep_branch.snap
@@ -0,0 +1,39 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "--no-delete-branch"
+ - feature-pruned-keep
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+○ Worktree directory missing for feature-pruned-keep; pruned