greengate_runtime/hooks/run_tests.rs
1//! pre-push-run-tests-js — run each touched JS package's gate before pushing.
2//!
3//! git feeds pre-push one line per ref on stdin. That list is parsed ONCE by
4//! the dispatcher (see `pushrefs`) and lent here, because stdin can only be
5//! consumed once and more than one check needs it:
6//! <local ref> <local oid> <remote ref> <remote oid>
7//! An all-zero local oid is a deletion; an all-zero remote oid means the branch
8//! is new, so everything it carries is in range.
9
10use super::common::program;
11use crate::check::Outcome;
12use crate::git;
13use std::process::{Command, Stdio};
14
15/// Whichever of these the package defines, cheapest first, stopping at the
16/// first failure — a type error costs seconds, not a full suite.
17///
18/// `lint` is deliberately absent: pre-commit-lint-js already lints staged files
19/// with the repo's pinned eslint, so repeating it here costs time and catches
20/// nothing new.
21///
22/// That argument is not special to `lint`. Any entry here can be moved earlier
23/// by a repository — see [`gated_at_commit`] — and once it runs on every commit,
24/// running it again on push is the same pure repetition. `typecheck` is the one
25/// people move: push is too late to hear about a type error you introduced an
26/// hour ago.
27const GATE: [&str; 3] = ["typecheck", "test:unit", "test"];
28
29/// GATE entries this repository already runs at COMMIT time, and so must not
30/// run again here.
31///
32/// A repository moves one earlier by declaring it in `amont.conf` under the
33/// name of the script:
34///
35/// ```text
36/// pre-commit typecheck *.ts,*.tsx block npm run typecheck
37/// ```
38///
39/// The name is the contract, deliberately — matching on the command would have
40/// to guess at `npm` vs `pnpm` vs `yarn`, at `--silent`, at a wrapper script,
41/// and would answer "no" to things that plainly are the same check.
42///
43/// **Only a declaration that would actually run, and actually block, counts**:
44///
45/// * `Kind::Runnable` excludes an unusable line and — through
46/// [`crate::manifest::gate`] — an UNTRUSTED manifest. A repository could
47/// otherwise declare `pre-commit typecheck`, never be trusted, and silently
48/// have types checked at neither end.
49/// * `hook.skip` is honoured for the same reason, one layer up: a declaration
50/// the author has switched off is not a check.
51/// * The EFFECTIVE severity must be `block`, overrides included. A `warn`
52/// declaration lets the commit through on failure, so treating it as
53/// commit-time coverage would replace a blocking push check with a
54/// non-blocking commit one.
55///
56/// The declaration's scope rides along rather than being judged here: whether
57/// it covered a given push depends on which files that push changed, which is
58/// a per-ref question `run` answers with [`crate::check::Scope::covers_all`].
59///
60/// Get any of these wrong and the result is the failure this project is
61/// arranged against — a push that reports a green gate having run nothing.
62/// A declaration passing this filter is still only a PROMISE: whether the
63/// check executed for the commits actually being pushed is what
64/// [`crate::gate_stamp`]'s per-commit stamps answer, in `run`.
65pub(crate) fn gated_at_commit(
66 settings: &crate::config::Settings,
67 declared: &[crate::manifest::External],
68) -> Vec<GateDecl> {
69 let mut decls = blocking_commit_decls(settings, declared);
70 decls.retain(|d| GATE.contains(&d.script.as_str()));
71 decls
72}
73
74/// EVERY blocking commit-time declaration, whatever its name — the general
75/// form [`gated_at_commit`] narrows to the npm GATE vocabulary. This is what
76/// earns stamps and what the bypass ledger counts: a `pre-commit test *.rs
77/// block cargo test` line gates exactly the way `typecheck` always has, and
78/// a same-named pre-push declaration defers to its stamps (see
79/// [`pair_verdict`]). The npm push gate was the first consumer of this
80/// machinery, not its definition.
81pub(crate) fn blocking_commit_decls(
82 settings: &crate::config::Settings,
83 declared: &[crate::manifest::External],
84) -> Vec<GateDecl> {
85 // The fast path: pre-commit calls this on every commit to know what to
86 // stamp, and most repositories declare nothing — no pre-commit
87 // declaration means no git spawns for skips and severity overrides.
88 if gate_names_declared(declared).is_empty() {
89 return Vec::new();
90 }
91 let skips = crate::configured_skips(settings);
92 let severities = crate::registry::Overrides::read(settings);
93 declared
94 .iter()
95 .filter_map(|ext| {
96 let crate::manifest::Kind::Runnable { scope, files, .. } = &ext.kind else {
97 return None;
98 };
99 (ext.stage == crate::check::Stage::PreCommit
100 && severities.of(ext) == crate::check::Severity::Block
101 && !skips.iter().any(|s| crate::skip_suppresses(&ext.id, s)))
102 .then(|| GateDecl {
103 script: ext.short_name.clone(),
104 id: ext.id.clone(),
105 scope: *scope,
106 files: *files,
107 })
108 })
109 .collect()
110}
111
112/// Names this manifest declares at pre-commit, before any config is read —
113/// the zero-spawn question "could this repository have a commit-time gate at
114/// all". [`blocking_commit_decls`] and the bypass ledger's fast path both
115/// start here, from the same predicate, so they cannot drift.
116pub(crate) fn gate_names_declared(declared: &[crate::manifest::External]) -> Vec<String> {
117 declared
118 .iter()
119 .filter(|ext| ext.stage == crate::check::Stage::PreCommit)
120 .map(|ext| ext.short_name.clone())
121 .collect()
122}
123
124/// How a `Gated` push was covered, so its line can say what the skip rests on.
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub(crate) enum Coverage {
127 /// Every pushed commit in the pair's scope carries its stamp.
128 EveryCommit,
129 /// At least one ref had a commit with no stamp, and was covered by its
130 /// TIP alone: these tips' own stamp keys hold the pair token (ADR-0019).
131 /// Short shas, one per such ref.
132 Tips(Vec<String>),
133}
134
135/// What a declared PRE-PUSH external should do about a same-named
136/// commit-time declaration — the general form of the npm gate's stamp
137/// suppression, for names the GATE list never heard of. Declaring `test`
138/// (or `lint`, or anything) at BOTH stages is the contract: the pre-commit
139/// side earns per-commit stamps, and the pre-push side runs only for pushes
140/// carrying commits with no record of it, unless a ref's tip itself passed.
141pub(crate) enum PairVerdict {
142 /// No blocking commit-time pair covers this push — run normally.
143 NotPaired,
144 /// Every judged ref is covered — skip, saying so, and how.
145 Gated(Coverage),
146 /// A pair exists but this many pushed commits carry no record of it —
147 /// run, saying why the declaration's word was not enough.
148 Unstamped(usize),
149 /// No pushed commit is unstamped except this many, whose gate the busy
150 /// policy deferred at commit (ADR-0013): defer the twin to CI as well.
151 /// Never `Gated`, which would attest a suite that ran nowhere.
152 Deferred(usize),
153}
154
155/// Judge a pre-push gate against its commit-time pair, with exactly the npm
156/// gate's rules: the pair must be BLOCKING (a warn check vouches for
157/// nothing), its scope must have seen every file this push changes that the
158/// push-side check would fire on, and every relevant commit must carry its
159/// stamp. Any git refusal reads as "no stamp", which runs the check — the
160/// only safe direction.
161///
162/// Takes the push side as `(name, scope)` rather than an `&External`,
163/// because those two are all it ever used and a BUILT-IN has both. That is
164/// the whole reason built-ins can be paired now: the logic never needed a
165/// declaration, only a name to match and a scope to judge against.
166///
167/// `name` is the SHORT name — `cargo-test`, not `pre-push-cargo-test`. It is
168/// compared against [`GateDecl::script`], which is what the author wrote in
169/// `amont.conf`. Passing an id here matches nothing and silently pairs
170/// nothing; see `Check::pairing_name`.
171pub(crate) fn pair_verdict(
172 settings: &crate::config::Settings,
173 name: &str,
174 push_scope: &crate::check::Scope,
175 manifest: &crate::manifest::Manifest,
176 push: &crate::pushrefs::PushRefs,
177) -> PairVerdict {
178 // Cheap name test before any config read or git spawn: most pre-push
179 // gates have no commit-time namesake.
180 if !manifest
181 .externals
182 .iter()
183 .any(|e| e.stage == crate::check::Stage::PreCommit && e.short_name == name)
184 {
185 return PairVerdict::NotPaired;
186 }
187 let Some(pair) = blocking_commit_decls(settings, &manifest.externals)
188 .into_iter()
189 .find(|d| d.script == name)
190 else {
191 return PairVerdict::NotPaired;
192 };
193 // A declaration this repository has not opted into never ran at commit
194 // time, so it has nothing to vouch with — the push side runs on its own
195 // word. Judged against the REPOSITORY, once, and never against a commit's
196 // changed files: see `repo_opted_in`.
197 if !repo_opted_in(&pair.scope) {
198 return PairVerdict::NotPaired;
199 }
200 // The complete token of the commit-time declaration. Unknown identity (its
201 // program cannot be found) means its stamps vouch for nothing: the push
202 // side runs on its own word, quietly, as if there were no pair.
203 let Some(pair_token) = manifest
204 .externals
205 .iter()
206 .find(|e| e.id == pair.id)
207 .and_then(|e| crate::gate_identity::external_token(e, &pair.script))
208 else {
209 return PairVerdict::NotPaired;
210 };
211 let zero = git::stdout(&["hash-object", "--stdin"])
212 .map(|h| "0".repeat(h.len()))
213 .unwrap_or_else(|| "0".repeat(40));
214 let mut unstamped = 0usize;
215 let mut deferred = 0usize;
216 let mut judged_any = false;
217 // The refs covered by their tip alone, as short shas for the line.
218 let mut tips: Vec<String> = Vec::new();
219 // Under `onBusy defer`, a commit whose gate the busy policy deferred is
220 // not "unstamped": its twin defers too (ADR-0013). `AMONT_ON_BUSY=wait`
221 // turns this off and the twin runs.
222 let defer = matches!(
223 crate::host_slots::busy_policy(settings),
224 crate::host_slots::BusyPolicy::Defer { .. }
225 );
226 for r in push.get() {
227 let changed = crate::pushrefs::changed_files_for(r, &zero);
228 // `covers`, NOT `matches`, and the difference is the whole reason
229 // built-ins can be paired at all.
230 //
231 // `matches` also asks the OPT-IN question — "is there a Cargo.toml
232 // here" — and asking it of a single path can only ever answer no.
233 // `pre-push-cargo-test` opts in on `Cargo.toml`, so every changed
234 // `.rs` file would be judged irrelevant, `judged_any` would stay
235 // false, and the verdict would be `NotPaired` for every push in
236 // every Rust repository. Silently: a gate that never pairs looks
237 // exactly like a gate with no pair declared.
238 //
239 // Opt-in is a fact about the REPOSITORY, settled once by the
240 // dispatcher when it decided this check runs here at all. What this
241 // loop needs is the per-file question, which is `covers`.
242 let relevant: Vec<String> = changed
243 .iter()
244 .filter(|f| push_scope.is_unscoped() || push_scope.covers(f))
245 .cloned()
246 .collect();
247 if relevant.is_empty() {
248 continue; // this ref never fires the push-side check
249 }
250 judged_any = true;
251 if !pair.scope.covers_all(&relevant) {
252 // The pair has not judged everything this push changes — its
253 // word covers nothing here, silently: claiming partial coverage
254 // out loud would read as reassurance.
255 return PairVerdict::NotPaired;
256 }
257 let per_commit = crate::pushrefs::commits_and_files_for(r, &zero);
258 let ids: Vec<String> = per_commit.iter().map(|(c, _)| c.clone()).collect();
259 let stamps = crate::gate_stamp::stamps_for(&ids);
260 // `touches`, NOT `matches`, for the same reason as above and with a
261 // worse consequence. `matches` asks the opt-in question of ONE
262 // COMMIT's changed files: a `*.txt+marker` pair judged a commit that
263 // changed `a.txt` and left `marker` alone as "would never fire", so
264 // the commit was not counted, `unstamped` stayed 0, and the verdict
265 // was `Gated` — the push-side twin skipped on the strength of a
266 // stamp that did not exist. Opt-in was settled for the repository
267 // above; per commit the only question is whether it touched the
268 // scope.
269 let missing: Vec<String> = per_commit
270 .iter()
271 .filter(|(_, files)| pair.scope.touches(files))
272 .filter(|(commit, _)| !stamps.get(commit).is_some_and(|s| s.contains(&pair_token)))
273 .map(|(commit, _)| commit.clone())
274 .collect();
275 // The tip is what ships. When its OWN stamp key — the tree's note, its
276 // declared-input fingerprints, its canonical tree (ADR-0011, ADR-0012),
277 // exactly what `stamps_for` read above — holds the pair token, the
278 // code being pushed passed the commit-time gate, and an older commit
279 // that never earned a stamp (relais's hookless `commit-tree`, a
280 // deferral) changes nothing about it (ADR-0019). A changed declared
281 // input or gate script gives the tip a different key, so it vouches
282 // for nothing and the per-commit count stands.
283 //
284 // Asked only when some commit is missing its stamp: a fully stamped
285 // ref is covered the old way, and its line keeps meaning so.
286 //
287 // Never for a `files` pair: its command saw only that commit's
288 // matched paths, so its stamp says nothing about the rest of the tree.
289 // holds-until: every pair without `files` judges the whole tree. A
290 // command that picks the staged paths itself (`lint-staged`,
291 // `--cached`, `--staged`) and has a pre-push twin breaks that; none
292 // existed in the fleet on 2026-11-06 (docs/custom-checks.md).
293 //
294 // AFTER the coverage guards above, never before: a ref whose changes
295 // the pair's scope does not cover is `NotPaired`, whatever its tip
296 // says.
297 if !missing.is_empty()
298 && !pair.files
299 && stamps
300 .get(&r.local_oid)
301 .is_some_and(|s| s.contains(&pair_token))
302 {
303 tips.push(crate::gate_evidence::short(&r.local_oid).to_string());
304 continue;
305 }
306 let excused = if defer {
307 crate::gate_stamp::deferred_for(&missing, &pair.script)
308 } else {
309 Default::default()
310 };
311 deferred += excused.len();
312 unstamped += missing.len() - excused.len();
313 }
314 if !judged_any {
315 return PairVerdict::NotPaired;
316 }
317 // Never `Gated` when a deferral covers a commit: `Gated` puts the twin
318 // in `passed`, which the signed attestation names, and CI would then skip
319 // a suite that ran nowhere.
320 if unstamped > 0 {
321 PairVerdict::Unstamped(unstamped)
322 } else if deferred > 0 {
323 PairVerdict::Deferred(deferred)
324 } else {
325 PairVerdict::Gated(if tips.is_empty() {
326 Coverage::EveryCommit
327 } else {
328 Coverage::Tips(tips)
329 })
330 }
331}
332
333/// Has this repository opted into `scope`? The index is the only honest
334/// source — the same question `manifest.rs` asks before running the
335/// declaration at commit time, so the stamp check and the run agree on
336/// whether it could have run at all.
337///
338/// `true` when git will not list the files: an unverified answer must not
339/// silently promote a declaration to "never ran" — that direction re-runs
340/// the push-side gate, which is the safe one. `tracked_files` is cached
341/// per process, so the git spawn is paid once however many pairs ask.
342fn repo_opted_in(scope: &crate::check::Scope) -> bool {
343 scope.opt_in.is_empty()
344 || crate::hooks::common::tracked_files().map_or(true, |tracked| scope.opted_in(&tracked))
345}
346
347/// One gate entry a commit-time declaration stands in for.
348pub(crate) struct GateDecl {
349 /// The declared name — a GATE script for the npm push gate, any name
350 /// for a declared pre-commit/pre-push pair.
351 pub script: String,
352 /// `<stage>-<name>` — what dispatch outcomes and `hook.skip` key on.
353 /// Carried so pre-commit can match "this declaration" to "that outcome"
354 /// without re-deriving the id and drifting.
355 pub id: String,
356 /// The declaration's scope, judged per ref by
357 /// [`crate::check::Scope::covers_all`].
358 pub scope: crate::check::Scope,
359 /// The `files` marker: the command is handed only the commit's matched
360 /// paths, so its stamp vouches for that commit's files and never for the
361 /// tree. Such a pair cannot cover a ref by its tip ([`pair_verdict`]).
362 pub files: bool,
363}
364
365/// The extensions this check treats as "JS worth testing". Exported so
366/// `registry.rs` declares the scope from the same constant — see
367/// `lint_json_yaml::EXTS` for the drift this prevents.
368pub const JS_EXTS: &[&str] = &[".js", ".jsx", ".ts", ".tsx", ".vue"];
369
370fn is_js(file: &str) -> bool {
371 JS_EXTS.iter().any(|e| file.ends_with(e))
372}
373
374fn parent_of(path: &str) -> &str {
375 match path.rfind('/') {
376 Some(i) => &path[..i],
377 None => "",
378 }
379}
380
381/// Does `package.json` define `script` under "scripts"?
382///
383/// A brace-matched scan rather than a JSON parser: the only question is whether
384/// one key exists in one object, and a dependency-free binary is the point of
385/// this migration. Restricted to the TOP-LEVEL "scripts" object so a
386/// same-named key elsewhere (a dependency called `test`, say) cannot answer
387/// for it.
388pub fn defines_script(pkg_json: &str, script: &str) -> bool {
389 let Some(body) = scripts_object(pkg_json) else {
390 return false;
391 };
392 let needle = format!("\"{script}\"");
393 let mut from = 0;
394 while let Some(i) = body[from..].find(&needle) {
395 let at = from + i;
396 let after = &body[at + needle.len()..];
397 if after.trim_start().starts_with(':') {
398 return true;
399 }
400 from = at + needle.len();
401 }
402 false
403}
404
405/// The text of the top-level `"scripts"` object, braces included.
406///
407/// A depth-tracking scan, not `find("\"scripts\"")`: anchoring on the FIRST
408/// occurrence of the substring anywhere meant `{"files":["scripts"],…}`
409/// handed the brace-matcher whichever object came next — so a dependency
410/// named `test` answered as a script while the real scripts object was never
411/// read, which is exactly the false positive `defines_script`'s doc promises
412/// away. A string only counts as a key when it sits at depth 1 (inside the
413/// document object, outside any array) AND its next non-space byte is `:` —
414/// `{"name": "scripts"}` is a value, not the key.
415fn scripts_object(pkg_json: &str) -> Option<&str> {
416 let bytes = pkg_json.as_bytes();
417 let mut depth = 0usize;
418 let mut i = 0usize;
419 while i < bytes.len() {
420 match bytes[i] {
421 b'"' => {
422 let start = i + 1;
423 let close = string_end(bytes, start)?;
424 let content = &pkg_json[start..close];
425 i = close + 1;
426 if depth != 1 {
427 continue;
428 }
429 let mut j = i;
430 while j < bytes.len() && bytes[j].is_ascii_whitespace() {
431 j += 1;
432 }
433 if j >= bytes.len() || bytes[j] != b':' {
434 continue; // a value, not a key
435 }
436 if content != "scripts" {
437 continue;
438 }
439 let mut k = j + 1;
440 while k < bytes.len() && bytes[k].is_ascii_whitespace() {
441 k += 1;
442 }
443 // The one top-level "scripts" key exists but is not an
444 // object: there are no scripts, and no later impostor may
445 // answer instead.
446 if k >= bytes.len() || bytes[k] != b'{' {
447 return None;
448 }
449 let end = object_end(bytes, k)?;
450 return Some(&pkg_json[k..=end]);
451 }
452 b'{' | b'[' => {
453 depth += 1;
454 i += 1;
455 }
456 b'}' | b']' => {
457 depth = depth.saturating_sub(1);
458 i += 1;
459 }
460 _ => i += 1,
461 }
462 }
463 None
464}
465
466/// Index of the closing quote of the string whose content starts at `from`.
467fn string_end(bytes: &[u8], from: usize) -> Option<usize> {
468 let mut escaped = false;
469 for (i, &c) in bytes.iter().enumerate().skip(from) {
470 if escaped {
471 escaped = false;
472 } else if c == b'\\' {
473 escaped = true;
474 } else if c == b'"' {
475 return Some(i);
476 }
477 }
478 None
479}
480
481/// Index of the `}` matching the `{` at `open`, string-aware.
482fn object_end(bytes: &[u8], open: usize) -> Option<usize> {
483 let mut depth = 0usize;
484 let mut i = open;
485 while i < bytes.len() {
486 match bytes[i] {
487 b'"' => i = string_end(bytes, i + 1)?,
488 b'{' => depth += 1,
489 b'}' => {
490 depth -= 1;
491 if depth == 0 {
492 return Some(i);
493 }
494 }
495 _ => {}
496 }
497 i += 1;
498 }
499 None
500}
501
502/// Tracked `package.json` paths, as directories relative to the repo root.
503///
504/// `git ls-files` instead of the shell version's `fd package.json`: it drops
505/// the `fd` dependency (undeclared, and one of two binaries the hooks silently
506/// required), and it is the more correct set anyway — only TRACKED packages can
507/// be part of a push, and node_modules is excluded by construction rather than
508/// by fd happening to honour .gitignore.
509pub fn package_dirs(ls_files: &[String]) -> Vec<String> {
510 let mut dirs: Vec<String> = ls_files
511 .iter()
512 .map(String::as_str)
513 .filter(|f| *f == "package.json" || f.ends_with("/package.json"))
514 .map(|f| parent_of(f).to_string())
515 .collect();
516 dirs.sort();
517 dirs.dedup();
518 dirs
519}
520
521/// Packages that actually contain one of the changed files.
522///
523/// `.iter().any()`, not the shell version's original `.filter()` — an empty
524/// array is truthy in JS, so that selected EVERY package regardless of what
525/// changed. Invisible in a single-package repo, quadratic noise in a monorepo.
526pub fn packages_to_test(pkg_dirs: &[String], changed_dirs: &[String]) -> Vec<String> {
527 pkg_dirs
528 .iter()
529 .filter(|pkg| {
530 changed_dirs.iter().any(|dir| {
531 if pkg.is_empty() {
532 true
533 } else {
534 dir == *pkg || dir.starts_with(&format!("{pkg}/"))
535 }
536 })
537 })
538 .cloned()
539 .collect()
540}
541
542/// The GATE, minus what a `pre-commit` declaration already covers.
543///
544/// Split from `run_gate` so the rule can be tested without a package on disk
545/// and without spawning npm — `run_gate` reaches for both.
546pub fn gate_for(pkg_json: &str, already: &[&str]) -> Vec<&'static str> {
547 GATE.iter()
548 .copied()
549 .filter(|s| defines_script(pkg_json, s) && !already.contains(s))
550 .collect()
551}
552
553/// True when the gate passed (or there was none to run).
554fn run_gate(
555 settings: &crate::config::Settings,
556 root: &str,
557 folder: &str,
558 already: &[&str],
559) -> bool {
560 let dir = if folder.is_empty() {
561 root.to_string()
562 } else {
563 format!("{root}/{folder}")
564 };
565 let Ok(pkg) = std::fs::read_to_string(format!("{dir}/package.json")) else {
566 return true;
567 };
568 for script in gate_for(&pkg, already) {
569 // Same hazard as cargo test: git exports GIT_DIR to hooks, and a JS
570 // test that shells out to git would then operate on this repo rather
571 // than its own fixture.
572 let mut cmd = Command::new(program("npm"));
573 cmd.args(["run", script])
574 .current_dir(&dir)
575 .stdin(Stdio::null());
576 super::common::strip_git_env(&mut cmd);
577 match super::common::status_streamed(settings, &mut cmd, super::common::Retry::Once) {
578 Ok(super::common::Ran::Status(status)) if status.success() => {}
579 Ok(super::common::Ran::TimedOut(budget)) => {
580 super::common::say_timed_out(script, budget);
581 return false;
582 }
583 // The gate's own exit code is not propagated: git only
584 // distinguishes zero from non-zero, and npm's codes said nothing
585 // the message above has not already said.
586 Ok(_) | Err(_) => return false,
587 }
588 }
589 true
590}
591
592pub fn run(
593 settings: &crate::config::Settings,
594 refs: &[crate::pushrefs::PushRef],
595 declared: &[crate::manifest::External],
596 gate: &str,
597) -> Outcome {
598 // An all-zero oid, of whatever length this repo's hash is (sha1 or sha256).
599 let zero = git::stdout(&["hash-object", "--stdin"])
600 .map(|h| "0".repeat(h.len()))
601 .unwrap_or_else(|| "0".repeat(40));
602
603 // `Unavailable`, never `Passed`, when git itself will not answer: a push
604 // gate that reports green having asked nothing is the exact conflation
605 // `Outcome::Unavailable` exists to prevent (see its doc in check.rs), and
606 // the same split `install::repo_hooks` was rewritten for. The dispatcher
607 // says "could not run" and does not block — loud, and honest.
608 let Some(root) = git::stdout(&["rev-parse", "--show-toplevel"]) else {
609 super::common::warn("run-tests-js: git would not answer — the gate did NOT run");
610 return Outcome::Unavailable;
611 };
612 let Some(tracked) = git::stdout_paths(&["ls-files"]) else {
613 super::common::warn("run-tests-js: git would not answer — the gate did NOT run");
614 return Outcome::Unavailable;
615 };
616 let pkg_dirs = package_dirs(&tracked);
617
618 // The DECLARATIONS are a property of the repository, resolved once; whether
619 // one covers a given push is a property of that ref's changed files and of
620 // its commits' stamps, judged inside the loop.
621 let declared_gate = gated_at_commit(settings, declared);
622 let mut announced: Vec<String> = Vec::new();
623 let mut warned: Vec<String> = Vec::new();
624
625 for r in refs {
626 let local_oid = r.local_oid.as_str();
627 if local_oid == zero {
628 continue; // deleting a ref pushes no code
629 }
630 // `pushrefs::changed_files_for` exists for exactly this question, and
631 // this check used to recompute it inline with all three bugs that
632 // function's doc comment records fixing:
633 //
634 // - a brand-new branch (`remote_oid == zero`) diffed only its TIP,
635 // so on a multi-commit push an earlier commit's `.ts` change was
636 // invisible and the suite never ran;
637 // - a two-dot range handed to `diff-tree` is a two-TREE compare, not
638 // a commit walk, so a file changed and reverted later in the same
639 // push netted to nothing;
640 // - merge commits show NOTHING without `-m`, so a file touched only
641 // to resolve a conflict selected no package.
642 //
643 // Every one of those let a push proceed GREEN with the suite never
644 // having run. `rust_tools::test` was already the model.
645 let changed = crate::pushrefs::changed_files_for(r, &zero);
646 let js_changed: Vec<String> = changed.iter().filter(|f| is_js(f)).cloned().collect();
647 let changed_dirs: Vec<String> = js_changed
648 .iter()
649 .map(|f| parent_of(f).to_string())
650 .collect();
651 if changed_dirs.is_empty() {
652 continue;
653 }
654
655 // A declaration only stands in for this push if its scope saw every JS
656 // file the push changes — and only for the ROOT package, because that
657 // is where the declared command runs. A sub-package's gate is a
658 // different command in a different directory, and no root declaration
659 // has judged it.
660 //
661 // And the declaration must have EXECUTED, which is the stamps'
662 // question: every commit in this push the declaration would have
663 // fired on must carry a `gate_stamp` note naming the script. A commit
664 // made with `--no-verify`, from a client that runs no hooks, on a
665 // machine without amont, or with a rewritten hash has no stamp — and
666 // an unstamped commit is one the check never judged, so the gate runs
667 // rather than trusting the declaration's word for it.
668 //
669 // And the REPOSITORY must have opted into it — judged against the
670 // index, not per commit: see `pair_verdict` for the skipped-gate bug
671 // that asking it of a commit's changed files produced.
672 let candidates: Vec<&GateDecl> = declared_gate
673 .iter()
674 .filter(|d| d.scope.covers_all(&js_changed) && repo_opted_in(&d.scope))
675 .collect();
676 let mut already: Vec<String> = Vec::new();
677 if !candidates.is_empty() {
678 let per_commit = crate::pushrefs::commits_and_files_for(r, &zero);
679 let ids: Vec<String> = per_commit.iter().map(|(c, _)| c.clone()).collect();
680 let stamps = crate::gate_stamp::stamps_for(&ids);
681 for d in candidates {
682 // Complete token or no vouching: a declaration whose program
683 // cannot be identified has every commit counted unstamped.
684 let token = declared
685 .iter()
686 .find(|e| e.id == d.id)
687 .and_then(|e| crate::gate_identity::external_token(e, &d.script));
688 let unstamped = per_commit
689 .iter()
690 .filter(|(_, files)| d.scope.touches(files))
691 .filter(|(commit, _)| {
692 !token
693 .as_ref()
694 .is_some_and(|t| stamps.get(commit).is_some_and(|s| s.contains(t)))
695 })
696 .count();
697 if unstamped == 0 {
698 already.push(d.script.clone());
699 } else if !warned.contains(&d.script) {
700 crate::say!(
701 "{} {} is declared at commit time, but {unstamped} pushed \
702 commit{} carr{} no record of it — running it here",
703 crate::ui::warning_sign(),
704 d.script,
705 if unstamped == 1 { "" } else { "s" },
706 if unstamped == 1 { "ies" } else { "y" },
707 );
708 warned.push(d.script.clone());
709 }
710 }
711 }
712
713 // Same question as cargo-test: the suite should be answering about
714 // the commits being pushed, not about whatever is open in the
715 // editor — and about THIS ref's commits, not some other ref in the
716 // same push. A single worktree shared across every ref would run a
717 // second ref's tests against a first ref's tree.
718 let (run_in, _guard) = crate::pushed_tree::where_to_run(settings, local_oid, &root, gate);
719 let where_ = run_in.to_string_lossy().into_owned();
720 let folders = packages_to_test(&pkg_dirs, &changed_dirs);
721
722 // Said out loud, and not folded into the pass line. A check that stops
723 // running is exactly what this project refuses to let happen quietly —
724 // the reader has to be able to see that `typecheck` moved rather than
725 // discover later that nothing ran it. Announced only when the skip is
726 // actually applied to this ref: claiming suppression that severity,
727 // scope or a missing root package disqualified would be the same lie
728 // in the other direction.
729 if folders.iter().any(|f| f.is_empty()) {
730 let newly: Vec<String> = already
731 .iter()
732 .filter(|s| !announced.contains(s))
733 .cloned()
734 .collect();
735 if !newly.is_empty() {
736 crate::hooks::common::ok(
737 settings,
738 &format!(
739 "{} gated at commit instead — not repeating {} here",
740 newly.join(", "),
741 if newly.len() == 1 { "it" } else { "them" },
742 ),
743 );
744 announced.extend(newly);
745 }
746 }
747
748 let already_strs: Vec<&str> = already.iter().map(String::as_str).collect();
749 for folder in folders {
750 // Root only: the declared command runs at the repo root.
751 let already_here: &[&str] = if folder.is_empty() {
752 &already_strs
753 } else {
754 &[]
755 };
756 if !run_gate(settings, &where_, &folder, already_here) {
757 return Outcome::Failed;
758 }
759 }
760 }
761 Outcome::Passed
762}
763
764#[cfg(test)]
765mod tests {
766 use super::*;
767
768 /// The filter itself, without a package on disk or an npm to spawn.
769 ///
770 /// Order is part of the contract and is asserted: GATE is cheapest-first so
771 /// a type error costs seconds rather than a full suite, and removing an
772 /// entry must not disturb what is left.
773 #[test]
774 fn the_gate_drops_only_what_commit_already_covers() {
775 let pkg = r#"{"scripts":{"typecheck":"tsc","test":"vitest run"}}"#;
776 assert_eq!(gate_for(pkg, &[]), vec!["typecheck", "test"]);
777 assert_eq!(gate_for(pkg, &["typecheck"]), vec!["test"]);
778 assert_eq!(gate_for(pkg, &["test"]), vec!["typecheck"]);
779 assert!(gate_for(pkg, &["typecheck", "test"]).is_empty());
780 // A name the package does not define is not a script to skip, and
781 // naming one must not disturb the rest.
782 assert_eq!(gate_for(pkg, &["test:unit"]), vec!["typecheck", "test"]);
783 }
784
785 /// Coverage is all-match: one changed file outside the declaration's scope
786 /// means commits this push carries were never judged by it.
787 #[test]
788 fn a_scope_covers_only_when_every_changed_file_matches() {
789 use crate::check::Scope;
790 const TS_ONLY: Scope = Scope::files(&[".ts", ".tsx"]);
791 let all_ts: Vec<String> = vec!["src/a.ts".into(), "src/b.tsx".into()];
792 let mixed: Vec<String> = vec!["src/a.ts".into(), "src/legacy.js".into()];
793 let js_only: Vec<String> = vec!["src/legacy.js".into()];
794 assert!(TS_ONLY.covers_all(&all_ts));
795 assert!(!TS_ONLY.covers_all(&mixed));
796 assert!(!TS_ONLY.covers_all(&js_only));
797 // An empty scope is `*` — it saw everything.
798 assert!(Scope::ALWAYS.covers_all(&mixed));
799 // Nothing relevant changed: nothing was missed.
800 assert!(TS_ONLY.covers_all(&[]));
801
802 // A bare-filename scope covers by BASENAME, never by suffix.
803 const BY_NAME: Scope = Scope {
804 files: &[],
805 names: &["package.json"],
806 dirs: &[],
807 opt_in: &[],
808 not_during: &[],
809 };
810 assert!(BY_NAME.covers_all(&["apps/web/package.json".into()]));
811 assert!(!BY_NAME.covers_all(&["not-package.json".into()]));
812 }
813
814 #[test]
815 fn finds_scripts_only_inside_the_scripts_object() {
816 let pkg = r#"{"name":"x","scripts":{"test":"vitest","typecheck":"tsc"},"devDependencies":{"lint":"1"}}"#;
817 assert!(defines_script(pkg, "test"));
818 assert!(defines_script(pkg, "typecheck"));
819 assert!(!defines_script(pkg, "test:unit"));
820 // present, but as a DEPENDENCY — must not answer for the scripts object
821 assert!(!defines_script(pkg, "lint"));
822 }
823
824 #[test]
825 fn survives_nested_objects_and_escaped_quotes() {
826 let pkg = r#"{"scripts":{"test":"echo \"hi\"","build":"x"},"other":{"test":"no"}}"#;
827 assert!(defines_script(pkg, "test"));
828 assert!(defines_script(pkg, "build"));
829 assert!(!defines_script(pkg, "other"));
830 }
831
832 #[test]
833 fn no_scripts_object_means_no_scripts() {
834 assert!(!defines_script(r#"{"name":"x"}"#, "test"));
835 }
836
837 /// The misanchor this scan replaced: `find("\"scripts\"")` hit the string
838 /// inside the `files` ARRAY, brace-matched the dependencies object that
839 /// followed, and a dependency named `test` answered as a script — while
840 /// the real scripts object was never read.
841 #[test]
842 fn a_scripts_string_elsewhere_cannot_anchor_the_scan() {
843 let pkg = r#"{"files":["scripts"],"dependencies":{"test":"1.0"},"scripts":{"build":"x"}}"#;
844 assert!(
845 !defines_script(pkg, "test"),
846 "a dependency answered as a script"
847 );
848 assert!(
849 defines_script(pkg, "build"),
850 "the real scripts object was skipped"
851 );
852
853 // The same shape via a string VALUE rather than an array element.
854 let pkg =
855 r#"{"description":"scripts","dependencies":{"test":"1.0"},"scripts":{"build":"x"}}"#;
856 assert!(!defines_script(pkg, "test"));
857 assert!(defines_script(pkg, "build"));
858
859 // A NESTED "scripts" key (inside another object) is not the top-level
860 // one.
861 let pkg = r#"{"config":{"scripts":{"test":"inner"}},"scripts":{"build":"x"}}"#;
862 assert!(!defines_script(pkg, "test"));
863 assert!(defines_script(pkg, "build"));
864 }
865
866 /// `"scripts"` as a top-level key whose value is not an object defines
867 /// nothing — and no later impostor may answer instead.
868 #[test]
869 fn a_non_object_scripts_value_defines_nothing() {
870 assert!(!defines_script(r#"{"scripts":"echo hi"}"#, "test"));
871 assert!(!defines_script(
872 r#"{"scripts":"x","other":{"test":"y"}}"#,
873 "test"
874 ));
875 }
876
877 #[test]
878 fn collects_package_directories() {
879 let ls: Vec<String> = [
880 "package.json",
881 "apps/web/package.json",
882 "apps/web/src/a.ts",
883 "README.md",
884 ]
885 .into_iter()
886 .map(String::from)
887 .collect();
888 assert_eq!(
889 package_dirs(&ls),
890 vec!["".to_string(), "apps/web".to_string()]
891 );
892 }
893
894 /// The JS bug: `.filter()` returns an array, `[]` is truthy, so every
895 /// package was selected whatever changed.
896 #[test]
897 fn selects_only_packages_containing_a_change() {
898 let pkgs = vec!["apps/web".to_string(), "apps/api".to_string()];
899 let changed = vec!["apps/web/src".to_string()];
900 assert_eq!(
901 packages_to_test(&pkgs, &changed),
902 vec!["apps/web".to_string()]
903 );
904 }
905
906 #[test]
907 fn the_repo_root_package_matches_any_change() {
908 let pkgs = vec!["".to_string()];
909 assert_eq!(
910 packages_to_test(&pkgs, &["src".to_string()]),
911 vec!["".to_string()]
912 );
913 }
914}