Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Change argument resolution to branch-first (#197)
Maximilian Roosfaf769f1b532
diff --git a/docs/content/remove.md b/docs/content/remove.mdindex 2fa4a9d9d..48e2c6ad0 100644--- a/docs/content/remove.md+++ b/docs/content/remove.md@@ -56,7 +56,9 @@ Use `-D` to force-delete branches with unmerged changes. Use `--no-delete-branchRemoval runs in the background by default (returns immediately). Logs are written to `.git/wt-logs/{branch}-remove.log`. Use `--no-background` to run in the foreground.-Arguments use path-first resolution—see [wt switch](@/switch.md#argument-resolution). Shortcuts: `@` (current), `-` (previous), `^` (main worktree).+## Shortcuts++`@` (current), `-` (previous), `^` (main worktree). See [wt switch](@/switch.md#argument-resolution) for argument resolution.## See alsodiff --git a/docs/content/switch.md b/docs/content/switch.mdindex 408fd9ec0..4d84034bc 100644--- a/docs/content/switch.md+++ b/docs/content/switch.md@@ -55,13 +55,9 @@ wt switch --create fix --base=@ # Branch from current HEAD## Argument resolution-Arguments resolve by checking the filesystem before git branches:+If the branch has a worktree, switch to it. Otherwise, create a worktree at the expected path.-1. Compute expected path from argument (using configured path template)-2. If worktree exists at that path, switch to it-3. Otherwise, look up as branch name--If the path and branch resolve to different worktrees (e.g., `repo.foo/` tracks branch `bar`), the path takes precedence.+If the expected path is occupied by a different branch's worktree, an error is raised.## See alsodiff --git a/src/cli.rs b/src/cli.rsindex 7890bbe78..2bbb9c6e3 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -2057,13 +2057,9 @@ wt switch --create fix --base=@ # Branch from current HEAD## Argument resolution-Arguments resolve by checking the filesystem before git branches:+If the branch has a worktree, switch to it. Otherwise, create a worktree at the expected path.-1. Compute expected path from argument (using configured path template)-2. If worktree exists at that path, switch to it-3. Otherwise, look up as branch name--If the path and branch resolve to different worktrees (e.g., `repo.foo/` tracks branch `bar`), the path takes precedence.+If the expected path is occupied by a different branch's worktree, an error is raised.## See also@@ -2166,7 +2162,9 @@ Use `-D` to force-delete branches with unmerged changes. Use `--no-delete-branchRemoval runs in the background by default (returns immediately). Logs are written to `.git/wt-logs/{branch}-remove.log`. Use `--no-background` to run in the foreground.-Arguments use path-first resolution—see [wt switch](@/switch.md#argument-resolution). Shortcuts: `@` (current), `-` (previous), `^` (main worktree).+## Shortcuts++`@` (current), `-` (previous), `^` (main worktree). See [wt switch](@/switch.md#argument-resolution) for argument resolution.## See alsodiff --git a/src/commands/mod.rs b/src/commands/mod.rsindex ead9ff5d7..785d1885e 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -38,7 +38,7 @@ pub use standalone::{};pub use worktree::{compute_worktree_path, handle_remove, handle_remove_by_path, handle_remove_current,- handle_switch, resolve_worktree_path_first,+ handle_switch, resolve_worktree_arg,};// Re-export Shell from the canonical locationdiff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex f4c7f71eb..40f535b3a 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -126,25 +126,22 @@ use super::command_executor::CommandContext;use super::hooks::{HookFailureStrategy, HookPipeline, HookSource};use super::repository_ext::RepositoryCliExt;-/// Resolve a worktree argument using path-first lookup.+/// Resolve a worktree argument using branch-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)+/// 2. Resolve argument as branch name+/// 3. If branch has a worktree, return it+/// 4. Otherwise, return branch-only (no worktree)///-/// 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(+/// If the branch has no worktree but expected path is occupied by another+/// branch's worktree, an error is raised.+pub fn resolve_worktree_arg(repo: &Repository,name: &str,config: &WorktrunkConfig,) -> anyhow::Result<ResolvedWorktree> {- // Special symbols bypass path-first lookup+ // Special symbolsmatch name {"@" => {// Current worktree by path - works even in detached HEAD@@ -164,46 +161,31 @@ pub fn resolve_worktree_path_first(_ => {}}- // Compute expected path for this argument- let expected_path = compute_worktree_path(repo, name, config)?;+ // Resolve as branch name+ let branch = repo.resolve_worktree_name(name)?;- // 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());- }- }+ // Branch-first: check if branch has worktree anywhere+ if let Some(path) = repo.worktree_for_branch(&branch)? {return Ok(ResolvedWorktree::Worktree {path,- branch: branch_at_path,+ branch: Some(branch),});}- // 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 }),+ // No worktree for branch - check if expected path is occupied+ let expected_path = compute_worktree_path(repo, name, config)?;+ if let Some((_, occupant_branch)) = repo.worktree_at_path(&expected_path)? {+ // Path is occupied by a different branch's worktree+ return Err(GitError::WorktreePathOccupied {+ branch,+ path: expected_path,+ occupant: occupant_branch,+ }+ .into());}++ // No worktree for branch or at expected path+ Ok(ResolvedWorktree::BranchOnly { branch })}/// Compute the expected worktree path for a branch name.@@ -369,20 +351,7 @@ pub fn handle_switch((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)? {- // Check if directory actually exists (git might have stale metadata)- if !existing_path.exists() {- let branch = path_branch.unwrap_or_else(|| resolved_branch.clone());- return Err(GitError::WorktreeMissing { branch }.into());- }- // Worktree exists at expected path - switch to it regardless of its branch- let _ = repo.record_switch_previous(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+ // Branch-first lookup: check if branch has a worktree anywherematch repo.worktree_for_branch(&resolved_branch)? {Some(existing_path) if existing_path.exists() => {let _ = repo.record_switch_previous(new_previous.as_deref());@@ -397,7 +366,23 @@ pub fn handle_switch(None => {}}- // No existing worktree at expected path or for branch - will create one+ // No worktree for branch - check if expected path is occupied by a different branch's worktree+ if let Some((existing_path, path_branch)) = repo.worktree_at_path(&expected_path)? {+ if !existing_path.exists() {+ // Stale worktree metadata - git thinks there's a worktree but directory is gone+ let branch = path_branch.unwrap_or_else(|| resolved_branch.clone());+ return Err(GitError::WorktreeMissing { branch }.into());+ }+ // Path is occupied by a different branch's worktree+ return Err(GitError::WorktreePathOccupied {+ branch: resolved_branch.clone(),+ path: expected_path,+ occupant: path_branch,+ }+ .into());+ }++ // No existing worktree for branch or at expected path - will create onelet worktree_path = expected_path;// If the target path already exists but is NOT a worktree (e.g., stale directory),diff --git a/src/git/error.rs b/src/git/error.rsindex 8d9e66241..6c0b56730 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -73,11 +73,6 @@ pub enum GitError {WorktreePathExists {path: PathBuf,},- WorktreePathMismatch {- branch: String,- expected_path: PathBuf,- actual_path: PathBuf,- },WorktreeCreationFailed {branch: String,base_branch: Option<String>,@@ -263,25 +258,6 @@ 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);- write!(- f,- "{}\n\n{}",- error_message(cformat!(- "Ambiguous: <bold>{expected}</> has a worktree on a different branch, but branch <bold>{branch}</> exists @ <bold>{actual}</>"- )),- hint_message(cformat!(- "Use <bright-black>wt list</> to see worktree-branch mappings"- ))- )- }-GitError::WorktreeCreationFailed {branch,base_branch,diff --git a/src/main.rs b/src/main.rsindex bea96463a..c4a6fb0fe 100644--- a/src/main.rs+++ b/src/main.rs@@ -32,8 +32,8 @@ use commands::{handle_configure_shell, handle_hook_show, handle_init, handle_list, handle_merge,handle_rebase, handle_remove, handle_remove_by_path, handle_remove_current, handle_show_theme,handle_squash, handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,- handle_state_show, handle_switch, handle_unconfigure_shell, resolve_worktree_path_first,- run_hook, step_commit, step_for_each,+ handle_state_show, handle_switch, handle_unconfigure_shell, resolve_worktree_arg, run_hook,+ step_commit, step_for_each,};use output::{execute_user_command, handle_remove_output, handle_switch_output};@@ -1320,8 +1320,7 @@ fn main() {// to avoid deleting the directory we're currently inlet 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.+ // Partition worktrees into current, others, and branch-only.// Collect errors for invalid names so we can report all of them.let mut others = Vec::new();let mut branch_only = Vec::new();@@ -1329,7 +1328,7 @@ fn main() {let mut errors: Vec<anyhow::Error> = Vec::new();for worktree_name in &worktrees {- match resolve_worktree_path_first(&repo, worktree_name, &config) {+ match resolve_worktree_arg(&repo, worktree_name, &config) {Ok(ResolvedWorktree::Worktree { path, branch }) => {if Some(&path) == current_worktree.as_ref() {current = Some((path, branch));diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rsindex b608caf72..bd9522780 100644--- a/tests/integration_tests/git_error_display.rs+++ b/tests/integration_tests/git_error_display.rs@@ -235,17 +235,6 @@ fn display_project_config_not_found() {assert_snapshot!("project_config_not_found", err.to_string());}-#[test]-fn display_worktree_path_mismatch() {- let err = GitError::WorktreePathMismatch {- branch: "feature".into(),- expected_path: PathBuf::from("/tmp/repo.feature"),- actual_path: PathBuf::from("/tmp/repo.other"),- };-- assert_snapshot!("worktree_path_mismatch", err.to_string());-}-#[test]fn display_parse_error() {let err = GitError::ParseError {diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_path_mismatch.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_path_mismatch.snapdeleted file mode 100644index f5b4467a6..000000000--- a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_path_mismatch.snap+++ /dev/null@@ -1,7 +0,0 @@-----source: tests/integration_tests/git_error_display.rs-expression: err.to_string()-----❌ [31mAmbiguous: [1m/tmp/repo.feature[22m has a worktree on a different branch, but branch [1mfeature[22m exists @ [1m/tmp/repo.other[22m[39m--💡 [2mUse [90mwt list[39m to see worktree-branch mappings[22mdiff --git a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap b/tests/snapshots/integration__integration_tests__help__help_remove_long.snapindex 2ce8cdab0..ec05ffacc 100644--- a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap@@ -99,7 +99,9 @@ Use [2m-D[0m to force-delete branches with unmerged changes. Use [2m--no-deleRemoval runs in the background by default (returns immediately). Logs are written to [2m.git/wt-logs/{branch}-remove.log[0m. Use [2m--no-background[0m to runin the foreground.-Arguments use path-first resolution—see wt switch. Shortcuts: [2m@[0m (current), [2m-[0m (previous), [2m^[0m (main worktree).+[32mShortcuts++[2m@[0m (current), [2m-[0m (previous), [2m^[0m (main worktree). See wt switch for argument resolution.[32mSee alsodiff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snapindex 9b48c6e5c..7ad96da37 100644--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap@@ -108,13 +108,9 @@ The [2m--create[0m flag creates a new branch from [2m--base[0m (defaults to[32mArgument resolution-Arguments resolve by checking the filesystem before git branches:+If the branch has a worktree, switch to it. Otherwise, create a worktree at the expected path.-1. Compute expected path from argument (using configured path template)-2. If worktree exists at that path, switch to it-3. Otherwise, look up as branch name--If the path and branch resolve to different worktrees (e.g., [2mrepo.foo/[0m tracks branch [2mbar[0m), the path takes precedence.+If the expected path is occupied by a different branch's worktree, an error is raised.[32mSee also