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 super::json_scan::{string_end, top_level_value};
12use crate::check::Outcome;
13use crate::git;
14use crate::manifest::ROOT_RUNS_KEY;
15use std::io::IsTerminal;
16use std::process::{Command, Stdio};
17
18/// Whichever of these the package defines, cheapest first, stopping at the
19/// first failure — a type error costs seconds, not a full suite.
20///
21/// `lint` is deliberately absent: pre-commit-lint-js already lints staged files
22/// with the repo's pinned eslint, so repeating it here costs time and catches
23/// nothing new.
24///
25/// That argument is not special to `lint`. Any entry here can be moved earlier
26/// by a repository — see [`gated_at_commit`] — and once it runs on every commit,
27/// running it again on push is the same pure repetition. `typecheck` is the one
28/// people move: push is too late to hear about a type error you introduced an
29/// hour ago.
30const GATE: [&str; 3] = crate::manifest::NPM_GATE_SCRIPTS;
31
32/// Whether `name` is one of the scripts the npm push gate runs ([`GATE`]).
33pub(crate) fn is_gate_script(name: &str) -> bool {
34 GATE.contains(&name)
35}
36
37/// GATE entries this repository already runs at COMMIT time, and so must not
38/// run again here.
39///
40/// A repository moves one earlier by declaring it in `amont.conf` under the
41/// name of the script:
42///
43/// ```text
44/// pre-commit typecheck *.ts,*.tsx block npm run typecheck
45/// ```
46///
47/// The name is the contract, deliberately — matching on the command would have
48/// to guess at `npm` vs `pnpm` vs `yarn`, at `--silent`, at a wrapper script,
49/// and would answer "no" to things that plainly are the same check.
50///
51/// **Only a declaration that would actually run, and actually block, counts**:
52///
53/// * `Kind::Runnable` excludes an unusable line and — through
54/// [`crate::manifest::gate`] — an UNTRUSTED manifest. A repository could
55/// otherwise declare `pre-commit typecheck`, never be trusted, and silently
56/// have types checked at neither end.
57/// * `hook.skip` is honoured for the same reason, one layer up: a declaration
58/// the author has switched off is not a check.
59/// * The EFFECTIVE severity must be `block`, overrides included. A `warn`
60/// declaration lets the commit through on failure, so treating it as
61/// commit-time coverage would replace a blocking push check with a
62/// non-blocking commit one.
63///
64/// The declaration's scope rides along rather than being judged here: whether
65/// it covered a given push depends on which files that push changed, which is
66/// a per-ref question `run` answers with [`crate::check::Scope::covers_all`].
67///
68/// Get any of these wrong and the result is the failure this project is
69/// arranged against — a push that reports a green gate having run nothing.
70/// A declaration passing this filter is still only a PROMISE: whether the
71/// check executed for the commits actually being pushed is what
72/// [`crate::gate_stamp`]'s per-commit stamps answer, in `run`.
73pub(crate) fn gated_at_commit(
74 settings: &crate::config::Settings,
75 declared: &[crate::manifest::External],
76) -> Vec<GateDecl> {
77 let mut decls = blocking_commit_decls(settings, declared);
78 decls.retain(|d| GATE.contains(&d.script.as_str()));
79 decls
80}
81
82/// EVERY blocking commit-time declaration, whatever its name — the general
83/// form [`gated_at_commit`] narrows to the npm GATE vocabulary. This is what
84/// earns stamps and what the bypass ledger counts: a `pre-commit test *.rs
85/// block cargo test` line gates exactly the way `typecheck` always has, and
86/// a same-named pre-push declaration defers to its stamps (see
87/// [`pair_verdict`]). The npm push gate was the first consumer of this
88/// machinery, not its definition.
89pub(crate) fn blocking_commit_decls(
90 settings: &crate::config::Settings,
91 declared: &[crate::manifest::External],
92) -> Vec<GateDecl> {
93 // The fast path: pre-commit calls this on every commit to know what to
94 // stamp, and most repositories declare nothing — no pre-commit
95 // declaration means no git spawns for skips and severity overrides.
96 if gate_names_declared(declared).is_empty() {
97 return Vec::new();
98 }
99 let skips = crate::configured_skips(settings);
100 let severities = crate::registry::Overrides::read(settings);
101 declared
102 .iter()
103 .filter_map(|ext| {
104 let crate::manifest::Kind::Runnable { files, .. } = &ext.kind else {
105 return None;
106 };
107 ext.blocks_at_commit(&severities, &skips).then(|| GateDecl {
108 script: ext.short_name.clone(),
109 id: ext.id.clone(),
110 lineno: ext.lineno,
111 // What it fires on and is judged on: the resolved trigger
112 // (its own scope united with its push twin's), else its own.
113 scope: ext.effective_scope(),
114 files: *files,
115 })
116 })
117 .collect()
118}
119
120/// Names this manifest declares at pre-commit, before any config is read —
121/// the zero-spawn question "could this repository have a commit-time gate at
122/// all". [`blocking_commit_decls`] and the bypass ledger's fast path both
123/// start here, from the same predicate, so they cannot drift.
124pub(crate) fn gate_names_declared(declared: &[crate::manifest::External]) -> Vec<String> {
125 declared
126 .iter()
127 .filter(|ext| ext.stage == crate::check::Stage::PreCommit)
128 .map(|ext| ext.short_name.clone())
129 .collect()
130}
131
132/// How a `Gated` push was covered, so its line can say what the skip rests on.
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub(crate) enum Coverage {
135 /// Every pushed commit in the pair's scope carries its stamp.
136 EveryCommit,
137 /// At least one ref had a commit with no stamp, and was covered by its
138 /// TIP alone: these tips' own stamp keys hold the pair token (ADR-0019).
139 /// Short shas, one per such ref.
140 Tips(Vec<String>),
141}
142
143/// Why a same-named commit-time declaration did not vouch for a push. Each of
144/// these used to be a silent `NotPaired`, and a silent rerun of the whole suite
145/// is how a land held for two hours (2026-11-10).
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub(crate) enum WhyNot {
148 /// Its scope does not cover these pushed files.
149 ScopeGap {
150 /// What the declaration covers, as written (`*.rs`).
151 scope: String,
152 uncovered: Vec<String>,
153 cause: GapCause,
154 /// The 1-based `amont.conf` line to edit, when it is known.
155 at: Option<usize>,
156 },
157 /// It is a warn check, which vouches for nothing.
158 Warn,
159 /// `hook.skip` switches it off here.
160 Skipped,
161 /// The repository lacks the marker that turns it on.
162 NotOptedIn(Vec<String>),
163 /// Its program was not found, so its stamps vouch for nothing.
164 Unidentified,
165}
166
167/// What left a declaration narrower than the files its push twin acts on.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub(crate) enum GapCause {
170 /// A `files` declaration is handed the matched paths, so it is never
171 /// widened.
172 Files,
173 /// The twin acts on every change, which widening would not follow.
174 UnscopedTwin,
175 /// Nothing explains it: the trigger was not resolved (a missed
176 /// `resolve_triggers` call), which is a bug here and not in the repository.
177 Unresolved,
178}
179
180/// The reason a declaration did not vouch because the repository lacks its
181/// opt-in marker.
182fn not_opted_in(scope: &crate::check::Scope) -> WhyNot {
183 WhyNot::NotOptedIn(scope.opt_in.iter().map(|m| m.to_string()).collect())
184}
185
186/// The reason a declaration did not vouch because its scope misses some of the
187/// files `relevant` to its push twin. One derivation for every gate that pairs
188/// (`pair_verdict` and the npm push gate), so the same gap gets the same
189/// words on both paths. `twin_line` is the `amont.conf` line of a DECLARED
190/// push twin that acts on every change, the line to scope.
191fn scope_gap(
192 pair: &GateDecl,
193 push_scope: &crate::check::Scope,
194 relevant: &[String],
195 twin_line: Option<usize>,
196) -> WhyNot {
197 let (cause, at) = if pair.files {
198 (GapCause::Files, pair.lineno)
199 } else if push_scope.is_unscoped() {
200 (GapCause::UnscopedTwin, twin_line)
201 } else {
202 (GapCause::Unresolved, pair.lineno)
203 };
204 WhyNot::ScopeGap {
205 scope: scope_label(&pair.scope),
206 uncovered: relevant
207 .iter()
208 .filter(|file| !pair.scope.covers(file))
209 .cloned()
210 .collect(),
211 cause,
212 at,
213 }
214}
215
216/// The `amont.conf` line of the `pre-push` declaration named `name`, if there
217/// is one: the line to edit when its twin acts on every change.
218fn declared_twin_line(manifest: &crate::manifest::Manifest, name: &str) -> Option<usize> {
219 manifest
220 .externals
221 .iter()
222 .find(|e| e.stage == crate::check::Stage::PrePush && e.short_name == name)
223 .and_then(|e| e.lineno)
224}
225
226/// Whether a reason's first line is cut to fit 80 columns.
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228pub(crate) enum LineWidth {
229 /// On a terminal: cut the variable part, keep the ending.
230 Cut,
231 /// Piped, in a CI log: every path in full.
232 Whole,
233}
234
235/// The lines that say why a same-named commit-time declaration did not vouch:
236/// the reason, then for a scope gap an indented line naming the `amont.conf`
237/// line to edit. Pure, so the words and their width are tested.
238///
239/// On a terminal the first line is cut to 80 columns (the sign and its space
240/// stand for two of them), and only its variable part is cut, so its ending,
241/// `— running it here`, always survives. Piped, nothing is cut: a CI log keeps
242/// every path. Every value from the manifest or the repository is sanitised.
243pub(crate) fn reason_lines(name: &str, why: &WhyNot, width: LineWidth) -> Vec<String> {
244 let name = crate::ui::sanitize(name);
245 let first = |prefix: String, variable: String, suffix: &str| -> String {
246 if width == LineWidth::Cut {
247 let line = crate::tree_lint::fit_line(&format!(" {prefix}"), &variable, suffix);
248 line.strip_prefix(" ").unwrap_or(&line).to_string()
249 } else {
250 format!("{prefix}{variable}{suffix}")
251 }
252 };
253 match why {
254 WhyNot::ScopeGap {
255 scope,
256 uncovered,
257 cause,
258 at,
259 } => {
260 let shown: Vec<String> = uncovered
261 .iter()
262 .take(3)
263 .map(|path| crate::ui::sanitize(path))
264 .collect();
265 let paths = match uncovered.len().saturating_sub(3) {
266 0 => shown.join(", "),
267 more => format!("{} and {more} more", shown.join(", ")),
268 };
269 let head = first(
270 format!(
271 "{name} at commit covers {}, not ",
272 crate::ui::sanitize(scope)
273 ),
274 paths,
275 " — running it here",
276 );
277 let at_known = at.is_some();
278 let at = match at {
279 Some(line) => format!("{} line {line}", crate::manifest::MANIFEST),
280 None => crate::manifest::MANIFEST.to_string(),
281 };
282 let first_path = shown.first().map(String::as_str).unwrap_or("it");
283 let fix = match cause {
284 GapCause::Files => {
285 format!(" a files declaration is not widened: add {first_path} to {at}")
286 }
287 GapCause::UnscopedTwin if at_known => {
288 format!(" its push twin runs on every change: scope that line in {at}")
289 }
290 GapCause::UnscopedTwin => format!(
291 " its push twin runs on every change: declare a scoped pre-push {name} line in {at}"
292 ),
293 GapCause::Unresolved => format!(
294 " its push twin's files were not applied: a {} bug, please report it",
295 crate::names::BIN
296 ),
297 };
298 vec![head, fix]
299 }
300 WhyNot::Warn => vec![first(
301 String::new(),
302 name,
303 " at commit is warn-only, so it vouches for nothing — running it here",
304 )],
305 WhyNot::Skipped => vec![first(
306 String::new(),
307 name,
308 " at commit is skipped here (hook.skip) — running it here",
309 )],
310 WhyNot::NotOptedIn(markers) => {
311 let markers: Vec<String> = markers.iter().map(|m| crate::ui::sanitize(m)).collect();
312 vec![first(
313 String::new(),
314 name,
315 &format!(
316 " at commit is not opted in (needs {}) — running it here",
317 markers.join(" | ")
318 ),
319 )]
320 }
321 WhyNot::Unidentified => vec![first(
322 String::new(),
323 name,
324 " at commit: its program was not found — running it here",
325 )],
326 }
327}
328
329/// Say why a same-named commit-time declaration did not vouch, before the push
330/// runs the gate. Exit codes are untouched: this is a line, not a verdict.
331pub(crate) fn say_why_not(name: &str, why: &WhyNot) {
332 let width = if std::io::stdout().is_terminal() {
333 LineWidth::Cut
334 } else {
335 LineWidth::Whole
336 };
337 let mut lines = reason_lines(name, why, width).into_iter();
338 if let Some(head) = lines.next() {
339 crate::say!("{} {head}", crate::ui::warning_sign());
340 }
341 for rest in lines {
342 crate::say!("{rest}");
343 }
344}
345
346/// What a declared PRE-PUSH external should do about a same-named
347/// commit-time declaration — the general form of the npm gate's stamp
348/// suppression, for names the GATE list never heard of. Declaring `test`
349/// (or `lint`, or anything) at BOTH stages is the contract: the pre-commit
350/// side earns per-commit stamps, and the pre-push side runs only for pushes
351/// carrying commits with no record of it, unless a ref's tip itself passed.
352pub(crate) enum PairVerdict {
353 /// No blocking commit-time pair covers this push — run normally. With the
354 /// reason, when a same-named commit-time declaration exists and did not
355 /// vouch: the push says so, then runs the gate. `None` when there is no
356 /// such declaration, or nothing for it to vouch for.
357 NotPaired(Option<WhyNot>),
358 /// Every judged ref is covered — skip, saying so, and how.
359 Gated(Coverage),
360 /// A pair exists but this many pushed commits carry no record of it —
361 /// run, saying why the declaration's word was not enough.
362 Unstamped(usize),
363 /// No pushed commit is unstamped except this many, whose gate the busy
364 /// policy deferred at commit (ADR-0013): defer the twin to CI as well.
365 /// Never `Gated`, which would attest a suite that ran nowhere.
366 Deferred(usize),
367}
368
369/// Judge a pre-push gate against its commit-time pair, with exactly the npm
370/// gate's rules: the pair must be BLOCKING (a warn check vouches for
371/// nothing), its scope must have seen every file this push changes that the
372/// push-side check would fire on, and every relevant commit must carry its
373/// stamp. Any git refusal reads as "no stamp", which runs the check — the
374/// only safe direction.
375///
376/// Takes the push side as `(name, scope)` rather than an `&External`,
377/// because those two are all it ever used and a BUILT-IN has both. That is
378/// the whole reason built-ins can be paired now: the logic never needed a
379/// declaration, only a name to match and a scope to judge against.
380///
381/// `name` is the SHORT name — `cargo-test`, not `pre-push-cargo-test`. It is
382/// compared against [`GateDecl::script`], which is what the author wrote in
383/// `amont.conf`. Passing an id here matches nothing and silently pairs
384/// nothing; see `Check::pairing_name`.
385pub(crate) fn pair_verdict(
386 settings: &crate::config::Settings,
387 name: &str,
388 push_scope: &crate::check::Scope,
389 manifest: &crate::manifest::Manifest,
390 push: &crate::pushrefs::PushRefs,
391) -> PairVerdict {
392 // Cheap name test before any config read or git spawn: most pre-push
393 // gates have no commit-time namesake.
394 let Some(commit_side) = manifest
395 .externals
396 .iter()
397 .find(|e| e.stage == crate::check::Stage::PreCommit && e.short_name == name)
398 else {
399 return PairVerdict::NotPaired(None);
400 };
401 let Some(pair) = blocking_commit_decls(settings, &manifest.externals)
402 .into_iter()
403 .find(|d| d.script == name)
404 else {
405 return PairVerdict::NotPaired(why_not_blocking(settings, commit_side));
406 };
407 // A declaration this repository has not opted into never ran at commit
408 // time, so it has nothing to vouch with — the push side runs on its own
409 // word. Judged against the REPOSITORY, once, and never against a commit's
410 // changed files: see `repo_opted_in`.
411 if !repo_opted_in(&pair.scope) {
412 return PairVerdict::NotPaired(Some(not_opted_in(&pair.scope)));
413 }
414 // The complete token of the commit-time declaration. Unknown identity (its
415 // program cannot be found) means its stamps vouch for nothing: the push
416 // says so, then runs on its own word.
417 let Some(pair_token) = manifest
418 .externals
419 .iter()
420 .find(|e| e.id == pair.id)
421 .and_then(|e| crate::gate_identity::external_token(e, &pair.script))
422 else {
423 return PairVerdict::NotPaired(Some(WhyNot::Unidentified));
424 };
425 let zero = git::stdout(&["hash-object", "--stdin"])
426 .map(|h| "0".repeat(h.len()))
427 .unwrap_or_else(|| "0".repeat(40));
428 let mut unstamped = 0usize;
429 let mut deferred = 0usize;
430 let mut judged_any = false;
431 // The refs covered by their tip alone, as short shas for the line.
432 let mut tips: Vec<String> = Vec::new();
433 // Under `onBusy defer`, a commit whose gate the busy policy deferred is
434 // not "unstamped": its twin defers too (ADR-0013). `AMONT_ON_BUSY=wait`
435 // turns this off and the twin runs.
436 let defer = matches!(
437 crate::host_slots::busy_policy(settings),
438 crate::host_slots::BusyPolicy::Defer { .. }
439 );
440 for r in push.get() {
441 let changed = crate::pushrefs::changed_files_for(r, &zero);
442 // `covers`, NOT `matches`, and the difference is the whole reason
443 // built-ins can be paired at all.
444 //
445 // `matches` also asks the OPT-IN question — "is there a Cargo.toml
446 // here" — and asking it of a single path can only ever answer no.
447 // `pre-push-cargo-test` opts in on `Cargo.toml`, so every changed
448 // `.rs` file would be judged irrelevant, `judged_any` would stay
449 // false, and the verdict would be `NotPaired` for every push in
450 // every Rust repository. Silently: a gate that never pairs looks
451 // exactly like a gate with no pair declared.
452 //
453 // Opt-in is a fact about the REPOSITORY, settled once by the
454 // dispatcher when it decided this check runs here at all. What this
455 // loop needs is the per-file question, which is `covers`.
456 let relevant: Vec<String> = changed
457 .iter()
458 .filter(|f| push_scope.is_unscoped() || push_scope.covers(f))
459 .cloned()
460 .collect();
461 if relevant.is_empty() {
462 continue; // this ref never fires the push-side check
463 }
464 judged_any = true;
465 if !pair.scope.covers_all(&relevant) {
466 // The pair has not judged everything this push changes, so its
467 // word covers nothing here. Said out loud, as "running it here"
468 // and never as partial coverage, which would read as
469 // reassurance: it names what the declaration misses.
470 return PairVerdict::NotPaired(Some(scope_gap(
471 &pair,
472 push_scope,
473 &relevant,
474 declared_twin_line(manifest, name),
475 )));
476 }
477 let per_commit = crate::pushrefs::commits_and_files_for(r, &zero);
478 let ids: Vec<String> = per_commit.iter().map(|(c, _)| c.clone()).collect();
479 let stamps = crate::gate_stamp::stamps_for(&ids);
480 // `touches`, NOT `matches`, for the same reason as above and with a
481 // worse consequence. `matches` asks the opt-in question of ONE
482 // COMMIT's changed files: a `*.txt+marker` pair judged a commit that
483 // changed `a.txt` and left `marker` alone as "would never fire", so
484 // the commit was not counted, `unstamped` stayed 0, and the verdict
485 // was `Gated` — the push-side twin skipped on the strength of a
486 // stamp that did not exist. Opt-in was settled for the repository
487 // above; per commit the only question is whether it touched the
488 // scope.
489 let missing: Vec<String> = per_commit
490 .iter()
491 .filter(|(_, files)| pair.scope.touches(files))
492 .filter(|(commit, _)| !stamps.get(commit).is_some_and(|s| s.contains(&pair_token)))
493 .map(|(commit, _)| commit.clone())
494 .collect();
495 // The tip is what ships. When its OWN stamp key — the tree's note, its
496 // declared-input fingerprints, its canonical tree (ADR-0011, ADR-0012),
497 // exactly what `stamps_for` read above — holds the pair token, the
498 // code being pushed passed the commit-time gate, and an older commit
499 // that never earned a stamp (relais's hookless `commit-tree`, a
500 // deferral) changes nothing about it (ADR-0019). A changed declared
501 // input or gate script gives the tip a different key, so it vouches
502 // for nothing and the per-commit count stands.
503 //
504 // Asked only when some commit is missing its stamp: a fully stamped
505 // ref is covered the old way, and its line keeps meaning so.
506 //
507 // Never for a `files` pair: its command saw only that commit's
508 // matched paths, so its stamp says nothing about the rest of the tree.
509 // holds-until: every pair without `files` judges the whole tree. A
510 // command that picks the staged paths itself (`lint-staged`,
511 // `--cached`, `--staged`) and has a pre-push twin breaks that; none
512 // existed in the fleet on 2026-11-06 (docs/custom-checks.md).
513 //
514 // AFTER the coverage guards above, never before: a ref whose changes
515 // the pair's scope does not cover is `NotPaired`, whatever its tip
516 // says.
517 if !missing.is_empty()
518 && !pair.files
519 && stamps
520 .get(&r.local_oid)
521 .is_some_and(|s| s.contains(&pair_token))
522 {
523 tips.push(crate::gate_evidence::short(&r.local_oid).to_string());
524 continue;
525 }
526 let excused = if defer {
527 crate::gate_stamp::deferred_for(&missing, &pair.script)
528 } else {
529 Default::default()
530 };
531 deferred += excused.len();
532 unstamped += missing.len() - excused.len();
533 }
534 if !judged_any {
535 return PairVerdict::NotPaired(None);
536 }
537 // Never `Gated` when a deferral covers a commit: `Gated` puts the twin
538 // in `passed`, which the signed attestation names, and CI would then skip
539 // a suite that ran nowhere.
540 if unstamped > 0 {
541 PairVerdict::Unstamped(unstamped)
542 } else if deferred > 0 {
543 PairVerdict::Deferred(deferred)
544 } else {
545 PairVerdict::Gated(if tips.is_empty() {
546 Coverage::EveryCommit
547 } else {
548 Coverage::Tips(tips)
549 })
550 }
551}
552
553/// A scope as a person writes it: `*.rs`, `Cargo.toml`, `dir/**/*.md`.
554fn scope_label(scope: &crate::check::Scope) -> String {
555 scope
556 .files
557 .iter()
558 .chain(scope.names.iter())
559 .chain(scope.dirs.iter())
560 .map(|t| {
561 if t.starts_with('.') {
562 format!("*{t}")
563 } else {
564 (*t).to_string()
565 }
566 })
567 .collect::<Vec<_>>()
568 .join(",")
569}
570
571/// Why a runnable commit-time declaration that is not among the blocking ones
572/// did not vouch: `hook.skip` switches it off, or it is a warn check. `None`
573/// for one that is not runnable at all (an untrusted manifest, a broken line),
574/// which the dispatchers already say once per stage.
575fn why_not_blocking(
576 settings: &crate::config::Settings,
577 ext: &crate::manifest::External,
578) -> Option<WhyNot> {
579 if !matches!(ext.kind, crate::manifest::Kind::Runnable { .. }) {
580 return None;
581 }
582 let skipped = crate::configured_skips(settings)
583 .iter()
584 .any(|s| crate::skip_suppresses(&ext.id, s));
585 Some(if skipped {
586 WhyNot::Skipped
587 } else {
588 WhyNot::Warn
589 })
590}
591
592/// Has this repository opted into `scope`? The index is the only honest
593/// source — the same question `manifest.rs` asks before running the
594/// declaration at commit time, so the stamp check and the run agree on
595/// whether it could have run at all.
596///
597/// `true` when git will not list the files: an unverified answer must not
598/// silently promote a declaration to "never ran" — that direction re-runs
599/// the push-side gate, which is the safe one. `tracked_files` is cached
600/// per process, so the git spawn is paid once however many pairs ask.
601fn repo_opted_in(scope: &crate::check::Scope) -> bool {
602 scope.opt_in.is_empty()
603 || crate::hooks::common::tracked_files().map_or(true, |tracked| scope.opted_in(&tracked))
604}
605
606/// One gate entry a commit-time declaration stands in for.
607pub(crate) struct GateDecl {
608 /// The declared name — a GATE script for the npm push gate, any name
609 /// for a declared pre-commit/pre-push pair.
610 pub script: String,
611 /// `<stage>-<name>` — what dispatch outcomes and `hook.skip` key on.
612 /// Carried so pre-commit can match "this declaration" to "that outcome"
613 /// without re-deriving the id and drifting.
614 pub id: String,
615 /// The declaration's scope, judged per ref by
616 /// [`crate::check::Scope::covers_all`].
617 pub scope: crate::check::Scope,
618 /// The `files` marker: the command is handed only the commit's matched
619 /// paths, so its stamp vouches for that commit's files and never for the
620 /// tree. Such a pair cannot cover a ref by its tip ([`pair_verdict`]).
621 pub files: bool,
622 /// The 1-based `amont.conf` line that declares it, for a message that
623 /// sends a person to the line to edit.
624 pub lineno: Option<usize>,
625}
626
627/// The extensions this check treats as "JS worth testing". Exported so
628/// `registry.rs` declares the scope from the same constant — see
629/// `lint_json_yaml::EXTS` for the drift this prevents.
630pub const JS_EXTS: &[&str] = &[".js", ".jsx", ".ts", ".tsx", ".vue"];
631
632fn is_js(file: &str) -> bool {
633 JS_EXTS.iter().any(|e| file.ends_with(e))
634}
635
636fn parent_of(path: &str) -> &str {
637 match path.rfind('/') {
638 Some(i) => &path[..i],
639 None => "",
640 }
641}
642
643/// Does `package.json` define `script` under "scripts"?
644///
645/// A brace-matched scan rather than a JSON parser: the only question is whether
646/// one key exists in one object, and a dependency-free binary is the point of
647/// this migration. Restricted to the TOP-LEVEL "scripts" object so a
648/// same-named key elsewhere (a dependency called `test`, say) cannot answer
649/// for it.
650pub fn defines_script(pkg_json: &str, script: &str) -> bool {
651 let Some(body) = scripts_object(pkg_json) else {
652 return false;
653 };
654 let needle = format!("\"{script}\"");
655 let mut from = 0;
656 while let Some(i) = body[from..].find(&needle) {
657 let at = from + i;
658 let after = &body[at + needle.len()..];
659 if after.trim_start().starts_with(':') {
660 return true;
661 }
662 from = at + needle.len();
663 }
664 false
665}
666
667/// The text of the top-level `"scripts"` object, braces included.
668///
669/// A depth-tracking scan, not `find("\"scripts\"")`: anchoring on the FIRST
670/// occurrence of the substring anywhere meant `{"files":["scripts"],…}`
671/// handed the brace-matcher whichever object came next — so a dependency
672/// named `test` answered as a script while the real scripts object was never
673/// read, which is exactly the false positive `defines_script`'s doc promises
674/// away. A string only counts as a key when it sits at depth 1 (inside the
675/// document object, outside any array) AND its next non-space byte is `:` —
676/// `{"name": "scripts"}` is a value, not the key.
677fn scripts_object(pkg_json: &str) -> Option<&str> {
678 top_level_value(pkg_json, "scripts").filter(|value| value.starts_with('{'))
679}
680
681/// Tracked `package.json` paths, as directories relative to the repo root.
682///
683/// `git ls-files` instead of the shell version's `fd package.json`: it drops
684/// the `fd` dependency (undeclared, and one of two binaries the hooks silently
685/// required), and it is the more correct set anyway — only TRACKED packages can
686/// be part of a push, and node_modules is excluded by construction rather than
687/// by fd happening to honour .gitignore.
688pub fn package_dirs(ls_files: &[String]) -> Vec<String> {
689 let mut dirs: Vec<String> = ls_files
690 .iter()
691 .map(String::as_str)
692 .filter(|f| *f == "package.json" || f.ends_with("/package.json"))
693 .map(|f| parent_of(f).to_string())
694 .collect();
695 dirs.sort();
696 dirs.dedup();
697 dirs
698}
699
700/// Packages that actually contain one of the changed files.
701///
702/// `.iter().any()`, not the shell version's original `.filter()` — an empty
703/// array is truthy in JS, so that selected EVERY package regardless of what
704/// changed. Invisible in a single-package repo, quadratic noise in a monorepo.
705pub fn packages_to_test(pkg_dirs: &[String], changed_dirs: &[String]) -> Vec<String> {
706 pkg_dirs
707 .iter()
708 .filter(|pkg| {
709 changed_dirs.iter().any(|dir| {
710 if pkg.is_empty() {
711 true
712 } else {
713 dir == *pkg || dir.starts_with(&format!("{pkg}/"))
714 }
715 })
716 })
717 .cloned()
718 .collect()
719}
720
721/// What a repository says about which of its ROOT package's scripts already run
722/// every workspace member (`set rootRunsMembers`).
723#[derive(Debug, Clone, PartialEq, Eq)]
724pub(crate) enum RootDeclaration {
725 /// Nothing declared: a root and a member that both ran a script may be a
726 /// repeat, and the push says how to declare it.
727 Unset,
728 /// These of the gate's scripts run every member from the root; none at all
729 /// for `none`. Names are the gate's own: anything else is dropped.
730 Declared(Vec<&'static str>),
731}
732
733/// The gate's scripts named in a `rootRunsMembers` value: `none` is none, and a
734/// name the gate does not run is dropped (the parser already refused one in the
735/// committed line, so only a local value can carry one).
736fn gate_scripts_named(raw: &str) -> Vec<&'static str> {
737 if raw.trim().eq_ignore_ascii_case("none") {
738 return Vec::new();
739 }
740 raw.split(',')
741 .map(str::trim)
742 .filter_map(|name| GATE.iter().copied().find(|script| *script == name))
743 .collect()
744}
745
746/// The declaration, held to what a local `git config` may do to the committed
747/// line: remove names, or set `none`, and never add one. A machine that could
748/// add a name would skip members' tests that no committed, trusted line vouches
749/// for. A local `none` with nothing committed only silences the hint. Pure: the
750/// raw values are read by [`root_declaration`].
751fn declared_from(committed: Option<&str>, effective: Option<&str>) -> RootDeclaration {
752 match (
753 committed.map(gate_scripts_named),
754 effective.map(gate_scripts_named),
755 ) {
756 (Some(committed), Some(effective)) => RootDeclaration::Declared(
757 committed
758 .into_iter()
759 .filter(|script| effective.contains(script))
760 .collect(),
761 ),
762 (Some(committed), None) => RootDeclaration::Declared(committed),
763 (None, Some(effective)) if effective.is_empty() => RootDeclaration::Declared(Vec::new()),
764 (None, _) => RootDeclaration::Unset,
765 }
766}
767
768/// What this repository declares: the committed line, from a trusted
769/// `amont.conf`, and the effective value after any local `git config`.
770pub(crate) fn root_declaration(settings: &crate::config::Settings) -> RootDeclaration {
771 let effective = crate::config::string_value(settings, ROOT_RUNS_KEY);
772 declared_from(
773 settings
774 .policy()
775 .settings
776 .get(ROOT_RUNS_KEY)
777 .map(String::as_str),
778 effective.as_deref(),
779 )
780}
781
782/// The scripts of `root_runs` the declaration says run every member.
783fn covering_scripts(
784 root_runs: &[&'static str],
785 declaration: &RootDeclaration,
786) -> Vec<&'static str> {
787 match declaration {
788 RootDeclaration::Declared(names) => root_runs
789 .iter()
790 .copied()
791 .filter(|script| names.contains(script))
792 .collect(),
793 RootDeclaration::Unset => Vec::new(),
794 }
795}
796
797/// Does an `amont.conf` this machine does not trust carry a
798/// `set rootRunsMembers` line? Its policy is withheld, but the file can still be
799/// read: only then does "trust it" tell the person something true.
800fn untrusted_line_declares(root: &str) -> bool {
801 crate::manifest::read_lines(std::path::Path::new(root))
802 .iter()
803 .any(|line| {
804 matches!(line, crate::manifest::Line::Policy {
805 what: crate::manifest::PolicyLine::Set { key, .. }, ..
806 } if key == ROOT_RUNS_KEY)
807 })
808}
809
810/// What the root covers in one push: the scripts it runs that are declared to
811/// run every member, and where the members are.
812struct RootCoverage {
813 covering: Vec<&'static str>,
814 members: Option<super::js_workspace::Members>,
815}
816
817impl RootCoverage {
818 /// The scripts a package does not run again because the root's run covers
819 /// it: the covering scripts for a member of the workspace, none for the
820 /// root itself or a package outside the globs.
821 fn skip_for(&self, folder: &str) -> &[&'static str] {
822 let covered = !folder.is_empty()
823 && self
824 .members
825 .as_ref()
826 .is_some_and(|members| members.covers(folder));
827 if covered {
828 &self.covering
829 } else {
830 &[]
831 }
832 }
833}
834
835/// The command `script` runs, as `package.json` writes it, when it is a plain
836/// string: what a stale declaration would be read against. `None` for a script
837/// that is absent or written with an escape.
838pub(crate) fn script_command(pkg_json: &str, script: &str) -> Option<String> {
839 let body = scripts_object(pkg_json)?;
840 let needle = format!("\"{script}\"");
841 let mut from = 0;
842 while let Some(i) = body[from..].find(&needle) {
843 let at = from + i;
844 let after = body[at + needle.len()..].trim_start();
845 if let Some(after_colon) = after.strip_prefix(':') {
846 let quoted_command = after_colon.trim_start().strip_prefix('"')?;
847 let close = string_end(quoted_command.as_bytes(), 0)?;
848 let command = "ed_command[..close];
849 return (!command.contains('\\')).then(|| command.to_string());
850 }
851 from = at + needle.len();
852 }
853 None
854}
855
856/// Whether the `amont.conf` that could declare the root's scripts counts here.
857#[derive(Debug, Clone, Copy, PartialEq, Eq)]
858pub(crate) enum Trust {
859 /// A declaration in it would count: the hint says how to add one.
860 Counted,
861 /// It carries a `set rootRunsMembers` line this machine does not trust, so
862 /// the line does not count until it is trusted.
863 Withheld,
864}
865
866/// The lines that say a script ran at the root and in members with nothing
867/// declaring that the root already runs them: a repeat, if it does, and what to
868/// do. Pure, so the words and their width are tested: the first line carries the
869/// sign, so it fits 78 columns, and so does every other line.
870pub(crate) fn repeat_hint_lines(script: &str, members: usize, trust: Trust) -> Vec<String> {
871 let plural = if members == 1 { "" } else { "s" };
872 let mut lines = vec![format!(
873 "{} ran at the root and in {members} package{plural} — a repeat if the root runs them",
874 crate::ui::sanitize(script)
875 )];
876 match trust {
877 Trust::Counted => lines.push(format!(
878 " declare it in {}: set rootRunsMembers {script} (or: none)",
879 crate::manifest::MANIFEST
880 )),
881 Trust::Withheld => {
882 lines.push(format!(
883 " {} is not trusted: its rootRunsMembers line does not count",
884 crate::manifest::MANIFEST
885 ));
886 lines.push(format!(" run: {} trust", crate::names::BIN));
887 }
888 }
889 lines
890}
891
892/// A terminal line is cut to this many columns.
893const LINE_COLUMNS: usize = 80;
894/// The `: ` and the two backticks around the root's command on the summary line.
895const COMMAND_FRAME: usize = 4;
896/// Fewer columns than this are not worth showing of a command.
897const MIN_COMMAND_COLUMNS: usize = 12;
898
899/// The one line that says how many members a declared root script skipped, so
900/// tests that did not run are never silent: the count, what covers them, and
901/// the root's command so a declaration gone stale reads against what it claims.
902/// On a terminal only the command is cut, so the count and the cause survive.
903pub(crate) fn skip_summary_line(
904 skipped: usize,
905 script: &str,
906 command: Option<&str>,
907 width: LineWidth,
908) -> String {
909 let plural = if skipped == 1 { "" } else { "s" };
910 let head = format!(
911 "{skipped} package{plural} skipped, covered by the root's {} (declared in {})",
912 crate::ui::sanitize(script),
913 crate::manifest::MANIFEST
914 );
915 let Some(command) = command else {
916 return head;
917 };
918 let command = crate::ui::sanitize(command);
919 match width {
920 // No room for even a few characters of the command: the count and the
921 // cause are what must survive, so the command goes, and a `…` says
922 // there was one.
923 LineWidth::Cut
924 if head.chars().count() + COMMAND_FRAME + MIN_COMMAND_COLUMNS > LINE_COLUMNS =>
925 {
926 crate::tree_lint::fit_line("", &head, ": …")
927 }
928 LineWidth::Cut => crate::tree_lint::fit_line(&format!("{head}: `"), &command, "`"),
929 LineWidth::Whole => format!("{head}: `{command}`"),
930 }
931}
932
933/// What the push says when a script is declared to cover the members but the
934/// workspace cannot be confirmed: the members run, and the globs are what to
935/// look at. Pure, so the width is tested: the first line carries the sign.
936pub(crate) fn unreadable_workspace_lines(file: &str) -> Vec<String> {
937 vec![
938 "rootRunsMembers is declared, but its workspace globs are not understood".to_string(),
939 format!(
940 " running every member; check the workspace globs in {}",
941 crate::ui::sanitize(file)
942 ),
943 ]
944}
945
946/// The line said before a script runs in a package, so a second run of the same
947/// script reads as a second run and not as the first one stalling. The folder
948/// comes from a git path, so it is sanitised like every other value here.
949pub(crate) fn announcement_line(script: &str, nth: usize, of: usize, folder: &str) -> String {
950 let place = if folder.is_empty() {
951 "the root".to_string()
952 } else {
953 crate::ui::sanitize(folder)
954 };
955 format!("npm run {script}: {nth} of {of}, in {place}")
956}
957
958/// The GATE, minus what a `pre-commit` declaration already covers.
959///
960/// Split from `run_gate` so the rule can be tested without a package on disk
961/// and without spawning npm — `run_gate` reaches for both.
962pub fn gate_for(pkg_json: &str, already: &[&str]) -> Vec<&'static str> {
963 GATE.iter()
964 .copied()
965 .filter(|s| defines_script(pkg_json, s) && !already.contains(s))
966 .collect()
967}
968
969/// How one package's gate went.
970enum GateRun {
971 /// Every script passed; these are the ones that ran.
972 Passed(Vec<&'static str>),
973 /// A script failed or timed out.
974 Failed,
975}
976
977/// Where in this push's list of runs a package is: for its announcement.
978#[derive(Clone, Copy)]
979struct Place {
980 nth: usize,
981 of: usize,
982}
983
984/// A package's directory in the checkout the gate runs in.
985fn package_dir(root: &str, folder: &str) -> String {
986 if folder.is_empty() {
987 root.to_string()
988 } else {
989 format!("{root}/{folder}")
990 }
991}
992
993/// Run `scripts` in one package, announcing each before it runs.
994fn run_gate(
995 settings: &crate::config::Settings,
996 root: &str,
997 folder: &str,
998 scripts: &[&'static str],
999 place: Place,
1000) -> GateRun {
1001 let dir = package_dir(root, folder);
1002 let mut ran = Vec::new();
1003 for &script in scripts {
1004 crate::say!("{}", announcement_line(script, place.nth, place.of, folder));
1005 // Same hazard as cargo test: git exports GIT_DIR to hooks, and a JS
1006 // test that shells out to git would then operate on this repo rather
1007 // than its own fixture.
1008 let mut cmd = Command::new(program("npm"));
1009 cmd.args(["run", script])
1010 .current_dir(&dir)
1011 .stdin(Stdio::null());
1012 super::common::strip_git_env(&mut cmd);
1013 match super::common::status_streamed(settings, &mut cmd, super::common::Retry::Once) {
1014 Ok(super::common::Ran::Status(status)) if status.success() => ran.push(script),
1015 Ok(super::common::Ran::TimedOut(budget)) => {
1016 super::common::say_timed_out(script, budget);
1017 return GateRun::Failed;
1018 }
1019 // The gate's own exit code is not propagated: git only
1020 // distinguishes zero from non-zero, and npm's codes said nothing
1021 // the message above has not already said.
1022 Ok(_) | Err(_) => return GateRun::Failed,
1023 }
1024 }
1025 GateRun::Passed(ran)
1026}
1027
1028pub fn run(
1029 settings: &crate::config::Settings,
1030 refs: &[crate::pushrefs::PushRef],
1031 manifest: &crate::manifest::Manifest,
1032 gate: &str,
1033) -> Outcome {
1034 let declared = manifest.externals.as_slice();
1035 // An all-zero oid, of whatever length this repo's hash is (sha1 or sha256).
1036 let zero = git::stdout(&["hash-object", "--stdin"])
1037 .map(|h| "0".repeat(h.len()))
1038 .unwrap_or_else(|| "0".repeat(40));
1039
1040 // `Unavailable`, never `Passed`, when git itself will not answer: a push
1041 // gate that reports green having asked nothing is the exact conflation
1042 // `Outcome::Unavailable` exists to prevent (see its doc in check.rs), and
1043 // the same split `install::repo_hooks` was rewritten for. The dispatcher
1044 // says "could not run" and does not block — loud, and honest.
1045 let Some(root) = git::stdout(&["rev-parse", "--show-toplevel"]) else {
1046 super::common::warn("run-tests-js: git would not answer — the gate did NOT run");
1047 return Outcome::Unavailable;
1048 };
1049 let Some(tracked) = git::stdout_paths(&["ls-files"]) else {
1050 super::common::warn("run-tests-js: git would not answer — the gate did NOT run");
1051 return Outcome::Unavailable;
1052 };
1053 let pkg_dirs = package_dirs(&tracked);
1054
1055 // The DECLARATIONS are a property of the repository, resolved once; whether
1056 // one covers a given push is a property of that ref's changed files and of
1057 // its commits' stamps, judged inside the loop.
1058 let declared_gate = gated_at_commit(settings, declared);
1059 let mut announced: Vec<String> = Vec::new();
1060 let mut warned: Vec<String> = Vec::new();
1061 let mut said_why: Vec<String> = Vec::new();
1062 // What the repository declares about its root scripts, read once; whether
1063 // its `amont.conf` counts; and what has been said once per push: the repeat
1064 // hint per script, and that a declared workspace could not be read.
1065 let root_declaration = root_declaration(settings);
1066 let trust = if manifest.policy_withheld.is_some() && untrusted_line_declares(&root) {
1067 Trust::Withheld
1068 } else {
1069 Trust::Counted
1070 };
1071 let mut hinted: Vec<&'static str> = Vec::new();
1072 let mut said_unreadable = false;
1073
1074 for r in refs {
1075 let local_oid = r.local_oid.as_str();
1076 if local_oid == zero {
1077 continue; // deleting a ref pushes no code
1078 }
1079 // `pushrefs::changed_files_for` exists for exactly this question, and
1080 // this check used to recompute it inline with all three bugs that
1081 // function's doc comment records fixing:
1082 //
1083 // - a brand-new branch (`remote_oid == zero`) diffed only its TIP,
1084 // so on a multi-commit push an earlier commit's `.ts` change was
1085 // invisible and the suite never ran;
1086 // - a two-dot range handed to `diff-tree` is a two-TREE compare, not
1087 // a commit walk, so a file changed and reverted later in the same
1088 // push netted to nothing;
1089 // - merge commits show NOTHING without `-m`, so a file touched only
1090 // to resolve a conflict selected no package.
1091 //
1092 // Every one of those let a push proceed GREEN with the suite never
1093 // having run. `rust_tools::test` was already the model.
1094 let changed = crate::pushrefs::changed_files_for(r, &zero);
1095 let js_changed: Vec<String> = changed.iter().filter(|f| is_js(f)).cloned().collect();
1096 let changed_dirs: Vec<String> = js_changed
1097 .iter()
1098 .map(|f| parent_of(f).to_string())
1099 .collect();
1100 if changed_dirs.is_empty() {
1101 continue;
1102 }
1103
1104 // A declaration only stands in for this push if its scope saw every JS
1105 // file the push changes — and only for the ROOT package, because that
1106 // is where the declared command runs. A sub-package's gate is a
1107 // different command in a different directory, and no root declaration
1108 // has judged it.
1109 //
1110 // And the declaration must have EXECUTED, which is the stamps'
1111 // question: every commit in this push the declaration would have
1112 // fired on must carry a `gate_stamp` note naming the script. A commit
1113 // made with `--no-verify`, from a client that runs no hooks, on a
1114 // machine without amont, or with a rewritten hash has no stamp — and
1115 // an unstamped commit is one the check never judged, so the gate runs
1116 // rather than trusting the declaration's word for it.
1117 //
1118 // And the REPOSITORY must have opted into it — judged against the
1119 // index, not per commit: see `pair_verdict` for the skipped-gate bug
1120 // that asking it of a commit's changed files produced.
1121 let candidates: Vec<&GateDecl> = declared_gate
1122 .iter()
1123 .filter(|d| d.scope.covers_all(&js_changed) && repo_opted_in(&d.scope))
1124 .collect();
1125 // A declaration that stood in for a script and did not cover this push
1126 // used to be dropped without a word, and the script ran again. Said
1127 // once per script, in the pair gates' words.
1128 for d in &declared_gate {
1129 if said_why.contains(&d.script) {
1130 continue;
1131 }
1132 let why = if !repo_opted_in(&d.scope) {
1133 Some(not_opted_in(&d.scope))
1134 } else if !d.scope.covers_all(&js_changed) {
1135 let js_scope = crate::check::Scope::files(JS_EXTS);
1136 Some(scope_gap(d, &js_scope, &js_changed, None))
1137 } else {
1138 None
1139 };
1140 if let Some(why) = why {
1141 say_why_not(&d.script, &why);
1142 said_why.push(d.script.clone());
1143 }
1144 }
1145 let mut already: Vec<String> = Vec::new();
1146 if !candidates.is_empty() {
1147 let per_commit = crate::pushrefs::commits_and_files_for(r, &zero);
1148 let ids: Vec<String> = per_commit.iter().map(|(c, _)| c.clone()).collect();
1149 let stamps = crate::gate_stamp::stamps_for(&ids);
1150 for d in candidates {
1151 // Complete token or no vouching: a declaration whose program
1152 // cannot be identified vouches for nothing, so it says so and
1153 // the script runs.
1154 let token = declared
1155 .iter()
1156 .find(|e| e.id == d.id)
1157 .and_then(|e| crate::gate_identity::external_token(e, &d.script));
1158 let Some(token) = token else {
1159 // Nothing to vouch with: say so once, and the script runs.
1160 if !said_why.contains(&d.script) {
1161 say_why_not(&d.script, &WhyNot::Unidentified);
1162 said_why.push(d.script.clone());
1163 }
1164 continue;
1165 };
1166 let unstamped = per_commit
1167 .iter()
1168 .filter(|(_, files)| d.scope.touches(files))
1169 .filter(|(commit, _)| {
1170 !stamps
1171 .get(commit)
1172 .is_some_and(|stamped| stamped.contains(&token))
1173 })
1174 .count();
1175 if unstamped == 0 {
1176 already.push(d.script.clone());
1177 } else if !warned.contains(&d.script) {
1178 crate::say!(
1179 "{} {} is declared at commit time, but {unstamped} pushed \
1180 commit{} carr{} no record of it — running it here",
1181 crate::ui::warning_sign(),
1182 d.script,
1183 if unstamped == 1 { "" } else { "s" },
1184 if unstamped == 1 { "ies" } else { "y" },
1185 );
1186 warned.push(d.script.clone());
1187 }
1188 }
1189 }
1190
1191 // Same question as cargo-test: the suite should be answering about
1192 // the commits being pushed, not about whatever is open in the
1193 // editor — and about THIS ref's commits, not some other ref in the
1194 // same push. A single worktree shared across every ref would run a
1195 // second ref's tests against a first ref's tree.
1196 let (run_in, _guard) = crate::pushed_tree::where_to_run(settings, local_oid, &root, gate);
1197 let where_ = run_in.to_string_lossy().into_owned();
1198 let folders = packages_to_test(&pkg_dirs, &changed_dirs);
1199
1200 // Said out loud, and not folded into the pass line. A check that stops
1201 // running is exactly what this project refuses to let happen quietly —
1202 // the reader has to be able to see that `typecheck` moved rather than
1203 // discover later that nothing ran it. Announced only when the skip is
1204 // actually applied to this ref: claiming suppression that severity,
1205 // scope or a missing root package disqualified would be the same lie
1206 // in the other direction.
1207 if folders.iter().any(|f| f.is_empty()) {
1208 let newly: Vec<String> = already
1209 .iter()
1210 .filter(|s| !announced.contains(s))
1211 .cloned()
1212 .collect();
1213 if !newly.is_empty() {
1214 crate::hooks::common::ok(
1215 settings,
1216 &format!(
1217 "{} gated at commit instead — not repeating {} here",
1218 newly.join(", "),
1219 if newly.len() == 1 { "it" } else { "them" },
1220 ),
1221 );
1222 announced.extend(newly);
1223 }
1224 }
1225
1226 let already_strs: Vec<&str> = already.iter().map(String::as_str).collect();
1227
1228 // The root's scripts that run in THIS push, and of those the ones the
1229 // repository declares run every member: a changed member the workspace
1230 // covers is not run again for them. Read from the pushed tree, like
1231 // the packages themselves.
1232 let root_pkg = if folders.iter().any(|f| f.is_empty()) {
1233 std::fs::read_to_string(format!("{where_}/package.json")).ok()
1234 } else {
1235 None
1236 };
1237 let root_runs: Vec<&'static str> = root_pkg
1238 .as_deref()
1239 .map(|pkg| gate_for(pkg, &already_strs))
1240 .unwrap_or_default();
1241 let covering = covering_scripts(&root_runs, &root_declaration);
1242 let members = if covering.is_empty() {
1243 None
1244 } else {
1245 super::js_workspace::members_of(std::path::Path::new(&where_))
1246 };
1247 // Declared, trusted, and unreadable: the members run (the safe side),
1248 // and the person is told why a declared line seems to do nothing.
1249 if !covering.is_empty() && members.is_none() && !said_unreadable {
1250 said_unreadable = true;
1251 let file = if std::path::Path::new(&where_)
1252 .join("pnpm-workspace.yaml")
1253 .is_file()
1254 {
1255 "pnpm-workspace.yaml"
1256 } else {
1257 "package.json"
1258 };
1259 let mut lines = unreadable_workspace_lines(file).into_iter();
1260 if let Some(head) = lines.next() {
1261 crate::say!("{} {head}", crate::ui::warning_sign());
1262 }
1263 for rest in lines {
1264 crate::say!("{rest}");
1265 }
1266 }
1267 let coverage = RootCoverage { covering, members };
1268
1269 // What each package runs here, and what the root's run lets it skip.
1270 let mut plan: Vec<(String, Vec<&'static str>)> = Vec::new();
1271 let mut skipped: Vec<(&'static str, usize)> = Vec::new();
1272 for folder in folders {
1273 let defined =
1274 std::fs::read_to_string(format!("{}/package.json", package_dir(&where_, &folder)))
1275 .map(|pkg| gate_for(&pkg, &[]))
1276 .unwrap_or_default();
1277 // The root's own skips are what a declared commit-time command
1278 // covers; a member's are what the root runs.
1279 let skip: &[&str] = if folder.is_empty() {
1280 &already_strs
1281 } else {
1282 coverage.skip_for(&folder)
1283 };
1284 let (skipped_here, to_run): (Vec<&'static str>, Vec<&'static str>) = defined
1285 .into_iter()
1286 .partition(|script| skip.contains(script));
1287 if !folder.is_empty() {
1288 for script in skipped_here {
1289 match skipped.iter_mut().find(|(name, _)| *name == script) {
1290 Some((_, count)) => *count += 1,
1291 None => skipped.push((script, 1)),
1292 }
1293 }
1294 }
1295 if !to_run.is_empty() {
1296 plan.push((folder, to_run));
1297 }
1298 }
1299 // One line per script for all the members it skips: said always, quiet
1300 // or not, because a line that says tests were NOT run is exactly the
1301 // kind this project does not let get hidden.
1302 let width = if std::io::stdout().is_terminal() {
1303 LineWidth::Cut
1304 } else {
1305 LineWidth::Whole
1306 };
1307 for &script in GATE.iter() {
1308 let Some(&(_, count)) = skipped.iter().find(|(name, _)| *name == script) else {
1309 continue;
1310 };
1311 let command = root_pkg
1312 .as_deref()
1313 .and_then(|pkg| script_command(pkg, script));
1314 crate::say!(
1315 "{}",
1316 skip_summary_line(count, script, command.as_deref(), width)
1317 );
1318 }
1319
1320 let total = plan.len();
1321 let mut ran_in_members: Vec<(&'static str, usize)> = Vec::new();
1322 let mut ran_at_root: Vec<&'static str> = Vec::new();
1323 for (index, (folder, scripts)) in plan.into_iter().enumerate() {
1324 let place = Place {
1325 nth: index + 1,
1326 of: total,
1327 };
1328 let GateRun::Passed(ran) = run_gate(settings, &where_, &folder, &scripts, place) else {
1329 return Outcome::Failed;
1330 };
1331 for script in ran {
1332 if folder.is_empty() {
1333 ran_at_root.push(script);
1334 } else if let Some((_, count)) =
1335 ran_in_members.iter_mut().find(|(name, _)| *name == script)
1336 {
1337 *count += 1;
1338 } else {
1339 ran_in_members.push((script, 1));
1340 }
1341 }
1342 }
1343 // A script that ran at the root AND in members, with nothing declared,
1344 // may be a repeat: said once per script, with what to do about it.
1345 if root_declaration == RootDeclaration::Unset {
1346 for (script, members) in ran_in_members {
1347 if ran_at_root.contains(&script) && !hinted.contains(&script) {
1348 hinted.push(script);
1349 let mut lines = repeat_hint_lines(script, members, trust).into_iter();
1350 if let Some(head) = lines.next() {
1351 crate::say!("{} {head}", crate::ui::warning_sign());
1352 }
1353 for rest in lines {
1354 crate::say!("{rest}");
1355 }
1356 }
1357 }
1358 }
1359 }
1360 Outcome::Passed
1361}
1362
1363#[cfg(test)]
1364mod tests {
1365 use super::*;
1366
1367 /// The filter itself, without a package on disk or an npm to spawn.
1368 ///
1369 /// Order is part of the contract and is asserted: GATE is cheapest-first so
1370 /// a type error costs seconds rather than a full suite, and removing an
1371 /// entry must not disturb what is left.
1372 #[test]
1373 fn the_gate_drops_only_what_commit_already_covers() {
1374 let pkg = r#"{"scripts":{"typecheck":"tsc","test":"vitest run"}}"#;
1375 assert_eq!(gate_for(pkg, &[]), vec!["typecheck", "test"]);
1376 assert_eq!(gate_for(pkg, &["typecheck"]), vec!["test"]);
1377 assert_eq!(gate_for(pkg, &["test"]), vec!["typecheck"]);
1378 assert!(gate_for(pkg, &["typecheck", "test"]).is_empty());
1379 // A name the package does not define is not a script to skip, and
1380 // naming one must not disturb the rest.
1381 assert_eq!(gate_for(pkg, &["test:unit"]), vec!["typecheck", "test"]);
1382 }
1383
1384 /// Coverage is all-match: one changed file outside the declaration's scope
1385 /// means commits this push carries were never judged by it.
1386 #[test]
1387 fn a_scope_covers_only_when_every_changed_file_matches() {
1388 use crate::check::Scope;
1389 const TS_ONLY: Scope = Scope::files(&[".ts", ".tsx"]);
1390 let all_ts: Vec<String> = vec!["src/a.ts".into(), "src/b.tsx".into()];
1391 let mixed: Vec<String> = vec!["src/a.ts".into(), "src/legacy.js".into()];
1392 let js_only: Vec<String> = vec!["src/legacy.js".into()];
1393 assert!(TS_ONLY.covers_all(&all_ts));
1394 assert!(!TS_ONLY.covers_all(&mixed));
1395 assert!(!TS_ONLY.covers_all(&js_only));
1396 // An empty scope is `*` — it saw everything.
1397 assert!(Scope::ALWAYS.covers_all(&mixed));
1398 // Nothing relevant changed: nothing was missed.
1399 assert!(TS_ONLY.covers_all(&[]));
1400
1401 // A bare-filename scope covers by BASENAME, never by suffix.
1402 const BY_NAME: Scope = Scope {
1403 files: &[],
1404 names: &["package.json"],
1405 dirs: &[],
1406 opt_in: &[],
1407 not_during: &[],
1408 };
1409 assert!(BY_NAME.covers_all(&["apps/web/package.json".into()]));
1410 assert!(!BY_NAME.covers_all(&["not-package.json".into()]));
1411 }
1412
1413 #[test]
1414 fn finds_scripts_only_inside_the_scripts_object() {
1415 let pkg = r#"{"name":"x","scripts":{"test":"vitest","typecheck":"tsc"},"devDependencies":{"lint":"1"}}"#;
1416 assert!(defines_script(pkg, "test"));
1417 assert!(defines_script(pkg, "typecheck"));
1418 assert!(!defines_script(pkg, "test:unit"));
1419 // present, but as a DEPENDENCY — must not answer for the scripts object
1420 assert!(!defines_script(pkg, "lint"));
1421 }
1422
1423 #[test]
1424 fn survives_nested_objects_and_escaped_quotes() {
1425 let pkg = r#"{"scripts":{"test":"echo \"hi\"","build":"x"},"other":{"test":"no"}}"#;
1426 assert!(defines_script(pkg, "test"));
1427 assert!(defines_script(pkg, "build"));
1428 assert!(!defines_script(pkg, "other"));
1429 }
1430
1431 #[test]
1432 fn no_scripts_object_means_no_scripts() {
1433 assert!(!defines_script(r#"{"name":"x"}"#, "test"));
1434 }
1435
1436 /// The misanchor this scan replaced: `find("\"scripts\"")` hit the string
1437 /// inside the `files` ARRAY, brace-matched the dependencies object that
1438 /// followed, and a dependency named `test` answered as a script — while
1439 /// the real scripts object was never read.
1440 #[test]
1441 fn a_scripts_string_elsewhere_cannot_anchor_the_scan() {
1442 let pkg = r#"{"files":["scripts"],"dependencies":{"test":"1.0"},"scripts":{"build":"x"}}"#;
1443 assert!(
1444 !defines_script(pkg, "test"),
1445 "a dependency answered as a script"
1446 );
1447 assert!(
1448 defines_script(pkg, "build"),
1449 "the real scripts object was skipped"
1450 );
1451
1452 // The same shape via a string VALUE rather than an array element.
1453 let pkg =
1454 r#"{"description":"scripts","dependencies":{"test":"1.0"},"scripts":{"build":"x"}}"#;
1455 assert!(!defines_script(pkg, "test"));
1456 assert!(defines_script(pkg, "build"));
1457
1458 // A NESTED "scripts" key (inside another object) is not the top-level
1459 // one.
1460 let pkg = r#"{"config":{"scripts":{"test":"inner"}},"scripts":{"build":"x"}}"#;
1461 assert!(!defines_script(pkg, "test"));
1462 assert!(defines_script(pkg, "build"));
1463 }
1464
1465 /// `"scripts"` as a top-level key whose value is not an object defines
1466 /// nothing — and no later impostor may answer instead.
1467 #[test]
1468 fn a_non_object_scripts_value_defines_nothing() {
1469 assert!(!defines_script(r#"{"scripts":"echo hi"}"#, "test"));
1470 assert!(!defines_script(
1471 r#"{"scripts":"x","other":{"test":"y"}}"#,
1472 "test"
1473 ));
1474 }
1475
1476 #[test]
1477 fn collects_package_directories() {
1478 let ls: Vec<String> = [
1479 "package.json",
1480 "apps/web/package.json",
1481 "apps/web/src/a.ts",
1482 "README.md",
1483 ]
1484 .into_iter()
1485 .map(String::from)
1486 .collect();
1487 assert_eq!(
1488 package_dirs(&ls),
1489 vec!["".to_string(), "apps/web".to_string()]
1490 );
1491 }
1492
1493 /// The JS bug: `.filter()` returns an array, `[]` is truthy, so every
1494 /// package was selected whatever changed.
1495 #[test]
1496 fn selects_only_packages_containing_a_change() {
1497 let pkgs = vec!["apps/web".to_string(), "apps/api".to_string()];
1498 let changed = vec!["apps/web/src".to_string()];
1499 assert_eq!(
1500 packages_to_test(&pkgs, &changed),
1501 vec!["apps/web".to_string()]
1502 );
1503 }
1504
1505 #[test]
1506 fn the_repo_root_package_matches_any_change() {
1507 let pkgs = vec!["".to_string()];
1508 assert_eq!(
1509 packages_to_test(&pkgs, &["src".to_string()]),
1510 vec!["".to_string()]
1511 );
1512 }
1513
1514 fn every_reason(path: &str) -> Vec<WhyNot> {
1515 vec![
1516 WhyNot::ScopeGap {
1517 scope: "*.rs".into(),
1518 uncovered: vec![path.into()],
1519 cause: GapCause::Files,
1520 at: Some(3),
1521 },
1522 WhyNot::Warn,
1523 WhyNot::Skipped,
1524 WhyNot::NotOptedIn(vec!["marker".into()]),
1525 WhyNot::Unidentified,
1526 ]
1527 }
1528
1529 /// The first line of every reason fits 80 columns with the sign and its
1530 /// space in front, for an ordinary name, and ends in `running it here`:
1531 /// the part a reader needs must never be the part that gets cut.
1532 #[test]
1533 fn every_reason_fits_its_line_and_keeps_its_ending() {
1534 for why in every_reason("rustfmt.toml") {
1535 let head = &reason_lines("cargo-test", &why, LineWidth::Whole)[0];
1536 assert!(head.chars().count() + 2 <= 80, "{head}");
1537 assert!(head.ends_with("— running it here"), "{head}");
1538 }
1539 }
1540
1541 /// On a terminal a long path, or a long name, is cut, never the ending.
1542 #[test]
1543 fn on_a_terminal_only_the_variable_part_is_cut() {
1544 let long = "crates/a/very/deep/package/directory/src/components/widgets/Button.stories.tsx";
1545 for why in every_reason(long) {
1546 let head = &reason_lines("cargo-test", &why, LineWidth::Cut)[0];
1547 assert!(head.chars().count() + 2 <= 80, "{head}");
1548 assert!(head.ends_with("— running it here"), "{head}");
1549 }
1550 let name = "a-rather-long-check-name-indeed-for-a-gate";
1551 for why in [
1552 WhyNot::Warn,
1553 WhyNot::Skipped,
1554 WhyNot::NotOptedIn(vec!["marker".into()]),
1555 WhyNot::Unidentified,
1556 ] {
1557 let head = &reason_lines(name, &why, LineWidth::Cut)[0];
1558 assert!(head.chars().count() + 2 <= 80, "{head}");
1559 assert!(head.ends_with("— running it here"), "{head}");
1560 }
1561 }
1562
1563 /// Piped, nothing is cut: a CI log keeps every path.
1564 #[test]
1565 fn piped_nothing_is_cut() {
1566 let long = "crates/a/very/deep/package/directory/src/components/widgets/Button.stories.tsx";
1567 let why = WhyNot::ScopeGap {
1568 scope: "*.rs".into(),
1569 uncovered: vec![long.into()],
1570 cause: GapCause::Files,
1571 at: None,
1572 };
1573 assert!(reason_lines("cargo-test", &why, LineWidth::Whole)[0].contains(long));
1574 }
1575
1576 /// Everything the manifest or the repository supplies is sanitised, the
1577 /// scope and the markers included.
1578 #[test]
1579 fn values_from_the_manifest_are_sanitised() {
1580 let why = WhyNot::NotOptedIn(vec!["mark\u{1b}[31mer".into()]);
1581 let head = &reason_lines("cargo-test", &why, LineWidth::Whole)[0];
1582 assert!(!head.contains('\u{1b}'), "{head:?}");
1583 }
1584
1585 /// What a declaration is read against: the root script's command, when it
1586 /// is a plain string.
1587 #[test]
1588 fn a_scripts_command_is_read_when_it_is_a_plain_string() {
1589 let pkg = r#"{"name":"r","scripts":{"build":"tsc","test":"pnpm -r --workspace-concurrency=2 test"}}"#;
1590 assert_eq!(
1591 script_command(pkg, "test").as_deref(),
1592 Some("pnpm -r --workspace-concurrency=2 test")
1593 );
1594 assert_eq!(script_command(pkg, "typecheck"), None, "absent");
1595 let escaped = r#"{"scripts":{"test":"echo \"x\""}}"#;
1596 assert_eq!(
1597 script_command(escaped, "test"),
1598 None,
1599 "an escape is not guessed at"
1600 );
1601 let elsewhere = r#"{"dependencies":{"test":"1.0.0"},"scripts":{}}"#;
1602 assert_eq!(
1603 script_command(elsewhere, "test"),
1604 None,
1605 "only the scripts object"
1606 );
1607 }
1608
1609 /// The repeat hint's lines fit 80 columns (the first with the sign), for
1610 /// every script the gate runs, and name the line to add; withheld, they say
1611 /// why a line there would not count and how to trust it.
1612 #[test]
1613 fn the_repeat_hint_fits_its_line_and_names_the_fix() {
1614 for script in crate::manifest::NPM_GATE_SCRIPTS {
1615 let lines = repeat_hint_lines(script, 30, Trust::Counted);
1616 assert!(lines[0].chars().count() + 2 <= 80, "{}", lines[0]);
1617 assert!(lines[0].contains("a repeat if the root runs them"));
1618 assert!(
1619 lines[1].contains(&format!("set rootRunsMembers {script}")),
1620 "{}",
1621 lines[1]
1622 );
1623 for line in &lines[1..] {
1624 assert!(line.chars().count() <= 80, "{line}");
1625 }
1626 }
1627 let one = repeat_hint_lines("test", 1, Trust::Counted);
1628 assert!(one[0].contains("in 1 package —"), "{}", one[0]);
1629 let withheld = repeat_hint_lines("test", 2, Trust::Withheld);
1630 assert!(withheld[1].contains("is not trusted"), "{}", withheld[1]);
1631 assert!(withheld[2].contains("trust"), "{}", withheld[2]);
1632 for line in &withheld[1..] {
1633 assert!(line.chars().count() <= 80, "{line}");
1634 assert!(!line.contains("declare it in"), "{line}");
1635 }
1636 }
1637
1638 /// The summary line keeps its count and its cause on a terminal, for every
1639 /// script the gate runs, and cuts only the command.
1640 #[test]
1641 fn the_skip_summary_fits_its_line() {
1642 for script in crate::manifest::NPM_GATE_SCRIPTS {
1643 // A count of any width still fits: three digits cost a column.
1644 for count in [1, 30, 100, 1000] {
1645 let line = skip_summary_line(count, script, Some("pnpm -r test"), LineWidth::Cut);
1646 assert!(line.chars().count() <= LINE_COLUMNS, "{line}");
1647 }
1648 let head = skip_summary_line(30, script, None, LineWidth::Cut);
1649 assert!(head.chars().count() <= 80, "{head}");
1650 assert!(head.contains("30 packages skipped"), "{head}");
1651 let cut = skip_summary_line(30, script, Some(&"x".repeat(200)), LineWidth::Cut);
1652 assert!(cut.chars().count() <= 80, "{cut}");
1653 assert!(cut.contains("covered by the root's"), "{cut}");
1654 // Every gate script's head leaves no room for the command, so the
1655 // marker branch is the one taken.
1656 assert!(cut.ends_with(": …"), "{cut}");
1657 }
1658 assert!(
1659 skip_summary_line(1, "test", None, LineWidth::Whole).starts_with("1 package skipped")
1660 );
1661 }
1662
1663 /// The warning sign and the space after it.
1664 const SIGN_COLUMNS: usize = 2;
1665
1666 /// A non-object top-level `scripts` answers "no scripts"; a nested
1667 /// `scripts` key later in the file never stands in for it.
1668 #[test]
1669 fn a_non_object_scripts_key_is_not_replaced_by_a_nested_one() {
1670 let pkg = r#"{"scripts":"none","other":{"scripts":{"test":"x"}}}"#;
1671 assert_eq!(scripts_object(pkg), None);
1672 assert!(!defines_script(pkg, "test"));
1673 }
1674
1675 /// The unreadable-workspace lines fit 80 columns, the first with its sign,
1676 /// and name the file read.
1677 #[test]
1678 fn the_unreadable_workspace_lines_fit_and_name_the_file() {
1679 for file in ["package.json", "pnpm-workspace.yaml"] {
1680 let lines = unreadable_workspace_lines(file);
1681 assert!(
1682 lines[0].chars().count() + SIGN_COLUMNS <= LINE_COLUMNS,
1683 "{}",
1684 lines[0]
1685 );
1686 assert!(lines[1].chars().count() <= LINE_COLUMNS, "{}", lines[1]);
1687 assert!(lines[1].contains(file), "{}", lines[1]);
1688 }
1689 }
1690
1691 /// The announcement counts a run, names its place, and sanitises the folder.
1692 #[test]
1693 fn the_announcement_names_its_place() {
1694 assert_eq!(
1695 announcement_line("test", 1, 3, ""),
1696 "npm run test: 1 of 3, in the root"
1697 );
1698 assert_eq!(
1699 announcement_line("test", 2, 3, "packages/a"),
1700 "npm run test: 2 of 3, in packages/a"
1701 );
1702 assert!(!announcement_line("test", 2, 3, "a\u{1b}[31mb").contains('\u{1b}'));
1703 }
1704
1705 /// A local `git config` is held to the committed line: it removes names or
1706 /// sets `none`, and never adds one.
1707 #[test]
1708 fn a_local_value_only_removes_what_is_committed() {
1709 use RootDeclaration::{Declared, Unset};
1710 assert_eq!(
1711 declared_from(Some("test,typecheck"), Some("test")),
1712 Declared(vec!["test"])
1713 );
1714 assert_eq!(declared_from(Some("test"), Some("none")), Declared(vec![]));
1715 assert_eq!(declared_from(Some("none"), Some("test")), Declared(vec![]));
1716 assert_eq!(declared_from(None, Some("none")), Declared(vec![]));
1717 assert_eq!(declared_from(None, Some("test")), Unset);
1718 assert_eq!(declared_from(None, None), Unset);
1719 assert_eq!(declared_from(Some("test"), None), Declared(vec!["test"]));
1720 assert_eq!(
1721 declared_from(Some("test,bogus"), None),
1722 Declared(vec!["test"])
1723 );
1724 }
1725
1726 /// Only the root's scripts that are declared cover members.
1727 #[test]
1728 fn only_declared_root_scripts_cover() {
1729 let declared = RootDeclaration::Declared(vec!["test"]);
1730 assert_eq!(
1731 covering_scripts(&["test", "typecheck"], &declared),
1732 vec!["test"]
1733 );
1734 assert!(covering_scripts(&["test"], &RootDeclaration::Unset).is_empty());
1735 }
1736
1737 /// Nothing declared reads as unset.
1738 #[test]
1739 fn nothing_declared_is_unset() {
1740 let settings = crate::config::Settings::default();
1741 assert_eq!(root_declaration(&settings), RootDeclaration::Unset);
1742 }
1743}