GitLabgitlab-org

cli

main
ply5 git calls309 ms98 KiB2 cachedprotocol v2
143 lines7.4 KiBRaw

glab CLI agent instructions

Go-based GitLab CLI. Entrypoint: cmd/glab/main.go. Commands live under internal/commands/<noun>/<verb>/ (noun-first grammar, for example, glab mr create).

Common tasks

For each common task, the one non-discoverable pointer the agent can't infer from reading the tree.

  • Adding or editing a command — first read the matching block of [`.gitlab/duo/mr-review-instructions.yaml`](.gitlab/duo/mr-review-instructions.yaml). It is the canonical source for code conventions (command structure, flag handling, IO streams, API client and pagination, test setup, test discipline) and is what GitLab Duo Code Review grades MRs against. Blocks are scoped by fileFilters, so only the ones that match the file you are editing apply.
  • Writing a comment — default to not writing one. Document only what a competent Go reader cannot infer from the code; a comment that restates the line below it is noise, and rewording it does not help. Two gates run in lefthook pre-commit and the lint:comments CI job: go run ./scripts/comment-overlap rejects comments whose words are already carried by the adjacent code, and gocritic's commentedOutCode rejects commented-out code. go run ./scripts/comment-ratio -base origin/main reports comment volume on a change and is advisory. Godoc on exported symbols is exempt from the overlap gate by position, so it is not flagged for repeating its own symbol name. Full rules: the Comments block of [`.gitlab/duo/mr-review-instructions.yaml`](.gitlab/duo/mr-review-instructions.yaml).
  • Looking for a helper before writing a new one — the most common feedback on this project is "use the existing helper":
    • internal/cmdutils/ — flag wiring (EnableRepoOverride, EnableJSONOutput, NewEnumValue), the Factory interface.
    • internal/testing/cmdtest/ — test setup (SetupCmdForTest, NewTestFactory, WithStdin/WithBranch/WithGitLabClient).
    • internal/iostreams/ — all output (LogInfo*, LogError*, PrintJSON) and interactive prompts (Confirm, Input, Select).
    • internal/glrepo/ — repository interface.
    • internal/tableprinter/ — formatted text output.
    • internal/text/ — ExperimentalString, BetaString.
    • internal/config/schema.go — every configuration key is registered in KeySchema. Add a KeyDef entry to introduce a new key (it drives the blank config, config set validation, defaults, env-var resolution, legacy aliases, and keyring eligibility).
  • Copying from a canonical example:
    • New command: internal/commands/gpg-key/get/get.go.
    • Paginated list command: internal/commands/securefile/list/list.go.
    • Command tests with API mocks: internal/commands/gpg-key/get/get_test.go.
    • JSON output assertion test: internal/commands/runnercontroller/token/list/list_test.go.
  • Updating a command's docs — author the change in the Go source (Short, Long, Example, flag descriptions on the cobra.Command), run make gen-docs, commit the regenerated files under docs/source/ in the same commit. Never edit docs/source/ directly. make gen-docs also prunes pages for removed, deprecated, and hidden commands (and deletes any emptied directories), so never hand-delete pages under docs/source/. Instead regenerate the docs and commit the deletions.
  • Reviewing MR feedback — use the glab CLI end-to-end, not raw glab api:
    • Fetch: glab mr view <id> --output json.
    • Reply: glab mr note create --reply <discussion-id> --message "...".
    • Resolve: glab mr note resolve <discussion-id>. Pass only the discussion ID — a trailing MR ID argument errors out.
    • Add a new inline diff comment: glab mr note create --file <path> --line <N> (or --line N:M, or --old-line N for a deletion).
  • Creating an MR that references an issue — add /copy_metadata #<issue-id> on its own line in the description. GitLab copies the issue's labels and milestone, so the glab mr create --label flags aren't needed.
  • Naming a new command or writing a commit message — verbs follow noun-first grammar (create, list, get, update, delete); see CONTRIBUTING.md "Grammar" before introducing a new verb. Commit messages are Conventional Commits, enforced by the commit-msg hook through scripts/commit-lint (needs Node.js).

Verify changes before you push

Lefthook runs automatically on git push. Install it once with lefthook install. Install all tools with make bootstrap, which uses mise and .tool-versions.

shell
lefthook run pre-push  # build, lint against origin/main, test-changed, generated-doc/code check, markdown/rumdl/vale/lychee
make check             # test + lint

To skip hooks, use LEFTHOOK=0 git push or LEFTHOOK_EXCLUDE=pre-push git push. Treat these like --no-verify, an escape hatch for debugging the hooks themselves, not a workaround for slow builds. The hooks catch generated-doc/code drift and lint regressions before merge.

Common commands

shell
make build                                    # compile to ./bin/glab
make lint                                     # golangci-lint (full)
make fix                                      # golangci-lint fmt + run --fix
make test                                     # all unit tests (gotestsum, writes coverage-unit.txt/coverage-unit.xml)
make test-changed                             # tests changed packages + reverse deps against origin/main
make test-race                                # unit tests with -race
go test ./internal/commands/mr/note/...       # single package
go test ./internal/commands/mr/note/... -run TestCreate
make gen-docs                                 # regenerate docs/source/** from cobra definitions
make generate                                 # go generate ./... (mockgen mocks)

make test and make test-race clear VISUAL, EDITOR, and PAGER, unset CI, GL_HOST, and every GITLAB_*, GLAB_*, and CI_* variable, and set CI_PROJECT_PATH from the origin remote. Tests therefore pass inside a CI job. If you run go test directly and see environment-dependent failures, replicate that setup. A test that needs one of these variables must set it with t.Setenv.

[!note] Local vendor workflow: vendor/ is gitignored. Do not request vendor updates in merge requests. On an inconsistent-vendoring error, run go mod vendor to resync. Do not use -mod=mod, which bypasses the vendor directory instead of fixing it.

Integration tests

Integration tests are tagged //go:build integration, use the file suffix _integration_test.go, and use the test name suffix _Integration. They are not run by make test. To run them, use make integration-test-race, which adds -tags=integration. They call a real GitLab instance. Locally they are skipped unless both GITLAB_TEST_HOST and GITLAB_TOKEN_TEST are set (see GetHostOrSkip in test/helpers.go). The token must have the api scope. The glab duo tests require a GitLab Duo-enabled user.

Environment variables

  • GITLAB_TOKEN — API token. Overrides configuration.
  • GITLAB_HOST, GITLAB_URI, GL_HOST — Default GitLab instance, outside Git repositories.
  • GLAB_CONFIG_DIR — Overrides the configuration directory. Highest priority.
  • GLAB_ENABLE_CI_AUTOLOGIN=true — Together with GITLAB_CI=true, enables CI_JOB_TOKEN auto-login.
  • GLAB_DEBUG=true — Verbose logging for Git commands, expanded aliases, and DNS.
1# glab CLI agent instructions
3Go-based GitLab CLI. Entrypoint: `cmd/glab/main.go`. Commands live under
4`internal/commands/<noun>/<verb>/` (noun-first grammar, for example,
5`glab mr create`).
7## Common tasks
9For each common task, the one non-discoverable pointer the agent can't
10infer from reading the tree.
12- **Adding or editing a command** — first read the matching block of
13 [`.gitlab/duo/mr-review-instructions.yaml`](.gitlab/duo/mr-review-instructions.yaml).
14 It is the canonical source for code conventions (command structure,
15 flag handling, IO streams, API client and pagination, test setup,
16 test discipline) and is what GitLab Duo Code Review grades MRs
17 against. Blocks are scoped by `fileFilters`, so only the ones that
18 match the file you are editing apply.
19- **Writing a comment** — default to not writing one. Document only what a
20 competent Go reader cannot infer from the code; a comment that restates
21 the line below it is noise, and rewording it does not help. Two gates run
22 in lefthook pre-commit and the `lint:comments` CI job:
23 `go run ./scripts/comment-overlap` rejects comments whose words are already
24 carried by the adjacent code, and `gocritic`'s `commentedOutCode` rejects
25 commented-out code. `go run ./scripts/comment-ratio -base origin/main`
26 reports comment volume on a change and is advisory. Godoc on exported
27 symbols is exempt from the overlap gate by position, so it is not flagged
28 for repeating its own symbol name. Full rules: the `Comments` block of
29 [`.gitlab/duo/mr-review-instructions.yaml`](.gitlab/duo/mr-review-instructions.yaml).
30- **Looking for a helper before writing a new one** — the most common
31 feedback on this project is "use the existing helper":
32 - `internal/cmdutils/` — flag wiring (`EnableRepoOverride`,
33 `EnableJSONOutput`, `NewEnumValue`), the `Factory` interface.
34 - `internal/testing/cmdtest/` — test setup (`SetupCmdForTest`,
35 `NewTestFactory`, `WithStdin`/`WithBranch`/`WithGitLabClient`).
36 - `internal/iostreams/` — all output (`LogInfo*`, `LogError*`,
37 `PrintJSON`) and interactive prompts (`Confirm`, `Input`, `Select`).
38 - `internal/glrepo/` — repository interface.
39 - `internal/tableprinter/` — formatted text output.
40 - `internal/text/` — `ExperimentalString`, `BetaString`.
41 - `internal/config/schema.go` — every configuration key is registered
42 in `KeySchema`. Add a `KeyDef` entry to introduce a new key (it
43 drives the blank config, `config set` validation, defaults, env-var
44 resolution, legacy aliases, and keyring eligibility).
45- **Copying from a canonical example**:
46 - New command: `internal/commands/gpg-key/get/get.go`.
47 - Paginated list command: `internal/commands/securefile/list/list.go`.
48 - Command tests with API mocks:
49 `internal/commands/gpg-key/get/get_test.go`.
50 - JSON output assertion test:
51 `internal/commands/runnercontroller/token/list/list_test.go`.
52- **Updating a command's docs** — author the change in the Go source
53 (`Short`, `Long`, `Example`, flag descriptions on the `cobra.Command`),
54 run `make gen-docs`, commit the regenerated files under `docs/source/`
55 in the same commit. Never edit `docs/source/` directly. `make gen-docs`
56 also prunes pages for removed, deprecated, and hidden commands (and
57 deletes any emptied directories), so never hand-delete pages under
58 `docs/source/`. Instead regenerate the docs and commit the deletions.
59- **Reviewing MR feedback** — use the `glab` CLI end-to-end, not raw
60 `glab api`:
61 - Fetch: `glab mr view <id> --output json`.
62 - Reply: `glab mr note create --reply <discussion-id> --message "..."`.
63 - Resolve: `glab mr note resolve <discussion-id>`. Pass **only** the
64 discussion ID — a trailing MR ID argument errors out.
65 - Add a new inline diff comment:
66 `glab mr note create --file <path> --line <N>` (or `--line N:M`, or
67 `--old-line N` for a deletion).
68- **Creating an MR that references an issue** — add
69 `/copy_metadata #<issue-id>` on its own line in the description.
70 GitLab copies the issue's labels and milestone, so the
71 `glab mr create --label` flags aren't needed.
72- **Naming a new command or writing a commit message** — verbs follow
73 noun-first grammar (`create`, `list`, `get`, `update`, `delete`);
74 see `CONTRIBUTING.md` "Grammar" before introducing a new verb.
75 Commit messages are Conventional Commits, enforced by the
76 `commit-msg` hook through `scripts/commit-lint` (needs Node.js).
78## Verify changes before you push
80Lefthook runs automatically on `git push`. Install it once with
81`lefthook install`. Install all tools with `make bootstrap`, which uses
82`mise` and `.tool-versions`.
84```shell
85lefthook run pre-push # build, lint against origin/main, test-changed, generated-doc/code check, markdown/rumdl/vale/lychee
86make check # test + lint
87```
89To skip hooks, use `LEFTHOOK=0 git push` or
90`LEFTHOOK_EXCLUDE=pre-push git push`. Treat these like `--no-verify`, an
91escape hatch for debugging the hooks themselves, not a workaround for slow
92builds. The hooks catch generated-doc/code drift and lint regressions
93before merge.
95## Common commands
97```shell
98make build # compile to ./bin/glab
99make lint # golangci-lint (full)
100make fix # golangci-lint fmt + run --fix
101make test # all unit tests (gotestsum, writes coverage-unit.txt/coverage-unit.xml)
102make test-changed # tests changed packages + reverse deps against origin/main
103make test-race # unit tests with -race
104go test ./internal/commands/mr/note/... # single package
105go test ./internal/commands/mr/note/... -run TestCreate
106make gen-docs # regenerate docs/source/** from cobra definitions
107make generate # go generate ./... (mockgen mocks)
108```
110`make test` and `make test-race` clear `VISUAL`, `EDITOR`, and `PAGER`,
111unset `CI`, `GL_HOST`, and every `GITLAB_*`, `GLAB_*`, and `CI_*` variable,
112and set `CI_PROJECT_PATH` from the origin remote. Tests therefore pass inside
113a CI job. If you run `go test` directly and see environment-dependent
114failures, replicate that setup. A test that needs one of these variables must
115set it with `t.Setenv`.
117> [!note]
118> Local vendor workflow: `vendor/` is gitignored. Do not request vendor
119> updates in merge requests. On an inconsistent-vendoring error,
120> run `go mod vendor` to resync. Do not use `-mod=mod`, which bypasses the
121> vendor directory instead of fixing it.
123## Integration tests
125Integration tests are tagged `//go:build integration`, use the file suffix
126`_integration_test.go`, and use the test name suffix `_Integration`. They
127are not run by `make test`. To run them, use `make integration-test-race`,
128which adds `-tags=integration`. They call a real GitLab instance. Locally
129they are skipped unless both `GITLAB_TEST_HOST` and `GITLAB_TOKEN_TEST` are
130set (see `GetHostOrSkip` in `test/helpers.go`). The token must have the
131`api` scope. The
132`glab duo` tests require a GitLab Duo-enabled user.
134## Environment variables
136- `GITLAB_TOKEN` — API token. Overrides configuration.
137- `GITLAB_HOST`, `GITLAB_URI`, `GL_HOST` — Default GitLab instance,
138 outside Git repositories.
139- `GLAB_CONFIG_DIR` — Overrides the configuration directory. Highest priority.
140- `GLAB_ENABLE_CI_AUTOLOGIN=true` — Together with `GITLAB_CI=true`,
141 enables `CI_JOB_TOKEN` auto-login.
142- `GLAB_DEBUG=true` — Verbose logging for Git commands, expanded aliases, and
143 DNS.
Diagnostics5 git calls · 309 ms
CallStatusSizeTime0309 ms
discover200185 B2 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
git.response.bytes=185
git.server.agent=git/2.56.g1891de4-Linux
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch server-option object-format
git.server.fetch=shallow wait-for-done filter
git.protocol.version=2
git.pkt.frames=9
git.pkt.data=7
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=185
git.pkt.payload.max=35
ls-refs20058 KiB8 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
git.response.bytes=59849
git.response.cache=UPDATING
git.response.duration_ms=8
git.protocol.version=2
git.pkt.frames=731
git.pkt.data=730
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=59849
git.pkt.payload.max=143
git.ls_refs.count=730
git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=4273
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=combine:blob:none+tree:2
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=1
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=7
git.pkt.data=5
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=4273
git.pkt.payload.max=4173
git.sideband.band1.bytes=4173
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=11
git.pack.bytes=4173
git.fetch.wide.objects=11
git.fetch.wide.extra_bytes=3930
git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=32926
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=22
git.pkt.data=20
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=32926
git.pkt.payload.max=32046
git.sideband.band1.bytes=32046
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=80
git.pack.bytes=32046
git.pack.ofs_delta=36
git.pack.ref_delta=0
git.pack.chain.max=2
git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91
git.pack.full=44
Open pack map
fetch2003.4 KiB299 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=299
git.response.bytes=3449
git.response.cache=MISS
git.response.duration_ms=299
git.fetch.wants=23ab8ac2b2e2d3a1fc08f19a0e6cadc21bf7cfa8
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=3449
git.pkt.payload.max=3422
git.sideband.band1.bytes=3422
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://gitlab.com/gitlab-org/cli
Ref
refs/heads/main
Commit
0dd7574dce9e385c5c30540e6c15657adc6bdce9
cf-ray
a5e10ba67b81910d
Request
80416d19…
Protocol
v2 · sha1
Agent
git/2.56.g1891de4-Linux
Filter
advertised
Fetch
shallow wait-for-done filter
Capabilities
agent ls-refs fetch server-option object-format