From 3811219f4d0daf91fdf20caab8c20c6a37df312e Mon Sep 17 00:00:00 2001 From: Adam Jedrzejewski Date: Sun, 19 Jul 2026 17:24:48 +0200 Subject: [PATCH 1/2] Allow deleting branches that have no worktree The mark-then-delete flow only let you mark items with a dedicated worktree, so plain local branches could never be bulk-deleted even though action.DeleteWorktrees already tolerated a missing path. Deletion now skips `git worktree remove` for such items and goes straight to `git branch -d`. Co-Authored-By: Claude Sonnet 5 --- README.md | 4 ++-- SPEC.md | 8 ++++---- cmd/wt/main.go | 6 +++--- integration_test.go | 30 ++++++++++++++++++++++++++++++ internal/action/action.go | 19 +++++++++++-------- internal/action/action_test.go | 13 +++++++++++++ internal/ui/ui.go | 33 +++++++++++++++++---------------- internal/ui/ui_test.go | 29 +++++++++++++++++++++-------- 8 files changed, 101 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 21d5db0..9320c7c 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/SPEC.md b/SPEC.md index 36c1293..65acddc 100644 --- a/SPEC.md +++ b/SPEC.md @@ -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 @@ -50,14 +50,14 @@ No `fzf` dependency is required, but the design deliberately keeps the same *int │ - plain branch → git switch (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. @@ -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 diff --git a/cmd/wt/main.go b/cmd/wt/main.go index b98213e..4117903 100644 --- a/cmd/wt/main.go +++ b/cmd/wt/main.go @@ -103,8 +103,8 @@ 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 { @@ -112,7 +112,7 @@ func applyDelete(items []gitdata.Item) error { 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 } diff --git a/integration_test.go b/integration_test.go index b13c29f..af7e8d4 100644 --- a/integration_test.go +++ b/integration_test.go @@ -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") diff --git a/internal/action/action.go b/internal/action/action.go index e0efc52..a9eecdd 100644 --- a/internal/action/action.go +++ b/internal/action/action.go @@ -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) } @@ -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 diff --git a/internal/action/action_test.go b/internal/action/action_test.go index 85fcadf..27cb07d 100644 --- a/internal/action/action_test.go +++ b/internal/action/action_test.go @@ -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" { diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 17928e7..a627ac3 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -41,7 +41,7 @@ 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 @@ -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] @@ -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() @@ -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) @@ -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 : ?", diff --git a/internal/ui/ui_test.go b/internal/ui/ui_test.go index 70c7b18..2866f22 100644 --- a/internal/ui/ui_test.go +++ b/internal/ui/ui_test.go @@ -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) } } @@ -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')) @@ -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") { @@ -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('?')) @@ -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) } } From 8d0af8b8a47cf72e76e848ac454d45c58975d62c Mon Sep 17 00:00:00 2001 From: Adam Jedrzejewski Date: Sun, 19 Jul 2026 17:32:25 +0200 Subject: [PATCH 2/2] no-mistakes(document): Update branch deletion documentation comments --- internal/ui/ui.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/ui/ui.go b/internal/ui/ui.go index a627ac3..43734b8 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -33,7 +33,7 @@ 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. @@ -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) {