GitLabgitlab-org
cli
main
1# Custom review instructions for GitLab Duo Code Review.
2# Spec: https://docs.gitlab.com/user/duo_agent_platform/customize/review_instructions/
3#
4# When updating: keep rules concrete and grep-able. Reference helpers by
5# their package + name (for example, `cmdutils.NewEnumValue`,
6# `cmdtest.SetupCmdForTest`) rather than vague guidance like "follow the
7# canonical pattern". Inlined rule text is used verbatim by Duo; file
8# references get summarized.
9instructions:
10 # ============================================================
11 # GENERAL GO CODE
12 # ============================================================
14 - name: Error handling
15 fileFilters:
16 - '**/*.go'
17 instructions: |
18 Most basics here are enforced by `errcheck`, `errorlint`, and
19 `staticcheck ST1005` in `.golangci.yml`. The rules below are the
20 project-specific judgments those linters can't make.
21 1. For `cmd.Flags().MarkRequired(...)` / `MarkFlagsMutuallyExclusive(...)`
22 and similar cobra calls that return an error, use `cobra.CheckErr(err)`
23 rather than `_ = ...`.
24 2. When a function has a primary error and a deferred cleanup error
25 (e.g., `defer file.Close()`), combine them with `errors.Join(primary, cleanupErr)`.
26 Do not print one and return the other; that splits the failure across
27 surfaces.
28 3. For deferred cleanup that must affect the returned error, use a named
29 return value and a closure:
31 ```go
32 func doThing() (err error) {
33 f, err := os.Open(...)
34 if err != nil { return err }
35 defer func() { err = errors.Join(err, f.Close()) }()
36 ...
37 }
38 ```
39 4. When a function returns `(value, error)`, do not silently convert a
40 sentinel error into `return nil, nil`. Distinguish "not found" from
41 "real error" via an explicit sentinel (e.g., `errors.Is(err,
42 ErrNotFound)`) or by documenting the contract. Quiet `(nil, nil)`
43 on a sentinel hides bugs at the call site.
44 5. Do not silently fall back to a default value or behavior when an
45 error occurs. Surface the error (return it, or log via the
46 `internal/dbg` package); let the caller choose the fallback.
47 Eating the error and substituting a default is a debugging
48 dead-end.
50 - name: Go idioms (Go 1.26+)
51 fileFilters:
52 - '**/*.go'
53 instructions: |
54 The project is on Go 1.26+. The `modernize` linter enforces `any`,
55 `slices.*`, `strings.Cut*`, and similar Go 1.21+ idioms, and `gocritic`
56 (diagnostic + style tags) enforces many of the rest. The remaining
57 project-specific judgments:
58 1. Prefer `new(literalValue)` over `gitlab.Ptr(literalValue)` or
59 intermediate variables for pointer-to-literal. For example, write
60 `new(true)` rather than `gitlab.Ptr(true)`. Background: client-go 3.0
61 deprecates `gitlab.Ptr`.
62 2. Replace long `if / else if / else if` chains over the same value with
63 a `switch` statement. Enforced by `gocritic`'s `ifElseChain`; prefer
64 `switch` here over the inverted-guard style, which applies to a long
65 block gated by one condition.
66 3. Use `map[K]struct{}` (not `map[K]bool`) for set-membership data
67 structures — less allocation, clearer intent.
68 4. Prefer `iter.Seq` / `iter.Seq2` range-over-func iterators (Go 1.23+)
69 for paged or generator-style traversals where they're available.
70 5. Compile regular expressions once at package scope (`var fooRe = regexp.MustCompile(...)`),
71 not inside the hot path of a function.
73 - name: Naming
74 fileFilters:
75 - '**/*.go'
76 instructions: |
77 1. Names describe the value, not the code that produced it. If a function
78 no longer needs full `iostreams.IOStreams` and only writes, rename the
79 parameter to `out io.Writer`. If a parameter's role changes, rename it.
80 2. When a function has a side effect (creating files, mutating state),
81 the name should reflect it. Split `ConfigFile()` (read-only) from
82 `EnsureConfigFile()` (creates if missing).
83 3. New command sub-packages export a single constructor named `NewCmd`,
84 not `NewCmdList` / `NewCmdGet` / etc. — the package name already
85 carries the verb.
86 4. Avoid identifier names that only differ from existing ones by suffix
87 (e.g., `projectAccessTokenResponseJson` next to
88 `projectAccessTokenResponse`). Pick a name that distinguishes the role.
89 5. Unexport types, constants, and functions that are not used outside
90 their package. Public API surface is a maintenance commitment.
91 6. When introducing a helper, field, or option that parallels a
92 standard-library API (especially `net/http`), mirror the stdlib
93 name. Example: a helper that derives an HTTP proxy URL from
94 glab's config is named `ProxyFromConfig` (parallel to
95 `http.ProxyFromEnvironment`), the struct field is `proxy` (parallel
96 to `http.Transport.Proxy`), the client option is `WithProxy`.
97 Don't bake the protocol into a name when the field is
98 protocol-agnostic (e.g., a generic proxy config key should be
99 `proxy`, not `https_proxy`).
101 - name: Code reuse and dead code
102 fileFilters:
103 - '**/*.go'
104 instructions: |
105 Dead code, unused fields, and unused parameters are enforced by
106 `unused` and `unparam` in `.golangci.yml`. The remaining rules
107 are project-specific code-reuse judgments.
108 1. Before adding a new helper, search the codebase for existing equivalents.
109 Common locations: `internal/cmdutils/`, `internal/iostreams/`,
110 `internal/testing/cmdtest/`, `internal/api/`, `internal/glrepo/`,
111 `internal/tableprinter/`, `internal/text/`. **Reuse, do not re-derive.**
112 2. If a new function substantially duplicates an existing one (bulk vs.
113 single-item operations, paired endpoint builders), refactor: call the
114 single-item function in a loop, or extract a shared helper.
115 3. Tests that don't make a meaningful assertion (e.g., construct a value
116 and check `assert.NotNil`) must either be strengthened to test behavior
117 or removed. `assert.True(t, true)` placeholders are not acceptable.
118 4. Function signatures should accept only the values they actually use.
119 If a helper only needs `note.Position`, take `*gitlab.NotePosition`,
120 not `*gitlab.Note`. Avoid passing `cmdutils.Factory` into helpers —
121 pass the resolved `glrepo.Interface` / `*gitlab.Client` / branch
122 string directly.
123 5. Prefer returning parsed/typed values (e.g., `*url.URL`, `time.Duration`)
124 over strings that the caller must re-parse. The parser belongs next
125 to the producer.
126 6. Inline single-use, single-line helpers at the call site unless the
127 helper carries a meaningful name. A two-statement helper called from
128 one place is rarely worth the indirection.
129 7. For ANSI-color stripping in tests, use `github.com/acarl005/stripansi`
130 (already a project dep) — see `internal/commands/schedule/list/list_test.go`.
131 Don't hand-roll regex stripping.
133 - name: Comments
134 fileFilters:
135 - '**/*.go'
136 instructions: |
137 `scripts/comment-overlap` rejects comments whose every word is already
138 carried by the adjacent code, and `gocritic`'s `commentedOutCode`
139 rejects commented-out code. Do not re-flag either. Those gates are
140 deliberately conservative and leave two gaps worth reviewing:
141 1. Partial restatement passes the gate. A comment only has to add one
142 word the code lacks to survive it, so `// Trim whitespace from the
143 line first` above `line = strings.TrimSpace(line)` still ships.
144 Document only what a competent Go reader cannot infer from the code,
145 and delete a restating comment rather than rewording it.
146 2. Godoc length is unenforced. `staticcheck` ST1020-ST1022 check the
147 form of a doc comment, nothing checks whether it earns its lines,
148 and doc comments are the larger share of comment volume in this
149 repo. Keep godoc to what the name and signature do not convey.
151 In both cases the test is whether the comment carries *why* — a
152 non-obvious constraint, an ordering requirement, an upstream bug being
153 worked around, a rejected alternative. Prose narrating *what* the code
154 does is the common failure.
156 - name: Control flow
157 fileFilters:
158 - '**/*.go'
159 instructions: |
160 1. Prefer inverted-guard / early-return style: when a long block is gated
161 by a single condition, flip it to `if !cond { return ... }` so the
162 happy path is unindented.
163 2. Declare variables as close to their use as possible. Don't pre-declare
164 at function top when only an inner block needs them.
165 3. Thread `context.Context` from `cmd.Context()` through every function
166 that calls into the GitLab client or another context-aware API. Pass
167 it via `gitlab.WithContext(ctx)` to client-go methods. Never drop the
168 context partway down the call chain.
170 # ============================================================
171 # COMMANDS
172 # ============================================================
174 - name: Command structure
175 fileFilters:
176 - 'internal/commands/**/*.go'
177 - '!**/*_test.go'
178 instructions: |
179 New (sub-)commands under `internal/commands/**` must follow the
180 "Command Structure" pattern in `CONTRIBUTING.md:185-195`:
182 1. Each (sub-)command is in its own package. The file where the cobra
183 command is defined is named the same as the package.
184 2. The command is created by a factory function named `NewCmd` (no
185 package-name suffix like `NewCmdList`) that takes a single argument:
186 the `cmdutils.Factory`.
187 3. Define an unexported `options` struct (just `options`, not
188 `xxxOptions`) inside the package. Methods and fields on `options` are
189 not exported. Optional constructor named `newOptions`.
190 4. In `NewCmd`, instantiate `opts := &options{...}` and pre-assign
191 factory dependencies onto the struct: `io: f.IO()`,
192 `baseRepo: f.BaseRepo`, `gitlabClient: f.GitLabClient`, etc.
193 5. Create the cobra command in a local `cmd` variable.
194 6. If multiple flags are added, retrieve `cmd.Flags()` once into a local
195 `fl` variable and use `fl` for all registrations.
196 7. Split logic into three methods on `*options`:
197 - `complete(cmd *cobra.Command, args []string) error` — populate
198 `opts` from CLI input.
199 - `validate() error` — validate the completed options beyond what
200 cobra can enforce.
201 - `run(ctx context.Context) error` — execute the business logic.
202 Only implement the methods you actually need.
203 8. The `cobra.Command.RunE` calls `complete` → `validate` → `run` and
204 passes `cmd.Context()` to `run`. **No business logic, validation, or
205 API calls in `RunE` itself.**
206 9. Commands must never read from or write to `os.Stdin/Stdout/Stderr`
207 directly. Always go through `opts.io` (an `*iostreams.IOStreams`
208 assigned from `f.IO()`).
209 10. If a needed seam is missing on `cmdutils.Factory` (e.g., for
210 subprocess execution), add it to the factory rather than introducing
211 a package-level `var foo = func(...)` shim. The factory exists to
212 provide test seams cleanly.
214 Canonical reference: `internal/commands/gpg-key/get/get.go`.
216 - name: Command documentation
217 fileFilters:
218 - 'internal/commands/**/*.go'
219 - '!**/*_test.go'
220 instructions: |
221 CLI documentation is generated from Go source files by `make gen-docs`.
222 The following rules apply to the documentation fields of `cobra.Command`
223 definitions.
225 Short description (`Short` field):
226 1. Write in the imperative mood. For example: `Create a new merge request.`
227 2. End with a period.
228 3. Do not duplicate the command name.
229 4. For experimental commands, append `(EXPERIMENTAL)`.
231 Synopsis (`Long` field):
232 5. All new commands must include a `Long` field.
233 6. Do not repeat information already in the `Short` field.
234 7. Use lists for multiple constraints, input types, or behavioral differences.
235 8. If the command requires a minimum GitLab version, state it.
236 For example: `This command requires GitLab 17.0 or later.`
237 9. **Do not reference underlying REST or GraphQL endpoint paths in
238 user-facing `Long` text.** Describe what the user gets, not how it's
239 implemented. Internals leak into docs and rot.
240 10. Document environment variables via the `cobra.Command.Annotations`
241 map (key: `help:environment`), not inside `Long`.
242 11. Write each paragraph in `Long` as one source line. Cobra emits
243 `Long` verbatim, so hard-wrapped source stays hard-wrapped in the
244 terminal — the terminal then re-wraps around the source breaks,
245 producing orphan fragments. Bullets, section headers, and
246 `Example` lines are exempt.
248 Usage line / positional arguments (`Use` field):
249 12. Format positional arguments with these conventions:
250 - Required: `<arg>` (e.g., `glab mr view <id>`).
251 - Optional: `[<arg>]` (e.g., `glab ci trace [<job-id>]`).
252 - One of several, required: `<id | branch | url>`
253 (e.g., `glab mr checkout <id | branch | url>`).
254 - One of several, optional: `[<id | branch>]`
255 (e.g., `glab mr note list [<id | branch>]`).
257 Experimental and beta features:
258 13. Use `text.ExperimentalString` or `text.BetaString` from
259 `internal/text/text.go`. Do not copy these strings manually.
260 14. When only a flag is experimental, prepend `(EXPERIMENTAL)` to its
261 description and add a note in `Long` explaining feature flag
262 requirements.
264 Examples (`Example` field):
265 15. Every command must include at least one realistic example. Do not
266 use examples that only repeat the command syntax.
267 16. Examples live on the leaf command they apply to, not on parent
268 group commands.
269 17. Annotate examples with an inline comment using `# Comment text`
270 above the command. Lead with the simplest realistic invocation and
271 annotate even that one — explicit beats implicit for users scanning
272 `--help`.
273 18. For commands with many options, show the most common combinations first.
274 19. Use `heredoc.Doc(\`...\`)` (from `github.com/MakeNowJust/heredoc/v2`)
275 for multi-line `Long` and `Example` content. Indent with tabs (the
276 heredoc package strips them). Never build these fields by
277 concatenating quoted literals with embedded `\n`:
278 ```go
279 Long: "First line.\n\n" +
280 "Second line.",
281 ```
282 Error and log messages are out of scope.
283 20. A heredoc block is a Go raw string, so it cannot contain a backtick
284 or an escape sequence — a literal `\n` renders as the two characters
285 `\` and `n`. If the content needs either, use `heredoc.Docf` with
286 `%[1]s` in place of each backtick and `` "`" `` as the final
287 argument:
288 ```go
289 Long: heredoc.Docf(`
290 Use %[1]s--foo%[1]s to enable foo.
291 `, "`"),
292 ```
293 Reference: `internal/commands/mr/note/mr_note_create.go`.
295 Flag descriptions:
296 21. Start each flag description with a capital letter and end with a period.
297 22. Use angle-bracket placeholders for user-supplied values:
298 `<username>`, `<branch>`, `<id>`.
299 23. Do not manually annotate boolean flag defaults. pflag automatically
300 appends `(default true)` for boolean flags whose default is `true`.
301 Do not add it manually. No default annotation is required for boolean
302 flags whose default is `false`; do not add `(default false)`.
303 24. Use standard metavars for common value types: `username` for a
304 username, `string` for a branch name / file path / output format,
305 `int` for an integer ID.
306 25. For output-format flags, use `-F, --output [text | json]` as the
307 canonical form.
308 26. For slice flags (`StringSliceVar`, `Int64SliceVar`, etc.), include
309 the phrase: `Multiple <items> can be comma-separated or specified by
310 repeating the flag.` Use `StringArrayVar` if comma-separation should
311 NOT be supported.
312 27. Do not use `-v` as a shorthand for anything — it collides with
313 `--verbose` and `--version` conventions.
315 - name: Help text sources
316 fileFilters:
317 - 'internal/**/*.go'
318 - '!**/*_test.go'
319 instructions: |
320 1. Do not embed help text from a sidecar `.md` file with `//go:embed`.
321 Inline the content in the Go source via `heredoc.Doc`. Sidecar
322 files bypass the CI markdown lint glob and split help text
323 across two files without a corresponding readability win.
324 `make check-embed` enforces this.
326 - name: Bundled skills
327 fileFilters:
328 - 'internal/commands/**/*.go'
329 - 'internal/commands/skills/bundled/assets/**/SKILL.md'
330 - '!**/*_test.go'
331 instructions: |
332 Bundled agent skills live in `internal/commands/skills/bundled/assets/`:
333 - `glab-stack/SKILL.md` covers `internal/commands/stack/**`.
334 - `glab/SKILL.md` covers general command usage across `glab`.
336 When an MR changes a command's user-visible contract, check whether
337 the matching `SKILL.md` still describes it correctly. A contract
338 change is any of: the command's `Use` or arguments, a flag that
339 is added, renamed, or removed, a new or removed TTY requirement,
340 prompt, or editor, or new required follow-up steps.
342 If the skill now gives instructions that would fail, hang, or
343 leave work unfinished, and the MR does not update that `SKILL.md`,
344 ask for the skill to be updated in the same MR. If the MR does
345 update the skill, check that each command it shows doesn't reach a
346 prompt, editor, or TTY check with the flags shown. Do not flag
347 internal refactors, test-only changes, or help-text wording changes.
349 When an MR edits a `SKILL.md`, with or without code changes, check
350 for what `TestBundledSkillsUseRealCommandsAndFlags` can't see: flags
351 that become required under certain conditions, and follow-up steps
352 the command needs before the work is finished. That test already
353 checks that every command and flag the skill mentions exists.
355 - name: Flag handling
356 fileFilters:
357 - 'internal/commands/**/*.go'
358 - '!**/*_test.go'
359 instructions: |
360 1. Prefer cobra's built-in flag/argument helpers over manual checks:
361 - `cmd.MarkFlagsMutuallyExclusive("a", "b")` instead of hand-rolled
362 `if foo != "" && bar != "" { return error }`.
363 - `cmd.MarkFlagsRequiredTogether("a", "b")`.
364 - `cmd.MarkFlagsOneRequired("a", "b")` when at least one is required.
365 - `cmd.MarkFlagRequired("flag")`.
366 - `Args: cobra.ExactArgs(N)` / `cobra.NoArgs` / `cobra.RangeArgs(...)`
367 instead of manual `len(args) != N` checks in `RunE`/`complete`.
368 For commands that take no positional arguments, use `cobra.NoArgs`,
369 never `cobra.ExactArgs(0)` — `NoArgs` names the unexpected argument
370 in its error. Enforced by `make check-args`.
371 2. For closed-set string flags, use `cmdutils.NewEnumValue(allowedValues,
372 defaultValue)` from `internal/cmdutils/enum_flag.go`. Do not validate
373 the string by hand in `complete`/`validate`.
374 3. Use typed cobra flag variants where available: `Int64Var`, `BoolVar`,
375 `TimeVar`, etc. Do not parse times/numbers from `StringVar` by hand.
376 4. To target a project, use `cmdutils.EnableRepoOverride(cmd, f)` from
377 `internal/cmdutils/repo_override.go` (`-R/--repo`). Do not invent a
378 custom `--project` flag.
379 5. For group-scoped commands, use `cmdutils.GroupOverride`.
380 6. When `-R`, `--group`, and `--instance` coexist, mark them mutually
381 exclusive: `cmd.MarkFlagsMutuallyExclusive("repo", "group", "instance")`.
382 7. Required flags are often a "bad" UX choice — prefer the first
383 positional argument when there's a clear primary subject (e.g., the
384 token ID, the runner ID).
385 8. To detect whether a flag was explicitly set by the user (vs. left
386 at its default), use `cmd.Flags().Changed("<name>")`. Do not infer
387 "unset" by comparing the bound value to its default — that breaks
388 when the user explicitly passes the default value, and it makes the
389 "no flag" case impossible to distinguish from "flag = default".
391 - name: IO streams and output
392 fileFilters:
393 - 'internal/commands/**/*.go'
394 - '!**/*_test.go'
395 instructions: |
396 The rules below are the project-specific output conventions.
397 1. For JSON output, use `opts.io.PrintJSON(v)` from
398 `internal/iostreams/print_json.go`. `PrintJSON` handles `--jq`
399 filtering and the nil-slice-to-`[]` normalization.
400 2. To register the canonical `-F/--output [text | json]` flag plus
401 `--jq`, use `cmdutils.EnableJSONOutput(cmd)` from
402 `internal/cmdutils/output_format.go`. Do not invent a separate
403 `--json` boolean.
404 3. **JSON output is for machines, not humans.** Do not pretty-print or
405 wrap it. Users can pipe to `jq` themselves.
406 4. For table output, use `internal/tableprinter` (`NewTablePrinter()`,
407 `AddRow(...)`, `String()`, `SetIsTTY(...)`).
408 5. For interactive prompts, use the helpers on `IOStreams`:
409 `Confirm`, `Input`, `Select`, `MultiSelect`, `Password`, `Multiline`,
410 `Editor`, `DirectEditor`. Do not hand-roll `fmt.Scanln` confirmation
411 loops. Check `io.PromptEnabled()` / `io.IsInteractive()` before
412 prompting so `NO_PROMPT` and non-TTY users are respected.
413 6. For terminal hyperlinks, use `io.Hyperlink(displayText, targetURL)`.
415 - name: API client and pagination
416 fileFilters:
417 - 'internal/**/*.go'
418 instructions: |
419 1. For commands tied to one repo, use `f.GitLabClient()`. For multi-repo
420 operations, use `f.ApiClient(host)`. Don't construct `*gitlab.Client`
421 directly in command code.
422 2. For unauthenticated flows (e.g., release-note fetching), use
423 `api.NewClientFromConfig(host, config.NewBlankConfig(), ...)`. Do not
424 drop down to `net/http` or `http.Get` for GitLab endpoints — even for
425 downloads, prefer the `gitlab.Client`.
426 3. Pass `gitlab.WithContext(ctx)` (from `cmd.Context()`) to every
427 client-go call. This is non-optional.
428 4. For paginated list endpoints, use `gitlab.ScanAndCollect` (or
429 `gitlab.Scan2` iterators). Do not hand-roll `for page := 1;` loops.
430 See `internal/cmdutils/cmdutils.go:92` for the canonical pattern.
431 5. For HTTP status checks, use `resp.HasStatusCode(http.StatusXxx)` —
432 never compare integers like `resp.StatusCode == 200`. Always use
433 `http.Status*` constants over magic numbers.
435 - name: Package layering
436 fileFilters:
437 - 'internal/commands/**/*.go'
438 - '!**/*_test.go'
439 instructions: |
440 1. API-shape concerns belong in an `api` (sub-)package, not in command
441 packages or `utils` packages. GraphQL queries, REST endpoint
442 construction, response struct definitions, case normalization for API
443 enums — these go in `internal/api/` or a command-local `api/`
444 subpackage.
445 2. Command packages should focus on CLI surface: flag parsing, prompts,
446 output formatting, calling into the api layer.
447 3. Do not import one command package from another. Shared command-level
448 utilities go in `internal/cmdutils/` (or a new shared package), not
449 a sibling command.
450 4. Helpers that take `io *iostreams.IOStreams` should put it as the first
451 parameter to mirror the standard-library convention of `io.Writer`-
452 first.
454 - name: Config and environment
455 fileFilters:
456 - 'internal/**/*.go'
457 instructions: |
458 1. New configuration keys (global or per-host) are declared in
459 `KeySchema` in `internal/config/schema.go` as a `KeyDef` entry.
460 The schema drives the blank config, `config set` validation,
461 defaults, env-var resolution, legacy aliases, and keyring
462 eligibility — do not read settings ad-hoc from disk or env.
463 2. Set `KeyDef.EnvVars` to declare environment variables that
464 override a key (the uppercase form of the key name is the
465 default when EnvVars is empty). Do not call `os.LookupEnv` /
466 `os.Getenv` in command code for settings that have, or should
467 have, a config-file equivalent.
468 3. Document environment variables on the `cobra.Command.Annotations`
469 map (key: `help:environment`), not in free-form `Long` text — that
470 placement is also surfaced in generated docs.
472 - name: Deprecations
473 fileFilters:
474 - 'internal/**/*.go'
475 instructions: |
476 1. When deprecating a flag with `cmd.Flags().MarkDeprecated(...)`, write
477 the message as a sentence continuation: Cobra prepends
478 `Flag --<flag> has been deprecated, ` (ending in a comma), so start
479 your message with a lowercase letter and end with a period. For
480 example, `use --output instead.` renders as
481 `Flag --output-format has been deprecated, use --output instead.`.
482 2. When the deprecated flag has a direct replacement, end the message
483 with `use --<replacement> instead.`. When there is no replacement,
484 describe the resulting behavior. For example, `tracking is enabled by default.`.
485 3. Avoid time-relative words like `now` or `currently` in deprecation
486 messages.
487 4. When deprecating an environment variable, update the `help:environment`
488 annotation in `root.go`: remove the deprecated entry, add the
489 replacement with a full description, keep all entries in alphabetical
490 order, and mirror the change in the README's environment variables
491 section.
493 # ============================================================
494 # TESTS
495 # ============================================================
497 - name: Test setup
498 fileFilters:
499 - 'internal/**/*_test.go'
500 instructions: |
501 1. Use `cmdtest.SetupCmdForTest(t, NewCmd, parseFlags, opts...)` from
502 `internal/testing/cmdtest/factory.go` to set up command tests. It
503 returns a `CmdExecFunc` you can call with the command's args.
504 2. Configure test state with `FactoryOption`s — see
505 `internal/testing/cmdtest/factory.go` for the full list:
506 `WithStdin`, `WithBranch`, `WithBaseRepo`, `WithGitLabClient`,
507 `WithApiClient`, `WithBuildInfo`, `WithExecutor`, `WithGitRunner`,
508 `WithConsole`, etc.
509 3. **If you need a seam that isn't there, add a new `FactoryOption` to
510 `cmdtest`** — do not hand-roll factory wiring inline in the test, and
511 do not introduce a package-level `var xxx = func(...)` shim in
512 production code to be overridden by the test.
513 4. For GitLab API mocking, use the client-go testing package:
514 `gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"`.
516 ```go
517 tc := gitlabtesting.NewTestClient(t)
518 tc.MockUsers.EXPECT().GetGPGKey(int64(123)).Return(testKey, nil, nil)
519 exec := cmdtest.SetupCmdForTest(t, NewCmd, false, cmdtest.WithGitLabClient(tc.Client))
520 ```
522 **Do not introduce new `httpmock`-based HTTP responders** for code
523 paths that go through client-go. Migrate existing HTTP mocks when
524 touching files in the same package.
525 5. For mock call ordering, use `gomock.InOrder(...)`.
526 6. Canonical reference: `internal/commands/gpg-key/get/get_test.go`;
527 JSON-assertion pattern: `internal/commands/runnercontroller/token/list/list_test.go`.
529 - name: Test discipline
530 fileFilters:
531 - 'internal/**/*_test.go'
532 instructions: |
533 Many test discipline basics are enforced by linters in `.golangci.yml`:
534 `testifylint` (use testify, `require` before indexing, `assert.Empty`
535 over `assert.Equal(t, "", ...)`, no `require` in HTTP handlers),
536 `tparallel` (`t.Parallel`), `usetesting` (`t.TempDir` / `t.Chdir` /
537 `t.Setenv`). The rules below are the project-specific judgments those
538 linters can't make.
539 1. New behavior gated by a flag, argument shape, or branch must include
540 a test for each meaningful path — including the "no flag set",
541 "invalid input", and "default" branches. A new `--<flag>` must not
542 ship without an exercising test.
543 2. When asserting on a command's JSON output, `json.Unmarshal` into a
544 typed struct and assert on fields. Do not substring-match on the raw
545 JSON text (`assert.Contains(out, '"id": 1')`). Reference:
546 `internal/commands/runnercontroller/token/list/list_test.go`.
547 3. **Test the user-visible behavior of the command**, not the
548 configuration plumbing or internal field assignments. If a test
549 constructs `options{}` directly and checks a field, it probably
550 should drive the command through `cmdtest.SetupCmdForTest` instead.
551 4. Prefer flat per-case assertions over loops. `for _, tc := range
552 testCases { tc.run() }` is fine for table-driven tests with shared
553 setup, but don't loop over a slice just to assert each element —
554 spell out the asserts (`assert.Equal(t, tokens[0].ID, results[0].ID)`,
555 `assert.Equal(t, tokens[1].ID, results[1].ID)`) so failures point at
556 the specific element.
557 5. When adding a flag-aware test variant, keep the original no-flag
558 test as well. Do not rename / repurpose existing baseline tests —
559 that quietly removes coverage. Add new tests alongside, don't
560 replace.
561 6. When adding behavior to one of a set of parallel sibling commands
562 (e.g., `token list` for project / group / personal tokens), add
563 the equivalent test in each sibling package — otherwise coverage
564 drifts asymmetrically.
565 7. `cmdtest.SetupCmdForTest` produces non-TTY IOStreams by default.
566 Don't reach for `t.Setenv("NO_COLOR", ...)` or other TTY-affecting
567 env hacks — if you need different behavior, pass a `FactoryOption`
568 (`cmdtest.WithIOStreamsOverride` or similar) rather than mutating
569 process environment.
570 8. Prefer test-local fixtures over package-level `var` blocks unless
571 the fixture is genuinely shared by multiple tests. Local fixtures
572 make ownership and lifetime obvious.
574 # ============================================================
575 # SHELL SCRIPTS
576 # ============================================================
578 - name: Shell scripts
579 fileFilters:
580 - 'scripts/**/*.sh'
581 - '*.sh'
582 instructions: |
583 1. Write usage messages and error output to stderr: `echo "..." >&2`.
584 User-consumable program output goes to stdout; diagnostics go to stderr.
585 2. Use a direct shebang (`#!/usr/bin/env bash` or `#!/bin/sh`) and make
586 the script executable. Do not invoke scripts with `bash ./script.sh`
587 from other scripts or CI config — call the script directly.
588 3. Validate required environment variables explicitly at the top of the
589 script (e.g., `: "${APPSTORE_CONNECT_API_KEY_FILE:?must be set}"`).
590 A surprising `:` mount or missing var should error early, not silently.
591 4. Use `set -euo pipefail` for new scripts.
593 # ============================================================
594 # PROJECT-LEVEL / DEPENDENCIES
595 # ============================================================
597 - name: Dependencies
598 fileFilters:
599 - 'go.mod'
600 - 'go.sum'
601 instructions: |
602 1. Before adding a new third-party dependency, check whether the
603 standard library or an existing dependency covers the need. For
604 example, prefer `os.UserConfigDir` over `github.com/adrg/xdg`.
605 2. New dependencies must be justified in the MR description: what the
606 stdlib can't do and why an existing dep won't suffice.
607 3. Unexpected `go.mod` / `go.sum` changes that don't trace to a
608 deliberate need should be removed or explained.
610 - name: Tool versions
611 fileFilters:
612 - '.tool-versions'
613 - 'Makefile'
614 - '.gitlab-ci.yml'
615 instructions: |
616 1. The project pins developer tools via `mise` and `.tool-versions`.
617 The Makefile reads the golangci-lint version from `.tool-versions`.
618 When bumping golangci-lint, also update the `lint` job image tag in
619 `.gitlab-ci.yml` so local and CI environments stay aligned.
620 2. New developer tools should be added to `.tool-versions` (not to the
621 Makefile alone).
Diagnostics6 git calls · 36 ms
CallStatusSizeTime036 ms
discover200185 B5 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=5 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 KiB · hit9 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=59849 git.response.cache=HIT git.response.duration_ms=9 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 · hit4 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=4 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=44Open pack map
fetchtree:0200166 B · 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=166 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=48b943196abef660296043919f29347e537bc3ef 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=166 git.pkt.payload.max=139 git.sideband.band1.bytes=139 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=139 git.pack.trailer=e2a4dbef6212a95219d29b5243191f270897ab2cOpen pack map
fetch20012 KiB · hit23 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=21 git.response.bytes=12348 git.response.cache=HIT git.response.duration_ms=23 git.fetch.wants=de956703adeff007e344600f96dab190af416b62 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=12348 git.pkt.payload.max=12321 git.sideband.band1.bytes=12321 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
- a5e2ce3a9ef3efad
- Request
- 74833417…
- 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