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