diff --git a/README.md b/README.md index 6cf1e1a..18af049 100644 --- a/README.md +++ b/README.md @@ -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/`, it asks `Fast-forward ...? [y/N]`; only yes runs +`git merge --ff-only origin/` 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/`, so +this covers branches pushed to the repository's `origin`, not fork PR heads. + Optional config file at `~/.config/wt/config.toml`: ```toml diff --git a/SPEC.md b/SPEC.md index 2a31401..1a8c4d1 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, 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 @@ -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`. @@ -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 │ │ │ └──────────────────────┘ @@ -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 to +origin/? [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 @@ -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 diff --git a/cmd/wt/main.go b/cmd/wt/main.go index 5e47be6..da0a2ae 100644 --- a/cmd/wt/main.go +++ b/cmd/wt/main.go @@ -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 { @@ -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") @@ -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/ +// 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 diff --git a/cmd/wt/main_test.go b/cmd/wt/main_test.go new file mode 100644 index 0000000..f98799a --- /dev/null +++ b/cmd/wt/main_test.go @@ -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) + } +} diff --git a/integration_test.go b/integration_test.go index 4305fa3..5beac41 100644 --- a/integration_test.go +++ b/integration_test.go @@ -483,6 +483,150 @@ func TestIntegrationForceUpdateWorktreeBranchToRemoteTip(t *testing.T) { } } +// initPRRemote initialises repo with a bare origin and pushes its first +// commit. Names are distinct from other PRs' helpers to keep branches +// independent until they merge. +func initPRRemote(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 +} + +func clonePRRemote(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 +} + +// advancedPRBranch pushes a new commit on branch from a second clone and +// returns the resulting remote tip. +func advancedPRBranch(t *testing.T, remote, branch string) string { + t.Helper() + other := clonePRRemote(t, remote) + runGit(t, other, "checkout", "-b", branch, "origin/"+branch) + runGit(t, other, "commit", "--allow-empty", "-m", "remote commit") + runGit(t, other, "push", "origin", branch) + return strings.TrimSpace(runGit(t, other, "rev-parse", branch)) +} + +func TestIntegrationPreparePRBranchFastForwardsPlainBranch(t *testing.T) { + repo := t.TempDir() + remote := initPRRemote(t, repo) + runGit(t, repo, "branch", "feature/x") + runGit(t, repo, "push", "origin", "feature/x") + want := advancedPRBranch(t, remote, "feature/x") + chdir(t, repo) + + ok, err := action.PreparePRBranch("feature/x", "", func() bool { return true }) + if err != nil || !ok { + t.Fatalf("PreparePRBranch() = %v, %v, want true, nil", ok, err) + } + if got := strings.TrimSpace(runGit(t, repo, "rev-parse", "feature/x")); got != want { + t.Fatalf("feature/x = %s, want remote tip %s", got, want) + } +} + +func TestIntegrationPreparePRBranchDeclinedLeavesBranchAlone(t *testing.T) { + repo := t.TempDir() + remote := initPRRemote(t, repo) + runGit(t, repo, "branch", "feature/x") + runGit(t, repo, "push", "origin", "feature/x") + before := strings.TrimSpace(runGit(t, repo, "rev-parse", "feature/x")) + advancedPRBranch(t, remote, "feature/x") + chdir(t, repo) + + asked := false + ok, err := action.PreparePRBranch("feature/x", "", func() bool { asked = true; return false }) + if err != nil { + t.Fatalf("PreparePRBranch() error = %v", err) + } + if ok || !asked { + t.Fatalf("PreparePRBranch() = %v, asked = %v, want false/true after decline", ok, asked) + } + if got := strings.TrimSpace(runGit(t, repo, "rev-parse", "feature/x")); got != before { + t.Fatalf("feature/x = %s after decline, want unchanged %s", got, before) + } +} + +func TestIntegrationPreparePRBranchRejectsDivergedBranch(t *testing.T) { + repo := t.TempDir() + remote := initPRRemote(t, repo) + runGit(t, repo, "branch", "feature/x") + runGit(t, repo, "push", "origin", "feature/x") + runGit(t, repo, "checkout", "feature/x") + runGit(t, repo, "commit", "--allow-empty", "-m", "local commit") + runGit(t, repo, "checkout", "main") + before := strings.TrimSpace(runGit(t, repo, "rev-parse", "feature/x")) + advancedPRBranch(t, remote, "feature/x") + chdir(t, repo) + + ok, err := action.PreparePRBranch("feature/x", "", func() bool { return true }) + if err == nil || !strings.Contains(err.Error(), "diverged") { + t.Fatalf("PreparePRBranch() error = %v, want diverged error", err) + } + if ok { + t.Fatal("PreparePRBranch() = true for a diverged branch, want false") + } + if got := strings.TrimSpace(runGit(t, repo, "rev-parse", "feature/x")); got != before { + t.Fatalf("feature/x = %s after rejected fast-forward, want unchanged %s", got, before) + } +} + +func TestIntegrationPreparePRBranchCreatesMissingBranch(t *testing.T) { + repo := t.TempDir() + remote := initPRRemote(t, repo) + other := clonePRRemote(t, remote) + runGit(t, other, "checkout", "-b", "feature/new") + runGit(t, other, "commit", "--allow-empty", "-m", "new PR commit") + runGit(t, other, "push", "-u", "origin", "feature/new") + want := strings.TrimSpace(runGit(t, other, "rev-parse", "feature/new")) + chdir(t, repo) + + if branches := runGit(t, repo, "branch", "--list", "feature/new"); strings.TrimSpace(branches) != "" { + t.Fatalf("feature/new already exists locally before prepare: %q", branches) + } + asked := false + ok, err := action.PreparePRBranch("feature/new", "", func() bool { asked = true; return true }) + if err != nil || !ok { + t.Fatalf("PreparePRBranch() = %v, %v, want true, nil", ok, err) + } + if asked { + t.Fatal("creating a missing branch should not ask for a fast-forward") + } + if got := strings.TrimSpace(runGit(t, repo, "rev-parse", "feature/new")); got != want { + t.Fatalf("feature/new = %s, want remote tip %s", got, want) + } +} + +func TestIntegrationPreparePRBranchFastForwardsWorktree(t *testing.T) { + repo := t.TempDir() + remote := initPRRemote(t, repo) + runGit(t, repo, "branch", "feature/x") + runGit(t, repo, "push", "origin", "feature/x") + wtDir := filepath.Join(t.TempDir(), "feature-x-checkout") + runGit(t, repo, "worktree", "add", wtDir, "feature/x") + want := advancedPRBranch(t, remote, "feature/x") + chdir(t, repo) + + ok, err := action.PreparePRBranch("feature/x", wtDir, func() bool { return true }) + if err != nil || !ok { + t.Fatalf("PreparePRBranch() = %v, %v, want true, nil", ok, err) + } + 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") diff --git a/internal/action/action.go b/internal/action/action.go index 2d9ed47..4cbf056 100644 --- a/internal/action/action.go +++ b/internal/action/action.go @@ -4,10 +4,12 @@ package action import ( + "bytes" "errors" "fmt" "os" "os/exec" + "strings" "github.com/AgileIndustrialComplex/wt/internal/gitdata" ) @@ -54,6 +56,83 @@ func newWorktreeWith(run runnerFunc, path, branch string) (string, error) { return path, nil } +type outputRunnerFunc func(args ...string) (string, error) + +func runGitOutput(args ...string) (string, error) { + cmd := exec.Command("git", args...) + cmd.Env = append(os.Environ(), "LC_ALL=C") + var out, errBuf bytes.Buffer + cmd.Stdout = &out + cmd.Stderr = &errBuf + if err := cmd.Run(); err != nil { + msg := strings.TrimSpace(errBuf.String()) + if msg == "" { + msg = err.Error() + } + return "", fmt.Errorf("git %s: %s", strings.Join(args, " "), msg) + } + return out.String(), nil +} + +// PreparePRBranch fetches a PR head branch from origin and makes the local +// branch ready to switch to. A local branch strictly behind origin/ +// is fast-forwarded only when confirm returns true; in that case a false +// return with a nil error means the user declined. A local branch that has +// diverged is rejected — only a fast-forward is allowed here. A missing +// local branch is created from the remote tip without asking. path is the +// branch's worktree, or "" when it has none. +func PreparePRBranch(branch, path string, confirm func() bool) (bool, error) { + return preparePRBranchWith(runGitOutput, branch, path, confirm) +} + +func preparePRBranchWith(run outputRunnerFunc, branch, path string, confirm func() bool) (bool, error) { + if _, err := run("fetch", "origin", branch); err != nil { + return false, fmt.Errorf("fetch origin %s: %w", branch, err) + } + ref := "origin/" + branch + local, err := run("rev-parse", "--verify", "--quiet", "refs/heads/"+branch) + if err != nil { + if _, err := run("branch", branch, ref); err != nil { + return false, fmt.Errorf("create %s from %s: %w", branch, ref, err) + } + return true, nil + } + remote, err := run("rev-parse", "--verify", "--quiet", ref) + if err != nil { + return false, fmt.Errorf("branch %s: no %s: %w", branch, ref, err) + } + if strings.TrimSpace(local) == strings.TrimSpace(remote) { + return true, nil + } + ahead, err := run("rev-list", "--count", ref+".."+branch) + if err != nil { + return false, err + } + behind, err := run("rev-list", "--count", branch+".."+ref) + if err != nil { + return false, err + } + if strings.TrimSpace(ahead) != "0" { + return false, fmt.Errorf("branch %s has diverged from %s; cannot fast-forward", branch, ref) + } + if strings.TrimSpace(behind) == "0" { + return true, nil + } + if !confirm() { + return false, nil + } + if path != "" { + if _, err := run("-C", path, "merge", "--ff-only", ref); err != nil { + return false, fmt.Errorf("fast-forward %s: %w", branch, err) + } + } else { + if _, err := run("branch", "-f", branch, ref); err != nil { + return false, fmt.Errorf("fast-forward %s: %w", branch, err) + } + } + return true, nil +} + // ForceUpdate resets each branch to its upstream tip. It runs a single // `git fetch origin`, then `git reset --hard origin/` for branches // with a worktree and `git branch -f origin/` for plain diff --git a/internal/action/action_test.go b/internal/action/action_test.go index 54e88d2..0828a19 100644 --- a/internal/action/action_test.go +++ b/internal/action/action_test.go @@ -229,6 +229,135 @@ func TestDeleteWorktreesWithContinuesAfterFailureAndCombinesErrors(t *testing.T) } } +func prFakeRunner(responses map[string]string) (outputRunnerFunc, *[][]string) { + var calls [][]string + run := func(args ...string) (string, error) { + calls = append(calls, append([]string{}, args...)) + key := strings.Join(args, " ") + if out, ok := responses[key]; ok { + return out, nil + } + if args[0] == "branch" || args[0] == "-C" { + return "", nil + } + return "", fmt.Errorf("unexpected git call: %v", args) + } + return run, &calls +} + +func prBehindResponses() map[string]string { + return map[string]string{ + "fetch origin feature/x": "", + "rev-parse --verify --quiet refs/heads/feature/x": "aaa", + "rev-parse --verify --quiet origin/feature/x": "bbb", + "rev-list --count origin/feature/x..feature/x": "0", + "rev-list --count feature/x..origin/feature/x": "2", + } +} + +func TestPreparePRBranchFastForwardsPlainBranchAfterConsent(t *testing.T) { + run, calls := prFakeRunner(prBehindResponses()) + confirmed := 0 + + ok, err := preparePRBranchWith(run, "feature/x", "", func() bool { confirmed++; return true }) + if err != nil { + t.Fatalf("preparePRBranchWith() error = %v", err) + } + if !ok { + t.Fatal("preparePRBranchWith() = false, want ready to switch") + } + if confirmed != 1 { + t.Fatalf("confirm called %d times, want 1", confirmed) + } + want := [][]string{ + {"fetch", "origin", "feature/x"}, + {"rev-parse", "--verify", "--quiet", "refs/heads/feature/x"}, + {"rev-parse", "--verify", "--quiet", "origin/feature/x"}, + {"rev-list", "--count", "origin/feature/x..feature/x"}, + {"rev-list", "--count", "feature/x..origin/feature/x"}, + {"branch", "-f", "feature/x", "origin/feature/x"}, + } + if !reflect.DeepEqual(*calls, want) { + t.Fatalf("git calls = %v, want %v", *calls, want) + } +} + +func TestPreparePRBranchFastForwardsWorktreeWithMerge(t *testing.T) { + run, calls := prFakeRunner(prBehindResponses()) + ok, err := preparePRBranchWith(run, "feature/x", "/repo/proj-x", func() bool { return true }) + if err != nil || !ok { + t.Fatalf("preparePRBranchWith() = %v, %v, want true, nil", ok, err) + } + wantLast := []string{"-C", "/repo/proj-x", "merge", "--ff-only", "origin/feature/x"} + if got := (*calls)[len(*calls)-1]; !reflect.DeepEqual(got, wantLast) { + t.Fatalf("last git call = %v, want %v", got, wantLast) + } +} + +func TestPreparePRBranchDeclinedDoesNotMutate(t *testing.T) { + run, calls := prFakeRunner(prBehindResponses()) + ok, err := preparePRBranchWith(run, "feature/x", "", func() bool { return false }) + if err != nil { + t.Fatalf("preparePRBranchWith() error = %v", err) + } + if ok { + t.Fatal("preparePRBranchWith() = true after decline, want false") + } + for _, call := range *calls { + if call[0] == "branch" || call[0] == "merge" || call[0] == "-C" { + t.Fatalf("unexpected mutation after decline: %v", call) + } + } +} + +func TestPreparePRBranchRejectsDivergedBranchWithoutAsking(t *testing.T) { + responses := prBehindResponses() + responses["rev-list --count origin/feature/x..feature/x"] = "1" + run, _ := prFakeRunner(responses) + asked := false + + ok, err := preparePRBranchWith(run, "feature/x", "", func() bool { asked = true; return true }) + if err == nil || !strings.Contains(err.Error(), "diverged") { + t.Fatalf("preparePRBranchWith() error = %v, want diverged error", err) + } + if ok || asked { + t.Fatalf("preparePRBranchWith() = %v, confirm asked = %v, want false/false", ok, asked) + } +} + +func TestPreparePRBranchCreatesMissingBranchFromRemoteTip(t *testing.T) { + responses := prBehindResponses() + delete(responses, "rev-parse --verify --quiet refs/heads/feature/x") + run, calls := prFakeRunner(responses) + asked := false + + ok, err := preparePRBranchWith(run, "feature/x", "", func() bool { asked = true; return true }) + if err != nil || !ok { + t.Fatalf("preparePRBranchWith() = %v, %v, want true, nil", ok, err) + } + if asked { + t.Fatal("missing branch should be created without asking") + } + wantLast := []string{"branch", "feature/x", "origin/feature/x"} + if got := (*calls)[len(*calls)-1]; !reflect.DeepEqual(got, wantLast) { + t.Fatalf("last git call = %v, want %v", got, wantLast) + } +} + +func TestPreparePRBranchUpToDateRunsNoMutation(t *testing.T) { + responses := prBehindResponses() + responses["rev-parse --verify --quiet origin/feature/x"] = "aaa" + run, calls := prFakeRunner(responses) + + ok, err := preparePRBranchWith(run, "feature/x", "", func() bool { return true }) + if err != nil || !ok { + t.Fatalf("preparePRBranchWith() = %v, %v, want true, nil", ok, err) + } + if len(*calls) != 3 { + t.Fatalf("git calls = %v, want only fetch and two rev-parse checks", *calls) + } +} + func TestNewWorktreeWithRunsGitWorktreeAdd(t *testing.T) { run, calls := recordingRunner() path, err := newWorktreeWith(run, "/repo/proj-login", "feature/login") diff --git a/internal/gitdata/gitdata.go b/internal/gitdata/gitdata.go index 0fb5a3b..a3215ae 100644 --- a/internal/gitdata/gitdata.go +++ b/internal/gitdata/gitdata.go @@ -24,8 +24,9 @@ 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) - Dirty bool // true if the worktree has modified or untracked files (git worktree remove would refuse it) + 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) + Display string // optional picker label (e.g. "#123 PR title"); falls back to Branch } // HasWorktree reports whether the branch is checked out anywhere. diff --git a/internal/github/pr.go b/internal/github/pr.go new file mode 100644 index 0000000..8d51294 --- /dev/null +++ b/internal/github/pr.go @@ -0,0 +1,72 @@ +// Package github reads pull requests through the gh CLI. It never +// reimplements GitHub's API or authentication. +package github + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "os/exec" + "strings" +) + +// PR is the minimum information wt needs to switch to a pull request. +type PR struct { + Number int `json:"number"` + Title string `json:"title"` + Branch string `json:"headRefName"` +} + +type runnerFunc func(args ...string) (string, error) + +func runGH(args ...string) (string, error) { + cmd := exec.Command("gh", args...) + cmd.Env = append(os.Environ(), "LC_ALL=C") + var out, errBuf bytes.Buffer + cmd.Stdout = &out + cmd.Stderr = &errBuf + if err := cmd.Run(); err != nil { + msg := strings.TrimSpace(errBuf.String()) + if msg == "" { + msg = err.Error() + } + return "", fmt.Errorf("gh %s: %s", strings.Join(args, " "), msg) + } + return out.String(), nil +} + +// OpenPRs lists the open pull requests of the repository in the current +// directory, newest first as returned by gh. +func OpenPRs() ([]PR, error) { + return openPRsWith(runGH) +} + +func openPRsWith(run runnerFunc) ([]PR, error) { + out, err := run("pr", "list", "--state", "open", "--json", "number,title,headRefName") + if err != nil { + return nil, err + } + var prs []PR + if err := json.Unmarshal([]byte(out), &prs); err != nil { + return nil, fmt.Errorf("parse gh pr list output: %w", err) + } + return prs, nil +} + +// Get returns the pull request identified by a number or URL. +func Get(number string) (PR, error) { + return getWith(runGH, number) +} + +func getWith(run runnerFunc, number string) (PR, error) { + out, err := run("pr", "view", number, "--json", "number,title,headRefName") + if err != nil { + return PR{}, err + } + var pr PR + if err := json.Unmarshal([]byte(out), &pr); err != nil { + return PR{}, fmt.Errorf("parse gh pr view output: %w", err) + } + return pr, nil +} diff --git a/internal/github/pr_test.go b/internal/github/pr_test.go new file mode 100644 index 0000000..e3d6a7c --- /dev/null +++ b/internal/github/pr_test.go @@ -0,0 +1,67 @@ +package github + +import ( + "fmt" + "reflect" + "strings" + "testing" +) + +func TestOpenPRsWithParsesGHListOutput(t *testing.T) { + var gotArgs []string + run := func(args ...string) (string, error) { + gotArgs = append([]string{}, args...) + return `[{"number":17,"title":"Add F key","headRefName":"feature/force-update"},{"number":18,"title":"PR work","headRefName":"feature/pr"}]`, nil + } + + prs, err := openPRsWith(run) + if err != nil { + t.Fatalf("openPRsWith() error = %v", err) + } + want := []PR{ + {Number: 17, Title: "Add F key", Branch: "feature/force-update"}, + {Number: 18, Title: "PR work", Branch: "feature/pr"}, + } + if !reflect.DeepEqual(prs, want) { + t.Fatalf("openPRsWith() = %+v, want %+v", prs, want) + } + wantArgs := []string{"pr", "list", "--state", "open", "--json", "number,title,headRefName"} + if !reflect.DeepEqual(gotArgs, wantArgs) { + t.Fatalf("gh args = %v, want %v", gotArgs, wantArgs) + } +} + +func TestGetWithParsesGHViewOutput(t *testing.T) { + var gotArgs []string + run := func(args ...string) (string, error) { + gotArgs = append([]string{}, args...) + return `{"number":123,"title":"Fix thing","headRefName":"fix/thing"}`, nil + } + + pr, err := getWith(run, "123") + if err != nil { + t.Fatalf("getWith() error = %v", err) + } + want := PR{Number: 123, Title: "Fix thing", Branch: "fix/thing"} + if pr != want { + t.Fatalf("getWith() = %+v, want %+v", pr, want) + } + wantArgs := []string{"pr", "view", "123", "--json", "number,title,headRefName"} + if !reflect.DeepEqual(gotArgs, wantArgs) { + t.Fatalf("gh args = %v, want %v", gotArgs, wantArgs) + } +} + +func TestOpenPRsWithPropagatesGHError(t *testing.T) { + run := func(args ...string) (string, error) { return "", fmt.Errorf("not logged in") } + if _, err := openPRsWith(run); err == nil || !strings.Contains(err.Error(), "not logged in") { + t.Fatalf("openPRsWith() error = %v, want gh error propagated", err) + } +} + +func TestGetWithReportsBadJSON(t *testing.T) { + run := func(args ...string) (string, error) { return "not json", nil } + if _, err := getWith(run, "1"); err == nil || !strings.Contains(err.Error(), "parse") { + t.Fatalf("getWith() error = %v, want parse error", err) + } +} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 544b047..ccb8790 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -60,6 +60,7 @@ type Model struct { defaultAction string keymap string height int + prMode bool // PR picker: rows show PR labels and mark/delete/force keys are disabled forceConfirmInput string // typed phrase in modeConfirmForceDelete forceTargets []gitdata.Item // branches F will force-update, marked set or highlighted item @@ -76,6 +77,14 @@ func New(items []gitdata.Item, toplevel string, worktreeRoot string, noColor boo return NewConfigured(items, toplevel, worktreeRoot, noColor, config.ActionPrompt, config.KeymapVim) } +// NewPR builds a picker for PR branches. Rows are labelled with the PR +// number and title, and the mark/delete/force-update keys are disabled. +func NewPR(items []gitdata.Item, toplevel string, worktreeRoot string, noColor bool, defaultAction, keymap string) Model { + m := NewConfigured(items, toplevel, worktreeRoot, noColor, defaultAction, keymap) + m.prMode = true + return m +} + func NewConfigured(items []gitdata.Item, toplevel string, worktreeRoot string, noColor bool, defaultAction, keymap string) Model { m := Model{ items: items, @@ -387,19 +396,23 @@ func (m Model) updateList(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return m, nil case msg.String() == "c": - m.toggleMarked() + if !m.prMode { + m.toggleMarked() + } return m, nil case msg.String() == "D": - if len(m.marked) > 0 { + if !m.prMode && len(m.marked) > 0 { m.mode = modeConfirmDelete } return m, nil case msg.String() == "F": - m.forceTargets = m.forceUpdateTargets() - if len(m.forceTargets) > 0 { - m.mode = modeConfirmForceUpdate + if !m.prMode { + m.forceTargets = m.forceUpdateTargets() + if len(m.forceTargets) > 0 { + m.mode = modeConfirmForceUpdate + } } return m, nil @@ -450,7 +463,7 @@ func (m *Model) movePage(delta int) { func (m *Model) applyFilter() { m.filtered = m.filtered[:0] for i, item := range m.items { - if m.filter == "" || strings.Contains(strings.ToLower(item.Branch), strings.ToLower(m.filter)) { + if m.filter == "" || strings.Contains(strings.ToLower(itemLabel(item)), strings.ToLower(m.filter)) { m.filtered = append(m.filtered, i) } } @@ -495,19 +508,32 @@ func (m Model) Marked() []gitdata.Item { return result } -// proposeWorktreePath suggests a sibling directory for a new worktree, named +func (m Model) proposeWorktreePath(branch string) string { + return ProposeWorktreePath(m.toplevel, m.worktreeRoot, branch) +} + +// itemLabel is the text shown in the picker. PR rows carry a label with the +// PR number and title; ordinary rows show their branch name. +func itemLabel(item gitdata.Item) string { + if item.Display != "" { + return item.Display + } + return item.Branch +} + +// ProposeWorktreePath suggests a sibling directory for a new worktree, named // after the repository directory plus the branch's last path segment, e.g. // branch "feature/login" next to "~/proj" proposes "~/proj-login". -func (m Model) proposeWorktreePath(branch string) string { +func ProposeWorktreePath(toplevel, worktreeRoot, branch string) string { segment := branch if i := strings.LastIndex(branch, "/"); i >= 0 { segment = branch[i+1:] } - if m.worktreeRoot != "" { - return filepath.Join(m.worktreeRoot, filepath.Base(m.toplevel)+"-"+segment) + if worktreeRoot != "" { + return filepath.Join(worktreeRoot, filepath.Base(toplevel)+"-"+segment) } - parent := filepath.Dir(m.toplevel) - return filepath.Join(parent, filepath.Base(m.toplevel)+"-"+segment) + parent := filepath.Dir(toplevel) + return filepath.Join(parent, filepath.Base(toplevel)+"-"+segment) } func isCancel(msg tea.KeyMsg) bool { @@ -677,9 +703,10 @@ func (m Model) View() string { marker = markedStyle.Render(marker) } } - line := fmt.Sprintf("%s %s %-28s", cursor, mark, item.Branch) + label := itemLabel(item) + line := fmt.Sprintf("%s %s %-28s", cursor, mark, label) if len(m.marked) > 0 { - line = fmt.Sprintf("%s %s %s %-28s", cursor, marker, mark, item.Branch) + line = fmt.Sprintf("%s %s %s %-28s", cursor, marker, mark, label) } if item.HasWorktree() { tag := "[worktree]" @@ -750,22 +777,29 @@ func (m Model) visibleRange() (int, int) { func (m Model) helpView() string { navigation := m.navigationHint() - return strings.Join([]string{ + lines := []string{ "Key bindings:", " navigation : " + navigation, " page down : Ctrl-D", " page up : Ctrl-U", " top/bottom : g / G", " filter : / (Esc clears)", - " mark : c (selection)", - " delete : D (marked branches, asks to confirm; unmerged branches, dirty worktrees, or locked worktrees require typing a phrase)", - " force update: F (highlighted or marked branches, asks to confirm; resets each to origin/)", + } + if !m.prMode { + lines = append(lines, + " mark : c (selection)", + " delete : D (marked branches, asks to confirm; unmerged branches, dirty worktrees, or locked worktrees require typing a phrase)", + " force update: F (highlighted or marked branches, asks to confirm; resets each to origin/)", + ) + } + lines = append(lines, " confirm : Enter", " cancel : Esc, Ctrl-C, q", " help : ?", "", "press any key to return", - }, "\n") + ) + return strings.Join(lines, "\n") } func (m Model) navigationHint() string { diff --git a/internal/ui/ui_test.go b/internal/ui/ui_test.go index 1b26872..17bcee2 100644 --- a/internal/ui/ui_test.go +++ b/internal/ui/ui_test.go @@ -704,6 +704,55 @@ func TestSelectedStyleResumesAfterNestedStyleReset(t *testing.T) { } } +func prItems() []gitdata.Item { + return []gitdata.Item{ + {Branch: "feature/force-update", Display: "#17 Add F key (feature/force-update)"}, + {Branch: "feature/pr", Display: "#18 PR support (feature/pr)"}, + } +} + +func TestPRPickerShowsNumberAndTitle(t *testing.T) { + m := NewPR(prItems(), "/repo/proj", "", true, config.ActionPrompt, config.KeymapVim) + view := m.View() + if !strings.Contains(view, "#17 Add F key") || !strings.Contains(view, "#18 PR support") { + t.Fatalf("PR picker view missing labels:\n%s", view) + } + if !strings.Contains(view, "feature/force-update") { + t.Fatalf("PR picker view missing branch name:\n%s", view) + } +} + +func TestPRPickerFiltersOnTitle(t *testing.T) { + m := NewPR(prItems(), "/repo/proj", "", true, config.ActionPrompt, config.KeymapVim) + m = send(t, m, key('/'), key('p'), key('r'), key(' '), keyType(tea.KeyEnter)) + if len(m.filtered) != 1 || m.items[m.filtered[0]].Branch != "feature/pr" { + t.Fatalf("filter on PR title -> %v, want only feature/pr", m.filtered) + } +} + +func TestPRPickerDisablesMarkDeleteAndForceKeys(t *testing.T) { + m := NewPR(prItems(), "/repo/proj", "", true, config.ActionPrompt, config.KeymapVim) + m = send(t, m, key('c'), key('D'), key('F')) + if len(m.Marked()) != 0 { + t.Fatalf("Marked() in PR picker = %+v, want none", m.Marked()) + } + if m.mode != modeList || m.quitting { + t.Fatalf("mode = %v, quitting = %v after c/D/F in PR picker, want list/not quitting", m.mode, m.quitting) + } +} + +func TestPRPickerHelpHidesMarkKeys(t *testing.T) { + m := NewPR(prItems(), "/repo/proj", "", true, config.ActionPrompt, config.KeymapVim) + m = send(t, m, key('?')) + view := m.View() + if strings.Contains(view, "mark :") || strings.Contains(view, "delete :") || strings.Contains(view, "force update:") { + t.Fatalf("PR help still shows mark/delete/force keys:\n%s", view) + } + if !strings.Contains(view, "filter") || !strings.Contains(view, "confirm") { + t.Fatalf("PR help missing navigation hints:\n%s", view) + } +} + func TestFKeyWithNoMarksTargetsHighlightedItem(t *testing.T) { m := New(testItems(), "/repo/proj", "", true) m = send(t, m, key('j'), key('F'))