| 1 |
package gitconfig |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"fmt" |
| 6 |
"io" |
| 7 |
"maps" |
| 8 |
"os" |
| 9 |
"path" |
| 10 |
"path/filepath" |
| 11 |
"regexp" |
| 12 |
"slices" |
| 13 |
"strconv" |
| 14 |
"strings" |
| 15 |
|
| 16 |
"github.com/gopasspw/gopass/pkg/debug" |
| 17 |
) |
| 18 |
|
| 19 |
var ( |
| 20 |
keyValueTpl = "\t%s = %s%s" |
| 21 |
keyTpl = "\t%s%s" |
| 22 |
reQuotedComment = regexp.MustCompile(`"[^"]*[#;][^"]*"`) |
| 23 |
// "The variable names are case-insensitive, allow only alphanumeric characters and -, and must start with an alphabetic character."". |
| 24 |
reValidKey = regexp.MustCompile(`^[a-z]+[a-z0-9-]*$`) |
| 25 |
|
| 26 |
// CompatMode enables compatibility mode, which disables certain features like value unescaping. |
| 27 |
CompatMode bool |
| 28 |
) |
| 29 |
|
| 30 |
// Config represents a single git configuration file from one scope. |
| 31 |
// |
| 32 |
// Config handles reading and writing a single configuration file while attempting |
| 33 |
// to preserve the original formatting (comments, whitespace, section order). |
| 34 |
// |
| 35 |
// Fields: |
| 36 |
// - path: File path of this config file |
| 37 |
// - readonly: If true, prevents any modifications (even in-memory) |
| 38 |
// - noWrites: If true, prevents persisting changes to disk (useful for testing) |
| 39 |
// - raw: Maintains the raw text representation for round-trip fidelity |
| 40 |
// - vars: Map of normalized keys to their values (may be multiple values per key) |
| 41 |
// - branch: Current git branch name (for onbranch conditionals) |
| 42 |
// |
| 43 |
// Note: Config is not thread-safe. Concurrent access from multiple goroutines |
| 44 |
// is not supported. Callers must provide synchronization if needed. |
| 45 |
// |
| 46 |
// Typical Usage: |
| 47 |
// |
| 48 |
// cfg, err := LoadConfig("~/.gitconfig") |
| 49 |
// if err != nil { ... } |
| 50 |
// value, ok := cfg.Get("core.editor") |
| 51 |
// if err := cfg.Set("core.pager", "less"); err != nil { ... } |
| 52 |
type Config struct { |
| 53 |
path string |
| 54 |
readonly bool // do not allow modifying values (even in memory) |
| 55 |
noWrites bool // do not persist changes to disk (e.g. for tests) |
| 56 |
raw strings.Builder |
| 57 |
vars map[string][]string |
| 58 |
branch string |
| 59 |
} |
| 60 |
|
| 61 |
// IsEmpty returns true if the config is empty (no configuration loaded). |
| 62 |
// |
| 63 |
// An empty config is one that: |
| 64 |
// - Is nil |
| 65 |
// - Has no variables loaded |
| 66 |
// - Has no raw content (not just missing path reference) |
| 67 |
// |
| 68 |
// This is used to distinguish between "not yet loaded" and "loaded but empty file". |
| 69 |
func (c *Config) IsEmpty() bool { |
| 70 |
if c == nil || c.vars == nil { |
| 71 |
return true |
| 72 |
} |
| 73 |
|
| 74 |
if c.raw.Len() > 0 { |
| 75 |
return false |
| 76 |
} |
| 77 |
|
| 78 |
return true |
| 79 |
} |
| 80 |
|
| 81 |
// Unset deletes a key from the config. |
| 82 |
// |
| 83 |
// Behavior: |
| 84 |
// - If the key exists, it's removed from vars and the raw config string |
| 85 |
// - If the key doesn't exist, this is a no-op (no error) |
| 86 |
// - The underlying config file is updated if possible |
| 87 |
// - Readonly configs silently ignore the unset operation |
| 88 |
// |
| 89 |
// Note: Currently does not remove entire sections, only individual keys within sections. |
| 90 |
// |
| 91 |
// Example: |
| 92 |
// |
| 93 |
// if err := cfg.Unset("core.pager"); err != nil { |
| 94 |
// log.Fatal(err) |
| 95 |
// } |
| 96 |
func (c *Config) Unset(key string) error { |
| 97 |
if c.readonly { |
| 98 |
return nil |
| 99 |
} |
| 100 |
|
| 101 |
section, _, subkey := splitKey(key) |
| 102 |
if section == "" || subkey == "" { |
| 103 |
return fmt.Errorf("%w: %s", ErrInvalidKey, key) |
| 104 |
} |
| 105 |
|
| 106 |
key = canonicalizeKey(key) |
| 107 |
|
| 108 |
_, present := c.vars[key] |
| 109 |
if !present { |
| 110 |
return nil |
| 111 |
} |
| 112 |
|
| 113 |
delete(c.vars, key) |
| 114 |
|
| 115 |
return c.rewriteRaw(key, "", func(fKey, key, value, comment, _ string) (string, bool) { |
| 116 |
return "", true |
| 117 |
}) |
| 118 |
} |
| 119 |
|
| 120 |
// Get returns the first value of the key. |
| 121 |
// |
| 122 |
// For keys with multiple values, Get returns only the first one. |
| 123 |
// Use GetAll to retrieve all values for a key. |
| 124 |
// |
| 125 |
// The key is case-insensitive for sections and key names but case-sensitive |
| 126 |
// for subsection names (per git-config specification). |
| 127 |
// |
| 128 |
// Returns (value, true) if the key is found, ("", false) otherwise. |
| 129 |
// |
| 130 |
// Example: |
| 131 |
// |
| 132 |
// v, ok := cfg.Get("core.editor") |
| 133 |
// if ok { |
| 134 |
// fmt.Printf("Editor: %s\n", v) |
| 135 |
// } |
| 136 |
func (c *Config) Get(key string) (string, bool) { |
| 137 |
key = canonicalizeKey(key) |
| 138 |
vs, found := c.vars[key] |
| 139 |
if !found || len(vs) < 1 { |
| 140 |
return "", false |
| 141 |
} |
| 142 |
|
| 143 |
return vs[0], true |
| 144 |
} |
| 145 |
|
| 146 |
// GetAll returns all values of the key. |
| 147 |
// |
| 148 |
// Git config allows multiple values for the same key. This is common for: |
| 149 |
// - Multiple include paths |
| 150 |
// - Multiple aliases |
| 151 |
// - Arrays in custom configurations |
| 152 |
// |
| 153 |
// Returns (values, true) if the key is found, (nil, false) otherwise. |
| 154 |
// If found, values will be non-nil but may be empty. |
| 155 |
// |
| 156 |
// Example: |
| 157 |
// |
| 158 |
// paths, ok := cfg.GetAll("include.path") |
| 159 |
// if ok { |
| 160 |
// for _, path := range paths { |
| 161 |
// fmt.Printf("Include: %s\n", path) |
| 162 |
// } |
| 163 |
// } |
| 164 |
func (c *Config) GetAll(key string) ([]string, bool) { |
| 165 |
key = canonicalizeKey(key) |
| 166 |
vs, found := c.vars[key] |
| 167 |
if !found { |
| 168 |
return nil, false |
| 169 |
} |
| 170 |
|
| 171 |
return vs, true |
| 172 |
} |
| 173 |
|
| 174 |
// IsSet returns true if the key was set in this config. |
| 175 |
// |
| 176 |
// Returns true even if the value is empty string (unlike checking Get with ok). |
| 177 |
// |
| 178 |
// Example: |
| 179 |
// |
| 180 |
// if cfg.IsSet("core.editor") { |
| 181 |
// fmt.Println("Editor is configured") |
| 182 |
// } |
| 183 |
func (c *Config) IsSet(key string) bool { |
| 184 |
key = canonicalizeKey(key) |
| 185 |
_, present := c.vars[key] |
| 186 |
|
| 187 |
return present |
| 188 |
} |
| 189 |
|
| 190 |
// Set updates or adds a key in the config. |
| 191 |
// |
| 192 |
// Behavior: |
| 193 |
// - If the key exists, the first value is updated |
| 194 |
// - If the key doesn't exist, it's added to an existing section or a new section |
| 195 |
// - If possible, the underlying config file is written to disk |
| 196 |
// - Original formatting (comments, whitespace) is preserved where possible |
| 197 |
// |
| 198 |
// Errors: |
| 199 |
// - Returns error if readonly or key is invalid (missing section or key name) |
| 200 |
// - Returns error if file write fails (but in-memory value may be set) |
| 201 |
// |
| 202 |
// This method normalizes the key (lowercase sections and key names) but preserves |
| 203 |
// subsect names' case. |
| 204 |
// |
| 205 |
// Example: |
| 206 |
// |
| 207 |
// if err := cfg.Set("core.pager", "less"); err != nil { |
| 208 |
// log.Fatal(err) |
| 209 |
// } |
| 210 |
func (c *Config) Set(key, value string) error { |
| 211 |
section, _, subkey := splitKey(key) |
| 212 |
if section == "" || subkey == "" { |
| 213 |
return fmt.Errorf("%w: %s", ErrInvalidKey, key) |
| 214 |
} |
| 215 |
|
| 216 |
// can't set env vars |
| 217 |
if c.readonly { |
| 218 |
debug.Log("can not write to a readonly config") |
| 219 |
|
| 220 |
return nil |
| 221 |
} |
| 222 |
|
| 223 |
if c.vars == nil { |
| 224 |
c.vars = make(map[string][]string, 16) |
| 225 |
} |
| 226 |
|
| 227 |
// already present at the same value, no need to rewrite the config |
| 228 |
if vs, found := c.vars[key]; found { |
| 229 |
if slices.Contains(vs, value) { |
| 230 |
debug.V(1).Log("key %q with value %q already present. Not re-writing.", key, value) |
| 231 |
|
| 232 |
return nil |
| 233 |
} |
| 234 |
} |
| 235 |
|
| 236 |
vs, present := c.vars[key] |
| 237 |
if vs == nil { |
| 238 |
vs = make([]string, 1) |
| 239 |
} |
| 240 |
vs[0] = value |
| 241 |
c.vars[key] = vs |
| 242 |
|
| 243 |
debug.V(3).Log("set %q to %q", key, value) |
| 244 |
|
| 245 |
// a new key, insert it into an existing section, if any |
| 246 |
if !present { |
| 247 |
debug.V(3).Log("inserting value") |
| 248 |
|
| 249 |
return c.insertValue(key, value) |
| 250 |
} |
| 251 |
|
| 252 |
debug.V(3).Log("updating value") |
| 253 |
|
| 254 |
var updated bool |
| 255 |
|
| 256 |
return c.rewriteRaw(key, value, func(fKey, sKey, value, comment, line string) (string, bool) { |
| 257 |
if updated { |
| 258 |
return line, false |
| 259 |
} |
| 260 |
updated = true |
| 261 |
|
| 262 |
return formatKeyValue(sKey, value, comment), false |
| 263 |
}) |
| 264 |
} |
| 265 |
|
| 266 |
func (c *Config) insertValue(key, value string) error { |
| 267 |
debug.V(3).Log("input (%s: %s): \n--------------\n%s\n--------------\n", key, value, strings.Join(strings.Split("- "+c.raw.String(), "\n"), "\n- ")) |
| 268 |
|
| 269 |
wSection, wSubsection, wKey := splitKey(key) |
| 270 |
|
| 271 |
s := bufio.NewScanner(strings.NewReader(c.raw.String())) |
| 272 |
|
| 273 |
lines := make([]string, 0, 128) |
| 274 |
var section string |
| 275 |
var subsection string |
| 276 |
var written bool |
| 277 |
for s.Scan() { |
| 278 |
line := s.Text() |
| 279 |
|
| 280 |
lines = append(lines, line) |
| 281 |
|
| 282 |
if written { |
| 283 |
continue |
| 284 |
} |
| 285 |
if strings.HasPrefix(line, "#") { |
| 286 |
continue |
| 287 |
} |
| 288 |
if strings.HasPrefix(line, ";") { |
| 289 |
continue |
| 290 |
} |
| 291 |
if strings.HasPrefix(line, "[") { |
| 292 |
s, subs, skip := parseSectionHeader(line) |
| 293 |
if skip { |
| 294 |
continue |
| 295 |
} |
| 296 |
section = s |
| 297 |
subsection = subs |
| 298 |
} |
| 299 |
|
| 300 |
if section != wSection { |
| 301 |
continue |
| 302 |
} |
| 303 |
if subsection != wSubsection { |
| 304 |
continue |
| 305 |
} |
| 306 |
|
| 307 |
lines = append(lines, formatKeyValue(wKey, value, "")) |
| 308 |
written = true |
| 309 |
} |
| 310 |
|
| 311 |
// not added to an existing section, so add it at the end |
| 312 |
if !written { |
| 313 |
sect := fmt.Sprintf("[%s]", wSection) |
| 314 |
if wSubsection != "" { |
| 315 |
sect = fmt.Sprintf("[%s \"%s\"]", wSection, wSubsection) |
| 316 |
} |
| 317 |
lines = append(lines, sect) |
| 318 |
lines = append(lines, formatKeyValue(wKey, value, "")) |
| 319 |
} |
| 320 |
|
| 321 |
c.raw = strings.Builder{} |
| 322 |
c.raw.WriteString(strings.Join(lines, "\n")) |
| 323 |
c.raw.WriteString("\n") |
| 324 |
|
| 325 |
debug.V(3).Log("output: \n--------------\n%s\n--------------\n", strings.Join(strings.Split("+ "+c.raw.String(), "\n"), "\n+ ")) |
| 326 |
|
| 327 |
return c.flushRaw() |
| 328 |
} |
| 329 |
|
| 330 |
// formatKeyValue formats a configuration key-value pair for writing to file. |
| 331 |
// If the value is empty or whitespace-only, only the key is written. |
| 332 |
// The comment parameter preserves any trailing comment from the original line. |
| 333 |
func formatKeyValue(key, value, comment string) string { |
| 334 |
if strings.TrimSpace(value) == "" { |
| 335 |
return fmt.Sprintf(keyTpl, key, comment) |
| 336 |
} |
| 337 |
|
| 338 |
return fmt.Sprintf(keyValueTpl, key, value, comment) |
| 339 |
} |
| 340 |
|
| 341 |
// parseSectionHeader extracts the section and subsection from a config file section header line. |
| 342 |
// For example: |
| 343 |
// |
| 344 |
// "[core]" returns ("core", "", false) |
| 345 |
// "[remote \"origin\"]" returns ("remote", "origin", false) |
| 346 |
// "[]" returns ("", "", true) to indicate skip |
| 347 |
// |
| 348 |
// The skip return value indicates whether this line should be ignored. |
| 349 |
func parseSectionHeader(line string) (section, subsection string, skip bool) { //nolint:nonamedreturns |
| 350 |
line = strings.Trim(line, "[]") |
| 351 |
if line == "" { |
| 352 |
return "", "", true |
| 353 |
} |
| 354 |
wsp := strings.Index(line, " ") |
| 355 |
if wsp < 0 { |
| 356 |
return line, "", false |
| 357 |
} |
| 358 |
|
| 359 |
section = line[:wsp] |
| 360 |
subsection = line[wsp+1:] |
| 361 |
subsection = strings.ReplaceAll(subsection, "\\", "") |
| 362 |
subsection = strings.TrimPrefix(subsection, "\"") |
| 363 |
subsection = strings.TrimSuffix(subsection, "\"") |
| 364 |
|
| 365 |
return section, subsection, false |
| 366 |
} |
| 367 |
|
| 368 |
// rewriteRaw is used to rewrite the raw config copy. It is used for set and unset operations |
| 369 |
// with different callbacks each. |
| 370 |
func (c *Config) rewriteRaw(key, value string, cb parseFunc) error { |
| 371 |
debug.V(3).Log("input (%s: %s): \n--------------\n%s\n--------------\n", key, value, strings.Join(strings.Split("- "+c.raw.String(), "\n"), "\n- ")) |
| 372 |
|
| 373 |
lines := parseConfig(strings.NewReader(c.raw.String()), key, value, cb) |
| 374 |
|
| 375 |
c.raw = strings.Builder{} |
| 376 |
c.raw.WriteString(strings.Join(lines, "\n")) |
| 377 |
c.raw.WriteString("\n") |
| 378 |
|
| 379 |
debug.V(3).Log("output: \n--------------\n%s\n--------------\n", strings.Join(strings.Split("+ "+c.raw.String(), "\n"), "\n+ ")) |
| 380 |
|
| 381 |
return c.flushRaw() |
| 382 |
} |
| 383 |
|
| 384 |
func (c *Config) flushRaw() error { |
| 385 |
if c.noWrites || c.path == "" { |
| 386 |
debug.V(3).Log("not writing changes to disk (noWrites %t, path %q)", c.noWrites, c.path) |
| 387 |
|
| 388 |
return nil |
| 389 |
} |
| 390 |
|
| 391 |
if err := os.MkdirAll(filepath.Dir(c.path), 0o700); err != nil { |
| 392 |
return fmt.Errorf("%w: %s: %w", ErrCreateConfigDir, filepath.Dir(c.path), err) |
| 393 |
} |
| 394 |
|
| 395 |
debug.V(3).Log("writing config to %s: \n--------------\n%s\n--------------", c.path, c.raw.String()) |
| 396 |
|
| 397 |
if err := os.WriteFile(c.path, []byte(c.raw.String()), 0o600); err != nil { |
| 398 |
return fmt.Errorf("%w: %s: %w", ErrWriteConfig, c.path, err) |
| 399 |
} |
| 400 |
|
| 401 |
debug.V(1).Log("wrote config to %s", c.path) |
| 402 |
|
| 403 |
return nil |
| 404 |
} |
| 405 |
|
| 406 |
type parseFunc func(fqkn, skn, value, comment, fullLine string) (newLine string, skipLine bool) |
| 407 |
|
| 408 |
// parseConfig implements a simple parser for the gitconfig subset we support. |
| 409 |
// The idea is to save all lines unaltered so we can reproduce the config |
| 410 |
// almost exactly. Then we skip comments and extract section and subsection |
| 411 |
// header. The next steps depend on the mode. Either we want to extract the |
| 412 |
// values when loading (key and value empty, parseFunc adds the key-value pairs |
| 413 |
// to the vars map), update a key (key is the target key, value the new value) |
| 414 |
// or delete a key (parseFunc returns skip). |
| 415 |
func parseConfig(in io.Reader, key, value string, cb parseFunc) []string { |
| 416 |
wSection, wSubsection, wKey := splitKey(key) |
| 417 |
|
| 418 |
s := bufio.NewScanner(in) |
| 419 |
|
| 420 |
lines := make([]string, 0, 128) |
| 421 |
var section string |
| 422 |
var subsection string |
| 423 |
for s.Scan() { |
| 424 |
fullLine := s.Text() |
| 425 |
|
| 426 |
lines = append(lines, fullLine) |
| 427 |
|
| 428 |
line := strings.TrimSpace(fullLine) |
| 429 |
// Handle full-line comments |
| 430 |
if strings.HasPrefix(line, "#") { |
| 431 |
continue |
| 432 |
} |
| 433 |
if strings.HasPrefix(line, ";") { |
| 434 |
continue |
| 435 |
} |
| 436 |
|
| 437 |
// Handle section headers |
| 438 |
if strings.HasPrefix(line, "[") { |
| 439 |
s, subs, skip := parseSectionHeader(line) |
| 440 |
if skip { |
| 441 |
continue |
| 442 |
} |
| 443 |
section = s |
| 444 |
subsection = subs |
| 445 |
} |
| 446 |
|
| 447 |
if key != "" && (section != wSection && subsection != wSubsection) { |
| 448 |
continue |
| 449 |
} |
| 450 |
|
| 451 |
// Reference: https://git-scm.com/docs/git-config#_syntax. |
| 452 |
k, v, found := strings.Cut(line, "=") |
| 453 |
// This is a special case for bare booleans. |
| 454 |
if !found && !strings.HasPrefix(line, "[") && strings.TrimSpace(line) != "" { |
| 455 |
v = "" |
| 456 |
found = true |
| 457 |
} |
| 458 |
if !found { |
| 459 |
debug.V(3).Log("no valid KV-pair on line: %q", line) |
| 460 |
|
| 461 |
continue |
| 462 |
} |
| 463 |
// Remove whitespace from key and value that might be around the '=' |
| 464 |
// "Whitespace characters surrounding name, = and value are discarded." |
| 465 |
// https://git-scm.com/docs/git-config#_syntax |
| 466 |
k = strings.TrimSpace(k) |
| 467 |
v = strings.TrimSpace(v) |
| 468 |
|
| 469 |
// keep a copy of the original key for serialization. |
| 470 |
ok := k |
| 471 |
// "The variable names are case-insensitive" |
| 472 |
k = strings.ToLower(k) |
| 473 |
|
| 474 |
if !reValidKey.MatchString(k) { |
| 475 |
debug.V(3).Log("invalid key %q in line: %q", k, line) |
| 476 |
|
| 477 |
continue |
| 478 |
} |
| 479 |
|
| 480 |
fKey := section + "." |
| 481 |
if subsection != "" { |
| 482 |
fKey += subsection + "." |
| 483 |
} |
| 484 |
fKey += k |
| 485 |
if key == "" { |
| 486 |
wKey = ok |
| 487 |
} |
| 488 |
|
| 489 |
// extract possilbe comment from the value |
| 490 |
oValue, comment := splitValueComment(v) |
| 491 |
|
| 492 |
// unescape value |
| 493 |
if !CompatMode { |
| 494 |
oValue = unescapeValue(oValue) |
| 495 |
} |
| 496 |
|
| 497 |
if key != "" && (key != fKey) { |
| 498 |
continue |
| 499 |
} |
| 500 |
if key != "" { |
| 501 |
oValue = value |
| 502 |
} |
| 503 |
|
| 504 |
newLine, skip := cb(fKey, wKey, oValue, comment, fullLine) |
| 505 |
debug.V(3).Log("parsed line: %q -> %q, skip: %t", fullLine, newLine, skip) |
| 506 |
if skip { |
| 507 |
// remove the last line |
| 508 |
lines = lines[:len(lines)-1] |
| 509 |
|
| 510 |
continue |
| 511 |
} |
| 512 |
lines[len(lines)-1] = newLine |
| 513 |
} |
| 514 |
|
| 515 |
return lines |
| 516 |
} |
| 517 |
|
| 518 |
// splitValueComment separates a config value from any trailing comment. |
| 519 |
// Handles three cases: no comment, unquoted value with comment, and quoted value with comment. |
| 520 |
// Returns the value (unquoted) and the comment portion (including # or ;). |
| 521 |
func splitValueComment(rValue string) (string, string) { |
| 522 |
// Trivial case: no comment. Return early, do not alter anything. |
| 523 |
if !strings.ContainsAny(rValue, "#;") { |
| 524 |
// "If value needs to contain leading or trailing whitespace characters, it must be enclosed in double quotation marks (")." |
| 525 |
rValue = strings.Trim(rValue, "\"") |
| 526 |
|
| 527 |
return rValue, "" |
| 528 |
} |
| 529 |
|
| 530 |
// Medium case: comment present, but not quoted. |
| 531 |
if !reQuotedComment.MatchString(rValue) { |
| 532 |
comment := " " + rValue[strings.IndexAny(rValue, "#;"):] |
| 533 |
rValue = rValue[:strings.IndexAny(rValue, "#;")] |
| 534 |
rValue = strings.TrimSpace(rValue) |
| 535 |
rValue = strings.Trim(rValue, "\"") |
| 536 |
|
| 537 |
return rValue, comment |
| 538 |
} |
| 539 |
|
| 540 |
// Hard case: comment present and quoted. |
| 541 |
return parseLineForComment(rValue) |
| 542 |
} |
| 543 |
|
| 544 |
// unescapeValue processes escape sequences in configuration values. |
| 545 |
// Supports: \\, \", \n (newline), \t (tab), \b (backspace). |
| 546 |
// Other escape sequences (including octal) are not supported per Git config spec. |
| 547 |
func unescapeValue(value string) string { |
| 548 |
value = strings.ReplaceAll(value, `\\`, `\`) |
| 549 |
value = strings.ReplaceAll(value, `\"`, `"`) |
| 550 |
value = strings.ReplaceAll(value, `\n`, "\n") |
| 551 |
value = strings.ReplaceAll(value, `\t`, "\t") |
| 552 |
value = strings.ReplaceAll(value, `\b`, "\b") |
| 553 |
|
| 554 |
return value |
| 555 |
} |
| 556 |
|
| 557 |
// NewFromMap allows creating a new preset config from a map. |
| 558 |
func NewFromMap(data map[string]string) *Config { |
| 559 |
c := &Config{ |
| 560 |
readonly: true, |
| 561 |
vars: make(map[string][]string, len(data)), |
| 562 |
} |
| 563 |
|
| 564 |
for k, v := range data { |
| 565 |
c.vars[k] = []string{v} |
| 566 |
} |
| 567 |
|
| 568 |
return c |
| 569 |
} |
| 570 |
|
| 571 |
// LoadConfig tries to load a gitconfig from the given path. |
| 572 |
func LoadConfig(fn string) (*Config, error) { |
| 573 |
return loadConfigs(fn, "") |
| 574 |
} |
| 575 |
|
| 576 |
// LoadConfigWithWorkdir tries to load a gitconfig from the given path and |
| 577 |
// a workdir. The workdir is used to resolve relative paths in the config. |
| 578 |
func LoadConfigWithWorkdir(fn, workdir string) (*Config, error) { |
| 579 |
c, err := loadConfigs(fn, workdir) |
| 580 |
if err != nil { |
| 581 |
return nil, err |
| 582 |
} |
| 583 |
|
| 584 |
return c, nil |
| 585 |
} |
| 586 |
|
| 587 |
func readGitBranch(workdir string) string { |
| 588 |
if workdir == "" { |
| 589 |
return "" |
| 590 |
} |
| 591 |
gitDir := filepath.Join(workdir, ".git") |
| 592 |
// check if .git is a directory |
| 593 |
if fi, err := os.Stat(gitDir); err != nil || !fi.IsDir() { |
| 594 |
// it might be a file with gitdir: path, not handled for now |
| 595 |
return "" |
| 596 |
} |
| 597 |
|
| 598 |
headFile := filepath.Join(gitDir, "HEAD") |
| 599 |
content, err := os.ReadFile(headFile) |
| 600 |
if err != nil { |
| 601 |
return "" |
| 602 |
} |
| 603 |
|
| 604 |
// content is like "ref: refs/heads/main" |
| 605 |
if branch, found := strings.CutPrefix(string(content), "ref: refs/heads/"); found { |
| 606 |
return strings.TrimSpace(branch) |
| 607 |
} |
| 608 |
|
| 609 |
return "" // detached HEAD or other cases |
| 610 |
} |
| 611 |
|
| 612 |
// getEffectiveIncludes returns all include paths from the config, combining |
| 613 |
// basic [include] directives with conditional [includeIf] directives. |
| 614 |
// The workdir parameter is used to evaluate conditional includes. |
| 615 |
func getEffectiveIncludes(c *Config, workdir string) ([]string, bool) { |
| 616 |
includePaths, includeExists := c.GetAll("include.path") |
| 617 |
|
| 618 |
if cIncludes := getConditionalIncludes(c, workdir); len(cIncludes) > 0 { |
| 619 |
includePaths = append(includePaths, cIncludes...) |
| 620 |
includeExists = true |
| 621 |
} |
| 622 |
|
| 623 |
return includePaths, includeExists |
| 624 |
} |
| 625 |
|
| 626 |
// getConditionalIncludes processes [includeIf "condition"] directives and returns |
| 627 |
// paths that match the current environment. |
| 628 |
// Supported conditions: |
| 629 |
// - gitdir:<pattern> - Include if git directory matches pattern (case-sensitive) |
| 630 |
// - gitdir/i:<pattern> - Include if git directory matches pattern (case-insensitive) |
| 631 |
func getConditionalIncludes(c *Config, workdir string) []string { |
| 632 |
candidates := []string{} |
| 633 |
for k := range c.vars { |
| 634 |
debug.V(3).Log("found config key: %q", k) |
| 635 |
// must have the form includeIf.<condition>.path |
| 636 |
// e.g. includeIf."gitdir:/path/to/group/".path |
| 637 |
// see https://git-scm.com/docs/git-config#_conditional_includes |
| 638 |
if !strings.HasPrefix(k, "includeif.") || !strings.HasSuffix(k, ".path") { |
| 639 |
continue |
| 640 |
} |
| 641 |
candidates = append(candidates, k) |
| 642 |
} |
| 643 |
|
| 644 |
out := make([]string, 0, len(candidates)) |
| 645 |
for _, k := range filterCandidates(candidates, workdir, c) { |
| 646 |
path, found := c.GetAll(k) |
| 647 |
if !found { |
| 648 |
debug.V(3).Log("skipping include candidate %q, no path found", k) |
| 649 |
|
| 650 |
continue |
| 651 |
} |
| 652 |
out = append(out, path...) |
| 653 |
} |
| 654 |
|
| 655 |
return out |
| 656 |
} |
| 657 |
|
| 658 |
// filterCandidates filters the candidates for include paths. |
| 659 |
// Currently only the gitdir condition is supported. |
| 660 |
// Others might be added in the future. |
| 661 |
func filterCandidates(candidates []string, workdir string, c *Config) []string { |
| 662 |
out := make([]string, 0, len(candidates)) |
| 663 |
for _, candidate := range candidates { |
| 664 |
sec, subsec, key := splitKey(candidate) |
| 665 |
if sec != "includeif" || subsec == "" || key != "path" { |
| 666 |
debug.V(3).Log("skipping invalid include candidate %q", candidate) |
| 667 |
|
| 668 |
continue |
| 669 |
} |
| 670 |
|
| 671 |
if matchSubSection(subsec, workdir, c) { |
| 672 |
out = append(out, candidate) |
| 673 |
} |
| 674 |
} |
| 675 |
|
| 676 |
return out |
| 677 |
} |
| 678 |
|
| 679 |
// matchSubSection determines if a subsection condition matches the current environment. |
| 680 |
// Handles gitdir, gitdir/i, onbranch, and other condition types. |
| 681 |
// Returns true if the condition matches and the config should be included. |
| 682 |
func matchSubSection(subsec, workdir string, c *Config) bool { |
| 683 |
if strings.HasPrefix(subsec, "gitdir") { |
| 684 |
caseInsensitive := strings.Contains(subsec, "/i:") |
| 685 |
p := strings.SplitN(subsec, ":", 2) |
| 686 |
dir := p[1] |
| 687 |
|
| 688 |
var exactMatch bool |
| 689 |
if caseInsensitive { |
| 690 |
exactMatch = strings.EqualFold(strings.TrimSuffix(workdir, "/"), strings.TrimSuffix(dir, "/")) |
| 691 |
} else { |
| 692 |
exactMatch = strings.TrimSuffix(workdir, "/") == strings.TrimSuffix(dir, "/") |
| 693 |
} |
| 694 |
|
| 695 |
if exactMatch || prefixMatch(dir, workdir, caseInsensitive) { |
| 696 |
return true |
| 697 |
} |
| 698 |
debug.V(3).Log("skipping include candidate, no exact match for workdir: %q == dir: %q and no prefix match for dir: %q, workdir: %q", subsec, workdir, dir, dir, workdir) |
| 699 |
|
| 700 |
return false |
| 701 |
} |
| 702 |
|
| 703 |
if strings.HasPrefix(subsec, "onbranch:") { |
| 704 |
p := strings.SplitN(subsec, ":", 2) |
| 705 |
branchPattern := p[1] |
| 706 |
if c.branch == "" { |
| 707 |
return false |
| 708 |
} |
| 709 |
|
| 710 |
match, err := globMatch(branchPattern, c.branch) |
| 711 |
if err != nil { |
| 712 |
debug.V(1).Log("invalid glob pattern in onbranch: %s", err) |
| 713 |
|
| 714 |
return false |
| 715 |
} |
| 716 |
if match { |
| 717 |
return true |
| 718 |
} |
| 719 |
|
| 720 |
return false |
| 721 |
} |
| 722 |
|
| 723 |
debug.V(3).Log("skipping unsupported include candidate %q", subsec) |
| 724 |
|
| 725 |
return false |
| 726 |
} |
| 727 |
|
| 728 |
// prefixMatch checks if a path matches a prefix pattern, with optional case-folding. |
| 729 |
// This is used for gitdir: and gitdir/i: conditional includes. |
| 730 |
// The fold parameter controls case-insensitive matching. |
| 731 |
func prefixMatch(path, prefix string, fold bool) bool { |
| 732 |
if !strings.HasSuffix(prefix, "/") { |
| 733 |
return false |
| 734 |
} |
| 735 |
if fold { |
| 736 |
return strings.HasPrefix(strings.ToLower(path), strings.ToLower(prefix)) |
| 737 |
} |
| 738 |
|
| 739 |
return strings.HasPrefix(path, prefix) |
| 740 |
} |
| 741 |
|
| 742 |
// loadConfigs loads a config file and recursively processes all include directives. |
| 743 |
// This is the main entry point for loading configs with include support. |
| 744 |
// Returns the merged configuration from all included files. |
| 745 |
func loadConfigs(fn, workdir string) (*Config, error) { |
| 746 |
c, err := loadConfig(fn) |
| 747 |
if err != nil { |
| 748 |
return nil, err |
| 749 |
} |
| 750 |
c.path = fn |
| 751 |
c.branch = readGitBranch(workdir) |
| 752 |
|
| 753 |
loadedConfigs := map[string]struct{}{ |
| 754 |
fn: {}, |
| 755 |
} |
| 756 |
configsToLoad := []string{} |
| 757 |
|
| 758 |
includePaths, includeExists := getEffectiveIncludes(c, workdir) |
| 759 |
if includeExists { |
| 760 |
configsToLoad = append(configsToLoad, getPathsForNestedConfig(includePaths, c.path)...) |
| 761 |
} |
| 762 |
|
| 763 |
// load all nested configs |
| 764 |
// this is using a slice as a stack because when we load a config |
| 765 |
// it may include other configs |
| 766 |
// so we need to load them in the order they are found. |
| 767 |
for len(configsToLoad) > 0 { |
| 768 |
head := configsToLoad[0] |
| 769 |
configsToLoad = configsToLoad[1:] |
| 770 |
|
| 771 |
// check if we already loaded this config |
| 772 |
// this is needed to avoid infinite loops when loading nested configs |
| 773 |
_, ignore := loadedConfigs[head] |
| 774 |
if ignore { |
| 775 |
debug.V(3).Log("skipping already loaded config %q", head) |
| 776 |
|
| 777 |
continue |
| 778 |
} |
| 779 |
|
| 780 |
debug.V(2).Log("loading nested config %q", head) |
| 781 |
nc, err := loadConfig(head) |
| 782 |
if err != nil { |
| 783 |
return nil, err |
| 784 |
} |
| 785 |
|
| 786 |
c = mergeConfigs(c, nc) |
| 787 |
loadedConfigs[head] = struct{}{} |
| 788 |
|
| 789 |
includePaths, includeExists := getEffectiveIncludes(nc, workdir) |
| 790 |
if includeExists { |
| 791 |
configsToLoad = append(configsToLoad, getPathsForNestedConfig(includePaths, nc.path)...) |
| 792 |
} |
| 793 |
} |
| 794 |
|
| 795 |
return c, nil |
| 796 |
} |
| 797 |
|
| 798 |
// loadConfig loads a single config file without processing includes. |
| 799 |
// This is used internally by loadConfigs to load individual files. |
| 800 |
func loadConfig(fn string) (*Config, error) { |
| 801 |
fh, err := os.Open(fn) |
| 802 |
if err != nil { |
| 803 |
return nil, err |
| 804 |
} |
| 805 |
defer fh.Close() //nolint:errcheck |
| 806 |
|
| 807 |
c := ParseConfig(fh) |
| 808 |
c.path = fn |
| 809 |
|
| 810 |
return c, nil |
| 811 |
} |
| 812 |
|
| 813 |
// mergeConfigs merge two configs, using first config as a base config extending it with vars, raw fields from the latter. |
| 814 |
func mergeConfigs(base *Config, extension *Config) *Config { |
| 815 |
newConfig := Config{path: base.path, readonly: base.readonly, noWrites: base.noWrites, raw: strings.Builder{}, vars: map[string][]string{}} |
| 816 |
newConfig.raw.WriteString(base.raw.String()) |
| 817 |
// Note: We can not append the included config raw to the base config raw, because it will |
| 818 |
// write the included config to the base config file when we write the base config. |
| 819 |
|
| 820 |
// populate the new config with the base config |
| 821 |
maps.Copy(newConfig.vars, base.vars) |
| 822 |
|
| 823 |
for k, v := range extension.vars { |
| 824 |
_, existing := newConfig.vars[k] |
| 825 |
if !existing { |
| 826 |
newConfig.vars[k] = []string{} |
| 827 |
} |
| 828 |
newConfig.vars[k] = append(newConfig.vars[k], v...) |
| 829 |
} |
| 830 |
|
| 831 |
return &newConfig |
| 832 |
} |
| 833 |
|
| 834 |
// getPathsForNestedConfig tries to convert paths of nested configs ('/absolute', '~/from/home', 'relative/to/base') to absolute paths. |
| 835 |
func getPathsForNestedConfig(nestedConfigs []string, baseConfig string) []string { |
| 836 |
absolutePaths := []string{} |
| 837 |
for _, nc := range nestedConfigs { |
| 838 |
if path.IsAbs(nc) { |
| 839 |
absolutePaths = append(absolutePaths, nc) |
| 840 |
|
| 841 |
continue |
| 842 |
} |
| 843 |
if strings.HasPrefix(nc, "~/") { |
| 844 |
home, exists := os.LookupEnv("HOME") |
| 845 |
if !exists { |
| 846 |
// cannot resolve home directory |
| 847 |
debug.V(3).Log("cannot resolve home directory, skipping %q", nc) |
| 848 |
|
| 849 |
continue |
| 850 |
} |
| 851 |
absolutePaths = append(absolutePaths, path.Join(home, strings.Replace(nc, "~/", "", 1))) |
| 852 |
|
| 853 |
continue |
| 854 |
} |
| 855 |
absolutePaths = append(absolutePaths, path.Clean(path.Join(path.Dir(baseConfig), nc))) |
| 856 |
} |
| 857 |
|
| 858 |
return absolutePaths |
| 859 |
} |
| 860 |
|
| 861 |
// ParseConfig will try to parse a gitconfig from the given io.Reader. It never fails. |
| 862 |
// Invalid configs will be silently rejected. |
| 863 |
func ParseConfig(r io.Reader) *Config { |
| 864 |
c := &Config{ |
| 865 |
vars: make(map[string][]string, 42), |
| 866 |
} |
| 867 |
|
| 868 |
lines := parseConfig(r, "", "", func(fk, k, v, comment, _ string) (string, bool) { |
| 869 |
fk = canonicalizeKey(fk) |
| 870 |
c.vars[fk] = append(c.vars[fk], v) |
| 871 |
|
| 872 |
return formatKeyValue(k, v, comment), false |
| 873 |
}) |
| 874 |
|
| 875 |
c.raw.WriteString(strings.Join(lines, "\n")) |
| 876 |
c.raw.WriteString("\n") |
| 877 |
|
| 878 |
debug.V(3).Log("processed config: %s\nvars: %+v", c.raw.String(), c.vars) |
| 879 |
|
| 880 |
return c |
| 881 |
} |
| 882 |
|
| 883 |
// LoadConfigFromEnv will try to parse an overlay config from the environment variables. |
| 884 |
// If no environment variables are set the resulting config will be valid but empty. |
| 885 |
// Either way it will not be writeable. |
| 886 |
func LoadConfigFromEnv(envPrefix string) *Config { |
| 887 |
c := &Config{ |
| 888 |
noWrites: true, |
| 889 |
} |
| 890 |
|
| 891 |
count, err := strconv.Atoi(os.Getenv(envPrefix + "_COUNT")) |
| 892 |
if err != nil || count < 1 { |
| 893 |
return &Config{ |
| 894 |
noWrites: true, |
| 895 |
} |
| 896 |
} |
| 897 |
|
| 898 |
c.vars = make(map[string][]string, count) |
| 899 |
|
| 900 |
for i := range count { |
| 901 |
keyVar := fmt.Sprintf("%s%d", envPrefix+"_KEY_", i) |
| 902 |
key := os.Getenv(keyVar) |
| 903 |
|
| 904 |
valVar := fmt.Sprintf("%s%d", envPrefix+"_VALUE_", i) |
| 905 |
value, found := os.LookupEnv(valVar) |
| 906 |
|
| 907 |
if key == "" || !found { |
| 908 |
return &Config{ |
| 909 |
noWrites: true, |
| 910 |
} |
| 911 |
} |
| 912 |
|
| 913 |
c.vars[key] = append(c.vars[key], value) |
| 914 |
debug.V(3).Log("added %s from env", key) |
| 915 |
} |
| 916 |
|
| 917 |
return c |
| 918 |
} |