Skip to content

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

feat: Introduce path-first worktree resolution

Maximilian Roosb0b8358670dc
diff --git a/README.md b/README.md
index a0138d04c..dd7e5a92d 100644
--- a/README.md
+++ b/README.md
@@ -389,9 +389,21 @@ Global Options:
## Operation
+### Worktree resolution
+
+Arguments are resolved using **path-first lookup**:
+
+1. Compute the expected path for the argument (using the configured path template)
+2. If a worktree exists at that path, switch to it (regardless of what branch it's on)
+3. Otherwise, treat the argument as a branch name
+
+**Example**: If `repo.foo/` exists but is on branch `bar`:
+- `wt switch foo` switches to `repo.foo/` (the `bar` branch worktree)
+- `wt switch bar` also works (falls back to branch lookup)
+
### Switching to Existing Worktree
-- If worktree exists for branch, changes directory via shell integration
+- If worktree exists at expected path or for branch, changes directory via shell integration
- No hooks run
- No branch creation
@@ -654,6 +666,27 @@ Removes worktree directory, git metadata, and branch. Requires clean working tre
- Removes specified worktree(s) and branches
- Current worktree removed last (switches to main first)
+### Worktree resolution
+
+Arguments are resolved to worktrees using **path-first lookup**:
+
+1. Compute the expected path for the argument (using the configured path template)
+2. If a worktree exists at that path, use it (regardless of what branch it's on)
+3. Otherwise, treat the argument as a branch name
+
+**Example**: If `repo.foo/` exists but is on branch `bar`:
+- `wt remove foo` removes `repo.foo/` and the `bar` branch
+- `wt remove bar` also works (falls back to branch lookup)
+
+**Conflict detection**: If path `repo.foo/` has a worktree on branch `bar`, but
+branch `foo` has a different worktree at `repo.bar/`, an error is raised.
+
+**Special arguments**:
+
+- `@` - current worktree (by path, works in detached HEAD)
+- `-` - previous worktree (from switch history)
+- `^` - main/default branch worktree
+
### Branch deletion
By default, branches are deleted only when their content has been integrated:
diff --git a/src/cli.rs b/src/cli.rs
index d103f30c9..18eab21e9 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -736,9 +736,21 @@ jq '.[] | select(.is_current == true)'
/// Switch to a worktree
#[command(after_long_help = r#"## Operation
+### Worktree resolution
+
+Arguments are resolved using **path-first lookup**:
+
+1. Compute the expected path for the argument (using the configured path template)
+2. If a worktree exists at that path, switch to it (regardless of what branch it's on)
+3. Otherwise, treat the argument as a branch name
+
+**Example**: If `repo.foo/` exists but is on branch `bar`:
+- `wt switch foo` switches to `repo.foo/` (the `bar` branch worktree)
+- `wt switch bar` also works (falls back to branch lookup)
+
### Switching to Existing Worktree
-- If worktree exists for branch, changes directory via shell integration
+- If worktree exists at expected path or for branch, changes directory via shell integration
- No hooks run
- No branch creation
@@ -866,6 +878,27 @@ Removes worktree directory, git metadata, and branch. Requires clean working tre
- Removes specified worktree(s) and branches
- Current worktree removed last (switches to main first)
+### Worktree resolution
+
+Arguments are resolved to worktrees using **path-first lookup**:
+
+1. Compute the expected path for the argument (using the configured path template)
+2. If a worktree exists at that path, use it (regardless of what branch it's on)
+3. Otherwise, treat the argument as a branch name
+
+**Example**: If `repo.foo/` exists but is on branch `bar`:
+- `wt remove foo` removes `repo.foo/` and the `bar` branch
+- `wt remove bar` also works (falls back to branch lookup)
+
+**Conflict detection**: If path `repo.foo/` has a worktree on branch `bar`, but
+branch `foo` has a different worktree at `repo.bar/`, an error is raised.
+
+**Special arguments**:
+
+- `@` - current worktree (by path, works in detached HEAD)
+- `-` - previous worktree (from switch history)
+- `^` - main/default branch worktree
+
### Branch deletion
By default, branches are deleted only when their content has been integrated:
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 20bebcfca..c84e574ac 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -216,7 +216,7 @@ pub fn handle_merge(
main_path: destination_path.clone(),
worktree_path: worktree_root,
changed_directory: true,
- branch_name: current_branch.clone(),
+ branch_name: Some(current_branch.clone()),
no_delete_branch: false,
force_delete: false,
target_branch: Some(target_branch.clone()),
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 48feb9fff..588a924a0 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -31,7 +31,10 @@ pub use standalone::{
RebaseResult, SquashResult, handle_rebase, handle_squash, handle_standalone_add_approvals,
handle_standalone_clear_approvals, handle_standalone_commit, handle_standalone_run_hook,
};
-pub use worktree::{handle_remove, handle_switch};
+pub use worktree::{
+ handle_remove, handle_remove_by_path, handle_remove_current, handle_switch,
+ resolve_worktree_path_first,
+};
// Re-export Shell from the canonical location
pub use worktrunk::shell::Shell;
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index da186a633..085d79f7c 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -30,6 +30,18 @@ pub trait RepositoryCliExt {
force_delete: bool,
) -> anyhow::Result<RemoveResult>;
+ /// Remove the current worktree (handles detached HEAD state).
+ ///
+ /// This method removes the worktree we're currently in, even if HEAD is detached.
+ /// It finds the branch from:
+ /// 1. The worktree's metadata (if not detached)
+ /// 2. The reflog (if detached from a branch)
+ fn remove_current_worktree(
+ &self,
+ no_delete_branch: bool,
+ force_delete: bool,
+ ) -> anyhow::Result<RemoveResult>;
+
/// Prepare the target worktree for push by auto-stashing non-overlapping changes when safe.
fn prepare_target_worktree(
&self,
@@ -110,7 +122,42 @@ impl RepositoryCliExt for Repository {
main_path,
worktree_path,
changed_directory,
- branch_name: branch_name.to_string(),
+ branch_name: Some(branch_name.to_string()),
+ no_delete_branch,
+ force_delete,
+ target_branch: None,
+ })
+ }
+
+ fn remove_current_worktree(
+ &self,
+ no_delete_branch: bool,
+ force_delete: bool,
+ ) -> anyhow::Result<RemoveResult> {
+ // Get current worktree path
+ let current_path = self.worktree_root()?;
+
+ // Find this worktree in the list to get its metadata
+ let worktrees = self.list_worktrees()?;
+ let current_wt = worktrees
+ .worktrees
+ .iter()
+ .find(|wt| wt.path == current_path);
+
+ // Get branch name if available (None for detached HEAD)
+ let branch_name = current_wt.and_then(|wt| wt.branch.clone());
+
+ // Ensure the working tree is clean
+ self.ensure_clean_working_tree(Some("remove worktree"))?;
+
+ // Get main worktree path (we're removing current, so we'll cd to main)
+ let main_path = worktrees.main().path.clone();
+
+ Ok(RemoveResult::RemovedWorktree {
+ main_path,
+ worktree_path: current_path,
+ changed_directory: true,
+ branch_name,
no_delete_branch,
force_delete,
target_branch: None,
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 6aa864224..d5193ca2b 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -113,13 +113,118 @@ use color_print::cformat;
use std::path::PathBuf;
use worktrunk::HookType;
use worktrunk::config::{CommandPhase, WorktrunkConfig};
-use worktrunk::git::{GitError, Repository, is_command_not_approved};
+use worktrunk::git::{GitError, Repository, ResolvedWorktree, is_command_not_approved};
use worktrunk::styling::format_with_gutter;
use super::command_executor::CommandContext;
use super::hooks::{HookFailureStrategy, HookPipeline};
use super::repository_ext::RepositoryCliExt;
+/// Resolve a worktree argument using path-first lookup.
+///
+/// Resolution order:
+/// 1. Special symbols ("@", "-", "^") are handled specially
+/// 2. Compute expected path for the argument using config template
+/// 3. If a worktree exists at that path, return it (regardless of branch)
+/// 4. Otherwise, look up by branch name (standard fallback)
+///
+/// Conflict detection: If expected path has a worktree on branch X, but argument
+/// matches branch Y which has a worktree elsewhere, an error is raised.
+///
+/// This allows `wt remove foo` to target the worktree at `repo.foo/` even if
+/// that worktree is on a different branch.
+pub fn resolve_worktree_path_first(
+ repo: &Repository,
+ name: &str,
+ config: &WorktrunkConfig,
+) -> anyhow::Result<ResolvedWorktree> {
+ // Special symbols bypass path-first lookup
+ match name {
+ "@" => {
+ // Current worktree by path - works even in detached HEAD
+ let path = repo.worktree_root()?;
+ let worktrees = repo.list_worktrees()?;
+ let branch = worktrees
+ .worktrees
+ .iter()
+ .find(|wt| wt.path == path)
+ .and_then(|wt| wt.branch.clone());
+ return Ok(ResolvedWorktree::Worktree { path, branch });
+ }
+ "-" | "^" => {
+ // These resolve to branch names, use standard branch-based lookup
+ return repo.resolve_worktree(name);
+ }
+ _ => {}
+ }
+
+ // Compute expected path for this argument
+ let expected_path = compute_worktree_path(repo, name, config)?;
+
+ // Check if a worktree exists at the expected path
+ if let Some((path, branch_at_path)) = repo.worktree_at_path(&expected_path)? {
+ // Worktree exists at expected path - check for ambiguity
+ // If the argument also matches a different branch with a worktree elsewhere,
+ // that's ambiguous and we should error
+ // Note: resolve_worktree_name won't fail with DetachedHead here because "@"
+ // was already handled in the early return above
+ let branch = repo.resolve_worktree_name(name)?;
+ if branch_at_path.as_deref() != Some(&branch) {
+ // The worktree at expected path is on a different branch than the argument
+ if let Some(other_path) = repo.worktree_for_branch(&branch)? {
+ // And the argument matches a branch that has a worktree elsewhere
+ // This is ambiguous - error to prevent confusion
+ return Err(GitError::WorktreePathMismatch {
+ branch,
+ expected_path,
+ actual_path: other_path,
+ }
+ .into());
+ }
+ }
+ return Ok(ResolvedWorktree::Worktree {
+ path,
+ branch: branch_at_path,
+ });
+ }
+
+ // No worktree at expected path - fall back to branch-based lookup
+ // This handles cases like manually-created worktrees at non-standard paths
+ let branch = repo.resolve_worktree_name(name)?;
+ match repo.worktree_for_branch(&branch)? {
+ Some(path) => Ok(ResolvedWorktree::Worktree {
+ path,
+ branch: Some(branch),
+ }),
+ None => Ok(ResolvedWorktree::BranchOnly { branch }),
+ }
+}
+
+/// Compute the expected worktree path for a branch name.
+fn compute_worktree_path(
+ repo: &Repository,
+ branch: &str,
+ config: &WorktrunkConfig,
+) -> anyhow::Result<PathBuf> {
+ let repo_root = repo.worktree_base()?;
+ let repo_name = repo_root
+ .file_name()
+ .ok_or_else(|| anyhow::anyhow!("Repository path has no filename: {}", repo_root.display()))?
+ .to_str()
+ .ok_or_else(|| {
+ anyhow::anyhow!(
+ "Repository path contains invalid UTF-8: {}",
+ repo_root.display()
+ )
+ })?;
+
+ let relative_path = config
+ .format_path(repo_name, branch)
+ .map_err(|e| anyhow::anyhow!("Failed to format worktree path: {}", e))?;
+
+ Ok(repo_root.join(relative_path))
+}
+
/// Flags indicating which merge operations occurred
#[derive(Debug, Clone, Copy)]
pub struct MergeOperations {
@@ -165,7 +270,8 @@ pub enum RemoveResult {
main_path: PathBuf,
worktree_path: PathBuf,
changed_directory: bool,
- branch_name: String,
+ /// Branch name, if known. None for detached HEAD state.
+ branch_name: Option<String>,
no_delete_branch: bool,
force_delete: bool,
target_branch: Option<String>,
@@ -247,33 +353,41 @@ pub fn handle_switch(
crate::output::warning("--base flag is only used with --create, ignoring")?;
}
- // Check if worktree already exists for this branch
+ // Compute expected worktree path for this branch
+ let expected_path = compute_worktree_path(&repo, &resolved_branch, config)?;
+
+ // Helper to build switch result for an existing worktree
+ let switch_to_existing = |path: PathBuf, branch: String| -> (SwitchResult, String) {
+ let canonical_path = path.canonicalize().unwrap_or(path);
+ let current_dir = std::env::current_dir()
+ .ok()
+ .and_then(|p| p.canonicalize().ok());
+ let already_at_worktree = current_dir
+ .as_ref()
+ .map(|cur| cur == &canonical_path)
+ .unwrap_or(false);
+
+ let result = if already_at_worktree {
+ SwitchResult::AlreadyAt(canonical_path)
+ } else {
+ SwitchResult::Existing(canonical_path)
+ };
+ (result, branch)
+ };
+
+ // Path-first lookup: check if a worktree exists at the expected path
+ if let Some((existing_path, path_branch)) = repo.worktree_at_path(&expected_path)? {
+ // Worktree exists at expected path - switch to it regardless of its branch
+ let _ = repo.record_switch_history(&new_current, new_previous.as_deref());
+ let actual_branch = path_branch.unwrap_or_else(|| resolved_branch.clone());
+ return Ok(switch_to_existing(existing_path, actual_branch));
+ }
+
+ // Fallback: check if branch has a worktree at a different path
match repo.worktree_for_branch(&resolved_branch)? {
Some(existing_path) if existing_path.exists() => {
- // Record successful switch in history for `wt switch -` support
let _ = repo.record_switch_history(&new_current, new_previous.as_deref());
-
- // Canonicalize the path for cleaner display
- let canonical_existing_path = existing_path.canonicalize().unwrap_or(existing_path);
-
- // Check if we're already at this worktree
- let current_dir = std::env::current_dir()
- .ok()
- .and_then(|p| p.canonicalize().ok());
-
- let already_at_worktree = current_dir
- .as_ref()
- .map(|cur| cur == &canonical_existing_path)
- .unwrap_or(false);
-
- return Ok((
- if already_at_worktree {
- SwitchResult::AlreadyAt(canonical_existing_path)
- } else {
- SwitchResult::Existing(canonical_existing_path)
- },
- resolved_branch,
- ));
+ return Ok(switch_to_existing(existing_path, resolved_branch));
}
Some(_) => {
return Err(GitError::WorktreeMissing {
@@ -284,37 +398,14 @@ pub fn handle_switch(
None => {}
}
- // No existing worktree, create one (or reuse target path if available)
- let repo_root = repo.worktree_base()?;
+ // No existing worktree at expected path or for branch - will create one
+ let worktree_path = expected_path;
- let repo_name = repo_root
- .file_name()
- .ok_or_else(|| anyhow::anyhow!("Repository path has no filename: {}", repo_root.display()))?
- .to_str()
- .ok_or_else(|| {
- anyhow::anyhow!(
- "Repository path contains invalid UTF-8: {}",
- repo_root.display()
- )
- })?;
-
- let worktree_path = repo_root.join(
- config
- .format_path(repo_name, &resolved_branch)
- .map_err(|e| anyhow::anyhow!("Failed to format worktree path: {}", e))?,
- );
-
- // If the target path already exists but no worktree is registered for this branch,
+ // If the target path already exists but is NOT a worktree (e.g., stale directory),
// surface a helpful error instead of letting git fail with "already exists".
- if repo.worktree_for_branch(&resolved_branch)?.is_none() && worktree_path.exists() {
- let occupant = Repository::at(&worktree_path)
- .current_branch()
- .ok()
- .flatten();
- return Err(GitError::WorktreePathOccupied {
- branch: resolved_branch.clone(),
+ if worktree_path.exists() {
+ return Err(GitError::WorktreePathExists {
path: worktree_path,
- occupant,
}
.into());
}
@@ -457,6 +548,63 @@ pub fn handle_remove(
repo.remove_worktree_by_name(worktree_name, no_delete_branch, force_delete)
}
+/// Handle removing the current worktree (supports detached HEAD state).
+///
+/// This is the path-based removal that handles the "@" shorthand, including
+/// when HEAD is detached.
+pub fn handle_remove_current(
+ no_delete_branch: bool,
+ force_delete: bool,
+ background: bool,
+) -> anyhow::Result<RemoveResult> {
+ let repo = Repository::current();
+
+ // Show progress (unless running in background - output handler will show command)
+ if !background {
+ crate::output::progress(cformat!("<cyan>Removing current worktree...</>"))?;
+ }
+
+ repo.remove_current_worktree(no_delete_branch, force_delete)
+}
+
+/// Handle removing a worktree by path (for detached non-current worktrees).
+///
+/// This is used when a worktree is in detached HEAD state and we're not
+/// currently in it. We can still remove the worktree, we just don't know
+/// which branch (if any) to delete.
+pub fn handle_remove_by_path(
+ path: &std::path::Path,
+ branch: Option<String>,
+ force_delete: bool,
+ background: bool,
+) -> anyhow::Result<RemoveResult> {
+ let repo = Repository::current();
+
+ if !background {
+ crate::output::progress(cformat!(
+ "<cyan>Removing worktree at <bold>{}</>...</>",
+ worktrunk::path::format_path_for_display(path)
+ ))?;
+ }
+
+ // Check that the worktree is clean
+ let target_repo = Repository::at(path);
+ target_repo.ensure_clean_working_tree(Some("remove worktree"))?;
+
+ // We're not in this worktree, so no directory change needed
+ let current_path = repo.worktree_root()?;
+
+ Ok(RemoveResult::RemovedWorktree {
+ main_path: current_path,
+ worktree_path: path.to_path_buf(),
+ changed_directory: false,
+ branch_name: branch,
+ no_delete_branch: true, // Can't delete branch for detached worktree
+ force_delete,
+ target_branch: None,
+ })
+}
+
impl<'a> CommandContext<'a> {
/// Execute post-create commands sequentially (blocking)
pub fn execute_post_create_commands(&self) -> anyhow::Result<()> {
diff --git a/src/git/error.rs b/src/git/error.rs
index 26fda08d3..223ed3cc9 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -65,6 +65,11 @@ pub enum GitError {
WorktreePathExists {
path: PathBuf,
},
+ WorktreePathMismatch {
+ branch: String,
+ expected_path: PathBuf,
+ actual_path: PathBuf,
+ },
WorktreeCreationFailed {
branch: String,
base_branch: Option<String>,
@@ -193,6 +198,19 @@ impl std::fmt::Display for GitError {
)
}
+ GitError::WorktreePathMismatch {
+ branch,
+ expected_path,
+ actual_path,
+ } => {
+ let expected = format_path_for_display(expected_path);
+ let actual = format_path_for_display(actual_path);
+ cwrite!(
+ f,
+ "{ERROR_EMOJI} <red>Ambiguous: <bold>{expected}</> has a worktree on a different branch, but branch <bold>{branch}</> exists at <bold>{actual}</></>\n\n{HINT_EMOJI} <dim>Use 'wt list' to see worktree-branch mappings</>"
+ )
+ }
+
GitError::WorktreeCreationFailed {
branch,
base_branch,
diff --git a/src/git/mod.rs b/src/git/mod.rs
index ed6f447f4..85e82a13e 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -39,7 +39,7 @@ pub use error::{
exit_code,
is_command_not_approved,
};
-pub use repository::{Repository, set_base_path};
+pub use repository::{Repository, ResolvedWorktree, set_base_path};
/// Category of branch for completion display
#[derive(Debug, Clone, PartialEq)]
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 052ede963..0795286c9 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -1,4 +1,4 @@
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
@@ -10,6 +10,27 @@ use super::{
SwitchHistory, Worktree, WorktreeList,
};
+/// Result of resolving a worktree name.
+///
+/// Used by `resolve_worktree` to handle different resolution outcomes:
+/// - A worktree exists (with optional branch for detached HEAD)
+/// - Only a branch exists (no worktree)
+#[derive(Debug, Clone)]
+pub enum ResolvedWorktree {
+ /// A worktree was found
+ Worktree {
+ /// The filesystem path to the worktree
+ path: PathBuf,
+ /// The branch name, if known (None for detached HEAD)
+ branch: Option<String>,
+ },
+ /// Only a branch exists (no worktree)
+ BranchOnly {
+ /// The branch name
+ branch: String,
+ },
+}
+
/// Global base path for repository operations, set by -C flag
static BASE_PATH: OnceLock<PathBuf> = OnceLock::new();
@@ -346,6 +367,50 @@ impl Repository {
}
}
+ /// Resolve a worktree by name, returning its path and branch (if known).
+ ///
+ /// Unlike `resolve_worktree_name` which returns a branch name, this returns
+ /// the worktree path directly. This is useful for commands like `wt remove`
+ /// that operate on worktrees, not branches.
+ ///
+ /// # Arguments
+ /// * `name` - The worktree name to resolve:
+ /// - "@" for current worktree (works even in detached HEAD)
+ /// - "-" for previous branch's worktree
+ /// - "^" for main/default branch's worktree
+ /// - any other string is treated as a branch name
+ ///
+ /// # Returns
+ /// - `Worktree { path, branch }` if a worktree exists
+ /// - `BranchOnly { branch }` if only the branch exists (no worktree)
+ /// - `Err` if neither worktree nor branch exists
+ pub fn resolve_worktree(&self, name: &str) -> anyhow::Result<ResolvedWorktree> {
+ match name {
+ "@" => {
+ // Current worktree by path - works even in detached HEAD
+ let path = self.worktree_root()?;
+ let worktrees = self.list_worktrees()?;
+ let branch = worktrees
+ .worktrees
+ .iter()
+ .find(|wt| wt.path == path)
+ .and_then(|wt| wt.branch.clone());
+ Ok(ResolvedWorktree::Worktree { path, branch })
+ }
+ _ => {
+ // Resolve to branch name first, then find its worktree
+ let branch = self.resolve_worktree_name(name)?;
+ match self.worktree_for_branch(&branch)? {
+ Some(path) => Ok(ResolvedWorktree::Worktree {
+ path,
+ branch: Some(branch),
+ }),
+ None => Ok(ResolvedWorktree::BranchOnly { branch }),
+ }
+ }
+ }
+ }
+
/// Get the default branch name for the repository.
///
/// **Performance note:** This method may trigger a network call on first invocation
@@ -1061,6 +1126,24 @@ impl Repository {
.map(|wt| wt.path.clone()))
}
+ /// Find the worktree at a given path, returning its branch if known.
+ ///
+ /// Returns `Some((path, branch))` if a worktree exists at the path,
+ /// where `branch` is `None` for detached HEAD worktrees.
+ pub fn worktree_at_path(
+ &self,
+ path: &Path,
+ ) -> anyhow::Result<Option<(PathBuf, Option<String>)>> {
+ let worktrees = self.list_worktrees()?;
+ let canonical_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
+
+ Ok(worktrees
+ .worktrees
+ .iter()
+ .find(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()) == canonical_path)
+ .map(|wt| (wt.path.clone(), wt.branch.clone())))
+ }
+
/// Get branches that don't have worktrees (available for switch).
pub fn available_branches(&self) -> anyhow::Result<Vec<String>> {
let all_branches = self.all_branches()?;
diff --git a/src/main.rs b/src/main.rs
index 4e7175a59..2038df95e 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,6 +1,7 @@
use anyhow::Context;
use clap::FromArgMatches;
use color_print::cformat;
+use std::path::PathBuf;
use std::process;
use worktrunk::config::{WorktrunkConfig, set_config_path};
use worktrunk::git::{Repository, exit_code, is_command_not_approved, set_base_path};
@@ -26,9 +27,10 @@ use commands::{
ConfigAction, RebaseResult, SquashResult, handle_cache_clear, handle_cache_refresh,
handle_cache_show, handle_config_create, handle_config_show, handle_config_status_set,
handle_config_status_unset, handle_configure_shell, handle_init, handle_list, handle_merge,
- handle_rebase, handle_remove, handle_squash, handle_standalone_add_approvals,
- handle_standalone_clear_approvals, handle_standalone_commit, handle_standalone_run_hook,
- handle_switch, handle_unconfigure_shell,
+ handle_rebase, handle_remove, handle_remove_by_path, handle_remove_current, handle_squash,
+ handle_standalone_add_approvals, handle_standalone_clear_approvals, handle_standalone_commit,
+ handle_standalone_run_hook, handle_switch, handle_unconfigure_shell,
+ resolve_worktree_path_first,
};
use output::{execute_user_command, handle_remove_output, handle_switch_output};
@@ -677,66 +679,86 @@ fn main() {
delete_branch,
force_delete,
background,
- } => (|| -> anyhow::Result<()> {
- // Validate conflicting flags
- if !delete_branch && force_delete {
- return Err(worktrunk::git::GitError::Other {
- message: "Cannot use --force-delete with --no-delete-branch".into(),
+ } => WorktrunkConfig::load()
+ .context("Failed to load config")
+ .and_then(|config| {
+ // Validate conflicting flags
+ if !delete_branch && force_delete {
+ return Err(worktrunk::git::GitError::Other {
+ message: "Cannot use --force-delete with --no-delete-branch".into(),
+ }
+ .into());
}
- .into());
- }
- let repo = Repository::current();
+ if worktrees.is_empty() {
+ // No worktrees specified, remove current worktree
+ // Uses path-based removal to handle detached HEAD state
+ let result = handle_remove_current(!delete_branch, force_delete, background)?;
+ handle_remove_output(&result, None, background)
+ } else {
+ use worktrunk::git::ResolvedWorktree;
- if worktrees.is_empty() {
- // No worktrees specified, remove current worktree
- let current_branch = repo.resolve_worktree_name("@")?;
- let result =
- handle_remove(&current_branch, !delete_branch, force_delete, background)?;
- handle_remove_output(&result, None, background)
- } else {
- // When removing multiple worktrees, we need to handle the current worktree last
- // to avoid deleting the directory we're currently in
- let current_worktree = repo.worktree_root().ok();
-
- // Partition worktrees into current and others, storing resolved names
- let mut others = Vec::new();
- let mut current = None;
-
- for worktree_name in &worktrees {
- // Resolve "@" to current branch (fail fast on errors like detached HEAD)
- let resolved = repo.resolve_worktree_name(worktree_name)?;
-
- // Check if this is the current worktree by comparing branch names
- if let Ok(Some(worktree_path)) = repo.worktree_for_branch(&resolved) {
- if Some(&worktree_path) == current_worktree.as_ref() {
- current = Some(resolved);
+ let repo = Repository::current();
+ // When removing multiple worktrees, we need to handle the current worktree last
+ // to avoid deleting the directory we're currently in
+ let current_worktree = repo.worktree_root().ok();
+
+ // Partition worktrees into current, others, and branch-only using path-first
+ // resolution, which checks expected path before falling back to branch lookup
+ let mut others = Vec::new();
+ let mut branch_only = Vec::new();
+ let mut current: Option<(PathBuf, Option<String>)> = None;
+
+ for worktree_name in &worktrees {
+ match resolve_worktree_path_first(&repo, worktree_name, &config)? {
+ ResolvedWorktree::Worktree { path, branch } => {
+ if Some(&path) == current_worktree.as_ref() {
+ current = Some((path, branch));
+ } else {
+ others.push((path, branch));
+ }
+ }
+ ResolvedWorktree::BranchOnly { branch } => {
+ branch_only.push(branch);
+ }
+ }
+ }
+
+ // Remove other worktrees first
+ for (path, branch) in &others {
+ if let Some(branch_name) = branch {
+ let result = handle_remove(
+ branch_name,
+ !delete_branch,
+ force_delete,
+ background,
+ )?;
+ handle_remove_output(&result, Some(branch_name), background)?;
} else {
- others.push(resolved);
+ // Non-current worktree is detached - remove by path (no branch to delete)
+ let result =
+ handle_remove_by_path(path, None, force_delete, background)?;
+ handle_remove_output(&result, None, background)?;
}
- } else {
- // Worktree doesn't exist or branch not found, will error when we try to remove
- others.push(resolved);
}
- }
- // Remove others first, then current last
- // Progress messages shown by handle_remove_output for all cases
- for resolved in &others {
- let result = handle_remove(resolved, !delete_branch, force_delete, background)?;
- handle_remove_output(&result, Some(resolved), background)?;
- }
+ // Handle branch-only cases (no worktree)
+ for branch in &branch_only {
+ let result =
+ handle_remove(branch, !delete_branch, force_delete, background)?;
+ handle_remove_output(&result, Some(branch), background)?;
+ }
- // Remove current worktree last (if it was in the list)
- if let Some(resolved) = current {
- let result =
- handle_remove(&resolved, !delete_branch, force_delete, background)?;
- handle_remove_output(&result, Some(&resolved), background)?;
- }
+ // Remove current worktree last (if it was in the list)
+ if let Some((_path, branch)) = current {
+ let result =
+ handle_remove_current(!delete_branch, force_delete, background)?;
+ handle_remove_output(&result, branch.as_deref(), background)?;
+ }
- Ok(())
- }
- })(),
+ Ok(())
+ }
+ }),
Commands::Merge {
target,
squash,
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 0bd36d793..af0dd8b50 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -293,6 +293,25 @@ fn build_remove_command(
}
}
+/// Build the shell command for background worktree removal (no branch)
+fn build_remove_command_no_branch(worktree_path: &std::path::Path) -> String {
+ use shell_escape::escape;
+
+ let worktree_path_str = worktree_path.to_string_lossy();
+ let worktree_escaped = escape(worktree_path_str.as_ref().into());
+
+ // Stop fsmonitor daemon first (best effort - ignore errors)
+ let stop_fsmonitor = format!(
+ "git -C {} fsmonitor--daemon stop 2>/dev/null || true",
+ worktree_escaped
+ );
+
+ format!(
+ "{} && git worktree remove {}",
+ stop_fsmonitor, worktree_escaped
+ )
+}
+
/// Handle output for a remove operation
pub fn handle_remove_output(
result: &RemoveResult,
@@ -312,7 +331,7 @@ pub fn handle_remove_output(
main_path,
worktree_path,
*changed_directory,
- branch_name,
+ branch_name.as_deref(),
*no_delete_branch,
*force_delete,
target_branch.as_deref(),
@@ -370,7 +389,7 @@ fn handle_removed_worktree_output(
main_path: &std::path::Path,
worktree_path: &std::path::Path,
changed_directory: bool,
- branch_name: &str,
+ branch_name: Option<&str>,
no_delete_branch: bool,
force_delete: bool,
target_branch: Option<&str>,
@@ -385,6 +404,32 @@ fn handle_removed_worktree_output(
let repo = worktrunk::git::Repository::current();
+ // Handle detached HEAD case (no branch known)
+ let Some(branch_name) = branch_name else {
+ // No branch associated - just remove the worktree
+ if background {
+ super::progress(
+ "Removing worktree in background (detached HEAD, no branch to delete)",
+ )?;
+ let remove_command = build_remove_command_no_branch(worktree_path);
+ spawn_detached(&repo, main_path, &remove_command, "detached", "remove")?;
+ } else {
+ let target_repo = worktrunk::git::Repository::at(worktree_path);
+ let _ = target_repo.run_command(&["fsmonitor--daemon", "stop"]);
+ if let Err(err) = repo.remove_worktree(worktree_path) {
+ return Err(GitError::WorktreeRemovalFailed {
+ branch: "(detached)".into(),
+ path: worktree_path.to_path_buf(),
+ error: err.to_string(),
+ }
+ .into());
+ }
+ super::success("Removed worktree (detached HEAD, no branch to delete)")?;
+ }
+ super::flush()?;
+ return Ok(());
+ };
+
if background {
// Background mode: spawn detached process
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 1de987274..ff9d42bc7 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -330,6 +330,50 @@ fn test_remove_branch_only_force_delete() {
);
}
+/// Test that remove works from a detached HEAD state in a worktree.
+///
+/// When in detached HEAD, we should still be able to remove the current worktree
+/// using path-based removal (no branch deletion).
+#[test]
+fn test_remove_from_detached_head_in_worktree() {
+ let mut repo = setup_remove_repo();
+
+ let worktree_path = repo.add_worktree("feature-detached");
+
+ // Detach HEAD in the worktree
+ repo.detach_head_in_worktree("feature-detached");
+
+ // Run remove from within the detached worktree (should still work)
+ snapshot_remove(
+ "remove_from_detached_head_in_worktree",
+ &repo,
+ &[],
+ Some(&worktree_path),
+ );
+}
+
+/// Test that `wt remove @` works from a detached HEAD state in a worktree.
+///
+/// This should behave identically to `wt remove` (no args) - path-based removal
+/// without branch deletion. The `@` symbol refers to the current worktree.
+#[test]
+fn test_remove_at_from_detached_head_in_worktree() {
+ let mut repo = setup_remove_repo();
+
+ let worktree_path = repo.add_worktree("feature-detached-at");
+
+ // Detach HEAD in the worktree
+ repo.detach_head_in_worktree("feature-detached-at");
+
+ // Run `wt remove @` from within the detached worktree (should behave same as no args)
+ snapshot_remove(
+ "remove_at_from_detached_head_in_worktree",
+ &repo,
+ &["@"],
+ Some(&worktree_path),
+ );
+}
+
/// Test that a branch with matching tree content (but not an ancestor) is deleted.
///
/// This simulates a squash merge workflow where:
diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
index 6876351d6..de3cd59df 100644
--- a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
@@ -62,6 +62,27 @@ Removes worktree directory, git metadata, and branch. Requires clean working tre
- Removes specified worktree(s) and branches
- Current worktree removed last (switches to main first)
+### Worktree resolution
+
+Arguments are resolved to worktrees using path-first lookup:
+
+1. Compute the expected path for the argument (using the configured path template)
+2. If a worktree exists at that path, use it (regardless of what branch it's on)
+3. Otherwise, treat the argument as a branch name
+
+Example: If repo.foo/ exists but is on branch bar:
+- wt remove foo removes repo.foo/ and the bar branch
+- wt remove bar also works (falls back to branch lookup)
+
+Conflict detection: If path repo.foo/ has a worktree on branch bar, but
+branch foo has a different worktree at repo.bar/, an error is raised.
+
+Special arguments:
+
+- @ - current worktree (by path, works in detached HEAD)
+- - - previous worktree (from switch history)
+- ^ - main/default branch worktree
+
### Branch deletion
By default, branches are deleted only when their content has been integrated:
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
index d436b0ac0..c0382a635 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
@@ -58,9 +58,21 @@ Global Options:
Operation
+### Worktree resolution
+
+Arguments are resolved using path-first lookup:
+
+1. Compute the expected path for the argument (using the configured path template)
+2. If a worktree exists at that path, switch to it (regardless of what branch it's on)
+3. Otherwise, treat the argument as a branch name
+
+Example: If repo.foo/ exists but is on branch bar:
+- wt switch foo switches to repo.foo/ (the bar branch worktree)
+- wt switch bar also works (falls back to branch lookup)
+
### Switching to Existing Worktree
-- If worktree exists for branch, changes directory via shell integration
+- If worktree exists at expected path or for branch, changes directory via shell integration
- No hooks run
- No branch creation
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_at_from_detached_head_in_worktree.snap b/tests/snapshots/integration__integration_tests__remove__remove_at_from_detached_head_in_worktree.snap
new file mode 100644
index 000000000..3176e5419
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_at_from_detached_head_in_worktree.snap
@@ -0,0 +1,27 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "@"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1735776000"
+ WORKTRUNK_BIN: ""
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+πŸ”„ Removing worktree in background (detached HEAD, no branch to delete)
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_from_detached_head_in_worktree.snap b/tests/snapshots/integration__integration_tests__remove__remove_from_detached_head_in_worktree.snap
new file mode 100644
index 000000000..aabaf4a3d
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_from_detached_head_in_worktree.snap
@@ -0,0 +1,26 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1735776000"
+ WORKTRUNK_BIN: ""
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+πŸ”„ Removing worktree in background (detached HEAD, no branch to delete)
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied.snap b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied.snap
index 2ba0f0d02..5f977516e 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied.snap
@@ -26,6 +26,6 @@ exit_code: 1
----- stdout -----
----- stderr -----
-❌ Cannot create worktree for occupied-branch: target path already exists
+❌ Directory already exists: [REPO]/../repo.occupied-branch
-πŸ’‘ Reuse the existing worktree at [REPO]/../repo.occupied-branch or remove it before retrying
+πŸ’‘ Remove the directory or use a different branch name