Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions PLAN.md
Original file line number Diff line number Diff line change
@@ -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 "<host index>:<cursor>" 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 <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 <token>`: GitLab accepts PATs and OAuth
tokens (what `glab auth login --web` stores) both that way.
- Base `https://<host>/api/v4` (seam `glEndpointFn`). Project ids are the
URL-encoded path (`group%2Fsub%2Fproj`).
- 401 → `signedOutError`; other non-2xx → `GitLab: HTTP n: <message>`.
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
`/<namespace…>/<project>/-/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.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<clone_root>/<owner>/<repo>`, after asking. |
Expand All @@ -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
Expand Down
16 changes: 6 additions & 10 deletions agents.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
66 changes: 66 additions & 0 deletions caps_test.go
Original file line number Diff line number Diff line change
@@ -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()
}
21 changes: 19 additions & 2 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down Expand Up @@ -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))
Expand All @@ -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
Expand All @@ -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 {
Expand Down
4 changes: 3 additions & 1 deletion demo.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()] {
Expand All @@ -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} }
Loading