greengate_runtime/lib.rs
1//! The git-templates hook logic: registry, dispatchers and every check.
2//!
3//! This is a library so that more than one binary can hold the same truth about
4//! what a hook IS. `amont` (the commit path) executes the checks;
5//! `amont-fleet` reports on how they are installed across the fleet. Before
6//! the split there was no lib target at all, which is why `cargo test --lib`
7//! failed outright.
8//!
9//! **This crate gains no third-party dependency.** The hook binary depends on
10//! it, so anything added here reaches every commit transitively. The one
11//! crate it links is `git-attest`, attest's std-only implementation of the
12//! attestation format (decisions ADR-0037), argued in Cargo.toml and checked
13//! by `scripts/check-no-deps.sh`. ratatui and friends belong in `amont-fleet`.
14//!
15//! Hooks are invoked through a thin `sh` shim at each hook path, which passes
16//! the hooks directory it lives in:
17//!
18//! ```text
19//! amont --hooks-dir <dir> pre-commit [args…]
20//! ```
21
22/// Serialises every test that moves the process cwd **or depends on it**.
23///
24/// The second half of that sentence was missing, and it cost a day. The
25/// lock started as "movers only" — `gate_stamp` and `attest`, which both
26/// talk to "the repository at cwd" and each carried its own mutex, so each
27/// was serialised against itself and raced against the other. But a mover
28/// is only half the hazard: a test that READS the ambient cwd is just as
29/// exposed, because production code spawns git without `-C`. While
30/// `gate_stamp` held cwd inside its fixture, `restage_distinguishes_
31/// nothing_from_failure` ran `git add` — landing in that fixture and
32/// taking its `.git/index.lock`, so the fixture's own `git commit` failed
33/// 128 and the panic surfaced three lines later as a missing gate stamp.
34/// Roughly one run in forty, and unreadable until the fixtures started
35/// reporting git's exit status.
36///
37/// So: if a test moves the cwd, or calls anything that spawns git without
38/// naming a directory, it takes this lock.
39#[cfg(test)]
40pub(crate) static TEST_CWD: std::sync::Mutex<()> = std::sync::Mutex::new(());
41
42pub mod agents_md;
43pub mod attest;
44pub mod attest_inputs;
45pub mod bypass;
46pub mod capture;
47pub mod check;
48pub mod clock;
49pub mod cluster;
50pub mod commit_style;
51pub mod config;
52pub mod content;
53pub mod dispatch;
54pub mod downgrade;
55pub mod excerpt;
56pub mod finding;
57pub mod gate_evidence;
58pub mod gate_identity;
59pub mod gate_stamp;
60pub mod git;
61pub mod hookfile;
62pub mod hooks;
63pub mod host_slots;
64pub mod install;
65pub mod json;
66pub mod json_read;
67pub mod land;
68pub mod live;
69pub mod load;
70pub mod manifest;
71pub mod names;
72pub mod pack;
73pub mod policy;
74pub mod proctree;
75pub mod pushed_tree;
76pub mod pushrefs;
77pub mod registry;
78pub mod rehearsal;
79pub mod run_stamp;
80pub mod setup;
81pub mod skew;
82pub mod slot_cmd;
83pub mod snapshot_prep;
84pub mod staged_only;
85pub mod tree_cache;
86pub mod tree_lint;
87pub mod tree_run;
88pub mod tree_skew;
89pub mod trust;
90pub mod ui;
91pub mod vocabulary;
92pub(crate) mod waves;
93
94use crate::names::BIN;
95use std::io::IsTerminal;
96use std::path::Path;
97use std::process::{Command, Stdio};
98
99/// `git config --get-all hook.skip`, or empty when unset/unavailable.
100/// The two triggers a check can be attached to, as they are spelled in config.
101///
102/// Deliberately the same strings as `Stage::as_str`, and
103/// `every_id_agrees_with_its_declared_stage` keeps them that way.
104pub const TRIGGERS: [&str; 2] = ["pre-commit", "pre-push"];
105
106/// How specifically a configured value names a check.
107///
108/// Ordered, so that when several keys match one check the most specific wins —
109/// which only matters for `amont.severity`, since a skip is a boolean.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
111pub enum Match {
112 /// `pre-commit` — every check on that trigger.
113 Trigger,
114 /// `clippy` — that check, whichever trigger it is on.
115 ShortName,
116 /// `pre-commit-clippy` — this check and no other.
117 FullId,
118}
119
120/// A check's id without its trigger — `pre-commit-clippy` → `clippy`.
121///
122/// For DISPLAY only, wherever the trigger is already established by a heading
123/// or a neighbouring column. Under a `pre-commit` heading, printing
124/// `pre-commit-clippy` on every row spends eleven columns restating what the
125/// heading said. Never write this to config or compare against it: two checks
126/// can share a short name, and telling them apart is what the id is for.
127pub fn short_name(check: &str) -> &str {
128 for trigger in TRIGGERS {
129 if let Some(short) = check
130 .strip_prefix(trigger)
131 .and_then(|rest| rest.strip_prefix('-'))
132 {
133 return short;
134 }
135 }
136 check
137}
138
139/// Does `pattern`, as written in `hook.skip` or `amont.severity.<pattern>`,
140/// name `check`?
141///
142/// A check's id is `<trigger>-<name>`, and exactly three things name it:
143///
144/// | written | means |
145/// |---|---|
146/// | `pre-commit-clippy` | that one check |
147/// | `pre-commit` | every check on that trigger |
148/// | `clippy` | that check, on any trigger |
149///
150/// Three exact comparisons. **No substring.** The previous rule was
151/// `check.contains(skip)`, which made `hook.skip = clippy` work by accident of
152/// reach — and `hook.skip = e` disable all twenty checks by the same accident,
153/// and `lint-js` silently also suppress `lint-json-yaml`. Naming the three
154/// things a user actually means keeps every useful case and removes every
155/// sharp edge, including the one the old doc comment called "not a bug".
156///
157/// This reads the trigger out of the ID, which is not the same as deriving a
158/// check's stage: `Stage` remains a declared field and is what the dispatcher
159/// obeys. Here we are parsing an identifier a human typed.
160///
161/// Defined ONCE because four callers need it — the dispatcher decides what
162/// runs, the severity resolver decides what blocks, the fleet view reports
163/// where a check applies, and the skip resolver computes reach. A
164/// reimplementation that disagreed would have the dashboard claim a check is
165/// active while the dispatcher skips it.
166pub fn names_check(check: &str, pattern: &str) -> Option<Match> {
167 if check == pattern {
168 return Some(Match::FullId);
169 }
170 for trigger in TRIGGERS {
171 let Some(short) = check
172 .strip_prefix(trigger)
173 .and_then(|rest| rest.strip_prefix('-'))
174 else {
175 continue;
176 };
177 // An id carries one trigger, so the first that matches is the answer.
178 if pattern == trigger {
179 return Some(Match::Trigger);
180 }
181 if pattern == short {
182 return Some(Match::ShortName);
183 }
184 return None;
185 }
186 None
187}
188
189/// Does `skip`, as configured in `hook.skip`, suppress `check`?
190pub fn skip_suppresses(check: &str, skip: &str) -> bool {
191 names_check(check, skip).is_some()
192}
193
194/// One check, as reported by `amont list`.
195///
196/// Deliberately flat — this is what gets rendered as text or serialised to
197/// JSON, and a reader (human or agent) parsing the latter should not have to
198/// chase nested objects for a yes/no question.
199#[derive(Debug, Clone)]
200pub struct CheckListing {
201 /// `<trigger>-<name>` — what `hook.skip` and `amont.severity.<key>`
202 /// resolve against.
203 pub id: String,
204 pub short_name: String,
205 pub stage: check::Stage,
206 pub source: Source,
207 /// What the check (or manifest line) declared.
208 pub declared_severity: check::Severity,
209 /// For a declared check, what its `amont.conf` line says, trusted or
210 /// not: `declared_severity` reads `warn` for a check that cannot run,
211 /// an untrusted one included, and a reader asking what the repository
212 /// declares needs the line's own word. `None` for a builtin and for a
213 /// line that did not parse.
214 pub manifest_severity: Option<check::Severity>,
215 /// What `registry::Overrides::of` would actually apply — NOT the same as
216 /// `declared_severity` once `amont.severity.*` is configured. This is
217 /// the one thing the old text-only `list_checks` never reported, and the
218 /// exact "declared vs. effective" gap that caused a real bug in the
219 /// fleet's own severity column (see `greengate-fleet/src/severities.rs`).
220 pub effective_severity: check::Severity,
221 pub severity_overridden: bool,
222 /// Where the winning override came from, only when one applies —
223 /// strictly additive next to `severity_overridden`, whose meaning is
224 /// unchanged.
225 pub severity_source: Option<registry::Source>,
226 pub fix: check::Fix,
227 pub status: Status,
228 /// Empty when `status == Status::Runs`; the same prose the text output
229 /// always showed for the other three states.
230 pub reason: String,
231 pub scope_files: Vec<String>,
232 pub scope_opt_in: Vec<String>,
233 /// `Some` only for a declared, `Runnable` external — a builtin has no
234 /// command to show, and an `Unusable` external never got far enough to
235 /// have one.
236 pub command: Option<String>,
237 /// The files a pre-commit declaration fires on only because its push twin
238 /// reads them (`Manifest::resolve_triggers`): the patterns of its
239 /// effective scope that `scope_files` does not list. Empty for every other
240 /// row. A trailing field, so a reader of the columns before it is not
241 /// disturbed.
242 pub scope_from_twin: Vec<String>,
243 /// The id of the push gate whose files `scope_from_twin` lists
244 /// (`pre-push-cargo-test`); `None` when the row is not widened.
245 pub scope_twin: Option<String>,
246}
247
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249pub enum Source {
250 Builtin,
251 Declared,
252}
253
254/// The four states the text output's glyphs already named. Not called
255/// `Outcome` — that type means what a check concluded when it RAN; this means
256/// whether it would run at all, the same question `Scope::matches` answers.
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub enum Status {
259 Runs,
260 Inert,
261 Skipped,
262 Unusable,
263}
264
265pub struct ListOptions {
266 pub json: bool,
267 pub stage: Option<check::Stage>,
268 pub pushed: bool,
269 /// Print the inert checks too, one row each, as this always did.
270 pub all: bool,
271}
272
273/// Every check that would be considered for `stage_filter` (or both stages,
274/// when `None`), evaluated against `paths`.
275///
276/// Reads `hook.skip` and `amont.severity.*` from the current repo's git
277/// config, same as the original `list_checks` did — this is why it is not
278/// unit-tested in isolation; see `hooks/pull_rebase.rs`'s own split between
279/// pure helpers (unit-tested) and config-dependent behaviour (integration
280/// tested) for the precedent.
281pub fn gather_checks(
282 settings: &crate::config::Settings,
283 stage_filter: Option<check::Stage>,
284 paths: &[String],
285 manifest: &manifest::Manifest,
286) -> Vec<CheckListing> {
287 use crate::check::Stage;
288 let stages: Vec<Stage> = match stage_filter {
289 Some(s) => vec![s],
290 None => vec![Stage::PreCommit, Stage::PrePush],
291 };
292 let skips = configured_skips(settings);
293 let overrides = registry::Overrides::read(settings);
294 let externals_by_id: std::collections::BTreeMap<&str, &manifest::External> = manifest
295 .externals
296 .iter()
297 .map(|e| (e.id.as_str(), e))
298 .collect();
299
300 let mut out = Vec::new();
301 for stage in stages {
302 // Externals are listed here too, and marked, because the question
303 // this command answers — "would this run here?" — is asked most
304 // often about the check somebody just added to `amont.conf`.
305 for check in registry::all_stage_checks(stage, manifest) {
306 let name = check.name();
307 let external = externals_by_id.get(name).copied();
308 let skipped = skips.iter().any(|s| skip_suppresses(name, s));
309 let applies = check.scope().matches(paths);
310
311 let unusable_why = external.and_then(|e| match &e.kind {
312 manifest::Kind::Unusable { why, .. } => Some(why.as_str()),
313 manifest::Kind::Runnable { .. } => None,
314 });
315 // Four states: a check that is correctly silent must never look
316 // like one that is disabled, and neither must look like one
317 // whose declaration could not be read.
318 let (status, reason) = if let Some(w) = unusable_why {
319 (Status::Unusable, format!("{} {w}", manifest::MANIFEST))
320 } else if skipped {
321 // Which source? Policy skips read differently from machine
322 // skips — the legend and the fleet detail pane echo this
323 // wording, so the three move together.
324 let via = if settings
325 .policy()
326 .skips
327 .iter()
328 .any(|s| skip_suppresses(name, s))
329 {
330 "skipped via amont.conf"
331 } else {
332 "skipped via hook.skip"
333 };
334 (Status::Skipped, via.to_string())
335 } else if applies {
336 (Status::Runs, String::new())
337 } else {
338 (
339 Status::Inert,
340 format!("inert here — needs {}", describe(check.scope())),
341 )
342 };
343
344 let command = external.and_then(|e| match &e.kind {
345 manifest::Kind::Runnable { program, args, .. } => Some(
346 std::iter::once(program.as_str())
347 .chain(args.iter().map(String::as_str))
348 .collect::<Vec<_>>()
349 .join(" "),
350 ),
351 manifest::Kind::Unusable { .. } => None,
352 });
353
354 // `scope_files` stays what the declaration says; what its push twin
355 // adds is reported beside it, in `scope_from_twin`.
356 let own_scope = match external.map(|e| &e.kind) {
357 Some(manifest::Kind::Runnable { scope, .. }) => *scope,
358 Some(manifest::Kind::Unusable { .. }) | None => check.scope(),
359 };
360 let scope_twin = external.and_then(|e| match &e.kind {
361 manifest::Kind::Runnable {
362 trigger: Some(trigger),
363 ..
364 } => Some(trigger.twin_ids().join(", ")),
365 manifest::Kind::Runnable { .. } | manifest::Kind::Unusable { .. } => None,
366 });
367 let effective_scope = check.scope();
368 let scope_from_twin: Vec<String> = effective_scope
369 .files
370 .iter()
371 .chain(effective_scope.names.iter())
372 .chain(effective_scope.dirs.iter())
373 .filter(|t| {
374 !own_scope.files.contains(t)
375 && !own_scope.names.contains(t)
376 && !own_scope.dirs.contains(t)
377 })
378 .map(|t| t.to_string())
379 .collect();
380 let declared_severity = check.severity();
381 let effective_severity = overrides.of(check);
382 let severity_source = overrides
383 .applied_with_source(name)
384 .map(|(_, _, src)| src)
385 .filter(|_| declared_severity != effective_severity);
386 out.push(CheckListing {
387 id: name.to_string(),
388 short_name: short_name(name).to_string(),
389 stage,
390 source: if external.is_some() {
391 Source::Declared
392 } else {
393 Source::Builtin
394 },
395 declared_severity,
396 manifest_severity: external.and_then(manifest::External::manifest_severity),
397 effective_severity,
398 severity_overridden: declared_severity != effective_severity,
399 severity_source,
400 fix: check.fix(),
401 status,
402 reason,
403 scope_files: own_scope
404 .files
405 .iter()
406 .chain(own_scope.names.iter())
407 .map(|s| s.to_string())
408 .collect(),
409 scope_opt_in: own_scope.opt_in.iter().map(|s| s.to_string()).collect(),
410 command,
411 scope_from_twin,
412 scope_twin,
413 });
414 }
415 }
416 out
417}
418
419/// BYTE-IDENTICAL to what `list_checks` printed before it grew `--json`.
420/// `listings` is already stage-grouped (`gather_checks` iterates stage by
421/// stage), so a heading prints exactly once per stage encountered, in the
422/// same order.
423/// The ecosystem a scope token belongs to, for the inert summary.
424///
425/// Presentational and deliberately incomplete: a token nobody has mapped
426/// simply does not get named, and its check is still counted. The alternative
427/// — a `family` field on every `Builtin` — is thirty-seven places for a label
428/// to drift out of step with the scope that actually decides anything.
429///
430/// Generic tokens (`.yaml`, `.json`) are absent on purpose. Four checks want
431/// `.yaml` for four different reasons, so naming YAML here would tell a reader
432/// their repository is "missing YAML checks" when what it is missing is
433/// Kubernetes.
434fn ecosystem(token: &str) -> Option<&'static str> {
435 Some(match token {
436 ".rs" | "Cargo.toml" | "Cargo.lock" => "Rust",
437 ".go" | "go.mod" | "go.sum" => "Go",
438 ".py"
439 | ".pyi"
440 | "requirements.txt"
441 | "pyproject.toml"
442 | "ruff.toml"
443 | ".ruff.toml"
444 | "pytest.ini"
445 | "conftest.py"
446 | "pyrightconfig.json"
447 | "pyrightconfig.jsonc" => "Python",
448 ".js" | ".jsx" | ".ts" | ".tsx" | ".vue" | "package.json" | "package-lock.json" => {
449 "JavaScript"
450 }
451 "kustomization.yaml" | "kustomization.yml" => "Kubernetes",
452 t if t.starts_with(".kube-linter") => "Kubernetes",
453 t if t.starts_with(".prettierrc") || t == "prettier.config.js" => "JavaScript",
454 _ => return None,
455 })
456}
457
458/// Every check that would run here, and one line for the ones that would not.
459///
460/// The default used to print all thirty-odd rows interleaved alphabetically.
461/// In a repository amont serves well that is about half inert; in one built on
462/// a stack it does not cover yet it is two thirds — and every one of those rows
463/// names somebody else's language. Read top to bottom it says "this tool is for
464/// other people", which is the opposite of true: the checks that DO run are
465/// `secrets`, `large-files` and `merge-conflict`, the ones that prevent
466/// incidents in any repository at all.
467///
468/// So the inert rows collapse to a count and the ecosystems they belong to.
469/// `--all` brings them back, because "why is clippy not running" is a real
470/// question with a real answer already written.
471///
472/// **Skipped and unusable rows are never collapsed.** `⊘` means somebody
473/// silenced a check and `✗` means a declaration is broken; both are things the
474/// reader has to act on, and both would be lost in a count.
475pub fn print_text(listings: &[CheckListing], all: bool) {
476 let shown: Vec<&CheckListing> = listings
477 .iter()
478 .filter(|l| all || l.status != Status::Inert)
479 .collect();
480
481 let mut current: Option<check::Stage> = None;
482 for l in &shown {
483 if current != Some(l.stage) {
484 println!("{}", ui::highlight(l.stage.as_str()));
485 current = Some(l.stage);
486 }
487 let glyph = match l.status {
488 Status::Unusable => '✗',
489 Status::Skipped => '⊘',
490 Status::Runs => '●',
491 Status::Inert => '○',
492 };
493 // The SHORT name: this loop is already inside a `pre-commit` /
494 // `pre-push` heading, so printing the trigger on all twenty rows
495 // restates the heading twenty times and pushes the reason — the part
496 // that differs per row — eleven columns to the right.
497 //
498 // Where a check CAME FROM belongs next to its name, not appended
499 // after a reason that is often empty. A reader scanning this list
500 // wants to know which of these their repository added.
501 // A declared check's name and its reason both come from the
502 // repository's manifest, and `amont list` is read at least as often
503 // as the trust prompt. Sanitised before padding, so the column width is
504 // computed on what is printed — see `ui::sanitize`.
505 let short_name = ui::sanitize(&l.short_name);
506 let label = match l.source {
507 Source::Declared => format!("{short_name} (declared)"),
508 Source::Builtin => short_name,
509 };
510 println!(" {glyph} {label:<26} {}", ui::sanitize(&l.reason));
511 // A declaration that also fires on its push twin's files says which,
512 // and why: piped, every path in full; on a terminal, cut to the
513 // 80 columns the rest of this output keeps.
514 if !l.scope_from_twin.is_empty() {
515 let paths = l
516 .scope_from_twin
517 .iter()
518 .map(|t| ui::sanitize(t))
519 .collect::<Vec<_>>()
520 .join(", ");
521 let read_by = l.scope_twin.as_deref().unwrap_or("its push twin");
522 let prefix = " also fires on ";
523 let suffix = format!(" (read by {})", ui::sanitize(read_by));
524 // Only the paths are cut, on a terminal, so the gate that reads
525 // them stays on the line.
526 if std::io::stdout().is_terminal() {
527 println!("{}", tree_lint::fit_line(prefix, &paths, &suffix));
528 } else {
529 println!("{prefix}{paths}{suffix}");
530 }
531 }
532 }
533
534 let runs = listings.iter().filter(|l| l.status == Status::Runs).count();
535 let inert: Vec<&CheckListing> = listings
536 .iter()
537 .filter(|l| l.status == Status::Inert)
538 .collect();
539
540 println!();
541 if inert.is_empty() {
542 println!(" {runs} active here.");
543 } else if all {
544 println!(" {runs} active here, {} inert.", inert.len());
545 } else {
546 let mut families: Vec<&str> = inert
547 .iter()
548 .flat_map(|l| l.scope_files.iter().chain(l.scope_opt_in.iter()))
549 .filter_map(|t| ecosystem(t))
550 .collect();
551 families.sort_unstable();
552 families.dedup();
553 let named = if families.is_empty() {
554 String::new()
555 } else {
556 format!(" ({})", families.join(", "))
557 };
558 println!(
559 " {runs} active here. {} inert{named} — {BIN} list --all",
560 inert.len()
561 );
562 }
563 println!(" ● runs here ○ inert ⊘ skipped via hook.skip ✗ declaration unusable");
564}
565
566/// What `commit-msg` will enforce here, and where each answer came from.
567///
568/// Printed **always**, not only when something has been configured. The
569/// defaults are the divisive part — a gitmoji in every subject, a 50-character
570/// description — and somebody who wants them changed has no reason to guess
571/// that four keys exist. `amont list` is where they are already looking, so
572/// it is where the dial belongs.
573///
574/// The source column appears only for a value somebody set: repeating
575/// "default" on four rows spends a column restating the line underneath.
576pub fn print_commit_style(style: &commit_style::Style, rows: &[commit_style::Setting]) {
577 println!();
578 println!("{}", ui::highlight("commit style"));
579 for r in rows {
580 let origin = if r.set_here {
581 format!("{} ({})", r.key, r.scope.as_str())
582 } else {
583 String::new()
584 };
585 println!(" {:<18} {:<10} {origin}", r.label, r.value);
586 }
587 println!();
588 for w in style.warnings() {
589 println!(" {} {w}", ui::warning_sign().trim());
590 }
591 println!(" `{BIN} setup` to change any of these");
592}
593
594/// The commit-style block as JSON: the effective value, the shipped default,
595/// whether they differ and where the answer came from — the same
596/// declared-vs-effective shape `CheckListing` uses for severity.
597fn commit_style_json(style: &commit_style::Style, rows: &[commit_style::Setting]) -> String {
598 let setting = |r: &commit_style::Setting, value: String, default: String| {
599 json::object(&[
600 format!("\"value\":{value}"),
601 format!("\"default\":{default}"),
602 json::bool_field("overridden", r.overridden),
603 json::bool_field("set_here", r.set_here),
604 json::string_field("source", r.scope.as_str()),
605 json::string_field("key", r.key),
606 ])
607 };
608 let d = commit_style::Style::default();
609 // `rows` is built in this order by `commit_style::describe`, and the
610 // numbers are emitted as numbers so a reader can compare them.
611 let quoted = |s: &str| format!("\"{}\"", json::escape(s));
612 let fields: Vec<String> = rows
613 .iter()
614 .map(|r| {
615 let (value, default) = match r.key {
616 commit_style::KEY_GITMOJI => {
617 (quoted(style.gitmoji.as_str()), quoted(d.gitmoji.as_str()))
618 }
619 commit_style::KEY_SUBJECT_MAX => {
620 (style.subject_max.to_string(), d.subject_max.to_string())
621 }
622 commit_style::KEY_DESCRIPTION_MAX => (
623 style.description_max.to_string(),
624 d.description_max.to_string(),
625 ),
626 _ => (style.body_wrap.to_string(), d.body_wrap.to_string()),
627 };
628 let name = r.key.rsplit('.').next().unwrap_or(r.key);
629 format!("\"{}\":{}", json::escape(name), setting(r, value, default))
630 })
631 .collect();
632
633 let warnings: Vec<String> = style.warnings();
634 let mut all = fields;
635 all.push(json::string_array_field("warnings", &warnings));
636 json::object(&all)
637}
638
639/// The format id this document declares, as its first field.
640///
641/// Every other machine-readable thing this tool writes carries one and
642/// REFUSES what it does not recognise — `amont-gate-v1`, `amont-held-v1`,
643/// `amont-skew-v1`, `amont-bypasses-v1`, and `amont-attest-v2`, whose bump
644/// exists precisely so a v1 verifier reads a v2 note as no note rather than
645/// misreading it. This document, the most public machine surface of the
646/// three, carried none: a reader had no way to state which contract it was
647/// written against, so a rename here would land as a silently different
648/// answer rather than a failure. Bump the version when a field's MEANING
649/// changes or one is removed; adding a field keeps it, which is what the
650/// object shape below was already for.
651pub const LIST_FORMAT: &str = "amont-list-v1";
652
653/// `{"format": "amont-list-v1", "stage_filter": ..., "checks": [...]}` — an
654/// object, not a bare array, so a field can be added later without changing
655/// the top-level shape.
656pub fn print_json(
657 settings: &crate::config::Settings,
658 stage_filter: Option<check::Stage>,
659 pushed: bool,
660 listings: &[CheckListing],
661 bypasses: &bypass::Ledger,
662 downgrades: &downgrade::Ledger,
663 conventions_apply: bool,
664) {
665 let checks: Vec<String> = listings
666 .iter()
667 .map(|l| {
668 json::object(&[
669 json::string_field("id", &l.id),
670 json::string_field("short_name", &l.short_name),
671 json::string_field("stage", l.stage.as_str()),
672 json::string_field(
673 "source",
674 match l.source {
675 Source::Builtin => "builtin",
676 Source::Declared => "declared",
677 },
678 ),
679 json::string_field("declared_severity", l.declared_severity.as_str()),
680 json::opt_string_field(
681 "manifest_severity",
682 l.manifest_severity.map(check::Severity::as_str),
683 ),
684 json::string_field("effective_severity", l.effective_severity.as_str()),
685 json::bool_field("severity_overridden", l.severity_overridden),
686 json::opt_string_field(
687 "severity_source",
688 l.severity_source.map(registry::Source::as_str),
689 ),
690 json::string_field("fix", l.fix.as_str()),
691 json::string_field(
692 "status",
693 match l.status {
694 Status::Runs => "runs",
695 Status::Inert => "inert",
696 Status::Skipped => "skipped",
697 Status::Unusable => "unusable",
698 },
699 ),
700 json::string_field("reason", &l.reason),
701 json::string_array_field("scope_files", &l.scope_files),
702 json::string_array_field("scope_opt_in", &l.scope_opt_in),
703 json::opt_string_field("command", l.command.as_deref()),
704 json::string_array_field("scope_from_twin", &l.scope_from_twin),
705 json::opt_string_field("scope_twin", l.scope_twin.as_deref()),
706 ])
707 })
708 .collect();
709
710 let (style, rows) = commit_style::describe(settings);
711 println!(
712 "{}",
713 json::object(&[
714 json::string_field("format", LIST_FORMAT),
715 json::opt_string_field("stage_filter", stage_filter.map(check::Stage::as_str)),
716 json::bool_field("pushed", pushed),
717 format!("\"checks\":{}", json::array(&checks)),
718 format!("\"commit_style\":{}", commit_style_json(&style, &rows)),
719 format!("\"branch_style\":{}", branch_style_json()),
720 format!("\"bypasses\":{}", bypasses_json(bypasses)),
721 format!("\"downgrades\":{}", downgrades_json(downgrades)),
722 json::bool_field("conventions_apply", conventions_apply),
723 format!("\"installed\":{}", install::installed_here().to_json()),
724 format!(
725 "\"template_dir\":{}",
726 install::installed_in_template_dir().to_json()
727 ),
728 ])
729 );
730}
731
732/// `{"total": N, "last": <epoch|null>, "by_script": [...]}` — the ledger of
733/// unverified commits, so a parsing reader (the fleet, an agent) sees the
734/// same numbers `amont list` prints.
735fn downgrades_json(l: &downgrade::Ledger) -> String {
736 let by_check: Vec<String> = l
737 .by_check
738 .iter()
739 .map(|c| {
740 json::object(&[
741 json::string_field("check", &c.check),
742 json::int_field("count", c.count as i64),
743 json::int_field("would_block", c.would_block as i64),
744 json::int_field("last", c.last as i64),
745 ])
746 })
747 .collect();
748 json::object(&[
749 json::int_field("total", l.total as i64),
750 json::int_field("would_block", l.would_block as i64),
751 json::int_field("commits", l.commits as i64),
752 json::opt_int_field("first", l.first.map(|v| v as i64)),
753 json::opt_int_field("last", l.last.map(|v| v as i64)),
754 format!("\"by_check\":{}", json::array(&by_check)),
755 ])
756}
757
758fn bypasses_json(l: &bypass::Ledger) -> String {
759 let by_script: Vec<String> = l
760 .by_script
761 .iter()
762 .map(|s| {
763 json::object(&[
764 json::string_field("script", &s.script),
765 json::int_field("count", s.count as i64),
766 json::int_field("last", s.last as i64),
767 ])
768 })
769 .collect();
770 json::object(&[
771 json::int_field("total", l.total as i64),
772 json::opt_int_field("last", l.last.map(|v| v as i64)),
773 format!("\"by_script\":{}", json::array(&by_script)),
774 ])
775}
776
777/// The branch contract, in the same document agents are told to consult — so
778/// the pattern is knowable BEFORE a branch is created rather than discovered
779/// at push time. Rendered from `vocabulary::BRANCH_PREFIXES`, the same table
780/// `pre-push-branch-pattern` enforces: there is no second copy to drift.
781fn branch_style_json() -> String {
782 let prefixes: Vec<String> = vocabulary::BRANCH_PREFIXES
783 .iter()
784 .map(|p| p.name.to_string())
785 .collect();
786 json::object(&[
787 json::string_field("shape", "<prefix>/<name>"),
788 json::string_field("pattern", &vocabulary::branch_contract()),
789 json::string_array_field("prefixes", &prefixes),
790 ])
791}
792
793/// `git ls-files` — every check's default scope evaluation, unchanged from
794/// what `list_checks` always did.
795///
796/// Through `git::stdout_paths`, i.e. with `-z`. A raw `ls-files` QUOTES any
797/// path holding an unusual byte: `é.json` comes back as the nine-byte literal
798/// `"\303\251.json"`, which ends with a quote rather than an extension, so
799/// `Scope::matches` reports a check as irrelevant to a repository it plainly
800/// covers. Cosmetic here (this only decides what `list` prints) and not
801/// cosmetic in `dispatch::enter_all_files_mode`, which is the same bug — so
802/// both ask the same way.
803pub(crate) fn tracked_paths() -> Vec<String> {
804 git::stdout_paths(&["ls-files"]).unwrap_or_default()
805}
806
807/// The pushed-range file list, computed standalone rather than from a real
808/// pre-push invocation's stdin.
809///
810/// Reuses `pushrefs::changed_files`, which already handles zero-oid deletes,
811/// merge commits and the `--stdin` trailing-newline edge case — this only
812/// SYNTHESISES the one `PushRef` a standalone invocation has no other way to
813/// obtain.
814fn pushed_paths() -> Result<Vec<String>, String> {
815 let synthetic = pushrefs::synthetic_from_upstream()?;
816 Ok(pushrefs::changed_files(&[synthetic]))
817}
818
819/// `amont list`: what would run here, and why — as prose, or as
820/// `--json` for a reader that wants to parse it.
821pub fn list_checks(opts: ListOptions) -> i32 {
822 let paths = if opts.pushed {
823 match pushed_paths() {
824 Ok(p) => p,
825 Err(msg) => {
826 if opts.json {
827 println!("{}", json::object(&[json::string_field("error", &msg)]));
828 } else {
829 eprintln!("{BIN}: {msg}");
830 }
831 return 2;
832 }
833 }
834 } else {
835 tracked_paths()
836 };
837 // Loaded HERE, with the repository this command is standing in — the
838 // owned-manifest shape every entrypoint now follows. See manifest::load.
839 // The policy is OWNED here and borrowed downstream. The invariant that
840 // used to be a comment — install immediately after load, before any
841 // config read — is now the borrow checker's: nothing downstream can read
842 // configuration without being handed this. `load_resolved` also resolves
843 // the commit-time triggers.
844 let (manifest, settings) =
845 manifest::load_resolved(std::path::Path::new(&hooks::common::repo_root()));
846 let listings = gather_checks(&settings, opts.stage, &paths, &manifest);
847 let bypasses = bypass::read();
848 let downgrades = downgrade::read();
849 let conventions_apply = dispatch::conventions_apply(&settings, &manifest);
850 if opts.json {
851 print_json(
852 &settings,
853 opts.stage,
854 opts.pushed,
855 &listings,
856 &bypasses,
857 &downgrades,
858 conventions_apply,
859 );
860 } else {
861 print_text(&listings, opts.all);
862 // Not filtered by `--stage`: commit style belongs to no stage, and
863 // suppressing it for `--stage pre-push` would only hide it from the
864 // reader who narrowed their question.
865 let (style, rows) = commit_style::describe(&settings);
866 print_commit_style(&style, &rows);
867 print_bypasses(&bypasses);
868 print_downgrades(&downgrades);
869 if !conventions_apply {
870 println!(
871 "\n ! conventions held back — no amont.conf here and amont.conventions \
872 is `declared`; only the safety net runs"
873 );
874 }
875 }
876 0
877}
878
879/// The shadow-mode worksheet, only when there is one — a repository that has
880/// never warned about anything keeps its old output byte-for-byte.
881///
882/// This is what a fortnight of `amont.severity.pre-commit warn` is FOR: the
883/// counts are the argument, and the footer carries the one action a reader
884/// takes afterwards. Repeating a config line per row would bury it.
885fn print_downgrades(l: &downgrade::Ledger) {
886 if l.total == 0 {
887 return;
888 }
889 let now = std::time::SystemTime::now()
890 .duration_since(std::time::UNIX_EPOCH)
891 .map(|d| d.as_secs())
892 .unwrap_or_default();
893 println!("\nproblems that did not block");
894 let pad = l
895 .by_check
896 .iter()
897 .map(|c| ui::sanitize(&c.check).chars().count())
898 .max()
899 .unwrap_or(0);
900 for c in &l.by_check {
901 // A check that declares `warn` itself was never going to block, and
902 // saying so inline stops it being read as rollout evidence.
903 let advisory = if c.would_block == 0 {
904 " (advisory)"
905 } else {
906 ""
907 };
908 println!(
909 " {:<pad$} {:>3} last {}{}",
910 ui::sanitize(&c.check),
911 c.count,
912 bypass::age(now, c.last),
913 advisory
914 );
915 }
916 // Events and commits are different facts: forty commits each tripping a
917 // check once is a check the team disagrees with, while one commit tripping
918 // it forty times is one person losing an afternoon.
919 let since = l
920 .first
921 .map(|f| format!(", since {}", bypass::age(now, f)))
922 .unwrap_or_default();
923 println!(
924 " {} event{} over {} commit{}{since}",
925 l.total,
926 if l.total == 1 { "" } else { "s" },
927 l.commits,
928 if l.commits == 1 { "" } else { "s" },
929 );
930 if l.would_block > 0 {
931 println!(
932 " {} of them would have blocked — set amont.severity.<check> to keep one \
933 advisory when you go back to block",
934 l.would_block
935 );
936 }
937}
938
939/// The unverified-commit tally, only when there is one — a clean repository's
940/// `amont list` output stays byte-identical to what it always was.
941fn print_bypasses(l: &bypass::Ledger) {
942 if l.total == 0 {
943 return;
944 }
945 let now = std::time::SystemTime::now()
946 .duration_since(std::time::UNIX_EPOCH)
947 .map(|d| d.as_secs())
948 .unwrap_or_default();
949 println!("\nunverified commits");
950 let pad = l
951 .by_script
952 .iter()
953 .map(|s| ui::sanitize(&s.script).chars().count())
954 .max()
955 .unwrap_or(0);
956 for s in &l.by_script {
957 println!(
958 " {:<pad$} {:>3} last {}",
959 ui::sanitize(&s.script),
960 s.count,
961 bypass::age(now, s.last)
962 );
963 }
964 println!(
965 " these commits carry no record that their commit-time gate ran — the push gate ran it instead"
966 );
967}
968
969fn describe(s: crate::check::Scope) -> String {
970 let files = if s.is_unscoped() {
971 String::new()
972 } else {
973 s.files
974 .iter()
975 .chain(s.names.iter())
976 .chain(s.dirs.iter())
977 .copied()
978 .collect::<Vec<_>>()
979 .join(" ")
980 };
981 let opt = s.opt_in.join(" | ");
982 match (files.is_empty(), opt.is_empty()) {
983 (false, false) => format!("{files} + {opt}"),
984 (false, true) => files,
985 (true, false) => opt,
986 (true, true) => "nothing".into(),
987 }
988}
989
990/// The machine's `hook.skip` entries PLUS the trusted policy's `skip`
991/// lines — the union every resolution site sees. Callers that must tell the
992/// two apart (the dispatcher announces them separately) use
993/// [`skips_by_source`].
994pub fn configured_skips(settings: &config::Settings) -> Vec<String> {
995 policy::union_skips(machine_skips(), settings.policy())
996}
997
998/// `(machine, policy)` — the split the announcements need: "you decided
999/// this" and "your team decided this" are different things to be told.
1000pub fn skips_by_source(settings: &config::Settings) -> (Vec<String>, Vec<String>) {
1001 (machine_skips(), settings.policy().skips.clone())
1002}
1003
1004/// The check names one `hook.skip` value carries. A value may join several
1005/// with commas (`-c hook.skip=clippy,prettier`), which is the same as one
1006/// `hook.skip` per name. A check id is letters, digits, `.`, `_` and `-`, so a
1007/// comma can never be part of a name and the split is never ambiguous. Names
1008/// are matched exactly afterwards, as ever: joining never turns one into a glob.
1009pub fn skip_names(value: &str) -> impl Iterator<Item = &str> {
1010 value
1011 .split(',')
1012 .map(str::trim)
1013 .filter(|name| !name.is_empty())
1014}
1015
1016fn machine_skips() -> Vec<String> {
1017 let Ok(out) = Command::new("git")
1018 .args(["config", "--get-all", "hook.skip"])
1019 .stderr(Stdio::null())
1020 .output()
1021 else {
1022 return Vec::new();
1023 };
1024 String::from_utf8_lossy(&out.stdout)
1025 .lines()
1026 .flat_map(skip_names)
1027 .map(str::to_owned)
1028 .collect()
1029}
1030
1031/// Which git operations are part-way through, from the markers in `$GIT_DIR`.
1032///
1033/// Asks git directly rather than deriving a path from `hooks_dir`. That used
1034/// to be `hooks_dir.parent()` — correct for the main worktree, where hooks
1035/// live in `.git/hooks` and `.git` IS `$GIT_DIR`, but wrong for a LINKED
1036/// worktree: hooks dispatch from the COMMON directory's `hooks/`, shared
1037/// across every worktree, while `MERGE_HEAD`/`CHERRY_PICK_HEAD`/etc. live in
1038/// each worktree's own PRIVATE gitdir under `.git/worktrees/<name>`.
1039/// Conflating the two silently disabled this guard for every linked
1040/// worktree — the same mistake `staged_only`'s store path made, which lost
1041/// unstaged work outright; see its module doc.
1042pub fn git_states_in_progress() -> Vec<crate::check::GitState> {
1043 let Some(git_dir) = crate::git::stdout(&["rev-parse", "--git-dir"]) else {
1044 return Vec::new();
1045 };
1046 let git_dir = Path::new(&git_dir);
1047 crate::check::GitState::ALL
1048 .into_iter()
1049 .filter(|state| {
1050 state
1051 .markers()
1052 .iter()
1053 .any(|marker| git_dir.join(marker).exists())
1054 })
1055 .collect()
1056}
1057
1058/// True during a cherry-pick, where the zsh `pre-commit` exited 0 immediately.
1059/// Superseded internally by [`git_states_in_progress`]; kept for whatever
1060/// still calls it directly. See that function for why this asks git rather
1061/// than deriving a path from `hooks_dir`.
1062pub fn cherry_pick_in_progress() -> bool {
1063 crate::git::stdout(&["rev-parse", "--git-dir"])
1064 .map(|d| Path::new(&d).join("CHERRY_PICK_HEAD").exists())
1065 .unwrap_or(false)
1066}
1067
1068#[cfg(test)]
1069mod naming {
1070 use super::*;
1071
1072 /// A joined value is the same as one skip per name; spaces, empty pieces
1073 /// and a trailing comma change nothing, and a lone name is untouched.
1074 #[test]
1075 fn a_comma_joined_skip_is_one_skip_per_name() {
1076 fn names(v: &str) -> Vec<&str> {
1077 skip_names(v).collect()
1078 }
1079 assert_eq!(names("clippy"), ["clippy"]);
1080 assert_eq!(
1081 names("pre-commit-cargo-test,pre-commit-plugin-test"),
1082 ["pre-commit-cargo-test", "pre-commit-plugin-test"]
1083 );
1084 assert_eq!(names(" a , b ,,c, "), ["a", "b", "c"]);
1085 assert!(names(" , ").is_empty());
1086 }
1087
1088 /// Joining never widens a name: each piece is matched exactly, as a
1089 /// separate `hook.skip` would be, so `e,clippy` still reaches nothing by `e`.
1090 #[test]
1091 fn joining_names_does_not_turn_them_into_globs() {
1092 assert!(!skip_suppresses("pre-commit-clippy", "e"));
1093 assert!(skip_names("e,clippy").any(|n| skip_suppresses("pre-commit-clippy", n)));
1094 assert!(!skip_names("e,lint").any(|n| skip_suppresses("pre-commit-clippy", n)));
1095 }
1096
1097 /// The three things a user can write, and what each reaches.
1098 #[test]
1099 fn three_ways_to_name_a_check() {
1100 assert_eq!(
1101 names_check("pre-commit-clippy", "pre-commit-clippy"),
1102 Some(Match::FullId)
1103 );
1104 assert_eq!(
1105 names_check("pre-commit-clippy", "pre-commit"),
1106 Some(Match::Trigger)
1107 );
1108 assert_eq!(
1109 names_check("pre-commit-clippy", "clippy"),
1110 Some(Match::ShortName)
1111 );
1112 }
1113
1114 /// The hazards the old substring rule created, all gone by construction.
1115 #[test]
1116 fn nothing_matches_by_accident() {
1117 // `hook.skip = e` disabled all twenty checks. It now reaches nothing.
1118 for pattern in ["e", "t", "i", ""] {
1119 assert_eq!(
1120 names_check("pre-commit-clippy", pattern),
1121 None,
1122 "{pattern:?}"
1123 );
1124 }
1125 // A partial word is not a name.
1126 assert_eq!(names_check("pre-commit-clippy", "clip"), None);
1127 assert_eq!(names_check("pre-commit-clippy", "lint"), None);
1128 // The wrong trigger reaches nothing.
1129 assert_eq!(names_check("pre-commit-clippy", "pre-push"), None);
1130 // And the empty string names nothing, rather than everything — git
1131 // stores `hook.skip` with no value as exactly this.
1132 assert_eq!(names_check("pre-commit-clippy", ""), None);
1133 }
1134
1135 /// The coupling `docs/hook-skip-management.md` warned about: `lint-js` is a
1136 /// substring of `lint-json-yaml`, so skipping one used to skip both.
1137 #[test]
1138 fn a_short_name_does_not_reach_a_longer_one() {
1139 assert!(names_check("pre-commit-lint-json-yaml", "lint-js").is_none());
1140 assert_eq!(
1141 names_check("pre-commit-lint-js", "lint-js"),
1142 Some(Match::ShortName)
1143 );
1144 assert_eq!(
1145 names_check("pre-commit-lint-json-yaml", "lint-json-yaml"),
1146 Some(Match::ShortName)
1147 );
1148 }
1149
1150 /// The one value that exists in the real fleet.
1151 #[test]
1152 fn the_fleets_only_skip_still_resolves() {
1153 assert_eq!(
1154 names_check("pre-push-run-tests-js", "run-tests-js"),
1155 Some(Match::ShortName)
1156 );
1157 }
1158
1159 /// A trigger reaches every check on it and none on the other.
1160 #[test]
1161 fn a_trigger_reaches_its_own_stage_only() {
1162 let pre_commit = registry::CHECKS
1163 .iter()
1164 .filter(|c| names_check(c.name, "pre-commit").is_some())
1165 .count();
1166 let pre_push = registry::CHECKS
1167 .iter()
1168 .filter(|c| names_check(c.name, "pre-push").is_some())
1169 .count();
1170 assert_eq!(pre_commit + pre_push, registry::CHECKS.len());
1171 assert!(pre_commit > 0 && pre_push > 0);
1172 }
1173
1174 /// Specificity ordering, which decides severity when several keys apply.
1175 #[test]
1176 fn a_full_id_outranks_a_short_name_outranks_a_trigger() {
1177 assert!(Match::FullId > Match::ShortName);
1178 assert!(Match::ShortName > Match::Trigger);
1179 }
1180
1181 /// The resolver reads the trigger out of the ID. That is only sound while
1182 /// every ID agrees with the stage its check actually declares — so it is
1183 /// checked rather than assumed.
1184 #[test]
1185 fn every_id_agrees_with_its_declared_stage() {
1186 for check in registry::CHECKS {
1187 assert_eq!(
1188 names_check(check.name, check.stage.as_str()),
1189 Some(Match::Trigger),
1190 "{} declares {:?} but its id says otherwise",
1191 check.name,
1192 check.stage
1193 );
1194 }
1195 }
1196}
1197
1198#[cfg(test)]
1199mod listing {
1200 use super::*;
1201
1202 /// The summary names ecosystems so the inert count reads as "other
1203 /// people's stacks" rather than "twenty-two things are broken".
1204 #[test]
1205 fn scope_tokens_map_to_the_ecosystem_a_reader_would_name() {
1206 assert_eq!(ecosystem(".rs"), Some("Rust"));
1207 assert_eq!(ecosystem("Cargo.lock"), Some("Rust"));
1208 assert_eq!(ecosystem("go.sum"), Some("Go"));
1209 assert_eq!(ecosystem("pyproject.toml"), Some("Python"));
1210 assert_eq!(ecosystem(".tsx"), Some("JavaScript"));
1211 assert_eq!(ecosystem(".prettierrc.json"), Some("JavaScript"));
1212 assert_eq!(ecosystem("kustomization.yaml"), Some("Kubernetes"));
1213 assert_eq!(ecosystem(".kube-linter.yaml"), Some("Kubernetes"));
1214 }
1215
1216 /// The generic tokens are unmapped ON PURPOSE. Four checks want `.yaml`
1217 /// for four unrelated reasons, so naming YAML would tell a reader their
1218 /// repository is missing "YAML checks" when what it is missing is
1219 /// Kubernetes. An unmapped token is still COUNTED — it just goes unnamed,
1220 /// which is the honest failure mode for a presentational map.
1221 #[test]
1222 fn generic_tokens_are_deliberately_unnamed() {
1223 for t in [".yaml", ".yml", ".json", ".md", ".sh", "unknown-thing"] {
1224 assert_eq!(ecosystem(t), None, "{t} should not name an ecosystem");
1225 }
1226 }
1227}