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