Debian Codegraph @

configs.go

raw
1 package gitconfig
2
3 import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "sort"
8 "strings"
9
10 "github.com/gopasspw/gopass/pkg/appdir"
11 "github.com/gopasspw/gopass/pkg/debug"
12 "github.com/gopasspw/gopass/pkg/set"
13 )
14
15 // Configs represents all git configuration files for a repository.
16 //
17 // Configs manages multiple Config objects from different scopes with a unified
18 // interface. It handles loading and merging configurations from multiple sourc with priority.
19 //
20 // Scope Priority (highest to lowest):
21 // 1. Environment variables (GIT_CONFIG_*)
22 // 2. Worktree-specific config (.git/config.worktree)
23 // 3. Local/repository config (.git/config)
24 // 4. Global/user config (~/.gitconfig)
25 // 5. System config (/etc/gitconfig)
26 // 6. Preset/built-in defaults
27 //
28 // Fields:
29 // - Preset: Built-in default configuration (optional)
30 // - system, global, local, worktree, env: Config objects for each scope
31 // - workdir: Working directory (used to locate local and worktree configs)
32 // - Name: Configuration set name (e.g., "git" or "gopass")
33 // - SystemConfig, GlobalConfig, LocalConfig, WorktreeConfig: File paths
34 // - EnvPrefix: Prefix for environment variables (e.g., "GIT_CONFIG")
35 // - NoWrites: If true, prevents all writes to disk
36 //
37 // Usage:
38 //
39 // cfg := New()
40 // cfg.LoadAll(".") // Load from current directory
41 // value := cfg.Get("core.editor") // Reads from all scopes
42 // cfg.SetLocal("core.pager", "less") // Write to local only
43 type Configs struct {
44 Preset *Config
45 system *Config
46 global *Config
47 local *Config
48 worktree *Config
49 env *Config
50 workdir string
51
52 Name string
53 SystemConfig string
54 GlobalConfig string
55 LocalConfig string
56 WorktreeConfig string
57 EnvPrefix string
58 NoWrites bool
59 }
60
61 // New creates a new Configs instance with default configuration.
62 //
63 // The returned instance is not yet loaded. Call LoadAll() to load configurations.
64 //
65 // Default settings:
66 // - Name: "git"
67 // - SystemConfig: "/etc/gitconfig" (Unix) or auto-detected (Windows)
68 // - GlobalConfig: "~/.gitconfig"
69 // - LocalConfig: "config" (relative to workdir)
70 // - WorktreeConfig: "config.worktree" (relative to workdir)
71 // - EnvPrefix: "GIT_CONFIG"
72 // - NoWrites: false (allows persisting changes)
73 //
74 // These settings can be customized before calling LoadAll():
75 //
76 // cfg := New()
77 // cfg.SystemConfig = "/etc/myapp/config"
78 // cfg.EnvPrefix = "MYAPP_CONFIG"
79 // cfg.LoadAll(".")
80 func New() *Configs {
81 return &Configs{
82 system: &Config{
83 readonly: true,
84 },
85 global: &Config{
86 path: globalConfigFile(name),
87 },
88 local: &Config{},
89 worktree: &Config{},
90 env: &Config{
91 noWrites: true,
92 },
93
94 Name: name,
95 SystemConfig: systemConfig,
96 GlobalConfig: globalConfig,
97 LocalConfig: localConfig,
98 WorktreeConfig: worktreeConfig,
99 EnvPrefix: envPrefix,
100 }
101 }
102
103 // Reload reloads all configuration files from disk.
104 //
105 // This is useful when configuration files have been modified externally.
106 // Uses the same workdir that was provided to the last LoadAll call.
107 func (cs *Configs) Reload() {
108 cs.LoadAll(cs.workdir)
109 }
110
111 // String implements fmt.Stringer for debugging.
112 func (cs *Configs) String() string {
113 return fmt.Sprintf("GitConfigs{Name: %s - Workdir: %s - Env: %s - System: %s - Global: %s - Local: %s - Worktree: %s}", cs.Name, cs.workdir, cs.EnvPrefix, cs.SystemConfig, cs.GlobalConfig, cs.LocalConfig, cs.WorktreeConfig)
114 }
115
116 // LoadAll loads all known configuration files from their configured locations.
117 //
118 // Behavior:
119 // - Loads configs from all scopes (system, global, local, worktree, env)
120 // - Missing or invalid files are silently ignored
121 // - Never returns an error (always returns &cs for chaining)
122 // - workdir is optional; if empty, local and worktree configs are not loaded
123 // - Processes include and includeIf directives
124 // - Merges all configs with proper scope priority
125 //
126 // Parameters:
127 // - workdir: Working directory (usually repo root) to locate local/worktree configs
128 //
129 // Example:
130 //
131 // cfg := New()
132 // cfg.LoadAll("/path/to/repo")
133 // // Now ready to use Get, Set, etc.
134 func (cs *Configs) LoadAll(workdir string) *Configs {
135 cs.workdir = workdir
136
137 debug.Log("Loading gitconfigs for %s", cs.Name)
138
139 // load the system config, if any
140 if os.Getenv(cs.EnvPrefix+"_NOSYSTEM") == "" {
141 c, err := LoadConfig(cs.SystemConfig)
142 if err != nil {
143 debug.V(1).Log("[%s] failed to load system config: %s", cs.Name, err)
144 } else {
145 debug.V(1).Log("[%s] loaded system config from %s", cs.Name, cs.SystemConfig)
146 cs.system = c
147 // the system config should generally not be written from gopass.
148 // in almost any scenario gopass shouldn't have write access
149 // and even if it does we shouldn't accidentially change it.
150 // It's for operators and package mainatiners.
151 cs.system.readonly = true
152 }
153 }
154
155 // load the "global" (per user) config, if any
156 cs.loadGlobalConfigs()
157 cs.global.noWrites = cs.NoWrites
158
159 // load the local config, if any
160 if workdir != "" {
161 localConfigPath := filepath.Join(workdir, cs.LocalConfig)
162 c, err := LoadConfig(localConfigPath)
163 if err != nil {
164 debug.V(1).Log("[%s] failed to load local config from %s: %s", cs.Name, localConfigPath, err)
165 // set the path just in case we want to modify / write to it later
166 cs.local.path = localConfigPath
167 } else {
168 debug.V(1).Log("[%s] loaded local config from %s", cs.Name, localConfigPath)
169 cs.local = c
170 }
171 }
172 cs.local.noWrites = cs.NoWrites
173
174 // load the worktree config, if any
175 if workdir != "" {
176 worktreeConfigPath := filepath.Join(workdir, cs.WorktreeConfig)
177 c, err := LoadConfig(worktreeConfigPath)
178 if err != nil {
179 debug.V(3).Log("[%s] failed to load worktree config from %s: %s", cs.Name, worktreeConfigPath, err)
180 // set the path just in case we want to modify / write to it later
181 cs.worktree.path = worktreeConfigPath
182 } else {
183 debug.V(1).Log("[%s] loaded worktree config from %s", cs.Name, worktreeConfigPath)
184 cs.worktree = c
185 }
186 }
187 cs.worktree.noWrites = cs.NoWrites
188
189 // load any env vars
190 cs.env = LoadConfigFromEnv(cs.EnvPrefix)
191
192 return cs
193 }
194
195 // globalConfigFile returns the path to the global (per-user) config file using XDG base directory spec.
196 //
197 // The defaultlocation is $XDG_CONFIG_HOME/<name>/config (typically ~/.config/git/config for Git).
198 // This follows the XDG Base Directory specification for user-specific configuration files.
199 func globalConfigFile(name string) string {
200 // $XDG_CONFIG_HOME/git/config
201 return filepath.Join(appdir.New(name).UserConfig(), "config")
202 }
203
204 // loadGlobalConfigs will try to load the per-user (Git calls them "global") configs.
205 // Since we might need to try different locations but only want to use the first one
206 // it's easier to handle this in its own method.
207 func (cs *Configs) loadGlobalConfigs() string {
208 locs := []string{
209 globalConfigFile(cs.Name),
210 }
211
212 if cs.GlobalConfig != "" {
213 // ~/.gitconfig
214 locs = append(locs, filepath.Join(appdir.UserHome(), cs.GlobalConfig))
215 }
216
217 // if we already have a global config we can just reload it instead of trying all locations
218 if !cs.global.IsEmpty() {
219 if p := cs.global.path; p != "" {
220 debug.V(1).Log("[%s] reloading existing global config from %s", cs.Name, p)
221 cfg, err := LoadConfig(p)
222 if err != nil {
223 debug.V(1).Log("[%s] failed to reload global config from %s", cs.Name, p)
224 } else {
225 cs.global = cfg
226
227 return p
228 }
229 }
230 }
231
232 debug.V(1).Log("[%s] trying to find global configs in %v", cs.Name, locs)
233 for _, p := range locs {
234 // GlobalConfig might be set to an empty string to disable it
235 // and instead of the XDG_CONFIG_HOME path only.
236 if p == "" {
237 continue
238 }
239 cfg, err := LoadConfig(p)
240 if err != nil {
241 debug.V(1).Log("[%s] failed to load global config from %s: %s", cs.Name, p, err)
242
243 continue
244 }
245
246 debug.V(1).Log("[%s] loaded global config from %s", cs.Name, p)
247 cs.global = cfg
248
249 return p
250 }
251
252 debug.V(1).Log("[%s] no global config found", cs.Name)
253
254 // set the path to the default one in case we want to write to it (create it) later
255 cs.global = &Config{
256 path: globalConfigFile(cs.Name),
257 }
258
259 return ""
260 }
261
262 // HasGlobalConfig indicates if a per-user config can be found.
263 //
264 // Returns true if a global config file exists at one of the configured locations.
265 func (cs *Configs) HasGlobalConfig() bool {
266 return cs.loadGlobalConfigs() != ""
267 }
268
269 // Get returns the value for the given key from the first scope that contains it.
270 //
271 // Lookup Order (by scope priority):
272 // 1. Environment variables (GIT_CONFIG_*)
273 // 2. Worktree config (.git/config.worktree)
274 // 3. Local config (.git/config)
275 // 4. Global config (~/.gitconfig)
276 // 5. System config (/etc/gitconfig)
277 // 6. Preset/defaults
278 //
279 // The search stops at the first scope that has the key. Earlier scopes override later ones.
280 //
281 // Returns the value as a string. For keys with multiple values, returns the first one.
282 // Returns empty string if key not found in any scope.
283 //
284 // Example:
285 //
286 // editor := cfg.Get("core.editor")
287 // if editor != "" {
288 // fmt.Printf("Using editor: %s\n", editor)
289 // }
290 func (cs *Configs) Get(key string) string {
291 for _, cfg := range []*Config{
292 cs.env,
293 cs.worktree,
294 cs.local,
295 cs.global,
296 cs.system,
297 cs.Preset,
298 } {
299 if cfg == nil || cfg.vars == nil {
300 continue
301 }
302 if v, found := cfg.Get(key); found {
303 return v
304 }
305 }
306
307 debug.V(3).Log("[%s] no value for %s found", cs.Name, key)
308
309 return ""
310 }
311
312 // GetAll returns all values for the given key from the first scope that contains it.
313 //
314 // Like Get but returns all values for keys that can have multiple entries.
315 // See Get documentation for scope priority.
316 //
317 // Returns nil if key not found in any scope.
318 func (cs *Configs) GetAll(key string) []string {
319 for _, cfg := range []*Config{
320 cs.env,
321 cs.worktree,
322 cs.local,
323 cs.global,
324 cs.system,
325 cs.Preset,
326 } {
327 if cfg == nil || cfg.vars == nil {
328 continue
329 }
330 if vs, found := cfg.GetAll(key); found {
331 return vs
332 }
333 }
334
335 debug.V(3).Log("[%s] no value for %s found", cs.Name, key)
336
337 return nil
338 }
339
340 // GetFrom returns the value for the given key from the given scope. Valid scopes are:
341 // env, worktree, local, global, system and preset.
342 func (cs *Configs) GetFrom(key string, scope string) (string, bool) {
343 switch strings.ToLower(scope) {
344 case "env":
345 return cs.env.Get(key)
346 case "worktree":
347 return cs.worktree.Get(key)
348 case "local":
349 return cs.local.Get(key)
350 case "global":
351 return cs.global.Get(key)
352 case "system":
353 return cs.system.Get(key)
354 case "preset":
355 return cs.Preset.Get(key)
356 default:
357 debug.V(3).Log("[%s] unknown config scope %s for key %s", cs.Name, scope, key)
358
359 return "", false
360 }
361 }
362
363 // GetGlobal specifically asks the per-user (global) config for a key.
364 //
365 // This bypasses the scope priority and only reads from the global config.
366 // Useful when you specifically want settings from ~/.gitconfig.
367 //
368 // Returns empty string if the key is not found in the global config.
369 //
370 // Example:
371 //
372 // name, _ := cfg.GetGlobal("user.name")
373 func (cs *Configs) GetGlobal(key string) string {
374 if cs.global == nil {
375 return ""
376 }
377
378 if v, found := cs.global.Get(key); found {
379 return v
380 }
381
382 debug.V(3).Log("[%s] no value for %s found", cs.Name, key)
383
384 return ""
385 }
386
387 // GetLocal specifically asks the per-directory (local) config for a key.
388 //
389 // This bypasses the scope priority and only reads from the local config (.git/config).
390 // Useful when you specifically want settings from the repository's config.
391 //
392 // Returns empty string if the key is not found in the local config.
393 //
394 // Example:
395 //
396 // url, _ := cfg.GetLocal("remote.origin.url")
397 func (cs *Configs) GetLocal(key string) string {
398 if cs.local == nil {
399 return ""
400 }
401
402 if v, found := cs.local.Get(key); found {
403 return v
404 }
405
406 debug.V(3).Log("[%s] no value for %s found", cs.Name, key)
407
408 return ""
409 }
410
411 // IsSet returns true if this key is set in any of our configs.
412 func (cs *Configs) IsSet(key string) bool {
413 for _, cfg := range []*Config{
414 cs.env,
415 cs.worktree,
416 cs.local,
417 cs.global,
418 cs.system,
419 cs.Preset,
420 } {
421 if cfg != nil && cfg.IsSet(key) {
422 return true
423 }
424 }
425
426 return false
427 }
428
429 // SetLocal sets (or adds) a key only in the per-directory (local) config.
430 func (cs *Configs) SetLocal(key, value string) error {
431 if cs.workdir == "" {
432 return ErrWorkdirNotSet
433 }
434 if cs.local == nil {
435 cs.local = &Config{
436 path: filepath.Join(cs.workdir, cs.LocalConfig),
437 }
438 }
439 if cs.local.path == "" {
440 cs.local.path = filepath.Join(cs.workdir, cs.LocalConfig)
441 }
442
443 return cs.local.Set(key, value)
444 }
445
446 // SetGlobal sets (or adds) a key only in the per-user (global) config.
447 func (cs *Configs) SetGlobal(key, value string) error {
448 if cs.global == nil {
449 cs.global = &Config{
450 path: globalConfigFile(cs.Name),
451 }
452 }
453
454 return cs.global.Set(key, value)
455 }
456
457 // SetEnv sets (or adds) a key in the per-process (env) config. Useful
458 // for persisting flags during the invocation.
459 func (cs *Configs) SetEnv(key, value string) error {
460 if cs.env == nil {
461 cs.env = &Config{
462 noWrites: true,
463 }
464 }
465
466 return cs.env.Set(key, value)
467 }
468
469 // UnsetLocal deletes a key from the local config.
470 func (cs *Configs) UnsetLocal(key string) error {
471 if cs.local == nil {
472 return nil
473 }
474
475 return cs.local.Unset(key)
476 }
477
478 // UnsetGlobal deletes a key from the global config.
479 func (cs *Configs) UnsetGlobal(key string) error {
480 if cs.global == nil {
481 return nil
482 }
483
484 return cs.global.Unset(key)
485 }
486
487 // Keys returns a list of all keys from all available scopes. Every key has section and possibly
488 // a subsection. They are separated by dots. The subsection itself may contain dots. The final
489 // key name and the section MUST NOT contain dots.
490 //
491 // Examples
492 // - remote.gist.gopass.pw.path -> section: remote, subsection: gist.gopass.pw, key: path
493 // - core.timeout -> section: core, key: timeout
494 func (cs *Configs) Keys() []string {
495 keys := make([]string, 0, 128)
496
497 for _, cfg := range []*Config{
498 cs.Preset,
499 cs.system,
500 cs.global,
501 cs.local,
502 cs.worktree,
503 cs.env,
504 } {
505 if cfg == nil {
506 continue
507 }
508 for k := range cfg.vars {
509 keys = append(keys, k)
510 }
511 }
512
513 return set.Sorted(keys)
514 }
515
516 // List returns all keys matching the given prefix. The prefix can be empty,
517 // then this is identical to Keys().
518 func (cs *Configs) List(prefix string) []string {
519 return set.SortedFiltered(cs.Keys(), func(k string) bool {
520 return strings.HasPrefix(k, prefix)
521 })
522 }
523
524 // ListSections returns a sorted list of all sections.
525 func (cs *Configs) ListSections() []string {
526 return set.Sorted(set.Apply(cs.Keys(), func(k string) string {
527 section, _, _ := splitKey(k)
528
529 return section
530 }))
531 }
532
533 // ListSubsections returns a sorted list of all subsections
534 // in the given section.
535 func (cs *Configs) ListSubsections(wantSection string) []string {
536 // apply extracts the subsection and matches it to the empty string
537 // if it doesn't belong to the section we're looking for. Then the
538 // filter func filters out any empty string.
539 return set.SortedFiltered(set.Apply(cs.Keys(), func(k string) string {
540 section, subsection, _ := splitKey(k)
541 if section != wantSection {
542 return ""
543 }
544
545 return subsection
546 }), func(s string) bool {
547 return s != ""
548 })
549 }
550
551 // KVList returns a list of all keys and values matching the given prefix.
552 func (cs *Configs) KVList(prefix, sep string) []string {
553 if sep == "" {
554 sep = "="
555 }
556 keys := cs.List(prefix)
557 kv := make([]string, 0, len(keys))
558 for _, k := range keys {
559 vs := cs.GetAll(k)
560 for _, v := range vs {
561 if v == "" {
562 continue
563 }
564 kv = append(kv, fmt.Sprintf("%s%s%s", k, sep, v))
565 }
566 }
567
568 sort.Strings(kv)
569
570 return kv
571 }