Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: handle prunable worktrees gracefully (#435)
Maximilian Roos58461216018c
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex a28f484f7..9309c11dd 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -46,7 +46,12 @@ use crate::output;/// All template variables from hooks are available, and context JSON is piped to stdin.pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {let repo = Repository::current();- let worktrees = repo.list_worktrees()?;+ // Filter out prunable worktrees (directory deleted) - can't run commands there+ let worktrees: Vec<_> = repo+ .list_worktrees()?+ .into_iter()+ .filter(|wt| !wt.is_prunable())+ .collect();let config = WorktrunkConfig::load()?;let mut failed: Vec<String> = Vec::new();diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex 150842fbc..723ba0cae 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -928,7 +928,10 @@ pub fn collect(let main_repo = Repository::at(&main_worktree.path);if main_repo.is_builtin_fsmonitor_enabled() {for wt in &sorted_worktrees {- Repository::at(&wt.path).start_fsmonitor_daemon();+ // Skip prunable worktrees (directory missing)+ if !wt.is_prunable() {+ Repository::at(&wt.path).start_fsmonitor_daemon();+ }}}}@@ -1094,6 +1097,19 @@ pub fn collect(crate::output::print(warning_message(diag))?;}+ // Compute status symbols for prunable worktrees (skipped during task spawning).+ // They didn't receive any task results, so status_symbols is still None.+ for item in &mut all_items {+ if item.status_symbols.is_none()+ && let Some(data) = item.worktree_data()+ && data.is_prunable()+ {+ // Use default context - no tasks ran, so no conflict/status info+ let ctx = StatusContext::default();+ ctx.apply_to(item, integration_target.as_str());+ }+ }+// Finalize progressive table or render buffered outputif let Some(mut table) = progressive_table {// Build final summary stringdiff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rsindex 08bcf1d49..c5b71fbb2 100644--- a/src/commands/list/collect_progressive_impl.rs+++ b/src/commands/list/collect_progressive_impl.rs@@ -723,6 +723,12 @@ pub fn collect_worktree_progressive(tx: Sender<Result<TaskResult, TaskError>>,expected_results: &Arc<ExpectedResults>,) {+ // Skip git operations for prunable worktrees (directory missing).+ // Git operations would fail anyway since the directory doesn't exist.+ if wt.is_prunable() {+ return;+ }+// Expand URL template for this item (deferred from pre-skeleton)let item_url = options.url_template.as_ref().and_then(|template| {wt.branch.as_ref().and_then(|branch| {diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rsindex 67e6e8880..cf63d8e45 100644--- a/src/commands/list/json_output.rs+++ b/src/commands/list/json_output.rs@@ -394,7 +394,7 @@ fn worktree_state_to_json(// Fallback: check direct fields when status_symbols is None// This can happen early in progressive rendering before status is computed- if data.prunable.is_some() {+ if data.is_prunable() {return (Some("prunable"), data.prunable.clone());}if data.locked.is_some() {diff --git a/src/commands/list/model.rs b/src/commands/list/model.rsindex d9fc2d936..a754c61ec 100644--- a/src/commands/list/model.rs+++ b/src/commands/list/model.rs@@ -221,6 +221,11 @@ pub struct WorktreeData {}impl WorktreeData {+ /// Returns true if this worktree is prunable (directory deleted but git still tracks metadata).+ pub fn is_prunable(&self) -> bool {+ self.prunable.is_some()+ }+/// Create WorktreeData from a Worktree, with all computed fields set to None.pub(crate) fn from_worktree(wt: &worktrunk::git::Worktree,@@ -643,7 +648,7 @@ impl ListItem {// Worktree location state - priority: branch_worktree_mismatch > prunable > lockedlet worktree_state = if data.branch_worktree_mismatch {WorktreeState::BranchWorktreeMismatch- } else if data.prunable.is_some() {+ } else if data.is_prunable() {WorktreeState::Prunable} else if data.locked.is_some() {WorktreeState::Lockeddiff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex e4c57e4db..e5ffcae5e 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -219,6 +219,11 @@ impl RepositoryCliExt for Repository {return Ok(None);};+ // Skip if target worktree directory is missing (prunable worktree)+ if !wt_path.exists() {+ return Ok(None);+ }+let wt_repo = Repository::at(wt_path);if !wt_repo.is_dirty()? {return Ok(None);diff --git a/src/git/mod.rs b/src/git/mod.rsindex 8c1de914a..0cf85bc6a 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -318,6 +318,14 @@ pub fn path_dir_name(path: &std::path::Path) -> &str {}impl Worktree {+ /// Returns true if this worktree is prunable (directory deleted but git still tracks metadata).+ ///+ /// Prunable worktrees cannot be operated on - the directory doesn't exist.+ /// Most iteration over worktrees should skip prunable ones.+ pub fn is_prunable(&self) -> bool {+ self.prunable.is_some()+ }+/// Returns the worktree directory name.////// This is the filesystem directory name (e.g., "repo.feature" from "/path/to/repo.feature").@@ -328,22 +336,29 @@ impl Worktree {}/// Find the "home" worktree - the default branch's worktree if it exists,- /// otherwise the first worktree in the list.+ /// otherwise the first non-prunable worktree in the list.////// This is the preferred destination when we need to cd somewhere/// (e.g., after removing the current worktree, or after merge removes the worktree).///+ /// Prunable worktrees (directory deleted but git still tracks metadata) are+ /// excluded since we can't cd to a directory that doesn't exist.+ ////// For normal repos, `worktrees[0]` is usually the default branch's worktree,/// so the fallback rarely matters. For bare repos, there's no semantic "main"/// worktree, so preferring the default branch's worktree provides consistency.///- /// Returns `None` only if `worktrees` is empty. If `default_branch` is empty- /// or doesn't match any worktree, returns the first worktree.+ /// Returns `None` if all worktrees are prunable or `worktrees` is empty.+ /// If `default_branch` doesn't match any non-prunable worktree, returns the+ /// first non-prunable worktree.pub fn find_home<'a>(worktrees: &'a [Worktree], default_branch: &str) -> Option<&'a Worktree> {+ // Filter out prunable worktrees (directory deleted but git still tracks metadata).+ // Can't cd to a worktree that doesn't exist.worktrees.iter()+ .filter(|wt| !wt.is_prunable()).find(|wt| wt.branch.as_deref() == Some(default_branch))- .or_else(|| worktrees.first())+ .or_else(|| worktrees.iter().find(|wt| !wt.is_prunable()))}}diff --git a/tests/integration_tests/for_each.rs b/tests/integration_tests/for_each.rsindex 4570089af..c09963b5b 100644--- a/tests/integration_tests/for_each.rs+++ b/tests/integration_tests/for_each.rs@@ -91,3 +91,31 @@ fn test_for_each_spawn_fails(mut repo: TestRepo) {None,));}++/// Test that prunable worktrees (directory deleted) are skipped without errors.+#[rstest]+fn test_for_each_skips_prunable_worktrees(mut repo: TestRepo) {+ let worktree_path = repo.add_worktree("feature");+ // Delete the worktree directory to make it prunable+ std::fs::remove_dir_all(&worktree_path).unwrap();++ // Verify git sees it as prunable+ let output = repo+ .git_command()+ .args(["worktree", "list", "--porcelain"])+ .output()+ .unwrap();+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ stdout.contains("prunable"),+ "Expected worktree to be prunable after deleting directory"+ );++ // wt step for-each should skip the prunable worktree and complete without errors+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "step",+ &["for-each", "--", "echo", "Running in {{ branch }}"],+ None,+ ));+}diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex f1dcfc058..dd72003e9 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -2324,3 +2324,31 @@ fn test_list_handles_orphan_branch(repo: TestRepo) {cmd});}++/// Test that prunable worktrees (directory deleted) don't generate error spam.+///+/// When a worktree directory is deleted but git still knows about it, the worktree+/// is marked as "prunable". We should skip git operations for these worktrees+/// rather than showing confusing "Failed to execute" errors.+#[rstest]+fn test_list_skips_operations_for_prunable_worktrees(mut repo: TestRepo) {+ let worktree_path = repo.add_worktree("feature");++ // Delete the worktree directory (making it prunable)+ std::fs::remove_dir_all(&worktree_path).unwrap();++ // Verify git sees it as prunable+ let output = repo+ .git_command()+ .args(["worktree", "list", "--porcelain"])+ .output()+ .unwrap();+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ stdout.contains("prunable"),+ "Expected worktree to be prunable after deleting directory"+ );++ // wt list should show the prunable worktree with ⊟ symbol but NO error warnings+ assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));+}diff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_skips_prunable_worktrees.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_skips_prunable_worktrees.snapnew file mode 100644index 000000000..182af096f--- /dev/null+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_skips_prunable_worktrees.snap@@ -0,0 +1,42 @@+---+source: tests/integration_tests/for_each.rs+assertion_line: 115+info:+ program: wt+ args:+ - step+ - for-each+ - "--"+ - echo+ - "Running in {{ branch }}"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[36m◎[39m [36mRunning in [1mmain[22m...[39m+Running in main++[32m✓[39m [32mCompleted in 1 worktree[39mdiff --git a/tests/snapshots/integration__integration_tests__list__list_skips_operations_for_prunable_worktrees.snap b/tests/snapshots/integration__integration_tests__list__list_skips_operations_for_prunable_worktrees.snapnew file mode 100644index 000000000..835d95dd3--- /dev/null+++ b/tests/snapshots/integration__integration_tests__list__list_skips_operations_for_prunable_worktrees.snap@@ -0,0 +1,38 @@+---+source: tests/integration_tests/list.rs+info:+ program: wt+ args:+ - list+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+ [1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage+@ main [2m^[22m . [2ma1e809f5[0m [2m1d[0m [2mInitial commit++ feature [33m⊟[39m ../repo.feature [2ma1e809f5[0m [2m⋯[0m [2m⋯++[2m○[22m [2mShowing 2 worktrees++----- stderr -----