Skip to content

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

fix(worktree): guard a registered path that no longer holds its worktree (#3785)

Maximilian Rooscf822f75cf19
diff --git a/docs/content/faq.md b/docs/content/faq.md
index 565aaa4b2..d2ce419dd 100644
--- a/docs/content/faq.md
+++ b/docs/content/faq.md
@@ -177,6 +177,8 @@ Worktrunk can delete **worktrees** and **branches**. Both have safeguards.
`wt remove` mirrors `git worktree remove`: it refuses to remove worktrees with uncommitted changes (staged, modified, or untracked files). The `--force` flag removes the worktree anyway, discarding all of those changes.
+Removal also refuses, `--force` included, when the directory at a registered path has come to hold a *different* repository — a clone made there after the worktree was deleted, say. `--force` waives uncommitted changes, not the check for whose directory it is, and `git worktree remove` refuses the same case.
+
To protect a worktree from removal entirely (say it holds a local database), lock it:
{{ terminal(cmd="git worktree lock ../myproject.feature --reason __WT_QUOT__Contains local database__WT_QUOT__") }}
diff --git a/plugins/worktrunk/skills/worktrunk/reference/faq.md b/plugins/worktrunk/skills/worktrunk/reference/faq.md
index 34c7d9b6b..2f2d7c5a6 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/faq.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/faq.md
@@ -170,6 +170,8 @@ Worktrunk can delete **worktrees** and **branches**. Both have safeguards.
`wt remove` mirrors `git worktree remove`: it refuses to remove worktrees with uncommitted changes (staged, modified, or untracked files). The `--force` flag removes the worktree anyway, discarding all of those changes.
+Removal also refuses, `--force` included, when the directory at a registered path has come to hold a *different* repository — a clone made there after the worktree was deleted, say. `--force` waives uncommitted changes, not the check for whose directory it is, and `git worktree remove` refuses the same case.
+
To protect a worktree from removal entirely (say it holds a local database), lock it:
```bash
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index 34c7d9b6b..2f2d7c5a6 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -170,6 +170,8 @@ Worktrunk can delete **worktrees** and **branches**. Both have safeguards.
`wt remove` mirrors `git worktree remove`: it refuses to remove worktrees with uncommitted changes (staged, modified, or untracked files). The `--force` flag removes the worktree anyway, discarding all of those changes.
+Removal also refuses, `--force` included, when the directory at a registered path has come to hold a *different* repository — a clone made there after the worktree was deleted, say. `--force` waives uncommitted changes, not the check for whose directory it is, and `git worktree remove` refuses the same case.
+
To protect a worktree from removal entirely (say it holds a local database), lock it:
```bash
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index d0cf5346c..ffb776484 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -260,7 +260,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
}
// Worktree for target is optional: if present we use it for safety checks and as destination.
- let target_worktree_path = repo.worktree_for_branch(&target_branch)?;
+ let target_worktree_path = repo.usable_worktree_for_branch(&target_branch)?;
// Where `post-merge` / `post-remove` / `post-switch` run: the target
// branch's worktree if it exists, else the primary worktree. Mirrors
// `finish_after_merge`'s destination resolution. (Config is resolved from
diff --git a/src/commands/remove.rs b/src/commands/remove.rs
index 59a4e295e..2d1e7545f 100644
--- a/src/commands/remove.rs
+++ b/src/commands/remove.rs
@@ -7,7 +7,7 @@ use std::path::Path;
use anyhow::Context;
use worktrunk::HookType;
use worktrunk::config::UserConfig;
-use worktrunk::git::{BranchDeletionMode, ErrorExt, Repository, ResolvedWorktree};
+use worktrunk::git::{BranchDeletionMode, ErrorExt, GitError, Repository, ResolvedWorktree};
use worktrunk::styling::{eprintln, info_message};
use crate::cli::{RemoveArgs, SwitchFormat};
@@ -126,19 +126,17 @@ fn validate_remove_targets(
// otherwise (see its shared-branch handling).
RemoveTarget::WorktreePath(path_canonical)
}
+ ResolvedWorktree::BranchOnly { branch } => RemoveTarget::BranchOnly(branch),
// Resolution tried the argument as a branch and as a worktree path
// and matched neither, so a directory sitting there is a leftover
- // skeleton rather than anything wt can remove. Reported here, where
- // the user's own token is still in hand — the picker and `wt step
- // prune` reach `prepare_worktree_removal` with a branch read off a
- // row, which is nobody's typed path.
- ResolvedWorktree::BranchOnly { branch } => match repo.path_selector_error(&branch) {
- Some(err) => {
- plans.record_error(err.into());
- continue;
- }
- None => RemoveTarget::BranchOnly(branch),
- },
+ // skeleton rather than anything wt can remove. Only a typed
+ // selector reaches this arm — the picker and `wt step prune` call
+ // `prepare_worktree_removal` with a branch read off a row, which is
+ // nobody's path.
+ ResolvedWorktree::NoWorktreeAtPath { path } => {
+ plans.record_error(GitError::WorktreeNotFoundAtPath { path }.into());
+ continue;
+ }
};
match repo.prepare_worktree_removal(
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index eae428f25..1b308fe58 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -238,6 +238,11 @@ impl RepositoryCliExt for Repository {
// 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()
{
@@ -245,6 +250,22 @@ impl RepositoryCliExt for Repository {
pruned_from: Some(wt.path.clone()),
branch: branch.to_string(),
}
+ } else if wt.is_prunable() {
+ // Registered, directory present, but it no longer holds
+ // this worktree — deleted and recreated, which is what an
+ // interrupted `wt switch` leaves behind. Neither route out
+ // of here works: the cleanup above needs the directory
+ // gone, and the removal below walks into git's own
+ // validation a few calls later, reaching the user as a raw
+ // `exit 128`. Only the repo-wide `git worktree prune`
+ // clears this one, and the hint names it.
+ return Err(GitError::WorktreeMissing {
+ branch: wt
+ .branch
+ .clone()
+ .unwrap_or_else(|| wt.dir_name().to_string()),
+ }
+ .into());
} else {
let is_current = worktrunk::path::paths_match(&wt.path, current_path);
Resolved::Worktree {
@@ -326,6 +347,21 @@ impl RepositoryCliExt for Repository {
// Phase 5: Remaining worktree-level validation.
let target_wt = self.worktree_at(&worktree_path);
+ // Ownership first: `ensure_clean` below runs `git status` in the
+ // directory, so against a foreign occupant it reports that
+ // repository's dirt as this worktree's and points at `--force`, the
+ // one flag that would carry the removal through. Planning is also
+ // upstream of the "Removing …" announcement, so the refusal arrives
+ // before wt claims to be doing it.
+ //
+ // `stage_worktree_removal` asks the same question at the rename, for
+ // the callers that reach it without planning here. That is not a
+ // re-validation of this one: `git_dir()` caches per worktree path for
+ // the process, so within a single removal the second call answers from
+ // the first. A directory swapped in between would not be caught — the
+ // same time-of-check window `ensure_clean` carries, and narrower.
+ target_wt.ensure_belongs_to_repo()?;
+
if !force_worktree {
target_wt.ensure_clean("remove worktree", branch_name.as_deref(), true)?;
}
diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rs
index 133928772..4150fa4ec 100644
--- a/src/commands/worktree/push.rs
+++ b/src/commands/worktree/push.rs
@@ -123,20 +123,13 @@ impl MergeContext {
repo.ensure_no_operation_in_progress("push")?;
let target_branch = repo.require_target_branch(target)?;
- let target_worktree_path = repo.worktree_for_branch(&target_branch)?;
+ // A registered worktree git calls prunable can't receive the sync in
+ // `advance_target` — git dies trying to cd into it. Refusing upfront
+ // gives a clear answer, and names the `git worktree prune` that clears
+ // the registration.
+ let target_worktree_path = repo.usable_worktree_for_branch(&target_branch)?;
- // A registered worktree whose directory is gone can't receive the
- // sync in `advance_target` — git dies trying to cd into it. Refusing
- // upfront gives a clear answer, and names the `git worktree prune`
- // that clears the registration.
if let Some(path) = &target_worktree_path {
- if !path.exists() {
- return Err(GitError::WorktreeMissing {
- branch: target_branch,
- }
- .into());
- }
-
// The target gets the same gate the source got above, for a
// reason the source's comment doesn't cover: `advance_target`
// syncs the target worktree with `read-tree -m -u`, which refuses
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index fe050836b..036f0e35e 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -21,7 +21,8 @@ use worktrunk::git::remote_ref::{
RemoteRefProvider, parse_ref_url,
};
use worktrunk::git::{
- ForgeKind, GitError, GitRemoteUrl, RefType, Repository, SwitchSuggestionCtx, current_or_recover,
+ ForgeKind, GitError, GitRemoteUrl, RefType, Repository, ResolvedWorktree, Selector,
+ SwitchSuggestionCtx, current_or_recover,
};
use worktrunk::shell_exec::{
ShellEscapeMode, directive_shell_escape_mode, shell_cwd, shell_escape_for,
@@ -49,8 +50,10 @@ use crate::output::{
/// Result of resolving the switch target.
struct ResolvedTarget {
- /// The resolved branch name
- branch: String,
+ /// The branch to switch to, carrying whether anything rewrote the token
+ /// the user typed — `pr:`/`mr:` dispatch and the remote-prefix strip both
+ /// do, and a rewritten token is no longer a path worth trying.
+ selector: Selector,
/// How to create the worktree
method: CreationMethod,
}
@@ -284,7 +287,7 @@ fn resolve_fork_ref(
))
);
return Ok(ResolvedTarget {
- branch: local_branch,
+ selector: Selector::rewritten_to(local_branch),
method: CreationMethod::Regular {
create_branch: false,
base_branch: None,
@@ -311,7 +314,7 @@ fn resolve_fork_ref(
))
);
return Ok(ResolvedTarget {
- branch: prefixed,
+ selector: Selector::rewritten_to(prefixed),
method: CreationMethod::Regular {
create_branch: false,
base_branch: None,
@@ -332,7 +335,7 @@ fn resolve_fork_ref(
// This is GitHub-only (GitLab doesn't support prefixed names)
let remote = remote_ref::find_remote(repo, info)?;
return Ok(ResolvedTarget {
- branch: prefixed,
+ selector: Selector::rewritten_to(prefixed),
method: CreationMethod::ForkRef {
ref_type,
number,
@@ -394,7 +397,7 @@ fn resolve_fork_ref(
};
Ok(ResolvedTarget {
- branch: local_branch,
+ selector: Selector::rewritten_to(local_branch),
method: CreationMethod::ForkRef {
ref_type,
number,
@@ -414,7 +417,7 @@ fn resolve_same_repo_ref(
fetch_same_repo_branch(repo, info)?;
Ok(ResolvedTarget {
- branch: info.source_branch.clone(),
+ selector: Selector::rewritten_to(info.source_branch.clone()),
method: CreationMethod::Regular {
create_branch: false,
base_branch: None,
@@ -464,7 +467,7 @@ fn parse_ref_shortcut(input: &str) -> Option<(RefType, u32)> {
}
/// Resolve a `--base` value, expanding `pr:`/`mr:` shortcuts. Non-shortcut
-/// inputs go through [`Repository::resolve_worktree_name`] (handles `@`/`-`/`^`).
+/// inputs go through [`Repository::expand_selector`] (handles `@`/`-`/`^`).
///
/// Returns the resolved ref plus, when the user picked a `pr:`/`mr:` shortcut
/// against a same-repo PR/MR, the `(remote, branch)` pair the new branch
@@ -488,7 +491,8 @@ fn resolve_base_ref(
None => {}
}
- let resolved = repo.resolve_worktree_name(base)?;
+ let selector = repo.expand_selector(base)?;
+ let resolved = selector.token().to_string();
if !repo.ref_exists(&resolved)? {
let remotes = repo.branch(&resolved).remotes()?;
@@ -497,8 +501,8 @@ fn resolve_base_ref(
}
// Neither a ref nor a branch on a remote: the base may be named by the
// path of the worktree it is checked out in, as targets elsewhere are.
- if resolved == base
- && let Some((_, Some(branch))) = repo.worktree_at_input_path(base)?
+ if selector.names_a_path()
+ && let Some((_, Some(branch))) = repo.worktree_at_input_path(selector.token())?
{
return Ok((branch, None));
}
@@ -571,21 +575,25 @@ fn resolve_switch_target(
None => {}
}
- // Regular branch switch
- let mut resolved_branch = repo
- .resolve_worktree_name(branch)
+ // Regular branch switch. `expand_selector` normalizes the token and
+ // expands `@` / `-` / `^`, reporting whether it rewrote anything.
+ let mut selector = repo
+ .expand_selector(branch)
.context("Failed to resolve branch name")?;
// Handle remote-tracking ref names (e.g., "origin/username/feature-1" from the picker).
// Strip the remote prefix only when there is no exact local branch/worktree,
// so a local branch literally named `origin/foo` is not retargeted to `foo`.
if !create
- && repo.worktree_for_branch(&resolved_branch)?.is_none()
- && !repo.branch(&resolved_branch).exists_locally()?
- && let Some(local_name) = repo.strip_remote_prefix(&resolved_branch)
+ && repo.worktree_for_branch(selector.token())?.is_none()
+ && !repo.branch(selector.token()).exists_locally()?
+ && let Some(local_name) = repo.strip_remote_prefix(selector.token())
{
- resolved_branch = local_name;
+ // A rewrite like any other: `origin/foo` may have been a path the user
+ // typed, but `foo` is one nobody did.
+ selector = Selector::rewritten_to(local_name);
}
+ let resolved_branch = selector.token().to_string();
// Resolve and validate base (only when --create is set)
let (resolved_base, base_pr_upstream) = if let Some(base_str) = base {
@@ -657,7 +665,14 @@ fn resolve_switch_target(
};
Ok(ResolvedTarget {
- branch: resolved_branch,
+ // Under `--create` the argument names a branch that does not exist
+ // yet, so it is not a path to look up — stated here, where `create`
+ // lives, rather than re-tested at each arm that consults it.
+ selector: if create {
+ selector.branch_only()
+ } else {
+ selector
+ },
method: CreationMethod::Regular {
create_branch: create,
base_branch,
@@ -830,55 +845,50 @@ fn plan_switch(
// Phase 1: Resolve target (handles pr:, validates --create/--base, may do network)
let target = resolve_switch_target(repo, branch, create, base)?;
- // Phase 2: Check if worktree already exists for this branch (fast path)
- // This avoids computing the worktree path template (~7 git commands) for existing switches.
- match repo.worktree_for_branch(&target.branch)? {
- Some(existing_path) if existing_path.exists() => {
- return Ok(SwitchPlan::Existing {
- path: canonicalize(&existing_path).unwrap_or(existing_path),
- branch: Some(target.branch),
- new_previous,
- });
- }
- Some(_) => {
- return Err(GitError::WorktreeMissing {
- branch: target.branch,
+ // Phase 2: the shared worktree ladder — the branch, then the argument as a
+ // worktree's own path (the way to name a detached one, which has no
+ // branch), then a verdict on what a selector matching neither was reaching
+ // for. `target.selector` carries whether Phase 1 rewrote the token, so the
+ // path arm switches itself off after a shortcut, `pr:`/`mr:`, or a stripped
+ // remote prefix.
+ //
+ // Resolving before the path template is also the fast path: an existing
+ // worktree answers without the ~7 git commands `compute_worktree_path` runs.
+ match repo.resolve_selector(&target.selector)? {
+ ResolvedWorktree::Worktree { path, branch } => {
+ // 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()),
+ }
+ .into());
}
- .into());
- }
- None => {}
- }
-
- // Phase 2b: the argument as the worktree's own path — the way to name a
- // detached worktree, which has no branch. Not under `--create`, where the
- // argument is the name of a branch that does not exist yet, and not when
- // Phase 1 rewrote the argument (a shortcut, `pr:`/`mr:`, a stripped remote
- // prefix), which is exactly when the literal token would be a nonsense path.
- if !create && target.branch == branch {
- if let Some((path, wt_branch)) = repo.worktree_at_input_path(branch)? {
- let canonical = canonicalize(&path).unwrap_or_else(|_| path.clone());
return Ok(SwitchPlan::Existing {
- path: canonical,
- branch: wt_branch,
+ path: canonicalize(&path).unwrap_or(path),
+ branch,
new_previous,
});
}
// Nothing is registered there, and a path is all the argument could
// have been — so stop here rather than carrying it to Phase 4, which
// would report a missing branch and offer to create one under a name
- // git rejects.
- if let Some(err) = repo.path_selector_error(branch) {
- return Err(err.into());
+ // git rejects. `--create` never reaches this arm: its selector says
+ // the token is not a path, so `resolve_selector` returns `BranchOnly`.
+ ResolvedWorktree::NoWorktreeAtPath { path } => {
+ return Err(GitError::WorktreeNotFoundAtPath { path }.into());
}
+ _ => {}
}
// Phase 3: Compute expected path (only needed for create)
- let expected_path = compute_worktree_path(repo, &target.branch, config)?;
+ let expected_path = compute_worktree_path(repo, target.selector.token(), config)?;
// Phase 4: Validate we can create at this path
let needs_clobber_backup = validate_worktree_creation(
repo,
- &target.branch,
+ target.selector.token(),
&expected_path,
clobber,
&target.method,
@@ -886,7 +896,7 @@ fn plan_switch(
// Phase 5: Return the plan
Ok(SwitchPlan::Create {
- branch: target.branch,
+ branch: target.selector.token().to_string(),
worktree_path: expected_path,
method: target.method,
needs_clobber_backup,
@@ -1378,8 +1388,12 @@ fn run_pre_switch_hooks(
) -> anyhow::Result<()> {
let current_wt = repo.current_worktree();
let current_path = current_wt.path().to_path_buf();
+ // `expand_selector`, not the bare shortcut expander: the `target` var a
+ // pre-switch hook receives has to name the same branch the switch goes on
+ // to resolve, normalization included.
let resolved_target = repo
- .resolve_worktree_name(target_branch)
+ .expand_selector(target_branch)
+ .map(|s| s.token().to_string())
.unwrap_or_else(|_| target_branch.to_string());
let pre_ctx = CommandContext::new(repo, config, Some(&resolved_target), &current_path, yes);
diff --git a/src/git/error.rs b/src/git/error.rs
index 836662c1d..2acb68b85 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -605,11 +605,27 @@ pub enum GitError {
/// branch without a checkout, [`GitError::WorktreeSelectorNotFound`] a
/// token that could have been either, and this one a directory `wt list`
/// will never show and only the user can delete. Built solely by
- /// [`Repository::path_selector_error`](crate::git::Repository::path_selector_error),
+ /// [`Repository::path_selector_directory`](crate::git::Repository::path_selector_directory),
/// which owns every test that has to pass before this claim is safe.
WorktreeNotFoundAtPath {
path: PathBuf,
},
+ /// A registered worktree's path that some *other* repository now occupies.
+ ///
+ /// The registration still resolves and the directory is still there, so
+ /// every check short of asking who owns it passes — including the
+ /// dirty-worktree gate, which reads the occupant's `git status` and
+ /// reports it as this worktree's. Removal is the operation that has to
+ /// care: the directory holds someone else's work, and possibly the only
+ /// copy of their objects.
+ ///
+ /// git refuses the same removal (`validation failed … is not a .git
+ /// file`), `--force` included. Worktrunk's fast path renames the directory
+ /// itself rather than asking git to, so it has to make this check for
+ /// itself — see `ensure_belongs_to_repo`.
+ WorktreePathNotOurs {
+ path: PathBuf,
+ },
/// --create flag used with pr:/mr: syntax (conflict - branch already exists)
RefCreateConflict {
ref_type: RefType,
@@ -876,6 +892,11 @@ impl GitError {
cformat!("No worktree @ <bold>{path_display}</>")
}
+ GitError::WorktreePathNotOurs { path } => {
+ let path_display = format_path_for_display(path);
+ cformat!("Directory @ <bold>{path_display}</> is not this repository's worktree")
+ }
+
GitError::RefCreateConflict {
ref_type,
number,
@@ -1445,6 +1466,22 @@ impl GitError {
)
}
+ GitError::WorktreePathNotOurs { .. } => {
+ let title = self.title();
+ write!(
+ f,
+ "{}\n{}",
+ error_message(&title),
+ // No `git worktree prune` on its own: prune keeps a
+ // registration whose directory resolves, which this one
+ // does — the occupant's own `.git` answers for it. Moving
+ // the directory is what makes prune able to act.
+ hint_message(cformat!(
+ "Removing it could destroy unrelated data; move the directory aside, then run <underline>git worktree prune</>"
+ ))
+ )
+ }
+
GitError::RefCreateConflict {
ref_type, number, ..
} => {
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 47659d9bf..46bac6114 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -80,8 +80,9 @@ pub use remove::{
pub use repository::sha_cache;
pub use repository::{
Branch, BranchDiffSpec, CommitMessageDetail, InProgressOperation, IntegrationTargets,
- RefSnapshot, Repository, ResolvedWorktree, TempIndex, WorkingTree, duplicated_branches,
- is_valid_branch_name, resolve_input_path, select_comparison_base, set_base_path,
+ RefSnapshot, Repository, ResolvedWorktree, Selector, 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};
diff --git a/src/git/recover.rs b/src/git/recover.rs
index 26fab0aa0..023657af0 100644
--- a/src/git/recover.rs
+++ b/src/git/recover.rs
@@ -65,12 +65,15 @@ pub fn cwd_removed_hint() -> Option<String> {
}
fn hint_for_repo(repo: &Repository) -> String {
+ // The hint is only worth printing if `wt switch ^` would land somewhere,
+ // which is more than the directory existing: a recreated one passes an
+ // existence probe while holding no worktree.
if let Some(branch) = repo.default_branch()
&& repo
.worktree_for_branch(&branch)
.ok()
.flatten()
- .is_some_and(|p| p.exists())
+ .is_some_and(|p| !repo.worktree_is_unusable(&p).unwrap_or(true))
{
return cformat!("Current directory was removed. Try: <underline>wt switch ^</>");
}
diff --git a/src/git/remove.rs b/src/git/remove.rs
index 34ca8102a..7855a6114 100644
--- a/src/git/remove.rs
+++ b/src/git/remove.rs
@@ -429,16 +429,34 @@ pub fn remove_worktree_with_cleanup(
/// holds a handle on the worktree that would fail it, and git's graceful stop
/// resolves the daemon by worktree path — unreachable once the path moves.
///
+/// The ownership check runs **before** the dirty-worktree gate, and outside
+/// the `force_worktree` branch that skips it. Both matter. The gate reads `git
+/// status` in the directory, so against a foreign occupant it reports *that*
+/// repository's dirt as this worktree's and offers `--force` as the remedy — a
+/// hint leading straight to the deletion the check refuses. And `--force` is
+/// the user waiving their own uncommitted changes, never a claim about who
+/// owns the directory, so it cannot be allowed to skip it; git's own
+/// validation is likewise unconditional.
+///
+/// `wt remove` and `wt merge --remove` have already asked this during
+/// planning, where the answer can precede the "Removing …" announcement. The
+/// call here is for the paths that stage without planning, not a fresh
+/// re-check — `git_dir()` caches per worktree path, so a second call in the
+/// same process answers from the first.
+///
/// # Errors
///
-/// Only the dirty-worktree gate errors. A failed rename is reported as `None`,
-/// not an error, and the daemon stop is best-effort throughout.
+/// The ownership check and the dirty-worktree gate error. A failed rename is
+/// reported as `None`, not an error, and the daemon stop is best-effort
+/// throughout.
pub fn stage_worktree_removal(
repo: &Repository,
worktree_path: &Path,
branch: Option<&str>,
force_worktree: bool,
) -> anyhow::Result<Option<PathBuf>> {
+ repo.worktree_at(worktree_path).ensure_belongs_to_repo()?;
+
if !force_worktree {
repo.worktree_at(worktree_path)
.ensure_clean("remove worktree", branch, true)?;
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index 4eefeceda..65973ba9a 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -11,7 +11,7 @@ use crate::config::ProjectConfig;
use crate::git::CommandError;
use crate::path::format_path_for_display;
-use super::{DefaultBranchName, GitError, Repository};
+use super::{DefaultBranchName, GitError, Repository, Selector};
/// How long `git ls-remote` may run before default-branch detection gives up.
///
@@ -498,35 +498,47 @@ impl Repository {
/// Resolve a target branch from an optional override
///
- /// If target is Some, expands special symbols ("@", "-", "^") via `resolve_worktree_name`.
+ /// If target is Some, expands special symbols ("@", "-", "^") via `expand_selector`.
/// Otherwise, queries the default branch.
/// This is a common pattern used throughout commands that accept an optional --target flag.
///
/// Note: This does not validate that the target exists. Use `require_target_branch` or
/// `require_target_ref` for validation before approval prompts.
pub fn resolve_target_branch(&self, target: Option<&str>) -> anyhow::Result<String> {
+ Ok(self.resolve_target_selector(target)?.token().to_string())
+ }
+
+ /// [`resolve_target_branch`](Self::resolve_target_branch), keeping the
+ /// [`Selector`] rather than flattening it to the name.
+ ///
+ /// The `require_target_*` pair needs what the selector carries: whether the
+ /// token is still one the user typed, which is what decides the path arm
+ /// below. A default branch read from the cache is nobody's path, so the
+ /// `None` target is a rewrite like any other.
+ pub fn resolve_target_selector(&self, target: Option<&str>) -> anyhow::Result<Selector> {
match target {
- Some(b) => self.resolve_worktree_name(b),
- None => self.default_branch().ok_or_else(|| {
- GitError::Other {
- message: cformat!(
- "Cannot determine default branch. Specify target explicitly or run <bold>wt config state default-branch set BRANCH</>"
- ),
- }
- .into()
- }),
+ Some(b) => self.expand_selector(b),
+ None => self
+ .default_branch()
+ .map(Selector::rewritten_to)
+ .ok_or_else(|| {
+ GitError::Other {
+ message: cformat!(
+ "Cannot determine default branch. Specify target explicitly or run <bold>wt config state default-branch set BRANCH</>"
+ ),
+ }
+ .into()
+ }),
}
}
- /// The branch checked out at `target`, when `target` is a worktree path.
+ /// The worktree a target names by path, when the target is one.
///
/// The path arm of a merge or rebase target: `wt merge ../repo.main` names
/// the same branch as `wt merge main`. Refs win, so this runs only once the
/// caller's own ref lookup has failed, and only for a target the user typed
- /// — a default branch that resolved from the cache is not a path.
- ///
- /// `resolved` is `target` after shortcut expansion; an expansion means the
- /// literal token was a symbol rather than a path.
+ /// — which [`Selector::names_a_path`] answers outright, where this used to
+ /// infer it by checking whether expansion had changed the string.
///
/// The worktree is returned whole rather than just its branch, so `None`
/// means "nothing registered here" alone. A detached worktree — `Some` with
@@ -535,13 +547,12 @@ impl Repository {
/// let a caller report a worktree `wt list` shows as absent.
fn target_worktree_at_path(
&self,
- target: Option<&str>,
- resolved: &str,
+ selector: &Selector,
) -> anyhow::Result<Option<(PathBuf, Option<String>)>> {
- let Some(target) = target.filter(|t| *t == resolved) else {
+ if !selector.names_a_path() {
return Ok(None);
- };
- self.worktree_at_input_path(target)
+ }
+ self.worktree_at_input_path(selector.token())
}
/// Resolve and validate a target that must be a branch.
@@ -555,9 +566,10 @@ impl Repository {
/// the generic "branch not found" — the user didn't type that name,
/// the persisted cache did.
pub fn require_target_branch(&self, target: Option<&str>) -> anyhow::Result<String> {
- let branch = self.resolve_target_branch(target)?;
+ let selector = self.resolve_target_selector(target)?;
+ let branch = selector.token().to_string();
if !self.branch(&branch).exists()? {
- match self.target_worktree_at_path(target, &branch)? {
+ match self.target_worktree_at_path(&selector)? {
Some((_, Some(from_path))) => return Ok(from_path),
// A worktree is there, so the path resolved — it just has no
// branch to be the target of a merge or a push.
@@ -574,15 +586,14 @@ impl Repository {
None => {}
}
if target.is_none() {
- if self.is_unborn_branch(&branch) {
- return Err(GitError::UnbornDefaultBranch { branch }.into());
- }
- return Err(GitError::StaleDefaultBranch { branch }.into());
+ return Err(self.uncached_default_branch_error(branch));
}
// Nothing is registered at the path, which is what this error
- // asserts; the arms above consumed both worktree cases.
- if let Some(err) = self.path_selector_error(&branch) {
- return Err(err.into());
+ // asserts; the arms above consumed both worktree cases. A target
+ // is spelled in a wider vocabulary than a worktree selector, so
+ // this stays here rather than routing through `resolve_selector`.
+ if let Some(path) = self.path_selector_directory(&branch) {
+ return Err(GitError::WorktreeNotFoundAtPath { path }.into());
}
return Err(GitError::BranchNotFound {
// Offering `--create` for a name git rejects sends the user to
@@ -608,24 +619,39 @@ impl Repository {
/// [`GitError::StaleDefaultBranch`] with cache-reset hints rather than
/// the generic "reference not found".
pub fn require_target_ref(&self, target: Option<&str>) -> anyhow::Result<String> {
- let reference = self.resolve_target_branch(target)?;
+ let selector = self.resolve_target_selector(target)?;
+ let reference = selector.token().to_string();
if !self.ref_exists(&reference)? {
- if let Some((_, Some(from_path))) = self.target_worktree_at_path(target, &reference)? {
+ if let Some((_, Some(from_path))) = self.target_worktree_at_path(&selector)? {
return Ok(from_path);
}
// No path claim here: a commit-ish is spelled in a wider vocabulary
// than a worktree selector, and `ReferenceNotFound` names all of it.
if target.is_none() {
- if self.is_unborn_branch(&reference) {
- return Err(GitError::UnbornDefaultBranch { branch: reference }.into());
- }
- return Err(GitError::StaleDefaultBranch { branch: reference }.into());
+ return Err(self.uncached_default_branch_error(reference));
}
return Err(GitError::ReferenceNotFound { reference }.into());
}
Ok(reference)
}
+ /// The error for a default branch that came from the cache rather than the
+ /// user, and then didn't resolve.
+ ///
+ /// The one part of `require_target_branch` and `require_target_ref` that is
+ /// identical rather than merely parallel: the rest of those two differ in
+ /// their existence predicate, their extra arms, and their final error, and
+ /// forcing them together would cost more in parameters than the duplication
+ /// does.
+ fn uncached_default_branch_error(&self, branch: String) -> anyhow::Error {
+ if self.is_unborn_branch(&branch) {
+ // No cache-reset hint: the cached name is right, the branch just
+ // has no commits yet.
+ return GitError::UnbornDefaultBranch { branch }.into();
+ }
+ GitError::StaleDefaultBranch { branch }.into()
+ }
+
/// True when `branch` is checked out as an unborn HEAD (no commits yet)
/// in some worktree — e.g. a freshly `git init`'d repo before its first
/// commit. Such a branch has no `refs/heads/<branch>` ref, so the
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index dcbd12ac3..8adf7499f 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -358,6 +358,7 @@ pub(super) struct RepoCache {
/// Used by `resolve_worktree` to handle different resolution outcomes:
/// - A worktree exists (with optional branch for detached HEAD)
/// - Only a branch exists (no worktree)
+/// - The selector named a directory that holds no worktree
#[derive(Debug, Clone)]
pub enum ResolvedWorktree {
/// A worktree was found
@@ -372,6 +373,82 @@ pub enum ResolvedWorktree {
/// The branch name
branch: String,
},
+ /// The selector named a directory holding no worktree — the skeleton an
+ /// interrupted create or remove leaves behind.
+ ///
+ /// A verdict rather than a caller's job: every place that reports "no such
+ /// thing" has to say whether it was looking for a branch or a path, and
+ /// [`Repository::path_selector_directory`] owns the four tests that make the
+ /// claim safe. Returning it here is what keeps those tests from being
+ /// re-invoked, or forgotten, at each reporting site.
+ NoWorktreeAtPath {
+ /// The directory, resolved against `-C` but spelled as the selector did
+ path: PathBuf,
+ },
+}
+
+/// A worktree selector after normalization and expansion — the token to look
+/// up, plus whether it may still be tried as a *path*.
+///
+/// Every assembly of the resolution ladder needs that second fact, and each
+/// used to re-derive it by comparing an expansion's output against its input —
+/// `branch == name` in `resolve_worktree`, `target.branch == branch` in
+/// `plan_switch`, `target.filter(|t| *t == resolved)` in
+/// `target_worktree_at_path`, `resolved == base` in `resolve_base_ref`. Four
+/// copies of one string heuristic standing in for something the producing step
+/// knows outright, and a trap for any normalization applied underneath them:
+/// stripping `docs/` to `docs` reads as a rewrite and silently disables the
+/// path arm.
+///
+/// So the producers state it. A token nobody touched may name a path
+/// ([`Selector::literal`]). One an earlier step produced may not
+/// ([`Selector::rewritten_to`]) — a shortcut expansion, a `pr:`/`mr:` lookup, a
+/// stripped remote prefix, a default branch read from cache. Neither does one
+/// that names a branch by construction ([`Selector::branch_only`]), which is
+/// `wt switch --create <name>`: nothing rewrote the argument, but it names a
+/// branch that does not exist yet, so a directory sitting at that spelling is
+/// not what the user meant.
+#[derive(Debug, Clone)]
+pub struct Selector {
+ token: String,
+ may_name_path: bool,
+}
+
+impl Selector {
+ /// A token the user typed and nothing rewrote — the path arm applies.
+ pub fn literal(token: impl Into<String>) -> Self {
+ Self {
+ token: token.into(),
+ may_name_path: true,
+ }
+ }
+
+ /// A token some earlier step produced, so the literal argument is not what
+ /// this names and a path lookup would be a nonsense one.
+ pub fn rewritten_to(token: impl Into<String>) -> Self {
+ Self {
+ token: token.into(),
+ may_name_path: false,
+ }
+ }
+
+ /// Take the path arm off a token that names a branch by construction.
+ pub fn branch_only(self) -> Self {
+ Self {
+ may_name_path: false,
+ ..self
+ }
+ }
+
+ /// The name to look up.
+ pub fn token(&self) -> &str {
+ &self.token
+ }
+
+ /// Whether this token may still be tried as a worktree path.
+ pub fn names_a_path(&self) -> bool {
+ self.may_name_path
+ }
}
/// Global base path for repository operations, set by -C flag.
@@ -520,6 +597,29 @@ pub fn resolve_input_path(path: impl AsRef<Path>) -> PathBuf {
}
}
+/// A worktree selector with trailing path separators removed.
+///
+/// Git's ref format forbids a name ending in `/`, so a selector that does can
+/// only be a path spelling — and shell completion is how one usually arrives.
+/// `wt switch docs<tab>` completes against the *directory* `./docs` whenever
+/// one sits beside the branch, yielding `docs/`, and the branch lookup then
+/// misses a branch that is right there.
+///
+/// Applied where a raw token enters resolution — [`Repository::resolve_worktree`],
+/// [`Repository::resolve_target_branch`], and `plan_switch` — rather than
+/// inside the shortcut expander they each call first. Both halves of "try the
+/// branch, then try the path" have to see one token: each gates its path
+/// attempt on the resolved name still equalling the input, which is how it
+/// tells a shortcut rewrite from a literal, and a name stripped underneath
+/// that test would read as a rewrite.
+///
+/// A selector of nothing but separators is returned unchanged — `/` is the
+/// root directory, and the empty string names nothing at all.
+pub fn normalize_selector(name: &str) -> &str {
+ let trimmed = name.trim_end_matches(std::path::is_separator);
+ if trimmed.is_empty() { name } else { trimmed }
+}
+
/// Repository state for git operations.
///
/// Represents the shared state of a git repository (the `.git` directory).
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index 6a8b40d32..7a97d05f2 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -1434,6 +1434,9 @@ fn resolve_worktree_does_not_treat_shortcuts_as_paths() {
let branch = match resolved {
ResolvedWorktree::Worktree { branch, .. } => branch,
ResolvedWorktree::BranchOnly { branch } => Some(branch),
+ ResolvedWorktree::NoWorktreeAtPath { path } => {
+ panic!("`^` resolved to a directory: {}", path.display())
+ }
};
assert_eq!(branch.as_deref(), Some(default_branch.as_str()));
}
@@ -1479,11 +1482,14 @@ fn directory_holding_no_worktree_is_reported_as_a_directory() {
let ghost = test.root_path().join("ghost");
std::fs::create_dir(&ghost).unwrap();
- // Resolution still falls through to branch-only; the selector's shape is
- // read where the failure is reported, not where it is resolved.
+ // Resolution reaches the verdict itself, so no reporting site has to
+ // re-derive what the selector was reaching for.
let selector = ghost.to_str().unwrap();
let resolved = test.repo.resolve_worktree(selector).unwrap();
- assert!(matches!(resolved, ResolvedWorktree::BranchOnly { .. }));
+ assert!(
+ matches!(resolved, ResolvedWorktree::NoWorktreeAtPath { .. }),
+ "a directory holding no worktree is its own verdict, got: {resolved:?}"
+ );
let rendered = test
.repo
@@ -1546,7 +1552,7 @@ fn directory_holding_no_worktree_is_reported_as_a_directory() {
for checkout in [&sibling, &bare] {
assert!(
test.repo
- .path_selector_error(checkout.to_str().unwrap())
+ .path_selector_directory(checkout.to_str().unwrap())
.is_none(),
"a directory holding git data must not be called a leftover: {}",
checkout.display()
@@ -1559,7 +1565,7 @@ fn directory_holding_no_worktree_is_reported_as_a_directory() {
std::fs::write(decoy.join("HEAD"), "").unwrap();
assert!(
test.repo
- .path_selector_error(decoy.to_str().unwrap())
+ .path_selector_directory(decoy.to_str().unwrap())
.is_some(),
"a directory that merely contains a HEAD file is still a leftover"
);
@@ -1596,7 +1602,7 @@ fn an_unresolvable_git_entry_still_counts_as_git_data() {
for checkout in checkouts {
assert!(
test.repo
- .path_selector_error(checkout.to_str().unwrap())
+ .path_selector_directory(checkout.to_str().unwrap())
.is_none(),
"an unresolvable .git must still withhold the claim: {}",
checkout.display()
@@ -1659,7 +1665,7 @@ fn path_selector_error_checks_for_a_registered_worktree() {
let selector = worktree_path.to_str().unwrap();
assert!(
- test.repo.path_selector_error(selector).is_none(),
+ test.repo.path_selector_directory(selector).is_none(),
"a registered worktree's own path must never be reported as holding none"
);
@@ -1923,3 +1929,150 @@ fn test_worktree_for_branch_dedups_duplicate_warning() {
assert!(first.is_some(), "an ambiguous branch still resolves");
assert_eq!(first, second, "resolution is stable across the dedup guard");
}
+
+/// A trailing path separator is not part of any branch name git will accept, so
+/// stripping it lets `docs/` — what shell completion produces beside a `docs`
+/// directory — find the branch. A selector made only of separators is left
+/// alone: `/` is the root directory and the empty string names nothing.
+#[test]
+fn normalize_selector_strips_only_trailing_separators() {
+ use crate::git::normalize_selector;
+
+ assert_eq!(normalize_selector("docs/"), "docs");
+ assert_eq!(normalize_selector("../repo.feature/"), "../repo.feature");
+ assert_eq!(normalize_selector("docs"), "docs");
+ assert_eq!(normalize_selector("feat/sub"), "feat/sub");
+ assert_eq!(normalize_selector("/"), "/");
+ assert_eq!(normalize_selector(""), "");
+}
+
+/// A worktree git reports as prunable is one nothing can run in, so the lookup
+/// every command shares refuses it rather than handing back a path that fails
+/// at `git rev-parse` a few calls later.
+///
+/// The directory is recreated rather than left absent, because that is the
+/// state the `Path::exists()` probes this replaced could not see.
+#[test]
+fn usable_worktree_for_branch_refuses_a_prunable_registration() {
+ use crate::git::Repository;
+ use crate::testing::TestRepo;
+
+ let mut test = TestRepo::with_initial_commit();
+ let worktree_path = test.add_worktree("feature");
+
+ assert_eq!(
+ test.repo.usable_worktree_for_branch("feature").unwrap(),
+ Some(worktree_path.clone()),
+ "a healthy worktree resolves"
+ );
+
+ std::fs::remove_dir_all(&worktree_path).unwrap();
+ std::fs::create_dir_all(&worktree_path).unwrap();
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ let err = repo.usable_worktree_for_branch("feature").unwrap_err();
+ assert!(
+ err.to_string().contains("Worktree directory missing"),
+ "a prunable registration must be refused, got: {err}"
+ );
+ assert_eq!(
+ repo.usable_worktree_for_branch("no-such-branch").unwrap(),
+ None,
+ "a branch with no worktree is a normal answer, not an error"
+ );
+}
+
+/// A selector reports whether anything rewrote it, rather than that being
+/// inferred by comparing an expansion's output against its input.
+///
+/// The two answers differ, which is the whole reason to carry the fact: an
+/// expansion can legitimately return the token it was given — `-` pointing at
+/// the branch you are already on — and string equality then reads a rewrite as
+/// a literal, turning the path arm back on for a token nobody typed.
+/// Normalization breaks it in the other direction: `docs/` and `docs` are one
+/// selector, and comparing them would read a rewrite that never happened.
+#[test]
+fn selector_reports_rewriting_rather_than_inferring_it() {
+ use crate::testing::TestRepo;
+
+ let test = TestRepo::with_initial_commit();
+ let repo = &test.repo;
+ let current = repo.current_worktree().branch().unwrap().unwrap();
+
+ let literal = repo.expand_selector("some-branch").unwrap();
+ assert_eq!(literal.token(), "some-branch");
+ assert!(literal.names_a_path(), "an untouched token may be a path");
+
+ // Normalization is not rewriting: `docs/` still gets its path arm, which
+ // is what keeps `../repo.feature/` resolving as a worktree path.
+ let normalized = repo.expand_selector("docs/").unwrap();
+ assert_eq!(normalized.token(), "docs");
+ assert!(
+ normalized.names_a_path(),
+ "stripping a separator must not read as a rewrite"
+ );
+
+ // `^` expands to the default branch, which here IS the current branch — so
+ // the expansion's output equals neither its input nor nothing useful. The
+ // flag, not a comparison, is what records that a shortcut fired.
+ let shortcut = repo.expand_selector("^").unwrap();
+ assert_eq!(shortcut.token(), current);
+ assert!(
+ !shortcut.names_a_path(),
+ "a shortcut's expansion is nobody's path"
+ );
+
+ // The degenerate case string equality gets wrong: history pointing at the
+ // branch already checked out. Output == input, yet a shortcut fired.
+ repo.set_switch_previous(Some(&current)).unwrap();
+ let previous = repo.expand_selector("-").unwrap();
+ assert_eq!(previous.token(), current);
+ assert!(
+ !previous.names_a_path(),
+ "a shortcut that expands to its own input is still a rewrite"
+ );
+}
+
+/// "Nothing can run here" is the union of two independent failures, because
+/// neither implies the other.
+///
+/// git withholds the `prunable` attribute from a **locked** worktree even when
+/// its directory is gone — prunability is git's pruning *policy*, and a lock
+/// means "don't prune this". So a `prunable`-only test reads a locked worktree
+/// on an unmounted volume as healthy, which is the state
+/// `prepare_worktree_removal`'s lock guard exists for. The recreated directory
+/// is the converse: present, so an existence probe passes, and holding nothing.
+#[test]
+fn worktree_is_unusable_covers_locked_absent_and_recreated() {
+ use crate::git::Repository;
+ use crate::testing::TestRepo;
+
+ let mut test = TestRepo::with_initial_commit();
+ let healthy = test.add_worktree("healthy");
+ let absent = test.add_worktree("absent");
+ let locked = test.add_worktree("locked-absent");
+ let recreated = test.add_worktree("recreated");
+
+ test.lock_worktree("locked-absent", Some("removable media"));
+ std::fs::remove_dir_all(&absent).unwrap();
+ std::fs::remove_dir_all(&locked).unwrap();
+ std::fs::remove_dir_all(&recreated).unwrap();
+ std::fs::create_dir_all(&recreated).unwrap();
+
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ assert!(!repo.worktree_is_unusable(&healthy).unwrap());
+ assert!(
+ repo.worktree_is_unusable(&absent).unwrap(),
+ "an absent directory is unusable"
+ );
+ assert!(
+ repo.worktree_is_unusable(&locked).unwrap(),
+ "a locked worktree whose directory is gone carries no `prunable` line, \
+ so only the existence half catches it"
+ );
+ assert!(
+ repo.worktree_is_unusable(&recreated).unwrap(),
+ "a recreated directory exists, so only the `prunable` half catches it"
+ );
+}
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index 7070356c7..48e235b4b 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -597,6 +597,50 @@ impl<'a> WorkingTree<'a> {
Ok(git_dir != common_dir)
}
+ /// Refuse when the directory at this worktree's path is not this
+ /// repository's worktree.
+ ///
+ /// Git makes this check itself before `git worktree remove` and refuses
+ /// with `validation failed … is not a .git file`, `--force` included.
+ /// Worktrunk's removal fast path renames the directory into trash rather
+ /// than asking git to (see
+ /// [`stage_worktree_removal`](crate::git::remove::stage_worktree_removal)),
+ /// so git's validation never runs and the guarantee has to be made here.
+ /// Removing the wrong directory is unrecoverable — the case this was
+ /// written for is a full clone that came to sit at a stale registration's
+ /// path, holding uncommitted work and the only copy of its objects.
+ ///
+ /// The test is ownership of the git directory rather than git's
+ /// `.git`-is-a-file shape: a linked worktree's git dir sits under
+ /// `<common>/worktrees/`, the main worktree's *is* the common dir, and
+ /// anything else answers to a different repository. One comparison covers
+ /// both worktree kinds with no special case, and it rejects a `.git` file
+ /// pointing at another repository, which the shape test alone accepts.
+ ///
+ /// Deliberately not a `prunable` check — git leaves the registration alone
+ /// precisely because the occupant's own `.git` resolves, so
+ /// [`Repository::usable_worktree_for_branch`] sees nothing wrong here. The
+ /// two cover different halves of "the directory no longer holds this
+ /// worktree": prunable is the half git notices, this is the half it does
+ /// not.
+ pub fn ensure_belongs_to_repo(&self) -> anyhow::Result<()> {
+ let common_dir = self.repo.git_common_dir();
+ // A git directory that can't be resolved at all is the strongest form
+ // of "not ours": nothing there answers for this worktree. Treating it
+ // as a refusal keeps the failure closed, where propagating git's exit
+ // 128 would leave the caller to decide.
+ let is_ours = self.git_dir().is_ok_and(|git_dir| {
+ git_dir == common_dir || git_dir.starts_with(common_dir.join("worktrees"))
+ });
+ if is_ours {
+ return Ok(());
+ }
+ Err(GitError::WorktreePathNotOurs {
+ path: self.path.clone(),
+ }
+ .into())
+ }
+
/// Ensure this worktree is clean (no uncommitted changes).
///
/// Returns an error if there are uncommitted changes.
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index 49d7fdf8e..7323f3c8d 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -9,7 +9,8 @@ use color_print::cformat;
use dunce::canonicalize;
use super::{
- GitError, Repository, ResolvedWorktree, WorktreeInfo, is_valid_branch_name, resolve_input_path,
+ GitError, Repository, ResolvedWorktree, Selector, WorktreeInfo, is_valid_branch_name,
+ normalize_selector, resolve_input_path,
};
use crate::path::{format_path_for_display, paths_match};
use crate::styling::{
@@ -85,6 +86,68 @@ impl Repository {
Ok(paths.into_iter().next())
}
+ /// The worktree `branch` is checked out in, refusing one nothing can run in.
+ ///
+ /// [`worktree_for_branch`](Self::worktree_for_branch) answers where git has
+ /// the worktree *registered*; this answers where a command can actually
+ /// work. The branch-first callers use it — `wt merge` and `wt step push`,
+ /// which look their target up by name. `wt switch` and
+ /// [`recover`](crate::git::recover) already hold a path by the time they
+ /// need the verdict, so they ask
+ /// [`worktree_is_unusable`](Self::worktree_is_unusable) directly; the
+ /// selector ladder asks neither, since resolution answers what the user
+ /// named rather than whether it can be worked in.
+ ///
+ /// The verdict is [`worktree_is_unusable`](Self::worktree_is_unusable).
+ ///
+ /// `Ok(None)` when the branch has no worktree at all — a normal answer,
+ /// and the caller's to interpret.
+ pub fn usable_worktree_for_branch(&self, branch: &str) -> anyhow::Result<Option<PathBuf>> {
+ let Some(path) = self.worktree_for_branch(branch)? else {
+ return Ok(None);
+ };
+ if self.worktree_is_unusable(&path)? {
+ return Err(GitError::WorktreeMissing {
+ branch: branch.to_string(),
+ }
+ .into());
+ }
+ Ok(Some(path))
+ }
+
+ /// Whether nothing can run in the worktree registered at `path`.
+ ///
+ /// Two independent ways for that to be true, and neither implies the other,
+ /// so the test is the union:
+ ///
+ /// - The directory is not there. `Path::exists()` is the whole of this one.
+ /// - Git reports the registration as `prunable` — its gitdir pointer no
+ /// longer resolves. This is the case an existence probe misses, because a
+ /// directory deleted and *recreated* (an interrupted `wt switch`, an
+ /// `rm -rf` followed by a `mkdir`) is there while holding nothing.
+ ///
+ /// `prunable` alone is not the wider test it looks like: git withholds the
+ /// attribute from a **locked** worktree even when the directory is gone,
+ /// because prunability is git's pruning *policy* and a lock means "don't
+ /// prune this". A locked worktree on an unmounted volume — the case
+ /// `prepare_worktree_removal`'s lock guard exists for — carries no
+ /// `prunable` line, so a `prunable`-only test reads it as healthy and lets
+ /// a command walk into a directory that is not there.
+ ///
+ /// The `prunable` half costs a lookup rather than a fork:
+ /// [`list_worktrees`](Self::list_worktrees) has already parsed and cached
+ /// the listing. `false` for a path git has no registration for — absence of
+ /// a registration is not breakage of one.
+ pub fn worktree_is_unusable(&self, path: &Path) -> anyhow::Result<bool> {
+ if !path.exists() {
+ return Ok(true);
+ }
+ Ok(self
+ .list_worktrees()?
+ .iter()
+ .any(|wt| paths_match(&wt.path, path) && wt.is_prunable()))
+ }
+
/// The "home" worktree — main worktree for normal repos, default branch worktree for bare.
///
/// Used as the default source for `copy-ignored` and the `{{ primary_worktree_path }}` template.
@@ -250,24 +313,18 @@ impl Repository {
Ok(())
}
- /// Resolve a worktree name, expanding "@" to current, "-" to previous, and "^" to the default branch.
- ///
- /// # Arguments
- /// * `name` - The worktree name to resolve:
- /// - "@" for current HEAD
- /// - "-" for previous branch (via worktrunk.history)
- /// - "^" for default branch
- /// - any other string is returned as-is
- ///
- /// # Returns
- /// - `Ok(name)` if not a special symbol
- /// - `Ok(current_branch)` if "@" and on a branch
- /// - `Ok(previous_branch)` if "-" and worktrunk.history has a previous branch
- /// - `Ok(default_branch)` if "^"
- /// - `Err(DetachedHead)` if "@" and in detached HEAD state
- /// - `Err` if "-" but no previous branch in history
- pub fn resolve_worktree_name(&self, name: &str) -> anyhow::Result<String> {
- match name {
+ /// Expand `@` / `-` / `^`, reporting whether `name` was one of them.
+ ///
+ /// `None` means the token is not a shortcut and reaches the caller
+ /// untouched — the fact [`Selector`] carries as `names_a_path`, stated by
+ /// the step that would have done the rewriting rather than inferred
+ /// downstream by comparing this function's output against its input. The
+ /// two are not the same question: an expansion can legitimately return the
+ /// token it was given (a `-` history entry naming the branch you are on),
+ /// and any normalization applied around the call makes the comparison lie
+ /// outright.
+ fn expand_shortcut(&self, name: &str) -> anyhow::Result<Option<String>> {
+ let expanded = match name {
"@" => self.current_worktree().branch()?.ok_or_else(|| {
GitError::DetachedHead {
action: Some("resolve @ to current branch".into()),
@@ -294,8 +351,23 @@ impl Repository {
}
.into()
}),
- _ => Ok(name.to_string()),
- }
+ _ => return Ok(None),
+ };
+ expanded.map(Some)
+ }
+
+ /// Normalize and expand a token the user typed into the [`Selector`] the
+ /// resolvers work on.
+ ///
+ /// The one place normalization happens for the worktree ladder — possible
+ /// only because `may_name_path` is set from whether `expand_shortcut`
+ /// fired, rather than from a string comparison this would corrupt.
+ pub fn expand_selector(&self, name: &str) -> anyhow::Result<Selector> {
+ let name = normalize_selector(name);
+ Ok(match self.expand_shortcut(name)? {
+ Some(token) => Selector::rewritten_to(token),
+ None => Selector::literal(name),
+ })
}
/// Resolve a worktree selector — the one place a token the user typed
@@ -316,60 +388,92 @@ impl Repository {
/// relative to `-C` (see [`resolve_input_path`])
/// 5. otherwise the branch alone, which may or may not exist
///
- /// A path that named no worktree lands in `BranchOnly` too, since step 5
- /// asks nothing of the token — as does a shortcut whose expansion matched
- /// nothing, which never reached step 4 at all. What the selector could have
- /// meant is worked out where the failure is reported, by
- /// [`path_selector_error`](Self::path_selector_error); the callers that go
- /// on to succeed never need the answer.
+ /// A path that named no worktree lands in `BranchOnly` or
+ /// `NoWorktreeAtPath` — [`resolve_selector`](Self::resolve_selector)
+ /// decides which, once, so no reporting site has to.
///
/// # Returns
/// - `Worktree { path, branch }` — `branch` is `None` for a detached worktree
/// - `BranchOnly { branch }` when nothing is checked out under that name
+ /// - `NoWorktreeAtPath { path }` when the selector named a directory instead
+ ///
+ /// A worktree git reports as *prunable* still resolves here. Resolution
+ /// answers "what did the user name", and `wt remove` names one precisely
+ /// in order to clean up its registration. Refusing to *work* in one is
+ /// [`usable_worktree_for_branch`](Self::usable_worktree_for_branch)'s job,
+ /// which the commands that go on to run there call instead.
pub fn resolve_worktree(&self, name: &str) -> anyhow::Result<ResolvedWorktree> {
- match name {
- "@" => {
- // Current worktree by path - works even in detached HEAD
- // If worktree_root fails (e.g., in bare repo directory), give a clear error
- let path = self
- .current_worktree()
- .root()
- .map_err(|_| GitError::NotInWorktree {
- action: Some("resolve @".into()),
- })?;
- // root() returns canonicalized path, so canonicalize worktree paths
- // for comparison to handle symlinks (e.g., macOS /var -> /private/var)
- let worktrees = self.list_worktrees()?;
- let branch = worktrees
- .iter()
- .find(|wt| canonicalize(&wt.path).map(|p| p == path).unwrap_or(false))
- .and_then(|wt| wt.branch.clone());
- Ok(ResolvedWorktree::Worktree { path, branch })
- }
- _ => {
- let branch = self.resolve_worktree_name(name)?;
- if let Some(path) = self.worktree_for_branch(&branch)? {
- return Ok(ResolvedWorktree::Worktree {
- path,
- branch: Some(branch),
- });
- }
+ // `@` is the only selector that resolves by path rather than by name,
+ // which is what lets it answer in a detached worktree — where the
+ // branch expansion `expand_selector` would apply has nothing to return.
+ let name = normalize_selector(name);
+ if name == "@" {
+ // If worktree_root fails (e.g., in bare repo directory), give a clear error
+ let path = self
+ .current_worktree()
+ .root()
+ .map_err(|_| GitError::NotInWorktree {
+ action: Some("resolve @".into()),
+ })?;
+ // root() returns canonicalized path, so canonicalize worktree paths
+ // for comparison to handle symlinks (e.g., macOS /var -> /private/var)
+ let branch = self
+ .list_worktrees()?
+ .iter()
+ .find(|wt| canonicalize(&wt.path).map(|p| p == path).unwrap_or(false))
+ .and_then(|wt| wt.branch.clone());
+ return Ok(ResolvedWorktree::Worktree { path, branch });
+ }
- // A shortcut named a branch, not a directory: `resolve_worktree_name`
- // returns a non-shortcut token unchanged, so an unequal result is
- // exactly the case where the literal token would be a nonsense path.
- if branch == name
- && let Some((path, wt_branch)) = self.worktree_at_input_path(name)?
- {
- return Ok(ResolvedWorktree::Worktree {
- path,
- branch: wt_branch,
- });
- }
+ self.resolve_selector(&self.expand_selector(name)?)
+ }
- Ok(ResolvedWorktree::BranchOnly { branch })
- }
+ /// The worktree ladder itself: branch first, then path, then a verdict on
+ /// what the selector could have meant.
+ ///
+ /// Split from [`resolve_worktree`](Self::resolve_worktree) for the callers
+ /// that do their own expanding before they get here — `wt switch`, whose
+ /// `pr:`/`mr:` dispatch and remote-prefix strip run first and report their
+ /// rewriting through the [`Selector`]. They used to re-implement these
+ /// three steps rather than expand into a shared one.
+ pub fn resolve_selector(&self, selector: &Selector) -> anyhow::Result<ResolvedWorktree> {
+ let token = selector.token();
+
+ if let Some(path) = self.worktree_for_branch(token)? {
+ return Ok(ResolvedWorktree::Worktree {
+ path,
+ branch: Some(token.to_string()),
+ });
+ }
+
+ // Both remaining steps are about the token as a path, so
+ // `names_a_path` gates them together — a caller that turns it off gets
+ // neither a worktree matched by path nor a verdict about a directory,
+ // which is what `wt switch --create` needs: the argument names a branch
+ // to create, and a directory sitting at that spelling is the clobber
+ // check's business.
+ if !selector.names_a_path() {
+ return Ok(ResolvedWorktree::BranchOnly {
+ branch: token.to_string(),
+ });
}
+
+ if let Some((path, wt_branch)) = self.worktree_at_input_path(token)? {
+ return Ok(ResolvedWorktree::Worktree {
+ path,
+ branch: wt_branch,
+ });
+ }
+
+ // Nothing matched, so say which of the two the selector was reaching
+ // for. Free for an ordinary branch name: `path_selector_directory`
+ // returns on `is_valid_branch_name` before touching the filesystem.
+ Ok(match self.path_selector_directory(token) {
+ Some(path) => ResolvedWorktree::NoWorktreeAtPath { path },
+ None => ResolvedWorktree::BranchOnly {
+ branch: token.to_string(),
+ },
+ })
}
/// The branch a selector names, erroring only when it names a detached
@@ -386,12 +490,12 @@ impl Repository {
branch: Some(branch),
..
} => Ok(branch),
- // A path selector reaches here only when it named no worktree, and
- // it can't be the branch the caller is about to key state by.
- ResolvedWorktree::BranchOnly { branch } => match self.path_selector_error(&branch) {
- Some(err) => Err(err.into()),
- None => Ok(branch),
- },
+ ResolvedWorktree::BranchOnly { branch } => Ok(branch),
+ // A path spelling can't be the branch the caller is about to key
+ // state by.
+ ResolvedWorktree::NoWorktreeAtPath { path } => {
+ Err(GitError::WorktreeNotFoundAtPath { path }.into())
+ }
ResolvedWorktree::Worktree { path, branch: None } => Err(GitError::DetachedHead {
action: Some(cformat!(
"{action} — <bold>{}</> is detached",
@@ -417,11 +521,14 @@ impl Repository {
match self.resolve_worktree(name)? {
ResolvedWorktree::Worktree { path, .. } => Ok(path),
ResolvedWorktree::BranchOnly { branch } => Err(self.no_worktree_error(branch)),
+ ResolvedWorktree::NoWorktreeAtPath { path } => {
+ Err(GitError::WorktreeNotFoundAtPath { path }.into())
+ }
}
}
- /// The not-found error for a selector naming a directory that holds no
- /// worktree — the skeleton an interrupted create or remove leaves behind.
+ /// The directory a selector names, when it names one holding no worktree —
+ /// the skeleton an interrupted create or remove leaves behind.
///
/// Every argument naming a worktree is tried as a branch first and as a
/// path second, so each place that reports "no such thing" has to say which
@@ -452,24 +559,26 @@ impl Repository {
/// interrupted create or remove leaves, which holds no git data at all
/// (see `holds_git_data`).
///
- /// `None` when any test fails, leaving the caller's own error in place.
+ /// `None` when any test fails, leaving the selector to be reported as a
+ /// branch. The verdict reaches callers as
+ /// [`ResolvedWorktree::NoWorktreeAtPath`] — this is
+ /// [`resolve_selector`](Self::resolve_selector)'s last step, and the only
+ /// caller that is not itself assembling the ladder is
+ /// [`require_target_branch`](Self::require_target_branch), whose target
+ /// vocabulary is wider than a worktree selector's.
///
/// The path is reported as the selector spells it, resolved against `-C`
- /// but not otherwise tidied. A trailing `/` is the reason: `docs/` and
- /// `docs` are the same directory but not the same selector — only the
- /// second finds the branch — and echoing back the spelling that works would
- /// hide the one character that did not. The cost is that a `-C` base and a
- /// `./`-prefixed selector join to a visible `/./`.
- ///
- /// Both hold on Unix only. Rendering runs through `format_path_for_display`
- /// and so through `path_slash`'s `to_slash_lossy`, which is
- /// `to_string_lossy` verbatim there but rebuilds the string from
- /// `Path::components()` on Windows: a trailing `/` is dropped (only a
- /// trailing `\`, the platform separator, survives) and an interior `/./`
- /// collapses. `wt switch docs/` reports `…/docs` there — true of the path,
- /// and missing the character that explains why the selector found no
- /// branch.
- pub fn path_selector_error(&self, selector: &str) -> Option<GitError> {
+ /// but not otherwise tidied — so a `-C` base and a `./`-prefixed selector
+ /// join to a visible `/./`. Cosmetic, and Unix-only: rendering runs through
+ /// `format_path_for_display` and so through `path_slash`'s
+ /// `to_slash_lossy`, which is `to_string_lossy` verbatim there but rebuilds
+ /// the string from `Path::components()` on Windows, collapsing an interior
+ /// `/./`.
+ ///
+ /// A trailing separator never reaches here: [`normalize_selector`] strips
+ /// it before resolution, so `docs/` and `docs` are one selector and both
+ /// find the branch.
+ pub fn path_selector_directory(&self, selector: &str) -> Option<PathBuf> {
if is_valid_branch_name(selector) {
return None;
}
@@ -485,14 +594,15 @@ impl Repository {
if holds_git_data(&path) {
return None;
}
- Some(GitError::WorktreeNotFoundAtPath { path })
+ Some(path)
}
/// The error for a selector that resolved to a branch with no checkout.
+ ///
+ /// The directory case never arrives here — `resolve_selector` has already
+ /// separated it out — so this only has to choose between "the branch has no
+ /// worktree" and "nothing answers to this name at all".
fn no_worktree_error(&self, branch: String) -> anyhow::Error {
- if let Some(err) = self.path_selector_error(&branch) {
- return err.into();
- }
match self.branch(&branch).exists_locally() {
Ok(true) => GitError::WorktreeNotFound { branch }.into(),
// A ref lookup that fails says nothing about the branch, so fall
diff --git a/tests/integration_tests/default_branch.rs b/tests/integration_tests/default_branch.rs
index 09a973fdc..95d8a7983 100644
--- a/tests/integration_tests/default_branch.rs
+++ b/tests/integration_tests/default_branch.rs
@@ -379,7 +379,7 @@ fn test_resolve_caret_fails_when_default_branch_unavailable(repo: TestRepo) {
// Now resolving "^" should fail with an error
let git_repo = Repository::at(repo.root_path()).unwrap();
- let result = git_repo.resolve_worktree_name("^");
+ let result = git_repo.expand_selector("^");
assert!(
result.is_err(),
"Expected error when resolving ^ without default branch"
@@ -392,6 +392,31 @@ fn test_resolve_caret_fails_when_default_branch_unavailable(repo: TestRepo) {
);
}
+/// An omitted target reaches the same "cannot determine default branch" error as
+/// `^` does, by a different route: `^` asks the shortcut expander, while
+/// `wt merge` with no argument asks `resolve_target_selector` for the default
+/// directly. Both are how a user meets a repo whose default branch is
+/// unknowable, and only the first had a test.
+#[rstest]
+fn test_omitted_target_fails_when_default_branch_unavailable(repo: TestRepo) {
+ repo.run_git(&["remote", "remove", "origin"]);
+ repo.git_command()
+ .args(["branch", "-m", "main", "xyz"])
+ .run()
+ .unwrap();
+ repo.git_command().args(["branch", "abc"]).run().unwrap();
+ repo.git_command().args(["branch", "def"]).run().unwrap();
+
+ let git_repo = Repository::at(repo.root_path()).unwrap();
+ let err = git_repo
+ .require_target_branch(None)
+ .expect_err("an unknowable default branch cannot be a merge target");
+ assert!(
+ err.to_string().contains("Cannot determine default branch"),
+ "got: {err}"
+ );
+}
+
// --- Forge URL resolution helpers ---
/// Configure a remote with a custom hostname and an insteadOf rewrite to a real forge.
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 4dd8eb598..68fd7430b 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -439,6 +439,74 @@ 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.
+#[rstest]
+fn test_remove_worktree_directory_recreated(mut repo: TestRepo) {
+ let worktree_path = repo.add_worktree("feature");
+ std::fs::remove_dir_all(&worktree_path).unwrap();
+ std::fs::create_dir_all(&worktree_path).unwrap();
+
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["feature"], None));
+}
+
+/// A registration whose directory now holds a *different* repository is not
+/// this repository's worktree, and removing it would destroy that one — its
+/// uncommitted work and, for a repo that was never pushed, the only copy of
+/// its objects.
+///
+/// `--force` is the case that matters. It is the user waiving their own
+/// uncommitted changes, never a claim about who owns the directory, and it is
+/// where the dirty-worktree gate stops applying — so it must not carry the
+/// removal through. `git worktree remove` refuses this same removal with
+/// `--force`; worktrunk's fast path renames the directory itself instead of
+/// asking git to, so it has to make the check for itself.
+#[rstest]
+fn test_remove_refuses_foreign_repository_at_worktree_path(mut repo: TestRepo) {
+ let worktree_path = repo.add_worktree("feature");
+ let parent = worktree_path.parent().unwrap().to_path_buf();
+ let dir_name = worktree_path.file_name().unwrap().to_str().unwrap();
+
+ // Replace the worktree with an unrelated repository at the same path — the
+ // registration still resolves, and the occupant's own `.git` keeps git
+ // from calling it prunable.
+ std::fs::remove_dir_all(&worktree_path).unwrap();
+ repo.run_git_in(&parent, &["init", "-b", "main", dir_name]);
+ std::fs::write(worktree_path.join("precious.txt"), "unpushed work").unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["remove", "--force", "feature", "--yes"])
+ .output()
+ .unwrap();
+
+ assert!(
+ !output.status.success(),
+ "wt remove --force must refuse a foreign repository at a registered path.\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr),
+ );
+ // The refusal is worth nothing if the directory went anyway: removal
+ // stages by rename and deletes in a detached process, so the exit code
+ // alone would not catch a staged-then-deleted tree.
+ assert!(
+ worktree_path.join("precious.txt").exists(),
+ "the foreign repository's uncommitted file must survive",
+ );
+ assert!(
+ worktree_path.join(".git").is_dir(),
+ "the foreign repository's object store must survive",
+ );
+}
+
#[rstest]
fn test_remove_partial_success(mut repo: TestRepo) {
// Create one valid worktree
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index c15fbb7db..3cd32fcb7 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -539,6 +539,77 @@ fn test_switch_path_holding_no_worktree(repo: TestRepo) {
);
}
+/// A worktree whose directory was deleted and *recreated* gets the same
+/// "directory missing" answer as one merely deleted, rather than a raw `git
+/// rev-parse --git-dir failed (exit 128)`.
+///
+/// The recreation is the point: `Path::exists()` passes it, which is why every
+/// command that resolved the branch used to walk on into git's failure. Asking
+/// git's own `prunable` instead collapses the two spellings of one state onto
+/// one message — see `test_switch_error_missing_worktree_directory` for the
+/// deleted half.
+#[rstest]
+fn test_switch_worktree_directory_recreated(mut repo: TestRepo) {
+ let worktree_path = repo.add_worktree("feature");
+ fs::remove_dir_all(&worktree_path).unwrap();
+ fs::create_dir_all(&worktree_path).unwrap();
+
+ snapshot_switch("switch_worktree_directory_recreated", &repo, &["feature"]);
+}
+
+/// `--create` names a branch that does not exist yet, so the argument is never
+/// tried as a path — even when a worktree is registered at that spelling.
+///
+/// The registered worktree is on a *different* branch, so resolving the
+/// argument as a path would return that worktree and silently drop `--create`.
+/// `resolve_switch_target`'s own `--create` guards do not catch it: they reject
+/// a branch that already exists locally, and this one does not.
+#[rstest]
+fn test_switch_create_ignores_a_worktree_at_that_path(mut repo: TestRepo) {
+ let occupied = repo.root_path().join("docs");
+ repo.add_worktree_at_path("other", &occupied);
+
+ let output = repo
+ .wt_command()
+ .args(["switch", "--create", "docs", "--no-hooks"])
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "stdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr),
+ );
+ let branches = repo.git_output(&["branch", "--format=%(refname:short)"]);
+ assert!(
+ branches.lines().any(|b| b == "docs"),
+ "--create must create the branch rather than switching to the worktree \
+ registered at ./docs, got branches: {branches}"
+ );
+}
+
+/// A trailing separator is stripped before resolution, so a branch whose name
+/// matches a directory in the repository is still found.
+///
+/// This is the shape shell completion produces: `wt switch docs<tab>` completes
+/// against `./docs` and yields `docs/`, which git's ref format rejects as a
+/// branch name — so the branch lookup used to miss a branch sitting right
+/// there.
+#[rstest]
+fn test_switch_branch_name_with_trailing_separator(mut repo: TestRepo) {
+ fs::create_dir_all(repo.root_path().join("docs")).unwrap();
+ fs::write(repo.root_path().join("docs/index.md"), "docs").unwrap();
+ repo.commit("add docs directory");
+ repo.add_worktree("docs");
+
+ snapshot_switch(
+ "switch_branch_name_with_trailing_separator",
+ &repo,
+ &["docs/"],
+ );
+}
+
#[rstest]
fn test_switch_nonexistent_branch(repo: TestRepo) {
// Switching to a nonexistent branch (without --create) should give a clear
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
new file mode 100644
index 000000000..165020d3b
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_worktree_directory_recreated.snap
@@ -0,0 +1,62 @@
+---
+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_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Worktree directory missing for feature
+↳ To clean up, run git worktree prune
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_branch_name_with_trailing_separator.snap b/tests/snapshots/integration__integration_tests__switch__switch_branch_name_with_trailing_separator.snap
new file mode 100644
index 000000000..1bc2de188
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_branch_name_with_trailing_separator.snap
@@ -0,0 +1,62 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - docs/
+ 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_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+▲ Worktree for docs @ _REPO_.docs, but cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
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
new file mode 100644
index 000000000..917ffa575
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_worktree_directory_recreated.snap
@@ -0,0 +1,62 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - 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_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Worktree directory missing for feature
+↳ To clean up, run git worktree prune