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}
219
220/// `amont run --quiet` or `--raw`.
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub enum QuietOverride {
223 Quiet,
224 Raw,
225}
226
227impl Settings {
228 /// Decide `greengate.quiet` for this run, ahead of the configuration:
229 /// `amont run --quiet` / `--raw`. Only before anything has read it —
230 /// a read first would have fixed the answer, and the flag would do
231 /// nothing; that is a bug in the caller, not a configuration.
232 pub fn override_quiet(&self, mode: QuietOverride) {
233 let quiet = match mode {
234 QuietOverride::Quiet => true,
235 QuietOverride::Raw => false,
236 };
237 self.quiet
238 .set(quiet)
239 .expect("greengate.quiet was read before --quiet/--raw could decide it");
240 }
241
242 /// The policy a trusted manifest declared — empty when nothing was
243 /// declared or the manifest was not trusted. `manifest::load` decides
244 /// that and hands the answer here.
245 pub fn new(policy: crate::policy::Policy) -> Self {
246 Self {
247 policy,
248 ..Self::default()
249 }
250 }
251
252 pub fn policy(&self) -> &crate::policy::Policy {
253 &self.policy
254 }
255
256 /// A fresh `Settings` over the same policy, with empty caches.
257 ///
258 /// For a spawned thread, which cannot borrow this one. It resolves the
259 /// same answers — same policy, same git config — and it resolves them
260 /// LAZILY, which is the property that matters: a paint or heartbeat
261 /// thread that never lives long enough to read a budget must not have
262 /// cost a `git config` spawn for it up front. Handing the thread
263 /// pre-resolved numbers did exactly that, and `spawn_budget` said so.
264 pub fn for_thread(&self) -> Settings {
265 Settings::new(self.policy.clone())
266 }
267}
268
269pub fn boolean(settings: &crate::config::Settings, key: &str) -> Value<bool> {
270 match resolve(settings, key, Some("bool")) {
271 Value::Set(v) => match v.as_str() {
272 "true" => Value::Set(true),
273 "false" => Value::Set(false),
274 other => Value::Bad {
275 why: format!("git normalised it to {other:?}, which is neither true nor false"),
276 },
277 },
278 Value::Unset => Value::Unset,
279 Value::Bad { why } => Value::Bad { why },
280 }
281}
282
283/// An integer, in git's own spelling — which includes the `k`/`m`/`g` suffixes
284/// git accepts, since `--type=int` expands them before we see them.
285pub fn integer(settings: &crate::config::Settings, key: &str) -> Value<i64> {
286 match resolve(settings, key, Some("int")) {
287 Value::Set(v) => match v.parse::<i64>() {
288 Ok(n) => Value::Set(n),
289 Err(_) => Value::Bad {
290 why: format!("git returned {v:?}, which is not a whole number"),
291 },
292 },
293 Value::Unset => Value::Unset,
294 Value::Bad { why } => Value::Bad { why },
295 }
296}
297
298/// One of a fixed set of words, compared case-insensitively.
299///
300/// Git has no `--type` for this, so the value is read raw and checked here —
301/// which means this is the one reader whose `Bad` message is ours. It names
302/// every accepted spelling, because a rejection that does not say what was
303/// wanted sends the reader to the documentation for a list we already hold.
304pub fn enumerated(
305 settings: &crate::config::Settings,
306 key: &str,
307 allowed: &[&'static str],
308) -> Value<&'static str> {
309 match resolve(settings, key, None) {
310 Value::Set(v) => {
311 let got = v.trim().to_ascii_lowercase();
312 match allowed.iter().find(|a| a.eq_ignore_ascii_case(&got)) {
313 Some(hit) => Value::Set(hit),
314 None => Value::Bad {
315 why: format!("{got:?} is not one of {}", allowed.join(", ")),
316 },
317 }
318 }
319 Value::Unset => Value::Unset,
320 Value::Bad { why } => Value::Bad { why },
321 }
322}
323
324/// Say once, per key, that a configured value could not be used.
325///
326/// Deduplicated because a key read twice in one run is a detail of how the
327/// code is arranged, and repeating the warning would make it look like two
328/// separate mistakes.
329/// A free-form string key, policy-aware. Untyped reads have no `--type`
330/// for git to refuse, so `Bad` cannot arise — this is Set-or-not.
331pub fn string_value(settings: &crate::config::Settings, key: &str) -> Option<String> {
332 match resolve(settings, key, None) {
333 Value::Set(v) => Some(v),
334 _ => None,
335 }
336}
337
338pub fn complain(key: &str, why: &str, using: &str) {
339 static SAID: OnceLock<Mutex<BTreeSet<String>>> = OnceLock::new();
340 let said = SAID.get_or_init(|| Mutex::new(BTreeSet::new()));
341 // A poisoned mutex means another thread panicked mid-insert; warning twice
342 // is strictly better than joining it in panicking.
343 let fresh = match said.lock() {
344 Ok(mut set) => set.insert(key.to_string()),
345 Err(_) => true,
346 };
347 if fresh {
348 eprintln!(
349 "{} {}: {why} — using {using}",
350 warning_sign().trim(),
351 highlight(key)
352 );
353 }
354}
355
356pub fn boolean_or(settings: &crate::config::Settings, key: &str, default: bool) -> bool {
357 match boolean(settings, key) {
358 Value::Set(v) => v,
359 Value::Unset => default,
360 Value::Bad { why } => {
361 complain(key, &why, &default.to_string());
362 default
363 }
364 }
365}
366
367/// An integer, clamped to what the setting can actually mean.
368///
369/// Out of range is treated exactly as unparseable: a `subjectMax` of 0 would
370/// block every commit forever from a config file, and one of 10_000 is not a
371/// limit. Both are mistakes, and both get the default plus a line saying so.
372pub fn integer_or(
373 settings: &crate::config::Settings,
374 key: &str,
375 default: i64,
376 range: RangeInclusive<i64>,
377) -> i64 {
378 match integer(settings, key) {
379 Value::Set(v) if range.contains(&v) => v,
380 Value::Set(v) => {
381 complain(
382 key,
383 &format!("{v} is outside {}..={}", range.start(), range.end()),
384 &default.to_string(),
385 );
386 default
387 }
388 Value::Unset => default,
389 Value::Bad { why } => {
390 complain(key, &why, &default.to_string());
391 default
392 }
393 }
394}
395
396/// The `greengate.*` rows of `git config --show-scope`, as (scope, lowercased
397/// key, value): one scan per `Settings`, shared by every host key read and by
398/// the slots crate's `HostSizing::resolve`. `None` when git cannot report
399/// config scopes.
400pub fn host_rows(settings: &crate::config::Settings) -> Option<&[greenharness_slots::host::Row]> {
401 settings
402 .host
403 .get_or_init(|| {
404 // The crate's reader: exit 1 (no `greengate.*` key at all) is no
405 // rows, not "git cannot report scopes".
406 let out = git::output(&greenharness_slots::host::GIT_ARGS)?;
407 greenharness_slots::host::rows_from(Some(out.code), out.stdout.as_bytes())
408 })
409 .as_deref()
410}
411
412/// A HOST key: a setting that describes the machine — how many heavy checks
413/// it runs at once, how far its load may stretch a budget — and so is read
414/// from `--global` or `--system` config only (ADR-0009). A value set in a
415/// repository is ignored with one warning naming the scope to use: two
416/// repositories that disagreed about the host's slot count would each take
417/// slots the other never sees. An environment variable named after the key
418/// (`greengate.idleLoadScale` → `GREENGATE_IDLE_LOAD_SCALE`) outranks both, which
419/// is the precedence `cli.config.precedence` gives it: flag or environment,
420/// then the person's config, then the system's, then the default. The
421/// `amont.conf` policy ladder does not apply: a committed file cannot set
422/// a host key.
423///
424/// One `--show-scope` scan per `Settings`, run on the first host key read
425/// and never before: `greengate.idleLoadScale` is read when the first observed
426/// tool of any check is spawned, so a commit that runs no tool spawns
427/// nothing for it and one that does pays exactly one spawn, pinned by
428/// `spawn_budget.rs`.
429pub fn host_integer_or(
430 settings: &crate::config::Settings,
431 key: &str,
432 default: i64,
433 range: RangeInclusive<i64>,
434) -> i64 {
435 let accept = |raw: &str, source: &str| -> Option<i64> {
436 match raw.trim().parse::<i64>() {
437 Ok(v) if range.contains(&v) => Some(v),
438 Ok(v) => {
439 complain(
440 key,
441 &format!(
442 "{v} ({source}) is outside {}..={}",
443 range.start(),
444 range.end()
445 ),
446 &default.to_string(),
447 );
448 None
449 }
450 Err(_) => {
451 complain(
452 key,
453 &format!("{raw:?} ({source}) is not a whole number"),
454 &default.to_string(),
455 );
456 None
457 }
458 }
459 };
460 let env_name = host_env_name(key);
461 if let Some(raw) = std::env::var(&env_name)
462 .ok()
463 .filter(|v| !v.trim().is_empty())
464 {
465 if let Some(v) = accept(&raw, &env_name) {
466 return v;
467 }
468 }
469 let Some(rows) = host_rows(settings) else {
470 // A git too old for `--show-scope`: the default, said once.
471 complain(key, "git cannot report config scopes", &default.to_string());
472 return default;
473 };
474 let wanted = key.to_ascii_lowercase();
475 let host = rows
476 .iter()
477 .rev()
478 .find(|(scope, k, _)| *k == wanted && (scope == "global" || scope == "system"));
479 if host.is_none() && rows.iter().any(|(_, k, _)| *k == wanted) {
480 complain(
481 key,
482 "is set in this repository's config, but a host key is read from --global or \
483 --system only",
484 &default.to_string(),
485 );
486 }
487 host.and_then(|(scope, _, v)| accept(v, scope))
488 .unwrap_or(default)
489}
490
491/// `greengate.idleLoadScale` → `GREENGATE_IDLE_LOAD_SCALE`: the environment name a
492/// host key answers to.
493pub fn host_env_name(key: &str) -> String {
494 let mut out = String::from(crate::names::ENV_PREFIX);
495 for part in key
496 .trim_start_matches(crate::names::CONFIG_PREFIX)
497 .split('.')
498 {
499 out.push('_');
500 for c in part.chars() {
501 if c.is_ascii_uppercase() {
502 out.push('_');
503 }
504 out.push(c.to_ascii_uppercase());
505 }
506 }
507 out
508}
509
510#[cfg(test)]
511mod host_key_tests {
512 /// The slots crate hardcodes the sizing key names (it sits below this
513 /// crate and cannot call `host_env_name`); they must not drift.
514 #[test]
515 fn the_slots_crate_names_match_host_env_name() {
516 use greenharness_slots::host::{CORES_ENV, CORES_KEY, SLOTS_ENV, SLOTS_KEY};
517 assert_eq!(super::host_env_name(CORES_KEY), CORES_ENV);
518 assert_eq!(super::host_env_name(SLOTS_KEY), SLOTS_ENV);
519 assert!(CORES_KEY.starts_with(crate::names::CONFIG_PREFIX));
520 assert!(SLOTS_KEY.starts_with(crate::names::CONFIG_PREFIX));
521 }
522
523 #[test]
524 fn a_host_key_names_its_environment_variable() {
525 use super::host_env_name;
526 assert_eq!(
527 host_env_name("greengate.idleLoadScale"),
528 "GREENGATE_IDLE_LOAD_SCALE"
529 );
530 assert_eq!(host_env_name("greengate.hostSlots"), "GREENGATE_HOST_SLOTS");
531 assert_eq!(host_env_name("greengate.timeout"), "GREENGATE_TIMEOUT");
532 assert_eq!(
533 host_env_name("greengate.commit.bodyWrap"),
534 "GREENGATE_COMMIT_BODY_WRAP"
535 );
536 }
537}
538
539pub fn enumerated_or(
540 settings: &crate::config::Settings,
541 key: &str,
542 allowed: &[&'static str],
543 default: &'static str,
544) -> &'static str {
545 match enumerated(settings, key, allowed) {
546 Value::Set(v) => v,
547 Value::Unset => default,
548 Value::Bad { why } => {
549 complain(key, &why, default);
550 default
551 }
552 }
553}
554
555/// Which keys under `prefix` are set at all — one git call for the whole
556/// family.
557///
558/// This runs on the commit path, where four independent `--get` calls would be
559/// four processes spent discovering that nobody has configured anything. One
560/// `--get-regexp` answers that, and only the keys it names are read for real.
561/// Same shape as `registry::Overrides::read`, for the same reason.
562///
563/// **Names come back lowercased.** Git lowercases the section and key parts of
564/// every name it prints, so `greengate.commit.subjectMax` is reported as
565/// `greengate.commit.subjectmax`. Keys are case-insensitive on lookup, so this
566/// only affects comparison here — hence [`is_present`] rather than a bare
567/// `contains`.
568pub fn present(settings: &crate::config::Settings, prefix: &str) -> BTreeSet<String> {
569 let pattern = format!("^{}", regex_escape(prefix));
570 let policy_names = || -> BTreeSet<String> {
571 settings
572 .policy()
573 .settings
574 .keys()
575 .filter(|k| {
576 k.to_ascii_lowercase()
577 .starts_with(&prefix.to_ascii_lowercase())
578 })
579 .map(|k| k.to_ascii_lowercase())
580 .collect()
581 };
582 let Some(out) = git::output(&["config", "--get-regexp", &pattern]) else {
583 return policy_names();
584 };
585 if out.code != 0 {
586 return policy_names();
587 }
588 let mut names: BTreeSet<String> = out
589 .stdout
590 .lines()
591 .filter_map(|l| l.split_whitespace().next())
592 .map(|k| k.to_ascii_lowercase())
593 .collect();
594 names.extend(
595 settings
596 .policy()
597 .settings
598 .keys()
599 .filter(|k| {
600 k.to_ascii_lowercase()
601 .starts_with(&prefix.to_ascii_lowercase())
602 })
603 .map(|k| k.to_ascii_lowercase()),
604 );
605 names
606}
607
608/// Is `key` among the names [`present`] returned? Case-insensitive, because
609/// git config key names are.
610pub fn is_present(names: &BTreeSet<String>, key: &str) -> bool {
611 names.contains(&key.to_ascii_lowercase())
612}
613
614/// Escape the characters a config key can hold that a POSIX basic regex would
615/// otherwise read as syntax. Only `.` occurs in practice; the rest are here so
616/// this cannot become wrong if a caller passes something else.
617fn regex_escape(s: &str) -> String {
618 let mut out = String::with_capacity(s.len() * 2);
619 for c in s.chars() {
620 if matches!(c, '.' | '*' | '[' | ']' | '^' | '$' | '\\') {
621 out.push('\\');
622 }
623 out.push(c);
624 }
625 out
626}
627
628/// Where a key's value came from, for the commands whose job is reading
629/// configuration back.
630///
631/// This costs a second git call per key and must never be used on the commit
632/// path — `amont list` and `amont setup` are the only callers, and they
633/// are already asking git several questions to render one screen.
634#[derive(Debug, Clone, Copy, PartialEq, Eq)]
635pub enum Scope {
636 Default,
637 Local,
638 Global,
639 System,
640 CommandLine,
641 /// The value in effect comes from the repository's committed policy.
642 Policy,
643 Other,
644}
645
646impl Scope {
647 pub fn as_str(self) -> &'static str {
648 match self {
649 Scope::Default => "default",
650 Scope::Local => "local",
651 Scope::Global => "global",
652 Scope::System => "system",
653 Scope::CommandLine => "command line",
654 Scope::Policy => "amont.conf",
655 Scope::Other => "other",
656 }
657 }
658}
659
660/// `git config --show-origin --get <key>` → which file it came from.
661///
662/// `Default` for a key nobody set, which is also the answer when git cannot be
663/// asked — the value in use is the shipped one either way.
664pub fn scope_of(settings: &crate::config::Settings, key: &str) -> Scope {
665 // Display mirrors resolution: policy owns the key unless something above
666 // it on the ladder set it. The precedence answer comes from the same
667 // classifier `resolve` uses, never re-derived from file paths.
668 if settings.policy().settings.contains_key(key) && !key_set_above_policy(settings, key) {
669 return Scope::Policy;
670 }
671 let Some(out) = git::output(&["config", "--show-origin", "--get", key]) else {
672 return Scope::Default;
673 };
674 if out.code != 0 {
675 return Scope::Default;
676 }
677 // `<origin>\t<value>`; the origin is `file:/path`, `command line:` or
678 // `blob:…`, and the path is what tells local from global.
679 let origin = out.stdout.split('\t').next().unwrap_or("");
680 if origin.starts_with("command line") {
681 return Scope::CommandLine;
682 }
683 let Some(path) = origin.strip_prefix("file:") else {
684 return Scope::Other;
685 };
686 let path = path.trim();
687 // A repository's own config is the only one inside a `.git` directory;
688 // asking git for the paths rather than guessing at `~` keeps this correct
689 // under `GIT_CONFIG_GLOBAL`, worktrees and `$XDG_CONFIG_HOME`.
690 if same_file(
691 path,
692 git::stdout(&["rev-parse", "--git-path", "config"]).as_deref(),
693 ) {
694 return Scope::Local;
695 }
696 for (flag, scope) in [("--global", Scope::Global), ("--system", Scope::System)] {
697 let listed = git::output(&["config", flag, "--list", "--show-origin"]);
698 if let Some(o) = listed {
699 if o.code == 0
700 && o.stdout
701 .lines()
702 .filter_map(|l| l.split('\t').next())
703 .filter_map(|o| o.strip_prefix("file:"))
704 .any(|p| same_file(path, Some(p.trim())))
705 {
706 return scope;
707 }
708 }
709 }
710 Scope::Other
711}
712
713/// Compare two paths as the same file where the filesystem can say so, falling
714/// back to the strings. `--git-path` answers relatively (`.git/config`) while
715/// `--show-origin` may answer absolutely, so a string comparison alone
716/// misreports a local key as `other`.
717fn same_file(a: &str, b: Option<&str>) -> bool {
718 let Some(b) = b else { return false };
719 if a == b {
720 return true;
721 }
722 match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
723 (Ok(x), Ok(y)) => x == y,
724 _ => false,
725 }
726}
727
728#[cfg(test)]
729mod tests {
730 use super::*;
731
732 /// The distinction the whole module exists for: git's two failure exits
733 /// mean opposite things, and `first_line` is what a reader is shown for
734 /// the one that is a mistake.
735 #[test]
736 fn a_fatal_line_is_reported_without_its_prefix() {
737 assert_eq!(
738 first_line("fatal: bad numeric config value 'wide' for 'a.b'"),
739 "bad numeric config value 'wide' for 'a.b'"
740 );
741 assert_eq!(first_line("first\nsecond"), "first");
742 }
743
744 /// A warning that names no cause is a puzzle, so there is always a cause.
745 #[test]
746 fn an_empty_diagnostic_still_says_something() {
747 assert!(!first_line("").is_empty());
748 assert!(!first_line(" \n ").is_empty());
749 }
750
751 #[test]
752 fn a_key_name_is_escaped_before_it_becomes_a_pattern() {
753 // Without escaping, `.` matches any character and the prefix would
754 // also select `amontXcommit.*`.
755 assert_eq!(regex_escape("greengate.commit."), "greengate\\.commit\\.");
756 assert_eq!(regex_escape("plain"), "plain");
757 }
758
759 /// Git lowercases the names it prints, so a presence test that respected
760 /// case would answer "not set" for every camelCase key we ship.
761 #[test]
762 fn presence_is_case_insensitive_because_git_lowercases_names() {
763 let names: BTreeSet<String> = ["greengate.commit.subjectmax".to_string()]
764 .into_iter()
765 .collect();
766 assert!(is_present(&names, "greengate.commit.subjectMax"));
767 assert!(is_present(&names, "GREENGATE.COMMIT.SUBJECTMAX"));
768 assert!(!is_present(&names, "greengate.commit.bodyWrap"));
769 }
770
771 #[test]
772 fn every_scope_has_a_name() {
773 for s in [
774 Scope::Default,
775 Scope::Local,
776 Scope::Global,
777 Scope::System,
778 Scope::CommandLine,
779 Scope::Other,
780 ] {
781 assert!(!s.as_str().is_empty());
782 }
783 }
784}