Skip to main content

amont_runtime/
check.rs

1//! What a check IS, as one value rather than four tables.
2//!
3//! Before this, a check was spread across `REGISTRY` (name → fn), two ordered
4//! name lists, and a language table in the fleet crate — four places keyed by
5//! the same string, held together by reconciliation tests. Those tests were
6//! good, but they policed a shape that should not have been splittable. With
7//! the metadata attached to the check, there is nothing left to reconcile.
8//!
9//! It also gives external checks somewhere to exist. A third party cannot add a
10//! Rust module without rebuilding the binary, so extension means a declared
11//! command implementing this same trait — and the dispatcher not caring which
12//! kind it is holding.
13
14use crate::registry::Ctx;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Stage {
18    PreCommit,
19    PrePush,
20}
21
22impl Stage {
23    pub fn as_str(self) -> &'static str {
24        match self {
25            Stage::PreCommit => "pre-commit",
26            Stage::PrePush => "pre-push",
27        }
28    }
29}
30
31/// When a check is relevant, declared rather than reimplemented by every
32/// reader.
33///
34/// A CONJUNCTION, not a choice: ruff is `.py` files AND a ruff config; clippy
35/// is `.rs` AND `Cargo.toml`. An earlier design offered these as alternatives
36/// plus a `Custom` escape hatch, which would have swallowed nearly every check
37/// and left the dashboard knowing nothing.
38/// A git operation that is part-way through.
39///
40/// Detected from the marker files git writes into `$GIT_DIR`, which is how git
41/// itself and every prompt-writer answers the question.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum GitState {
44    Merge,
45    Rebase,
46    CherryPick,
47    Revert,
48    Bisect,
49}
50
51impl GitState {
52    /// The marker git writes. `rebase-merge` and `rebase-apply` are
53    /// DIRECTORIES; the rest are files, and `Path::exists` covers both.
54    pub fn markers(self) -> &'static [&'static str] {
55        match self {
56            GitState::Merge => &["MERGE_HEAD"],
57            GitState::Rebase => &["REBASE_HEAD", "rebase-merge", "rebase-apply"],
58            GitState::CherryPick => &["CHERRY_PICK_HEAD"],
59            GitState::Revert => &["REVERT_HEAD"],
60            GitState::Bisect => &["BISECT_LOG"],
61        }
62    }
63
64    pub fn as_str(self) -> &'static str {
65        match self {
66            GitState::Merge => "a merge",
67            GitState::Rebase => "a rebase",
68            GitState::CherryPick => "a cherry-pick",
69            GitState::Revert => "a revert",
70            GitState::Bisect => "a bisect",
71        }
72    }
73
74    pub const ALL: [GitState; 5] = [
75        GitState::Merge,
76        GitState::Rebase,
77        GitState::CherryPick,
78        GitState::Revert,
79        GitState::Bisect,
80    ];
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct Scope {
85    /// Extensions that trigger it. Empty means any change.
86    pub files: &'static [&'static str],
87    /// Exact FILENAMES that trigger it — `package.json`, `Dockerfile` —
88    /// matched against the path's basename, never as a suffix: an extension
89    /// list cannot say "package.json" without also matching
90    /// `not-package.json`. Builtins keep this empty; the manifest's scope
91    /// column fills it.
92    pub names: &'static [&'static str],
93    /// Config paths that opt a repository in. Empty means always on.
94    pub opt_in: &'static [&'static str],
95    /// Git operations during which this check does not run.
96    ///
97    /// The other half of "when does this apply". `files` and `opt_in` say which
98    /// REPOSITORIES and which CHANGES; this says which repository STATES — a
99    /// question that used to be answered by one hard-coded `CHERRY_PICK_HEAD`
100    /// test in one dispatcher, with the other carrying a comment admitting it
101    /// had none because the shell version had none.
102    pub not_during: &'static [GitState],
103}
104
105impl Scope {
106    pub const ALWAYS: Scope = Scope {
107        files: &[],
108        names: &[],
109        opt_in: &[],
110        not_during: &[],
111    };
112
113    pub const fn files(files: &'static [&'static str]) -> Scope {
114        Scope {
115            files,
116            names: &[],
117            opt_in: &[],
118            not_during: &[],
119        }
120    }
121
122    pub const fn new(files: &'static [&'static str], opt_in: &'static [&'static str]) -> Scope {
123        Scope {
124            files,
125            names: &[],
126            opt_in,
127            not_during: &[],
128        }
129    }
130
131    /// The same scope, silent during these operations.
132    pub const fn not_during(self, states: &'static [GitState]) -> Scope {
133        Scope {
134            files: self.files,
135            names: self.names,
136            opt_in: self.opt_in,
137            not_during: states,
138        }
139    }
140
141    /// No file gate at all — every change is in scope.
142    pub fn is_unscoped(&self) -> bool {
143        self.files.is_empty() && self.names.is_empty()
144    }
145
146    /// Does ONE path fall inside the file gate?
147    pub fn covers(&self, path: &str) -> bool {
148        self.files.iter().any(|ext| path.ends_with(ext)) || {
149            let base = path.rsplit('/').next().unwrap_or(path);
150            self.names.contains(&base)
151        }
152    }
153
154    /// Does this gate have work to do, given the files a PUSH changed?
155    ///
156    /// Distinct from [`matches`], and the distinction is the bug this was
157    /// written for. `matches` answers "would this check ever fire in a
158    /// repository containing these paths", so it also consults `opt_in` —
159    /// the marker that says a repository is a Rust one at all. Feeding a
160    /// push DIFF to that question conflates two things: whether the
161    /// repository is Rust (settled long before, when the dispatcher decided
162    /// this check runs here) and whether this push changed any Rust.
163    ///
164    /// `pre-push-cargo-test` opts in on `Cargo.toml`. A `.rs`-only push, in
165    /// a repository with a `Cargo.toml` sitting right there, therefore
166    /// answered NO to "is this a Rust repository" — because that one file
167    /// was not in the diff — and was judged to have nothing worth attesting.
168    /// Which is to say: the most ordinary Rust push there is.
169    ///
170    /// Opt-in is a fact about the repository. This asks only about the
171    /// change, which is what a caller holding a diff means.
172    pub fn touches(&self, paths: &[String]) -> bool {
173        self.is_unscoped() || paths.iter().any(|p| self.covers(p))
174    }
175
176    /// Did the gate see EVERY one of `paths`? All-match, where [`matches`]
177    /// is any-match: the caller asking this is deciding whether a commit-time
178    /// run COVERED a push, and under-approximating is the safe direction.
179    pub fn covers_all(&self, paths: &[String]) -> bool {
180        self.is_unscoped() || paths.iter().all(|p| self.covers(p))
181    }
182
183    /// Would this check ever fire, given the paths a repository contains?
184    ///
185    /// Deliberately coarse for checks that resolve an ancestor at run time —
186    /// `cargo-fmt` declares `Cargo.toml` meaning "somewhere here" while
187    /// enforcing "nearest above the staged file". The dispatcher asks the
188    /// precise question by running the check; this answers the dashboard's
189    /// question, "would it ever fire", where over-approximating is the safe
190    /// direction.
191    pub fn matches(&self, paths: &[String]) -> bool {
192        let by_ext = self.is_unscoped() || paths.iter().any(|path| self.covers(path));
193        let opted_in = self.opt_in.is_empty()
194            || paths.iter().any(|p| {
195                let name = p.rsplit('/').next().unwrap_or(p);
196                self.opt_in.iter().any(|c| {
197                    // A trailing `*` is a prefix match: `.kube-linter*.yaml`.
198                    match c.split_once('*') {
199                        Some((pre, suf)) => name.starts_with(pre) && name.ends_with(suf),
200                        None => name == *c,
201                    }
202                })
203            });
204        by_ext && opted_in
205    }
206}
207
208/// What a check meant, as opposed to what it printed.
209///
210/// The fourth variant is the point. Fifteen sites used to warn and return 0,
211/// collapsing two different situations: "I ran and found something you should
212/// know" and "I could not run at all". `ruff config found but no ruff binary`
213/// was indistinguishable from ruff running clean — to the dispatcher, and to
214/// the dashboard. A repository where a check has silently never executed read
215/// as one where it passes.
216///
217/// That is the same invisibility `hook.skip` had before skipped checks were
218/// announced, and it took three PRs to notice there.
219///
220/// The check still prints its own message; this only classifies the result.
221///
222/// Deliberately NO `Default`. It used to be `Failed`, to fill the slot of a
223/// check whose thread died — a real rule, but `Default` means "the neutral
224/// value" to every reader and to every `#[derive(Default)]` that might later
225/// contain one. The rule is now written where it applies, in the runner.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum Outcome {
228    Passed,
229    /// Ran, found a problem. Whether that blocks is `Severity`, not this.
230    Failed,
231    /// Ran, found something worth saying, which does not block.
232    Warned,
233    /// Ran, found a problem, and REPAIRED it. The commit proceeds with the
234    /// repair staged, which is neither `Passed` (something happened, and the
235    /// author should know their files changed) nor `Failed`.
236    Fixed,
237    /// COULD NOT RUN — a tool is missing, or the opt-in config is absent.
238    Unavailable,
239}
240
241/// What a HOOK concluded — the only thing git actually reads.
242///
243/// Distinct from `Outcome`, which is what one CHECK concluded. Git has exactly
244/// two questions to ask a hook, so this has exactly two answers, and the `i32`
245/// that expresses them lives at the process boundary rather than being threaded
246/// through every hook, dispatcher and handler as it used to be.
247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
248pub enum Verdict {
249    Proceed,
250    Block,
251}
252
253impl Verdict {
254    /// The exit code git reads. The ONLY place a hook result becomes a number.
255    pub fn exit_code(self) -> i32 {
256        match self {
257            Verdict::Proceed => 0,
258            Verdict::Block => 1,
259        }
260    }
261
262    pub fn blocking(blocked: bool) -> Verdict {
263        if blocked {
264            Verdict::Block
265        } else {
266            Verdict::Proceed
267        }
268    }
269}
270
271/// Whether a failing check stops the commit or merely reports.
272///
273/// Declared per check and overridable per repository with
274/// `git config amont.severity.<check> warn`. That is a better escape hatch
275/// than `hook.skip`, which is all-or-nothing and invisible enough that
276/// `hook.skip = e` disables all twenty checks: a downgrade keeps the signal and
277/// removes only the block.
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279pub enum Severity {
280    Block,
281    Warn,
282}
283
284impl Severity {
285    /// The ONE mapping from configured text to severity.
286    ///
287    /// There were four: this key's reader, the manifest's severity column, the
288    /// dashboard's copy, and the dashboard's reverse mapping for `--json`. They
289    /// agreed, but nothing made them — and the dashboard's copy is its
290    /// prediction of what the dispatcher will do, which is the one thing it must
291    /// never get wrong.
292    ///
293    /// `None` for anything else, deliberately: git validates nothing here, so an
294    /// unrecognised value must fall back to the declared severity rather than
295    /// silently disable a check.
296    pub fn parse(value: &str) -> Option<Severity> {
297        match value {
298            "warn" => Some(Severity::Warn),
299            "block" => Some(Severity::Block),
300            _ => None,
301        }
302    }
303
304    /// How it is written in config and in `--json`.
305    pub fn as_str(self) -> &'static str {
306        match self {
307            Severity::Block => "block",
308            Severity::Warn => "warn",
309        }
310    }
311}
312
313/// Whether a check can rewrite the files it inspects.
314///
315/// Off by default and per check, never global: a hook that edits your files
316/// without being asked is a larger surprise than one that complains.
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318pub enum Fix {
319    /// Reports only. Every check, until somebody declares otherwise.
320    None,
321    /// Runs a command that rewrites files, and stages what it changed.
322    ///
323    /// Only reachable from a `Stage::PreCommit` declaration. A pre-push hook
324    /// must not modify the worktree or index: the pushed commit would then
325    /// differ from the tree the developer is looking at.
326    Rewrite,
327}
328
329impl Fix {
330    /// How it is written in `--json`. No `parse()`: nothing reads a `Fix`
331    /// back out of text — the manifest's `fix` marker has its own, unrelated
332    /// parsing path in `manifest.rs`.
333    pub fn as_str(self) -> &'static str {
334        match self {
335            Fix::None => "none",
336            Fix::Rewrite => "rewrite",
337        }
338    }
339}
340
341/// One check, whether compiled in or declared by the repository.
342///
343/// `Sync` because `pre-commit` hands every check to its own thread. Both
344/// implementations satisfy it for free, and requiring it here is what lets the
345/// dispatcher hold `&'static dyn Check` without caring which kind it has.
346pub trait Check: Sync {
347    fn name(&self) -> &str;
348    fn stage(&self) -> Stage;
349    fn scope(&self) -> Scope;
350    /// The name a commit-time declaration must use to pair with this gate.
351    ///
352    /// Deliberately the SHORT name, and deliberately not the id: pairing is
353    /// cross-stage by definition — `test` declared at `pre-commit` pairs
354    /// with `test` at `pre-push` — so the id, which encodes the stage, is
355    /// the one key that cannot work. `pre-push-cargo-test` would be compared
356    /// against a `GateDecl.script` of `cargo-test` and never match, and the
357    /// failure would be silence rather than an error: the gate simply never
358    /// pairs and nobody is told why.
359    ///
360    /// This is the single place where comparing short names is correct,
361    /// which is why it is a named method rather than a `short_name()` call
362    /// at the comparison site — that function's own documentation says never
363    /// to compare against it, and it is right everywhere else.
364    fn pairing_name(&self) -> &str {
365        crate::short_name(self.name())
366    }
367    fn severity(&self) -> Severity;
368    /// Whether this check can repair what it finds. `None` for almost all.
369    fn fix(&self) -> Fix {
370        Fix::None
371    }
372    /// How far the check reaches when `amont.conventions` is `declared` —
373    /// see [`Reach`]. Externals default to `Convention`, which costs them
374    /// nothing: a declared check only exists where an `amont.conf` does,
375    /// and that is exactly the declaration the mode asks for.
376    fn reach(&self) -> Reach {
377        Reach::Convention
378    }
379    fn run(&self, ctx: &Ctx) -> Outcome;
380}
381
382/// How far a check reaches into repositories that never asked for it.
383///
384/// With `git config --global amont.conventions declared`, hooks installed by
385/// a standing grant (`init.templateDir`) split in two: `Safety` checks run in
386/// EVERY repository, because their findings are mistakes in any codebase — a
387/// conflict marker, a leaked credential, a hundred-megabyte blob, a
388/// `debugger;` left in the diff. `Convention` checks run only where the
389/// repository has committed an `amont.conf` — they are one team's house
390/// rules (commit shapes, branch names, lint severities, test gates), and a
391/// clone of somebody else's project did not agree to them.
392///
393/// The default mode is `everywhere`, where this distinction is inert.
394#[derive(Debug, Clone, Copy, PartialEq, Eq)]
395pub enum Reach {
396    /// A mistake anywhere: runs regardless of declaration.
397    Safety,
398    /// A house rule: runs only where the repository declares amont.
399    Convention,
400}
401
402/// A check compiled into the binary.
403pub struct Builtin {
404    pub name: &'static str,
405    pub stage: Stage,
406    pub scope: Scope,
407    pub severity: Severity,
408    pub run: fn(&Ctx) -> Outcome,
409    /// Almost always `Fix::None`; see `CHECKS`.
410    pub fix: Fix,
411    /// Almost always `Convention`; the exceptions are pinned in the registry.
412    pub reach: Reach,
413}
414
415impl Check for Builtin {
416    fn name(&self) -> &str {
417        self.name
418    }
419    fn stage(&self) -> Stage {
420        self.stage
421    }
422    fn scope(&self) -> Scope {
423        self.scope
424    }
425    fn severity(&self) -> Severity {
426        self.severity
427    }
428    fn fix(&self) -> Fix {
429        self.fix
430    }
431    fn reach(&self) -> Reach {
432        self.reach
433    }
434    fn run(&self, ctx: &Ctx) -> Outcome {
435        (self.run)(ctx)
436    }
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442
443    /// Round-trips, and refuses everything else. A `Some` for an unknown value
444    /// would turn a typo into a silent disable.
445    #[test]
446    fn severity_parses_exactly_the_two_words_it_documents() {
447        for s in [Severity::Block, Severity::Warn] {
448            assert_eq!(Severity::parse(s.as_str()), Some(s));
449        }
450        for bad in ["", "Warn", "WARN", "advisory", "true", "1", " warn"] {
451            assert_eq!(Severity::parse(bad), None, "{bad:?} must not parse");
452        }
453    }
454
455    #[test]
456    fn fix_says_how_it_is_written_in_json() {
457        assert_eq!(Fix::None.as_str(), "none");
458        assert_eq!(Fix::Rewrite.as_str(), "rewrite");
459    }
460
461    #[test]
462    fn always_matches_anything() {
463        assert!(Scope::ALWAYS.matches(&[]));
464        assert!(Scope::ALWAYS.matches(&["README.md".into()]));
465    }
466
467    #[test]
468    fn extensions_gate_on_the_file_type() {
469        let s = Scope::files(&[".rs"]);
470        assert!(s.matches(&["src/main.rs".into()]));
471        assert!(!s.matches(&["README.md".into()]));
472    }
473
474    /// The case the enum could not express: BOTH conditions must hold.
475    #[test]
476    fn files_and_opt_in_are_a_conjunction() {
477        let ruff = Scope::new(&[".py"], &["ruff.toml", "pyproject.toml"]);
478        assert!(
479            !ruff.matches(&["a.py".into()]),
480            "python alone is not enough — the repo must opt in"
481        );
482        assert!(
483            !ruff.matches(&["pyproject.toml".into()]),
484            "and a config alone is not enough without python"
485        );
486        assert!(ruff.matches(&["a.py".into(), "pyproject.toml".into()]));
487    }
488
489    /// `.kube-linter*.yaml` is a real config name in this repo's own hooks.
490    #[test]
491    fn a_trailing_star_is_a_prefix_match() {
492        let s = Scope::new(&[".yaml"], &[".kube-linter*.yaml"]);
493        assert!(s.matches(&["k8s/x.yaml".into(), ".kube-linter-prod.yaml".into()]));
494        assert!(!s.matches(&["k8s/x.yaml".into(), ".kube-lint.yaml".into()]));
495    }
496
497    /// Opt-in matches a BASENAME anywhere, which is what makes the coarse
498    /// answer right for a check that resolves an ancestor when it runs.
499    #[test]
500    fn opt_in_matches_a_nested_manifest() {
501        let cargo = Scope::new(&[".rs"], &["Cargo.toml"]);
502        assert!(cargo.matches(&["crates/a/src/lib.rs".into(), "crates/a/Cargo.toml".into()]));
503    }
504}