amont_runtime/dispatch.rs
1//! The two dispatchers.
2//!
3//! They are NOT the same shape, and both shapes are load-bearing:
4//!
5//! - `pre-commit` runs its checks CONCURRENTLY and reports EVERY failure.
6//! Serial would be a visible slowdown on each commit; stopping at the first
7//! failure would hide the rest, so you'd fix one lint error, commit, and
8//! immediately meet the next.
9//! - `pre-push` runs them SERIALLY and stops at the FIRST failure, naming just
10//! that check. The steps are ordered and expensive (protected branch, then
11//! branch name, then rebase, then the whole test suite) and there is no point
12//! running tests after a rebase conflict.
13//!
14//! Resist the tempting shared `run_all` helper — collapsing these is the
15//! obvious way to silently lose the distinction. `tests/dispatchers.rs` pins
16//! both.
17//!
18//! Checks are FUNCTIONS in this binary, called directly. They used to be files:
19//! `.git/hooks/pre-commit-*`, each an identical `sh` shim whose only job was to
20//! re-exec this same binary and tell it its own name. One commit therefore cost
21//! 27 processes — a shim, the binary, then 13 more shims and 13 more binaries —
22//! to do work the binary already had in a table.
23//!
24//! Deleting that removed the filename glob (order was lexicographic, so a
25//! rename could silently reorder a gate), the shebang emulation Windows needed
26//! because it cannot execute a `#!` script, and the spawn plumbing under both.
27//! Order is now a declared list in `registry`.
28
29use std::sync::Mutex;
30
31use crate::check::{Check, Outcome, Severity, Stage, Verdict};
32use crate::configured_skips;
33use crate::registry::{all_stage_checks, Ctx, Overrides};
34use crate::ui::{highlight, valid_sign, warning_sign};
35
36/// The checks for a stage, minus anything `hook.skip` filters out. Resolution
37/// goes through `names_check`, the one rule this and the severity lookup share:
38/// `git config hook.skip ruff` skips `pre-commit-ruff` by short name.
39fn selected(stage: Stage, manifest: &crate::manifest::Manifest) -> Vec<&dyn Check> {
40 selected_during(stage, &[], manifest)
41}
42
43/// Do this repository's hooks apply the CONVENTIONS, or only the safety net?
44///
45/// `git config amont.conventions declared` (usually `--global`, set by
46/// `amont enroll`) scopes the house rules to repositories that commit an
47/// `amont.conf` — the standing grant of `init.templateDir` then becomes safe
48/// to hand a whole team: a clone of somebody else's project gets conflict,
49/// secret, size and debug-leftover protection, and none of this team's
50/// opinions about commit subjects or branch names. The default,
51/// `everywhere`, keeps today's behaviour exactly.
52///
53/// Presence of the manifest is the declaration; its CONTENT stays
54/// trust-gated. Reading presence executes nothing, so no consent is needed.
55pub fn conventions_apply(manifest: &crate::manifest::Manifest) -> bool {
56 manifest.declared || !declared_mode()
57}
58
59/// One config read per process — this sits on the hook path of every commit.
60fn declared_mode() -> bool {
61 static MODE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
62 *MODE.get_or_init(|| {
63 crate::config::enumerated_or(
64 "amont.conventions",
65 &["everywhere", "declared"],
66 "everywhere",
67 ) == "declared"
68 })
69}
70
71/// The checks for a stage, minus `hook.skip` and minus anything that declares
72/// it does not run during an operation currently in progress.
73fn selected_during<'a>(
74 stage: Stage,
75 in_progress: &[crate::check::GitState],
76 manifest: &'a crate::manifest::Manifest,
77) -> Vec<&'a dyn Check> {
78 let skips = configured_skips();
79 // Externals are included here, so `hook.skip` and the severity override
80 // govern a declared command exactly as they govern a built-in. A repository
81 // that can add a check it cannot disable would be a worse deal than not
82 // being able to add one.
83 let (kept, dropped): (Vec<_>, Vec<_>) = all_stage_checks(stage, manifest)
84 .into_iter()
85 .partition(|c| !skips.iter().any(|s| crate::skip_suppresses(c.name(), s)));
86 let names: Vec<&str> = dropped.iter().map(|c| c.name()).collect();
87 announce_skips(&names);
88
89 // Announced separately from `hook.skip`, and with the operation named: "not
90 // during a rebase" is a property of the moment and will be true again in a
91 // minute, which is a different thing to tell a reader than "you disabled
92 // this".
93 let (kept, paused): (Vec<_>, Vec<_>) = kept.into_iter().partition(|check| {
94 !check
95 .scope()
96 .not_during
97 .iter()
98 .any(|state| in_progress.contains(state))
99 });
100 if !paused.is_empty() {
101 let what = in_progress
102 .iter()
103 .map(|s| s.as_str())
104 .collect::<Vec<_>>()
105 .join(" and ");
106 println!(
107 "{} {} check(s) paused during {what}: {}",
108 warning_sign(),
109 paused.len(),
110 paused
111 .iter()
112 .map(|c| c.name())
113 .collect::<Vec<_>>()
114 .join(", ")
115 );
116 }
117
118 // The conventions split, last: a held-back check was neither skipped (a
119 // choice about THIS repository) nor paused (a property of the moment) —
120 // this repository simply never subscribed. One line, count not names:
121 // in the clone-of-somebody-else's-project case this prints on every
122 // commit, and fifteen names every time is how a safety message becomes
123 // scroll-past noise.
124 if conventions_apply(manifest) {
125 return kept;
126 }
127 let (kept, held): (Vec<_>, Vec<_>) = kept
128 .into_iter()
129 .partition(|check| check.reach() == crate::check::Reach::Safety);
130 if !held.is_empty() {
131 println!(
132 "{} {} convention check(s) held back — no amont.conf here and \
133 amont.conventions is `declared`; the safety net still runs",
134 warning_sign(),
135 held.len(),
136 );
137 }
138 kept
139}
140
141/// Say out loud which checks did not run.
142///
143/// A skip is otherwise invisible at exactly the moment it matters. With
144/// `hook.skip = merge-conflict` set, a commit printed six green ticks and no
145/// hint that a seventh check had been disabled — the developer sees a clean run
146/// and concludes they are covered.
147///
148/// It is worse than it sounds, because one value can silence a whole stage:
149/// `hook.skip = pre-commit` suppresses all fifteen. That is now something
150/// somebody meant rather than the accident it once was — `e` used to cost
151/// twenty by substring reach — but a commit under it still looks exactly like a
152/// commit that had nothing to report.
153///
154/// One line, only when something was actually skipped, so a normal commit is
155/// unchanged. This reaches every skip however it was created — hand-edited
156/// config included — which no dashboard can claim.
157fn announce_skips(dropped: &[&str]) {
158 if dropped.is_empty() {
159 return;
160 }
161 let plural = if dropped.len() == 1 {
162 "check"
163 } else {
164 "checks"
165 };
166 println!(
167 "{} {} {plural} skipped by {}: {}",
168 warning_sign(),
169 dropped.len(),
170 highlight("hook.skip"),
171 dropped.join(", ")
172 );
173}
174
175/// Run every item concurrently and collect `(name, code)` in the INPUT order.
176///
177/// Extracted so the concurrency itself can be tested with a rendezvous instead
178/// of a stopwatch — an earlier wall-clock test was flaky the moment the machine
179/// was busy, and a threshold that trips under load teaches you to ignore it.
180fn run_concurrently<T, R, F>(items: &[T], run: F, if_thread_died: R) -> Vec<R>
181where
182 T: Sync,
183 R: Send + Sync + Clone,
184 F: Fn(&T) -> R + Sync,
185{
186 let slots: Vec<Mutex<Option<R>>> = items.iter().map(|_| Mutex::new(None)).collect();
187 std::thread::scope(|scope| {
188 for (item, slot) in items.iter().zip(&slots) {
189 let run = &run;
190 let died = &if_thread_died;
191 scope.spawn(move || {
192 // CAUGHT, not propagated. `thread::scope` re-raises a child
193 // panic in the parent, which would abort the whole hook with a
194 // backtrace and throw away the other nineteen checks' results —
195 // and would make `if_thread_died` unreachable, which is what it
196 // was until this test existed to notice.
197 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(item)))
198 .unwrap_or_else(|_| died.clone());
199 *slot.lock().expect("poisoned") = Some(outcome);
200 });
201 }
202 });
203 slots
204 .into_iter()
205 .map(|s| {
206 s.into_inner()
207 .expect("poisoned")
208 .unwrap_or_else(|| if_thread_died.clone())
209 })
210 .collect()
211}
212
213/// Take the index-fidelity hold, or say why the caller must stop.
214///
215/// Extracted from `pre_commit` so that `amont run` — which its own doc
216/// comment calls "a rehearsal of the hook" — can take exactly the same hold
217/// rather than judging the working tree while a real commit judges the index.
218///
219/// Around the WHOLE fan-out, not per check: twenty checks run concurrently and
220/// would fight over one working tree.
221fn hold_unstaged() -> Result<crate::staged_only::StagedOnly, Verdict> {
222 // BEFORE `enter()`, not after: `enter()` is what checks out the tree and
223 // parks the unstaged half, and a signal landing in the gap between that
224 // and the handler being armed would hit the default disposition — dead
225 // process, tree left checked out, nothing restored. The handler no-ops
226 // harmlessly on a signal that arrives before there is anything held.
227 crate::staged_only::install_signal_handler();
228 match crate::staged_only::StagedOnly::enter() {
229 Ok(guard) => Ok(guard),
230 Err(e) => {
231 // Refusing to check the wrong content is the safe direction; a
232 // check that read the tree would be answering about a commit
233 // nobody is making.
234 eprintln!("{e}");
235 Err(Verdict::Block)
236 }
237 }
238}
239
240pub fn pre_commit(ctx: &Ctx) -> Verdict {
241 // Before anything runs: a pinned tool at the wrong version makes every
242 // verdict below it suspect, and the warning costs one --version per pin.
243 crate::manifest::verify_tool_pins(&ctx.manifest.pins);
244 let in_progress = crate::git_states_in_progress();
245 let checks = selected_during(Stage::PreCommit, &in_progress, ctx.manifest);
246
247 let held = match hold_unstaged() {
248 Ok(guard) => guard,
249 Err(verdict) => return verdict,
250 };
251
252 let (verdict, outcomes) = run_stage_traced(&checks, ctx, &Overrides::read());
253
254 // What post-commit will bind to the commit: the gate-declared checks
255 // that RAN clean, recorded while the index still is the commit's tree.
256 // Called on every verdict — an empty record clears any leftover marker,
257 // so a blocked attempt (or a repo with nothing declared) cannot leave an
258 // earlier attempt's marker to vouch for the next commit. `Unavailable`
259 // deliberately does not qualify: a check whose tool is missing judged
260 // nothing, and stamping it would be the paper promise this exists to
261 // replace.
262 // EVERY blocking declaration, not only the npm GATE names: a custom
263 // `pre-commit check … block …` earns its stamp the same way, and a
264 // same-named pre-push declaration defers to it (see `pair_verdict`).
265 let ran: Vec<String> = if matches!(verdict, Verdict::Block) {
266 Vec::new()
267 } else {
268 crate::hooks::run_tests::blocking_commit_decls(&ctx.manifest.externals)
269 .into_iter()
270 .filter(|d| {
271 checks
272 .iter()
273 .zip(&outcomes)
274 .any(|(c, o)| c.name() == d.id && matches!(o, Outcome::Passed | Outcome::Fixed))
275 })
276 .map(|d| d.script)
277 .collect()
278 };
279 let ran: Vec<&str> = ran.iter().map(String::as_str).collect();
280 crate::gate_stamp::record(&ran);
281
282 drop(held);
283 verdict
284}
285
286/// The pre-commit body, over the checks it is GIVEN.
287///
288/// A seam, so a test can hand it a check that panics. Without it the value
289/// standing in for a dead check was a literal at one call site that no test
290/// could reach — the rule was asserted on the runner and merely hoped for here.
291fn run_stage(checks: &[&dyn Check], ctx: &Ctx, severities: &Overrides) -> Verdict {
292 run_stage_traced(checks, ctx, severities).0
293}
294
295/// [`run_stage`], keeping the per-check outcomes — index-aligned with
296/// `checks` — alive past the verdict. `pre_commit` needs them to know which
297/// gate-declared checks actually ran (`gate_stamp`); `Report` cannot answer
298/// that, because `classify` deliberately drops the names of `Passed`.
299fn run_stage_traced(
300 checks: &[&dyn Check],
301 ctx: &Ctx,
302 severities: &Overrides,
303) -> (Verdict, Vec<Outcome>) {
304 if checks.is_empty() {
305 return (Verdict::Proceed, Vec::new());
306 }
307 // One slot per check: everything a check says lands in its own buffer
308 // and reaches stdout as ONE block when it finishes — see `live`. Off
309 // (`amont.progress false`), no sink is ever installed and every print
310 // streams exactly as it always did.
311 let stage = crate::live::enabled().then(|| {
312 let names: Vec<&str> = checks.iter().map(|c| c.name()).collect();
313 crate::live::Stage::begin(&names)
314 });
315 let items: Vec<(usize, &&dyn Check)> = checks.iter().enumerate().collect();
316 let outcomes = run_concurrently(
317 &items,
318 |(idx, check)| {
319 let _sink = stage.as_ref().map(|s| s.enter(*idx));
320 // The block is emitted however the check leaves — a panicking
321 // check's partial output still reaches the reader, above the
322 // dead-check verdict `run_concurrently` fills in.
323 let _flush = stage
324 .as_ref()
325 .map(|s| crate::live::FinishOnDrop::new(s, *idx));
326 let sub = Ctx {
327 name: check.name(),
328 args: ctx.args,
329 hooks_dir: ctx.hooks_dir,
330 push: ctx.push,
331 manifest: ctx.manifest,
332 };
333 check.run(&sub)
334 },
335 // A check whose thread died has not passed. Stated here, where the slot
336 // is filled, rather than hidden in a `Default` impl that every future
337 // `#[derive(Default)]` would silently inherit.
338 Outcome::Failed,
339 );
340
341 let report = classify(checks, &outcomes, severities);
342 announce(&report);
343 (report.verdict(), outcomes)
344}
345
346/// What a stage concluded, before anything is printed or exited.
347///
348/// A VALUE, so the classification can be asserted directly. While this was one
349/// function that classified, printed and returned an exit code, its tests could
350/// only check the code — whether the right thing was SAID went untested.
351#[derive(Debug, Default, PartialEq, Eq)]
352struct Report<'a> {
353 /// Repaired. The commit proceeds, but the author's files changed under
354 /// them and that must be said out loud.
355 fixed: Vec<&'a str>,
356 /// Failed, and the severity that applies blocks.
357 blocked: Vec<&'a str>,
358 /// Failed, but configured to warn. The check printed an error and meant it,
359 /// so somebody has to say it did not block.
360 downgraded: Vec<&'a str>,
361 /// Could not run. Distinct from "passed", which is the whole point.
362 unavailable: Vec<&'a str>,
363}
364
365impl Report<'_> {
366 fn verdict(&self) -> Verdict {
367 Verdict::blocking(!self.blocked.is_empty())
368 }
369}
370
371/// Pure: outcomes and severities in, a verdict out. No IO.
372fn classify<'a>(
373 checks: &[&'a dyn Check],
374 outcomes: &[Outcome],
375 severities: &Overrides,
376) -> Report<'a> {
377 let mut report = Report::default();
378 for (check, outcome) in checks.iter().zip(outcomes) {
379 match outcome {
380 // `Warned` needs nothing: a check that chose to warn has already
381 // said what it wanted to, and a roll-up would only repeat it.
382 Outcome::Passed | Outcome::Warned => {}
383 Outcome::Fixed => report.fixed.push(check.name()),
384 Outcome::Unavailable => report.unavailable.push(check.name()),
385 Outcome::Failed => match severities.of(*check) {
386 Severity::Block => report.blocked.push(check.name()),
387 Severity::Warn => report.downgraded.push(check.name()),
388 },
389 }
390 }
391 report
392}
393
394/// Says what happened. Prints; decides nothing.
395fn announce(report: &Report) {
396 if !report.fixed.is_empty() {
397 // Louder than a pass, because files on disk are not what the author
398 // left them: they asked for the repair, but they did not watch it.
399 println!(
400 "{} {} check(s) fixed and re-staged: {}",
401 valid_sign(),
402 report.fixed.len(),
403 report.fixed.join(", ")
404 );
405 }
406 if !report.unavailable.is_empty() {
407 // Distinct from "passed". Silence here is how a repo looks verified
408 // when nothing actually ran — the trailing count is the one line
409 // guaranteed to be read, whatever the twenty blocks above said.
410 println!(
411 "{} {} check(s) could not run: {}",
412 warning_sign(),
413 report.unavailable.len(),
414 report.unavailable.join(", ")
415 );
416 }
417 if !report.downgraded.is_empty() {
418 println!(
419 "{} {} check(s) reported a problem but are set to warn: {}",
420 warning_sign(),
421 report.downgraded.len(),
422 report.downgraded.join(", ")
423 );
424 }
425 if report.blocked.is_empty() {
426 return;
427 }
428 println!("\n🚨 Error raised by:");
429 for name in &report.blocked {
430 println!(" - {}", highlight(name));
431 }
432}
433
434/// Point every check at `git ls-files` instead of the index.
435///
436/// THE definition, called from both entry points. There used to be two: this
437/// one, and a copy in `main.rs` built from a RAW `ls-files` — no `-z` — whose
438/// output git QUOTES for any unusual byte, so `é.json` arrived as the nine-byte
439/// literal `"\303\251.json"` and was handed to prettier and eslint as a path
440/// that does not exist. And because `override_file_set` writes a `OnceLock`,
441/// main's quoted list WON: whichever ran first was the one that counted, and
442/// main's ran first. `git.rs` documents this exact failure.
443pub fn enter_all_files_mode() {
444 crate::hooks::common::override_file_set(
445 crate::git::stdout_paths(&["ls-files"]).unwrap_or_default(),
446 );
447}
448
449/// `amont run` — every applicable check, on demand.
450///
451/// Two questions, and the mode says which it answers:
452///
453/// - **staged** (default) is "would my commit pass" — the same set a commit
454/// would check, so it is a rehearsal of the hook, and it takes the same
455/// index-fidelity hold the hook takes.
456/// - **`--all-files`** is "does my working tree pass". Deliberately NOT the same
457/// question: on a dirty tree it reports on content that is not committed and
458/// may never be. That is right for adopting a check into an existing
459/// repository, where `git add .` is not an acceptable way to measure the mess,
460/// and it is why `--all-files` takes no stash — there is no staged/unstaged
461/// distinction to protect when the answer is "all of it".
462pub fn run_all(ctx: &Ctx, all_files: bool) -> Verdict {
463 // ORDER: the override goes in FIRST. It is what tells `fixing_enabled` and
464 // `restage` that the file set is not the index, and both are consulted
465 // from inside the checks below.
466 if all_files {
467 enter_all_files_mode();
468 if crate::hooks::common::fixing_requested() {
469 println!(
470 "{} {} is set, but fixing is off for {}: the input set is the \
471 working tree, not the index",
472 warning_sign(),
473 highlight("amont.fix"),
474 highlight("--all-files")
475 );
476 }
477 // Stash-free, per decision 1 of docs/index-fidelity-and-run-modes.md:
478 // there is no staged/unstaged distinction to protect when the input
479 // set is `git ls-files`, so a hold would be surprising extra mutation
480 // with no correctness upside.
481 return run_stage(
482 &selected(Stage::PreCommit, ctx.manifest),
483 ctx,
484 &Overrides::read(),
485 );
486 }
487
488 // Staged mode IS a rehearsal of the commit, so it takes the same hold the
489 // commit does. Without it, `amont run` failed on garbage in the tree
490 // that `git commit` — which holds the unstaged half aside — passed, and
491 // vice versa: the two modes disagreed about the same repository, which is
492 // exactly what this mode exists not to do.
493 let held = match hold_unstaged() {
494 Ok(guard) => guard,
495 Err(verdict) => return verdict,
496 };
497 let verdict = run_stage(
498 &selected(Stage::PreCommit, ctx.manifest),
499 ctx,
500 &Overrides::read(),
501 );
502 // AFTER the report has been printed: dropping earlier would put the
503 // unstaged content back under a check that is still reading files.
504 drop(held);
505 verdict
506}
507
508/// `amont run <check>` — one check by name. `None` when there is no such
509/// check, which the caller turns into a usage error.
510///
511/// Lives here rather than in `main.rs` so `registry::lookup` stays inside the
512/// runtime, and so the hold decision is made once: a named check takes the
513/// index-fidelity hold only when it is a `Stage::PreCommit` check running in
514/// staged mode. A pre-push or commit-msg check invoked by name must never
515/// touch the working tree — nothing about a push is a staging operation.
516/// Resolve what `amont run <name>` means, exactly as `hook.skip` resolves a
517/// name — the rest of the tool taught `ban-terms`; making `run` demand the
518/// full id was a pointless second vocabulary. Ambiguity is an answer, not a
519/// guess: the two `branch-pattern` checks are different code at different
520/// stages.
521///
522/// Public because the CALLER needs the answer before anything else happens:
523/// main decides whether to synthesize push refs from the resolved name, and
524/// an ambiguous name must say so rather than fail on a missing upstream it
525/// was never going to use.
526pub fn resolve_check_name(name: &str, manifest: &crate::manifest::Manifest) -> Named2 {
527 if crate::registry::lookup(name, manifest).is_some() {
528 return Named2::Resolved(name.to_string());
529 }
530 let mut matches: Vec<String> = crate::registry::CHECKS
531 .iter()
532 .map(|c| c.name.to_string())
533 .chain(manifest.externals.iter().map(|e| e.id.clone()))
534 .filter(|id| crate::skip_suppresses(id, name))
535 .collect();
536 matches.dedup();
537 match matches.len() {
538 0 => Named2::Unknown,
539 1 => Named2::Resolved(matches.remove(0)),
540 _ => Named2::Ambiguous(matches),
541 }
542}
543
544/// How a run name resolved.
545pub enum Named2 {
546 Resolved(String),
547 Unknown,
548 Ambiguous(Vec<String>),
549}
550
551pub fn run_named(ctx: &Ctx, name: &str, all_files: bool) -> Named {
552 let full: String = match resolve_check_name(name, ctx.manifest) {
553 Named2::Resolved(id) => id,
554 Named2::Unknown => return Named::Unknown,
555 Named2::Ambiguous(ids) => return Named::Ambiguous(ids),
556 };
557 let name = full.as_str();
558 let Some(run_check) = crate::registry::lookup(name, ctx.manifest) else {
559 return Named::Unknown;
560 };
561 // The Ctx must carry the RESOLVED id: lookup's closure re-resolves
562 // through `ctx.name`, and handing it the short name back would panic on
563 // the very ambiguity this function just settled.
564 let ctx = &Ctx {
565 name,
566 args: ctx.args,
567 hooks_dir: ctx.hooks_dir,
568 push: ctx.push,
569 manifest: ctx.manifest,
570 };
571 if all_files {
572 enter_all_files_mode();
573 return Named::Ran(run_check(ctx));
574 }
575 let is_pre_commit_check = crate::registry::one_named(name, ctx.manifest)
576 .is_some_and(|c| c.stage() == Stage::PreCommit);
577 if !is_pre_commit_check {
578 return Named::Ran(run_check(ctx));
579 }
580 let held = match hold_unstaged() {
581 Ok(guard) => guard,
582 Err(verdict) => return Named::Ran(verdict),
583 };
584 let verdict = run_check(ctx);
585 drop(held);
586 Named::Ran(verdict)
587}
588
589/// What `run_named` resolved a name to.
590pub enum Named {
591 Ran(Verdict),
592 /// Nothing matches — full id, short name, or entrypoint.
593 Unknown,
594 /// A short name that reaches more than one check; the caller lists them
595 /// so the user can pick a full id.
596 Ambiguous(Vec<String>),
597}
598
599pub fn pre_push(ctx: &Ctx) -> Verdict {
600 // The notes push `attest` makes re-enters this hook; its ref list is only
601 // ever the attest ref, so there is nothing to prove — and proving it
602 // would recurse.
603 if crate::attest::push_guard_active() {
604 return Verdict::Proceed;
605 }
606 crate::manifest::verify_tool_pins(&ctx.manifest.pins);
607 // NB: no CHERRY_PICK_HEAD check here — the zsh pre-push had none either.
608 let severities = Overrides::read();
609 // pre-push had NO state guard at all, with a comment admitting it existed
610 // only because the zsh version had none. Now it asks the same question
611 // pre-commit does and each check answers for itself.
612 let in_progress = crate::git_states_in_progress();
613 let pre_push_checks = selected_during(Stage::PrePush, &in_progress, ctx.manifest);
614 let stage = crate::live::enabled().then(|| {
615 let names: Vec<&str> = pre_push_checks.iter().map(|c| c.name()).collect();
616 crate::live::Stage::begin(&names)
617 });
618 // What actually PASSED, for the attestation at the bottom. `Warned` and
619 // `Unavailable` stay out — "could not run" is not "passed" — and a
620 // commit-time-gated pair counts, because its stamps say the check ran on
621 // every pushed tree.
622 let mut passed: Vec<String> = Vec::new();
623 for (idx, check) in pre_push_checks.iter().enumerate() {
624 let _sink = stage.as_ref().map(|s| s.enter(idx));
625 let _flush = stage
626 .as_ref()
627 .map(|s| crate::live::FinishOnDrop::new(s, idx));
628 // A declared pre-push external whose NAME is also declared at
629 // pre-commit (blocking) is a gate pair: the commit-time side earned
630 // per-commit stamps, and this side runs only for pushes carrying
631 // commits with no record of it — the same contract the npm gate has
632 // always had, for vocabularies npm never heard of (`cargo test`,
633 // `pytest`, anything). Messages mirror the npm gate's exactly;
634 // docs/checks.md quotes them.
635 if let Some(ext) = ctx
636 .manifest
637 .externals
638 .iter()
639 .find(|e| e.stage == Stage::PrePush && e.id == check.name())
640 {
641 match crate::hooks::run_tests::pair_verdict(ext, ctx.manifest, ctx.push) {
642 crate::hooks::run_tests::PairVerdict::Gated => {
643 crate::say!(
644 "{} {} gated at commit instead — not repeating it here",
645 valid_sign(),
646 highlight(&ext.short_name),
647 );
648 passed.push(check.name().to_string());
649 continue;
650 }
651 crate::hooks::run_tests::PairVerdict::Unstamped(n) => {
652 crate::say!(
653 "{} {} is declared at commit time, but {n} pushed \
654 commit{} carr{} no record of it — running it here",
655 warning_sign(),
656 ext.short_name,
657 if n == 1 { "" } else { "s" },
658 if n == 1 { "ies" } else { "y" },
659 );
660 }
661 crate::hooks::run_tests::PairVerdict::NotPaired => {}
662 }
663 }
664 let sub = Ctx {
665 name: check.name(),
666 args: ctx.args,
667 hooks_dir: ctx.hooks_dir,
668 push: ctx.push,
669 manifest: ctx.manifest,
670 };
671 match check.run(&sub) {
672 Outcome::Passed => passed.push(check.name().to_string()),
673 // Announced, never fatal: a check that could not run has not
674 // invalidated anything, and neither has a warning.
675 Outcome::Unavailable => {
676 println!(
677 "{} {} could not run",
678 warning_sign(),
679 highlight(check.name())
680 )
681 }
682 Outcome::Warned => {}
683 // Cannot occur: `Fix::Rewrite` is refused on a pre-push
684 // declaration, so nothing here can repair anything.
685 Outcome::Fixed => {}
686 Outcome::Failed => match severities.of(*check) {
687 Severity::Warn => println!(
688 "{} {} reported a problem (severity warn)",
689 warning_sign(),
690 highlight(check.name())
691 ),
692 // Fail-fast applies ONLY to Block: the later steps are
693 // expensive and their preconditions are gone.
694 Severity::Block => {
695 println!("\n🚨 Error raised by hook {}", highlight(check.name()));
696 return Verdict::Block;
697 }
698 },
699 }
700 }
701 // Every block gate passed — say so to CI, if this repository opted in.
702 // Gated behind `enabled()` HERE, not just inside `attest_push`: reading
703 // `ctx.push` may consume stdin, and a disabled repo should leave stdin
704 // exactly as it found it.
705 if !passed.is_empty() && crate::attest::enabled() {
706 let remote = ctx
707 .args
708 .first()
709 .map(|a| a.to_string_lossy().into_owned())
710 .unwrap_or_default();
711 crate::attest::attest_push(&remote, ctx.push.get(), &passed);
712 }
713 Verdict::Proceed
714}
715
716#[cfg(test)]
717mod tests {
718 use super::*;
719 use crate::check::{Builtin, Scope};
720 use std::sync::atomic::{AtomicUsize, Ordering};
721
722 /// A check whose only job is to carry a name and a severity into `report`.
723 /// Its `run` is never called — `report` is fed outcomes directly, which is
724 /// what makes `Unavailable` testable at all: the real thing needs a missing
725 /// binary, and a test that uninstalls the developer's toolchain is worse
726 /// than no test.
727 const fn stub(name: &'static str, severity: Severity) -> Builtin {
728 Builtin {
729 name,
730 stage: Stage::PreCommit,
731 scope: Scope::ALWAYS,
732 severity,
733 run: |_| Outcome::Passed,
734 fix: crate::check::Fix::None,
735 reach: crate::check::Reach::Convention,
736 }
737 }
738
739 /// No overrides configured. `report` takes them as a VALUE now, so its
740 /// tests need no repository and no git at all.
741 fn none() -> Overrides {
742 Overrides::default()
743 }
744
745 static BLOCKER: Builtin = stub("stub-blocker", Severity::Block);
746 static WARNER: Builtin = stub("stub-warner", Severity::Warn);
747
748 /// The unit tests hold `&dyn Check` for the same reason the dispatcher
749 /// does: `report` must not be able to tell a built-in from an external.
750 const fn as_checks(cs: [&'static Builtin; 3]) -> [&'static dyn Check; 3] {
751 [cs[0], cs[1], cs[2]]
752 }
753
754 /// The classification itself, which used to be unreachable: while one
755 /// function classified AND printed AND returned a code, a test could assert
756 /// the code and nothing else.
757 #[test]
758 fn every_outcome_lands_in_the_right_bucket() {
759 let checks: [&dyn Check; 4] = [&BLOCKER, &BLOCKER, &WARNER, &BLOCKER];
760 let got = classify(
761 &checks,
762 &[
763 Outcome::Passed,
764 Outcome::Unavailable,
765 Outcome::Failed,
766 Outcome::Failed,
767 ],
768 &none(),
769 );
770 assert_eq!(got.blocked, ["stub-blocker"], "{got:?}");
771 assert_eq!(got.downgraded, ["stub-warner"], "{got:?}");
772 assert_eq!(got.unavailable, ["stub-blocker"], "{got:?}");
773 }
774
775 /// A clean stage concludes nothing at all — not an empty message, no
776 /// message. Twenty checks that passed should print no roll-ups.
777 #[test]
778 fn a_clean_stage_has_nothing_to_report() {
779 let checks: [&dyn Check; 2] = [&BLOCKER, &WARNER];
780 let got = classify(&checks, &[Outcome::Passed, Outcome::Warned], &none());
781 assert_eq!(got, Report::default());
782 assert_eq!(got.verdict(), Verdict::Proceed);
783 }
784
785 #[test]
786 fn a_blocking_failure_is_the_only_thing_that_fails_the_commit() {
787 let b: &dyn Check = &BLOCKER;
788 let w: &dyn Check = &WARNER;
789 assert_eq!(
790 classify(&[b], &[Outcome::Failed], &none()).verdict(),
791 Verdict::Block
792 );
793 assert_eq!(
794 classify(&[b], &[Outcome::Passed], &none()).verdict(),
795 Verdict::Proceed
796 );
797 // Every non-blocking shape, one at a time, so a regression cannot hide
798 // behind a passing sibling.
799 assert_eq!(
800 classify(&[b], &[Outcome::Warned], &none()).verdict(),
801 Verdict::Proceed
802 );
803 assert_eq!(
804 classify(&[b], &[Outcome::Unavailable], &none()).verdict(),
805 Verdict::Proceed
806 );
807 assert_eq!(
808 classify(&[w], &[Outcome::Failed], &none()).verdict(),
809 Verdict::Proceed
810 );
811 }
812
813 #[test]
814 fn one_blocking_failure_among_many_still_fails() {
815 let checks = as_checks([&BLOCKER, &WARNER, &BLOCKER]);
816 assert_eq!(
817 classify(
818 &checks,
819 &[Outcome::Unavailable, Outcome::Failed, Outcome::Failed],
820 &none()
821 )
822 .verdict(),
823 Verdict::Block
824 );
825 // Same shape, with the only *blocking* failure removed.
826 assert_eq!(
827 classify(
828 &checks,
829 &[Outcome::Unavailable, Outcome::Failed, Outcome::Passed],
830 &none()
831 )
832 .verdict(),
833 Verdict::Proceed
834 );
835 }
836
837 /// The slot of a check whose thread died. Reading that as a pass is how a
838 /// crash becomes a green commit.
839 ///
840 /// Asserted through the RUNNER, not through a `Default` impl: the rule
841 /// belongs to this call site, and a test on `Outcome::default()` proved
842 /// only that a trait impl existed, not that the runner used it.
843 /// A check that PANICS must fail the commit, not pass it — and must not
844 /// take the other checks down with it.
845 ///
846 /// Driven through the stage body rather than the runner, because the value
847 /// that stands in for a dead check is chosen at the call site and the
848 /// runner's own test cannot see that choice.
849 #[test]
850 fn a_panicking_check_blocks_the_commit() {
851 static DIES: Builtin = Builtin {
852 name: "stub-dies",
853 stage: Stage::PreCommit,
854 scope: Scope::ALWAYS,
855 severity: Severity::Block,
856 run: |_| panic!("this check died"),
857 fix: crate::check::Fix::None,
858 reach: crate::check::Reach::Convention,
859 };
860 let hook = std::panic::take_hook();
861 std::panic::set_hook(Box::new(|_| {}));
862 let push = crate::pushrefs::PushRefs::default();
863 let manifest = crate::manifest::Manifest::default();
864 let ctx = Ctx {
865 name: "pre-commit",
866 args: &[],
867 hooks_dir: std::path::Path::new("."),
868 push: &push,
869 manifest: &manifest,
870 };
871 let verdict = run_stage(&[&DIES], &ctx, &none());
872 std::panic::set_hook(hook);
873 assert_eq!(
874 verdict,
875 Verdict::Block,
876 "a check that died must not let the commit through"
877 );
878 }
879
880 #[test]
881 fn a_thread_that_dies_leaves_a_failure_behind() {
882 // The default hook would print a backtrace for the deliberate panic and
883 // make a passing run look broken.
884 let hook = std::panic::take_hook();
885 std::panic::set_hook(Box::new(|_| {}));
886 let items = ["a", "b", "c"];
887 let out = run_concurrently(
888 &items,
889 |n: &&str| {
890 if *n == "b" {
891 panic!("this check died");
892 }
893 Outcome::Passed
894 },
895 Outcome::Failed,
896 );
897 std::panic::set_hook(hook);
898 assert_eq!(
899 out,
900 vec![Outcome::Passed, Outcome::Failed, Outcome::Passed],
901 "a dead check must not read as one that passed, \
902 and must not take the other checks down with it"
903 );
904 }
905 use std::time::{Duration, Instant};
906
907 /// Concurrency proved by RENDEZVOUS, not by a stopwatch: every task must
908 /// observe all the others arrive. Were the runner serial, the first task
909 /// would wait alone, time out, and return non-zero — a failure, not a hang.
910 #[test]
911 fn run_concurrently_actually_overlaps() {
912 static ARRIVED: AtomicUsize = AtomicUsize::new(0);
913 ARRIVED.store(0, Ordering::SeqCst);
914 let names: Vec<&'static str> = vec!["a", "b", "c", "d"];
915 let n = names.len();
916
917 let out = run_concurrently(
918 &names,
919 move |_: &&str| {
920 ARRIVED.fetch_add(1, Ordering::SeqCst);
921 let deadline = Instant::now() + Duration::from_secs(10);
922 while ARRIVED.load(Ordering::SeqCst) < n {
923 if Instant::now() > deadline {
924 return 1; // never met the others — execution was serial
925 }
926 std::thread::yield_now();
927 }
928 0
929 },
930 1,
931 );
932 assert!(
933 out.iter().all(|c| *c == 0),
934 "tasks did not overlap: {out:?}"
935 );
936 }
937
938 #[test]
939 fn results_come_back_in_input_order() {
940 let names: Vec<&'static str> = vec!["first", "second", "third"];
941 let out = run_concurrently(&names, |n| if *n == "second" { 7 } else { 0 }, -1);
942 assert_eq!(out, vec![0, 7, 0], "results keep the input order");
943 }
944
945 /// The filter calls the shared resolver rather than restating it. This test
946 /// used to inline `n.contains(s)` — its own copy of the rule — and so went
947 /// on passing after the rule changed underneath it.
948 #[test]
949 fn skips_are_filtered_by_the_shared_resolver() {
950 let all = ["pre-commit-ruff", "pre-commit-prettier"];
951 let skips = ["ruff".to_string()];
952 let kept: Vec<_> = all
953 .iter()
954 .copied()
955 .filter(|n| !skips.iter().any(|s| crate::skip_suppresses(n, s)))
956 .collect();
957 assert_eq!(kept, vec!["pre-commit-prettier"]);
958 }
959}