diff --git a/PLAN.md b/PLAN.md new file mode 100644 index 0000000..00b0426 --- /dev/null +++ b/PLAN.md @@ -0,0 +1,117 @@ +# GitLab source (mrolafsson/herdr-github#6) + +Builds on the forge-agnostic refactor (#5): a `gitlabForge` descriptor and a +`gitlabSource` behind the `source` interface, over GitLab REST v4, stdlib +only. GitHub stays the default and its behavior is unchanged. + +## Switch + +Runtime, from config: `"forge": "gitlab"` in config.json (default `github`). +`run` calls `useForge` before anything talks to a forge, which sets +`theForge` and the `tokenFn` seam. The demo always runs on `githubForge` (it +impersonates GitHub). The descriptor gains what the TUI and the label hooks +build per forge: `newSource`, `prsForBranches`, `prsByNumber`, `viewer` (for +`status`), `startPrompt` (the default prompt names the CLI), and +`nestedPaths` (GitLab namespaces nest: `group/sub/project`). + +Call sites that hard-coded GitHub now go through the descriptor: +`newGitHubSource` in tui.go/repopicker.go, `newClient(...).prsForBranches` in +labels.go, `.prsByNumber` in agents.go, the `status` command. A few +user-facing strings that said "GitHub" use `theForge.name` (same text on +GitHub). + +## Shared, extracted (no behavior change for GitHub) + +- `fanOut`: the Mine/Review multi-host cursor (JSON host → cursor) and the + signed-out/partial handling, out of `githubSource.list`. +- `pageHosts`: the repo picker's ":" paging, out of + `githubSource.repos`. +- `pr.repo()` cuts at the last `/` (identical for `owner/name`), and + `parseRepoKey`/`parseRemote` accept nested owners when the forge says so. + +## Auth and transport (gitlab.go) + +- Token: `GITLAB_TOKEN`, `GITLAB_ACCESS_TOKEN`, `OAUTH_TOKEN` (when + `GITLAB_HOST` is unset or names this host), then + `glab config get token --host `. `glab auth token` does not exist + (gitlab-org/cli#8231, closed won't-do); `config get token` reads the + keyring or config file and prints just the value. +- Header `Authorization: Bearer `: GitLab accepts PATs and OAuth + tokens (what `glab auth login --web` stores) both that way. +- Base `https:///api/v4` (seam `glEndpointFn`). Project ids are the + URL-encoded path (`group%2Fsub%2Fproj`). +- 401 → `signedOutError`; other non-2xx → `GitLab: HTTP n: `. + Every decoded value goes through `sanitize`; `description` and note + `body` decode into fields named `Body`, so they keep their line breaks. +- Pages: `page`/`per_page`, next from `X-Next-Page`; the cursor is that page + number. + +## Mapping (GitLab JSON → shared structs) + +| pullRequest / prDetail | GitLab | +|---|---| +| ID | global `id` (unused by the GitLab source) | +| Number | `iid` | +| Title, URL, UpdatedAt | `title`, `web_url`, `updated_at` | +| IsDraft | `draft` | +| State | `opened`→OPEN, `merged`→MERGED, `closed`/`locked`→CLOSED | +| Author.Login | `author.username` | +| Repository.NameWithOwner | path from `web_url` before `/-/` | +| HeadRefName, BaseRefName, HeadRefOid | `source_branch`, `target_branch`, `sha` | +| IsCrossRepository | `source_project_id != target_project_id` | +| HeadRepository, HeadRepositoryOwner | source project's `path_with_namespace` (GET /projects/:id, cached); owner = its namespace | +| Mergeable | `conflict` or `has_conflicts`→CONFLICTING, `mergeable`→MERGEABLE, else UNKNOWN | +| MergeStateStatus | `mergeable`→CLEAN, `need_rebase`→BEHIND, `conflict`→DIRTY, `draft_status`→DRAFT, checking/unchecked/preparing/approvals_syncing→UNKNOWN, any other check→BLOCKED | +| ReviewDecision | `requested_changes`→CHANGES_REQUESTED, `not_approved`→REVIEW_REQUIRED; detail: approvals `approved` with approvers→APPROVED | +| Commits rollup | `head_pipeline.status` (single MR only): success→SUCCESS, failed/canceled→FAILURE, running/pending/created/…→PENDING | +| Labels | `labels` with `with_labels_details=true`, `#` stripped from color | +| AutoMergeRequest | set when `merge_when_pipeline_succeeds`; method SQUASH when `squash` | +| Body | `description` | +| ChangedFiles, Additions, Deletions | `changes_count`; +/− counted from `/diffs` (first 300 files) | +| MaintainerCanModify | `allow_collaboration` | +| HeadRef | the source branch (deleted via DELETE /repository/branches/:branch) | +| Checks | jobs of `head_pipeline` (GET /projects/:pid/pipelines/:id/jobs): required = `!allow_failure` | +| Reviewers | /reviewers (`approved`, `requested_changes`, `unreviewed`→PENDING, else COMMENTED) + /approvals `approved_by` | +| Comments, Threads | /discussions: individual non-system notes; resolvable diff discussions with `position.new_path/new_line` | +| RepoSettings | project `squash_option`: never→MERGE, always→SQUASH, else both (default_on prefers SQUASH); `DeleteBranchOnMerge` = `force_remove_source_branch` or `should_remove_source_branch`; auto-merge allowed | +| ViewerCanMerge | `user.can_merge` | + +## Endpoints + +- Mine: `GET /merge_requests?scope=created_by_me&state=opened&order_by=updated_at&non_archived=true` +- Repo: `GET /projects/:id/merge_requests?state=opened&order_by=updated_at` +- Review: none (`caps.reviewRequested=false`; the tab is hidden). +- Detail: single MR + project + approvals + reviewers + discussions + jobs + diffs. +- Draft: re-read the title, then `PUT /projects/:id/merge_requests/:iid` with `title` prefixed `Draft: ` or stripped of GitLab's draft prefixes. +- Merge: `PUT …/merge` with `sha` (pinned head), `squash`, and for auto `auto_merge` and `merge_when_pipeline_succeeds` (pre-17.11). +- Auto-merge off: `POST …/cancel_auto_merge`, falling back to `cancel_merge_when_pipeline_succeeds` on 404 (pre-19.5). +- Labels: per branch `GET /projects/:id/merge_requests?source_branch=…&state=all&order_by=updated_at`, then the picked MR in full (for its pipeline). +- Agents: per number `GET /projects/:id/merge_requests/:iid` (404 = gone). +- Repos: `GET /projects?membership=true&simple=true&archived=false&order_by=last_activity_at`. +- status: `GET /user`. + +## Descriptor + +`name` GitLab, `defaultHost` gitlab.com, `prFromPath` parses +`///-/merge_requests/N`, `prHeadRef` +`refs/merge-requests/N/head`, clone `glab repo clone` with `GITLAB_HOST`, +login `glab auth login --hostname H --web`, methods MERGE "Merge" / SQUASH +"Squash and merge". + +## Tests (gitlab_test.go) + +Fake GitLab server (httptest) behind `glEndpointFn`/`tokenFn`: list paging by +`X-Next-Page`, MR→pullRequest mapping (state, draft, fork, labels, nested +path), detail mapping (checks, reviewers, threads, settings), merge pinning +(`sha`, `squash`, `auto_merge`), draft toggle title rewrite, cancel fallback, +401 → signed out, prFromPath, prHeadRef, caps (Review tab hidden through the +real TUI), config switch. + +## Steps + +1. Plan. +2. Descriptor seams + shared extraction (GitHub unchanged; suite green). +3. gitlab.go client + source + descriptor. +4. Config switch. +5. Tests. +6. Full checks, deslop, no-comments, push. diff --git a/README.md b/README.md index 8808696..51c9252 100644 --- a/README.md +++ b/README.md @@ -510,6 +510,7 @@ Everything is optional. Put `config.json` in the plugin's config directory | key | default | what it does | |-------------------------|------------------|--------------| +| `forge` | `github` | `gitlab` serves GitLab merge requests instead (see [GitLab](#gitlab)). | | `hosts` | `["github.com"]` | Hosts the Mine and Review tabs search, e.g. add your GitHub Enterprise host. Sign in to each with `gh auth login --hostname …`. | | `repos` | none | `"owner/repo"` (or `"host/owner/repo"`) → checkout, for one the plugin can't find by its remotes (an SSH host alias, say). | | `clone_root` | `~/code` | Where a repo with no checkout is cloned, as `//`, after asking. | @@ -522,6 +523,20 @@ Everything is optional. Put `config.json` in the plugin's config directory A copy is in [`config.example.json`](config.example.json). +### GitLab + +With `"forge": "gitlab"` the plugin lists GitLab merge requests (gitlab.com, +or self-managed hosts under `hosts`), through GitLab's REST API. It signs in +the way `glab` does: `GITLAB_TOKEN` (or `GITLAB_ACCESS_TOKEN`, `OAUTH_TOKEN`), +else the token `glab auth login` stored. Differences from GitHub: + +- No Review tab: GitLab has no list of the merge requests waiting on your + review. +- Merge methods are merge and squash, as the project's squash setting + allows; a draft is a `Draft:` title prefix, which `d` adds or removes. +- Checks are the head pipeline's jobs; one allowed to fail isn't required. +- The demo stays on GitHub. + ### Colours Colours follow herdr's own `[theme]` (how it's read is described in diff --git a/agents.go b/agents.go index 7a8ebef..812a714 100644 --- a/agents.go +++ b/agents.go @@ -201,22 +201,18 @@ func parseLine(cfg config, line []byte) (note, bool) { return n, n.number > 0 } -// prFromURL is the PR at https://host/owner/repo/pull/number, when that's a -// host of ours and the number is the one given. Number 0: it isn't. +// prFromURL is the PR the forge knows at that URL, when the host is one of +// ours and the number is the one given. Number 0: it isn't. func prFromURL(cfg config, raw string, number int) (repoRef, int) { u, err := url.Parse(raw) if err != nil || u.Scheme != "https" || !cfg.knownHost(u.Hostname()) || number <= 0 { return repoRef{}, 0 } - parts := strings.Split(strings.Trim(u.Path, "/"), "/") - if len(parts) != 4 || parts[2] != "pull" || parts[3] != strconv.Itoa(number) { - return repoRef{}, 0 - } - r := repoRef{Host: strings.ToLower(u.Hostname()), Owner: parts[0], Name: parts[1]} - if !r.valid() { + r, n, ok := theForge.prFromPath(u.Hostname(), u.Path, number) + if !ok { return repoRef{}, 0 } - return r, number + return r, n } // lineCwd is the working directory a transcript line was written in. @@ -390,7 +386,7 @@ func (st *labelState) note(cfg config, t transcript, line []byte) { // numberLookupFn is GitHub, a seam for tests. var numberLookupFn = func(ctx context.Context, r repoRef, numbers []int) (map[int]prStatus, error) { - return newClient(r.Host).prsByNumber(ctx, r, numbers) + return theForge.api(r.Host).prsByNumber(ctx, r, numbers) } // refreshTracked asks GitHub how the tracked PRs are doing, a repo at a diff --git a/caps_test.go b/caps_test.go new file mode 100644 index 0000000..c9bb1ae --- /dev/null +++ b/caps_test.go @@ -0,0 +1,66 @@ +package main + +import ( + "strings" + "testing" +) + +// cappedDemo is the demo with a source that lacks a forge's capabilities: +// the TUI must hide the Review tab and the merge key without the rest +// breaking. +type cappedDemo struct { + *demoSource + c caps +} + +func (c cappedDemo) caps() caps { return c.c } + +func cappedModel(t *testing.T, c caps) model { + t.Helper() + d := cappedDemo{newDemoSource(), c} + home := d.homeRepo() + m := newModel(nil, withDefaults(config{}), d, "", &home) + m.width, m.height = 110, 34 + return m +} + +func TestNoReviewRequestedHidesTheTab(t *testing.T) { + m := cappedModel(t, caps{autoMerge: true}) + _, cells := m.tabBar() + for _, c := range cells { + if c.tab == tabReview { + t.Fatalf("the Review tab shows: %s", plain(m)) + } + } + // Tab cycling skips it rather than landing on an empty tab. + if next := m.cycleTab(1); next == tabReview { + t.Fatal("cycling landed on the hidden tab") + } + full := cappedModel(t, caps{reviewRequested: true, autoMerge: true}) + _, cells = full.tabBar() + if len(cells) != 3 { + t.Fatalf("a forge with everything keeps three tabs: %v", cells) + } +} + +func TestNoAutoMergeHidesTheKey(t *testing.T) { + m := cappedModel(t, caps{reviewRequested: true}) + pr := pullRequest{Number: 1, State: "OPEN"} + m.cur = &pr + if hs := m.detailFooter(); strings.Contains(hintsText(hs), "merge") { + t.Fatalf("the footer offers a merge key: %v", hs) + } + full := cappedModel(t, caps{reviewRequested: true, autoMerge: true}) + full.cur = &pr + if hs := full.detailFooter(); !strings.Contains(hintsText(hs), "merge") { + t.Fatalf("a forge with auto-merge keeps the key: %v", hs) + } +} + +func hintsText(hs []hint) string { + var b strings.Builder + for _, h := range hs { + b.WriteString(h.label + " ") + } + return b.String() +} diff --git a/config.go b/config.go index cbe2739..1985775 100644 --- a/config.go +++ b/config.go @@ -5,10 +5,14 @@ import ( "errors" "os" "path/filepath" + "strconv" "strings" ) type config struct { + // Forge is the service the plugin serves: "github" (the default) or + // "gitlab". + Forge string `json:"forge"` // Hosts are the GitHub hosts whose pull requests the Mine and Review // tabs list: github.com, and any GitHub Enterprise host gh is signed in to. Hosts []string `json:"hosts"` @@ -90,12 +94,16 @@ func readConfig() (config, error) { return cfg, errors.New("config.json: " + err.Error()) } } + if _, ok := forgeNamed(cfg.Forge); !ok { + return config{}, errors.New(`config.json: "forge" is "github" or "gitlab", not ` + strconv.Quote(cfg.Forge)) + } return cfg, nil } func withDefaults(cfg config) config { + f := cfg.forge() if len(cfg.Hosts) == 0 { - cfg.Hosts = []string{"github.com"} + cfg.Hosts = []string{f.defaultHost} } for i, h := range cfg.Hosts { cfg.Hosts[i] = strings.ToLower(strings.TrimSpace(h)) @@ -105,7 +113,7 @@ func withDefaults(cfg config) config { } cfg.CloneRoot = expandHome(cfg.CloneRoot) if cfg.StartPrompt == "" { - cfg.StartPrompt = "Pull request {url} is checked out here. Read it with `gh pr view {number} --comments`, look at any failing checks, and tell me what's left to do." + cfg.StartPrompt = f.startPrompt } if cfg.AgentWaitSeconds <= 0 { cfg.AgentWaitSeconds = 90 @@ -121,6 +129,15 @@ func withDefaults(cfg config) config { return cfg } +// forge is the forge the config names, GitHub when it names none it knows. +func (c config) forge() forge { + f, ok := forgeNamed(c.Forge) + if !ok { + return githubForge + } + return f +} + // knownHost says whether h is one of the configured GitHub hosts. func (c config) knownHost(h string) bool { for _, x := range c.Hosts { diff --git a/demo.go b/demo.go index 127c5b4..96c25bb 100644 --- a/demo.go +++ b/demo.go @@ -378,7 +378,7 @@ func (d *demoSource) worktree(pr pullRequest, start bool) demoDoneMsg { verb = "open the worktree on " + branch } if pr.IsCrossRepository { - verb += fmt.Sprintf(" (fetched from refs/pull/%d/head)", pr.Number) + verb += fmt.Sprintf(" (fetched from %s)", theForge.prHeadRef(pr.Number)) } note := "Demo: would " + verb if start && !d.trees[pr.key()] { @@ -387,3 +387,5 @@ func (d *demoSource) worktree(pr pullRequest, start bool) demoDoneMsg { d.trees[pr.key()] = true return demoDoneMsg{note: strings.TrimSpace(note), key: pr.key()} } + +func (d *demoSource) caps() caps { return caps{reviewRequested: true, autoMerge: true} } diff --git a/detail.go b/detail.go index fae95c6..685f0e1 100644 --- a/detail.go +++ b/detail.go @@ -154,6 +154,9 @@ func (m model) handleDetailKey(k tea.KeyMsg) (tea.Model, tea.Cmd) { case "d": return m.toggleDraft() case "m": + if !m.client.caps().autoMerge { + return m, nil + } return m.mergeMenu() case "ctrl+r": m.err, m.flash = "", "" @@ -193,8 +196,9 @@ func (m model) toggleDraft() (tea.Model, tea.Cmd) { // ── merging ─────────────────────────────────────────────────────────────────── -var methodNames = map[string]string{"MERGE": "Create a merge commit", "SQUASH": "Squash and merge", "REBASE": "Rebase and merge"} -var methodVerbs = map[string]string{"MERGE": "Merge", "SQUASH": "Squash-merge", "REBASE": "Rebase-merge"} +// The merge methods' names and verbs are the forge's vocabulary. +func methodNames() map[string]string { return theForge.methodNames } +func methodVerbs() map[string]string { return theForge.methodVerbs } // mergeableNow says whether GitHub would merge it right now. func mergeableNow(d *prDetail) bool { @@ -243,7 +247,7 @@ func readiness(d *prDetail) (text string, style lipgloss.Style) { s = "Blocked by the branch's rules" } default: - s, style = "GitHub is still working out whether it can merge (ctrl+r)", styleDim + s, style = theForge.name+" is still working out whether it can merge (ctrl+r)", styleDim } if !d.ViewerCanMerge { s += " · you can't merge in this repo" @@ -308,11 +312,11 @@ func (m model) mergeMenu() (tea.Model, tea.Cmd) { for _, meth := range methods { meth := meth if now { - mn.items = append(mn.items, menuItem{label: methodNames[meth], run: func(m model) (tea.Model, tea.Cmd) { + mn.items = append(mn.items, menuItem{label: methodNames()[meth], run: func(m model) (tea.Model, tea.Cmd) { return m.openMenu(confirmMerge(d, meth, false)), nil }}) } else if d.RepoSettings.AutoMergeAllowed && d.AutoMergeRequest == nil && d.Mergeable != "CONFLICTING" { - mn.items = append(mn.items, menuItem{label: "Auto-merge when ready: " + strings.ToLower(methodNames[meth]), run: func(m model) (tea.Model, tea.Cmd) { + mn.items = append(mn.items, menuItem{label: "Auto-merge when ready: " + strings.ToLower(methodNames()[meth]), run: func(m model) (tea.Model, tea.Cmd) { return m.openMenu(confirmMerge(d, meth, true)), nil }}) } @@ -347,10 +351,10 @@ func orderMethods(methods []string, preferred string) []string { // confirmMerge asks once more, naming exactly what's about to happen. func confirmMerge(d *prDetail, method string, auto bool) *menu { - title := fmt.Sprintf("%s #%d into %s now?", methodVerbs[method], d.Number, d.BaseRefName) - yes := methodVerbs[method] + " it" + title := fmt.Sprintf("%s #%d into %s now?", methodVerbs()[method], d.Number, d.BaseRefName) + yes := methodVerbs()[method] + " it" if auto { - title = fmt.Sprintf("Turn on auto-merge (%s) for #%d? It merges once checks and reviews allow.", strings.ToLower(methodNames[method]), d.Number) + title = fmt.Sprintf("Turn on auto-merge (%s) for #%d? It merges once checks and reviews allow.", strings.ToLower(methodNames()[method]), d.Number) yes = "Turn on auto-merge" } return &menu{title: title, cursor: 1, noDigits: true, items: []menuItem{ @@ -432,7 +436,7 @@ func (m model) cleanupMenu(d *prDetail) *menu { mn.items = append(mn.items, run("Delete the branch and remove the worktree", true, true)) } if canDelete { - mn.items = append(mn.items, run("Delete the branch "+d.HeadRefName+" on GitHub", true, false)) + mn.items = append(mn.items, run("Delete the branch "+d.HeadRefName+" on "+theForge.name, true, false)) } if hasTree { mn.items = append(mn.items, run("Remove the worktree (and close its space)", false, true)) @@ -451,7 +455,7 @@ func (m *model) openURL(u string) { return } if !m.isGitHubURL(u) { - m.err = "Not opening " + u + ": not a link to your GitHub" + m.err = "Not opening " + u + ": not a link to your " + theForge.name return } // A browser here wouldn't be in front of you (over SSH), or there's none @@ -773,7 +777,9 @@ func (m model) detailFooter() []hint { } else { hs = append(hs, hint{"d draft", "d", hintAct}) } - hs = append(hs, hint{"m merge", "m", hintAct}) + if m.client.caps().autoMerge { + hs = append(hs, hint{"m merge", "m", hintAct}) + } } hs = append(hs, hint{"o open", "o", hintView}, hint{"y copy url", "y", hintView}) if m.direct { diff --git a/forge.go b/forge.go new file mode 100644 index 0000000..7a0fe82 --- /dev/null +++ b/forge.go @@ -0,0 +1,136 @@ +package main + +import ( + "context" + "fmt" + "os" + "os/exec" + "strings" +) + +// A forge is a code-hosting service: GitHub or GitLab. Its client +// (github.go, gitlab.go) speaks the service's API; the forge holds what the +// rest of the plugin needs to know about it: how to authenticate, how a PR's +// URL and fork refs are spelled, how clones and sign-ins happen, and what +// its merge methods are called. A process runs as one forge, chosen by the +// config's "forge"; `theForge` is it. + +type forge struct { + // name is the service's name, as errors and notices spell it ("GitHub"). + name string + // defaultHost is the host shown without spelling: a repo on another + // host of the same forge says "ghe.example.com/o/r" instead of "o/r". + defaultHost string + // token finds the auth token for a host: the service's CLI, say. + token func(ctx context.Context, host string) (string, error) + // prFromPath is the repo and PR number a URL's host and path point at, + // when they're one of this forge's PRs ("/owner/repo/pull/N"). + prFromPath func(host, path string, number int) (repoRef, int, bool) + // prHeadRef is the ref a fork's PR head lives at in the base repo + // ("refs/pull/N/head"). + prHeadRef func(number int) string + // cloneCmd is the command that clones r into dest, authenticating the + // way this forge does. + cloneCmd func(ctx context.Context, host string, r repoRef, dest string) *exec.Cmd + // loginCmd is the command that signs you in to host, in the popup. + loginCmd func(host string) *exec.Cmd + // loginText is that command as it's said on the signed-out screen and + // prefixed to a sign-in error ("gh auth login"): what you'd run yourself. + loginText string + // cliName is the CLI itself, as the signed-out screen names it ("gh"). + cliName string + // methodNames and methodVerbs spell this forge's merge methods: what + // its API calls them (the keys) and what each is called and said to do. + methodNames map[string]string + methodVerbs map[string]string + // startPrompt is the default first prompt for a new worktree's agent. + startPrompt string + // nestedPaths: a repo's owner can itself have slashes in it (GitLab's + // groups and subgroups: "group/sub/project"). + nestedPaths bool + // newSource is the picker's source of pull requests for this forge. + newSource func(cfg config, repo *repoRef) source + // api is what the label hooks and `status` ask a host, outside the picker. + api func(host string) forgeAPI +} + +// forgeAPI is a host's answers to the label hooks and `status`. +type forgeAPI interface { + prsForBranches(ctx context.Context, r repoRef, heads []branchHead) (map[branchHead]prStatus, error) + prsByNumber(ctx context.Context, r repoRef, numbers []int) (map[int]prStatus, error) + // viewer is the login the host's token belongs to. + viewer(ctx context.Context) (string, error) +} + +// forges are the forges a config can choose, by its "forge" setting. +var forges = map[string]forge{"github": githubForge, "gitlab": gitlabForge} + +// forgeNamed is the forge a config names; "" is GitHub. +func forgeNamed(name string) (forge, bool) { + if name == "" { + return githubForge, true + } + f, ok := forges[strings.ToLower(name)] + return f, ok +} + +// useForge makes f the forge this process serves. +func useForge(f forge) { + theForge, tokenFn = f, f.token +} + +// splitRepoPath reads "owner/name", or with nested paths "group/sub/name". +func splitRepoPath(path string, nested bool) (owner, name string, ok bool) { + i := strings.LastIndex(path, "/") + if i < 0 { + return "", "", false + } + owner, name = path[:i], path[i+1:] + if owner == "" || name == "" || (!nested && strings.Contains(owner, "/")) { + return "", "", false + } + return owner, name, true +} + +// theForge is the forge this process serves (useForge). The demo always +// runs on GitHub's, which it impersonates. +var theForge = githubForge + +// isDefaultHost says whether host is the forge's default host, and so needn't +// be spelled out next to a repo's name. +func (f forge) isDefaultHost(host string) bool { + return strings.EqualFold(host, f.defaultHost) +} + +var githubForge = forge{ + name: "GitHub", + defaultHost: "github.com", + token: ghToken, + prFromPath: func(host, path string, number int) (repoRef, int, bool) { + parts := strings.Split(strings.Trim(path, "/"), "/") + if len(parts) != 4 || parts[2] != "pull" || parts[3] != fmt.Sprint(number) { + return repoRef{}, 0, false + } + r := repoRef{Host: strings.ToLower(host), Owner: parts[0], Name: parts[1]} + if !r.valid() { + return repoRef{}, 0, false + } + return r, number, true + }, + prHeadRef: func(number int) string { return fmt.Sprintf("refs/pull/%d/head", number) }, + cloneCmd: func(ctx context.Context, host string, r repoRef, dest string) *exec.Cmd { + cmd := exec.CommandContext(ctx, "gh", "repo", "clone", r.String(), dest) + cmd.Env = append(os.Environ(), "GH_HOST="+host) + return cmd + }, + loginCmd: func(host string) *exec.Cmd { + return exec.Command("gh", "auth", "login", "--hostname", host, "--web") + }, + loginText: "gh auth login", + cliName: "gh", + methodNames: map[string]string{"MERGE": "Create a merge commit", "SQUASH": "Squash and merge", "REBASE": "Rebase and merge"}, + methodVerbs: map[string]string{"MERGE": "Merge", "SQUASH": "Squash-merge", "REBASE": "Rebase-merge"}, + startPrompt: "Pull request {url} is checked out here. Read it with `gh pr view {number} --comments`, look at any failing checks, and tell me what's left to do.", + newSource: func(cfg config, repo *repoRef) source { return newGitHubSource(cfg, repo) }, + api: func(host string) forgeAPI { return newClient(host) }, +} diff --git a/forge_test.go b/forge_test.go new file mode 100644 index 0000000..cfc3353 --- /dev/null +++ b/forge_test.go @@ -0,0 +1,63 @@ +package main + +import ( + "context" + "fmt" + "strings" + "testing" +) + +func TestGithubPRFromPath(t *testing.T) { + for _, c := range []struct { + path string + number int + want string // "" for no match + }{ + {"/o/r/pull/12", 12, "github.com/o/r#12"}, + {"/o/r/pull/12/", 12, "github.com/o/r#12"}, + {"/o/r/issues/12", 12, ""}, + {"/o/r/pull/13", 12, ""}, // the number the URL doesn't say + {"/o/r/pull/abc", 12, ""}, + {"/o/r", 12, ""}, + {"/o/r/pull/12/files", 12, ""}, + {"/pull/12", 12, ""}, + } { + r, n, ok := theForge.prFromPath("github.com", c.path, c.number) + got := "" + if ok { + got = fmt.Sprintf("%s/%s/%s#%d", r.Host, r.Owner, r.Name, n) + } + if got != c.want { + t.Errorf("prFromPath(%q, %d) = %q, want %q", c.path, c.number, got, c.want) + } + } +} + +func TestIsDefaultHost(t *testing.T) { + if !theForge.isDefaultHost("GitHub.com") || theForge.isDefaultHost("ghe.example.com") || theForge.isDefaultHost("") { + t.Fatal("isDefaultHost") + } +} + +// A clone runs with the environment this process has, plus the forge's own +// additions: gh needs PATH, HOME and any GH_* token to work at all. +func TestCloneCmdInheritsTheEnvironment(t *testing.T) { + cmd := theForge.cloneCmd(context.Background(), "github.com", repoRef{"github.com", "o", "r"}, "/tmp/dest") + for _, want := range []string{"PATH=", "HOME="} { + found := false + for _, kv := range cmd.Env { + if strings.HasPrefix(kv, want) { + found = true + } + } + if !found { + t.Errorf("cloneCmd's Env lacks %s: %v", want, cmd.Env) + } + } + for _, kv := range cmd.Env { + if kv == "GH_HOST=github.com" { + return + } + } + t.Errorf("cloneCmd's Env lacks GH_HOST: %v", cmd.Env) +} diff --git a/github.go b/github.go index d06491d..ca13214 100644 --- a/github.go +++ b/github.go @@ -18,13 +18,14 @@ import ( // ── errors ──────────────────────────────────────────────────────────────────── -// errSignedOut: gh has no working token for a host. signedOutError says which. -var errSignedOut = errors.New("not signed in to GitHub") +// errSignedOut: the forge's CLI has no working token for a host. +// signedOutError says which. +var errSignedOut = errors.New("not signed in to " + theForge.name) type signedOutError struct{ Host string } func (e *signedOutError) Error() string { - return "not signed in to " + e.Host + ": run `gh auth login --hostname " + e.Host + "`" + return "not signed in to " + e.Host + ": run `" + theForge.loginText + " --hostname " + e.Host + "`" } func (e *signedOutError) Unwrap() error { return errSignedOut } @@ -41,7 +42,13 @@ type partialError struct { func (e *partialError) Error() string { return e.msg } // errTruncated: a list stopped at the cap rather than page on without end. -var errTruncated = errors.New("showing the first 200: filter, or open GitHub for the rest") +var errTruncated error = truncatedError{} + +type truncatedError struct{} + +func (truncatedError) Error() string { + return "showing the first 200: filter, or open " + theForge.name + " for the rest" +} // ── data ────────────────────────────────────────────────────────────────────── @@ -110,7 +117,7 @@ func (pr pullRequest) checks() string { } func (pr pullRequest) repo() repoRef { - owner, name, _ := strings.Cut(pr.Repository.NameWithOwner, "/") + owner, name, _ := splitRepoPath(pr.Repository.NameWithOwner, true) return repoRef{Host: pr.Host, Owner: owner, Name: name} } @@ -259,9 +266,9 @@ func (s repoSettings) methods() []string { // ── client ──────────────────────────────────────────────────────────────────── -// tokenFn finds the token for a host; a seam for tests. gh's own environment -// variables win, as they do for gh. -var tokenFn = ghToken +// tokenFn finds the token for a host; a seam for tests. The forge's own +// environment variables win, as they do for its CLI. +var tokenFn = theForge.token func ghToken(ctx context.Context, host string) (string, error) { vars := []string{"GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"} @@ -796,6 +803,16 @@ func pickPR(nodes []prStatus, owner string) (prStatus, bool) { return prStatus{}, false } +func (c *ghClient) viewer(ctx context.Context) (string, error) { + var res struct { + Viewer struct { + Login string `json:"login"` + } `json:"viewer"` + } + err := c.graphql(ctx, `query { viewer { login } }`, nil, &res) + return res.Viewer.Login, err +} + // ── your repos, for the repo picker ─────────────────────────────────────────── // repoInfo is a repo you can reach, and when it was last pushed to. diff --git a/gitlab.go b/gitlab.go new file mode 100644 index 0000000..c2b2dd9 --- /dev/null +++ b/gitlab.go @@ -0,0 +1,1003 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "os/exec" + "regexp" + "strconv" + "strings" + "sync" + "time" +) + +// GitLab, over its REST API (v4). Its merge requests are mapped onto the +// plugin's pull requests (pullRequest, prDetail, prStatus). + +var gitlabForge = forge{ + name: "GitLab", + defaultHost: "gitlab.com", + token: glToken, + prFromPath: func(host, path string, number int) (repoRef, int, bool) { + project, rest, ok := strings.Cut(strings.Trim(path, "/"), "/-/") + if !ok || rest != "merge_requests/"+strconv.Itoa(number) { + return repoRef{}, 0, false + } + owner, name, ok := splitRepoPath(project, true) + r := repoRef{Host: strings.ToLower(host), Owner: owner, Name: name} + if !ok || !r.valid() { + return repoRef{}, 0, false + } + return r, number, true + }, + prHeadRef: func(number int) string { return fmt.Sprintf("refs/merge-requests/%d/head", number) }, + cloneCmd: func(ctx context.Context, host string, r repoRef, dest string) *exec.Cmd { + cmd := exec.CommandContext(ctx, "glab", "repo", "clone", r.String(), dest) + cmd.Env = append(os.Environ(), "GITLAB_HOST="+host) + return cmd + }, + loginCmd: func(host string) *exec.Cmd { + return exec.Command("glab", "auth", "login", "--hostname", host, "--web") + }, + loginText: "glab auth login", + cliName: "glab", + methodNames: map[string]string{"MERGE": "Merge", "SQUASH": "Squash and merge"}, + methodVerbs: map[string]string{"MERGE": "Merge", "SQUASH": "Squash-merge"}, + startPrompt: "Merge request {url} is checked out here. Read it with `glab mr view {number} --comments`, look at any failing checks, and tell me what's left to do.", + nestedPaths: true, + newSource: func(cfg config, repo *repoRef) source { return newGitLabSource(cfg, repo) }, + api: func(host string) forgeAPI { return newGLClient(host) }, +} + +// ── auth and transport ──────────────────────────────────────────────────────── + +// glToken finds a host's token as glab does: its environment variables +// first (for the host GITLAB_HOST names, or any host when it names none), +// then glab's own store. glab has no `auth token`; `config get token` reads +// the keyring or its config file and prints only the token. +func glToken(ctx context.Context, host string) (string, error) { + if h := os.Getenv("GITLAB_HOST"); h == "" || strings.EqualFold(hostOf(h), host) { + for _, v := range []string{"GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN", "OAUTH_TOKEN"} { + if t := strings.TrimSpace(os.Getenv(v)); t != "" { + return t, nil + } + } + } + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, "glab", "config", "get", "token", "--host", host).Output() + if err != nil { + var ee *exec.Error + if errors.As(err, &ee) { + return "", errors.New("glab isn't installed: https://gitlab.com/gitlab-org/cli") + } + return "", &signedOutError{host} + } + t := strings.TrimSpace(string(out)) + if t == "" { + return "", &signedOutError{host} + } + return t, nil +} + +// hostOf is the host in GITLAB_HOST, which can be a URL. +func hostOf(s string) string { + if u, err := url.Parse(s); err == nil && u.Host != "" { + return u.Hostname() + } + return strings.TrimSuffix(s, "/") +} + +// glEndpointFn is the REST API's base URL for a host; a seam for tests. +var glEndpointFn = func(host string) string { return "https://" + host + "/api/v4" } + +// glPageSize is every list page's size: GitLab pages by number, so the size +// can't change between one page and the next. +const glPageSize = 50 + +type glClient struct { + host string + mu sync.Mutex + token string + http *http.Client + projects map[int]string // project id → its path, for forks +} + +func newGLClient(host string) *glClient { + return &glClient{host: host, http: &http.Client{Timeout: 30 * time.Second}, projects: map[int]string{}} +} + +func (c *glClient) auth(ctx context.Context) (string, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.token != "" { + return c.token, nil + } + t, err := tokenFn(ctx, c.host) + if err != nil { + return "", err + } + c.token = t + return t, nil +} + +// glHTTPError is an answer GitLab refused with. +type glHTTPError struct { + status int + msg string +} + +func (e *glHTTPError) Error() string { + if e.msg == "" { + return fmt.Sprintf("GitLab: HTTP %d", e.status) + } + return fmt.Sprintf("GitLab: HTTP %d: %s", e.status, e.msg) +} + +func isStatus(err error, status int) bool { + var h *glHTTPError + return errors.As(err, &h) && h.status == status +} + +// call makes one request; body, when there is one, is sent as JSON. Every +// string in the answer was written by someone else, so it's sanitized +// before anything else sees it. +func (c *glClient) call(ctx context.Context, method, path string, q url.Values, body any, out any) (http.Header, error) { + token, err := c.auth(ctx) + if err != nil { + return nil, err + } + u := glEndpointFn(c.host) + path + if len(q) > 0 { + u += "?" + q.Encode() + } + var rd io.Reader + if body != nil { + data, err := json.Marshal(body) + if err != nil { + return nil, err + } + rd = bytes.NewReader(data) + } + req, err := http.NewRequestWithContext(ctx, method, u, rd) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("User-Agent", "herdr-github") + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := c.http.Do(req) + if err != nil { + return nil, fmt.Errorf("GitLab: %w", err) + } + defer resp.Body.Close() + data, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20)) + if err != nil { + return nil, fmt.Errorf("GitLab: %w", err) + } + if resp.StatusCode == http.StatusUnauthorized { + c.mu.Lock() + c.token = "" + c.mu.Unlock() + return nil, &signedOutError{c.host} + } + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return nil, &glHTTPError{resp.StatusCode, glMessage(data)} + } + if out != nil && len(data) > 0 { + if err := json.Unmarshal(data, out); err != nil { + return nil, fmt.Errorf("GitLab: bad reply: %w", err) + } + sanitize(out) + } + return resp.Header, nil +} + +// glMessage is what an error reply says: its "message" or "error", which +// can be a string or, for a validation error, an object. +func glMessage(data []byte) string { + var reply struct { + Message json.RawMessage `json:"message"` + Error json.RawMessage `json:"error"` + } + if json.Unmarshal(data, &reply) != nil { + return "" + } + raw := reply.Message + if len(raw) == 0 { + raw = reply.Error + } + var s string + if json.Unmarshal(raw, &s) != nil { + s = string(raw) + } + return clean(s, false) +} + +func projectPath(r repoRef) string { + return "/projects/" + url.PathEscape(r.Owner+"/"+r.Name) +} + +func mrPath(r repoRef, iid int) string { + return projectPath(r) + "/merge_requests/" + strconv.Itoa(iid) +} + +// each runs fn for 0..n-1, a few at a time. +func each(n int, fn func(i int)) { + sem := make(chan struct{}, 6) + var wg sync.WaitGroup + for i := range n { + wg.Add(1) + sem <- struct{}{} + go func() { + defer func() { <-sem; wg.Done() }() + fn(i) + }() + } + wg.Wait() +} + +// ── data ────────────────────────────────────────────────────────────────────── + +type glUser struct { + Username string `json:"username"` +} + +type glPipeline struct { + ID int `json:"id"` + ProjectID int `json:"project_id"` + Status string `json:"status"` +} + +// glLabels are an MR's labels: names, or with with_labels_details objects +// with a colour too. +type glLabels []label + +func (l *glLabels) UnmarshalJSON(data []byte) error { + var raw []json.RawMessage + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + for _, r := range raw { + var x label + if json.Unmarshal(r, &x.Name) != nil { + if err := json.Unmarshal(r, &x); err != nil { + return err + } + } + x.Color = strings.TrimPrefix(x.Color, "#") + *l = append(*l, x) + } + return nil +} + +type glMR struct { + ID int `json:"id"` + IID int `json:"iid"` + Title string `json:"title"` + Body string `json:"description"` + State string `json:"state"` + WebURL string `json:"web_url"` + Draft bool `json:"draft"` + UpdatedAt time.Time `json:"updated_at"` + ClosedAt *time.Time `json:"closed_at"` + MergedAt *time.Time `json:"merged_at"` + Author *glUser `json:"author"` + SourceBranch string `json:"source_branch"` + TargetBranch string `json:"target_branch"` + SHA string `json:"sha"` + SourceProjectID int `json:"source_project_id"` + TargetProjectID int `json:"target_project_id"` + DetailedMergeStatus string `json:"detailed_merge_status"` + HasConflicts bool `json:"has_conflicts"` + MergeWhenPipelineSucceeds bool `json:"merge_when_pipeline_succeeds"` + Squash bool `json:"squash"` + ShouldRemoveSourceBranch *bool `json:"should_remove_source_branch"` + ForceRemoveSourceBranch *bool `json:"force_remove_source_branch"` + AllowCollaboration bool `json:"allow_collaboration"` + HeadPipeline *glPipeline `json:"head_pipeline"` + ChangesCount string `json:"changes_count"` + Labels glLabels `json:"labels"` + User *struct { + CanMerge bool `json:"can_merge"` + } `json:"user"` +} + +func (mr glMR) fork() bool { + return mr.SourceProjectID != 0 && mr.SourceProjectID != mr.TargetProjectID +} + +// state is GitLab's state as GitHub spells it. A locked MR is one being +// merged right now: still open. +func (mr glMR) state() string { + switch mr.State { + case "merged": + return "MERGED" + case "closed": + return "CLOSED" + } + return "OPEN" +} + +func (mr glMR) mergeable() string { + switch { + case mr.HasConflicts || mr.DetailedMergeStatus == "conflict": + return "CONFLICTING" + case mr.DetailedMergeStatus == "mergeable": + return "MERGEABLE" + } + return "UNKNOWN" +} + +// mergeState is detailed_merge_status as GitHub's mergeStateStatus: what +// the PR screen says about merging. +func (mr glMR) mergeState() string { + switch mr.DetailedMergeStatus { + case "mergeable": + return "CLEAN" + case "need_rebase": + return "BEHIND" + case "conflict": + return "DIRTY" + case "draft_status": + return "DRAFT" + case "", "checking", "unchecked", "preparing", "approvals_syncing": + return "UNKNOWN" + } + return "BLOCKED" +} + +// reviewDecision is what detailed_merge_status says of reviews; the PR +// screen adds what the approvals say. +func (mr glMR) reviewDecision() string { + switch mr.DetailedMergeStatus { + case "requested_changes": + return "CHANGES_REQUESTED" + case "not_approved": + return "REVIEW_REQUIRED" + } + return "" +} + +// checks is the head pipeline's state as a check rollup. A list's MRs come +// without their pipeline: then what detailed_merge_status says of it. +func (mr glMR) checks() string { + if p := mr.HeadPipeline; p != nil { + switch p.Status { + case "success": + return "SUCCESS" + case "failed": + return "FAILURE" + case "canceled": + return "ERROR" + case "skipped", "manual": + return "" + } + return "PENDING" + } + switch mr.DetailedMergeStatus { + case "ci_still_running": + return "PENDING" + case "ci_must_pass": + return "FAILURE" + } + return "" +} + +func checkRollup(state string) rollup { + var r rollup + if state == "" { + return r + } + r.Nodes = make([]struct { + Commit struct { + StatusCheckRollup *struct { + State string `json:"state"` + } `json:"statusCheckRollup"` + } `json:"commit"` + }, 1) + r.Nodes[0].Commit.StatusCheckRollup = &struct { + State string `json:"state"` + }{state} + return r +} + +// projectOf is the MR's project path, from its URL ("…/group/proj/-/merge_requests/1"). +func projectOf(webURL string) string { + u, err := url.Parse(webURL) + if err != nil { + return "" + } + p, _, ok := strings.Cut(u.Path, "/-/merge_requests/") + if !ok { + return "" + } + return strings.Trim(p, "/") +} + +// sourcePath is the path of a fork MR's source project; "" when it isn't +// a fork's, or the fork can't be seen. +func (c *glClient) sourcePath(ctx context.Context, mr glMR) string { + if !mr.fork() { + return "" + } + c.mu.Lock() + p, ok := c.projects[mr.SourceProjectID] + c.mu.Unlock() + if ok { + return p + } + var proj struct { + Path string `json:"path_with_namespace"` + } + if _, err := c.call(ctx, "GET", "/projects/"+strconv.Itoa(mr.SourceProjectID), nil, nil, &proj); err != nil { + return "" + } + c.mu.Lock() + c.projects[mr.SourceProjectID] = proj.Path + c.mu.Unlock() + return proj.Path +} + +// pr is the MR as a row in the lists. +func (c *glClient) pr(ctx context.Context, mr glMR) pullRequest { + pr := pullRequest{ + Host: c.host, ID: strconv.Itoa(mr.ID), Number: mr.IID, Title: mr.Title, URL: mr.WebURL, + IsDraft: mr.Draft, State: mr.state(), UpdatedAt: mr.UpdatedAt, + HeadRefName: mr.SourceBranch, BaseRefName: mr.TargetBranch, IsCrossRepository: mr.fork(), + ReviewDecision: mr.reviewDecision(), Mergeable: mr.mergeable(), Commits: checkRollup(mr.checks()), + } + if mr.Author != nil { + pr.Author = &actor{mr.Author.Username} + } + pr.Repository.NameWithOwner = projectOf(mr.WebURL) + pr.Labels.Nodes = mr.Labels + if src := c.sourcePath(ctx, mr); src != "" { + owner, _, _ := splitRepoPath(src, true) + pr.HeadRepositoryOwner = &actor{owner} + pr.HeadRepository = &struct { + NameWithOwner string `json:"nameWithOwner"` + }{src} + } + if mr.MergeWhenPipelineSucceeds { + method := "MERGE" + if mr.Squash { + method = "SQUASH" + } + pr.AutoMergeRequest = &struct { + EnabledAt string `json:"enabledAt"` + MergeMethod string `json:"mergeMethod"` + }{MergeMethod: method} + } + return pr +} + +// status is the MR as a sidebar label has it. +func (c *glClient) status(ctx context.Context, mr glMR) prStatus { + pr := c.pr(ctx, mr) + s := prStatus{ + Number: pr.Number, State: pr.State, IsDraft: pr.IsDraft, ReviewDecision: pr.ReviewDecision, + Mergeable: pr.Mergeable, URL: pr.URL, HeadRepositoryOwner: pr.HeadRepositoryOwner, Commits: pr.Commits, + } + if mr.MergeWhenPipelineSucceeds { + s.AutoMergeRequest = &struct { + EnabledAt string `json:"enabledAt"` + }{} + } + if mr.MergedAt != nil { + s.ClosedAt = mr.MergedAt + } else if mr.ClosedAt != nil { + s.ClosedAt = mr.ClosedAt + } + return s +} + +// ── lists ───────────────────────────────────────────────────────────────────── + +// mrPage is one page of an MR list. The cursor is GitLab's page number. +func (c *glClient) mrPage(ctx context.Context, path string, q url.Values, cursor string) ([]pullRequest, string, error) { + q.Set("state", "opened") + q.Set("order_by", "updated_at") + q.Set("with_labels_details", "true") + q.Set("per_page", strconv.Itoa(glPageSize)) + if cursor != "" { + q.Set("page", cursor) + } + var mrs []glMR + h, err := c.call(ctx, "GET", path, q, nil, &mrs) + if err != nil { + return nil, "", err + } + prs := make([]pullRequest, len(mrs)) + each(len(mrs), func(i int) { prs[i] = c.pr(ctx, mrs[i]) }) + return prs, h.Get("X-Next-Page"), nil +} + +func (c *glClient) mr(ctx context.Context, r repoRef, iid int) (glMR, error) { + var mr glMR + _, err := c.call(ctx, "GET", mrPath(r, iid), nil, nil, &mr) + return mr, err +} + +// ── the PR screen ───────────────────────────────────────────────────────────── + +func (c *glClient) detail(ctx context.Context, pr pullRequest) (*prDetail, error) { + r := pr.repo() + mr, err := c.mr(ctx, r, pr.Number) + if err != nil { + if isStatus(err, http.StatusNotFound) { + return nil, fmt.Errorf("!%d isn't there any more", pr.Number) + } + return nil, err + } + d := &prDetail{pullRequest: c.pr(ctx, mr), Body: mr.Body, MergeStateStatus: mr.mergeState(), + HeadRefOid: mr.SHA, MaintainerCanModify: mr.AllowCollaboration} + if !mr.fork() { + d.HeadRef = &struct { + ID string `json:"id"` + }{mr.SourceBranch} + } + d.ViewerCanMerge = mr.User != nil && mr.User.CanMerge + d.RepoSettings.AutoMergeAllowed = true + d.RepoSettings.DeleteBranchOnMerge = (mr.ForceRemoveSourceBranch != nil && *mr.ForceRemoveSourceBranch) || + (mr.ShouldRemoveSourceBranch != nil && *mr.ShouldRemoveSourceBranch) + d.ChangedFiles, _ = strconv.Atoi(strings.TrimSuffix(mr.ChangesCount, "+")) + + // The rest is extra: what can't be had is left out, not an error. + var wg sync.WaitGroup + run := func(f func()) { wg.Add(1); go func() { defer wg.Done(); f() }() } + var approved bool + var approvers, reviewers []reviewer + run(func() { c.settings(ctx, r, d) }) + run(func() { approved, approvers = c.approvals(ctx, r, mr.IID) }) + run(func() { reviewers = c.reviewers(ctx, r, mr.IID) }) + run(func() { d.Comments, d.Threads = c.discussions(ctx, r, mr.IID) }) + run(func() { d.Checks = c.jobs(ctx, mr.HeadPipeline) }) + run(func() { d.Additions, d.Deletions = c.lineCounts(ctx, r, mr.IID) }) + wg.Wait() + + sortChecks(d.Checks) + d.Reviewers = mergeReviewers(reviewers, approvers) + if d.ReviewDecision == "" && approved && len(approvers) > 0 { + d.ReviewDecision = "APPROVED" + } + return d, nil +} + +// settings are the project's merge settings. squash_option decides which +// methods there are: never, always, or either, with one ticked by default. +func (c *glClient) settings(ctx context.Context, r repoRef, d *prDetail) { + var p struct { + SquashOption string `json:"squash_option"` + } + if _, err := c.call(ctx, "GET", projectPath(r), nil, nil, &p); err != nil { + p.SquashOption = "default_off" + } + s := &d.RepoSettings + s.MergeCommitAllowed = p.SquashOption != "always" + s.SquashMergeAllowed = p.SquashOption != "never" + s.ViewerDefaultMergeMethod = "MERGE" + if p.SquashOption == "always" || p.SquashOption == "default_on" { + s.ViewerDefaultMergeMethod = "SQUASH" + } +} + +func (c *glClient) approvals(ctx context.Context, r repoRef, iid int) (bool, []reviewer) { + var a struct { + Approved bool `json:"approved"` + ApprovedBy []struct { + User glUser `json:"user"` + } `json:"approved_by"` + } + if _, err := c.call(ctx, "GET", mrPath(r, iid)+"/approvals", nil, nil, &a); err != nil { + return false, nil + } + var out []reviewer + for _, u := range a.ApprovedBy { + out = append(out, reviewer{u.User.Username, "APPROVED"}) + } + return a.Approved, out +} + +func (c *glClient) reviewers(ctx context.Context, r repoRef, iid int) []reviewer { + var rs []struct { + User glUser `json:"user"` + State string `json:"state"` + } + if _, err := c.call(ctx, "GET", mrPath(r, iid)+"/reviewers", nil, nil, &rs); err != nil { + return nil + } + var out []reviewer + for _, x := range rs { + state := map[string]string{"approved": "APPROVED", "requested_changes": "CHANGES_REQUESTED", "reviewed": "COMMENTED"}[x.State] + if state == "" { + state = "PENDING" + } + out = append(out, reviewer{x.User.Username, state}) + } + return out +} + +// mergeReviewers is the reviewers, with an approval counting for whoever +// gave it, reviewer or not. +func mergeReviewers(reviewers, approvers []reviewer) []reviewer { + out := append([]reviewer(nil), reviewers...) + for _, a := range approvers { + found := false + for i := range out { + if out[i].Name == a.Name { + out[i].State, found = "APPROVED", true + } + } + if !found { + out = append(out, a) + } + } + return out +} + +// discussions are the MR's comments and its threads on the code. A comment +// thread that isn't on a line of code reads as a comment. +func (c *glClient) discussions(ctx context.Context, r repoRef, iid int) ([]comment, []thread) { + var ds []struct { + Notes []struct { + Author *glUser `json:"author"` + Body string `json:"body"` + CreatedAt time.Time `json:"created_at"` + System bool `json:"system"` + Resolvable bool `json:"resolvable"` + Resolved bool `json:"resolved"` + Position *struct { + NewPath string `json:"new_path"` + NewLine int `json:"new_line"` + } `json:"position"` + } `json:"notes"` + } + if _, err := c.call(ctx, "GET", mrPath(r, iid)+"/discussions", url.Values{"per_page": {"100"}}, nil, &ds); err != nil { + return nil, nil + } + var comments []comment + var threads []thread + for _, d := range ds { + if len(d.Notes) == 0 || d.Notes[0].System { + continue + } + first := d.Notes[0] + if first.Position == nil { + for _, n := range d.Notes { + if !n.System { + comments = append(comments, comment{Author: glActor(n.Author), Body: n.Body, CreatedAt: n.CreatedAt}) + } + } + continue + } + t := thread{IsResolved: first.Resolved, Path: first.Position.NewPath, Line: first.Position.NewLine} + for _, n := range d.Notes { + if !n.System && len(t.Comments.Nodes) < 4 { + t.Comments.Nodes = append(t.Comments.Nodes, comment{Author: glActor(n.Author), Body: n.Body, CreatedAt: n.CreatedAt}) + } + } + threads = append(threads, t) + } + return comments, threads +} + +func glActor(u *glUser) *actor { + if u == nil { + return nil + } + return &actor{u.Username} +} + +// jobs are the head pipeline's jobs as checks: one allowed to fail isn't +// required. +func (c *glClient) jobs(ctx context.Context, p *glPipeline) []check { + if p == nil { + return nil + } + var js []struct { + Name string `json:"name"` + Status string `json:"status"` + AllowFailure bool `json:"allow_failure"` + WebURL string `json:"web_url"` + } + path := fmt.Sprintf("/projects/%d/pipelines/%d/jobs", p.ProjectID, p.ID) + if _, err := c.call(ctx, "GET", path, url.Values{"per_page": {"100"}}, nil, &js); err != nil { + return nil + } + out := make([]check, 0, len(js)) + for _, j := range js { + ch := check{Typename: "CheckRun", Name: j.Name, Status: "COMPLETED", IsRequired: !j.AllowFailure, DetailsURL: j.WebURL} + switch j.Status { + case "success": + ch.Conclusion = "SUCCESS" + case "failed", "canceled": + ch.Conclusion = "FAILURE" + if j.AllowFailure { + ch.Conclusion = "NEUTRAL" + } + case "skipped", "manual": + ch.Conclusion = "SKIPPED" + default: + ch.Status = "IN_PROGRESS" + } + out = append(out, ch) + } + return out +} + +// lineCounts adds up the lines the MR's diffs add and remove, over its +// first 100 files. +func (c *glClient) lineCounts(ctx context.Context, r repoRef, iid int) (add, del int) { + var diffs []struct { + Body string `json:"diff"` // Body: sanitize keeps its line breaks + } + if _, err := c.call(ctx, "GET", mrPath(r, iid)+"/diffs", url.Values{"per_page": {"100"}}, nil, &diffs); err != nil { + return 0, 0 + } + for _, d := range diffs { + for _, line := range strings.Split(d.Body, "\n") { + switch { + case strings.HasPrefix(line, "+++"), strings.HasPrefix(line, "---"): + case strings.HasPrefix(line, "+"): + add++ + case strings.HasPrefix(line, "-"): + del++ + } + } + } + return add, del +} + +// ── changes ─────────────────────────────────────────────────────────────────── + +// draftPrefix is how GitLab marks a draft in a title, and how it used to. +var draftPrefix = regexp.MustCompile(`(?i)^\s*(\[draft\]|\(draft\)|draft:|\[wip\]|wip:)\s*`) + +// setDraft retitles the MR: GitLab's drafts are a title prefix. The title +// is read again first, so a rename since the list loaded isn't undone. +func (c *glClient) setDraft(ctx context.Context, r repoRef, iid int, draft bool) error { + var mr glMR + if _, err := c.call(ctx, "GET", mrPath(r, iid), nil, nil, &mr); err != nil { + return err + } + title := mr.Title + for draftPrefix.MatchString(title) { + title = draftPrefix.ReplaceAllString(title, "") + } + if draft { + title = "Draft: " + title + } + _, err := c.call(ctx, "PUT", mrPath(r, iid), nil, map[string]any{"title": title}, nil) + return err +} + +// merge merges now, or with auto once its pipeline passes. The head commit +// is pinned: if someone pushed since the PR screen loaded, GitLab refuses +// rather than merge code you haven't seen. +func (c *glClient) merge(ctx context.Context, d *prDetail, method string, auto bool) error { + body := map[string]any{"sha": d.HeadRefOid, "squash": method == "SQUASH"} + if auto { + // auto_merge since GitLab 17.11; merge_when_pipeline_succeeds before. + body["auto_merge"], body["merge_when_pipeline_succeeds"] = true, true + } + _, err := c.call(ctx, "PUT", mrPath(d.repo(), d.Number)+"/merge", nil, body, nil) + if isStatus(err, http.StatusConflict) { + return fmt.Errorf("!%d changed since it was loaded: look again (ctrl+r) before merging", d.Number) + } + return err +} + +// disableAutoMerge cancels auto-merge, by the endpoint GitLab 19.5 added or, +// on an older GitLab, the one before it. +func (c *glClient) disableAutoMerge(ctx context.Context, d *prDetail) error { + path := mrPath(d.repo(), d.Number) + _, err := c.call(ctx, "POST", path+"/cancel_auto_merge", nil, nil, nil) + if isStatus(err, http.StatusNotFound) { + _, err = c.call(ctx, "POST", path+"/cancel_merge_when_pipeline_succeeds", nil, nil, nil) + } + return err +} + +func (c *glClient) deleteBranch(ctx context.Context, r repoRef, branch string) error { + _, err := c.call(ctx, "DELETE", projectPath(r)+"/repository/branches/"+url.PathEscape(branch), nil, nil, nil) + return err +} + +// ── the label hooks and `status` ────────────────────────────────────────────── + +// prsForBranches finds each head branch's MR in one project: an open one +// first, else the latest, from the expected owner's project. Any lookup +// failing fails them all: a branch GitLab didn't answer for would read as +// having no MR. +func (c *glClient) prsForBranches(ctx context.Context, r repoRef, heads []branchHead) (map[branchHead]prStatus, error) { + found := make([]*prStatus, len(heads)) + errs := make([]error, len(heads)) + each(len(heads), func(i int) { + q := url.Values{"source_branch": {heads[i].Branch}, "state": {"all"}, "order_by": {"updated_at"}, "per_page": {"5"}} + var mrs []glMR + if _, errs[i] = c.call(ctx, "GET", projectPath(r)+"/merge_requests", q, nil, &mrs); errs[i] != nil { + return + } + nodes := make([]prStatus, len(mrs)) + for j, mr := range mrs { + nodes[j] = c.status(ctx, mr) + } + s, ok := pickPR(nodes, heads[i].Owner) + if !ok { + return + } + // A list's MRs come without their pipeline: the one picked, in full. + mr, err := c.mr(ctx, r, s.Number) + if errs[i] = err; err == nil { + s = c.status(ctx, mr) + found[i] = &s + } + }) + if err := errors.Join(errs...); err != nil { + return nil, err + } + out := map[branchHead]prStatus{} + for i, s := range found { + if s != nil { + out[heads[i]] = *s + } + } + return out, nil +} + +// prsByNumber is the status of MRs in one project. One that isn't there is +// left out. +func (c *glClient) prsByNumber(ctx context.Context, r repoRef, numbers []int) (map[int]prStatus, error) { + found := make([]*prStatus, len(numbers)) + errs := make([]error, len(numbers)) + each(len(numbers), func(i int) { + mr, err := c.mr(ctx, r, numbers[i]) + switch { + case isStatus(err, http.StatusNotFound): + case err != nil: + errs[i] = err + default: + s := c.status(ctx, mr) + found[i] = &s + } + }) + if err := errors.Join(errs...); err != nil { + return nil, err + } + out := map[int]prStatus{} + for i, s := range found { + if s != nil { + out[numbers[i]] = *s + } + } + return out, nil +} + +func (c *glClient) viewer(ctx context.Context) (string, error) { + var u glUser + _, err := c.call(ctx, "GET", "/user", nil, nil, &u) + return u.Username, err +} + +// reposPage is one page of the projects you're a member of, most recently +// active first. +func (c *glClient) reposPage(ctx context.Context, cursor string) ([]repoInfo, string, error) { + q := url.Values{"membership": {"true"}, "simple": {"true"}, "archived": {"false"}, + "order_by": {"last_activity_at"}, "per_page": {"100"}} + if cursor != "" { + q.Set("page", cursor) + } + var ps []struct { + Path string `json:"path_with_namespace"` + LastActivity time.Time `json:"last_activity_at"` + } + h, err := c.call(ctx, "GET", "/projects", q, nil, &ps) + if err != nil { + return nil, "", err + } + var out []repoInfo + for _, p := range ps { + if owner, name, ok := splitRepoPath(p.Path, true); ok { + out = append(out, repoInfo{repoRef{Host: c.host, Owner: owner, Name: name}, p.LastActivity}) + } + } + return out, h.Get("X-Next-Page"), nil +} + +// ── the source ──────────────────────────────────────────────────────────────── + +// gitlabSource talks to every configured host, one client per host. +type gitlabSource struct { + cfg config + repo *repoRef + mu sync.Mutex + clients map[string]*glClient +} + +func newGitLabSource(cfg config, repo *repoRef) *gitlabSource { + return &gitlabSource{cfg: cfg, repo: repo, clients: map[string]*glClient{}} +} + +func (s *gitlabSource) client(host string) *glClient { + s.mu.Lock() + defer s.mu.Unlock() + c, ok := s.clients[host] + if !ok { + c = newGLClient(host) + s.clients[host] = c + } + return c +} + +// list: GitLab has no list of the MRs waiting on your review, so there's no +// Review tab (caps); Mine is every host's MRs of yours, the repo tab one +// project's. +func (s *gitlabSource) list(ctx context.Context, t tab, cursor string) (page, error) { + switch t { + case tabRepo: + if s.repo == nil { + return page{}, nil + } + prs, next, err := s.client(s.repo.Host).mrPage(ctx, projectPath(*s.repo)+"/merge_requests", url.Values{}, cursor) + return page{prs, next}, err + case tabMine: + return fanOut(s.cfg.Hosts, t, cursor, func(host, after string) ([]pullRequest, string, error) { + q := url.Values{"scope": {"created_by_me"}, "non_archived": {"true"}} + return s.client(host).mrPage(ctx, "/merge_requests", q, after) + }) + } + return page{}, nil +} + +func (s *gitlabSource) detail(ctx context.Context, pr pullRequest) (*prDetail, error) { + return s.client(pr.Host).detail(ctx, pr) +} + +func (s *gitlabSource) byNumber(ctx context.Context, r repoRef, number int) (pullRequest, error) { + c := s.client(r.Host) + mr, err := c.mr(ctx, r, number) + if isStatus(err, http.StatusNotFound) { + err = fmt.Errorf("%s!%d isn't there, or isn't yours to see", r, number) + } + if err != nil { + return pullRequest{}, err + } + return c.pr(ctx, mr), nil +} + +func (s *gitlabSource) setDraft(ctx context.Context, pr pullRequest, draft bool) error { + return s.client(pr.Host).setDraft(ctx, pr.repo(), pr.Number, draft) +} + +func (s *gitlabSource) merge(ctx context.Context, d *prDetail, method string, auto bool) error { + return s.client(d.Host).merge(ctx, d, method, auto) +} + +func (s *gitlabSource) disableAutoMerge(ctx context.Context, d *prDetail) error { + return s.client(d.Host).disableAutoMerge(ctx, d) +} + +func (s *gitlabSource) deleteBranch(ctx context.Context, d *prDetail) error { + if d.HeadRef == nil { + return errors.New("the branch is already gone") + } + return s.client(d.Host).deleteBranch(ctx, d.repo(), d.HeadRef.ID) +} + +func (s *gitlabSource) repos(ctx context.Context, cursor string) ([]repoInfo, string, error) { + return pageHosts(s.cfg.Hosts, cursor, func(host, after string) ([]repoInfo, string, error) { + return s.client(host).reposPage(ctx, after) + }) +} + +func (s *gitlabSource) caps() caps { return caps{reviewRequested: false, autoMerge: true} } diff --git a/gitlab_test.go b/gitlab_test.go new file mode 100644 index 0000000..5350f29 --- /dev/null +++ b/gitlab_test.go @@ -0,0 +1,455 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" +) + +// fakeGitLab serves the REST API from h, with a token that works, and makes +// GitLab the forge for the test. +func fakeGitLab(t *testing.T, h http.HandlerFunc) { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("Authorization"); got != "Bearer tok" { + t.Errorf("Authorization = %q", got) + } + h(w, r) + })) + oldE, oldT, oldF := glEndpointFn, tokenFn, theForge + glEndpointFn = func(string) string { return srv.URL } + theForge = gitlabForge + tokenFn = func(context.Context, string) (string, error) { return "tok", nil } + t.Cleanup(func() { + srv.Close() + glEndpointFn, tokenFn, theForge = oldE, oldT, oldF + }) +} + +func send(w http.ResponseWriter, v any) { _ = json.NewEncoder(w).Encode(v) } + +func mrJSON(iid int, extra map[string]any) map[string]any { + m := map[string]any{ + "id": 1000 + iid, "iid": iid, "title": "t", "state": "opened", "draft": false, + "web_url": fmt.Sprintf("https://gitlab.com/grp/sub/proj/-/merge_requests/%d", iid), + "updated_at": "2026-09-20T10:00:00Z", "author": map[string]any{"username": "ana"}, + "source_branch": "feat", "target_branch": "main", "sha": "abc123", + "source_project_id": 7, "target_project_id": 7, "detailed_merge_status": "mergeable", + } + for k, v := range extra { + m[k] = v + } + return m +} + +var glRepo = repoRef{"gitlab.com", "grp/sub", "proj"} + +func TestGitLabMinePagesByNextPage(t *testing.T) { + fakeGitLab(t, func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + if r.URL.Path != "/merge_requests" || q.Get("scope") != "created_by_me" || q.Get("state") != "opened" { + t.Errorf("asked %s", r.URL) + } + if q.Get("page") == "" { + w.Header().Set("X-Next-Page", "2") + send(w, []any{mrJSON(1, nil)}) + return + } + if q.Get("page") != "2" { + t.Errorf("page = %q", q.Get("page")) + } + send(w, []any{mrJSON(2, nil)}) + }) + s := newGitLabSource(withDefaults(config{Forge: "gitlab"}), nil) + p, err := s.list(context.Background(), tabMine, "") + if err != nil || len(p.prs) != 1 || p.next == "" { + t.Fatalf("first page: %+v %v", p, err) + } + p2, err := s.list(context.Background(), tabMine, p.next) + if err != nil || len(p2.prs) != 1 || p2.prs[0].Number != 2 || p2.next != "" { + t.Fatalf("second page: %+v %v", p2, err) + } + if r, _ := s.list(context.Background(), tabReview, ""); len(r.prs) != 0 { + t.Fatal("GitLab has no Review list") + } +} + +func TestGitLabRepoTabAsksTheProject(t *testing.T) { + fakeGitLab(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.EscapedPath() != "/projects/grp%2Fsub%2Fproj/merge_requests" { + t.Errorf("path %s", r.URL.EscapedPath()) + } + send(w, []any{}) + }) + r := glRepo + if _, err := newGitLabSource(withDefaults(config{Forge: "gitlab"}), &r).list(context.Background(), tabRepo, ""); err != nil { + t.Fatal(err) + } +} + +func TestGitLabMRMapsOntoAPullRequest(t *testing.T) { + fakeGitLab(t, func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/merge_requests": + send(w, []any{ + mrJSON(5, map[string]any{ + "title": "Draft: fix \x1b]52;c;evil\x07it", "draft": true, "source_project_id": 9, + "detailed_merge_status": "conflict", "merge_when_pipeline_succeeds": true, "squash": true, + "labels": []any{map[string]any{"name": "bug", "color": "#ff0000"}}, + }), + mrJSON(6, map[string]any{"state": "merged", "detailed_merge_status": "requested_changes", "labels": []any{"plain"}}), + }) + case "/projects/9": + send(w, map[string]any{"path_with_namespace": "alice/proj"}) + default: + t.Errorf("asked %s", r.URL) + } + }) + p, err := newGitLabSource(withDefaults(config{Forge: "gitlab"}), nil).list(context.Background(), tabMine, "") + if err != nil || len(p.prs) != 2 { + t.Fatalf("%+v %v", p, err) + } + byNum := map[int]pullRequest{} + for _, pr := range p.prs { + byNum[pr.Number] = pr + } + a, b := byNum[5], byNum[6] + if a.repo() != glRepo || a.key() != "gitlab.com/grp/sub/proj#5" { + t.Errorf("repo %+v key %s", a.repo(), a.key()) + } + if strings.ContainsRune(a.Title, 0x1b) || !a.IsDraft || a.State != "OPEN" || a.author() != "ana" { + t.Errorf("row %+v", a) + } + if !a.IsCrossRepository || a.headOwner() != "alice" || a.HeadRepository.NameWithOwner != "alice/proj" { + t.Errorf("fork %+v %+v", a.HeadRepositoryOwner, a.HeadRepository) + } + if a.Mergeable != "CONFLICTING" || a.AutoMergeRequest == nil || a.AutoMergeRequest.MergeMethod != "SQUASH" { + t.Errorf("merge state %q %+v", a.Mergeable, a.AutoMergeRequest) + } + if len(a.Labels.Nodes) != 1 || a.Labels.Nodes[0] != (label{"bug", "ff0000"}) { + t.Errorf("labels %+v", a.Labels.Nodes) + } + if b.State != "MERGED" || b.ReviewDecision != "CHANGES_REQUESTED" || b.IsCrossRepository || b.Labels.Nodes[0].Name != "plain" { + t.Errorf("second %+v", b) + } +} + +func TestGitLabDetail(t *testing.T) { + fakeGitLab(t, func(w http.ResponseWriter, r *http.Request) { + base := "/projects/grp/sub/proj" + switch r.URL.Path { + case base + "/merge_requests/5": + send(w, mrJSON(5, map[string]any{ + "description": "line one\nline two", "changes_count": "3", "user": map[string]any{"can_merge": true}, + "detailed_merge_status": "ci_still_running", + "head_pipeline": map[string]any{"id": 77, "project_id": 7, "status": "running"}, + })) + case base: + send(w, map[string]any{"squash_option": "default_on"}) + case base + "/merge_requests/5/approvals": + send(w, map[string]any{"approved": true, "approved_by": []any{map[string]any{"user": map[string]any{"username": "bo"}}}}) + case base + "/merge_requests/5/reviewers": + send(w, []any{ + map[string]any{"user": map[string]any{"username": "bo"}, "state": "unreviewed"}, + map[string]any{"user": map[string]any{"username": "cy"}, "state": "unreviewed"}, + }) + case base + "/merge_requests/5/discussions": + send(w, []any{ + map[string]any{"notes": []any{map[string]any{"author": map[string]any{"username": "cy"}, "body": "hi", "created_at": "2026-09-20T10:00:00Z"}}}, + map[string]any{"notes": []any{map[string]any{"system": true, "body": "added a commit"}}}, + map[string]any{"notes": []any{map[string]any{"author": map[string]any{"username": "bo"}, "body": "nit", "resolvable": true, "resolved": false, + "position": map[string]any{"new_path": "a.go", "new_line": 4}}}}, + }) + case "/projects/7/pipelines/77/jobs": + send(w, []any{ + map[string]any{"name": "test", "status": "failed"}, + map[string]any{"name": "lint", "status": "failed", "allow_failure": true}, + map[string]any{"name": "build", "status": "running"}, + }) + case base + "/merge_requests/5/diffs": + send(w, []any{map[string]any{"diff": "--- a/a.go\n+++ b/a.go\n@@ -1 +1,2 @@\n-x\n+y\n+z\n"}}) + default: + t.Errorf("asked %s", r.URL) + w.WriteHeader(http.StatusNotFound) + } + }) + s := newGitLabSource(withDefaults(config{Forge: "gitlab"}), nil) + d, err := s.detail(context.Background(), pullRequest{Host: "gitlab.com", Number: 5, Repository: struct { + NameWithOwner string `json:"nameWithOwner"` + }{"grp/sub/proj"}}) + if err != nil { + t.Fatal(err) + } + if d.Body != "line one\nline two" || d.HeadRefOid != "abc123" || !d.ViewerCanMerge || d.ChangedFiles != 3 { + t.Errorf("detail %+v", d) + } + if d.MergeStateStatus != "BLOCKED" || d.checks() != "PENDING" || d.ReviewDecision != "APPROVED" { + t.Errorf("state %q checks %q review %q", d.MergeStateStatus, d.checks(), d.ReviewDecision) + } + if got := d.RepoSettings.methods(); len(got) != 2 || d.RepoSettings.ViewerDefaultMergeMethod != "SQUASH" || !d.RepoSettings.AutoMergeAllowed { + t.Errorf("settings %+v", d.RepoSettings) + } + if d.HeadRef == nil || d.HeadRef.ID != "feat" || d.Additions != 2 || d.Deletions != 1 { + t.Errorf("head %+v +%d -%d", d.HeadRef, d.Additions, d.Deletions) + } + want := []reviewer{{"bo", "APPROVED"}, {"cy", "PENDING"}} + if fmt.Sprint(d.Reviewers) != fmt.Sprint(want) { + t.Errorf("reviewers %v", d.Reviewers) + } + if len(d.Comments) != 1 || d.Comments[0].Body != "hi" || len(d.Threads) != 1 || d.Threads[0].Path != "a.go" || d.Threads[0].Line != 4 { + t.Errorf("comments %+v threads %+v", d.Comments, d.Threads) + } + failing, pending := requiredCounts(d.Checks) + if len(d.Checks) != 3 || failing != 1 || pending != 1 || d.Checks[0].name() != "test" { + t.Errorf("checks %+v", d.Checks) + } +} + +func TestGitLabMergePinsTheHead(t *testing.T) { + var got []map[string]any + fakeGitLab(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != "PUT" || r.URL.Path != "/projects/grp/sub/proj/merge_requests/5/merge" { + t.Errorf("%s %s", r.Method, r.URL) + } + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + got = append(got, body) + if len(got) == 3 { + w.WriteHeader(http.StatusConflict) + send(w, map[string]any{"message": "SHA does not match HEAD of source branch"}) + return + } + send(w, mrJSON(5, nil)) + }) + s := newGitLabSource(withDefaults(config{Forge: "gitlab"}), nil) + d := &prDetail{pullRequest: pullRequest{Host: "gitlab.com", Number: 5}, HeadRefOid: "abc123"} + d.Repository.NameWithOwner = "grp/sub/proj" + if err := s.merge(context.Background(), d, "SQUASH", false); err != nil { + t.Fatal(err) + } + if err := s.merge(context.Background(), d, "MERGE", true); err != nil { + t.Fatal(err) + } + if got[0]["sha"] != "abc123" || got[0]["squash"] != true || got[0]["auto_merge"] != nil { + t.Errorf("merge now %v", got[0]) + } + if got[1]["sha"] != "abc123" || got[1]["squash"] != false || got[1]["auto_merge"] != true || got[1]["merge_when_pipeline_succeeds"] != true { + t.Errorf("auto-merge %v", got[1]) + } + if err := s.merge(context.Background(), d, "MERGE", false); err == nil || !strings.Contains(err.Error(), "changed since") { + t.Errorf("a moved head: %v", err) + } +} + +func TestGitLabDraftRewritesTheTitle(t *testing.T) { + title := "Draft: [WIP] fix it" + var mu sync.Mutex + fakeGitLab(t, func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + if r.Method == "PUT" { + var body map[string]string + _ = json.NewDecoder(r.Body).Decode(&body) + title = body["title"] + } + send(w, mrJSON(5, map[string]any{"title": title})) + }) + s := newGitLabSource(withDefaults(config{Forge: "gitlab"}), nil) + pr := pullRequest{Host: "gitlab.com", Number: 5} + pr.Repository.NameWithOwner = "grp/sub/proj" + if err := s.setDraft(context.Background(), pr, false); err != nil || title != "fix it" { + t.Fatalf("ready: %q %v", title, err) + } + if err := s.setDraft(context.Background(), pr, true); err != nil || title != "Draft: fix it" { + t.Fatalf("draft: %q %v", title, err) + } +} + +func TestGitLabCancelAutoMergeFallsBack(t *testing.T) { + var asked []string + fakeGitLab(t, func(w http.ResponseWriter, r *http.Request) { + asked = append(asked, r.URL.Path) + if strings.HasSuffix(r.URL.Path, "/cancel_auto_merge") { + w.WriteHeader(http.StatusNotFound) + return + } + send(w, mrJSON(5, nil)) + }) + d := &prDetail{pullRequest: pullRequest{Host: "gitlab.com", Number: 5}} + d.Repository.NameWithOwner = "grp/sub/proj" + if err := newGitLabSource(withDefaults(config{Forge: "gitlab"}), nil).disableAutoMerge(context.Background(), d); err != nil { + t.Fatal(err) + } + if len(asked) != 2 || !strings.HasSuffix(asked[1], "/cancel_merge_when_pipeline_succeeds") { + t.Fatalf("asked %v", asked) + } +} + +func TestGitLabUnauthorizedIsSignedOut(t *testing.T) { + fakeGitLab(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + }) + _, err := newGitLabSource(withDefaults(config{Forge: "gitlab"}), nil).list(context.Background(), tabMine, "") + if !errors.Is(err, errSignedOut) { + t.Fatalf("err = %v", err) + } +} + +func TestGitLabLabelLookups(t *testing.T) { + fakeGitLab(t, func(w http.ResponseWriter, r *http.Request) { + base := "/projects/grp/sub/proj/merge_requests" + switch r.URL.Path { + case base: + if r.URL.Query().Get("source_branch") != "feat" { + send(w, []any{}) + return + } + send(w, []any{mrJSON(4, map[string]any{"state": "closed"}), mrJSON(5, nil)}) + case base + "/5": + send(w, mrJSON(5, map[string]any{"head_pipeline": map[string]any{"status": "failed"}})) + case base + "/9": + w.WriteHeader(http.StatusNotFound) + default: + t.Errorf("asked %s", r.URL) + } + }) + c := newGLClient("gitlab.com") + found, err := c.prsForBranches(context.Background(), glRepo, []branchHead{{"feat", "grp/sub"}, {"other", ""}}) + if err != nil || len(found) != 1 { + t.Fatalf("%v %v", found, err) + } + if s := found[branchHead{"feat", "grp/sub"}]; s.Number != 5 || s.checks() != "FAILURE" { + t.Errorf("picked %+v", s) + } + byNum, err := c.prsByNumber(context.Background(), glRepo, []int{5, 9}) + if err != nil || len(byNum) != 1 || byNum[5].State != "OPEN" { + t.Fatalf("%v %v", byNum, err) + } +} + +func TestGitLabRepos(t *testing.T) { + fakeGitLab(t, func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + if q.Get("membership") != "true" || q.Get("order_by") != "last_activity_at" { + t.Errorf("asked %s", r.URL) + } + send(w, []any{map[string]any{"path_with_namespace": "grp/sub/proj", "last_activity_at": "2026-09-20T10:00:00Z"}}) + }) + rs, next, err := newGitLabSource(withDefaults(config{Forge: "gitlab"}), nil).repos(context.Background(), "") + if err != nil || next != "" || len(rs) != 1 || rs[0].Repo != glRepo { + t.Fatalf("%+v %q %v", rs, next, err) + } +} + +func TestGitLabPRFromPath(t *testing.T) { + for _, c := range []struct { + path string + number int + want string + }{ + {"/grp/proj/-/merge_requests/12", 12, "gitlab.com grp/proj#12"}, + {"/grp/sub/proj/-/merge_requests/12/", 12, "gitlab.com grp/sub/proj#12"}, + {"/grp/proj/-/merge_requests/13", 12, ""}, + {"/grp/proj/-/merge_requests/12/diffs", 12, ""}, + {"/grp/proj/-/issues/12", 12, ""}, + {"/grp/proj/pull/12", 12, ""}, + {"/proj/-/merge_requests/12", 12, ""}, + } { + r, n, ok := gitlabForge.prFromPath("GitLab.com", c.path, c.number) + got := "" + if ok { + got = fmt.Sprintf("%s %s/%s#%d", r.Host, r.Owner, r.Name, n) + } + if got != c.want { + t.Errorf("prFromPath(%q) = %q, want %q", c.path, got, c.want) + } + } + if gitlabForge.prHeadRef(7) != "refs/merge-requests/7/head" { + t.Fatal(gitlabForge.prHeadRef(7)) + } +} + +func TestGitLabNestedPaths(t *testing.T) { + old := theForge + t.Cleanup(func() { theForge = old }) + if _, ok := parseRemote("git@gitlab.com:grp/sub/proj.git"); ok { + t.Fatal("GitHub has no nested paths") + } + theForge = gitlabForge + r, ok := parseRemote("git@gitlab.com:grp/sub/proj.git") + if !ok || r != glRepo { + t.Fatalf("%+v", r) + } + if r, ok := typedRepo("gitlab.example.com/grp/sub/proj", "gitlab.com"); !ok || r.Host != "gitlab.example.com" || r.Owner != "grp/sub" { + t.Fatalf("typed %+v", r) + } + if r, ok := parseRepoKey("gitlab.com/grp/sub/proj"); !ok || r != glRepo { + t.Fatalf("key %+v", r) + } +} + +// GitLab has no review-requested list: its picker has no Review tab. +func TestGitLabHasNoReviewTab(t *testing.T) { + cfg := withDefaults(config{Forge: "gitlab"}) + m := newModel(nil, cfg, newGitLabSource(cfg, nil), "", nil) + m.width, m.height = 110, 34 + _, cells := m.tabBar() + for _, c := range cells { + if c.tab == tabReview { + t.Fatalf("the Review tab shows: %s", plain(m)) + } + } + if len(cells) != 2 { + t.Fatalf("cells %v", cells) + } +} + +func TestConfigChoosesTheForge(t *testing.T) { + path := filepath.Join(configDir(), "config.json") + if err := os.MkdirAll(configDir(), 0o700); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.Remove(path) }) + write := func(s string) { + if err := os.WriteFile(path, []byte(s), 0o600); err != nil { + t.Fatal(err) + } + } + write(`{"forge": "gitlab"}`) + cfg, err := loadConfig() + if err != nil || cfg.forge().name != "GitLab" || cfg.Hosts[0] != "gitlab.com" || !strings.Contains(cfg.StartPrompt, "glab mr view") { + t.Fatalf("%+v %v", cfg, err) + } + write(`{}`) + if cfg, err := loadConfig(); err != nil || cfg.forge().name != "GitHub" || cfg.Hosts[0] != "github.com" { + t.Fatalf("%+v %v", cfg, err) + } + write(`{"forge": "bitbucket"}`) + if _, err := loadConfig(); err == nil { + t.Fatal("an unknown forge is accepted") + } +} + +// loadAll skips a hidden tab: with the Review tab hidden, its load isn't +// fired, so no reply to it can flip the popup after the fact. +func TestNoReviewRequestedSkipsTheLoad(t *testing.T) { + for _, c := range []caps{{autoMerge: true}, {reviewRequested: true, autoMerge: true}} { + m := cappedModel(t, c) + m.ctx = context.Background() + m = drive(m, m.loadAll()) + if m.loaded[tabReview] && !c.reviewRequested { + t.Fatalf("loadAll loaded the hidden Review tab: %v", c) + } + if c.reviewRequested && !m.loaded[tabReview] { + t.Fatalf("a forge with the Review tab did not load it: %v", c) + } + } +} diff --git a/groups.go b/groups.go index 4b6c5c0..311fd72 100644 --- a/groups.go +++ b/groups.go @@ -131,13 +131,24 @@ func (m model) tabName(t tab, short bool) string { return m.repo.Name } +// tabShown says whether a tab is offered: a forge that can't list the PRs +// waiting on your review has no Review tab. +func (m model) tabShown(t tab) bool { + return t != tabReview || m.client.caps().reviewRequested +} + // tabBar is the popup's first line: the tabs, each with how many pull // requests it has (and a + while more are on their way), the one shown as a // pill, in line with the keys' pills along the bottom. The popup's name is // on its frame, which herdr draws. Too wide for the popup, the labels // shorten. On a PR's screen no tab is the one shown: they're the way back. func (m model) tabBar() (string, []tabCell) { - cells := []tabCell{{tab: tabMine}, {tab: tabReview}, {tab: tabRepo}} + var cells []tabCell + for _, t := range []tab{tabMine, tabReview, tabRepo} { + if m.tabShown(t) { + cells = append(cells, tabCell{tab: t}) + } + } var line string for _, short := range []bool{false, true} { line = " " diff --git a/herdr.go b/herdr.go index c0792dc..284c1e6 100644 --- a/herdr.go +++ b/herdr.go @@ -84,8 +84,9 @@ func isHerdrCode(err error, code string) bool { return errors.As(err, &he) && he.Code == code } -func notify(title, body string) { - _ = herdrCall("notification.show", map[string]any{"title": title, "body": body}, nil) +// notify shows a toast titled with the forge's name. +func notify(body string) { + _ = herdrCall("notification.show", map[string]any{"title": theForge.name, "body": body}, nil) } type paneInfo struct { diff --git a/labels.go b/labels.go index 135fbec..853c6a4 100644 --- a/labels.go +++ b/labels.go @@ -298,7 +298,7 @@ func spaceBranchOf(ctx context.Context, cfg config, w workspaceInfo) (spaceBranc // Seams for tests. var ( branchLookupFn = func(ctx context.Context, r repoRef, heads []branchHead) (map[branchHead]prStatus, error) { - return newClient(r.Host).prsForBranches(ctx, r, heads) + return theForge.api(r.Host).prsForBranches(ctx, r, heads) } nowFn = time.Now ) diff --git a/links.go b/links.go index 20b51d3..825d8f2 100644 --- a/links.go +++ b/links.go @@ -92,7 +92,7 @@ func runHandoff(arg string) error { } } if err != nil { - notify("GitHub", "Couldn't open "+p.PluginID+": "+err.Error()) + notify("Couldn't open " + p.PluginID + ": " + err.Error()) } return err } diff --git a/main.go b/main.go index 6842230..31d5123 100644 --- a/main.go +++ b/main.go @@ -46,6 +46,7 @@ func run(ctx context.Context, args []string) error { return nil } cfg, cfgErr := loadConfig() + useForge(cfg.forge()) if cfgErr != nil { switch { case args[0] == "tick": @@ -53,7 +54,7 @@ func run(ctx context.Context, args []string) error { // plugin log, and go on with the defaults. fmt.Fprintln(os.Stderr, "herdr-github: ignoring", cfgErr) case args[0] == "action": - notify("GitHub", cfgErr.Error()) + notify(cfgErr.Error()) return cfgErr default: return cfgErr @@ -109,7 +110,7 @@ func runAction(ctx context.Context, cfg config, name string) error { cwd = inv.FocusedPaneCwd } if err := openPicker(map[string]string{"HERDR_GITHUB_CWD": cwd}); err != nil { - notify("GitHub", "Couldn't open the picker: "+err.Error()) + notify("Couldn't open the picker: " + err.Error()) return err } return nil @@ -124,13 +125,13 @@ func runAction(ctx context.Context, cfg config, name string) error { } env := map[string]string{"HERDR_GITHUB_CWD": cwd, "HERDR_GITHUB_PANE": inv.FocusedPaneID, "HERDR_GITHUB_SPACE": inv.WorkspaceID} if err := openPicker(env); err != nil { - notify("GitHub", "Couldn't open the pull request: "+err.Error()) + notify("Couldn't open the pull request: " + err.Error()) return err } return nil case "demo": if err := openPicker(map[string]string{"HERDR_GITHUB_DEMO": "1"}); err != nil { - notify("GitHub", "Couldn't open the demo: "+err.Error()) + notify("Couldn't open the demo: " + err.Error()) return err } return nil @@ -138,13 +139,13 @@ func runAction(ctx context.Context, cfg config, name string) error { err := tick(ctx, cfg, true) switch { case !cfg.labelsOn(): - notify("GitHub", "Labels are off (\"labels\": false in config.json), so they were cleared.") + notify("Labels are off (\"labels\": false in config.json), so they were cleared.") case errors.Is(err, errSignedOut): - notify("GitHub", err.Error()) + notify(err.Error()) case err != nil: - notify("GitHub", "Couldn't refresh every label: "+err.Error()) + notify("Couldn't refresh every label: " + err.Error()) default: - notify("GitHub", "PR labels refreshed.") + notify("PR labels refreshed.") } return nil } @@ -159,16 +160,12 @@ func status(ctx context.Context, cfg config) error { fmt.Printf("%s: %v\n", h, err) continue } - var res struct { - Viewer struct { - Login string `json:"login"` - } `json:"viewer"` - } - if err := newClient(h).graphql(ctx, `query { viewer { login } }`, nil, &res); err != nil { - fmt.Printf("%s: gh has a token, but GitHub refused it: %v\n", h, err) + login, err := theForge.api(h).viewer(ctx) + if err != nil { + fmt.Printf("%s: %s has a token, but %s refused it: %v\n", h, theForge.cliName, theForge.name, err) continue } - fmt.Printf("%s: signed in as %s (through gh)\n", h, res.Viewer.Login) + fmt.Printf("%s: signed in as %s (through %s)\n", h, login, theForge.cliName) } fmt.Println("Labels:", map[bool]string{true: "on", false: "off"}[cfg.labelsOn()], "· config:", strings.TrimSpace(configDir()+"/config.json")) return nil diff --git a/popup.go b/popup.go index 350a087..3b34b97 100644 --- a/popup.go +++ b/popup.go @@ -22,7 +22,7 @@ func openPicker(env map[string]string) error { err := openPopup("picker", "85%", "80%", env) if isHerdrCode(err, "ui_busy") { if !endOwnPopup() { - notify("GitHub", "Another popup is open: close it (esc) and try again.") + notify("Another popup is open: close it (esc) and try again.") return err } err = openPopup("picker", "85%", "80%", env) diff --git a/repopicker.go b/repopicker.go index 2c8c79e..24b85fb 100644 --- a/repopicker.go +++ b/repopicker.go @@ -125,7 +125,7 @@ func (m model) takeRemoteRepos(msg remoteReposMsg) (model, tea.Cmd) { m.remoteLoading, m.remoteLoaded = false, true // Keep last time's list; say so only if there's none. if len(m.repoRemote) == 0 && m.menu != nil && m.menu.id == "repos" { - m.err = "Couldn't list your GitHub repos: " + msg.err.Error() + m.err = "Couldn't list your " + theForge.name + " repos: " + msg.err.Error() } return m.refreshRepoMenu(), nil } @@ -162,7 +162,7 @@ type repoEntry struct { func (m model) repoMenu() *menu { title := "Pull requests of which repo?" if !m.remoteLoaded && len(m.repoRemote) == 0 { - title += " (loading yours from GitHub…)" + title += " (loading yours from " + theForge.name + "…)" } mn := &menu{id: "repos", title: title, filterable: true} @@ -196,7 +196,7 @@ func (m model) repoMenu() *menu { g, ok := groups[k] if !ok { name := e.repo.Owner - if e.repo.Host != "github.com" { + if !theForge.isDefaultHost(e.repo.Host) { name = e.repo.Host + "/" + name } g = &group{name: name, rank: -1} @@ -294,22 +294,25 @@ var repoNamePart = regexp.MustCompile(`^[A-Za-z0-9_.-]+$`) // typedRepo reads "owner/repo" (on host) or "host/owner/repo". func typedRepo(q, host string) (repoRef, bool) { parts := strings.Split(q, "/") - if len(parts) == 3 && strings.Contains(parts[0], ".") { + if len(parts) >= 3 && strings.Contains(parts[0], ".") { host, parts = strings.ToLower(parts[0]), parts[1:] } - if len(parts) != 2 || !repoNamePart.MatchString(parts[0]) || !repoNamePart.MatchString(parts[1]) { + if len(parts) < 2 || (len(parts) > 2 && !theForge.nestedPaths) { return repoRef{}, false } - return repoRef{Host: host, Owner: parts[0], Name: parts[1]}, true + for _, p := range parts { + if !repoNamePart.MatchString(p) { + return repoRef{}, false + } + } + return repoRef{Host: host, Owner: strings.Join(parts[:len(parts)-1], "/"), Name: parts[len(parts)-1]}, true } func parseRepoKey(k string) (repoRef, bool) { - parts := strings.Split(k, "/") - if len(parts) != 3 { - return repoRef{}, false - } - r := repoRef{Host: parts[0], Owner: parts[1], Name: parts[2]} - return r, r.valid() + host, path, _ := strings.Cut(k, "/") + owner, name, ok := splitRepoPath(path, theForge.nestedPaths) + r := repoRef{Host: host, Owner: owner, Name: name} + return r, ok && r.valid() } // openRepoPicker opens the picker once the local choices are gathered; your @@ -328,8 +331,8 @@ func (m model) openRepoPicker() (tea.Model, tea.Cmd) { func (m model) switchRepo(r repoRef) (tea.Model, tea.Cmd) { m.repo = &r switch c := m.client.(type) { - case *githubSource: - m.client = newGitHubSource(m.cfg, &r) + case *githubSource, *gitlabSource: + m.client = theForge.newSource(m.cfg, &r) case *demoSource: c.setHome(r) } diff --git a/repos.go b/repos.go index 4619c23..1dfcf77 100644 --- a/repos.go +++ b/repos.go @@ -49,8 +49,8 @@ func parseRemote(raw string) (repoRef, bool) { return repoRef{}, false } path = strings.TrimSuffix(strings.Trim(path, "/"), ".git") - owner, name, ok := strings.Cut(path, "/") - if !ok || owner == "" || name == "" || strings.Contains(name, "/") { + owner, name, ok := splitRepoPath(path, theForge.nestedPaths) + if !ok { return repoRef{}, false } return repoRef{Host: strings.ToLower(host), Owner: owner, Name: name}, true @@ -137,15 +137,15 @@ func remoteFor(ctx context.Context, dir string, r repoRef) (remote, bool) { // remoteForCheckout is remoteFor for a checkout already chosen (mapped in // the config, say), where a remote may name the host by an SSH alias // ("git@work-github:o/r"): then owner and name are enough. Not for a remote -// on another GitHub you use: o/r there is a different repo. +// on another host of this forge you use: o/r there is a different repo. func remoteForCheckout(ctx context.Context, cfg config, dir string, r repoRef) (remote, bool) { if x, ok := remoteFor(ctx, dir, r); ok { return x, true } var found []remote for _, x := range remotesOf(ctx, dir) { - if cfg.knownHost(x.Repo.Host) || x.Repo.Host == "github.com" { - continue // a real GitHub host, and not r's + if cfg.knownHost(x.Repo.Host) || theForge.isDefaultHost(x.Repo.Host) { + continue // a real host of this forge, and not r's } if strings.EqualFold(x.Repo.Owner, r.Owner) && strings.EqualFold(x.Repo.Name, r.Name) { found = append(found, x) @@ -220,8 +220,8 @@ func cloneDest(cfg config, r repoRef) string { return filepath.Join(cfg.CloneRoot, r.Owner, r.Name) } -// clone clones r into its place under clone_root with gh, which knows how -// to authenticate for private repos and GitHub Enterprise. +// clone clones r into its place under clone_root, by the forge's own CLI, +// which knows how to authenticate for private repos. func clone(ctx context.Context, cfg config, r repoRef) (string, error) { dest := cloneDest(cfg, r) if _, err := os.Stat(dest); err == nil { @@ -232,8 +232,8 @@ func clone(ctx context.Context, cfg config, r repoRef) (string, error) { } ctx, cancel := context.WithTimeout(ctx, 10*time.Minute) defer cancel() - cmd := exec.CommandContext(ctx, "gh", "repo", "clone", r.String(), dest) - cmd.Env = append(os.Environ(), "GH_HOST="+r.Host, "GIT_TERMINAL_PROMPT=0") + cmd := theForge.cloneCmd(ctx, r.Host, r, dest) + cmd.Env = append(cmd.Env, "GIT_TERMINAL_PROMPT=0") if out, err := cmd.CombinedOutput(); err != nil { msg := strings.TrimSpace(string(out)) if msg == "" { diff --git a/screen_test.go b/screen_test.go new file mode 100644 index 0000000..dfb387c --- /dev/null +++ b/screen_test.go @@ -0,0 +1,24 @@ +package main + +import ( + "strings" + "testing" +) + +// The signed-out screen says exactly what main said for GitHub, through the +// forge's own words: the command you'd run yourself, and gh's token. +func TestSignedOutScreenWording(t *testing.T) { + m := demoModel(t, tabMine) + next, _ := m.Update(listMsg{tab: tabMine, err: &signedOutError{"github.com"}, gen: m.gen}) + m = next.(model) + got := plain(m) + for _, want := range []string{ + "GitHub isn't connected: gh has no working sign-in for github.com.", + "Press enter to run gh auth login here; it opens your browser.", + "The plugin uses gh's token and keeps none of its own.", + } { + if !strings.Contains(got, want) { + t.Errorf("screen lacks %q:\n%s", want, got) + } + } +} diff --git a/source.go b/source.go index 9097e58..e865746 100644 --- a/source.go +++ b/source.go @@ -39,12 +39,24 @@ type source interface { // repos pages through the repos you can reach, for the repo list: // the first page with cursor "", then each page's next until it's "". repos(ctx context.Context, cursor string) ([]repoInfo, string, error) + // caps says which tabs and actions this forge's PRs offer: a forge + // without review-requested lists doesn't show that tab, one without + // auto-merge doesn't offer it. + caps() caps +} + +// caps is what a source's PRs support. A forge without one of these +// (GitLab has no review-requested list) turns its tab or key off, and +// everything else keeps working. +type caps struct { + reviewRequested bool // the Review tab: PRs waiting on your review + autoMerge bool // merging once checks and reviews allow } // githubSource talks to every configured host, one client per host. type githubSource struct { cfg config - repo *repoRef // the repo the picker was opened in, if it's a GitHub one + repo *repoRef // the repo the picker was opened in, if it's on this forge mu sync.Mutex clients map[string]*ghClient } @@ -70,9 +82,7 @@ var tabQueries = map[tab]string{ } // list runs the tab's search. The repo tab pages through one search; Mine -// and Review search every host at once, and their cursor holds each host's -// place (JSON: host → cursor). A host you're signed out of is skipped while -// another answers; with none answering, the error stands. +// and Review search every host at once (fanOut). func (s *githubSource) list(ctx context.Context, t tab, cursor string) (page, error) { size := firstPage if cursor != "" { @@ -85,10 +95,18 @@ func (s *githubSource) list(ctx context.Context, t tab, cursor string) (page, er prs, next, err := s.client(s.repo.Host).searchPage(ctx, "is:pr is:open repo:"+s.repo.String()+" sort:updated-desc", size, cursor) return page{prs, next}, err } + return fanOut(s.cfg.Hosts, t, cursor, func(host, after string) ([]pullRequest, string, error) { + return s.client(host).searchPage(ctx, tabQueries[t], size, after) + }) +} +// fanOut lists a tab on every host at once. Its cursor holds each host's +// place (JSON: host → that host's cursor). A host you're signed out of is +// skipped while another answers; with none answering, the error stands. +func fanOut(hostList []string, t tab, cursor string, pageOf func(host, after string) ([]pullRequest, string, error)) (page, error) { hosts := map[string]string{} // host → where to continue if cursor == "" { - for _, h := range s.cfg.Hosts { + for _, h := range hostList { hosts[h] = "" } } else if err := json.Unmarshal([]byte(cursor), &hosts); err != nil { @@ -103,7 +121,7 @@ func (s *githubSource) list(ctx context.Context, t tab, cursor string) (page, er results := make(chan result, len(hosts)) for h, after := range hosts { go func() { - prs, next, err := s.client(h).searchPage(ctx, tabQueries[t], size, after) + prs, next, err := pageOf(h, after) results <- result{h, prs, next, err} }() } @@ -187,27 +205,36 @@ func isPartial(err error) bool { return errors.As(err, &p) } -// repos pages through each host in turn. The cursor is ":". A host that fails is skipped, unless it's the only one. +// repos pages through each host in turn (pageHosts). func (s *githubSource) repos(ctx context.Context, cursor string) ([]repoInfo, string, error) { + return pageHosts(s.cfg.Hosts, cursor, func(host, after string) ([]repoInfo, string, error) { + return s.client(host).viewerReposPage(ctx, after) + }) +} + +// pageHosts pages through each host in turn, its cursor ":". A host that fails is skipped, unless it's the only one. +func pageHosts(hosts []string, cursor string, pageOf func(host, after string) ([]repoInfo, string, error)) ([]repoInfo, string, error) { i, after := 0, "" if cursor != "" { n, rest, _ := strings.Cut(cursor, ":") i, _ = strconv.Atoi(n) after = rest } - if i >= len(s.cfg.Hosts) { + if i >= len(hosts) { return nil, "", nil } - rs, next, err := s.client(s.cfg.Hosts[i]).viewerReposPage(ctx, after) + rs, next, err := pageOf(hosts[i], after) switch { case next != "": next = strconv.Itoa(i) + ":" + next - case i+1 < len(s.cfg.Hosts): + case i+1 < len(hosts): next = strconv.Itoa(i+1) + ":" } - if err != nil && len(s.cfg.Hosts) > 1 { + if err != nil && len(hosts) > 1 { return rs, next, nil } return rs, next, err } + +func (s *githubSource) caps() caps { return caps{reviewRequested: true, autoMerge: true} } diff --git a/tui.go b/tui.go index 7b05046..3e02260 100644 --- a/tui.go +++ b/tui.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "os" - "os/exec" "sort" "strconv" "strings" @@ -256,7 +255,10 @@ func (m model) settle() model { // loadAll asks for every tab at once, so switching tabs doesn't wait. func (m model) loadAll() tea.Cmd { - cmds := []tea.Cmd{m.loadTab(tabMine, ""), m.loadTab(tabReview, ""), m.loadAgents()} + cmds := []tea.Cmd{m.loadTab(tabMine, ""), m.loadAgents()} + if m.tabShown(tabReview) { + cmds = append(cmds, m.loadTab(tabReview, "")) + } if m.repo != nil { cmds = append(cmds, m.loadTab(tabRepo, "")) } @@ -477,7 +479,7 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case loginDoneMsg: if msg.err != nil { - m.err = "gh auth login: " + msg.err.Error() + m.err = theForge.loginText + ": " + msg.err.Error() } return m.refreshAll() @@ -521,9 +523,12 @@ func (m model) refreshAll() (model, tea.Cmd) { m.gen++ m.prs, m.loaded, m.stale, m.paging, m.tabErr = map[tab][]pullRequest{}, map[tab]bool{}, map[tab]bool{}, map[tab]bool{}, map[tab]string{} m.mode, m.err = modeLoading, "" - if gs, ok := m.client.(*githubSource); ok { - // A new sign-in means new tokens: start the clients afresh. - m.client = newGitHubSource(m.cfg, gs.repo) + // A new sign-in means new tokens: start the clients afresh. + switch c := m.client.(type) { + case *githubSource: + m.client = theForge.newSource(m.cfg, c.repo) + case *gitlabSource: + m.client = theForge.newSource(m.cfg, c.repo) } m = m.settle() return m, tea.Batch(m.spin.Tick, m.loadAll()) @@ -614,9 +619,9 @@ func (m model) handleKey(k tea.KeyMsg) (tea.Model, tea.Cmd) { } return m.leave() case "tab", "shift+tab": - next := (m.tab + 1) % 3 + next := m.cycleTab(1) if k.String() == "shift+tab" { - next = (m.tab + 2) % 3 + next = m.cycleTab(-1) } return m.switchTab(next) case "left", "right": @@ -625,9 +630,9 @@ func (m model) handleKey(k tea.KeyMsg) (tea.Model, tea.Cmd) { break } if k.String() == "right" { - return m.switchTab((m.tab + 1) % 3) + return m.switchTab(m.cycleTab(1)) } - return m.switchTab((m.tab + 2) % 3) + return m.switchTab(m.cycleTab(-1)) case "up", "ctrl+p", "ctrl+k": m.move(-1) return m, nil @@ -685,6 +690,19 @@ func (m model) handleKey(k tea.KeyMsg) (tea.Model, tea.Cmd) { return m, cmd } +// cycleTab is the tab delta away: a forge without review-requested lists +// has no Review tab to land on. +func (m model) cycleTab(delta int) tab { + next := m.tab + for range 2 { + next = tab((int(next) + delta + 3) % 3) + if m.tabShown(next) { + return next + } + } + return m.tab +} + func (m model) switchTab(t tab) (tea.Model, tea.Cmd) { m.tab, m.err, m.flash = t, "", "" if !m.demo { @@ -718,14 +736,14 @@ func (m model) reloadLists() (model, tea.Cmd) { return m, tea.Batch(m.spin.Tick, m.loadAll()) } -// login runs `gh auth login` in the popup itself: it's a terminal, and gh's -// prompts and browser hand-off work as they would anywhere else. +// login runs the forge's sign-in in the popup itself: it's a terminal, and +// the CLI's prompts and browser hand-off work as they would anywhere else. func (m model) login() tea.Cmd { host := m.host if host == "" { - host = "github.com" + host = theForge.defaultHost } - return tea.ExecProcess(exec.Command("gh", "auth", "login", "--hostname", host, "--web"), func(err error) tea.Msg { + return tea.ExecProcess(theForge.loginCmd(host), func(err error) tea.Msg { return loginDoneMsg{err} }) } @@ -942,11 +960,11 @@ func (m model) view() string { if m.mode == modeSignedOut { host := m.host if host == "" { - host = "github.com" + host = theForge.defaultHost } - b.WriteString("\n " + styleHeader.Render("GitHub isn't connected") + ": gh has no working sign-in for " + host + ".\n\n") - b.WriteString(" Press enter to run " + styleTabOn.Render("gh auth login") + " here; it opens your browser.\n") - b.WriteString(styleDim.Render(" The plugin uses gh's token and keeps none of its own.") + "\n") + b.WriteString("\n " + styleHeader.Render(theForge.name+" isn't connected") + ": " + theForge.cliName + " has no working sign-in for " + host + ".\n\n") + b.WriteString(" Press enter to run " + styleTabOn.Render(theForge.loginText) + " here; it opens your browser.\n") + b.WriteString(styleDim.Render(" The plugin uses "+theForge.cliName+"'s token and keeps none of its own.") + "\n") if m.err != "" { b.WriteString("\n " + styleErr.Render(shorten(clean(m.err, false), max(10, m.width-4))) + "\n") } @@ -1107,7 +1125,7 @@ func (m model) viewRow(r row, selected bool) []string { name := "Pick a repo" if m.repo != nil { name = m.repo.String() - if m.repo.Host != "github.com" { + if !theForge.isDefaultHost(m.repo.Host) { name = m.repo.Host + "/" + name } left += styleHeader.Render(name) @@ -1163,7 +1181,7 @@ func (m model) repoName(pr pullRequest) string { r := pr.repo() for _, other := range m.prs[m.tab] { if o := other.repo(); o.Name == r.Name && !o.same(r) { - if pr.Host != "github.com" && pr.Host != "" { + if pr.Host != "" && !theForge.isDefaultHost(pr.Host) { return pr.Host + "/" + pr.Repository.NameWithOwner } return pr.Repository.NameWithOwner @@ -1605,6 +1623,9 @@ func runPicker(ctx context.Context, cfg config, demo bool) error { var client source var repo *repoRef if demo { + // The demo impersonates GitHub, whichever forge is configured. + useForge(githubForge) + cfg.Hosts = []string{githubForge.defaultHost} d := newDemoSource() home := d.homeRepo() client, repo = d, &home @@ -1617,12 +1638,12 @@ func runPicker(ctx context.Context, cfg config, demo bool) error { } } } - client = newGitHubSource(cfg, repo) + client = theForge.newSource(cfg, repo) } m := newModel(ctx, cfg, client, invoked, repo) if !demo { // Open on the tab you were last on, showing last time's lists. - if t, ok := lastTab(); ok { + if t, ok := lastTab(); ok && m.tabShown(t) { m.tab = t } m = m.useCache(readListCache(repo)) diff --git a/tui_test.go b/tui_test.go index 7ce4932..e1851e4 100644 --- a/tui_test.go +++ b/tui_test.go @@ -442,7 +442,7 @@ func TestSignedOutScreen(t *testing.T) { m := demoModel(t, tabMine) next, _ := m.Update(listMsg{tab: tabMine, err: &signedOutError{"github.com"}, gen: m.gen}) m = next.(model) - if m.mode != modeSignedOut || !strings.Contains(plain(m), "gh auth login") { + if m.mode != modeSignedOut || !strings.Contains(plain(m), theForge.loginText) { t.Fatalf("signed out:\n%s", plain(m)) } if _, cmd := m.Update(keyMsg("esc")); !quits(cmd) { diff --git a/worktree.go b/worktree.go index 2214e17..4b97ac4 100644 --- a/worktree.go +++ b/worktree.go @@ -150,7 +150,7 @@ func openWorktree(ctx context.Context, cfg config, pr pullRequest, dir string) ( // fork's PR, never into a local branch that might hold your work. src, dst := "refs/heads/"+pr.HeadRefName, "refs/remotes/"+rem.Name+"/"+pr.HeadRefName if pr.IsCrossRepository { - src, dst = fmt.Sprintf("refs/pull/%d/head", pr.Number), fmt.Sprintf("refs/remotes/%s/pr/%d", rem.Name, pr.Number) + src, dst = theForge.prHeadRef(pr.Number), fmt.Sprintf("refs/remotes/%s/pr/%d", rem.Name, pr.Number) } fctx, cancel := context.WithTimeout(ctx, 60*time.Second) _, fetchErr := git(fctx, dir, "fetch", "--quiet", "--no-tags", rem.Name, "+"+src+":"+dst) @@ -353,7 +353,7 @@ func kickoff(cfg config, workspaceID, rootPaneID, text string) error { case isHerdrCode(err, "agent_prompt_stalled"), isHerdrCode(err, "timeout"): // It may still be sitting in the input box: resending could // duplicate it, so stop here and say so. - notify("GitHub", "Typed the prompt but the agent didn't start. Press enter in the new space.") + notify("Typed the prompt but the agent didn't start. Press enter in the new space.") return err case isHerdrCode(err, "agent_blocked"): // A dialog came up: wait for it to be answered. @@ -363,7 +363,7 @@ func kickoff(cfg config, workspaceID, rootPaneID, text string) error { } time.Sleep(time.Second) } - notify("GitHub", "No agent came up in the new space, so the PR prompt wasn't sent.") + notify("No agent came up in the new space, so the PR prompt wasn't sent.") return errors.New("no ready agent before the deadline") }