use super::common::program;
use crate::check::Outcome;
use crate::git;
use std::io::IsTerminal;
use std::process::{Command, Stdio};
const GATE: [&str; 3] = ["typecheck", "test:unit", "test"];
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> {
let bytes = pkg_json.as_bytes();
let mut depth = 0usize;
let mut i = 0usize;
while i < bytes.len() {
match bytes[i] {
b'"' => {
let start = i + 1;
let close = string_end(bytes, start)?;
let content = &pkg_json[start..close];
i = close + 1;
if depth != 1 {
continue;
}
let mut j = i;
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
if j >= bytes.len() || bytes[j] != b':' {
continue; }
if content != "scripts" {
continue;
}
let mut k = j + 1;
while k < bytes.len() && bytes[k].is_ascii_whitespace() {
k += 1;
}
if k >= bytes.len() || bytes[k] != b'{' {
return None;
}
let end = object_end(bytes, k)?;
return Some(&pkg_json[k..=end]);
}
b'{' | b'[' => {
depth += 1;
i += 1;
}
b'}' | b']' => {
depth = depth.saturating_sub(1);
i += 1;
}
_ => i += 1,
}
}
None
}
fn string_end(bytes: &[u8], from: usize) -> Option<usize> {
let mut escaped = false;
for (i, &c) in bytes.iter().enumerate().skip(from) {
if escaped {
escaped = false;
} else if c == b'\\' {
escaped = true;
} else if c == b'"' {
return Some(i);
}
}
None
}
fn object_end(bytes: &[u8], open: usize) -> Option<usize> {
let mut depth = 0usize;
let mut i = open;
while i < bytes.len() {
match bytes[i] {
b'"' => i = string_end(bytes, i + 1)?,
b'{' => depth += 1,
b'}' => {
depth -= 1;
if depth == 0 {
return Some(i);
}
}
_ => {}
}
i += 1;
}
None
}
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()
}
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()
}
fn run_gate(
settings: &crate::config::Settings,
root: &str,
folder: &str,
already: &[&str],
) -> bool {
let dir = if folder.is_empty() {
root.to_string()
} else {
format!("{root}/{folder}")
};
let Ok(pkg) = std::fs::read_to_string(format!("{dir}/package.json")) else {
return true;
};
for script in gate_for(&pkg, already) {
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() => {}
Ok(super::common::Ran::TimedOut(budget)) => {
super::common::say_timed_out(script, budget);
return false;
}
Ok(_) | Err(_) => return false,
}
}
true
}
pub fn run(
settings: &crate::config::Settings,
refs: &[crate::pushrefs::PushRef],
declared: &[crate::manifest::External],
gate: &str,
) -> Outcome {
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();
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();
for folder in folders {
let already_here: &[&str] = if folder.is_empty() {
&already_strs
} else {
&[]
};
if !run_gate(settings, &where_, &folder, already_here) {
return Outcome::Failed;
}
}
}
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:?}");
}
}