greengate_runtime/check.rs
1//! What a check IS, as one value rather than four tables.
2//!
3//! Before this, a check was spread across `REGISTRY` (name → fn), two ordered
4//! name lists, and a language table in the fleet crate — four places keyed by
5//! the same string, held together by reconciliation tests. Those tests were
6//! good, but they policed a shape that should not have been splittable. With
7//! the metadata attached to the check, there is nothing left to reconcile.
8//!
9//! It also gives external checks somewhere to exist. A third party cannot add a
10//! Rust module without rebuilding the binary, so extension means a declared
11//! command implementing this same trait — and the dispatcher not caring which
12//! kind it is holding.
13
14use crate::registry::Ctx;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Stage {
18 PreCommit,
19 PrePush,
20}
21
22impl Stage {
23 pub fn as_str(self) -> &'static str {
24 match self {
25 Stage::PreCommit => "pre-commit",
26 Stage::PrePush => "pre-push",
27 }
28 }
29}
30
31/// When a check is relevant, declared rather than reimplemented by every
32/// reader.
33///
34/// A CONJUNCTION, not a choice: ruff is `.py` files AND a ruff config; clippy
35/// is `.rs` AND `Cargo.toml`. An earlier design offered these as alternatives
36/// plus a `Custom` escape hatch, which would have swallowed nearly every check
37/// and left the dashboard knowing nothing.
38/// A git operation that is part-way through.
39///
40/// Detected from the marker files git writes into `$GIT_DIR`, which is how git
41/// itself and every prompt-writer answers the question.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum GitState {
44 Merge,
45 Rebase,
46 CherryPick,
47 Revert,
48 Bisect,
49}
50
51impl GitState {
52 /// The marker git writes. `rebase-merge` and `rebase-apply` are
53 /// DIRECTORIES; the rest are files, and `Path::exists` covers both.
54 ///
55 /// **`REBASE_HEAD` is deliberately NOT one of them.** Every other marker
56 /// here is removed when the operation ends — `MERGE_HEAD`,
57 /// `CHERRY_PICK_HEAD` and `REVERT_HEAD` go when the commit lands — but
58 /// git leaves `REBASE_HEAD` behind after `rebase --continue` finishes, as
59 /// a convenience ref naming the commit the rebase last stopped on. It
60 /// says a rebase HAPPENED, not that one is happening.
61 ///
62 /// Reading it as state made every check that declares `not_during`
63 /// a rebase — `pull-rebase` and all four test gates — pause FOREVER in
64 /// any worktree that had ever hit a rebase conflict. Silently, apart from
65 /// one line that reads as a passing condition ("5 check(s) paused during
66 /// a rebase") and would be true again in a minute. It never was. Found by
67 /// this repository's own audit branch, one rebase conflict after it was
68 /// created: `git status` clean, no rebase directory, every push gate off.
69 ///
70 /// The two directories are the honest answer, and they are what git's own
71 /// prompt scripts read.
72 pub fn markers(self) -> &'static [&'static str] {
73 match self {
74 GitState::Merge => &["MERGE_HEAD"],
75 GitState::Rebase => &["rebase-merge", "rebase-apply"],
76 GitState::CherryPick => &["CHERRY_PICK_HEAD"],
77 GitState::Revert => &["REVERT_HEAD"],
78 GitState::Bisect => &["BISECT_LOG"],
79 }
80 }
81
82 pub fn as_str(self) -> &'static str {
83 match self {
84 GitState::Merge => "a merge",
85 GitState::Rebase => "a rebase",
86 GitState::CherryPick => "a cherry-pick",
87 GitState::Revert => "a revert",
88 GitState::Bisect => "a bisect",
89 }
90 }
91
92 pub const ALL: [GitState; 5] = [
93 GitState::Merge,
94 GitState::Rebase,
95 GitState::CherryPick,
96 GitState::Revert,
97 GitState::Bisect,
98 ];
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub struct Scope {
103 /// Extensions that trigger it. Empty means any change.
104 pub files: &'static [&'static str],
105 /// Exact FILENAMES that trigger it — `package.json`, `Dockerfile` —
106 /// matched against the path's basename, never as a suffix: an extension
107 /// list cannot say "package.json" without also matching
108 /// `not-package.json`.
109 ///
110 /// The manifest's scope column fills this, and so does
111 /// `pre-commit-hadolint`, the first builtin to need it: a Dockerfile has
112 /// no extension to gate on.
113 pub names: &'static [&'static str],
114 /// Directory-scoped triggers, each written `dir/**/*.ext`: a path is in
115 /// scope when it sits under `dir/` and ends with `.ext`. The manifest's
116 /// scope column is the only writer; a built-in never needs one.
117 pub dirs: &'static [&'static str],
118 /// Config paths that opt a repository in. Empty means always on.
119 pub opt_in: &'static [&'static str],
120 /// Git operations during which this check does not run.
121 ///
122 /// The other half of "when does this apply". `files` and `opt_in` say which
123 /// REPOSITORIES and which CHANGES; this says which repository STATES — a
124 /// question that used to be answered by one hard-coded `CHERRY_PICK_HEAD`
125 /// test in one dispatcher, with the other carrying a comment admitting it
126 /// had none because the shell version had none.
127 pub not_during: &'static [GitState],
128}
129
130impl Scope {
131 pub const ALWAYS: Scope = Scope {
132 files: &[],
133 names: &[],
134 dirs: &[],
135 opt_in: &[],
136 not_during: &[],
137 };
138
139 pub const fn files(files: &'static [&'static str]) -> Scope {
140 Scope {
141 files,
142 names: &[],
143 dirs: &[],
144 opt_in: &[],
145 not_during: &[],
146 }
147 }
148
149 /// Gated on exact basenames rather than extensions — what a `Dockerfile`
150 /// needs, having none.
151 pub const fn named(names: &'static [&'static str]) -> Scope {
152 Scope {
153 files: &[],
154 names,
155 dirs: &[],
156 opt_in: &[],
157 not_during: &[],
158 }
159 }
160
161 pub const fn new(files: &'static [&'static str], opt_in: &'static [&'static str]) -> Scope {
162 Scope {
163 files,
164 names: &[],
165 dirs: &[],
166 opt_in,
167 not_during: &[],
168 }
169 }
170
171 /// The same scope, silent during these operations.
172 pub const fn not_during(self, states: &'static [GitState]) -> Scope {
173 Scope {
174 files: self.files,
175 names: self.names,
176 dirs: self.dirs,
177 opt_in: self.opt_in,
178 not_during: states,
179 }
180 }
181
182 /// No file gate at all — every change is in scope.
183 /// What fires when EITHER `self` or `twin` would: both scopes' file
184 /// patterns, with `self`'s own opt-in and `not_during`. The scope a
185 /// commit-time declaration fires on once its push twin's files count too
186 /// (`Manifest::resolve_triggers`).
187 ///
188 /// An unscoped `self` already fires on everything, and merging patterns
189 /// into it would NARROW it, so it is returned as it is. The slices are
190 /// leaked like every declared scope (see `manifest::leak`), once, and only
191 /// when the twin adds something.
192 pub fn union(&self, twin: &Scope) -> Scope {
193 fn merged(
194 own: &'static [&'static str],
195 twin: &'static [&'static str],
196 ) -> &'static [&'static str] {
197 let mut all: Vec<&'static str> = own.to_vec();
198 for item in twin {
199 if !all.contains(item) {
200 all.push(item);
201 }
202 }
203 if all.len() == own.len() {
204 return own;
205 }
206 Box::leak(all.into_boxed_slice())
207 }
208 if self.is_unscoped() {
209 return *self;
210 }
211 Scope {
212 files: merged(self.files, twin.files),
213 names: merged(self.names, twin.names),
214 dirs: merged(self.dirs, twin.dirs),
215 opt_in: self.opt_in,
216 not_during: self.not_during,
217 }
218 }
219
220 pub fn is_unscoped(&self) -> bool {
221 self.files.is_empty() && self.names.is_empty() && self.dirs.is_empty()
222 }
223
224 /// Does ONE path fall inside the file gate?
225 pub fn covers(&self, path: &str) -> bool {
226 self.files.iter().any(|ext| path.ends_with(ext))
227 || self.dirs.iter().any(|token| in_dir(token, path))
228 || {
229 let base = path.rsplit('/').next().unwrap_or(path);
230 self.names.contains(&base)
231 }
232 }
233
234 /// Does this gate have work to do, given the files a PUSH changed?
235 ///
236 /// Distinct from [`matches`], and the distinction is the bug this was
237 /// written for. `matches` answers "would this check ever fire in a
238 /// repository containing these paths", so it also consults `opt_in` —
239 /// the marker that says a repository is a Rust one at all. Feeding a
240 /// push DIFF to that question conflates two things: whether the
241 /// repository is Rust (settled long before, when the dispatcher decided
242 /// this check runs here) and whether this push changed any Rust.
243 ///
244 /// `pre-push-cargo-test` opts in on `Cargo.toml`. A `.rs`-only push, in
245 /// a repository with a `Cargo.toml` sitting right there, therefore
246 /// answered NO to "is this a Rust repository" — because that one file
247 /// was not in the diff — and was judged to have nothing worth attesting.
248 /// Which is to say: the most ordinary Rust push there is.
249 ///
250 /// Opt-in is a fact about the repository. This asks only about the
251 /// change, which is what a caller holding a diff means.
252 pub fn touches(&self, paths: &[String]) -> bool {
253 self.is_unscoped() || paths.iter().any(|p| self.covers(p))
254 }
255
256 /// Did the gate see EVERY one of `paths`? All-match, where [`matches`]
257 /// is any-match: the caller asking this is deciding whether a commit-time
258 /// run COVERED a push, and under-approximating is the safe direction.
259 pub fn covers_all(&self, paths: &[String]) -> bool {
260 self.is_unscoped() || paths.iter().all(|p| self.covers(p))
261 }
262
263 /// Would this check ever fire, given the paths a repository contains?
264 ///
265 /// Deliberately coarse for checks that resolve an ancestor at run time —
266 /// `cargo-fmt` declares `Cargo.toml` meaning "somewhere here" while
267 /// enforcing "nearest above the staged file". The dispatcher asks the
268 /// precise question by running the check; this answers the dashboard's
269 /// question, "would it ever fire", where over-approximating is the safe
270 /// direction.
271 pub fn matches(&self, paths: &[String]) -> bool {
272 self.touches(paths) && self.opted_in(paths)
273 }
274
275 /// Does this repository carry the marker that turns the check on?
276 ///
277 /// Split out of [`matches`] because the two halves ask about DIFFERENT
278 /// path lists, and conflating them is a bug this codebase has now made
279 /// twice. `touches` asks about the CHANGE — the staged set, or the push
280 /// diff. This asks about the REPOSITORY, and the only honest source for
281 /// that is the index (`git ls-files`).
282 ///
283 /// Feed a change to this question and it can only answer no unless that
284 /// change happened to touch the marker: a `+pom.xml` row would run when
285 /// you edited `pom.xml` and never when you edited only `.java`, which is
286 /// the ordinary case and the entire point of the gate. See `attestable`
287 /// in `dispatch.rs` for the first occurrence, in the attestation path.
288 pub fn opted_in(&self, paths: &[String]) -> bool {
289 self.opt_in.is_empty()
290 || paths.iter().any(|p| {
291 let name = p.rsplit('/').next().unwrap_or(p);
292 self.opt_in.iter().any(|c| {
293 // A trailing `*` is a prefix match: `.kube-linter*.yaml`.
294 match c.split_once('*') {
295 Some((pre, suf)) => name.starts_with(pre) && name.ends_with(suf),
296 None => name == *c,
297 }
298 })
299 })
300 }
301}
302
303/// What a check meant, as opposed to what it printed.
304///
305/// The fourth variant is the point. Fifteen sites used to warn and return 0,
306/// collapsing two different situations: "I ran and found something you should
307/// know" and "I could not run at all". `ruff config found but no ruff binary`
308/// was indistinguishable from ruff running clean — to the dispatcher, and to
309/// the dashboard. A repository where a check has silently never executed read
310/// as one where it passes.
311///
312/// That is the same invisibility `hook.skip` had before skipped checks were
313/// announced, and it took three PRs to notice there.
314///
315/// The check still prints its own message; this only classifies the result.
316///
317/// Deliberately NO `Default`. It used to be `Failed`, to fill the slot of a
318/// check whose thread died — a real rule, but `Default` means "the neutral
319/// value" to every reader and to every `#[derive(Default)]` that might later
320/// contain one. The rule is now written where it applies, in the runner.
321#[derive(Debug, Clone, Copy, PartialEq, Eq)]
322pub enum Outcome {
323 Passed,
324 /// Ran, found a problem. Whether that blocks is `Severity`, not this.
325 Failed,
326 /// Ran, found something worth saying, which does not block.
327 Warned,
328 /// Ran, found a problem, and REPAIRED it. The commit proceeds with the
329 /// repair staged, which is neither `Passed` (something happened, and the
330 /// author should know their files changed) nor `Failed`.
331 Fixed,
332 /// COULD NOT RUN — a tool is missing, or a precondition it needs to
333 /// answer at all is not met.
334 Unavailable,
335 /// NOTHING TO DO HERE — the repository lacks the marker that turns
336 /// the check on, so it judged nothing. Neither `Passed` (nothing was
337 /// verified, so nothing may be stamped or attested) nor
338 /// `Unavailable` (nothing is wrong: `amont list` calls this "inert",
339 /// and a check that is inert by the registry's own account has no
340 /// business announcing that it could not run).
341 Inert,
342 /// DEFERRED TO CI — a Heavy check whose host slot did not free within
343 /// `slotWait` under `onBusy defer` (ADR-0013). It did not run, so nothing
344 /// may be stamped or attested and CI runs it; it never blocks, whatever
345 /// the severity, because nothing was judged.
346 Deferred,
347 /// SKIPPED — a Heavy pre-commit check that never started, because a
348 /// Light check before it already blocked the commit (ADR-0020). Nothing
349 /// was judged, so nothing may be stamped or attested; it never blocks by
350 /// itself (the Light failure does), and it is always said, so a commit
351 /// that was refused never reads as one whose suite passed.
352 Skipped,
353}
354
355impl Outcome {
356 /// Did the check judge something, or would it have but for a skip? What
357 /// the pre-commit wave ledger counts as a Heavy check that waited
358 /// (ADR-0020). Every variant named, so a new one is a compile error here.
359 pub fn judged_or_skipped(self) -> bool {
360 match self {
361 Outcome::Passed
362 | Outcome::Failed
363 | Outcome::Warned
364 | Outcome::Fixed
365 | Outcome::Skipped => true,
366 Outcome::Unavailable | Outcome::Inert | Outcome::Deferred => false,
367 }
368 }
369}
370
371/// What a HOOK concluded — the only thing git actually reads.
372///
373/// Distinct from `Outcome`, which is what one CHECK concluded. Git has exactly
374/// two questions to ask a hook, so this has exactly two answers, and the `i32`
375/// that expresses them lives at the process boundary rather than being threaded
376/// through every hook, dispatcher and handler as it used to be.
377#[derive(Debug, Clone, Copy, PartialEq, Eq)]
378pub enum Verdict {
379 Proceed,
380 Block,
381}
382
383impl Verdict {
384 /// The exit code git reads. The ONLY place a hook result becomes a number.
385 pub fn exit_code(self) -> i32 {
386 match self {
387 Verdict::Proceed => 0,
388 Verdict::Block => 1,
389 }
390 }
391
392 pub fn blocking(blocked: bool) -> Verdict {
393 if blocked {
394 Verdict::Block
395 } else {
396 Verdict::Proceed
397 }
398 }
399}
400
401/// Whether a failing check stops the commit or merely reports.
402///
403/// Declared per check and overridable per repository with
404/// `git config greengate.severity.<check> warn`. That is a better escape hatch
405/// than `hook.skip`, which is all-or-nothing and invisible enough that
406/// `hook.skip = e` disables all twenty checks: a downgrade keeps the signal and
407/// removes only the block.
408#[derive(Debug, Clone, Copy, PartialEq, Eq)]
409pub enum Severity {
410 Block,
411 Warn,
412}
413
414impl Severity {
415 /// The ONE mapping from configured text to severity.
416 ///
417 /// There were four: this key's reader, the manifest's severity column, the
418 /// dashboard's copy, and the dashboard's reverse mapping for `--json`. They
419 /// agreed, but nothing made them — and the dashboard's copy is its
420 /// prediction of what the dispatcher will do, which is the one thing it must
421 /// never get wrong.
422 ///
423 /// `None` for anything else, deliberately: git validates nothing here, so an
424 /// unrecognised value must fall back to the declared severity rather than
425 /// silently disable a check.
426 pub fn parse(value: &str) -> Option<Severity> {
427 match value {
428 "warn" => Some(Severity::Warn),
429 "block" => Some(Severity::Block),
430 _ => None,
431 }
432 }
433
434 /// How it is written in config and in `--json`.
435 pub fn as_str(self) -> &'static str {
436 match self {
437 Severity::Block => "block",
438 Severity::Warn => "warn",
439 }
440 }
441}
442
443/// Whether a check can rewrite the files it inspects.
444///
445/// Off by default and per check, never global: a hook that edits your files
446/// without being asked is a larger surprise than one that complains.
447#[derive(Debug, Clone, Copy, PartialEq, Eq)]
448pub enum Fix {
449 /// Reports only. Every check, until somebody declares otherwise.
450 None,
451 /// Runs a command that rewrites files, and stages what it changed.
452 ///
453 /// Only reachable from a `Stage::PreCommit` declaration. A pre-push hook
454 /// must not modify the worktree or index: the pushed commit would then
455 /// differ from the tree the developer is looking at.
456 Rewrite,
457}
458
459impl Fix {
460 /// How it is written in `--json`. No `parse()`: nothing reads a `Fix`
461 /// back out of text — the manifest's `fix` marker has its own, unrelated
462 /// parsing path in `manifest.rs`.
463 pub fn as_str(self) -> &'static str {
464 match self {
465 Fix::None => "none",
466 Fix::Rewrite => "rewrite",
467 }
468 }
469}
470
471/// One check, whether compiled in or declared by the repository.
472///
473/// `Sync` because `pre-commit` hands every check to its own thread. Both
474/// implementations satisfy it for free, and requiring it here is what lets the
475/// dispatcher hold `&'static dyn Check` without caring which kind it has.
476pub trait Check: Sync {
477 fn name(&self) -> &str;
478 fn stage(&self) -> Stage;
479 fn scope(&self) -> Scope;
480 /// The name a commit-time declaration must use to pair with this gate.
481 ///
482 /// Deliberately the SHORT name, and deliberately not the id: pairing is
483 /// cross-stage by definition — `test` declared at `pre-commit` pairs
484 /// with `test` at `pre-push` — so the id, which encodes the stage, is
485 /// the one key that cannot work. `pre-push-cargo-test` would be compared
486 /// against a `GateDecl.script` of `cargo-test` and never match, and the
487 /// failure would be silence rather than an error: the gate simply never
488 /// pairs and nobody is told why.
489 ///
490 /// This is the single place where comparing short names is correct,
491 /// which is why it is a named method rather than a `short_name()` call
492 /// at the comparison site — that function's own documentation says never
493 /// to compare against it, and it is right everywhere else.
494 fn pairing_name(&self) -> &str {
495 crate::short_name(self.name())
496 }
497 fn severity(&self) -> Severity;
498 /// Whether this check can repair what it finds. `None` for almost all.
499 fn fix(&self) -> Fix {
500 Fix::None
501 }
502 /// How far the check reaches when `greengate.conventions` is `declared` —
503 /// see [`Reach`]. Externals default to `Convention`, which costs them
504 /// nothing: a declared check only exists where an `amont.conf` does,
505 /// and that is exactly the declaration the mode asks for.
506 fn reach(&self) -> Reach {
507 Reach::Convention
508 }
509 /// Whether the check takes a host slot (ADR-0009, ADR-0013). Built-ins
510 /// are Heavy by name; a declared check answers for itself.
511 fn weight(&self) -> crate::host_slots::Weight {
512 crate::host_slots::weight_of(self.name())
513 }
514 /// Would this check judge something for this change, were it run? The
515 /// change touches its scope and the repository opted in: the two
516 /// questions every scoped check asks before it does anything. A Heavy
517 /// check the pre-commit waves hold back is `Skipped` when this says yes
518 /// and `Inert` when it says no (ADR-0020). `tracked: None` (git would not
519 /// list the index) answers yes: a skip is said, never hidden.
520 fn would_judge(&self, staged: &[String], tracked: Option<&[String]>) -> bool {
521 let scope = self.scope();
522 scope.touches(staged) && tracked.map_or(true, |t| scope.opted_in(t))
523 }
524 fn run(&self, ctx: &Ctx) -> Outcome;
525}
526
527/// How far a check reaches into repositories that never asked for it.
528///
529/// With `git config --global greengate.conventions declared`, hooks installed by
530/// a standing grant (`init.templateDir`) split in two: `Safety` checks run in
531/// EVERY repository, because their findings are mistakes in any codebase — a
532/// conflict marker, a leaked credential, a hundred-megabyte blob, a
533/// `debugger;` left in the diff. `Convention` checks run only where the
534/// repository has committed an `amont.conf` — they are one team's house
535/// rules (commit shapes, branch names, lint severities, test gates), and a
536/// clone of somebody else's project did not agree to them.
537///
538/// The default mode is `everywhere`, where this distinction is inert.
539#[derive(Debug, Clone, Copy, PartialEq, Eq)]
540pub enum Reach {
541 /// A mistake anywhere: runs regardless of declaration.
542 Safety,
543 /// A house rule: runs only where the repository declares amont.
544 Convention,
545}
546
547/// A check compiled into the binary.
548pub struct Builtin {
549 pub name: &'static str,
550 pub stage: Stage,
551 pub scope: Scope,
552 pub severity: Severity,
553 pub run: fn(&Ctx) -> Outcome,
554 /// Almost always `Fix::None`; see `CHECKS`.
555 pub fix: Fix,
556 /// Almost always `Convention`; the exceptions are pinned in the registry.
557 pub reach: Reach,
558}
559
560impl Check for Builtin {
561 fn name(&self) -> &str {
562 self.name
563 }
564 fn stage(&self) -> Stage {
565 self.stage
566 }
567 fn scope(&self) -> Scope {
568 self.scope
569 }
570 fn severity(&self) -> Severity {
571 self.severity
572 }
573 fn fix(&self) -> Fix {
574 self.fix
575 }
576 fn reach(&self) -> Reach {
577 self.reach
578 }
579 fn run(&self, ctx: &Ctx) -> Outcome {
580 (self.run)(ctx)
581 }
582}
583
584/// Does `path` fall under a `dir/**/*.ext` token? The prefix is a whole
585/// directory, so `claude-plugin/**/*.md` covers `claude-plugin/a/b.md` and
586/// never `claude-plugin-old/b.md`. Malformed tokens are refused by the
587/// manifest before they reach here; a built-in never writes one.
588pub fn in_dir(token: &str, path: &str) -> bool {
589 let Some((dir, ext)) = token.split_once("/**/*") else {
590 return false;
591 };
592 path.strip_prefix(dir)
593 .and_then(|rest| rest.strip_prefix('/'))
594 .is_some_and(|rest| !rest.is_empty() && path.ends_with(ext))
595}
596
597#[cfg(test)]
598mod tests {
599 use super::*;
600
601 /// Round-trips, and refuses everything else. A `Some` for an unknown value
602 /// would turn a typo into a silent disable.
603 #[test]
604 fn severity_parses_exactly_the_two_words_it_documents() {
605 for s in [Severity::Block, Severity::Warn] {
606 assert_eq!(Severity::parse(s.as_str()), Some(s));
607 }
608 for bad in ["", "Warn", "WARN", "advisory", "true", "1", " warn"] {
609 assert_eq!(Severity::parse(bad), None, "{bad:?} must not parse");
610 }
611 }
612
613 #[test]
614 fn fix_says_how_it_is_written_in_json() {
615 assert_eq!(Fix::None.as_str(), "none");
616 assert_eq!(Fix::Rewrite.as_str(), "rewrite");
617 }
618
619 #[test]
620 fn always_matches_anything() {
621 assert!(Scope::ALWAYS.matches(&[]));
622 assert!(Scope::ALWAYS.matches(&["README.md".into()]));
623 }
624
625 #[test]
626 fn extensions_gate_on_the_file_type() {
627 let s = Scope::files(&[".rs"]);
628 assert!(s.matches(&["src/main.rs".into()]));
629 assert!(!s.matches(&["README.md".into()]));
630 }
631
632 /// The case the enum could not express: BOTH conditions must hold.
633 #[test]
634 fn files_and_opt_in_are_a_conjunction() {
635 let ruff = Scope::new(&[".py"], &["ruff.toml", "pyproject.toml"]);
636 assert!(
637 !ruff.matches(&["a.py".into()]),
638 "python alone is not enough — the repo must opt in"
639 );
640 assert!(
641 !ruff.matches(&["pyproject.toml".into()]),
642 "and a config alone is not enough without python"
643 );
644 assert!(ruff.matches(&["a.py".into(), "pyproject.toml".into()]));
645 }
646
647 /// `.kube-linter*.yaml` is a real config name in this repo's own hooks.
648 #[test]
649 fn a_trailing_star_is_a_prefix_match() {
650 let s = Scope::new(&[".yaml"], &[".kube-linter*.yaml"]);
651 assert!(s.matches(&["k8s/x.yaml".into(), ".kube-linter-prod.yaml".into()]));
652 assert!(!s.matches(&["k8s/x.yaml".into(), ".kube-lint.yaml".into()]));
653 }
654
655 /// Opt-in matches a BASENAME anywhere, which is what makes the coarse
656 /// answer right for a check that resolves an ancestor when it runs.
657 #[test]
658 fn opt_in_matches_a_nested_manifest() {
659 let cargo = Scope::new(&[".rs"], &["Cargo.toml"]);
660 assert!(cargo.matches(&["crates/a/src/lib.rs".into(), "crates/a/Cargo.toml".into()]));
661 }
662
663 #[test]
664 fn a_directory_token_covers_its_subtree_and_not_a_lookalike() {
665 let s = Scope {
666 files: &[],
667 names: &[],
668 dirs: &["claude-plugin/**/*.md"],
669 opt_in: &[],
670 not_during: &[],
671 };
672 assert!(!s.is_unscoped());
673 assert!(s.covers("claude-plugin/SKILL.md"));
674 assert!(s.covers("claude-plugin/skills/x/SKILL.md"));
675 assert!(!s.covers("claude-plugin-old/SKILL.md"));
676 assert!(!s.covers("claude-plugin/SKILL.rs"));
677 assert!(!s.covers("docs/claude-plugin/x.md"));
678 }
679
680 /// The scope a declaration fires on once its push twin's files count:
681 /// the patterns of both, the declaration's own opt-in, nothing leaked
682 /// when the twin adds nothing.
683 #[test]
684 fn a_union_fires_where_either_scope_would() {
685 let own = Scope::files(&[".rs"]);
686 let twin = Scope::new(&[".rs", "Cargo.toml", "Cargo.lock"], &["Cargo.toml"]);
687 let widened_scope = own.union(&twin);
688 assert!(
689 widened_scope.covers("src/a.rs")
690 && widened_scope.covers("Cargo.lock")
691 && widened_scope.covers("crates/a/Cargo.toml")
692 );
693 assert!(!widened_scope.covers("README.md"));
694 assert!(
695 widened_scope.opt_in.is_empty(),
696 "the declaration keeps its own opt-in"
697 );
698 let same = own.union(&Scope::files(&[".rs"]));
699 assert!(
700 std::ptr::eq(same.files, own.files),
701 "nothing added, nothing leaked"
702 );
703 assert_eq!(same, own);
704 }
705
706 /// An unscoped declaration already fires on everything: merging the
707 /// twin's patterns into it would narrow it.
708 #[test]
709 fn an_unscoped_scope_is_never_narrowed_by_a_union() {
710 let widened_scope = Scope::ALWAYS.union(&Scope::files(&[".rs"]));
711 assert!(widened_scope.is_unscoped() && widened_scope.touches(&["README.md".into()]));
712 }
713}