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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ Once at least one item is marked, a hint line appears below the list telling you

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.

Highlight a branch — or mark several with `c` — and press `F` to force update them. A confirmation screen lists the target branch(es); `Enter` runs `git fetch origin`, then resets each branch to `origin/<branch>` (`git reset --hard` in its worktree, `git branch -f` for a plain branch with no worktree). This discards local commits and, in worktrees, uncommitted changes; the confirmation screen warns when a target worktree is dirty. Detached worktrees have no branch and are skipped. `Esc`/`Ctrl-C`/`q` cancels without touching Git state or clearing marks.

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 Expand Up @@ -98,7 +100,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`, 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.
`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`, confirmed `git branch -D`, and confirmed `git fetch origin` + `git reset --hard` / `git branch -f`), 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
17 changes: 14 additions & 3 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`, 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.
`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, and force-update one or more branches to their upstream tip via a similar confirmation 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`, explicitly confirmed `branch -D`, and confirmed `fetch` + `reset --hard` / `branch -f`) happens only after user confirmation, and only via standard `git` invocations.

## 2. Technology Choice

Expand Down Expand Up @@ -52,13 +52,14 @@ No `fzf` dependency is required, but the design deliberately keeps the same *int
│ - worktree path → emit cd path to wrapper (no git mutation)
│ - existing path → return it to the shell wrapper
│ - marked set → git worktree remove (forced if dirty/locked) + git branch -d/-D, per item
│ - F target set → git fetch origin, then reset --hard / branch -f to origin/<branch>
└──────────────────────┘
```

**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 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.
3. `action` executes exactly one of: `git switch`, `git worktree add`, a directory change (for worktrees), the mark-then-`D`-then-confirm deletion flow, or the `F`-then-confirm force-update flow: one `git fetch origin`, then `git reset --hard origin/<branch>` for each target branch with a worktree and `git branch -f <branch> origin/<branch>` for each target branch without one. Detached worktrees have no branch and are skipped.

**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 @@ -136,6 +137,16 @@ Type "delete" and press Enter to proceed, or Esc to cancel:
screen on their own, though they can still trigger it via the dirty
check if they have modified or untracked files.

**Force-updating branches:** highlighting a row (or marking several with
`c`) and pressing `F` opens a confirmation screen listing the target
branch(es) and their worktree paths (or `(no worktree)`). `Enter` runs one
`git fetch origin`, then `git reset --hard origin/<branch>` for each target
with a worktree and `git branch -f <branch> origin/<branch>` for each plain
target. This discards local commits and, in worktrees, uncommitted changes;
the confirmation screen warns when a target worktree is dirty. Detached
worktrees are skipped. `Esc`/`Ctrl-C`/`q` cancels without touching Git state
or clearing marks. The hint line and `?` overlay document the binding.

## 5. Implementation Details

**Command-line arguments:**
Expand Down Expand Up @@ -170,7 +181,7 @@ The authoritative collector and action implementations are in
**Integration tests** (real repositories):
- Use `t.TempDir()` to create scratch repositories via actual `git init`, `git commit --allow-empty`, and `git worktree add` commands.
- Drive the action and collection layers against the scratch repository and assert the resulting paths and Git repository state.
- Cover switching a plain branch, resolving an existing worktree, creating a worktree, and deleting marked branches, both with and without a worktree.
- Cover switching a plain branch, resolving an existing worktree, creating a worktree, deleting marked branches (with and without a worktree), and force-updating both a plain branch and a worktree branch to a remote tip that has advanced locally.

## 7. Building

Expand Down
13 changes: 13 additions & 0 deletions cmd/wt/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ func run(pathOnly bool, worktreeRootFlag string, noColor bool) error {
if len(result.Delete) > 0 {
return applyDelete(result.Delete)
}
if len(result.ForceUpdate) > 0 {
return applyForceUpdate(result.ForceUpdate)
}

dest, err := applyResult(result)
if err != nil {
Expand Down Expand Up @@ -116,6 +119,16 @@ func applyDelete(items []gitdata.Item) error {
return nil
}

// applyForceUpdate resets each confirmed branch to its upstream tip,
// reporting success to stderr on completion.
func applyForceUpdate(items []gitdata.Item) error {
if err := action.ForceUpdate(items); err != nil {
return err
}
fmt.Fprintf(os.Stderr, "wt: force-updated %d branch(es)\n", len(items))
return nil
}

func applyResult(result ui.Result) (string, error) {
if result.Item.HasWorktree() {
return action.Switch(result.Item)
Expand Down
105 changes: 105 additions & 0 deletions integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,12 @@ func applyResult(t *testing.T, result ui.Result) string {
}
return ""
}
if len(result.ForceUpdate) > 0 {
if err := action.ForceUpdate(result.ForceUpdate); err != nil {
t.Fatalf("action.ForceUpdate: %v", err)
}
return ""
}
if result.Item.HasWorktree() {
dest, err := action.Switch(result.Item)
if err != nil {
Expand Down Expand Up @@ -378,6 +384,105 @@ func TestIntegrationDeleteDirtyWorktreeRequiresForcePhrase(t *testing.T) {
}
}

// initRepoWithRemote initialises repo and pushes its initial commit to a
// fresh bare origin, returning the origin path.
func initRepoWithRemote(t *testing.T, repo string) string {
t.Helper()
initRepo(t, repo)
tmp := t.TempDir()
remote := filepath.Join(tmp, "origin.git")
runGit(t, tmp, "init", "--bare", "-b", "main", remote)
runGit(t, repo, "remote", "add", "origin", remote)
runGit(t, repo, "push", "-u", "origin", "main")
return remote
}

// cloneOrigin clones remote into a fresh directory and configures a committer.
func cloneOrigin(t *testing.T, remote string) string {
t.Helper()
parent := t.TempDir()
clone := filepath.Join(parent, "clone")
runGit(t, parent, "clone", remote, clone)
runGit(t, clone, "config", "user.email", "wt-test@example.com")
runGit(t, clone, "config", "user.name", "wt test")
runGit(t, clone, "config", "commit.gpgsign", "false")
return clone
}

func TestIntegrationForceUpdatePlainBranchToRemoteTip(t *testing.T) {
repo := t.TempDir()
remote := initRepoWithRemote(t, repo)

// Advance origin/main from a second clone so the local repo is behind.
other := cloneOrigin(t, remote)
runGit(t, other, "commit", "--allow-empty", "-m", "remote commit")
runGit(t, other, "push", "origin", "main")
want := strings.TrimSpace(runGit(t, other, "rev-parse", "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)
}

// main is highlighted at cursor 0: F then Enter confirms the force update.
m := ui.New(items, top, "", true)
result := drivePicker(t, m, keyRune('F'), keyEnter)
if len(result.ForceUpdate) != 1 || result.ForceUpdate[0].Branch != "main" {
t.Fatalf("result.ForceUpdate = %+v, want [main]", result.ForceUpdate)
}
applyResult(t, result)

if got := strings.TrimSpace(runGit(t, repo, "rev-parse", "main")); got != want {
t.Fatalf("main = %s, want remote tip %s", got, want)
}
}

func TestIntegrationForceUpdateWorktreeBranchToRemoteTip(t *testing.T) {
repo := t.TempDir()
remote := initRepoWithRemote(t, repo)
runGit(t, repo, "branch", "feature/x")
runGit(t, repo, "push", "origin", "feature/x")

// Advance origin/feature/x from a second clone.
other := cloneOrigin(t, remote)
runGit(t, other, "checkout", "-b", "feature/x", "origin/feature/x")
runGit(t, other, "commit", "--allow-empty", "-m", "remote feature commit")
runGit(t, other, "push", "origin", "feature/x")
want := strings.TrimSpace(runGit(t, other, "rev-parse", "feature/x"))

// The local worktree diverges with its own commit.
wtDir := filepath.Join(t.TempDir(), "feature-x-checkout")
runGit(t, repo, "worktree", "add", wtDir, "feature/x")
runGit(t, wtDir, "commit", "--allow-empty", "-m", "local divergence")
chdir(t, repo)

items, err := gitdata.Collect()
if err != nil {
t.Fatalf("gitdata.Collect: %v", err)
}
top, err := gitdata.Toplevel()
if err != nil {
t.Fatalf("gitdata.Toplevel: %v", err)
}

// order: main (cursor 0, current), feature/x (cursor 1) -> down, mark, F, Enter.
m := ui.New(items, top, "", true)
result := drivePicker(t, m, keyDown, keyRune('c'), keyRune('F'), keyEnter)
if len(result.ForceUpdate) != 1 || result.ForceUpdate[0].Branch != "feature/x" {
t.Fatalf("result.ForceUpdate = %+v, want [feature/x]", result.ForceUpdate)
}
applyResult(t, result)

if got := strings.TrimSpace(runGit(t, wtDir, "rev-parse", "HEAD")); got != want {
t.Fatalf("feature/x worktree HEAD = %s, want remote tip %s", got, want)
}
}

func worktreePathForBranch(t *testing.T, repo, branch string) string {
t.Helper()
out := runGit(t, repo, "worktree", "list", "--porcelain")
Expand Down
41 changes: 41 additions & 0 deletions internal/action/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,47 @@ func newWorktreeWith(run runnerFunc, path, branch string) (string, error) {
return path, nil
}

// ForceUpdate resets each branch to its upstream tip. It runs a single
// `git fetch origin`, then `git reset --hard origin/<branch>` for branches
// with a worktree and `git branch -f <branch> origin/<branch>` for plain
// branches. Callers must only pass items after the user has confirmed the
// action (see internal/ui's modeConfirmForceUpdate) — this function performs
// no confirmation of its own. Detached worktrees have no branch and are
// skipped. Every item is attempted even if earlier ones fail; all failures
// are combined into a single returned error.
func ForceUpdate(items []gitdata.Item) error {
return forceUpdateWith(runGit, items)
}

func forceUpdateWith(run runnerFunc, items []gitdata.Item) error {
var targets []gitdata.Item
for _, item := range items {
if !item.Detached {
targets = append(targets, item)
}
}
if len(targets) == 0 {
return nil
}
if err := run("fetch", "origin"); err != nil {
return fmt.Errorf("fetch origin: %w", err)
}
var errs []error
for _, item := range targets {
ref := "origin/" + item.Branch
if item.HasWorktree() {
if err := run("-C", item.Path, "reset", "--hard", ref); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", item.Branch, err))
}
continue
}
if err := run("branch", "-f", item.Branch, ref); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", item.Branch, err))
}
}
return errors.Join(errs...)
}

// DeleteWorktrees removes each item's worktree, if it has one, via
// `git worktree remove`, or `git worktree remove --force` when item.Dirty is
// set, or `git worktree remove --force --force` when item.Locked is set (a
Expand Down
69 changes: 69 additions & 0 deletions internal/action/action_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,3 +243,72 @@ func TestNewWorktreeWithRunsGitWorktreeAdd(t *testing.T) {
t.Fatalf("git calls = %v, want %v", *calls, want)
}
}

func TestForceUpdateWithFetchesOnceThenResetsWorktreeAndMovesPlainBranch(t *testing.T) {
run, calls := recordingRunner()
items := []gitdata.Item{
{Branch: "feature/login", Path: "/repo/proj-login"},
{Branch: "bugfix/api-timeout"},
}

if err := forceUpdateWith(run, items); err != nil {
t.Fatalf("forceUpdateWith() error = %v", err)
}
want := [][]string{
{"fetch", "origin"},
{"-C", "/repo/proj-login", "reset", "--hard", "origin/feature/login"},
{"branch", "-f", "bugfix/api-timeout", "origin/bugfix/api-timeout"},
}
if !reflect.DeepEqual(*calls, want) {
t.Fatalf("git calls = %v, want %v", *calls, want)
}
}

func TestForceUpdateWithDetachedOnlyRunsNoGit(t *testing.T) {
run, calls := recordingRunner()
item := gitdata.Item{Branch: "(detached)", Path: "/repo/proj-scratch", Detached: true}

if err := forceUpdateWith(run, []gitdata.Item{item}); err != nil {
t.Fatalf("forceUpdateWith() error = %v", err)
}
if len(*calls) != 0 {
t.Fatalf("git calls = %v, want none for a detached worktree", *calls)
}
}

func TestForceUpdateWithFetchFailureStopsBeforeAnyReset(t *testing.T) {
run := func(args ...string) error {
if args[0] == "fetch" {
return fmt.Errorf("no remote")
}
t.Fatalf("unexpected git call after failed fetch: %v", args)
return nil
}
item := gitdata.Item{Branch: "feature/login", Path: "/repo/proj-login"}

err := forceUpdateWith(run, []gitdata.Item{item})
if err == nil || !strings.Contains(err.Error(), "fetch origin") {
t.Fatalf("forceUpdateWith() error = %v, want fetch origin error", err)
}
}

func TestForceUpdateWithContinuesAfterFailureAndCombinesErrors(t *testing.T) {
run := func(args ...string) error {
if args[len(args)-1] == "origin/feature/login" {
return fmt.Errorf("boom")
}
return nil
}
items := []gitdata.Item{
{Branch: "feature/login", Path: "/repo/proj-login"},
{Branch: "bugfix/api-timeout"},
}

err := forceUpdateWith(run, items)
if err == nil {
t.Fatal("forceUpdateWith() error = nil, want combined error from the failing item")
}
if !strings.Contains(err.Error(), "feature/login") {
t.Fatalf("error = %v, want it to mention feature/login", err)
}
}
Loading
Loading