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