Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,9 @@ Select branch or worktree (j/k, / to filter, c to mark, ? for help)

Navigate with the arrow keys, `j`/`k`, or `Ctrl-N`/`Ctrl-P`. Jump to the top or bottom with `g`/`G`, page with `Ctrl-D`/`Ctrl-U`, and filter the list by typing `/` followed by a search term. Press `Enter` to confirm, or `Esc`/`Ctrl-C`/`q` to cancel.

Highlight a worktree and press `c` to mark or unmark it as part of the selection. After the first mark, a `[x]`/`[ ]` marker column appears and remains visible until the last mark is removed. Marked state persists as you move the cursor or filter. Plain branches, the current worktree, and locked worktrees cannot be marked.
Highlight a branch or worktree and press `c` to mark or unmark it as part of the selection. After the first mark, a `[x]`/`[ ]` marker column appears and remains visible until the last mark is removed. Marked state persists as you move the cursor or filter. The current worktree and locked worktrees cannot be marked.

Once at least one item is marked, a hint line appears below the list telling you which key acts on the marked set. Press `D` to delete every marked worktree: a confirmation screen lists the branches and paths about to be removed, `Enter` runs the deletion (`git worktree remove` then `git branch -d` for each), and any cancel key (`Esc`, `Ctrl-C`, `q`) backs out without touching Git state or losing your marked selection.
Once at least one item is marked, a hint line appears below the list telling you which key acts on the marked set. Press `D` to delete every marked branch: a confirmation screen lists the branches (and worktree paths, where applicable) about to be removed, `Enter` runs the deletion (`git worktree remove` for items with a worktree, then `git branch -d` for each), and any cancel key (`Esc`, `Ctrl-C`, `q`) backs out without touching Git state or losing your marked selection.

The picker uses color to distinguish the selected row, current worktree, marked items, worktree tags, locked worktrees, and filter prompt. Pass `--no-color` to disable all ANSI styling.

Expand Down
8 changes: 4 additions & 4 deletions SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## 1. Overview

`wt` is a single-binary CLI tool that presents a unified, interactively navigable list of local branches and Git worktrees, and switches the user's shell context to whichever one they select — either by `cd`-ing into an existing worktree or by checking out a branch in the current repository. It can also delete one or more worktrees (and their branches) in bulk, via a mark-then-confirm flow. It never mutates Git state on its own; every write (checkout, `worktree add`, `worktree remove`, `branch -d`) happens only after explicit user confirmation, and only via standard `git` invocations.
`wt` is a single-binary CLI tool that presents a unified, interactively navigable list of local branches and Git worktrees, and switches the user's shell context to whichever one they select — either by `cd`-ing into an existing worktree or by checking out a branch in the current repository. It can also delete one or more branches (and their worktrees, where present) in bulk, via a mark-then-confirm flow. It never mutates Git state on its own; every write (checkout, `worktree add`, `worktree remove`, `branch -d`) happens only after explicit user confirmation, and only via standard `git` invocations.

## 2. Technology Choice

Expand Down Expand Up @@ -50,14 +50,14 @@ No `fzf` dependency is required, but the design deliberately keeps the same *int
│ - plain branch → git switch <branch> (in cwd repo)
│ - worktree path → emit cd path to wrapper (no git mutation)
│ - existing path → return it to the shell wrapper
│ - marked set → git worktree remove + git branch -d, per item
│ - marked set → git worktree remove (if any) + git branch -d, per item
└──────────────────────┘
```

**Data flow:**
1. `gitdata` runs `git branch --list --format='%(refname:short)'` and `git worktree list --porcelain -z`, parses both, and produces a single normalized list of items, cross-referencing which branches are already checked out in a worktree (the exact information `git switch` uses to produce its "already checked out" error — surfacing it up front removes the dead end).
2. `ui` renders the list, handles keystrokes purely as state transitions (no side effects) until the user confirms.
3. `action` executes exactly one of: `git switch`, `git worktree add`, a directory change (for worktrees), or — after the mark-then-`D`-then-confirm flow — `git worktree remove` and `git branch -d` for each marked item.
3. `action` executes exactly one of: `git switch`, `git worktree add`, a directory change (for worktrees), or — after the mark-then-`D`-then-confirm flow — `git worktree remove` (only for marked items that have a worktree) followed by `git branch -d` for each marked item.

**Directory-change trick:** a subprocess cannot change its parent shell's `cwd`. `wt` handles this the same way `zoxide`/`fzf`-based `cd` wrappers do — see §5.

Expand Down Expand Up @@ -122,7 +122,7 @@ The authoritative collector and action implementations are in
**Integration tests** (real repositories):
- Use `t.TempDir()` to create scratch repositories via actual `git init`, `git commit --allow-empty`, and `git worktree add` commands.
- Drive the action and collection layers against the scratch repository and assert the resulting paths and Git repository state.
- Cover switching a plain branch, resolving an existing worktree, creating a worktree, and deleting marked worktrees and their branches.
- Cover switching a plain branch, resolving an existing worktree, creating a worktree, and deleting marked branches, both with and without a worktree.

## 7. Building

Expand Down
6 changes: 3 additions & 3 deletions cmd/wt/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,16 +103,16 @@ func run(pathOnly bool, worktreeRootFlag string, noColor bool) error {
return nil
}

// applyDelete removes each marked worktree and its branch, reporting
// success to stderr on completion. It returns any error(s) action.
// applyDelete removes each marked branch (and its worktree, if it has one),
// reporting success to stderr on completion. It returns any error(s) action.
// DeleteWorktrees encountered so main exits non-zero, but every item is
// still attempted regardless of earlier failures.
func applyDelete(items []gitdata.Item) error {
err := action.DeleteWorktrees(items)
if err != nil {
return err
}
fmt.Fprintf(os.Stderr, "wt: deleted %d worktree(s)\n", len(items))
fmt.Fprintf(os.Stderr, "wt: deleted %d branch(es)\n", len(items))
return nil
}

Expand Down
30 changes: 30 additions & 0 deletions integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,36 @@ func TestIntegrationDeleteMarkedWorktree(t *testing.T) {
}
}

func TestIntegrationDeleteMarkedBranchWithoutWorktree(t *testing.T) {
repo := t.TempDir()
initRepo(t, repo)
runGit(t, repo, "branch", "alpha") // plain branch, no worktree
chdir(t, repo)

items, err := gitdata.Collect()
if err != nil {
t.Fatalf("gitdata.Collect: %v", err)
}
top, err := gitdata.Toplevel()
if err != nil {
t.Fatalf("gitdata.Toplevel: %v", err)
}

// order: main (cursor 0), alpha (cursor 1) -> down, mark, D, Enter.
m := ui.New(items, top, "", true)
result := drivePicker(t, m, keyDown, keyRune('c'), keyRune('D'), keyEnter)

if len(result.Delete) != 1 || result.Delete[0].Branch != "alpha" {
t.Fatalf("result.Delete = %+v, want [alpha]", result.Delete)
}
applyResult(t, result)

branches := runGit(t, repo, "branch", "--list", "alpha")
if strings.TrimSpace(branches) != "" {
t.Fatalf("branch alpha still exists after delete: %q", branches)
}
}

func worktreePathForBranch(t *testing.T, repo, branch string) string {
t.Helper()
out := runGit(t, repo, "worktree", "list", "--porcelain")
Expand Down
19 changes: 11 additions & 8 deletions internal/action/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,12 @@ func newWorktreeWith(run runnerFunc, path, branch string) (string, error) {
return path, nil
}

// DeleteWorktrees removes each item's worktree via `git worktree remove`,
// then deletes the now-unattached branch via `git branch -d` (non-force: a
// branch with unmerged commits is left in place and reported as an error).
// Every item is attempted even if earlier ones fail; all failures are
// combined into a single returned error.
// DeleteWorktrees removes each item's worktree, if it has one, via
// `git worktree remove`, then deletes the branch via `git branch -d`
// (non-force: a branch with unmerged commits is left in place and reported
// as an error). Items without a worktree skip straight to the branch
// delete. Every item is attempted even if earlier ones fail; all failures
// are combined into a single returned error.
func DeleteWorktrees(items []gitdata.Item) error {
return deleteWorktreesWith(runGit, items)
}
Expand All @@ -74,9 +75,11 @@ func deleteWorktreesWith(run runnerFunc, items []gitdata.Item) error {
errs = append(errs, fmt.Errorf("%s: cannot delete a locked worktree", item.Branch))
continue
}
if err := run("worktree", "remove", item.Path); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", item.Branch, err))
continue
if item.HasWorktree() {
if err := run("worktree", "remove", item.Path); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", item.Branch, err))
continue
}
}
if item.Detached {
continue
Expand Down
13 changes: 13 additions & 0 deletions internal/action/action_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,19 @@ func TestDeleteWorktreesWithRemovesWorktreeThenDeletesBranch(t *testing.T) {
}
}

func TestDeleteWorktreesWithBranchWithoutWorktreeSkipsWorktreeRemove(t *testing.T) {
run, calls := recordingRunner()
item := gitdata.Item{Branch: "bugfix/api-timeout"}

if err := deleteWorktreesWith(run, []gitdata.Item{item}); err != nil {
t.Fatalf("deleteWorktreesWith() error = %v", err)
}
want := [][]string{{"branch", "-d", "bugfix/api-timeout"}}
if !reflect.DeepEqual(*calls, want) {
t.Fatalf("git calls = %v, want %v", *calls, want)
}
}

func TestDeleteWorktreesWithSkipsBranchDeleteOnWorktreeRemoveFailure(t *testing.T) {
run := func(args ...string) error {
if args[0] == "worktree" {
Expand Down
37 changes: 19 additions & 18 deletions internal/ui/ui.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@ type Result struct {
Item gitdata.Item
Resolution string // config.ActionSwitch or config.ActionWorktree, set only when Item has no worktree
NewWorktreePath string // suggested path, set only when Resolution == config.ActionWorktree
Delete []gitdata.Item // set when the user confirmed bulk deletion of the marked worktrees
Delete []gitdata.Item // set when the user confirmed bulk deletion of the marked branches
}

// Model is the bubbletea model for the picker.
type Model struct {
items []gitdata.Item
filtered []int
cursor int
marked map[int]bool // keyed by index into items, worktree items only
marked map[int]bool // keyed by index into items
filter string
mode mode
toplevel string
Expand Down Expand Up @@ -113,7 +113,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}

// updateConfirmDelete handles the approval step shown after pressing D with
// at least one worktree marked. Enter confirms and quits with the marked
// at least one branch marked. Enter confirms and quits with the marked
// items in Result.Delete; any cancel key stops the operation and returns to
// the list without quitting the picker.
func (m Model) updateConfirmDelete(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
Expand Down Expand Up @@ -328,15 +328,15 @@ func (m Model) selected() *gitdata.Item {
return &m.items[m.filtered[m.cursor]]
}

// toggleMarked flips the marked state of the highlighted item. Only removable
// worktrees can be marked: plain branches, the current worktree, and locked
// toggleMarked flips the marked state of the highlighted item. Only
// removable branches can be marked: the current worktree and locked
// worktrees are excluded.
func (m *Model) toggleMarked() {
if m.cursor < 0 || m.cursor >= len(m.filtered) {
return
}
idx := m.filtered[m.cursor]
if !m.items[idx].HasWorktree() || m.items[idx].IsCurrent || m.items[idx].Locked {
if m.items[idx].IsCurrent || m.items[idx].Locked {
return
}
m.marked[idx] = !m.marked[idx]
Expand Down Expand Up @@ -450,9 +450,13 @@ func (m Model) View() string {
return b.String()
case modeConfirmDelete:
marked := m.Marked()
fmt.Fprintf(&b, "Delete %d worktree(s) and their branches?\n", len(marked))
fmt.Fprintf(&b, "Delete %d branch(es) (and their worktrees, if any)?\n", len(marked))
for _, item := range marked {
fmt.Fprintf(&b, " %s %s\n", item.Branch, item.Path)
path := item.Path
if path == "" {
path = "(no worktree)"
}
fmt.Fprintf(&b, " %s %s\n", item.Branch, path)
}
b.WriteString("[Enter] confirm [Esc] cancel\n")
return b.String()
Expand Down Expand Up @@ -483,14 +487,11 @@ func (m Model) View() string {
mark = currentStyle.Render(mark)
}
}
marker := " "
if item.HasWorktree() {
marker = "[ ]"
if m.marked[idx] {
marker = "[x]"
if !m.noColor {
marker = markedStyle.Render(marker)
}
marker := "[ ]"
if m.marked[idx] {
marker = "[x]"
if !m.noColor {
marker = markedStyle.Render(marker)
}
}
line := fmt.Sprintf("%s %s %-28s", cursor, mark, item.Branch)
Expand Down Expand Up @@ -573,8 +574,8 @@ func (m Model) helpView() string {
" page up : Ctrl-U",
" top/bottom : g / G",
" filter : / (Esc clears)",
" mark : c (worktrees only; selection)",
" delete : D (marked worktrees, asks to confirm)",
" mark : c (selection)",
" delete : D (marked branches, asks to confirm)",
" confirm : Enter",
" cancel : Esc, Ctrl-C, q",
" help : ?",
Expand Down
29 changes: 21 additions & 8 deletions internal/ui/ui_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,11 +202,12 @@ func TestMarkTogglesWorktreeItem(t *testing.T) {
}
}

func TestMarkIgnoredOnItemWithoutWorktree(t *testing.T) {
func TestMarkAllowedOnItemWithoutWorktree(t *testing.T) {
m := New(testItems(), "/repo/proj", "", true)
m = send(t, m, key('j'), key('j'), key('c')) // -> bugfix/api-timeout, no worktree
if len(m.Marked()) != 0 {
t.Fatalf("Marked() = %+v, want empty for item without a worktree", m.Marked())
marked := m.Marked()
if len(marked) != 1 || marked[0].Branch != "bugfix/api-timeout" {
t.Fatalf("Marked() = %+v, want [bugfix/api-timeout]", marked)
}
}

Expand Down Expand Up @@ -270,8 +271,8 @@ func TestViewShowsMarkColumnOnlyWhileItemsAreMarked(t *testing.T) {
m = send(t, m, key('j')) // bugfix/api-timeout, no worktree
view = m.View()
line := lineContaining(view, "bugfix/api-timeout")
if strings.Contains(line, "[") {
t.Fatalf("View() should render no marker for item without a worktree:\n%s", line)
if !strings.Contains(line, "[ ]") {
t.Fatalf("View() should render an unmarked marker for item without a worktree:\n%s", line)
}

m = send(t, m, key('k'), key('c'))
Expand Down Expand Up @@ -357,7 +358,7 @@ func TestConfirmDeleteViewListsMarkedBranches(t *testing.T) {
m := New(items, "/repo/proj", "", true)
m = send(t, m, key('j'), key('c'), key('j'), key('j'), key('c'), key('D'))
view := m.View()
if !strings.Contains(view, "Delete 2 worktree(s)") {
if !strings.Contains(view, "Delete 2 branch(es)") {
t.Fatalf("confirm view missing count:\n%s", view)
}
if !strings.Contains(view, "feature/login") || !strings.Contains(view, "release/2.1") {
Expand All @@ -368,6 +369,18 @@ func TestConfirmDeleteViewListsMarkedBranches(t *testing.T) {
}
}

func TestConfirmDeleteViewShowsNoWorktreeForPlainBranch(t *testing.T) {
m := New(testItems(), "/repo/proj", "", true)
m = send(t, m, key('j'), key('j'), key('c'), key('D')) // mark bugfix/api-timeout, no worktree
view := m.View()
if !strings.Contains(view, "Delete 1 branch(es)") {
t.Fatalf("confirm view missing count:\n%s", view)
}
if !strings.Contains(view, "bugfix/api-timeout") || !strings.Contains(view, "(no worktree)") {
t.Fatalf("confirm view missing branch without worktree:\n%s", view)
}
}

func TestHelpOverlayReturnsToList(t *testing.T) {
m := New(testItems(), "/repo/proj", "", true)
m = send(t, m, key('?'))
Expand All @@ -384,10 +397,10 @@ func TestHelpOverlayDocumentsMarkBindingAndSemantics(t *testing.T) {
m := New(testItems(), "/repo/proj", "", true)
m = send(t, m, key('?'))
view := m.View()
if !strings.Contains(view, "mark : c (worktrees only; selection)") {
if !strings.Contains(view, "mark : c (selection)") {
t.Fatalf("help overlay missing mark binding:\n%s", view)
}
if !strings.Contains(view, "delete : D (marked worktrees, asks to confirm)") {
if !strings.Contains(view, "delete : D (marked branches, asks to confirm)") {
t.Fatalf("help overlay missing delete semantics:\n%s", view)
}
}
Expand Down
Loading