Skip to content

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

fix(prune): unregister stale worktrees whose directory remains (#4228)

Maximilian Roos3de0b5f29a55
diff --git a/docs/src/content/docs/faq.md b/docs/src/content/docs/faq.md
index 023dd1c26..6c06d591a 100644
--- a/docs/src/content/docs/faq.md
+++ b/docs/src/content/docs/faq.md
@@ -212,6 +212,7 @@ A branch checked out in a second worktree is retained regardless, `-D` included.
### Other cleanup
- `wt merge` / `wt step push` — the target branch's checked-out worktree is updated to the merged commits, so a file those commits delete disappears from it, and an ignored file at a path they track is overwritten — the same result a `git merge` run in that worktree would produce. Uncommitted changes at paths the merge doesn't touch stay in place, staged or not; one at a path it does touch refuses the merge upfront, naming the file
+- `wt remove` / `wt step prune` — unregister a stale worktree (`⊟` in `wt list`) by deleting its `.git/worktrees/<id>` entry, as `git worktree prune` does, but for that worktree only. Files still in its directory stay. An entry whose index holds staged changes, or with a rebase, merge, or other operation in progress, is kept unless `wt remove --force` names it, since `git worktree repair` can restore it only while the entry exists
- `wt remove` — also stops the removed worktree's `git fsmonitor--daemon` (under `core.fsmonitor=true`), and sweeps `.git/wt/trash/` entries older than 24 hours along with fsmonitor daemons whose worktree no longer exists
- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)
- `wt config shell install` — replaces an existing fish or Nushell wrapper file whole, and removes one an older version installed at a previous location (fish `conf.d/wt.fish`, Nushell `<config-dir>/vendor/autoload/wt.nu`), printing each removal; [Files created](/shell-integration/#files-created) names the file each shell gets
diff --git a/docs/src/content/docs/list.md b/docs/src/content/docs/list.md
index e21331b25..4c12707df 100644
--- a/docs/src/content/docs/list.md
+++ b/docs/src/content/docs/list.md
@@ -172,7 +172,7 @@ An in-progress git operation, a worktree-location attribute, or a branch with no
|--------|------|---------|
| `✘` | `worktree.changes.conflicted` | Merge conflicts |
| `↻` | `worktree.operation` `"rebase"`, `"merge"`, `"cherry_pick"`, `"revert"`, `"bisect"` | A git operation is in progress; `git status` names it |
-| `⊟` | `worktree.prunable` | Prunable (worktree directory missing) |
+| `⊟` | `worktree.prunable` | Prunable (worktree directory or its `.git` gone) |
| `⊞` | `worktree.locked` | Locked worktree |
| `⊘` | `worktree.detached` | Detached HEAD |
| `⚑` | `worktree.duplicate_branch` | Branch checked out in more than one worktree |
diff --git a/docs/src/content/docs/step.md b/docs/src/content/docs/step.md
index 5e6a820a3..303b86cf4 100644
--- a/docs/src/content/docs/step.md
+++ b/docs/src/content/docs/step.md
@@ -813,7 +813,7 @@ Automation:
Remove worktrees and branches merged into the default branch.
-Bulk-removes worktrees and branches that are integrated into the default branch, using the same criteria as `wt remove`'s branch cleanup. Stale worktree entries are cleaned up too.
+Bulk-removes worktrees and branches that are integrated into the default branch, using the same criteria as `wt remove`'s branch cleanup. Stale worktree entries are cleaned up too, except one whose git metadata holds staged changes or an operation in progress; `git worktree repair` can still restore those.
In `wt list`, candidates show `_` (same commit) or `⊂` (content integrated). Run `--dry-run` to preview. See `wt remove --help` for the full integration criteria.
diff --git a/plugins/worktrunk/skills/worktrunk/reference/faq.md b/plugins/worktrunk/skills/worktrunk/reference/faq.md
index e3e8e4d4a..d365bf051 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/faq.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/faq.md
@@ -208,6 +208,7 @@ A branch checked out in a second worktree is retained regardless, `-D` included.
### Other cleanup
- `wt merge` / `wt step push` — the target branch's checked-out worktree is updated to the merged commits, so a file those commits delete disappears from it, and an ignored file at a path they track is overwritten — the same result a `git merge` run in that worktree would produce. Uncommitted changes at paths the merge doesn't touch stay in place, staged or not; one at a path it does touch refuses the merge upfront, naming the file
+- `wt remove` / `wt step prune` — unregister a stale worktree (`⊟` in `wt list`) by deleting its `.git/worktrees/<id>` entry, as `git worktree prune` does, but for that worktree only. Files still in its directory stay. An entry whose index holds staged changes, or with a rebase, merge, or other operation in progress, is kept unless `wt remove --force` names it, since `git worktree repair` can restore it only while the entry exists
- `wt remove` — also stops the removed worktree's `git fsmonitor--daemon` (under `core.fsmonitor=true`), and sweeps `.git/wt/trash/` entries older than 24 hours along with fsmonitor daemons whose worktree no longer exists
- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)
- `wt config shell install` — replaces an existing fish or Nushell wrapper file whole, and removes one an older version installed at a previous location (fish `conf.d/wt.fish`, Nushell `<config-dir>/vendor/autoload/wt.nu`), printing each removal; [Files created](https://worktrunk.dev/shell-integration/#files-created) names the file each shell gets
diff --git a/plugins/worktrunk/skills/worktrunk/reference/list.md b/plugins/worktrunk/skills/worktrunk/reference/list.md
index 35d585fd8..f5a8a2f85 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/list.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/list.md
@@ -156,7 +156,7 @@ An in-progress git operation, a worktree-location attribute, or a branch with no
|--------|------|---------|
| `✘` | `worktree.changes.conflicted` | Merge conflicts |
| `↻` | `worktree.operation` `"rebase"`, `"merge"`, `"cherry_pick"`, `"revert"`, `"bisect"` | A git operation is in progress; `git status` names it |
-| `⊟` | `worktree.prunable` | Prunable (worktree directory missing) |
+| `⊟` | `worktree.prunable` | Prunable (worktree directory or its `.git` gone) |
| `⊞` | `worktree.locked` | Locked worktree |
| `⊘` | `worktree.detached` | Detached HEAD |
| `⚑` | `worktree.duplicate_branch` | Branch checked out in more than one worktree |
diff --git a/plugins/worktrunk/skills/worktrunk/reference/step.md b/plugins/worktrunk/skills/worktrunk/reference/step.md
index 5571ae05d..99c397072 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/step.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/step.md
@@ -801,7 +801,7 @@ Automation:
Remove worktrees and branches merged into the default branch.
-Bulk-removes worktrees and branches that are integrated into the default branch, using the same criteria as `wt remove`'s branch cleanup. Stale worktree entries are cleaned up too.
+Bulk-removes worktrees and branches that are integrated into the default branch, using the same criteria as `wt remove`'s branch cleanup. Stale worktree entries are cleaned up too, except one whose git metadata holds staged changes or an operation in progress; `git worktree repair` can still restore those.
In `wt list`, candidates show `_` (same commit) or `⊂` (content integrated). Run `--dry-run` to preview. See `wt remove --help` for the full integration criteria.
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index e3e8e4d4a..d365bf051 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -208,6 +208,7 @@ A branch checked out in a second worktree is retained regardless, `-D` included.
### Other cleanup
- `wt merge` / `wt step push` — the target branch's checked-out worktree is updated to the merged commits, so a file those commits delete disappears from it, and an ignored file at a path they track is overwritten — the same result a `git merge` run in that worktree would produce. Uncommitted changes at paths the merge doesn't touch stay in place, staged or not; one at a path it does touch refuses the merge upfront, naming the file
+- `wt remove` / `wt step prune` — unregister a stale worktree (`⊟` in `wt list`) by deleting its `.git/worktrees/<id>` entry, as `git worktree prune` does, but for that worktree only. Files still in its directory stay. An entry whose index holds staged changes, or with a rebase, merge, or other operation in progress, is kept unless `wt remove --force` names it, since `git worktree repair` can restore it only while the entry exists
- `wt remove` — also stops the removed worktree's `git fsmonitor--daemon` (under `core.fsmonitor=true`), and sweeps `.git/wt/trash/` entries older than 24 hours along with fsmonitor daemons whose worktree no longer exists
- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)
- `wt config shell install` — replaces an existing fish or Nushell wrapper file whole, and removes one an older version installed at a previous location (fish `conf.d/wt.fish`, Nushell `<config-dir>/vendor/autoload/wt.nu`), printing each removal; [Files created](https://worktrunk.dev/shell-integration/#files-created) names the file each shell gets
diff --git a/skills/worktrunk/reference/list.md b/skills/worktrunk/reference/list.md
index 35d585fd8..f5a8a2f85 100644
--- a/skills/worktrunk/reference/list.md
+++ b/skills/worktrunk/reference/list.md
@@ -156,7 +156,7 @@ An in-progress git operation, a worktree-location attribute, or a branch with no
|--------|------|---------|
| `✘` | `worktree.changes.conflicted` | Merge conflicts |
| `↻` | `worktree.operation` `"rebase"`, `"merge"`, `"cherry_pick"`, `"revert"`, `"bisect"` | A git operation is in progress; `git status` names it |
-| `⊟` | `worktree.prunable` | Prunable (worktree directory missing) |
+| `⊟` | `worktree.prunable` | Prunable (worktree directory or its `.git` gone) |
| `⊞` | `worktree.locked` | Locked worktree |
| `⊘` | `worktree.detached` | Detached HEAD |
| `⚑` | `worktree.duplicate_branch` | Branch checked out in more than one worktree |
diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.md
index 5571ae05d..99c397072 100644
--- a/skills/worktrunk/reference/step.md
+++ b/skills/worktrunk/reference/step.md
@@ -801,7 +801,7 @@ Automation:
Remove worktrees and branches merged into the default branch.
-Bulk-removes worktrees and branches that are integrated into the default branch, using the same criteria as `wt remove`'s branch cleanup. Stale worktree entries are cleaned up too.
+Bulk-removes worktrees and branches that are integrated into the default branch, using the same criteria as `wt remove`'s branch cleanup. Stale worktree entries are cleaned up too, except one whose git metadata holds staged changes or an operation in progress; `git worktree repair` can still restore those.
In `wt list`, candidates show `_` (same commit) or `⊂` (content integrated). Run `--dry-run` to preview. See `wt remove --help` for the full integration criteria.
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 9900e5546..c2a8c3b95 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -935,7 +935,7 @@ An in-progress git operation, a worktree-location attribute, or a branch with no
|--------|------|---------|
| `✘` | `worktree.changes.conflicted` | Merge conflicts |
| `↻` | `worktree.operation` `"rebase"`, `"merge"`, `"cherry_pick"`, `"revert"`, `"bisect"` | A git operation is in progress; `git status` names it |
-| `⊟` | `worktree.prunable` | Prunable (worktree directory missing) |
+| `⊟` | `worktree.prunable` | Prunable (worktree directory or its `.git` gone) |
| `⊞` | `worktree.locked` | Locked worktree |
| `⊘` | `worktree.detached` | Detached HEAD |
| `⚑` | `worktree.duplicate_branch` | Branch checked out in more than one worktree |
diff --git a/src/cli/step.rs b/src/cli/step.rs
index 85d627476..8a8a39980 100644
--- a/src/cli/step.rs
+++ b/src/cli/step.rs
@@ -615,7 +615,7 @@ Gitignored files (build artifacts, `node_modules/`, `.env`) are swapped along wi
/// Remove worktrees and branches merged into the default branch
#[command(
- after_long_help = r#"Bulk-removes worktrees and branches that are integrated into the default branch, using the same criteria as `wt remove`'s branch cleanup. Stale worktree entries are cleaned up too.
+ after_long_help = r#"Bulk-removes worktrees and branches that are integrated into the default branch, using the same criteria as `wt remove`'s branch cleanup. Stale worktree entries are cleaned up too, except one whose git metadata holds staged changes or an operation in progress; `git worktree repair` can still restore those.
In `wt list`, candidates show `_` (same commit) or `⊂` (content integrated). Run `--dry-run` to preview. See `wt remove --help` for the full integration criteria.
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 30b6b44f9..f5682feb2 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -51,7 +51,7 @@ use crate::output::print_json;
pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> anyhow::Result<()> {
let json_mode = format == crate::cli::SwitchFormat::Json;
let repo = Repository::current()?;
- // Filter out prunable worktrees (directory deleted) - can't run commands there
+ // Filter out prunable worktrees (directory or its `.git` gone) - can't run commands there
let worktrees: Vec<&WorktreeInfo> = repo
.list_worktrees()?
.iter()
diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rs
index e9d27a85a..91be25906 100644
--- a/src/commands/list/collect/execution.rs
+++ b/src/commands/list/collect/execution.rs
@@ -245,7 +245,7 @@ pub(super) fn seed_unborn_main_state(item: &mut ListItem) {
/// Pre-seed every gate on a prunable worktree so the only visible symbol
/// is `⊟` (from the metadata `worktree_state`).
///
-/// Prunable worktrees have their directory missing from disk, so no task
+/// Prunable worktrees have lost their directory or its `.git`, so no task
/// can run for them. Without this seeding, every gate would stay `None`
/// forever and the cell would render as seven `·` placeholders. This
/// helper replaces the runtime fallback in `refresh_status_symbols`
@@ -302,7 +302,8 @@ pub fn work_items_for_worktree(
tx: &chan::Sender<Result<TaskResult, TaskError>>,
item: &mut ListItem,
) -> Vec<WorkItem> {
- // Prunable worktrees have their directory missing — no task can run.
+ // Prunable worktrees have lost their directory or its `.git` — no task
+ // can run.
// Seed every gate directly so the cell shows just the `⊟` metadata
// symbol rather than seven `·` placeholders.
if item.worktree_data().is_some_and(|data| data.is_prunable()) {
diff --git a/src/commands/list/model/item.rs b/src/commands/list/model/item.rs
index 2f17a8b8e..b93e1b705 100644
--- a/src/commands/list/model/item.rs
+++ b/src/commands/list/model/item.rs
@@ -93,7 +93,8 @@ pub struct WorktreeData {
}
impl WorktreeData {
- /// Returns true if this worktree is prunable (directory deleted but git still tracks metadata).
+ /// Returns true if git reports this worktree prunable: its directory or
+ /// that directory's `.git` is gone.
pub fn is_prunable(&self) -> bool {
self.prunable.is_some()
}
@@ -497,8 +498,9 @@ impl ListItem {
/// The glyph this row's unresolved cells render, given the render's
/// current one.
///
- /// A prunable worktree's directory is gone, so `work_items_for_worktree`
- /// spawns nothing for it and no cell a task would fill will ever arrive.
+ /// A prunable worktree has lost its directory or its `.git`, so
+ /// `work_items_for_worktree` spawns nothing for it and no cell a task
+ /// would fill will ever arrive.
/// The loading dot would promise data that isn't coming — for the life of
/// the row, not for a tick — so those cells stay blank and the `⊟` in
/// Status is the row's whole story.
diff --git a/src/commands/list/model/state.rs b/src/commands/list/model/state.rs
index 2582779c0..253c80f6b 100644
--- a/src/commands/list/model/state.rs
+++ b/src/commands/list/model/state.rs
@@ -98,7 +98,7 @@ pub enum WorktreeState {
DuplicateBranch,
/// Detached HEAD: the worktree is on a commit, not a branch
Detached,
- /// Prunable (worktree directory missing)
+ /// Prunable (worktree directory or its `.git` gone)
Prunable,
/// Locked (protected from removal)
Locked,
diff --git a/src/commands/list/model/status_symbols.rs b/src/commands/list/model/status_symbols.rs
index 11c4b5d75..981de17e3 100644
--- a/src/commands/list/model/status_symbols.rs
+++ b/src/commands/list/model/status_symbols.rs
@@ -380,7 +380,7 @@ impl WorkingTreeStatus {
/// Priority: ✘ > ↻ > ⊟ > ⊞ > ⊘ > ⚑ > /
/// - ✘: Actual conflicts (must resolve)
/// - ↻: A git operation is in progress (rebase, merge, cherry-pick, revert, bisect)
-/// - ⊟: Prunable (directory missing)
+/// - ⊟: Prunable (directory or its `.git` gone)
/// - ⊞: Locked worktree
/// - ⊘: Detached HEAD — the worktree is on a commit, not a branch
/// - ⚑: Irregular branch ⇔ worktree mapping — the branch is checked out in
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 070e4557d..362b991b5 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -396,8 +396,20 @@ impl AltXRemover {
RemovalPlan::BranchOnly {
branch_name,
deletion_mode,
+ prune_entry,
..
} => {
+ // The stale entry goes first, as `wt remove` does it: deleting
+ // the branch under a registration that still names it would
+ // leave an entry with an unborn `HEAD`, which `wt step prune`
+ // never collects. A failed prune keeps the branch, so the row
+ // is restored.
+ if let Some(path) = prune_entry
+ && let Err(e) = repo.prune_worktree_entry(path)
+ {
+ tracing::warn!(branch = %branch_name, error = %e, "picker: failed to prune stale worktree for '{branch_name}': {e:#}");
+ return Ok(());
+ }
if !deletion_mode.should_keep() {
let default_branch = repo.default_branch();
let target = default_branch.as_deref().unwrap_or("HEAD");
@@ -2898,6 +2910,63 @@ pub mod tests {
assert!(output.is_empty(), "integrated branch should be deleted");
}
+ /// A stale row's plan carries its registration, which goes along with the
+ /// branch; deleting the branch alone would leave an entry naming a branch
+ /// that no longer exists.
+ #[test]
+ fn test_do_removal_branch_only_prunes_stale_entry() {
+ let mut test = worktrunk::testing::TestRepo::with_initial_commit();
+ let wt_path = test.add_worktree("feature");
+ fs::remove_file(wt_path.join(".git")).unwrap();
+ let repo = worktrunk::git::Repository::at(test.path()).unwrap();
+
+ let result = RemovalPlan::BranchOnly {
+ branch_name: "feature".to_string(),
+ deletion_mode: BranchDeletionMode::SafeDelete,
+ prune_entry: Some(wt_path.clone()),
+ target_branch: None,
+ integration_reason: None,
+ branch_checked_out_at: None,
+ };
+ AltXRemover::do_removal(&repo, &result, &Approvals::default()).unwrap();
+
+ let list = repo
+ .run_command(&["worktree", "list", "--porcelain"])
+ .unwrap();
+ assert!(
+ !list.contains("prunable"),
+ "stale entry should be pruned:\n{list}"
+ );
+ let output = repo.run_command(&["branch", "--list", "feature"]).unwrap();
+ assert!(output.is_empty(), "integrated branch should be deleted");
+ assert!(wt_path.is_dir(), "the directory should stay");
+ }
+
+ /// A prune that fails leaves the branch alone, so the row is restored
+ /// rather than showing a removal that only half happened.
+ #[test]
+ fn test_do_removal_branch_only_keeps_branch_when_prune_fails() {
+ let test = worktrunk::testing::TestRepo::with_initial_commit();
+ let repo = worktrunk::git::Repository::at(test.path()).unwrap();
+ repo.run_command(&["branch", "feature"]).unwrap();
+
+ let result = RemovalPlan::BranchOnly {
+ branch_name: "feature".to_string(),
+ deletion_mode: BranchDeletionMode::SafeDelete,
+ prune_entry: Some(test.path().join("not-registered")),
+ target_branch: None,
+ integration_reason: None,
+ branch_checked_out_at: None,
+ };
+ AltXRemover::do_removal(&repo, &result, &Approvals::default()).unwrap();
+
+ let output = repo.run_command(&["branch", "--list", "feature"]).unwrap();
+ assert!(
+ !output.is_empty(),
+ "the branch should survive a failed prune"
+ );
+ }
+
#[test]
fn test_do_removal_branch_only_retains_unmerged_branch() {
let test = worktrunk::testing::TestRepo::with_initial_commit();
@@ -3318,8 +3387,8 @@ pub mod tests {
/// concurrent background removal can trigger.
///
/// `apply` renames the worktree into the trash (so its path vanishes) and
- /// then runs `git worktree remove` on it, which deletes that worktree's
- /// `.git/worktrees/<id>` admin dir — all on a background thread.
+ /// then unregisters it, deleting that worktree's `.git/worktrees/<id>`
+ /// admin dir — all on a background thread.
/// `git branch --list` enumerates
/// worktrees to mark checked-out branches, so a query that races the
/// in-flight prune can read a half-deleted admin dir and fail with
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rs
index 0643ff721..d7c4ad3aa 100644
--- a/src/commands/relocate.rs
+++ b/src/commands/relocate.rs
@@ -165,12 +165,12 @@ pub fn gather_candidates(
for arg in filter_branches {
let path = repo.require_worktree(arg)?;
let Some(wt) = worktrees.iter().find(|wt| paths_match(&path, &wt.path)) else {
- // Resolved, but pruned out above: its directory is gone, so
- // there is nothing to move.
+ // Resolved, but pruned out above: its directory or `.git` is
+ // gone, so there is nothing to move.
bail!(
"{}",
cformat!(
- "Cannot relocate worktree @ {} — its directory is gone; to clear the entry, run <bold>wt step prune</>",
+ "Cannot relocate worktree @ {} — it is stale; to clear the entry, run <bold>wt step prune</>",
format_path_for_display(&path)
)
);
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index baee7ccff..f05736902 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -215,54 +215,46 @@ impl RepositoryCliExt for Repository {
}
.into());
}
- // Directory missing (e.g. external `rm -rf`): fall back to
- // branch-only deletion, recording the stale entry in the plan
- // so execution unregisters it — planning stays a pure read
- // (`wt step prune`'s scan doubles as `--dry-run`, and `wt
- // remove` plans before its approval prompt). A detached
- // worktree has no branch to fall back to, so an absent
- // directory leaves it to the prunable arm below rather than
- // here.
- //
- // The recorded prune names this worktree rather than sweeping
- // the repo, so a sibling whose directory is merely absent
- // right now keeps its registration. `git worktree remove`
- // refuses a locked worktree where a repo-wide prune ignored
- // one, which needs no guard here: the lock check above already
- // returned for every locked entry in this arm.
- //
- // `exists()` is that cleanup's precondition rather than a
- // proxy for health: `prune_worktree_entry` unregisters with
- // `git worktree remove`, which skips its validation only while
- // the directory is absent.
- if let Some(branch) = wt.branch.as_deref()
- && !wt.path.exists()
- {
+ // Stale entry — git calls it prunable once `<path>/.git` is
+ // gone, whether the whole directory went (an external `rm -rf`)
+ // or was recreated empty (an interrupted `wt switch`). Git
+ // withholds `prunable` from a locked entry, and the lock guard
+ // above has returned for those anyway. Fall back to branch-only
+ // deletion, recording the entry in the plan so execution
+ // unregisters it and leaves any directory in place — planning
+ // stays a pure read (`wt step prune`'s scan doubles as
+ // `--dry-run`, and `wt remove` plans before its approval
+ // prompt). The recorded prune names this worktree rather than
+ // sweeping the repo, so a sibling whose directory is merely
+ // absent right now keeps its registration. An entry whose
+ // registration holds staged changes or an operation partway
+ // through is kept unless `--force` waives it, as it waives a
+ // live worktree's uncommitted changes: unregistering deletes
+ // those, and `git worktree repair` can still bring them back.
+ if wt.is_prunable() {
+ // A detached entry has no branch to fall back to, and no
+ // plan shape of its own, so it is reported rather than
+ // removed. `wt step prune` unregisters one without a plan.
+ let Some(branch) = wt.branch.clone() else {
+ return Err(GitError::worktree_missing(
+ wt.dir_name().to_string(),
+ &wt.path,
+ )
+ .into());
+ };
+ if !force_worktree && let Some(work) = self.stale_worktree_work(&wt.path)? {
+ return Err(GitError::StaleWorktreeHoldsWork {
+ branch,
+ path: wt.path.clone(),
+ directory_remains: wt.path.is_dir(),
+ work,
+ }
+ .into());
+ }
Resolved::BranchOnly {
pruned_from: Some(wt.path.clone()),
- branch: branch.to_string(),
- }
- } else if wt.is_prunable() {
- // Still registered, but the directory no longer holds this
- // worktree. Two shapes reach here: one deleted and
- // recreated, which is what an interrupted `wt switch`
- // leaves behind; and a detached one simply deleted, which
- // the branch-only cleanup above cannot take because it has
- // no branch to fall back to. Neither route out of here
- // works: that cleanup wants a branch *and* an absent
- // directory, and for the recreated directory the removal
- // below walks into git's own validation a few calls later,
- // reaching the user as a raw `exit 128`. The hint names the
- // repo-wide `git worktree prune` because it is what clears
- // both; the detached one, whose directory is absent, a
- // targeted `git worktree remove <path>` would also clear.
- return Err(GitError::WorktreeMissing {
- branch: wt
- .branch
- .clone()
- .unwrap_or_else(|| wt.dir_name().to_string()),
+ branch,
}
- .into());
} else {
let is_current = worktrunk::path::paths_match(&wt.path, current_path);
Resolved::Worktree {
diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rs
index f59cb0e56..6c3c0fbf6 100644
--- a/src/commands/step/prune.rs
+++ b/src/commands/step/prune.rs
@@ -144,7 +144,7 @@ impl CandidateKind {
/// Where a candidate originated, used to drive integration checks and dry-run labels.
enum CheckSource {
- /// Worktree with directory gone (prunable)
+ /// Stale worktree entry: git calls it prunable once its `.git` is gone
Prunable { wt_idx: usize },
/// Linked worktree
Linked { wt_idx: usize },
@@ -322,8 +322,8 @@ fn try_remove(
// Name the stale entry rather than sweeping the repository, so a
// sibling whose directory is merely absent right now (unmounted
// volume, half-finished `mv`) keeps its registration. `gather_check_items`
- // never selects a locked worktree, so the scoped removal can't hit
- // git's lock refusal.
+ // never selects a locked worktree, so the prune refuses one only when
+ // the lock was taken after the scan.
let path = candidate
.path
.as_deref()
@@ -408,8 +408,8 @@ struct CheckOutcome {
/// `prune_entry`; execution performs it), which is what lets this scan
/// double as `--dry-run` and plan every source. `None` means not
/// removable (dirty, locked, primary — filtered silently, never reported
- /// as "younger than") — except detached stale entries whose directory is
- /// gone, which need no plan: `try_remove` prunes them directly.
+ /// as "younger than") — except detached stale entries, which need no
+ /// plan: `try_remove` prunes them directly.
plan: Option<RemovalPlan>,
/// Whether the item passed the removability gate (see `plan`).
removable: bool,
@@ -449,14 +449,10 @@ fn check_one(
});
}
// A detached stale entry can't be planned — `prepare_worktree_removal`'s
- // missing-directory fallback needs a branch to fall back to — and needs
- // no plan: `try_remove` prunes the entry directly. It still needs that
- // fallback's precondition, an absent directory. Git also calls an entry
- // prunable when only the `.git` file inside the directory went (a temp-dir
- // sweep that deletes idle files and keeps directories), and `git worktree
- // remove` refuses an entry whose directory remains, failing the run. Such
- // an entry stays registered, as its branch-bearing twin does when planning
- // refuses it with `WorktreeMissing`.
+ // stale-entry fallback needs a branch to fall back to — and needs no plan:
+ // `try_remove` prunes the entry directly. It still gets that fallback's
+ // check: an entry whose registration holds staged changes or an operation
+ // partway through stays, and so does one the check fails on.
let stale_detached = match &item.source {
CheckSource::Prunable { wt_idx } if worktrees[*wt_idx].branch.is_none() => {
Some(&worktrees[*wt_idx])
@@ -485,7 +481,7 @@ fn check_one(
// checkout, which for a duplicated branch is a different
// worktree — and for a stale entry is the live one. A
// `WorktreePath` target degrades to branch-only deletion
- // when the directory is gone, so a stale entry plans its
+ // when the entry is prunable, so a stale entry plans its
// prune.
RemoveTarget::WorktreePath(wt.path.clone()),
BranchDeletionMode::SafeDelete,
@@ -499,7 +495,7 @@ fn check_one(
}
};
let removable = match stale_detached {
- Some(wt) => !wt.path.exists(),
+ Some(wt) => matches!(repo.stale_worktree_work(&wt.path), Ok(None)),
None => plan.is_some(),
};
let deletes_branch = plan.as_ref().is_some_and(RemovalPlan::deletes_branch);
@@ -927,10 +923,8 @@ fn render_dry_run(
/// `.config/wt.toml`, whatever its anchor).
///
/// Only `Linked` items can plan a worktree removal, the one plan that runs
-/// hooks. `Orphan` items name no worktree. A `Prunable` entry plans a pure
-/// branch deletion when its directory is gone and nothing when it remains
-/// (`prepare_worktree_removal` refuses it with `WorktreeMissing`, and a
-/// detached one is left out in [`check_one`]).
+/// hooks. `Orphan` items name no worktree, and a `Prunable` entry plans a pure
+/// branch deletion, or nothing at all when it is detached.
fn build_pessimistic_plan(
repo: &Repository,
check_items: &[CheckItem],
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 1766dcbab..bf3c048e3 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -764,10 +764,7 @@ fn validate_worktree_creation(
if let Some((existing_path, occupant)) = repo.worktree_at_path(path)? {
if !existing_path.exists() {
let occupant_branch = occupant.unwrap_or_else(|| branch.to_string());
- return Err(GitError::WorktreeMissing {
- branch: occupant_branch,
- }
- .into());
+ return Err(GitError::worktree_missing(occupant_branch, &existing_path).into());
}
return Err(GitError::WorktreePathOccupied {
branch: branch.to_string(),
@@ -948,10 +945,10 @@ fn plan_switch(
// A registration whose directory is gone or broken has nothing to
// switch into; `wt remove` is the one command that still wants it.
if repo.worktree_is_unusable(&path)? {
- return Err(GitError::WorktreeMissing {
- branch: branch
- .unwrap_or_else(|| worktrunk::git::path_dir_name(&path).to_string()),
- }
+ return Err(GitError::worktree_missing(
+ branch.unwrap_or_else(|| worktrunk::git::path_dir_name(&path).to_string()),
+ &path,
+ )
.into());
}
return Ok(SwitchPlan::Existing {
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index 3e24ca0f6..8bdee26cb 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -325,19 +325,19 @@ pub enum RemovalPlan {
/// [`SharedBranchCheckout`].
branch_checked_out_at: Option<SharedBranchCheckout>,
},
- /// Branch exists but has no worktree directory - attempt branch deletion
+ /// Branch exists but has no usable worktree - attempt branch deletion
/// only, unregistering the stale worktree entry first when one remains.
BranchOnly {
branch_name: String,
deletion_mode: BranchDeletionMode,
/// Stale worktree entry to unregister, recorded when the plan fell
- /// back from a worktree whose directory was missing. Planning never
- /// mutates — execution performs the prune (`git worktree remove`,
- /// which validates before touching anything, so a directory that
- /// reappears at this path between planning and execution is handled
- /// by git: a clean reconnected worktree is removed, a dirty or
- /// foreign one refuses loudly). `None` when the branch has no
- /// worktree entry at all.
+ /// back from a prunable worktree. Planning never mutates — execution
+ /// performs the prune
+ /// ([`prune_worktree_entry`](worktrunk::git::Repository::prune_worktree_entry)),
+ /// which repeats git's prune test first, so a worktree reconnected at
+ /// this path between planning and execution refuses rather than
+ /// losing its registration. Whatever remains of the directory stays.
+ /// `None` when the branch has no worktree entry at all.
prune_entry: Option<PathBuf>,
/// Integration target for display. May be the effective target (e.g.,
/// `origin/main` when upstream is ahead) or the local default branch.
@@ -347,9 +347,9 @@ pub enum RemovalPlan {
/// executor still rechecks topology and ref state before safe deletion.
integration_reason: Option<worktrunk::git::IntegrationReason>,
/// A surviving checkout of `branch_name`, when one exists. Only reachable
- /// on a pruned removal — the target's directory was gone, but a sibling
- /// checkout of the same branch survives the fallback to branch-only
- /// deletion. See [`SharedBranchCheckout`].
+ /// on a pruned removal — the target was stale, but a sibling checkout
+ /// of the same branch survives the fallback to branch-only deletion.
+ /// See [`SharedBranchCheckout`].
branch_checked_out_at: Option<SharedBranchCheckout>,
},
}
diff --git a/src/git/error.rs b/src/git/error.rs
index 18c0617fd..d2b03d51c 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -22,12 +22,12 @@
//! emits its rendered output.
use std::borrow::Cow;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use color_print::cformat;
use shell_escape::unix::escape;
-use super::HookType;
+use super::{HookType, InProgressOperation, StaleWorktreeWork};
use crate::path::format_path_for_display;
use crate::styling::{
error_message, format_bash_with_gutter, format_with_gutter, hint_message, info_message,
@@ -480,8 +480,22 @@ pub enum GitError {
/// The action that requires being in a worktree
action: Option<String>,
},
+ /// A registered worktree git calls prunable, or whose directory is gone.
+ /// Built with [`GitError::worktree_missing`].
WorktreeMissing {
branch: String,
+ /// The worktree's path while its directory remains, where `git
+ /// worktree repair` can reconnect it; `None` once the directory is gone.
+ repairable_at: Option<PathBuf>,
+ },
+ /// A stale worktree whose registration holds what unregistering it would
+ /// destroy — see [`Repository::stale_worktree_work`](super::Repository::stale_worktree_work).
+ StaleWorktreeHoldsWork {
+ branch: String,
+ path: PathBuf,
+ /// Whether the directory remains, so repair needs no recreating first.
+ directory_remains: bool,
+ work: StaleWorktreeWork,
},
RemoteOnlyBranch {
branch: String,
@@ -714,7 +728,27 @@ pub fn format_unresolved_conflicts(count: usize) -> String {
format!("{count} {paths} with unresolved conflicts")
}
+/// The operation's name as a message reads it ("a rebase in progress").
+fn operation_noun(operation: InProgressOperation) -> &'static str {
+ match operation {
+ InProgressOperation::Merge => "merge",
+ InProgressOperation::Rebase => "rebase",
+ InProgressOperation::CherryPick => "cherry-pick",
+ InProgressOperation::Revert => "revert",
+ InProgressOperation::Bisect => "bisect",
+ }
+}
+
impl GitError {
+ /// [`GitError::WorktreeMissing`] for the worktree registered at `path`,
+ /// recording whether its directory remains for the hint to offer repair.
+ pub fn worktree_missing(branch: String, path: &Path) -> Self {
+ GitError::WorktreeMissing {
+ branch,
+ repairable_at: path.is_dir().then(|| path.to_path_buf()),
+ }
+ }
+
/// Styled title for this variant (first line, with inline `<bold>`
/// highlights on entity names like branch and path).
///
@@ -788,10 +822,20 @@ impl GitError {
None => "Not in a worktree".to_string(),
},
- GitError::WorktreeMissing { branch } => {
- cformat!("Worktree directory missing for <bold>{branch}</>")
+ GitError::WorktreeMissing { branch, .. } => {
+ cformat!("Worktree for <bold>{branch}</> is stale; its directory or .git is gone")
}
+ GitError::StaleWorktreeHoldsWork { branch, work, .. } => match work {
+ StaleWorktreeWork::StagedChanges => {
+ cformat!("Worktree for <bold>{branch}</> is stale but holds staged changes")
+ }
+ StaleWorktreeWork::Operation(operation) => cformat!(
+ "Worktree for <bold>{branch}</> is stale with a {} in progress",
+ operation_noun(*operation)
+ ),
+ },
+
GitError::RemoteOnlyBranch { branch, remote } => {
cformat!("Branch <bold>{branch}</> exists only on remote ({remote}/{branch})")
}
@@ -1138,14 +1182,42 @@ impl GitError {
)
}
- GitError::WorktreeMissing { .. } => {
+ GitError::WorktreeMissing { repairable_at, .. } => {
+ let title = self.title();
+ // Repair reconnects a directory that remains, whatever it holds;
+ // once the directory is gone there is nothing to reconnect.
+ let hint = match repairable_at {
+ Some(path) => cformat!(
+ "To restore the worktree, run <underline>git worktree repair {}</>",
+ format_path_for_display(path)
+ ),
+ None => cformat!("To clean up, run <underline>git worktree prune</>"),
+ };
+ write!(f, "{}\n{}", error_message(&title), hint_message(hint))
+ }
+
+ GitError::StaleWorktreeHoldsWork {
+ branch,
+ path,
+ directory_remains,
+ ..
+ } => {
let title = self.title();
+ let discard = suggest_command("remove", &[branch], &["-f"]);
+ let path_display = format_path_for_display(path);
+ let restore = if *directory_remains {
+ cformat!("run <underline>git worktree repair {path_display}</>")
+ } else {
+ cformat!(
+ "recreate its directory, then run <underline>git worktree repair {path_display}</>"
+ )
+ };
write!(
f,
"{}\n{}",
error_message(&title),
hint_message(cformat!(
- "To clean up, run <underline>git worktree prune</>"
+ "To discard the stale worktree, run <underline>{discard}</>; to restore it, {restore}"
))
)
}
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 497b0dcd8..71d2e524b 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -100,9 +100,9 @@ pub use remove::{
pub use repository::sha_cache;
pub use repository::{
Branch, BranchDiffSpec, CommitMessageDetail, InProgressOperation, IntegrationTargets,
- PreparedDiff, RefSnapshot, Repository, ResolvedWorktree, Selector, TempIndex, WorkingTree,
- duplicated_branches, is_valid_branch_name, normalize_selector, resolve_input_path,
- select_comparison_base, set_base_path,
+ PreparedDiff, RefSnapshot, Repository, ResolvedWorktree, Selector, StaleWorktreeWork,
+ TempIndex, WorkingTree, duplicated_branches, is_valid_branch_name, normalize_selector,
+ resolve_input_path, select_comparison_base, set_base_path,
};
pub use url::parse_owner_repo;
pub use url::{GitRemoteUrl, GitRepoInfo, GitRepoProvider};
@@ -826,10 +826,12 @@ impl WorktreeInfo {
WorktreeRef::new(self.path.clone(), self.branch.as_deref(), &self.head)
}
- /// Returns true if this worktree is prunable (directory deleted but git still tracks metadata).
+ /// Returns true if git reports this worktree prunable: the `.git` its
+ /// registration names is gone, with the directory or without it.
///
- /// Prunable worktrees cannot be operated on - the directory doesn't exist.
- /// Most iteration over worktrees should skip prunable ones.
+ /// Prunable worktrees cannot be operated on — git no longer resolves the
+ /// directory, if one remains, as this worktree. Most iteration over
+ /// worktrees should skip prunable ones.
pub fn is_prunable(&self) -> bool {
self.prunable.is_some()
}
diff --git a/src/git/remove.rs b/src/git/remove.rs
index 117a17158..ab29630d4 100644
--- a/src/git/remove.rs
+++ b/src/git/remove.rs
@@ -507,9 +507,8 @@ fn rename_into_trash(repo: &Repository, worktree_path: &Path) -> Option<PathBuf>
let staged_path = generate_removing_path(&trash_dir, worktree_path);
if std::fs::rename(worktree_path, &staged_path).is_ok() {
- // The rename moved the directory out from under `worktree_path`, so
- // git resolves the entry by its recorded path and skips the clean
- // check.
+ // The rename moved the directory out from under `worktree_path`,
+ // leaving its registration stale for the prune to delete.
if let Err(e) = repo.prune_worktree_entry(worktree_path) {
tracing::debug!(error = %e, "Failed to prune worktree entry after rename: {e}");
}
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index 0a16e4968..1cc1292c1 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -660,6 +660,18 @@ impl Repository {
)
}
+ /// The tree-ish an index is compared against for staged changes: `head`,
+ /// or the empty tree when `head` is `None` (an unborn branch).
+ ///
+ /// Porcelain `git diff --cached` picks this itself; plumbing
+ /// (`diff-index --cached`) needs it spelled out.
+ pub(super) fn index_base_for(&self, head: Option<String>) -> anyhow::Result<String> {
+ match head {
+ Some(head) => Ok(head),
+ None => Ok(self.empty_tree_sha()?.to_string()),
+ }
+ }
+
/// Resolve how to diff a branch's content against the mainline for the
/// diff/summary preview panes. `head` is a resolved commit SHA. See
/// [`BranchDiffSpec`]. Returns `None` when there's no comparison base (no
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 74804393e..5cec93e23 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -174,7 +174,7 @@ pub use integration::{BranchDiffSpec, IntegrationTargets, select_comparison_base
pub use ref_snapshot::RefSnapshot;
pub(super) use working_tree::path_to_logging_context;
pub use working_tree::{InProgressOperation, TempIndex, WorkingTree};
-pub use worktrees::duplicated_branches;
+pub use worktrees::{StaleWorktreeWork, duplicated_branches};
// ============================================================================
// Repository Cache
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index a9dfe3c1b..11ca9d5d6 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -2059,7 +2059,7 @@ fn usable_worktree_for_branch_refuses_a_prunable_registration() {
let err = repo.usable_worktree_for_branch("feature").unwrap_err();
assert!(
- err.to_string().contains("Worktree directory missing"),
+ err.to_string().contains("is stale"),
"a prunable registration must be refused, got: {err}"
);
assert_eq!(
@@ -2164,6 +2164,240 @@ fn worktree_is_unusable_covers_locked_absent_and_recreated() {
);
}
+/// Unregistering a stale worktree repeats git's own prune test at deletion
+/// time, since the caller's `prunable` came from an earlier listing: an entry
+/// locked or reconnected since is refused and keeps its registration. A stale
+/// entry goes whatever is left at its path — nothing, a directory, or a file —
+/// and a directory that remains keeps its files.
+#[test]
+fn prune_worktree_entry_repeats_git_prune_test() {
+ use crate::git::Repository;
+ use crate::testing::TestRepo;
+
+ let mut test = TestRepo::with_initial_commit();
+ let live = test.add_worktree("live");
+ let locked = test.add_worktree("locked-absent");
+ let absent = test.add_worktree("absent");
+ let dotgit_gone = test.add_worktree("dotgit-gone");
+ let now_a_file = test.add_worktree("now-a-file");
+
+ test.lock_worktree("locked-absent", Some("removable media"));
+ std::fs::remove_dir_all(&locked).unwrap();
+ std::fs::remove_dir_all(&absent).unwrap();
+ std::fs::remove_file(dotgit_gone.join(".git")).unwrap();
+ std::fs::write(dotgit_gone.join("leftover.txt"), "kept").unwrap();
+ // `now-a-file/.git` fails with `NotADirectory`, which git also counts as
+ // nothing there.
+ std::fs::remove_dir_all(&now_a_file).unwrap();
+ std::fs::write(&now_a_file, "not a directory").unwrap();
+
+ let repo = Repository::at(test.root_path()).unwrap();
+ let registered = || {
+ test.git_output(&["worktree", "list", "--porcelain"])
+ .lines()
+ .filter_map(|line| line.strip_prefix("worktree "))
+ .filter_map(|path| PathBuf::from(path).file_name().map(|n| n.to_owned()))
+ .collect::<Vec<_>>()
+ };
+
+ let err = repo.prune_worktree_entry(&live).unwrap_err();
+ assert!(err.to_string().contains("no longer stale"), "got: {err}");
+ let err = repo.prune_worktree_entry(&locked).unwrap_err();
+ assert!(err.to_string().contains("is locked"), "got: {err}");
+
+ repo.prune_worktree_entry(&absent).unwrap();
+ repo.prune_worktree_entry(&dotgit_gone).unwrap();
+ repo.prune_worktree_entry(&now_a_file).unwrap();
+ let names = registered();
+ for (path, kept) in [
+ (&live, true),
+ (&locked, true),
+ (&absent, false),
+ (&dotgit_gone, false),
+ (&now_a_file, false),
+ ] {
+ assert_eq!(
+ names.iter().any(|name| name == path.file_name().unwrap()),
+ kept,
+ "{} registration; worktrees: {names:?}",
+ path.display()
+ );
+ }
+ assert!(dotgit_gone.join("leftover.txt").is_file());
+
+ let err = repo.prune_worktree_entry(&absent).unwrap_err();
+ assert!(
+ err.to_string().contains("No worktree registered"),
+ "got: {err}"
+ );
+}
+
+/// A `.git` that can't be statted is not taken for an absent one: the entry
+/// keeps its registration, and the error names what couldn't be checked.
+#[cfg(unix)]
+#[test]
+fn prune_worktree_entry_keeps_an_entry_it_cannot_check() {
+ use std::os::unix::fs::PermissionsExt;
+
+ use crate::git::Repository;
+ use crate::testing::TestRepo;
+
+ let test = TestRepo::with_initial_commit();
+ let guarded = test.root_path().parent().unwrap().join("guarded");
+ std::fs::create_dir(&guarded).unwrap();
+ let worktree_path = guarded.join("wt");
+ test.run_git(&[
+ "worktree",
+ "add",
+ "--detach",
+ worktree_path.to_str().unwrap(),
+ ]);
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ let set_mode =
+ |mode| std::fs::set_permissions(&guarded, std::fs::Permissions::from_mode(mode)).unwrap();
+ set_mode(0o000);
+ // Skip if running as root: euid 0 ignores DAC mode bits, so the stat
+ // would succeed. Probe with the stat the mode should refuse.
+ if std::fs::symlink_metadata(worktree_path.join(".git")).is_ok() {
+ set_mode(0o755);
+ crate::styling::eprintln!("Skipping - running with elevated privileges");
+ return;
+ }
+ let result = repo.prune_worktree_entry(&worktree_path);
+ set_mode(0o755);
+
+ let err = result.unwrap_err();
+ assert!(
+ format!("{err:#}").contains("Failed to check"),
+ "got: {err:#}"
+ );
+ assert!(
+ test.git_output(&["worktree", "list", "--porcelain"])
+ .contains("guarded/wt"),
+ "the entry should stay registered"
+ );
+}
+
+/// A stale registration is asked what unregistering it would destroy: its
+/// index against `HEAD`, and git's in-progress state files. A registration
+/// with no index has nothing staged, and on an unborn branch the index is
+/// read against the empty tree, so a staged file counts and an emptied index
+/// doesn't.
+#[test]
+fn stale_worktree_work_reads_the_registration() {
+ use crate::git::{InProgressOperation, Repository, StaleWorktreeWork};
+ use crate::testing::TestRepo;
+
+ let mut test = TestRepo::with_initial_commit();
+ let clean = test.add_worktree("clean");
+ let staged = test.add_worktree("staged");
+ std::fs::write(staged.join("new.txt"), "work").unwrap();
+ test.run_git_in(&staged, &["add", "new.txt"]);
+ let bisecting = test.add_worktree("bisecting");
+ test.run_git_in(&bisecting, &["bisect", "start"]);
+ let parent = test.root_path().parent().unwrap().to_path_buf();
+ let no_checkout = parent.join("repo.no-checkout");
+ test.run_git(&[
+ "worktree",
+ "add",
+ "--no-checkout",
+ "--detach",
+ no_checkout.to_str().unwrap(),
+ ]);
+ let unborn = parent.join("repo.unborn");
+ test.run_git(&[
+ "worktree",
+ "add",
+ "--orphan",
+ "-b",
+ "fresh",
+ unborn.to_str().unwrap(),
+ ]);
+ std::fs::write(unborn.join("first.txt"), "work").unwrap();
+ test.run_git_in(&unborn, &["add", "first.txt"]);
+ // An unborn branch whose index exists but holds nothing.
+ let unborn_empty = parent.join("repo.unborn-empty");
+ test.run_git(&[
+ "worktree",
+ "add",
+ "--orphan",
+ "-b",
+ "fresh-empty",
+ unborn_empty.to_str().unwrap(),
+ ]);
+ std::fs::write(unborn_empty.join("first.txt"), "work").unwrap();
+ test.run_git_in(&unborn_empty, &["add", "first.txt"]);
+ test.run_git_in(&unborn_empty, &["rm", "--cached", "-q", "first.txt"]);
+ for path in [
+ &clean,
+ &staged,
+ &bisecting,
+ &no_checkout,
+ &unborn,
+ &unborn_empty,
+ ] {
+ std::fs::remove_dir_all(path).unwrap();
+ }
+
+ let repo = Repository::at(test.root_path()).unwrap();
+ assert_eq!(repo.stale_worktree_work(&clean).unwrap(), None);
+ assert_eq!(
+ repo.stale_worktree_work(&staged).unwrap(),
+ Some(StaleWorktreeWork::StagedChanges)
+ );
+ assert_eq!(
+ repo.stale_worktree_work(&bisecting).unwrap(),
+ Some(StaleWorktreeWork::Operation(InProgressOperation::Bisect))
+ );
+ assert_eq!(repo.stale_worktree_work(&no_checkout).unwrap(), None);
+ assert_eq!(
+ repo.stale_worktree_work(&unborn).unwrap(),
+ Some(StaleWorktreeWork::StagedChanges)
+ );
+ assert_eq!(repo.stale_worktree_work(&unborn_empty).unwrap(), None);
+}
+
+/// The deletion waits for in-process registry readers: `git worktree list`
+/// reads every entry's files, so one overlapping the deletion could read the
+/// entry half-deleted and fail. A held read guard keeps the entry intact; its
+/// release lets the prune through.
+#[test]
+fn prune_worktree_entry_waits_for_registry_readers() {
+ use std::time::{Duration, Instant};
+
+ use crate::git::Repository;
+ use crate::testing::TestRepo;
+
+ let mut test = TestRepo::with_initial_commit();
+ let worktree_path = test.add_worktree("feature");
+ std::fs::remove_dir_all(&worktree_path).unwrap();
+ let registration = test
+ .root_path()
+ .join(".git/worktrees")
+ .join(worktree_path.file_name().unwrap());
+ assert!(registration.is_dir());
+ let repo = Repository::at(test.root_path()).unwrap();
+ let worker_repo = repo.clone();
+
+ let reader = repo.worktree_registry_read();
+ let worker = std::thread::spawn(move || worker_repo.prune_worktree_entry(&worktree_path));
+ let deadline = Instant::now() + Duration::from_millis(200);
+ while registration.exists() && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let survived_reader = registration.exists();
+ drop(reader);
+ let result = worker.join().expect("prune thread should not panic");
+
+ assert!(
+ survived_reader,
+ "the prune ran under a held registry read guard"
+ );
+ result.unwrap();
+ assert!(!registration.exists());
+}
+
/// The ownership gate accepts a worktree that holds its own registration, in
/// both shapes: a linked worktree, whose `.git` file names a registration that
/// names it back, and the main worktree, which has no registration at all
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index a91176550..16dea9e10 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -176,7 +176,7 @@ fn sequencer_operation(git_dir: &Path) -> Option<InProgressOperation> {
/// no longer exist — the case the caller is usually asking about, and the path it
/// then shows the user. Normalizing rewrites spellings only, so it cannot make
/// two directories compare equal.
-fn registration_worktree_path(registration: &Path) -> Option<PathBuf> {
+pub(super) fn registration_worktree_path(registration: &Path) -> Option<PathBuf> {
let content = std::fs::read_to_string(registration.join("gitdir")).ok()?;
let recorded = PathBuf::from(content.trim());
let absolute = if recorded.is_relative() {
@@ -187,6 +187,49 @@ fn registration_worktree_path(registration: &Path) -> Option<PathBuf> {
absolute.parent().map(canonicalize_with_parents)
}
+/// The git operation the worktree whose git dir is `git_dir` is partway
+/// through, if any.
+///
+/// Reads the state files git writes under that git dir, in the order
+/// [`git status`](https://git-scm.com/docs/git-status) consults them, so the
+/// answer tracks what git itself calls "in progress". Takes the git dir rather
+/// than a worktree because a stale worktree's registration is still asked,
+/// after its `.git` file — the usual route to that dir — has gone.
+pub(super) fn operation_in_progress_at(git_dir: &Path) -> Option<InProgressOperation> {
+ if git_dir.join("MERGE_HEAD").exists() {
+ return Some(InProgressOperation::Merge);
+ }
+
+ // `rebase-merge` (interactive/merge backend) and `rebase-apply` (am
+ // backend, also used by `git am`) are mutually exclusive; either one
+ // means commits are mid-replay.
+ if git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists() {
+ return Some(InProgressOperation::Rebase);
+ }
+
+ if git_dir.join("CHERRY_PICK_HEAD").exists() {
+ return Some(InProgressOperation::CherryPick);
+ }
+
+ if git_dir.join("REVERT_HEAD").exists() {
+ return Some(InProgressOperation::Revert);
+ }
+
+ // The two `_HEAD` files above exist only while a single pick is
+ // stopped: resolving one with `git commit` instead of `--continue`
+ // removes it and leaves the rest of the sequence queued, which git
+ // still reports as in progress.
+ if let Some(operation) = sequencer_operation(git_dir) {
+ return Some(operation);
+ }
+
+ if git_dir.join("BISECT_LOG").exists() {
+ return Some(InProgressOperation::Bisect);
+ }
+
+ None
+}
+
/// Typed snapshot returned by [`WorkingTree::prewarm_info`].
///
/// Mirrors what the batched `git rev-parse` actually resolved so callers can
@@ -484,15 +527,10 @@ impl<'a> WorkingTree<'a> {
}
/// The tree-ish the index is compared against for staged changes: HEAD,
- /// or the empty tree on an unborn branch.
- ///
- /// Porcelain `git diff --cached` picks this itself; plumbing
- /// (`diff-index --cached`) needs it spelled out.
+ /// or the empty tree on an unborn branch. Plumbing (`diff-index --cached`)
+ /// needs this spelled out; porcelain `git diff --cached` picks it itself.
pub fn index_base(&self) -> anyhow::Result<String> {
- match self.head_sha()? {
- Some(head) => Ok(head),
- None => Ok(self.repo.empty_tree_sha()?.to_string()),
- }
+ self.repo.index_base_for(self.head_sha()?)
}
/// Return cached `git status --porcelain` output for this worktree.
@@ -638,46 +676,11 @@ impl<'a> WorkingTree<'a> {
}
}
- /// The git operation this worktree is partway through, if any.
- ///
- /// Reads the state files git writes under the worktree's git dir, in the
- /// order [`git status`](https://git-scm.com/docs/git-status) consults them,
- /// so the answer tracks what git itself calls "in progress".
+ /// The git operation this worktree is partway through, if any, read from
+ /// the state files git writes under its git dir in the order
+ /// [`git status`](https://git-scm.com/docs/git-status) consults them.
pub fn operation_in_progress(&self) -> anyhow::Result<Option<InProgressOperation>> {
- let git_dir = self.git_dir()?;
-
- if git_dir.join("MERGE_HEAD").exists() {
- return Ok(Some(InProgressOperation::Merge));
- }
-
- // `rebase-merge` (interactive/merge backend) and `rebase-apply` (am
- // backend, also used by `git am`) are mutually exclusive; either one
- // means commits are mid-replay.
- if git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists() {
- return Ok(Some(InProgressOperation::Rebase));
- }
-
- if git_dir.join("CHERRY_PICK_HEAD").exists() {
- return Ok(Some(InProgressOperation::CherryPick));
- }
-
- if git_dir.join("REVERT_HEAD").exists() {
- return Ok(Some(InProgressOperation::Revert));
- }
-
- // The two `_HEAD` files above exist only while a single pick is
- // stopped: resolving one with `git commit` instead of `--continue`
- // removes it and leaves the rest of the sequence queued, which git
- // still reports as in progress.
- if let Some(operation) = sequencer_operation(&git_dir) {
- return Ok(Some(operation));
- }
-
- if git_dir.join("BISECT_LOG").exists() {
- return Ok(Some(InProgressOperation::Bisect));
- }
-
- Ok(None)
+ Ok(operation_in_progress_at(&self.git_dir()?))
}
/// Paths the index still records as unmerged.
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index 698edcf43..aa0b4b5de 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -8,12 +8,16 @@ use anyhow::Context as _;
use color_print::cformat;
use dunce::canonicalize;
+use super::working_tree::{
+ operation_in_progress_at, path_to_logging_context, registration_worktree_path,
+};
use super::{
- GitError, Repository, ResolvedWorktree, Selector, WorktreeInfo, is_valid_branch_name,
- normalize_selector, resolve_input_path,
+ GitError, InProgressOperation, Repository, ResolvedWorktree, Selector, WorktreeInfo,
+ is_valid_branch_name, normalize_selector, resolve_input_path,
};
-use crate::git::{WorktreeId, is_bare_repo_dir};
+use crate::git::{CommandError, PlumbingDiff, WorktreeId, is_bare_repo_dir};
use crate::path::{format_path_for_display, paths_match};
+use crate::shell_exec::Cmd;
use crate::styling::{
eprintln, format_with_gutter, hint_message, suggest_command, warning_message,
};
@@ -111,10 +115,7 @@ impl Repository {
return Ok(None);
};
if self.worktree_is_unusable(&path)? {
- return Err(GitError::WorktreeMissing {
- branch: branch.to_string(),
- }
- .into());
+ return Err(GitError::worktree_missing(branch.to_string(), &path).into());
}
Ok(Some(path))
}
@@ -189,14 +190,35 @@ impl Repository {
.map(|wt| (wt.path.clone(), wt.branch.clone())))
}
- /// Unregister the one worktree at `path`, whose directory is already gone.
+ /// Unregister the one stale worktree at `path`, as `git worktree prune`
+ /// would, leaving whatever remains of its directory in place.
///
- /// Git tracks worktrees in `.git/worktrees/<id>/`. When a worktree's
- /// directory disappears — deleted externally, or renamed into the trash by
+ /// Git tracks worktrees in `.git/worktrees/<id>/` and calls an entry
+ /// prunable once `<path>/.git` is gone. Usually the whole directory went —
+ /// deleted externally, or renamed into the trash by
/// [`stage_worktree_removal`](crate::git::remove::stage_worktree_removal) —
- /// that admin dir is stale and has to go. `git worktree remove` skips its
- /// clean check when the directory is missing and deletes just that entry,
- /// so it is the scoped spelling of the cleanup.
+ /// but a sweep that deletes idle files and keeps directories, like macOS's
+ /// `$TMPDIR` cleanup, takes only the `.git`. Either way the admin dir is
+ /// stale, and deleting it is all `git worktree prune` does to the entry.
+ ///
+ /// # Why not a git command
+ ///
+ /// No git command unregisters one prunable entry in both shapes.
+ /// `git worktree prune` takes no path (below), and `git worktree remove`
+ /// refuses an entry whose directory remains, `--force` included: its
+ /// validation wants `<path>/.git` unless the whole directory is gone. So
+ /// this reproduces git's prune for the one entry — its test, then its
+ /// deletion.
+ ///
+ /// The test is git's own (`should_prune_worktree`): the entry is not
+ /// locked, and nothing is at the `.git` its `gitdir` file names. It runs
+ /// under the registry lock just before the deletion, because the caller's
+ /// `prunable` came from an earlier listing, and it refuses rather than
+ /// deletes when either half has changed since — a lock taken, or a
+ /// remounted volume that reconnected the worktree. Deleting a live
+ /// worktree's admin dir would strand its checkout. Only a definite absence
+ /// counts as nothing being at `.git`; one that can't be statted for another
+ /// reason keeps the entry, where git's own test would prune it.
///
/// # Why not `git worktree prune`
///
@@ -210,48 +232,116 @@ impl Repository {
/// the per-worktree reflog, `refs/worktree/*` and `refs/bisect/*`, and any
/// in-progress rebase or merge all go with it. `git worktree repair`
/// cannot rebuild them — it relinks an admin dir, it does not recreate
- /// one. Naming the target keeps a removal's blast radius equal to its
- /// intent.
- ///
- /// # Locked worktrees
- ///
- /// A repo-wide prune silently skips a locked entry; `git worktree remove`
- /// fails on one instead. Every call site has already established the target
- /// is unlocked, by a different route each: `prepare_worktree_removal`
- /// returns `WorktreeLocked` at the top of its path/current arm and rejects
- /// a locked worktree before staging one for removal, and prune's
- /// `gather_check_items` never selects one as a candidate.
+ /// one. A detached entry loses more: its `HEAD` was the only ref holding
+ /// commits made there, which the next `git gc` may then delete. Naming
+ /// the target keeps a removal's blast radius equal to its intent.
///
/// # Concurrent calls
///
- /// This method and [`Repository::remove_worktree`] serialize their `git
- /// worktree remove` commands with each other for the same repository.
- /// Naming one entry bounds what a call *deletes*, not what it *reads*.
- /// `git worktree remove` enumerates *every* sibling under `.git/worktrees/`
- /// and reads each one's `commondir` while resolving its target, so a
- /// teardown overlapping another worker's teardown — or a branch delete's
- /// `list_worktrees` probe — can read an entry mid-deletion and fail
- /// (`failed to read …/commondir` / `Invalid path …/.git/worktrees/<id>`).
- /// That is Git's own TOCTOU between the enumerator's `readdir` and its
- /// `open`. The repository-scoped write lock closes the in-process window;
- /// [`Repository::list_worktrees`] takes the matching read side.
- ///
- /// Git also `rmdir`s the containing `.git/worktrees` once the last entry
- /// goes, but that only succeeds on an already-empty directory, and every
- /// per-worktree command in the removal chain (`git status`, the fsmonitor
- /// stop) runs while that worktree is still registered, so an emptied
- /// directory has no in-flight reader left to strand. A `git worktree list`
- /// in an *unrelated* process — outside wt's lock — remains exposed to the
- /// same `Invalid path` race; wt's serialization only covers its own
- /// removals.
+ /// This deletion and [`Repository::remove_worktree`]'s `git worktree
+ /// remove` serialize with each other for the same repository. Naming one
+ /// entry bounds what a call *deletes*, not what others *read*: `git
+ /// worktree remove` and `git worktree list` enumerate *every* entry under
+ /// `.git/worktrees/` and read each one's files, so one overlapping this
+ /// deletion can read the entry mid-deletion and fail (`failed to read
+ /// …/commondir` / `Invalid path …/.git/worktrees/<id>`). That is Git's own
+ /// TOCTOU between the enumerator's `readdir` and its `open`. The
+ /// repository-scoped write lock closes the in-process window;
+ /// [`Repository::list_worktrees`] takes the matching read side. A `git
+ /// worktree list` in an *unrelated* process — outside wt's lock — remains
+ /// exposed; wt's serialization only covers its own removals.
+ ///
+ /// Git also `rmdir`s `.git/worktrees` once its last entry goes. This
+ /// leaves the empty directory, which git reads as no linked worktrees.
pub fn prune_worktree_entry(&self, path: &Path) -> anyhow::Result<()> {
- // Every caller's path came from `list_worktrees`, which parses git's
- // porcelain as UTF-8, so this only fires if that edge ever stops
- // guaranteeing it — a bare `?` rather than a rendered path.
- let path_str = path.to_str().context("worktree path is not valid UTF-8")?;
+ let display = format_path_for_display(path);
let _registry = self.worktree_registry_write();
- self.run_command(&["worktree", "remove", path_str])?;
- Ok(())
+ let (registration, recorded) = self.registration_at(path)?;
+ if !definitely_absent(&registration.join("locked"))? {
+ anyhow::bail!("Worktree @ {display} is locked");
+ }
+ if !definitely_absent(&recorded.join(".git"))? {
+ anyhow::bail!("Worktree @ {display} is no longer stale; its .git exists");
+ }
+ std::fs::remove_dir_all(&registration).with_context(|| {
+ format!(
+ "Failed to delete {}",
+ format_path_for_display(&registration)
+ )
+ })
+ }
+
+ /// What unregistering the stale worktree at `path` would destroy that
+ /// nothing else holds: staged changes in its index, or a git operation
+ /// partway through. `None` when its registration holds neither.
+ ///
+ /// [`prune_worktree_entry`](Self::prune_worktree_entry) deletes the
+ /// registration, and the index and any rebase, merge, cherry-pick, revert
+ /// or bisect state go with it. While the registration survives, `git
+ /// worktree repair <path>` reconnects the directory — recreated first, if
+ /// it went too — and all of that comes back; afterwards staged files
+ /// survive only as dangling blobs. So the stale-removal paths ask this
+ /// first and keep an entry that holds either, which is where they are
+ /// more careful than `git worktree prune`. Files in a directory that
+ /// remains stay on disk either way, and a registration with no index has
+ /// nothing staged.
+ pub fn stale_worktree_work(&self, path: &Path) -> anyhow::Result<Option<StaleWorktreeWork>> {
+ let (registration, _) = self.registration_at(path)?;
+ if let Some(operation) = operation_in_progress_at(&registration) {
+ return Ok(Some(StaleWorktreeWork::Operation(operation)));
+ }
+ if definitely_absent(&registration.join("index"))? {
+ return Ok(None);
+ }
+ // The registration is a git dir in its own right, so its index is read
+ // against its `HEAD` without the working tree git can no longer find.
+ // Both commands answer with exit 0 or 1; anything else is a failure.
+ let registration_arg = registration.to_string_lossy();
+ let git = |args: &[&str]| -> anyhow::Result<(bool, String)> {
+ let mut all = vec!["--git-dir", registration_arg.as_ref()];
+ all.extend_from_slice(args);
+ let output = self
+ .with_object_store_env(
+ Cmd::new("git")
+ .args(all.iter().copied())
+ .context(path_to_logging_context(path))
+ .scrub_git_discovery_env(),
+ )
+ .run()
+ .with_context(|| format!("Failed to execute: git {}", all.join(" ")))?;
+ match output.status.code() {
+ Some(0 | 1) => Ok((
+ output.status.success(),
+ String::from_utf8_lossy(&output.stdout).trim().to_owned(),
+ )),
+ _ => Err(CommandError::from_failed_output("git", &all, &output).into()),
+ }
+ };
+ // An unborn `HEAD` compares against the empty tree, so everything in
+ // its index counts as staged.
+ let (born, head) = git(&["rev-parse", "--verify", "--quiet", "HEAD"])?;
+ let base = self.index_base_for(born.then_some(head))?;
+ // `--quiet` exits 1 when the index differs from the base.
+ let (unchanged, _) = git(&PlumbingDiff::Index.args(&["--cached", "--quiet", &base, "--"]))?;
+ Ok((!unchanged).then_some(StaleWorktreeWork::StagedChanges))
+ }
+
+ /// The registration `<common>/worktrees/<id>` whose `gitdir` names the
+ /// worktree at `path`, with the worktree path it records.
+ ///
+ /// Unreadable siblings (an entry another process is deleting) are not
+ /// this one, so they are passed over rather than failing the lookup.
+ fn registration_at(&self, path: &Path) -> anyhow::Result<(PathBuf, PathBuf)> {
+ let registrations = self.git_common_dir().join("worktrees");
+ std::fs::read_dir(&registrations)
+ .with_context(|| format!("Failed to read {}", format_path_for_display(&registrations)))?
+ .filter_map(Result::ok)
+ .map(|entry| entry.path())
+ .find_map(|registration| {
+ let recorded = registration_worktree_path(&registration)?;
+ paths_match(&recorded, path).then_some((registration, recorded))
+ })
+ .with_context(|| format!("No worktree registered @ {}", format_path_for_display(path)))
}
/// Remove a worktree at the specified path.
@@ -648,6 +738,30 @@ impl Repository {
}
}
+/// What a stale worktree's registration holds that unregistering it would
+/// destroy — see [`Repository::stale_worktree_work`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum StaleWorktreeWork {
+ /// The index differs from `HEAD`.
+ StagedChanges,
+ /// A git operation is partway through.
+ Operation(InProgressOperation),
+}
+
+/// Whether nothing is at `path`: `NotFound`, or `NotADirectory` where a parent
+/// became a file. Any other error is returned, so a caller deciding whether to
+/// delete keeps what it could not check.
+fn definitely_absent(path: &Path) -> anyhow::Result<bool> {
+ match std::fs::symlink_metadata(path) {
+ Ok(_) => Ok(false),
+ Err(e) => match e.kind() {
+ std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory => Ok(true),
+ _ => Err(anyhow::Error::new(e)
+ .context(format!("Failed to check {}", format_path_for_display(path)))),
+ },
+ }
+}
+
/// Whether `path` is a directory git would find data in — somebody's checkout
/// or repository, rather than a leftover skeleton.
///
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 31dd63854..7118fb00f 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1275,15 +1275,19 @@ fn handle_branch_only_output(
} else {
false
};
+ // A stale entry's directory may remain (only its `.git` went), so the line
+ // names the entry rather than a missing directory.
let branch_info = if pruned {
- cformat!("Worktree directory missing for <bold>{branch_name}</>; pruned")
+ success_message(cformat!("Pruned stale worktree for <bold>{branch_name}</>"))
} else {
- cformat!("No worktree found for branch <bold>{branch_name}</>")
+ info_message(cformat!(
+ "No worktree found for branch <bold>{branch_name}</>"
+ ))
};
// If we won't delete the branch, show info and return early
if deletion_mode.should_keep() {
- eprintln!("{}", info_message(&branch_info));
+ eprintln!("{branch_info}");
// A sibling `--force` checkout kept the branch alive; name it so the
// user knows why the pruned branch survived rather than being deleted.
if let Some(shared) = branch_checked_out_at {
@@ -1338,7 +1342,7 @@ fn handle_branch_only_output(
let retained = match &deletion.result.outcome {
BranchDeletionOutcome::RetainedCheckedOut { path } => {
- eprintln!("{}", info_message(&branch_info));
+ eprintln!("{branch_info}");
eprintln!(
"{}",
retained_checked_out_branch_message(branch_name, path, false)
@@ -1346,12 +1350,12 @@ fn handle_branch_only_output(
true
}
BranchDeletionOutcome::RetainedRaced => {
- eprintln!("{}", info_message(&branch_info));
+ eprintln!("{branch_info}");
eprintln!("{}", retained_raced_branch_message(branch_name, false));
true
}
BranchDeletionOutcome::NotDeleted => {
- eprintln!("{}", info_message(&branch_info));
+ eprintln!("{branch_info}");
if deletion.show_unmerged_hint {
print_retained_unmerged_branch(branch_name);
}
@@ -1379,7 +1383,7 @@ fn handle_branch_only_output(
);
} else {
if !quiet {
- eprintln!("{}", info_message(&branch_info));
+ eprintln!("{branch_info}");
}
eprintln!(
"{}",
diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rs
index 765e22ca9..7feec1298 100644
--- a/tests/integration_tests/git_error_display.rs
+++ b/tests/integration_tests/git_error_display.rs
@@ -3,8 +3,8 @@ use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;
use worktrunk::git::{
- Diagnostic, FailedCommand, GitError, HookErrorWithHint, HookType, RefType, WorktrunkError,
- add_hook_skip_hint,
+ Diagnostic, FailedCommand, GitError, HookErrorWithHint, HookType, InProgressOperation, RefType,
+ StaleWorktreeWork, WorktrunkError, add_hook_skip_hint,
};
use crate::common::{mock_commands::MockConfig, test_tempdir, wt_command};
@@ -113,9 +113,48 @@ fn worktree_errors_render() {
"worktree missing",
GitError::WorktreeMissing {
branch: "stale-branch".into(),
+ repairable_at: None,
}
.render(),
),
+ (
+ "worktree missing its .git, directory remaining at a path needing quotes",
+ GitError::WorktreeMissing {
+ branch: "stale-branch".into(),
+ repairable_at: Some(PathBuf::from("/tmp/my repo.stale-branch")),
+ }
+ .render(),
+ ),
+ (
+ "stale worktree holding staged changes",
+ GitError::StaleWorktreeHoldsWork {
+ branch: "stale-branch".into(),
+ path: PathBuf::from("/tmp/repo.stale-branch"),
+ directory_remains: true,
+ work: StaleWorktreeWork::StagedChanges,
+ }
+ .render(),
+ ),
+ (
+ "stale worktree mid-operation, directory gone, at a path needing quotes",
+ [
+ InProgressOperation::Merge,
+ InProgressOperation::Rebase,
+ InProgressOperation::CherryPick,
+ InProgressOperation::Revert,
+ InProgressOperation::Bisect,
+ ]
+ .map(|operation| {
+ GitError::StaleWorktreeHoldsWork {
+ branch: "stale-branch".into(),
+ path: PathBuf::from("/tmp/my repo.stale-branch"),
+ directory_remains: false,
+ work: StaleWorktreeWork::Operation(operation),
+ }
+ .render()
+ })
+ .join("\n"),
+ ),
(
"no worktree at a leftover directory",
GitError::WorktreeNotFoundAtPath {
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 03cb643a2..6cc612f23 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -523,16 +523,12 @@ fn test_remove_path_holding_no_worktree(repo: TestRepo) {
));
}
-/// A worktree directory deleted and *recreated* is reported, not carried into
-/// git's own validation failure.
-///
-/// It is a stale registration either way, but only the absent spelling can be
-/// cleaned up here: `prune_worktree_entry` unregisters with `git worktree
-/// remove`, which skips its validation only while the directory is gone. With
-/// a directory sitting there git refuses — `--force` included — so the answer
-/// is the message naming the repo-wide `git worktree prune` that does clear
-/// it. `test_remove_pruned_worktree_directory_missing` covers the absent half,
-/// which still removes without a prompt.
+/// A worktree directory deleted and *recreated* is a stale registration like
+/// one deleted outright, and is cleaned up the same way: the entry is
+/// unregistered and the branch removed, while the directory itself stays.
+/// `git worktree remove` refuses this entry, `--force` included, so handing
+/// it to git would surface as a raw `exit 128`.
+/// `test_remove_pruned_worktree_directory_missing` covers the absent half.
#[rstest]
fn test_remove_worktree_directory_recreated(mut repo: TestRepo) {
let worktree_path = repo.add_worktree("feature");
@@ -540,6 +536,67 @@ fn test_remove_worktree_directory_recreated(mut repo: TestRepo) {
std::fs::create_dir_all(&worktree_path).unwrap();
assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["feature"], None));
+ assert!(
+ worktree_path.is_dir(),
+ "the recreated directory should stay"
+ );
+}
+
+/// A stale worktree whose registration holds staged changes is refused, with
+/// the repair that restores it; `--force` discards them as it discards a live
+/// worktree's uncommitted changes.
+#[rstest]
+fn test_remove_stale_worktree_holding_staged_changes(mut repo: TestRepo) {
+ let wt_path = repo.add_worktree("feature");
+ std::fs::write(wt_path.join("new.txt"), "work").unwrap();
+ repo.run_git_in(&wt_path, &["add", "new.txt"]);
+ std::fs::remove_file(wt_path.join(".git")).unwrap();
+
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["feature"], None));
+
+ let output = repo
+ .wt_command()
+ .args(["remove", "-f", "feature", "--yes"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let list = repo.git_output(&["worktree", "list", "--porcelain"]);
+ assert!(!list.contains("prunable"), "worktrees:\n{list}");
+ assert!(
+ wt_path.join("new.txt").is_file(),
+ "the directory's files stay"
+ );
+}
+
+/// A detached stale entry has no branch for the removal to fall back to, so
+/// `wt remove` reports it rather than removing it; `wt step prune` is what
+/// unregisters one.
+#[rstest]
+fn test_remove_stale_detached_worktree_reports_it(repo: TestRepo) {
+ let wt_path = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("repo.detached-stale");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "--detach",
+ wt_path.to_str().unwrap(),
+ "HEAD",
+ ]);
+ std::fs::remove_dir_all(&wt_path).unwrap();
+
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "remove",
+ &["../repo.detached-stale"],
+ None
+ ));
}
/// A registration whose directory now holds a *different* repository is not
@@ -4799,7 +4856,7 @@ fn test_remove_pruned_dir_with_sibling_checkout_retains_branch(mut repo: TestRep
assert_branch_exists(&repo, "feature", true, &stderr);
assert_not_orphaned(&repo, &survivor, &stderr);
assert!(
- stderr.contains("pruned")
+ stderr.contains("Pruned stale worktree")
&& stderr.contains("retained")
&& stderr.contains("still checked out"),
"output should report the prune and explain the branch was retained\nstderr:\n{stderr}",
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_errors.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_errors.snap
index 50ee1b283..5296703dc 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_errors.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_errors.snap
@@ -43,9 +43,32 @@ expression: render_cases(cases)
## worktree missing
-✗ Worktree directory missing for stale-branch
+✗ Worktree for stale-branch is stale; its directory or .git is gone
↳ To clean up, run git worktree prune
+## worktree missing its .git, directory remaining at a path needing quotes
+
+✗ Worktree for stale-branch is stale; its directory or .git is gone
+↳ To restore the worktree, run git worktree repair '/tmp/my repo.stale-branch'
+
+## stale worktree holding staged changes
+
+✗ Worktree for stale-branch is stale but holds staged changes
+↳ To discard the stale worktree, run wt remove -f stale-branch; to restore it, run git worktree repair /tmp/repo.stale-branch
+
+## stale worktree mid-operation, directory gone, at a path needing quotes
+
+✗ Worktree for stale-branch is stale with a merge in progress
+↳ To discard the stale worktree, run wt remove -f stale-branch; to restore it, recreate its directory, then run git worktree repair '/tmp/my repo.stale-branch'
+✗ Worktree for stale-branch is stale with a rebase in progress
+↳ To discard the stale worktree, run wt remove -f stale-branch; to restore it, recreate its directory, then run git worktree repair '/tmp/my repo.stale-branch'
+✗ Worktree for stale-branch is stale with a cherry-pick in progress
+↳ To discard the stale worktree, run wt remove -f stale-branch; to restore it, recreate its directory, then run git worktree repair '/tmp/my repo.stale-branch'
+✗ Worktree for stale-branch is stale with a revert in progress
+↳ To discard the stale worktree, run wt remove -f stale-branch; to restore it, recreate its directory, then run git worktree repair '/tmp/my repo.stale-branch'
+✗ Worktree for stale-branch is stale with a bisect in progress
+↳ To discard the stale worktree, run wt remove -f stale-branch; to restore it, recreate its directory, then run git worktree repair '/tmp/my repo.stale-branch'
+
## no worktree at a leftover directory
✗ No worktree @ /tmp/repo/.claude/worktrees/ghost
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index eee51479d..ed0daceac 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -690,29 +690,37 @@ fn test_prune_stale_detached_worktree(repo: TestRepo) {
);
}
-/// Prune leaves a detached entry registered when git calls it prunable only
-/// because the `.git` file inside its directory went, and removes the rest.
-/// `git worktree remove` refuses an entry whose directory remains, so selecting
-/// it would fail the whole prune with git's `validation failed` error.
+/// Prune unregisters a stale entry whose directory remains, as `git worktree
+/// prune` does, and leaves the directory and its files in place. Git calls an
+/// entry prunable once the `.git` file inside it goes, which a temp-dir sweep
+/// that deletes idle files and keeps directories does. `git worktree remove`
+/// refuses such an entry, so handing it to git would fail the whole prune with
+/// git's `validation failed` error.
#[rstest]
-fn test_prune_keeps_stale_detached_entry_whose_directory_remains(mut repo: TestRepo) {
+fn test_prune_unregisters_stale_entries_whose_directory_remains(mut repo: TestRepo) {
repo.commit("initial");
- repo.add_worktree("merged");
-
- let wt_path = repo.root_path().parent().unwrap().join("repo.dotgit-gone");
+ let branch_path = repo.add_worktree("dotgit-gone");
+ let detached_path = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("repo.detached-dotgit-gone");
repo.run_git(&[
"worktree",
"add",
"--detach",
- wt_path.to_str().unwrap(),
+ detached_path.to_str().unwrap(),
"HEAD",
]);
- std::fs::remove_file(wt_path.join(".git")).unwrap();
+ for path in [&branch_path, &detached_path] {
+ std::fs::remove_file(path.join(".git")).unwrap();
+ std::fs::write(path.join("leftover.txt"), "kept").unwrap();
+ }
let list_before = repo.git_output(&["worktree", "list", "--porcelain"]);
- let wt_path_str = porcelain_worktree_path(&list_before, "repo.dotgit-gone");
- assert!(
- list_before.contains("prunable") && wt_path.is_dir(),
- "git should report the entry prunable with its directory intact; worktrees:\n{list_before}"
+ assert_eq!(
+ list_before.matches("prunable").count(),
+ 2,
+ "git should report both entries prunable; worktrees:\n{list_before}"
);
let output = repo
@@ -733,15 +741,87 @@ fn test_prune_keeps_stale_detached_entry_whose_directory_remains(mut repo: TestR
assert!(output.status.success(), "prune failed\nstderr:\n{stderr}");
let items: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();
- let branches: Vec<_> = items.iter().map(|item| item["branch"].as_str()).collect();
- assert_eq!(branches, [Some("merged")], "stderr:\n{stderr}");
+ let mut pruned: Vec<_> = items
+ .iter()
+ .map(|item| (item["kind"].as_str(), item["branch"].as_str()))
+ .collect();
+ pruned.sort();
+ assert_eq!(
+ pruned,
+ [
+ (Some("branch_only"), Some("dotgit-gone")),
+ (Some("stale_worktree"), None)
+ ],
+ "stderr:\n{stderr}"
+ );
let list_after = repo.git_output(&["worktree", "list", "--porcelain"]);
assert!(
- list_after.contains(wt_path_str),
- "the entry should stay registered; worktrees:\n{list_after}"
+ !list_after.contains("prunable"),
+ "both entries should be unregistered; worktrees:\n{list_after}"
+ );
+ for path in [&branch_path, &detached_path] {
+ assert!(
+ path.join("leftover.txt").is_file(),
+ "{} should keep its files",
+ path.display()
+ );
+ }
+}
+
+/// Prune keeps a stale entry whose registration holds what unregistering it
+/// would destroy — staged changes, or a git operation partway through — and
+/// removes a clean one beside them. `git worktree repair` can bring either
+/// back only while the registration survives.
+#[rstest]
+fn test_prune_keeps_stale_entries_holding_work(mut repo: TestRepo) {
+ repo.commit("initial");
+ repo.add_worktree("merged");
+ std::fs::remove_dir_all(repo.worktree_path("merged")).unwrap();
+
+ // Staged work, and only the `.git` file gone: the shape repair restores.
+ let staged = repo.add_worktree("staged");
+ std::fs::write(staged.join("new.txt"), "work").unwrap();
+ repo.run_git_in(&staged, &["add", "new.txt"]);
+ std::fs::remove_file(staged.join(".git")).unwrap();
+
+ let bisecting = repo.root_path().parent().unwrap().join("repo.bisecting");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "--detach",
+ bisecting.to_str().unwrap(),
+ "HEAD",
+ ]);
+ repo.run_git_in(&bisecting, &["bisect", "start"]);
+ std::fs::remove_dir_all(&bisecting).unwrap();
+
+ let output = repo
+ .wt_command()
+ .args([
+ "step",
+ "prune",
+ "--yes",
+ "--min-age=0s",
+ "--format=json",
+ "--foreground",
+ ])
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr)
+ .ansi_strip()
+ .into_owned();
+ assert!(output.status.success(), "prune failed\nstderr:\n{stderr}");
+
+ let items: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();
+ let branches: Vec<_> = items.iter().map(|item| item["branch"].as_str()).collect();
+ assert_eq!(branches, [Some("merged")], "stderr:\n{stderr}");
+ let list = repo.git_output(&["worktree", "list", "--porcelain"]);
+ assert_eq!(
+ list.matches("prunable").count(),
+ 2,
+ "the entries holding work should stay registered; worktrees:\n{list}"
);
- assert!(wt_path.is_dir(), "the directory should be left in place");
}
/// Min-age check passes when worktrees are old enough.
@@ -1754,32 +1834,47 @@ fn test_prune_fallback_config_race_canary(mut repo: TestRepo) {
/// A stale worktree entry whose metadata prune fails at execution surfaces
/// the failure rather than pretending the candidate was removed: the scan
/// records the prune in the plan (`prune_entry`), execution runs it before
-/// the branch deletion, and its error fails the run — the branch and the
-/// entry both survive intact. A `git` shim failing `worktree remove` is the
-/// deterministic trigger. Unix-only for the same `CreateProcess` reason as
-/// the canary shim above.
+/// the branch deletion, and its error fails the run — the branch survives and
+/// the entry stays registered. A read-only registration directory is the
+/// deterministic trigger: its files can't be unlinked. Unix-only, since the
+/// trigger is a permission bit.
#[cfg(unix)]
#[rstest]
fn test_prune_surfaces_failing_metadata_prune(mut repo: TestRepo) {
+ use std::os::unix::fs::PermissionsExt;
+
repo.commit("initial");
// Integrated branch whose worktree directory is deleted out-of-band → a
// stale (prunable) worktree entry, prune's `Prunable` check source.
- repo.add_worktree("stale-merged");
- std::fs::remove_dir_all(repo.worktree_path("stale-merged")).unwrap();
-
- let mut cmd = repo.wt_command();
- let git_wrapper_dir = repo.home_path().join("git-wrapper");
- std::fs::create_dir_all(&git_wrapper_dir).unwrap();
- write_failing_worktree_remove_wrapper(&git_wrapper_dir, &which::which("git").unwrap());
- prepend_path(&mut cmd, &git_wrapper_dir);
- let prune_failed_marker = repo.home_path().join("worktree-remove-failed");
- cmd.env("WT_TEST_WORKTREE_REMOVE_FAILED", &prune_failed_marker);
+ let wt_path = repo.add_worktree("stale-merged");
+ std::fs::remove_dir_all(&wt_path).unwrap();
+ // Git names a registration after its worktree directory.
+ let registration = repo
+ .root_path()
+ .join(".git/worktrees")
+ .join(wt_path.file_name().unwrap());
+ assert!(registration.is_dir(), "{} missing", registration.display());
+ let set_mode = |mode| {
+ std::fs::set_permissions(&registration, std::fs::Permissions::from_mode(mode)).unwrap()
+ };
+ set_mode(0o555);
+ // Skip if running as root: euid 0 ignores DAC mode bits, so the deletion
+ // would succeed. Probe with a write the mode should refuse.
+ let probe = registration.join("probe");
+ if std::fs::write(&probe, "").is_ok() {
+ let _ = std::fs::remove_file(&probe);
+ set_mode(0o755);
+ eprintln!("Skipping - running with elevated privileges");
+ return;
+ }
- let output = cmd
+ let output = repo
+ .wt_command()
.args(["step", "prune", "--yes", "--min-age=0s"])
.output()
.unwrap();
+ set_mode(0o755);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
@@ -1790,11 +1885,6 @@ fn test_prune_surfaces_failing_metadata_prune(mut repo: TestRepo) {
stderr.contains("stale-merged"),
"the error must name the failed candidate.\nstderr:\n{stderr}"
);
- assert!(
- prune_failed_marker.exists(),
- "the shim never fired — the metadata prune was not exercised"
- );
- // Nothing half-done: the entry is still registered and the branch intact.
let list = repo.git_output(&["worktree", "list", "--porcelain"]);
assert!(
list.contains("prunable"),
@@ -1807,6 +1897,51 @@ fn test_prune_surfaces_failing_metadata_prune(mut repo: TestRepo) {
);
}
+/// A stale entry is unregistered before its branch is deleted, so it goes
+/// even when the branch deletion loses its compare-and-swap: prune reports the
+/// pruned entry, then the kept branch. The shim fails the CAS delete and leaves
+/// the ref, which is how a branch that moved during deletion reads.
+#[cfg(unix)]
+#[rstest]
+fn test_prune_unregisters_stale_entry_when_branch_delete_races(mut repo: TestRepo) {
+ repo.commit("initial");
+ let wt_path = repo.add_worktree("stale-raced");
+ std::fs::remove_dir_all(&wt_path).unwrap();
+
+ let mut cmd = repo.wt_command();
+ let git_wrapper_dir = repo.home_path().join("git-wrapper");
+ std::fs::create_dir_all(&git_wrapper_dir).unwrap();
+ write_failing_branch_delete_wrapper(&git_wrapper_dir, &which::which("git").unwrap());
+ prepend_path(&mut cmd, &git_wrapper_dir);
+ cmd.env("WT_TEST_FAIL_DELETE_BRANCH", "stale-raced");
+ cmd.env("WT_TEST_FAIL_DELETE_KEEPS_REF", "1");
+
+ let output = cmd
+ .args(["step", "prune", "--yes", "--min-age=0s"])
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr)
+ .ansi_strip()
+ .into_owned();
+
+ assert!(output.status.success(), "prune failed\nstderr:\n{stderr}");
+ assert!(
+ stderr.contains("Pruned stale worktree for stale-raced")
+ && stderr.contains("moved during deletion"),
+ "prune should report the pruned entry and the kept branch\nstderr:\n{stderr}"
+ );
+ let list = repo.git_output(&["worktree", "list", "--porcelain"]);
+ assert!(
+ !list.contains("prunable"),
+ "the entry should be unregistered; worktrees:\n{list}"
+ );
+ let branches = repo.git_output(&["branch", "--format=%(refname:short)"]);
+ assert!(
+ branches.lines().any(|branch| branch == "stale-raced"),
+ "the raced branch should be kept; branches:\n{branches}"
+ );
+}
+
/// `--dry-run` mutates nothing, even though the scan now plans stale entries
/// through `prepare_worktree_removal` like every other source: planning is
/// pure — the metadata prune rides the plan and only execution performs it.
@@ -1909,113 +2044,6 @@ fn test_prune_removals_run_concurrently(repo: TestRepo) {
}
}
-/// The removals that unregister stale worktree metadata serialize through the
-/// repository registry lock — one `git worktree remove` teardown at a time.
-///
-/// Four stale entries: two carrying a branch (`BranchOnly` plans whose
-/// `prune_entry` executes the prune) and two detached (`StaleDetached`, which
-/// prune in place of a removal). Each unregisters its own metadata with
-/// `git worktree remove <path>`, which enumerates every sibling's `commondir`
-/// as it resolves its target — so two overlapping teardowns can read an entry
-/// another worker is mid-deleting and fail (issue #3661). The shim probes for
-/// that overlap with an atomic `mkdir` lock held across a fixed window around
-/// each teardown; serialized, no two ever hold it at once, so the test asserts
-/// no `overlap-` sentinel appears (and every entry still pruned). If the lock
-/// regressed, all four teardowns would fire at once and three would collide in
-/// the window. Unix-only for the same `CreateProcess` shim reason as the canary
-/// above.
-///
-/// `--foreground` runs both ways. It reserves `check_lock`'s write side for the
-/// TTY trash-cleanup spinner, which only a worktree removal paints; every
-/// candidate here plans a branch deletion or a bare prune, so the flag changes
-/// nothing — the registry teardowns serialize inside `Repository` regardless.
-#[cfg(unix)]
-#[rstest]
-fn test_prune_metadata_removals_serialize(
- mut repo: TestRepo,
- #[values(false, true)] foreground: bool,
-) {
- repo.commit("initial");
-
- // At main HEAD, so every entry is same-commit integrated.
- let mut stale = vec![repo.add_worktree("stale-a"), repo.add_worktree("stale-b")];
- for name in ["det-a", "det-b"] {
- let path = repo
- .root_path()
- .parent()
- .unwrap()
- .join(format!("repo.{name}"));
- repo.run_git(&[
- "worktree",
- "add",
- "--detach",
- path.to_str().unwrap(),
- "HEAD",
- ]);
- stale.push(path);
- }
- for path in &stale {
- std::fs::remove_dir_all(path).unwrap();
- }
-
- let mut cmd = repo.wt_command();
- // The removal pool is sized from the rayon thread count; pin it to four so
- // all four teardowns would run at once if the registry lock regressed (the
- // workers block in subprocess waits, so four threads don't need four CPUs).
- cmd.env("RAYON_NUM_THREADS", "4");
- let git_wrapper_dir = repo.home_path().join("git-wrapper");
- std::fs::create_dir_all(&git_wrapper_dir).unwrap();
- write_overlap_probe_worktree_remove_wrapper(&git_wrapper_dir, &which::which("git").unwrap());
- prepend_path(&mut cmd, &git_wrapper_dir);
- let barrier_dir = repo.home_path().join("barrier");
- std::fs::create_dir_all(&barrier_dir).unwrap();
- cmd.env("WT_TEST_BARRIER_DIR", &barrier_dir);
-
- cmd.args(["step", "prune", "--yes", "--min-age=0s"]);
- if foreground {
- cmd.arg("--foreground");
- }
- let output = cmd.output().unwrap();
- let stderr = String::from_utf8_lossy(&output.stderr);
-
- assert!(output.status.success(), "prune should succeed:\n{stderr}");
- let sentinels: Vec<String> = std::fs::read_dir(&barrier_dir)
- .unwrap()
- .filter_map(|e| e.ok())
- .map(|e| e.file_name().to_string_lossy().into_owned())
- .collect();
- let started: Vec<&String> = sentinels
- .iter()
- .filter(|n| n.starts_with("started-"))
- .collect();
- assert_eq!(
- started.len(),
- stale.len(),
- "every stale entry should have pruned its own metadata: {started:?}"
- );
- let overlaps: Vec<&String> = sentinels
- .iter()
- .filter(|n| n.starts_with("overlap-"))
- .collect();
- assert!(
- overlaps.is_empty(),
- "two `git worktree remove` teardowns overlapped — the repository registry \
- lock did not serialize them (issue #3661): {overlaps:?}"
- );
- let list = repo.git_output(&["worktree", "list", "--porcelain"]);
- assert!(
- !list.contains("prunable"),
- "every stale entry should be unregistered; worktrees:\n{list}"
- );
- let branches = repo.git_output(&["branch", "--format=%(refname:short)"]);
- for name in ["stale-a", "stale-b"] {
- assert!(
- !branches.lines().any(|branch| branch == name),
- "{name} should have been deleted; branches:\n{branches}"
- );
- }
-}
-
/// The first failing removal aborts the rest of the queue.
///
/// Three integrated orphan branches scan in sorted order (`abort-a` first)
@@ -2123,10 +2151,11 @@ fn test_prune_concurrent_removal_failures_report_first(repo: TestRepo) {
);
}
-/// A `git` shim that deletes `refs/heads/$WT_TEST_FAIL_DELETE_BRANCH` for
-/// real and then reports failure when prune's CAS delete targets it —
-/// making `cas_delete_branch_outcome` propagate an error (ref gone on
-/// re-check) instead of `RetainedRaced` (ref still present).
+/// A `git` shim that fails prune's CAS delete of
+/// `refs/heads/$WT_TEST_FAIL_DELETE_BRANCH`. By default it deletes the ref for
+/// real first, making `cas_delete_branch_outcome` propagate an error (ref gone
+/// on re-check); with `WT_TEST_FAIL_DELETE_KEEPS_REF` set it leaves the ref,
+/// which reads as `RetainedRaced` (a branch that moved during deletion).
#[cfg(unix)]
fn write_failing_branch_delete_wrapper(dir: &std::path::Path, real_git: &std::path::Path) {
use std::os::unix::fs::PermissionsExt;
@@ -2135,7 +2164,7 @@ fn write_failing_branch_delete_wrapper(dir: &std::path::Path, real_git: &std::pa
let script = format!(
r#"#!/bin/sh
if [ "$1" = "update-ref" ] && [ "$2" = "-d" ] && [ "$3" = "refs/heads/$WT_TEST_FAIL_DELETE_BRANCH" ]; then
- {real_git} update-ref -d "$3" || true
+ [ -n "$WT_TEST_FAIL_DELETE_KEEPS_REF" ] || {real_git} update-ref -d "$3" || true
exit 1
fi
exec {real_git} "$@"
@@ -2183,42 +2212,6 @@ exit 1
std::fs::set_permissions(&path, permissions).unwrap();
}
-/// A `git` shim whose `worktree remove` arms a probe for overlap (see
-/// `test_prune_metadata_removals_serialize`): each records that it started,
-/// then takes an atomic `mkdir` lock for a fixed window. Under the registry
-/// serialization this is testing, no two teardowns ever hold it at once, so a
-/// failed `mkdir` — a concurrent teardown mid-window — drops an `overlap-`
-/// sentinel the test asserts absent. Everything else passes through to the real
-/// git.
-#[cfg(unix)]
-fn write_overlap_probe_worktree_remove_wrapper(dir: &std::path::Path, real_git: &std::path::Path) {
- use std::os::unix::fs::PermissionsExt;
-
- let real_git = shell_escape::unix::escape(real_git.to_string_lossy());
- let script = format!(
- r#"#!/bin/sh
-case "$1 $2" in
- "worktree remove") ;;
- *) exec {real_git} "$@" ;;
-esac
-own=$(basename "$3")
-: > "$WT_TEST_BARRIER_DIR/started-$own"
-if mkdir "$WT_TEST_BARRIER_DIR/active" 2>/dev/null; then
- sleep 0.2
- rmdir "$WT_TEST_BARRIER_DIR/active"
-else
- : > "$WT_TEST_BARRIER_DIR/overlap-$own"
-fi
-exec {real_git} "$@"
-"#
- );
- let path = dir.join("git");
- std::fs::write(&path, script).unwrap();
- let mut permissions = std::fs::metadata(&path).unwrap().permissions();
- permissions.set_mode(0o755);
- std::fs::set_permissions(&path, permissions).unwrap();
-}
-
/// A `git` shim that holds the reflog read for `refs/heads/packed-b` until
/// `update-ref -d refs/heads/packed-a` has finished (see
/// `test_prune_removals_keep_packed_branch_ages`); everything else passes
@@ -2296,30 +2289,6 @@ exec {real_git} "$@"
std::fs::set_permissions(&path, permissions).unwrap();
}
-/// A `git` shim that fails every `git worktree remove` and passes everything
-/// else through to the real git.
-#[cfg(unix)]
-fn write_failing_worktree_remove_wrapper(dir: &std::path::Path, real_git: &std::path::Path) {
- use std::os::unix::fs::PermissionsExt;
-
- let real_git = shell_escape::unix::escape(real_git.to_string_lossy());
- let script = format!(
- r#"#!/bin/sh
-if [ "$1" = "worktree" ] && [ "$2" = "remove" ]; then
- : > "$WT_TEST_WORKTREE_REMOVE_FAILED"
- echo "shim: worktree remove disabled" >&2
- exit 1
-fi
-exec {real_git} "$@"
-"#
- );
- let path = dir.join("git");
- std::fs::write(&path, script).unwrap();
- let mut permissions = std::fs::metadata(&path).unwrap().permissions();
- permissions.set_mode(0o755);
- std::fs::set_permissions(&path, permissions).unwrap();
-}
-
#[cfg(unix)]
fn prepend_path(cmd: &mut std::process::Command, dir: &std::path::Path) {
let (path_var_name, current_path) = std::env::vars_os()
diff --git a/tests/integration_tests/step_relocate.rs b/tests/integration_tests/step_relocate.rs
index e8e94754e..47d39e7fc 100644
--- a/tests/integration_tests/step_relocate.rs
+++ b/tests/integration_tests/step_relocate.rs
@@ -1556,7 +1556,7 @@ fn step_relocate_rejects_prunable_worktree(mut repo: TestRepo) {
assert!(!output.status.success(), "a prunable worktree should fail");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
- stderr.contains("directory is gone"),
+ stderr.contains("it is stale"),
"expected a prunable-worktree error, got: {stderr}"
);
}
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_long.snap b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
index 7cf443746..4f803f490 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
@@ -234,7 +234,7 @@ An in-progress git operation, a worktree-location attribute, or a branch with no
────── ─────────────────────────────────────────────────────────────────────── ───────────────────────────────────────────────────
✘ worktree.changes.conflicted Merge conflicts
↻ worktree.operation "rebase", "merge", "cherry_pick", "revert", "bisect" A git operation is in progress; git status names it
- ⊟ worktree.prunable Prunable (worktree directory missing)
+ ⊟ worktree.prunable Prunable (worktree directory or its .git gone)
⊞ worktree.locked Locked worktree
⊘ worktree.detached Detached HEAD
⚑ worktree.duplicate_branch Branch checked out in more than one worktree
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
index a6eb7d0b7..57c6edb89 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
@@ -285,7 +285,8 @@ An in-progress git operation, a worktree-location attribute, or a branch with no
"rebase", "merge", names it
"cherry_pick", "revert",
"bisect"
- ⊟ worktree.prunable Prunable (worktree directory missing)
+ ⊟ worktree.prunable Prunable (worktree directory or its .git
+ gone)
⊞ worktree.locked Locked worktree
⊘ worktree.detached Detached HEAD
⚑ worktree.duplicate_branch Branch checked out in more than one worktree
diff --git a/tests/snapshots/integration__integration_tests__push__push_target_worktree_missing.snap b/tests/snapshots/integration__integration_tests__push__push_target_worktree_missing.snap
index 032120f47..cdfb56864 100644
--- a/tests/snapshots/integration__integration_tests__push__push_target_worktree_missing.snap
+++ b/tests/snapshots/integration__integration_tests__push__push_target_worktree_missing.snap
@@ -60,5 +60,5 @@ exit_code: 1
----- stdout -----
----- stderr -----
-✗ Worktree directory missing for main
+✗ Worktree for main is stale; its directory or .git is gone
↳ To clean up, run git worktree prune
diff --git a/tests/snapshots/integration__integration_tests__push__push_target_worktree_missing_no_ff.snap b/tests/snapshots/integration__integration_tests__push__push_target_worktree_missing_no_ff.snap
index 0a349e4d5..479522ec3 100644
--- a/tests/snapshots/integration__integration_tests__push__push_target_worktree_missing_no_ff.snap
+++ b/tests/snapshots/integration__integration_tests__push__push_target_worktree_missing_no_ff.snap
@@ -61,5 +61,5 @@ exit_code: 1
----- stdout -----
----- stderr -----
-✗ Worktree directory missing for main
+✗ Worktree for main is stale; its directory or .git is gone
↳ To clean up, run git worktree prune
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
index 20cf35996..14ff428b9 100644
--- 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
@@ -60,4 +60,4 @@ exit_code: 0
----- stdout -----
----- stderr -----
-○ Worktree directory missing for feature-pruned-keep; pruned
+✓ Pruned stale worktree for feature-pruned-keep
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_pruned_worktree_unmerged_branch.snap b/tests/snapshots/integration__integration_tests__remove__remove_pruned_worktree_unmerged_branch.snap
index ef9a718f8..9d26fbf87 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_pruned_worktree_unmerged_branch.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_pruned_worktree_unmerged_branch.snap
@@ -59,6 +59,6 @@ exit_code: 0
----- stdout -----
----- stderr -----
-○ Worktree directory missing for feature-pruned-unmerged; pruned
+✓ Pruned stale worktree for feature-pruned-unmerged
○ Branch feature-pruned-unmerged retained; has unmerged changes
↳ To delete the unmerged branch, run wt remove -D feature-pruned-unmerged
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_stale_detached_worktree_reports_it.snap b/tests/snapshots/integration__integration_tests__remove__remove_stale_detached_worktree_reports_it.snap
new file mode 100644
index 000000000..f4bc44a60
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_stale_detached_worktree_reports_it.snap
@@ -0,0 +1,63 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "../repo.detached-stale"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Worktree for repo.detached-stale is stale; its directory or .git is gone
+↳ To clean up, run git worktree prune
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_stale_worktree_holding_staged_changes.snap b/tests/snapshots/integration__integration_tests__remove__remove_stale_worktree_holding_staged_changes.snap
new file mode 100644
index 000000000..539d40341
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_stale_worktree_holding_staged_changes.snap
@@ -0,0 +1,63 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Worktree for feature is stale but holds staged changes
+↳ To discard the stale worktree, run wt remove -f feature; to restore it, run git worktree repair _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_worktree_directory_recreated.snap b/tests/snapshots/integration__integration_tests__remove__remove_worktree_directory_recreated.snap
index 818d07035..7e769a4cf 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_worktree_directory_recreated.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_worktree_directory_recreated.snap
@@ -54,10 +54,9 @@ info:
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
-success: false
-exit_code: 1
+success: true
+exit_code: 0
----- stdout -----
----- stderr -----
-✗ Worktree directory missing for feature
-↳ To clean up, run git worktree prune
+✓ Pruned stale worktree & removed branch feature (same commit as main, _)
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_error_missing_directory.snap b/tests/snapshots/integration__integration_tests__switch__switch_error_missing_directory.snap
index 47d5cd1cb..0129bd87c 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_error_missing_directory.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_error_missing_directory.snap
@@ -59,5 +59,5 @@ exit_code: 1
----- stdout -----
----- stderr -----
-✗ Worktree directory missing for missing-wt
+✗ Worktree for missing-wt is stale; its directory or .git is gone
↳ To clean up, run git worktree prune
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_missing.snap b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_missing.snap
index e166c2e8b..777c55486 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_missing.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_missing.snap
@@ -60,5 +60,5 @@ exit_code: 1
----- stdout -----
----- stderr -----
-✗ Worktree directory missing for feature/collision
+✗ Worktree for feature/collision is stale; its directory or .git is gone
↳ To clean up, run git worktree prune
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_worktree_directory_recreated.snap b/tests/snapshots/integration__integration_tests__switch__switch_worktree_directory_recreated.snap
index 316fe49a5..6b9fd73d7 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_worktree_directory_recreated.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_worktree_directory_recreated.snap
@@ -59,5 +59,5 @@ exit_code: 1
----- stdout -----
----- stderr -----
-✗ Worktree directory missing for feature
-↳ To clean up, run git worktree prune
+✗ Worktree for feature is stale; its directory or .git is gone
+↳ To restore the worktree, run git worktree repair _REPO_.feature