GitLabgitlab-org

cli

main
ply6 git calls243 ms102 KiB4 cachedprotocol v2
720 lines24 KiBRaw
1package main
3import (
4 "bytes"
5 "errors"
6 "fmt"
7 "io"
8 "io/fs"
9 "os"
10 "path/filepath"
11 "slices"
12 "strings"
14 "github.com/spf13/cobra"
15 "github.com/spf13/cobra/doc"
16 "github.com/spf13/pflag"
18 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
20 "gitlab.com/gitlab-org/cli/cmd/gen-docs/urlwrapper"
21 "gitlab.com/gitlab-org/cli/internal/api"
22 "gitlab.com/gitlab-org/cli/internal/cmdutils"
23 "gitlab.com/gitlab-org/cli/internal/commands"
24 "gitlab.com/gitlab-org/cli/internal/commands/help"
25 "gitlab.com/gitlab-org/cli/internal/config"
26 "gitlab.com/gitlab-org/cli/internal/config/confighelp"
27 "gitlab.com/gitlab-org/cli/internal/git"
28 "gitlab.com/gitlab-org/cli/internal/glinstance"
29 "gitlab.com/gitlab-org/cli/internal/glrepo"
30 "gitlab.com/gitlab-org/cli/internal/iostreams"
33// generatedMarker identifies pages produced by this generator. Pruning only
34// removes Markdown files that carry it, so hand-maintained files and images
35// under the docs directory are never deleted.
36const generatedMarker = "This documentation is auto generated by a script."
38func main() {
39 var flagErr pflag.ErrorHandling
40 docsCmd := pflag.NewFlagSet("", flagErr)
41 manpage := docsCmd.BoolP("manpage", "m", false, "Generate manual pages instead of web docs.")
42 path := docsCmd.StringP("path", "p", "./docs/source/", "Path where you want the generated docs saved.")
43 navPath := docsCmd.StringP("nav-path", "n", "./docs/navigation-glab.yaml", "Path where the generated navigation YAML is saved.")
44 readmePath := docsCmd.StringP("readme-path", "r", "./README.md", "Path to the README file whose command list is regenerated.")
45 help := docsCmd.BoolP("help", "h", false, "Help about any command.")
47 if err := docsCmd.Parse(os.Args); err != nil {
48 fatal(err)
49 }
50 if *help {
51 _, err := fmt.Fprintf(os.Stderr, "Usage of %s:\n\n%s", os.Args[0], docsCmd.FlagUsages())
52 if err != nil {
53 fatal(err)
54 }
55 os.Exit(1)
56 }
57 err := os.MkdirAll(*path, 0o750)
58 if err != nil {
59 fatal(err)
60 }
62 glabCli := commands.NewCmdRoot(&factory{io: iostreams.New()})
63 glabCli.DisableAutoGenTag = true
64 if *manpage {
65 if err := genManPage(glabCli, *path); err != nil {
66 fatal(err)
67 }
68 } else {
69 if err := genWebDocs(glabCli, *path, *readmePath); err != nil {
70 fatal(err)
71 }
72 if err := genNav(glabCli, *navPath); err != nil {
73 fatal(err)
74 }
75 }
78func genManPage(glabCli *cobra.Command, path string) error {
79 header := &doc.GenManHeader{
80 Title: "glab",
81 Section: "1",
82 Source: "",
83 Manual: "",
84 }
85 err := doc.GenManTree(glabCli, header, path)
86 if err != nil {
87 return err
88 }
89 return nil
92func genWebDocs(glabCli *cobra.Command, basePath, readmePath string) error {
93 // Remove previously generated pages first so that pages for commands that no
94 // longer exist are not left behind. Only marker-bearing Markdown files are
95 // pruned; images and any hand-maintained files are preserved. Regenerating
96 // below recreates every page that is still documented.
97 if err := pruneGeneratedPages(basePath); err != nil {
98 return err
99 }
101 // Rewrite the command list in README.md between the sentinel markers.
102 if err := genReadmeCommandList(glabCli, readmePath); err != nil {
103 return err
104 }
106 // Rewrite the environment variable reference in the hand-maintained
107 // configuration page, which the pruning step above leaves alone.
108 if err := genEnvVarReference(filepath.Join(basePath, "configuration.md")); err != nil {
109 return err
110 }
112 // Generate docs for root command with special handling
113 if err := genRootCommandDocs(glabCli, basePath); err != nil {
114 return err
115 }
117 // Generate the landing page that lists every top-level command
118 if err := genCommandsPage(glabCli, basePath); err != nil {
119 return err
120 }
122 // Generate docs for all top-level commands
123 for _, cmd := range glabCli.Commands() {
124 if err := genCommandDocs(cmd, basePath, []string{}); err != nil {
125 return err
126 }
127 }
129 // Drop directories left empty after pruning, for example a removed
130 // command's folder.
131 return removeEmptyDirs(basePath)
134// pruneGeneratedPages deletes every Markdown file under basePath that carries
135// the generated-by-a-script marker. Because genWebDocs regenerates all
136// documented commands afterwards, a page whose command was removed from the
137// tree stays deleted. Only marker-bearing .md files are touched, so images and
138// any hand-maintained files are left in place.
139func pruneGeneratedPages(basePath string) error {
140 return filepath.WalkDir(basePath, func(path string, d fs.DirEntry, err error) error {
141 if err != nil {
142 return err
143 }
144 if d.IsDir() || !strings.HasSuffix(d.Name(), ".md") {
145 return nil
146 }
147 content, err := os.ReadFile(path)
148 if err != nil {
149 return err
150 }
151 if !bytes.Contains(content, []byte(generatedMarker)) {
152 return nil
153 }
154 return os.Remove(path)
155 })
158// removeEmptyDirs deletes directories left empty under basePath, deepest first
159// so that parents emptied by removing their children are also cleaned up.
160// basePath itself is never removed.
161func removeEmptyDirs(basePath string) error {
162 var dirs []string
163 err := filepath.WalkDir(basePath, func(path string, d fs.DirEntry, err error) error {
164 if err != nil {
165 return err
166 }
167 if d.IsDir() && path != basePath {
168 dirs = append(dirs, path)
169 }
170 return nil
171 })
172 if err != nil {
173 return err
174 }
176 // Remove the deepest directories first so a parent that becomes empty once
177 // its children are gone is caught in the same pass.
178 slices.SortFunc(dirs, func(a, b string) int { return len(b) - len(a) })
179 for _, dir := range dirs {
180 entries, err := os.ReadDir(dir)
181 if err != nil {
182 return err
183 }
184 if len(entries) == 0 {
185 if err := os.Remove(dir); err != nil {
186 return err
187 }
188 }
189 }
190 return nil
193// genNav writes the GitLab CLI (glab) navigation submenu consumed by the
194// GitLab Docs site (docs-gitlab-com): a standalone YAML list of the glab
195// submenu's children at zero base indentation, which the docs site splices
196// between sentinel comments. It walks the same command tree as the web docs,
197// so the nav and the generated pages always agree on what exists.
198func genNav(glabCli *cobra.Command, navPath string) error {
199 buf := new(strings.Builder)
200 buf.WriteString("# This file is auto-generated by `make gen-docs` in gitlab-org/cli.\n")
201 buf.WriteString("# Do not edit it directly. It is spliced into the GitLab CLI (glab)\n")
202 buf.WriteString("# section of data/en-us/navigation.yaml in docs-gitlab-com.\n")
203 walk(glabCli, []string{}, 0, buf)
204 return config.WriteFile(navPath, []byte(buf.String()), 0o644)
207// walk recursively emits a YAML list entry for each available subcommand of
208// cmd, mirroring the directory tree that the web docs produce.
209//
210// For depth d (top-level commands are depth 0):
211// - the "- title:" line is indented d*4 spaces
212// - the "url:"/"submenu:" keys are indented d*4+2 spaces
213// - children are emitted at depth d+1
214func walk(cmd *cobra.Command, path []string, depth int, buf *strings.Builder) {
215 for _, c := range cmd.Commands() {
216 // Skip help commands and unavailable (hidden/deprecated) commands,
217 // matching the web docs so the nav and docs stay aligned.
218 if c.Name() == "help" || !c.IsAvailableCommand() {
219 continue
220 }
222 p := append(append([]string{}, path...), c.Name())
223 dash := strings.Repeat(" ", depth*4)
225 fmt.Fprintf(buf, "%s- title: glab %s\n", dash, strings.Join(p, " "))
226 fmt.Fprintf(buf, "%s url: 'cli/%s/'\n", dash, strings.Join(p, "/"))
228 if c.HasAvailableSubCommands() {
229 fmt.Fprintf(buf, "%s submenu:\n", dash)
230 walk(c, p, depth+1, buf)
231 }
232 }
235// genCommandDocs recursively generates documentation for a command and all its subcommands
236// Top-level commands always get their own folder with _index.md
237// Non-top-level commands with subcommands get their own folder with _index.md
238// Non-top-level commands without subcommands get a .md file in their parent's directory
239// and do not create their own directory
240func genCommandDocs(cmd *cobra.Command, basePath string, parentPath []string) error {
241 // Skip help commands and unavailable commands (hidden/deprecated)
242 if cmd.Name() == "help" || !cmd.IsAvailableCommand() {
243 return nil
244 }
246 // Build the current command path
247 currentPath := append(slices.Clone(parentPath), cmd.Name())
248 fullPath := filepath.Join(append([]string{basePath}, currentPath...)...)
250 fmt.Println("Generating docs for " + strings.Join(currentPath, " "))
252 // Only create directory if this command has subcommands or is top-level
253 if cmd.HasAvailableSubCommands() || len(parentPath) == 0 {
254 if err := os.MkdirAll(fullPath, 0o750); err != nil {
255 return err
256 }
257 }
259 // Generate the command documentation
260 out := new(bytes.Buffer)
261 if err := GenMarkdownCustom(cmd, out); err != nil {
262 return err
263 }
265 // Write the documentation file
266 // - Top-level commands always get folder/_index.md (even without subcommands)
267 // - Non-top-level commands with subcommands get folder/_index.md
268 // - Non-top-level commands without subcommands get parent/command.md
269 var filename string
270 if cmd.HasAvailableSubCommands() || len(parentPath) == 0 {
271 // Commands with subcommands OR top-level commands always get folder/_index.md
272 filename = filepath.Join(fullPath, "_index.md")
273 } else {
274 // Non-top-level leaf commands (no subcommands) write as a .md file in the parent directory
275 parentDir := filepath.Join(append([]string{basePath}, parentPath...)...)
276 filename = filepath.Join(parentDir, cmd.Name()+".md")
277 }
279 if err := config.WriteFile(filename, out.Bytes(), 0o644); err != nil {
280 return err
281 }
283 // Recursively generate docs for all subcommands
284 for _, subCmd := range cmd.Commands() {
285 if subCmd.Name() != "help" && subCmd.IsAvailableCommand() {
286 if err := genCommandDocs(subCmd, basePath, currentPath); err != nil {
287 return err
288 }
289 }
290 }
292 return nil
295// genRootCommandDocs generates documentation for the root command with custom content preservation
296func genRootCommandDocs(cmd *cobra.Command, basePath string) error {
297 fmt.Println("Generating docs for root command")
299 // Generate the root command documentation with custom intro content
300 out := new(bytes.Buffer)
301 if err := GenRootMarkdownCustom(cmd, out); err != nil {
302 return err
303 }
305 // Write to _index.md in the base path
306 filename := filepath.Join(basePath, "_index.md")
307 if err := config.WriteFile(filename, out.Bytes(), 0o644); err != nil {
308 return err
309 }
311 return nil
314// writeGeneratedHeader writes the GitLab docs metadata front matter and the
315// generated-by-a-script comment that every page this generator produces starts
316// with. The comment carries generatedMarker, so pages written through this
317// helper are pruned and rewritten on each run.
318func writeGeneratedHeader(buf *bytes.Buffer, title string) {
319 buf.WriteString("---" + "\n")
320 buf.WriteString("title: " + title + "\n")
321 buf.WriteString("stage: AI Clients" + "\n")
322 buf.WriteString("group: Developer Clients" + "\n")
323 buf.WriteString("info: To determine the technical writer assigned to the Stage/Group associated with this page, see <https://handbook.gitlab.com/handbook/marketing/product-and-technical-marketing/technical-writing/#assignments>" + "\n")
324 buf.WriteString("---" + "\n\n")
326 buf.WriteString("<!--" + "\n")
327 buf.WriteString(generatedMarker + "\n")
328 buf.WriteString("Please do not edit this file directly. Run `make gen-docs` instead." + "\n")
329 buf.WriteString("-->" + "\n\n")
332// genCommandsPage writes the commands landing page, which lists every
333// top-level command. The GitLab Docs navigation gives every entry a URL, so the
334// Commands parent of the generated command reference needs a real page at
335// cli/commands/.
336func genCommandsPage(cmd *cobra.Command, basePath string) error {
337 fmt.Println("Generating docs for the commands landing page")
339 buf := new(bytes.Buffer)
340 writeGeneratedHeader(buf, "Commands")
342 buf.WriteString("{{< details >}}\n\n")
343 buf.WriteString("- Tier: Free, Premium, Ultimate\n")
344 buf.WriteString("- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated\n\n")
345 buf.WriteString("{{< /details >}}\n\n")
347 buf.WriteString("`glab` provides these top-level commands. Each page describes the command's\n")
348 buf.WriteString("subcommands, options, and examples.\n\n")
349 buf.WriteString(rootSubcommandList(cmd))
351 filename := filepath.Join(basePath, "commands.md")
352 return config.WriteFile(filename, buf.Bytes(), 0o644)
355func printSubcommands(cmd *cobra.Command, buf *bytes.Buffer) {
356 if len(cmd.Commands()) < 1 {
357 return
358 }
360 var subcommands strings.Builder
361 // Generate children commands
362 for _, cmdC := range cmd.Commands() {
363 if cmdC.Name() != "help" && cmdC.IsAvailableCommand() {
364 if cmdC.HasAvailableSubCommands() {
365 subcommands.WriteString(fmt.Sprintf("- [%#q](%s/_index.md)\n", cmdC.Name(), cmdC.Name()))
366 } else {
367 subcommands.WriteString(fmt.Sprintf("- [%#q](%s.md)\n", cmdC.Name(), cmdC.Name()))
368 }
369 }
370 }
372 if subcommands.String() != "" {
373 buf.WriteString("\n## Subcommands\n\n")
374 buf.WriteString(subcommands.String())
375 }
378// rootSubcommandList returns a Markdown bullet list of the root command's
379// available top-level commands. All top-level commands get directories and
380// _index.md files based on the generation logic, and the links are relative to
381// the docs base directory, so the list is valid from any page written there.
382func rootSubcommandList(cmd *cobra.Command) string {
383 var subcommands strings.Builder
384 for _, cmdC := range cmd.Commands() {
385 if cmdC.Name() != "help" && cmdC.IsAvailableCommand() {
386 fmt.Fprintf(&subcommands, "- [`glab %s`](%s/_index.md)\n", cmdC.Name(), cmdC.Name())
387 }
388 }
389 return subcommands.String()
392func genReadmeCommandList(cmd *cobra.Command, readmePath string) error {
393 content, err := os.ReadFile(readmePath)
394 if err != nil {
395 return fmt.Errorf("reading %s: %w", readmePath, err)
396 }
397 updated, err := updateReadme(content, cmd)
398 if err != nil {
399 return err
400 }
401 return config.WriteFile(readmePath, updated, 0o644)
404// Sentinel comments that delimit the auto-generated command list in README.md.
405const (
406 readmeCommandListStart = "<!-- commands-list-start: generated by 'make gen-docs'; do not edit by hand -->"
407 readmeCommandListEnd = "<!-- commands-list-end -->"
410// Sentinel comments that delimit the auto-generated environment variable
411// reference in docs/source/configuration.md.
412const (
413 envVarTableStart = "<!-- env-vars-start: generated by 'make gen-docs'; do not edit by hand -->"
414 envVarTableEnd = "<!-- env-vars-end -->"
417func genEnvVarReference(configPath string) error {
418 content, err := os.ReadFile(configPath)
419 if err != nil {
420 return fmt.Errorf("reading %s: %w", configPath, err)
421 }
422 updated, err := replaceMarkedSection(string(content), envVarTableStart, envVarTableEnd, envVarTable())
423 if err != nil {
424 return fmt.Errorf("%s: %w", configPath, err)
425 }
426 return config.WriteFile(configPath, []byte(updated), 0o644)
429func envVarTable() string {
430 var b strings.Builder
431 b.WriteString("\n<!-- markdownlint-disable MD044 MD034 -->\n")
432 for _, section := range confighelp.EnvVarsByGroup() {
433 fmt.Fprintf(&b, "\n### %s\n\n", section.Group)
434 b.WriteString("| Variable | Configuration key | Default | Description |\n")
435 b.WriteString("|----------|-------------------|---------|-------------|\n")
436 for _, ev := range section.Vars {
437 configKey := "-"
438 if ev.ConfigKey != "" {
439 configKey = "`" + ev.ConfigKey + "`"
440 }
441 defaultValue := "-"
442 if ev.Default != "" {
443 defaultValue = "`" + ev.Default + "`"
444 }
445 description := urlwrapper.MDWrap(escapeTableCell(ev.Description))
446 fmt.Fprintf(&b, "| `%s` | %s | %s | %s |\n", ev.Name, configKey, defaultValue, description)
447 }
448 }
449 b.WriteString("\n<!-- markdownlint-enable MD044 MD034 -->\n")
450 return b.String()
453func escapeTableCell(s string) string {
454 return strings.ReplaceAll(s, "|", `\|`)
457func replaceMarkedSection(content, startMarker, endMarker, body string) (string, error) {
458 start := strings.Index(content, startMarker)
459 end := strings.Index(content, endMarker)
460 if start == -1 || end == -1 || end < start {
461 return "", fmt.Errorf("missing or malformed sentinel markers %q / %q", startMarker, endMarker)
462 }
463 return content[:start+len(startMarker)] + body + content[end:], nil
466func readmeCommandList(cmd *cobra.Command) string {
467 var b strings.Builder
468 for _, c := range cmd.Commands() {
469 if c.Name() == "help" || !c.IsAvailableCommand() {
470 continue
471 }
472 fmt.Fprintf(&b, "- [`glab %s`](docs/source/%s): %s\n", c.Name(), c.Name(), c.Short)
473 }
474 return b.String()
477func updateReadme(content []byte, cmd *cobra.Command) ([]byte, error) {
478 updated, err := replaceMarkedSection(string(content), readmeCommandListStart, readmeCommandListEnd, "\n"+readmeCommandList(cmd))
479 if err != nil {
480 return nil, fmt.Errorf("README.md: %w", err)
481 }
482 return []byte(updated), nil
485// printRootOptions is like printOptions but without the leading newline for root command
486func printRootOptions(buf *bytes.Buffer, cmd *cobra.Command) error {
487 flags := cmd.NonInheritedFlags()
488 flags.SetOutput(buf)
489 if flags.HasAvailableFlags() {
490 buf.WriteString("## Options\n\n```plaintext\n")
491 flags.PrintDefaults()
492 buf.WriteString("```\n")
493 }
495 parentFlags := cmd.InheritedFlags()
496 parentFlags.SetOutput(buf)
497 if parentFlags.HasAvailableFlags() {
498 buf.WriteString("\n## Options inherited from parent commands\n\n```plaintext\n")
499 parentFlags.PrintDefaults()
500 buf.WriteString("```\n")
501 }
502 return nil
505func fatal(err error) {
506 fmt.Fprintln(os.Stderr, err)
507 os.Exit(1)
510type factory struct {
511 io *iostreams.IOStreams
514func (f *factory) RepoOverride(repo string) error {
515 return nil
518func (f *factory) ApiClient(repoHost string) (*api.Client, error) {
519 return nil, errors.New("not implemented")
522func (f *factory) GitLabClient() (*gitlab.Client, error) {
523 return nil, errors.New("not implemented")
526func (f *factory) BaseRepo() (glrepo.Interface, error) {
527 return nil, errors.New("not implemented")
530func (f *factory) Remotes() (glrepo.Remotes, error) {
531 return nil, errors.New("not implemented")
534func (f *factory) Config() config.Config {
535 return nil
538func (f *factory) Branch() (string, error) {
539 return "", errors.New("not implemented")
542func (f *factory) IO() *iostreams.IOStreams {
543 return f.io
546func (f *factory) DefaultHostname() string {
547 return glinstance.DefaultHostname
550func (f *factory) BuildInfo() api.BuildInfo {
551 return api.BuildInfo{}
554func (f *factory) Executor() cmdutils.Executor {
555 return nil
558func (f *factory) GitRunner() git.GitRunner {
559 return git.StandardGitCommand{}
562// adapted from: github.com/spf13/cobra/blob/main/doc/md_docs.go
563// GenMarkdownTreeCustom is the same as GenMarkdownTree, but
564// with custom filePrepender and linkHandler.
565func GenMarkdownTreeCustom(cmd *cobra.Command, dir string) error {
566 for _, c := range cmd.Commands() {
567 if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
568 continue
569 }
570 if err := GenMarkdownTreeCustom(c, dir); err != nil {
571 return err
572 }
573 }
575 basename := strings.ReplaceAll(cmd.Name(), " ", "_") + ".md"
576 filename := filepath.Join(dir, basename)
577 f, err := os.Create(filename)
578 if err != nil {
579 return err
580 }
581 defer f.Close()
583 if err := GenMarkdownCustom(cmd, f); err != nil {
584 return err
585 }
586 return nil
589// GenMarkdownCustom creates custom Markdown output. github.com/spf13/cobra/blob/main/doc/md_docs.go
590func GenMarkdownCustom(cmd *cobra.Command, w io.Writer) error {
591 cmd.InitDefaultHelpCmd()
592 cmd.InitDefaultHelpFlag()
594 buf := new(bytes.Buffer)
595 name := cmd.CommandPath()
596 writeGeneratedHeader(buf, "'`"+name+"`'")
598 // Wrap URLs in Short description
599 shortDesc := urlwrapper.MDWrap(cmd.Short)
600 buf.WriteString(shortDesc + "\n")
602 if cmd.Long != "" {
603 // Skipping `help` commands until Long description can be revised
604 if cmd.Name() != "help" {
605 buf.WriteString("\n## Synopsis\n\n")
606 // Wrap URLs in Long description
607 longDesc := urlwrapper.MDWrap(cmd.Long)
608 buf.WriteString(longDesc)
609 }
610 }
612 if cmd.Runnable() {
613 fmt.Fprintf(buf, "\n```plaintext\n%s\n```\n", cmd.UseLine())
614 }
616 if len(cmd.Aliases) > 0 {
617 buf.WriteString("\n## Aliases\n\n")
618 fmt.Fprintf(buf, "```plaintext\n%s\n```\n", strings.Join(cmd.Aliases, "\n"))
619 }
621 if cmd.Example != "" {
622 buf.WriteString("\n## Examples\n\n")
623 fmt.Fprintf(buf, "```console\n%s\n```\n", cmd.Example)
624 }
626 for _, s := range help.AnnotationSections(cmd) {
627 fmt.Fprintf(buf, "\n## %s\n\n```plaintext\n%s\n```\n", s.Title, s.Body)
628 }
630 if err := printOptions(buf, cmd); err != nil {
631 return err
632 }
634 printSubcommands(cmd, buf)
636 _, err := buf.WriteTo(w)
637 return err
640// adapted from: github.com/spf13/cobra/blob/main/doc/md_docs.go
641func printOptions(buf *bytes.Buffer, cmd *cobra.Command) error {
642 flags := cmd.NonInheritedFlags()
643 flags.SetOutput(buf)
644 if flags.HasAvailableFlags() {
645 buf.WriteString("\n## Options\n\n```plaintext\n")
646 flags.PrintDefaults()
647 buf.WriteString("```\n")
648 }
650 parentFlags := cmd.InheritedFlags()
651 parentFlags.SetOutput(buf)
652 if parentFlags.HasAvailableFlags() {
653 buf.WriteString("\n## Options inherited from parent commands\n\n```plaintext\n")
654 parentFlags.PrintDefaults()
655 buf.WriteString("```\n")
656 }
657 return nil
660// GenRootMarkdownCustom creates custom markdown for the root command with preserved intro content
661func GenRootMarkdownCustom(cmd *cobra.Command, w io.Writer) error {
662 buf := new(bytes.Buffer)
663 writeGeneratedHeader(buf, "GitLab CLI (glab)")
665 // Add details shortcode
666 buf.WriteString("{{< details >}}\n\n")
667 buf.WriteString("- Tier: Free, Premium, Ultimate\n")
668 buf.WriteString("- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated\n\n")
669 buf.WriteString("{{< /details >}}\n\n")
671 // Custom title and intro content (from README)
672 buf.WriteString("GLab is an open source GitLab CLI tool. It brings GitLab to your terminal, next to where you are already working with `git` and your code, without switching between windows and browser tabs. While it's powerful for issues and merge requests, `glab` does even more:\n\n")
673 buf.WriteString("- View, manage, and retry CI/CD pipelines directly from your CLI.\n")
674 buf.WriteString("- Create changelogs.\n")
675 buf.WriteString("- Create and manage releases.\n")
676 buf.WriteString("- Ask GitLab Duo Chat (Classic) questions about Git.\n")
677 buf.WriteString("- Manage GitLab agents for Kubernetes.\n\n")
678 buf.WriteString("`glab` is available for repositories hosted on GitLab.com, GitLab Dedicated, and GitLab Self-Managed. It supports multiple authenticated GitLab instances, and automatically detects the authenticated hostname from the remotes available in your working Git directory.\n\n")
679 buf.WriteString("![command example](img/getting-started.gif)\n\n")
681 // Install and authenticate sections (moved up, with README links)
682 buf.WriteString("## Install the CLI\n\n")
683 buf.WriteString("Installation instructions are available in the GLab\n")
684 buf.WriteString("[`README`](https://gitlab.com/gitlab-org/cli/#installation).\n\n")
686 buf.WriteString("## Authenticate with GitLab\n\n")
687 buf.WriteString("GLab supports multiple authentication methods including OAuth and personal access tokens.\n")
688 buf.WriteString("To get started, run `glab auth login` and follow the interactive setup.\n\n")
689 buf.WriteString("For detailed authentication instructions, see\n")
690 buf.WriteString("[Authenticate with GitLab](authentication.md).\n\n")
692 // Pagination section
693 buf.WriteString("## Pagination\n\n")
694 buf.WriteString("Commands that return lists of items are paginated. Use `--page` and `--per-page` to\n")
695 buf.WriteString("navigate results. These commands respect the pagination limits configured on your\n")
696 buf.WriteString("GitLab instance.\n\n")
698 if cmd.Runnable() {
699 fmt.Fprintf(buf, "```plaintext\n%s\n```\n\n", cmd.UseLine())
700 }
702 buf.WriteString("## Environment variables\n\n")
703 buf.WriteString("For every environment variable `glab` reads, see\n")
704 buf.WriteString("[environment variables](configuration.md#environment-variables).\n\n")
705 if err := printRootOptions(buf, cmd); err != nil {
706 return err
707 }
709 // Point at the commands landing page, which holds the full list
710 buf.WriteString("\n## Commands\n\n")
711 buf.WriteString("For the list of top-level `glab` commands, see [Commands](commands.md).\n")
713 // Add report issues section at the end
714 buf.WriteString("\n## Report issues\n\n")
715 buf.WriteString("Open an issue in the [`gitlab-org/cli` repository](https://gitlab.com/gitlab-org/cli/issues/new)\n")
716 buf.WriteString("to send us feedback.\n")
718 _, err := buf.WriteTo(w)
719 return err
Diagnostics6 git calls · 243 ms
CallStatusSizeTime0243 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 KiB · hit2 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=HIT
git.response.duration_ms=2
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
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
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:0200174 B · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=174
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=9a364b543bd220d89afac6cc877ed8db92abf022
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=174
git.pkt.payload.max=147
git.sideband.band1.bytes=147
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=147
git.pack.trailer=5a3ab82bf6fbb95581196169deb2e857fd8acdf5
Open pack map
fetch2006.9 KiB236 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=236
git.response.bytes=7025
git.response.cache=MISS
git.response.duration_ms=236
git.fetch.wants=4c6994252942ee83c76fbd084f97f83c0244bca1
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=7025
git.pkt.payload.max=6998
git.sideband.band1.bytes=6998
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
a5e130130d4ea9fe
Request
8ff8dce5…
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