Skip to main content

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    crate::manifest::verify_tool_pins(&ctx.manifest.pins);
601    // NB: no CHERRY_PICK_HEAD check here — the zsh pre-push had none either.
602    let severities = Overrides::read();
603    // pre-push had NO state guard at all, with a comment admitting it existed
604    // only because the zsh version had none. Now it asks the same question
605    // pre-commit does and each check answers for itself.
606    let in_progress = crate::git_states_in_progress();
607    let pre_push_checks = selected_during(Stage::PrePush, &in_progress, ctx.manifest);
608    let stage = crate::live::enabled().then(|| {
609        let names: Vec<&str> = pre_push_checks.iter().map(|c| c.name()).collect();
610        crate::live::Stage::begin(&names)
611    });
612    for (idx, check) in pre_push_checks.iter().enumerate() {
613        let _sink = stage.as_ref().map(|s| s.enter(idx));
614        let _flush = stage
615            .as_ref()
616            .map(|s| crate::live::FinishOnDrop::new(s, idx));
617        // A declared pre-push external whose NAME is also declared at
618        // pre-commit (blocking) is a gate pair: the commit-time side earned
619        // per-commit stamps, and this side runs only for pushes carrying
620        // commits with no record of it — the same contract the npm gate has
621        // always had, for vocabularies npm never heard of (`cargo test`,
622        // `pytest`, anything). Messages mirror the npm gate's exactly;
623        // docs/checks.md quotes them.
624        if let Some(ext) = ctx
625            .manifest
626            .externals
627            .iter()
628            .find(|e| e.stage == Stage::PrePush && e.id == check.name())
629        {
630            match crate::hooks::run_tests::pair_verdict(ext, ctx.manifest, ctx.push) {
631                crate::hooks::run_tests::PairVerdict::Gated => {
632                    crate::say!(
633                        "{} {} gated at commit instead — not repeating it here",
634                        valid_sign(),
635                        highlight(&ext.short_name),
636                    );
637                    continue;
638                }
639                crate::hooks::run_tests::PairVerdict::Unstamped(n) => {
640                    crate::say!(
641                        "{} {} is declared at commit time, but {n} pushed \
642                         commit{} carr{} no record of it — running it here",
643                        warning_sign(),
644                        ext.short_name,
645                        if n == 1 { "" } else { "s" },
646                        if n == 1 { "ies" } else { "y" },
647                    );
648                }
649                crate::hooks::run_tests::PairVerdict::NotPaired => {}
650            }
651        }
652        let sub = Ctx {
653            name: check.name(),
654            args: ctx.args,
655            hooks_dir: ctx.hooks_dir,
656            push: ctx.push,
657            manifest: ctx.manifest,
658        };
659        match check.run(&sub) {
660            Outcome::Passed => {}
661            // Announced, never fatal: a check that could not run has not
662            // invalidated anything, and neither has a warning.
663            Outcome::Unavailable => {
664                println!(
665                    "{} {} could not run",
666                    warning_sign(),
667                    highlight(check.name())
668                )
669            }
670            Outcome::Warned => {}
671            // Cannot occur: `Fix::Rewrite` is refused on a pre-push
672            // declaration, so nothing here can repair anything.
673            Outcome::Fixed => {}
674            Outcome::Failed => match severities.of(*check) {
675                Severity::Warn => println!(
676                    "{} {} reported a problem (severity warn)",
677                    warning_sign(),
678                    highlight(check.name())
679                ),
680                // Fail-fast applies ONLY to Block: the later steps are
681                // expensive and their preconditions are gone.
682                Severity::Block => {
683                    println!("\n🚨  Error raised by hook {}", highlight(check.name()));
684                    return Verdict::Block;
685                }
686            },
687        }
688    }
689    Verdict::Proceed
690}
691
692#[cfg(test)]
693mod tests {
694    use super::*;
695    use crate::check::{Builtin, Scope};
696    use std::sync::atomic::{AtomicUsize, Ordering};
697
698    /// A check whose only job is to carry a name and a severity into `report`.
699    /// Its `run` is never called — `report` is fed outcomes directly, which is
700    /// what makes `Unavailable` testable at all: the real thing needs a missing
701    /// binary, and a test that uninstalls the developer's toolchain is worse
702    /// than no test.
703    const fn stub(name: &'static str, severity: Severity) -> Builtin {
704        Builtin {
705            name,
706            stage: Stage::PreCommit,
707            scope: Scope::ALWAYS,
708            severity,
709            run: |_| Outcome::Passed,
710            fix: crate::check::Fix::None,
711            reach: crate::check::Reach::Convention,
712        }
713    }
714
715    /// No overrides configured. `report` takes them as a VALUE now, so its
716    /// tests need no repository and no git at all.
717    fn none() -> Overrides {
718        Overrides::default()
719    }
720
721    static BLOCKER: Builtin = stub("stub-blocker", Severity::Block);
722    static WARNER: Builtin = stub("stub-warner", Severity::Warn);
723
724    /// The unit tests hold `&dyn Check` for the same reason the dispatcher
725    /// does: `report` must not be able to tell a built-in from an external.
726    const fn as_checks(cs: [&'static Builtin; 3]) -> [&'static dyn Check; 3] {
727        [cs[0], cs[1], cs[2]]
728    }
729
730    /// The classification itself, which used to be unreachable: while one
731    /// function classified AND printed AND returned a code, a test could assert
732    /// the code and nothing else.
733    #[test]
734    fn every_outcome_lands_in_the_right_bucket() {
735        let checks: [&dyn Check; 4] = [&BLOCKER, &BLOCKER, &WARNER, &BLOCKER];
736        let got = classify(
737            &checks,
738            &[
739                Outcome::Passed,
740                Outcome::Unavailable,
741                Outcome::Failed,
742                Outcome::Failed,
743            ],
744            &none(),
745        );
746        assert_eq!(got.blocked, ["stub-blocker"], "{got:?}");
747        assert_eq!(got.downgraded, ["stub-warner"], "{got:?}");
748        assert_eq!(got.unavailable, ["stub-blocker"], "{got:?}");
749    }
750
751    /// A clean stage concludes nothing at all — not an empty message, no
752    /// message. Twenty checks that passed should print no roll-ups.
753    #[test]
754    fn a_clean_stage_has_nothing_to_report() {
755        let checks: [&dyn Check; 2] = [&BLOCKER, &WARNER];
756        let got = classify(&checks, &[Outcome::Passed, Outcome::Warned], &none());
757        assert_eq!(got, Report::default());
758        assert_eq!(got.verdict(), Verdict::Proceed);
759    }
760
761    #[test]
762    fn a_blocking_failure_is_the_only_thing_that_fails_the_commit() {
763        let b: &dyn Check = &BLOCKER;
764        let w: &dyn Check = &WARNER;
765        assert_eq!(
766            classify(&[b], &[Outcome::Failed], &none()).verdict(),
767            Verdict::Block
768        );
769        assert_eq!(
770            classify(&[b], &[Outcome::Passed], &none()).verdict(),
771            Verdict::Proceed
772        );
773        // Every non-blocking shape, one at a time, so a regression cannot hide
774        // behind a passing sibling.
775        assert_eq!(
776            classify(&[b], &[Outcome::Warned], &none()).verdict(),
777            Verdict::Proceed
778        );
779        assert_eq!(
780            classify(&[b], &[Outcome::Unavailable], &none()).verdict(),
781            Verdict::Proceed
782        );
783        assert_eq!(
784            classify(&[w], &[Outcome::Failed], &none()).verdict(),
785            Verdict::Proceed
786        );
787    }
788
789    #[test]
790    fn one_blocking_failure_among_many_still_fails() {
791        let checks = as_checks([&BLOCKER, &WARNER, &BLOCKER]);
792        assert_eq!(
793            classify(
794                &checks,
795                &[Outcome::Unavailable, Outcome::Failed, Outcome::Failed],
796                &none()
797            )
798            .verdict(),
799            Verdict::Block
800        );
801        // Same shape, with the only *blocking* failure removed.
802        assert_eq!(
803            classify(
804                &checks,
805                &[Outcome::Unavailable, Outcome::Failed, Outcome::Passed],
806                &none()
807            )
808            .verdict(),
809            Verdict::Proceed
810        );
811    }
812
813    /// The slot of a check whose thread died. Reading that as a pass is how a
814    /// crash becomes a green commit.
815    ///
816    /// Asserted through the RUNNER, not through a `Default` impl: the rule
817    /// belongs to this call site, and a test on `Outcome::default()` proved
818    /// only that a trait impl existed, not that the runner used it.
819    /// A check that PANICS must fail the commit, not pass it — and must not
820    /// take the other checks down with it.
821    ///
822    /// Driven through the stage body rather than the runner, because the value
823    /// that stands in for a dead check is chosen at the call site and the
824    /// runner's own test cannot see that choice.
825    #[test]
826    fn a_panicking_check_blocks_the_commit() {
827        static DIES: Builtin = Builtin {
828            name: "stub-dies",
829            stage: Stage::PreCommit,
830            scope: Scope::ALWAYS,
831            severity: Severity::Block,
832            run: |_| panic!("this check died"),
833            fix: crate::check::Fix::None,
834            reach: crate::check::Reach::Convention,
835        };
836        let hook = std::panic::take_hook();
837        std::panic::set_hook(Box::new(|_| {}));
838        let push = crate::pushrefs::PushRefs::default();
839        let manifest = crate::manifest::Manifest::default();
840        let ctx = Ctx {
841            name: "pre-commit",
842            args: &[],
843            hooks_dir: std::path::Path::new("."),
844            push: &push,
845            manifest: &manifest,
846        };
847        let verdict = run_stage(&[&DIES], &ctx, &none());
848        std::panic::set_hook(hook);
849        assert_eq!(
850            verdict,
851            Verdict::Block,
852            "a check that died must not let the commit through"
853        );
854    }
855
856    #[test]
857    fn a_thread_that_dies_leaves_a_failure_behind() {
858        // The default hook would print a backtrace for the deliberate panic and
859        // make a passing run look broken.
860        let hook = std::panic::take_hook();
861        std::panic::set_hook(Box::new(|_| {}));
862        let items = ["a", "b", "c"];
863        let out = run_concurrently(
864            &items,
865            |n: &&str| {
866                if *n == "b" {
867                    panic!("this check died");
868                }
869                Outcome::Passed
870            },
871            Outcome::Failed,
872        );
873        std::panic::set_hook(hook);
874        assert_eq!(
875            out,
876            vec![Outcome::Passed, Outcome::Failed, Outcome::Passed],
877            "a dead check must not read as one that passed, \
878             and must not take the other checks down with it"
879        );
880    }
881    use std::time::{Duration, Instant};
882
883    /// Concurrency proved by RENDEZVOUS, not by a stopwatch: every task must
884    /// observe all the others arrive. Were the runner serial, the first task
885    /// would wait alone, time out, and return non-zero — a failure, not a hang.
886    #[test]
887    fn run_concurrently_actually_overlaps() {
888        static ARRIVED: AtomicUsize = AtomicUsize::new(0);
889        ARRIVED.store(0, Ordering::SeqCst);
890        let names: Vec<&'static str> = vec!["a", "b", "c", "d"];
891        let n = names.len();
892
893        let out = run_concurrently(
894            &names,
895            move |_: &&str| {
896                ARRIVED.fetch_add(1, Ordering::SeqCst);
897                let deadline = Instant::now() + Duration::from_secs(10);
898                while ARRIVED.load(Ordering::SeqCst) < n {
899                    if Instant::now() > deadline {
900                        return 1; // never met the others — execution was serial
901                    }
902                    std::thread::yield_now();
903                }
904                0
905            },
906            1,
907        );
908        assert!(
909            out.iter().all(|c| *c == 0),
910            "tasks did not overlap: {out:?}"
911        );
912    }
913
914    #[test]
915    fn results_come_back_in_input_order() {
916        let names: Vec<&'static str> = vec!["first", "second", "third"];
917        let out = run_concurrently(&names, |n| if *n == "second" { 7 } else { 0 }, -1);
918        assert_eq!(out, vec![0, 7, 0], "results keep the input order");
919    }
920
921    /// The filter calls the shared resolver rather than restating it. This test
922    /// used to inline `n.contains(s)` — its own copy of the rule — and so went
923    /// on passing after the rule changed underneath it.
924    #[test]
925    fn skips_are_filtered_by_the_shared_resolver() {
926        let all = ["pre-commit-ruff", "pre-commit-prettier"];
927        let skips = ["ruff".to_string()];
928        let kept: Vec<_> = all
929            .iter()
930            .copied()
931            .filter(|n| !skips.iter().any(|s| crate::skip_suppresses(n, s)))
932            .collect();
933        assert_eq!(kept, vec!["pre-commit-prettier"]);
934    }
935}