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 // The programme skill's `prog/<slug>/<id>` is in `pattern`, not offered
790 // as a prefix for ordinary work.
791 .filter(|p| !p.nested)
792 .map(|p| p.name.to_string())
793 .collect();
794 json::object(&[
795 json::string_field("shape", "<prefix>/<name>"),
796 json::string_field("pattern", &vocabulary::branch_contract()),
797 json::string_array_field("prefixes", &prefixes),
798 ])
799}
800
801/// `git ls-files` — every check's default scope evaluation, unchanged from
802/// what `list_checks` always did.
803///
804/// Through `git::stdout_paths`, i.e. with `-z`. A raw `ls-files` QUOTES any
805/// path holding an unusual byte: `é.json` comes back as the nine-byte literal
806/// `"\303\251.json"`, which ends with a quote rather than an extension, so
807/// `Scope::matches` reports a check as irrelevant to a repository it plainly
808/// covers. Cosmetic here (this only decides what `list` prints) and not
809/// cosmetic in `dispatch::enter_all_files_mode`, which is the same bug — so
810/// both ask the same way.
811pub(crate) fn tracked_paths() -> Vec<String> {
812 git::stdout_paths(&["ls-files"]).unwrap_or_default()
813}
814
815/// The pushed-range file list, computed standalone rather than from a real
816/// pre-push invocation's stdin.
817///
818/// Reuses `pushrefs::changed_files`, which already handles zero-oid deletes,
819/// merge commits and the `--stdin` trailing-newline edge case — this only
820/// SYNTHESISES the one `PushRef` a standalone invocation has no other way to
821/// obtain.
822fn pushed_paths() -> Result<Vec<String>, String> {
823 let synthetic = pushrefs::synthetic_from_upstream()?;
824 Ok(pushrefs::changed_files(&[synthetic]))
825}
826
827/// `amont list`: what would run here, and why — as prose, or as
828/// `--json` for a reader that wants to parse it.
829pub fn list_checks(opts: ListOptions) -> i32 {
830 let paths = if opts.pushed {
831 match pushed_paths() {
832 Ok(p) => p,
833 Err(msg) => {
834 if opts.json {
835 println!("{}", json::object(&[json::string_field("error", &msg)]));
836 } else {
837 eprintln!("{BIN}: {msg}");
838 }
839 return 2;
840 }
841 }
842 } else {
843 tracked_paths()
844 };
845 // Loaded HERE, with the repository this command is standing in — the
846 // owned-manifest shape every entrypoint now follows. See manifest::load.
847 // The policy is OWNED here and borrowed downstream. The invariant that
848 // used to be a comment — install immediately after load, before any
849 // config read — is now the borrow checker's: nothing downstream can read
850 // configuration without being handed this. `load_resolved` also resolves
851 // the commit-time triggers.
852 let (manifest, settings) =
853 manifest::load_resolved(std::path::Path::new(&hooks::common::repo_root()));
854 let listings = gather_checks(&settings, opts.stage, &paths, &manifest);
855 let bypasses = bypass::read();
856 let downgrades = downgrade::read();
857 let conventions_apply = dispatch::conventions_apply(&settings, &manifest);
858 if opts.json {
859 print_json(
860 &settings,
861 opts.stage,
862 opts.pushed,
863 &listings,
864 &bypasses,
865 &downgrades,
866 conventions_apply,
867 );
868 } else {
869 print_text(&listings, opts.all);
870 // Not filtered by `--stage`: commit style belongs to no stage, and
871 // suppressing it for `--stage pre-push` would only hide it from the
872 // reader who narrowed their question.
873 let (style, rows) = commit_style::describe(&settings);
874 print_commit_style(&style, &rows);
875 print_bypasses(&bypasses);
876 print_downgrades(&downgrades);
877 if !conventions_apply {
878 println!(
879 "\n ! conventions held back — no {} here and greengate.conventions \
880 is `declared`; only the safety net runs",
881 manifest.file_name()
882 );
883 }
884 }
885 0
886}
887
888/// The shadow-mode worksheet, only when there is one — a repository that has
889/// never warned about anything keeps its old output byte-for-byte.
890///
891/// This is what a fortnight of `greengate.severity.pre-commit warn` is FOR: the
892/// counts are the argument, and the footer carries the one action a reader
893/// takes afterwards. Repeating a config line per row would bury it.
894fn print_downgrades(l: &downgrade::Ledger) {
895 if l.total == 0 {
896 return;
897 }
898 let now = std::time::SystemTime::now()
899 .duration_since(std::time::UNIX_EPOCH)
900 .map(|d| d.as_secs())
901 .unwrap_or_default();
902 println!("\nproblems that did not block");
903 let pad = l
904 .by_check
905 .iter()
906 .map(|c| ui::sanitize(&c.check).chars().count())
907 .max()
908 .unwrap_or(0);
909 for c in &l.by_check {
910 // A check that declares `warn` itself was never going to block, and
911 // saying so inline stops it being read as rollout evidence.
912 let advisory = if c.would_block == 0 {
913 " (advisory)"
914 } else {
915 ""
916 };
917 println!(
918 " {:<pad$} {:>3} last {}{}",
919 ui::sanitize(&c.check),
920 c.count,
921 bypass::age(now, c.last),
922 advisory
923 );
924 }
925 // Events and commits are different facts: forty commits each tripping a
926 // check once is a check the team disagrees with, while one commit tripping
927 // it forty times is one person losing an afternoon.
928 let since = l
929 .first
930 .map(|f| format!(", since {}", bypass::age(now, f)))
931 .unwrap_or_default();
932 println!(
933 " {} event{} over {} commit{}{since}",
934 l.total,
935 if l.total == 1 { "" } else { "s" },
936 l.commits,
937 if l.commits == 1 { "" } else { "s" },
938 );
939 if l.would_block > 0 {
940 println!(
941 " {} of them would have blocked — set greengate.severity.<check> to keep one \
942 advisory when you go back to block",
943 l.would_block
944 );
945 }
946}
947
948/// The unverified-commit tally, only when there is one — a clean repository's
949/// `amont list` output stays byte-identical to what it always was.
950fn print_bypasses(l: &bypass::Ledger) {
951 if l.total == 0 {
952 return;
953 }
954 let now = std::time::SystemTime::now()
955 .duration_since(std::time::UNIX_EPOCH)
956 .map(|d| d.as_secs())
957 .unwrap_or_default();
958 println!("\nunverified commits");
959 let pad = l
960 .by_script
961 .iter()
962 .map(|s| ui::sanitize(&s.script).chars().count())
963 .max()
964 .unwrap_or(0);
965 for s in &l.by_script {
966 println!(
967 " {:<pad$} {:>3} last {}",
968 ui::sanitize(&s.script),
969 s.count,
970 bypass::age(now, s.last)
971 );
972 }
973 println!(
974 " these commits carry no record that their commit-time gate ran — the push gate ran it instead"
975 );
976}
977
978fn describe(s: crate::check::Scope) -> String {
979 let files = if s.is_unscoped() {
980 String::new()
981 } else {
982 s.files
983 .iter()
984 .chain(s.names.iter())
985 .chain(s.dirs.iter())
986 .copied()
987 .collect::<Vec<_>>()
988 .join(" ")
989 };
990 let opt = s.opt_in.join(" | ");
991 match (files.is_empty(), opt.is_empty()) {
992 (false, false) => format!("{files} + {opt}"),
993 (false, true) => files,
994 (true, false) => opt,
995 (true, true) => "nothing".into(),
996 }
997}
998
999/// The machine's `hook.skip` entries PLUS the trusted policy's `skip`
1000/// lines — the union every resolution site sees. Callers that must tell the
1001/// two apart (the dispatcher announces them separately) use
1002/// [`skips_by_source`].
1003pub fn configured_skips(settings: &config::Settings) -> Vec<String> {
1004 policy::union_skips(machine_skips(), settings.policy())
1005}
1006
1007/// `(machine, policy)` — the split the announcements need: "you decided
1008/// this" and "your team decided this" are different things to be told.
1009pub fn skips_by_source(settings: &config::Settings) -> (Vec<String>, Vec<String>) {
1010 (machine_skips(), settings.policy().skips.clone())
1011}
1012
1013/// The check names one `hook.skip` value carries. A value may join several
1014/// with commas (`-c hook.skip=clippy,prettier`), which is the same as one
1015/// `hook.skip` per name. A check id is letters, digits, `.`, `_` and `-`, so a
1016/// comma can never be part of a name and the split is never ambiguous. Names
1017/// are matched exactly afterwards, as ever: joining never turns one into a glob.
1018pub fn skip_names(value: &str) -> impl Iterator<Item = &str> {
1019 value
1020 .split(',')
1021 .map(str::trim)
1022 .filter(|name| !name.is_empty())
1023}
1024
1025fn machine_skips() -> Vec<String> {
1026 let Ok(out) = Command::new("git")
1027 .args(["config", "--get-all", "hook.skip"])
1028 .stderr(Stdio::null())
1029 .output()
1030 else {
1031 return Vec::new();
1032 };
1033 String::from_utf8_lossy(&out.stdout)
1034 .lines()
1035 .flat_map(skip_names)
1036 .map(str::to_owned)
1037 .collect()
1038}
1039
1040/// Which git operations are part-way through, from the markers in `$GIT_DIR`.
1041///
1042/// Asks git directly rather than deriving a path from `hooks_dir`. That used
1043/// to be `hooks_dir.parent()` — correct for the main worktree, where hooks
1044/// live in `.git/hooks` and `.git` IS `$GIT_DIR`, but wrong for a LINKED
1045/// worktree: hooks dispatch from the COMMON directory's `hooks/`, shared
1046/// across every worktree, while `MERGE_HEAD`/`CHERRY_PICK_HEAD`/etc. live in
1047/// each worktree's own PRIVATE gitdir under `.git/worktrees/<name>`.
1048/// Conflating the two silently disabled this guard for every linked
1049/// worktree — the same mistake `staged_only`'s store path made, which lost
1050/// unstaged work outright; see its module doc.
1051pub fn git_states_in_progress() -> Vec<crate::check::GitState> {
1052 let Some(git_dir) = crate::git::stdout(&["rev-parse", "--git-dir"]) else {
1053 return Vec::new();
1054 };
1055 let git_dir = Path::new(&git_dir);
1056 crate::check::GitState::ALL
1057 .into_iter()
1058 .filter(|state| {
1059 state
1060 .markers()
1061 .iter()
1062 .any(|marker| git_dir.join(marker).exists())
1063 })
1064 .collect()
1065}
1066
1067/// True during a cherry-pick, where the zsh `pre-commit` exited 0 immediately.
1068/// Superseded internally by [`git_states_in_progress`]; kept for whatever
1069/// still calls it directly. See that function for why this asks git rather
1070/// than deriving a path from `hooks_dir`.
1071pub fn cherry_pick_in_progress() -> bool {
1072 crate::git::stdout(&["rev-parse", "--git-dir"])
1073 .map(|d| Path::new(&d).join("CHERRY_PICK_HEAD").exists())
1074 .unwrap_or(false)
1075}
1076
1077#[cfg(test)]
1078mod naming {
1079 use super::*;
1080
1081 /// A joined value is the same as one skip per name; spaces, empty pieces
1082 /// and a trailing comma change nothing, and a lone name is untouched.
1083 #[test]
1084 fn a_comma_joined_skip_is_one_skip_per_name() {
1085 fn names(v: &str) -> Vec<&str> {
1086 skip_names(v).collect()
1087 }
1088 assert_eq!(names("clippy"), ["clippy"]);
1089 assert_eq!(
1090 names("pre-commit-cargo-test,pre-commit-plugin-test"),
1091 ["pre-commit-cargo-test", "pre-commit-plugin-test"]
1092 );
1093 assert_eq!(names(" a , b ,,c, "), ["a", "b", "c"]);
1094 assert!(names(" , ").is_empty());
1095 }
1096
1097 /// Joining never widens a name: each piece is matched exactly, as a
1098 /// separate `hook.skip` would be, so `e,clippy` still reaches nothing by `e`.
1099 #[test]
1100 fn joining_names_does_not_turn_them_into_globs() {
1101 assert!(!skip_suppresses("pre-commit-clippy", "e"));
1102 assert!(skip_names("e,clippy").any(|n| skip_suppresses("pre-commit-clippy", n)));
1103 assert!(!skip_names("e,lint").any(|n| skip_suppresses("pre-commit-clippy", n)));
1104 }
1105
1106 /// The three things a user can write, and what each reaches.
1107 #[test]
1108 fn three_ways_to_name_a_check() {
1109 assert_eq!(
1110 names_check("pre-commit-clippy", "pre-commit-clippy"),
1111 Some(Match::FullId)
1112 );
1113 assert_eq!(
1114 names_check("pre-commit-clippy", "pre-commit"),
1115 Some(Match::Trigger)
1116 );
1117 assert_eq!(
1118 names_check("pre-commit-clippy", "clippy"),
1119 Some(Match::ShortName)
1120 );
1121 }
1122
1123 /// The hazards the old substring rule created, all gone by construction.
1124 #[test]
1125 fn nothing_matches_by_accident() {
1126 // `hook.skip = e` disabled all twenty checks. It now reaches nothing.
1127 for pattern in ["e", "t", "i", ""] {
1128 assert_eq!(
1129 names_check("pre-commit-clippy", pattern),
1130 None,
1131 "{pattern:?}"
1132 );
1133 }
1134 // A partial word is not a name.
1135 assert_eq!(names_check("pre-commit-clippy", "clip"), None);
1136 assert_eq!(names_check("pre-commit-clippy", "lint"), None);
1137 // The wrong trigger reaches nothing.
1138 assert_eq!(names_check("pre-commit-clippy", "pre-push"), None);
1139 // And the empty string names nothing, rather than everything — git
1140 // stores `hook.skip` with no value as exactly this.
1141 assert_eq!(names_check("pre-commit-clippy", ""), None);
1142 }
1143
1144 /// The coupling `docs/hook-skip-management.md` warned about: `lint-js` is a
1145 /// substring of `lint-json-yaml`, so skipping one used to skip both.
1146 #[test]
1147 fn a_short_name_does_not_reach_a_longer_one() {
1148 assert!(names_check("pre-commit-lint-json-yaml", "lint-js").is_none());
1149 assert_eq!(
1150 names_check("pre-commit-lint-js", "lint-js"),
1151 Some(Match::ShortName)
1152 );
1153 assert_eq!(
1154 names_check("pre-commit-lint-json-yaml", "lint-json-yaml"),
1155 Some(Match::ShortName)
1156 );
1157 }
1158
1159 /// The one value that exists in the real fleet.
1160 #[test]
1161 fn the_fleets_only_skip_still_resolves() {
1162 assert_eq!(
1163 names_check("pre-push-run-tests-js", "run-tests-js"),
1164 Some(Match::ShortName)
1165 );
1166 }
1167
1168 /// A trigger reaches every check on it and none on the other.
1169 #[test]
1170 fn a_trigger_reaches_its_own_stage_only() {
1171 let pre_commit = registry::CHECKS
1172 .iter()
1173 .filter(|c| names_check(c.name, "pre-commit").is_some())
1174 .count();
1175 let pre_push = registry::CHECKS
1176 .iter()
1177 .filter(|c| names_check(c.name, "pre-push").is_some())
1178 .count();
1179 assert_eq!(pre_commit + pre_push, registry::CHECKS.len());
1180 assert!(pre_commit > 0 && pre_push > 0);
1181 }
1182
1183 /// Specificity ordering, which decides severity when several keys apply.
1184 #[test]
1185 fn a_full_id_outranks_a_short_name_outranks_a_trigger() {
1186 assert!(Match::FullId > Match::ShortName);
1187 assert!(Match::ShortName > Match::Trigger);
1188 }
1189
1190 /// The resolver reads the trigger out of the ID. That is only sound while
1191 /// every ID agrees with the stage its check actually declares — so it is
1192 /// checked rather than assumed.
1193 #[test]
1194 fn every_id_agrees_with_its_declared_stage() {
1195 for check in registry::CHECKS {
1196 assert_eq!(
1197 names_check(check.name, check.stage.as_str()),
1198 Some(Match::Trigger),
1199 "{} declares {:?} but its id says otherwise",
1200 check.name,
1201 check.stage
1202 );
1203 }
1204 }
1205}
1206
1207#[cfg(test)]
1208mod listing {
1209 use super::*;
1210
1211 /// The summary names ecosystems so the inert count reads as "other
1212 /// people's stacks" rather than "twenty-two things are broken".
1213 #[test]
1214 fn scope_tokens_map_to_the_ecosystem_a_reader_would_name() {
1215 assert_eq!(ecosystem(".rs"), Some("Rust"));
1216 assert_eq!(ecosystem("Cargo.lock"), Some("Rust"));
1217 assert_eq!(ecosystem("go.sum"), Some("Go"));
1218 assert_eq!(ecosystem("pyproject.toml"), Some("Python"));
1219 assert_eq!(ecosystem(".tsx"), Some("JavaScript"));
1220 assert_eq!(ecosystem(".prettierrc.json"), Some("JavaScript"));
1221 assert_eq!(ecosystem("kustomization.yaml"), Some("Kubernetes"));
1222 assert_eq!(ecosystem(".kube-linter.yaml"), Some("Kubernetes"));
1223 }
1224
1225 /// The generic tokens are unmapped ON PURPOSE. Four checks want `.yaml`
1226 /// for four unrelated reasons, so naming YAML would tell a reader their
1227 /// repository is missing "YAML checks" when what it is missing is
1228 /// Kubernetes. An unmapped token is still COUNTED — it just goes unnamed,
1229 /// which is the honest failure mode for a presentational map.
1230 #[test]
1231 fn generic_tokens_are_deliberately_unnamed() {
1232 for t in [".yaml", ".yml", ".json", ".md", ".sh", "unknown-thing"] {
1233 assert_eq!(ecosystem(t), None, "{t} should not name an ecosystem");
1234 }
1235 }
1236}