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
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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 <shell>`, to perform the actual `cd`. This keeps your working directory untouched unless a switch actually happens.

Expand Down
64 changes: 38 additions & 26 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 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

Expand Down Expand Up @@ -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, ...}
┌─────────▼───────────┐
Expand All @@ -50,14 +51,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 (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.

Expand Down Expand Up @@ -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 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
`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

Expand Down
54 changes: 54 additions & 0 deletions integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
12 changes: 9 additions & 3 deletions internal/action/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
Expand Down
21 changes: 21 additions & 0 deletions internal/action/action_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand Down
Loading
Loading