Skip to main content

amont_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 amont.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 — `amont.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 '^amont\.'` 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"^amont\."]).map(|scoped| {
151            scoped
152                .lines()
153                .filter_map(|line| {
154                    let (scope, rest) = line.split_once('\t')?;
155                    match scope {
156                        "system" | "global" => None,
157                        _ => rest.split_whitespace().next().map(str::to_ascii_lowercase),
158                    }
159                })
160                .collect()
161        })
162    });
163    match above {
164        Some(set) => set.contains(&key.to_ascii_lowercase()),
165        // Degraded: no scope information — any set key beats policy.
166        None => untyped(key).is_set(),
167    }
168}
169
170/// Git's `fatal:` line, without the noise around it. Empty stderr still yields
171/// something printable, because a warning that names no cause is a puzzle.
172fn first_line(stderr: &str) -> String {
173    let line = stderr.lines().next().unwrap_or("").trim();
174    let line = line.strip_prefix("fatal: ").unwrap_or(line);
175    if line.is_empty() {
176        "git could not read the value".to_string()
177    } else {
178        line.to_string()
179    }
180}
181
182/// Everything this process resolved once about configuration: the trusted
183/// repository policy, and the reads memoised on top of it.
184///
185/// This replaces a process-global `OnceLock<Policy>`. The global was correct
186/// for the hook path — one process means one repository — but it made a rule
187/// the compiler could not see. A multi-repo walker had to KNOW not to seed
188/// it, and `amont-fleet` carried that knowledge as a comment with no test
189/// able to assert it, because asserting it would have meant seeding it.
190///
191/// Owned high and borrowed everywhere — the shape `Ctx` already uses for
192/// `manifest` and `push` — the rule stops needing to be remembered: there is
193/// no store to seed. The memo fields keep the per-process caching these reads
194/// have always had, which `spawn_budget` measures; one `Settings` per process
195/// buys the same number of git spawns the statics did.
196#[derive(Debug, Default)]
197pub struct Settings {
198    policy: crate::policy::Policy,
199    /// The precedence reader: one `--show-scope` scan per process.
200    scoped: OnceLock<Option<BTreeSet<String>>>,
201    /// Reads memoised on first use. Each was a module-level `OnceLock` beside
202    /// its accessor; here, "resolved once" is scoped to a `Settings` rather
203    /// than to the process, so a second one cannot inherit the first's answers.
204    pub(crate) timeout: OnceLock<u64>,
205    pub(crate) idle: OnceLock<u64>,
206    pub(crate) quiet: OnceLock<bool>,
207    pub(crate) progress: OnceLock<bool>,
208    pub(crate) declared_mode: OnceLock<bool>,
209    pub(crate) fixing: OnceLock<bool>,
210}
211
212impl Settings {
213    /// The policy a trusted manifest declared — empty when nothing was
214    /// declared or the manifest was not trusted. `manifest::load` decides
215    /// that and hands the answer here.
216    pub fn new(policy: crate::policy::Policy) -> Self {
217        Self {
218            policy,
219            ..Self::default()
220        }
221    }
222
223    pub fn policy(&self) -> &crate::policy::Policy {
224        &self.policy
225    }
226
227    /// A fresh `Settings` over the same policy, with empty caches.
228    ///
229    /// For a spawned thread, which cannot borrow this one. It resolves the
230    /// same answers — same policy, same git config — and it resolves them
231    /// LAZILY, which is the property that matters: a paint or heartbeat
232    /// thread that never lives long enough to read a budget must not have
233    /// cost a `git config` spawn for it up front. Handing the thread
234    /// pre-resolved numbers did exactly that, and `spawn_budget` said so.
235    pub fn for_thread(&self) -> Settings {
236        Settings::new(self.policy.clone())
237    }
238}
239
240pub fn boolean(settings: &crate::config::Settings, key: &str) -> Value<bool> {
241    match resolve(settings, key, Some("bool")) {
242        Value::Set(v) => match v.as_str() {
243            "true" => Value::Set(true),
244            "false" => Value::Set(false),
245            other => Value::Bad {
246                why: format!("git normalised it to {other:?}, which is neither true nor false"),
247            },
248        },
249        Value::Unset => Value::Unset,
250        Value::Bad { why } => Value::Bad { why },
251    }
252}
253
254/// An integer, in git's own spelling — which includes the `k`/`m`/`g` suffixes
255/// git accepts, since `--type=int` expands them before we see them.
256pub fn integer(settings: &crate::config::Settings, key: &str) -> Value<i64> {
257    match resolve(settings, key, Some("int")) {
258        Value::Set(v) => match v.parse::<i64>() {
259            Ok(n) => Value::Set(n),
260            Err(_) => Value::Bad {
261                why: format!("git returned {v:?}, which is not a whole number"),
262            },
263        },
264        Value::Unset => Value::Unset,
265        Value::Bad { why } => Value::Bad { why },
266    }
267}
268
269/// One of a fixed set of words, compared case-insensitively.
270///
271/// Git has no `--type` for this, so the value is read raw and checked here —
272/// which means this is the one reader whose `Bad` message is ours. It names
273/// every accepted spelling, because a rejection that does not say what was
274/// wanted sends the reader to the documentation for a list we already hold.
275pub fn enumerated(
276    settings: &crate::config::Settings,
277    key: &str,
278    allowed: &[&'static str],
279) -> Value<&'static str> {
280    match resolve(settings, key, None) {
281        Value::Set(v) => {
282            let got = v.trim().to_ascii_lowercase();
283            match allowed.iter().find(|a| a.eq_ignore_ascii_case(&got)) {
284                Some(hit) => Value::Set(hit),
285                None => Value::Bad {
286                    why: format!("{got:?} is not one of {}", allowed.join(", ")),
287                },
288            }
289        }
290        Value::Unset => Value::Unset,
291        Value::Bad { why } => Value::Bad { why },
292    }
293}
294
295/// Say once, per key, that a configured value could not be used.
296///
297/// Deduplicated because a key read twice in one run is a detail of how the
298/// code is arranged, and repeating the warning would make it look like two
299/// separate mistakes.
300/// A free-form string key, policy-aware. Untyped reads have no `--type`
301/// for git to refuse, so `Bad` cannot arise — this is Set-or-not.
302pub fn string_value(settings: &crate::config::Settings, key: &str) -> Option<String> {
303    match resolve(settings, key, None) {
304        Value::Set(v) => Some(v),
305        _ => None,
306    }
307}
308
309pub fn complain(key: &str, why: &str, using: &str) {
310    static SAID: OnceLock<Mutex<BTreeSet<String>>> = OnceLock::new();
311    let said = SAID.get_or_init(|| Mutex::new(BTreeSet::new()));
312    // A poisoned mutex means another thread panicked mid-insert; warning twice
313    // is strictly better than joining it in panicking.
314    let fresh = match said.lock() {
315        Ok(mut set) => set.insert(key.to_string()),
316        Err(_) => true,
317    };
318    if fresh {
319        eprintln!(
320            "{} {}: {why} — using {using}",
321            warning_sign().trim(),
322            highlight(key)
323        );
324    }
325}
326
327pub fn boolean_or(settings: &crate::config::Settings, key: &str, default: bool) -> bool {
328    match boolean(settings, key) {
329        Value::Set(v) => v,
330        Value::Unset => default,
331        Value::Bad { why } => {
332            complain(key, &why, &default.to_string());
333            default
334        }
335    }
336}
337
338/// An integer, clamped to what the setting can actually mean.
339///
340/// Out of range is treated exactly as unparseable: a `subjectMax` of 0 would
341/// block every commit forever from a config file, and one of 10_000 is not a
342/// limit. Both are mistakes, and both get the default plus a line saying so.
343pub fn integer_or(
344    settings: &crate::config::Settings,
345    key: &str,
346    default: i64,
347    range: RangeInclusive<i64>,
348) -> i64 {
349    match integer(settings, key) {
350        Value::Set(v) if range.contains(&v) => v,
351        Value::Set(v) => {
352            complain(
353                key,
354                &format!("{v} is outside {}..={}", range.start(), range.end()),
355                &default.to_string(),
356            );
357            default
358        }
359        Value::Unset => default,
360        Value::Bad { why } => {
361            complain(key, &why, &default.to_string());
362            default
363        }
364    }
365}
366
367pub fn enumerated_or(
368    settings: &crate::config::Settings,
369    key: &str,
370    allowed: &[&'static str],
371    default: &'static str,
372) -> &'static str {
373    match enumerated(settings, key, allowed) {
374        Value::Set(v) => v,
375        Value::Unset => default,
376        Value::Bad { why } => {
377            complain(key, &why, default);
378            default
379        }
380    }
381}
382
383/// Which keys under `prefix` are set at all — one git call for the whole
384/// family.
385///
386/// This runs on the commit path, where four independent `--get` calls would be
387/// four processes spent discovering that nobody has configured anything. One
388/// `--get-regexp` answers that, and only the keys it names are read for real.
389/// Same shape as `registry::Overrides::read`, for the same reason.
390///
391/// **Names come back lowercased.** Git lowercases the section and key parts of
392/// every name it prints, so `amont.commit.subjectMax` is reported as
393/// `amont.commit.subjectmax`. Keys are case-insensitive on lookup, so this
394/// only affects comparison here — hence [`is_present`] rather than a bare
395/// `contains`.
396pub fn present(settings: &crate::config::Settings, prefix: &str) -> BTreeSet<String> {
397    let pattern = format!("^{}", regex_escape(prefix));
398    let policy_names = || -> BTreeSet<String> {
399        settings
400            .policy()
401            .settings
402            .keys()
403            .filter(|k| {
404                k.to_ascii_lowercase()
405                    .starts_with(&prefix.to_ascii_lowercase())
406            })
407            .map(|k| k.to_ascii_lowercase())
408            .collect()
409    };
410    let Some(out) = git::output(&["config", "--get-regexp", &pattern]) else {
411        return policy_names();
412    };
413    if out.code != 0 {
414        return policy_names();
415    }
416    let mut names: BTreeSet<String> = out
417        .stdout
418        .lines()
419        .filter_map(|l| l.split_whitespace().next())
420        .map(|k| k.to_ascii_lowercase())
421        .collect();
422    names.extend(
423        settings
424            .policy()
425            .settings
426            .keys()
427            .filter(|k| {
428                k.to_ascii_lowercase()
429                    .starts_with(&prefix.to_ascii_lowercase())
430            })
431            .map(|k| k.to_ascii_lowercase()),
432    );
433    names
434}
435
436/// Is `key` among the names [`present`] returned? Case-insensitive, because
437/// git config key names are.
438pub fn is_present(names: &BTreeSet<String>, key: &str) -> bool {
439    names.contains(&key.to_ascii_lowercase())
440}
441
442/// Escape the characters a config key can hold that a POSIX basic regex would
443/// otherwise read as syntax. Only `.` occurs in practice; the rest are here so
444/// this cannot become wrong if a caller passes something else.
445fn regex_escape(s: &str) -> String {
446    let mut out = String::with_capacity(s.len() * 2);
447    for c in s.chars() {
448        if matches!(c, '.' | '*' | '[' | ']' | '^' | '$' | '\\') {
449            out.push('\\');
450        }
451        out.push(c);
452    }
453    out
454}
455
456/// Where a key's value came from, for the commands whose job is reading
457/// configuration back.
458///
459/// This costs a second git call per key and must never be used on the commit
460/// path — `amont list` and `amont setup` are the only callers, and they
461/// are already asking git several questions to render one screen.
462#[derive(Debug, Clone, Copy, PartialEq, Eq)]
463pub enum Scope {
464    Default,
465    Local,
466    Global,
467    System,
468    CommandLine,
469    /// The value in effect comes from the repository's committed policy.
470    Policy,
471    Other,
472}
473
474impl Scope {
475    pub fn as_str(self) -> &'static str {
476        match self {
477            Scope::Default => "default",
478            Scope::Local => "local",
479            Scope::Global => "global",
480            Scope::System => "system",
481            Scope::CommandLine => "command line",
482            Scope::Policy => "amont.conf",
483            Scope::Other => "other",
484        }
485    }
486}
487
488/// `git config --show-origin --get <key>` → which file it came from.
489///
490/// `Default` for a key nobody set, which is also the answer when git cannot be
491/// asked — the value in use is the shipped one either way.
492pub fn scope_of(settings: &crate::config::Settings, key: &str) -> Scope {
493    // Display mirrors resolution: policy owns the key unless something above
494    // it on the ladder set it. The precedence answer comes from the same
495    // classifier `resolve` uses, never re-derived from file paths.
496    if settings.policy().settings.contains_key(key) && !key_set_above_policy(settings, key) {
497        return Scope::Policy;
498    }
499    let Some(out) = git::output(&["config", "--show-origin", "--get", key]) else {
500        return Scope::Default;
501    };
502    if out.code != 0 {
503        return Scope::Default;
504    }
505    // `<origin>\t<value>`; the origin is `file:/path`, `command line:` or
506    // `blob:…`, and the path is what tells local from global.
507    let origin = out.stdout.split('\t').next().unwrap_or("");
508    if origin.starts_with("command line") {
509        return Scope::CommandLine;
510    }
511    let Some(path) = origin.strip_prefix("file:") else {
512        return Scope::Other;
513    };
514    let path = path.trim();
515    // A repository's own config is the only one inside a `.git` directory;
516    // asking git for the paths rather than guessing at `~` keeps this correct
517    // under `GIT_CONFIG_GLOBAL`, worktrees and `$XDG_CONFIG_HOME`.
518    if same_file(
519        path,
520        git::stdout(&["rev-parse", "--git-path", "config"]).as_deref(),
521    ) {
522        return Scope::Local;
523    }
524    for (flag, scope) in [("--global", Scope::Global), ("--system", Scope::System)] {
525        let listed = git::output(&["config", flag, "--list", "--show-origin"]);
526        if let Some(o) = listed {
527            if o.code == 0
528                && o.stdout
529                    .lines()
530                    .filter_map(|l| l.split('\t').next())
531                    .filter_map(|o| o.strip_prefix("file:"))
532                    .any(|p| same_file(path, Some(p.trim())))
533            {
534                return scope;
535            }
536        }
537    }
538    Scope::Other
539}
540
541/// Compare two paths as the same file where the filesystem can say so, falling
542/// back to the strings. `--git-path` answers relatively (`.git/config`) while
543/// `--show-origin` may answer absolutely, so a string comparison alone
544/// misreports a local key as `other`.
545fn same_file(a: &str, b: Option<&str>) -> bool {
546    let Some(b) = b else { return false };
547    if a == b {
548        return true;
549    }
550    match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
551        (Ok(x), Ok(y)) => x == y,
552        _ => false,
553    }
554}
555
556#[cfg(test)]
557mod tests {
558    use super::*;
559
560    /// The distinction the whole module exists for: git's two failure exits
561    /// mean opposite things, and `first_line` is what a reader is shown for
562    /// the one that is a mistake.
563    #[test]
564    fn a_fatal_line_is_reported_without_its_prefix() {
565        assert_eq!(
566            first_line("fatal: bad numeric config value 'wide' for 'a.b'"),
567            "bad numeric config value 'wide' for 'a.b'"
568        );
569        assert_eq!(first_line("first\nsecond"), "first");
570    }
571
572    /// A warning that names no cause is a puzzle, so there is always a cause.
573    #[test]
574    fn an_empty_diagnostic_still_says_something() {
575        assert!(!first_line("").is_empty());
576        assert!(!first_line("   \n  ").is_empty());
577    }
578
579    #[test]
580    fn a_key_name_is_escaped_before_it_becomes_a_pattern() {
581        // Without escaping, `.` matches any character and the prefix would
582        // also select `amontXcommit.*`.
583        assert_eq!(regex_escape("amont.commit."), "amont\\.commit\\.");
584        assert_eq!(regex_escape("plain"), "plain");
585    }
586
587    /// Git lowercases the names it prints, so a presence test that respected
588    /// case would answer "not set" for every camelCase key we ship.
589    #[test]
590    fn presence_is_case_insensitive_because_git_lowercases_names() {
591        let names: BTreeSet<String> = ["amont.commit.subjectmax".to_string()]
592            .into_iter()
593            .collect();
594        assert!(is_present(&names, "amont.commit.subjectMax"));
595        assert!(is_present(&names, "AMONT.COMMIT.SUBJECTMAX"));
596        assert!(!is_present(&names, "amont.commit.bodyWrap"));
597    }
598
599    #[test]
600    fn every_scope_has_a_name() {
601        for s in [
602            Scope::Default,
603            Scope::Local,
604            Scope::Global,
605            Scope::System,
606            Scope::CommandLine,
607            Scope::Other,
608        ] {
609            assert!(!s.as_str().is_empty());
610        }
611    }
612}