use super::common::program;
use super::json_scan::{string_end, top_level_value};
use crate::check::Outcome;
use crate::git;
use crate::manifest::ROOT_RUNS_KEY;
use std::io::IsTerminal;
use std::process::{Command, Stdio};
const GATE: [&str; 3] = crate::manifest::NPM_GATE_SCRIPTS;
pub(crate) fn is_gate_script(name: &str) -> bool {
GATE.contains(&name)
}
pub(crate) fn gated_at_commit(
settings: &crate::config::Settings,
declared: &[crate::manifest::External],
) -> Vec<GateDecl> {
let mut decls = blocking_commit_decls(settings, declared);
decls.retain(|d| GATE.contains(&d.script.as_str()));
decls
}
pub(crate) fn blocking_commit_decls(
settings: &crate::config::Settings,
declared: &[crate::manifest::External],
) -> Vec<GateDecl> {
if gate_names_declared(declared).is_empty() {
return Vec::new();
}
let skips = crate::configured_skips(settings);
let severities = crate::registry::Overrides::read(settings);
declared
.iter()
.filter_map(|ext| {
let crate::manifest::Kind::Runnable { files, .. } = &ext.kind else {
return None;
};
ext.blocks_at_commit(&severities, &skips).then(|| GateDecl {
script: ext.short_name.clone(),
id: ext.id.clone(),
lineno: ext.lineno,
scope: ext.effective_scope(),
files: *files,
})
})
.collect()
}
pub(crate) fn gate_names_declared(declared: &[crate::manifest::External]) -> Vec<String> {
declared
.iter()
.filter(|ext| ext.stage == crate::check::Stage::PreCommit)
.map(|ext| ext.short_name.clone())
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Coverage {
EveryCommit,
Tips(Vec<String>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum WhyNot {
ScopeGap {
scope: String,
uncovered: Vec<String>,
cause: GapCause,
at: Option<usize>,
},
Warn,
Skipped,
NotOptedIn(Vec<String>),
Unidentified,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum GapCause {
Files,
UnscopedTwin,
Unresolved,
}
fn not_opted_in(scope: &crate::check::Scope) -> WhyNot {
WhyNot::NotOptedIn(scope.opt_in.iter().map(|m| m.to_string()).collect())
}
fn scope_gap(
pair: &GateDecl,
push_scope: &crate::check::Scope,
relevant: &[String],
twin_line: Option<usize>,
) -> WhyNot {
let (cause, at) = if pair.files {
(GapCause::Files, pair.lineno)
} else if push_scope.is_unscoped() {
(GapCause::UnscopedTwin, twin_line)
} else {
(GapCause::Unresolved, pair.lineno)
};
WhyNot::ScopeGap {
scope: scope_label(&pair.scope),
uncovered: relevant
.iter()
.filter(|file| !pair.scope.covers(file))
.cloned()
.collect(),
cause,
at,
}
}
fn declared_twin_line(manifest: &crate::manifest::Manifest, name: &str) -> Option<usize> {
manifest
.externals
.iter()
.find(|e| e.stage == crate::check::Stage::PrePush && e.short_name == name)
.and_then(|e| e.lineno)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LineWidth {
Cut,
Whole,
}
pub(crate) fn reason_lines(name: &str, why: &WhyNot, width: LineWidth) -> Vec<String> {
let name = crate::ui::sanitize(name);
let first = |prefix: String, variable: String, suffix: &str| -> String {
if width == LineWidth::Cut {
let line = crate::tree_lint::fit_line(&format!(" {prefix}"), &variable, suffix);
line.strip_prefix(" ").unwrap_or(&line).to_string()
} else {
format!("{prefix}{variable}{suffix}")
}
};
match why {
WhyNot::ScopeGap {
scope,
uncovered,
cause,
at,
} => {
let shown: Vec<String> = uncovered
.iter()
.take(3)
.map(|path| crate::ui::sanitize(path))
.collect();
let paths = match uncovered.len().saturating_sub(3) {
0 => shown.join(", "),
more => format!("{} and {more} more", shown.join(", ")),
};
let head = first(
format!(
"{name} at commit covers {}, not ",
crate::ui::sanitize(scope)
),
paths,
" — running it here",
);
let at_known = at.is_some();
let at = match at {
Some(line) => format!("{} line {line}", crate::manifest::MANIFEST),
None => crate::manifest::MANIFEST.to_string(),
};
let first_path = shown.first().map(String::as_str).unwrap_or("it");
let fix = match cause {
GapCause::Files => {
format!(" a files declaration is not widened: add {first_path} to {at}")
}
GapCause::UnscopedTwin if at_known => {
format!(" its push twin runs on every change: scope that line in {at}")
}
GapCause::UnscopedTwin => format!(
" its push twin runs on every change: declare a scoped pre-push {name} line in {at}"
),
GapCause::Unresolved => format!(
" its push twin's files were not applied: a {} bug, please report it",
crate::names::BIN
),
};
vec![head, fix]
}
WhyNot::Warn => vec![first(
String::new(),
name,
" at commit is warn-only, so it vouches for nothing — running it here",
)],
WhyNot::Skipped => vec![first(
String::new(),
name,
" at commit is skipped here (hook.skip) — running it here",
)],
WhyNot::NotOptedIn(markers) => {
let markers: Vec<String> = markers.iter().map(|m| crate::ui::sanitize(m)).collect();
vec![first(
String::new(),
name,
&format!(
" at commit is not opted in (needs {}) — running it here",
markers.join(" | ")
),
)]
}
WhyNot::Unidentified => vec![first(
String::new(),
name,
" at commit: its program was not found — running it here",
)],
}
}
pub(crate) fn say_why_not(name: &str, why: &WhyNot) {
let width = if std::io::stdout().is_terminal() {
LineWidth::Cut
} else {
LineWidth::Whole
};
let mut lines = reason_lines(name, why, width).into_iter();
if let Some(head) = lines.next() {
crate::say!("{} {head}", crate::ui::warning_sign());
}
for rest in lines {
crate::say!("{rest}");
}
}
pub(crate) enum PairVerdict {
NotPaired(Option<WhyNot>),
Gated(Coverage),
Unstamped(usize),
Deferred(usize),
}
pub(crate) fn pair_verdict(
settings: &crate::config::Settings,
name: &str,
push_scope: &crate::check::Scope,
manifest: &crate::manifest::Manifest,
push: &crate::pushrefs::PushRefs,
) -> PairVerdict {
let Some(commit_side) = manifest
.externals
.iter()
.find(|e| e.stage == crate::check::Stage::PreCommit && e.short_name == name)
else {
return PairVerdict::NotPaired(None);
};
let Some(pair) = blocking_commit_decls(settings, &manifest.externals)
.into_iter()
.find(|d| d.script == name)
else {
return PairVerdict::NotPaired(why_not_blocking(settings, commit_side));
};
if !repo_opted_in(&pair.scope) {
return PairVerdict::NotPaired(Some(not_opted_in(&pair.scope)));
}
let Some(pair_token) = manifest
.externals
.iter()
.find(|e| e.id == pair.id)
.and_then(|e| crate::gate_identity::external_token(e, &pair.script))
else {
return PairVerdict::NotPaired(Some(WhyNot::Unidentified));
};
let zero = git::stdout(&["hash-object", "--stdin"])
.map(|h| "0".repeat(h.len()))
.unwrap_or_else(|| "0".repeat(40));
let mut unstamped = 0usize;
let mut deferred = 0usize;
let mut judged_any = false;
let mut tips: Vec<String> = Vec::new();
let defer = matches!(
crate::host_slots::busy_policy(settings),
crate::host_slots::BusyPolicy::Defer { .. }
);
for r in push.get() {
let changed = crate::pushrefs::changed_files_for(r, &zero);
let relevant: Vec<String> = changed
.iter()
.filter(|f| push_scope.is_unscoped() || push_scope.covers(f))
.cloned()
.collect();
if relevant.is_empty() {
continue; }
judged_any = true;
if !pair.scope.covers_all(&relevant) {
return PairVerdict::NotPaired(Some(scope_gap(
&pair,
push_scope,
&relevant,
declared_twin_line(manifest, name),
)));
}
let per_commit = crate::pushrefs::commits_and_files_for(r, &zero);
let ids: Vec<String> = per_commit.iter().map(|(c, _)| c.clone()).collect();
let stamps = crate::gate_stamp::stamps_for(&ids);
let missing: Vec<String> = per_commit
.iter()
.filter(|(_, files)| pair.scope.touches(files))
.filter(|(commit, _)| !stamps.get(commit).is_some_and(|s| s.contains(&pair_token)))
.map(|(commit, _)| commit.clone())
.collect();
if !missing.is_empty()
&& !pair.files
&& stamps
.get(&r.local_oid)
.is_some_and(|s| s.contains(&pair_token))
{
tips.push(crate::gate_evidence::short(&r.local_oid).to_string());
continue;
}
let excused = if defer {
crate::gate_stamp::deferred_for(&missing, &pair.script)
} else {
Default::default()
};
deferred += excused.len();
unstamped += missing.len() - excused.len();
}
if !judged_any {
return PairVerdict::NotPaired(None);
}
if unstamped > 0 {
PairVerdict::Unstamped(unstamped)
} else if deferred > 0 {
PairVerdict::Deferred(deferred)
} else {
PairVerdict::Gated(if tips.is_empty() {
Coverage::EveryCommit
} else {
Coverage::Tips(tips)
})
}
}
fn scope_label(scope: &crate::check::Scope) -> String {
scope
.files
.iter()
.chain(scope.names.iter())
.chain(scope.dirs.iter())
.map(|t| {
if t.starts_with('.') {
format!("*{t}")
} else {
(*t).to_string()
}
})
.collect::<Vec<_>>()
.join(",")
}
fn why_not_blocking(
settings: &crate::config::Settings,
ext: &crate::manifest::External,
) -> Option<WhyNot> {
if !matches!(ext.kind, crate::manifest::Kind::Runnable { .. }) {
return None;
}
let skipped = crate::configured_skips(settings)
.iter()
.any(|s| crate::skip_suppresses(&ext.id, s));
Some(if skipped {
WhyNot::Skipped
} else {
WhyNot::Warn
})
}
fn repo_opted_in(scope: &crate::check::Scope) -> bool {
scope.opt_in.is_empty()
|| crate::hooks::common::tracked_files().map_or(true, |tracked| scope.opted_in(&tracked))
}
pub(crate) struct GateDecl {
pub script: String,
pub id: String,
pub scope: crate::check::Scope,
pub files: bool,
pub lineno: Option<usize>,
}
pub const JS_EXTS: &[&str] = &[".js", ".jsx", ".ts", ".tsx", ".vue"];
fn is_js(file: &str) -> bool {
JS_EXTS.iter().any(|e| file.ends_with(e))
}
fn parent_of(path: &str) -> &str {
match path.rfind('/') {
Some(i) => &path[..i],
None => "",
}
}
pub fn defines_script(pkg_json: &str, script: &str) -> bool {
let Some(body) = scripts_object(pkg_json) else {
return false;
};
let needle = format!("\"{script}\"");
let mut from = 0;
while let Some(i) = body[from..].find(&needle) {
let at = from + i;
let after = &body[at + needle.len()..];
if after.trim_start().starts_with(':') {
return true;
}
from = at + needle.len();
}
false
}
fn scripts_object(pkg_json: &str) -> Option<&str> {
top_level_value(pkg_json, "scripts").filter(|value| value.starts_with('{'))
}
pub fn package_dirs(ls_files: &[String]) -> Vec<String> {
let mut dirs: Vec<String> = ls_files
.iter()
.map(String::as_str)
.filter(|f| *f == "package.json" || f.ends_with("/package.json"))
.map(|f| parent_of(f).to_string())
.collect();
dirs.sort();
dirs.dedup();
dirs
}
pub fn packages_to_test(pkg_dirs: &[String], changed_dirs: &[String]) -> Vec<String> {
pkg_dirs
.iter()
.filter(|pkg| {
changed_dirs.iter().any(|dir| {
if pkg.is_empty() {
true
} else {
dir == *pkg || dir.starts_with(&format!("{pkg}/"))
}
})
})
.cloned()
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum RootDeclaration {
Unset,
Declared(Vec<&'static str>),
}
fn gate_scripts_named(raw: &str) -> Vec<&'static str> {
if raw.trim().eq_ignore_ascii_case("none") {
return Vec::new();
}
raw.split(',')
.map(str::trim)
.filter_map(|name| GATE.iter().copied().find(|script| *script == name))
.collect()
}
fn declared_from(committed: Option<&str>, effective: Option<&str>) -> RootDeclaration {
match (
committed.map(gate_scripts_named),
effective.map(gate_scripts_named),
) {
(Some(committed), Some(effective)) => RootDeclaration::Declared(
committed
.into_iter()
.filter(|script| effective.contains(script))
.collect(),
),
(Some(committed), None) => RootDeclaration::Declared(committed),
(None, Some(effective)) if effective.is_empty() => RootDeclaration::Declared(Vec::new()),
(None, _) => RootDeclaration::Unset,
}
}
pub(crate) fn root_declaration(settings: &crate::config::Settings) -> RootDeclaration {
let effective = crate::config::string_value(settings, ROOT_RUNS_KEY);
declared_from(
settings
.policy()
.settings
.get(ROOT_RUNS_KEY)
.map(String::as_str),
effective.as_deref(),
)
}
fn covering_scripts(
root_runs: &[&'static str],
declaration: &RootDeclaration,
) -> Vec<&'static str> {
match declaration {
RootDeclaration::Declared(names) => root_runs
.iter()
.copied()
.filter(|script| names.contains(script))
.collect(),
RootDeclaration::Unset => Vec::new(),
}
}
fn untrusted_line_declares(root: &str) -> bool {
crate::manifest::read_lines(std::path::Path::new(root))
.iter()
.any(|line| {
matches!(line, crate::manifest::Line::Policy {
what: crate::manifest::PolicyLine::Set { key, .. }, ..
} if key == ROOT_RUNS_KEY)
})
}
struct RootCoverage {
covering: Vec<&'static str>,
members: Option<super::js_workspace::Members>,
}
impl RootCoverage {
fn skip_for(&self, folder: &str) -> &[&'static str] {
let covered = !folder.is_empty()
&& self
.members
.as_ref()
.is_some_and(|members| members.covers(folder));
if covered {
&self.covering
} else {
&[]
}
}
}
pub(crate) fn script_command(pkg_json: &str, script: &str) -> Option<String> {
let body = scripts_object(pkg_json)?;
let needle = format!("\"{script}\"");
let mut from = 0;
while let Some(i) = body[from..].find(&needle) {
let at = from + i;
let after = body[at + needle.len()..].trim_start();
if let Some(after_colon) = after.strip_prefix(':') {
let quoted_command = after_colon.trim_start().strip_prefix('"')?;
let close = string_end(quoted_command.as_bytes(), 0)?;
let command = "ed_command[..close];
return (!command.contains('\\')).then(|| command.to_string());
}
from = at + needle.len();
}
None
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Trust {
Counted,
Withheld,
}
pub(crate) fn repeat_hint_lines(script: &str, members: usize, trust: Trust) -> Vec<String> {
let plural = if members == 1 { "" } else { "s" };
let mut lines = vec![format!(
"{} ran at the root and in {members} package{plural} — a repeat if the root runs them",
crate::ui::sanitize(script)
)];
match trust {
Trust::Counted => lines.push(format!(
" declare it in {}: set rootRunsMembers {script} (or: none)",
crate::manifest::MANIFEST
)),
Trust::Withheld => {
lines.push(format!(
" {} is not trusted: its rootRunsMembers line does not count",
crate::manifest::MANIFEST
));
lines.push(format!(" run: {} trust", crate::names::BIN));
}
}
lines
}
const LINE_COLUMNS: usize = 80;
const COMMAND_FRAME: usize = 4;
const MIN_COMMAND_COLUMNS: usize = 12;
pub(crate) fn skip_summary_line(
skipped: usize,
script: &str,
command: Option<&str>,
width: LineWidth,
) -> String {
let plural = if skipped == 1 { "" } else { "s" };
let head = format!(
"{skipped} package{plural} skipped, covered by the root's {} (declared in {})",
crate::ui::sanitize(script),
crate::manifest::MANIFEST
);
let Some(command) = command else {
return head;
};
let command = crate::ui::sanitize(command);
match width {
LineWidth::Cut
if head.chars().count() + COMMAND_FRAME + MIN_COMMAND_COLUMNS > LINE_COLUMNS =>
{
crate::tree_lint::fit_line("", &head, ": …")
}
LineWidth::Cut => crate::tree_lint::fit_line(&format!("{head}: `"), &command, "`"),
LineWidth::Whole => format!("{head}: `{command}`"),
}
}
pub(crate) fn unreadable_workspace_lines(file: &str) -> Vec<String> {
vec![
"rootRunsMembers is declared, but its workspace globs are not understood".to_string(),
format!(
" running every member; check the workspace globs in {}",
crate::ui::sanitize(file)
),
]
}
pub(crate) fn announcement_line(script: &str, nth: usize, of: usize, folder: &str) -> String {
let place = if folder.is_empty() {
"the root".to_string()
} else {
crate::ui::sanitize(folder)
};
format!("npm run {script}: {nth} of {of}, in {place}")
}
pub fn gate_for(pkg_json: &str, already: &[&str]) -> Vec<&'static str> {
GATE.iter()
.copied()
.filter(|s| defines_script(pkg_json, s) && !already.contains(s))
.collect()
}
enum GateRun {
Passed(Vec<&'static str>),
Failed,
}
#[derive(Clone, Copy)]
struct Place {
nth: usize,
of: usize,
}
fn package_dir(root: &str, folder: &str) -> String {
if folder.is_empty() {
root.to_string()
} else {
format!("{root}/{folder}")
}
}
fn run_gate(
settings: &crate::config::Settings,
root: &str,
folder: &str,
scripts: &[&'static str],
place: Place,
) -> GateRun {
let dir = package_dir(root, folder);
let mut ran = Vec::new();
for &script in scripts {
crate::say!("{}", announcement_line(script, place.nth, place.of, folder));
let mut cmd = Command::new(program("npm"));
cmd.args(["run", script])
.current_dir(&dir)
.stdin(Stdio::null());
super::common::strip_git_env(&mut cmd);
match super::common::status_streamed(settings, &mut cmd, super::common::Retry::Once) {
Ok(super::common::Ran::Status(status)) if status.success() => ran.push(script),
Ok(super::common::Ran::TimedOut(budget)) => {
super::common::say_timed_out(script, budget);
return GateRun::Failed;
}
Ok(_) | Err(_) => return GateRun::Failed,
}
}
GateRun::Passed(ran)
}
pub fn run(
settings: &crate::config::Settings,
refs: &[crate::pushrefs::PushRef],
manifest: &crate::manifest::Manifest,
gate: &str,
) -> Outcome {
let declared = manifest.externals.as_slice();
let zero = git::stdout(&["hash-object", "--stdin"])
.map(|h| "0".repeat(h.len()))
.unwrap_or_else(|| "0".repeat(40));
let Some(root) = git::stdout(&["rev-parse", "--show-toplevel"]) else {
super::common::warn("run-tests-js: git would not answer — the gate did NOT run");
return Outcome::Unavailable;
};
let Some(tracked) = git::stdout_paths(&["ls-files"]) else {
super::common::warn("run-tests-js: git would not answer — the gate did NOT run");
return Outcome::Unavailable;
};
let pkg_dirs = package_dirs(&tracked);
let declared_gate = gated_at_commit(settings, declared);
let mut announced: Vec<String> = Vec::new();
let mut warned: Vec<String> = Vec::new();
let mut said_why: Vec<String> = Vec::new();
let root_declaration = root_declaration(settings);
let trust = if manifest.policy_withheld.is_some() && untrusted_line_declares(&root) {
Trust::Withheld
} else {
Trust::Counted
};
let mut hinted: Vec<&'static str> = Vec::new();
let mut said_unreadable = false;
for r in refs {
let local_oid = r.local_oid.as_str();
if local_oid == zero {
continue; }
let changed = crate::pushrefs::changed_files_for(r, &zero);
let js_changed: Vec<String> = changed.iter().filter(|f| is_js(f)).cloned().collect();
let changed_dirs: Vec<String> = js_changed
.iter()
.map(|f| parent_of(f).to_string())
.collect();
if changed_dirs.is_empty() {
continue;
}
let candidates: Vec<&GateDecl> = declared_gate
.iter()
.filter(|d| d.scope.covers_all(&js_changed) && repo_opted_in(&d.scope))
.collect();
for d in &declared_gate {
if said_why.contains(&d.script) {
continue;
}
let why = if !repo_opted_in(&d.scope) {
Some(not_opted_in(&d.scope))
} else if !d.scope.covers_all(&js_changed) {
let js_scope = crate::check::Scope::files(JS_EXTS);
Some(scope_gap(d, &js_scope, &js_changed, None))
} else {
None
};
if let Some(why) = why {
say_why_not(&d.script, &why);
said_why.push(d.script.clone());
}
}
let mut already: Vec<String> = Vec::new();
if !candidates.is_empty() {
let per_commit = crate::pushrefs::commits_and_files_for(r, &zero);
let ids: Vec<String> = per_commit.iter().map(|(c, _)| c.clone()).collect();
let stamps = crate::gate_stamp::stamps_for(&ids);
for d in candidates {
let token = declared
.iter()
.find(|e| e.id == d.id)
.and_then(|e| crate::gate_identity::external_token(e, &d.script));
let Some(token) = token else {
if !said_why.contains(&d.script) {
say_why_not(&d.script, &WhyNot::Unidentified);
said_why.push(d.script.clone());
}
continue;
};
let unstamped = per_commit
.iter()
.filter(|(_, files)| d.scope.touches(files))
.filter(|(commit, _)| {
!stamps
.get(commit)
.is_some_and(|stamped| stamped.contains(&token))
})
.count();
if unstamped == 0 {
already.push(d.script.clone());
} else if !warned.contains(&d.script) {
crate::say!(
"{} {} is declared at commit time, but {unstamped} pushed \
commit{} carr{} no record of it — running it here",
crate::ui::warning_sign(),
d.script,
if unstamped == 1 { "" } else { "s" },
if unstamped == 1 { "ies" } else { "y" },
);
warned.push(d.script.clone());
}
}
}
let (run_in, _guard) = crate::pushed_tree::where_to_run(settings, local_oid, &root, gate);
let where_ = run_in.to_string_lossy().into_owned();
let folders = packages_to_test(&pkg_dirs, &changed_dirs);
if folders.iter().any(|f| f.is_empty()) {
let newly: Vec<String> = already
.iter()
.filter(|s| !announced.contains(s))
.cloned()
.collect();
if !newly.is_empty() {
crate::hooks::common::ok(
settings,
&format!(
"{} gated at commit instead — not repeating {} here",
newly.join(", "),
if newly.len() == 1 { "it" } else { "them" },
),
);
announced.extend(newly);
}
}
let already_strs: Vec<&str> = already.iter().map(String::as_str).collect();
let root_pkg = if folders.iter().any(|f| f.is_empty()) {
std::fs::read_to_string(format!("{where_}/package.json")).ok()
} else {
None
};
let root_runs: Vec<&'static str> = root_pkg
.as_deref()
.map(|pkg| gate_for(pkg, &already_strs))
.unwrap_or_default();
let covering = covering_scripts(&root_runs, &root_declaration);
let members = if covering.is_empty() {
None
} else {
super::js_workspace::members_of(std::path::Path::new(&where_))
};
if !covering.is_empty() && members.is_none() && !said_unreadable {
said_unreadable = true;
let file = if std::path::Path::new(&where_)
.join("pnpm-workspace.yaml")
.is_file()
{
"pnpm-workspace.yaml"
} else {
"package.json"
};
let mut lines = unreadable_workspace_lines(file).into_iter();
if let Some(head) = lines.next() {
crate::say!("{} {head}", crate::ui::warning_sign());
}
for rest in lines {
crate::say!("{rest}");
}
}
let coverage = RootCoverage { covering, members };
let mut plan: Vec<(String, Vec<&'static str>)> = Vec::new();
let mut skipped: Vec<(&'static str, usize)> = Vec::new();
for folder in folders {
let defined =
std::fs::read_to_string(format!("{}/package.json", package_dir(&where_, &folder)))
.map(|pkg| gate_for(&pkg, &[]))
.unwrap_or_default();
let skip: &[&str] = if folder.is_empty() {
&already_strs
} else {
coverage.skip_for(&folder)
};
let (skipped_here, to_run): (Vec<&'static str>, Vec<&'static str>) = defined
.into_iter()
.partition(|script| skip.contains(script));
if !folder.is_empty() {
for script in skipped_here {
match skipped.iter_mut().find(|(name, _)| *name == script) {
Some((_, count)) => *count += 1,
None => skipped.push((script, 1)),
}
}
}
if !to_run.is_empty() {
plan.push((folder, to_run));
}
}
let width = if std::io::stdout().is_terminal() {
LineWidth::Cut
} else {
LineWidth::Whole
};
for &script in GATE.iter() {
let Some(&(_, count)) = skipped.iter().find(|(name, _)| *name == script) else {
continue;
};
let command = root_pkg
.as_deref()
.and_then(|pkg| script_command(pkg, script));
crate::say!(
"{}",
skip_summary_line(count, script, command.as_deref(), width)
);
}
let total = plan.len();
let mut ran_in_members: Vec<(&'static str, usize)> = Vec::new();
let mut ran_at_root: Vec<&'static str> = Vec::new();
for (index, (folder, scripts)) in plan.into_iter().enumerate() {
let place = Place {
nth: index + 1,
of: total,
};
let GateRun::Passed(ran) = run_gate(settings, &where_, &folder, &scripts, place) else {
return Outcome::Failed;
};
for script in ran {
if folder.is_empty() {
ran_at_root.push(script);
} else if let Some((_, count)) =
ran_in_members.iter_mut().find(|(name, _)| *name == script)
{
*count += 1;
} else {
ran_in_members.push((script, 1));
}
}
}
if root_declaration == RootDeclaration::Unset {
for (script, members) in ran_in_members {
if ran_at_root.contains(&script) && !hinted.contains(&script) {
hinted.push(script);
let mut lines = repeat_hint_lines(script, members, trust).into_iter();
if let Some(head) = lines.next() {
crate::say!("{} {head}", crate::ui::warning_sign());
}
for rest in lines {
crate::say!("{rest}");
}
}
}
}
}
Outcome::Passed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_gate_drops_only_what_commit_already_covers() {
let pkg = r#"{"scripts":{"typecheck":"tsc","test":"vitest run"}}"#;
assert_eq!(gate_for(pkg, &[]), vec!["typecheck", "test"]);
assert_eq!(gate_for(pkg, &["typecheck"]), vec!["test"]);
assert_eq!(gate_for(pkg, &["test"]), vec!["typecheck"]);
assert!(gate_for(pkg, &["typecheck", "test"]).is_empty());
assert_eq!(gate_for(pkg, &["test:unit"]), vec!["typecheck", "test"]);
}
#[test]
fn a_scope_covers_only_when_every_changed_file_matches() {
use crate::check::Scope;
const TS_ONLY: Scope = Scope::files(&[".ts", ".tsx"]);
let all_ts: Vec<String> = vec!["src/a.ts".into(), "src/b.tsx".into()];
let mixed: Vec<String> = vec!["src/a.ts".into(), "src/legacy.js".into()];
let js_only: Vec<String> = vec!["src/legacy.js".into()];
assert!(TS_ONLY.covers_all(&all_ts));
assert!(!TS_ONLY.covers_all(&mixed));
assert!(!TS_ONLY.covers_all(&js_only));
assert!(Scope::ALWAYS.covers_all(&mixed));
assert!(TS_ONLY.covers_all(&[]));
const BY_NAME: Scope = Scope {
files: &[],
names: &["package.json"],
dirs: &[],
opt_in: &[],
not_during: &[],
};
assert!(BY_NAME.covers_all(&["apps/web/package.json".into()]));
assert!(!BY_NAME.covers_all(&["not-package.json".into()]));
}
#[test]
fn finds_scripts_only_inside_the_scripts_object() {
let pkg = r#"{"name":"x","scripts":{"test":"vitest","typecheck":"tsc"},"devDependencies":{"lint":"1"}}"#;
assert!(defines_script(pkg, "test"));
assert!(defines_script(pkg, "typecheck"));
assert!(!defines_script(pkg, "test:unit"));
assert!(!defines_script(pkg, "lint"));
}
#[test]
fn survives_nested_objects_and_escaped_quotes() {
let pkg = r#"{"scripts":{"test":"echo \"hi\"","build":"x"},"other":{"test":"no"}}"#;
assert!(defines_script(pkg, "test"));
assert!(defines_script(pkg, "build"));
assert!(!defines_script(pkg, "other"));
}
#[test]
fn no_scripts_object_means_no_scripts() {
assert!(!defines_script(r#"{"name":"x"}"#, "test"));
}
#[test]
fn a_scripts_string_elsewhere_cannot_anchor_the_scan() {
let pkg = r#"{"files":["scripts"],"dependencies":{"test":"1.0"},"scripts":{"build":"x"}}"#;
assert!(
!defines_script(pkg, "test"),
"a dependency answered as a script"
);
assert!(
defines_script(pkg, "build"),
"the real scripts object was skipped"
);
let pkg =
r#"{"description":"scripts","dependencies":{"test":"1.0"},"scripts":{"build":"x"}}"#;
assert!(!defines_script(pkg, "test"));
assert!(defines_script(pkg, "build"));
let pkg = r#"{"config":{"scripts":{"test":"inner"}},"scripts":{"build":"x"}}"#;
assert!(!defines_script(pkg, "test"));
assert!(defines_script(pkg, "build"));
}
#[test]
fn a_non_object_scripts_value_defines_nothing() {
assert!(!defines_script(r#"{"scripts":"echo hi"}"#, "test"));
assert!(!defines_script(
r#"{"scripts":"x","other":{"test":"y"}}"#,
"test"
));
}
#[test]
fn collects_package_directories() {
let ls: Vec<String> = [
"package.json",
"apps/web/package.json",
"apps/web/src/a.ts",
"README.md",
]
.into_iter()
.map(String::from)
.collect();
assert_eq!(
package_dirs(&ls),
vec!["".to_string(), "apps/web".to_string()]
);
}
#[test]
fn selects_only_packages_containing_a_change() {
let pkgs = vec!["apps/web".to_string(), "apps/api".to_string()];
let changed = vec!["apps/web/src".to_string()];
assert_eq!(
packages_to_test(&pkgs, &changed),
vec!["apps/web".to_string()]
);
}
#[test]
fn the_repo_root_package_matches_any_change() {
let pkgs = vec!["".to_string()];
assert_eq!(
packages_to_test(&pkgs, &["src".to_string()]),
vec!["".to_string()]
);
}
fn every_reason(path: &str) -> Vec<WhyNot> {
vec![
WhyNot::ScopeGap {
scope: "*.rs".into(),
uncovered: vec![path.into()],
cause: GapCause::Files,
at: Some(3),
},
WhyNot::Warn,
WhyNot::Skipped,
WhyNot::NotOptedIn(vec!["marker".into()]),
WhyNot::Unidentified,
]
}
#[test]
fn every_reason_fits_its_line_and_keeps_its_ending() {
for why in every_reason("rustfmt.toml") {
let head = &reason_lines("cargo-test", &why, LineWidth::Whole)[0];
assert!(head.chars().count() + 2 <= 80, "{head}");
assert!(head.ends_with("— running it here"), "{head}");
}
}
#[test]
fn on_a_terminal_only_the_variable_part_is_cut() {
let long = "crates/a/very/deep/package/directory/src/components/widgets/Button.stories.tsx";
for why in every_reason(long) {
let head = &reason_lines("cargo-test", &why, LineWidth::Cut)[0];
assert!(head.chars().count() + 2 <= 80, "{head}");
assert!(head.ends_with("— running it here"), "{head}");
}
let name = "a-rather-long-check-name-indeed-for-a-gate";
for why in [
WhyNot::Warn,
WhyNot::Skipped,
WhyNot::NotOptedIn(vec!["marker".into()]),
WhyNot::Unidentified,
] {
let head = &reason_lines(name, &why, LineWidth::Cut)[0];
assert!(head.chars().count() + 2 <= 80, "{head}");
assert!(head.ends_with("— running it here"), "{head}");
}
}
#[test]
fn piped_nothing_is_cut() {
let long = "crates/a/very/deep/package/directory/src/components/widgets/Button.stories.tsx";
let why = WhyNot::ScopeGap {
scope: "*.rs".into(),
uncovered: vec![long.into()],
cause: GapCause::Files,
at: None,
};
assert!(reason_lines("cargo-test", &why, LineWidth::Whole)[0].contains(long));
}
#[test]
fn values_from_the_manifest_are_sanitised() {
let why = WhyNot::NotOptedIn(vec!["mark\u{1b}[31mer".into()]);
let head = &reason_lines("cargo-test", &why, LineWidth::Whole)[0];
assert!(!head.contains('\u{1b}'), "{head:?}");
}
#[test]
fn a_scripts_command_is_read_when_it_is_a_plain_string() {
let pkg = r#"{"name":"r","scripts":{"build":"tsc","test":"pnpm -r --workspace-concurrency=2 test"}}"#;
assert_eq!(
script_command(pkg, "test").as_deref(),
Some("pnpm -r --workspace-concurrency=2 test")
);
assert_eq!(script_command(pkg, "typecheck"), None, "absent");
let escaped = r#"{"scripts":{"test":"echo \"x\""}}"#;
assert_eq!(
script_command(escaped, "test"),
None,
"an escape is not guessed at"
);
let elsewhere = r#"{"dependencies":{"test":"1.0.0"},"scripts":{}}"#;
assert_eq!(
script_command(elsewhere, "test"),
None,
"only the scripts object"
);
}
#[test]
fn the_repeat_hint_fits_its_line_and_names_the_fix() {
for script in crate::manifest::NPM_GATE_SCRIPTS {
let lines = repeat_hint_lines(script, 30, Trust::Counted);
assert!(lines[0].chars().count() + 2 <= 80, "{}", lines[0]);
assert!(lines[0].contains("a repeat if the root runs them"));
assert!(
lines[1].contains(&format!("set rootRunsMembers {script}")),
"{}",
lines[1]
);
for line in &lines[1..] {
assert!(line.chars().count() <= 80, "{line}");
}
}
let one = repeat_hint_lines("test", 1, Trust::Counted);
assert!(one[0].contains("in 1 package —"), "{}", one[0]);
let withheld = repeat_hint_lines("test", 2, Trust::Withheld);
assert!(withheld[1].contains("is not trusted"), "{}", withheld[1]);
assert!(withheld[2].contains("trust"), "{}", withheld[2]);
for line in &withheld[1..] {
assert!(line.chars().count() <= 80, "{line}");
assert!(!line.contains("declare it in"), "{line}");
}
}
#[test]
fn the_skip_summary_fits_its_line() {
for script in crate::manifest::NPM_GATE_SCRIPTS {
for count in [1, 30, 100, 1000] {
let line = skip_summary_line(count, script, Some("pnpm -r test"), LineWidth::Cut);
assert!(line.chars().count() <= LINE_COLUMNS, "{line}");
}
let head = skip_summary_line(30, script, None, LineWidth::Cut);
assert!(head.chars().count() <= 80, "{head}");
assert!(head.contains("30 packages skipped"), "{head}");
let cut = skip_summary_line(30, script, Some(&"x".repeat(200)), LineWidth::Cut);
assert!(cut.chars().count() <= 80, "{cut}");
assert!(cut.contains("covered by the root's"), "{cut}");
assert!(cut.ends_with(": …"), "{cut}");
}
assert!(
skip_summary_line(1, "test", None, LineWidth::Whole).starts_with("1 package skipped")
);
}
const SIGN_COLUMNS: usize = 2;
#[test]
fn a_non_object_scripts_key_is_not_replaced_by_a_nested_one() {
let pkg = r#"{"scripts":"none","other":{"scripts":{"test":"x"}}}"#;
assert_eq!(scripts_object(pkg), None);
assert!(!defines_script(pkg, "test"));
}
#[test]
fn the_unreadable_workspace_lines_fit_and_name_the_file() {
for file in ["package.json", "pnpm-workspace.yaml"] {
let lines = unreadable_workspace_lines(file);
assert!(
lines[0].chars().count() + SIGN_COLUMNS <= LINE_COLUMNS,
"{}",
lines[0]
);
assert!(lines[1].chars().count() <= LINE_COLUMNS, "{}", lines[1]);
assert!(lines[1].contains(file), "{}", lines[1]);
}
}
#[test]
fn the_announcement_names_its_place() {
assert_eq!(
announcement_line("test", 1, 3, ""),
"npm run test: 1 of 3, in the root"
);
assert_eq!(
announcement_line("test", 2, 3, "packages/a"),
"npm run test: 2 of 3, in packages/a"
);
assert!(!announcement_line("test", 2, 3, "a\u{1b}[31mb").contains('\u{1b}'));
}
#[test]
fn a_local_value_only_removes_what_is_committed() {
use RootDeclaration::{Declared, Unset};
assert_eq!(
declared_from(Some("test,typecheck"), Some("test")),
Declared(vec!["test"])
);
assert_eq!(declared_from(Some("test"), Some("none")), Declared(vec![]));
assert_eq!(declared_from(Some("none"), Some("test")), Declared(vec![]));
assert_eq!(declared_from(None, Some("none")), Declared(vec![]));
assert_eq!(declared_from(None, Some("test")), Unset);
assert_eq!(declared_from(None, None), Unset);
assert_eq!(declared_from(Some("test"), None), Declared(vec!["test"]));
assert_eq!(
declared_from(Some("test,bogus"), None),
Declared(vec!["test"])
);
}
#[test]
fn only_declared_root_scripts_cover() {
let declared = RootDeclaration::Declared(vec!["test"]);
assert_eq!(
covering_scripts(&["test", "typecheck"], &declared),
vec!["test"]
);
assert!(covering_scripts(&["test"], &RootDeclaration::Unset).is_empty());
}
#[test]
fn nothing_declared_is_unset() {
let settings = crate::config::Settings::default();
assert_eq!(root_declaration(&settings), RootDeclaration::Unset);
}
}