Skip to main content

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