GitLabgitlab-org
cli
main
1package main
3import (
4 "context"
5 "errors"
6 "fmt"
7 "os"
8 "os/exec"
9 "runtime"
10 "slices"
11 "strconv"
12 "syscall"
14 "charm.land/fang/v2"
15 "charm.land/lipgloss/v2"
16 "github.com/spf13/cobra"
18 "gitlab.com/gitlab-org/cli/internal/api"
19 "gitlab.com/gitlab-org/cli/internal/cmdutils"
20 "gitlab.com/gitlab-org/cli/internal/commands"
21 "gitlab.com/gitlab-org/cli/internal/commands/alias/expand"
22 "gitlab.com/gitlab-org/cli/internal/commands/help"
23 "gitlab.com/gitlab-org/cli/internal/commands/update"
24 "gitlab.com/gitlab-org/cli/internal/config"
25 "gitlab.com/gitlab-org/cli/internal/dbg"
26 "gitlab.com/gitlab-org/cli/internal/iostreams"
27 "gitlab.com/gitlab-org/cli/internal/run"
28 "gitlab.com/gitlab-org/cli/internal/tableprinter"
29 "gitlab.com/gitlab-org/cli/internal/text"
30 "gitlab.com/gitlab-org/cli/internal/theme"
31 "gitlab.com/gitlab-org/cli/internal/utils"
32)
34var (
35 // version is set dynamically at build
36 version = "DEV"
37 // commit is set dynamically at build
38 commit string
39 // platform is set dynamically at build
40 platform = runtime.GOOS
42 // debugMode is set dynamically at build and can be overridden by
43 // the configuration file or environment variable
44 // sets to "true" or "false" or "1" or "0" as string
45 debugMode = "false"
46)
48// gitLabColorScheme returns a custom color scheme using GitLab product colors
49// for semantic meaning and accessibility across different terminal backgrounds.
50// The theme is defined in internal/theme/gitlab.go for reuse across Charm libraries.
51func gitLabColorScheme(lightDarkFunc lipgloss.LightDarkFunc) fang.ColorScheme {
52 return theme.FangColorScheme(lightDarkFunc)
53}
55func main() {
56 cfg, err := config.Init()
57 if err != nil {
58 fmt.Fprintf(os.Stderr, "failed to read configuration: %s\n", err)
59 os.Exit(2)
60 }
62 // Set Debug mode from config if not previously set by debugMode
63 debug := debugMode == "true" || debugMode == "1"
64 if !debug {
65 debugModeCfg, _ := cfg.Get("", "debug")
66 debug = debugModeCfg == "true" || debugModeCfg == "1"
67 }
69 // Initialize factory and iostreams
70 cmdFactory := cmdutils.NewFactory(
71 iostreams.New(
72 iostreams.WithStdin(os.Stdin, iostreams.IsTerminal(os.Stdin)),
73 iostreams.WithStdout(iostreams.NewColorable(os.Stdout), iostreams.IsTerminal(os.Stdout)),
74 iostreams.WithStderr(iostreams.NewColorable(os.Stderr), iostreams.IsTerminal(os.Stderr)),
75 iostreams.WithPagerCommand(iostreams.PagerCommandFromEnv()),
77 // overwrite pager from env if set via config
78 func(i *iostreams.IOStreams) {
79 if pager, _ := cfg.Get("", "glab_pager"); pager != "" {
80 i.SetPager(pager)
81 }
82 },
84 // configure hyperlink display
85 func(i *iostreams.IOStreams) {
86 configureHyperlinks(i, cfg)
87 },
89 // configure color from the `color` key / GLAB_COLOR
90 func(i *iostreams.IOStreams) {
91 configureColorMode(i, cfg)
92 },
94 // configure prompt
95 func(i *iostreams.IOStreams) {
96 if value, found := utils.IsEnvVarEnabled("NO_PROMPT"); found {
97 i.SetPrompt(strconv.FormatBool(value))
98 return
99 }
101 if value, found := utils.IsEnvVarEnabled("GLAB_NO_PROMPT"); found {
102 i.SetPrompt(strconv.FormatBool(value))
103 return
104 }
106 if promptDisabled, _ := cfg.Get("", "no_prompt"); promptDisabled != "" {
107 i.SetPrompt(promptDisabled)
108 }
109 },
110 ),
111 true,
112 cfg,
113 api.BuildInfo{Version: version, Commit: commit, Platform: platform, Architecture: runtime.GOARCH, CodingAgent: api.DetectCodingAgent()},
114 )
116 // Setup command
117 var expandedArgs []string
118 if len(os.Args) > 0 {
119 expandedArgs = os.Args[1:]
120 }
121 rootCmd := commands.NewCmdRoot(cmdFactory)
122 cmd, _, err := rootCmd.Traverse(expandedArgs)
124 if err != nil || cmd == rootCmd {
125 originalArgs := expandedArgs
126 isShell := false
127 expandedArgs, isShell, err = expand.ExpandAlias(cfg, os.Args, nil)
128 if err != nil {
129 cmdFactory.IO().LogErrorf("Failed to process alias: %s\n", err)
130 os.Exit(2)
131 }
133 if debug {
134 fmt.Printf("%v -> %v\n", originalArgs, expandedArgs)
135 }
137 if isShell {
138 externalCmd := exec.Command(expandedArgs[0], expandedArgs[1:]...)
139 externalCmd.Stderr = os.Stderr
140 externalCmd.Stdout = os.Stdout
141 externalCmd.Stdin = os.Stdin
142 preparedCmd := run.PrepareCmd(externalCmd)
144 err = preparedCmd.Run()
145 if err != nil {
146 ee := &exec.ExitError{}
147 if errors.As(err, &ee) {
148 os.Exit(ee.ExitCode())
149 }
151 cmdFactory.IO().LogErrorf("failed to run external command: %s\n", err)
152 os.Exit(3)
153 }
155 os.Exit(0)
156 }
157 }
159 // Override the default column separator of tableprinter to double spaces
160 tableprinter.SetTTYSeparator(" ")
161 // Override the default terminal width of tableprinter
162 tableprinter.SetTerminalWidth(cmdFactory.IO().TerminalWidth())
163 // set whether terminal is a TTY or non-TTY
164 tableprinter.SetIsTTY(cmdFactory.IO().IsOutputTTY())
166 rootCmd.SetArgs(expandedArgs)
167 setupTelemetryHook(cfg, cmdFactory, rootCmd, expandedArgs)
169 // Convert markdown [text](url) links in command Long and Example fields to
170 // OSC 8 terminal hyperlinks before Fang renders help text.
171 preprocessCommandLinks(rootCmd, cmdFactory.IO())
173 colorEnv := newFangColorEnv(cmdFactory.IO().ColorMode())
174 colorEnv.apply()
175 scopeColorEnvToFang(rootCmd, colorEnv)
177 help.AppendAnnotationSections(rootCmd, cmdFactory.IO())
179 if err := fang.Execute(context.Background(), rootCmd,
180 fang.WithoutCompletions(),
181 fang.WithoutManpage(),
182 fang.WithColorSchemeFunc(gitLabColorScheme),
183 fang.WithErrorHandler(cmdutils.NewGitLabErrorHandler(cmdFactory.IO())),
184 fang.WithNotifySignal(os.Interrupt, syscall.SIGTERM),
185 ); err != nil {
186 var exitError *cmdutils.ExitError
187 if errors.As(err, &exitError) {
188 os.Exit(exitError.Code)
189 } else {
190 os.Exit(1)
191 }
192 }
194 if help.HasFailed() {
195 os.Exit(1)
196 }
198 var argCommand string
199 if expandedArgs != nil {
200 argCommand = expandedArgs[0]
201 }
202 if !update.ShouldSkipUpdate(argCommand) && !ranFromAgentHook(rootCmd, expandedArgs) {
203 update.MaybeShowPostUpgradeBanner(cmdFactory.IO(), cmdFactory.Config(), cmdFactory.BuildInfo())
204 checkForUpdate(cmdFactory, rootCmd, debug)
205 }
206}
208// ranFromAgentHook reports whether the command in args ran from an agent's hook
209// that waits for it. The agent reads the hook's output, and waits for it to
210// exit.
211func ranFromAgentHook(rootCmd *cobra.Command, args []string) bool {
212 cmd, _, err := rootCmd.Find(args)
213 return err == nil && runByAgentHook(cmd)
214}
216func setupTelemetryHook(cfg config.Config, f cmdutils.Factory, rootCmd *cobra.Command, args []string) {
217 if isTelemetryEnabled(cfg) {
218 cobra.OnFinalize(addTelemetryHook(f, rootCmd, args))
219 }
220}
222func checkForUpdate(f cmdutils.Factory, rootCmd *cobra.Command, debug bool) {
223 if !isUpdateCheckEnabled(f) {
224 return
225 }
227 if err := update.CheckUpdate(f, true); err != nil {
228 update.PrintUpdateError(f.IO(), err, rootCmd, debug)
229 }
230}
232func isUpdateCheckEnabled(f cmdutils.Factory) bool {
233 if enabled, found := utils.IsEnvVarEnabled("GLAB_CHECK_UPDATE"); found {
234 return enabled
235 }
237 val, err := f.Config().Get("", "check_update")
238 // WARN: I return true here since I think we should always check for updates
239 // and an error likely indicates that the value wasn't found in the config.
240 if err != nil || val == "" {
241 return true
242 }
244 checkUpdate, err := strconv.ParseBool(val)
245 if err != nil {
246 f.IO().LogErrorf("ERROR: Could not parse config value %q: %s", "check_update", err)
247 }
249 return checkUpdate
250}
252func preprocessCommandLinks(cmd *cobra.Command, io *iostreams.IOStreams) {
253 if cmd.Long != "" {
254 cmd.Long = text.ConvertMarkdownLinks(cmd.Long, io.Hyperlink)
255 }
256 if cmd.Example != "" {
257 cmd.Example = text.ConvertMarkdownLinks(cmd.Example, io.Hyperlink)
258 }
259 for _, sub := range cmd.Commands() {
260 preprocessCommandLinks(sub, io)
261 }
262}
264// configureHyperlinks sets the IOStreams hyperlink mode based on
265// FORCE_HYPERLINKS, GLAB_FORCE_HYPERLINKS, and the `display_hyperlinks`
266// config value, in that order of precedence.
267//
268// A falsy env var value (`0`, `false`) falls through to the config check
269// so that a user with `FORCE_HYPERLINKS=0` in their shell baseline can
270// still opt out through `display_hyperlinks: false`.
271func configureHyperlinks(i *iostreams.IOStreams, cfg config.Config) {
272 if enabled, found := utils.IsEnvVarEnabled("FORCE_HYPERLINKS"); found && enabled {
273 i.SetDisplayHyperlinks("always")
274 return
275 }
277 if enabled, found := utils.IsEnvVarEnabled("GLAB_FORCE_HYPERLINKS"); found && enabled {
278 i.SetDisplayHyperlinks("always")
279 return
280 }
282 switch displayHyperlinks, _ := cfg.Get("", "display_hyperlinks"); displayHyperlinks {
283 case "false":
284 i.SetDisplayHyperlinks("never")
285 case "true":
286 i.SetDisplayHyperlinks("auto")
287 }
288}
290// configureColorMode sets whether glab colors output from the `color` config
291// key, which config.Get already resolves against GLAB_COLOR per the key's
292// declared EnvVars (see internal/config/schema.go). An unrecognized value
293// falls back to ColorModeAuto rather than failing the command, matching how
294// glab treats other soft-fallback config values (e.g. an invalid theme).
295func configureColorMode(i *iostreams.IOStreams, cfg config.Config) {
296 value, _ := cfg.Get("", "color")
297 mode := iostreams.ColorMode(value)
298 if value != "" && !slices.Contains(iostreams.AllColorModes(), mode) {
299 dbg.Debugf("color: %q is not a recognized value (want one of %v); falling back to auto", value, iostreams.AllColorModes())
300 mode = iostreams.ColorModeAuto
301 }
302 i.SetColorMode(mode)
303}
305// fangColorEnv carries the color mode to fang, which reads its color level
306// only from the process environment. CLICOLOR_FORCE beats NO_COLOR for
307// colorprofile on a non-TTY, so each mode clears the variable it opposes.
308type fangColorEnv struct {
309 set map[string]string
310 unset []string
311 orig map[string]string
312 origSet map[string]bool
313}
315func newFangColorEnv(mode iostreams.ColorMode) *fangColorEnv {
316 e := &fangColorEnv{orig: map[string]string{}, origSet: map[string]bool{}}
317 switch mode {
318 case iostreams.ColorModeNever:
319 e.set = map[string]string{"NO_COLOR": "1"}
320 e.unset = []string{"CLICOLOR_FORCE"}
321 case iostreams.ColorModeAlways:
322 e.set = map[string]string{"CLICOLOR_FORCE": "1"}
323 e.unset = []string{"NO_COLOR"}
324 }
325 for _, k := range append(e.unset, keys(e.set)...) {
326 e.orig[k], e.origSet[k] = os.LookupEnv(k)
327 }
328 return e
329}
331func keys(m map[string]string) []string {
332 out := make([]string, 0, len(m))
333 for k := range m {
334 out = append(out, k)
335 }
336 return out
337}
339func (e *fangColorEnv) apply() {
340 for _, k := range e.unset {
341 setenv(k, "", false)
342 }
343 for k, v := range e.set {
344 setenv(k, v, true)
345 }
346}
348func (e *fangColorEnv) restore() {
349 for k := range e.orig {
350 setenv(k, e.orig[k], e.origSet[k])
351 }
352}
354func setenv(key, value string, present bool) {
355 var err error
356 if present {
357 err = os.Setenv(key, value)
358 } else {
359 err = os.Unsetenv(key)
360 }
361 if err != nil {
362 dbg.Debugf("color: could not update %s for fang: %v", key, err)
363 }
364}
366// scopeColorEnvToFang restores the original environment while a command runs,
367// so children glab starts (git, pagers, editors, alias shells) don't inherit
368// the variables meant for fang, and re-applies it afterwards for fang's error
369// output.
370func scopeColorEnvToFang(root *cobra.Command, e *fangColorEnv) {
371 var walk func(*cobra.Command)
372 walk = func(c *cobra.Command) {
373 if run := c.Run; run != nil {
374 c.Run = func(cmd *cobra.Command, args []string) {
375 e.restore()
376 defer e.apply()
377 run(cmd, args)
378 }
379 }
380 if runE := c.RunE; runE != nil {
381 c.RunE = func(cmd *cobra.Command, args []string) error {
382 e.restore()
383 defer e.apply()
384 return runE(cmd, args)
385 }
386 }
387 for _, sub := range c.Commands() {
388 walk(sub)
389 }
390 }
391 walk(root)
392}
Diagnostics6 git calls · 254 ms
CallStatusSizeTime0254 ms
discover200185 B4 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 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 KiB2 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=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 · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=3 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
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=5 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=4 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:0200195 B · hit5 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=241 git.response.bytes=195 git.response.cache=HIT git.response.duration_ms=5 git.fetch.filter=tree:0 git.fetch.wants=62ad6b84b990e694d7e6e68667ba67fcbef93a08 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=195 git.pkt.payload.max=168 git.sideband.band1.bytes=168 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=168 git.pack.trailer=946df40edc15e3ab53d2f74cc477577e7e3fbcdcOpen pack map
fetch2003.9 KiB241 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=4033 git.response.cache=MISS git.response.duration_ms=241 git.fetch.wants=8bca2365052e1df4a42ee003ee4f21bca2cd1b19 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=4033 git.pkt.payload.max=4006 git.sideband.band1.bytes=4006 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
- a5e20f1cfeed7f3b
- Request
- 83b5ad6d…
- 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