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