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