Skip to content

fix(gw): resolve a branch to the worktree git already has for it - #1

Open
ohwhen wants to merge 1 commit into
mainfrom
owen/resolve-worktree-by-branch
Open

ohwhen wants to merge 1 commit into
mainfrom
owen/resolve-worktree-by-branch

Conversation

@ohwhen

@ohwhen ohwhen commented Sep 10, 2026

Copy link
Copy Markdown
Owner

Why

This PR fixes gw <branch> failing with fatal: '<branch>' is already used by worktree at ... whenever that worktree was created outside gw.

gw derives the directory from the branch name by replacing slashes with dashes, so owen/feature maps to .worktrees/owen-feature. A worktree made by hand, or renamed since, sits at some other path. gw does not find its derived path, falls through to git worktree add, and git refuses because the branch is already checked out. Completion makes it worse: it lists any branch whose worktree is under .worktrees/, so the branch you tab-completed is exactly the one that then errors.

What changed

  • _gw_path_for_branch asks git worktree list --porcelain where a branch is actually checked out. It reads the path with substr($0, 10) rather than $2, so paths containing spaces survive.
  • gw prefers that path over the derived one. It is assigned once, before the mode dispatch, so -d and -D pick it up too. Deleting a non-conventional worktree previously failed the same way.

Two behaviors improve as a side effect. gw main now cds to the main worktree instead of erroring, and gw -b on an already checked-out branch cds there rather than failing, matching what it already did when the derived directory existed.

gw derived the worktree path from the branch name alone, so a worktree
created outside gw was invisible to it: the derived path did not exist,
gw fell through to `git worktree add`, and git refused because the branch
was already checked out elsewhere.

Ask git where the branch lives before falling back to the derived path.
Setting wt_path once, before the mode dispatch, fixes -d and -D too.

Claude-Session: https://claude.ai/code/session_01J467etVSU3EDkjv3CXXFGi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant