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