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
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,27 @@ Select branch or worktree (j/k, / to filter, c to mark, ? for help)
○ release/2.1 [worktree, locked]
```

### Pull requests

`wt pr` needs the GitHub CLI (`gh`) installed and logged in for the current
repository.

```bash
wt pr # list open PRs with number, title and branch; pick one to switch to
wt pr 123 # switch straight to the branch of PR #123
```

`wt` fetches the PR head from `origin` first. If the local branch is strictly
behind `origin/<branch>`, it asks `Fast-forward ...? [y/N]`; only yes runs
`git merge --ff-only origin/<branch>` in the branch's worktree (or a
fast-forward ref update for a plain branch). A branch that has diverged is
reported as an error and left untouched; a missing local branch is created
from the remote tip without asking. Switching then follows the usual rules:
a branch with a worktree returns its path, a plain branch shows the
`[s]witch here / [w]orktree` prompt. `--no-color`, `--worktree-root DIR` and
`--path-only` work here too. PR heads are resolved as `origin/<branch>`, so
this covers branches pushed to the repository's `origin`, not fork PR heads.

Optional config file at `~/.config/wt/config.toml`:

```toml
Expand Down
24 changes: 21 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, 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.
`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 can switch to a GitHub pull request branch, picked from the open PRs or given by number, asking before fast-forwarding a local branch that is behind the PR head. 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 All @@ -21,6 +21,7 @@
| List and substring filter | Hand-rolled Bubble Tea model | Keeps navigation, filtering, and pagination behavior explicit and small. |
| Styling | [`lipgloss`](https://github.com/charmbracelet/lipgloss) | Highlights the selected row; `--no-color` disables that styling. |
| Git interaction | none (shell out to system `git` via `os/exec`) | Avoids embedding a Git implementation (e.g. `go-git`), which is heavyweight and can diverge in behavior from the user's actual Git config/hooks/credential helpers. Shelling out guarantees identical behavior to manual `git` commands. |
| PR interaction | none (shell out to the system `gh` CLI) | Reuses the user's GitHub login, repo detection and API behavior; `wt` only parses `gh pr list/view --json` output. |
| CLI flags | Go standard `flag` package | Sufficient for a single-purpose tool and keeps the dependency tree minimal. |

No `fzf` dependency is required, but the design deliberately keeps the same *interaction feel* the user's `fzf` one-liner already provides, while merging branches and worktrees into one list and natively understanding worktree-vs-plain-branch semantics — avoiding the "already checked out elsewhere" dead end of `git switch`.
Expand All @@ -34,8 +35,9 @@ No `fzf` dependency is required, but the design deliberately keeps the same *int
│
┌─────────▼───────────┐ ┌──────────────────────┐
│ gitdata (collector) │────▶│ git branch --list │
│ │ │ git worktree list │
│ - parses branches │ │ git rev-parse ... │
│ github (PR reader) │ │ git worktree list │
│ │ │ git rev-parse ... │
│ - parses branches │ │ gh pr list / view │
│ - parses worktrees │ │ git status │
│ - merges into Items │ │ --porcelain │
│ │ └──────────────────────┘
Expand Down Expand Up @@ -153,12 +155,27 @@ or clearing marks. The hint line and `?` overlay document the binding.

```
wt # interactive picker, default action
wt pr # list open PRs (#number, title, branch) and pick one
wt pr 123 # switch to the branch of PR #123
wt --path-only # print a selected worktree path for shell integration
wt --worktree-root DIR # base dir for new worktrees (overrides config)
wt --no-color
wt --version / --help
```

**Pull requests:** `wt pr` runs `gh pr list --state open --json
number,title,headRefName` and shows a picker with `#number title (branch)`
rows; `wt pr 123` runs `gh pr view 123 --json ...` and skips the picker. Both
then call `action.PreparePRBranch(branch, worktreePath, confirm)`: fetch that
branch from `origin`, create the local branch if missing, or — if the local
branch is strictly behind the remote tip — ask `Fast-forward <branch> to
origin/<branch>? [y/N]` and fast-forward only on yes (`git merge --ff-only`
in the worktree, `git branch -f` for a plain branch). A branch that has
diverged is rejected with an error and left untouched. Switching afterwards
is the same as a normal selection: return the worktree path, or use the
`[s]witch here / [w]orktree` prompt for a plain branch. `gh` must be installed
and authenticated for these commands.

**Config file** (`~/.config/wt/config.toml`, optional):

```toml
Expand All @@ -182,6 +199,7 @@ The authoritative collector and action implementations are in
- 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, 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.
- Cover PR preparation against a real bare origin: fast-forward on consent, no change on decline, an error on a diverged branch, creation of a missing branch, and a fast-forward inside a worktree. Parser tests cover `gh pr list/view` JSON and exact command shape.

## 7. Building

Expand Down
206 changes: 206 additions & 0 deletions cmd/wt/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,44 @@
package main

import (
"bufio"
"errors"
"flag"
"fmt"
"os"
"strings"

tea "github.com/charmbracelet/bubbletea"

"github.com/AgileIndustrialComplex/wt/internal/action"
"github.com/AgileIndustrialComplex/wt/internal/config"
"github.com/AgileIndustrialComplex/wt/internal/gitdata"
"github.com/AgileIndustrialComplex/wt/internal/github"
"github.com/AgileIndustrialComplex/wt/internal/ui"
)

var version = "dev"

// subcommand returns the first non-flag argument and its position in args,
// skipping flags that take a separate value. The shell wrapper prepends
// --path-only, so a subcommand may not be the first argument.
func subcommand(args []string) (string, int) {
for i := 0; i < len(args); i++ {
arg := args[i]
if !strings.HasPrefix(arg, "-") {
return arg, i
}
if (arg == "--worktree-root" || arg == "-worktree-root") && i+1 < len(args) {
i++
}
}
return "", -1
}

// One reader for all prompts: a fresh bufio.Reader would buffer and discard
// answers meant for the next prompt in the same invocation.
var stdinReader = bufio.NewReader(os.Stdin)

func main() {
if len(os.Args) > 1 && os.Args[1] == "init" {
if len(os.Args) != 3 {
Expand All @@ -31,6 +54,47 @@ func main() {
return
}

if cmd, cmdIdx := subcommand(os.Args[1:]); cmd == "pr" {
// The shell wrapper prepends --path-only, so "pr" is not necessarily
// the first argument. Pass every other argument to the PR flag set.
prArgs := append(append([]string{}, os.Args[1:cmdIdx+1]...), os.Args[cmdIdx+2:]...)
prFlags := flag.NewFlagSet("pr", flag.ExitOnError)
prPathOnly := prFlags.Bool("path-only", false, "print the chosen destination path, no cd (for scripting)")
prWorktreeRoot := prFlags.String("worktree-root", "", "base directory to propose for new worktrees")
prNoColor := prFlags.Bool("no-color", false, "disable colored output")
// flag stops at the first positional arg, so move the PR number
// after any flags: both `wt pr 123 --no-color` and
// `wt pr --no-color 123` must work.
var flagArgs, positional []string
args := prArgs
for i := 0; i < len(args); i++ {
arg := args[i]
if !strings.HasPrefix(arg, "-") {
positional = append(positional, arg)
continue
}
flagArgs = append(flagArgs, arg)
if (arg == "--worktree-root" || arg == "-worktree-root") && i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
i++
flagArgs = append(flagArgs, args[i])
}
}
_ = prFlags.Parse(append(flagArgs, positional...))
if prFlags.NArg() > 1 {
fmt.Fprintln(os.Stderr, "usage: wt pr [number] [--no-color] [--worktree-root DIR] [--path-only]")
os.Exit(1)
}
number := ""
if prFlags.NArg() == 1 {
number = prFlags.Arg(0)
}
if err := runPR(number, *prPathOnly, *prWorktreeRoot, *prNoColor); err != nil {
fmt.Fprintln(os.Stderr, "wt:", err)
os.Exit(1)
}
return
}

pathOnly := flag.Bool("path-only", false, "print the chosen destination path, no cd (for scripting)")
worktreeRoot := flag.String("worktree-root", "", "base directory to propose for new worktrees")
noColor := flag.Bool("no-color", false, "disable colored output")
Expand Down Expand Up @@ -106,6 +170,148 @@ func run(pathOnly bool, worktreeRootFlag string, noColor bool) error {
return nil
}

// runPR switches to the branch of a pull request. With a number it goes
// straight there; otherwise it lists open PRs and lets the picker choose.
// Before switching, a local branch that is strictly behind origin/<branch>
// is fast-forwarded only after an explicit yes.
func runPR(number string, pathOnly bool, worktreeRootFlag string, noColor bool) error {
cfg, err := config.Load()
if err != nil {
return err
}
worktreeRoot := cfg.WorktreeRoot
if worktreeRootFlag != "" {
worktreeRoot = worktreeRootFlag
}

branch := number
if number == "" {
prs, err := github.OpenPRs()
if err != nil {
return err
}
if len(prs) == 0 {
fmt.Fprintln(os.Stderr, "wt: no open pull requests")
return nil
}
items := make([]gitdata.Item, 0, len(prs))
for _, pr := range prs {
items = append(items, gitdata.Item{
Branch: pr.Branch,
Display: fmt.Sprintf("#%d %s (%s)", pr.Number, pr.Title, pr.Branch),
})
}
top, err := gitdata.Toplevel()
if err != nil {
return err
}
m := ui.NewPR(items, top, worktreeRoot, noColor, cfg.DefaultAction, cfg.Keymap)
program := tea.NewProgram(m, tea.WithOutput(os.Stderr))
final, err := program.Run()
if err != nil {
return err
}
result := final.(ui.Model).Result()
if result.Cancelled || result.Item.Branch == "" {
return nil
}
branch = result.Item.Branch
} else {
pr, err := github.Get(number)
if err != nil {
return err
}
branch = pr.Branch
}

local, err := itemForBranch(branch)
if err != nil {
return err
}
proceed, err := action.PreparePRBranch(branch, local.Path, func() bool { return askFastForward(branch) })
if err != nil {
return err
}
if !proceed {
return nil
}

local, err = itemForBranch(branch)
if err != nil {
return err
}
dest, err := switchPRBranch(local, worktreeRoot, cfg.DefaultAction)
if err != nil {
return err
}
if pathOnly {
fmt.Println(dest)
return nil
}
if dest != "" {
fmt.Fprintf(os.Stderr, "wt: run 'cd %s', or use shell integration (see `wt init`) to change directory automatically.\n", dest)
}
return nil
}

// itemForBranch returns the picker item for branch, or a bare item when the
// branch does not exist locally yet.
func itemForBranch(branch string) (gitdata.Item, error) {
items, err := gitdata.Collect()
if err != nil {
return gitdata.Item{}, err
}
for _, item := range items {
if item.Branch == branch {
return item, nil
}
}
return gitdata.Item{Branch: branch}, nil
}

// readAnswer consumes one line from the shared stdin reader, so several
// prompts in one invocation each get their own answer.
func readAnswer() string {
line, err := stdinReader.ReadString('\n')
if err != nil {
return ""
}
return strings.ToLower(strings.TrimSpace(line))
}

func askFastForward(branch string) bool {
fmt.Fprintf(os.Stderr, "Fast-forward %s to origin/%s? [y/N] ", branch, branch)
answer := readAnswer()
return answer == "y" || answer == "yes"
}

func switchPRBranch(item gitdata.Item, worktreeRoot, defaultAction string) (string, error) {
if item.HasWorktree() {
return action.Switch(item)
}
top, err := gitdata.Toplevel()
if err != nil {
return "", err
}
path := ui.ProposeWorktreePath(top, worktreeRoot, item.Branch)
switch defaultAction {
case config.ActionSwitch:
return action.Switch(item)
case config.ActionWorktree:
return action.NewWorktree(path, item.Branch)
default:
fmt.Fprintf(os.Stderr, "'%s' has no worktree. [s]witch here [w]orktree at %s [Esc] cancel: ", item.Branch, path)
switch readAnswer() {
case "s":
return action.Switch(item)
case "w":
return action.NewWorktree(path, item.Branch)
default:
return "", nil
}
}
}

// applyDelete removes each marked branch (and its worktree, if it has one),
// reporting success to stderr on completion. It returns any error(s) action.
// DeleteWorktrees encountered so main exits non-zero, but every item is
Expand Down
52 changes: 52 additions & 0 deletions cmd/wt/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package main

import (
"bufio"
"os"
"testing"
)

func TestSubcommandSkipsLeadingWrapperFlags(t *testing.T) {
for _, tc := range []struct {
args []string
want string
idx int
}{
{[]string{"--path-only", "pr", "123"}, "pr", 1},
{[]string{"pr", "123", "--no-color"}, "pr", 0},
{[]string{"--worktree-root", "/wt", "--path-only", "pr"}, "pr", 3},
{[]string{"--version"}, "", -1},
} {
cmd, idx := subcommand(tc.args)
if cmd != tc.want || idx != tc.idx {
t.Errorf("subcommand(%v) = %q, %d, want %q, %d", tc.args, cmd, idx, tc.want, tc.idx)
}
}
}

func TestReadAnswerConsumesOneLinePerPrompt(t *testing.T) {
old := stdinReader
t.Cleanup(func() { stdinReader = old })

r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
if _, err := w.WriteString("y\ns\n"); err != nil {
t.Fatal(err)
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
stdinReader = bufio.NewReader(r)

if got := readAnswer(); got != "y" {
t.Fatalf("first answer = %q, want y", got)
}
if got := readAnswer(); got != "s" {
t.Fatalf("second answer = %q, want s (a fresh reader would have discarded it)", got)
}
if got := readAnswer(); got != "" {
t.Fatalf("answer after EOF = %q, want empty", got)
}
}
Loading
Loading