Skip to main content

grit_lib/config/
core.rs

1//! Git-compatible configuration file parser and accessor.
2//!
3//! Supports the standard Git config file format:
4//!
5//! ```text
6//! [section]
7//!     key = value
8//! [section "subsection"]
9//!     key = value
10//! ```
11//!
12//! # Multi-file layering
13//!
14//! Git reads configuration from several files in priority order:
15//!
16//! 1. System (`/etc/gitconfig`)
17//! 2. Global (`~/.gitconfig` or `$XDG_CONFIG_HOME/git/config`)
18//! 3. Local (`.git/config`)
19//! 4. Worktree (`.git/config.worktree`)
20//! 5. Command-line (`-c key=value` or `GIT_CONFIG_*`)
21//!
22//! [`ConfigSet`] merges all layers; last-wins for single-valued keys.
23//!
24//! # Include directives
25//!
26//! `[include] path = <path>` and `[includeIf "<condition>"] path = <path>`
27//! are supported. Conditions: `gitdir:`, `gitdir/i:`, `onbranch:`,
28//! and `hasconfig:remote.*.url:`.
29//!
30//! An included file is merged in place, at the position of its directive, so
31//! later entries still override it. `hasconfig:remote.*.url:<glob>` matches
32//! against every `remote.<name>.url` value of the whole load, not just the
33//! files read so far: a global include can select a work identity from a
34//! remote defined in the repository `config`. As in Git, remote URLs may not
35//! be set in a file reached through a conditional include once such a
36//! condition is evaluated ([`ConfigError::RemoteUrlInHasconfigInclude`]).
37
38use crate::git_path::CanonicalizeExt;
39use std::borrow::Cow;
40use std::collections::HashMap;
41
42use crate::environment::Environment;
43use std::fmt;
44use std::fs;
45use std::path::{Path, PathBuf};
46use std::sync::Arc;
47use std::time::SystemTime;
48
49use crate::error::{
50    BadNumericSource, ConfigError, ConfigValueError, Error, InvalidKeyReason, Result,
51};
52
53/// Test-only counters for config cascade load activity (see `porcelain_ops_load_config_cascade_once`).
54#[cfg(test)]
55pub mod cascade_load_counters {
56    use std::cell::Cell;
57
58    // Counters are per thread like `MEASURING`, so tests measuring on parallel threads do not
59    // add to or reset each other's counts.
60    thread_local! {
61        static MEASURING: Cell<bool> = const { Cell::new(false) };
62        static UNCACHED: Cell<usize> = const { Cell::new(0) };
63        static CACHE_VALIDATED: Cell<usize> = const { Cell::new(0) };
64    }
65
66    /// Run `f` while recording cascade loads on this thread only (parallel-safe).
67    pub fn measure<R>(f: impl FnOnce() -> R) -> R {
68        MEASURING.with(|m| {
69            m.set(true);
70            reset();
71            let out = f();
72            m.set(false);
73            out
74        })
75    }
76
77    /// Reset counters before an operation under test.
78    pub fn reset() {
79        UNCACHED.with(|c| c.set(0));
80        CACHE_VALIDATED.with(|c| c.set(0));
81    }
82
83    /// Full cascade parses (cache miss).
84    #[must_use]
85    pub fn uncached_loads() -> usize {
86        UNCACHED.with(Cell::get)
87    }
88
89    /// Served from the process-global config cache after stat revalidation.
90    #[must_use]
91    pub fn cache_validated_loads() -> usize {
92        CACHE_VALIDATED.with(Cell::get)
93    }
94
95    /// Total [`ConfigSet::load`] invocations.
96    #[must_use]
97    pub fn total_loads() -> usize {
98        uncached_loads().saturating_add(cache_validated_loads())
99    }
100
101    pub(crate) fn record_uncached() {
102        if MEASURING.with(Cell::get) {
103            UNCACHED.with(|c| c.set(c.get() + 1));
104        }
105    }
106}
107use crate::refs;
108use crate::wildmatch::{wildmatch, WM_CASEFOLD, WM_PATHNAME};
109
110/// The scope (origin) of a configuration value.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
112pub enum ConfigScope {
113    /// System-wide configuration (`/etc/gitconfig`).
114    System,
115    /// Per-user global configuration (`~/.gitconfig` or XDG).
116    Global,
117    /// Repository-local configuration (`.git/config`).
118    Local,
119    /// Per-worktree configuration (`.git/config.worktree`).
120    Worktree,
121    /// Command-line overrides (`-c key=value`).
122    Command,
123}
124
125impl fmt::Display for ConfigScope {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        match self {
128            Self::System => write!(f, "system"),
129            Self::Global => write!(f, "global"),
130            Self::Local => write!(f, "local"),
131            Self::Worktree => write!(f, "worktree"),
132            Self::Command => write!(f, "command"),
133        }
134    }
135}
136
137/// Origin metadata for the winning config value of a key.
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct ConfigValueOrigin {
140    /// String value, or `"true"` for a bare boolean key. Only `None` when the key is missing
141    /// (this struct is not used for missing keys — see [`ConfigSet::origin_of`]).
142    pub value: Option<String>,
143    /// Config layer that supplied the value.
144    pub scope: ConfigScope,
145    /// Source file when file-backed; absent for command-line overrides.
146    pub file: Option<PathBuf>,
147    /// One-based line number in `file`; `None` for command-line / `-f` scope (Git has no file line).
148    pub line: Option<usize>,
149}
150
151/// A single configuration entry with its origin metadata.
152#[derive(Debug, Clone)]
153pub struct ConfigEntry {
154    /// Fully-qualified key in canonical form: `section.subsection.name`
155    /// (section and name lowercased; subsection preserves case).
156    pub key: String,
157    /// The raw string value, or `None` for a boolean-true bare key.
158    pub value: Option<String>,
159    /// Which scope this entry came from.
160    pub scope: ConfigScope,
161    /// The file this entry was read from (if file-backed).
162    pub file: Option<PathBuf>,
163    /// One-based line number in the source file.
164    pub line: usize,
165}
166
167/// Where a [`ConfigFile`] was loaded from for Git include semantics.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub enum ConfigIncludeOrigin {
170    /// Normal path on disk (`-f`, global/local config files, etc.).
171    Disk,
172    /// `--file -` (stdin).
173    Stdin,
174    /// Synthetic file built from `GIT_CONFIG_PARAMETERS` / `git -c`.
175    CommandLine,
176    /// `git config --blob=…`.
177    Blob,
178}
179
180/// A parsed configuration file that preserves the raw text for round-trip
181/// editing (set/unset/rename-section/remove-section).
182#[derive(Debug, Clone)]
183pub struct ConfigFile {
184    /// The path to this config file on disk.
185    pub path: PathBuf,
186    /// The scope this file represents.
187    pub scope: ConfigScope,
188    /// Parsed entries (in file order).
189    pub entries: Vec<ConfigEntry>,
190    /// Raw lines of the file (for round-trip editing).
191    raw_lines: Vec<String>,
192    /// Source kind for `[include]` resolution (Git `CONFIG_ORIGIN_*`).
193    pub include_origin: ConfigIncludeOrigin,
194}
195
196/// A merged view across all configuration scopes.
197///
198/// Entries are stored in file-order within each scope; scopes are layered
199/// in priority order (system < global < local < worktree < command).
200///
201/// # Examples
202///
203/// ```
204/// use grit_lib::repo::{InitOptions, Repository};
205///
206/// # fn main() -> grit_lib::error::Result<()> {
207/// let dir = tempfile::tempdir()?;
208/// let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
209/// let cfg = repo.config().snapshot()?;
210/// assert!(cfg.get("core.repositoryformatversion")?.is_some());
211/// # Ok(())
212/// # }
213/// ```
214#[derive(Debug, Clone, Default)]
215pub struct ConfigSet {
216    /// All entries across all scopes, in load order.
217    entries: Vec<ConfigEntry>,
218}
219
220/// Context for evaluating `[includeIf]` conditions (`gitdir:`, `onbranch:`, `hasconfig:`).
221#[derive(Debug, Clone)]
222pub struct IncludeContext {
223    /// Git directory path used for `gitdir:` matching (may contain unresolved symlinks).
224    pub git_dir: Option<PathBuf>,
225    /// When true, `git -c include.path=relative` fails instead of ignoring the include.
226    pub command_line_relative_include_is_error: bool,
227    /// Working directory for relative include resolution (from [`Environment::cwd`]).
228    pub cwd: PathBuf,
229    /// Symlink-preserving `$PWD` for `gitdir:` matching when set.
230    pub pwd: Option<String>,
231    /// Environment used for `~/` expansion in include paths.
232    pub env: std::sync::Arc<Environment>,
233}
234
235impl Default for IncludeContext {
236    fn default() -> Self {
237        Self {
238            git_dir: None,
239            command_line_relative_include_is_error: false,
240            cwd: PathBuf::from("."),
241            pwd: None,
242            env: std::sync::Arc::new(Environment::empty()),
243        }
244    }
245}
246
247/// Whether [`ConfigSet::merge_file`] expands `[include]` / `[includeIf]` directives.
248#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
249#[non_exhaustive]
250pub enum IncludeMode {
251    /// Read the files `include.path` / `includeIf.<cond>.path` name, like Git's cascade.
252    #[default]
253    Follow,
254    /// Keep include directives as ordinary entries (`git config -f <file> --no-includes`).
255    Ignore,
256}
257
258/// Options for [`ConfigSet::merge_file`].
259#[derive(Debug, Clone, Default)]
260#[non_exhaustive]
261pub struct IncludeOptions {
262    /// Whether include directives are expanded.
263    pub mode: IncludeMode,
264    /// Context for resolving include paths and evaluating `[includeIf]` conditions.
265    pub context: IncludeContext,
266}
267
268impl IncludeOptions {
269    /// Sets [`mode`](Self::mode).
270    #[must_use]
271    pub fn with_mode(mut self, mode: IncludeMode) -> Self {
272        self.mode = mode;
273        self
274    }
275
276    /// Sets [`context`](Self::context).
277    #[must_use]
278    pub fn with_context(mut self, context: IncludeContext) -> Self {
279        self.context = context;
280        self
281    }
282}
283
284/// Options controlling how [`ConfigSet::load`] merges files and includes.
285#[derive(Clone)]
286pub struct LoadConfigOptions {
287    /// Load `/etc/gitconfig` (unless `GIT_CONFIG_NOSYSTEM` is enabled).
288    pub include_system: bool,
289    /// Load only the repository `config` file (no system/global/env overrides).
290    pub repo_local_only: bool,
291    /// Git **protected** config: system (optional), global, and command-line only.
292    pub protected_only: bool,
293    /// Expand `[include]` / `[includeIf]` while reading file-backed layers.
294    pub process_includes: bool,
295    /// Expand includes for synthetic command-line config built from `GIT_CONFIG_PARAMETERS`.
296    pub command_includes: bool,
297    /// Git directory and environment used to evaluate `[includeIf]` conditions.
298    pub include_ctx: IncludeContext,
299    /// Optional sink for non-fatal config load warnings.
300    pub diagnostics: Option<crate::diagnostics::DiagnosticsHandle>,
301    /// When set, repository-local `config` is read at most once per [`crate::repo_caches::RepoCaches`] handle.
302    pub repo_caches: Option<std::sync::Arc<crate::repo_caches::RepoCaches>>,
303}
304
305impl std::fmt::Debug for LoadConfigOptions {
306    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
307        f.debug_struct("LoadConfigOptions")
308            .field("include_system", &self.include_system)
309            .field("process_includes", &self.process_includes)
310            .field("command_includes", &self.command_includes)
311            .field("include_ctx", &self.include_ctx)
312            .finish_non_exhaustive()
313    }
314}
315
316impl Default for LoadConfigOptions {
317    fn default() -> Self {
318        Self {
319            include_system: true,
320            repo_local_only: false,
321            protected_only: false,
322            process_includes: true,
323            command_includes: true,
324            include_ctx: IncludeContext::default(),
325            diagnostics: None,
326            repo_caches: None,
327        }
328    }
329}
330
331impl LoadConfigOptions {
332    /// Standard repository cascade (system, global, local, worktree, environment overrides).
333    #[must_use]
334    pub fn standard(env: &Environment, git_dir: Option<&Path>) -> Self {
335        Self {
336            include_ctx: IncludeContext {
337                git_dir: git_dir.map(Path::to_path_buf),
338                cwd: env.cwd.clone(),
339                pwd: env.pwd.clone(),
340                env: std::sync::Arc::new(env.clone()),
341                ..Default::default()
342            },
343            ..Self::default()
344        }
345    }
346
347    /// Only `.git/config` (plus `[include]` targets), ignoring system/global/env overrides.
348    #[must_use]
349    pub fn repo_local_only(git_dir: &Path) -> Self {
350        Self {
351            include_system: false,
352            repo_local_only: true,
353            include_ctx: IncludeContext {
354                git_dir: Some(git_dir.to_path_buf()),
355                command_line_relative_include_is_error: false,
356                cwd: PathBuf::from("."),
357                pwd: None,
358                env: std::sync::Arc::new(Environment::empty()),
359            },
360            ..Self::default()
361        }
362    }
363
364    /// Git protected config (hooks): system (optional), global, and `-c` / env parameters only.
365    #[must_use]
366    pub fn protected(env: &Environment, include_system: bool) -> Self {
367        Self {
368            include_system,
369            protected_only: true,
370            include_ctx: IncludeContext {
371                git_dir: None,
372                command_line_relative_include_is_error: false,
373                cwd: env.cwd.clone(),
374                pwd: env.pwd.clone(),
375                env: std::sync::Arc::new(env.clone()),
376            },
377            ..Self::default()
378        }
379    }
380
381    /// Options for the full cascade of the repository at `git_dir`, as its
382    /// [`crate::repo::Repository`] handle loads it: system config included, `gitdir:`
383    /// conditions matched against `git_dir`, and the local `config` read through `repo_caches`.
384    ///
385    /// Every loader of one repository's cascade must use these options so they share a single
386    /// [`crate::repo_caches::RepoCaches`] cache entry instead of parsing the files again.
387    pub(crate) fn for_repository(
388        env: &Environment,
389        git_dir: Option<&Path>,
390        repo_caches: Option<Arc<crate::repo_caches::RepoCaches>>,
391    ) -> Self {
392        Self {
393            include_ctx: IncludeContext {
394                git_dir: git_dir.map(Path::to_path_buf),
395                cwd: env.cwd.clone(),
396                pwd: env.pwd.clone(),
397                ..IncludeContext::default()
398            },
399            repo_caches,
400            ..Self::default()
401        }
402    }
403}
404
405/// Source file for `--show-origin` style output.
406///
407/// `-f` / `--file` reads use `command` scope but keep a real file path; synthetic
408/// `GIT_CONFIG_PARAMETERS` / `-c` entries have no file.
409#[must_use]
410pub fn config_entry_origin_file(entry: &ConfigEntry) -> Option<&Path> {
411    if entry.scope == ConfigScope::Command && entry.file.is_none() {
412        None
413    } else {
414        entry.file.as_deref()
415    }
416}
417
418/// One-based source line for `--show-origin` output, when applicable.
419#[must_use]
420pub fn config_entry_origin_line(entry: &ConfigEntry) -> Option<usize> {
421    if entry.scope == ConfigScope::Command && entry.file.is_none() {
422        None
423    } else {
424        (entry.line > 0).then_some(entry.line)
425    }
426}
427
428// ── Canonical key helpers ────────────────────────────────────────────
429
430/// Normalise a config key to canonical form.
431///
432/// - Section name is lowercased.
433/// - Variable name (last dot-separated component) is lowercased.
434/// - Subsection (middle components) preserves original case.
435///
436/// Returns `Err` if the key has fewer than two dot-separated parts.
437///
438/// # Examples
439///
440/// - `core.bare` → `core.bare`
441/// - `Section.SubSection.Key` → `section.SubSection.key`
442/// - `CORE.BARE` → `core.bare`
443pub fn canonical_key(raw: &str) -> Result<String> {
444    let invalid = |reason| {
445        Error::Config(ConfigError::InvalidKey {
446            key: raw.to_owned(),
447            reason,
448        })
449    };
450    if raw.contains('\n') || raw.contains('\r') {
451        return Err(invalid(InvalidKeyReason::LineBreak));
452    }
453
454    let (Some(first_dot), Some(last_dot)) = (raw.find('.'), raw.rfind('.')) else {
455        return Err(invalid(InvalidKeyReason::MissingSection));
456    };
457
458    if last_dot == raw.len() - 1 {
459        return Err(invalid(InvalidKeyReason::MissingVariable));
460    }
461
462    let section = &raw[..first_dot];
463    let name = &raw[last_dot + 1..];
464
465    // Validate section name: must be alphanumeric or hyphen
466    if section.is_empty() || !section.chars().all(|c| c.is_alphanumeric() || c == '-') {
467        return Err(invalid(InvalidKeyReason::InvalidSection));
468    }
469
470    // Validate variable name: must start with alpha, rest alphanumeric or hyphen
471    if !name.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
472        || !name.chars().all(|c| c.is_alphanumeric() || c == '-')
473    {
474        return Err(invalid(InvalidKeyReason::InvalidVariable));
475    }
476
477    let mut key = String::with_capacity(raw.len());
478    push_lowercase(&mut key, section);
479    key.push('.');
480    if first_dot != last_dot {
481        key.push_str(&raw[first_dot + 1..last_dot]);
482        key.push('.');
483    }
484    push_lowercase(&mut key, name);
485    Ok(key)
486}
487
488/// Append `s` lowercased like [`str::to_lowercase`], without a temporary for ASCII input.
489fn push_lowercase(out: &mut String, s: &str) {
490    if s.is_ascii() {
491        out.extend(s.bytes().map(|b| char::from(b.to_ascii_lowercase())));
492    } else {
493        out.push_str(&s.to_lowercase());
494    }
495}
496
497// ── Parser ──────────────────────────────────────────────────────────
498
499/// Display path for config diagnostics (matches the internal `config_error_path_display` helper for public callers).
500#[must_use]
501pub fn config_file_display_for_error(path: &Path) -> String {
502    config_error_path_display(path)
503}
504
505fn config_error_path_display(path: &Path) -> String {
506    if path == Path::new("-") {
507        return "standard input".to_owned();
508    }
509    if path.file_name().and_then(|s| s.to_str()) == Some("config")
510        && path
511            .parent()
512            .and_then(|p| p.file_name())
513            .and_then(|s| s.to_str())
514            == Some(".git")
515    {
516        return ".git/config".to_owned();
517    }
518    path.display().to_string()
519}
520
521/// `fetch.negotiationAlgorithm` written without `= value` is rejected at parse time.
522fn reject_valueless_negotiation_algorithm(
523    key: &str,
524    value: Option<&str>,
525    path: &Path,
526    line: usize,
527) -> Result<()> {
528    if key != "fetch.negotiationalgorithm" || value.is_some() {
529        return Ok(());
530    }
531    Err(ConfigError::BadConfigVariable {
532        key: key.to_owned(),
533        file: config_error_path_display(path),
534        line,
535    }
536    .into())
537}
538
539/// State tracked while parsing a config file line-by-line.
540struct Parser {
541    section: String,
542    subsection: Option<String>,
543    /// `section.` or `section.subsection.` in canonical case, shared by every key of the
544    /// current section.
545    key_prefix: String,
546}
547
548impl Parser {
549    fn new() -> Self {
550        Self {
551            section: String::new(),
552            subsection: None,
553            key_prefix: String::new(),
554        }
555    }
556
557    fn valid_variable_name(name: &str) -> bool {
558        let name = name.trim();
559        name.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
560            && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
561    }
562
563    fn set_section(&mut self, section: String, subsection: Option<String>) {
564        self.key_prefix.clear();
565        push_lowercase(&mut self.key_prefix, &section);
566        self.key_prefix.push('.');
567        if let Some(sub) = &subsection {
568            self.key_prefix.push_str(sub);
569            self.key_prefix.push('.');
570        }
571        self.section = section;
572        self.subsection = subsection;
573    }
574
575    /// Build the canonical key for a variable name in the current section.
576    ///
577    /// `name` must already satisfy [`Self::valid_variable_name`], so it is ASCII.
578    fn make_key(&self, name: &str) -> String {
579        let mut key = String::with_capacity(self.key_prefix.len() + name.len());
580        key.push_str(&self.key_prefix);
581        push_lowercase(&mut key, name);
582        key
583    }
584
585    /// Parse a section header line like `[section]` or `[section "subsection"]`.
586    ///
587    /// Returns `true` if the line was a section header.
588    /// If there is content after `]` (an inline key=value), it is returned
589    /// via the `inline_remainder` parameter.
590    fn try_parse_section_with_remainder<'a>(
591        &mut self,
592        line: &'a str,
593        inline_remainder: &mut Option<&'a str>,
594    ) -> bool {
595        let trimmed = line.trim();
596        if !trimmed.starts_with('[') {
597            return false;
598        }
599        // Find the closing `]` — but for subsection headers like
600        // [section "sub\"escaped"], we need to skip escaped chars
601        // inside quotes.
602        let end = {
603            let bytes = trimmed.as_bytes();
604            let mut i = 1; // skip opening '['
605            let mut in_quotes = false;
606            let mut found = None;
607            while i < bytes.len() {
608                if in_quotes {
609                    if bytes[i] == b'\\' {
610                        i += 2; // skip escaped char
611                        continue;
612                    }
613                    if bytes[i] == b'"' {
614                        in_quotes = false;
615                    }
616                } else {
617                    if bytes[i] == b'"' {
618                        in_quotes = true;
619                    }
620                    if bytes[i] == b']' {
621                        found = Some(i);
622                        break;
623                    }
624                }
625                i += 1;
626            }
627            match found {
628                Some(i) => i,
629                None => return false,
630            }
631        };
632        let inside = &trimmed[1..end];
633        // Check for subsection: [section "subsection"]
634        if let Some(quote_start) = inside.find('"') {
635            let section = inside[..quote_start].trim().to_owned();
636            let rest = &inside[quote_start + 1..];
637            // Find unescaped closing quote
638            let mut sub = String::new();
639            let mut chars = rest.chars();
640            while let Some(ch) = chars.next() {
641                if ch == '\\' {
642                    if let Some(escaped) = chars.next() {
643                        sub.push(escaped);
644                    }
645                } else if ch == '"' {
646                    break;
647                } else {
648                    sub.push(ch);
649                }
650            }
651            self.set_section(section, Some(sub));
652        } else {
653            self.set_section(inside.trim().to_owned(), None);
654        }
655        // Check for inline content after the closing `]`
656        let after = trimmed[end + 1..].trim();
657        if !after.is_empty() && !after.starts_with('#') && !after.starts_with(';') {
658            *inline_remainder = Some(after);
659        } else {
660            *inline_remainder = None;
661        }
662        true
663    }
664
665    /// Parse a section header line (without inline remainder tracking).
666    fn try_parse_section(&mut self, line: &str) -> bool {
667        let mut _remainder = None;
668        self.try_parse_section_with_remainder(line, &mut _remainder)
669    }
670
671    /// Parse a `key = value` or bare `key` line.
672    ///
673    /// Returns `Some((canonical_key, value))` if this is a variable line.
674    fn try_parse_entry(&self, line: &str) -> Option<(String, Option<String>)> {
675        let trimmed = line.trim();
676        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
677            return None;
678        }
679        if trimmed.starts_with('[') {
680            return None;
681        }
682        if self.section.is_empty() {
683            return None;
684        }
685
686        if let Some(eq_pos) = trimmed.find('=') {
687            let raw_name = trimmed[..eq_pos].trim();
688            if !Self::valid_variable_name(raw_name) {
689                return None;
690            }
691            let raw_value = trimmed[eq_pos + 1..].trim();
692            // Strip inline comment (not inside quotes)
693            let value = parse_config_value(strip_inline_comment(raw_value));
694            let key = self.make_key(raw_name);
695            Some((key, Some(value)))
696        } else {
697            // Bare key (boolean true)
698            let raw_name = strip_inline_comment(trimmed);
699            if raw_name.split_whitespace().count() > 1 {
700                return None;
701            }
702            let raw_name = raw_name.trim();
703            if !Self::valid_variable_name(raw_name) {
704                return None;
705            }
706            let key = self.make_key(raw_name);
707            Some((key, None))
708        }
709    }
710}
711
712/// Check if a value line ends with a continuation backslash.
713///
714/// This checks the value portion (after `=`) for a trailing `\` that is
715/// outside quotes and outside an inline comment. If the `\` is after
716/// a `#` or `;` that starts a comment, it does NOT count as continuation.
717/// True when the value portion (after the first `=`) ends inside an unclosed double-quoted span.
718///
719/// Mirrors Git config continuation rules: a line ending with an open `"` continues on the next
720/// physical line. Outside quotes, `#` / `;` start comments and the line is complete.
721fn entry_line_value_has_unclosed_quote(line: &str) -> bool {
722    let trimmed = line.trim();
723    let Some(eq_pos) = trimmed.find('=') else {
724        return false;
725    };
726    let raw_value = trimmed[eq_pos + 1..].trim_start();
727    let mut in_quote = false;
728    let mut last_was_backslash = false;
729    // Every byte that matters is ASCII, and UTF-8 never reuses ASCII bytes inside a
730    // multi-byte character, so scanning bytes gives the same answer as scanning chars.
731    for b in raw_value.bytes() {
732        match b {
733            b'"' if !last_was_backslash => {
734                in_quote = !in_quote;
735                last_was_backslash = false;
736            }
737            b'\\' if !last_was_backslash => {
738                last_was_backslash = true;
739                continue;
740            }
741            b'#' | b';' if !in_quote && !last_was_backslash => return false,
742            _ => {
743                last_was_backslash = false;
744            }
745        }
746    }
747    in_quote
748}
749
750fn value_line_continues(line: &str) -> bool {
751    let trimmed = line.trim();
752    if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
753        return false;
754    }
755    // Find the value portion (after '=')
756    // If no '=', this is a bare key — no continuation
757    let value_part = match trimmed.find('=') {
758        Some(pos) => &trimmed[pos + 1..],
759        None => return false,
760    };
761    // Walk the value portion tracking quotes and comments
762    let mut in_quote = false;
763    let mut last_was_backslash = false;
764    let mut in_comment = false;
765    for b in value_part.bytes() {
766        if in_comment {
767            // Inside comment, backslash doesn't matter
768            last_was_backslash = false;
769            continue;
770        }
771        match b {
772            b'"' if !last_was_backslash => {
773                in_quote = !in_quote;
774                last_was_backslash = false;
775            }
776            b'\\' if !last_was_backslash => {
777                last_was_backslash = true;
778                continue;
779            }
780            b'#' | b';' if !in_quote && !last_was_backslash => {
781                in_comment = true;
782                last_was_backslash = false;
783            }
784            _ => {
785                last_was_backslash = false;
786            }
787        }
788    }
789    // The line continues if it ends with an unescaped backslash outside comments
790    last_was_backslash && !in_comment
791}
792
793/// Strip an inline comment (`#` or `;`) that is not inside quotes, and the whitespace
794/// before it. The result is always a prefix of `s`.
795fn strip_inline_comment(s: &str) -> &str {
796    let bytes = s.as_bytes();
797    let mut in_quote = false;
798    let mut last_was_backslash = false;
799    let mut i = 0;
800    while i < bytes.len() {
801        match bytes[i] {
802            b'"' if !last_was_backslash => {
803                in_quote = !in_quote;
804                last_was_backslash = false;
805            }
806            b'\\' if !last_was_backslash => {
807                last_was_backslash = true;
808                if in_quote && i + 1 < bytes.len() {
809                    i += 1;
810                    last_was_backslash = false;
811                }
812            }
813            b'#' | b';' if !in_quote && !last_was_backslash => break,
814            _ => last_was_backslash = false,
815        }
816        i += 1;
817    }
818    // `i` stops on an ASCII byte or the end, so it is a char boundary.
819    s[..i].trim_end()
820}
821
822/// Parse a config value after `=` (comments already stripped).
823fn parse_config_value(s: &str) -> String {
824    if s.starts_with('"') {
825        unescape_value(s)
826    } else {
827        unescape_unquoted_value(s)
828    }
829}
830
831/// Unquoted config values: backslash escapes; literal TAB characters are preserved to match
832/// `git config --get` on Git **≥ 2.55** (older Git collapses literal tabs to spaces; see
833/// `t1300_*` oracle gating in `grit-lib/tests/config_parse.rs`).
834fn unescape_unquoted_value(s: &str) -> String {
835    let mut result = String::with_capacity(s.len());
836    let mut chars = s.chars();
837    while let Some(ch) = chars.next() {
838        if ch == '\\' {
839            match chars.next() {
840                Some('n') => result.push('\n'),
841                Some('r') => result.push('\r'),
842                Some('t') => result.push('\t'),
843                Some('b') => result.push('\x08'),
844                Some('\\') => result.push('\\'),
845                Some('"') => result.push('"'),
846                Some(other) => {
847                    result.push('\\');
848                    result.push(other);
849                }
850                None => result.push('\\'),
851            }
852        } else {
853            result.push(ch);
854        }
855    }
856    result
857}
858
859/// Unescape a quoted config value: handle `\"`, `\\`, `\n`, `\t`, `\b`, and strip
860/// surrounding quotes.
861fn unescape_value(s: &str) -> String {
862    let mut result = String::with_capacity(s.len());
863    let mut chars = s.chars();
864    while let Some(ch) = chars.next() {
865        match ch {
866            '"' => { /* strip quotes */ }
867            '\\' => match chars.next() {
868                Some('n') => result.push('\n'),
869                Some('r') => result.push('\r'),
870                Some('t') => result.push('\t'),
871                Some('b') => result.push('\x08'),
872                Some('\\') => result.push('\\'),
873                Some('"') => result.push('"'),
874                Some(other) => {
875                    result.push('\\');
876                    result.push(other);
877                }
878                None => result.push('\\'),
879            },
880            _ => result.push(ch),
881        }
882    }
883    result
884}
885
886/// Escape a config value for writing back to a file.
887///
888/// Wraps in double quotes if the value contains leading/trailing whitespace,
889/// internal quotes, backslashes, or special characters.
890/// Escape a subsection name for writing in a config section header.
891/// In subsection names, `"` and `\` must be escaped.
892fn escape_subsection(s: &str) -> String {
893    let mut out = String::with_capacity(s.len());
894    for ch in s.chars() {
895        match ch {
896            '"' => out.push_str("\\\""),
897            '\\' => out.push_str("\\\\"),
898            other => out.push(other),
899        }
900    }
901    out
902}
903
904fn escape_value(s: &str) -> String {
905    // Quote leading `-` so values are not mistaken for config options (Git does this for
906    // submodule paths like `-sub` in `.gitmodules`), but leave signed numeric values bare.
907    let leading_dash_needs_quoting = s.starts_with('-') && parse_i64(s).is_err();
908    let must_quote = leading_dash_needs_quoting
909        || s.starts_with(' ')
910        || s.starts_with('\t')
911        || s.ends_with(' ')
912        || s.ends_with('\t')
913        || s.contains('"')
914        || s.contains('#')
915        || s.contains(';');
916
917    if must_quote {
918        return escape_value_quoted(s);
919    }
920
921    if s.contains('\n') || s.contains('\r') || s.contains('\t') || s.contains('\\') {
922        let mut out = String::with_capacity(s.len() + 4);
923        for ch in s.chars() {
924            match ch {
925                '\n' => out.push_str("\\n"),
926                '\r' => out.push_str("\\r"),
927                '\t' => out.push_str("\\t"),
928                '\\' => out.push_str("\\\\"),
929                '"' => out.push_str("\\\""),
930                other => out.push(other),
931            }
932        }
933        return out;
934    }
935
936    s.to_owned()
937}
938
939/// Compile a Git config value-pattern (`drop`, `!keep`, or full regex).
940fn compile_config_value_pattern(pat: &str) -> std::result::Result<(regex::Regex, bool), Error> {
941    let (negated, actual_pat) = if let Some(rest) = pat.strip_prefix('!') {
942        (true, rest)
943    } else {
944        (false, pat)
945    };
946    let re = regex::Regex::new(actual_pat).map_err(|e| {
947        Error::Config(ConfigError::InvalidValuePattern {
948            pattern: pat.to_owned(),
949            reason: e.to_string(),
950        })
951    })?;
952    Ok((re, negated))
953}
954
955fn value_matches_config_pattern(re: &regex::Regex, negated: bool, value: &str) -> bool {
956    let matched = re.is_match(value);
957    if negated {
958        !matched
959    } else {
960        matched
961    }
962}
963
964fn escape_value_quoted(s: &str) -> String {
965    let mut out = String::with_capacity(s.len() + 4);
966    out.push('"');
967    for ch in s.chars() {
968        match ch {
969            '"' => out.push_str("\\\""),
970            '\\' => out.push_str("\\\\"),
971            '\n' => out.push_str("\\n"),
972            '\r' => out.push_str("\\r"),
973            '\t' => out.push_str("\\t"),
974            other => out.push(other),
975        }
976    }
977    out.push('"');
978    out
979}
980
981/// Format a comment suffix for appending to a config value line.
982///
983/// Matches Git's `git_config_prepare_comment_string` normalization:
984/// leading space/tab is preserved only when followed by `#`; otherwise ` # ` is inserted.
985///
986/// # Errors
987///
988/// Returns [`ConfigError::MultilineCommentNotAllowed`] when `comment` contains `\n` or `\r`.
989fn format_comment_suffix(comment: Option<&str>) -> Result<String> {
990    match comment {
991        None => Ok(String::new()),
992        Some(c) => {
993            if c.contains('\n') || c.contains('\r') {
994                return Err(Error::Config(ConfigError::MultilineCommentNotAllowed));
995            }
996            let leading_blanks = c.find(|ch| ch != ' ' && ch != '\t').unwrap_or(c.len());
997            let after_blanks = &c[leading_blanks..];
998            if leading_blanks > 0 && after_blanks.starts_with('#') {
999                Ok(c.to_owned())
1000            } else if c.starts_with('#') {
1001                Ok(format!(" {c}"))
1002            } else {
1003                Ok(format!(" # {c}"))
1004            }
1005        }
1006    }
1007}
1008
1009impl ConfigFile {
1010    /// Parse a config file from its raw text content.
1011    ///
1012    /// # Parameters
1013    ///
1014    /// - `path` — the file path (stored for diagnostics and round-trip writes).
1015    /// - `content` — the raw text of the file.
1016    /// - `scope` — the [`ConfigScope`] this file represents.
1017    ///
1018    /// # Errors
1019    ///
1020    /// Returns [`Error::Config`] on malformed input.
1021    pub fn parse(path: &Path, content: &str, scope: ConfigScope) -> Result<Self> {
1022        let content = content.strip_prefix('\u{feff}').unwrap_or(content);
1023        let raw_lines: Vec<String> = content
1024            .lines()
1025            .map(|l| l.strip_suffix('\r').unwrap_or(l))
1026            .map(String::from)
1027            .collect();
1028        let mut entries = Vec::new();
1029        let mut parser = Parser::new();
1030
1031        let mut idx = 0;
1032        while idx < raw_lines.len() {
1033            let start_idx = idx;
1034            let line = &raw_lines[idx];
1035            idx += 1;
1036
1037            // Pure comment lines don't continue even with trailing \
1038            let trimmed = line.trim();
1039            if trimmed.starts_with('#') || trimmed.starts_with(';') {
1040                continue;
1041            }
1042
1043            let mut inline_remainder = None;
1044            if parser.try_parse_section_with_remainder(line, &mut inline_remainder) {
1045                // Check if there's an inline key=value after the section header
1046                if let Some(remainder) = inline_remainder {
1047                    if let Some((key, value)) = parser.try_parse_entry(remainder) {
1048                        reject_valueless_negotiation_algorithm(
1049                            &key,
1050                            value.as_deref(),
1051                            path,
1052                            start_idx + 1,
1053                        )?;
1054                        entries.push(ConfigEntry {
1055                            key,
1056                            value,
1057                            scope,
1058                            file: Some(path.to_path_buf()),
1059                            line: start_idx + 1,
1060                        });
1061                    }
1062                }
1063                continue;
1064            }
1065
1066            // For entry lines, we need to check continuation.
1067            // Build a logical line by joining continuations.
1068            let mut logical_line = Cow::Borrowed(line.as_str());
1069            while value_line_continues(&logical_line) && idx < raw_lines.len() {
1070                // Remove the trailing backslash
1071                let t = logical_line.trim_end();
1072                let mut joined = t[..t.len() - 1].to_string();
1073                // Append next line (trimmed of leading whitespace)
1074                joined.push_str(raw_lines[idx].trim_start());
1075                logical_line = Cow::Owned(joined);
1076                idx += 1;
1077            }
1078
1079            let mut unclosed_quote = entry_line_value_has_unclosed_quote(&logical_line);
1080            while unclosed_quote && idx < raw_lines.len() {
1081                let next = raw_lines[idx].trim_start();
1082                logical_line.to_mut().push_str(next);
1083                idx += 1;
1084                unclosed_quote = entry_line_value_has_unclosed_quote(&logical_line);
1085            }
1086            if unclosed_quote {
1087                let file_disp = config_error_path_display(path);
1088                return Err(ConfigError::BadConfigLineInFile {
1089                    file: file_disp,
1090                    line: start_idx + 1,
1091                }
1092                .into());
1093            }
1094
1095            if let Some((key, value)) = parser.try_parse_entry(&logical_line) {
1096                reject_valueless_negotiation_algorithm(
1097                    &key,
1098                    value.as_deref(),
1099                    path,
1100                    start_idx + 1,
1101                )?;
1102                entries.push(ConfigEntry {
1103                    key,
1104                    value,
1105                    scope,
1106                    file: Some(path.to_path_buf()),
1107                    line: start_idx + 1,
1108                });
1109            } else if logical_line.trim().is_empty() {
1110                continue;
1111            } else {
1112                let file_disp = config_error_path_display(path);
1113                let location = if path == Path::new("-") {
1114                    file_disp
1115                } else {
1116                    format!("file {file_disp}")
1117                };
1118                return Err(ConfigError::BadConfigLine {
1119                    location,
1120                    line: start_idx + 1,
1121                }
1122                .into());
1123            }
1124        }
1125
1126        Ok(Self {
1127            path: path.to_path_buf(),
1128            scope,
1129            entries,
1130            raw_lines,
1131            include_origin: ConfigIncludeOrigin::Disk,
1132        })
1133    }
1134
1135    /// Like [`Self::parse`] for `.gitmodules`, but on an unclosed-quote / bad line returns entries
1136    /// parsed **before** that line plus the one-based line number of the bad logical line.
1137    ///
1138    /// Git streams config and still applies entries from valid preceding lines; submodule-config
1139    /// tests rely on that when a later `.gitmodules` line is malformed.
1140    pub fn parse_gitmodules_best_effort(
1141        path: &Path,
1142        content: &str,
1143        scope: ConfigScope,
1144    ) -> (Vec<ConfigEntry>, Option<usize>) {
1145        let raw_lines: Vec<String> = content
1146            .lines()
1147            .map(|l| l.strip_suffix('\r').unwrap_or(l))
1148            .map(String::from)
1149            .collect();
1150        let mut entries = Vec::new();
1151        let mut parser = Parser::new();
1152
1153        let mut idx = 0;
1154        while idx < raw_lines.len() {
1155            let start_idx = idx;
1156            let line = &raw_lines[idx];
1157            idx += 1;
1158
1159            let trimmed = line.trim();
1160            if trimmed.starts_with('#') || trimmed.starts_with(';') {
1161                continue;
1162            }
1163
1164            let mut inline_remainder = None;
1165            if parser.try_parse_section_with_remainder(line, &mut inline_remainder) {
1166                if let Some(remainder) = inline_remainder {
1167                    if let Some((key, value)) = parser.try_parse_entry(remainder) {
1168                        entries.push(ConfigEntry {
1169                            key,
1170                            value,
1171                            scope,
1172                            file: Some(path.to_path_buf()),
1173                            line: start_idx + 1,
1174                        });
1175                    }
1176                }
1177                continue;
1178            }
1179
1180            let mut logical_line = line.clone();
1181            while value_line_continues(&logical_line) && idx < raw_lines.len() {
1182                let t = logical_line.trim_end();
1183                logical_line = t[..t.len() - 1].to_string();
1184                let next = raw_lines[idx].trim_start();
1185                logical_line.push_str(next);
1186                idx += 1;
1187            }
1188
1189            while entry_line_value_has_unclosed_quote(&logical_line) && idx < raw_lines.len() {
1190                let next = raw_lines[idx].trim_start();
1191                logical_line.push_str(next);
1192                idx += 1;
1193            }
1194            if entry_line_value_has_unclosed_quote(&logical_line) {
1195                return (entries, Some(start_idx + 1));
1196            }
1197
1198            if let Some((key, value)) = parser.try_parse_entry(&logical_line) {
1199                entries.push(ConfigEntry {
1200                    key,
1201                    value,
1202                    scope,
1203                    file: Some(path.to_path_buf()),
1204                    line: start_idx + 1,
1205                });
1206            }
1207        }
1208
1209        (entries, None)
1210    }
1211
1212    /// Last value for `key` in this file only (canonical key, case-insensitive section/var like Git).
1213    #[must_use]
1214    pub fn get(&self, key: &str) -> Option<String> {
1215        let canon = canonical_key(key).ok()?;
1216        self.entries
1217            .iter()
1218            .rev()
1219            .find(|e| e.key == canon)
1220            .map(|e| e.value.clone().unwrap_or_else(|| "true".to_owned()))
1221    }
1222
1223    /// Build a synthetic [`ConfigFile`] from `GIT_CONFIG_PARAMETERS` / `git -c` payloads.
1224    ///
1225    /// Unlike [`Self::parse`], this accepts flat `key=value` assignments without `[section]`
1226    /// headers, matching how Git injects command-line configuration.
1227    pub fn from_git_config_parameters(path: &Path, raw: &str) -> Result<Self> {
1228        let mut entries = Vec::new();
1229        for entry in parse_config_parameters_strict(raw)? {
1230            match entry {
1231                ConfigParameter::Pair { key, value } => {
1232                    let canon = canonical_key(key.trim())?;
1233                    entries.push(ConfigEntry {
1234                        key: canon,
1235                        value,
1236                        scope: ConfigScope::Command,
1237                        file: None,
1238                        line: 0,
1239                    });
1240                }
1241                ConfigParameter::OldStyle(entry) => {
1242                    if let Some((key, val)) = entry.split_once('=') {
1243                        let canon = canonical_key(key.trim())?;
1244                        entries.push(ConfigEntry {
1245                            key: canon,
1246                            value: Some(val.to_owned()),
1247                            scope: ConfigScope::Command,
1248                            file: None,
1249                            line: 0,
1250                        });
1251                    } else {
1252                        let canon = canonical_key(entry.trim())?;
1253                        entries.push(ConfigEntry {
1254                            key: canon,
1255                            value: None,
1256                            scope: ConfigScope::Command,
1257                            file: None,
1258                            line: 0,
1259                        });
1260                    }
1261                }
1262            }
1263        }
1264        Ok(Self {
1265            path: path.to_path_buf(),
1266            scope: ConfigScope::Command,
1267            entries,
1268            raw_lines: Vec::new(),
1269            include_origin: ConfigIncludeOrigin::CommandLine,
1270        })
1271    }
1272
1273    /// Read and parse a config file from disk.
1274    ///
1275    /// Returns `Ok(None)` if the file does not exist.
1276    ///
1277    /// # Errors
1278    ///
1279    /// Returns [`Error::Io`] on read failure (other than not-found) or
1280    /// [`Error::Config`] on parse failure.
1281    pub fn from_path(path: &Path, scope: ConfigScope) -> Result<Option<Self>> {
1282        match fs::read_to_string(path) {
1283            Ok(content) => Ok(Some(Self::parse(path, &content, scope)?)),
1284            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1285            Err(e) => Err(Error::Io(e)),
1286        }
1287    }
1288
1289    /// Set a value in this config file, creating the section if needed.
1290    ///
1291    /// If the key already exists, its last occurrence is updated in-place.
1292    /// Otherwise a new entry is appended (creating the section header if
1293    /// necessary).
1294    ///
1295    /// # Parameters
1296    ///
1297    /// - `key` — canonical key (e.g. `core.bare`).
1298    /// - `value` — the value to set.
1299    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
1300        self.set_value(key, value, None)
1301    }
1302
1303    /// Like [`Self::set`], appending `comment` inline after the value (`git config --comment`).
1304    ///
1305    /// # Errors
1306    ///
1307    /// Same as [`Self::set`], plus [`ConfigError`] for a comment containing a newline.
1308    pub fn set_commented(&mut self, key: &str, value: &str, comment: &str) -> Result<()> {
1309        self.set_value(key, value, Some(comment))
1310    }
1311
1312    fn set_value(&mut self, key: &str, value: &str, comment: Option<&str>) -> Result<()> {
1313        let canon = canonical_key(key)?;
1314        if self.entries.iter().filter(|e| e.key == canon).count() > 1 {
1315            return Err(Error::Config(ConfigError::MultipleValues {
1316                key: key.to_owned(),
1317            }));
1318        }
1319        let raw_var = raw_variable_name(key);
1320        let comment_suffix = format_comment_suffix(comment)?;
1321
1322        // Find the last entry with this key to replace in-place.
1323        let existing_idx = self.entries.iter().rposition(|e| e.key == canon);
1324
1325        if let Some(idx) = existing_idx {
1326            let line_idx = self.entries[idx].line - 1;
1327            let raw_line = &self.raw_lines[line_idx];
1328            if is_section_header_with_inline_entry(raw_line) {
1329                // Entry is on the same line as a section header — split it
1330                let header_only = extract_section_header(raw_line);
1331                self.raw_lines[line_idx] = header_only;
1332                let new_line = format!("\t{} = {}{}", raw_var, escape_value(value), comment_suffix);
1333                self.raw_lines.insert(line_idx + 1, new_line);
1334                // Re-parse to fix up entries and line numbers
1335                let content = self.raw_lines.join("\n");
1336                let reparsed = Self::parse(&self.path, &content, self.scope)?;
1337                self.entries = reparsed.entries;
1338                self.raw_lines = reparsed.raw_lines;
1339            } else {
1340                self.raw_lines[line_idx] =
1341                    format!("\t{} = {}{}", raw_var, escape_value(value), comment_suffix);
1342                self.entries[idx].value = Some(value.to_owned());
1343            }
1344        } else {
1345            // Need to add: find or create the section
1346            let (section, subsection, _var) = split_key(&canon)?;
1347            let (raw_sec, raw_sub) = raw_section_parts(key);
1348            let section_line = self.find_or_create_section_preserving_case(
1349                &section,
1350                subsection.as_deref(),
1351                &raw_sec,
1352                raw_sub.as_deref(),
1353            );
1354            let new_line = format!("\t{} = {}{}", raw_var, escape_value(value), comment_suffix);
1355
1356            // Insert after the section header (or last entry in section)
1357            let insert_at = self.last_line_in_section(section_line) + 1;
1358            self.raw_lines.insert(insert_at, new_line);
1359
1360            // Re-parse to fix up line numbers
1361            let content = self.raw_lines.join("\n");
1362            let reparsed = Self::parse(&self.path, &content, self.scope)?;
1363            self.entries = reparsed.entries;
1364            self.raw_lines = reparsed.raw_lines;
1365        }
1366
1367        Ok(())
1368    }
1369
1370    /// Replace ALL occurrences of a key with a new value.
1371    ///
1372    /// Removes all but the last occurrence from the file, then updates
1373    /// the last occurrence with the new value (matching Git behaviour).
1374    pub fn replace_all(
1375        &mut self,
1376        key: &str,
1377        value: &str,
1378        value_pattern: Option<&str>,
1379    ) -> Result<()> {
1380        self.replace_all_values(key, value, value_pattern, None)
1381    }
1382
1383    /// Like [`Self::replace_all`], appending `comment` inline after the new value.
1384    ///
1385    /// Value patterns starting with `!` are treated as negated regex
1386    /// (matching values that do NOT match the pattern).
1387    ///
1388    /// # Errors
1389    ///
1390    /// Same as [`Self::replace_all`], plus [`ConfigError`] for a comment containing a newline.
1391    pub fn replace_all_commented(
1392        &mut self,
1393        key: &str,
1394        value: &str,
1395        value_pattern: Option<&str>,
1396        comment: &str,
1397    ) -> Result<()> {
1398        self.replace_all_values(key, value, value_pattern, Some(comment))
1399    }
1400
1401    fn replace_all_values(
1402        &mut self,
1403        key: &str,
1404        value: &str,
1405        value_pattern: Option<&str>,
1406        comment: Option<&str>,
1407    ) -> Result<()> {
1408        let canon = canonical_key(key)?;
1409        let comment_suffix = format_comment_suffix(comment)?;
1410
1411        let (re, negated) = match value_pattern {
1412            Some(pat) => {
1413                let (compiled, neg) = compile_config_value_pattern(pat)?;
1414                (Some(compiled), neg)
1415            }
1416            None => (None, false),
1417        };
1418
1419        // Find all matching entries (by key, and optionally by value pattern)
1420        let matching_indices: Vec<usize> = self
1421            .entries
1422            .iter()
1423            .enumerate()
1424            .filter(|(_, e)| {
1425                if e.key != canon {
1426                    return false;
1427                }
1428                if let Some(ref re) = re {
1429                    let v = e.value.as_deref().unwrap_or("");
1430                    value_matches_config_pattern(re, negated, v)
1431                } else {
1432                    true
1433                }
1434            })
1435            .map(|(i, _)| i)
1436            .collect();
1437
1438        let Some(&target_idx) = matching_indices.last() else {
1439            // No matching entries — add a new one at the end of the section
1440            return self.append_value(key, value, comment);
1441        };
1442
1443        let raw_var = raw_variable_name(key);
1444
1445        let target_line_idx = self.entries[target_idx].line - 1;
1446        let raw_line = &self.raw_lines[target_line_idx];
1447        if is_section_header_with_inline_entry(raw_line) {
1448            let header = extract_section_header(raw_line);
1449            self.raw_lines[target_line_idx] = header;
1450            let new_line = format!("\t{} = {}{}", raw_var, escape_value(value), comment_suffix);
1451            self.raw_lines.insert(target_line_idx + 1, new_line);
1452        } else {
1453            self.raw_lines[target_line_idx] =
1454                format!("\t{} = {}{}", raw_var, escape_value(value), comment_suffix);
1455        }
1456
1457        for &idx in matching_indices.iter().rev() {
1458            if idx == target_idx {
1459                continue;
1460            }
1461            let line_idx = self.entries[idx].line - 1;
1462            self.remove_entry_line(line_idx);
1463        }
1464
1465        // Re-parse
1466        let content = self.raw_lines.join("\n");
1467        let reparsed = Self::parse(&self.path, &content, self.scope)?;
1468        self.entries = reparsed.entries;
1469        self.raw_lines = reparsed.raw_lines;
1470
1471        Ok(())
1472    }
1473
1474    /// Count how many entries exist for a key.
1475    pub fn count(&self, key: &str) -> Result<usize> {
1476        let canon = canonical_key(key)?;
1477        Ok(self.entries.iter().filter(|e| e.key == canon).count())
1478    }
1479
1480    /// Remove an entry at the given raw line index.
1481    ///
1482    /// If the line is a section header with an inline entry, only the inline
1483    /// portion is removed (the header is kept). Otherwise the entire line is
1484    /// removed. Also removes continuation lines following the entry.
1485    /// Remove an entry at the given raw line index.
1486    ///
1487    /// If the line is a section header with an inline entry, only the inline
1488    /// portion is removed (the header is kept). Otherwise the entire line
1489    /// (and any continuation lines) is removed.
1490    fn remove_entry_line(&mut self, line_idx: usize) {
1491        if is_section_header_with_inline_entry(&self.raw_lines[line_idx]) {
1492            // Keep the section header, strip the inline entry
1493            let header = extract_section_header(&self.raw_lines[line_idx]);
1494            self.raw_lines[line_idx] = header;
1495        } else {
1496            // Check if this line has continuation lines and remove them too
1497            let mut lines_to_remove = 1;
1498            let mut check_line = self.raw_lines[line_idx].clone();
1499            while value_line_continues(&check_line)
1500                && (line_idx + lines_to_remove) < self.raw_lines.len()
1501            {
1502                check_line = self.raw_lines[line_idx + lines_to_remove].clone();
1503                lines_to_remove += 1;
1504            }
1505            for _ in 0..lines_to_remove {
1506                self.raw_lines.remove(line_idx);
1507            }
1508        }
1509    }
1510
1511    /// Unset (remove) only the last occurrence of a key.
1512    ///
1513    /// Returns the number of entries removed (0 or 1).
1514    pub fn unset_last(&mut self, key: &str) -> Result<usize> {
1515        let canon = canonical_key(key)?;
1516        let last_idx = self.entries.iter().rposition(|e| e.key == canon);
1517
1518        if let Some(idx) = last_idx {
1519            let line_idx = self.entries[idx].line - 1;
1520            self.remove_entry_line(line_idx);
1521            let (section, subsection, _) = split_key(&canon)?;
1522            self.remove_empty_section_headers_matching(&section, subsection.as_deref());
1523            let content = self.raw_lines.join("\n");
1524            let reparsed = Self::parse(&self.path, &content, self.scope)?;
1525            self.entries = reparsed.entries;
1526            self.raw_lines = reparsed.raw_lines;
1527            Ok(1)
1528        } else {
1529            Ok(0)
1530        }
1531    }
1532
1533    /// Unset (remove) all occurrences of a key.
1534    ///
1535    /// # Parameters
1536    ///
1537    /// - `key` — canonical key (e.g. `core.bare`).
1538    ///
1539    /// # Returns
1540    ///
1541    /// The number of entries removed.
1542    pub fn unset(&mut self, key: &str) -> Result<usize> {
1543        let canon = canonical_key(key)?;
1544        let line_indices: Vec<usize> = self
1545            .entries
1546            .iter()
1547            .filter(|e| e.key == canon)
1548            .map(|e| e.line - 1)
1549            .collect();
1550
1551        let count = line_indices.len();
1552        // Remove from bottom to top to keep indices valid
1553        for &idx in line_indices.iter().rev() {
1554            self.remove_entry_line(idx);
1555        }
1556
1557        if count > 0 {
1558            if let Ok((section, subsection, _)) = split_key(&canon) {
1559                self.remove_empty_section_headers_matching(&section, subsection.as_deref());
1560            }
1561            let content = self.raw_lines.join("\n");
1562            let reparsed = Self::parse(&self.path, &content, self.scope)?;
1563            self.entries = reparsed.entries;
1564            self.raw_lines = reparsed.raw_lines;
1565        }
1566
1567        Ok(count)
1568    }
1569
1570    /// Unset entries matching a key and optional value-pattern regex.
1571    ///
1572    /// If `value_pattern` is `None`, removes all entries with the given key.
1573    /// If `value_pattern` is `Some(pat)`, only removes entries whose value matches the regex.
1574    ///
1575    /// When `preserve_empty_section_header` is `true`, a section header is kept even if the
1576    /// section has no remaining keys (Git's `config unset --all`). When `false`, empty sections
1577    /// are stripped (`config --unset`, `config --unset-all`, and value-pattern unsets).
1578    pub fn unset_matching(
1579        &mut self,
1580        key: &str,
1581        value_pattern: Option<&str>,
1582        preserve_empty_section_header: bool,
1583    ) -> Result<usize> {
1584        let canon = canonical_key(key)?;
1585        let pattern = match value_pattern {
1586            Some(pat) => {
1587                let (re, negated) = compile_config_value_pattern(pat)?;
1588                Some((re, negated))
1589            }
1590            None => None,
1591        };
1592
1593        let line_indices: Vec<usize> = self
1594            .entries
1595            .iter()
1596            .filter(|e| {
1597                if e.key != canon {
1598                    return false;
1599                }
1600                if let Some((ref re, negated)) = pattern {
1601                    let v = e.value.as_deref().unwrap_or("");
1602                    value_matches_config_pattern(re, negated, v)
1603                } else {
1604                    true
1605                }
1606            })
1607            .map(|e| e.line - 1)
1608            .collect();
1609
1610        let count = line_indices.len();
1611        for &idx in line_indices.iter().rev() {
1612            self.remove_entry_line(idx);
1613        }
1614
1615        if count > 0 {
1616            if !preserve_empty_section_header {
1617                let (section, subsection, _) = split_key(&canon)?;
1618                self.remove_empty_section_headers_matching(&section, subsection.as_deref());
1619            }
1620
1621            let content = self.raw_lines.join("\n");
1622            let reparsed = Self::parse(&self.path, &content, self.scope)?;
1623            self.entries = reparsed.entries;
1624            self.raw_lines = reparsed.raw_lines;
1625        }
1626
1627        Ok(count)
1628    }
1629
1630    /// Remove an entire section (and all its entries).
1631    ///
1632    /// # Parameters
1633    ///
1634    /// - `section` — section name (e.g. `"core"`, `"remote.origin"`).
1635    pub fn remove_section(&mut self, section: &str) -> Result<bool> {
1636        let (sec_name, sub_name) = parse_section_name(section);
1637        let sec_lower = sec_name.to_lowercase();
1638
1639        let mut remove = vec![false; self.raw_lines.len()];
1640        let mut removing = false;
1641        let mut found = false;
1642        let mut parser = Parser::new();
1643
1644        for (idx, line) in self.raw_lines.iter().enumerate() {
1645            if parser.try_parse_section(line) {
1646                removing = section_matches(&parser, &sec_lower, sub_name);
1647                found |= removing;
1648            }
1649            if removing {
1650                remove[idx] = true;
1651            }
1652        }
1653
1654        if found {
1655            self.raw_lines = self
1656                .raw_lines
1657                .iter()
1658                .enumerate()
1659                .filter_map(|(idx, line)| (!remove[idx]).then_some(line.clone()))
1660                .collect();
1661            let content = self.raw_lines.join("\n");
1662            let reparsed = Self::parse(&self.path, &content, self.scope)?;
1663            self.entries = reparsed.entries;
1664            self.raw_lines = reparsed.raw_lines;
1665            Ok(true)
1666        } else {
1667            Ok(false)
1668        }
1669    }
1670
1671    /// Rename a section.
1672    ///
1673    /// # Parameters
1674    ///
1675    /// - `old_name` — current section name (e.g. `"branch.main"`).
1676    /// - `new_name` — new section name (e.g. `"branch.develop"`).
1677    pub fn rename_section(&mut self, old_name: &str, new_name: &str) -> Result<bool> {
1678        let (old_sec, old_sub) = parse_section_name(old_name);
1679        let (new_sec, new_sub) = parse_section_name(new_name);
1680        validate_section_name(new_name, new_sec, new_sub)?;
1681        let old_lower = old_sec.to_lowercase();
1682
1683        let mut found = false;
1684        let mut parser = Parser::new();
1685
1686        let mut idx = 0usize;
1687        while idx < self.raw_lines.len() {
1688            let line = self.raw_lines[idx].clone();
1689            let mut inline_remainder = None;
1690            if parser.try_parse_section_with_remainder(&line, &mut inline_remainder)
1691                && section_matches(&parser, &old_lower, old_sub)
1692            {
1693                // Rewrite the section header
1694                let header = match new_sub {
1695                    Some(sub) => format!("[{} \"{}\"]", new_sec, sub),
1696                    None => format!("[{}]", new_sec),
1697                };
1698                self.raw_lines[idx] = header;
1699                if let Some(remainder) = inline_remainder {
1700                    self.raw_lines
1701                        .insert(idx + 1, format!("\t{}", remainder.trim()));
1702                    idx += 1;
1703                }
1704                found = true;
1705            }
1706            idx += 1;
1707        }
1708
1709        if found {
1710            let content = self.raw_lines.join("\n");
1711            let reparsed = Self::parse(&self.path, &content, self.scope)?;
1712            self.entries = reparsed.entries;
1713            self.raw_lines = reparsed.raw_lines;
1714        }
1715
1716        Ok(found)
1717    }
1718
1719    /// Append a new value for a key without removing existing entries.
1720    ///
1721    /// This is the behaviour of `git config --add section.key value`.
1722    /// If the section doesn't exist, it is created.
1723    pub fn add_value(&mut self, key: &str, value: &str) -> Result<()> {
1724        self.append_value(key, value, None)
1725    }
1726
1727    /// Like [`Self::add_value`], appending `comment` inline after the value.
1728    ///
1729    /// # Errors
1730    ///
1731    /// Same as [`Self::add_value`], plus [`ConfigError`] for a comment containing a newline.
1732    pub fn add_value_commented(&mut self, key: &str, value: &str, comment: &str) -> Result<()> {
1733        self.append_value(key, value, Some(comment))
1734    }
1735
1736    fn append_value(&mut self, key: &str, value: &str, comment: Option<&str>) -> Result<()> {
1737        let canon = canonical_key(key)?;
1738        let raw_var = raw_variable_name(key);
1739        let comment_suffix = format_comment_suffix(comment)?;
1740        let (section, subsection, _var) = split_key(&canon)?;
1741        let (raw_sec, raw_sub) = raw_section_parts(key);
1742
1743        let section_line = self.find_or_create_section_preserving_case(
1744            &section,
1745            subsection.as_deref(),
1746            &raw_sec,
1747            raw_sub.as_deref(),
1748        );
1749        let new_line = format!("\t{} = {}{}", raw_var, escape_value(value), comment_suffix);
1750        let insert_at = self.last_line_in_section(section_line) + 1;
1751        self.raw_lines.insert(insert_at, new_line);
1752
1753        // Re-parse to fix up entries and line numbers
1754        let content = self.raw_lines.join("\n");
1755        let reparsed = Self::parse(&self.path, &content, self.scope)?;
1756        self.entries = reparsed.entries;
1757        self.raw_lines = reparsed.raw_lines;
1758
1759        Ok(())
1760    }
1761
1762    /// Write the (possibly modified) config back to disk.
1763    /// Remove section headers that have no remaining entries or comments.
1764    fn remove_empty_section_headers_matching(&mut self, section: &str, subsection: Option<&str>) {
1765        let (Ok(section_re), Ok(comment_re)) = (
1766            regex::Regex::new(r"^\s*\["),
1767            regex::Regex::new(r"^\s*(#|;)"),
1768        ) else {
1769            // Static patterns: compilation cannot fail in practice; bail out safely.
1770            return;
1771        };
1772
1773        let mut to_remove: Vec<usize> = Vec::new();
1774        let len = self.raw_lines.len();
1775        let section_lower = section.to_lowercase();
1776        let mut parser = Parser::new();
1777
1778        for i in 0..len {
1779            let line = &self.raw_lines[i];
1780            if !section_re.is_match(line) {
1781                continue;
1782            }
1783            if !parser.try_parse_section(line)
1784                || !section_matches(&parser, &section_lower, subsection)
1785            {
1786                continue;
1787            }
1788            // Don't remove section headers that have inline key=value entries
1789            if is_section_header_with_inline_entry(line) {
1790                continue;
1791            }
1792            let has_attached_leading_comment = self.raw_lines[..i]
1793                .iter()
1794                .enumerate()
1795                .rev()
1796                .find(|(_, line)| !line.trim().is_empty())
1797                .is_some_and(|(idx, line)| {
1798                    comment_re.is_match(line)
1799                        && idx
1800                            .checked_sub(1)
1801                            .is_none_or(|prev| !value_line_continues(&self.raw_lines[prev]))
1802                });
1803            if has_attached_leading_comment {
1804                continue;
1805            }
1806            // Check if this section header is followed only by blank lines,
1807            // comments, or another section header (or end of file).
1808            let mut has_entries = false;
1809            for j in (i + 1)..len {
1810                let next = self.raw_lines[j].trim();
1811                if next.is_empty() {
1812                    continue;
1813                }
1814                if section_re.is_match(&self.raw_lines[j]) {
1815                    break;
1816                }
1817                if comment_re.is_match(&self.raw_lines[j]) {
1818                    // Has comments — keep the section
1819                    has_entries = true;
1820                    break;
1821                }
1822                // Has a key-value entry
1823                has_entries = true;
1824                break;
1825            }
1826            if !has_entries {
1827                to_remove.push(i);
1828            }
1829        }
1830
1831        // Remove in reverse to preserve indices
1832        for &idx in to_remove.iter().rev() {
1833            self.raw_lines.remove(idx);
1834        }
1835
1836        // Also remove trailing blank lines
1837        while self.raw_lines.last().is_some_and(|l| l.trim().is_empty()) {
1838            self.raw_lines.pop();
1839        }
1840    }
1841
1842    /// Write the file back to [`Self::path`] through `{path}.lock` and an atomic rename.
1843    ///
1844    /// The existing file's permission bits are kept. Like Git, which has no `core.fsync`
1845    /// component for config files, the lock file is not fsynced before the rename: readers
1846    /// always see either the old or the new file, but a crash may lose the update.
1847    ///
1848    /// # Errors
1849    ///
1850    /// Returns [`Error::Io`] on write failure, or [`ConfigError::ConfigFileLocked`] when
1851    /// `{path}.lock` already exists.
1852    pub fn write(&self) -> Result<()> {
1853        let lock_path = config_lock_path(&self.path);
1854        let content = self.raw_lines.join("\n");
1855        let bytes: Vec<u8> = if content.trim().is_empty() {
1856            Vec::new()
1857        } else if content.ends_with('\n') {
1858            content.into_bytes()
1859        } else {
1860            format!("{content}\n").into_bytes()
1861        };
1862
1863        let mut lock_file = fs::OpenOptions::new()
1864            .write(true)
1865            .create_new(true)
1866            .open(&lock_path)
1867            .map_err(|e| {
1868                if e.kind() == std::io::ErrorKind::AlreadyExists {
1869                    Error::Config(ConfigError::ConfigFileLocked {
1870                        path: lock_path.display().to_string(),
1871                    })
1872                } else {
1873                    Error::Io(e)
1874                }
1875            })?;
1876
1877        #[cfg(unix)]
1878        if let Ok(meta) = fs::metadata(&self.path) {
1879            let _ = lock_file.set_permissions(meta.permissions());
1880        }
1881
1882        use std::io::Write as _;
1883        lock_file.write_all(&bytes).map_err(|e| {
1884            let _ = fs::remove_file(&lock_path);
1885            Error::Io(e)
1886        })?;
1887        drop(lock_file);
1888
1889        fs::rename(&lock_path, &self.path).map_err(|e| {
1890            let _ = fs::remove_file(&lock_path);
1891            Error::Io(e)
1892        })?;
1893        Ok(())
1894    }
1895
1896    /// Find the line index of a section header (case-insensitive match),
1897    /// or create one using the original-case names from user input.
1898    fn find_or_create_section_preserving_case(
1899        &mut self,
1900        section: &str,
1901        subsection: Option<&str>,
1902        raw_section: &str,
1903        raw_subsection: Option<&str>,
1904    ) -> usize {
1905        let sec_lower = section.to_lowercase();
1906        let mut parser = Parser::new();
1907        let mut last_match = None;
1908
1909        for (idx, line) in self.raw_lines.iter().enumerate() {
1910            if parser.try_parse_section(line) && section_matches(&parser, &sec_lower, subsection) {
1911                last_match = Some(idx);
1912            }
1913        }
1914        if let Some(idx) = last_match {
1915            return idx;
1916        }
1917
1918        // Create new section at end of file, using original case
1919        let header = match raw_subsection {
1920            Some(sub) => {
1921                let escaped = escape_subsection(sub);
1922                format!("[{} \"{}\"]", raw_section, escaped)
1923            }
1924            None => format!("[{}]", raw_section),
1925        };
1926        self.raw_lines.push(header);
1927        self.raw_lines.len() - 1
1928    }
1929
1930    /// Find the last line that belongs to the section starting at `section_line`.
1931    fn last_line_in_section(&self, section_line: usize) -> usize {
1932        let mut last = section_line;
1933        for idx in (section_line + 1)..self.raw_lines.len() {
1934            let trimmed = self.raw_lines[idx].trim();
1935            if trimmed.starts_with('[') {
1936                break;
1937            }
1938            last = idx;
1939        }
1940        last
1941    }
1942}
1943
1944// ── ConfigSet ───────────────────────────────────────────────────────
1945
1946impl ConfigSet {
1947    /// Create an empty config set.
1948    #[must_use]
1949    pub fn new() -> Self {
1950        Self {
1951            entries: Vec::new(),
1952        }
1953    }
1954
1955    /// All merged entries in load order (for listing keys such as `alias.*`).
1956    #[must_use]
1957    pub fn entries(&self) -> &[ConfigEntry] {
1958        &self.entries
1959    }
1960
1961    /// Merge entries from a [`ConfigFile`] into this set.
1962    ///
1963    /// Entries are appended; later values override earlier ones for
1964    /// single-value lookups.
1965    pub fn merge(&mut self, file: &ConfigFile) {
1966        self.entries.extend(file.entries.iter().cloned());
1967    }
1968
1969    /// Merge another [`ConfigSet`] into this set (entries appended in order).
1970    pub fn merge_set(&mut self, other: &ConfigSet) {
1971        self.entries.extend(other.entries.iter().cloned());
1972    }
1973
1974    /// Add a command-line override (`-c key=value`).
1975    pub fn add_command_override(&mut self, key: &str, value: &str) -> Result<()> {
1976        let canon = canonical_key(key)?;
1977        self.entries.push(ConfigEntry {
1978            key: canon,
1979            value: Some(value.to_owned()),
1980            scope: ConfigScope::Command,
1981            file: None,
1982            line: 0,
1983        });
1984        Ok(())
1985    }
1986
1987    /// Get the last (highest-priority) value for a key.
1988    ///
1989    /// # Parameters
1990    ///
1991    /// - `key` — the key to look up (will be canonicalized).
1992    ///
1993    /// # Returns
1994    ///
1995    /// `Some(value)` for the last matching entry, or `None` if not found.
1996    /// Bare boolean keys return `Some("true")`.
1997    ///
1998    /// Invalid keys are treated as unset (legacy lenient lookup for internal call sites).
1999    #[must_use]
2000    pub(crate) fn value(&self, key: &str) -> Option<String> {
2001        let canon = canonical_key(key).ok()?;
2002        self.entries
2003            .iter()
2004            .rev()
2005            .find(|e| e.key == canon)
2006            .map(|e| e.value.clone().unwrap_or_else(|| "true".to_owned()))
2007    }
2008
2009    /// Winning string value for `key`, or `None` when unset.
2010    ///
2011    /// # Errors
2012    ///
2013    /// Returns [`ConfigError::InvalidKey`] when `key` is not a valid Git config key.
2014    pub fn get(&self, key: &str) -> std::result::Result<Option<String>, ConfigError> {
2015        let canon = canonical_key(key).map_err(|e| match e {
2016            Error::Config(c) => c,
2017            _ => ConfigError::InvalidKey {
2018                key: key.to_owned(),
2019                reason: InvalidKeyReason::InvalidVariable,
2020            },
2021        })?;
2022        Ok(self
2023            .entries
2024            .iter()
2025            .rev()
2026            .find(|e| e.key == canon)
2027            .map(|e| e.value.clone().unwrap_or_else(|| "true".to_owned())))
2028    }
2029
2030    /// Last (highest-priority) [`ConfigEntry`] for a key, including origin metadata.
2031    ///
2032    /// Bare boolean keys are returned with [`ConfigEntry::value`] set to `None` (same as `get`,
2033    /// which maps them to `"true"` for string lookups).
2034    #[must_use]
2035    pub fn get_last_entry(&self, key: &str) -> Option<ConfigEntry> {
2036        let canon = canonical_key(key).ok()?;
2037        self.entries.iter().rev().find(|e| e.key == canon).cloned()
2038    }
2039
2040    /// Winning value for `key` plus scope, source file, and line (Git `--show-origin --show-scope`).
2041    ///
2042    /// # Errors
2043    ///
2044    /// Returns [`Error::Config`] when `key` is not a valid Git config key.
2045    pub fn origin_of(&self, key: &str) -> Result<Option<ConfigValueOrigin>> {
2046        let _canon = canonical_key(key)?;
2047        Ok(self.get_last_entry(key).map(|e| ConfigValueOrigin {
2048            value: e.value.clone().or_else(|| Some("true".to_owned())),
2049            scope: e.scope,
2050            file: config_entry_origin_file(&e).map(Path::to_path_buf),
2051            line: config_entry_origin_line(&e),
2052        }))
2053    }
2054
2055    /// Every value for `key` in load order, with origin metadata (Git `--get-all`).
2056    ///
2057    /// # Errors
2058    ///
2059    /// Returns [`Error::Config`] when `key` is not a valid Git config key.
2060    pub fn origins_of(&self, key: &str) -> Result<Vec<ConfigValueOrigin>> {
2061        let canon = canonical_key(key)?;
2062        Ok(self
2063            .entries
2064            .iter()
2065            .filter(|e| e.key == canon)
2066            .map(|e| ConfigValueOrigin {
2067                value: e.value.clone().or_else(|| Some("true".to_owned())),
2068                scope: e.scope,
2069                file: config_entry_origin_file(e).map(Path::to_path_buf),
2070                line: config_entry_origin_line(e),
2071            })
2072            .collect())
2073    }
2074
2075    /// All values for `key` in load order (lenient; invalid keys yield an empty list).
2076    #[must_use]
2077    pub(crate) fn values_all(&self, key: &str) -> Vec<String> {
2078        let canon = match canonical_key(key) {
2079            Ok(c) => c,
2080            Err(_) => return Vec::new(),
2081        };
2082        self.entries
2083            .iter()
2084            .filter(|e| e.key == canon)
2085            .map(|e| e.value.clone().unwrap_or_default())
2086            .collect()
2087    }
2088
2089    /// All values for `key` in load order.
2090    ///
2091    /// # Errors
2092    ///
2093    /// Returns [`ConfigError::InvalidKey`] when `key` is not valid.
2094    pub fn get_all(&self, key: &str) -> std::result::Result<Vec<String>, ConfigError> {
2095        let canon = canonical_key(key).map_err(|e| match e {
2096            Error::Config(c) => c,
2097            _ => ConfigError::InvalidKey {
2098                key: key.to_owned(),
2099                reason: InvalidKeyReason::InvalidVariable,
2100            },
2101        })?;
2102        Ok(self
2103            .entries
2104            .iter()
2105            .filter(|e| e.key == canon)
2106            .map(|e| e.value.clone().unwrap_or_default())
2107            .collect())
2108    }
2109
2110    /// All raw values for a key in load order, preserving `None` for bare boolean keys.
2111    ///
2112    /// Matches Git's multi-value list where `NULL` means a value-less / boolean-true key.
2113    #[must_use]
2114    pub fn get_all_raw(&self, key: &str) -> Vec<Option<String>> {
2115        let canon = match canonical_key(key) {
2116            Ok(c) => c,
2117            Err(_) => return Vec::new(),
2118        };
2119        self.entries
2120            .iter()
2121            .filter(|e| e.key == canon)
2122            .map(|e| e.value.clone())
2123            .collect()
2124    }
2125
2126    /// True if any config entry uses `key` (after canonicalization), including bare boolean keys.
2127    ///
2128    /// Unlike [`Self::get`], this does not treat a missing value as `"true"` — it reports whether
2129    /// the key appears in the merged config at all (Git `repo_config_get` / `git_configset_get`).
2130    #[must_use]
2131    pub fn has_key(&self, key: &str) -> bool {
2132        let Ok(canon) = canonical_key(key) else {
2133            return false;
2134        };
2135        self.entries.iter().any(|e| e.key == canon)
2136    }
2137
2138    /// Get a boolean value, interpreting `true`/`yes`/`on`/`1` as true and
2139    /// `false`/`no`/`off`/`0` as false.
2140    ///
2141    /// `pack.allowPackReuse` may be `single` or `multi` (Git enum, not a bool). Those values are
2142    /// treated as unset for boolean lookup so `get_bool` does not error during broad config scans.
2143    ///
2144    /// # Returns
2145    ///
2146    /// `None` when `key` is unset, otherwise the parsed value.
2147    ///
2148    /// # Errors
2149    ///
2150    /// [`ConfigError::InvalidValue`] naming `key` when the value is not a Git boolean.
2151    pub fn get_bool(&self, key: &str) -> std::result::Result<Option<bool>, ConfigError> {
2152        let Some(v) = self.get(key)? else {
2153            return Ok(None);
2154        };
2155        if canonical_key(key).ok().as_deref() == Some("pack.allowpackreuse") {
2156            let lower = v.trim().to_ascii_lowercase();
2157            if lower == "single" || lower == "multi" {
2158                return Ok(None);
2159            }
2160        }
2161        parse_bool(&v).map(Some).map_err(|e| e.for_key(key))
2162    }
2163
2164    /// Lenient boolean read: unset or invalid values fall back to `default`.
2165    pub(crate) fn bool_with_default(&self, key: &str, default: bool) -> bool {
2166        match self.get_bool(key) {
2167            Ok(Some(b)) => b,
2168            Ok(None) | Err(_) => default,
2169        }
2170    }
2171
2172    /// Whether path comparisons fold ASCII case (`core.ignoreCase`, default `false`).
2173    #[must_use]
2174    pub fn ignore_case(&self) -> bool {
2175        self.bool_with_default("core.ignoreCase", false)
2176    }
2177
2178    /// Whether paths are stored NFC-precomposed (`core.precomposeUnicode`, default `false`).
2179    ///
2180    /// This is the value in this set only; callers that may not have a loaded set use
2181    /// `effective_core_precomposeunicode_with_config`.
2182    #[must_use]
2183    pub fn precompose_unicode(&self) -> bool {
2184        self.bool_with_default("core.precomposeUnicode", false)
2185    }
2186
2187    /// Whether index refresh may stat entries in parallel (`core.preloadIndex`, default `true`).
2188    #[must_use]
2189    pub fn preload_index(&self) -> bool {
2190        self.bool_with_default("core.preloadIndex", true)
2191    }
2192
2193    /// Whether the executable bit in the work tree is trusted (`core.fileMode`, default `true`).
2194    #[must_use]
2195    pub fn file_mode(&self) -> bool {
2196        self.bool_with_default("core.fileMode", true)
2197    }
2198
2199    /// Whether pathnames in human-readable output should fully C-quote non-ASCII bytes as octal.
2200    ///
2201    /// Maps to Git's `quote_path_fully` (`core.quotePath`, default true). When false, UTF-8 and
2202    /// other high bytes are emitted literally; only ASCII specials are escaped.
2203    #[must_use]
2204    pub fn quote_path_fully(&self) -> bool {
2205        self.bool_with_default("core.quotePath", true)
2206    }
2207
2208    /// Default for `pack.writeBitmapHashCache` (Git default: true).
2209    #[must_use]
2210    pub fn pack_write_bitmap_hash_cache(&self) -> bool {
2211        self.bool_with_default("pack.writeBitmapHashCache", true)
2212    }
2213
2214    /// Default for `pack.writeBitmapLookupTable` (Git default: false).
2215    #[must_use]
2216    pub fn pack_write_bitmap_lookup_table(&self) -> bool {
2217        self.bool_with_default("pack.writeBitmapLookupTable", false)
2218    }
2219
2220    /// Values of `pack.preferBitmapTips` (may appear multiple times).
2221    #[must_use]
2222    pub fn pack_prefer_bitmap_tips(&self) -> Vec<String> {
2223        let mut out = self.values_all("pack.preferbitmaptips");
2224        if out.is_empty() {
2225            out = self.values_all("pack.preferBitmapTips");
2226        }
2227        out
2228    }
2229
2230    /// Build [`crate::pack_bitmap::PackBitmapWriteOptions`] from config keys.
2231    #[must_use]
2232    pub fn pack_bitmap_write_options(&self) -> crate::pack_bitmap::PackBitmapWriteOptions {
2233        crate::pack_bitmap::PackBitmapWriteOptions {
2234            full_dag: true,
2235            hash_cache: self.pack_write_bitmap_hash_cache(),
2236            lookup_table: self.pack_write_bitmap_lookup_table(),
2237            prefer_bitmap_tips: self.pack_prefer_bitmap_tips(),
2238            verify_reachability_closure: true,
2239            reachability_roots: None,
2240        }
2241    }
2242
2243    /// Default for `pack.writeReverseIndex` / `pack.writereverseindex` (Git default: true).
2244    #[must_use]
2245    pub fn pack_write_reverse_index_default(&self) -> bool {
2246        if self
2247            .value("pack.writeReverseIndex")
2248            .is_some_and(|v| v.trim().is_empty())
2249        {
2250            return false;
2251        }
2252        self.bool_with_default("pack.writeReverseIndex", true)
2253    }
2254
2255    /// Resolved worker count for pack indexing (`pack.threads`, Git default: unset → all CPUs).
2256    #[must_use]
2257    pub fn pack_index_threads(&self) -> Option<usize> {
2258        self.get_i64("pack.threads")
2259            .ok()
2260            .flatten()
2261            .and_then(|n| usize::try_from(n).ok())
2262    }
2263
2264    /// In-pack delta window (`pack.window`, Git default: 10 when unset).
2265    ///
2266    /// An explicit `0` disables newly computed deltas (on-disk reuse may still apply).
2267    #[must_use]
2268    pub fn pack_object_window(&self) -> usize {
2269        match self.get_i64("pack.window").ok().flatten() {
2270            None => 10,
2271            Some(n) if n >= 0 => usize::try_from(n).unwrap_or(10),
2272            Some(_) => 10,
2273        }
2274    }
2275
2276    /// In-pack delta chain depth cap (`pack.depth`, Git default: 50 when unset).
2277    ///
2278    /// An explicit `0` disables newly computed deltas (on-disk reuse may still apply).
2279    #[must_use]
2280    /// Sliding-window memory cap for delta search (`pack.windowMemory`, Git default: unlimited).
2281    pub fn pack_window_memory_bytes(&self) -> u64 {
2282        match self.get_i64("pack.windowmemory").ok().flatten() {
2283            None => 0,
2284            Some(n) if n >= 0 => u64::try_from(n).unwrap_or(0),
2285            Some(_) => 0,
2286        }
2287    }
2288
2289    /// Maximum delta depth for `git pack-objects` (`pack.depth`, Git default 50).
2290    pub fn pack_object_depth(&self) -> usize {
2291        match self.get_i64("pack.depth").ok().flatten() {
2292            None => crate::pack::DEFAULT_PACK_DEPTH,
2293            Some(n) if n >= 0 => usize::try_from(n).unwrap_or(crate::pack::DEFAULT_PACK_DEPTH),
2294            Some(_) => crate::pack::DEFAULT_PACK_DEPTH,
2295        }
2296    }
2297
2298    /// Approximate loose-object count above which automatic maintenance packs loose objects
2299    /// (`gc.auto`, Git default 6700).
2300    ///
2301    /// Returns `None` when `gc.auto` is zero or negative, which turns off automatic maintenance
2302    /// entirely (including the [`Self::gc_auto_pack_limit`] trigger). Unparsable values fall
2303    /// back to the default.
2304    #[must_use]
2305    pub fn gc_auto_threshold(&self) -> Option<usize> {
2306        match self.get_i64("gc.auto").ok().flatten() {
2307            Some(n) if n <= 0 => None,
2308            Some(n) => Some(usize::try_from(n).unwrap_or(usize::MAX)),
2309            None => Some(DEFAULT_GC_AUTO_THRESHOLD),
2310        }
2311    }
2312
2313    /// Number of non-`.keep` local packs above which automatic maintenance consolidates every
2314    /// pack into one (`gc.autoPackLimit`, Git default 50).
2315    ///
2316    /// Returns `None` when the value is zero or negative (pack consolidation trigger off).
2317    /// Unparsable values fall back to the default.
2318    #[must_use]
2319    pub fn gc_auto_pack_limit(&self) -> Option<usize> {
2320        match self.get_i64("gc.autoPackLimit").ok().flatten() {
2321            Some(n) if n <= 0 => None,
2322            Some(n) => Some(usize::try_from(n).unwrap_or(usize::MAX)),
2323            None => Some(DEFAULT_GC_AUTO_PACK_LIMIT),
2324        }
2325    }
2326
2327    /// Whether automatic maintenance runs in a detached background process
2328    /// (`gc.autoDetach`, default `true`).
2329    #[must_use]
2330    pub fn gc_auto_detach(&self) -> bool {
2331        self.bool_with_default("gc.autoDetach", true)
2332    }
2333
2334    /// Whether commands may start automatic maintenance at all (`maintenance.auto`, default
2335    /// `true`).
2336    #[must_use]
2337    pub fn maintenance_auto(&self) -> bool {
2338        self.bool_with_default("maintenance.auto", true)
2339    }
2340
2341    /// [`crate::hash::Parallelism`] for pack indexing from merged config.
2342    ///
2343    /// # Errors
2344    ///
2345    /// Returns [`ConfigError`] when `pack.threads` is set to a value Git rejects.
2346    pub fn try_pack_index_parallelism(
2347        &self,
2348    ) -> std::result::Result<crate::parallel::Parallelism, ConfigError> {
2349        Ok(crate::parallel::ThreadPolicy::default()
2350            .try_resolve(crate::parallel::ParallelOp::IndexPack, self)?
2351            .parallelism())
2352    }
2353
2354    /// Like [`Self::try_pack_index_parallelism`], but an invalid `pack.threads`
2355    /// falls back to the default (all available cores) instead of an error.
2356    #[must_use]
2357    pub fn pack_index_parallelism(&self) -> crate::parallel::Parallelism {
2358        self.try_pack_index_parallelism()
2359            .unwrap_or_else(|_| crate::parallel::Parallelism::resolve(None))
2360    }
2361
2362    /// Load config for `git_dir` (if any) and resolve [`crate::hash::Parallelism`] for index-pack.
2363    ///
2364    /// # Errors
2365    ///
2366    /// Propagates config load failures and invalid `pack.threads`.
2367    pub fn try_pack_index_parallelism_for_git_dir(
2368        env: &Environment,
2369        git_dir: Option<&std::path::Path>,
2370    ) -> Result<crate::parallel::Parallelism> {
2371        match git_dir {
2372            Some(d) => {
2373                let cfg = Self::load(env, Some(d), &LoadConfigOptions::standard(env, Some(d)))?;
2374                Ok(cfg.try_pack_index_parallelism()?)
2375            }
2376            None => Ok(crate::parallel::Parallelism::resolve(None)),
2377        }
2378    }
2379
2380    /// Load config for `git_dir` (if any) and resolve [`crate::hash::Parallelism`] for index-pack.
2381    #[must_use]
2382    pub fn pack_index_parallelism_for_git_dir(
2383        env: &Environment,
2384        git_dir: Option<&std::path::Path>,
2385    ) -> crate::parallel::Parallelism {
2386        Self::try_pack_index_parallelism_for_git_dir(env, git_dir)
2387            .unwrap_or_else(|_| crate::parallel::Parallelism::resolve(None))
2388    }
2389
2390    /// Default for `pack.readReverseIndex` / `pack.readreverseindex` (Git default: true).
2391    #[must_use]
2392    pub fn pack_read_reverse_index_default(&self) -> bool {
2393        self.bool_with_default("pack.readReverseIndex", true)
2394    }
2395
2396    /// `core.logAllRefUpdates` as configured in this set, or [`refs::LogRefsConfig::Unset`] when
2397    /// the key is absent or holds an unrecognised value.
2398    #[must_use]
2399    pub(crate) fn log_refs_config(&self) -> refs::LogRefsConfig {
2400        self.value("core.logAllRefUpdates")
2401            .and_then(|v| refs::LogRefsConfig::parse(&v))
2402            .unwrap_or(refs::LogRefsConfig::Unset)
2403    }
2404
2405    /// Resolved `core.logAllRefUpdates` using this merged set (includes `git -c` / env), then Git's
2406    /// bare-repo default when the key is unset everywhere.
2407    ///
2408    /// Never returns [`refs::LogRefsConfig::Unset`]: an unset (or unrecognised) value resolves to
2409    /// [`refs::LogRefsConfig::None`] in a bare repository and [`refs::LogRefsConfig::Normal`]
2410    /// otherwise.
2411    #[must_use]
2412    pub fn effective_log_refs_config(&self) -> refs::LogRefsConfig {
2413        match self.log_refs_config() {
2414            refs::LogRefsConfig::Unset if self.bool_with_default("core.bare", false) => {
2415                refs::LogRefsConfig::None
2416            }
2417            refs::LogRefsConfig::Unset => refs::LogRefsConfig::Normal,
2418            mode => mode,
2419        }
2420    }
2421
2422    /// Build a set from already-parsed entries (in load order).
2423    pub(crate) fn from_entries(entries: Vec<ConfigEntry>) -> Self {
2424        Self { entries }
2425    }
2426
2427    /// Get an integer value, supporting Git's `k`/`m`/`g` suffixes.
2428    ///
2429    /// # Returns
2430    ///
2431    /// `None` when `key` is unset, otherwise the parsed value.
2432    ///
2433    /// # Errors
2434    ///
2435    /// [`ConfigError::InvalidValue`] naming `key` when the value is not an integer or
2436    /// overflows `i64`.
2437    pub fn get_i64(&self, key: &str) -> std::result::Result<Option<i64>, ConfigError> {
2438        self.get(key)?
2439            .map(|v| parse_i64(&v).map_err(|e| e.for_key(key)))
2440            .transpose()
2441    }
2442
2443    /// Expand a path value using `env` (tilde and environment variables).
2444    pub fn get_path(
2445        &self,
2446        env: &Environment,
2447        key: &str,
2448    ) -> std::result::Result<Option<PathBuf>, ConfigError> {
2449        Ok(self.get(key)?.map(|v| PathBuf::from(parse_path(env, &v))))
2450    }
2451
2452    /// Parse a Git color value for `key`.
2453    pub fn get_color(&self, key: &str) -> std::result::Result<Option<String>, ConfigError> {
2454        self.get(key)?
2455            .map(|v| parse_color(&v).map_err(|e| e.for_key(key)))
2456            .transpose()
2457    }
2458
2459    /// Parse `core.compression` / `core.looseCompression` style zlib level integers.
2460    ///
2461    /// `-1` selects zlib's default (level 6). Valid values are `-1` or `0..=9`; anything else
2462    /// is a configuration error.
2463    fn parse_zlib_compression_level(key: &str, raw: &str) -> Result<i32> {
2464        const Z_DEFAULT_COMPRESSION: i32 = 6;
2465        const Z_BEST_COMPRESSION: i32 = 9;
2466
2467        let bad = |reason| {
2468            Error::Config(ConfigError::BadNumericValue {
2469                key: key.to_owned(),
2470                value: raw.to_owned(),
2471                reason,
2472            })
2473        };
2474        let v = parse_git_config_int_strict(raw.trim()).map_err(|e| bad(e.into()))?;
2475        if v == -1 {
2476            return Ok(Z_DEFAULT_COMPRESSION);
2477        }
2478        if v < 0 || v > i64::from(Z_BEST_COMPRESSION) {
2479            return Err(bad(BadNumericSource::OutOfRange));
2480        }
2481        Ok(v as i32)
2482    }
2483
2484    /// Zlib deflate level for loose objects (Git's `zlib_compression_level`).
2485    ///
2486    /// Walks [`Self::entries`] in load order. Every `core.compression` and `core.looseCompression`
2487    /// entry is parsed and validated (including shadowed or overridden values); bare keys and
2488    /// invalid numbers return [`Error::Config`]. `core.compression` sets the loose level until
2489    /// the first valid `core.looseCompression` is seen; later `core.compression` entries are still
2490    /// validated but ignored for the loose level. When neither key appears, returns
2491    /// [`Self::LOOSE_OBJECTS_ZLIB_DEFAULT`] (`Z_BEST_SPEED`, level 1).
2492    ///
2493    /// `-1` means zlib default (level 6). Valid values are `-1` or `0..=9`.
2494    pub fn loose_objects_zlib_level(&self) -> Result<i32> {
2495        let mut loose_level = Self::LOOSE_OBJECTS_ZLIB_DEFAULT;
2496        let mut loose_compression_seen = false;
2497        let missing_value = |key: &str| {
2498            Error::Config(ConfigError::MissingValue {
2499                key: key.to_owned(),
2500            })
2501        };
2502
2503        for e in self.entries() {
2504            match e.key.as_str() {
2505                "core.compression" => {
2506                    let val = e.value.as_deref().ok_or_else(|| missing_value(&e.key))?;
2507                    let level = Self::parse_zlib_compression_level(&e.key, val)?;
2508                    if !loose_compression_seen {
2509                        loose_level = level;
2510                    }
2511                }
2512                "core.loosecompression" => {
2513                    let val = e.value.as_deref().ok_or_else(|| missing_value(&e.key))?;
2514                    let level = Self::parse_zlib_compression_level(&e.key, val)?;
2515                    loose_level = level;
2516                    loose_compression_seen = true;
2517                }
2518                _ => {}
2519            }
2520        }
2521
2522        Ok(loose_level)
2523    }
2524
2525    /// Git's default zlib level for loose objects when neither `core.looseCompression` nor
2526    /// `core.compression` is set (`Z_BEST_SPEED`).
2527    pub const LOOSE_OBJECTS_ZLIB_DEFAULT: i32 = 1;
2528
2529    /// Git's default `core.bigFileThreshold` (512 MiB).
2530    pub const BIG_FILE_THRESHOLD_DEFAULT: u64 = 512 * 1024 * 1024;
2531
2532    /// Size in bytes at or above which files are treated as big (`core.bigFileThreshold`).
2533    ///
2534    /// Big files are hashed and stored as a stream instead of being read into memory, and
2535    /// are written straight into a pack. The value accepts Git's `k`/`m`/`g` suffixes; the
2536    /// last entry wins. When unset, returns [`Self::BIG_FILE_THRESHOLD_DEFAULT`].
2537    ///
2538    /// # Errors
2539    ///
2540    /// Returns [`ConfigError::BadNumericValue`] when the value is missing, not a number, has
2541    /// an unknown unit, or is negative.
2542    pub fn big_file_threshold(&self) -> Result<u64> {
2543        const KEY: &str = "core.bigfilethreshold";
2544        let Some(entry) = self.get_last_entry(KEY) else {
2545            return Ok(Self::BIG_FILE_THRESHOLD_DEFAULT);
2546        };
2547        let raw = entry.value.as_deref().unwrap_or_default();
2548        let bad = |reason| {
2549            Error::Config(ConfigError::BadNumericValue {
2550                key: KEY.to_owned(),
2551                value: raw.to_owned(),
2552                reason,
2553            })
2554        };
2555        let value = parse_git_config_int_strict(raw.trim()).map_err(|e| bad(e.into()))?;
2556        u64::try_from(value).map_err(|_| bad(BadNumericSource::OutOfRange))
2557    }
2558
2559    /// Zlib deflate level for `git pack-objects` (Git's `pack_compression_level`).
2560    ///
2561    /// Entries are applied in [`Self::entries`] order. `core.compression` sets the pack level
2562    /// until a `pack.compression` appears (Git `pack_compression_seen`). `core.loosecompression`
2563    /// is ignored here — it only affects loose-object zlib, not packs.
2564    ///
2565    /// `-1` means zlib default (level 6). Valid values are `-1` or `0..=9`.
2566    pub fn pack_objects_zlib_level(&self) -> Result<i32> {
2567        const Z_DEFAULT_COMPRESSION: i32 = 6;
2568
2569        // `core.loosecompression` affects loose objects only (Git `zlib_compression_level`), not pack.
2570        let mut pack_level = Z_DEFAULT_COMPRESSION;
2571        let mut pack_compression_seen = false;
2572
2573        for e in self.entries() {
2574            match e.key.as_str() {
2575                "core.compression" => {
2576                    let Some(val) = e.value.as_deref() else {
2577                        continue;
2578                    };
2579                    let level = Self::parse_zlib_compression_level(&e.key, val)?;
2580                    if !pack_compression_seen {
2581                        pack_level = level;
2582                    }
2583                }
2584                "pack.compression" => {
2585                    let Some(val) = e.value.as_deref() else {
2586                        continue;
2587                    };
2588                    pack_level = Self::parse_zlib_compression_level(&e.key, val)?;
2589                    pack_compression_seen = true;
2590                }
2591                _ => {}
2592            }
2593        }
2594
2595        Ok(pack_level)
2596    }
2597
2598    /// Get all entries matching a key pattern (regex).
2599    ///
2600    /// Used by `git config --get-regexp`. Returns an error if the pattern
2601    /// is not a valid regex.
2602    pub fn get_regexp(&self, pattern: &str) -> std::result::Result<Vec<&ConfigEntry>, ConfigError> {
2603        let re = regex::Regex::new(pattern).map_err(|source| ConfigError::InvalidPattern {
2604            pattern: pattern.to_owned(),
2605            source,
2606        })?;
2607        Ok(self
2608            .entries
2609            .iter()
2610            .filter(|e| re.is_match(&e.key))
2611            .collect())
2612    }
2613
2614    /// Load the Git configuration cascade.
2615    ///
2616    /// See [`LoadConfigOptions`] for system/global/local scope, includes, and command-line overrides.
2617    ///
2618    /// Uncached load: parses the cascade from disk every call. Repository-scoped memoization
2619    /// lives on [`crate::repo_caches::RepoCaches::load_config_with_options`].
2620    ///
2621    /// # Errors
2622    ///
2623    /// Returns errors from file I/O or parsing.
2624    pub fn load(
2625        env: &Environment,
2626        git_dir: Option<&Path>,
2627        opts: &LoadConfigOptions,
2628    ) -> Result<Self> {
2629        Self::load_with_options_uncached(env, git_dir, opts, &mut Vec::new())
2630    }
2631
2632    fn read_local_config_text_optional(
2633        path: &Path,
2634        caches: Option<&std::sync::Arc<crate::repo_caches::RepoCaches>>,
2635    ) -> Result<Option<String>> {
2636        let read = |p: &Path| -> Result<Option<String>> {
2637            match fs::read_to_string(p) {
2638                Ok(text) => Ok(Some(text)),
2639                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
2640                Err(e) => Err(Error::Io(e)),
2641            }
2642        };
2643        let Some(c) = caches else {
2644            return read(path);
2645        };
2646        match c.local_config_text(path) {
2647            Ok(text) => Ok(Some(text)),
2648            Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
2649            Err(e) => Err(e),
2650        }
2651    }
2652
2653    pub(crate) fn load_with_options_uncached(
2654        env: &Environment,
2655        git_dir: Option<&Path>,
2656        opts: &LoadConfigOptions,
2657        included_files: &mut Vec<PathBuf>,
2658    ) -> Result<Self> {
2659        let proc = opts.process_includes;
2660        let mut ctx = opts.include_ctx.clone();
2661        if ctx.cwd.as_os_str().is_empty() {
2662            ctx.cwd = env.cwd.clone();
2663        }
2664        ctx.pwd = env.pwd.clone();
2665        ctx.env = std::sync::Arc::new(env.clone());
2666        let mut layers = Vec::new();
2667
2668        if opts.repo_local_only {
2669            let gd = git_dir
2670                .or(opts.include_ctx.git_dir.as_deref())
2671                .ok_or_else(|| Error::Config(ConfigError::RepositoryRequired))?;
2672            let local_path = gd.join("config");
2673            let mut set = Self::new();
2674            if let Ok(Some(f)) = ConfigFile::from_path(&local_path, ConfigScope::Local) {
2675                set.merge_layers(&[ConfigLayer::file(f)], proc, &ctx, included_files)?;
2676            }
2677            return Ok(set);
2678        }
2679
2680        if opts.include_system && !git_config_nosystem_enabled(env) {
2681            let system_path = system_config_path(env);
2682            if let Some(f) = ConfigFile::from_path(&system_path, ConfigScope::System)? {
2683                layers.push(ConfigLayer::file(f));
2684            }
2685        }
2686
2687        // Global config (Git merges every existing file: XDG then ~/.gitconfig).
2688        for path in global_config_paths(env) {
2689            if let Some(f) = ConfigFile::from_path(&path, ConfigScope::Global)? {
2690                layers.push(ConfigLayer::file(f));
2691            }
2692        }
2693
2694        // Local config — linked worktrees read `commondir/config`, not the admin `config`.
2695        if !opts.protected_only {
2696            if let Some(gd) = git_dir {
2697                let common_dir = crate::repo::common_git_dir_for_config(gd);
2698                let local_path = common_dir.join("config");
2699                let local_text =
2700                    Self::read_local_config_text_optional(&local_path, opts.repo_caches.as_ref())?;
2701                if let Some(msg) =
2702                    crate::repo::early_config_ignore_repo_reason_for_text(local_text.as_deref())
2703                {
2704                    if let Some(sink) = opts.diagnostics.as_ref() {
2705                        sink.warn(crate::diagnostics::Warning::IgnoredGitDir {
2706                            path: gd.to_path_buf(),
2707                            reason: msg,
2708                        });
2709                    }
2710                } else if let Some(text) = local_text.as_deref() {
2711                    let f = ConfigFile::parse(&local_path, text, ConfigScope::Local)?;
2712                    layers.push(ConfigLayer::file(f));
2713                }
2714
2715                // Worktree config — Git only reads `config.worktree` when
2716                // `extensions.worktreeConfig` is enabled in the common repository `config`.
2717                let wt_path = gd.join("config.worktree");
2718                if crate::repo::worktree_config_enabled_for_text(local_text.as_deref()) {
2719                    if let Some(f) = ConfigFile::from_path(&wt_path, ConfigScope::Worktree)? {
2720                        layers.push(ConfigLayer::file(f));
2721                    }
2722                }
2723            }
2724        }
2725
2726        if !opts.protected_only {
2727            if let Some(path) = env.git_config.as_deref() {
2728                let path = resolve_config_override_path(env, path);
2729                if let Some(f) = ConfigFile::from_path(&path, ConfigScope::Command)? {
2730                    layers.push(ConfigLayer::file(f));
2731                }
2732            }
2733        }
2734
2735        layers.push(ConfigLayer::Entries(environment_config_pair_entries(env)?));
2736
2737        // GIT_CONFIG_PARAMETERS — used by `git -c key=value`.
2738        if let Some(params) = env
2739            .git_config_parameters
2740            .as_deref()
2741            .filter(|p| !p.trim().is_empty())
2742        {
2743            if proc && opts.command_includes {
2744                let pseudo = Path::new(":GIT_CONFIG_PARAMETERS");
2745                let cmd_file = ConfigFile::from_git_config_parameters(pseudo, params)?;
2746                layers.push(ConfigLayer::file(cmd_file));
2747            } else {
2748                layers.push(ConfigLayer::Entries(command_override_entries(params)));
2749            }
2750        }
2751
2752        let mut set = Self::new();
2753        set.merge_layers(&layers, proc, &ctx, included_files)?;
2754        Ok(set)
2755    }
2756
2757    /// Read configuration the way Git's `read_early_config` / `do_git_config_sequence` does:
2758    /// system (unless disabled), global files in Git order, optional repository `config` /
2759    /// `config.worktree`, then `GIT_CONFIG_PARAMETERS`.
2760    ///
2761    /// When `git_dir` is `None` (no discovered repository, e.g. `GIT_CEILING_DIRECTORIES`), only
2762    /// non-repo layers are read — matching Git when discovery returns no gitdir (t1309 ceiling #2).
2763    ///
2764    /// Returns all values for `key` in load order (Git's `read_early_config` callback runs once per
2765    /// occurrence).
2766    ///
2767    /// This matches upstream ordering for `test-tool config read_early_config` (t1309, t1305).
2768    pub fn read_early_config(
2769        env: &Environment,
2770        git_dir: Option<&Path>,
2771        key: &str,
2772    ) -> Result<Vec<String>> {
2773        let ctx = IncludeContext {
2774            git_dir: git_dir.map(PathBuf::from),
2775            command_line_relative_include_is_error: false,
2776            cwd: env.cwd.clone(),
2777            pwd: env.pwd.clone(),
2778            env: std::sync::Arc::new(env.clone()),
2779        };
2780        let mut layers = Vec::new();
2781
2782        if !git_config_nosystem_enabled(env) {
2783            let system_path = system_config_path(env);
2784            if let Ok(Some(f)) = ConfigFile::from_path(&system_path, ConfigScope::System) {
2785                layers.push(ConfigLayer::file(f));
2786            }
2787        }
2788
2789        // Global: all existing candidates (Git merges every readable file).
2790        for path in global_config_paths(env) {
2791            if let Ok(Some(f)) = ConfigFile::from_path(&path, ConfigScope::Global) {
2792                layers.push(ConfigLayer::file(f));
2793            }
2794        }
2795
2796        if let Some(gd) = git_dir {
2797            let common_dir = crate::repo::common_git_dir_for_config(gd);
2798            // Local (commondir) — skip when format is newer than supported (t1309).
2799            let local_path = common_dir.join("config");
2800            if crate::repo::early_config_ignore_repo_reason(&common_dir).is_some() {
2801                // Local config skipped for unsupported repository format (see `Warning::IgnoredGitDir`).
2802            } else if let Ok(Some(f)) = ConfigFile::from_path(&local_path, ConfigScope::Local) {
2803                layers.push(ConfigLayer::file(f));
2804            }
2805
2806            // Worktree-specific config (when enabled for this repo).
2807            let wt_path = gd.join("config.worktree");
2808            if crate::repo::worktree_config_enabled(&common_dir) {
2809                if let Ok(Some(f)) = ConfigFile::from_path(&wt_path, ConfigScope::Worktree) {
2810                    layers.push(ConfigLayer::file(f));
2811                }
2812            }
2813        }
2814
2815        // GIT_CONFIG_PARAMETERS — same as full load (`load_with_options` default).
2816        if let Some(params) = env
2817            .git_config_parameters
2818            .as_deref()
2819            .filter(|p| !p.trim().is_empty())
2820        {
2821            let pseudo = Path::new(":GIT_CONFIG_PARAMETERS");
2822            let cmd_file = ConfigFile::from_git_config_parameters(pseudo, params)?;
2823            layers.push(ConfigLayer::file(cmd_file));
2824        }
2825
2826        let mut set = Self::new();
2827        set.merge_layers(&layers, true, &ctx, &mut Vec::new())?;
2828        Ok(set.values_all(key))
2829    }
2830
2831    /// Merge a single config file, optionally expanding `[include]` / `[includeIf]`.
2832    ///
2833    /// Used by `grit config -f` and scoped reads; [`ConfigSet::load`] uses the same
2834    /// internal routine for the standard cascade.
2835    ///
2836    /// `hasconfig:remote.*.url:` conditions match only remote URLs reachable from `file`
2837    /// itself (like `git config -f <file> --includes`), not URLs already in `self`.
2838    ///
2839    /// # Errors
2840    ///
2841    /// Unreadable or unparsable include targets, include recursion past Git's depth limit,
2842    /// and [`ConfigError::RemoteUrlInHasconfigInclude`].
2843    pub fn merge_file(&mut self, file: &ConfigFile, options: &IncludeOptions) -> Result<()> {
2844        let ctx = &options.context;
2845        self.merge_layers(
2846            &[ConfigLayer::File(Cow::Borrowed(file))],
2847            options.mode == IncludeMode::Follow,
2848            ctx,
2849            &mut Vec::new(),
2850        )
2851    }
2852
2853    /// Merge `layers` in order, expanding includes in file layers when `process_includes`.
2854    ///
2855    /// `hasconfig:remote.*.url:` conditions anywhere in the load match against the remote
2856    /// URLs of *all* layers (Git evaluates them against the complete configuration), so a
2857    /// global include can depend on a remote defined in the repository `config`. Every
2858    /// include target opened is recorded in `included_files` so the cascade cache can stamp it.
2859    fn merge_layers(
2860        &mut self,
2861        layers: &[ConfigLayer<'_>],
2862        process_includes: bool,
2863        ctx: &IncludeContext,
2864        included_files: &mut Vec<PathBuf>,
2865    ) -> Result<()> {
2866        // Headroom for the entries of typical small include files (identities, aliases), so
2867        // merging one does not double a vector sized exactly to the top-level layers.
2868        const INCLUDE_HEADROOM: usize = 64;
2869        let mut remote_urls = RemoteUrls::new(layers);
2870        let top_level: usize = layers
2871            .iter()
2872            .map(|layer| match layer {
2873                ConfigLayer::File(file) => file.entries.len(),
2874                ConfigLayer::Entries(entries) => entries.len(),
2875            })
2876            .sum();
2877        self.entries.reserve(top_level + INCLUDE_HEADROOM);
2878        for layer in layers {
2879            match layer {
2880                ConfigLayer::File(file) => Self::merge_with_includes(
2881                    self,
2882                    file,
2883                    process_includes,
2884                    0,
2885                    ctx,
2886                    &mut remote_urls,
2887                    included_files,
2888                )?,
2889                ConfigLayer::Entries(entries) => self.entries.extend(entries.iter().cloned()),
2890            }
2891        }
2892        Ok(())
2893    }
2894
2895    /// Merge `file`, expanding `[include]` / `[includeIf]` targets in place.
2896    fn merge_with_includes(
2897        set: &mut Self,
2898        file: &ConfigFile,
2899        process_includes: bool,
2900        depth: usize,
2901        ctx: &IncludeContext,
2902        remote_urls: &mut RemoteUrls<'_>,
2903        included_files: &mut Vec<PathBuf>,
2904    ) -> Result<()> {
2905        check_include_depth(depth)?;
2906        if !process_includes {
2907            set.merge(file);
2908            return Ok(());
2909        }
2910
2911        for entry in &file.entries {
2912            set.entries.push(entry.clone());
2913
2914            let Some((inc_path, condition)) = include_directive_for_entry(entry) else {
2915                continue;
2916            };
2917            if let Some(cond) = condition.as_deref() {
2918                let holds = match hasconfig_remote_url_pattern(cond) {
2919                    Some(pattern) => remote_urls.any_matches(pattern, ctx, included_files)?,
2920                    None => evaluate_include_condition(cond, file, ctx),
2921                };
2922                if !holds {
2923                    continue;
2924                }
2925            }
2926            let Some(inc_file) = open_include_target(&inc_path, file, ctx, included_files)? else {
2927                continue;
2928            };
2929            Self::merge_with_includes(
2930                set,
2931                &inc_file,
2932                process_includes,
2933                depth + 1,
2934                ctx,
2935                remote_urls,
2936                included_files,
2937            )?;
2938        }
2939
2940        Ok(())
2941    }
2942}
2943
2944/// One step of a configuration load, merged in order by [`ConfigSet::merge_layers`].
2945enum ConfigLayer<'a> {
2946    /// A config file whose includes are expanded when the load processes includes.
2947    File(Cow<'a, ConfigFile>),
2948    /// Entries appended verbatim (`GIT_CONFIG_COUNT` pairs, `-c` overrides read without includes).
2949    Entries(Vec<ConfigEntry>),
2950}
2951
2952impl ConfigLayer<'_> {
2953    fn file(file: ConfigFile) -> Self {
2954        Self::File(Cow::Owned(file))
2955    }
2956}
2957
2958/// Remote URLs that `hasconfig:remote.*.url:` conditions match against, collected from every
2959/// layer of the current load on the first such condition and reused for the rest of it.
2960struct RemoteUrls<'a> {
2961    layers: &'a [ConfigLayer<'a>],
2962    urls: Option<Vec<String>>,
2963}
2964
2965impl<'a> RemoteUrls<'a> {
2966    fn new(layers: &'a [ConfigLayer<'a>]) -> Self {
2967        Self { layers, urls: None }
2968    }
2969
2970    /// Whether any `remote.<name>.url` value in the load matches `pattern` (`WM_PATHNAME`).
2971    fn any_matches(
2972        &mut self,
2973        pattern: &str,
2974        ctx: &IncludeContext,
2975        included_files: &mut Vec<PathBuf>,
2976    ) -> Result<bool> {
2977        let urls = match self.urls.take() {
2978            Some(urls) => urls,
2979            None => self.collect(ctx, included_files)?,
2980        };
2981        let hit = urls
2982            .iter()
2983            .any(|url| wildmatch(pattern.as_bytes(), url.as_bytes(), WM_PATHNAME));
2984        self.urls = Some(urls);
2985        Ok(hit)
2986    }
2987
2988    fn collect(
2989        &self,
2990        ctx: &IncludeContext,
2991        included_files: &mut Vec<PathBuf>,
2992    ) -> Result<Vec<String>> {
2993        let mut urls = Vec::new();
2994        for layer in self.layers {
2995            match layer {
2996                ConfigLayer::File(file) => {
2997                    collect_remote_urls(file, false, 0, ctx, &mut urls, included_files)?;
2998                }
2999                ConfigLayer::Entries(entries) => urls.extend(
3000                    entries
3001                        .iter()
3002                        .filter(|entry| is_remote_url_entry(entry))
3003                        .filter_map(|entry| entry.value.clone()),
3004                ),
3005            }
3006        }
3007        Ok(urls)
3008    }
3009}
3010
3011/// Collect `remote.<name>.url` values from `file` and everything it includes.
3012///
3013/// As in Git, this pass opens every `[includeIf]` target whose condition holds, treating every
3014/// `hasconfig:remote.*.url:` condition as holding. Remote URLs may not come from a conditional
3015/// include (directly or through nested includes), since they could change which conditions hold:
3016/// finding one there is [`ConfigError::RemoteUrlInHasconfigInclude`].
3017fn collect_remote_urls(
3018    file: &ConfigFile,
3019    in_conditional_include: bool,
3020    depth: usize,
3021    ctx: &IncludeContext,
3022    urls: &mut Vec<String>,
3023    included_files: &mut Vec<PathBuf>,
3024) -> Result<()> {
3025    check_include_depth(depth)?;
3026    for entry in &file.entries {
3027        if is_remote_url_entry(entry) {
3028            if in_conditional_include {
3029                return Err(ConfigError::RemoteUrlInHasconfigInclude.into());
3030            }
3031            urls.extend(entry.value.clone());
3032            continue;
3033        }
3034        let Some((inc_path, condition)) = include_directive_for_entry(entry) else {
3035            continue;
3036        };
3037        let conditional = match condition.as_deref() {
3038            None => in_conditional_include,
3039            Some(cond) => {
3040                if hasconfig_remote_url_pattern(cond).is_none()
3041                    && !evaluate_include_condition(cond, file, ctx)
3042                {
3043                    continue;
3044                }
3045                true
3046            }
3047        };
3048        let Some(inc_file) = open_include_target(&inc_path, file, ctx, included_files)? else {
3049            continue;
3050        };
3051        collect_remote_urls(&inc_file, conditional, depth + 1, ctx, urls, included_files)?;
3052    }
3053    Ok(())
3054}
3055
3056/// Fail once include nesting exceeds Git's limit, which stops runaway recursion.
3057fn check_include_depth(depth: usize) -> Result<()> {
3058    const MAX_INCLUDE_DEPTH: usize = 10;
3059    if depth > MAX_INCLUDE_DEPTH {
3060        return Err(ConfigError::IncludeDepthExceeded {
3061            depth,
3062            limit: MAX_INCLUDE_DEPTH,
3063        }
3064        .into());
3065    }
3066    Ok(())
3067}
3068
3069/// Resolve and parse the target of an include directive in `file`, recording the resolved path
3070/// in `included_files` (even when missing) so the cascade cache stamps it.
3071///
3072/// Returns `None` for a missing target or a path Git skips. Parse errors in the target are
3073/// fatal, as in Git (t0001 `re-init reads matching includeIf.onbranch`).
3074fn open_include_target(
3075    inc_path: &str,
3076    file: &ConfigFile,
3077    ctx: &IncludeContext,
3078    included_files: &mut Vec<PathBuf>,
3079) -> Result<Option<ConfigFile>> {
3080    let Some(resolved) = resolve_include_file_path(inc_path, file, ctx)? else {
3081        return Ok(None);
3082    };
3083    included_files.push(resolved.clone());
3084    ConfigFile::from_path(&resolved, file.scope)
3085}
3086
3087fn include_directive_for_entry(entry: &ConfigEntry) -> Option<(String, Option<String>)> {
3088    let val = entry.value.as_ref()?;
3089    if entry.key == "include.path" {
3090        return Some((val.clone(), None));
3091    }
3092    if entry.key.starts_with("includeif.") && entry.key.ends_with(".path") {
3093        let mid = &entry.key["includeif.".len()..entry.key.len() - ".path".len()];
3094        return Some((val.clone(), Some(mid.to_owned())));
3095    }
3096    None
3097}
3098
3099// ── Process-lifetime config cascade cache ───────────────────────────
3100//
3101// `ConfigSet::load` / `load_with_options` are called per file in hot loops
3102// (grep/diff/add re-load the cascade for every path), so the parsed cascade
3103// is memoized for the lifetime of the process. A cached entry is served only
3104// when every input that fed it is provably unchanged:
3105//
3106// - the stat stamps (mtime + size, or "absent") of every base cascade file,
3107//   recorded *before* the parse, still match. `HEAD` is stamped too so that
3108//   `includeIf.onbranch:` condition flips invalidate;
3109// - every include target the parse resolved (even ones that were missing)
3110//   still carries the stamp it had at parse time;
3111// - the config-relevant environment is byte-identical.
3112//
3113// The remaining `includeIf` condition inputs are covered transitively:
3114// `gitdir:` depends only on the cache key and environment, and
3115// `hasconfig:remote.*.url:` depends only on the (stamped) file contents —
3116// every file its URL scan opens is recorded as an include target — plus the
3117// command-line config already in the environment fingerprint.
3118//
3119// In-process writers ([`ConfigFile::write`]) additionally evict every entry
3120// whose cascade contains the written path, closing the window where a
3121// rewrite lands within one mtime tick at an unchanged size. External writers
3122// in that same window are not detectable by stat; C git parses the cascade
3123// once per process with no revalidation at all, so serving a stamped copy is
3124// strictly more conservative than upstream.
3125
3126/// Stat snapshot of one cascade file (`None` = file absent).
3127pub(crate) type ConfigFileStamp = (PathBuf, Option<(SystemTime, u64)>);
3128
3129/// Stamp metadata stored with a memoized config cascade entry.
3130pub(crate) type ConfigCacheEntryStamps = (
3131    Vec<(String, Option<String>)>,
3132    Vec<ConfigFileStamp>,
3133    Vec<ConfigFileStamp>,
3134);
3135
3136#[derive(Clone, PartialEq, Eq, Hash)]
3137pub(crate) struct ConfigCacheKey {
3138    pub(crate) git_dir: Option<PathBuf>,
3139    include_system: bool,
3140    process_includes: bool,
3141    command_includes: bool,
3142    ctx_git_dir: Option<PathBuf>,
3143    ctx_relative_include_is_error: bool,
3144}
3145
3146impl ConfigCacheKey {
3147    pub fn new(git_dir: Option<&Path>, opts: &LoadConfigOptions) -> Self {
3148        Self {
3149            git_dir: git_dir.map(Path::to_path_buf),
3150            include_system: opts.include_system,
3151            process_includes: opts.process_includes,
3152            command_includes: opts.command_includes,
3153            ctx_git_dir: opts.include_ctx.git_dir.clone(),
3154            ctx_relative_include_is_error: opts.include_ctx.command_line_relative_include_is_error,
3155        }
3156    }
3157}
3158
3159pub(crate) struct ConfigCacheEntry {
3160    pub(crate) env_fingerprint: Vec<(String, Option<String>)>,
3161    /// Stamps of the fixed cascade files (recomputable from key + env).
3162    pub(crate) base_stamps: Vec<ConfigFileStamp>,
3163    /// Stamps of the include targets this parse resolved (revalidated by
3164    /// re-statting each stored path).
3165    pub(crate) extra_stamps: Vec<ConfigFileStamp>,
3166    pub(crate) set: Arc<ConfigSet>,
3167}
3168
3169/// The on-disk files [`ConfigSet::load_with_options_uncached`] would consult,
3170/// in cascade order.
3171fn config_cascade_file_paths(
3172    env: &Environment,
3173    git_dir: Option<&Path>,
3174    opts: &LoadConfigOptions,
3175) -> Vec<PathBuf> {
3176    let mut paths = Vec::new();
3177    if opts.include_system && !git_config_nosystem_enabled(env) {
3178        paths.push(system_config_path(env));
3179    }
3180    paths.extend(global_config_paths(env));
3181    if let Some(gd) = git_dir {
3182        let common_dir = crate::repo::common_git_dir_for_config(gd);
3183        paths.push(common_dir.join("config"));
3184        // Stamped unconditionally: whether it is merged depends on
3185        // `extensions.worktreeConfig` in the (stamped) common config.
3186        paths.push(gd.join("config.worktree"));
3187        // `includeIf.onbranch:` conditions read HEAD; stamping it means a
3188        // branch switch invalidates cascades that could depend on it.
3189        paths.push(gd.join("HEAD"));
3190    }
3191    if let Some(cgd) = &opts.include_ctx.git_dir {
3192        if Some(cgd.as_path()) != git_dir {
3193            paths.push(cgd.join("HEAD"));
3194        }
3195    }
3196    if let Some(p) = env.git_config.as_deref() {
3197        paths.push(resolve_config_override_path(env, p));
3198    }
3199    paths
3200}
3201
3202pub(crate) fn stamp_for_path(path: &Path) -> Option<(SystemTime, u64)> {
3203    fs::metadata(path)
3204        .ok()
3205        .and_then(|m| Some((m.modified().ok()?, m.len())))
3206}
3207
3208pub(crate) fn stamp_paths(paths: Vec<PathBuf>) -> Vec<ConfigFileStamp> {
3209    paths
3210        .into_iter()
3211        .map(|path| {
3212            let stamp = stamp_for_path(&path);
3213            (path, stamp)
3214        })
3215        .collect()
3216}
3217
3218pub(crate) fn config_file_stamps(
3219    env: &Environment,
3220    git_dir: Option<&Path>,
3221    opts: &LoadConfigOptions,
3222) -> Vec<ConfigFileStamp> {
3223    stamp_paths(config_cascade_file_paths(env, git_dir, opts))
3224}
3225
3226pub(crate) fn config_cache_lookup(
3227    cache: &HashMap<ConfigCacheKey, ConfigCacheEntry>,
3228    key: &ConfigCacheKey,
3229    env_fp: &[(String, Option<String>)],
3230    base_stamps: &[ConfigFileStamp],
3231) -> Option<Arc<ConfigSet>> {
3232    let entry = cache.get(key)?;
3233    if entry.env_fingerprint.as_slice() != env_fp || entry.base_stamps.as_slice() != base_stamps {
3234        return None;
3235    }
3236    for (path, stamp) in &entry.extra_stamps {
3237        if stamp_for_path(path) != *stamp {
3238            return None;
3239        }
3240    }
3241    Some(Arc::clone(&entry.set))
3242}
3243
3244pub(crate) fn config_cache_store(
3245    cache: &mut HashMap<ConfigCacheKey, ConfigCacheEntry>,
3246    key: ConfigCacheKey,
3247    env_fingerprint: Vec<(String, Option<String>)>,
3248    base_stamps: Vec<ConfigFileStamp>,
3249    extra_stamps: Vec<ConfigFileStamp>,
3250    set: Arc<ConfigSet>,
3251) {
3252    cache.insert(
3253        key,
3254        ConfigCacheEntry {
3255            env_fingerprint,
3256            base_stamps,
3257            extra_stamps,
3258            set,
3259        },
3260    );
3261}
3262
3263fn git_config_nosystem_enabled(env: &Environment) -> bool {
3264    env.git_config_nosystem
3265        .as_deref()
3266        .map(|value| parse_bool(value).unwrap_or(true))
3267        .unwrap_or(false)
3268}
3269
3270/// Entries from `GIT_CONFIG_COUNT` / `GIT_CONFIG_KEY_<n>` / `GIT_CONFIG_VALUE_<n>`.
3271fn environment_config_pair_entries(env: &Environment) -> Result<Vec<ConfigEntry>> {
3272    let Some(count_str) = env.git_config_count.as_deref() else {
3273        return Ok(Vec::new());
3274    };
3275    if count_str.is_empty() {
3276        return Ok(Vec::new());
3277    }
3278
3279    let count = count_str
3280        .parse::<usize>()
3281        .ok()
3282        .filter(|&n| n <= i32::MAX as usize)
3283        .ok_or_else(|| {
3284            Error::Config(ConfigError::InvalidEnvironmentCount {
3285                value: count_str.to_owned(),
3286            })
3287        })?;
3288
3289    let mut set = ConfigSet::new();
3290    for i in 0..count {
3291        let (key, value) = env.git_config_pairs.get(i).ok_or(Error::Config(
3292            ConfigError::MissingEnvironmentKey { index: i },
3293        ))?;
3294        set.add_command_override(key, value)?;
3295    }
3296    Ok(set.entries)
3297}
3298
3299/// `GIT_CONFIG_PARAMETERS` as plain command-scope entries (no include processing); entries
3300/// with an invalid key are skipped.
3301fn command_override_entries(params: &str) -> Vec<ConfigEntry> {
3302    let mut set = ConfigSet::new();
3303    for entry in parse_config_parameters(params) {
3304        let (key, val) = entry
3305            .split_once('\u{1}')
3306            .or_else(|| entry.split_once('='))
3307            .unwrap_or((entry.as_str(), "true"));
3308        let _ = set.add_command_override(key.trim(), val);
3309    }
3310    set.entries
3311}
3312
3313// ── Type coercion helpers ───────────────────────────────────────────
3314
3315/// Parse a Git boolean value.
3316///
3317/// Accepts: `true`, `yes`, `on`, `1` as true.
3318/// Accepts: `false`, `no`, `off`, `0` as false.
3319///
3320/// Note: bare config keys are represented as `None` in [`ConfigEntry`] and
3321/// are normalized to `"true"` by higher-level readers (`ConfigSet::get`).
3322/// An explicit empty assignment (`key =` with no value) is stored as `""` and
3323/// is treated as false for `--bool` / [`parse_bool`]. Bare keys are represented
3324/// as `None` and normalized to `"true"` by callers before reaching this parser.
3325///
3326/// # Errors
3327///
3328/// [`ConfigValueError::InvalidBool`] when `s` is neither a boolean word nor an integer.
3329pub fn parse_bool(s: &str) -> std::result::Result<bool, ConfigValueError> {
3330    match s.to_lowercase().as_str() {
3331        "true" | "yes" | "on" => Ok(true),
3332        "" => Ok(false),
3333        "false" | "no" | "off" => Ok(false),
3334        _ => parse_git_config_maybe_bool(s).ok_or_else(|| ConfigValueError::InvalidBool {
3335            value: s.to_owned(),
3336        }),
3337    }
3338}
3339
3340/// Parse a Git integer value with optional `k`/`m`/`g` suffix.
3341///
3342/// # Errors
3343///
3344/// [`ConfigValueError::EmptyInteger`] for an empty value,
3345/// [`ConfigValueError::InvalidInteger`] when it is not a number, and
3346/// [`ConfigValueError::IntegerOverflow`] when the scaled value does not fit in `i64`.
3347pub fn parse_i64(s: &str) -> std::result::Result<i64, ConfigValueError> {
3348    let s = s.trim();
3349    if s.is_empty() {
3350        return Err(ConfigValueError::EmptyInteger);
3351    }
3352
3353    let (num_str, multiplier) = match s.as_bytes().last() {
3354        Some(b'k' | b'K') => (&s[..s.len() - 1], 1024_i64),
3355        Some(b'm' | b'M') => (&s[..s.len() - 1], 1024 * 1024),
3356        Some(b'g' | b'G') => (&s[..s.len() - 1], 1024 * 1024 * 1024),
3357        _ => (s, 1_i64),
3358    };
3359
3360    let base: i64 = num_str
3361        .parse()
3362        .map_err(|_| ConfigValueError::InvalidInteger {
3363            value: s.to_owned(),
3364        })?;
3365    base.checked_mul(multiplier)
3366        .ok_or_else(|| ConfigValueError::IntegerOverflow {
3367            value: s.to_owned(),
3368        })
3369}
3370
3371/// Why [`parse_git_config_int_strict`] failed (mirrors Git `errno` after `git_parse_signed`).
3372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3373#[non_exhaustive]
3374pub enum GitConfigIntStrictError {
3375    /// `EINVAL` — trailing junk, unknown unit suffix, or not a number.
3376    InvalidUnit,
3377    /// `ERANGE` — value does not fit in `i64` after scaling.
3378    OutOfRange,
3379}
3380
3381/// Parse a signed decimal integer with optional `k`/`m`/`g` multiplier suffix, requiring the
3382/// entire input (trimmed) to be consumed — same constraints as Git's `git_parse_signed` used by
3383/// `git_config_int` (so `no` and `1foo` are rejected, unlike [`parse_i64`]).
3384pub fn parse_git_config_int_strict(raw: &str) -> std::result::Result<i64, GitConfigIntStrictError> {
3385    let s = raw.trim();
3386    if s.is_empty() {
3387        return Err(GitConfigIntStrictError::InvalidUnit);
3388    }
3389
3390    let bytes = s.as_bytes();
3391    let mut idx = 0usize;
3392    if matches!(bytes.first(), Some(b'+') | Some(b'-')) {
3393        idx = 1;
3394    }
3395    if idx >= bytes.len() {
3396        return Err(GitConfigIntStrictError::InvalidUnit);
3397    }
3398    let digit_start = idx;
3399    while idx < bytes.len() && bytes[idx].is_ascii_digit() {
3400        idx += 1;
3401    }
3402    if idx == digit_start {
3403        return Err(GitConfigIntStrictError::InvalidUnit);
3404    }
3405
3406    let num_part =
3407        std::str::from_utf8(&bytes[..idx]).map_err(|_| GitConfigIntStrictError::InvalidUnit)?;
3408    let suffix =
3409        std::str::from_utf8(&bytes[idx..]).map_err(|_| GitConfigIntStrictError::InvalidUnit)?;
3410    let mult: i64 = match suffix {
3411        "" => 1,
3412        "k" | "K" => 1024,
3413        "m" | "M" => 1024 * 1024,
3414        "g" | "G" => 1024_i64
3415            .checked_mul(1024)
3416            .and_then(|x| x.checked_mul(1024))
3417            .ok_or(GitConfigIntStrictError::OutOfRange)?,
3418        _ => return Err(GitConfigIntStrictError::InvalidUnit),
3419    };
3420
3421    let val: i64 = num_part
3422        .parse()
3423        .map_err(|_| GitConfigIntStrictError::InvalidUnit)?;
3424    val.checked_mul(mult)
3425        .ok_or(GitConfigIntStrictError::OutOfRange)
3426}
3427
3428fn is_c_locale_space(b: u8) -> bool {
3429    matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c)
3430}
3431
3432fn skip_c_locale_leading_whitespace(s: &str) -> &str {
3433    let bytes = s.as_bytes();
3434    let mut i = 0usize;
3435    while i < bytes.len() && is_c_locale_space(bytes[i]) {
3436        i += 1;
3437    }
3438    &s[i..]
3439}
3440
3441fn git_unit_factor(suffix: &str) -> std::result::Result<i64, GitConfigIntStrictError> {
3442    match suffix {
3443        "" => Ok(1),
3444        "k" | "K" => Ok(1024),
3445        "m" | "M" => Ok(1024 * 1024),
3446        "g" | "G" => Ok(1024_i64 * 1024 * 1024),
3447        _ => Err(GitConfigIntStrictError::InvalidUnit),
3448    }
3449}
3450
3451/// Parse a base-0 signed integer prefix (Git `strtoimax(..., 0)`), returning unconsumed suffix.
3452fn parse_base0_signed_prefix(s: &str) -> std::result::Result<(i64, &str), GitConfigIntStrictError> {
3453    let bytes = s.as_bytes();
3454    if bytes.is_empty() {
3455        return Err(GitConfigIntStrictError::InvalidUnit);
3456    }
3457    let mut i = 0usize;
3458    let mut sign: i64 = 1;
3459    if bytes[i] == b'+' {
3460        i += 1;
3461    } else if bytes[i] == b'-' {
3462        sign = -1;
3463        i += 1;
3464    }
3465    if i >= bytes.len() {
3466        return Err(GitConfigIntStrictError::InvalidUnit);
3467    }
3468
3469    let base = if bytes[i] == b'0' {
3470        if i + 1 < bytes.len() && matches!(bytes[i + 1], b'x' | b'X') {
3471            i += 2;
3472            if i >= bytes.len() {
3473                return Err(GitConfigIntStrictError::InvalidUnit);
3474            }
3475            16
3476        } else {
3477            8
3478        }
3479    } else {
3480        10
3481    };
3482
3483    let digit_start = i;
3484    let mut acc: i128 = 0;
3485    while i < bytes.len() {
3486        let ch = char::from(bytes[i]);
3487        let digit = match base {
3488            10 => ch.to_digit(10),
3489            8 => ch.to_digit(8),
3490            16 => ch.to_digit(16),
3491            _ => None,
3492        };
3493        let Some(d) = digit else {
3494            break;
3495        };
3496        acc = acc
3497            .checked_mul(base as i128)
3498            .and_then(|v| v.checked_add(i128::from(d)))
3499            .ok_or(GitConfigIntStrictError::OutOfRange)?;
3500        i += 1;
3501    }
3502    if i == digit_start {
3503        return Err(GitConfigIntStrictError::InvalidUnit);
3504    }
3505
3506    let signed = if sign < 0 { -acc } else { acc };
3507    let val = i64::try_from(signed).map_err(|_| GitConfigIntStrictError::OutOfRange)?;
3508    Ok((val, &s[i..]))
3509}
3510
3511/// Parse a signed integer with optional `k`/`m`/`g` scaling using Git base-0 rules (`git_parse_signed`).
3512pub fn parse_git_signed_config(
3513    raw: &str,
3514    max: i64,
3515) -> std::result::Result<i64, GitConfigIntStrictError> {
3516    if max < 0 {
3517        return Err(GitConfigIntStrictError::InvalidUnit);
3518    }
3519    let s = skip_c_locale_leading_whitespace(raw);
3520    if s.is_empty() {
3521        return Err(GitConfigIntStrictError::InvalidUnit);
3522    }
3523
3524    let (val, rest) = parse_base0_signed_prefix(s)?;
3525    let factor = git_unit_factor(rest)?;
3526
3527    if val < 0 {
3528        let min = -max - 1;
3529        if min / factor > val {
3530            return Err(GitConfigIntStrictError::OutOfRange);
3531        }
3532    } else if val > 0 && max / factor < val {
3533        return Err(GitConfigIntStrictError::OutOfRange);
3534    }
3535
3536    val.checked_mul(factor)
3537        .ok_or(GitConfigIntStrictError::OutOfRange)
3538}
3539
3540/// Parse a signed 32-bit config integer (`git_parse_int`).
3541pub fn parse_git_config_int(raw: &str) -> std::result::Result<i32, GitConfigIntStrictError> {
3542    let max = i32::MAX as i64;
3543    let n = parse_git_signed_config(raw, max)?;
3544    i32::try_from(n).map_err(|_| GitConfigIntStrictError::OutOfRange)
3545}
3546
3547/// Parse Git `git_parse_maybe_bool`: `Some(true/false)` or `None` if unrecognized.
3548pub fn parse_git_config_maybe_bool(raw: &str) -> Option<bool> {
3549    if raw.is_empty() {
3550        return Some(false);
3551    }
3552    let lower = raw.to_ascii_lowercase();
3553    match lower.as_str() {
3554        "true" | "yes" | "on" => Some(true),
3555        "false" | "no" | "off" => Some(false),
3556        _ => parse_git_config_int(raw).ok().map(|n| n != 0),
3557    }
3558}
3559
3560const DIFF_CONTEXT_KEY: &str = "diff.context";
3561
3562/// Git's documented default for `gc.auto`.
3563const DEFAULT_GC_AUTO_THRESHOLD: usize = 6700;
3564/// Git's documented default for `gc.autoPackLimit`.
3565const DEFAULT_GC_AUTO_PACK_LIMIT: usize = 50;
3566
3567fn bad_numeric_diff_context(
3568    value: &str,
3569    err: GitConfigIntStrictError,
3570    entry: &ConfigEntry,
3571) -> ConfigError {
3572    let reason = match err {
3573        GitConfigIntStrictError::InvalidUnit => crate::error::BadNumericSource::InvalidUnit,
3574        GitConfigIntStrictError::OutOfRange => crate::error::BadNumericSource::OutOfRange,
3575    };
3576    if entry.scope == ConfigScope::Command || entry.file.is_none() {
3577        ConfigError::BadNumericValue {
3578            key: DIFF_CONTEXT_KEY.to_owned(),
3579            value: value.to_owned(),
3580            reason,
3581        }
3582    } else {
3583        let path = entry
3584            .file
3585            .as_deref()
3586            .map(config_error_path_display)
3587            .unwrap_or_default();
3588        ConfigError::BadNumericValueInFile {
3589            key: DIFF_CONTEXT_KEY.to_owned(),
3590            value: value.to_owned(),
3591            file: path,
3592            reason,
3593        }
3594    }
3595}
3596
3597fn bad_diff_context_variable(entry: &ConfigEntry) -> ConfigError {
3598    if entry.scope == ConfigScope::Command || entry.file.is_none() {
3599        ConfigError::UnableToParseFromCommandLine {
3600            key: DIFF_CONTEXT_KEY.to_owned(),
3601        }
3602    } else {
3603        let path = entry
3604            .file
3605            .as_deref()
3606            .map(config_error_path_display)
3607            .unwrap_or_default();
3608        ConfigError::BadConfigVariableAtLine {
3609            key: DIFF_CONTEXT_KEY.to_owned(),
3610            file: path,
3611            line: entry.line,
3612        }
3613    }
3614}
3615
3616/// Read `diff.context` from a loaded [`ConfigSet`] with Git-compatible validation.
3617///
3618/// Returns `Ok(None)` when the key is unset. When set, the value must be a non-negative integer
3619/// acceptable to Git's diff machinery (same rules as `git diff` / `git log -p`).
3620pub fn resolve_diff_context_lines(cfg: &ConfigSet) -> Result<Option<usize>> {
3621    let Some(entry) = cfg.get_last_entry(DIFF_CONTEXT_KEY) else {
3622        return Ok(None);
3623    };
3624    let value_src = entry.value.as_deref().unwrap_or("").trim();
3625    match parse_git_config_int_strict(value_src) {
3626        Ok(n) if n < 0 => Err(bad_diff_context_variable(&entry).into()),
3627        Ok(n) => Ok(Some(usize::try_from(n).map_err(|_| {
3628            bad_numeric_diff_context(value_src, GitConfigIntStrictError::OutOfRange, &entry)
3629        })?)),
3630        Err(e) => Err(bad_numeric_diff_context(value_src, e, &entry).into()),
3631    }
3632}
3633
3634/// Parse a Git color value and return the ANSI escape sequence.
3635///
3636/// Matches Git's `color_parse_mem` (`git/color.c`): whitespace-separated words,
3637/// optional leading `reset`, up to two color tokens (foreground then background),
3638/// then graphic rendition attributes. Attribute codes are accumulated as a
3639/// bitmask keyed by SGR number (so `bold` sets bit 1, `nobold` sets bit 22).
3640///
3641/// # Errors
3642///
3643/// [`ConfigValueError::InvalidColor`] when a word is neither a color nor an attribute, more
3644/// than two colors are given, or nothing usable is left.
3645pub fn parse_color(s: &str) -> std::result::Result<String, ConfigValueError> {
3646    const COLOR_BACKGROUND_OFFSET: i32 = 10;
3647    const COLOR_FOREGROUND_ANSI: i32 = 30;
3648    const COLOR_FOREGROUND_RGB: i32 = 38;
3649    const COLOR_FOREGROUND_256: i32 = 38;
3650    const COLOR_FOREGROUND_BRIGHT_ANSI: i32 = 90;
3651
3652    #[derive(Clone, Copy, Default)]
3653    struct Color {
3654        kind: u8,
3655        value: u8,
3656        red: u8,
3657        green: u8,
3658        blue: u8,
3659    }
3660
3661    const COLOR_UNSPECIFIED: u8 = 0;
3662    const COLOR_NORMAL: u8 = 1;
3663    const COLOR_ANSI: u8 = 2;
3664    const COLOR_256: u8 = 3;
3665    const COLOR_RGB: u8 = 4;
3666
3667    fn color_empty(c: &Color) -> bool {
3668        c.kind == COLOR_UNSPECIFIED || c.kind == COLOR_NORMAL
3669    }
3670
3671    fn parse_ansi_color(name: &str) -> Option<Color> {
3672        let color_names = [
3673            "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white",
3674        ];
3675        let color_offset = COLOR_FOREGROUND_ANSI;
3676
3677        if name.eq_ignore_ascii_case("default") {
3678            return Some(Color {
3679                kind: COLOR_ANSI,
3680                value: (9 + color_offset) as u8,
3681                ..Default::default()
3682            });
3683        }
3684
3685        let (name, color_offset) = if name.len() >= 6 && name[..6].eq_ignore_ascii_case("bright") {
3686            (&name[6..], COLOR_FOREGROUND_BRIGHT_ANSI)
3687        } else {
3688            (name, COLOR_FOREGROUND_ANSI)
3689        };
3690
3691        for (i, cn) in color_names.iter().enumerate() {
3692            if name.eq_ignore_ascii_case(cn) {
3693                return Some(Color {
3694                    kind: COLOR_ANSI,
3695                    value: (i as i32 + color_offset) as u8,
3696                    ..Default::default()
3697                });
3698            }
3699        }
3700        None
3701    }
3702
3703    fn hex_val(b: u8) -> Option<u8> {
3704        match b {
3705            b'0'..=b'9' => Some(b - b'0'),
3706            b'a'..=b'f' => Some(b - b'a' + 10),
3707            b'A'..=b'F' => Some(b - b'A' + 10),
3708            _ => None,
3709        }
3710    }
3711
3712    fn get_hex_color(chars: &[u8], width: usize) -> Option<(u8, usize)> {
3713        assert!(width == 1 || width == 2);
3714        if chars.len() < width {
3715            return None;
3716        }
3717        let v = if width == 2 {
3718            let hi = hex_val(chars[0])?;
3719            let lo = hex_val(chars[1])?;
3720            (hi << 4) | lo
3721        } else {
3722            let n = hex_val(chars[0])?;
3723            (n << 4) | n
3724        };
3725        Some((v, width))
3726    }
3727
3728    fn parse_single_color(word: &str) -> Option<Color> {
3729        if word.eq_ignore_ascii_case("normal") {
3730            return Some(Color {
3731                kind: COLOR_NORMAL,
3732                ..Default::default()
3733            });
3734        }
3735
3736        let bytes = word.as_bytes();
3737        if (bytes.len() == 7 || bytes.len() == 4) && bytes.first() == Some(&b'#') {
3738            let width = if bytes.len() == 7 { 2 } else { 1 };
3739            let mut idx = 1;
3740            let (r, n1) = get_hex_color(&bytes[idx..], width)?;
3741            idx += n1;
3742            let (g, n2) = get_hex_color(&bytes[idx..], width)?;
3743            idx += n2;
3744            let (b, n3) = get_hex_color(&bytes[idx..], width)?;
3745            idx += n3;
3746            if idx != bytes.len() {
3747                return None;
3748            }
3749            return Some(Color {
3750                kind: COLOR_RGB,
3751                red: r,
3752                green: g,
3753                blue: b,
3754                ..Default::default()
3755            });
3756        }
3757
3758        if let Some(c) = parse_ansi_color(word) {
3759            return Some(c);
3760        }
3761
3762        let Ok(val) = word.parse::<i64>() else {
3763            return None;
3764        };
3765        if val < -1 {
3766            return None;
3767        }
3768        if val < 0 {
3769            return Some(Color {
3770                kind: COLOR_NORMAL,
3771                ..Default::default()
3772            });
3773        }
3774        if val < 8 {
3775            return Some(Color {
3776                kind: COLOR_ANSI,
3777                value: (val as i32 + COLOR_FOREGROUND_ANSI) as u8,
3778                ..Default::default()
3779            });
3780        }
3781        if val < 16 {
3782            return Some(Color {
3783                kind: COLOR_ANSI,
3784                value: (val as i32 - 8 + COLOR_FOREGROUND_BRIGHT_ANSI) as u8,
3785                ..Default::default()
3786            });
3787        }
3788        if val < 256 {
3789            return Some(Color {
3790                kind: COLOR_256,
3791                value: val as u8,
3792                ..Default::default()
3793            });
3794        }
3795        None
3796    }
3797
3798    fn parse_attr(word: &str) -> Option<u8> {
3799        const ATTRS: [(&str, u8, u8); 8] = [
3800            ("bold", 1, 22),
3801            ("dim", 2, 22),
3802            ("italic", 3, 23),
3803            ("ul", 4, 24),
3804            ("underline", 4, 24),
3805            ("blink", 5, 25),
3806            ("reverse", 7, 27),
3807            ("strike", 9, 29),
3808        ];
3809
3810        let mut negate = false;
3811        let mut rest = word;
3812        if let Some(stripped) = rest.strip_prefix("no") {
3813            negate = true;
3814            rest = stripped;
3815            if let Some(s) = rest.strip_prefix('-') {
3816                rest = s;
3817            }
3818        }
3819
3820        for (name, val, neg) in ATTRS {
3821            if rest == name {
3822                return Some(if negate { neg } else { val });
3823            }
3824        }
3825        None
3826    }
3827
3828    fn append_color_output(out: &mut String, c: &Color, background: bool) {
3829        let offset = if background {
3830            COLOR_BACKGROUND_OFFSET
3831        } else {
3832            0
3833        };
3834        match c.kind {
3835            COLOR_UNSPECIFIED | COLOR_NORMAL => {}
3836            COLOR_ANSI => {
3837                use std::fmt::Write;
3838                let _ = write!(out, "{}", i32::from(c.value) + offset);
3839            }
3840            COLOR_256 => {
3841                use std::fmt::Write;
3842                let _ = write!(out, "{};5;{}", COLOR_FOREGROUND_256 + offset, c.value);
3843            }
3844            COLOR_RGB => {
3845                use std::fmt::Write;
3846                let _ = write!(
3847                    out,
3848                    "{};2;{};{};{}",
3849                    COLOR_FOREGROUND_RGB + offset,
3850                    c.red,
3851                    c.green,
3852                    c.blue
3853                );
3854            }
3855            _ => {}
3856        }
3857    }
3858
3859    let s = s.trim();
3860    let bad_color = || ConfigValueError::InvalidColor {
3861        value: s.to_owned(),
3862    };
3863    if s.is_empty() {
3864        return Ok(String::new());
3865    }
3866
3867    let mut has_reset = false;
3868    let mut attr: u64 = 0;
3869    let mut fg = Color::default();
3870    let mut bg = Color::default();
3871    fg.kind = COLOR_UNSPECIFIED;
3872    bg.kind = COLOR_UNSPECIFIED;
3873
3874    for word in s.split_whitespace() {
3875        if word.eq_ignore_ascii_case("reset") {
3876            has_reset = true;
3877            continue;
3878        }
3879
3880        if let Some(c) = parse_single_color(word) {
3881            if fg.kind == COLOR_UNSPECIFIED {
3882                fg = c;
3883                continue;
3884            }
3885            if bg.kind == COLOR_UNSPECIFIED {
3886                bg = c;
3887                continue;
3888            }
3889            return Err(bad_color());
3890        }
3891
3892        if let Some(code) = parse_attr(word) {
3893            attr |= 1u64 << u64::from(code);
3894            continue;
3895        }
3896
3897        return Err(bad_color());
3898    }
3899
3900    if !has_reset && attr == 0 && color_empty(&fg) && color_empty(&bg) {
3901        return Err(bad_color());
3902    }
3903
3904    let mut out = String::from("\x1b[");
3905    let mut sep = if has_reset { 1u32 } else { 0u32 };
3906
3907    let mut attr_bits = attr;
3908    let mut i = 0u32;
3909    while attr_bits != 0 {
3910        let bit = 1u64 << i;
3911        if attr_bits & bit == 0 {
3912            i += 1;
3913            continue;
3914        }
3915        attr_bits &= !bit;
3916        if sep > 0 {
3917            out.push(';');
3918        }
3919        sep += 1;
3920        use std::fmt::Write;
3921        let _ = write!(out, "{i}");
3922        i += 1;
3923    }
3924
3925    if !color_empty(&fg) {
3926        if sep > 0 {
3927            out.push(';');
3928        }
3929        sep += 1;
3930        append_color_output(&mut out, &fg, false);
3931    }
3932    if !color_empty(&bg) {
3933        if sep > 0 {
3934            out.push(';');
3935        }
3936        append_color_output(&mut out, &bg, true);
3937    }
3938    out.push('m');
3939    Ok(out)
3940}
3941
3942#[derive(Debug, Clone)]
3943struct UrlParts {
3944    scheme: String,
3945    user: Option<String>,
3946    host: String,
3947    port: Option<String>,
3948    path: String,
3949}
3950
3951#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3952struct UrlMatchScore {
3953    host_len: usize,
3954    path_len: usize,
3955    user_matched: bool,
3956}
3957
3958fn parse_config_url(url: &str) -> Option<UrlParts> {
3959    let (scheme, rest) = url.split_once("://")?;
3960    let (authority, path) = match rest.find('/') {
3961        Some(idx) => (&rest[..idx], &rest[idx..]),
3962        None => (rest, "/"),
3963    };
3964    let (user, host_port) = match authority.rsplit_once('@') {
3965        Some((user, host)) => (Some(user.to_owned()), host),
3966        None => (None, authority),
3967    };
3968    let (host, port) = match host_port.rsplit_once(':') {
3969        Some((host, port)) if !host.contains(']') => (host, Some(port.to_owned())),
3970        _ => (host_port, None),
3971    };
3972    Some(UrlParts {
3973        scheme: scheme.to_lowercase(),
3974        user,
3975        host: host.to_lowercase(),
3976        port,
3977        path: if path.is_empty() {
3978            "/".to_owned()
3979        } else {
3980            path.trim_end_matches('/').to_owned()
3981        },
3982    })
3983}
3984
3985fn host_matches(pattern: &str, target: &str) -> bool {
3986    let pattern_parts: Vec<&str> = pattern.split('.').collect();
3987    let target_parts: Vec<&str> = target.split('.').collect();
3988    pattern_parts.len() == target_parts.len()
3989        && pattern_parts
3990            .iter()
3991            .zip(target_parts)
3992            .all(|(pattern, target)| *pattern == "*" || *pattern == target)
3993}
3994
3995fn path_match_len(pattern: &str, target: &str) -> Option<usize> {
3996    let pattern = if pattern.is_empty() { "/" } else { pattern };
3997    let target = if target.is_empty() { "/" } else { target };
3998    if pattern == "/" {
3999        return Some(1);
4000    }
4001    let pattern = pattern.trim_end_matches('/');
4002    if target == pattern
4003        || target
4004            .strip_prefix(pattern)
4005            .is_some_and(|rest| rest.starts_with('/'))
4006    {
4007        Some(pattern.len() + 1)
4008    } else {
4009        None
4010    }
4011}
4012
4013fn url_match_score(pattern_url: &str, target_url: &str) -> Option<UrlMatchScore> {
4014    let pattern = parse_config_url(pattern_url)?;
4015    let target = parse_config_url(target_url)?;
4016    if pattern.scheme != target.scheme {
4017        return None;
4018    }
4019    let user_matched = match pattern.user.as_deref() {
4020        Some(user) if target.user.as_deref() == Some(user) => true,
4021        Some(_) => return None,
4022        None => false,
4023    };
4024    if !host_matches(&pattern.host, &target.host) || pattern.port != target.port {
4025        return None;
4026    }
4027    let path_len = path_match_len(&pattern.path, &target.path)?;
4028    Some(UrlMatchScore {
4029        host_len: pattern.host.len(),
4030        path_len,
4031        user_matched,
4032    })
4033}
4034
4035/// Match a URL against a URL pattern from config.
4036pub fn url_matches(pattern_url: &str, target_url: &str) -> bool {
4037    url_match_score(pattern_url, target_url).is_some()
4038}
4039
4040/// Get the best URL match for a specific key.
4041pub fn get_urlmatch_entries<'a>(
4042    entries: &'a [ConfigEntry],
4043    section: &str,
4044    variable: &str,
4045    url: &str,
4046) -> Vec<&'a ConfigEntry> {
4047    let section_lower = section.to_lowercase();
4048    let variable_lower = variable.to_lowercase();
4049    let mut matches: Vec<(UrlMatchScore, &'a ConfigEntry)> = Vec::new();
4050
4051    for entry in entries {
4052        let key = &entry.key;
4053        let first_dot = match key.find('.') {
4054            Some(i) => i,
4055            None => continue,
4056        };
4057        let last_dot = match key.rfind('.') {
4058            Some(i) => i,
4059            None => continue,
4060        };
4061        let entry_section = &key[..first_dot];
4062        let entry_variable = &key[last_dot + 1..];
4063        if entry_section.to_lowercase() != section_lower
4064            || entry_variable.to_lowercase() != variable_lower
4065        {
4066            continue;
4067        }
4068        if first_dot == last_dot {
4069            matches.push((
4070                UrlMatchScore {
4071                    host_len: 0,
4072                    path_len: 0,
4073                    user_matched: false,
4074                },
4075                entry,
4076            ));
4077        } else {
4078            let subsection = &key[first_dot + 1..last_dot];
4079            if let Some(score) = url_match_score(subsection, url) {
4080                matches.push((score, entry));
4081            }
4082        }
4083    }
4084    matches.sort_by_key(|a| a.0);
4085    matches.into_iter().map(|(_, e)| e).collect()
4086}
4087
4088/// Get all matching variables in a section for a given URL.
4089pub fn get_urlmatch_all_in_section(
4090    entries: &[ConfigEntry],
4091    section: &str,
4092    url: &str,
4093) -> Vec<(String, String, ConfigScope)> {
4094    let section_lower = section.to_lowercase();
4095    let mut matches: Vec<(String, UrlMatchScore, String, String, ConfigScope)> = Vec::new();
4096
4097    for entry in entries {
4098        let key = &entry.key;
4099        let first_dot = match key.find('.') {
4100            Some(i) => i,
4101            None => continue,
4102        };
4103        let last_dot = match key.rfind('.') {
4104            Some(i) => i,
4105            None => continue,
4106        };
4107        let entry_section = &key[..first_dot];
4108        if entry_section.to_lowercase() != section_lower {
4109            continue;
4110        }
4111        let entry_variable = &key[last_dot + 1..];
4112        let val = entry.value.as_deref().unwrap_or("");
4113        if first_dot == last_dot {
4114            let canonical = format!("{}.{}", section_lower, entry_variable);
4115            matches.push((
4116                entry_variable.to_lowercase(),
4117                UrlMatchScore {
4118                    host_len: 0,
4119                    path_len: 0,
4120                    user_matched: false,
4121                },
4122                val.to_owned(),
4123                canonical,
4124                entry.scope,
4125            ));
4126        } else {
4127            let subsection = &key[first_dot + 1..last_dot];
4128            if let Some(score) = url_match_score(subsection, url) {
4129                let canonical = format!("{}.{}", section_lower, entry_variable);
4130                matches.push((
4131                    entry_variable.to_lowercase(),
4132                    score,
4133                    val.to_owned(),
4134                    canonical,
4135                    entry.scope,
4136                ));
4137            }
4138        }
4139    }
4140
4141    let mut best: std::collections::BTreeMap<String, (UrlMatchScore, String, String, ConfigScope)> =
4142        std::collections::BTreeMap::new();
4143    for (var, specificity, val, canonical, scope) in matches {
4144        let entry = best.entry(var).or_insert((
4145            UrlMatchScore {
4146                host_len: 0,
4147                path_len: 0,
4148                user_matched: false,
4149            },
4150            String::new(),
4151            String::new(),
4152            scope,
4153        ));
4154        if specificity >= entry.0 {
4155            *entry = (specificity, val, canonical, scope);
4156        }
4157    }
4158    best.into_values()
4159        .map(|(_, val, canonical, scope)| (canonical, val, scope))
4160        .collect()
4161}
4162
4163/// Parse a Git path value (expand `~/` to home directory).
4164/// Parse a path value. Returns the resolved path string.
4165/// Does NOT handle :(optional) prefix — use `parse_path_optional` for that.
4166pub fn parse_path(env: &Environment, s: &str) -> String {
4167    if let Some(rest) = s.strip_prefix("~/") {
4168        if let Some(home) = home_dir(env) {
4169            return home.join(rest).to_string_lossy().to_string();
4170        }
4171    }
4172    s.to_owned()
4173}
4174
4175/// Parse a path value that may have an `:(optional)` prefix.
4176///
4177/// Returns `Some(path)` if the path should be used, `None` if the path
4178/// is optional and does not exist (meaning the entry should be skipped).
4179pub fn parse_path_optional(env: &Environment, s: &str) -> Option<String> {
4180    if let Some(rest) = s.strip_prefix(":(optional)") {
4181        let resolved = parse_path(env, rest);
4182        if std::path::Path::new(&resolved).exists() {
4183            Some(resolved)
4184        } else {
4185            None // optional and missing → skip
4186        }
4187    } else {
4188        Some(parse_path(env, s))
4189    }
4190}
4191
4192// ── Helpers ─────────────────────────────────────────────────────────
4193
4194/// Parse `GIT_CONFIG_PARAMETERS` payloads.
4195///
4196/// We support the common formats seen in tests and wrappers:
4197/// - single-quoted entries: `'key=value'`
4198/// - double-quoted entries: `"key=value"`
4199/// - unquoted `key=value` tokens separated by whitespace
4200///
4201/// Backslash escapes are interpreted minimally inside double quotes.
4202///
4203/// Return the last `key=value` assignment for `key` in a `GIT_CONFIG_PARAMETERS` payload.
4204///
4205/// Matches Git's command-line config layering: later tokens win. Keys are canonicalized the same
4206/// way as file-backed config (`fetch.output` and `FETCH.Output` both match `fetch.output`).
4207#[must_use]
4208pub fn git_config_parameters_last_value(raw: &str, key: &str) -> Option<String> {
4209    let Ok(canon) = canonical_key(key) else {
4210        return None;
4211    };
4212    let mut last: Option<String> = None;
4213    for entry in parse_config_parameters_strict(raw).ok()? {
4214        match entry {
4215            ConfigParameter::Pair { key, value } => {
4216                if canonical_key(key.trim()).ok().as_ref() == Some(&canon) {
4217                    last = Some(value.unwrap_or_else(|| "true".to_owned()));
4218                }
4219            }
4220            ConfigParameter::OldStyle(entry) => {
4221                if let Some((k, v)) = entry.split_once('=') {
4222                    if canonical_key(k.trim()).ok().as_ref() == Some(&canon) {
4223                        last = Some(v.to_owned());
4224                    }
4225                } else if canonical_key(entry.trim()).ok().as_ref() == Some(&canon) {
4226                    last = Some("true".to_owned());
4227                }
4228            }
4229        }
4230    }
4231    last
4232}
4233
4234#[derive(Debug, Clone, PartialEq, Eq)]
4235enum ConfigParameter {
4236    OldStyle(String),
4237    Pair { key: String, value: Option<String> },
4238}
4239
4240/// Parse `GIT_CONFIG_PARAMETERS` / `-c key=value` style parameter strings.
4241///
4242/// Returns Git's internal NUL-delimited representation used when bootstrapping config.
4243pub fn parse_config_parameters(raw: &str) -> Vec<String> {
4244    parse_config_parameters_strict(raw)
4245        .map(|entries| {
4246            entries
4247                .into_iter()
4248                .map(|entry| match entry {
4249                    ConfigParameter::OldStyle(entry) => entry,
4250                    ConfigParameter::Pair {
4251                        key,
4252                        value: Some(value),
4253                    } => format!("{key}\u{1}{value}"),
4254                    ConfigParameter::Pair { key, value: None } => format!("{key}\u{1}"),
4255                })
4256                .collect()
4257        })
4258        .unwrap_or_default()
4259}
4260
4261fn parse_config_parameters_strict(raw: &str) -> Result<Vec<ConfigParameter>> {
4262    let mut out: Vec<ConfigParameter> = Vec::new();
4263    let chars: Vec<char> = raw.chars().collect();
4264    let mut idx = skip_config_parameter_spaces(&chars, 0);
4265
4266    while idx < chars.len() {
4267        let (key, next) = sq_dequote_step_chars(&chars, idx)?;
4268        let Some(next_idx) = next else {
4269            out.push(ConfigParameter::OldStyle(key));
4270            break;
4271        };
4272
4273        if chars[next_idx].is_whitespace() {
4274            out.push(ConfigParameter::OldStyle(key));
4275            idx = skip_config_parameter_spaces(&chars, next_idx);
4276            continue;
4277        }
4278
4279        if chars[next_idx] != '=' {
4280            return Err(Error::Config(ConfigError::MalformedConfigParameters));
4281        }
4282
4283        let value_start = next_idx + 1;
4284        if value_start >= chars.len() || chars[value_start].is_whitespace() {
4285            out.push(ConfigParameter::Pair { key, value: None });
4286            idx = skip_config_parameter_spaces(&chars, value_start);
4287            continue;
4288        }
4289
4290        if chars[value_start] != '\'' {
4291            return Err(Error::Config(ConfigError::MalformedConfigParameters));
4292        }
4293        let (value, value_next) = sq_dequote_step_chars(&chars, value_start)?;
4294        if let Some(value_next) = value_next {
4295            if !chars[value_next].is_whitespace() {
4296                return Err(Error::Config(ConfigError::MalformedConfigParameters));
4297            }
4298            idx = skip_config_parameter_spaces(&chars, value_next);
4299        } else {
4300            idx = chars.len();
4301        }
4302        out.push(ConfigParameter::Pair {
4303            key,
4304            value: Some(value),
4305        });
4306    }
4307
4308    Ok(out)
4309}
4310
4311fn skip_config_parameter_spaces(chars: &[char], mut idx: usize) -> usize {
4312    while idx < chars.len() && chars[idx].is_whitespace() {
4313        idx += 1;
4314    }
4315    idx
4316}
4317
4318fn sq_dequote_step_chars(chars: &[char], start: usize) -> Result<(String, Option<usize>)> {
4319    if chars.get(start) != Some(&'\'') {
4320        return Err(Error::Config(ConfigError::MalformedConfigParameters));
4321    }
4322
4323    let mut out = String::new();
4324    let mut idx = start + 1;
4325    loop {
4326        let Some(&ch) = chars.get(idx) else {
4327            return Err(Error::Config(ConfigError::MalformedConfigParameters));
4328        };
4329        if ch != '\'' {
4330            out.push(ch);
4331            idx += 1;
4332            continue;
4333        }
4334
4335        idx += 1;
4336        match chars.get(idx).copied() {
4337            None => return Ok((out, None)),
4338            Some('\\')
4339                if chars
4340                    .get(idx + 1)
4341                    .copied()
4342                    .is_some_and(needs_sq_backslash_quote)
4343                    && chars.get(idx + 2) == Some(&'\'') =>
4344            {
4345                if let Some(escaped) = chars.get(idx + 1) {
4346                    out.push(*escaped);
4347                }
4348                idx += 3;
4349            }
4350            _ => return Ok((out, Some(idx))),
4351        }
4352    }
4353}
4354
4355fn needs_sq_backslash_quote(ch: char) -> bool {
4356    ch == '\'' || ch == '!'
4357}
4358
4359/// Resolve a config file path from `GIT_CONFIG*` overrides relative to [`Environment::cwd`].
4360pub(crate) fn resolve_config_override_path(env: &Environment, path: &str) -> PathBuf {
4361    let p = Path::new(path);
4362    if p.is_absolute() {
4363        p.to_path_buf()
4364    } else {
4365        env.cwd.join(p)
4366    }
4367}
4368
4369/// Return candidate paths for the global config file, in priority order.
4370/// Public accessor for the ordered list of global config file paths.
4371pub fn global_config_paths_pub(env: &Environment) -> Vec<PathBuf> {
4372    global_config_paths(env)
4373}
4374
4375fn global_config_paths(env: &Environment) -> Vec<PathBuf> {
4376    let mut paths = Vec::new();
4377
4378    // $GIT_CONFIG_GLOBAL overrides
4379    if let Some(p) = env.git_config_global.as_deref() {
4380        paths.push(resolve_config_override_path(env, p));
4381        return paths;
4382    }
4383
4384    // Git order: XDG `git/config` first, then `~/.gitconfig` (see `git_global_config_paths`).
4385    if let Some(xdg) = env.xdg_config_home.as_deref() {
4386        paths.push(PathBuf::from(xdg).join("git/config"));
4387    } else if let Some(home) = home_dir(env) {
4388        paths.push(home.join(".config/git/config"));
4389    }
4390    if let Some(home) = home_dir(env) {
4391        paths.push(home.join(".gitconfig"));
4392    }
4393
4394    paths
4395}
4396
4397/// Path to the system-wide Git configuration file.
4398///
4399/// Honors `GIT_CONFIG_SYSTEM`. On Windows, falls back to Git for Windows'
4400/// `etc/gitconfig` when `/etc/gitconfig` is absent (stock shells, not MSYS).
4401#[must_use]
4402pub fn system_config_path(env: &Environment) -> PathBuf {
4403    if let Some(p) = env.git_config_system.as_deref() {
4404        return resolve_config_override_path(env, p);
4405    }
4406    let unix_default = PathBuf::from("/etc/gitconfig");
4407    #[cfg(windows)]
4408    {
4409        if unix_default.is_file() {
4410            return unix_default;
4411        }
4412        if let Some(root) = env.git_install_root.as_ref() {
4413            let candidate = PathBuf::from(root).join("etc").join("gitconfig");
4414            if candidate.is_file() {
4415                return candidate;
4416            }
4417        }
4418        for pf in [
4419            env.program_files.as_deref(),
4420            env.program_files_x86.as_deref(),
4421        ]
4422        .into_iter()
4423        .flatten()
4424        {
4425            let candidate = PathBuf::from(pf).join("Git").join("etc").join("gitconfig");
4426            if candidate.is_file() {
4427                return candidate;
4428            }
4429        }
4430    }
4431    unix_default
4432}
4433
4434/// Return the user's home directory.
4435///
4436/// `$HOME` is honored on every platform. On Windows, where `$HOME` is usually
4437/// unset outside a Git-for-Windows/MSYS shell, we fall back to the same sources
4438/// Git does: `%HOMEDRIVE%%HOMEPATH%`, then `%USERPROFILE%`. Without this, global
4439/// config (`~/.gitconfig`) would be invisible on a stock Windows shell.
4440fn home_dir(env: &Environment) -> Option<PathBuf> {
4441    if let Some(home) = env.home.as_ref().filter(|h| !h.is_empty()) {
4442        return Some(PathBuf::from(home));
4443    }
4444    #[cfg(windows)]
4445    {
4446        if let (Some(drive), Some(path)) = (
4447            env.homedrive.as_ref().filter(|d| !d.is_empty()),
4448            env.homepath.as_ref().filter(|p| !p.is_empty()),
4449        ) {
4450            let mut combined = drive.clone();
4451            combined.push(path);
4452            return Some(PathBuf::from(combined));
4453        }
4454        if let Some(profile) = env.userprofile.as_ref().filter(|p| !p.is_empty()) {
4455            return Some(PathBuf::from(profile));
4456        }
4457    }
4458    None
4459}
4460
4461/// True when Git would treat the config source as `CONFIG_ORIGIN_FILE` for includes.
4462fn include_source_is_disk_file(file: &ConfigFile) -> bool {
4463    file.include_origin == ConfigIncludeOrigin::Disk
4464}
4465
4466/// Resolve an include file path (Git `handle_path_include` semantics).
4467///
4468/// Relative paths are only allowed when the including config came from a real on-disk file.
4469/// Returns `None` for a relative include from command-line config when the context allows
4470/// skipping it.
4471fn resolve_include_file_path(
4472    path: &str,
4473    file: &ConfigFile,
4474    ctx: &IncludeContext,
4475) -> Result<Option<PathBuf>> {
4476    let expanded = parse_path(ctx.env.as_ref(), path);
4477    let p = Path::new(&expanded);
4478    if p.is_absolute() {
4479        return Ok(Some(p.to_path_buf()));
4480    }
4481    if !include_source_is_disk_file(file) {
4482        if file.include_origin == ConfigIncludeOrigin::CommandLine
4483            && !ctx.command_line_relative_include_is_error
4484        {
4485            return Ok(None);
4486        }
4487        return Err(Error::Config(ConfigError::RelativeIncludeOutsideFile));
4488    }
4489    let base = match file.path.parent() {
4490        Some(p) if !p.as_os_str().is_empty() => p,
4491        Some(_) | None => Path::new("."),
4492    };
4493    Ok(Some(base.join(p)))
4494}
4495
4496fn is_dir_sep(b: u8) -> bool {
4497    b == b'/' || b == b'\\'
4498}
4499
4500fn add_trailing_starstar_for_dir(pat: &mut String) {
4501    let bytes = pat.as_bytes();
4502    if bytes.last().is_some_and(|&b| is_dir_sep(b)) {
4503        pat.push_str("**");
4504    }
4505}
4506
4507/// Prepare a `gitdir:` / `gitdir/i:` pattern (Git `prepare_include_condition_pattern`).
4508///
4509/// Returns `None` when a relative (`./`) pattern cannot be anchored: the config did not come
4510/// from a file on disk, or its directory cannot be resolved.
4511fn prepare_gitdir_pattern(
4512    condition: &str,
4513    file: &ConfigFile,
4514    ctx: &IncludeContext,
4515) -> Option<(String, usize)> {
4516    // Git `interpolate_path`: expand `~/` in the condition before pattern rules.
4517    let mut pat = parse_path(ctx.env.as_ref(), condition);
4518    if pat.starts_with("./") || pat.starts_with(".\\") {
4519        let parent = file
4520            .path
4521            .parent()
4522            .filter(|_| include_source_is_disk_file(file))?;
4523        let real = parent.canonicalize_simplified().ok()?;
4524        let mut dir = real.to_string_lossy().into_owned();
4525        if !dir.ends_with('/') && !dir.ends_with('\\') {
4526            dir.push('/');
4527        }
4528        let rest = &pat[2..];
4529        pat = format!("{dir}{rest}");
4530        let prefix_len = dir.len();
4531        add_trailing_starstar_for_dir(&mut pat);
4532        return Some((pat, prefix_len));
4533    }
4534    let p = Path::new(&pat);
4535    if !p.is_absolute() {
4536        pat.insert_str(0, "**/");
4537    }
4538    add_trailing_starstar_for_dir(&mut pat);
4539    Some((pat, 0))
4540}
4541
4542/// Git `include_by_gitdir` tries `strbuf_realpath` first, then `strbuf_add_absolute_path` if no match.
4543///
4544/// `text_abs` uses `$PWD` (which preserves symlinks) when available, matching Git's
4545/// `strbuf_add_absolute_path` behaviour. This lets `gitdir:bar/` match when `bar` is a symlink.
4546fn git_dir_match_texts(ctx: &IncludeContext, git_dir: &Path) -> (String, String) {
4547    let real = git_dir
4548        .canonicalize_simplified()
4549        .map(|p| p.to_string_lossy().into_owned())
4550        .unwrap_or_else(|_| git_dir.to_string_lossy().into_owned());
4551    // Build the non-canonical absolute path using $PWD (symlink-preserving) when available.
4552    // Git C uses `strbuf_add_absolute_path` which prefers $PWD over getcwd() to preserve symlinks.
4553    let abs = if git_dir.is_absolute() {
4554        // If git_dir is already canonical, try to reconstruct the symlink-preserving variant
4555        // by replacing the canonical cwd prefix with $PWD.
4556        let pwd_abs = ctx.pwd.as_deref().and_then(|pwd| {
4557            let pwd_path = std::path::Path::new(pwd);
4558            if !pwd_path.is_absolute() {
4559                return None;
4560            }
4561            let pwd_canon = pwd_path.canonicalize_simplified().ok()?;
4562            let git_dir_str = git_dir.to_string_lossy();
4563            let pwd_canon_str = pwd_canon.to_string_lossy();
4564            // If git_dir starts with the canonical cwd, replace that prefix with $PWD
4565            let suffix = git_dir_str.strip_prefix(pwd_canon_str.as_ref())?;
4566            Some(format!("{pwd}{suffix}"))
4567        });
4568        pwd_abs.unwrap_or_else(|| git_dir.to_string_lossy().into_owned())
4569    } else {
4570        ctx.cwd.join(git_dir).to_string_lossy().into_owned()
4571    };
4572    (real, abs)
4573}
4574
4575fn include_by_gitdir(
4576    condition: &str,
4577    file: &ConfigFile,
4578    ctx: &IncludeContext,
4579    icase: bool,
4580) -> bool {
4581    let Some(git_dir) = ctx.git_dir.as_ref() else {
4582        return false;
4583    };
4584    let Some((pattern, prefix)) = prepare_gitdir_pattern(condition, file, ctx) else {
4585        return false;
4586    };
4587    let flags = WM_PATHNAME | if icase { WM_CASEFOLD } else { 0 };
4588    let (text_real, text_abs) = git_dir_match_texts(ctx, git_dir);
4589    let try_match = |text: &str| -> bool {
4590        let t = text.as_bytes();
4591        let p = pattern.as_bytes();
4592        if prefix > 0 {
4593            if t.len() < prefix {
4594                return false;
4595            }
4596            let pre = &p[..prefix];
4597            let te = &t[..prefix];
4598            let ok = if icase {
4599                pre.eq_ignore_ascii_case(te)
4600            } else {
4601                pre == te
4602            };
4603            if !ok {
4604                return false;
4605            }
4606            return wildmatch(&p[prefix..], &t[prefix..], flags);
4607        }
4608        wildmatch(p, t, flags)
4609    };
4610    if try_match(&text_real) {
4611        return true;
4612    }
4613    text_real != text_abs && try_match(&text_abs)
4614}
4615
4616fn current_branch_short_name(git_dir: Option<&Path>) -> Option<String> {
4617    let gd = git_dir?;
4618    let target = refs::read_symbolic_ref(gd, "HEAD").ok()??;
4619    let rest = target.strip_prefix("refs/heads/")?;
4620    Some(rest.to_owned())
4621}
4622
4623fn include_by_onbranch(condition: &str, ctx: &IncludeContext) -> bool {
4624    let Some(short) = current_branch_short_name(ctx.git_dir.as_deref()) else {
4625        return false;
4626    };
4627    let mut pattern = condition.to_owned();
4628    add_trailing_starstar_for_dir(&mut pattern);
4629    wildmatch(pattern.as_bytes(), short.as_bytes(), WM_PATHNAME)
4630}
4631
4632/// Whether `entry` is `remote.<name>.url` (keys are canonical: section and variable lowercase).
4633fn is_remote_url_entry(entry: &ConfigEntry) -> bool {
4634    entry
4635        .key
4636        .strip_prefix("remote.")
4637        .is_some_and(|rest| rest.ends_with(".url"))
4638}
4639
4640/// The URL glob of a `hasconfig:remote.*.url:<glob>` include condition.
4641fn hasconfig_remote_url_pattern(condition: &str) -> Option<&str> {
4642    condition.strip_prefix("hasconfig:remote.*.url:")
4643}
4644
4645/// Evaluate an `[includeIf]` condition.
4646///
4647/// Supports `gitdir:`, `gitdir/i:` and `onbranch:` like Git. `hasconfig:remote.*.url:` needs
4648/// the whole load's remote URLs and is evaluated by [`RemoteUrls::any_matches`]. Unknown
4649/// prefixes are false.
4650fn evaluate_include_condition(condition: &str, file: &ConfigFile, ctx: &IncludeContext) -> bool {
4651    if let Some(rest) = condition.strip_prefix("gitdir/i:") {
4652        return include_by_gitdir(rest, file, ctx, true);
4653    }
4654    if let Some(rest) = condition.strip_prefix("gitdir:") {
4655        return include_by_gitdir(rest, file, ctx, false);
4656    }
4657    if let Some(rest) = condition.strip_prefix("onbranch:") {
4658        return include_by_onbranch(rest, ctx);
4659    }
4660    false
4661}
4662
4663/// Split a canonical key into (section, subsection, variable).
4664fn split_key(key: &str) -> Result<(String, Option<String>, String)> {
4665    let (Some(first_dot), Some(last_dot)) = (key.find('.'), key.rfind('.')) else {
4666        return Err(Error::Config(ConfigError::InvalidKey {
4667            key: key.to_owned(),
4668            reason: InvalidKeyReason::MissingSection,
4669        }));
4670    };
4671
4672    let section = key[..first_dot].to_owned();
4673    let variable = key[last_dot + 1..].to_owned();
4674
4675    let subsection = if first_dot == last_dot {
4676        None
4677    } else {
4678        Some(key[first_dot + 1..last_dot].to_owned())
4679    };
4680
4681    Ok((section, subsection, variable))
4682}
4683
4684/// Parse a section name that may contain a subsection (e.g. `"remote.origin"`).
4685///
4686/// Returns (section, subsection).
4687fn parse_section_name(name: &str) -> (&str, Option<&str>) {
4688    match name.find('.') {
4689        Some(i) => (&name[..i], Some(&name[i + 1..])),
4690        None => (name, None),
4691    }
4692}
4693
4694fn section_matches(parser: &Parser, section_lower: &str, subsection: Option<&str>) -> bool {
4695    if parser.section.to_lowercase() == section_lower && parser.subsection.as_deref() == subsection
4696    {
4697        return true;
4698    }
4699    let Some(subsection) = subsection else {
4700        return false;
4701    };
4702    parser.subsection.is_none()
4703        && parser.section.to_lowercase() == format!("{section_lower}.{}", subsection.to_lowercase())
4704}
4705
4706/// Path to the lock file Git uses when updating a config file (`config.lock`).
4707#[must_use]
4708pub fn config_lock_path(path: &Path) -> PathBuf {
4709    let file_name = path
4710        .file_name()
4711        .and_then(|s| s.to_str())
4712        .unwrap_or("config");
4713    path.with_file_name(format!("{file_name}.lock"))
4714}
4715
4716/// Reject a section name whose section part is not ASCII letters, digits and `-`, or whose
4717/// subsection is present but empty. `name` is the caller's full input, kept for the error.
4718fn validate_section_name(name: &str, section: &str, subsection: Option<&str>) -> Result<()> {
4719    if section.is_empty()
4720        || !section
4721            .chars()
4722            .all(|ch| ch.is_ascii_alphanumeric() || ch == '-')
4723        || subsection.is_some_and(str::is_empty)
4724    {
4725        return Err(Error::Config(ConfigError::InvalidSectionName {
4726            section: name.to_owned(),
4727        }));
4728    }
4729    Ok(())
4730}
4731
4732/// Extract the original-case variable name from a raw (user-typed) key.
4733///
4734/// E.g. `"Section.Movie"` → `"Movie"`, `"a.b.CamelCase"` → `"CamelCase"`.
4735fn raw_variable_name(raw_key: &str) -> &str {
4736    match raw_key.rfind('.') {
4737        Some(i) => &raw_key[i + 1..],
4738        None => raw_key,
4739    }
4740}
4741
4742/// Extract the original-case section and subsection from a raw (user-typed) key.
4743///
4744/// E.g. `"Section.key"` → `("Section", None)`,
4745///      `"Remote.origin.url"` → `("Remote", Some("origin"))`.
4746fn raw_section_parts(raw_key: &str) -> (String, Option<String>) {
4747    let first_dot = match raw_key.find('.') {
4748        Some(i) => i,
4749        None => return (raw_key.to_owned(), None),
4750    };
4751    // rfind always succeeds here since we already found at least one dot above.
4752    let last_dot = match raw_key.rfind('.') {
4753        Some(i) => i,
4754        None => return (raw_key[..first_dot].to_owned(), None),
4755    };
4756    let section = raw_key[..first_dot].to_owned();
4757    if first_dot == last_dot {
4758        (section, None)
4759    } else {
4760        let subsection = raw_key[first_dot + 1..last_dot].to_owned();
4761        (section, Some(subsection))
4762    }
4763}
4764
4765/// Check if a raw line is a section header that also contains an inline key=value.
4766fn is_section_header_with_inline_entry(line: &str) -> bool {
4767    let trimmed = line.trim();
4768    if !trimmed.starts_with('[') {
4769        return false;
4770    }
4771    let end = match trimmed.find(']') {
4772        Some(i) => i,
4773        None => return false,
4774    };
4775    let after = trimmed[end + 1..].trim();
4776    // Has non-comment content after the ]
4777    !after.is_empty() && !after.starts_with('#') && !after.starts_with(';')
4778}
4779
4780/// Extract just the section header portion (up to and including `]` and any
4781/// comment after it, but not any inline key=value) from a raw line.
4782fn extract_section_header(line: &str) -> String {
4783    let trimmed = line.trim();
4784    let end = match trimmed.find(']') {
4785        Some(i) => i,
4786        None => return line.to_owned(),
4787    };
4788    // Preserve any comment on the section header itself (between ] and key),
4789    // but git doesn't really do this. Just return up to ].
4790    trimmed[..=end].to_owned()
4791}
4792
4793#[cfg(test)]
4794mod pack_object_config_tests {
4795    use super::{ConfigFile, ConfigScope, ConfigSet};
4796    use std::path::Path;
4797
4798    fn set_from_snippet(text: &str) -> ConfigSet {
4799        let path = Path::new(".git/config");
4800        let file = ConfigFile::parse(path, text, ConfigScope::Local).expect("parse config snippet");
4801        let mut set = ConfigSet::new();
4802        set.merge(&file);
4803        set
4804    }
4805
4806    #[test]
4807    fn pack_object_window_and_depth_defaults() {
4808        let set = ConfigSet::new();
4809        assert_eq!(set.pack_object_window(), 10);
4810        assert_eq!(set.pack_object_depth(), crate::pack::DEFAULT_PACK_DEPTH);
4811    }
4812
4813    #[test]
4814    fn pack_object_window_and_depth_preserve_explicit_zero() {
4815        let set = set_from_snippet("[pack]\n\twindow = 0\n\tdepth = 0\n");
4816        assert_eq!(set.pack_object_window(), 0);
4817        assert_eq!(set.pack_object_depth(), 0);
4818    }
4819
4820    #[test]
4821    fn gc_auto_limits_from_config() {
4822        let set = set_from_snippet("[gc]\n\tauto = 100\n\tautoPackLimit = 3\n");
4823        assert_eq!(set.gc_auto_threshold(), Some(100));
4824        assert_eq!(set.gc_auto_pack_limit(), Some(3));
4825        let defaults = ConfigSet::new();
4826        assert_eq!(defaults.gc_auto_threshold(), Some(6700));
4827        assert_eq!(defaults.gc_auto_pack_limit(), Some(50));
4828        assert!(defaults.gc_auto_detach());
4829        assert!(defaults.maintenance_auto());
4830        let disabled = set_from_snippet("[gc]\n\tautoPackLimit = 0\n");
4831        assert_eq!(disabled.gc_auto_pack_limit(), None);
4832        assert_eq!(disabled.gc_auto_threshold(), Some(6700));
4833        let auto_off = set_from_snippet("[gc]\n\tauto = 0\n");
4834        assert_eq!(auto_off.gc_auto_threshold(), None);
4835        let negative = set_from_snippet("[gc]\n\tauto = -1\n\tautoPackLimit = -1\n");
4836        assert_eq!(negative.gc_auto_threshold(), None);
4837        assert_eq!(negative.gc_auto_pack_limit(), None);
4838        let unparsable = set_from_snippet("[gc]\n\tauto = lots\n");
4839        assert_eq!(unparsable.gc_auto_threshold(), Some(6700));
4840        let foreground =
4841            set_from_snippet("[gc]\n\tautoDetach = false\n[maintenance]\n\tauto = false\n");
4842        assert!(!foreground.gc_auto_detach());
4843        assert!(!foreground.maintenance_auto());
4844    }
4845}
4846
4847#[cfg(test)]
4848mod value_error_tests {
4849    use super::{parse_bool, parse_color, parse_i64, ConfigFile, ConfigScope, ConfigSet};
4850    use crate::error::{ConfigError, ConfigValueError, Error};
4851    use std::path::Path;
4852
4853    fn set_from_snippet(text: &str) -> ConfigSet {
4854        let file = ConfigFile::parse(Path::new(".git/config"), text, ConfigScope::Local)
4855            .expect("parse config snippet");
4856        let mut set = ConfigSet::new();
4857        set.merge(&file);
4858        set
4859    }
4860
4861    #[test]
4862    fn parse_bool_rejects_non_boolean_with_the_value() {
4863        assert_eq!(
4864            parse_bool("maybe"),
4865            Err(ConfigValueError::InvalidBool {
4866                value: "maybe".to_owned()
4867            })
4868        );
4869        assert_eq!(parse_bool("2"), Ok(true));
4870        assert_eq!(parse_bool(""), Ok(false));
4871    }
4872
4873    #[test]
4874    fn parse_i64_distinguishes_empty_invalid_and_overflow() {
4875        assert_eq!(parse_i64("  "), Err(ConfigValueError::EmptyInteger));
4876        assert_eq!(
4877            parse_i64(" 12x "),
4878            Err(ConfigValueError::InvalidInteger {
4879                value: "12x".to_owned()
4880            })
4881        );
4882        assert_eq!(
4883            parse_i64("9223372036854775807k"),
4884            Err(ConfigValueError::IntegerOverflow {
4885                value: "9223372036854775807k".to_owned()
4886            })
4887        );
4888        assert_eq!(parse_i64("2m"), Ok(2 * 1024 * 1024));
4889    }
4890
4891    #[test]
4892    fn parse_color_reports_the_trimmed_value() {
4893        let bad = ConfigValueError::InvalidColor {
4894            value: "red green blue".to_owned(),
4895        };
4896        assert_eq!(parse_color(" red green blue "), Err(bad));
4897        assert_eq!(
4898            parse_color("nonsense").map_err(|e| e.to_string()),
4899            Err("bad color value 'nonsense'".to_owned())
4900        );
4901        assert_eq!(parse_color("  "), Ok(String::new()));
4902    }
4903
4904    #[test]
4905    fn get_bool_and_get_i64_name_the_key() {
4906        let set = set_from_snippet("[core]\n\tbare = sometimes\n[pack]\n\tthreads = many\n");
4907        let bool_err = set.get_bool("core.bare").unwrap_err();
4908        assert_eq!(
4909            bool_err,
4910            ConfigError::InvalidValue {
4911                key: "core.bare".to_owned(),
4912                source: ConfigValueError::InvalidBool {
4913                    value: "sometimes".to_owned()
4914                },
4915            }
4916        );
4917        assert_eq!(
4918            bool_err.to_string(),
4919            "bad boolean config value 'sometimes' for 'core.bare'"
4920        );
4921        let int_err = set.get_i64("pack.threads").unwrap_err();
4922        assert!(matches!(
4923            &int_err,
4924            ConfigError::InvalidValue { key, source: ConfigValueError::InvalidInteger { value } }
4925                if key == "pack.threads" && value == "many"
4926        ));
4927        assert!(matches!(Error::from(int_err), Error::Config(_)));
4928        assert_eq!(set.get_bool("core.missing").unwrap(), None);
4929    }
4930
4931    #[test]
4932    fn typed_readers_match_any_casing_of_the_key() {
4933        let set = set_from_snippet(
4934            "[CORE]\n\tQUOTEPATH = false\n[pack]\n\twritebitmaphashcache = false\n\tREADREVERSEINDEX = false\n",
4935        );
4936        assert!(!set.quote_path_fully());
4937        assert!(!set.pack_write_bitmap_hash_cache());
4938        assert!(!set.pack_read_reverse_index_default());
4939        assert_eq!(set.get_bool("Core.QuotePath").unwrap(), Some(false));
4940    }
4941
4942    #[test]
4943    fn bool_or_uses_the_default_only_when_unset_or_invalid() {
4944        let set = set_from_snippet(
4945            "[core]\n\tbare = sometimes\n\tlogAllRefUpdates\n[feature]\n\tmanyFiles = off\n",
4946        );
4947        for default in [false, true] {
4948            assert_eq!(set.bool_with_default("core.missing", default), default);
4949            assert_eq!(set.bool_with_default("core.bare", default), default);
4950            assert!(set.bool_with_default("core.logallrefupdates", default));
4951            assert!(!set.bool_with_default("FEATURE.MANYFILES", default));
4952        }
4953    }
4954
4955    #[test]
4956    fn core_bool_accessors_use_git_defaults() {
4957        let unset = set_from_snippet("");
4958        assert!(!unset.ignore_case());
4959        assert!(!unset.precompose_unicode());
4960        assert!(unset.preload_index());
4961        assert!(unset.file_mode());
4962
4963        let flipped = set_from_snippet(
4964            "[core]\n\tignorecase = true\n\tprecomposeunicode = yes\n\tpreloadindex = 0\n\tfilemode = off\n",
4965        );
4966        assert!(flipped.ignore_case());
4967        assert!(flipped.precompose_unicode());
4968        assert!(!flipped.preload_index());
4969        assert!(!flipped.file_mode());
4970
4971        let invalid = set_from_snippet(
4972            "[core]\n\tignoreCase = maybe\n\tprecomposeUnicode = maybe\n\tpreloadIndex = maybe\n\tfileMode = maybe\n",
4973        );
4974        assert!(!invalid.ignore_case());
4975        assert!(!invalid.precompose_unicode());
4976        assert!(invalid.preload_index());
4977        assert!(invalid.file_mode());
4978    }
4979
4980    #[test]
4981    fn for_key_keeps_the_source_error() {
4982        let err = ConfigValueError::EmptyInteger.for_key("gc.auto");
4983        assert_eq!(err.to_string(), "empty integer value for 'gc.auto'");
4984        let source = std::error::Error::source(&err).map(ToString::to_string);
4985        assert_eq!(source.as_deref(), Some("empty integer value"));
4986    }
4987}
4988
4989#[cfg(test)]
4990mod get_regexp_tests {
4991    use super::{ConfigFile, ConfigScope, ConfigSet};
4992    use std::path::Path;
4993
4994    fn set_from_snippet(text: &str) -> ConfigSet {
4995        let path = Path::new(".git/config");
4996        let file = ConfigFile::parse(path, text, ConfigScope::Local).expect("parse config snippet");
4997        let mut set = ConfigSet::new();
4998        set.merge(&file);
4999        set
5000    }
5001
5002    #[test]
5003    fn get_regexp_matches_section_prefix_like_git_config() {
5004        let text = r#"
5005[user]
5006    email = alice@example.com
5007    name = Alice
5008[core]
5009    bare = false
5010"#;
5011        let set = set_from_snippet(text);
5012        let keys: Vec<_> = set
5013            .get_regexp("user")
5014            .expect("valid pattern")
5015            .into_iter()
5016            .map(|e| e.key.as_str())
5017            .collect();
5018        assert!(keys.contains(&"user.email"));
5019        assert!(keys.contains(&"user.name"));
5020        assert!(!keys.iter().any(|k| k.starts_with("core.")));
5021    }
5022
5023    #[test]
5024    fn get_regexp_returns_all_multi_value_entries_in_order() {
5025        let text = r#"
5026[remote "origin"]
5027    url = https://example.com/repo.git
5028    fetch = +refs/heads/*:refs/remotes/origin/*
5029    push = +refs/heads/main:refs/heads/main
5030    push = +refs/heads/develop:refs/heads/develop
5031"#;
5032        let set = set_from_snippet(text);
5033        let matches = set.get_regexp("remote.origin").expect("valid pattern");
5034        let push_vals: Vec<_> = matches
5035            .iter()
5036            .filter(|e| e.key == "remote.origin.push")
5037            .map(|e| e.value.as_deref().unwrap_or(""))
5038            .collect();
5039        assert_eq!(push_vals.len(), 2);
5040        assert_eq!(push_vals[0], "+refs/heads/main:refs/heads/main");
5041        assert_eq!(push_vals[1], "+refs/heads/develop:refs/heads/develop");
5042    }
5043
5044    #[test]
5045    fn get_regexp_dot_matches_any_key() {
5046        let text = r#"
5047[a]
5048    x = 1
5049[b]
5050    y = 2
5051"#;
5052        let set = set_from_snippet(text);
5053        let m = set.get_regexp(".").expect("valid pattern");
5054        assert_eq!(m.len(), 2);
5055    }
5056
5057    #[test]
5058    fn get_regexp_no_match_returns_empty_vec() {
5059        let set = set_from_snippet("[user]\n\tname = x\n");
5060        let m = set.get_regexp("zzz").expect("valid pattern");
5061        assert!(m.is_empty());
5062    }
5063
5064    #[test]
5065    fn get_regexp_invalid_pattern_is_error() {
5066        use crate::error::ConfigError;
5067
5068        let set = set_from_snippet("[user]\n\tname = x\n");
5069        let err = set.get_regexp("(").expect_err("unclosed group");
5070        assert!(
5071            matches!(err, ConfigError::InvalidPattern { .. }),
5072            "got: {err:?}"
5073        );
5074    }
5075
5076    #[test]
5077    fn valueless_negotiation_algorithm_is_a_typed_config_error() {
5078        use crate::error::{ConfigError, Error};
5079
5080        let path = Path::new("/repo/.git/config");
5081        for (text, line) in [
5082            (
5083                "[core]\n\tbare = false\n[fetch]\n\tnegotiationAlgorithm\n",
5084                4,
5085            ),
5086            ("[fetch] negotiationAlgorithm\n", 1),
5087        ] {
5088            let err = ConfigFile::parse(path, text, ConfigScope::Local).expect_err(text);
5089            let Error::Config(config_err) = err else {
5090                panic!("expected a config error for {text:?}, got {err:?}");
5091            };
5092            assert_eq!(
5093                config_err,
5094                ConfigError::BadConfigVariable {
5095                    key: "fetch.negotiationalgorithm".to_owned(),
5096                    file: ".git/config".to_owned(),
5097                    line,
5098                },
5099                "{text:?}"
5100            );
5101        }
5102
5103        let ok = ConfigFile::parse(
5104            path,
5105            "[fetch]\n\tnegotiationAlgorithm = skipping\n",
5106            ConfigScope::Local,
5107        )
5108        .expect("valued key parses");
5109        assert_eq!(ok.entries[0].value.as_deref(), Some("skipping"));
5110    }
5111}
5112
5113#[cfg(test)]
5114mod loose_compression_tests {
5115    use std::path::Path;
5116
5117    use super::{ConfigFile, ConfigScope, ConfigSet, Error};
5118
5119    fn set_from_snippet(text: &str) -> ConfigSet {
5120        let path = Path::new(".git/config");
5121        let file = ConfigFile::parse(path, text, ConfigScope::Local).expect("parse config snippet");
5122        let mut set = ConfigSet::new();
5123        set.merge(&file);
5124        set
5125    }
5126
5127    #[test]
5128    fn big_file_threshold_default_suffixes_and_errors() {
5129        assert_eq!(
5130            ConfigSet::new().big_file_threshold().unwrap(),
5131            512 * 1024 * 1024
5132        );
5133        let cases = [
5134            ("1000", 1000),
5135            ("0", 0),
5136            ("4k", 4096),
5137            ("2m", 2 * 1024 * 1024),
5138            ("1g", 1024 * 1024 * 1024),
5139            ("8G", 8 * 1024 * 1024 * 1024),
5140        ];
5141        for (raw, want) in cases {
5142            let set = set_from_snippet(&format!("[core]\n\tbigFileThreshold = {raw}\n"));
5143            assert_eq!(set.big_file_threshold().unwrap(), want, "value {raw}");
5144        }
5145        let set = set_from_snippet("[core]\n\tbigfilethreshold = 1k\n\tbigFileThreshold = 3k\n");
5146        assert_eq!(set.big_file_threshold().unwrap(), 3 * 1024);
5147
5148        for raw in ["-1", "12x", "lots", ""] {
5149            let snippet = if raw.is_empty() {
5150                "[core]\n\tbigFileThreshold\n".to_owned()
5151            } else {
5152                format!("[core]\n\tbigFileThreshold = {raw}\n")
5153            };
5154            let err = set_from_snippet(&snippet).big_file_threshold().unwrap_err();
5155            assert!(
5156                matches!(
5157                    err,
5158                    Error::Config(super::ConfigError::BadNumericValue { ref key, .. })
5159                        if key == "core.bigfilethreshold"
5160                ),
5161                "value {raw:?}: {err:?}"
5162            );
5163        }
5164    }
5165
5166    #[test]
5167    fn loose_compression_cascade() {
5168        let set = ConfigSet::new();
5169        assert_eq!(
5170            set.loose_objects_zlib_level().unwrap(),
5171            ConfigSet::LOOSE_OBJECTS_ZLIB_DEFAULT
5172        );
5173
5174        let set = set_from_snippet("[core]\n\tcompression = 0\n");
5175        assert_eq!(set.loose_objects_zlib_level().unwrap(), 0);
5176
5177        let set = set_from_snippet("[core]\n\tcompression = 9\n");
5178        assert_eq!(set.loose_objects_zlib_level().unwrap(), 9);
5179
5180        let set = set_from_snippet("[core]\n\tcompression = 0\n\tloosecompression = 9\n");
5181        assert_eq!(set.loose_objects_zlib_level().unwrap(), 9);
5182
5183        let set = set_from_snippet("[core]\n\tloosecompression = 3\n");
5184        assert_eq!(set.loose_objects_zlib_level().unwrap(), 3);
5185
5186        let set = set_from_snippet("[core]\n\tcompression = -1\n");
5187        assert_eq!(set.loose_objects_zlib_level().unwrap(), 6);
5188
5189        for level in 0..=9 {
5190            let set = set_from_snippet(&format!("[core]\n\tloosecompression = {level}\n"));
5191            assert_eq!(set.loose_objects_zlib_level().unwrap(), level);
5192        }
5193
5194        let set = set_from_snippet("[core]\n\tloosecompression = -1\n");
5195        assert_eq!(set.loose_objects_zlib_level().unwrap(), 6);
5196
5197        let err = set_from_snippet("[core]\n\tloosecompression = 10\n")
5198            .loose_objects_zlib_level()
5199            .unwrap_err();
5200        assert!(matches!(err, Error::Config(_)));
5201
5202        let err = set_from_snippet("[core]\n\tloosecompression = not-a-number\n")
5203            .loose_objects_zlib_level()
5204            .unwrap_err();
5205        assert!(matches!(err, Error::Config(_)));
5206
5207        let err = set_from_snippet("[core]\n\tcompression = 42\n")
5208            .loose_objects_zlib_level()
5209            .unwrap_err();
5210        assert!(matches!(err, Error::Config(_)));
5211
5212        let err = set_from_snippet("[core]\n\tcompression = nope\n\tloosecompression = 1\n")
5213            .loose_objects_zlib_level()
5214            .unwrap_err();
5215        assert!(matches!(err, Error::Config(_)));
5216
5217        let err = set_from_snippet("[core]\n\tloosecompression = nope\n\tloosecompression = 1\n")
5218            .loose_objects_zlib_level()
5219            .unwrap_err();
5220        assert!(matches!(err, Error::Config(_)));
5221
5222        let set = set_from_snippet("[core]\n\tloosecompression = 1\n\tcompression = 9\n");
5223        assert_eq!(set.loose_objects_zlib_level().unwrap(), 1);
5224
5225        let err = set_from_snippet("[core]\n\tloosecompression\n")
5226            .loose_objects_zlib_level()
5227            .unwrap_err();
5228        assert!(matches!(err, Error::Config(_)));
5229    }
5230}
5231
5232#[cfg(test)]
5233mod pack_compression_tests {
5234    use super::{ConfigFile, ConfigScope, ConfigSet};
5235    use std::path::Path;
5236
5237    fn set_from_snippet(text: &str) -> ConfigSet {
5238        let path = Path::new(".git/config");
5239        let file = ConfigFile::parse(path, text, ConfigScope::Local).expect("parse config snippet");
5240        let mut set = ConfigSet::new();
5241        set.merge(&file);
5242        set
5243    }
5244
5245    #[test]
5246    fn pack_objects_zlib_level_defaults_to_six() {
5247        let set = ConfigSet::new();
5248        assert_eq!(set.pack_objects_zlib_level().unwrap(), 6);
5249    }
5250
5251    #[test]
5252    fn pack_objects_zlib_level_core_compression() {
5253        let set = set_from_snippet("[core]\n\tcompression = 0\n");
5254        assert_eq!(set.pack_objects_zlib_level().unwrap(), 0);
5255        let set = set_from_snippet("[core]\n\tcompression = 9\n");
5256        assert_eq!(set.pack_objects_zlib_level().unwrap(), 9);
5257    }
5258
5259    #[test]
5260    fn pack_objects_zlib_level_pack_overrides_core() {
5261        let set = set_from_snippet("[core]\n\tcompression = 9\n[pack]\n\tcompression = 0\n");
5262        assert_eq!(set.pack_objects_zlib_level().unwrap(), 0);
5263        let set = set_from_snippet("[core]\n\tcompression = 0\n[pack]\n\tcompression = 9\n");
5264        assert_eq!(set.pack_objects_zlib_level().unwrap(), 9);
5265    }
5266
5267    #[test]
5268    fn pack_objects_zlib_level_later_core_does_not_override_earlier_pack() {
5269        let mut set = ConfigSet::new();
5270        set.merge(
5271            &ConfigFile::parse(
5272                Path::new("a"),
5273                "[pack]\n\tcompression = 9\n",
5274                ConfigScope::Local,
5275            )
5276            .unwrap(),
5277        );
5278        set.merge(
5279            &ConfigFile::parse(
5280                Path::new("b"),
5281                "[core]\n\tcompression = 0\n",
5282                ConfigScope::Local,
5283            )
5284            .unwrap(),
5285        );
5286        assert_eq!(set.pack_objects_zlib_level().unwrap(), 9);
5287    }
5288
5289    #[test]
5290    fn pack_objects_zlib_level_loosecompression_does_not_block_core_pack_level() {
5291        let set = set_from_snippet("[core]\n\tloosecompression = 1\n\tcompression = 0\n");
5292        assert_eq!(set.pack_objects_zlib_level().unwrap(), 0);
5293    }
5294
5295    #[test]
5296    fn pack_objects_zlib_level_pack_wins_after_loose_and_core() {
5297        let set = set_from_snippet(
5298            "[core]\n\tloosecompression = 1\n\tcompression = 0\n[pack]\n\tcompression = 9\n",
5299        );
5300        assert_eq!(set.pack_objects_zlib_level().unwrap(), 9);
5301    }
5302}
5303
5304#[cfg(test)]
5305mod config_cache_tests {
5306    use super::*;
5307    use filetime::FileTime;
5308
5309    fn local_opts(git_dir: &Path) -> LoadConfigOptions {
5310        LoadConfigOptions {
5311            include_system: false,
5312            include_ctx: IncludeContext {
5313                git_dir: Some(git_dir.to_path_buf()),
5314                ..Default::default()
5315            },
5316            ..Default::default()
5317        }
5318    }
5319
5320    fn load_value(caches: &crate::repo_caches::RepoCaches, git_dir: &Path) -> Option<String> {
5321        let opts = local_opts(git_dir);
5322        let set = caches
5323            .load_config_with_options(&Environment::empty(), Some(git_dir), &opts)
5324            .expect("load cascade");
5325        set.value("gritcachetest.value")
5326    }
5327
5328    fn mtime_of(path: &Path) -> FileTime {
5329        FileTime::from_last_modification_time(&fs::metadata(path).expect("stat config"))
5330    }
5331
5332    fn restore_mtime(path: &Path, stamp: FileTime) {
5333        filetime::set_file_mtime(path, stamp).expect("restore mtime");
5334    }
5335
5336    #[test]
5337    fn cache_serves_same_stamp_and_config_write_evicts() {
5338        let caches =
5339            crate::repo_caches::RepoCaches::new(crate::command_runner::system_command_runner());
5340        let td = tempfile::tempdir().expect("tempdir");
5341        let gd = td.path();
5342        let cfg = gd.join("config");
5343        fs::write(&cfg, "[gritcachetest]\n\tvalue = aaa\n").expect("write v1");
5344        let t0 = mtime_of(&cfg);
5345        assert_eq!(load_value(&caches, gd).as_deref(), Some("aaa"));
5346
5347        // Same size + restored mtime: indistinguishable by stat, so the cache
5348        // serves the old parse. (This is the window explicit eviction closes
5349        // for in-process writers; C git would not re-read at all.)
5350        fs::write(&cfg, "[gritcachetest]\n\tvalue = bbb\n").expect("write v2");
5351        restore_mtime(&cfg, t0);
5352        assert_eq!(load_value(&caches, gd).as_deref(), Some("aaa"));
5353
5354        // An in-process `ConfigFile::write` plus eviction sees new content even with identical stamps.
5355        let mut file = ConfigFile::from_path(&cfg, ConfigScope::Local)
5356            .expect("read config")
5357            .expect("config exists");
5358        file.set("gritcachetest.value", "ccc").expect("set value");
5359        file.write().expect("persist");
5360        caches.evict_config_for_path(&cfg);
5361        restore_mtime(&cfg, t0);
5362        assert_eq!(load_value(&caches, gd).as_deref(), Some("ccc"));
5363    }
5364
5365    #[test]
5366    fn cache_invalidates_on_size_or_existence_change() {
5367        let caches =
5368            crate::repo_caches::RepoCaches::new(crate::command_runner::system_command_runner());
5369        let td = tempfile::tempdir().expect("tempdir");
5370        let gd = td.path();
5371        let cfg = gd.join("config");
5372        // Absent local config is cached as "absent"...
5373        assert_eq!(load_value(&caches, gd), None);
5374        // ...and creating the file is a stamp change (None -> Some).
5375        fs::write(&cfg, "[gritcachetest]\n\tvalue = first\n").expect("create");
5376        assert_eq!(load_value(&caches, gd).as_deref(), Some("first"));
5377        // A size change invalidates even with a restored mtime.
5378        let t0 = mtime_of(&cfg);
5379        fs::write(&cfg, "[gritcachetest]\n\tvalue = second-longer\n").expect("rewrite");
5380        restore_mtime(&cfg, t0);
5381        assert_eq!(load_value(&caches, gd).as_deref(), Some("second-longer"));
5382    }
5383
5384    #[test]
5385    fn include_targets_are_stamped_and_invalidate() {
5386        let caches =
5387            crate::repo_caches::RepoCaches::new(crate::command_runner::system_command_runner());
5388        let td = tempfile::tempdir().expect("tempdir");
5389        let gd = td.path();
5390        fs::write(gd.join("config"), "[include]\n\tpath = extra.conf\n").expect("write parent");
5391        let inc = gd.join("extra.conf");
5392        fs::write(&inc, "[gritcachetest]\n\tvalue = one\n").expect("write include v1");
5393        assert_eq!(load_value(&caches, gd).as_deref(), Some("one"));
5394
5395        // Same-size + restored-mtime rewrite of only the included file: the
5396        // parse result is served from cache (proving the include target is
5397        // stamped rather than re-read)...
5398        let t0 = mtime_of(&inc);
5399        fs::write(&inc, "[gritcachetest]\n\tvalue = two\n").expect("write include v2");
5400        restore_mtime(&inc, t0);
5401        assert_eq!(load_value(&caches, gd).as_deref(), Some("one"));
5402
5403        // ...while a stat-visible change to the included file invalidates.
5404        fs::write(&inc, "[gritcachetest]\n\tvalue = two-longer\n").expect("write include v3");
5405        assert_eq!(load_value(&caches, gd).as_deref(), Some("two-longer"));
5406    }
5407
5408    #[test]
5409    fn missing_include_target_is_watched() {
5410        let caches =
5411            crate::repo_caches::RepoCaches::new(crate::command_runner::system_command_runner());
5412        let td = tempfile::tempdir().expect("tempdir");
5413        let gd = td.path();
5414        fs::write(gd.join("config"), "[include]\n\tpath = extra.conf\n").expect("write parent");
5415        assert_eq!(load_value(&caches, gd), None);
5416
5417        // The resolved-but-missing target was stamped as absent; creating it
5418        // must invalidate the cached parse.
5419        fs::write(gd.join("extra.conf"), "[gritcachetest]\n\tvalue = born\n").expect("create");
5420        assert_eq!(load_value(&caches, gd).as_deref(), Some("born"));
5421    }
5422
5423    #[test]
5424    fn onbranch_condition_follows_head() {
5425        let caches =
5426            crate::repo_caches::RepoCaches::new(crate::command_runner::system_command_runner());
5427        let td = tempfile::tempdir().expect("tempdir");
5428        let gd = td.path();
5429        fs::write(gd.join("HEAD"), "ref: refs/heads/main\n").expect("write HEAD");
5430        fs::write(
5431            gd.join("config"),
5432            "[includeIf \"onbranch:main\"]\n\tpath = branch.conf\n",
5433        )
5434        .expect("write config");
5435        fs::write(
5436            gd.join("branch.conf"),
5437            "[gritcachetest]\n\tvalue = onmain\n",
5438        )
5439        .expect("write branch config");
5440        assert_eq!(load_value(&caches, gd).as_deref(), Some("onmain"));
5441
5442        // Switching branches rewrites HEAD; the stamped HEAD must invalidate
5443        // the cached cascade so the condition is re-evaluated.
5444        fs::write(gd.join("HEAD"), "ref: refs/heads/dev\n").expect("rewrite HEAD");
5445        assert_eq!(load_value(&caches, gd), None);
5446    }
5447
5448    #[test]
5449    #[cfg(unix)]
5450    fn load_propagates_local_config_io_errors() {
5451        use std::os::unix::fs::symlink;
5452        let td = tempfile::tempdir().expect("tempdir");
5453        let git_dir = td.path();
5454        let config = git_dir.join("config");
5455        symlink("config", &config).expect("self-referential symlink");
5456        let err = ConfigSet::load(
5457            &Environment::empty(),
5458            Some(git_dir),
5459            &crate::config::LoadConfigOptions::standard(&Environment::empty(), Some(git_dir)),
5460        )
5461        .unwrap_err();
5462        assert!(
5463            matches!(err, Error::Io(_)),
5464            "expected I/O error for symlink loop, got {err:?}"
5465        );
5466    }
5467}
5468
5469#[cfg(test)]
5470mod line_scan_tests {
5471    use super::*;
5472
5473    /// The char-at-a-time comment stripper the byte scan replaced, kept as the reference.
5474    fn strip_inline_comment_by_chars(s: &str) -> String {
5475        let mut in_quote = false;
5476        let mut last_was_backslash = false;
5477        let mut result = String::with_capacity(s.len());
5478        let mut chars = s.chars().peekable();
5479        while let Some(ch) = chars.next() {
5480            match ch {
5481                '"' if !last_was_backslash => {
5482                    in_quote = !in_quote;
5483                    result.push(ch);
5484                    last_was_backslash = false;
5485                }
5486                '\\' if !last_was_backslash => {
5487                    last_was_backslash = true;
5488                    result.push(ch);
5489                    if in_quote {
5490                        if let Some(&next) = chars.peek() {
5491                            result.push(next);
5492                            chars.next();
5493                            last_was_backslash = false;
5494                        }
5495                    }
5496                }
5497                '#' | ';' if !in_quote && !last_was_backslash => break,
5498                _ => {
5499                    last_was_backslash = false;
5500                    result.push(ch);
5501                }
5502            }
5503        }
5504        result.trim_end().to_owned()
5505    }
5506
5507    fn unclosed_quote_by_chars(line: &str) -> bool {
5508        let trimmed = line.trim();
5509        let Some(eq_pos) = trimmed.find('=') else {
5510            return false;
5511        };
5512        let mut in_quote = false;
5513        let mut last_was_backslash = false;
5514        for ch in trimmed[eq_pos + 1..].trim_start().chars() {
5515            match ch {
5516                '"' if !last_was_backslash => {
5517                    in_quote = !in_quote;
5518                    last_was_backslash = false;
5519                }
5520                '\\' if !last_was_backslash => {
5521                    last_was_backslash = true;
5522                    continue;
5523                }
5524                '#' | ';' if !in_quote && !last_was_backslash => return false,
5525                _ => last_was_backslash = false,
5526            }
5527        }
5528        in_quote
5529    }
5530
5531    fn continues_by_chars(line: &str) -> bool {
5532        let trimmed = line.trim();
5533        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
5534            return false;
5535        }
5536        let Some(pos) = trimmed.find('=') else {
5537            return false;
5538        };
5539        let mut in_quote = false;
5540        let mut last_was_backslash = false;
5541        let mut in_comment = false;
5542        for ch in trimmed[pos + 1..].chars() {
5543            if in_comment {
5544                last_was_backslash = false;
5545                continue;
5546            }
5547            match ch {
5548                '"' if !last_was_backslash => {
5549                    in_quote = !in_quote;
5550                    last_was_backslash = false;
5551                }
5552                '\\' if !last_was_backslash => {
5553                    last_was_backslash = true;
5554                    continue;
5555                }
5556                '#' | ';' if !in_quote && !last_was_backslash => {
5557                    in_comment = true;
5558                    last_was_backslash = false;
5559                }
5560                _ => last_was_backslash = false,
5561            }
5562        }
5563        last_was_backslash && !in_comment
5564    }
5565
5566    /// Every string of up to five tokens drawn from the characters the scanners treat
5567    /// specially, plus ASCII and multi-byte text and Unicode whitespace.
5568    fn corpus() -> Vec<String> {
5569        const TOKENS: [&str; 11] = [
5570            "a", "\"", "\\", "#", ";", " ", "=", "\t", "é", "日", "\u{2003}",
5571        ];
5572        let mut out = vec![String::new()];
5573        let mut frontier = vec![String::new()];
5574        for _ in 0..5 {
5575            let mut next = Vec::with_capacity(frontier.len() * TOKENS.len());
5576            for prefix in &frontier {
5577                for token in TOKENS {
5578                    next.push(format!("{prefix}{token}"));
5579                }
5580            }
5581            out.extend(next.iter().cloned());
5582            frontier = next;
5583        }
5584        out
5585    }
5586
5587    #[test]
5588    fn byte_scanners_match_char_scanners_on_every_short_line() {
5589        for s in corpus() {
5590            assert_eq!(
5591                strip_inline_comment(&s),
5592                strip_inline_comment_by_chars(&s),
5593                "strip_inline_comment({s:?})"
5594            );
5595            let line = format!("k = {s}");
5596            assert_eq!(
5597                entry_line_value_has_unclosed_quote(&line),
5598                unclosed_quote_by_chars(&line),
5599                "unclosed quote in {line:?}"
5600            );
5601            assert_eq!(
5602                value_line_continues(&line),
5603                continues_by_chars(&line),
5604                "continuation of {line:?}"
5605            );
5606            assert_eq!(
5607                entry_line_value_has_unclosed_quote(&s),
5608                unclosed_quote_by_chars(&s),
5609                "unclosed quote in {s:?}"
5610            );
5611            assert_eq!(
5612                value_line_continues(&s),
5613                continues_by_chars(&s),
5614                "continuation of {s:?}"
5615            );
5616        }
5617    }
5618
5619    #[test]
5620    fn strip_inline_comment_borrows_a_prefix() {
5621        let s = "\"a # b\" tail ; comment";
5622        let stripped = strip_inline_comment(s);
5623        assert_eq!(stripped, "\"a # b\" tail");
5624        assert_eq!(stripped.as_ptr(), s.as_ptr());
5625        assert_eq!(strip_inline_comment("\"\\\"#\" x"), "\"\\\"#\" x");
5626        assert_eq!(strip_inline_comment("v\\#kept # gone"), "v\\#kept");
5627    }
5628
5629    #[test]
5630    fn canonical_key_lowercases_section_and_name_only() {
5631        assert_eq!(canonical_key("core.bare").unwrap(), "core.bare");
5632        assert_eq!(canonical_key("CORE.BARE").unwrap(), "core.bare");
5633        assert_eq!(
5634            canonical_key("Remote.Origin.URL").unwrap(),
5635            "remote.Origin.url"
5636        );
5637        assert_eq!(canonical_key("a.B.C.D").unwrap(), "a.B.C.d");
5638        assert!(canonical_key("nodot").is_err());
5639        assert!(canonical_key("core.").is_err());
5640        assert!(canonical_key("core.1bad").is_err());
5641        assert!(canonical_key("core.ba\nre").is_err());
5642    }
5643
5644    #[test]
5645    fn parsed_keys_reuse_the_section_prefix_per_header() {
5646        let text = "[Core]\n\tBare = false\n\tFileMode\n\
5647                    [Remote \"Origin\"]\n\tURL = /x\n\
5648                    [branch \"Main\"] Remote = origin\n\
5649                    [core]\n\tEditor = vi ; trailing\n";
5650        let file = ConfigFile::parse(Path::new("cfg"), text, ConfigScope::Local).unwrap();
5651        let keys: Vec<(&str, Option<&str>)> = file
5652            .entries
5653            .iter()
5654            .map(|e| (e.key.as_str(), e.value.as_deref()))
5655            .collect();
5656        assert_eq!(
5657            keys,
5658            [
5659                ("core.bare", Some("false")),
5660                ("core.filemode", None),
5661                ("remote.Origin.url", Some("/x")),
5662                ("branch.Main.remote", Some("origin")),
5663                ("core.editor", Some("vi")),
5664            ]
5665        );
5666    }
5667
5668    #[test]
5669    fn push_lowercase_matches_to_lowercase() {
5670        for s in ["", "core", "MiXeD-09", "ÄBC", "İx", "ΣΑΣ"] {
5671            let mut out = String::from("p.");
5672            push_lowercase(&mut out, s);
5673            assert_eq!(out, format!("p.{}", s.to_lowercase()));
5674        }
5675    }
5676}