diff --git a/README.md b/README.md index 20d2848..12a5f71 100644 --- a/README.md +++ b/README.md @@ -62,11 +62,11 @@ 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 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. +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. Only the current worktree cannot be marked; locked worktrees can be marked and deleted, subject to the same typed confirmation as dirty worktrees below. -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. For a batch containing only merged branches and clean worktrees, `Enter` runs the deletion (`git worktree remove` for items with a worktree, then `git branch -d` for each); 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. For a batch containing only merged branches and clean, unlocked worktrees, `Enter` runs the deletion (`git worktree remove` for items with a worktree, then `git branch -d` for each); any cancel key (`Esc`, `Ctrl-C`, `q`) backs out without touching Git state or losing your marked selection. -If any marked branch has unmerged changes, or any marked worktree has modified or untracked files, confirming does not delete anything yet — `git branch -d` and `git worktree remove` would refuse them anyway. Instead a second screen lists the unmerged branch(es) and/or dirty worktree(s) and requires you to type `delete` and press `Enter` before the whole batch is deleted: merged branches via `git branch -d` and unmerged ones via `git branch -D`, clean worktrees via `git worktree remove` and dirty ones via `git worktree remove --force`. `Esc`/`Ctrl-C` cancels the entire batch and returns to the list without touching Git state. +If any marked branch has unmerged changes, any marked worktree has modified or untracked files, or any marked worktree is locked, confirming does not delete anything yet — `git branch -d` and `git worktree remove` would refuse them anyway. Instead a second screen lists the unmerged branch(es), dirty worktree(s), and/or locked worktree(s) and requires you to type `delete` and press `Enter` before the whole batch is deleted: merged branches via `git branch -d` and unmerged ones via `git branch -D`, clean and unlocked worktrees via `git worktree remove`, dirty ones via `git worktree remove --force`, and locked ones via `git worktree remove --force --force` (git requires `--force` twice to remove a locked worktree). `Esc`/`Ctrl-C` cancels the entire batch and returns to the list without touching Git state. 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. @@ -98,7 +98,7 @@ keymap = "vim" # vim | emacs | arrows-only `wt` is written in Go and compiles to a single static binary, so there is no interpreter or runtime to install alongside it. The interactive list is built with the `bubbletea` terminal UI framework, which handles raw terminal mode, key events, and resizing consistently across Linux, macOS, and Windows. -`wt` never reimplements Git logic. It shells out to the real `git` binary for every read (`git branch`, including its merged-branch query, `git worktree list --porcelain`, and `git status --porcelain`) and every write (`git switch`, `git worktree add`, `git worktree remove`, confirmed `git worktree remove --force`, `git branch -d`, and confirmed `git branch -D`), so behavior always matches what you would get running those commands yourself, including your existing hooks and credential helpers. A small collector step parses those outputs and merges them into one list, tagging each branch with its merge status, whether it already has a worktree, whether that worktree is dirty, and whether it is locked. That merged view is what makes the "already checked out elsewhere" case visible instead of being an error you hit after the fact. +`wt` never reimplements Git logic. It shells out to the real `git` binary for every read (`git branch`, including its merged-branch query, `git worktree list --porcelain`, and `git status --porcelain`) and every write (`git switch`, `git worktree add`, `git worktree remove`, confirmed `git worktree remove --force`, confirmed `git worktree remove --force --force`, `git branch -d`, and confirmed `git branch -D`), so behavior always matches what you would get running those commands yourself, including your existing hooks and credential helpers. A small collector step parses those outputs and merges them into one list, tagging each branch with its merge status, whether it already has a worktree, whether that worktree is dirty, and whether it is locked. That merged view is what makes the "already checked out elsewhere" case visible instead of being an error you hit after the fact. Because a subprocess cannot change its parent shell's working directory, `wt` prints the destination path and relies on a thin shell function, installed once via `wt init `, to perform the actual `cd`. This keeps your working directory untouched unless a switch actually happens. diff --git a/SPEC.md b/SPEC.md index 33e144f..e63d54d 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 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` or explicitly confirmed `worktree remove --force`, `branch -d`, or explicitly confirmed `branch -D`) happens only after 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`, explicitly confirmed `worktree remove --force` or `worktree remove --force --force`, `branch -d`, or explicitly confirmed `branch -D`) happens only after user confirmation, and only via standard `git` invocations. ## 2. Technology Choice @@ -51,14 +51,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 (--force if dirty) + git branch -d/-D, per item +│ - marked set → git worktree remove (forced if dirty/locked) + git branch -d/-D, per item └──────────────────────┘ ``` **Data flow:** 1. `gitdata` runs `git branch --list --format='%(refname:short)'`, `git branch --format='%(refname:short)' --merged`, `git worktree list --porcelain -z`, and `git status --porcelain` scoped to each worktree's path, parses their output, and produces a single normalized list of items, cross-referencing merge status, dirty (modified/untracked) status, and 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` (only for marked items that have a worktree; `--force` for worktrees with modified or untracked files, after phrase-typed confirmation) followed by `git branch -d` for merged branches or, after phrase-typed confirmation, `git branch -D` for unmerged branches. +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; `--force` for dirty worktrees and `--force --force` for locked worktrees, after phrase-typed confirmation) followed by `git branch -d` for merged branches or, after phrase-typed confirmation, `git branch -D` for unmerged branches. **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. @@ -89,15 +89,16 @@ Selecting a plain branch with no worktree and confirming prompts one extra line: ``` This directly resolves the stated pain point: instead of `git switch` erroring out, the tool offers the two valid resolutions inline. -**Deleting branches with unmerged changes, or worktrees with modified or -untracked files:** `git branch -d` (the non-force delete `wt` uses for merged +**Deleting branches with unmerged changes, dirty worktrees, or locked +worktrees:** `git branch -d` (the non-force delete `wt` uses for merged branches) refuses branches not fully merged, and `git worktree remove` (the non-force removal `wt` uses by default) refuses worktrees with modified -or untracked files. `wt` detects both ahead of time — each `Item` carries an -`Unmerged` flag computed from `git branch --merged`, and a `Dirty` flag -computed from `git status --porcelain` scoped to the worktree's path, both -during collection — and if any branch in the marked set is unmerged, or any -worktree in the marked set is dirty, confirming the normal delete screen +or untracked files or a lock. `wt` detects all three ahead of time — each +`Item` carries an `Unmerged` flag computed from `git branch --merged`, and a `Dirty` flag +computed from `git status --porcelain` scoped to the worktree's path, while +`Locked` comes from `git worktree list --porcelain` — and if any branch in the +marked set is unmerged, or any worktree in the marked set is dirty or locked, +confirming the normal delete screen (`D` then `Enter`) does not delete anything yet. Instead a second screen appears: @@ -106,24 +107,28 @@ The following branch(es) have unmerged changes and will be permanently lost: feature/wip-thing The following worktree(s) have modified or untracked files that will be permanently lost: scratch/notes ../proj-scratch +The following worktree(s) are locked and will be force-unlocked and removed: + release/2.1 ../proj-release Type "delete" and press Enter to proceed, or Esc to cancel: > _ ``` - This screen only appears when at least one marked branch is unmerged or - at least one marked worktree is dirty; each condition contributes its own - section to the screen, and either section is omitted when it has nothing - to list. Marked sets that are entirely merged and clean delete exactly as - before, with no extra step. + at least one marked worktree is dirty or locked; each condition contributes + its own section to the screen, and each section is omitted when it has + nothing to list. Marked sets that are entirely merged, clean, and unlocked + delete exactly as before, with no extra step. - The user must type **"delete"** exactly (case-sensitive) and press `Enter` to proceed; any mismatch is rejected and the input stays open for correction. `Esc` or `Ctrl-C` cancels the whole batch — including any - merged or clean items marked alongside the unmerged/dirty one(s) — and + merged, clean, or unlocked items marked alongside the risky one(s) — and returns to the list without touching Git state or losing the marked selection. - Once confirmed, `wt` deletes the batch in one pass: `git worktree remove` - as before, or `git worktree remove --force` for dirty worktrees; then + as before, `git worktree remove --force` for dirty worktrees, or `git + worktree remove --force --force` for locked worktrees (including worktrees + that are both locked and dirty); then `git branch -d` as before, or `git branch -D` (force) for unmerged branches — since explicit, phrase-level consent was already obtained. - Detached-HEAD worktree entries (which have no associated branch to diff --git a/internal/action/action.go b/internal/action/action.go index 96f1432..7105610 100644 --- a/internal/action/action.go +++ b/internal/action/action.go @@ -56,10 +56,12 @@ func newWorktreeWith(run runnerFunc, path, branch string) (string, error) { // DeleteWorktrees removes each item's worktree, if it has one, via // `git worktree remove`, or `git worktree remove --force` when item.Dirty is -// set, then deletes the branch via `git branch -d`, or `git branch -D` -// (force) when item.Unmerged is set. Callers must only pass Dirty or -// Unmerged items after the user has given explicit, phrase-typed consent -// (see internal/ui's modeConfirmForceDelete) — this function performs no +// set, or `git worktree remove --force --force` when item.Locked is set (a +// single --force is not enough for git to remove a locked worktree), then +// deletes the branch via `git branch -d`, or `git branch -D` (force) when +// item.Unmerged is set. Callers must only pass Dirty, Locked, or Unmerged +// items after the user has given explicit, phrase-typed consent (see +// internal/ui's modeConfirmForceDelete) — this function performs no // confirmation of its own. 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. @@ -74,13 +76,12 @@ func deleteWorktreesWith(run runnerFunc, items []gitdata.Item) error { errs = append(errs, fmt.Errorf("%s: cannot delete the current worktree", item.Branch)) continue } - if item.Locked { - errs = append(errs, fmt.Errorf("%s: cannot delete a locked worktree", item.Branch)) - continue - } if item.HasWorktree() { args := []string{"worktree", "remove"} - if item.Dirty { + switch { + case item.Locked: + args = append(args, "--force", "--force") + case item.Dirty: args = append(args, "--force") } args = append(args, item.Path) diff --git a/internal/action/action_test.go b/internal/action/action_test.go index 15e56cd..19c34ce 100644 --- a/internal/action/action_test.go +++ b/internal/action/action_test.go @@ -163,16 +163,35 @@ func TestDeleteWorktreesWithRejectsCurrentWorktree(t *testing.T) { } } -func TestDeleteWorktreesWithRejectsLockedWorktree(t *testing.T) { +func TestDeleteWorktreesWithForcesRemoveOfLockedWorktreeTwice(t *testing.T) { run, calls := recordingRunner() item := gitdata.Item{Branch: "release/2.1", Path: "/repo/proj-release", Locked: true} - err := deleteWorktreesWith(run, []gitdata.Item{item}) - if err == nil || !strings.Contains(err.Error(), "locked worktree") { - t.Fatalf("deleteWorktreesWith() error = %v, want locked worktree error", err) + if err := deleteWorktreesWith(run, []gitdata.Item{item}); err != nil { + t.Fatalf("deleteWorktreesWith() error = %v", err) } - if len(*calls) != 0 { - t.Fatalf("git calls = %v, want none", *calls) + want := [][]string{ + {"worktree", "remove", "--force", "--force", "/repo/proj-release"}, + {"branch", "-d", "release/2.1"}, + } + if !reflect.DeepEqual(*calls, want) { + t.Fatalf("git calls = %v, want %v", *calls, want) + } +} + +func TestDeleteWorktreesWithLockedAndDirtyUsesOnlyDoubleForce(t *testing.T) { + run, calls := recordingRunner() + item := gitdata.Item{Branch: "release/2.1", Path: "/repo/proj-release", Locked: true, Dirty: true} + + if err := deleteWorktreesWith(run, []gitdata.Item{item}); err != nil { + t.Fatalf("deleteWorktreesWith() error = %v", err) + } + want := [][]string{ + {"worktree", "remove", "--force", "--force", "/repo/proj-release"}, + {"branch", "-d", "release/2.1"}, + } + if !reflect.DeepEqual(*calls, want) { + t.Fatalf("git calls = %v, want %v", *calls, want) } } diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 4f89a0a..f47e7f5 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -29,10 +29,10 @@ const ( ) // ForceDeleteConfirmPhrase is the exact text a user must type to delete a -// branch with unmerged changes, or a worktree with modified or untracked -// files. It must match verbatim (case-sensitive) — this is deliberate -// friction against losing uncommitted work, so it is never made -// configurable. +// branch with unmerged changes, a worktree with modified or untracked files, +// or a locked worktree. It must match verbatim (case-sensitive) — this is +// deliberate friction against losing uncommitted work or bypassing an +// explicit lock, so it is never made configurable. const ForceDeleteConfirmPhrase = "delete" // Result is what the picker produced when the program exited. @@ -126,7 +126,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 branch marked. Enter confirms: if any marked branch is -// unmerged, or any marked worktree is dirty, it advances to +// unmerged, or any marked worktree is dirty or locked, it advances to // modeConfirmForceDelete for an explicit phrase-typed confirmation instead // of quitting immediately. Any cancel key stops the operation and returns to // the list without quitting the picker. @@ -137,7 +137,7 @@ func (m Model) updateConfirmDelete(msg tea.KeyMsg) (tea.Model, tea.Cmd) { } if msg.Type == tea.KeyEnter { marked := m.Marked() - if hasUnmergedBranch(marked) || hasDirtyWorktree(marked) { + if hasUnmergedBranch(marked) || hasDirtyWorktree(marked) || hasLockedWorktree(marked) { m.forceConfirmInput = "" m.mode = modeConfirmForceDelete return m, nil @@ -151,11 +151,12 @@ func (m Model) updateConfirmDelete(msg tea.KeyMsg) (tea.Model, tea.Cmd) { // updateConfirmForceDelete handles the phrase-typed approval step shown // when at least one marked branch has unmerged changes, or at least one -// marked worktree has modified or untracked files. Esc/Ctrl-C cancel back to -// the list; Enter only confirms and quits (with the full marked set in -// Result.Delete) when the typed text matches ForceDeleteConfirmPhrase -// exactly, otherwise it is a no-op so the user can keep correcting the -// input. "q" is not treated as cancel here since it is valid input text. +// marked worktree has modified or untracked files or is locked. Esc/Ctrl-C +// cancel back to the list; Enter only confirms and quits (with the full +// marked set in Result.Delete) when the typed text matches +// ForceDeleteConfirmPhrase exactly, otherwise it is a no-op so the user can +// keep correcting the input. "q" is not treated as cancel here since it is +// valid input text. func (m Model) updateConfirmForceDelete(msg tea.KeyMsg) (tea.Model, tea.Cmd) { switch msg.Type { case tea.KeyEsc, tea.KeyCtrlC: @@ -206,6 +207,19 @@ func hasDirtyWorktree(items []gitdata.Item) bool { return false } +// hasLockedWorktree reports whether any item's worktree is locked — the +// condition that makes `git worktree remove` refuse to delete it even with +// a single --force (git requires --force twice to remove a locked +// worktree). +func hasLockedWorktree(items []gitdata.Item) bool { + for _, item := range items { + if item.Locked { + return true + } + } + return false +} + func (m Model) updateLocked(msg tea.KeyMsg) (tea.Model, tea.Cmd) { if isCancel(msg) { m.mode = modeList @@ -405,15 +419,16 @@ func (m Model) selected() *gitdata.Item { return &m.items[m.filtered[m.cursor]] } -// toggleMarked flips the marked state of the highlighted item. Only -// removable branches can be marked: the current worktree and locked -// worktrees are excluded. +// toggleMarked flips the marked state of the highlighted item. Only the +// current worktree is excluded from marking; locked worktrees can be +// marked and deleted, subject to the phrase-typed force-delete +// confirmation in modeConfirmForceDelete. func (m *Model) toggleMarked() { if m.cursor < 0 || m.cursor >= len(m.filtered) { return } idx := m.filtered[m.cursor] - if m.items[idx].IsCurrent || m.items[idx].Locked { + if m.items[idx].IsCurrent { return } m.marked[idx] = !m.marked[idx] @@ -555,6 +570,14 @@ func (m Model) View() string { } } } + if hasLockedWorktree(marked) { + b.WriteString("The following worktree(s) are locked and will be force-unlocked and removed:\n") + for _, item := range marked { + if item.Locked { + fmt.Fprintf(&b, " %s %s\n", item.Branch, item.Path) + } + } + } fmt.Fprintf(&b, "Type %q and press Enter to proceed, or Esc to cancel:\n\n", ForceDeleteConfirmPhrase) fmt.Fprintf(&b, "> %s\n", m.forceConfirmInput) return b.String() @@ -673,7 +696,7 @@ func (m Model) helpView() string { " top/bottom : g / G", " filter : / (Esc clears)", " mark : c (selection)", - " delete : D (marked branches, asks to confirm; unmerged branches or dirty worktrees require typing a phrase)", + " delete : D (marked branches, asks to confirm; unmerged branches, dirty worktrees, or locked worktrees require typing a phrase)", " confirm : Enter", " cancel : Esc, Ctrl-C, q", " help : ?", diff --git a/internal/ui/ui_test.go b/internal/ui/ui_test.go index 7688f87..25e6fb1 100644 --- a/internal/ui/ui_test.go +++ b/internal/ui/ui_test.go @@ -219,11 +219,12 @@ func TestMarkIgnoredOnCurrentWorktree(t *testing.T) { } } -func TestMarkIgnoredOnLockedWorktree(t *testing.T) { +func TestMarkAllowedOnLockedWorktree(t *testing.T) { m := New(testItems(), "/repo/proj", "", true) m = send(t, m, key('G'), key('c')) - if len(m.Marked()) != 0 { - t.Fatalf("Marked() = %+v, want empty for locked worktree", m.Marked()) + marked := m.Marked() + if len(marked) != 1 || marked[0].Branch != "release/2.1" { + t.Fatalf("Marked() = %+v, want [release/2.1]", marked) } } @@ -563,6 +564,51 @@ func TestForceDeleteViewListsBothUnmergedBranchAndDirtyWorktree(t *testing.T) { } } +func TestConfirmDeleteEnterWithLockedWorktreeEntersForceDeleteMode(t *testing.T) { + m := New(testItems(), "/repo/proj", "", true) // release/2.1 is locked + m = send(t, m, key('G'), key('c'), key('D'), keyType(tea.KeyEnter)) + if m.mode != modeConfirmForceDelete { + t.Fatalf("mode after confirming delete with a locked worktree = %v, want modeConfirmForceDelete", m.mode) + } + if m.quitting { + t.Fatal("Enter in modeConfirmDelete with a locked worktree should not quit yet") + } +} + +func TestForceDeleteViewListsOnlyLockedWorktreesFromMixedBatch(t *testing.T) { + m := New(testItems(), "/repo/proj", "", true) + m = send(t, m, key('j'), key('c'), key('G'), key('c'), key('D'), keyType(tea.KeyEnter)) + view := m.View() + if !strings.Contains(view, "release/2.1") { + t.Fatalf("force-delete view missing locked worktree:\n%s", view) + } + if strings.Contains(view, "feature/login") { + t.Fatalf("force-delete view should not list unlocked worktree feature/login:\n%s", view) + } + if !strings.Contains(view, "locked") { + t.Fatalf("force-delete view missing locked-worktree section:\n%s", view) + } + if !strings.Contains(view, ForceDeleteConfirmPhrase) { + t.Fatalf("force-delete view missing required phrase:\n%s", view) + } +} + +func TestForceDeleteExactPhraseQuitsWithLockedWorktree(t *testing.T) { + m := New(testItems(), "/repo/proj", "", true) + m = send(t, m, key('G'), key('c'), key('D'), keyType(tea.KeyEnter)) + for _, r := range ForceDeleteConfirmPhrase { + m = send(t, m, key(r)) + } + m = send(t, m, keyType(tea.KeyEnter)) + if !m.quitting { + t.Fatal("Enter with the exact phrase in modeConfirmForceDelete should quit the program") + } + res := m.Result() + if len(res.Delete) != 1 || res.Delete[0].Branch != "release/2.1" { + t.Fatalf("Result().Delete = %+v, want [release/2.1]", res.Delete) + } +} + func TestHelpOverlayReturnsToList(t *testing.T) { m := New(testItems(), "/repo/proj", "", true) m = send(t, m, key('?')) @@ -582,7 +628,7 @@ func TestHelpOverlayDocumentsMarkBindingAndSemantics(t *testing.T) { if !strings.Contains(view, "mark : c (selection)") { t.Fatalf("help overlay missing mark binding:\n%s", view) } - if !strings.Contains(view, "delete : D (marked branches, asks to confirm; unmerged branches or dirty worktrees require typing a phrase)") { + if !strings.Contains(view, "delete : D (marked branches, asks to confirm; unmerged branches, dirty worktrees, or locked worktrees require typing a phrase)") { t.Fatalf("help overlay missing delete semantics:\n%s", view) } }