Skip to main content

greengate_runtime/
config.rs

1//! Reading configuration — and reading it the way git itself does.
2//!
3//! Everything this project can be tuned with is a `git config` key, so the
4//! honest implementation of that promise is to let git do the parsing.
5//! `git config --type=bool` implements git-config(1) by definition: `on`,
6//! `yes`, `1`, an empty value, and every capitalisation of each. A hand-rolled
7//! `matches!(v, "true" | "1" | "yes")` is our own dialect wearing git's
8//! clothes, and it had already drifted — `git config greengate.fix on` looked
9//! like it worked and did not.
10//!
11//! The exit code carries the part that matters most:
12//!
13//! | exit | means |
14//! |---|---|
15//! | 0 | the key is set, and stdout is git's normalised value |
16//! | 1 | the key is not set anywhere git looked |
17//! | 128 | the key is set to something git refuses to parse, and said so on stderr |
18//!
19//! Collapsing 1 and 128 into "no" is the bug this module exists to prevent: a
20//! limit you believe you raised and did not is exactly the silent-config
21//! failure that `hook.skip` announcements were introduced for. So a bad value
22//! falls back to the shipped default **and says so**, once per key per run.
23
24use crate::git;
25use crate::ui::{highlight, warning_sign};
26use std::collections::BTreeSet;
27use std::ops::RangeInclusive;
28use std::sync::{Mutex, OnceLock};
29
30/// What a key said. Three answers, because "unset" is a state this project
31/// makes decisions with — `greengate.commit.gitmoji` has four meanings and one
32/// of them is absence.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum Value<T> {
35    Unset,
36    Set(T),
37    /// Set to something that could not be read. `why` is git's own diagnostic
38    /// where git produced one, and ours where the constraint is ours (a value
39    /// outside an allowed set, or outside a range).
40    Bad {
41        why: String,
42    },
43}
44
45impl<T> Value<T> {
46    pub fn is_set(&self) -> bool {
47        matches!(self, Value::Set(_))
48    }
49}
50
51/// `git config --type=<ty> --get <key>`, with the three exits kept apart.
52///
53/// Git failing to run at all is reported as `Unset`: this crate's standing
54/// posture is that an unanswerable question takes the default rather than
55/// blocking a commit.
56fn typed(key: &str, ty: &str) -> Value<String> {
57    let type_flag = format!("--type={ty}");
58    let Some(out) = git::output(&["config", &type_flag, "--get", key]) else {
59        return Value::Unset;
60    };
61    match out.code {
62        0 => Value::Set(out.stdout),
63        1 => Value::Unset,
64        _ => Value::Bad {
65            why: first_line(&out.stderr),
66        },
67    }
68}
69
70/// As [`typed`], but reading a POLICY-SUPPLIED literal instead of the
71/// machine's config: `git -c <key>=<raw> config --type=<ty> --get <key>`.
72/// GIT parses the value, so `Value::Bad` and `complain` work unchanged and
73/// no second config dialect exists — the founding argument of this module.
74fn typed_literal(key: &str, raw: &str, ty: Option<&str>) -> Value<String> {
75    let assignment = format!("{key}={raw}");
76    let mut args: Vec<&str> = vec!["-c", &assignment, "config"];
77    let type_flag = ty.map(|t| format!("--type={t}"));
78    if let Some(tf) = &type_flag {
79        args.push(tf);
80    }
81    args.extend(["--get", key]);
82    let Some(out) = git::output(&args) else {
83        return Value::Unset;
84    };
85    match out.code {
86        0 => Value::Set(out.stdout),
87        1 => Value::Unset,
88        _ => Value::Bad {
89            why: first_line(&out.stderr),
90        },
91    }
92}
93
94/// The ladder, as a short-circuit rather than a general mechanism:
95///
96///   policy has no value for `key`      → [`typed`], byte-for-byte as before
97///   key set at local/worktree/command  → [`typed`] — the machine wins
98///   otherwise                          → [`typed_literal`] — policy wins
99///
100/// The invariant this shape buys: a repository with no `set` lines spawns
101/// not one extra git process anywhere — the scoped scan below runs only
102/// when the policy actually carries settings.
103fn resolve(settings: &crate::config::Settings, key: &str, ty: Option<&str>) -> Value<String> {
104    let policy = settings.policy();
105    let Some(raw) = policy.settings.get(key) else {
106        return match ty {
107            Some(t) => typed(key, t),
108            None => untyped(key),
109        };
110    };
111    if key_set_above_policy(settings, key) {
112        return match ty {
113            Some(t) => typed(key, t),
114            None => untyped(key),
115        };
116    }
117    typed_literal(key, raw, ty)
118}
119
120/// The raw read `enumerated` has always done, factored so `resolve` can
121/// route it.
122fn untyped(key: &str) -> Value<String> {
123    let Some(out) = git::output(&["config", "--get", key]) else {
124        return Value::Unset;
125    };
126    match out.code {
127        0 => Value::Set(out.stdout),
128        1 => Value::Unset,
129        _ => Value::Bad {
130            why: first_line(&out.stderr),
131        },
132    }
133}
134
135/// Is `key` set at a scope that outranks policy (local/worktree/command)?
136///
137/// One lazily-cached `git config --show-scope --get-regexp '^greengate\.'` for
138/// the whole process — this is the PRECEDENCE reader, deliberately separate
139/// from [`scope_of`], which is `--show-origin`-based and display-oriented.
140/// Scope words `system`/`global` rank below policy; every other word —
141/// `local`, `worktree`, `command`, and whatever a future git invents —
142/// ranks above, because misreading a local as below would let a file pulled
143/// from a remote silently override a person's explicit machine setting.
144///
145/// On a git too old for `--show-scope` the cache is `None` and this
146/// DEGRADES fail-safe: any set key counts as above, i.e. all git config
147/// beats policy.
148fn key_set_above_policy(settings: &crate::config::Settings, key: &str) -> bool {
149    let above = settings.scoped.get_or_init(|| {
150        crate::git::stdout(&["config", "--show-scope", "--get-regexp", r"^greengate\."]).map(
151            |scoped| {
152                scoped
153                    .lines()
154                    .filter_map(|line| {
155                        let (scope, rest) = line.split_once('\t')?;
156                        match scope {
157                            "system" | "global" => None,
158                            _ => rest.split_whitespace().next().map(str::to_ascii_lowercase),
159                        }
160                    })
161                    .collect()
162            },
163        )
164    });
165    match above {
166        Some(set) => set.contains(&key.to_ascii_lowercase()),
167        // Degraded: no scope information — any set key beats policy.
168        None => untyped(key).is_set(),
169    }
170}
171
172/// Git's `fatal:` line, without the noise around it. Empty stderr still yields
173/// something printable, because a warning that names no cause is a puzzle.
174fn first_line(stderr: &str) -> String {
175    let line = stderr.lines().next().unwrap_or("").trim();
176    let line = line.strip_prefix("fatal: ").unwrap_or(line);
177    if line.is_empty() {
178        "git could not read the value".to_string()
179    } else {
180        line.to_string()
181    }
182}
183
184/// Everything this process resolved once about configuration: the trusted
185/// repository policy, and the reads memoised on top of it.
186///
187/// This replaces a process-global `OnceLock<Policy>`. The global was correct
188/// for the hook path — one process means one repository — but it made a rule
189/// the compiler could not see. A multi-repo walker had to KNOW not to seed
190/// it, and `amont-fleet` carried that knowledge as a comment with no test
191/// able to assert it, because asserting it would have meant seeding it.
192///
193/// Owned high and borrowed everywhere — the shape `Ctx` already uses for
194/// `manifest` and `push` — the rule stops needing to be remembered: there is
195/// no store to seed. The memo fields keep the per-process caching these reads
196/// have always had, which `spawn_budget` measures; one `Settings` per process
197/// buys the same number of git spawns the statics did.
198#[derive(Debug, Default)]
199pub struct Settings {
200    policy: crate::policy::Policy,
201    /// The precedence reader: one `--show-scope` scan per process.
202    scoped: OnceLock<Option<BTreeSet<String>>>,
203    /// The host-key reader: one `--show-scope` scan with values, run only
204    /// when a host key is first read. `(scope, key lowercased, value)`.
205    host: OnceLock<Option<Vec<(String, String, String)>>>,
206    /// Reads memoised on first use. Each was a module-level `OnceLock` beside
207    /// its accessor; here, "resolved once" is scoped to a `Settings` rather
208    /// than to the process, so a second one cannot inherit the first's answers.
209    pub(crate) timeout: OnceLock<u64>,
210    pub(crate) idle: OnceLock<u64>,
211    pub(crate) idle_cpu: OnceLock<bool>,
212    pub(crate) lock_wait: OnceLock<u64>,
213    pub(crate) idle_load_scale: OnceLock<u64>,
214    pub(crate) quiet: OnceLock<bool>,
215    pub(crate) progress: OnceLock<bool>,
216    pub(crate) declared_mode: OnceLock<bool>,
217    pub(crate) fixing: OnceLock<bool>,
218    /// This process's held marker and its once-per-run journal row (t15): a
219    /// fact of the environment, memoised on the settings that every check of
220    /// the run reads, not in a module-level static.
221    pub(crate) marker: OnceLock<greenharness_slots::Marker>,
222    pub(crate) marker_log: greenharness_slots::MarkerLog,
223}
224
225/// `amont run --quiet` or `--raw`.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum QuietOverride {
228    Quiet,
229    Raw,
230}
231
232impl Settings {
233    /// Decide `greengate.quiet` for this run, ahead of the configuration:
234    /// `amont run --quiet` / `--raw`. Only before anything has read it —
235    /// a read first would have fixed the answer, and the flag would do
236    /// nothing; that is a bug in the caller, not a configuration.
237    pub fn override_quiet(&self, mode: QuietOverride) {
238        let quiet = match mode {
239            QuietOverride::Quiet => true,
240            QuietOverride::Raw => false,
241        };
242        self.quiet
243            .set(quiet)
244            .expect("greengate.quiet was read before --quiet/--raw could decide it");
245    }
246
247    /// The policy a trusted manifest declared — empty when nothing was
248    /// declared or the manifest was not trusted. `manifest::load` decides
249    /// that and hands the answer here.
250    pub fn new(policy: crate::policy::Policy) -> Self {
251        Self {
252            policy,
253            ..Self::default()
254        }
255    }
256
257    pub fn policy(&self) -> &crate::policy::Policy {
258        &self.policy
259    }
260
261    /// A fresh `Settings` over the same policy, with empty caches.
262    ///
263    /// For a spawned thread, which cannot borrow this one. It resolves the
264    /// same answers — same policy, same git config — and it resolves them
265    /// LAZILY, which is the property that matters: a paint or heartbeat
266    /// thread that never lives long enough to read a budget must not have
267    /// cost a `git config` spawn for it up front. Handing the thread
268    /// pre-resolved numbers did exactly that, and `spawn_budget` said so.
269    pub fn for_thread(&self) -> Settings {
270        Settings::new(self.policy.clone())
271    }
272}
273
274pub fn boolean(settings: &crate::config::Settings, key: &str) -> Value<bool> {
275    match resolve(settings, key, Some("bool")) {
276        Value::Set(v) => match v.as_str() {
277            "true" => Value::Set(true),
278            "false" => Value::Set(false),
279            other => Value::Bad {
280                why: format!("git normalised it to {other:?}, which is neither true nor false"),
281            },
282        },
283        Value::Unset => Value::Unset,
284        Value::Bad { why } => Value::Bad { why },
285    }
286}
287
288/// An integer, in git's own spelling — which includes the `k`/`m`/`g` suffixes
289/// git accepts, since `--type=int` expands them before we see them.
290pub fn integer(settings: &crate::config::Settings, key: &str) -> Value<i64> {
291    match resolve(settings, key, Some("int")) {
292        Value::Set(v) => match v.parse::<i64>() {
293            Ok(n) => Value::Set(n),
294            Err(_) => Value::Bad {
295                why: format!("git returned {v:?}, which is not a whole number"),
296            },
297        },
298        Value::Unset => Value::Unset,
299        Value::Bad { why } => Value::Bad { why },
300    }
301}
302
303/// One of a fixed set of words, compared case-insensitively.
304///
305/// Git has no `--type` for this, so the value is read raw and checked here —
306/// which means this is the one reader whose `Bad` message is ours. It names
307/// every accepted spelling, because a rejection that does not say what was
308/// wanted sends the reader to the documentation for a list we already hold.
309pub fn enumerated(
310    settings: &crate::config::Settings,
311    key: &str,
312    allowed: &[&'static str],
313) -> Value<&'static str> {
314    match resolve(settings, key, None) {
315        Value::Set(v) => {
316            let got = v.trim().to_ascii_lowercase();
317            match allowed.iter().find(|a| a.eq_ignore_ascii_case(&got)) {
318                Some(hit) => Value::Set(hit),
319                None => Value::Bad {
320                    why: format!("{got:?} is not one of {}", allowed.join(", ")),
321                },
322            }
323        }
324        Value::Unset => Value::Unset,
325        Value::Bad { why } => Value::Bad { why },
326    }
327}
328
329/// Say once, per key, that a configured value could not be used.
330///
331/// Deduplicated because a key read twice in one run is a detail of how the
332/// code is arranged, and repeating the warning would make it look like two
333/// separate mistakes.
334/// A free-form string key, policy-aware. Untyped reads have no `--type`
335/// for git to refuse, so `Bad` cannot arise — this is Set-or-not.
336pub fn string_value(settings: &crate::config::Settings, key: &str) -> Option<String> {
337    match resolve(settings, key, None) {
338        Value::Set(v) => Some(v),
339        _ => None,
340    }
341}
342
343pub fn complain(key: &str, why: &str, using: &str) {
344    static SAID: OnceLock<Mutex<BTreeSet<String>>> = OnceLock::new();
345    let said = SAID.get_or_init(|| Mutex::new(BTreeSet::new()));
346    // A poisoned mutex means another thread panicked mid-insert; warning twice
347    // is strictly better than joining it in panicking.
348    let fresh = match said.lock() {
349        Ok(mut set) => set.insert(key.to_string()),
350        Err(_) => true,
351    };
352    if fresh {
353        eprintln!(
354            "{} {}: {why} — using {using}",
355            warning_sign().trim(),
356            highlight(key)
357        );
358    }
359}
360
361pub fn boolean_or(settings: &crate::config::Settings, key: &str, default: bool) -> bool {
362    match boolean(settings, key) {
363        Value::Set(v) => v,
364        Value::Unset => default,
365        Value::Bad { why } => {
366            complain(key, &why, &default.to_string());
367            default
368        }
369    }
370}
371
372/// An integer, clamped to what the setting can actually mean.
373///
374/// Out of range is treated exactly as unparseable: a `subjectMax` of 0 would
375/// block every commit forever from a config file, and one of 10_000 is not a
376/// limit. Both are mistakes, and both get the default plus a line saying so.
377pub fn integer_or(
378    settings: &crate::config::Settings,
379    key: &str,
380    default: i64,
381    range: RangeInclusive<i64>,
382) -> i64 {
383    match integer(settings, key) {
384        Value::Set(v) if range.contains(&v) => v,
385        Value::Set(v) => {
386            complain(
387                key,
388                &format!("{v} is outside {}..={}", range.start(), range.end()),
389                &default.to_string(),
390            );
391            default
392        }
393        Value::Unset => default,
394        Value::Bad { why } => {
395            complain(key, &why, &default.to_string());
396            default
397        }
398    }
399}
400
401/// The `greengate.*` rows of `git config --show-scope`, as (scope, lowercased
402/// key, value): one scan per `Settings`, shared by every host key read and by
403/// the slots crate's `HostSizing::resolve`. `None` when git cannot report
404/// config scopes.
405pub fn host_rows(settings: &crate::config::Settings) -> Option<&[greenharness_slots::host::Row]> {
406    settings
407        .host
408        .get_or_init(|| {
409            // The crate's reader: exit 1 (no `greengate.*` key at all) is no
410            // rows, not "git cannot report scopes".
411            let out = git::output(&greenharness_slots::host::GIT_ARGS)?;
412            greenharness_slots::host::rows_from(Some(out.code), out.stdout.as_bytes())
413        })
414        .as_deref()
415}
416
417/// A HOST key: a setting that describes the machine — how many heavy checks
418/// it runs at once, how far its load may stretch a budget — and so is read
419/// from `--global` or `--system` config only (ADR-0009). A value set in a
420/// repository is ignored with one warning naming the scope to use: two
421/// repositories that disagreed about the host's slot count would each take
422/// slots the other never sees. An environment variable named after the key
423/// (`greengate.idleLoadScale` → `GREENGATE_IDLE_LOAD_SCALE`) outranks both, which
424/// is the precedence `cli.config.precedence` gives it: flag or environment,
425/// then the person's config, then the system's, then the default. The
426/// `amont.conf` policy ladder does not apply: a committed file cannot set
427/// a host key.
428///
429/// One `--show-scope` scan per `Settings`, run on the first host key read
430/// and never before: `greengate.idleLoadScale` is read when the first observed
431/// tool of any check is spawned, so a commit that runs no tool spawns
432/// nothing for it and one that does pays exactly one spawn, pinned by
433/// `spawn_budget.rs`.
434pub fn host_integer_or(
435    settings: &crate::config::Settings,
436    key: &str,
437    default: i64,
438    range: RangeInclusive<i64>,
439) -> i64 {
440    let accept = |raw: &str, source: &str| -> Option<i64> {
441        match raw.trim().parse::<i64>() {
442            Ok(v) if range.contains(&v) => Some(v),
443            Ok(v) => {
444                complain(
445                    key,
446                    &format!(
447                        "{v} ({source}) is outside {}..={}",
448                        range.start(),
449                        range.end()
450                    ),
451                    &default.to_string(),
452                );
453                None
454            }
455            Err(_) => {
456                complain(
457                    key,
458                    &format!("{raw:?} ({source}) is not a whole number"),
459                    &default.to_string(),
460                );
461                None
462            }
463        }
464    };
465    let env_name = host_env_name(key);
466    if let Some(raw) = std::env::var(&env_name)
467        .ok()
468        .filter(|v| !v.trim().is_empty())
469    {
470        if let Some(v) = accept(&raw, &env_name) {
471            return v;
472        }
473    }
474    let Some(rows) = host_rows(settings) else {
475        // A git too old for `--show-scope`: the default, said once.
476        complain(key, "git cannot report config scopes", &default.to_string());
477        return default;
478    };
479    let wanted = key.to_ascii_lowercase();
480    let host = rows
481        .iter()
482        .rev()
483        .find(|(scope, k, _)| *k == wanted && (scope == "global" || scope == "system"));
484    if host.is_none() && rows.iter().any(|(_, k, _)| *k == wanted) {
485        complain(
486            key,
487            "is set in this repository's config, but a host key is read from --global or \
488             --system only",
489            &default.to_string(),
490        );
491    }
492    host.and_then(|(scope, _, v)| accept(v, scope))
493        .unwrap_or(default)
494}
495
496/// `greengate.idleLoadScale` → `GREENGATE_IDLE_LOAD_SCALE`: the environment name a
497/// host key answers to.
498pub fn host_env_name(key: &str) -> String {
499    let mut out = String::from(crate::names::ENV_PREFIX);
500    for part in key
501        .trim_start_matches(crate::names::CONFIG_PREFIX)
502        .split('.')
503    {
504        out.push('_');
505        for c in part.chars() {
506            if c.is_ascii_uppercase() {
507                out.push('_');
508            }
509            out.push(c.to_ascii_uppercase());
510        }
511    }
512    out
513}
514
515#[cfg(test)]
516mod host_key_tests {
517    /// The slots crate hardcodes the sizing key names (it sits below this
518    /// crate and cannot call `host_env_name`); they must not drift.
519    #[test]
520    fn the_slots_crate_names_match_host_env_name() {
521        use greenharness_slots::host::{CORES_ENV, CORES_KEY, SLOTS_ENV, SLOTS_KEY};
522        assert_eq!(super::host_env_name(CORES_KEY), CORES_ENV);
523        assert_eq!(super::host_env_name(SLOTS_KEY), SLOTS_ENV);
524        assert!(CORES_KEY.starts_with(crate::names::CONFIG_PREFIX));
525        assert!(SLOTS_KEY.starts_with(crate::names::CONFIG_PREFIX));
526    }
527
528    #[test]
529    fn a_host_key_names_its_environment_variable() {
530        use super::host_env_name;
531        assert_eq!(
532            host_env_name("greengate.idleLoadScale"),
533            "GREENGATE_IDLE_LOAD_SCALE"
534        );
535        assert_eq!(host_env_name("greengate.hostSlots"), "GREENGATE_HOST_SLOTS");
536        assert_eq!(host_env_name("greengate.timeout"), "GREENGATE_TIMEOUT");
537        assert_eq!(
538            host_env_name("greengate.commit.bodyWrap"),
539            "GREENGATE_COMMIT_BODY_WRAP"
540        );
541    }
542}
543
544pub fn enumerated_or(
545    settings: &crate::config::Settings,
546    key: &str,
547    allowed: &[&'static str],
548    default: &'static str,
549) -> &'static str {
550    match enumerated(settings, key, allowed) {
551        Value::Set(v) => v,
552        Value::Unset => default,
553        Value::Bad { why } => {
554            complain(key, &why, default);
555            default
556        }
557    }
558}
559
560/// Which keys under `prefix` are set at all — one git call for the whole
561/// family.
562///
563/// This runs on the commit path, where four independent `--get` calls would be
564/// four processes spent discovering that nobody has configured anything. One
565/// `--get-regexp` answers that, and only the keys it names are read for real.
566/// Same shape as `registry::Overrides::read`, for the same reason.
567///
568/// **Names come back lowercased.** Git lowercases the section and key parts of
569/// every name it prints, so `greengate.commit.subjectMax` is reported as
570/// `greengate.commit.subjectmax`. Keys are case-insensitive on lookup, so this
571/// only affects comparison here — hence [`is_present`] rather than a bare
572/// `contains`.
573pub fn present(settings: &crate::config::Settings, prefix: &str) -> BTreeSet<String> {
574    let pattern = format!("^{}", regex_escape(prefix));
575    let policy_names = || -> BTreeSet<String> {
576        settings
577            .policy()
578            .settings
579            .keys()
580            .filter(|k| {
581                k.to_ascii_lowercase()
582                    .starts_with(&prefix.to_ascii_lowercase())
583            })
584            .map(|k| k.to_ascii_lowercase())
585            .collect()
586    };
587    let Some(out) = git::output(&["config", "--get-regexp", &pattern]) else {
588        return policy_names();
589    };
590    if out.code != 0 {
591        return policy_names();
592    }
593    let mut names: BTreeSet<String> = out
594        .stdout
595        .lines()
596        .filter_map(|l| l.split_whitespace().next())
597        .map(|k| k.to_ascii_lowercase())
598        .collect();
599    names.extend(
600        settings
601            .policy()
602            .settings
603            .keys()
604            .filter(|k| {
605                k.to_ascii_lowercase()
606                    .starts_with(&prefix.to_ascii_lowercase())
607            })
608            .map(|k| k.to_ascii_lowercase()),
609    );
610    names
611}
612
613/// Is `key` among the names [`present`] returned? Case-insensitive, because
614/// git config key names are.
615pub fn is_present(names: &BTreeSet<String>, key: &str) -> bool {
616    names.contains(&key.to_ascii_lowercase())
617}
618
619/// Escape the characters a config key can hold that a POSIX basic regex would
620/// otherwise read as syntax. Only `.` occurs in practice; the rest are here so
621/// this cannot become wrong if a caller passes something else.
622fn regex_escape(s: &str) -> String {
623    let mut out = String::with_capacity(s.len() * 2);
624    for c in s.chars() {
625        if matches!(c, '.' | '*' | '[' | ']' | '^' | '$' | '\\') {
626            out.push('\\');
627        }
628        out.push(c);
629    }
630    out
631}
632
633/// Where a key's value came from, for the commands whose job is reading
634/// configuration back.
635///
636/// This costs a second git call per key and must never be used on the commit
637/// path — `amont list` and `amont setup` are the only callers, and they
638/// are already asking git several questions to render one screen.
639#[derive(Debug, Clone, Copy, PartialEq, Eq)]
640pub enum Scope {
641    Default,
642    Local,
643    Global,
644    System,
645    CommandLine,
646    /// The value in effect comes from the repository's committed policy.
647    Policy,
648    Other,
649}
650
651impl Scope {
652    pub fn as_str(self) -> &'static str {
653        match self {
654            Scope::Default => "default",
655            Scope::Local => "local",
656            Scope::Global => "global",
657            Scope::System => "system",
658            Scope::CommandLine => "command line",
659            Scope::Policy => crate::names::MANIFEST,
660            Scope::Other => "other",
661        }
662    }
663}
664
665/// `git config --show-origin --get <key>` → which file it came from.
666///
667/// `Default` for a key nobody set, which is also the answer when git cannot be
668/// asked — the value in use is the shipped one either way.
669pub fn scope_of(settings: &crate::config::Settings, key: &str) -> Scope {
670    // Display mirrors resolution: policy owns the key unless something above
671    // it on the ladder set it. The precedence answer comes from the same
672    // classifier `resolve` uses, never re-derived from file paths.
673    if settings.policy().settings.contains_key(key) && !key_set_above_policy(settings, key) {
674        return Scope::Policy;
675    }
676    let Some(out) = git::output(&["config", "--show-origin", "--get", key]) else {
677        return Scope::Default;
678    };
679    if out.code != 0 {
680        return Scope::Default;
681    }
682    // `<origin>\t<value>`; the origin is `file:/path`, `command line:` or
683    // `blob:…`, and the path is what tells local from global.
684    let origin = out.stdout.split('\t').next().unwrap_or("");
685    if origin.starts_with("command line") {
686        return Scope::CommandLine;
687    }
688    let Some(path) = origin.strip_prefix("file:") else {
689        return Scope::Other;
690    };
691    let path = path.trim();
692    // A repository's own config is the only one inside a `.git` directory;
693    // asking git for the paths rather than guessing at `~` keeps this correct
694    // under `GIT_CONFIG_GLOBAL`, worktrees and `$XDG_CONFIG_HOME`.
695    if same_file(
696        path,
697        git::stdout(&["rev-parse", "--git-path", "config"]).as_deref(),
698    ) {
699        return Scope::Local;
700    }
701    for (flag, scope) in [("--global", Scope::Global), ("--system", Scope::System)] {
702        let listed = git::output(&["config", flag, "--list", "--show-origin"]);
703        if let Some(o) = listed {
704            if o.code == 0
705                && o.stdout
706                    .lines()
707                    .filter_map(|l| l.split('\t').next())
708                    .filter_map(|o| o.strip_prefix("file:"))
709                    .any(|p| same_file(path, Some(p.trim())))
710            {
711                return scope;
712            }
713        }
714    }
715    Scope::Other
716}
717
718/// Compare two paths as the same file where the filesystem can say so, falling
719/// back to the strings. `--git-path` answers relatively (`.git/config`) while
720/// `--show-origin` may answer absolutely, so a string comparison alone
721/// misreports a local key as `other`.
722fn same_file(a: &str, b: Option<&str>) -> bool {
723    let Some(b) = b else { return false };
724    if a == b {
725        return true;
726    }
727    match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
728        (Ok(x), Ok(y)) => x == y,
729        _ => false,
730    }
731}
732
733#[cfg(test)]
734mod tests {
735    use super::*;
736
737    /// The distinction the whole module exists for: git's two failure exits
738    /// mean opposite things, and `first_line` is what a reader is shown for
739    /// the one that is a mistake.
740    #[test]
741    fn a_fatal_line_is_reported_without_its_prefix() {
742        assert_eq!(
743            first_line("fatal: bad numeric config value 'wide' for 'a.b'"),
744            "bad numeric config value 'wide' for 'a.b'"
745        );
746        assert_eq!(first_line("first\nsecond"), "first");
747    }
748
749    /// A warning that names no cause is a puzzle, so there is always a cause.
750    #[test]
751    fn an_empty_diagnostic_still_says_something() {
752        assert!(!first_line("").is_empty());
753        assert!(!first_line("   \n  ").is_empty());
754    }
755
756    #[test]
757    fn a_key_name_is_escaped_before_it_becomes_a_pattern() {
758        // Without escaping, `.` matches any character and the prefix would
759        // also select `amontXcommit.*`.
760        assert_eq!(regex_escape("greengate.commit."), "greengate\\.commit\\.");
761        assert_eq!(regex_escape("plain"), "plain");
762    }
763
764    /// Git lowercases the names it prints, so a presence test that respected
765    /// case would answer "not set" for every camelCase key we ship.
766    #[test]
767    fn presence_is_case_insensitive_because_git_lowercases_names() {
768        let names: BTreeSet<String> = ["greengate.commit.subjectmax".to_string()]
769            .into_iter()
770            .collect();
771        assert!(is_present(&names, "greengate.commit.subjectMax"));
772        assert!(is_present(&names, "GREENGATE.COMMIT.SUBJECTMAX"));
773        assert!(!is_present(&names, "greengate.commit.bodyWrap"));
774    }
775
776    #[test]
777    fn every_scope_has_a_name() {
778        for s in [
779            Scope::Default,
780            Scope::Local,
781            Scope::Global,
782            Scope::System,
783            Scope::CommandLine,
784            Scope::Other,
785        ] {
786            assert!(!s.as_str().is_empty());
787        }
788    }
789}