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