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