Skip to content

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

fix: show remaining entries when foreground removal fails (#1150)

Maximilian Roos9d6f8c523a90
diff --git a/src/git/error.rs b/src/git/error.rs
index 8c5bdea58..3818a6d9e 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -219,6 +219,8 @@ pub enum GitError {
branch: String,
path: PathBuf,
error: String,
+ /// Top-level entries remaining in the directory (for "Directory not empty" diagnostics)
+ remaining_entries: Option<Vec<String>>,
},
CannotRemoveMainWorktree,
WorktreeLocked {
@@ -549,12 +551,40 @@ impl GitError {
branch,
path,
error,
+ remaining_entries,
} => {
let path_display = format_path_for_display(path);
let header = error_message(cformat!(
"Failed to remove worktree for <bold>{branch}</> @ <bold>{path_display}</>"
));
- write!(f, "{}", format_error_block(header, error))
+ write!(f, "{}", format_error_block(header, error))?;
+ if let Some(entries) = remaining_entries {
+ const MAX_SHOWN: usize = 10;
+ let listing = if entries.len() > MAX_SHOWN {
+ let shown = entries[..MAX_SHOWN].join(", ");
+ let remaining = entries.len() - MAX_SHOWN;
+ format!("{shown}, and {remaining} more")
+ } else {
+ entries.join(", ")
+ };
+ write!(
+ f,
+ "\n{}",
+ hint_message(cformat!(
+ "Remaining in directory: <bright-black>{listing}</>"
+ ))
+ )?;
+ }
+ if error.contains("not empty") {
+ write!(
+ f,
+ "\n{}",
+ hint_message(cformat!(
+ "A background process may be writing files; try <bright-black>wt remove</> (without --foreground)"
+ ))
+ )?;
+ }
+ Ok(())
}
GitError::CannotRemoveMainWorktree => {
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index e8a106cd2..528190d2d 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -77,6 +77,27 @@ fn execute_instant_removal_or_fallback(
}
}
+/// List top-level entries remaining in a directory after a failed removal.
+///
+/// Returns None if the directory doesn't exist, can't be read, or is empty.
+/// Entries are sorted, with directories suffixed with `/`.
+fn list_remaining_entries(path: &Path) -> Option<Vec<String>> {
+ let mut entries: Vec<String> = std::fs::read_dir(path)
+ .ok()?
+ .filter_map(|e| {
+ let e = e.ok()?;
+ let name = e.file_name().to_string_lossy().into_owned();
+ if e.file_type().ok()?.is_dir() {
+ Some(format!("{name}/"))
+ } else {
+ Some(name)
+ }
+ })
+ .collect();
+ entries.sort();
+ (!entries.is_empty()).then_some(entries)
+}
+
// ============================================================================
// Switch Output Handlers
// ============================================================================
@@ -1032,6 +1053,7 @@ fn handle_removed_worktree_output(
return Err(GitError::WorktreeRemovalFailed {
branch: path_dir_name(worktree_path).to_string(),
path: worktree_path.to_path_buf(),
+ remaining_entries: list_remaining_entries(worktree_path),
error: err.to_string(),
}
.into());
@@ -1129,6 +1151,7 @@ fn handle_removed_worktree_output(
return Err(GitError::WorktreeRemovalFailed {
branch: branch_name.into(),
path: worktree_path.to_path_buf(),
+ remaining_entries: list_remaining_entries(worktree_path),
error: err.to_string(),
}
.into());
diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rs
index 6ea43182d..552857a9d 100644
--- a/tests/integration_tests/git_error_display.rs
+++ b/tests/integration_tests/git_error_display.rs
@@ -12,11 +12,61 @@ fn display_worktree_removal_failed() {
branch: "feature-x".into(),
path: PathBuf::from("/tmp/repo.feature-x"),
error: "fatal: worktree is dirty\nerror: could not remove worktree".into(),
+ remaining_entries: None,
};
assert_snapshot!("worktree_removal_failed", err.to_string());
}
+#[test]
+fn display_worktree_removal_failed_directory_not_empty() {
+ let err = GitError::WorktreeRemovalFailed {
+ branch: "feature-x".into(),
+ path: PathBuf::from("/tmp/repo.feature-x"),
+ error: "error: failed to delete '/tmp/repo.feature-x': Directory not empty".into(),
+ remaining_entries: Some(vec![
+ ".vite/".into(),
+ "node_modules/".into(),
+ "target/".into(),
+ ]),
+ };
+
+ assert_snapshot!(
+ "worktree_removal_failed_directory_not_empty",
+ err.to_string()
+ );
+}
+
+#[test]
+fn display_worktree_removal_failed_with_remaining_entries() {
+ let err = GitError::WorktreeRemovalFailed {
+ branch: "feature-x".into(),
+ path: PathBuf::from("/tmp/repo.feature-x"),
+ error: "error: failed to remove '/tmp/repo.feature-x/target': Permission denied".into(),
+ remaining_entries: Some(vec!["target/".into()]),
+ };
+
+ assert_snapshot!(
+ "worktree_removal_failed_with_remaining_entries",
+ err.to_string()
+ );
+}
+
+#[test]
+fn display_worktree_removal_failed_many_remaining_entries() {
+ let err = GitError::WorktreeRemovalFailed {
+ branch: "feature-x".into(),
+ path: PathBuf::from("/tmp/repo.feature-x"),
+ error: "error: failed to delete '/tmp/repo.feature-x': Directory not empty".into(),
+ remaining_entries: Some((0..15).map(|i| format!("dir-{i:02}/")).collect()),
+ };
+
+ assert_snapshot!(
+ "worktree_removal_failed_many_remaining_entries",
+ err.to_string()
+ );
+}
+
#[test]
fn display_worktree_creation_failed() {
let err = GitError::WorktreeCreationFailed {
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 85bcd97db..3e9763d2f 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -2099,3 +2099,131 @@ fn test_remove_stale_staging_dir_from_crashed_removal(mut repo: TestRepo) {
"Stale staging directory from crashed removal is never cleaned up"
);
}
+
+/// Tests that foreground removal shows remaining directory entries when
+/// `git worktree remove` fails because a directory can't be deleted.
+///
+/// Uses Unix permissions (non-writable directory) to prevent deletion of
+/// a gitignored directory, triggering the `WorktreeRemovalFailed` error path
+/// that lists remaining entries.
+#[rstest]
+#[cfg(unix)]
+fn test_remove_foreground_failure_shows_remaining_entries(mut repo: TestRepo) {
+ use std::fs::{self, Permissions};
+ use std::os::unix::fs::PermissionsExt;
+
+ let worktree_path = repo.add_worktree("feature-stuck");
+
+ // Add .gitignore so the stuck directory passes the clean check
+ fs::write(worktree_path.join(".gitignore"), "stuck/\n").unwrap();
+ repo.run_git_in(&worktree_path, &["add", ".gitignore"]);
+ repo.run_git_in(&worktree_path, &["commit", "-m", "Add gitignore"]);
+
+ // Create gitignored directory with a file inside
+ let stuck_dir = worktree_path.join("stuck");
+ fs::create_dir_all(&stuck_dir).unwrap();
+ fs::write(stuck_dir.join("file.txt"), "content").unwrap();
+
+ // Make directory non-writable so git can't unlink the file inside
+ fs::set_permissions(&stuck_dir, Permissions::from_mode(0o555)).unwrap();
+
+ // Check if permissions actually restrict us (skip if running as root)
+ let test_file = stuck_dir.join("test_write");
+ if fs::write(&test_file, "test").is_ok() {
+ let _ = fs::remove_file(&test_file);
+ fs::set_permissions(&stuck_dir, Permissions::from_mode(0o755)).unwrap();
+ eprintln!("Skipping - running with elevated privileges");
+ return;
+ }
+
+ let output = repo
+ .wt_command()
+ .args(["remove", "--foreground", "feature-stuck"])
+ .output()
+ .unwrap();
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ // Restore permissions before assertions so TempDir cleanup works
+ restore_dir_permissions(&stuck_dir);
+
+ assert!(
+ !output.status.success(),
+ "Remove should have failed, got: {stderr}"
+ );
+ assert!(
+ stderr.contains("Remaining in directory:"),
+ "Error should show remaining entries, got: {stderr}"
+ );
+ assert!(
+ stderr.contains("stuck/"),
+ "Error should list the stuck directory, got: {stderr}"
+ );
+}
+
+/// Same as above but for the detached HEAD code path.
+#[rstest]
+#[cfg(unix)]
+fn test_remove_foreground_failure_shows_remaining_entries_detached(mut repo: TestRepo) {
+ use std::fs::{self, Permissions};
+ use std::os::unix::fs::PermissionsExt;
+
+ let worktree_path = repo.add_worktree("feature-stuck-detached");
+
+ // Commit .gitignore, then detach HEAD
+ fs::write(worktree_path.join(".gitignore"), "stuck/\n").unwrap();
+ repo.run_git_in(&worktree_path, &["add", ".gitignore"]);
+ repo.run_git_in(&worktree_path, &["commit", "-m", "Add gitignore"]);
+ repo.detach_head_in_worktree("feature-stuck-detached");
+
+ // Create gitignored directory with a file inside
+ let stuck_dir = worktree_path.join("stuck");
+ fs::create_dir_all(&stuck_dir).unwrap();
+ fs::write(stuck_dir.join("file.txt"), "content").unwrap();
+ fs::set_permissions(&stuck_dir, Permissions::from_mode(0o555)).unwrap();
+
+ // Skip if running as root
+ let test_file = stuck_dir.join("test_write");
+ if fs::write(&test_file, "test").is_ok() {
+ let _ = fs::remove_file(&test_file);
+ fs::set_permissions(&stuck_dir, Permissions::from_mode(0o755)).unwrap();
+ eprintln!("Skipping - running with elevated privileges");
+ return;
+ }
+
+ let output = repo
+ .wt_command()
+ .args(["remove", "--foreground"])
+ .current_dir(&worktree_path)
+ .output()
+ .unwrap();
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ restore_dir_permissions(&stuck_dir);
+
+ assert!(
+ !output.status.success(),
+ "Remove should have failed, got: {stderr}"
+ );
+ assert!(
+ stderr.contains("Remaining in directory:"),
+ "Error should show remaining entries, got: {stderr}"
+ );
+}
+
+/// Restore write permissions recursively so TempDir cleanup succeeds.
+#[cfg(unix)]
+fn restore_dir_permissions(dir: &std::path::Path) {
+ use std::fs::{self, Permissions};
+ use std::os::unix::fs::PermissionsExt;
+
+ let _ = fs::set_permissions(dir, Permissions::from_mode(0o755));
+ if let Ok(entries) = fs::read_dir(dir) {
+ for entry in entries.flatten() {
+ if entry.file_type().is_ok_and(|t| t.is_dir()) {
+ restore_dir_permissions(&entry.path());
+ }
+ }
+ }
+}
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_removal_failed_directory_not_empty.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_removal_failed_directory_not_empty.snap
new file mode 100644
index 000000000..a835819a7
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_removal_failed_directory_not_empty.snap
@@ -0,0 +1,8 @@
+---
+source: tests/integration_tests/git_error_display.rs
+expression: err.to_string()
+---
+✗ Failed to remove worktree for feature-x @ /tmp/repo.feature-x
+  error: failed to delete '/tmp/repo.feature-x': Directory not empty
+↳ Remaining in directory: .vite/, node_modules/, target/
+↳ A background process may be writing files; try wt remove (without --foreground)
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_removal_failed_many_remaining_entries.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_removal_failed_many_remaining_entries.snap
new file mode 100644
index 000000000..be94c466d
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_removal_failed_many_remaining_entries.snap
@@ -0,0 +1,8 @@
+---
+source: tests/integration_tests/git_error_display.rs
+expression: err.to_string()
+---
+✗ Failed to remove worktree for feature-x @ /tmp/repo.feature-x
+  error: failed to delete '/tmp/repo.feature-x': Directory not empty
+↳ Remaining in directory: dir-00/, dir-01/, dir-02/, dir-03/, dir-04/, dir-05/, dir-06/, dir-07/, dir-08/, dir-09/, and 5 more
+↳ A background process may be writing files; try wt remove (without --foreground)
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_removal_failed_with_remaining_entries.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_removal_failed_with_remaining_entries.snap
new file mode 100644
index 000000000..37d420abf
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_removal_failed_with_remaining_entries.snap
@@ -0,0 +1,7 @@
+---
+source: tests/integration_tests/git_error_display.rs
+expression: err.to_string()
+---
+✗ Failed to remove worktree for feature-x @ /tmp/repo.feature-x
+  error: failed to remove '/tmp/repo.feature-x/target': Permission denied
+↳ Remaining in directory: target/