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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ Highlight a branch or worktree and press `c` to mark or unmark it as part of the

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.

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 the exact phrase `Yes, I want to remove the branch that has changes that have been unmerged.` 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.

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.

Selecting a worktree changes your shell's directory to it. Selecting a plain branch with no worktree prompts you to either switch to it in place or create a new worktree for it:
Expand Down
35 changes: 35 additions & 0 deletions SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,41 @@ 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) refuses branches not fully merged, so by default such a
branch is simply left in place. `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:

```
The following branch(es) have unmerged changes and will be permanently lost:
feature/wip-thing
Type the phrase below exactly and press Enter to proceed, or Esc to cancel:

Yes, I want to remove the branch that has changes that have been unmerged.

> _
```

- 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.
- The user must type the phrase **"Yes, I want to remove the branch that has
changes that have been unmerged."** exactly (case-sensitive, full
punctuation) 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.
- 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.

## 5. Implementation Details

**Command-line arguments:**
Expand Down
50 changes: 50 additions & 0 deletions integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,56 @@ func TestIntegrationDeleteMarkedBranchWithoutWorktree(t *testing.T) {
}
}

func TestIntegrationDeleteUnmergedBranchRequiresForcePhrase(t *testing.T) {
repo := t.TempDir()
initRepo(t, repo)
runGit(t, repo, "branch", "wip")
runGit(t, repo, "checkout", "wip")
runGit(t, repo, "commit", "--allow-empty", "-m", "unmerged work")
runGit(t, repo, "checkout", "main")
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 wip *gitdata.Item
for i := range items {
if items[i].Branch == "wip" {
wip = &items[i]
}
}
if wip == nil || !wip.Unmerged {
t.Fatalf("items = %+v, want a wip branch marked Unmerged", items)
}

// order: main (cursor 0), wip (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 != "wip" {
t.Fatalf("result.Delete = %+v, want [wip]", result.Delete)
}
applyResult(t, result)

branches := runGit(t, repo, "branch", "--list", "wip")
if strings.TrimSpace(branches) != "" {
t.Fatalf("branch wip 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
18 changes: 12 additions & 6 deletions internal/action/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,13 @@ 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`
// (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.
// `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
// 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.
func DeleteWorktrees(items []gitdata.Item) error {
return deleteWorktreesWith(runGit, items)
}
Expand All @@ -84,7 +86,11 @@ func deleteWorktreesWith(run runnerFunc, items []gitdata.Item) error {
if item.Detached {
continue
}
if err := run("branch", "-d", item.Branch); err != nil {
deleteFlag := "-d"
if item.Unmerged {
deleteFlag = "-D"
}
if err := run("branch", deleteFlag, item.Branch); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", item.Branch, err))
}
}
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 @@ -79,6 +79,27 @@ func TestDeleteWorktreesWithRemovesWorktreeThenDeletesBranch(t *testing.T) {
}
}

func TestDeleteWorktreesWithForcesDeleteOfUnmergedBranch(t *testing.T) {
run, calls := recordingRunner()
items := []gitdata.Item{
{Branch: "feature/wip", Path: "/repo/proj-wip", Unmerged: 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", "/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
12 changes: 11 additions & 1 deletion internal/gitdata/gitdata.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type Item struct {
IsCurrent bool
Locked bool
Detached bool
Unmerged bool // true if the branch is not fully merged into HEAD (git branch -d would refuse it)
}

// HasWorktree reports whether the branch is checked out anywhere.
Expand Down Expand Up @@ -99,14 +100,23 @@ func collect(run runnerFunc) ([]Item, error) {
}
branches := parseLines(brOut)

mergedOut, err := run("branch", "--format=%(refname:short)", "--merged")
if err != nil {
return nil, err
}
merged := make(map[string]bool, len(branches))
for _, b := range parseLines(mergedOut) {
merged[b] = true
}

top, err := toplevel(run)
if err != nil {
return nil, err
}

items := make([]Item, 0, len(branches)+len(worktrees))
for _, b := range branches {
item := Item{Branch: b}
item := Item{Branch: b, Unmerged: !merged[b]}
if w, ok := byBranch[b]; ok {
item.Path = w.path
item.Locked = w.locked
Expand Down
52 changes: 39 additions & 13 deletions internal/gitdata/gitdata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,12 @@ func TestParseLines(t *testing.T) {
}
}

// fakeRunner returns canned output per git subcommand, keyed by the first arg.
// fakeRunner returns canned output per full git invocation, keyed by the
// space-joined args (e.g. "branch --format=%(refname:short) --merged").
type fakeRunner map[string]string

func (f fakeRunner) run(args ...string) (string, error) {
out, ok := f[args[0]]
out, ok := f[strings.Join(args, " ")]
if !ok {
return "", fmt.Errorf("unexpected git subcommand: %v", args)
}
Expand All @@ -89,7 +90,7 @@ func (f fakeRunner) run(args ...string) (string, error) {

func TestCollectMergesBranchesAndWorktrees(t *testing.T) {
fr := fakeRunner{
"worktree": strings.Join([]string{
"worktree list --porcelain -z": strings.Join([]string{
"worktree /repo/proj",
"HEAD abc123",
"branch refs/heads/main",
Expand All @@ -108,8 +109,9 @@ func TestCollectMergesBranchesAndWorktrees(t *testing.T) {
"detached",
"",
}, "\x00"),
"branch": "main\nfeature/login\nbugfix/api-timeout\nrelease/2.1\n",
"rev-parse": "/repo/proj\n",
"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",
}

items, err := collect(fr.run)
Expand All @@ -119,9 +121,9 @@ func TestCollectMergesBranchesAndWorktrees(t *testing.T) {

want := []Item{
{Branch: "main", Path: "/repo/proj", IsCurrent: true},
{Branch: "feature/login", Path: "/repo/proj-login"},
{Branch: "feature/login", Path: "/repo/proj-login", Unmerged: true},
{Branch: "bugfix/api-timeout"},
{Branch: "release/2.1", Path: "/repo/proj-release", Locked: true},
{Branch: "release/2.1", Path: "/repo/proj-release", Locked: true, Unmerged: true},
{Branch: "(detached)", Path: "/repo/proj-scratch", Detached: true},
}
if !reflect.DeepEqual(items, want) {
Expand All @@ -131,9 +133,10 @@ func TestCollectMergesBranchesAndWorktrees(t *testing.T) {

func TestCollectMovesCurrentItemFirst(t *testing.T) {
fr := fakeRunner{
"worktree": "worktree /repo/proj\x00HEAD abc123\x00branch refs/heads/z-current\x00",
"branch": "a-first\nz-current\n",
"rev-parse": "/repo/proj\n",
"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",
}
items, err := collect(fr.run)
if err != nil {
Expand All @@ -146,7 +149,7 @@ func TestCollectMovesCurrentItemFirst(t *testing.T) {

func TestCollectMovesCurrentFirstPreservingRemainingOrder(t *testing.T) {
fr := fakeRunner{
"worktree": strings.Join([]string{
"worktree list --porcelain -z": strings.Join([]string{
"worktree /repo/proj-current",
"HEAD abc123",
"branch refs/heads/z-current",
Expand All @@ -156,8 +159,9 @@ func TestCollectMovesCurrentFirstPreservingRemainingOrder(t *testing.T) {
"detached",
"",
}, "\x00"),
"branch": "a-first\nb-middle\nz-current\n",
"rev-parse": "/repo/proj-current\n",
"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",
}

items, err := collect(fr.run)
Expand All @@ -176,6 +180,28 @@ func TestCollectMovesCurrentFirstPreservingRemainingOrder(t *testing.T) {
}
}

func TestCollectMarksUnmergedBranches(t *testing.T) {
fr := fakeRunner{
"worktree list --porcelain -z": "",
"branch --list --format=%(refname:short)": "main\nfeature/wip\n",
"branch --format=%(refname:short) --merged": "main\n",
"rev-parse --show-toplevel": "/repo/proj\n",
}

items, err := collect(fr.run)
if err != nil {
t.Fatalf("collect() error = %v", err)
}

want := []Item{
{Branch: "main"},
{Branch: "feature/wip", Unmerged: true},
}
if !reflect.DeepEqual(items, want) {
t.Fatalf("collect() = %#v, want %#v", items, want)
}
}

func TestParseWorktreePorcelainPreservesSpecialPath(t *testing.T) {
out := "worktree /repo/café folder\\name\x00HEAD abc123\x00detached\x00\x00"
got := parseWorktreePorcelain(out)
Expand Down
Loading
Loading