use std::collections::HashMap;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::process::{ChildStderr, Command, ExitStatus, Stdio};
use std::time::{Instant, SystemTime};
use anyhow::{Context, Result};
use super::plan::{GatePlan, Unit, What};
use super::{Fault, Mode};
use crate::config::Layer;
use crate::evidence;
use crate::facts::{Outcome, Run};
use crate::lock::{self, Line};
use crate::mutation::{self, Outcomes};
use crate::steps::{self, Base, Kind, MutationPlan, Step};
use crate::{laws, TOOL_LOCK};
pub(crate) struct Prepared {
pub(crate) judge: Option<laws::Judge>,
}
struct Clock {
began: SystemTime,
watch: Instant,
}
impl Clock {
fn start() -> Self {
Self {
began: SystemTime::now(),
watch: Instant::now(),
}
}
}
pub(crate) struct Timing {
pub(crate) layer: String,
pub(crate) began: SystemTime,
pub(crate) seconds: f64,
pub(crate) tool_version: Option<String>,
}
pub(crate) struct Executed<'a> {
pub(crate) started: SystemTime,
pub(crate) runs: Vec<Run>,
pub(crate) timing: Vec<Timing>,
pub(crate) shared: Vec<(&'a str, &'static str)>,
pub(crate) not_run: Vec<String>,
pub(crate) listed: usize,
pub(crate) found: Option<Result<Outcomes, String>>,
}
pub(crate) fn prepare(dir: &Path, plan: &GatePlan<'_>, mode: Mode) -> Result<Prepared, Fault> {
if !plan.laws_on || mode == Mode::DryRun {
return Ok(Prepared { judge: None });
}
match laws::ensure_bend(dir) {
Ok(judge) => Ok(Prepared { judge: Some(judge) }),
Err(msg) => {
println!("\nfail: {msg}");
Err(Fault::announced(msg))
}
}
}
const CARGO_BUILTINS: [&str; 6] = ["test", "build", "check", "doc", "run", "bench"];
fn version_of(dir: &Path, argv: &[String], cache: &mut Answers) -> Option<String> {
let (program, rest) = argv.split_first()?;
ask_cached(
dir,
&version_ask(program, rest.first().map(String::as_str)),
cache,
)
.ok()
.filter(|line| !line.is_empty())
}
type Answers = HashMap<String, Result<String, String>>;
fn ask_cached(dir: &Path, asks: &[&str], cache: &mut Answers) -> Result<String, String> {
cache
.entry(asks.join(" "))
.or_insert_with(|| {
lock::run_probe(dir, asks, lock::PROBE_LIMIT).map(|out| {
out.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.unwrap_or_default()
.to_string()
})
})
.clone()
}
fn version_ask<'a>(program: &'a str, first: Option<&'a str>) -> Vec<&'a str> {
match (program, first) {
("cargo", Some(sub)) if !sub.starts_with('-') && !CARGO_BUILTINS.contains(&sub) => {
vec!["cargo", sub, "--version"]
}
("cargo", _) => vec!["cargo", "--version"],
(other, _) => vec![other, "--version"],
}
}
fn first_tool(chain: &[Step]) -> Option<&[String]> {
chain
.iter()
.find(|step| step.kind == Kind::Tool)
.map(|step| step.argv.as_slice())
}
pub(crate) fn run<'a>(dir: &Path, plan: &GatePlan<'a>, mode: Mode) -> Result<Executed<'a>, Fault> {
let mut runner = Runner {
dir,
plan,
live: mode == Mode::Run,
done: Executed {
started: SystemTime::now(),
runs: Vec::new(),
timing: Vec::new(),
shared: Vec::new(),
not_run: Vec::new(),
listed: 0,
found: None,
},
versions: HashMap::new(),
asked: HashMap::new(),
};
for warning in &plan.pin_warnings {
println!("{warning}");
}
for unit in &plan.units {
if !runner.pinned_tools_stop(unit.layer) {
runner.unit(unit)?;
}
}
if runner.live {
runner.take_shared();
} else {
runner.list_laws();
}
Ok(runner.done)
}
struct Runner<'p, 'a> {
dir: &'p Path,
plan: &'p GatePlan<'a>,
live: bool,
done: Executed<'a>,
versions: Answers,
asked: HashMap<&'static str, Line>,
}
impl<'a> Runner<'_, 'a> {
fn unit(&mut self, unit: &Unit<'a>) -> Result<(), Fault> {
let layer = unit.layer;
match &unit.what {
What::Shared(from) => self.shared(layer, from),
What::NotRun => self.not_run(layer),
What::Mutation(mutation) => self.mutation(layer, mutation)?,
What::Chains(chains) => {
for chain in chains {
self.chain(layer, chain)?;
}
}
}
Ok(())
}
fn pinned_tools_stop(&mut self, layer: &Layer) -> bool {
let pins = self.plan.pins_of(&layer.id);
if pins.is_empty() {
return false;
}
let named: Vec<String> = pins
.iter()
.map(|(row, pin)| format!("{} {pin}", row.key))
.collect();
println!(
"\n==> [{}] {TOOL_LOCK} pins, asked first: {}",
layer.id,
named.join(", ")
);
if !self.live {
return false;
}
let clock = Clock::start();
let Some(run) = self.ask_pins(layer) else {
return false;
};
self.done.record(run, &clock, None);
true
}
fn ask_pins(&mut self, layer: &Layer) -> Option<Run> {
let dir = self.dir;
let mut stops = Vec::new();
for (row, pin) in self.plan.pins_of(&layer.id) {
let line = self.asked.entry(row.key).or_insert_with(|| {
lock::check_row(row, pin, &mut |argv| {
ask_cached(dir, argv, &mut self.versions)
})
});
stops.extend(line.stop());
}
let first = stops.first()?;
let note: Vec<&str> = stops.iter().map(|stop| stop.text.as_str()).collect();
let outcome = if stops.iter().any(|stop| stop.mismatch) {
Outcome::ToolMismatch
} else {
Outcome::ToolMissing
};
Some(pin_stop_run(
&layer.id,
outcome,
&first.asked,
note.join("; "),
))
}
fn shared(&mut self, layer: &'a Layer, from: &'static str) {
println!(
"\n==> [{}] no command of its own: it takes the {from} run's outcome",
layer.id
);
self.done.shared.push((&layer.id, from));
}
fn not_run(&mut self, layer: &Layer) {
let tier = crate::tiers::tier_for(layer);
println!(
"\nNotRun [{}]: enabled at tier {tier} (<= --max-tier {}) and no command is mapped",
layer.id, self.plan.max_tier
);
self.done.not_run.push(format!(
"{}: NotRun (enabled at tier {tier}, no command mapped; disable it or lower --max-tier)",
layer.id
));
}
fn mutation(&mut self, layer: &Layer, mutation: &MutationPlan) -> Result<(), Fault> {
println!(
"\n==> [{}] {} && {}",
layer.id,
mutation.diff.display(),
mutation.mutants.display()
);
self.done.listed += 1;
if self.live {
let clock = Clock::start();
let Mutated { run, found } =
run_mutation(self.dir, &layer.id, mutation).map_err(Fault::env)?;
self.done.found = found;
let version = (run.outcome != Outcome::ToolMissing
&& run.cmd.contains(&mutation.mutants.display()))
.then(|| version_of(self.dir, &mutation.mutants.argv, &mut self.versions))
.flatten();
self.done.record(run, &clock, version);
}
Ok(())
}
fn chain(&mut self, layer: &Layer, chain: &[Step]) -> Result<(), Fault> {
println!(
"\n==> [{}] {}",
layer.id,
chain
.iter()
.map(Step::display)
.collect::<Vec<_>>()
.join(" && ")
);
self.done.listed += 1;
if !self.live {
return Ok(());
}
let clock = Clock::start();
let run = run_chain(self.dir, &layer.id, chain).map_err(Fault::env)?;
let version = first_tool(chain)
.filter(|_| run.outcome != Outcome::ToolMissing)
.filter(|_| layer.id != "crap" || !self.plan.pins_of("crap").is_empty())
.and_then(|argv| version_of(self.dir, argv, &mut self.versions));
self.done.record(run, &clock, version);
Ok(())
}
fn list_laws(&self) {
if self.plan.laws_on {
println!(
"\n==> [laws] sh {} (only if Bend from {} is not installed)",
laws::FETCH,
laws::LOCK
);
println!(
"\n==> [laws] bend {}/cases.bend",
laws::report_display(self.dir)
);
}
}
fn credited(&self, layer: &str, from: &str) -> Run {
let mut run = self.plan.tests.take(layer, from, &self.done.runs);
let Some(filter) = self.plan.filters.for_layer(layer) else {
return run;
};
if run.outcome != Outcome::Passed {
return run;
}
let root = laws::workspace_root(self.dir).unwrap_or_else(|| self.dir.to_path_buf());
let since = self
.done
.timing
.iter()
.find(|timing| timing.layer == from)
.map_or(self.done.started, |timing| timing.began);
if let Err(why) = evidence::credit(layer, &root, filter, since) {
run.outcome = Outcome::Failed;
run.note = Some(why);
}
run
}
fn take_shared(&mut self) {
for (layer, from) in self.done.shared.clone() {
let run = self.credited(layer, from);
match &run.note {
Some(note) => {
println!("[{layer}] took the {from} run, but it is no credit: {note}");
}
None => println!("[{layer}] took the {from} run's outcome: {}", run.outcome),
}
self.done.runs.push(run);
self.done.timing.push(Timing {
layer: layer.to_string(),
began: SystemTime::now(),
seconds: 0.0,
tool_version: None,
});
}
}
}
impl Executed<'_> {
fn record(&mut self, run: Run, clock: &Clock, tool_version: Option<String>) {
self.timing.push(Timing {
layer: run.layer.clone(),
began: clock.began,
seconds: clock.watch.elapsed().as_secs_f64(),
tool_version,
});
self.runs.push(run);
}
pub(crate) fn seconds(&self, layer: &str) -> f64 {
self.timing
.iter()
.filter(|timing| timing.layer == layer)
.map(|timing| timing.seconds)
.sum::<f64>()
+ 0.0
}
pub(crate) fn tool_version(&self, layer: &str) -> Option<String> {
let mut seen: Vec<&str> = Vec::new();
for version in self
.timing
.iter()
.filter(|timing| timing.layer == layer)
.filter_map(|timing| timing.tool_version.as_deref())
{
if !seen.contains(&version) {
seen.push(version);
}
}
(!seen.is_empty()).then(|| seen.join("; "))
}
}
pub(crate) fn finish(layer: &str, ran: &[String], outcome: Outcome) -> Run {
Run {
layer: layer.to_string(),
cmd: ran.join(" && "),
step: ran.last().cloned().unwrap_or_default(),
outcome,
note: None,
}
}
pub(crate) fn run_chain(dir: &Path, layer: &str, chain: &[Step]) -> Result<Run> {
let mut ran = Vec::new();
let mut outcome = Outcome::Passed;
for step in chain {
ran.push(step.display());
outcome = run_step(dir, step)?;
if !steps::chain_continues(outcome) {
break;
}
}
Ok(finish(layer, &ran, outcome))
}
fn pin_stop_run(layer: &str, outcome: Outcome, asked: &str, note: String) -> Run {
let label = if outcome == Outcome::ToolMismatch {
"tool-mismatch"
} else {
"tool-missing"
};
println!("{label} [{layer}]: {note}");
Run {
layer: layer.to_string(),
cmd: String::new(),
step: asked.to_string(),
outcome,
note: Some(note),
}
}
pub(crate) struct Mutated {
pub(crate) run: Run,
pub(crate) found: Option<Result<Outcomes, String>>,
}
impl Mutated {
fn without_outcomes(run: Run) -> Self {
Self { run, found: None }
}
}
pub(crate) fn run_mutation(dir: &Path, layer: &str, plan: &MutationPlan) -> Result<Mutated> {
if let Err(missing) = steps::check_tool(&plan.mutants.argv) {
println!("{missing}");
return Ok(Mutated::without_outcomes(finish(
layer,
&[plan.mutants.display()],
Outcome::ToolMissing,
)));
}
if matches!(plan.base, Base::Unresolved { .. }) {
return Ok(Mutated::without_outcomes(stopped(
layer,
&[],
&plan.base,
Outcome::Failed,
)));
}
let mut ran = vec![plan.diff.display()];
let diff_ok = run_step(dir, &plan.diff)? == Outcome::Passed;
let diff = steps::judge_diff(diff_ok, &plan.diff_path);
let Some(mutants) = plan.after_diff(diff) else {
return Ok(Mutated::without_outcomes(stopped(
layer, &ran, &plan.base, diff,
)));
};
ran.push(mutants.display());
mutation::clear(&plan.output)?;
let ended = run_mutants(dir, mutants)?;
Ok(settled(
finish(layer, &ran, ended.outcome),
&ended,
&plan.output,
))
}
fn settled(mut run: Run, ended: &Ended, output: &Path) -> Mutated {
if ended.outcome != Outcome::Passed {
run.note = (ended.outcome == Outcome::Failed)
.then(|| format!("`{}` {}", run.step, exit_meaning(ended.code)));
return Mutated::without_outcomes(run);
}
let found = mutation::read(output, ended.code.unwrap_or_default(), &ended.stderr);
if let Err(why) = &found {
run.outcome = Outcome::Failed;
run.note = Some(why.clone());
}
Mutated {
run,
found: Some(found),
}
}
fn exit_meaning(code: Option<i32>) -> String {
match code {
Some(1) => "exited 1: it was given arguments it does not accept".to_string(),
Some(4) => {
"exited 4: the tests fail in the unmutated tree, so no mutant was tested".to_string()
}
Some(code) => format!("exited {code}"),
None => "was ended by a signal".to_string(),
}
}
fn stopped(layer: &str, ran: &[String], base: &Base, diff: Outcome) -> Run {
let (outcome, note) = steps::stop_note(base, diff)
.unwrap_or_else(|| (diff, format!("the mutation diff ended as {diff}")));
println!("{outcome}: {note}");
let command_failed = diff == Outcome::Failed && !matches!(base, Base::Unresolved { .. });
let kept = match ran.last() {
Some(step) if command_failed => format!("`{step}` failed: {note}"),
_ => note,
};
Run {
note: Some(kept),
..finish(layer, ran, outcome)
}
}
pub(crate) fn run_step(dir: &Path, step: &Step) -> Result<Outcome> {
match step.kind {
Kind::Artifact => {
return Ok(step.artifact_path().map_or(Outcome::Failed, |path| {
steps::artifact_outcome(&dir.join(path))
}));
}
Kind::Tool => {
if let Err(missing) = steps::check_tool(&step.argv) {
println!("{missing}");
return Ok(Outcome::ToolMissing);
}
}
Kind::Command => {}
}
Ok(match spawn(dir, step)? {
Spawned::Exited(status) if status.success() => Outcome::Passed,
Spawned::Exited(_) | Spawned::NoProgram => Outcome::Failed,
Spawned::Missing => Outcome::ToolMissing,
})
}
struct Ended {
outcome: Outcome,
code: Option<i32>,
stderr: String,
}
impl Ended {
fn without_output(outcome: Outcome) -> Self {
Self {
outcome,
code: None,
stderr: String::new(),
}
}
}
fn run_mutants(dir: &Path, step: &Step) -> Result<Ended> {
let Some((program, args)) = step.program() else {
return Ok(Ended::without_output(Outcome::Failed));
};
let mut child = match Command::new(program)
.args(args)
.current_dir(dir)
.stderr(Stdio::piped())
.spawn()
{
Ok(child) => child,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
println!(
"{}",
steps::MissingTool {
binary: program.to_string()
}
);
return Ok(Ended::without_output(Outcome::ToolMissing));
}
Err(err) => return Err(err).with_context(|| format!("spawn: {}", step.display())),
};
let stderr = tee(child.stderr.take());
let status = child
.wait()
.with_context(|| format!("wait: {}", step.display()))?;
let code = status.code();
let outcome = if matches!(code, Some(0 | 2 | 3)) {
Outcome::Passed
} else {
Outcome::Failed
};
Ok(Ended {
outcome,
code,
stderr,
})
}
fn tee(pipe: Option<ChildStderr>) -> String {
let Some(pipe) = pipe else {
return String::new();
};
let mut kept = String::new();
for line in BufReader::new(pipe).split(b'\n').map_while(Result::ok) {
let line = String::from_utf8_lossy(&line).into_owned();
eprintln!("{line}");
kept.push_str(&line);
kept.push('\n');
}
kept
}
enum Spawned {
Exited(ExitStatus),
Missing,
NoProgram,
}
fn spawn(dir: &Path, step: &Step) -> Result<Spawned> {
let Some((program, args)) = step.program() else {
return Ok(Spawned::NoProgram);
};
match Command::new(program).args(args).current_dir(dir).status() {
Ok(status) => Ok(Spawned::Exited(status)),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
println!(
"{}",
steps::MissingTool {
binary: program.to_string()
}
);
Ok(Spawned::Missing)
}
Err(err) => Err(err).with_context(|| format!("spawn: {}", step.display())),
}
}
#[cfg(test)]
mod tests {
use super::{exit_meaning, run_mutants, run_step, version_ask, Executed, Timing};
use crate::facts::Outcome;
use crate::steps::Step;
use std::fs;
use std::path::Path;
use std::time::SystemTime;
#[test]
fn a_plugin_asks_itself_and_a_built_in_asks_cargo() {
assert_eq!(
version_ask("cargo", Some("deny")),
["cargo", "deny", "--version"]
);
for built_in in ["test", "build", "check", "doc", "run", "bench"] {
assert_eq!(
version_ask("cargo", Some(built_in)),
["cargo", "--version"],
"{built_in}"
);
}
assert_eq!(
version_ask("cargo", Some("--version")),
["cargo", "--version"]
);
assert_eq!(version_ask("cargo", None), ["cargo", "--version"]);
assert_eq!(version_ask("bend", Some("run")), ["bend", "--version"]);
}
fn timing(layer: &str, seconds: f64) -> Timing {
Timing {
layer: layer.to_string(),
began: SystemTime::UNIX_EPOCH,
seconds,
tool_version: None,
}
}
#[test]
fn a_layer_is_timed_over_its_own_commands_only() {
let done = Executed {
started: SystemTime::now(),
runs: Vec::new(),
timing: vec![timing("a", 1.5), timing("b", 4.0), timing("a", 2.0)],
shared: Vec::new(),
not_run: Vec::new(),
listed: 0,
found: None,
};
assert!((done.seconds("a") - 3.5).abs() < 1e-9);
assert!((done.seconds("b") - 4.0).abs() < 1e-9);
assert!(done.seconds("c").abs() < 1e-9 && done.seconds("c").is_sign_positive());
}
#[test]
fn a_missing_program_is_a_missing_tool_and_any_other_spawn_error_is_not() {
let dir = std::env::temp_dir().join(format!("cargo-tops-exec-{}", std::process::id()));
fs::remove_dir_all(&dir).ok();
fs::create_dir_all(&dir).expect("mkdir");
let missing = Step::command([dir.join("no-such-program").display().to_string()]);
assert_eq!(
run_step(Path::new("."), &missing).expect("a missing program is an outcome"),
Outcome::ToolMissing
);
let plain = dir.join("plain");
fs::write(&plain, "x").expect("write");
let blocked = Step::command([plain.display().to_string()]);
let err = run_step(Path::new("."), &blocked).expect_err("not spawnable");
assert!(format!("{err:#}").contains("spawn"), "{err:#}");
fs::remove_dir_all(&dir).ok();
}
#[test]
fn cargo_mutants_exits_0_2_and_3_are_a_finished_run() {
let wants = [
(0, Outcome::Passed),
(1, Outcome::Failed),
(2, Outcome::Passed),
(3, Outcome::Passed),
(4, Outcome::Failed),
(101, Outcome::Failed),
];
for (code, want) in wants {
let step = Step::command(["sh".to_string(), "-c".to_string(), format!("exit {code}")]);
let got = run_mutants(Path::new("."), &step).expect("it ran");
assert_eq!(got.outcome, want, "exit {code}");
assert_eq!(got.code, Some(code), "exit {code}");
let plain = run_step(Path::new("."), &step).expect("it ran");
let plain_want = if code == 0 {
Outcome::Passed
} else {
Outcome::Failed
};
assert_eq!(plain, plain_want, "exit {code}");
}
let nowhere = Step::command(["/no/such/program/here"]);
assert_eq!(
run_mutants(Path::new("."), &nowhere)
.expect("an outcome")
.outcome,
Outcome::ToolMissing
);
}
#[test]
fn a_mutants_spawn_error_is_an_error_and_a_signal_is_named() {
let dir = std::env::temp_dir().join(format!("cargo-tops-mutexec-{}", std::process::id()));
fs::remove_dir_all(&dir).ok();
fs::create_dir_all(&dir).expect("mkdir");
let plain = dir.join("plain");
fs::write(&plain, "x").expect("write");
let blocked = Step::command([plain.display().to_string()]);
let err = run_mutants(Path::new("."), &blocked)
.err()
.expect("not spawnable");
assert!(format!("{err:#}").contains("spawn"), "{err:#}");
fs::remove_dir_all(&dir).ok();
let killed = Step::command(["sh".to_string(), "-c".to_string(), "kill -9 $$".to_string()]);
let ended = run_mutants(Path::new("."), &killed).expect("it ran");
assert_eq!((ended.outcome, ended.code), (Outcome::Failed, None));
assert!(exit_meaning(None).contains("signal"));
assert!(exit_meaning(Some(4)).contains("unmutated tree"));
assert!(exit_meaning(Some(1)).contains("exited 1"));
assert_eq!(exit_meaning(Some(77)), "exited 77");
}
}