Skip to main content

amont_runtime/
manifest.rs

1//! `amont.conf` — checks a repository declares for itself.
2//!
3//! A third party cannot add a Rust module without rebuilding this binary, so
4//! extension means declared commands.
5//!
6//! The manifest is **committed at the repository root**, and that is the point.
7//! `.git/hooks` is not committed, so under the old filename-prefix mechanism a
8//! team could never actually share a custom hook — every member had to install
9//! it by hand, and nothing told them when it changed. That flaw mattered more
10//! than the lexicographic ordering usually cited against prefixes.
11//!
12//! ```text
13//! # stage       name        scope   severity  command
14//! pre-commit    lint-shell  *.sh    block     scripts/lint-shell.sh
15//! pre-push      smoke       *       warn      make smoke
16//! ```
17//!
18//! Whitespace-delimited, in file order. TOML would be nicer to write and costs a
19//! dependency tree that would then run on every commit in ninety-six
20//! repositories; for four fields and a command, the twenty lines of parsing win.
21//! See `scripts/check-no-deps.sh` for why that trade is the default here.
22//!
23//! ## No shell
24//!
25//! The command is split on whitespace and executed directly. There is no shell,
26//! so no pipes, no redirection, no globbing and no quoting. Two reasons, and the
27//! second is the one that decided it: Windows has no `sh`, and every emulation
28//! of one this project has tried has been a source of bugs; and a manifest line
29//! that silently gained shell semantics would be a much larger thing to have
30//! introduced than it looks. A pipeline belongs in a script the line invokes.
31//!
32//! ## A line that cannot be understood is not skipped
33//!
34//! A malformed line means a check the repository asked for is not running, which
35//! is precisely the "looks verified, enforced nothing" failure `Outcome` exists
36//! to name. So a broken line still produces a check — one that runs to
37//! `Unavailable` and says why. It appears in the dispatcher's "could not run"
38//! roll-up like any other gap, rather than needing a mechanism of its own.
39
40use std::path::Path;
41use std::process::{Command, Stdio};
42
43use crate::check::{Check, Fix, Outcome, Scope, Severity, Stage};
44use crate::hooks::common::Restaged;
45use crate::registry::{Ctx, CHECKS, ENTRYPOINTS};
46
47pub const MANIFEST: &str = "amont.conf";
48
49/// Why a line could not be used.
50///
51/// A type rather than a `String`: the prose belongs in `Display`, and a caller
52/// that wants to ask "was this a duplicate?" should not have to grep for the
53/// word. The tests used to assert on substrings, which coupled them to wording
54/// and would have kept passing if the wording stayed while the meaning changed.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum ParseError {
57    MissingFields,
58    MissingName,
59    /// Names a check compiled into the binary.
60    NameTaken(String),
61    /// The name is a trigger, or carries one as a prefix.
62    ///
63    /// `pre-commit  pre-commit-clippy  …` would declare a check whose SHORT
64    /// name is another check's full id, so `hook.skip pre-commit-clippy` would
65    /// mean two things at once. The stage column supplies the trigger; writing
66    /// it again in the name is the one way to make an id ambiguous.
67    TriggerInName(String),
68    /// A second USABLE line claiming a name already claimed ON THE SAME
69    /// TRIGGER. The same name on both triggers is two checks, not a clash.
70    Duplicate(String),
71    BadStage(String),
72    BadScope(String),
73    BadSeverity(String),
74    /// A `tool` line with the wrong shape.
75    BadTool,
76    /// A `severity`/`skip`/`set` line with the wrong shape; carries the usage.
77    BadPolicyLine(&'static str),
78    /// A `set` line naming a key policy may not reach.
79    UnsettableKey(String),
80    /// A `pre-push` line asked to rewrite files.
81    ///
82    /// Refused HERE, beside `NameTaken` and `Duplicate`, rather than as a
83    /// runtime "contract violation" at push time: same fact, discovered
84    /// earlier, by more people, at the moment it is cheapest to fix. A pre-push
85    /// hook must not modify the worktree or index — the pushed commit would
86    /// then differ from the tree the developer is looking at.
87    FixOnPrePush,
88}
89
90impl std::fmt::Display for ParseError {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        match self {
93            ParseError::MissingFields => {
94                write!(f, "expected 5 fields: stage name scope severity command")
95            }
96            ParseError::MissingName => write!(f, "missing name"),
97            ParseError::NameTaken(n) => write!(f, "{n:?} already names a check"),
98            ParseError::TriggerInName(n) => write!(
99                f,
100                "{n:?} must not be a trigger or start with one — the stage column says which"
101            ),
102            ParseError::Duplicate(n) => write!(f, "{n:?} is declared twice on one trigger"),
103            ParseError::BadStage(t) => {
104                write!(f, "stage {t:?} must be `pre-commit` or `pre-push`")
105            }
106            ParseError::BadScope(t) => write!(
107                f,
108                "scope {t:?} must be `*`, `*.<ext>`, or a bare filename (no `/`), \
109                 optionally followed by `+<file>` the repository must carry"
110            ),
111            ParseError::BadTool => write!(
112                f,
113                "a tool pin is exactly `tool <program> <version-substring>`"
114            ),
115            ParseError::BadPolicyLine(usage) => write!(f, "a policy line is `{usage}`"),
116            ParseError::UnsettableKey(k) => write!(
117                f,
118                "set {k:?} is not a policy-settable key — see docs/custom-checks.md"
119            ),
120            ParseError::FixOnPrePush => write!(
121                f,
122                "`fix` is only for pre-commit — a pre-push hook must not rewrite files"
123            ),
124            ParseError::BadSeverity(t) => {
125                write!(f, "severity {t:?} must be `block` or `warn`")
126            }
127        }
128    }
129}
130
131/// A line that parsed. Every field means something.
132///
133/// `program` and `args` rather than one `argv`: a runnable check must have a
134/// command, and splitting the head off makes that structural instead of a
135/// `split_first` guard that can only ever be dead code.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct Declared {
138    /// `Fix::Rewrite` when the command column began `fix `.
139    pub fix: Fix,
140    /// The command column carried the `files` marker.
141    pub files: bool,
142    pub name: String,
143    pub stage: Stage,
144    pub severity: Severity,
145    /// Extensions that gate it. Empty means any change — the `*` scope.
146    pub exts: Vec<String>,
147    /// Exact filenames that gate it — the scope column's bare tokens.
148    pub names: Vec<String>,
149    /// Files the REPOSITORY must carry for this check to apply at all — the
150    /// scope column's `+` half. Empty means always applicable, which is what
151    /// every declaration meant before `amont add` made a line something you
152    /// could acquire rather than write.
153    pub opt_in: Vec<String>,
154    pub program: String,
155    pub args: Vec<String>,
156}
157
158impl Declared {
159    /// `<trigger>-<name>`, the same shape a built-in has.
160    ///
161    /// This is what `hook.skip` and `amont.severity.<key>` resolve against,
162    /// so a declared check answers to its trigger and its short name exactly as
163    /// a compiled-in one does. Before it had an id, `hook.skip pre-commit`
164    /// silenced fifteen built-ins and left every declared check running.
165    pub fn id(&self) -> String {
166        format!("{}-{}", self.stage.as_str(), self.name)
167    }
168
169    /// The command as written, for display.
170    pub fn command(&self) -> String {
171        std::iter::once(self.program.as_str())
172            .chain(self.args.iter().map(String::as_str))
173            .collect::<Vec<_>>()
174            .join(" ")
175    }
176}
177
178/// One manifest line: usable, or not.
179///
180/// A SUM, not a struct with an `Option<why>` beside the fields. The struct
181/// form let a broken line carry a severity, a scope and an argv that meant
182/// nothing — and it produced a wrong diagnosis: because broken and usable
183/// entries shared one list, a valid line was rejected as "declared twice" for
184/// colliding with a line that could not run. Dedup now sees only `Usable`.
185///
186/// Separate from `External` because the fleet reads ninety-six manifests and may
187/// re-read them on every refresh, while `External` holds a `Scope` whose
188/// `&'static` slices are LEAKED.
189/// `tool <program> <version-substring>` — a version this repository expects
190/// of a tool its checks drive, so cross-machine skew is a printed fact
191/// instead of "the hook is flaky here". Verified once per hook run, warn-only.
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct ToolPin {
194    pub program: String,
195    /// A substring `<program> --version`'s first line must contain — `0.6.`
196    /// pins a minor, `0.6.3` pins a patch. Substring, not semver: the point
197    /// is agreement between machines, not range arithmetic.
198    pub want: String,
199}
200
201/// A committed policy statement about a BUILT-IN (or declared) check — the
202/// team's decision, shipped with the repository, trust-gated like everything
203/// else the manifest says. See `policy`.
204#[derive(Debug, Clone, PartialEq, Eq)]
205pub enum PolicyLine {
206    /// `severity <check|short-name|trigger> warn|block`
207    Severity { target: String, severity: Severity },
208    /// `skip <check|short-name|trigger>`
209    Skip { target: String },
210    /// `set <key> <value>` — a committed default for an allowlisted
211    /// `amont.*` config key. `key` is the FULL git key (`amont.timeout`),
212    /// canonicalised from whatever case the file used, because git keys are
213    /// case-insensitive and a policy file stricter than git is a trap.
214    Set { key: String, value: String },
215}
216
217/// The keys `set` may reach, in canonical spelling. Deliberately absent:
218/// `fix` (a committed file must not change what already-trusted commands may
219/// DO to your working tree — a different consent than "I read these
220/// commands"), `trusted`, `conventions`, `recordBypasses`, `progress`,
221/// `knownIdentity`, and the `severity.*` family (its own line kind).
222pub const SETTABLE: &[&str] = &[
223    "largeFileWarn",
224    "largeFileBlock",
225    "commit.gitmoji",
226    "commit.subjectMax",
227    "commit.descriptionMax",
228    "commit.bodyWrap",
229    "autoRebase",
230    "timeout",
231    "testPushedTree",
232    "minVersion",
233];
234
235impl PolicyLine {
236    /// The one-line rendering the trust prompt shows — consent must see the
237    /// policy it is granting.
238    pub fn describe(&self) -> String {
239        match self {
240            PolicyLine::Severity { target, severity } => {
241                format!("severity  {target}  {}", severity.as_str())
242            }
243            PolicyLine::Skip { target } => format!("skip      {target}"),
244            PolicyLine::Set { key, value } => format!("set       {key}  {value}"),
245        }
246    }
247}
248
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub enum Line {
251    Usable(Declared),
252    /// A tool version pin — carries no check.
253    Tool(ToolPin),
254    /// A policy statement — carries no check either. The line number rides
255    /// along because a "names no check here" note must point somewhere.
256    Policy {
257        what: PolicyLine,
258        lineno: usize,
259    },
260    Broken {
261        /// The declared name, or `<file>:<lineno>` when the line has none — a
262        /// gap has to be nameable to be reportable.
263        name: String,
264        /// Broken lines land on pre-commit unless the stage token parsed: seen
265        /// on every commit beats seen on every push.
266        stage: Stage,
267        lineno: usize,
268        why: ParseError,
269    },
270}
271
272impl Line {
273    pub fn name(&self) -> &str {
274        match self {
275            Line::Usable(d) => &d.name,
276            Line::Tool(pin) => &pin.program,
277            Line::Policy {
278                what: PolicyLine::Severity { target, .. } | PolicyLine::Skip { target },
279                ..
280            } => target,
281            Line::Policy {
282                what: PolicyLine::Set { key, .. },
283                ..
284            } => key,
285            Line::Broken { name, .. } => name,
286        }
287    }
288
289    /// Does this line declare a CHECK? `Tool` and `Policy` lines do not, and
290    /// every consumer that projects lines into checks — `parse`, the trust
291    /// prompt, the fleet's declared column — must filter on this rather than
292    /// pattern-match variants it will forget to extend. A `Broken` line IS a
293    /// check (one that runs to Unavailable and says why).
294    pub fn is_check(&self) -> bool {
295        matches!(self, Line::Usable(_) | Line::Broken { .. })
296    }
297    pub fn stage(&self) -> Stage {
298        match self {
299            Line::Usable(d) => d.stage,
300            // A pin has no stage; it is verified at both. The value only
301            // feeds displays that will not ask a pin for one. Policy lines
302            // likewise — `is_check()` keeps both out of anything that would.
303            Line::Tool(_) | Line::Policy { .. } => Stage::PreCommit,
304            Line::Broken { stage, .. } => *stage,
305        }
306    }
307    /// `Some(reason)` when this line declares a check that cannot run.
308    pub fn broken(&self) -> Option<String> {
309        match self {
310            Line::Usable(_) | Line::Tool(_) | Line::Policy { .. } => None,
311            Line::Broken { lineno, why, .. } => Some(format!("line {lineno}: {why}")),
312        }
313    }
314
315    /// `<trigger>-<name>`, matching `Declared::id` and `External::id`. A broken
316    /// line has one too: `hook.skip pre-commit` should silence its nag exactly
317    /// as it silences the checks that do run.
318    pub fn id(&self) -> String {
319        format!("{}-{}", self.stage().as_str(), self.name())
320    }
321
322    /// Consume into the identity every line has, and either the declaration or
323    /// the reason there is none.
324    ///
325    /// Both consumers — `External::from` and the fleet's projection — used to
326    /// destructure this by hand, and both carried an arm for a combination the
327    /// type forbids, because they computed the reason BEFORE matching. Written
328    /// once, that arm has nowhere to appear.
329    pub fn into_parts(self) -> (String, Stage, Result<Declared, String>) {
330        let name = self.name().to_string();
331        let stage = self.stage();
332        let parsed = match self {
333            Line::Usable(d) => Ok(d),
334            // Reachable only through a consumer that skipped `is_check()` —
335            // kept total so the type stays honest, worded so a leak is
336            // recognisable in whatever display it lands in.
337            Line::Tool(pin) => Err(format!("tool pin: {} {}", pin.program, pin.want)),
338            Line::Policy { what, .. } => Err(format!("policy: {}", what.describe())),
339            Line::Broken { lineno, why, .. } => Err(format!("line {lineno}: {why}")),
340        };
341        (name, stage, parsed)
342    }
343}
344
345/// A check a repository declares, rather than one compiled in.
346pub struct External {
347    /// `<trigger>-<name>` — what `hook.skip` and `amont.severity.<key>`
348    /// resolve against, and what `Check::name` returns. Built-ins have had this
349    /// shape all along; declared checks answering to a bare name were invisible
350    /// to `hook.skip pre-commit`.
351    pub id: String,
352    /// The name as written in the manifest — the "short name" of the vocabulary
353    /// — used for messages. A line too malformed to name itself falls back to
354    /// its position, and reading `pre-commit-amont.conf:3` back to somebody
355    /// helps nobody.
356    pub short_name: String,
357    pub stage: Stage,
358    pub kind: Kind,
359}
360
361/// The two things an external can be. `Scope` and `Severity` live only on the
362/// runnable side, so a broken external cannot carry a severity nobody applies.
363pub enum Kind {
364    Runnable {
365        scope: Scope,
366        severity: Severity,
367        program: String,
368        args: Vec<String>,
369        fix: Fix,
370        /// The command column began `files ` — append the matched paths to
371        /// the argv, the way a builtin hands its tool the staged list.
372        files: bool,
373    },
374    Unusable {
375        why: String,
376    },
377}
378
379impl Check for External {
380    fn name(&self) -> &str {
381        &self.id
382    }
383    fn stage(&self) -> Stage {
384        self.stage
385    }
386    /// Derived for an unusable check rather than stored: it never runs, so its
387    /// scope is a question with no answer, and computing one here keeps the
388    /// DATA from carrying a value that means nothing.
389    fn scope(&self) -> Scope {
390        match &self.kind {
391            Kind::Runnable { scope, .. } => *scope,
392            Kind::Unusable { .. } => Scope::ALWAYS,
393        }
394    }
395    fn severity(&self) -> Severity {
396        match &self.kind {
397            Kind::Runnable { severity, .. } => *severity,
398            // Never consulted: an unusable check reports `Unavailable`, which
399            // no severity can turn into a block.
400            Kind::Unusable { .. } => Severity::Warn,
401        }
402    }
403
404    fn run(&self, ctx: &Ctx) -> Outcome {
405        let (scope, program, args, fix, files) = match &self.kind {
406            Kind::Runnable {
407                scope,
408                program,
409                args,
410                fix,
411                files,
412                ..
413            } => (scope, program, args, *fix, *files),
414            Kind::Unusable { why } => {
415                crate::hooks::common::warn(&format!(
416                    "{MANIFEST}: {} — {}",
417                    crate::ui::highlight(&self.short_name),
418                    // Carries repo tokens: `BadStage("…")` quotes the manifest.
419                    crate::ui::sanitize(why)
420                ));
421                return Outcome::Unavailable;
422            }
423        };
424
425        // The scope gate lives HERE, unlike a built-in's, which enforces its own
426        // in its first three lines. A declared command has no way to know what
427        // was staged, so if this did not gate it, `*.sh` would run on every
428        // commit and the column would be decoration.
429        //
430        // Which files to test against depends on the stage: what is staged for
431        // a commit, what is being pushed for a push. `*` short-circuits before
432        // either is computed, which is the common case.
433        // A check whose whole job is to rewrite has nothing to say when nobody
434        // asked for rewriting — so it does not RUN, rather than running and
435        // having its result discarded. Gating only the re-staging let the
436        // command edit files with `amont.fix` off, which is precisely the
437        // surprise the gate exists to prevent.
438        //
439        // `Unavailable`, not `Passed`. `check.rs` defines `Unavailable` as
440        // "COULD NOT RUN — a tool is missing, or the opt-in config is absent",
441        // which is exactly this; `Passed` is the one verdict it must not
442        // report, because the dispatcher's roll-up and the fleet dashboard
443        // then show a check that never executed as clean. With a message,
444        // because every other `Unavailable` in this codebase says what was
445        // missing and an unexplained count on every commit is worse than none.
446        if fix == Fix::Rewrite && !crate::hooks::common::fixing_enabled() {
447            crate::hooks::common::warn(&format!(
448                "{}: declares fix, and {} is off — not run",
449                crate::ui::highlight(&self.short_name),
450                crate::ui::highlight("amont.fix")
451            ));
452            return Outcome::Unavailable;
453        }
454
455        let in_scope = match self.stage {
456            Stage::PreCommit => crate::hooks::common::staged_files(&[]),
457            Stage::PrePush => crate::pushrefs::changed_files(ctx.push.get()),
458        };
459        if !scope.is_unscoped() && !scope.matches(&in_scope) {
460            return Outcome::Passed;
461        }
462        // The paths the declaration's scope actually matched — what a builtin
463        // would be handed. Computed here, after the gate, and given to the
464        // command two ways: `$AMONT_FILES` always (newline-separated, so a
465        // wrapper script never re-derives `git diff --cached` and diverges
466        // from the set this gate judged — `amont run --all-files` overrides
467        // the set in-process, invisibly to any child that asks git itself),
468        // and appended to the argv when the declaration carries the `files`
469        // marker.
470        let matched = scoped(scope, &in_scope);
471        // A files-taking command with no files has nothing to judge — running
472        // it bare would make most linters error on an empty argv, blocking a
473        // commit over nothing. The builtin convention, applied here.
474        if files && matched.is_empty() {
475            return Outcome::Passed;
476        }
477        let root = crate::hooks::common::repo_root();
478        // Through `program()`, exactly like every builtin: on Windows,
479        // `Command::new("npx")` cannot start `npx.cmd`, and an external that
480        // fails to SPAWN reports Unavailable — warn, never block — so the
481        // check would silently never run. The guard test that enforces this
482        // for builtins scans only `src/hooks/`; this call is the manifest's
483        // half of the same rule.
484        let mut cmd = Command::new(crate::hooks::common::program(program));
485        cmd.args(args).current_dir(&root).stdin(Stdio::null());
486        // Env, not only argv: newline-separated so ordinary shell loops can
487        // read it. A path with a newline in its name would split wrong — the
488        // list is repo-controlled and such a path is already hostile input —
489        // and a change set too large for an environment variable (rare, but
490        // E2BIG kills the spawn outright) travels as an empty variable
491        // instead, which a wrapper treats exactly like "derive it yourself".
492        let joined = matched.join("\n");
493        cmd.env(
494            "AMONT_FILES",
495            if joined.len() <= 100_000 {
496                joined.as_str()
497            } else {
498                ""
499            },
500        );
501        if files {
502            cmd.args(&matched);
503        }
504        crate::hooks::common::strip_git_env(&mut cmd);
505        // Under the deadline: repo-authored code that outlives the budget is
506        // killed and FAILS — "hung" must not read as "passed", and pre-push
507        // runs these serially where one hang stalls the entire push.
508        let status = match crate::hooks::common::status_streamed(&mut cmd) {
509            Ok(crate::hooks::common::Ran::Status(s)) => Ok(s),
510            Ok(crate::hooks::common::Ran::TimedOut(budget)) => {
511                crate::hooks::common::say_timed_out(&self.short_name, budget);
512                return Outcome::Failed;
513            }
514            Err(e) => Err(e),
515        };
516        match status {
517            // A command that could not be STARTED has not judged anything. This
518            // is the distinction `Outcome` was added for: reporting a missing
519            // `shellcheck` as a lint failure sends someone hunting for a lint
520            // error that does not exist.
521            Err(e) => {
522                crate::hooks::common::warn(&format!(
523                    "{MANIFEST}: {} could not run {} — {}",
524                    crate::ui::highlight(&self.short_name),
525                    crate::ui::highlight(program),
526                    // The io error's text embeds the program name it tried.
527                    crate::ui::sanitize(&e.to_string())
528                ));
529                Outcome::Unavailable
530            }
531            Ok(s) if s.success() => {
532                // A declared fixer that ran clean may still have rewritten
533                // something; re-stage exactly what moved. Only its own scope,
534                // so it cannot stage a file it never looked at.
535                if fix == Fix::Rewrite && crate::hooks::common::fixing_enabled() {
536                    match crate::hooks::common::restage(&matched) {
537                        Restaged::Staged => {
538                            crate::hooks::common::ok(&format!(
539                                "{} fixed and re-staged",
540                                crate::ui::highlight(&self.short_name)
541                            ));
542                            return Outcome::Fixed;
543                        }
544                        // `git add` failed, so the index still holds whatever
545                        // the command has already replaced on disk. This used
546                        // to be indistinguishable from "nothing moved" and was
547                        // reported as a pass.
548                        Restaged::Failed(stuck) => {
549                            crate::hooks::common::fail(&format!(
550                                "{} rewrote files but {} failed — the index still holds the \
551                                 OLD content: {}",
552                                crate::ui::highlight(&self.short_name),
553                                crate::ui::highlight("git add"),
554                                crate::ui::sanitize(&stuck.join(", "))
555                            ));
556                            return Outcome::Failed;
557                        }
558                        Restaged::Nothing => {}
559                    }
560                }
561                Outcome::Passed
562            }
563            Ok(_) => {
564                crate::hooks::common::fail(&format!(
565                    "{} failed (output above)",
566                    crate::ui::highlight(&self.short_name)
567                ));
568                Outcome::Failed
569            }
570        }
571    }
572}
573
574/// The paths this check's scope actually covers.
575fn scoped(scope: &Scope, paths: &[String]) -> Vec<String> {
576    if scope.is_unscoped() {
577        return paths.to_vec();
578    }
579    paths.iter().filter(|p| scope.covers(p)).cloned().collect()
580}
581
582/// `Scope` holds `&'static` slices so a built-in can be a `const`. A parsed
583/// manifest has neither, so its extension list is leaked.
584///
585/// This is bounded and deliberate: the manifest is read at most once per
586/// process, holds a handful of short strings, and the process is a git hook that
587/// exits in milliseconds. The alternative — a lifetime on `Scope` — would
588/// propagate through the trait, both dispatchers and the fleet crate to buy back
589/// a few hundred bytes that the kernel reclaims moments later.
590fn leak(exts: Vec<String>) -> &'static [&'static str] {
591    let refs: Vec<&'static str> = exts
592        .into_iter()
593        .map(|s| &*Box::leak(s.into_boxed_str()))
594        .collect();
595    Box::leak(refs.into_boxed_slice())
596}
597
598/// `*` means any change; `*.sh` or `*.sh,*.bash` gate on extensions; and
599/// `<triggers>+<opt-ins>` adds the repository condition a builtin has.
600///
601/// # `+`, and why there is now an opt-in at all
602///
603/// This used to read: *"No `opt_in` counterpart, because the manifest IS the
604/// opt-in: a repository that does not want the check deletes the line."* That
605/// was true while every line was one somebody typed. `amont add` ended it — a
606/// vendored line is in your manifest because you took a whole PACK, not
607/// because you chose that tool, so a packaged `rubocop` fired on every `.rb`
608/// in a repository with no rubocop config and simply errored. That is the
609/// "ninety-five nags" `hooks::yamllint` documents avoiding, which is a
610/// courtesy every builtin has had and no declaration could express.
611///
612/// The separator is `+` because that is what `amont list` already PRINTS
613/// between the two halves — `inert here — needs .rs + Cargo.toml`. What you
614/// read in the listing is what you write in the file. No spaces: the column
615/// grammar splits on whitespace.
616///
617/// Both sides are comma-separated, and each side is an OR — any trigger, and
618/// any one opt-in. Between the sides it is an AND, matching `Scope`'s own
619/// semantics.
620///
621/// Splitting on the FIRST `+` means a filename containing one is not
622/// expressible. That is the same class of limit as directories being
623/// inexpressible, and it is stated in `docs/custom-checks.md` rather than
624/// worked around with quoting this grammar deliberately does not have.
625///
626/// Returns owned strings rather than a `Scope`, so validating a manifest
627/// costs nothing permanent. Only `External::from` turns these into the
628/// `&'static` form `Scope` requires.
629type ParsedScope = (Vec<String>, Vec<String>, Vec<String>);
630
631fn parse_scope(token: &str) -> Result<ParsedScope, ParseError> {
632    let (triggers, opt_in) = match token.split_once('+') {
633        None => (token, Vec::new()),
634        Some((left, right)) => {
635            // `*.rb+` promises a condition and states none. Refused rather
636            // than read as "no condition", which is the opposite of what the
637            // author was reaching for.
638            let opts: Vec<String> = right
639                .split(',')
640                .filter(|p| !p.is_empty())
641                .map(str::to_string)
642                .collect();
643            if opts.is_empty() || right.contains('+') {
644                return Err(ParseError::BadScope(token.to_string()));
645            }
646            for o in &opts {
647                if o.contains(['*', '?', '[', '/']) {
648                    return Err(ParseError::BadScope(o.clone()));
649                }
650            }
651            // `+cfg` with nothing on the left is "any change, if this repo has
652            // cfg" — a real shape, and `*` is how the trigger half spells
653            // "anything".
654            (if left.is_empty() { "*" } else { left }, opts)
655        }
656    };
657    if triggers == "*" {
658        return Ok((Vec::new(), Vec::new(), opt_in));
659    }
660    let mut exts = Vec::new();
661    let mut names = Vec::new();
662    for part in triggers.split(',') {
663        if let Some(ext) = part.strip_prefix('*').filter(|ext| ext.starts_with('.')) {
664            exts.push(ext.to_string());
665            continue;
666        }
667        // A bare token is an exact FILENAME — `package.json`, `Dockerfile`,
668        // `.prettierrc` — matched against the basename. Directories are not
669        // expressible (a `/` is refused), and anything that LOOKS like a glob
670        // (`*`, `?`, `[`) is refused as the typo it almost certainly is —
671        // this grammar deliberately has no globs to mis-guess.
672        if !part.is_empty() && !part.contains(['*', '?', '[', '/']) {
673            names.push(part.to_string());
674            continue;
675        }
676        return Err(ParseError::BadScope(part.to_string()));
677    }
678    Ok((exts, names, opt_in))
679}
680
681fn parse_stage(token: &str) -> Option<Stage> {
682    match token {
683        "pre-commit" => Some(Stage::PreCommit),
684        "pre-push" => Some(Stage::PrePush),
685        _ => None,
686    }
687}
688
689/// An identity already spoken for. An external must not be able to shadow
690/// `pre-push-branch-protect` — nor silently lose to it, which is what a
691/// first-match lookup would do without this.
692///
693/// Judged on the ID, which is why `clippy` on `pre-push` is now legal: it is
694/// `pre-push-clippy`, a different check from `pre-commit-clippy`. Judged on the
695/// bare name, as it was, the two collided and the second was refused.
696///
697fn name_is_taken(id: &str) -> bool {
698    CHECKS.iter().any(|c| c.name == id) || ENTRYPOINTS.iter().any(|(n, _)| *n == id)
699}
700
701/// A short name that says its own trigger — either by being one, or by starting
702/// with one.
703///
704/// Both make an id ambiguous rather than merely ugly. `pre-commit` as a name
705/// gives `hook.skip pre-commit` two readings; `pre-commit-clippy` as a name
706/// gives a check whose SHORT name is the built-in's FULL id, so one skip
707/// silences both. The stage column already says which trigger this is.
708fn name_says_its_trigger(name: &str) -> bool {
709    crate::TRIGGERS
710        .iter()
711        .any(|t| name == *t || name.starts_with(&format!("{t}-")))
712}
713
714/// The four leading tokens and the untouched remainder, or `None` when the line
715/// does not have them.
716///
717/// The arity is in the TYPE. Returning a `Vec` made "four or it is malformed"
718/// a rule every caller had to remember and none could be checked against.
719///
720/// NOT `splitn(5, char::is_whitespace)`: that splits at the FIRST whitespace
721/// character every time, so a file aligned into columns — which is how the
722/// format invites you to write it — yields empty fields for every run of
723/// spaces after the first.
724fn tokenise(line: &str) -> Option<([&str; 4], &str)> {
725    let mut fields: [&str; 4] = [""; 4];
726    let mut rest = line;
727    for slot in fields.iter_mut() {
728        rest = rest.trim_start();
729        let i = rest.find(char::is_whitespace)?;
730        *slot = &rest[..i];
731        rest = &rest[i..];
732    }
733    let command = rest.trim();
734    (!command.is_empty()).then_some((fields, command))
735}
736
737pub fn parse_lines(text: &str) -> Vec<Line> {
738    let mut out: Vec<Line> = Vec::new();
739    for (i, raw) in text.lines().enumerate() {
740        let line = raw.trim();
741        if line.is_empty() || line.starts_with('#') {
742            continue;
743        }
744        let lineno = i + 1;
745        out.push(parse_line(lineno, line, &out));
746    }
747    out
748}
749
750/// One line, given the lines already accepted.
751///
752/// `earlier` is read ONLY for the duplicate check, and only its `Usable`
753/// entries — a line that cannot run does not reserve its name. Before this, a
754/// valid declaration was rejected as "declared twice" for colliding with a
755/// broken one, which pointed the reader at the wrong line entirely.
756fn parse_line(lineno: usize, line: &str, earlier: &[Line]) -> Line {
757    // `tool` was never a valid stage, so claiming it as a keyword breaks no
758    // manifest that ever parsed. Handled before `tokenise`, whose five-column
759    // shape a three-token pin does not have.
760    if line == "tool" || line.starts_with("tool ") || line.starts_with("tool\t") {
761        let mut it = line.split_whitespace().skip(1);
762        return match (it.next(), it.next(), it.next()) {
763            (Some(program), Some(want), None) => Line::Tool(ToolPin {
764                program: program.to_string(),
765                want: want.to_string(),
766            }),
767            _ => broken_at(
768                lineno,
769                format!("{MANIFEST}:{lineno}"),
770                None,
771                ParseError::BadTool,
772            ),
773        };
774    }
775    // `severity` and `skip` were never valid stages either — the same
776    // keyword claim `tool` made. Fixed arity; anything else is a positional
777    // gap, never a phantom check named after its target (a broken
778    // `severity clippy loud` must not mint `pre-commit-clippy`).
779    if line == "severity" || line.starts_with("severity ") || line.starts_with("severity\t") {
780        let mut it = line.split_whitespace().skip(1);
781        return match (it.next(), it.next(), it.next()) {
782            (Some(target), Some(word), None) => match Severity::parse(word) {
783                Some(severity) => Line::Policy {
784                    what: PolicyLine::Severity {
785                        target: target.to_string(),
786                        severity,
787                    },
788                    lineno,
789                },
790                None => broken_at(
791                    lineno,
792                    format!("{MANIFEST}:{lineno}"),
793                    None,
794                    ParseError::BadSeverity(word.to_string()),
795                ),
796            },
797            _ => broken_at(
798                lineno,
799                format!("{MANIFEST}:{lineno}"),
800                None,
801                ParseError::BadPolicyLine("severity <check> warn|block"),
802            ),
803        };
804    }
805    if line == "skip" || line.starts_with("skip ") || line.starts_with("skip\t") {
806        let mut it = line.split_whitespace().skip(1);
807        return match (it.next(), it.next()) {
808            (Some(target), None) => Line::Policy {
809                what: PolicyLine::Skip {
810                    target: target.to_string(),
811                },
812                lineno,
813            },
814            _ => broken_at(
815                lineno,
816                format!("{MANIFEST}:{lineno}"),
817                None,
818                ParseError::BadPolicyLine("skip <check>"),
819            ),
820        };
821    }
822    if line == "set" || line.starts_with("set ") || line.starts_with("set\t") {
823        let mut it = line.split_whitespace().skip(1);
824        return match (it.next(), it.next(), it.next()) {
825            (Some(key), Some(value), None) => {
826                // Case-insensitive against the allowlist, canonical spelling
827                // stored — `set commit.subjectmax 72` must work, because git
828                // would have accepted the key in any case.
829                match SETTABLE.iter().find(|k| k.eq_ignore_ascii_case(key)) {
830                    Some(canonical) => Line::Policy {
831                        what: PolicyLine::Set {
832                            key: format!("amont.{canonical}"),
833                            value: value.to_string(),
834                        },
835                        lineno,
836                    },
837                    None => broken_at(
838                        lineno,
839                        format!("{MANIFEST}:{lineno}"),
840                        None,
841                        ParseError::UnsettableKey(key.to_string()),
842                    ),
843                }
844            }
845            _ => broken_at(
846                lineno,
847                format!("{MANIFEST}:{lineno}"),
848                None,
849                ParseError::BadPolicyLine("set <key> <value>"),
850            ),
851        };
852    }
853    let (fields, command) = match tokenise(line) {
854        Some(t) => t,
855        // No name to report: fall back to the position, which is the only
856        // handle a reader has on a line this malformed.
857        None => {
858            return broken_at(
859                lineno,
860                name_or_position(tokenise(line).map(|(f, _)| f[1]).unwrap_or(""), lineno),
861                None,
862                ParseError::MissingFields,
863            )
864        }
865    };
866    let [stage_tok, declared, scope_tok, severity_tok] = fields;
867    let stage = parse_stage(stage_tok);
868    let name = name_or_position(declared, lineno);
869    let fail = |why| broken_at(lineno, name.clone(), stage, why);
870
871    if declared.is_empty() {
872        return fail(ParseError::MissingName);
873    }
874    // The stage is settled BEFORE the name is judged, because the identity
875    // being judged is `<trigger>-<name>` and there is no such thing without a
876    // trigger. Ordered the other way, a line with an unusable stage was refused
877    // for a name clash that could not be assessed yet.
878    let Some(stage) = stage else {
879        return fail(ParseError::BadStage(stage_tok.to_string()));
880    };
881    if name_says_its_trigger(declared) {
882        return fail(ParseError::TriggerInName(declared.to_string()));
883    }
884    let id = format!("{}-{}", stage.as_str(), declared);
885    if name_is_taken(&id) {
886        return fail(ParseError::NameTaken(declared.to_string()));
887    }
888    if earlier
889        .iter()
890        .any(|l| matches!(l, Line::Usable(d) if d.id() == id))
891    {
892        return fail(ParseError::Duplicate(declared.to_string()));
893    }
894    let (exts, names, opt_in) = match parse_scope(scope_tok) {
895        Ok(e) => e,
896        Err(why) => return fail(why),
897    };
898    let Some(severity) = Severity::parse(severity_tok) else {
899        return fail(ParseError::BadSeverity(severity_tok.to_string()));
900    };
901    // `fix` and `files` are leading markers on the command column rather
902    // than extra fields, so every manifest written before them still parses.
903    // A loop, so `fix files cmd` and `files fix cmd` both work — two markers
904    // whose order carries no meaning must not be order-sensitive.
905    let mut command = command;
906    let mut wants_fix = false;
907    let mut wants_files = false;
908    loop {
909        if let Some(rest) = command.strip_prefix("fix ") {
910            command = rest.trim_start();
911            wants_fix = true;
912            continue;
913        }
914        if let Some(rest) = command.strip_prefix("files ") {
915            command = rest.trim_start();
916            wants_files = true;
917            continue;
918        }
919        break;
920    }
921    if wants_fix && stage == Stage::PrePush {
922        return fail(ParseError::FixOnPrePush);
923    }
924    // `tokenise` guarantees a non-empty command, so the split cannot fail.
925    let mut argv = command.split_whitespace().map(str::to_owned);
926    let Some(program) = argv.next() else {
927        return fail(ParseError::MissingFields);
928    };
929    Line::Usable(Declared {
930        fix: if wants_fix { Fix::Rewrite } else { Fix::None },
931        files: wants_files,
932        name: declared.to_string(),
933        stage,
934        severity,
935        exts,
936        names,
937        opt_in,
938        program,
939        args: argv.collect(),
940    })
941}
942
943fn name_or_position(declared: &str, lineno: usize) -> String {
944    if declared.is_empty() {
945        format!("{MANIFEST}:{lineno}")
946    } else {
947        declared.to_string()
948    }
949}
950
951fn broken_at(lineno: usize, name: String, stage: Option<Stage>, why: ParseError) -> Line {
952    Line::Broken {
953        name,
954        stage: stage.unwrap_or(Stage::PreCommit),
955        lineno,
956        why,
957    }
958}
959
960impl From<Line> for External {
961    fn from(l: Line) -> External {
962        let (name, stage, parsed) = l.into_parts();
963        let kind = match parsed {
964            Ok(d) => Kind::Runnable {
965                // `ALWAYS` only when NOTHING narrows it. An opt-in alone is a
966                // narrowing — `+Gemfile` means "any change, in a Ruby
967                // repository" — and collapsing that to `ALWAYS` would run the
968                // check everywhere, which is the exact bug this field exists
969                // to prevent.
970                scope: if d.exts.is_empty() && d.names.is_empty() && d.opt_in.is_empty() {
971                    Scope::ALWAYS
972                } else {
973                    Scope {
974                        files: leak(d.exts),
975                        names: leak(d.names),
976                        opt_in: leak(d.opt_in),
977                        not_during: &[],
978                    }
979                },
980                severity: d.severity,
981                program: d.program,
982                args: d.args,
983                fix: d.fix,
984                files: d.files,
985            },
986            Err(why) => Kind::Unusable { why },
987        };
988        let id = format!("{}-{}", stage.as_str(), name);
989        External {
990            id,
991            short_name: name,
992            stage,
993            kind,
994        }
995    }
996}
997
998pub fn parse(text: &str) -> Vec<External> {
999    parse_lines(text)
1000        .into_iter()
1001        .filter(Line::is_check)
1002        .map(External::from)
1003        .collect()
1004}
1005
1006/// The manifest for `root`, or an empty list. Read once per process.
1007pub fn read(root: &Path) -> Vec<External> {
1008    std::fs::read_to_string(root.join(MANIFEST))
1009        .map(|t| parse(&t))
1010        .unwrap_or_default()
1011}
1012
1013/// The same file, without building the `Scope`s — for a reader that inspects
1014/// many repositories and must not leak once per manifest per refresh.
1015pub fn read_lines(root: &Path) -> Vec<Line> {
1016    std::fs::read_to_string(root.join(MANIFEST))
1017        .map(|t| parse_lines(&t))
1018        .unwrap_or_default()
1019}
1020
1021/// Everything one repository's manifest declares, parsed and trust-gated
1022/// ONCE, owned by the entrypoint that loaded it and lent down through `Ctx`.
1023///
1024/// This replaced two process-global `OnceLock`s keyed on the working
1025/// directory at first call — safe in a hook, which handles one repository
1026/// and exits, and a trap for anything that walks many. Owned data has no
1027/// first-call: the caller says which repository it means, every time.
1028#[derive(Default)]
1029pub struct Manifest {
1030    /// Declared checks — untrusted ones present but `Unusable`, so the
1031    /// decision waiting on the reader stays visible. See [`gate`].
1032    pub externals: Vec<External>,
1033    /// Tool version pins — DROPPED entirely when untrusted, because verifying
1034    /// one executes `<program> --version` for a name the repository chose,
1035    /// which is exactly the consent the trust model exists to collect.
1036    pub pins: Vec<ToolPin>,
1037    /// Whether an `amont.conf` EXISTS in this repository — the committed
1038    /// declaration that this project subscribes to amont's conventions.
1039    /// Presence, not content: an empty file declares, and declaring executes
1040    /// nothing, so this is safe to read before any trust decision. What the
1041    /// file SAYS stays trust-gated above.
1042    pub declared: bool,
1043    /// Committed `severity`/`skip` policy — POPULATED ONLY WHEN TRUSTED,
1044    /// like the pins: applying a repository's opinion about your safety net
1045    /// is exactly the consent the trust model collects. See `policy`.
1046    pub policy: crate::policy::Policy,
1047    /// `trust::why(state)` when policy lines exist but the manifest is not
1048    /// trusted — the dispatchers say it once per stage, because policy that
1049    /// silently does not apply is a silent behaviour change.
1050    pub policy_withheld: Option<&'static str>,
1051    /// `severity`/`skip` targets that name no check here, with positions —
1052    /// a typo in committed policy must be loud, not a phantom check.
1053    pub policy_notes: Vec<String>,
1054}
1055
1056/// Read and trust-gate `root`'s manifest.
1057///
1058/// ONE read. The bytes that get PARSED and the bytes that get HASHED are the
1059/// same bytes: an earlier shape `read(root)`-ed and then let `trust::state`
1060/// open the file a second time, so anything that changed it in between — a
1061/// `git checkout`, a watcher, a `make` target already running — produced a
1062/// trust decision about content that is not the content about to be
1063/// executed.
1064///
1065/// Each call leaks the `Scope` slices it builds (see [`leak`]) — pennies for
1066/// the hook path, which loads once per process, and the reason the fleet
1067/// keeps reading [`read_lines`] instead: a scanner must not leak once per
1068/// repository per refresh.
1069pub fn load(root: &Path) -> Manifest {
1070    // Non-UTF-8 yields nothing, as it always has: `parse` takes a `&str`,
1071    // and a manifest we cannot read as text is one we cannot act on. Not
1072    // lossy — that would invent a manifest nobody wrote.
1073    let declared = root.join(MANIFEST).exists();
1074    let Ok(bytes) = std::fs::read(root.join(MANIFEST)) else {
1075        return Manifest {
1076            declared,
1077            ..Manifest::default()
1078        };
1079    };
1080    let Ok(text) = String::from_utf8(bytes.clone()) else {
1081        return Manifest {
1082            declared,
1083            ..Manifest::default()
1084        };
1085    };
1086    let state = crate::trust::state_of(root, &bytes);
1087    let lines = parse_lines(&text);
1088    let externals = gate(
1089        lines
1090            .iter()
1091            .filter(|l| l.is_check())
1092            .cloned()
1093            .map(External::from)
1094            .collect(),
1095        state,
1096    );
1097    let trusted = state == crate::trust::State::Trusted;
1098    let pins = if trusted {
1099        lines
1100            .iter()
1101            .filter_map(|l| match l {
1102                Line::Tool(pin) => Some(pin.clone()),
1103                _ => None,
1104            })
1105            .collect()
1106    } else {
1107        Vec::new()
1108    };
1109    let has_policy = lines.iter().any(|l| matches!(l, Line::Policy { .. }));
1110    let (policy, policy_notes) = if trusted {
1111        crate::policy::Policy::from_lines(&lines)
1112    } else {
1113        (crate::policy::Policy::default(), Vec::new())
1114    };
1115    // NOTE: load() computes but never INSTALLS the policy — the entrypoints
1116    // do, immediately after this returns and before any config read. A
1117    // multi-repo walker (the fleet) reads `read_lines` and must never seed
1118    // the process-global store.
1119    let policy_withheld = if has_policy && !trusted {
1120        crate::trust::why(state)
1121    } else {
1122        None
1123    };
1124    Manifest {
1125        externals,
1126        pins,
1127        declared,
1128        policy,
1129        policy_withheld,
1130        policy_notes,
1131    }
1132}
1133
1134/// Check every trusted pin against the tool actually on this machine, and say
1135/// what disagrees. Warn-only, once per hook run, at BOTH stages: skew never
1136/// blocks a commit — its cost is a check disagreeing with CI, and the fix is
1137/// a human decision — but it stops being invisible, which is the whole point.
1138pub fn verify_tool_pins(pins: &[ToolPin]) {
1139    for pin in pins {
1140        match version_of(&pin.program) {
1141            None => crate::hooks::common::warn(&format!(
1142                "{} is pinned to {} in {MANIFEST}, but `{} --version` would not run",
1143                crate::ui::highlight(&pin.program),
1144                crate::ui::sanitize(&pin.want),
1145                crate::ui::sanitize(&pin.program),
1146            )),
1147            Some(v) if !v.contains(&pin.want) => crate::hooks::common::warn(&format!(
1148                "{} reports {} — {MANIFEST} pins {}; this machine may disagree with CI",
1149                crate::ui::highlight(&pin.program),
1150                crate::ui::sanitize(&v),
1151                crate::ui::sanitize(&pin.want),
1152            )),
1153            _ => {}
1154        }
1155    }
1156}
1157
1158/// First line of `<program> --version`, resolved the way every check resolves
1159/// a tool. A version probe answers in milliseconds or not at all, so it is
1160/// deliberately not under the check deadline.
1161fn version_of(program: &str) -> Option<String> {
1162    let out = Command::new(crate::hooks::common::program(program))
1163        .arg("--version")
1164        .stdin(Stdio::null())
1165        .output()
1166        .ok()?;
1167    if !out.status.success() {
1168        return None;
1169    }
1170    let text = String::from_utf8_lossy(&out.stdout);
1171    let line = text.lines().next().unwrap_or("").trim();
1172    if line.is_empty() {
1173        return None;
1174    }
1175    Some(line.to_string())
1176}
1177
1178/// Apply a trust verdict to what the manifest declared.
1179///
1180/// Untrusted declarations are kept and DISABLED, not dropped. The names stay
1181/// visible in `amont list`, in the dashboard and in the "could not run"
1182/// roll-up, because a repository quietly declaring checks that never run is the
1183/// failure this project is arranged against — and the reader needs to know
1184/// there is a decision waiting for them.
1185///
1186/// Split out of [`load`] so the rule can be asserted without a repository on
1187/// disk — and kept split even now that `load` takes an explicit root, because
1188/// a trust verdict is one input among several there and this is the part with
1189/// the rule in it.
1190pub(crate) fn gate(declared: Vec<External>, state: crate::trust::State) -> Vec<External> {
1191    match crate::trust::why(state) {
1192        None => declared,
1193        Some(reason) => declared
1194            .into_iter()
1195            .map(|external| External {
1196                kind: Kind::Unusable {
1197                    why: reason.to_string(),
1198                },
1199                ..external
1200            })
1201            .collect(),
1202    }
1203}
1204
1205#[cfg(test)]
1206mod tests {
1207    use super::*;
1208
1209    fn one(text: &str) -> Line {
1210        let mut v = parse_lines(text);
1211        assert_eq!(v.len(), 1, "expected one entry from {text:?}");
1212        v.pop().expect("one")
1213    }
1214
1215    /// The error a line produced, as a VALUE. Tests used to match on the prose,
1216    /// which coupled them to wording and would have kept passing if the wording
1217    /// stayed while the meaning changed.
1218    fn why(l: &Line) -> ParseError {
1219        match l {
1220            Line::Broken { why, .. } => why.clone(),
1221            Line::Usable(d) => panic!("{} parsed when it should not have", d.name),
1222            Line::Tool(pin) => panic!("{} parsed as a pin, not a broken line", pin.program),
1223            Line::Policy { what, .. } => {
1224                panic!("{} parsed as policy, not a broken line", what.describe())
1225            }
1226        }
1227    }
1228
1229    fn usable(l: &Line) -> &Declared {
1230        match l {
1231            Line::Usable(d) => d,
1232            Line::Broken { name, why, .. } => panic!("{name} failed to parse: {why}"),
1233            Line::Tool(pin) => panic!("{} is a tool pin, not a declaration", pin.program),
1234            Line::Policy { what, .. } => {
1235                panic!("{} is policy, not a declaration", what.describe())
1236            }
1237        }
1238    }
1239
1240    /// The scope column's bare tokens are exact filenames — basename-matched,
1241    /// so `package.json` cannot be counterfeited by `not-package.json` — and
1242    /// they mix freely with extensions. Directories and free `*` stay refused.
1243    #[test]
1244    fn a_bare_scope_token_is_an_exact_filename() {
1245        let line = one("pre-commit  lockcheck  package.json  block  ./check.sh\n");
1246        let d = usable(&line);
1247        assert!(d.exts.is_empty());
1248        assert_eq!(d.names, ["package.json"]);
1249
1250        let line = one("pre-commit  x  *.ts,package.json,.prettierrc  block  ./x\n");
1251        let d = usable(&line);
1252        assert_eq!(d.exts, [".ts"]);
1253        assert_eq!(d.names, ["package.json", ".prettierrc"]);
1254
1255        assert_eq!(
1256            why(&one("pre-commit  x  src/package.json  block  ./x\n")),
1257            ParseError::BadScope("src/package.json".into())
1258        );
1259        assert_eq!(
1260            why(&one("pre-commit  x  pkg*  block  ./x\n")),
1261            ParseError::BadScope("pkg*".into())
1262        );
1263    }
1264
1265    /// `+` adds the repository condition a builtin has always had.
1266    ///
1267    /// The separator is the one `amont list` already prints between the two
1268    /// halves (`needs .rs + Cargo.toml`), so what a reader sees in the listing
1269    /// is what they write in the file.
1270    #[test]
1271    fn a_scope_can_name_what_the_repository_must_carry() {
1272        let line = one("pre-commit  rubocop  *.rb+.rubocop.yml  block  rubocop\n");
1273        let d = usable(&line);
1274        assert_eq!(d.exts, [".rb"]);
1275        assert!(d.names.is_empty());
1276        assert_eq!(d.opt_in, [".rubocop.yml"]);
1277
1278        // Both sides comma-separated: any trigger, and any ONE opt-in.
1279        let line = one("pre-commit  x  *.rb,Rakefile+.rubocop.yml,.rubocop_todo.yml  block  ./x\n");
1280        let d = usable(&line);
1281        assert_eq!(d.exts, [".rb"]);
1282        assert_eq!(d.names, ["Rakefile"]);
1283        assert_eq!(d.opt_in, [".rubocop.yml", ".rubocop_todo.yml"]);
1284
1285        // No trigger half: "any change, in a repository that carries this".
1286        let line = one("pre-commit  x  +Gemfile  block  ./x\n");
1287        let d = usable(&line);
1288        assert!(d.exts.is_empty() && d.names.is_empty());
1289        assert_eq!(d.opt_in, ["Gemfile"]);
1290    }
1291
1292    /// Every declaration written before `+` existed keeps its meaning: no
1293    /// opt-in is the old behaviour, which is "applies wherever it triggers".
1294    #[test]
1295    fn a_scope_without_a_plus_is_unchanged() {
1296        let line = one("pre-commit  x  *.ts,package.json  block  ./x\n");
1297        let d = usable(&line);
1298        assert!(d.opt_in.is_empty());
1299        let line = one("pre-commit  x  *  block  ./x\n");
1300        let d = usable(&line);
1301        assert!(d.opt_in.is_empty() && d.exts.is_empty() && d.names.is_empty());
1302    }
1303
1304    /// A `+` that promises a condition and names none is refused, rather than
1305    /// read as "no condition" — which is the opposite of what was reached for.
1306    #[test]
1307    fn a_malformed_opt_in_half_is_refused() {
1308        for bad in [
1309            "*.rb+",            // promised, not given
1310            "*.rb+,",           // still nothing
1311            "*.rb+a+b",         // a second separator is not a filename
1312            "*.rb+sub/dir.yml", // directories are inexpressible, as on the left
1313            "*.rb+*.yml",       // this grammar has no globs to mis-guess
1314        ] {
1315            let line = one(&format!("pre-commit  x  {bad}  block  ./x\n"));
1316            assert!(
1317                matches!(line, Line::Broken { .. }),
1318                "{bad} should be refused, got {line:?}"
1319            );
1320        }
1321    }
1322
1323    /// The pin grammar: exactly three tokens, claimed from a first token that
1324    /// was never a valid stage — no manifest that ever parsed changes meaning.
1325    #[test]
1326    fn a_tool_pin_parses_and_a_malformed_one_is_broken() {
1327        let line = one("tool  ruff  0.6.\n");
1328        assert_eq!(
1329            line,
1330            Line::Tool(ToolPin {
1331                program: "ruff".into(),
1332                want: "0.6.".into()
1333            })
1334        );
1335        assert_eq!(why(&one("tool ruff\n")), ParseError::BadTool);
1336        assert_eq!(why(&one("tool ruff 0.6. extra\n")), ParseError::BadTool);
1337        // `tool` is only a keyword in column one — a check NAMED tool still
1338        // parses as the check it always was.
1339        let line = one("pre-commit  tool  *  block  make tool\n");
1340        assert_eq!(usable(&line).name, "tool");
1341    }
1342
1343    #[test]
1344    fn parses_the_documented_example() {
1345        let v = parse_lines(
1346            "# stage       name        scope   severity  command\n\
1347             pre-commit    lint-shell  *.sh    block     scripts/lint-shell.sh\n\
1348             pre-push      smoke       *       warn      make smoke\n",
1349        );
1350        assert_eq!(v.len(), 2);
1351
1352        let a = usable(&v[0]);
1353        assert_eq!(a.name, "lint-shell");
1354        assert_eq!(a.stage, Stage::PreCommit);
1355        assert_eq!(a.severity, Severity::Block);
1356        assert_eq!(a.program, "scripts/lint-shell.sh");
1357        assert!(a.args.is_empty());
1358        assert_eq!(a.exts, [".sh"]);
1359
1360        let b = usable(&v[1]);
1361        assert_eq!(b.stage, Stage::PrePush);
1362        assert_eq!(b.severity, Severity::Warn);
1363        // A command with arguments is split, not handed to a shell.
1364        assert_eq!(b.program, "make");
1365        assert_eq!(b.args, ["smoke"]);
1366        assert!(b.exts.is_empty(), "`*` gates on nothing");
1367    }
1368
1369    /// Blank lines and comments are not entries, and must not become broken
1370    /// ones — a file that is mostly documentation would otherwise report a
1371    /// dozen gaps.
1372    #[test]
1373    fn comments_and_blank_lines_produce_nothing() {
1374        assert!(parse_lines("\n  \n# just a comment\n\t# indented\n").is_empty());
1375    }
1376
1377    /// The rule the module commits to: a line that cannot be understood still
1378    /// yields a check, so its absence is visible. Matched by VARIANT.
1379    #[test]
1380    fn a_malformed_line_becomes_a_visible_gap() {
1381        let cases: [(&str, ParseError); 4] = [
1382            (
1383                "pre-commit lint-shell *.sh block\n",
1384                ParseError::MissingFields,
1385            ),
1386            (
1387                "nonsense lint-shell *.sh block x\n",
1388                ParseError::BadStage("nonsense".into()),
1389            ),
1390            (
1391                "pre-commit lint-shell ?.sh block x\n",
1392                ParseError::BadScope("?.sh".into()),
1393            ),
1394            (
1395                "pre-commit lint-shell *.sh loud x\n",
1396                ParseError::BadSeverity("loud".into()),
1397            ),
1398        ];
1399        for (text, expected) in cases {
1400            assert_eq!(why(&one(text)), expected, "for {text:?}");
1401        }
1402    }
1403
1404    /// The prose still has to locate the line, even though the tests no longer
1405    /// depend on its wording.
1406    #[test]
1407    fn a_gap_reports_where_it_is() {
1408        let l = one("pre-commit lint-shell *.sh loud x\n");
1409        let said = l.broken().expect("broken");
1410        assert!(said.contains("line 1"), "{said}");
1411        assert!(said.contains("severity"), "{said}");
1412    }
1413
1414    /// `fix` on a pre-push line is refused where every other bad declaration is
1415    /// refused — on every commit, named and located — rather than as a runtime
1416    /// "contract violation" discovered later at push time by fewer people.
1417    #[test]
1418    fn fix_is_refused_on_a_pre_push_line() {
1419        assert_eq!(
1420            why(&one("pre-push  smoke  *  block  fix make smoke\n")),
1421            ParseError::FixOnPrePush
1422        );
1423        // …and accepted on pre-commit.
1424        let line = one("pre-commit  fmt  *  block  fix make format\n");
1425        let declared = usable(&line);
1426        assert_eq!(declared.fix, Fix::Rewrite);
1427        assert_eq!(declared.program, "make");
1428        assert_eq!(declared.args, ["format"]);
1429    }
1430
1431    /// Every manifest written before `fix` existed must still parse the same.
1432    #[test]
1433    fn a_command_that_merely_starts_with_fix_is_not_a_marker() {
1434        let line = one("pre-commit  x  *  block  fixup-tool --check\n");
1435        let declared = usable(&line);
1436        assert_eq!(declared.fix, Fix::None);
1437        assert_eq!(declared.program, "fixup-tool");
1438    }
1439
1440    /// The `files` marker, alone and stacked with `fix` in either order —
1441    /// two markers whose order carries no meaning must not be
1442    /// order-sensitive.
1443    #[test]
1444    fn the_files_marker_parses_alone_and_in_either_order_with_fix() {
1445        let line = one("pre-commit  sc  *.sh  block  files shellcheck\n");
1446        let declared = usable(&line);
1447        assert!(declared.files);
1448        assert_eq!(declared.fix, Fix::None);
1449        assert_eq!(declared.program, "shellcheck");
1450
1451        for text in [
1452            "pre-commit  fmt  *  block  fix files prettier --write\n",
1453            "pre-commit  fmt  *  block  files fix prettier --write\n",
1454        ] {
1455            let line = one(text);
1456            let declared = usable(&line);
1457            assert!(declared.files, "for {text:?}");
1458            assert_eq!(declared.fix, Fix::Rewrite, "for {text:?}");
1459            assert_eq!(declared.program, "prettier", "for {text:?}");
1460            assert_eq!(declared.args, ["--write"], "for {text:?}");
1461        }
1462    }
1463
1464    /// A command that merely starts with `files` keeps its name, exactly as
1465    /// `fixup-tool` keeps its own.
1466    #[test]
1467    fn a_command_that_merely_starts_with_files_is_not_a_marker() {
1468        let line = one("pre-commit  x  *  block  files-checker --strict\n");
1469        let declared = usable(&line);
1470        assert!(!declared.files);
1471        assert_eq!(declared.program, "files-checker");
1472    }
1473
1474    /// A gap with no name cannot be reported, and a line this broken has none.
1475    #[test]
1476    fn a_nameless_line_is_named_after_its_position() {
1477        let l = one("pre-commit\n");
1478        assert_eq!(l.name(), "amont.conf:1");
1479        assert_eq!(why(&l), ParseError::MissingFields);
1480    }
1481
1482    /// An external must not be able to take a built-in's id — it would either
1483    /// shadow `pre-push-branch-protect` or silently lose to it, and neither is
1484    /// something a repository should be able to do by editing a text file.
1485    ///
1486    /// Judged on the id, so the same declaration is refused on one trigger and
1487    /// accepted on the other. That is not a loophole: `pre-push-clippy` is a
1488    /// different check from `pre-commit-clippy`, and nothing is shadowed.
1489    #[test]
1490    fn a_built_in_id_is_refused() {
1491        assert_eq!(
1492            why(&one("pre-commit clippy *.rs block x\n")),
1493            ParseError::NameTaken("clippy".into())
1494        );
1495        assert!(matches!(
1496            one("pre-push clippy *.rs block x\n"),
1497            Line::Usable(_)
1498        ));
1499        // And a pre-push built-in is protected on pre-push, not on pre-commit,
1500        // for the same reason.
1501        assert_eq!(
1502            why(&one("pre-push pull-rebase * block x\n")),
1503            ParseError::NameTaken("pull-rebase".into())
1504        );
1505        assert!(matches!(
1506            one("pre-commit pull-rebase * block x\n"),
1507            Line::Usable(_)
1508        ));
1509    }
1510
1511    /// The stage column says which trigger a line is for. Saying it again in
1512    /// the name is the one way to make an id ambiguous: `pre-commit-clippy` as
1513    /// a NAME is a check whose short name is the built-in's full id, so one
1514    /// `hook.skip` would silence both.
1515    #[test]
1516    fn a_name_that_says_its_own_trigger_is_refused() {
1517        for name in ["pre-commit", "pre-push", "pre-commit-clippy", "pre-push-x"] {
1518            assert_eq!(
1519                why(&one(&format!("pre-commit {name} * block x\n"))),
1520                ParseError::TriggerInName(name.into()),
1521                "{name}"
1522            );
1523        }
1524        // A name that merely begins with the same letters is fine — the trigger
1525        // has to be followed by the separator to count.
1526        assert!(matches!(
1527            one("pre-commit pre-commitish * block x\n"),
1528            Line::Usable(_)
1529        ));
1530    }
1531
1532    /// Two USABLE lines with one ID: the second cannot be addressed by
1533    /// `hook.skip` or by a severity override, so it is refused.
1534    #[test]
1535    fn a_duplicate_id_is_refused() {
1536        let v = parse_lines(
1537            "pre-commit smoke * block a\n\
1538             pre-commit smoke * block b\n",
1539        );
1540        assert_eq!(v.len(), 2);
1541        assert_eq!(usable(&v[0]).id(), "pre-commit-smoke");
1542        assert_eq!(why(&v[1]), ParseError::Duplicate("smoke".into()));
1543    }
1544
1545    /// The same name on both triggers is TWO checks, and this used to refuse
1546    /// the second. Somebody wanting a `show-unicorn` on commit and on push had
1547    /// no way to write it, and no way to skip or downgrade one without the
1548    /// other — the bare name could not tell them apart.
1549    #[test]
1550    fn the_same_name_on_two_triggers_is_allowed() {
1551        let v = parse_lines(
1552            "pre-commit show-unicorn * block a\n\
1553             pre-push   show-unicorn * block b\n",
1554        );
1555        assert_eq!(v.len(), 2);
1556        assert_eq!(usable(&v[0]).id(), "pre-commit-show-unicorn");
1557        assert_eq!(usable(&v[1]).id(), "pre-push-show-unicorn");
1558
1559        // And each is separately addressable, while the short name takes both —
1560        // which is the whole vocabulary, applied to declared checks.
1561        for (id, only) in [
1562            ("pre-commit-show-unicorn", "pre-push-show-unicorn"),
1563            ("pre-push-show-unicorn", "pre-commit-show-unicorn"),
1564        ] {
1565            assert!(crate::skip_suppresses(id, id));
1566            assert!(!crate::skip_suppresses(only, id));
1567        }
1568        assert!(crate::skip_suppresses(
1569            "pre-commit-show-unicorn",
1570            "show-unicorn"
1571        ));
1572        assert!(crate::skip_suppresses(
1573            "pre-push-show-unicorn",
1574            "show-unicorn"
1575        ));
1576        assert!(crate::skip_suppresses(
1577            "pre-commit-show-unicorn",
1578            "pre-commit"
1579        ));
1580        assert!(!crate::skip_suppresses(
1581            "pre-push-show-unicorn",
1582            "pre-commit"
1583        ));
1584    }
1585
1586    /// A line that cannot run does not RESERVE its name.
1587    ///
1588    /// It used to: broken and usable entries shared one list, so a valid
1589    /// declaration was rejected as "declared twice" for colliding with a line
1590    /// that could never execute — pointing the reader at the wrong line, and
1591    /// forcing them to fix the first before the second would work at all.
1592    #[test]
1593    fn a_broken_line_does_not_reserve_its_name() {
1594        let v = parse_lines(
1595            "pre-commit smoke * LOUD   make a\n\
1596             pre-commit smoke * block  make b\n",
1597        );
1598        assert_eq!(v.len(), 2);
1599        assert_eq!(why(&v[0]), ParseError::BadSeverity("LOUD".into()));
1600        let good = usable(&v[1]);
1601        assert_eq!(good.name, "smoke");
1602        assert_eq!(good.program, "make");
1603    }
1604
1605    /// Alignment is cosmetic. A file someone has lined up with tabs, or not
1606    /// lined up at all, must parse identically.
1607    #[test]
1608    fn field_alignment_does_not_matter() {
1609        let spaced = one("pre-commit      lint-shell    *.sh      block     make lint\n");
1610        let tabbed = one("pre-commit\tlint-shell\t*.sh\tblock\tmake lint\n");
1611        assert_eq!(usable(&spaced), usable(&tabbed));
1612        assert_eq!(usable(&spaced).args, ["lint"]);
1613    }
1614
1615    #[test]
1616    fn several_extensions_can_gate_one_check() {
1617        let e = External::from(one("pre-commit shell *.sh,*.bash block make lint\n"));
1618        assert!(e.scope().matches(&["a.bash".into()]));
1619        assert!(e.scope().matches(&["a.sh".into()]));
1620        assert!(!e.scope().matches(&["a.zsh".into()]));
1621    }
1622
1623    /// `tokenise` states its arity in the type, so "four tokens then a command"
1624    /// is checked rather than remembered.
1625    #[test]
1626    fn tokenise_wants_four_fields_and_a_command() {
1627        assert!(tokenise("a b c").is_none(), "too few fields");
1628        assert!(tokenise("a b c d").is_none(), "four fields, no command");
1629        // Trailing whitespace reaches the four fields but still leaves nothing
1630        // to run — the case the `?` on the last field cannot catch.
1631        assert!(
1632            tokenise("a b c d   ").is_none(),
1633            "command is all whitespace"
1634        );
1635        assert!(tokenise("a b c d\t").is_none(), "command is a tab");
1636        let (fields, cmd) = tokenise("a  b\tc   d   run it").expect("four and a command");
1637        assert_eq!(fields, ["a", "b", "c", "d"]);
1638        assert_eq!(cmd, "run it");
1639    }
1640
1641    /// An unusable line carries no command at all — the type has nowhere to put
1642    /// one, which is the point of the split.
1643    #[test]
1644    fn an_unusable_external_holds_no_command() {
1645        let e = External::from(one("pre-commit lint-shell *.sh loud echo hi\n"));
1646        assert!(matches!(e.kind, Kind::Unusable { .. }));
1647        // And it can never block, whatever severity anyone configures.
1648        assert_eq!(e.severity(), Severity::Warn);
1649    }
1650
1651    /// A missing manifest is the normal case and must not be an error.
1652    #[test]
1653    fn a_repository_with_no_manifest_declares_nothing() {
1654        assert!(read(Path::new("/nonexistent-c8f2")).is_empty());
1655        assert!(read_lines(Path::new("/nonexistent-c8f2")).is_empty());
1656    }
1657
1658    /// `Line` exists to spare the dashboard a leak, not to become a second
1659    /// opinion about what a manifest says.
1660    #[test]
1661    fn the_leaking_and_non_leaking_parsers_agree() {
1662        let text = "pre-commit  lint-shell  *.sh,*.bash  block  make lint\n\
1663                    pre-push    smoke       *            warn   make smoke\n\
1664                    pre-commit  broken      ?            block  x\n";
1665        let lines = parse_lines(text);
1666        let externals = parse(text);
1667        assert_eq!(lines.len(), externals.len());
1668        for (l, e) in lines.iter().zip(&externals) {
1669            assert_eq!(l.id(), e.name(), "the id is what a check answers to");
1670            assert_eq!(
1671                l.name(),
1672                e.short_name,
1673                "and the short name is what it is called"
1674            );
1675            assert_eq!(l.stage(), e.stage());
1676            assert_eq!(
1677                l.broken().is_some(),
1678                matches!(e.kind, Kind::Unusable { .. })
1679            );
1680            if let Line::Usable(d) = l {
1681                assert_eq!(d.severity, e.severity());
1682                // The scope the dashboard would DESCRIBE is the scope the
1683                // dispatcher would ENFORCE.
1684                assert_eq!(d.exts, e.scope().files);
1685            }
1686        }
1687    }
1688}