GitLabgitlab-org
cli
main
1package iostreams
3import (
4 "fmt"
5 "image/color"
6 "io"
7 "os"
8 "strings"
10 "charm.land/lipgloss/v2"
11 "github.com/charmbracelet/colorprofile"
12 "github.com/mattn/go-colorable"
13 "github.com/muesli/termenv"
15 "gitlab.com/gitlab-org/cli/internal/theme"
16)
18// ColorMode selects whether glab emits color. It mirrors the convention of
19// git, ls, and ripgrep: auto detects from the environment and TTY state, never
20// disables color, always forces it on. The resolved value becomes the single
21// colorprofile.Profile on IOStreams; see resolveColorProfile.
22type ColorMode string
24const (
25 // ColorModeAuto detects color support from the environment and TTY state,
26 // the same as glab's historical behavior.
27 ColorModeAuto ColorMode = "auto"
28 // ColorModeNever disables color output entirely, regardless of TTY state.
29 ColorModeNever ColorMode = "never"
30 // ColorModeAlways forces color on regardless of TTY state, at whatever
31 // tier the terminal advertises.
32 ColorModeAlways ColorMode = "always"
33)
35// AllColorModes returns every valid ColorMode value, in the order they
36// should be presented to users.
37func AllColorModes() []ColorMode {
38 return []ColorMode{
39 ColorModeAuto,
40 ColorModeNever,
41 ColorModeAlways,
42 }
43}
45// colorTier is the richest profile the environment advertises, whether or
46// not color is wanted. It is the only place TERM and COLORTERM are read.
47// Forced color still needs a tier on a dumb terminal, so it never reports
48// less than ANSI.
49func colorTier() colorprofile.Profile {
50 switch {
51 case isTrueColorSupported():
52 return colorprofile.TrueColor
53 case is256ColorSupported():
54 return colorprofile.ANSI256
55 default:
56 return colorprofile.ANSI
57 }
58}
60// resolveColorProfile turns the color mode into the single profile that
61// stdout output reads: NoTTY when color is off, the terminal tier when on.
62func resolveColorProfile(mode ColorMode, isTTY bool) colorprofile.Profile {
63 switch mode {
64 case ColorModeNever:
65 return colorprofile.NoTTY
66 case ColorModeAlways:
67 return colorTier()
68 default:
69 if detectIsColorEnabled() && isTTY {
70 return colorTier()
71 }
72 return colorprofile.NoTTY
73 }
74}
76type ColorPalette struct {
77 // Magenta outputs ANSI color if stdout is a tty
78 Magenta func(string) string
79 // Cyan outputs ANSI color if stdout is a tty
80 Cyan func(string) string
81 // Red outputs ANSI color if stdout is a tty
82 Red func(string) string
83 // Yellow outputs ANSI color if stdout is a tty
84 Yellow func(string) string
85 // Blue outputs ANSI color if stdout is a tty
86 Blue func(string) string
87 // Green outputs ANSI color if stdout is a tty
88 Green func(string) string
89 // Gray outputs ANSI color if stdout is a tty
90 Gray func(string) string
91 // Bold outputs ANSI color if stdout is a tty
92 Bold func(string) string
93}
95func (s *IOStreams) Color() *ColorPalette {
96 return s.colorPalette(s.ColorEnabled() && s.IsaTTY)
97}
99// ColorProfile returns the resolved color profile for stdout output. Whether
100// color is on, and which tier it uses, are both read off this one value.
101func (s *IOStreams) ColorProfile() colorprofile.Profile {
102 return s.colorProfile
103}
105// profileIf gives the terminal tier when enabled and NoTTY otherwise, for
106// outputs (like CI logs) that decide on/off themselves but share the tier.
107func profileIf(enabled bool) colorprofile.Profile {
108 if enabled {
109 return colorTier()
110 }
111 return colorprofile.NoTTY
112}
114// ColorForCILogs returns a palette that stays colored in GitLab CI job logs
115// (which are not a TTY) while honoring NO_COLOR, unlike Color which gates on
116// the TTY. Callers that need color in CI output should use this.
117func (s *IOStreams) ColorForCILogs() *ColorPalette {
118 return s.colorPalette(s.ColorEnabledForCILogs())
119}
121func (s *IOStreams) colorPalette(isColorfulOutput bool) *ColorPalette {
122 var isDark bool
123 switch s.BackgroundColor() { // could be simplified if commands like `ci list` called `ResolveBackgroundColor()`
124 case "dark":
125 isDark = true
126 case "light":
127 isDark = false
128 default: // "none" — not yet resolved, detect now if color is enabled
129 isDark = isColorfulOutput && termenv.HasDarkBackground()
130 }
131 lightDark := lipgloss.LightDark(isDark)
132 glc := theme.NewGitLabColors(lightDark) // reuse existing palette
133 profile := profileIf(isColorfulOutput)
135 return &ColorPalette{
136 Magenta: makeColorFunc(profile, glc.Purple, "magenta"),
137 Cyan: makeColorFunc(profile, nil, "cyan"), // not in theme, falls back to ANSI
138 Red: makeColorFunc(profile, glc.Red, "red"),
139 Yellow: makeColorFunc(profile, glc.Warning, "yellow"),
140 Blue: makeColorFunc(profile, glc.Blue, "blue"),
141 Green: makeColorFunc(profile, glc.Green, "green"),
142 Gray: makeColorFunc(profile, nil, "black+h"),
143 Bold: makeColorFunc(profile, nil, "default+b"),
144 }
145}
147// NewColorable returns an output stream that handles ANSI color sequences on Windows
148func NewColorable(out io.Writer) io.Writer {
149 if outFile, isFile := out.(*os.File); isFile {
150 return colorable.NewColorable(outFile)
151 }
152 return out
153}
155func makeColorFunc(profile colorprofile.Profile, brandColor color.Color, ansiName string) func(string) string {
156 if profile <= colorprofile.ASCII {
157 return func(arg string) string {
158 return arg
159 }
160 }
162 // 24-bit truecolor and we got a color from lipgloss'd theme
163 if brandColor != nil && profile == colorprofile.TrueColor {
164 r16, g16, b16, _ := brandColor.RGBA() // standard Go interface, 16-bit per channel
165 r, g, b := uint8(r16>>8), uint8(g16>>8), uint8(b16>>8)
166 return func(t string) string {
167 return fmt.Sprintf("\x1b[38;2;%d;%d;%dm%s\x1b[m", r, g, b, t)
168 }
169 }
171 // 256 colors gray
172 if ansiName == "black+h" && profile >= colorprofile.ANSI256 {
173 return func(t string) string {
174 return fmt.Sprintf("\x1b[38;5;242m%s\x1b[m", t)
175 }
176 }
178 code, ok := basicANSICodes[ansiName]
179 if !ok {
180 return func(t string) string {
181 return t
182 }
183 }
184 return func(t string) string {
185 if t == "" {
186 return t
187 }
188 return "\x1b[" + code + "m" + t + "\x1b[0m"
189 }
190}
192// basicANSICodes maps the palette's color names to SGR parameters, matching
193// the sequences github.com/mgutz/ansi produced for them.
194var basicANSICodes = map[string]string{
195 "magenta": "0;35",
196 "cyan": "0;36",
197 "red": "0;31",
198 "yellow": "0;33",
199 "blue": "0;34",
200 "green": "0;32",
201 "black+h": "0;90",
202 "default+b": "0;1;39",
203}
205// detectIsColorEnabled determines whether color output should be enabled based on environment variables.
206// It follows the NO_COLOR specification (https://no-color.org/) with an override mechanism:
207//
208// - If NO_COLOR environment variable exists (with any value), color is disabled by default
209// - If COLOR_ENABLED is set to "1" or "true", it overrides NO_COLOR and forces color to be enabled
210// - If NO_COLOR doesn't exist, color is enabled by default
211//
212// This allows users to disable color globally with NO_COLOR while still providing an escape hatch
213// via COLOR_ENABLED for specific use cases.
214// ColorEnabledForCILogs reports whether color should be emitted, treating a
215// GitLab CI job log as color-capable even though it is not a TTY. It still
216// honors the NO_COLOR contract (via detectIsColorEnabled): a CI job that sets
217// NO_COLOR gets no color unless COLOR_ENABLED overrides it. Use this for output
218// that is meant to stay colored in CI logs; everything else should keep using
219// ColorEnabled/Color, which gate on the TTY. The color setting `never` always
220// wins, including in CI.
221func (s *IOStreams) ColorEnabledForCILogs() bool {
222 if s.colorMode == ColorModeNever {
223 return false
224 }
225 if s.ColorEnabled() {
226 return true
227 }
228 return detectIsColorEnabled() && inGitLabCI()
229}
231// inGitLabCI reports whether we're running inside a GitLab CI job.
232func inGitLabCI() bool {
233 return os.Getenv("GITLAB_CI") != ""
234}
236func detectIsColorEnabled() bool {
237 // Check if NO_COLOR environment variable exists (any value disables color)
238 _, noColorVarExists := os.LookupEnv("NO_COLOR")
240 // If NO_COLOR exists, check if COLOR_ENABLED explicitly overrides it
241 if noColorVarExists {
242 colorEnabled := os.Getenv("COLOR_ENABLED")
243 return colorEnabled == "1" || colorEnabled == "true"
244 }
246 // If NO_COLOR doesn't exist, color is enabled by default
247 return true
248}
250func isTrueColorSupported() bool {
251 term, colorterm := os.Getenv("TERM"), os.Getenv("COLORTERM")
253 return strings.Contains(term, "24bit") || strings.Contains(term, "truecolor") ||
254 strings.Contains(colorterm, "24bit") || strings.Contains(colorterm, "truecolor")
255}
257func is256ColorSupported() bool {
258 term, colorterm := os.Getenv("TERM"), os.Getenv("COLORTERM")
260 return strings.Contains(term, "256") || strings.Contains(colorterm, "256") ||
261 isTrueColorSupported()
262}
Diagnostics6 git calls · 224 ms
CallStatusSizeTime0224 ms
discover200185 B4 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=4 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 KiB199 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=181 git.response.bytes=59849 git.response.cache=EXPIRED git.response.duration_ms=199 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=3 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 · hit3 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=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
fetchtree:0200432 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=432 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=a79e8e89fbedf0d57724da455f6326f6e79de3b5 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=432 git.pkt.payload.max=405 git.sideband.band1.bytes=405 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=405 git.pack.trailer=6b5f558fa7a37603ce66aafb676f53aedcb02370Open pack map
fetch2003.0 KiB · hit20 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=20 git.response.bytes=3057 git.response.cache=HIT git.response.duration_ms=20 git.fetch.wants=9feabb5631e481aa0be5cbccfef152cd2e8f1f59 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=3057 git.pkt.payload.max=3030 git.sideband.band1.bytes=3030 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
- a5e295f6eac92407
- Request
- df07a1f0…
- 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