GitLabgitlab-org
cli
main
1package config
3import (
4 "errors"
5 "fmt"
6 "io"
7 "os"
8 "path/filepath"
9 "slices"
10 "syscall"
12 "github.com/adrg/xdg"
13 "go.yaml.in/yaml/v3"
15 "gitlab.com/gitlab-org/cli/internal/dbg"
16)
18var (
19 cachedConfig Config
20 configError error
21)
23// legacyConfigDir returns the legacy config directory (~/.config/glab-cli).
24// This was the default location before XDG platform-specific paths were adopted.
25// Uses os.UserHomeDir() for cross-platform compatibility (works on Windows, macOS, Linux).
26func legacyConfigDir() string {
27 home, err := os.UserHomeDir()
28 if err != nil || home == "" {
29 return ""
30 }
31 return filepath.Join(home, ".config", "glab-cli")
32}
34// ConfigDir returns the config directory for writing configuration.
35// It respects GLAB_CONFIG_DIR as the highest priority override.
36// For backward compatibility, if a legacy config exists at ~/.config/glab-cli/,
37// that location continues to be used. Otherwise, uses XDG_CONFIG_HOME.
38func ConfigDir() string {
39 glabDir := os.Getenv("GLAB_CONFIG_DIR")
40 if glabDir != "" {
41 return glabDir
42 }
44 // Check for legacy config location for backward compatibility
45 legacyDir := legacyConfigDir()
46 if legacyDir != "" {
47 legacyConfigFile := filepath.Join(legacyDir, "config.yml")
48 if _, err := os.Stat(legacyConfigFile); err == nil {
49 return legacyDir
50 }
51 }
53 return filepath.Join(xdg.ConfigHome, "glab-cli")
54}
56// ConfigFile returns the config file path.
57// It respects GLAB_CONFIG_DIR as the highest priority override,
58// otherwise returns the XDG-compliant user config file path.
59// This function only determines the path without creating directories.
60func ConfigFile() string {
61 return filepath.Join(ConfigDir(), "config.yml")
62}
64// SearchConfigFile searches for an existing config file across all config paths.
65// It respects GLAB_CONFIG_DIR as the highest priority override.
66// Search order:
67// 1. $GLAB_CONFIG_DIR/config.yml (if GLAB_CONFIG_DIR is set)
68// 2. ~/.config/glab-cli/config.yml (legacy location, for backward compatibility)
69// 3. $XDG_CONFIG_HOME/glab-cli/config.yml (platform-specific XDG location)
70// 4. $XDG_CONFIG_DIRS/glab-cli/config.yml (system-wide configs)
71//
72// Returns the path to the first config file found, or an error if none exist.
73func SearchConfigFile() (string, error) {
74 // HIGHEST PRIORITY: GLAB_CONFIG_DIR completely bypasses XDG
75 if os.Getenv("GLAB_CONFIG_DIR") != "" {
76 configPath := ConfigFile()
77 if _, err := os.Stat(configPath); err == nil {
78 return configPath, nil
79 }
80 // If GLAB_CONFIG_DIR is set but file doesn't exist,
81 // still return this path (don't fall through to XDG)
82 return configPath, os.ErrNotExist
83 }
85 // Check legacy location first for backward compatibility
86 legacyDir := legacyConfigDir()
87 if legacyDir != "" {
88 legacyConfigPath := filepath.Join(legacyDir, "config.yml")
89 if _, err := os.Stat(legacyConfigPath); err == nil {
90 return legacyConfigPath, nil
91 }
92 }
94 // XDG search: user config → system configs
95 configPath, err := xdg.SearchConfigFile("glab-cli/config.yml")
96 if err != nil {
97 return "", err
98 }
99 return configPath, nil
100}
102// checkForDuplicateConfigs warns if multiple config files exist across different locations.
103// Since we don't support config merging (yet), only the first file found is used, which can
104// be confusing if users have configs in multiple locations.
105func checkForDuplicateConfigs(out io.Writer) {
106 // Only check if GLAB_CONFIG_DIR is not set
107 if os.Getenv("GLAB_CONFIG_DIR") != "" {
108 return
109 }
111 type configEntry struct {
112 path string
113 info os.FileInfo
114 }
115 var existingConfigs []configEntry
117 // addIfUnique adds a config path if it points to a distinct file.
118 // Uses os.SameFile to handle symlinks (e.g., /home -> /var/home on Silverblue).
119 addIfUnique := func(configPath string) {
120 info, err := os.Stat(configPath)
121 if err != nil {
122 return
123 }
124 for _, entry := range existingConfigs {
125 if os.SameFile(entry.info, info) {
126 return // Same file, skip
127 }
128 }
129 existingConfigs = append(existingConfigs, configEntry{configPath, info})
130 }
132 // Check legacy location first
133 if legacyDir := legacyConfigDir(); legacyDir != "" {
134 addIfUnique(filepath.Join(legacyDir, "config.yml"))
135 }
137 // Check XDG user config
138 addIfUnique(filepath.Join(xdg.ConfigHome, "glab-cli", "config.yml"))
140 // Check system-wide XDG configs
141 for _, dir := range xdg.ConfigDirs {
142 if dir == xdg.ConfigHome {
143 continue
144 }
145 addIfUnique(filepath.Join(dir, "glab-cli", "config.yml"))
146 }
148 // Warn if multiple configs exist
149 if len(existingConfigs) > 1 {
150 fmt.Fprintf(out, "Warning: Multiple config files found. Only the first one will be used.\n")
151 fmt.Fprintf(out, " Using: %s\n", existingConfigs[0].path)
152 for _, entry := range existingConfigs[1:] {
153 fmt.Fprintf(out, " Ignoring: %s\n", entry.path)
154 }
155 fmt.Fprintf(out, "Consider consolidating to one location to avoid confusion.\n")
156 }
157}
159// Init initialises and returns the cached configuration
160func Init() (Config, error) {
161 if cachedConfig != nil || configError != nil {
162 return cachedConfig, configError
163 }
165 // Ensure the config directory exists before attempting to read/write config files.
166 // This is especially important on Windows where os.ReadFile returns a different error
167 // when the parent directory doesn't exist vs. when just the file doesn't exist.
168 configDir := ConfigDir()
169 if err := os.MkdirAll(configDir, 0o750); err != nil {
170 return nil, fmt.Errorf("failed to create config directory: %w", err)
171 }
173 // Check for duplicate configs and warn user
174 checkForDuplicateConfigs(os.Stderr)
176 cachedConfig, configError = ParseDefaultConfig()
178 if os.IsNotExist(configError) {
179 // A fresh config is seeded from the current schema defaults
180 // (glamour_style: auto already), so it needs no migration.
181 if err := cachedConfig.WriteAll(); err != nil {
182 return nil, err
183 }
184 configError = nil
185 } else if configError == nil {
186 if err := migrateGlamourStyleAutoDetection(cachedConfig); err != nil {
187 return nil, err
188 }
189 }
190 return cachedConfig, configError
191}
193// migrateGlamourStyleAutoDetection flips a seeded `glamour_style: dark` to `auto`
194// once, so a later explicit `dark` is kept.
195func migrateGlamourStyleAutoDetection(cfg Config) error {
196 migrated, _, err := cfg.GetWithSource("", "glamour_style_auto_migrated", false)
197 if err != nil {
198 return err
199 }
200 if migrated == "true" {
201 return nil
202 }
204 style, _, err := cfg.GetWithSource("", "glamour_style", false)
205 if err != nil {
206 return err
207 }
208 if style == "dark" {
209 if err := cfg.Set("", "glamour_style", "auto"); err != nil {
210 return err
211 }
212 }
214 if err := cfg.Set("", "glamour_style_auto_migrated", "true"); err != nil {
215 return err
216 }
217 // Read-only config dirs (Nix, containers) must keep working: the
218 // in-memory value already applies, and the next run retries the write.
219 if err := cfg.Write(); err != nil {
220 dbg.Debugf("config: could not persist glamour_style migration: %v", err)
221 }
222 return nil
223}
225func ParseDefaultConfig() (Config, error) {
226 // Try to find existing config first (searches all XDG paths)
227 configPath, err := SearchConfigFile()
228 if err != nil {
229 // No config found, use default writable location
230 configPath = ConfigFile()
231 }
233 // Merge the git-based local config; this is the production path where a
234 // per-repository .git/glab-cli/config.yml may override global settings.
235 cfg, cfgErr := parseConfig(configPath, LocalConfigFile())
237 // SearchConfigFile may locate the config in a read-only system-wide XDG
238 // directory, but glab always persists to the user's writable config dir.
239 // Pin the persistence target to ConfigDir() so Write() keeps writing there
240 // even when the config was read from elsewhere.
241 if fc, ok := cfg.(*fileConfig); ok {
242 fc.dir = ConfigDir()
243 }
245 return cfg, cfgErr
246}
248func readConfigFile(filename string) ([]byte, error) {
249 data, err := os.ReadFile(filename)
250 if err != nil {
251 return nil, pathError(err)
252 }
254 return data, nil
255}
257func writeConfigFile(filename string, data []byte) error {
258 if err := os.MkdirAll(filepath.Dir(filename), 0o750); err != nil {
259 return pathError(err)
260 }
261 return WriteFile(filename, data, 0o600)
262}
264// isSharedConfigDir reports whether dir is a system-wide configuration
265// directory rather than the user's own.
266//
267// legacyConfigDir() is excluded by name because on macOS xdg.ConfigDirs
268// contains $HOME/.config, whose glab-cli subdirectory is that legacy user
269// directory -- membership alone would drop the 0600 rule for the file it
270// protects. Symlinks are resolved so two names for one directory compare equal.
271func isSharedConfigDir(dir string) bool {
272 resolved := resolvePath(dir)
274 if legacy := legacyConfigDir(); legacy != "" && resolvePath(legacy) == resolved {
275 return false
276 }
278 return slices.ContainsFunc(xdg.ConfigDirs, func(base string) bool {
279 return resolvePath(filepath.Join(base, "glab-cli")) == resolved
280 })
281}
283// resolvePath follows symlinks where it can and falls back to an absolute path,
284// so two names for one directory compare equal.
285func resolvePath(p string) string {
286 if resolved, err := filepath.EvalSymlinks(p); err == nil {
287 return resolved
288 }
289 if abs, err := filepath.Abs(p); err == nil {
290 return abs
291 }
292 return p
293}
295func ParseConfigFile(filename string) ([]byte, *yaml.Node, error) {
296 // we want to check if there actually is a file, sometimes
297 // configs are just passed via stubs
298 if stat, err := os.Stat(filename); err == nil {
299 perm := stat.Mode().Perm()
300 // Classify on the directory: parseConfig also reads aliases.yml from it,
301 // and a permission error there is not ErrNotExist, so it fails all of glab.
302 if isSharedConfigDir(filepath.Dir(filename)) {
303 // A config file can run a command through custom_headers.valueFromCommand,
304 // so a shared file another account can write is code execution.
305 if !HasSafeSharedPerms(perm) {
306 return nil, nil, fmt.Errorf(
307 "%s has the permissions %o, but glab requires a system-wide configuration file not to be writable by group or others.\nConsider running `chmod go-w %s`",
308 filename, perm, filename,
309 )
310 }
311 } else if !HasSecurePerms(perm) {
312 return nil, nil, fmt.Errorf(
313 "%s has the permissions %o, but glab requires 600.\nConsider running `chmod 600 %s`",
314 filename, perm, filename,
315 )
316 }
317 }
319 data, err := readConfigFile(filename)
320 if err != nil {
321 return nil, nil, err
322 }
324 root, err := parseConfigData(data)
325 if err != nil {
326 return nil, nil, err
327 }
328 return data, root, err
329}
331func parseConfigData(data []byte) (*yaml.Node, error) {
332 var root yaml.Node
333 err := yaml.Unmarshal(data, &root)
334 if err != nil {
335 return nil, err
336 }
338 if len(root.Content) == 0 {
339 return &yaml.Node{
340 Kind: yaml.DocumentNode,
341 Content: []*yaml.Node{{Kind: yaml.MappingNode}},
342 }, nil
343 }
344 if root.Content[0].Kind != yaml.MappingNode {
345 return &root, fmt.Errorf("expected a top level map")
346 }
347 return &root, nil
348}
350// ParseConfig reads the main config from filename and the aliases file from the
351// same directory. It does not read a separate local config file; callers that
352// need local (per-repository) overrides merged in pass the path explicitly via
353// parseConfig.
354func ParseConfig(filename string) (Config, error) {
355 return parseConfig(filename, "")
356}
358// parseConfig reads the main config from filename and the aliases file from the
359// same directory. When localPath is non-empty, the local config file at that
360// path is merged in under a "local" key (production passes the git-based path;
361// tests pass a temp file). The returned config persists back to the directory
362// it was parsed from, so a config read from a temp dir (tests) or a custom
363// GLAB_CONFIG_DIR writes back to the same place instead of recomputing a global
364// path on Write().
365func parseConfig(filename, localPath string) (Config, error) {
366 dir := filepath.Dir(filename)
368 _, root, err := ParseConfigFile(filename)
369 var confError error
370 if err != nil {
371 if os.IsNotExist(err) {
372 root = NewBlankRoot()
373 confError = os.ErrNotExist
374 } else {
375 return nil, err
376 }
377 }
379 // Merge the local (per-repository) config file when a path is given.
380 if localPath != "" {
381 if _, localRoot, err := ParseConfigFile(localPath); err == nil {
382 if len(localRoot.Content[0].Content) > 0 {
383 newContent := []*yaml.Node{
384 {Value: "local"},
385 localRoot.Content[0],
386 }
387 restContent := root.Content[0].Content
388 root.Content[0].Content = slices.Concat(newContent, restContent)
389 }
390 } else if !errors.Is(err, os.ErrNotExist) {
391 return nil, err
392 }
393 }
395 // Load the aliases file from the same directory as the main config.
396 if _, aliasesRoot, err := ParseConfigFile(filepath.Join(dir, "aliases.yml")); err == nil {
397 if len(aliasesRoot.Content[0].Content) > 0 {
398 newContent := []*yaml.Node{
399 {Value: "aliases"},
400 aliasesRoot.Content[0],
401 }
402 restContent := root.Content[0].Content
403 root.Content[0].Content = slices.Concat(newContent, restContent)
404 }
405 } else if !errors.Is(err, os.ErrNotExist) {
406 return nil, err
407 }
409 return newConfig(root, dir, localPath), confError
410}
412func pathError(err error) error {
413 var pathError *os.PathError
414 if errors.As(err, &pathError) && errors.Is(pathError.Err, syscall.ENOTDIR) {
415 if p := findRegularFile(pathError.Path); p != "" {
416 return fmt.Errorf("remove or rename regular file `%s` (must be a directory)", p)
417 }
418 }
419 return err
420}
422func findRegularFile(p string) string {
423 for {
424 if s, err := os.Stat(p); err == nil && s.Mode().IsRegular() {
425 return p
426 }
427 newPath := filepath.Dir(p)
428 if newPath == p || newPath == "/" || newPath == "." {
429 break
430 }
431 p = newPath
432 }
433 return ""
434}
Diagnostics6 git calls · 30 ms
CallStatusSizeTime030 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
fetchcombine:blob:none+tree:2 · deepen 12004.2 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=4273 git.response.cache=HIT git.response.duration_ms=3 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=3 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:02001.4 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=1391 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=e9da9edfdcf44933ee5fa121d411de326220161c 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=1391 git.pkt.payload.max=1364 git.sideband.band1.bytes=1364 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=1364 git.pack.trailer=bf750bd385ed98d15e1fea1289d3b00caa61d64cOpen pack map
fetch2004.4 KiB · hit23 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=23 git.response.bytes=4474 git.response.cache=HIT git.response.duration_ms=23 git.fetch.wants=d419b3d2d011f9ee2ffcb9f9bda9253b163f2b92 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=4474 git.pkt.payload.max=4447 git.sideband.band1.bytes=4447 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
- a5e1901b4ea05b65
- Request
- 6f65f705…
- 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