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