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