From ca2fc4f28f05021e399dfe1f1b8b6f3084534353 Mon Sep 17 00:00:00 2001 From: Adam Jedrzejewski Date: Mon, 20 Jul 2026 00:21:25 +0200 Subject: [PATCH 1/3] Handle deleting worktrees with untracked or modified files Mirrors the existing unmerged-branch force-delete flow: gitdata now detects dirty worktrees via `git status --porcelain`, the picker routes marked dirty worktrees through the same phrase-typed confirmation screen as unmerged branches, and action force-removes them with `git worktree remove --force` only after that explicit consent. Co-Authored-By: Claude Sonnet 5 --- README.md | 4 +- SPEC.md | 64 +++++++++++++++++------------ integration_test.go | 54 ++++++++++++++++++++++++ internal/action/action.go | 12 ++++-- internal/action/action_test.go | 21 ++++++++++ internal/gitdata/gitdata.go | 22 ++++++++++ internal/gitdata/gitdata_test.go | 53 ++++++++++++++++++++++++ internal/ui/ui.go | 56 ++++++++++++++++++------- internal/ui/ui_test.go | 70 +++++++++++++++++++++++++++++++- 9 files changed, 309 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 6b61f17..57a48c5 100644 --- a/README.md +++ b/README.md @@ -64,9 +64,9 @@ Navigate with the arrow keys, `j`/`k`, or `Ctrl-N`/`Ctrl-P`. Jump to the top or 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 branch: a confirmation screen lists the branches (and worktree paths, where applicable) about to be removed. For a batch containing only merged branches, `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 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, confirming does not delete anything yet — `git branch -d` would refuse it anyway. Instead a second screen lists the unmerged branch(es) and requires you to type `delete` and press `Enter` before the whole batch (merged and unmerged branches alike) is deleted, force-deleting only the unmerged ones (`git branch -D`). `Esc`/`Ctrl-C` cancels the entire batch and returns to the list without touching Git state. +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. 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 32d08da..d6c841a 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`, `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` or explicitly confirmed `worktree remove --force`, `branch -d`, or explicitly confirmed `branch -D`) happens only after user confirmation, and only via standard `git` invocations. ## 2. Technology Choice @@ -32,12 +32,13 @@ No `fzf` dependency is required, but the design deliberately keeps the same *int │ cmd/wt (main) │ parses flags, loads config, wires everything └─────────┬───────────┘ │ -┌─────────▼───────────┐ ┌────────────────────┐ -│ gitdata (collector) │────▶│ git branch --list │ -│ │ │ git worktree list │ -│ - parses branches │ │ git rev-parse ... │ -│ - parses worktrees │ └────────────────────┘ -│ - merges into Items │ +┌─────────▼───────────┐ ┌──────────────────────┐ +│ gitdata (collector) │────▶│ git branch --list │ +│ │ │ git worktree list │ +│ - parses branches │ │ git rev-parse ... │ +│ - parses worktrees │ │ git status │ +│ - merges into Items │ │ --porcelain │ +│ │ └──────────────────────┘ └─────────┬───────────┘ │ []Item{Name, Path, IsWorktree, IsCurrent, Locked, ...} ┌─────────▼───────────┐ @@ -50,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 (if any) + git branch -d/-D, per item +│ - marked set → git worktree remove (--force if dirty) + git branch -d/-D, per item └──────────────────────┘ ``` **Data flow:** -1. `gitdata` runs `git branch --list --format='%(refname:short)'`, `git branch --format='%(refname:short)' --merged`, and `git worktree list --porcelain -z`, parses their output, and produces a single normalized list of items, cross-referencing merge 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). +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) 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 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. **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. @@ -88,36 +89,47 @@ 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:** `git branch -d` (the non-force -delete `wt` uses for merged branches) refuses branches not fully merged. -`wt` detects this ahead of time — each -`Item` carries an `Unmerged` flag computed from `git branch --merged` during -collection — and if any branch in the marked set is unmerged, confirming the -normal delete screen (`D` then `Enter`) does not delete anything yet. -Instead a second screen appears: +**Deleting branches with unmerged changes, or worktrees with untracked +files:** `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 +(`D` then `Enter`) does not delete anything yet. Instead a second screen +appears: ``` 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 Type "delete" and press Enter to proceed, or Esc to cancel: > _ ``` -- This screen only appears when at least one marked branch is unmerged; - marked sets containing only merged branches delete exactly as before, - with no extra step. +- 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. - 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 branches marked alongside the unmerged 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: merged branches via - `git branch -d` as before, unmerged branches via `git branch -D` (force), - since explicit, phrase-level consent was already obtained. + merged or clean items marked alongside the unmerged/dirty 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 + `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 delete) are excluded from the unmerged check and never trigger this - screen on their own. + screen on their own, though they can still trigger it via the dirty + check if they have modified or untracked files. ## 5. Implementation Details diff --git a/integration_test.go b/integration_test.go index a7574ed..03c0ad1 100644 --- a/integration_test.go +++ b/integration_test.go @@ -324,6 +324,60 @@ func TestIntegrationDeleteUnmergedBranchRequiresForcePhrase(t *testing.T) { } } +func TestIntegrationDeleteDirtyWorktreeRequiresForcePhrase(t *testing.T) { + repo := t.TempDir() + initRepo(t, repo) + wtDir := filepath.Join(t.TempDir(), "scratch-wt-checkout") + runGit(t, repo, "worktree", "add", "-b", "scratch", wtDir) + if err := os.WriteFile(filepath.Join(wtDir, "untracked.txt"), []byte("scratch"), 0o644); err != nil { + t.Fatalf("write untracked file: %v", err) + } + 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) + } + + var scratch *gitdata.Item + for i := range items { + if items[i].Branch == "scratch" { + scratch = &items[i] + } + } + if scratch == nil || !scratch.Dirty { + t.Fatalf("items = %+v, want a scratch branch marked Dirty", items) + } + + // order: main (cursor 0), scratch (cursor 1) -> down, mark, D, Enter + // (opens the force-delete phrase prompt), type the required phrase, Enter. + keys := []tea.KeyMsg{keyDown, keyRune('c'), keyRune('D'), keyEnter} + for _, r := range ui.ForceDeleteConfirmPhrase { + keys = append(keys, keyRune(r)) + } + keys = append(keys, keyEnter) + + m := ui.New(items, top, "", true) + result := drivePicker(t, m, keys...) + + if len(result.Delete) != 1 || result.Delete[0].Branch != "scratch" { + t.Fatalf("result.Delete = %+v, want [scratch]", result.Delete) + } + applyResult(t, result) + + if _, err := os.Stat(wtDir); !os.IsNotExist(err) { + t.Fatalf("worktree dir %q still exists after force delete", wtDir) + } + branches := runGit(t, repo, "branch", "--list", "scratch") + if strings.TrimSpace(branches) != "" { + t.Fatalf("branch scratch still exists after force 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 3f27bb6..96f1432 100644 --- a/internal/action/action.go +++ b/internal/action/action.go @@ -55,8 +55,9 @@ func newWorktreeWith(run runnerFunc, path, branch string) (string, error) { } // DeleteWorktrees removes each item's worktree, if it has one, via -// `git worktree remove`, then deletes the branch via `git branch -d`, or -// `git branch -D` (force) when item.Unmerged is set. Callers must only pass +// `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 // confirmation of its own. Items without a worktree skip straight to the @@ -78,7 +79,12 @@ func deleteWorktreesWith(run runnerFunc, items []gitdata.Item) error { continue } if item.HasWorktree() { - if err := run("worktree", "remove", item.Path); err != nil { + args := []string{"worktree", "remove"} + if item.Dirty { + args = append(args, "--force") + } + args = append(args, item.Path) + if err := run(args...); err != nil { errs = append(errs, fmt.Errorf("%s: %w", item.Branch, err)) continue } diff --git a/internal/action/action_test.go b/internal/action/action_test.go index ba430ac..15e56cd 100644 --- a/internal/action/action_test.go +++ b/internal/action/action_test.go @@ -100,6 +100,27 @@ func TestDeleteWorktreesWithForcesDeleteOfUnmergedBranch(t *testing.T) { } } +func TestDeleteWorktreesWithForcesRemoveOfDirtyWorktree(t *testing.T) { + run, calls := recordingRunner() + items := []gitdata.Item{ + {Branch: "feature/wip", Path: "/repo/proj-wip", Dirty: true}, + {Branch: "release/2.1", Path: "/repo/proj-release"}, + } + + if err := deleteWorktreesWith(run, items); err != nil { + t.Fatalf("deleteWorktreesWith() error = %v", err) + } + want := [][]string{ + {"worktree", "remove", "--force", "/repo/proj-wip"}, + {"branch", "-d", "feature/wip"}, + {"worktree", "remove", "/repo/proj-release"}, + {"branch", "-d", "release/2.1"}, + } + if !reflect.DeepEqual(*calls, want) { + t.Fatalf("git calls = %v, want %v", *calls, want) + } +} + func TestDeleteWorktreesWithBranchWithoutWorktreeSkipsWorktreeRemove(t *testing.T) { run, calls := recordingRunner() item := gitdata.Item{Branch: "bugfix/api-timeout"} diff --git a/internal/gitdata/gitdata.go b/internal/gitdata/gitdata.go index 644f094..048c639 100644 --- a/internal/gitdata/gitdata.go +++ b/internal/gitdata/gitdata.go @@ -25,6 +25,7 @@ type Item struct { Locked bool Detached bool Unmerged bool // true if the branch is not fully merged into HEAD (git branch -d would refuse it) + Dirty bool // true if the worktree has modified or untracked files (git worktree remove would refuse it) } // HasWorktree reports whether the branch is checked out anywhere. @@ -123,6 +124,11 @@ func collect(run runnerFunc) ([]Item, error) { item.Path = w.path item.Locked = w.locked item.IsCurrent = normalizePath(w.path) == top + dirty, err := isDirty(run, w.path) + if err != nil { + return nil, err + } + item.Dirty = dirty } items = append(items, item) } @@ -130,12 +136,17 @@ func collect(run runnerFunc) ([]Item, error) { if !w.detached { continue } + dirty, err := isDirty(run, w.path) + if err != nil { + return nil, err + } items = append(items, Item{ Branch: "(detached)", Path: w.path, IsCurrent: normalizePath(w.path) == top, Locked: w.locked, Detached: true, + Dirty: dirty, }) } for i := range items { @@ -206,3 +217,14 @@ func parseLines(out string) []string { func normalizePath(p string) string { return filepath.Clean(p) } + +// isDirty reports whether the worktree at path has modified or untracked +// files — the same condition that makes `git worktree remove` (without +// --force) refuse to delete it. +func isDirty(run runnerFunc, path string) (bool, error) { + out, err := run("-C", path, "status", "--porcelain") + if err != nil { + return false, err + } + return strings.TrimSpace(out) != "", nil +} diff --git a/internal/gitdata/gitdata_test.go b/internal/gitdata/gitdata_test.go index cf7c3e7..612c09b 100644 --- a/internal/gitdata/gitdata_test.go +++ b/internal/gitdata/gitdata_test.go @@ -112,6 +112,10 @@ func TestCollectMergesBranchesAndWorktrees(t *testing.T) { "branch --list --format=%(refname:short)": "main\nfeature/login\nbugfix/api-timeout\nrelease/2.1\n", "branch --format=%(refname:short) --merged": "main\nbugfix/api-timeout\n", "rev-parse --show-toplevel": "/repo/proj\n", + "-C /repo/proj status --porcelain": "", + "-C /repo/proj-login status --porcelain": "", + "-C /repo/proj-release status --porcelain": "", + "-C /repo/proj-scratch status --porcelain": "", } items, err := collect(fr.run) @@ -137,6 +141,7 @@ func TestCollectMovesCurrentItemFirst(t *testing.T) { "branch --list --format=%(refname:short)": "a-first\nz-current\n", "branch --format=%(refname:short) --merged": "a-first\nz-current\n", "rev-parse --show-toplevel": "/repo/proj\n", + "-C /repo/proj status --porcelain": "", } items, err := collect(fr.run) if err != nil { @@ -162,6 +167,8 @@ func TestCollectMovesCurrentFirstPreservingRemainingOrder(t *testing.T) { "branch --list --format=%(refname:short)": "a-first\nb-middle\nz-current\n", "branch --format=%(refname:short) --merged": "a-first\nb-middle\nz-current\n", "rev-parse --show-toplevel": "/repo/proj-current\n", + "-C /repo/proj-current status --porcelain": "", + "-C /repo/proj-scratch status --porcelain": "", } items, err := collect(fr.run) @@ -202,6 +209,52 @@ func TestCollectMarksUnmergedBranches(t *testing.T) { } } +func TestCollectMarksDirtyWorktrees(t *testing.T) { + fr := fakeRunner{ + "worktree list --porcelain -z": strings.Join([]string{ + "worktree /repo/proj", + "HEAD abc123", + "branch refs/heads/main", + "", + "worktree /repo/proj-login", + "HEAD def456", + "branch refs/heads/feature/login", + "", + }, "\x00"), + "branch --list --format=%(refname:short)": "main\nfeature/login\n", + "branch --format=%(refname:short) --merged": "main\nfeature/login\n", + "rev-parse --show-toplevel": "/repo/proj\n", + "-C /repo/proj status --porcelain": "", + "-C /repo/proj-login status --porcelain": " M tracked.go\n?? scratch.txt\n", + } + + items, err := collect(fr.run) + if err != nil { + t.Fatalf("collect() error = %v", err) + } + + want := []Item{ + {Branch: "main", Path: "/repo/proj", IsCurrent: true}, + {Branch: "feature/login", Path: "/repo/proj-login", Dirty: true}, + } + if !reflect.DeepEqual(items, want) { + t.Fatalf("collect() = %#v, want %#v", items, want) + } +} + +func TestCollectPropagatesStatusErrors(t *testing.T) { + fr := fakeRunner{ + "worktree list --porcelain -z": "worktree /repo/proj\x00HEAD abc123\x00branch refs/heads/main\x00", + "branch --list --format=%(refname:short)": "main\n", + "branch --format=%(refname:short) --merged": "main\n", + "rev-parse --show-toplevel": "/repo/proj\n", + // "-C /repo/proj status --porcelain" deliberately omitted -> "unexpected" error + } + if _, err := collect(fr.run); err == nil { + t.Fatal("collect() error = nil, want error when git status fails") + } +} + func TestCollectSkipsMergedQueryWhenThereAreNoBranches(t *testing.T) { fr := fakeRunner{ "worktree list --porcelain -z": "", diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 194a1e5..4f89a0a 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -29,9 +29,10 @@ const ( ) // ForceDeleteConfirmPhrase is the exact text a user must type to delete a -// branch with unmerged changes. It must match verbatim (case-sensitive) — -// this is deliberate friction against losing unmerged work, so it is never -// made configurable. +// 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. const ForceDeleteConfirmPhrase = "delete" // Result is what the picker produced when the program exited. @@ -125,9 +126,10 @@ 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, 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. +// unmerged, or any marked worktree is dirty, 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. func (m Model) updateConfirmDelete(msg tea.KeyMsg) (tea.Model, tea.Cmd) { if isCancel(msg) { m.mode = modeList @@ -135,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) { + if hasUnmergedBranch(marked) || hasDirtyWorktree(marked) { m.forceConfirmInput = "" m.mode = modeConfirmForceDelete return m, nil @@ -148,9 +150,10 @@ 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. 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 +// 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. func (m Model) updateConfirmForceDelete(msg tea.KeyMsg) (tea.Model, tea.Cmd) { @@ -191,6 +194,18 @@ func hasUnmergedBranch(items []gitdata.Item) bool { return false } +// hasDirtyWorktree reports whether any item's worktree has modified or +// untracked files — the condition that makes `git worktree remove` (without +// --force) refuse to delete it. +func hasDirtyWorktree(items []gitdata.Item) bool { + for _, item := range items { + if item.Dirty { + return true + } + } + return false +} + func (m Model) updateLocked(msg tea.KeyMsg) (tea.Model, tea.Cmd) { if isCancel(msg) { m.mode = modeList @@ -523,10 +538,21 @@ func (m Model) View() string { b.WriteString("[Enter] confirm [Esc] cancel\n") return b.String() case modeConfirmForceDelete: - b.WriteString("The following branch(es) have unmerged changes and will be permanently lost:\n") - for _, item := range m.Marked() { - if item.Unmerged && !item.Detached { - fmt.Fprintf(&b, " %s\n", item.Branch) + marked := m.Marked() + if hasUnmergedBranch(marked) { + b.WriteString("The following branch(es) have unmerged changes and will be permanently lost:\n") + for _, item := range marked { + if item.Unmerged && !item.Detached { + fmt.Fprintf(&b, " %s\n", item.Branch) + } + } + } + if hasDirtyWorktree(marked) { + b.WriteString("The following worktree(s) have modified or untracked files that will be permanently lost:\n") + for _, item := range marked { + if item.Dirty { + 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) @@ -647,7 +673,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 require typing a phrase)", + " delete : D (marked branches, asks to confirm; unmerged branches or dirty 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 ec60749..7688f87 100644 --- a/internal/ui/ui_test.go +++ b/internal/ui/ui_test.go @@ -495,6 +495,74 @@ func TestForceDeleteConfirmsWholeMixedBatch(t *testing.T) { } } +func TestConfirmDeleteEnterWithDirtyWorktreeEntersForceDeleteMode(t *testing.T) { + items := testItems() + items[1].Dirty = true // feature/login + m := New(items, "/repo/proj", "", true) + m = send(t, m, key('j'), key('c'), key('D'), keyType(tea.KeyEnter)) + if m.mode != modeConfirmForceDelete { + t.Fatalf("mode after confirming delete with a dirty worktree = %v, want modeConfirmForceDelete", m.mode) + } + if m.quitting { + t.Fatal("Enter in modeConfirmDelete with a dirty worktree should not quit yet") + } +} + +func TestForceDeleteViewListsOnlyDirtyWorktreesFromMixedBatch(t *testing.T) { + items := testItems() + items[3].Locked = false + items[1].Dirty = true // feature/login dirty; release/2.1 stays clean + m := New(items, "/repo/proj", "", true) + m = send(t, m, key('j'), key('c'), key('j'), key('j'), key('c'), key('D'), keyType(tea.KeyEnter)) + view := m.View() + if !strings.Contains(view, "feature/login") { + t.Fatalf("force-delete view missing dirty worktree:\n%s", view) + } + if strings.Contains(view, "release/2.1") { + t.Fatalf("force-delete view should not list clean worktree release/2.1:\n%s", view) + } + if !strings.Contains(view, ForceDeleteConfirmPhrase) { + t.Fatalf("force-delete view missing required phrase:\n%s", view) + } +} + +func TestForceDeleteExactPhraseQuitsWithDirtyWorktree(t *testing.T) { + items := testItems() + items[1].Dirty = true + m := New(items, "/repo/proj", "", true) + m = send(t, m, key('j'), 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 != "feature/login" { + t.Fatalf("Result().Delete = %+v, want [feature/login]", res.Delete) + } +} + +func TestForceDeleteViewListsBothUnmergedBranchAndDirtyWorktree(t *testing.T) { + items := testItems() + items[3].Locked = false + items[1].Dirty = true // feature/login dirty + items[3].Unmerged = true // release/2.1 unmerged + m := New(items, "/repo/proj", "", true) + m = send(t, m, key('j'), key('c'), key('j'), key('j'), key('c'), key('D'), keyType(tea.KeyEnter)) + view := m.View() + if !strings.Contains(view, "unmerged changes") { + t.Fatalf("force-delete view missing unmerged-branch section:\n%s", view) + } + if !strings.Contains(view, "modified or untracked files") { + t.Fatalf("force-delete view missing dirty-worktree section:\n%s", view) + } + if !strings.Contains(view, "feature/login") || !strings.Contains(view, "release/2.1") { + t.Fatalf("force-delete view missing both items:\n%s", view) + } +} + func TestHelpOverlayReturnsToList(t *testing.T) { m := New(testItems(), "/repo/proj", "", true) m = send(t, m, key('?')) @@ -514,7 +582,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 require typing a phrase)") { + if !strings.Contains(view, "delete : D (marked branches, asks to confirm; unmerged branches or dirty worktrees require typing a phrase)") { t.Fatalf("help overlay missing delete semantics:\n%s", view) } } From 371c8824e500b0d722d6ccebeb4cae7e2a7df4ca Mon Sep 17 00:00:00 2001 From: Adam Jedrzejewski Date: Mon, 20 Jul 2026 00:23:33 +0200 Subject: [PATCH 2/3] no-mistakes(review): Handle hidden untracked files and prunable worktrees --- internal/gitdata/gitdata.go | 27 +++++++---- internal/gitdata/gitdata_test.go | 77 ++++++++++++++++++++++---------- 2 files changed, 72 insertions(+), 32 deletions(-) diff --git a/internal/gitdata/gitdata.go b/internal/gitdata/gitdata.go index 048c639..0fb5a3b 100644 --- a/internal/gitdata/gitdata.go +++ b/internal/gitdata/gitdata.go @@ -38,6 +38,7 @@ type worktreeInfo struct { branch string // short branch name, "" if detached locked bool detached bool + prunable bool } // Collect runs git branch and git worktree list against the repository @@ -124,11 +125,13 @@ func collect(run runnerFunc) ([]Item, error) { item.Path = w.path item.Locked = w.locked item.IsCurrent = normalizePath(w.path) == top - dirty, err := isDirty(run, w.path) - if err != nil { - return nil, err + if !w.prunable { + dirty, err := isDirty(run, w.path) + if err != nil { + return nil, err + } + item.Dirty = dirty } - item.Dirty = dirty } items = append(items, item) } @@ -136,9 +139,13 @@ func collect(run runnerFunc) ([]Item, error) { if !w.detached { continue } - dirty, err := isDirty(run, w.path) - if err != nil { - return nil, err + dirty := false + if !w.prunable { + var err error + dirty, err = isDirty(run, w.path) + if err != nil { + return nil, err + } } items = append(items, Item{ Branch: "(detached)", @@ -197,6 +204,10 @@ func parseWorktreePorcelain(out string) []worktreeInfo { if cur != nil { cur.locked = true } + case "prunable": + if cur != nil { + cur.prunable = true + } } } flush() @@ -222,7 +233,7 @@ func normalizePath(p string) string { // files — the same condition that makes `git worktree remove` (without // --force) refuse to delete it. func isDirty(run runnerFunc, path string) (bool, error) { - out, err := run("-C", path, "status", "--porcelain") + out, err := run("-C", path, "status", "--porcelain", "--untracked-files=all") if err != nil { return false, err } diff --git a/internal/gitdata/gitdata_test.go b/internal/gitdata/gitdata_test.go index 612c09b..89b970b 100644 --- a/internal/gitdata/gitdata_test.go +++ b/internal/gitdata/gitdata_test.go @@ -44,6 +44,7 @@ func TestParseWorktreePorcelain(t *testing.T) { "worktree /repo/proj-scratch", "HEAD jkl012", "detached", + "prunable gitdir file points to non-existent location", "", }, "\x00") @@ -52,7 +53,7 @@ func TestParseWorktreePorcelain(t *testing.T) { {path: "/repo/proj", branch: "main"}, {path: "/repo/proj-login", branch: "feature/login"}, {path: "/repo/proj-release", branch: "release/2.1", locked: true}, - {path: "/repo/proj-scratch", detached: true}, + {path: "/repo/proj-scratch", detached: true, prunable: true}, } if !reflect.DeepEqual(got, want) { t.Fatalf("parseWorktreePorcelain() = %#v, want %#v", got, want) @@ -109,13 +110,13 @@ func TestCollectMergesBranchesAndWorktrees(t *testing.T) { "detached", "", }, "\x00"), - "branch --list --format=%(refname:short)": "main\nfeature/login\nbugfix/api-timeout\nrelease/2.1\n", - "branch --format=%(refname:short) --merged": "main\nbugfix/api-timeout\n", - "rev-parse --show-toplevel": "/repo/proj\n", - "-C /repo/proj status --porcelain": "", - "-C /repo/proj-login status --porcelain": "", - "-C /repo/proj-release status --porcelain": "", - "-C /repo/proj-scratch status --porcelain": "", + "branch --list --format=%(refname:short)": "main\nfeature/login\nbugfix/api-timeout\nrelease/2.1\n", + "branch --format=%(refname:short) --merged": "main\nbugfix/api-timeout\n", + "rev-parse --show-toplevel": "/repo/proj\n", + "-C /repo/proj status --porcelain --untracked-files=all": "", + "-C /repo/proj-login status --porcelain --untracked-files=all": "", + "-C /repo/proj-release status --porcelain --untracked-files=all": "", + "-C /repo/proj-scratch status --porcelain --untracked-files=all": "", } items, err := collect(fr.run) @@ -137,11 +138,11 @@ func TestCollectMergesBranchesAndWorktrees(t *testing.T) { func TestCollectMovesCurrentItemFirst(t *testing.T) { fr := fakeRunner{ - "worktree list --porcelain -z": "worktree /repo/proj\x00HEAD abc123\x00branch refs/heads/z-current\x00", - "branch --list --format=%(refname:short)": "a-first\nz-current\n", - "branch --format=%(refname:short) --merged": "a-first\nz-current\n", - "rev-parse --show-toplevel": "/repo/proj\n", - "-C /repo/proj status --porcelain": "", + "worktree list --porcelain -z": "worktree /repo/proj\x00HEAD abc123\x00branch refs/heads/z-current\x00", + "branch --list --format=%(refname:short)": "a-first\nz-current\n", + "branch --format=%(refname:short) --merged": "a-first\nz-current\n", + "rev-parse --show-toplevel": "/repo/proj\n", + "-C /repo/proj status --porcelain --untracked-files=all": "", } items, err := collect(fr.run) if err != nil { @@ -164,11 +165,11 @@ func TestCollectMovesCurrentFirstPreservingRemainingOrder(t *testing.T) { "detached", "", }, "\x00"), - "branch --list --format=%(refname:short)": "a-first\nb-middle\nz-current\n", - "branch --format=%(refname:short) --merged": "a-first\nb-middle\nz-current\n", - "rev-parse --show-toplevel": "/repo/proj-current\n", - "-C /repo/proj-current status --porcelain": "", - "-C /repo/proj-scratch status --porcelain": "", + "branch --list --format=%(refname:short)": "a-first\nb-middle\nz-current\n", + "branch --format=%(refname:short) --merged": "a-first\nb-middle\nz-current\n", + "rev-parse --show-toplevel": "/repo/proj-current\n", + "-C /repo/proj-current status --porcelain --untracked-files=all": "", + "-C /repo/proj-scratch status --porcelain --untracked-files=all": "", } items, err := collect(fr.run) @@ -221,11 +222,11 @@ func TestCollectMarksDirtyWorktrees(t *testing.T) { "branch refs/heads/feature/login", "", }, "\x00"), - "branch --list --format=%(refname:short)": "main\nfeature/login\n", - "branch --format=%(refname:short) --merged": "main\nfeature/login\n", - "rev-parse --show-toplevel": "/repo/proj\n", - "-C /repo/proj status --porcelain": "", - "-C /repo/proj-login status --porcelain": " M tracked.go\n?? scratch.txt\n", + "branch --list --format=%(refname:short)": "main\nfeature/login\n", + "branch --format=%(refname:short) --merged": "main\nfeature/login\n", + "rev-parse --show-toplevel": "/repo/proj\n", + "-C /repo/proj status --porcelain --untracked-files=all": "", + "-C /repo/proj-login status --porcelain --untracked-files=all": " M tracked.go\n?? scratch.txt\n", } items, err := collect(fr.run) @@ -248,13 +249,41 @@ func TestCollectPropagatesStatusErrors(t *testing.T) { "branch --list --format=%(refname:short)": "main\n", "branch --format=%(refname:short) --merged": "main\n", "rev-parse --show-toplevel": "/repo/proj\n", - // "-C /repo/proj status --porcelain" deliberately omitted -> "unexpected" error + // Status response deliberately omitted to produce an unexpected-subcommand error. } if _, err := collect(fr.run); err == nil { t.Fatal("collect() error = nil, want error when git status fails") } } +func TestCollectSkipsStatusForPrunableWorktrees(t *testing.T) { + fr := fakeRunner{ + "worktree list --porcelain -z": strings.Join([]string{ + "worktree /repo/proj", + "HEAD abc123", + "branch refs/heads/main", + "", + "worktree /repo/missing", + "HEAD def456", + "branch refs/heads/stale", + "prunable gitdir file points to non-existent location", + "", + }, "\x00"), + "branch --list --format=%(refname:short)": "main\nstale\n", + "branch --format=%(refname:short) --merged": "main\nstale\n", + "rev-parse --show-toplevel": "/repo/proj\n", + "-C /repo/proj status --porcelain --untracked-files=all": "", + } + + items, err := collect(fr.run) + if err != nil { + t.Fatalf("collect() error = %v", err) + } + if len(items) != 2 || items[1].Path != "/repo/missing" || items[1].Dirty { + t.Fatalf("collect() = %#v, want clean stale worktree without status probe", items) + } +} + func TestCollectSkipsMergedQueryWhenThereAreNoBranches(t *testing.T) { fr := fakeRunner{ "worktree list --porcelain -z": "", From 64f4a321008fb755382023b822fef76b8241fda1 Mon Sep 17 00:00:00 2001 From: Adam Jedrzejewski Date: Mon, 20 Jul 2026 00:27:19 +0200 Subject: [PATCH 3/3] no-mistakes(document): Refresh dirty worktree deletion documentation --- README.md | 2 +- SPEC.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 57a48c5..20d2848 100644 --- a/README.md +++ b/README.md @@ -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, and `git worktree list --porcelain`) and every write (`git switch`, `git worktree add`, `git worktree remove`, `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, and whether that worktree 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`, `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 d6c841a..33e144f 100644 --- a/SPEC.md +++ b/SPEC.md @@ -89,8 +89,8 @@ 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 untracked -files:** `git branch -d` (the non-force delete `wt` uses for merged +**Deleting branches with unmerged changes, or worktrees with modified or +untracked files:** `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