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