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