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 /// `docs-skip` on a pre-push line: a push has no staged change to judge as docs.
89 DocsSkipOnPrePush,
90 /// A `tree` line with the wrong shape; carries what was wrong.
91 BadTreeLine(&'static str),
92 /// A `tree` line naming a tool amont does not know how to attest.
93 BadTreeTool(String),
94 /// A `tree` gate name that cannot become a note's gate token.
95 BadTreeName(String),
96 /// A `tree` option amont does not know, or one whose value is unsafe.
97 BadTreeOption(String),
98 /// `{cache}` on a tool that has no cache, or more than once.
99 BadTreeCache,
100}
101
102impl std::fmt::Display for ParseError {
103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104 match self {
105 ParseError::MissingFields => {
106 write!(f, "expected 5 fields: stage name scope severity command")
107 }
108 ParseError::MissingName => write!(f, "missing name"),
109 ParseError::NameTaken(n) => write!(f, "{n:?} already names a check"),
110 ParseError::TriggerInName(n) => write!(
111 f,
112 "{n:?} must not be a trigger or start with one — the stage column says which"
113 ),
114 ParseError::Duplicate(n) => write!(f, "{n:?} is declared twice on one trigger"),
115 ParseError::BadStage(t) => {
116 write!(f, "stage {t:?} must be `pre-commit` or `pre-push`")
117 }
118 ParseError::BadScope(t) => write!(
119 f,
120 "scope {t:?} must be `*`, `*.<ext>`, or a bare filename (no `/`), \
121 optionally followed by `+<file>` the repository must carry"
122 ),
123 ParseError::BadTool => write!(
124 f,
125 "a tool pin is exactly `tool <program> <version-substring>`"
126 ),
127 ParseError::BadPolicyLine(usage) => write!(f, "a policy line is `{usage}`"),
128 ParseError::UnsettableKey(k) => write!(
129 f,
130 "set {k:?} is not a policy-settable key — see docs/custom-checks.md"
131 ),
132 ParseError::BadTreeLine(what) => write!(
133 f,
134 "a tree gate is `tree <name> <tool> <scope> attest [cwd=<dir>] \
135 [inputs=<path>,...] <command>` — {what}"
136 ),
137 ParseError::BadTreeTool(t) => write!(
138 f,
139 "tree tool {t:?} must be one of: {}",
140 TreeTool::ALL
141 .iter()
142 .map(|t| t.as_str())
143 .collect::<Vec<_>>()
144 .join(", ")
145 ),
146 ParseError::BadTreeName(n) => write!(
147 f,
148 "tree gate name {n:?} must match [A-Za-z0-9][A-Za-z0-9._-]{{0,58}}"
149 ),
150 ParseError::BadTreeOption(o) => write!(
151 f,
152 "tree option {o:?}: only `cwd=<relative dir>` and \
153 `inputs=<path>,...` (literal paths, no globs, no `..`)"
154 ),
155 ParseError::BadTreeCache => write!(
156 f,
157 "`{{cache}}` may appear once, and only for eslint or prettier"
158 ),
159 ParseError::FixOnPrePush => write!(
160 f,
161 "`fix` is only for pre-commit — a pre-push hook must not rewrite files"
162 ),
163 ParseError::DocsSkipOnPrePush => write!(
164 f,
165 "`docs-skip` is only for pre-commit — a push has no staged change to judge"
166 ),
167 ParseError::BadSeverity(t) => {
168 write!(f, "severity {t:?} must be `block` or `warn`")
169 }
170 }
171 }
172}
173
174/// A line that parsed. Every field means something.
175///
176/// `program` and `args` rather than one `argv`: a runnable check must have a
177/// command, and splitting the head off makes that structural instead of a
178/// `split_first` guard that can only ever be dead code.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct Declared {
181 /// `Fix::Rewrite` when the command column began `fix `.
182 pub fix: Fix,
183 /// The command column carried the `files` marker.
184 pub files: bool,
185 /// The command column began `docs-skip ` — do not run on a commit whose
186 /// staged change only edits existing documentation (`staged_docs_only`).
187 pub docs_skip: bool,
188 pub name: String,
189 pub stage: Stage,
190 pub severity: Severity,
191 /// Extensions that gate it. Empty means any change — the `*` scope.
192 pub exts: Vec<String>,
193 /// Exact filenames that gate it — the scope column's bare tokens.
194 pub names: Vec<String>,
195 /// Directory triggers, each `dir/**/*.ext` — see `parse_scope`.
196 pub dirs: Vec<String>,
197 /// Files the REPOSITORY must carry for this check to apply at all — the
198 /// scope column's `+` half. Empty means always applicable, which is what
199 /// every declaration meant before `amont add` made a line something you
200 /// could acquire rather than write.
201 pub opt_in: Vec<String>,
202 pub program: String,
203 pub args: Vec<String>,
204}
205
206impl Declared {
207 /// `<trigger>-<name>`, the same shape a built-in has.
208 ///
209 /// This is what `hook.skip` and `amont.severity.<key>` resolve against,
210 /// so a declared check answers to its trigger and its short name exactly as
211 /// a compiled-in one does. Before it had an id, `hook.skip pre-commit`
212 /// silenced fifteen built-ins and left every declared check running.
213 pub fn id(&self) -> String {
214 format!("{}-{}", self.stage.as_str(), self.name)
215 }
216
217 /// The command as written, for display.
218 pub fn command(&self) -> String {
219 std::iter::once(self.program.as_str())
220 .chain(self.args.iter().map(String::as_str))
221 .collect::<Vec<_>>()
222 .join(" ")
223 }
224}
225
226/// One manifest line: usable, or not.
227///
228/// A SUM, not a struct with an `Option<why>` beside the fields. The struct
229/// form let a broken line carry a severity, a scope and an argv that meant
230/// nothing — and it produced a wrong diagnosis: because broken and usable
231/// entries shared one list, a valid line was rejected as "declared twice" for
232/// colliding with a line that could not run. Dedup now sees only `Usable`.
233///
234/// Separate from `External` because the fleet reads ninety-six manifests and may
235/// re-read them on every refresh, while `External` holds a `Scope` whose
236/// `&'static` slices are LEAKED.
237/// `tool <program> <version-substring>` — a version this repository expects
238/// of a tool its checks drive, so cross-machine skew is a printed fact
239/// instead of "the hook is flaky here". Verified once per hook run, warn-only.
240#[derive(Debug, Clone, PartialEq, Eq)]
241pub struct ToolPin {
242 pub program: String,
243 /// A substring `<program> --version`'s first line must contain — `0.6.`
244 /// pins a minor, `0.6.3` pins a patch. Substring, not semver: the point
245 /// is agreement between machines, not range arithmetic.
246 pub want: String,
247}
248
249/// The tools a `tree` gate may name. The tool is declared, never guessed from
250/// the command: `npm run lint` says nothing about what it runs, and amont needs
251/// to know what `{cache}` expands to and how to read the version the gate
252/// actually executes (ADR-0024, `ci.skip-needs-the-same-command`).
253#[derive(Debug, Clone, Copy, PartialEq, Eq)]
254pub enum TreeTool {
255 Eslint,
256 Prettier,
257 Ruff,
258 Pyright,
259 Gofmt,
260}
261
262impl TreeTool {
263 pub const ALL: &'static [TreeTool] = &[
264 TreeTool::Eslint,
265 TreeTool::Prettier,
266 TreeTool::Ruff,
267 TreeTool::Pyright,
268 TreeTool::Gofmt,
269 ];
270
271 pub fn parse(token: &str) -> Option<TreeTool> {
272 TreeTool::ALL.iter().copied().find(|t| t.as_str() == token)
273 }
274
275 pub fn as_str(self) -> &'static str {
276 match self {
277 TreeTool::Eslint => "eslint",
278 TreeTool::Prettier => "prettier",
279 TreeTool::Ruff => "ruff",
280 TreeTool::Pyright => "pyright",
281 TreeTool::Gofmt => "gofmt",
282 }
283 }
284
285 /// Whether the tool has an on-disk cache `{cache}` can point at. Ruff has
286 /// one too, but it manages it itself and a whole-tree run is already
287 /// sub-second; pyright and gofmt have none.
288 pub fn has_cache(self) -> bool {
289 matches!(self, TreeTool::Eslint | TreeTool::Prettier)
290 }
291}
292
293/// `tree <name> <tool> <scope> attest [cwd=<dir>] [inputs=<path>,...] <command>`
294/// — a whole-tree check whose pass may be ATTESTED so CI skips the step that
295/// runs the same command (ADR-0024).
296///
297/// The declaration IS the CI command. `normalized()` is what the workflow
298/// step's `run:` must equal, character for character; `{cache}` is the only
299/// thing amont may add, and it never changes a verdict. A tree gate never
300/// decides a commit: it is not a pre-commit or pre-push check, so it has no
301/// severity column — `attest` stands where the severity would be, saying what
302/// the line is for.
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct TreeGate {
305 pub name: String,
306 pub tool: TreeTool,
307 pub exts: Vec<String>,
308 pub names: Vec<String>,
309 pub dirs: Vec<String>,
310 pub opt_in: Vec<String>,
311 /// The directory the command runs in, relative to the repository root.
312 pub cwd: Option<String>,
313 /// Extra paths that belong to the gate's cache namespace.
314 pub inputs: Vec<String>,
315 /// The command as declared, `{cache}` and all.
316 pub command: String,
317 pub lineno: usize,
318}
319
320/// The placeholder a `tree` command may carry for the tool's cache flags.
321pub const CACHE_PLACEHOLDER: &str = "{cache}";
322
323impl TreeGate {
324 /// The gate token in the attestation note — what CI's `if:` names.
325 pub fn id(&self) -> String {
326 format!("tree-{}", self.name)
327 }
328
329 /// The key a tree proof is stamped under. Distinct from every commit-stamp
330 /// token (short names like `cargo-test`) by its `:`, so no per-commit
331 /// reader can mistake a staged-only pass for a whole-tree one.
332 pub fn stamp_key(&self) -> String {
333 format!("tree:{}", self.name)
334 }
335
336 /// The command CI must run: `{cache}` removed, then a dangling trailing
337 /// `--` (left behind by `npm run lint -- {cache}`), then whitespace
338 /// collapsed.
339 pub fn normalized(&self) -> String {
340 normalize_command(&self.command)
341 }
342}
343
344/// See [`TreeGate::normalized`]. Free so `tree-parity` can normalize a
345/// workflow's `run:` the same way.
346pub fn normalize_command(command: &str) -> String {
347 let mut words: Vec<&str> = command
348 .split_whitespace()
349 .filter(|w| *w != CACHE_PLACEHOLDER)
350 .collect();
351 if words.last() == Some(&"--") {
352 words.pop();
353 }
354 words.join(" ")
355}
356
357/// A committed policy statement about a BUILT-IN (or declared) check — the
358/// team's decision, shipped with the repository, trust-gated like everything
359/// else the manifest says. See `policy`.
360#[derive(Debug, Clone, PartialEq, Eq)]
361pub enum PolicyLine {
362 /// `severity <check|short-name|trigger> warn|block`
363 Severity { target: String, severity: Severity },
364 /// `skip <check|short-name|trigger>`
365 Skip { target: String },
366 /// `set <key> <value>` — a committed default for an allowlisted
367 /// `amont.*` config key. `key` is the FULL git key (`amont.timeout`),
368 /// canonicalised from whatever case the file used, because git keys are
369 /// case-insensitive and a policy file stricter than git is a trap.
370 Set { key: String, value: String },
371}
372
373/// The keys `set` may reach, in canonical spelling. Deliberately absent:
374/// `fix` (a committed file must not change what already-trusted commands may
375/// DO to your working tree — a different consent than "I read these
376/// commands"), `trusted`, `conventions`, `recordBypasses`, `progress`,
377/// `knownIdentity`, and the `severity.*` family (its own line kind).
378pub const SETTABLE: &[&str] = &[
379 "largeFileWarn",
380 "largeFileBlock",
381 "commit.gitmoji",
382 "commit.subjectMax",
383 "commit.descriptionMax",
384 "commit.bodyWrap",
385 "autoRebase",
386 "timeout",
387 // How long a tool may sit in a declared lock wait (ADR-0009). A property
388 // of the project's build — a workspace whose cold check holds the cargo
389 // lock for ten minutes is the project's to know — and, like `timeout`,
390 // only ever lengthens or shortens a wait; it enforces nothing.
391 "lockWait",
392 "testPushedTree",
393 "minVersion",
394 // A snapshot is not a workspace. `testPushedTree` is settable here, so a
395 // repository can say "run the gate on a checkout of the commit" — and
396 // before this it could not say how to make that checkout runnable, which
397 // for a pnpm or npm workspace means an install. The repository is what
398 // knows; requiring every clone to discover `git config
399 // amont.snapshotPrepare` by hand made the declarable half useless.
400 //
401 // Safe on the same terms as a declared check: policy is populated ONLY
402 // when the manifest is trusted, `PolicyLine::describe` puts the command
403 // in front of the person consenting, and any edit revokes that consent.
404 // A local `git config` still outranks it (see `policy`'s ladder), so a
405 // developer can override without touching the file.
406 "snapshotPrepare",
407 // The two halves of making a snapshot runnable that amont does itself.
408 // `snapshotDeps` picks how dependencies arrive (`install`, `reuse`,
409 // `off`); `snapshotCarry` names untracked files copied in from the
410 // working tree — never over tracked content, which is refused. Both are
411 // properties of the project, and trust-gated like `snapshotPrepare`.
412 "snapshotDeps",
413 "snapshotCarry",
414 // Ordering only. `amont.order evidence` permutes the push gates a
415 // repository already runs, using that machine's own record of them; it
416 // adds nothing, removes nothing and skips nothing, so it grants a
417 // committed file no power over what is enforced — which is the line
418 // `fix` and the `severity.*` family are kept on the other side of. Which
419 // ORDER a team's suites are attempted in is a property of the project
420 // (the four-minute suite, the five-second audit), so the project is the
421 // right place to be able to say it; a local `git config` still wins.
422 "order",
423 // Tree gates (ADR-0024). Whether they run, how long they may add to a
424 // commit after its checks, and which ignored paths are the repository's
425 // reproducible outputs rather than inputs a linter could import. None of
426 // them decides a commit; they only decide whether a stamp is earned.
427 "treeLint",
428 "treeLintSlack",
429 "treeLintWait",
430 "treeLintRehearsalTimeout",
431 "snapshotPrepareOutputs",
432];
433
434impl PolicyLine {
435 /// The one-line rendering the trust prompt shows — consent must see the
436 /// policy it is granting.
437 pub fn describe(&self) -> String {
438 match self {
439 PolicyLine::Severity { target, severity } => {
440 format!("severity {target} {}", severity.as_str())
441 }
442 PolicyLine::Skip { target } => format!("skip {target}"),
443 PolicyLine::Set { key, value } => format!("set {key} {value}"),
444 }
445 }
446}
447
448#[derive(Debug, Clone, PartialEq, Eq)]
449pub enum Line {
450 Usable(Declared),
451 /// A tool version pin — carries no check.
452 Tool(ToolPin),
453 /// A policy statement — carries no check either. The line number rides
454 /// along because a "names no check here" note must point somewhere.
455 Policy {
456 what: PolicyLine,
457 lineno: usize,
458 },
459 /// A whole-tree gate that may be attested — carries no check: it never
460 /// decides a commit or a push (ADR-0024).
461 Tree(TreeGate),
462 Broken {
463 /// The declared name, or `<file>:<lineno>` when the line has none — a
464 /// gap has to be nameable to be reportable.
465 name: String,
466 /// Broken lines land on pre-commit unless the stage token parsed: seen
467 /// on every commit beats seen on every push.
468 stage: Stage,
469 lineno: usize,
470 why: ParseError,
471 },
472}
473
474impl Line {
475 pub fn name(&self) -> &str {
476 match self {
477 Line::Usable(d) => &d.name,
478 Line::Tool(pin) => &pin.program,
479 Line::Policy {
480 what: PolicyLine::Severity { target, .. } | PolicyLine::Skip { target },
481 ..
482 } => target,
483 Line::Policy {
484 what: PolicyLine::Set { key, .. },
485 ..
486 } => key,
487 Line::Tree(gate) => &gate.name,
488 Line::Broken { name, .. } => name,
489 }
490 }
491
492 /// Does this line declare a CHECK? `Tool` and `Policy` lines do not, and
493 /// every consumer that projects lines into checks — `parse`, the trust
494 /// prompt, the fleet's declared column — must filter on this rather than
495 /// pattern-match variants it will forget to extend. A `Broken` line IS a
496 /// check (one that runs to Unavailable and says why).
497 pub fn is_check(&self) -> bool {
498 matches!(self, Line::Usable(_) | Line::Broken { .. })
499 }
500 pub fn stage(&self) -> Stage {
501 match self {
502 Line::Usable(d) => d.stage,
503 // A pin has no stage; it is verified at both. The value only
504 // feeds displays that will not ask a pin for one. Policy lines
505 // likewise — `is_check()` keeps both out of anything that would.
506 Line::Tool(_) | Line::Policy { .. } | Line::Tree(_) => Stage::PreCommit,
507 Line::Broken { stage, .. } => *stage,
508 }
509 }
510 /// `Some(reason)` when this line declares a check that cannot run.
511 pub fn broken(&self) -> Option<String> {
512 match self {
513 Line::Usable(_) | Line::Tool(_) | Line::Policy { .. } | Line::Tree(_) => None,
514 Line::Broken { lineno, why, .. } => Some(format!("line {lineno}: {why}")),
515 }
516 }
517
518 /// `<trigger>-<name>`, matching `Declared::id` and `External::id`. A broken
519 /// line has one too: `hook.skip pre-commit` should silence its nag exactly
520 /// as it silences the checks that do run.
521 pub fn id(&self) -> String {
522 format!("{}-{}", self.stage().as_str(), self.name())
523 }
524
525 /// Consume into the identity every line has, and either the declaration or
526 /// the reason there is none.
527 ///
528 /// Both consumers — `External::from` and the fleet's projection — used to
529 /// destructure this by hand, and both carried an arm for a combination the
530 /// type forbids, because they computed the reason BEFORE matching. Written
531 /// once, that arm has nowhere to appear.
532 pub fn into_parts(self) -> (String, Stage, Result<Declared, String>) {
533 let name = self.name().to_string();
534 let stage = self.stage();
535 let parsed = match self {
536 Line::Usable(d) => Ok(d),
537 // Reachable only through a consumer that skipped `is_check()` —
538 // kept total so the type stays honest, worded so a leak is
539 // recognisable in whatever display it lands in.
540 Line::Tool(pin) => Err(format!("tool pin: {} {}", pin.program, pin.want)),
541 Line::Policy { what, .. } => Err(format!("policy: {}", what.describe())),
542 Line::Tree(gate) => Err(format!("tree gate: {} {}", gate.name, gate.command)),
543 Line::Broken { lineno, why, .. } => Err(format!("line {lineno}: {why}")),
544 };
545 (name, stage, parsed)
546 }
547}
548
549/// A check a repository declares, rather than one compiled in.
550pub struct External {
551 /// `<trigger>-<name>` — what `hook.skip` and `amont.severity.<key>`
552 /// resolve against, and what `Check::name` returns. Built-ins have had this
553 /// shape all along; declared checks answering to a bare name were invisible
554 /// to `hook.skip pre-commit`.
555 pub id: String,
556 /// The name as written in the manifest — the "short name" of the vocabulary
557 /// — used for messages. A line too malformed to name itself falls back to
558 /// its position, and reading `pre-commit-amont.conf:3` back to somebody
559 /// helps nobody.
560 pub short_name: String,
561 pub stage: Stage,
562 pub kind: Kind,
563}
564
565/// The two things an external can be. `Scope` and `Severity` live only on the
566/// runnable side, so a broken external cannot carry a severity nobody applies.
567pub enum Kind {
568 Runnable {
569 scope: Scope,
570 severity: Severity,
571 program: String,
572 args: Vec<String>,
573 fix: Fix,
574 /// The command column began `files ` — append the matched paths to
575 /// the argv, the way a builtin hands its tool the staged list.
576 files: bool,
577 /// The command column began `docs-skip ` — see `Declared::docs_skip`.
578 docs_skip: bool,
579 },
580 Unusable {
581 why: String,
582 },
583}
584
585/// The scripts already vouched for against the staged tree, read once per
586/// hook process — a stage's externals run concurrently, and each asking git
587/// itself would be two spawns per check for one answer.
588fn vouched_for_staged_tree() -> &'static std::collections::HashSet<String> {
589 static VOUCHED: std::sync::OnceLock<std::collections::HashSet<String>> =
590 std::sync::OnceLock::new();
591 VOUCHED.get_or_init(crate::gate_stamp::vouched_for_staged_tree)
592}
593
594impl Check for External {
595 fn name(&self) -> &str {
596 &self.id
597 }
598 fn stage(&self) -> Stage {
599 self.stage
600 }
601 /// Derived for an unusable check rather than stored: it never runs, so its
602 /// scope is a question with no answer, and computing one here keeps the
603 /// DATA from carrying a value that means nothing.
604 fn scope(&self) -> Scope {
605 match &self.kind {
606 Kind::Runnable { scope, .. } => *scope,
607 Kind::Unusable { .. } => Scope::ALWAYS,
608 }
609 }
610 fn severity(&self) -> Severity {
611 match &self.kind {
612 Kind::Runnable { severity, .. } => *severity,
613 // Never consulted: an unusable check reports `Unavailable`, which
614 // no severity can turn into a block.
615 Kind::Unusable { .. } => Severity::Warn,
616 }
617 }
618
619 fn run(&self, ctx: &Ctx) -> Outcome {
620 let settings = ctx.settings;
621 let (scope, program, args, fix, files, docs_skip) = match &self.kind {
622 Kind::Runnable {
623 scope,
624 program,
625 args,
626 fix,
627 files,
628 docs_skip,
629 ..
630 } => (scope, program, args, *fix, *files, *docs_skip),
631 Kind::Unusable { why } => {
632 crate::hooks::common::warn(&format!(
633 "{MANIFEST}: {} — {}",
634 crate::ui::highlight(&self.short_name),
635 // Carries repo tokens: `BadStage("…")` quotes the manifest.
636 crate::ui::sanitize(why)
637 ));
638 return Outcome::Unavailable;
639 }
640 };
641
642 // The scope gate lives HERE, unlike a built-in's, which enforces its own
643 // in its first three lines. A declared command has no way to know what
644 // was staged, so if this did not gate it, `*.sh` would run on every
645 // commit and the column would be decoration.
646 //
647 // Which files to test against depends on the stage: what is staged for
648 // a commit, what is being pushed for a push. `*` short-circuits before
649 // either is computed, which is the common case.
650 // A check whose whole job is to rewrite has nothing to say when nobody
651 // asked for rewriting — so it does not RUN, rather than running and
652 // having its result discarded. Gating only the re-staging let the
653 // command edit files with `amont.fix` off, which is precisely the
654 // surprise the gate exists to prevent.
655 //
656 // `Unavailable`, not `Passed`. `check.rs` defines `Unavailable` as
657 // "COULD NOT RUN — a tool is missing, or the opt-in config is absent",
658 // which is exactly this; `Passed` is the one verdict it must not
659 // report, because the dispatcher's roll-up and the fleet dashboard
660 // then show a check that never executed as clean. With a message,
661 // because every other `Unavailable` in this codebase says what was
662 // missing and an unexplained count on every commit is worse than none.
663 if fix == Fix::Rewrite && !crate::hooks::common::fixing_enabled(settings) {
664 crate::hooks::common::warn(&format!(
665 "{}: declares fix, and {} is off — not run",
666 crate::ui::highlight(&self.short_name),
667 crate::ui::highlight("amont.fix")
668 ));
669 return Outcome::Unavailable;
670 }
671
672 // Two questions, two path lists. `touches` asks what the CHANGE
673 // contains; `opted_in` asks what the REPOSITORY carries, and answering
674 // the second from the change set made a `+marker` row fire only when
675 // the marker itself was staged — so a pack that followed our own
676 // advice to gate every row was a pack that never ran. `tracked_files`
677 // returning `None` means git would not say, and an unverified answer
678 // must not silently switch a check off: run it, and let the command
679 // judge.
680 let opted_in =
681 crate::hooks::common::tracked_files().map_or(true, |tracked| scope.opted_in(&tracked));
682 if !opted_in {
683 return Outcome::Passed;
684 }
685 let root = crate::hooks::common::repo_root();
686 match self.stage {
687 Stage::PreCommit => {
688 let staged = crate::hooks::common::staged_files(&[]);
689 // The declaration's own bet is that an edit to existing
690 // documentation does not change what this gate judges. Said
691 // out loud, like every other skip that is a decision and not a
692 // missing tool.
693 //
694 // `Inert`, not `Passed`: a bet is not a verdict. `Passed` is
695 // what the stamp and the push-side pairing read as "this gate
696 // ran clean on this tree", and a stamp for a run that never
697 // happened would let a same-named `pre-push` declaration defer
698 // to it, or an attestation tell CI the gate is covered. Left
699 // unstamped, the push gate runs it as it would have.
700 if docs_skip && crate::hooks::common::staged_docs_only() {
701 crate::say!(
702 "{} {} skipped — the commit only edits existing documentation",
703 crate::ui::valid_sign(),
704 crate::ui::highlight(&self.short_name),
705 );
706 return Outcome::Inert;
707 }
708 let Some(matched) = files_to_judge(scope, files, &staged) else {
709 return Outcome::Passed;
710 };
711 // A blocking gate that already ran clean against exactly this
712 // staged tree is not run again: the attempt that ran it never
713 // reached post-commit (commit-msg refused the subject, the
714 // editor was closed on the message) or the same tree is
715 // being re-committed. Said out loud, in the push gate's
716 // words, and answered as `Passed` so pre-commit records the
717 // marker again and post-commit binds it as usual. What can
718 // and cannot be vouched for: `gate_stamp::vouched_for_staged_tree`.
719 if self.severity() == Severity::Block
720 && crate::gate_stamp::commit_stamps_enabled(settings)
721 && vouched_for_staged_tree().contains(&self.short_name)
722 {
723 crate::say!(
724 "{} {} passed on this exact tree earlier — not repeating it here",
725 crate::ui::valid_sign(),
726 crate::ui::highlight(&self.short_name),
727 );
728 return Outcome::Passed;
729 }
730 self.execute(
731 settings,
732 program,
733 args,
734 fix,
735 files,
736 &matched,
737 Path::new(&root),
738 )
739 }
740 // PER REF, and — when `amont.testPushedTree` asks for it — in a
741 // checkout of that ref's tip, exactly as the built-in suites do
742 // and for the same reason: a declared `test *.rs block cargo
743 // test` line used to run once, in the working tree, whatever the
744 // flag said. It passed on an uncommitted fix, and `stamp_tips`
745 // then read the flag and stamped it onto the tip as though it had
746 // run there, so the next push of that tip skipped it. The flag is
747 // a promise about what a push gate tests; a declared gate is a
748 // push gate.
749 Stage::PrePush => {
750 let zero = crate::git::stdout(&["hash-object", "--stdin"])
751 .map(|h| "0".repeat(h.len()))
752 .unwrap_or_else(|| "0".repeat(40));
753 for r in ctx.push.get() {
754 if r.local_oid == zero {
755 continue; // deleting a ref pushes no code
756 }
757 let changed = crate::pushrefs::changed_files_for(r, &zero);
758 let Some(matched) = files_to_judge(scope, files, &changed) else {
759 continue;
760 };
761 // `_guard` owns the checkout for the length of this ref's
762 // run; dropping it removes the worktree before the next
763 // ref's begins. `self.id`, because that is what a stamp
764 // names and what `stamp_tips` asks `ran_on_tip` about.
765 let (run_in, _guard) =
766 crate::pushed_tree::where_to_run(settings, &r.local_oid, &root, &self.id);
767 match self.execute(settings, program, args, fix, files, &matched, &run_in) {
768 Outcome::Passed => {}
769 other => return other,
770 }
771 }
772 Outcome::Passed
773 }
774 }
775 }
776}
777
778/// The paths a declared check is handed for `in_scope`, or `None` when it
779/// has nothing to judge and must not run.
780///
781/// No `is_unscoped()` guard: `touches` already answers true for an unscoped
782/// trigger, so the gate reduces to the opt-in the caller has already
783/// settled — which is what a row with nothing on the left (`+Gemfile`: "any
784/// change, in a repository that carries a Gemfile") means. Guarding on it
785/// here skipped the opt-in for exactly those rows.
786///
787/// The paths are what the declaration's scope actually matched — what a
788/// builtin would be handed. A files-taking command with no files has
789/// nothing to judge — running it bare would make most linters error on an
790/// empty argv, blocking a commit over nothing. The builtin convention,
791/// applied here.
792fn files_to_judge(scope: &Scope, files: bool, in_scope: &[String]) -> Option<Vec<String>> {
793 if !scope.touches(in_scope) {
794 return None;
795 }
796 let matched = scoped(scope, in_scope);
797 if files && matched.is_empty() {
798 return None;
799 }
800 Some(matched)
801}
802
803impl External {
804 /// Spawn the declared command over `matched`, in `run_in`, and judge it.
805 ///
806 /// `matched` reaches the command two ways: `$AMONT_FILES` always
807 /// (newline-separated, so a wrapper script never re-derives `git diff
808 /// --cached` and diverges from the set this gate judged — `amont run
809 /// --all-files` overrides the set in-process, invisibly to any child that
810 /// asks git itself), and appended to the argv when the declaration
811 /// carries the `files` marker.
812 #[allow(clippy::too_many_arguments)]
813 fn execute(
814 &self,
815 settings: &crate::config::Settings,
816 program: &str,
817 args: &[String],
818 fix: Fix,
819 files: bool,
820 matched: &[String],
821 run_in: &Path,
822 ) -> Outcome {
823 // Through `program()`, exactly like every builtin: on Windows,
824 // `Command::new("npx")` cannot start `npx.cmd`, and an external that
825 // fails to SPAWN reports Unavailable — warn, never block — so the
826 // check would silently never run. The guard test that enforces this
827 // for builtins scans only `src/hooks/`; this call is the manifest's
828 // half of the same rule.
829 let mut cmd = Command::new(crate::hooks::common::program(program));
830 cmd.args(args).current_dir(run_in).stdin(Stdio::null());
831 // Env, not only argv: newline-separated so ordinary shell loops can
832 // read it. A path with a newline in its name would split wrong — the
833 // list is repo-controlled and such a path is already hostile input —
834 // and a change set too large for an environment variable (rare, but
835 // E2BIG kills the spawn outright) travels as an empty variable
836 // instead, which a wrapper treats exactly like "derive it yourself".
837 let joined = matched.join("\n");
838 cmd.env(
839 "AMONT_FILES",
840 if joined.len() <= 100_000 {
841 joined.as_str()
842 } else {
843 ""
844 },
845 );
846 if files {
847 cmd.args(matched);
848 }
849 crate::hooks::common::strip_git_env(&mut cmd);
850 // Under the deadline: repo-authored code that outlives the budget is
851 // killed and FAILS — "hung" must not read as "passed", and pre-push
852 // runs these serially where one hang stalls the entire push.
853 let status = match crate::hooks::common::status_streamed(
854 settings,
855 &mut cmd,
856 crate::hooks::common::Retry::Never,
857 ) {
858 Ok(crate::hooks::common::Ran::Status(s)) => Ok(s),
859 Ok(crate::hooks::common::Ran::TimedOut(budget)) => {
860 crate::hooks::common::say_timed_out(&self.short_name, budget);
861 return Outcome::Failed;
862 }
863 Err(e) => Err(e),
864 };
865 match status {
866 // A command that could not be STARTED has not judged anything. This
867 // is the distinction `Outcome` was added for: reporting a missing
868 // `shellcheck` as a lint failure sends someone hunting for a lint
869 // error that does not exist.
870 Err(e) => {
871 crate::hooks::common::warn(&format!(
872 "{MANIFEST}: {} could not run {} — {}",
873 crate::ui::highlight(&self.short_name),
874 crate::ui::highlight(program),
875 // The io error's text embeds the program name it tried.
876 crate::ui::sanitize(&e.to_string())
877 ));
878 Outcome::Unavailable
879 }
880 Ok(s) if s.success() => {
881 // A declared fixer that ran clean may still have rewritten
882 // something; re-stage exactly what moved. Only its own scope,
883 // so it cannot stage a file it never looked at.
884 if fix == Fix::Rewrite && crate::hooks::common::fixing_enabled(settings) {
885 match crate::hooks::common::restage(matched) {
886 Restaged::Staged => {
887 crate::hooks::common::ok(
888 settings,
889 &format!(
890 "{} fixed and re-staged",
891 crate::ui::highlight(&self.short_name)
892 ),
893 );
894 return Outcome::Fixed;
895 }
896 // `git add` failed, so the index still holds whatever
897 // the command has already replaced on disk. This used
898 // to be indistinguishable from "nothing moved" and was
899 // reported as a pass.
900 Restaged::Failed(stuck) => {
901 crate::hooks::common::fail(&format!(
902 "{} rewrote files but {} failed — the index still holds the \
903 OLD content: {}",
904 crate::ui::highlight(&self.short_name),
905 crate::ui::highlight("git add"),
906 crate::ui::sanitize(&stuck.join(", "))
907 ));
908 return Outcome::Failed;
909 }
910 Restaged::Nothing => {}
911 }
912 }
913 Outcome::Passed
914 }
915 Ok(_) => {
916 crate::hooks::common::fail(&format!(
917 "{} failed (output above)",
918 crate::ui::highlight(&self.short_name)
919 ));
920 Outcome::Failed
921 }
922 }
923 }
924}
925
926/// The paths this check's scope actually covers.
927fn scoped(scope: &Scope, paths: &[String]) -> Vec<String> {
928 if scope.is_unscoped() {
929 return paths.to_vec();
930 }
931 paths.iter().filter(|p| scope.covers(p)).cloned().collect()
932}
933
934/// `Scope` holds `&'static` slices so a built-in can be a `const`. A parsed
935/// manifest has neither, so its extension list is leaked.
936///
937/// This is bounded and deliberate: the manifest is read at most once per
938/// process, holds a handful of short strings, and the process is a git hook that
939/// exits in milliseconds. The alternative — a lifetime on `Scope` — would
940/// propagate through the trait, both dispatchers and the fleet crate to buy back
941/// a few hundred bytes that the kernel reclaims moments later.
942fn leak(exts: Vec<String>) -> &'static [&'static str] {
943 let refs: Vec<&'static str> = exts
944 .into_iter()
945 .map(|s| &*Box::leak(s.into_boxed_str()))
946 .collect();
947 Box::leak(refs.into_boxed_slice())
948}
949
950/// `*` means any change; `*.sh` or `*.sh,*.bash` gate on extensions; and
951/// `<triggers>+<opt-ins>` adds the repository condition a builtin has.
952///
953/// # `+`, and why there is now an opt-in at all
954///
955/// This used to read: *"No `opt_in` counterpart, because the manifest IS the
956/// opt-in: a repository that does not want the check deletes the line."* That
957/// was true while every line was one somebody typed. `amont add` ended it — a
958/// vendored line is in your manifest because you took a whole PACK, not
959/// because you chose that tool, so a packaged `rubocop` fired on every `.rb`
960/// in a repository with no rubocop config and simply errored. That is the
961/// "ninety-five nags" `hooks::yamllint` documents avoiding, which is a
962/// courtesy every builtin has had and no declaration could express.
963///
964/// The separator is `+` because that is what `amont list` already PRINTS
965/// between the two halves — `inert here — needs .rs + Cargo.toml`. What you
966/// read in the listing is what you write in the file. No spaces: the column
967/// grammar splits on whitespace.
968///
969/// Both sides are comma-separated, and each side is an OR — any trigger, and
970/// any one opt-in. Between the sides it is an AND, matching `Scope`'s own
971/// semantics.
972///
973/// Splitting on the FIRST `+` means a filename containing one is not
974/// expressible. It is stated in `docs/custom-checks.md` rather than worked
975/// around with quoting this grammar deliberately does not have.
976///
977/// Returns owned strings rather than a `Scope`, so validating a manifest
978/// costs nothing permanent. Only `External::from` turns these into the
979/// `&'static` form `Scope` requires.
980#[derive(Debug, Default, PartialEq, Eq)]
981struct ParsedScope {
982 exts: Vec<String>,
983 names: Vec<String>,
984 dirs: Vec<String>,
985 opt_in: Vec<String>,
986}
987
988/// A directory trigger: `dir/**/*.ext`. The directory is whole segments with no
989/// glob characters, so `claude-plugin/**/*.md` is in and `claude-*/**/*.md`,
990/// `/abs/**/*.md`, `a//b/**/*.md` and `../x/**/*.md` are out. The extension is
991/// a plain suffix. Nothing else in the grammar gets a `/` or a glob.
992fn is_dir_token(part: &str) -> bool {
993 let Some((dir, ext)) = part.split_once("/**/*") else {
994 return false;
995 };
996 !dir.is_empty()
997 && dir.split('/').all(|seg| {
998 !seg.is_empty() && seg != "." && seg != ".." && !seg.contains(['*', '?', '['])
999 })
1000 && ext.len() > 1
1001 && ext.starts_with('.')
1002 && !ext.contains(['*', '?', '[', '/'])
1003}
1004
1005fn parse_scope(token: &str) -> Result<ParsedScope, ParseError> {
1006 let (triggers, opt_in) = match token.split_once('+') {
1007 None => (token, Vec::new()),
1008 Some((left, right)) => {
1009 // `*.rb+` promises a condition and states none. Refused rather
1010 // than read as "no condition", which is the opposite of what the
1011 // author was reaching for.
1012 let opts: Vec<String> = right
1013 .split(',')
1014 .filter(|p| !p.is_empty())
1015 .map(str::to_string)
1016 .collect();
1017 if opts.is_empty() || right.contains('+') {
1018 return Err(ParseError::BadScope(token.to_string()));
1019 }
1020 for o in &opts {
1021 if o.contains(['*', '?', '[', '/']) {
1022 return Err(ParseError::BadScope(o.clone()));
1023 }
1024 }
1025 // `+cfg` with nothing on the left is "any change, if this repo has
1026 // cfg" — a real shape, and `*` is how the trigger half spells
1027 // "anything".
1028 (if left.is_empty() { "*" } else { left }, opts)
1029 }
1030 };
1031 if triggers == "*" {
1032 return Ok(ParsedScope {
1033 opt_in,
1034 ..ParsedScope::default()
1035 });
1036 }
1037 let mut exts = Vec::new();
1038 let mut names = Vec::new();
1039 let mut dirs = Vec::new();
1040 for part in triggers.split(',') {
1041 if let Some(ext) = part.strip_prefix('*').filter(|ext| ext.starts_with('.')) {
1042 exts.push(ext.to_string());
1043 continue;
1044 }
1045 if part.contains("/**/*") {
1046 if is_dir_token(part) {
1047 dirs.push(part.to_string());
1048 continue;
1049 }
1050 return Err(ParseError::BadScope(part.to_string()));
1051 }
1052 // A bare token is an exact FILENAME — `package.json`, `Dockerfile`,
1053 // `.prettierrc` — matched against the basename. A directory is only
1054 // ever `dir/**/*.ext`, handled above; any other `/`, and anything that
1055 // LOOKS like a glob (`*`, `?`, `[`), is refused as the typo it almost
1056 // certainly is — this grammar has no globs to mis-guess.
1057 if !part.is_empty() && !part.contains(['*', '?', '[', '/']) {
1058 names.push(part.to_string());
1059 continue;
1060 }
1061 return Err(ParseError::BadScope(part.to_string()));
1062 }
1063 Ok(ParsedScope {
1064 exts,
1065 names,
1066 dirs,
1067 opt_in,
1068 })
1069}
1070
1071fn parse_stage(token: &str) -> Option<Stage> {
1072 match token {
1073 "pre-commit" => Some(Stage::PreCommit),
1074 "pre-push" => Some(Stage::PrePush),
1075 _ => None,
1076 }
1077}
1078
1079/// An identity already spoken for. An external must not be able to shadow
1080/// `pre-push-branch-protect` — nor silently lose to it, which is what a
1081/// first-match lookup would do without this.
1082///
1083/// Judged on the ID, which is why `clippy` on `pre-push` is now legal: it is
1084/// `pre-push-clippy`, a different check from `pre-commit-clippy`. Judged on the
1085/// bare name, as it was, the two collided and the second was refused.
1086///
1087fn name_is_taken(id: &str) -> bool {
1088 CHECKS.iter().any(|c| c.name == id) || ENTRYPOINTS.iter().any(|(n, _)| *n == id)
1089}
1090
1091/// A short name that says its own trigger — either by being one, or by starting
1092/// with one.
1093///
1094/// Both make an id ambiguous rather than merely ugly. `pre-commit` as a name
1095/// gives `hook.skip pre-commit` two readings; `pre-commit-clippy` as a name
1096/// gives a check whose SHORT name is the built-in's FULL id, so one skip
1097/// silences both. The stage column already says which trigger this is.
1098fn name_says_its_trigger(name: &str) -> bool {
1099 crate::TRIGGERS
1100 .iter()
1101 .any(|t| name == *t || name.starts_with(&format!("{t}-")))
1102}
1103
1104/// The four leading tokens and the untouched remainder, or `None` when the line
1105/// does not have them.
1106///
1107/// The arity is in the TYPE. Returning a `Vec` made "four or it is malformed"
1108/// a rule every caller had to remember and none could be checked against.
1109///
1110/// NOT `splitn(5, char::is_whitespace)`: that splits at the FIRST whitespace
1111/// character every time, so a file aligned into columns — which is how the
1112/// format invites you to write it — yields empty fields for every run of
1113/// spaces after the first.
1114fn tokenise(line: &str) -> Option<([&str; 4], &str)> {
1115 let mut fields: [&str; 4] = [""; 4];
1116 let mut rest = line;
1117 for slot in fields.iter_mut() {
1118 rest = rest.trim_start();
1119 let i = rest.find(char::is_whitespace)?;
1120 *slot = &rest[..i];
1121 rest = &rest[i..];
1122 }
1123 let command = rest.trim();
1124 (!command.is_empty()).then_some((fields, command))
1125}
1126
1127pub fn parse_lines(text: &str) -> Vec<Line> {
1128 let mut out: Vec<Line> = Vec::new();
1129 for (i, raw) in text.lines().enumerate() {
1130 let line = raw.trim();
1131 if line.is_empty() || line.starts_with('#') {
1132 continue;
1133 }
1134 let lineno = i + 1;
1135 out.push(parse_line(lineno, line, &out));
1136 }
1137 out
1138}
1139
1140/// One line, given the lines already accepted.
1141///
1142/// `earlier` is read ONLY for the duplicate check, and only its `Usable`
1143/// entries — a line that cannot run does not reserve its name. Before this, a
1144/// valid declaration was rejected as "declared twice" for colliding with a
1145/// broken one, which pointed the reader at the wrong line entirely.
1146fn parse_line(lineno: usize, line: &str, earlier: &[Line]) -> Line {
1147 // `tool` was never a valid stage, so claiming it as a keyword breaks no
1148 // manifest that ever parsed. Handled before `tokenise`, whose five-column
1149 // shape a three-token pin does not have.
1150 if line == "tool" || line.starts_with("tool ") || line.starts_with("tool\t") {
1151 let mut it = line.split_whitespace().skip(1);
1152 return match (it.next(), it.next(), it.next()) {
1153 (Some(program), Some(want), None) => Line::Tool(ToolPin {
1154 program: program.to_string(),
1155 want: want.to_string(),
1156 }),
1157 _ => broken_at(
1158 lineno,
1159 format!("{MANIFEST}:{lineno}"),
1160 None,
1161 ParseError::BadTool,
1162 ),
1163 };
1164 }
1165 // `severity` and `skip` were never valid stages either — the same
1166 // keyword claim `tool` made. Fixed arity; anything else is a positional
1167 // gap, never a phantom check named after its target (a broken
1168 // `severity clippy loud` must not mint `pre-commit-clippy`).
1169 if line == "severity" || line.starts_with("severity ") || line.starts_with("severity\t") {
1170 let mut it = line.split_whitespace().skip(1);
1171 return match (it.next(), it.next(), it.next()) {
1172 (Some(target), Some(word), None) => match Severity::parse(word) {
1173 Some(severity) => Line::Policy {
1174 what: PolicyLine::Severity {
1175 target: target.to_string(),
1176 severity,
1177 },
1178 lineno,
1179 },
1180 None => broken_at(
1181 lineno,
1182 format!("{MANIFEST}:{lineno}"),
1183 None,
1184 ParseError::BadSeverity(word.to_string()),
1185 ),
1186 },
1187 _ => broken_at(
1188 lineno,
1189 format!("{MANIFEST}:{lineno}"),
1190 None,
1191 ParseError::BadPolicyLine("severity <check> warn|block"),
1192 ),
1193 };
1194 }
1195 if line == "skip" || line.starts_with("skip ") || line.starts_with("skip\t") {
1196 let mut it = line.split_whitespace().skip(1);
1197 return match (it.next(), it.next()) {
1198 (Some(target), None) => Line::Policy {
1199 what: PolicyLine::Skip {
1200 target: target.to_string(),
1201 },
1202 lineno,
1203 },
1204 _ => broken_at(
1205 lineno,
1206 format!("{MANIFEST}:{lineno}"),
1207 None,
1208 ParseError::BadPolicyLine("skip <check>"),
1209 ),
1210 };
1211 }
1212 // `tree` was never a valid stage either. Its own shape: it carries a
1213 // command but decides nothing, so it gets no severity column.
1214 if line == "tree" || line.starts_with("tree ") || line.starts_with("tree\t") {
1215 return parse_tree_line(lineno, line, earlier);
1216 }
1217 if line == "set" || line.starts_with("set ") || line.starts_with("set\t") {
1218 // The value is the REST of the line, not a third token. Every key
1219 // settable before this took a single word — `true`, `72`, a version —
1220 // so splitting on whitespace was indistinguishable from splitting
1221 // once. `snapshotPrepare` is a shell command, and a rule that only
1222 // ever admits one-word values cannot express it.
1223 //
1224 // A trailing `#` stays part of the value, exactly as it does in a
1225 // check's command: comments here are whole-line only (see the caller).
1226 let rest = line[3..].trim();
1227 let split = rest
1228 .split_once(char::is_whitespace)
1229 .map(|(k, v)| (k, v.trim()))
1230 .filter(|(_, v)| !v.is_empty());
1231 return match split {
1232 Some((key, value)) => {
1233 // Case-insensitive against the allowlist, canonical spelling
1234 // stored — `set commit.subjectmax 72` must work, because git
1235 // would have accepted the key in any case.
1236 match SETTABLE.iter().find(|k| k.eq_ignore_ascii_case(key)) {
1237 Some(canonical) => Line::Policy {
1238 what: PolicyLine::Set {
1239 key: format!("amont.{canonical}"),
1240 value: value.to_string(),
1241 },
1242 lineno,
1243 },
1244 None => broken_at(
1245 lineno,
1246 format!("{MANIFEST}:{lineno}"),
1247 None,
1248 ParseError::UnsettableKey(key.to_string()),
1249 ),
1250 }
1251 }
1252 None => broken_at(
1253 lineno,
1254 format!("{MANIFEST}:{lineno}"),
1255 None,
1256 ParseError::BadPolicyLine("set <key> <value>"),
1257 ),
1258 };
1259 }
1260 let (fields, command) = match tokenise(line) {
1261 Some(t) => t,
1262 // No name to report: fall back to the position, which is the only
1263 // handle a reader has on a line this malformed.
1264 None => {
1265 return broken_at(
1266 lineno,
1267 name_or_position(tokenise(line).map(|(f, _)| f[1]).unwrap_or(""), lineno),
1268 None,
1269 ParseError::MissingFields,
1270 )
1271 }
1272 };
1273 let [stage_tok, declared, scope_tok, severity_tok] = fields;
1274 let stage = parse_stage(stage_tok);
1275 let name = name_or_position(declared, lineno);
1276 let fail = |why| broken_at(lineno, name.clone(), stage, why);
1277
1278 if declared.is_empty() {
1279 return fail(ParseError::MissingName);
1280 }
1281 // The stage is settled BEFORE the name is judged, because the identity
1282 // being judged is `<trigger>-<name>` and there is no such thing without a
1283 // trigger. Ordered the other way, a line with an unusable stage was refused
1284 // for a name clash that could not be assessed yet.
1285 let Some(stage) = stage else {
1286 return fail(ParseError::BadStage(stage_tok.to_string()));
1287 };
1288 if name_says_its_trigger(declared) {
1289 return fail(ParseError::TriggerInName(declared.to_string()));
1290 }
1291 let id = format!("{}-{}", stage.as_str(), declared);
1292 if name_is_taken(&id) {
1293 return fail(ParseError::NameTaken(declared.to_string()));
1294 }
1295 if earlier
1296 .iter()
1297 .any(|l| matches!(l, Line::Usable(d) if d.id() == id))
1298 {
1299 return fail(ParseError::Duplicate(declared.to_string()));
1300 }
1301 let ParsedScope {
1302 exts,
1303 names,
1304 dirs,
1305 opt_in,
1306 } = match parse_scope(scope_tok) {
1307 Ok(e) => e,
1308 Err(why) => return fail(why),
1309 };
1310 let Some(severity) = Severity::parse(severity_tok) else {
1311 return fail(ParseError::BadSeverity(severity_tok.to_string()));
1312 };
1313 // `fix` and `files` are leading markers on the command column rather
1314 // than extra fields, so every manifest written before them still parses.
1315 // A loop, so `fix files cmd` and `files fix cmd` both work — two markers
1316 // whose order carries no meaning must not be order-sensitive.
1317 let mut command = command;
1318 let mut wants_fix = false;
1319 let mut wants_files = false;
1320 let mut wants_docs_skip = false;
1321 loop {
1322 if let Some(rest) = command.strip_prefix("fix ") {
1323 command = rest.trim_start();
1324 wants_fix = true;
1325 continue;
1326 }
1327 if let Some(rest) = command.strip_prefix("files ") {
1328 command = rest.trim_start();
1329 wants_files = true;
1330 continue;
1331 }
1332 if let Some(rest) = command.strip_prefix("docs-skip ") {
1333 command = rest.trim_start();
1334 wants_docs_skip = true;
1335 continue;
1336 }
1337 break;
1338 }
1339 if wants_fix && stage == Stage::PrePush {
1340 return fail(ParseError::FixOnPrePush);
1341 }
1342 if wants_docs_skip && stage == Stage::PrePush {
1343 return fail(ParseError::DocsSkipOnPrePush);
1344 }
1345 // `tokenise` guarantees a non-empty command, so the split cannot fail.
1346 let mut argv = command.split_whitespace().map(str::to_owned);
1347 let Some(program) = argv.next() else {
1348 return fail(ParseError::MissingFields);
1349 };
1350 Line::Usable(Declared {
1351 fix: if wants_fix { Fix::Rewrite } else { Fix::None },
1352 files: wants_files,
1353 docs_skip: wants_docs_skip,
1354 name: declared.to_string(),
1355 stage,
1356 severity,
1357 exts,
1358 names,
1359 dirs,
1360 opt_in,
1361 program,
1362 args: argv.collect(),
1363 })
1364}
1365
1366/// The first whitespace-separated token of `s`, and what follows it untouched.
1367fn split_token(s: &str) -> Option<(&str, &str)> {
1368 let s = s.trim_start();
1369 if s.is_empty() {
1370 return None;
1371 }
1372 let end = s.find(char::is_whitespace).unwrap_or(s.len());
1373 Some((&s[..end], &s[end..]))
1374}
1375
1376/// A gate name the attestation note can carry: the note's token grammar is
1377/// `[A-Za-z0-9][A-Za-z0-9._-]{0,63}` and `tree-` spends five of it.
1378fn tree_name_valid(name: &str) -> bool {
1379 let mut chars = name.chars();
1380 matches!(chars.next(), Some(c) if c.is_ascii_alphanumeric())
1381 && name.len() <= 59
1382 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
1383}
1384
1385/// A path a `cwd=` or `inputs=` may name: relative, literal, inside the tree.
1386fn tree_path_safe(path: &str) -> bool {
1387 !path.is_empty()
1388 && !path.starts_with('/')
1389 && !path.contains(['*', '?', '[', '\\'])
1390 && !path.split('/').any(|seg| seg == "..")
1391}
1392
1393fn parse_tree_line(lineno: usize, line: &str, earlier: &[Line]) -> Line {
1394 let position = format!("{MANIFEST}:{lineno}");
1395 let fail = |name: &str, why| {
1396 broken_at(
1397 lineno,
1398 if name.is_empty() {
1399 position.clone()
1400 } else {
1401 name.to_string()
1402 },
1403 None,
1404 why,
1405 )
1406 };
1407 let rest = &line[4..];
1408 let Some((name, rest)) = split_token(rest) else {
1409 return fail("", ParseError::BadTreeLine("missing name"));
1410 };
1411 if !tree_name_valid(name) {
1412 return fail(name, ParseError::BadTreeName(name.to_string()));
1413 }
1414 if name_says_its_trigger(name) {
1415 return fail(name, ParseError::TriggerInName(name.to_string()));
1416 }
1417 if earlier
1418 .iter()
1419 .any(|l| matches!(l, Line::Tree(g) if g.name == name))
1420 {
1421 return fail(name, ParseError::Duplicate(name.to_string()));
1422 }
1423 let Some((tool_tok, rest)) = split_token(rest) else {
1424 return fail(name, ParseError::BadTreeLine("missing tool"));
1425 };
1426 let Some(tool) = TreeTool::parse(tool_tok) else {
1427 return fail(name, ParseError::BadTreeTool(tool_tok.to_string()));
1428 };
1429 let Some((scope_tok, rest)) = split_token(rest) else {
1430 return fail(name, ParseError::BadTreeLine("missing scope"));
1431 };
1432 let ParsedScope {
1433 exts,
1434 names,
1435 dirs,
1436 opt_in,
1437 } = match parse_scope(scope_tok) {
1438 Ok(s) => s,
1439 Err(why) => return fail(name, why),
1440 };
1441 match split_token(rest) {
1442 Some(("attest", _)) => {}
1443 _ => {
1444 return fail(
1445 name,
1446 ParseError::BadTreeLine("the fifth column must be `attest`"),
1447 )
1448 }
1449 }
1450 let mut rest = split_token(rest).map(|(_, r)| r).unwrap_or("");
1451 let mut cwd = None;
1452 let mut inputs = Vec::new();
1453 // Options are LOWERCASE `key=value` tokens. An uppercase one
1454 // (`NODE_OPTIONS=… npm run lint`) is an environment assignment that begins
1455 // the command, so an env-prefixed command stays expressible.
1456 while let Some((tok, after)) = split_token(rest) {
1457 let Some((key, value)) = tok.split_once('=') else {
1458 break;
1459 };
1460 if key.is_empty() || !key.chars().all(|c| c.is_ascii_lowercase()) {
1461 break;
1462 }
1463 match key {
1464 "cwd" if cwd.is_none() && tree_path_safe(value) => {
1465 cwd = Some(value.trim_end_matches('/').to_string());
1466 }
1467 "inputs" if inputs.is_empty() => {
1468 let paths: Vec<String> = value.split(',').map(str::to_string).collect();
1469 if !paths.iter().all(|p| tree_path_safe(p)) {
1470 return fail(name, ParseError::BadTreeOption(tok.to_string()));
1471 }
1472 inputs = paths;
1473 }
1474 _ => return fail(name, ParseError::BadTreeOption(tok.to_string())),
1475 }
1476 rest = after;
1477 }
1478 let command = rest.trim();
1479 if command.is_empty() {
1480 return fail(name, ParseError::BadTreeLine("missing command"));
1481 }
1482 let placeholders = command
1483 .split_whitespace()
1484 .filter(|w| *w == CACHE_PLACEHOLDER)
1485 .count();
1486 if placeholders > 1 || (placeholders == 1 && !tool.has_cache()) {
1487 return fail(name, ParseError::BadTreeCache);
1488 }
1489 if normalize_command(command).is_empty() {
1490 return fail(name, ParseError::BadTreeLine("missing command"));
1491 }
1492 Line::Tree(TreeGate {
1493 name: name.to_string(),
1494 tool,
1495 exts,
1496 names,
1497 dirs,
1498 opt_in,
1499 cwd,
1500 inputs,
1501 command: command.to_string(),
1502 lineno,
1503 })
1504}
1505
1506/// The usable tree gates a manifest text declares — untrusted, for readers
1507/// that execute nothing (`tree-parity` compares text with text). Anything that
1508/// RUNS a gate reads [`Manifest::tree`], which is trust-gated.
1509pub fn tree_gates(text: &str) -> Vec<TreeGate> {
1510 parse_lines(text)
1511 .into_iter()
1512 .filter_map(|l| match l {
1513 Line::Tree(g) => Some(g),
1514 _ => None,
1515 })
1516 .collect()
1517}
1518
1519fn name_or_position(declared: &str, lineno: usize) -> String {
1520 if declared.is_empty() {
1521 format!("{MANIFEST}:{lineno}")
1522 } else {
1523 declared.to_string()
1524 }
1525}
1526
1527fn broken_at(lineno: usize, name: String, stage: Option<Stage>, why: ParseError) -> Line {
1528 Line::Broken {
1529 name,
1530 stage: stage.unwrap_or(Stage::PreCommit),
1531 lineno,
1532 why,
1533 }
1534}
1535
1536impl From<Line> for External {
1537 fn from(l: Line) -> External {
1538 let (name, stage, parsed) = l.into_parts();
1539 let kind = match parsed {
1540 Ok(d) => Kind::Runnable {
1541 // `ALWAYS` only when NOTHING narrows it. An opt-in alone is a
1542 // narrowing — `+Gemfile` means "any change, in a Ruby
1543 // repository" — and collapsing that to `ALWAYS` would run the
1544 // check everywhere, which is the exact bug this field exists
1545 // to prevent.
1546 scope: if d.exts.is_empty()
1547 && d.names.is_empty()
1548 && d.dirs.is_empty()
1549 && d.opt_in.is_empty()
1550 {
1551 Scope::ALWAYS
1552 } else {
1553 Scope {
1554 files: leak(d.exts),
1555 names: leak(d.names),
1556 dirs: leak(d.dirs),
1557 opt_in: leak(d.opt_in),
1558 not_during: &[],
1559 }
1560 },
1561 severity: d.severity,
1562 program: d.program,
1563 args: d.args,
1564 fix: d.fix,
1565 files: d.files,
1566 docs_skip: d.docs_skip,
1567 },
1568 Err(why) => Kind::Unusable { why },
1569 };
1570 let id = format!("{}-{}", stage.as_str(), name);
1571 External {
1572 id,
1573 short_name: name,
1574 stage,
1575 kind,
1576 }
1577 }
1578}
1579
1580pub fn parse(text: &str) -> Vec<External> {
1581 parse_lines(text)
1582 .into_iter()
1583 .filter(Line::is_check)
1584 .map(External::from)
1585 .collect()
1586}
1587
1588/// The manifest for `root`, or an empty list. Read once per process.
1589pub fn read(root: &Path) -> Vec<External> {
1590 std::fs::read_to_string(root.join(MANIFEST))
1591 .map(|t| parse(&t))
1592 .unwrap_or_default()
1593}
1594
1595/// The same file, without building the `Scope`s — for a reader that inspects
1596/// many repositories and must not leak once per manifest per refresh.
1597pub fn read_lines(root: &Path) -> Vec<Line> {
1598 std::fs::read_to_string(root.join(MANIFEST))
1599 .map(|t| parse_lines(&t))
1600 .unwrap_or_default()
1601}
1602
1603/// Everything one repository's manifest declares, parsed and trust-gated
1604/// ONCE, owned by the entrypoint that loaded it and lent down through `Ctx`.
1605///
1606/// This replaced two process-global `OnceLock`s keyed on the working
1607/// directory at first call — safe in a hook, which handles one repository
1608/// and exits, and a trap for anything that walks many. Owned data has no
1609/// first-call: the caller says which repository it means, every time.
1610#[derive(Default)]
1611pub struct Manifest {
1612 /// Declared checks — untrusted ones present but `Unusable`, so the
1613 /// decision waiting on the reader stays visible. See [`gate`].
1614 pub externals: Vec<External>,
1615 /// Tool version pins — DROPPED entirely when untrusted, because verifying
1616 /// one executes `<program> --version` for a name the repository chose,
1617 /// which is exactly the consent the trust model exists to collect.
1618 pub pins: Vec<ToolPin>,
1619 /// Tree gates — DROPPED entirely when untrusted, like the pins: running
1620 /// one executes a command the repository chose.
1621 pub tree: Vec<TreeGate>,
1622 /// Whether an `amont.conf` EXISTS in this repository — the committed
1623 /// declaration that this project subscribes to amont's conventions.
1624 /// Presence, not content: an empty file declares, and declaring executes
1625 /// nothing, so this is safe to read before any trust decision. What the
1626 /// file SAYS stays trust-gated above.
1627 pub declared: bool,
1628 /// Committed `severity`/`skip` policy — POPULATED ONLY WHEN TRUSTED,
1629 /// like the pins: applying a repository's opinion about your safety net
1630 /// is exactly the consent the trust model collects. See `policy`.
1631 pub policy: crate::policy::Policy,
1632 /// `trust::why(state)` when policy lines exist but the manifest is not
1633 /// trusted — the dispatchers say it once per stage, because policy that
1634 /// silently does not apply is a silent behaviour change.
1635 pub policy_withheld: Option<&'static str>,
1636 /// `severity`/`skip` targets that name no check here, with positions —
1637 /// a typo in committed policy must be loud, not a phantom check.
1638 pub policy_notes: Vec<String>,
1639}
1640
1641/// Read and trust-gate `root`'s manifest.
1642///
1643/// ONE read. The bytes that get PARSED and the bytes that get HASHED are the
1644/// same bytes: an earlier shape `read(root)`-ed and then let `trust::state`
1645/// open the file a second time, so anything that changed it in between — a
1646/// `git checkout`, a watcher, a `make` target already running — produced a
1647/// trust decision about content that is not the content about to be
1648/// executed.
1649///
1650/// Each call leaks the `Scope` slices it builds (see [`leak`]) — pennies for
1651/// the hook path, which loads once per process, and the reason the fleet
1652/// keeps reading [`read_lines`] instead: a scanner must not leak once per
1653/// repository per refresh.
1654pub fn load(root: &Path) -> Manifest {
1655 // Non-UTF-8 yields nothing, as it always has: `parse` takes a `&str`,
1656 // and a manifest we cannot read as text is one we cannot act on. Not
1657 // lossy — that would invent a manifest nobody wrote.
1658 let declared = root.join(MANIFEST).exists();
1659 let Ok(bytes) = std::fs::read(root.join(MANIFEST)) else {
1660 return Manifest {
1661 declared,
1662 ..Manifest::default()
1663 };
1664 };
1665 let Ok(text) = String::from_utf8(bytes.clone()) else {
1666 return Manifest {
1667 declared,
1668 ..Manifest::default()
1669 };
1670 };
1671 let state = crate::trust::state_of(root, &bytes);
1672 let lines = parse_lines(&text);
1673 let externals = gate(
1674 lines
1675 .iter()
1676 .filter(|l| l.is_check())
1677 .cloned()
1678 .map(External::from)
1679 .collect(),
1680 state,
1681 );
1682 let trusted = state == crate::trust::State::Trusted;
1683 let pins = if trusted {
1684 lines
1685 .iter()
1686 .filter_map(|l| match l {
1687 Line::Tool(pin) => Some(pin.clone()),
1688 _ => None,
1689 })
1690 .collect()
1691 } else {
1692 Vec::new()
1693 };
1694 let tree = if trusted {
1695 lines
1696 .iter()
1697 .filter_map(|l| match l {
1698 Line::Tree(gate) => Some(gate.clone()),
1699 _ => None,
1700 })
1701 .collect()
1702 } else {
1703 Vec::new()
1704 };
1705 let has_policy = lines.iter().any(|l| matches!(l, Line::Policy { .. }));
1706 let (policy, policy_notes) = if trusted {
1707 crate::policy::Policy::from_lines(&lines)
1708 } else {
1709 (crate::policy::Policy::default(), Vec::new())
1710 };
1711 // NOTE: load() computes but never INSTALLS the policy — the entrypoints
1712 // do, immediately after this returns and before any config read. A
1713 // multi-repo walker (the fleet) reads `read_lines` and must never seed
1714 // the process-global store.
1715 let policy_withheld = if has_policy && !trusted {
1716 crate::trust::why(state)
1717 } else {
1718 None
1719 };
1720 Manifest {
1721 externals,
1722 pins,
1723 tree,
1724 declared,
1725 policy,
1726 policy_withheld,
1727 policy_notes,
1728 }
1729}
1730
1731/// Check every trusted pin against the tool actually on this machine, and say
1732/// what disagrees. Warn-only, once per hook run, at BOTH stages: skew never
1733/// blocks a commit — its cost is a check disagreeing with CI, and the fix is
1734/// a human decision — but it stops being invisible, which is the whole point.
1735pub fn verify_tool_pins(pins: &[ToolPin]) {
1736 for pin in pins {
1737 match version_of(&pin.program) {
1738 None => crate::hooks::common::warn(&format!(
1739 "{} is pinned to {} in {MANIFEST}, but `{} --version` would not run",
1740 crate::ui::highlight(&pin.program),
1741 crate::ui::sanitize(&pin.want),
1742 crate::ui::sanitize(&pin.program),
1743 )),
1744 Some(v) if !v.contains(&pin.want) => crate::hooks::common::warn(&format!(
1745 "{} reports {} — {MANIFEST} pins {}; this machine may disagree with CI",
1746 crate::ui::highlight(&pin.program),
1747 crate::ui::sanitize(&v),
1748 crate::ui::sanitize(&pin.want),
1749 )),
1750 _ => {}
1751 }
1752 }
1753}
1754
1755/// First line of `<program> --version`, resolved the way every check resolves
1756/// a tool. A version probe answers in milliseconds or not at all, so it is
1757/// deliberately not under the check deadline.
1758fn version_of(program: &str) -> Option<String> {
1759 let out = Command::new(crate::hooks::common::program(program))
1760 .arg("--version")
1761 .stdin(Stdio::null())
1762 .output()
1763 .ok()?;
1764 if !out.status.success() {
1765 return None;
1766 }
1767 let text = String::from_utf8_lossy(&out.stdout);
1768 let line = text.lines().next().unwrap_or("").trim();
1769 if line.is_empty() {
1770 return None;
1771 }
1772 Some(line.to_string())
1773}
1774
1775/// Apply a trust verdict to what the manifest declared.
1776///
1777/// Untrusted declarations are kept and DISABLED, not dropped. The names stay
1778/// visible in `amont list`, in the dashboard and in the "could not run"
1779/// roll-up, because a repository quietly declaring checks that never run is the
1780/// failure this project is arranged against — and the reader needs to know
1781/// there is a decision waiting for them.
1782///
1783/// Split out of [`load`] so the rule can be asserted without a repository on
1784/// disk — and kept split even now that `load` takes an explicit root, because
1785/// a trust verdict is one input among several there and this is the part with
1786/// the rule in it.
1787pub(crate) fn gate(declared: Vec<External>, state: crate::trust::State) -> Vec<External> {
1788 match crate::trust::why(state) {
1789 None => declared,
1790 Some(reason) => declared
1791 .into_iter()
1792 .map(|external| External {
1793 kind: Kind::Unusable {
1794 why: reason.to_string(),
1795 },
1796 ..external
1797 })
1798 .collect(),
1799 }
1800}
1801
1802#[cfg(test)]
1803mod tests {
1804 use super::*;
1805
1806 fn one(text: &str) -> Line {
1807 let mut v = parse_lines(text);
1808 assert_eq!(v.len(), 1, "expected one entry from {text:?}");
1809 v.pop().expect("one")
1810 }
1811
1812 /// The error a line produced, as a VALUE. Tests used to match on the prose,
1813 /// which coupled them to wording and would have kept passing if the wording
1814 /// stayed while the meaning changed.
1815 fn why(l: &Line) -> ParseError {
1816 match l {
1817 Line::Broken { why, .. } => why.clone(),
1818 Line::Usable(d) => panic!("{} parsed when it should not have", d.name),
1819 Line::Tool(pin) => panic!("{} parsed as a pin, not a broken line", pin.program),
1820 Line::Policy { what, .. } => {
1821 panic!("{} parsed as policy, not a broken line", what.describe())
1822 }
1823 Line::Tree(g) => panic!("{} parsed as a tree gate, not a broken line", g.name),
1824 }
1825 }
1826
1827 fn usable(l: &Line) -> &Declared {
1828 match l {
1829 Line::Usable(d) => d,
1830 Line::Broken { name, why, .. } => panic!("{name} failed to parse: {why}"),
1831 Line::Tool(pin) => panic!("{} is a tool pin, not a declaration", pin.program),
1832 Line::Policy { what, .. } => {
1833 panic!("{} is policy, not a declaration", what.describe())
1834 }
1835 Line::Tree(g) => panic!("{} is a tree gate, not a declaration", g.name),
1836 }
1837 }
1838
1839 fn tree(l: &Line) -> &TreeGate {
1840 match l {
1841 Line::Tree(g) => g,
1842 Line::Broken { name, why, .. } => panic!("{name} failed to parse: {why}"),
1843 other => panic!("{} is not a tree gate", other.name()),
1844 }
1845 }
1846
1847 #[test]
1848 fn tree_full_line_parses_with_options() {
1849 let l = one("tree eslint eslint *.ts,*.tsx attest cwd=web/ inputs=tsconfig.json,.eslintignore npm run lint -- {cache}");
1850 let g = tree(&l);
1851 assert_eq!(g.name, "eslint");
1852 assert_eq!(g.tool, TreeTool::Eslint);
1853 assert_eq!(g.exts, vec![".ts".to_string(), ".tsx".to_string()]);
1854 assert_eq!(g.cwd.as_deref(), Some("web"));
1855 assert_eq!(
1856 g.inputs,
1857 vec!["tsconfig.json".to_string(), ".eslintignore".to_string()]
1858 );
1859 assert_eq!(g.command, "npm run lint -- {cache}");
1860 assert_eq!(g.id(), "tree-eslint");
1861 assert_eq!(g.stamp_key(), "tree:eslint");
1862 assert!(!l.is_check());
1863 }
1864
1865 #[test]
1866 fn tree_normalizes_cache_dangling_dashes_and_whitespace() {
1867 assert_eq!(normalize_command("npm run lint -- {cache}"), "npm run lint");
1868 assert_eq!(normalize_command("npx eslint . {cache}"), "npx eslint .");
1869 assert_eq!(
1870 normalize_command("uvx ruff@0.16.0 check packages"),
1871 "uvx ruff@0.16.0 check packages"
1872 );
1873 // A `--` that is NOT trailing is the command's own and stays.
1874 assert_eq!(
1875 normalize_command("npm run lint -- --quiet"),
1876 "npm run lint -- --quiet"
1877 );
1878 }
1879
1880 #[test]
1881 fn tree_env_assignment_begins_the_command() {
1882 let l =
1883 one("tree eslint eslint * attest NODE_OPTIONS=--max-old-space-size=4096 npm run lint");
1884 let g = tree(&l);
1885 assert_eq!(g.cwd, None);
1886 assert_eq!(
1887 g.command,
1888 "NODE_OPTIONS=--max-old-space-size=4096 npm run lint"
1889 );
1890 }
1891
1892 /// `dir/**/*.ext` is the one trigger with a `/` in it: a whole directory
1893 /// prefix and a plain suffix. Everything else with a slash, a glob or an
1894 /// empty segment is refused, so the grammar cannot grow a glob by accident.
1895 #[test]
1896 fn a_directory_token_is_a_trigger_and_nothing_else_with_a_slash_is() {
1897 let Line::Usable(d) = one("pre-commit plugin claude-plugin/**/*.md block true\n")
1898 else {
1899 panic!("a directory trigger should parse");
1900 };
1901 assert_eq!(d.dirs, ["claude-plugin/**/*.md"]);
1902 assert!(d.exts.is_empty() && d.names.is_empty());
1903
1904 let Line::Usable(d) = one("pre-commit plugin docs/x/**/*.md+Cargo.toml block true\n")
1905 else {
1906 panic!("a directory trigger with an opt-in should parse");
1907 };
1908 assert_eq!(d.dirs, ["docs/x/**/*.md"]);
1909 assert_eq!(d.opt_in, ["Cargo.toml"]);
1910
1911 for bad in [
1912 "claude-*/**/*.md",
1913 "/abs/**/*.md",
1914 "a//b/**/*.md",
1915 "../x/**/*.md",
1916 "a/./**/*.md",
1917 "x/**/*",
1918 "claude-plugin/*.md",
1919 "claude-plugin/**/*.md/x",
1920 ] {
1921 let l = one(&format!("pre-commit plugin {bad} block true\n"));
1922 assert!(
1923 matches!(why(&l), ParseError::BadScope(_)),
1924 "{bad} must be refused"
1925 );
1926 }
1927 }
1928
1929 /// `docs-skip` is a leading marker like `fix` and `files`, and it means
1930 /// something only where there is a staged change to judge.
1931 #[test]
1932 fn docs_skip_is_a_marker_and_refused_on_pre_push() {
1933 let Line::Usable(d) = one("pre-commit adr *+.adr.yaml block docs-skip aval check\n")
1934 else {
1935 panic!("docs-skip should parse on pre-commit");
1936 };
1937 assert!(d.docs_skip);
1938 assert_eq!(d.program, "aval");
1939 assert_eq!(
1940 why(&one("pre-push adr * block docs-skip aval check\n")),
1941 ParseError::DocsSkipOnPrePush
1942 );
1943 }
1944
1945 #[test]
1946 fn tree_cache_refused_for_a_tool_without_one() {
1947 let l = one("tree ruff-check ruff * attest uvx ruff@0.16.0 check packages {cache}");
1948 assert_eq!(why(&l), ParseError::BadTreeCache);
1949 }
1950
1951 #[test]
1952 fn tree_cache_twice_refused() {
1953 let l = one("tree eslint eslint * attest npx eslint {cache} . {cache}");
1954 assert_eq!(why(&l), ParseError::BadTreeCache);
1955 }
1956
1957 #[test]
1958 fn tree_bad_tool_refused() {
1959 let l = one("tree lint biome * attest npx biome check .");
1960 assert_eq!(why(&l), ParseError::BadTreeTool("biome".into()));
1961 }
1962
1963 #[test]
1964 fn tree_missing_attest_refused() {
1965 let l = one("tree eslint eslint * block npx eslint .");
1966 assert!(matches!(why(&l), ParseError::BadTreeLine(_)));
1967 }
1968
1969 #[test]
1970 fn tree_absolute_cwd_refused() {
1971 let l = one("tree eslint eslint * attest cwd=/etc npx eslint .");
1972 assert_eq!(why(&l), ParseError::BadTreeOption("cwd=/etc".into()));
1973 }
1974
1975 #[test]
1976 fn tree_parent_dir_in_cwd_refused() {
1977 let l = one("tree eslint eslint * attest cwd=web/../.. npx eslint .");
1978 assert_eq!(why(&l), ParseError::BadTreeOption("cwd=web/../..".into()));
1979 }
1980
1981 #[test]
1982 fn tree_glob_in_inputs_refused() {
1983 let l = one("tree eslint eslint * attest inputs=src/*.json npx eslint .");
1984 assert_eq!(
1985 why(&l),
1986 ParseError::BadTreeOption("inputs=src/*.json".into())
1987 );
1988 }
1989
1990 #[test]
1991 fn tree_unknown_option_refused() {
1992 let l = one("tree eslint eslint * attest shell=bash npx eslint .");
1993 assert_eq!(why(&l), ParseError::BadTreeOption("shell=bash".into()));
1994 }
1995
1996 #[test]
1997 fn tree_duplicate_name_refused() {
1998 let v = parse_lines(
1999 "tree eslint eslint * attest npx eslint .\ntree eslint eslint * attest npx eslint src",
2000 );
2001 assert_eq!(v.len(), 2);
2002 tree(&v[0]);
2003 assert_eq!(why(&v[1]), ParseError::Duplicate("eslint".into()));
2004 }
2005
2006 #[test]
2007 fn tree_name_saying_its_trigger_refused() {
2008 let l = one("tree pre-commit-lint eslint * attest npx eslint .");
2009 assert_eq!(why(&l), ParseError::TriggerInName("pre-commit-lint".into()));
2010 }
2011
2012 #[test]
2013 fn tree_bad_name_refused() {
2014 let l = one("tree -lint eslint * attest npx eslint .");
2015 assert_eq!(why(&l), ParseError::BadTreeName("-lint".into()));
2016 }
2017
2018 #[test]
2019 fn tree_gates_are_not_runnable_checks() {
2020 let text = "tree eslint eslint * attest npx eslint .\npre-commit smoke * block true";
2021 let checks = parse(text);
2022 assert_eq!(checks.len(), 1);
2023 assert_eq!(checks[0].id, "pre-commit-smoke");
2024 let gates = tree_gates(text);
2025 assert_eq!(gates.len(), 1);
2026 assert_eq!(gates[0].normalized(), "npx eslint .");
2027 }
2028
2029 /// The scope column's bare tokens are exact filenames — basename-matched,
2030 /// so `package.json` cannot be counterfeited by `not-package.json` — and
2031 /// they mix freely with extensions. Directories and free `*` stay refused.
2032 #[test]
2033 fn a_bare_scope_token_is_an_exact_filename() {
2034 let line = one("pre-commit lockcheck package.json block ./check.sh\n");
2035 let d = usable(&line);
2036 assert!(d.exts.is_empty());
2037 assert_eq!(d.names, ["package.json"]);
2038
2039 let line = one("pre-commit x *.ts,package.json,.prettierrc block ./x\n");
2040 let d = usable(&line);
2041 assert_eq!(d.exts, [".ts"]);
2042 assert_eq!(d.names, ["package.json", ".prettierrc"]);
2043
2044 assert_eq!(
2045 why(&one("pre-commit x src/package.json block ./x\n")),
2046 ParseError::BadScope("src/package.json".into())
2047 );
2048 assert_eq!(
2049 why(&one("pre-commit x pkg* block ./x\n")),
2050 ParseError::BadScope("pkg*".into())
2051 );
2052 }
2053
2054 /// `+` adds the repository condition a builtin has always had.
2055 ///
2056 /// The separator is the one `amont list` already prints between the two
2057 /// halves (`needs .rs + Cargo.toml`), so what a reader sees in the listing
2058 /// is what they write in the file.
2059 #[test]
2060 fn a_scope_can_name_what_the_repository_must_carry() {
2061 let line = one("pre-commit rubocop *.rb+.rubocop.yml block rubocop\n");
2062 let d = usable(&line);
2063 assert_eq!(d.exts, [".rb"]);
2064 assert!(d.names.is_empty());
2065 assert_eq!(d.opt_in, [".rubocop.yml"]);
2066
2067 // Both sides comma-separated: any trigger, and any ONE opt-in.
2068 let line = one("pre-commit x *.rb,Rakefile+.rubocop.yml,.rubocop_todo.yml block ./x\n");
2069 let d = usable(&line);
2070 assert_eq!(d.exts, [".rb"]);
2071 assert_eq!(d.names, ["Rakefile"]);
2072 assert_eq!(d.opt_in, [".rubocop.yml", ".rubocop_todo.yml"]);
2073
2074 // No trigger half: "any change, in a repository that carries this".
2075 let line = one("pre-commit x +Gemfile block ./x\n");
2076 let d = usable(&line);
2077 assert!(d.exts.is_empty() && d.names.is_empty());
2078 assert_eq!(d.opt_in, ["Gemfile"]);
2079 }
2080
2081 /// Every declaration written before `+` existed keeps its meaning: no
2082 /// opt-in is the old behaviour, which is "applies wherever it triggers".
2083 #[test]
2084 fn a_scope_without_a_plus_is_unchanged() {
2085 let line = one("pre-commit x *.ts,package.json block ./x\n");
2086 let d = usable(&line);
2087 assert!(d.opt_in.is_empty());
2088 let line = one("pre-commit x * block ./x\n");
2089 let d = usable(&line);
2090 assert!(d.opt_in.is_empty() && d.exts.is_empty() && d.names.is_empty());
2091 }
2092
2093 /// A `+` that promises a condition and names none is refused, rather than
2094 /// read as "no condition" — which is the opposite of what was reached for.
2095 #[test]
2096 fn a_malformed_opt_in_half_is_refused() {
2097 for bad in [
2098 "*.rb+", // promised, not given
2099 "*.rb+,", // still nothing
2100 "*.rb+a+b", // a second separator is not a filename
2101 "*.rb+sub/dir.yml", // directories are inexpressible, as on the left
2102 "*.rb+*.yml", // this grammar has no globs to mis-guess
2103 ] {
2104 let line = one(&format!("pre-commit x {bad} block ./x\n"));
2105 assert!(
2106 matches!(line, Line::Broken { .. }),
2107 "{bad} should be refused, got {line:?}"
2108 );
2109 }
2110 }
2111
2112 /// The pin grammar: exactly three tokens, claimed from a first token that
2113 /// was never a valid stage — no manifest that ever parsed changes meaning.
2114 #[test]
2115 fn a_tool_pin_parses_and_a_malformed_one_is_broken() {
2116 let line = one("tool ruff 0.6.\n");
2117 assert_eq!(
2118 line,
2119 Line::Tool(ToolPin {
2120 program: "ruff".into(),
2121 want: "0.6.".into()
2122 })
2123 );
2124 assert_eq!(why(&one("tool ruff\n")), ParseError::BadTool);
2125 assert_eq!(why(&one("tool ruff 0.6. extra\n")), ParseError::BadTool);
2126 // `tool` is only a keyword in column one — a check NAMED tool still
2127 // parses as the check it always was.
2128 let line = one("pre-commit tool * block make tool\n");
2129 assert_eq!(usable(&line).name, "tool");
2130 }
2131
2132 #[test]
2133 fn parses_the_documented_example() {
2134 let v = parse_lines(
2135 "# stage name scope severity command\n\
2136 pre-commit lint-shell *.sh block scripts/lint-shell.sh\n\
2137 pre-push smoke * warn make smoke\n",
2138 );
2139 assert_eq!(v.len(), 2);
2140
2141 let a = usable(&v[0]);
2142 assert_eq!(a.name, "lint-shell");
2143 assert_eq!(a.stage, Stage::PreCommit);
2144 assert_eq!(a.severity, Severity::Block);
2145 assert_eq!(a.program, "scripts/lint-shell.sh");
2146 assert!(a.args.is_empty());
2147 assert_eq!(a.exts, [".sh"]);
2148
2149 let b = usable(&v[1]);
2150 assert_eq!(b.stage, Stage::PrePush);
2151 assert_eq!(b.severity, Severity::Warn);
2152 // A command with arguments is split, not handed to a shell.
2153 assert_eq!(b.program, "make");
2154 assert_eq!(b.args, ["smoke"]);
2155 assert!(b.exts.is_empty(), "`*` gates on nothing");
2156 }
2157
2158 /// Blank lines and comments are not entries, and must not become broken
2159 /// ones — a file that is mostly documentation would otherwise report a
2160 /// dozen gaps.
2161 #[test]
2162 fn comments_and_blank_lines_produce_nothing() {
2163 assert!(parse_lines("\n \n# just a comment\n\t# indented\n").is_empty());
2164 }
2165
2166 /// The rule the module commits to: a line that cannot be understood still
2167 /// yields a check, so its absence is visible. Matched by VARIANT.
2168 #[test]
2169 fn a_malformed_line_becomes_a_visible_gap() {
2170 let cases: [(&str, ParseError); 4] = [
2171 (
2172 "pre-commit lint-shell *.sh block\n",
2173 ParseError::MissingFields,
2174 ),
2175 (
2176 "nonsense lint-shell *.sh block x\n",
2177 ParseError::BadStage("nonsense".into()),
2178 ),
2179 (
2180 "pre-commit lint-shell ?.sh block x\n",
2181 ParseError::BadScope("?.sh".into()),
2182 ),
2183 (
2184 "pre-commit lint-shell *.sh loud x\n",
2185 ParseError::BadSeverity("loud".into()),
2186 ),
2187 ];
2188 for (text, expected) in cases {
2189 assert_eq!(why(&one(text)), expected, "for {text:?}");
2190 }
2191 }
2192
2193 /// The prose still has to locate the line, even though the tests no longer
2194 /// depend on its wording.
2195 #[test]
2196 fn a_gap_reports_where_it_is() {
2197 let l = one("pre-commit lint-shell *.sh loud x\n");
2198 let said = l.broken().expect("broken");
2199 assert!(said.contains("line 1"), "{said}");
2200 assert!(said.contains("severity"), "{said}");
2201 }
2202
2203 /// `fix` on a pre-push line is refused where every other bad declaration is
2204 /// refused — on every commit, named and located — rather than as a runtime
2205 /// "contract violation" discovered later at push time by fewer people.
2206 #[test]
2207 fn fix_is_refused_on_a_pre_push_line() {
2208 assert_eq!(
2209 why(&one("pre-push smoke * block fix make smoke\n")),
2210 ParseError::FixOnPrePush
2211 );
2212 // …and accepted on pre-commit.
2213 let line = one("pre-commit fmt * block fix make format\n");
2214 let declared = usable(&line);
2215 assert_eq!(declared.fix, Fix::Rewrite);
2216 assert_eq!(declared.program, "make");
2217 assert_eq!(declared.args, ["format"]);
2218 }
2219
2220 /// Every manifest written before `fix` existed must still parse the same.
2221 #[test]
2222 fn a_command_that_merely_starts_with_fix_is_not_a_marker() {
2223 let line = one("pre-commit x * block fixup-tool --check\n");
2224 let declared = usable(&line);
2225 assert_eq!(declared.fix, Fix::None);
2226 assert_eq!(declared.program, "fixup-tool");
2227 }
2228
2229 /// The `files` marker, alone and stacked with `fix` in either order —
2230 /// two markers whose order carries no meaning must not be
2231 /// order-sensitive.
2232 #[test]
2233 fn the_files_marker_parses_alone_and_in_either_order_with_fix() {
2234 let line = one("pre-commit sc *.sh block files shellcheck\n");
2235 let declared = usable(&line);
2236 assert!(declared.files);
2237 assert_eq!(declared.fix, Fix::None);
2238 assert_eq!(declared.program, "shellcheck");
2239
2240 for text in [
2241 "pre-commit fmt * block fix files prettier --write\n",
2242 "pre-commit fmt * block files fix prettier --write\n",
2243 ] {
2244 let line = one(text);
2245 let declared = usable(&line);
2246 assert!(declared.files, "for {text:?}");
2247 assert_eq!(declared.fix, Fix::Rewrite, "for {text:?}");
2248 assert_eq!(declared.program, "prettier", "for {text:?}");
2249 assert_eq!(declared.args, ["--write"], "for {text:?}");
2250 }
2251 }
2252
2253 /// A command that merely starts with `files` keeps its name, exactly as
2254 /// `fixup-tool` keeps its own.
2255 #[test]
2256 fn a_command_that_merely_starts_with_files_is_not_a_marker() {
2257 let line = one("pre-commit x * block files-checker --strict\n");
2258 let declared = usable(&line);
2259 assert!(!declared.files);
2260 assert_eq!(declared.program, "files-checker");
2261 }
2262
2263 /// A gap with no name cannot be reported, and a line this broken has none.
2264 #[test]
2265 fn a_nameless_line_is_named_after_its_position() {
2266 let l = one("pre-commit\n");
2267 assert_eq!(l.name(), "amont.conf:1");
2268 assert_eq!(why(&l), ParseError::MissingFields);
2269 }
2270
2271 /// An external must not be able to take a built-in's id — it would either
2272 /// shadow `pre-push-branch-protect` or silently lose to it, and neither is
2273 /// something a repository should be able to do by editing a text file.
2274 ///
2275 /// Judged on the id, so the same declaration is refused on one trigger and
2276 /// accepted on the other. That is not a loophole: `pre-push-clippy` is a
2277 /// different check from `pre-commit-clippy`, and nothing is shadowed.
2278 #[test]
2279 fn a_built_in_id_is_refused() {
2280 assert_eq!(
2281 why(&one("pre-commit clippy *.rs block x\n")),
2282 ParseError::NameTaken("clippy".into())
2283 );
2284 assert!(matches!(
2285 one("pre-push clippy *.rs block x\n"),
2286 Line::Usable(_)
2287 ));
2288 // And a pre-push built-in is protected on pre-push, not on pre-commit,
2289 // for the same reason.
2290 assert_eq!(
2291 why(&one("pre-push pull-rebase * block x\n")),
2292 ParseError::NameTaken("pull-rebase".into())
2293 );
2294 assert!(matches!(
2295 one("pre-commit pull-rebase * block x\n"),
2296 Line::Usable(_)
2297 ));
2298 }
2299
2300 /// The stage column says which trigger a line is for. Saying it again in
2301 /// the name is the one way to make an id ambiguous: `pre-commit-clippy` as
2302 /// a NAME is a check whose short name is the built-in's full id, so one
2303 /// `hook.skip` would silence both.
2304 #[test]
2305 fn a_name_that_says_its_own_trigger_is_refused() {
2306 for name in ["pre-commit", "pre-push", "pre-commit-clippy", "pre-push-x"] {
2307 assert_eq!(
2308 why(&one(&format!("pre-commit {name} * block x\n"))),
2309 ParseError::TriggerInName(name.into()),
2310 "{name}"
2311 );
2312 }
2313 // A name that merely begins with the same letters is fine — the trigger
2314 // has to be followed by the separator to count.
2315 assert!(matches!(
2316 one("pre-commit pre-commitish * block x\n"),
2317 Line::Usable(_)
2318 ));
2319 }
2320
2321 /// Two USABLE lines with one ID: the second cannot be addressed by
2322 /// `hook.skip` or by a severity override, so it is refused.
2323 #[test]
2324 fn a_duplicate_id_is_refused() {
2325 let v = parse_lines(
2326 "pre-commit smoke * block a\n\
2327 pre-commit smoke * block b\n",
2328 );
2329 assert_eq!(v.len(), 2);
2330 assert_eq!(usable(&v[0]).id(), "pre-commit-smoke");
2331 assert_eq!(why(&v[1]), ParseError::Duplicate("smoke".into()));
2332 }
2333
2334 /// The same name on both triggers is TWO checks, and this used to refuse
2335 /// the second. Somebody wanting a `show-unicorn` on commit and on push had
2336 /// no way to write it, and no way to skip or downgrade one without the
2337 /// other — the bare name could not tell them apart.
2338 #[test]
2339 fn the_same_name_on_two_triggers_is_allowed() {
2340 let v = parse_lines(
2341 "pre-commit show-unicorn * block a\n\
2342 pre-push show-unicorn * block b\n",
2343 );
2344 assert_eq!(v.len(), 2);
2345 assert_eq!(usable(&v[0]).id(), "pre-commit-show-unicorn");
2346 assert_eq!(usable(&v[1]).id(), "pre-push-show-unicorn");
2347
2348 // And each is separately addressable, while the short name takes both —
2349 // which is the whole vocabulary, applied to declared checks.
2350 for (id, only) in [
2351 ("pre-commit-show-unicorn", "pre-push-show-unicorn"),
2352 ("pre-push-show-unicorn", "pre-commit-show-unicorn"),
2353 ] {
2354 assert!(crate::skip_suppresses(id, id));
2355 assert!(!crate::skip_suppresses(only, id));
2356 }
2357 assert!(crate::skip_suppresses(
2358 "pre-commit-show-unicorn",
2359 "show-unicorn"
2360 ));
2361 assert!(crate::skip_suppresses(
2362 "pre-push-show-unicorn",
2363 "show-unicorn"
2364 ));
2365 assert!(crate::skip_suppresses(
2366 "pre-commit-show-unicorn",
2367 "pre-commit"
2368 ));
2369 assert!(!crate::skip_suppresses(
2370 "pre-push-show-unicorn",
2371 "pre-commit"
2372 ));
2373 }
2374
2375 /// A line that cannot run does not RESERVE its name.
2376 ///
2377 /// It used to: broken and usable entries shared one list, so a valid
2378 /// declaration was rejected as "declared twice" for colliding with a line
2379 /// that could never execute — pointing the reader at the wrong line, and
2380 /// forcing them to fix the first before the second would work at all.
2381 #[test]
2382 fn a_broken_line_does_not_reserve_its_name() {
2383 let v = parse_lines(
2384 "pre-commit smoke * LOUD make a\n\
2385 pre-commit smoke * block make b\n",
2386 );
2387 assert_eq!(v.len(), 2);
2388 assert_eq!(why(&v[0]), ParseError::BadSeverity("LOUD".into()));
2389 let good = usable(&v[1]);
2390 assert_eq!(good.name, "smoke");
2391 assert_eq!(good.program, "make");
2392 }
2393
2394 /// Alignment is cosmetic. A file someone has lined up with tabs, or not
2395 /// lined up at all, must parse identically.
2396 #[test]
2397 fn field_alignment_does_not_matter() {
2398 let spaced = one("pre-commit lint-shell *.sh block make lint\n");
2399 let tabbed = one("pre-commit\tlint-shell\t*.sh\tblock\tmake lint\n");
2400 assert_eq!(usable(&spaced), usable(&tabbed));
2401 assert_eq!(usable(&spaced).args, ["lint"]);
2402 }
2403
2404 #[test]
2405 fn several_extensions_can_gate_one_check() {
2406 let e = External::from(one("pre-commit shell *.sh,*.bash block make lint\n"));
2407 assert!(e.scope().matches(&["a.bash".into()]));
2408 assert!(e.scope().matches(&["a.sh".into()]));
2409 assert!(!e.scope().matches(&["a.zsh".into()]));
2410 }
2411
2412 /// `tokenise` states its arity in the type, so "four tokens then a command"
2413 /// is checked rather than remembered.
2414 #[test]
2415 fn tokenise_wants_four_fields_and_a_command() {
2416 assert!(tokenise("a b c").is_none(), "too few fields");
2417 assert!(tokenise("a b c d").is_none(), "four fields, no command");
2418 // Trailing whitespace reaches the four fields but still leaves nothing
2419 // to run — the case the `?` on the last field cannot catch.
2420 assert!(
2421 tokenise("a b c d ").is_none(),
2422 "command is all whitespace"
2423 );
2424 assert!(tokenise("a b c d\t").is_none(), "command is a tab");
2425 let (fields, cmd) = tokenise("a b\tc d run it").expect("four and a command");
2426 assert_eq!(fields, ["a", "b", "c", "d"]);
2427 assert_eq!(cmd, "run it");
2428 }
2429
2430 /// An unusable line carries no command at all — the type has nowhere to put
2431 /// one, which is the point of the split.
2432 #[test]
2433 fn an_unusable_external_holds_no_command() {
2434 let e = External::from(one("pre-commit lint-shell *.sh loud echo hi\n"));
2435 assert!(matches!(e.kind, Kind::Unusable { .. }));
2436 // And it can never block, whatever severity anyone configures.
2437 assert_eq!(e.severity(), Severity::Warn);
2438 }
2439
2440 /// A missing manifest is the normal case and must not be an error.
2441 #[test]
2442 fn a_repository_with_no_manifest_declares_nothing() {
2443 assert!(read(Path::new("/nonexistent-c8f2")).is_empty());
2444 assert!(read_lines(Path::new("/nonexistent-c8f2")).is_empty());
2445 }
2446
2447 /// `Line` exists to spare the dashboard a leak, not to become a second
2448 /// opinion about what a manifest says.
2449 #[test]
2450 fn the_leaking_and_non_leaking_parsers_agree() {
2451 let text = "pre-commit lint-shell *.sh,*.bash block make lint\n\
2452 pre-push smoke * warn make smoke\n\
2453 pre-commit broken ? block x\n";
2454 let lines = parse_lines(text);
2455 let externals = parse(text);
2456 assert_eq!(lines.len(), externals.len());
2457 for (l, e) in lines.iter().zip(&externals) {
2458 assert_eq!(l.id(), e.name(), "the id is what a check answers to");
2459 assert_eq!(
2460 l.name(),
2461 e.short_name,
2462 "and the short name is what it is called"
2463 );
2464 assert_eq!(l.stage(), e.stage());
2465 assert_eq!(
2466 l.broken().is_some(),
2467 matches!(e.kind, Kind::Unusable { .. })
2468 );
2469 if let Line::Usable(d) = l {
2470 assert_eq!(d.severity, e.severity());
2471 // The scope the dashboard would DESCRIBE is the scope the
2472 // dispatcher would ENFORCE.
2473 assert_eq!(d.exts, e.scope().files);
2474 }
2475 }
2476 }
2477}