use serde_json::json;
use supercov_engine::{
agent_json::{AgentError, ErrorCode},
coverage_query::{DecisionSort, MinimizeMetric},
indexed_query::IndexedQueryRequest,
};
const DEFAULT_LIMIT: usize = 20;
const DEFAULT_MAX_STATES: usize = 5_000;
const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
pub fn help_for(command: &str, arguments: &[String]) -> Option<String> {
if !arguments
.iter()
.any(|argument| matches!(argument.as_str(), "--help" | "-h"))
{
return None;
}
if command == "diff" {
return Some(
"Usage: supercov diff <older-run> <newer-run> [options]\n\nOptions:\n --filter <all|passed|failed>\n --kind <kind>\n --runner <runner>\n --tag <tag> only tests with this tag (@e2e, a pytest marker, a JUnit @Tag); repeat for any of several; \'!api\' leaves those out\n --title <text> only tests whose name contains this\n --test-file <path> only tests in this file or directory\n --metric <metric>\n --gained only what the newer run covers that the older did not\n --offset <n>\n --limit <n> entries per page (default 20; 0 for all); a page names the --limit that shows all\n --json\n"
.into(),
);
}
let run = arguments
.first()
.filter(|argument| !argument.starts_with('-'));
let Some(_) = run else {
return Some(
"Usage: supercov runs [options]\n supercov runs <run-id> [query]\n\nLists runs and lazily calculates their coverage summaries.\n\nOptions:\n --filter <all|passed|failed>\n --offset <n>\n --limit <n> entries per page (default 20; 0 for all); a page names the --limit that shows all\n --json\n"
.into(),
);
};
let child = arguments
.get(1)
.filter(|argument| !argument.starts_with('-'))
.map(String::as_str);
let Some(child) = child else {
return Some(
"Usage: supercov runs <run-id> [query] [options]\n\nWithout a query, prints the run's coverage summary.\n\nQueries:\n files every included file, including fully covered files; --group dir for coverage by directory\n gaps only files with unresolved coverage or measurement gaps\n file <path> gap lines with consolidated obligations\n line <file:line> line state, obligations, tests and phases\n decision <location> MC/DC vectors and witness pairs for one decision\n test <id|name> coverage attributed to one test\n kinds coverage grouped by unit/component/integration/e2e\n runners coverage grouped by test runner\n scope what is source and what is not, by directory; --files lists every file\n minimize smallest test set for a coverage target\n tests affected tests the changes since the run could have reached\n tests without-evidence tests that made assertions and recorded no coverage\n assertions how much executed code the tests assert; see runs <run-id> assertions --help\n mutants how far the tests got toward killing each mutant; see runs <run-id> mutants --help\n\nCommon options:\n --filter <all|passed|failed> recalculate coverage from those attempts only\n --kind <kind>\n --runner <runner>\n --tag <tag> only tests with this tag (@e2e, a pytest marker, a JUnit @Tag); repeat for any of several; \'!api\' leaves those out\n --title <text> only tests whose name contains this\n --test-file <path> only tests in this file or directory\n --offset <n>\n --limit <n> entries per page (default 20; 0 for all); a page names the --limit that shows all\n --json\n\nRun any query with --help for its exact usage.\n"
.replace(" minimize ", " source <path> matching current source with line numbers\n minimize "),
);
};
let usage = match child {
"summary" => {
"supercov runs <run-id> [--filter <all|passed|failed>] [--kind <kind>] [--runner <runner>] [--tag <tag>] [--title <text>] [--test-file <path>] [--json]"
}
"files" => {
"supercov runs <run-id> files [--group dir [--depth <n>]] [--metric <all|lines|statements|functions|branches|mcdc>] [--filter <all|passed|failed>] [--kind <kind>] [--runner <runner>] [--tag <tag>] [--title <text>] [--test-file <path>] [--offset <n>] [--limit <n>] [--json]"
}
"gaps" => {
"supercov runs <run-id> gaps [--metric <all|lines|statements|functions|branches|mcdc>] [--filter <all|passed|failed>] [--kind <kind>] [--runner <runner>] [--tag <tag>] [--title <text>] [--test-file <path>] [--offset <n>] [--limit <n>] [--json]\n supercov runs <run-id> gaps --format jsonl [--metric <metric>] [--filter <all|passed|failed>] [--kind <kind>] [--runner <runner>] [--tag <tag>] [--title <text>] [--test-file <path>] [--output <file>]"
}
"tests-without-evidence" => {
"supercov runs <run-id> tests without-evidence [--filter <all|passed|failed>] [--kind <kind>] [--runner <runner>] [--tag <tag>] [--title <text>] [--test-file <path>] [--offset <n>] [--limit <n>] [--json]"
}
"kinds" => {
"supercov runs <run-id> kinds [--filter <all|passed|failed>] [--runner <runner>] [--tag <tag>] [--title <text>] [--test-file <path>] [--offset <n>] [--limit <n>] [--json]"
}
"runners" => {
"supercov runs <run-id> runners [--filter <all|passed|failed>] [--kind <kind>] [--offset <n>] [--limit <n>] [--json]"
}
"scope" => "supercov runs <run-id> scope [--files] [--offset <n>] [--limit <n>] [--json]",
"file" => {
"supercov runs <run-id> file <path> [--group decision] [--sort <location|missing>] [--filter <all|passed|failed>] [--kind <kind>] [--runner <runner>] [--tag <tag>] [--title <text>] [--test-file <path>] [--offset <n>] [--limit <n>] [--json]"
}
"decision" => {
"supercov runs <run-id> decision <id|source-file:line> [--filter <all|passed|failed>] [--kind <kind>] [--runner <runner>] [--tag <tag>] [--title <text>] [--test-file <path>] [--json]"
}
"line" => {
"supercov runs <run-id> line <source-file:line> [--filter <all|passed|failed>] [--kind <kind>] [--runner <runner>] [--tag <tag>] [--title <text>] [--test-file <path>] [--offset <n>] [--limit <n>] [--json]"
}
"test" => {
"supercov runs <run-id> test <id|name-fragment> [--filter <all|passed|failed>] [--json]"
}
"mutants" => {
return Some(MUTANTS_HELP.into());
}
"minimize" => {
"supercov runs <run-id> minimize [--target <0..100>] [--metric <all|lines|statements|functions|branches|mcdc>] [--filter <all|passed|failed>] [--kind <kind>] [--runner <runner>] [--tag <tag>] [--title <text>] [--test-file <path>] [--json]"
}
_ => "supercov runs <run-id> --help",
};
Some(format!("Usage: {usage}\n"))
}
const MUTANTS_HELP: &str = "Usage: supercov runs <run-id> mutants [<file>[:<line>]] [--status <s1,s2>] [--mutator <name>] [--stryker <report|dir>...] [--stryker-root <dir>] [--kind <kind>] [--runner <runner>] [--tag <tag>] [--title <text>] [--test-file <path>] [--diff <base>] [--fail-on <s1,s2>] [--offset <n>] [--limit <n>] [--json | --format jsonl|markdown|stryker|pit [--output <file>]]
Weak mutation: for each mutant the language's established tool would make
(StrykerJS for JavaScript and TypeScript; in preview, mutmut for Python,
cargo-mutants for Rust, Gremlins for Go and mutant for Ruby), whether a test
ran the mutated code (reach) and whether its value differed there
(infection), read from the run without running anything. A run lists its
mutants from its sources the first time they are asked for.
Without a file, a table of files by how many mutants no test infects, then
by how many no test reaches; with a file, its mutants by line; with
file:line, that line's mutants and why.
Options:
--status <s1,s2> only mutants with these statuses: not-reached, not-infected, infected, unknown, equivalent, or strong verdicts: survived, killed, timeout, no-coverage, error, unviable
--mutator <name> only this mutator's mutants, by its tool's name (EqualityOperator, ConditionalExpression, ...)
--stryker <report|dir>... join StrykerJS's results by mutant id: mutation.json reports, and directories
of them (every .json file inside, recursively); a file to query goes before it
--stryker-root <dir> the directory the reports' file paths are relative to (default: the project root)
--diff <base> only mutants on lines the change added or modified since it left <base> (a git
ref, such as origin/main): the run's commit against the merge base, or the
working tree where the run had uncommitted changes; not infected and not
reached listed first
--fail-on <s1,s2> exit 1 when any mutant asked about has one of these statuses: a CI gate
--kind, --runner, --tag, --title, --test-file
only the verdicts of those tests: a mutant only other tests infect is not infected there
--offset <n>
--limit <n> entries per page (default 20; 0 for all)
--json the coverage.mutants reply, a page at a time
--format jsonl every mutant asked about, one JSON object per line, as --json lists each
--format markdown the not-infected and not-reached mutants (or --status's) as a table for a pull
request's comment, the first 25 and the command for the rest; once
mutants test ran, the survivors with their verdicts and the mutation score
--format stryker StrykerJS's mutation.json (the mutation testing report schema), for
mutation-testing-elements, the Stryker Dashboard and CI integrations
--format pit PIT's mutations.xml, for PIT's report aggregator and Sonar's PIT plugin
--output <file> with --format, write them there instead of to standard output
Exit codes:
0 the answer was given
1 with --stryker, a soundness violation: a mutant this run says no test infects or reaches, which StrykerJS killed;
with --fail-on, a mutant with one of its statuses
2 the run cannot answer, or the request is invalid
";
#[derive(Debug)]
pub struct PublicQueryError {
pub command: Option<String>,
pub json: bool,
pub error: Box<AgentError>,
}
impl PublicQueryError {
fn invalid(command: Option<&str>, json_output: bool, message: impl Into<String>) -> Self {
Self {
command: command.map(str::to_owned),
json: json_output,
error: Box::new(AgentError {
code: ErrorCode::InvalidArgument,
message: message.into(),
retryable: false,
details: None,
}),
}
}
fn unknown(
command: Option<&str>,
json_output: bool,
message: impl Into<String>,
details: serde_json::Value,
) -> Self {
Self {
command: command.map(str::to_owned),
json: json_output,
error: Box::new(AgentError {
code: ErrorCode::UnknownCommand,
message: message.into(),
retryable: false,
details: Some(details),
}),
}
}
}
#[derive(Debug)]
pub enum PublicQueryInvocation {
Runs {
filter: String,
offset: usize,
limit: usize,
json: bool,
},
Coverage {
request: Box<IndexedQueryRequest>,
newer_run_id: Option<String>,
agent_command: String,
json: bool,
},
}
#[derive(Debug)]
struct QueryOptions {
/// `line --from-file <path>`: locations to ask, one per line.
from_file: Option<String>,
run: Option<String>,
kind: Option<String>,
runner: Option<String>,
/// `--tag`, `--title`, `--test-file`: tests picked by what they carry.
tags: Vec<String>,
titles: Vec<String>,
test_files: Vec<String>,
filter: String,
limit: usize,
offset: usize,
json: bool,
target: Option<f64>,
metric: MinimizeMetric,
group_decision: bool,
/// `scope --files`: the scope file by file.
scope_files: bool,
/// `files --group dir`: files rolled up by directory.
group_dir: bool,
depth: Option<usize>,
/// `diff --gained`.
gained: bool,
sort: DecisionSort,
/// `mutants --status`, `--mutator`, `--stryker`, `--stryker-root`.
statuses: Vec<supercov_engine::coverage_index::MutantStatus>,
/// `mutants --status` with strong verdicts.
strong_statuses: Vec<String>,
mutator: Option<String>,
stryker: Vec<String>,
stryker_root: Option<String>,
/// `mutants --diff`, `--fail-on`.
diff_base: Option<String>,
fail_on: Vec<supercov_engine::coverage_index::MutantStatus>,
positional: Vec<String>,
}
impl Default for QueryOptions {
fn default() -> Self {
Self {
from_file: None,
run: None,
kind: None,
runner: None,
tags: Vec::new(),
titles: Vec::new(),
test_files: Vec::new(),
filter: "all".into(),
limit: DEFAULT_LIMIT,
offset: 0,
json: false,
target: None,
metric: MinimizeMetric::All,
group_decision: false,
scope_files: false,
group_dir: false,
depth: None,
gained: false,
sort: DecisionSort::Location,
statuses: Vec::new(),
strong_statuses: Vec::new(),
mutator: None,
stryker: Vec::new(),
stryker_root: None,
diff_base: None,
fail_on: Vec::new(),
positional: Vec::new(),
}
}
}
fn parse_unsigned(value: Option<&String>, positive: bool) -> Option<usize> {
let value = value?;
let parsed = value.parse::<f64>().ok()?;
if !parsed.is_finite()
|| parsed.fract() != 0.0
|| parsed < 0.0
|| parsed > MAX_SAFE_INTEGER as f64
|| (positive && parsed == 0.0)
{
return None;
}
Some(parsed as usize)
}
fn parse_options(
command: &str,
arguments: &[String],
json_output: bool,
) -> Result<QueryOptions, PublicQueryError> {
let agent_command = if matches!(command, "runs" | "diff" | "help") {
command.to_owned()
} else {
format!("coverage.{command}")
};
let mut options = QueryOptions {
json: json_output,
..QueryOptions::default()
};
let mut index = 0;
while index < arguments.len() {
let value = &arguments[index];
match value.as_str() {
"--json" => options.json = true,
"--run" => {
index += 1;
let Some(run) = arguments.get(index) else {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--run requires a run ID",
));
};
options.run = Some(run.clone());
}
"--kind" => {
index += 1;
let Some(kind) = arguments.get(index) else {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--kind requires a test kind",
));
};
options.kind = Some(kind.to_lowercase());
}
"--runner" => {
index += 1;
let Some(runner) = arguments.get(index) else {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--runner requires a runner name",
));
};
options.runner = Some(runner.to_lowercase());
}
flag @ ("--tag" | "--title" | "--test-file") => {
index += 1;
let Some(value) = arguments.get(index).filter(|value| !value.is_empty()) else {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
match flag {
"--tag" => "--tag requires a tag, such as @e2e",
"--title" => "--title requires text the test's name contains",
_ => "--test-file requires a test file or directory",
},
));
};
match flag {
"--tag" => options.tags.push(value.clone()),
"--title" => options.titles.push(value.clone()),
_ => options.test_files.push(value.clone()),
}
}
"--filter" => {
index += 1;
let filter = arguments.get(index).map(|filter| filter.to_lowercase());
if !matches!(filter.as_deref(), Some("all" | "passed" | "failed")) {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--filter must be all, passed, or failed",
));
}
options.filter = filter.expect("validated coverage filter");
}
"--target" => {
index += 1;
let target = arguments
.get(index)
.and_then(|value| value.parse::<f64>().ok());
if !target
.is_some_and(|target| target.is_finite() && (0.0..=100.0).contains(&target))
{
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--target must be between 0 and 100",
));
}
options.target = target;
}
"--metric" => {
index += 1;
options.metric = match arguments.get(index).map(|metric| metric.to_lowercase()) {
Some(metric) if metric == "all" => MinimizeMetric::All,
Some(metric) if metric == "lines" => MinimizeMetric::Lines,
Some(metric) if metric == "statements" => MinimizeMetric::Statements,
Some(metric) if metric == "functions" => MinimizeMetric::Functions,
Some(metric) if metric == "branches" => MinimizeMetric::Branches,
Some(metric) if metric == "mcdc" => MinimizeMetric::Mcdc,
_ => {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--metric must be all, lines, statements, functions, branches, or mcdc",
));
}
};
}
"--limit" => {
index += 1;
// `--limit 0` is every entry, as `assertions`, `quality` and
// `security` spell it.
let Some(limit) = parse_unsigned(arguments.get(index), false) else {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--limit must be a number of entries, or 0 for all of them",
));
};
options.limit = if limit == 0 { usize::MAX } else { limit };
}
"--offset" => {
index += 1;
let Some(offset) = parse_unsigned(arguments.get(index), false) else {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--offset must be a non-negative integer",
));
};
options.offset = offset;
}
"--files" => {
if command != "scope" {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--files is only supported by: supercov runs <run-id> scope",
));
}
options.scope_files = true;
}
"--from-file" => {
index += 1;
let Some(path) = arguments.get(index) else {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--from-file needs a file of <source-file>:<line> locations, one per line",
));
};
options.from_file = Some(path.clone());
}
"--group" => {
index += 1;
let group = arguments.get(index).map(|group| group.to_lowercase());
match (command, group.as_deref()) {
("file", Some("decision")) => options.group_decision = true,
("files", Some("dir")) => options.group_dir = true,
("file", _) => {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--group must be decision",
));
}
("files", _) => {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--group must be dir",
));
}
_ => {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--group is only supported by: supercov runs <run-id> file <source-file> --group decision, and supercov runs <run-id> files --group dir",
));
}
}
}
flag @ ("--status" | "--mutator" | "--stryker" | "--stryker-root" | "--diff"
| "--fail-on") => {
if command != "mutants" {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
format!("{flag} is only supported by: supercov runs <run-id> mutants"),
));
}
index += 1;
let Some(value) = arguments.get(index).filter(|value| !value.is_empty()) else {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
match flag {
"--status" => {
"--status requires statuses, such as not-infected,not-reached"
}
"--mutator" => {
"--mutator requires a StrykerJS mutator, such as EqualityOperator"
}
"--stryker" => "--stryker requires a StrykerJS mutation.json report",
"--diff" => {
"--diff requires a git ref to compare with, such as origin/main"
}
"--fail-on" => {
"--fail-on requires statuses, such as not-infected,not-reached"
}
_ => "--stryker-root requires a directory",
},
));
};
match flag {
"--status" | "--fail-on" => {
for name in value
.split(',')
.map(str::trim)
.filter(|name| !name.is_empty())
{
let name = name.to_lowercase();
let strong = matches!(
name.as_str(),
"killed"
| "survived"
| "timeout"
| "no-coverage"
| "error"
| "unviable"
);
// A strong verdict, which `mutants test` saved into the run.
if strong && flag == "--status" {
if !options.strong_statuses.contains(&name) {
options.strong_statuses.push(name);
}
continue;
}
let Some(status) =
supercov_engine::coverage_index::MutantStatus::parse(&name)
else {
let message = if strong {
format!(
"{flag} {name} is a strong verdict: gate on it with supercov runs <run-id> mutants test --fail-on {name}; here use not-reached, not-infected, infected, unknown or equivalent"
)
} else {
format!(
"{flag} {name} is not a status; use not-reached, not-infected, infected, unknown or equivalent, or a strong verdict: killed, survived, timeout, no-coverage, error or unviable"
)
};
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
message,
));
};
let statuses = if flag == "--status" {
&mut options.statuses
} else {
&mut options.fail_on
};
if !statuses.contains(&status) {
statuses.push(status);
}
}
}
"--mutator" => options.mutator = Some(value.clone()),
"--diff" => options.diff_base = Some(value.clone()),
"--stryker" => {
// Every report after it, as a shell's glob gives
// them: the words that are a `.json` file or a
// directory. A file to query goes before it.
options.stryker.push(value.clone());
while let Some(next) = arguments.get(index + 1).filter(|next| {
!next.starts_with('-')
&& (next.to_ascii_lowercase().ends_with(".json")
|| std::path::Path::new(next.as_str()).is_dir())
}) {
options.stryker.push(next.clone());
index += 1;
}
}
_ => options.stryker_root = Some(value.clone()),
}
}
"--gained" => options.gained = true,
"--depth" => {
index += 1;
let Some(depth) = parse_unsigned(arguments.get(index), true) else {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--depth must be a positive integer",
));
};
options.depth = Some(depth);
}
"--sort" => {
index += 1;
options.sort = match arguments.get(index).map(|sort| sort.to_lowercase()) {
Some(sort) if sort == "location" => DecisionSort::Location,
Some(sort) if sort == "missing" => DecisionSort::Missing,
_ => {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--sort must be location or missing",
));
}
};
}
// A single dash is an option too (`-q`), except in a test name.
option
if option.starts_with("--")
|| (option.starts_with('-') && option.len() > 1 && command != "test") =>
{
let mut error = PublicQueryError::invalid(
Some(&agent_command),
json_output,
format!("Unknown option: {option}"),
);
error.error.details = Some(json!({ "option": option }));
return Err(error);
}
_ => options.positional.push(value.clone()),
}
index += 1;
}
if options.stryker_root.is_some() && options.stryker.is_empty() {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--stryker-root requires --stryker",
));
}
if command == "mutants" && options.filter != "all" {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"mutants are worked out from every attempt; --filter passed and failed are not supported. Narrow the tests with --kind, --runner, --tag, --title or --test-file",
));
}
if options.sort != DecisionSort::Location && !options.group_decision {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--sort requires --group decision",
));
}
if options.depth.is_some() && !options.group_dir {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--depth requires --group dir",
));
}
if options.group_decision
&& !matches!(options.metric, MinimizeMetric::All | MinimizeMetric::Mcdc)
{
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"--group decision lists MC/DC decisions; omit --metric or use --metric mcdc",
));
}
Ok(options)
}
/// `file:line` or `file:line:column`; lines count from 1.
fn parse_location(selector: &str) -> Option<(String, usize)> {
let without_column = selector.rsplit_once(':')?;
let (file_and_maybe_line, final_number) = without_column;
let final_number = final_number.parse::<usize>().ok()?;
if let Some((file, line)) = file_and_maybe_line.rsplit_once(':')
&& let Ok(line) = line.parse::<usize>()
{
return (line > 0).then(|| (file.to_owned(), line));
}
(final_number > 0).then(|| (file_and_maybe_line.to_owned(), final_number))
}
fn coverage_invocation(
run_id: String,
command: &str,
arguments: &[String],
json_output: bool,
) -> Result<PublicQueryInvocation, PublicQueryError> {
let (request, json) = coverage_request(run_id, command, arguments, json_output)?;
Ok(PublicQueryInvocation::Coverage {
request: Box::new(request),
newer_run_id: None,
agent_command: format!("coverage.{command}"),
json,
})
}
/// The request `runs <run> <command> <arguments>` makes of the run's index,
/// and whether its answer is asked for as JSON.
pub(crate) fn coverage_request(
run_id: String,
command: &str,
arguments: &[String],
json_output: bool,
) -> Result<(IndexedQueryRequest, bool), PublicQueryError> {
let options = parse_options(command, arguments, json_output)?;
let agent_command = format!("coverage.{command}");
let mut request = IndexedQueryRequest {
run_id,
filter: options.filter,
command: command.into(),
metric: options.metric,
kind: options.kind,
runner: options.runner,
file: None,
line: None,
selector: None,
sort: None,
valid: None,
test_exit_code: None,
stale: None,
stale_reasons: None,
offset: options.offset,
limit: options.limit,
target: None,
max_states: None,
group: None,
depth: None,
gained_only: false,
more_lines: Vec::new(),
tags: options.tags.clone(),
titles: options.titles.clone(),
test_files: options.test_files.clone(),
mutants: supercov_engine::mutants_query::MutantsOptions::default(),
};
// A word a query does not take would be read as a filter it is not.
let takes = match command {
"file" | "decision" | "mutants" => 1,
"line" | "test" => usize::MAX,
_ => 0,
};
if let Some(extra) = options.positional.get(takes) {
let mut error = PublicQueryError::invalid(
Some(&agent_command),
json_output,
format!("Unexpected argument: {extra}"),
);
error.error.details = Some(json!({ "argument": extra }));
return Err(error);
}
match command {
"summary" | "kinds" | "runners" | "gaps" | "tests-without-evidence" => {}
"mutants" => {
if let Some(selector) = options.positional.first() {
match parse_location(selector) {
Some((file, line)) => {
request.file = Some(file);
request.line = Some(line);
}
None => request.file = Some(selector.clone()),
}
}
request.mutants.statuses = options.statuses.clone();
request.mutants.strong_statuses = options.strong_statuses.clone();
request.mutants.mutator = options.mutator.clone();
request.mutants.diff_base = options.diff_base.clone();
// A change's mutants for a reader: what its tests leave alive.
// The JSON and the export list them all unless asked.
if options.diff_base.is_some() && options.statuses.is_empty() && !json_output {
request.mutants.statuses = vec![
supercov_engine::coverage_index::MutantStatus::NotInfected,
supercov_engine::coverage_index::MutantStatus::NotReached,
];
}
request.mutants.fail_on = options.fail_on.clone();
if !options.stryker.is_empty() {
request.mutants.stryker = Some(
read_stryker_reports(&options.stryker, options.stryker_root.as_deref())
.map_err(|message| {
PublicQueryError::invalid(Some(&agent_command), json_output, message)
})?,
);
}
}
"files" => {
if options.group_dir {
request.group = Some("dir".into());
request.depth = options.depth;
}
}
"scope" => {
if options.scope_files {
request.group = Some("file".into());
}
}
"file" => {
let Some(file) = options.positional.first() else {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"Usage: supercov runs <run-id> file <source-file>",
));
};
request.file = Some(file.clone());
if options.group_decision {
request.command = "file-decisions".into();
request.sort = Some(options.sort);
} else {
request.command = "file-detail".into();
}
}
"decision" => {
let Some(selector) = options.positional.first() else {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"Usage: supercov runs <run-id> decision <id|source-file:line>",
));
};
request.selector = Some(selector.clone());
}
"line" => {
// Every location named, and every line of a file of them: one
// call answers them all from one opened run, which is most of
// what a query costs.
let mut selectors = options.positional.clone();
if let Some(path) = &options.from_file {
let text = supercov_engine::fault_fs::read_to_string(path).map_err(|error| {
PublicQueryError::invalid(
Some(&agent_command),
json_output,
format!("Could not read {path}: {error}"),
)
})?;
selectors.extend(
text.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && !line.starts_with('#'))
.map(str::to_owned),
);
}
if selectors.is_empty() {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"Usage: supercov runs <run-id> line <source-file:line>... [--from-file <path>]",
));
}
let mut locations = selectors
.iter()
.map(|selector| {
parse_location(selector).ok_or_else(|| {
let mut error = PublicQueryError::invalid(
Some(&agent_command),
json_output,
"Expected <source-file>:<line>, with lines counted from 1",
);
error.error.details = Some(json!({ "selector": selector }));
error
})
})
.collect::<Result<Vec<_>, _>>()?;
let (file, line) = locations.remove(0);
request.file = Some(file);
request.line = Some(line);
request.more_lines = locations;
}
"test" => {
if options.positional.is_empty() {
return Err(PublicQueryError::invalid(
Some(&agent_command),
json_output,
"Usage: supercov runs <run-id> test <id|name-fragment>",
));
}
request.selector = Some(options.positional.join(" ").to_lowercase());
}
// `minimize`, the last of the commands the hierarchy lets through.
_ => {
request.target = options.target;
request.max_states = Some(DEFAULT_MAX_STATES);
}
}
Ok((request, options.json))
}
/// StrykerJS's reports, each mutant's file from the project root: a report's
/// paths are relative to `root` (the project root when not given), or
/// absolute.
fn read_stryker_reports(
paths: &[String],
root: Option<&str>,
) -> Result<supercov_engine::mutants_query::StrykerReports, String> {
use std::path::{Component, Path, PathBuf};
let project = std::env::current_dir()
.map_err(|error| format!("Could not resolve the current directory: {error}"))?;
let base = project.join(root.unwrap_or("."));
// Both paths are absolute, so no `.` is left among their components.
let normal = |path: &Path| {
path.components()
.fold(PathBuf::new(), |mut normal, component| {
match component {
Component::ParentDir => {
normal.pop();
}
other => normal.push(other),
}
normal
})
};
let project = normal(&project);
let path_of = |file: &str| {
let full = normal(&base.join(file));
full.strip_prefix(&project)
.unwrap_or(&full)
.components()
.map(|component| component.as_os_str().to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join("/")
};
let mut reports = supercov_engine::mutants_query::StrykerReports {
given: paths.to_vec(),
root: root.map(str::to_owned),
..Default::default()
};
// `--stryker` names one report at least, and a directory with none is
// refused: there is always a file to read.
let mut files = Vec::new();
paths.iter().try_for_each(|path| {
if Path::new(path).is_dir() {
let found = json_files(Path::new(path))
.map_err(|error| format!("Could not read {path}: {error}"))?;
if found.is_empty() {
return Err(format!("{path} holds no .json report"));
}
files.extend(found);
} else {
files.push(path.clone());
}
Ok(())
})?;
files.into_iter().try_for_each(|path| {
// A report named twice, or found in two directories given, once.
if reports.reports.contains(&path) {
return Ok(());
}
let bytes = supercov_engine::fault_fs::read(&path)
.map_err(|error| format!("Could not read {path}: {error}"))?;
let mutants = if supercov_engine::ruby_mutants::is_mutant_session(&bytes) {
// The mutant gem's session results, matched by the methods its
// mutations make.
supercov_engine::ruby_mutants::parse_mutant_session(&bytes, path_of, |file| {
std::fs::read(project.join(file)).ok()
})
.map_err(|reason| {
format!("Could not read {path} as mutant's session results: {reason}")
})?
} else {
let text = String::from_utf8(bytes)
.map_err(|error| format!("Could not read {path}: {error}"))?;
supercov_engine::mutants_query::parse_stryker_report(&text, path_of).map_err(
|reason| format!("Could not read {path} as a StrykerJS report: {reason}"),
)?
};
reports.reports.push(path);
reports.mutants.extend(mutants);
Ok::<(), String>(())
})?;
Ok(reports)
}
/// Every `.json` file under `directory`, in order of path, named as
/// `directory` was given with the rest joined by `/`.
fn json_files(directory: &std::path::Path) -> std::io::Result<Vec<String>> {
let mut found = Vec::new();
let mut pending = Vec::new();
// The directory given first, then each found below it.
let mut directory = directory.to_path_buf();
loop {
for entry in supercov_engine::fault_fs::read_dir(&directory)? {
let path = entry?.path();
if path.is_dir() {
pending.push(path);
} else if path
.extension()
.is_some_and(|extension| extension.eq_ignore_ascii_case("json"))
|| path.to_string_lossy().ends_with(".json.gz")
{
found.push(path.to_string_lossy().replace('\\', "/"));
}
}
match pending.pop() {
Some(next) => directory = next,
None => break,
}
}
found.sort();
Ok(found)
}
pub fn parse_public_query(
command: &str,
arguments: &[String],
) -> Result<PublicQueryInvocation, PublicQueryError> {
let json_output = arguments.iter().any(|argument| argument == "--json");
if command == "diff" {
let options = parse_options(command, arguments, json_output)?;
let Some(older) = options.positional.first() else {
return Err(PublicQueryError::invalid(
Some("diff"),
json_output,
"Usage: supercov diff <older-run> <newer-run>",
));
};
let Some(newer) = options.positional.get(1) else {
return Err(PublicQueryError::invalid(
Some("diff"),
json_output,
"Usage: supercov diff <older-run> <newer-run>",
));
};
if let Some(extra) = options.positional.get(2) {
return Err(PublicQueryError::invalid(
Some("diff"),
json_output,
format!(
"unexpected argument {extra}\n\nUsage: supercov diff <older-run> <newer-run>"
),
));
}
return Ok(PublicQueryInvocation::Coverage {
request: Box::new(IndexedQueryRequest {
run_id: older.clone(),
filter: options.filter,
command: "diff".into(),
metric: options.metric,
kind: options.kind,
runner: options.runner,
file: None,
line: None,
selector: None,
sort: None,
valid: None,
test_exit_code: None,
stale: None,
stale_reasons: None,
offset: options.offset,
limit: options.limit,
target: None,
max_states: None,
group: None,
depth: None,
gained_only: options.gained,
more_lines: Vec::new(),
tags: options.tags.clone(),
titles: options.titles.clone(),
test_files: options.test_files.clone(),
mutants: supercov_engine::mutants_query::MutantsOptions::default(),
}),
newer_run_id: Some(newer.clone()),
agent_command: "diff".into(),
json: options.json,
});
}
debug_assert_eq!(command, "runs");
let Some(run_id) = arguments
.first()
.filter(|argument| !argument.starts_with('-'))
else {
let options = parse_options(command, arguments, json_output)?;
return Ok(PublicQueryInvocation::Runs {
filter: options.filter,
offset: options.offset,
limit: options.limit,
json: options.json,
});
};
let child_index = 1;
let child = arguments
.get(child_index)
.filter(|child| !child.starts_with('-'))
.map_or("summary", String::as_str);
if !matches!(
child,
"summary"
| "kinds"
| "runners"
| "scope"
| "files"
| "gaps"
| "tests-without-evidence"
| "file"
| "decision"
| "line"
| "test"
| "minimize"
| "mutants"
) {
return Err(PublicQueryError::unknown(
Some(&format!("coverage.{child}")),
json_output,
format!("Unknown run query: {child}. Try supercov runs <run-id> --help."),
json!({ "command": child }),
));
}
let child_arguments = if arguments
.get(child_index)
.is_some_and(|candidate| !candidate.starts_with('-'))
{
&arguments[child_index + 1..]
} else {
&arguments[child_index..]
};
coverage_invocation(run_id.clone(), child, child_arguments, json_output)
}
#[cfg(test)]
mod tests {
/// `--stryker` reads the mutant gem's session results beside StrykerJS
/// reports, and says which session it could not read.
#[test]
fn mutant_sessions_are_read_beside_stryker_reports() {
let directory = std::env::temp_dir().join(format!(
"supercov-mutant-sessions-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&directory).unwrap();
let session = serde_json::json!({
"subject_results": [{
"source_path": "lib/none.rb",
"identification": "A#b:lib/none.rb:1",
"coverage_results": [{
"mutation_result": {
"mutation_type": "evil",
"mutation_source": "def b\n nil\nend",
"mutation_identification": "evil:A#b:x",
},
"criteria_result": { "test_result": true },
}],
}],
});
let good = directory.join("session.json");
std::fs::write(&good, session.to_string()).unwrap();
let read = read_stryker_reports(&[good.display().to_string()], None).unwrap();
assert_eq!(read.reports, [good.display().to_string()]);
let bad = directory.join("broken.json.gz");
std::fs::write(&bad, [0x1f, 0x8b, 0, 0]).unwrap();
let refused = read_stryker_reports(&[bad.display().to_string()], None).unwrap_err();
assert!(refused.contains("as mutant's session results"), "{refused}");
std::fs::remove_dir_all(&directory).unwrap();
}
/// Each query's help names its own usage; an unknown one, the list.
#[test]
fn each_query_s_help_is_its_own_usage() {
let help = |child: &str| {
help_for(
"runs",
&["latest".to_owned(), child.to_owned(), "--help".to_owned()],
)
.unwrap()
};
for child in [
"summary",
"files",
"gaps",
"tests-without-evidence",
"kinds",
"runners",
"scope",
"file",
"decision",
"line",
"test",
"minimize",
"mutants",
] {
let usage = help(child);
let named = if child == "summary" {
"[--filter"
} else {
child.split('-').next().unwrap()
};
assert!(
usage.starts_with("Usage: supercov runs <run-id> "),
"{child}: {usage}"
);
assert!(usage.contains(named), "{child}: {usage}");
}
assert_eq!(help("unknown"), "Usage: supercov runs <run-id> --help\n");
}
use super::*;
fn args(values: &[&str]) -> Vec<String> {
values.iter().map(|value| (*value).into()).collect()
}
#[test]
fn parses_the_instance_first_summary_and_default_pagination() {
let PublicQueryInvocation::Coverage {
request,
agent_command,
json,
..
} = parse_public_query("runs", &args(&["latest", "--json"])).unwrap()
else {
panic!("expected coverage invocation");
};
assert_eq!(request.run_id, "latest");
assert_eq!(request.command, "summary");
assert_eq!(request.offset, 0);
assert_eq!(request.limit, 20);
assert_eq!(agent_command, "coverage.summary");
assert!(json);
let PublicQueryInvocation::Coverage { request, .. } =
parse_public_query("runs", &args(&["run_abc123"])).unwrap()
else {
panic!("expected default coverage invocation");
};
assert_eq!(request.run_id, "run_abc123");
assert_eq!(request.command, "summary");
}
#[test]
fn parses_all_structural_file_and_test_options() {
let PublicQueryInvocation::Coverage { request, .. } = parse_public_query(
"runs",
&args(&[
"run-1",
"file",
"src/a.ts",
"--group",
"decision",
"--sort",
"missing",
"--metric",
"mcdc",
"--filter",
"passed",
"--kind",
"E2E",
"--runner",
"Playwright",
"--offset",
"40",
]),
)
.unwrap() else {
panic!("expected coverage invocation");
};
assert_eq!(request.command, "file-decisions");
assert_eq!(request.file.as_deref(), Some("src/a.ts"));
assert_eq!(request.sort, Some(DecisionSort::Missing));
assert_eq!(request.filter, "passed");
assert_eq!(request.kind.as_deref(), Some("e2e"));
assert_eq!(request.runner.as_deref(), Some("playwright"));
assert_eq!(request.offset, 40);
assert_eq!(request.limit, 20);
}
#[test]
fn mutants_take_a_file_or_a_line_and_pick_statuses_and_a_mutator() {
let request = |arguments: &[&str]| {
let PublicQueryInvocation::Coverage {
request,
agent_command,
..
} = parse_public_query("runs", &args(arguments)).unwrap()
else {
panic!("expected a mutants query");
};
assert_eq!(agent_command, "coverage.mutants");
request
};
let line = request(&[
"run-1",
"mutants",
"src/a.ts:42",
"--status",
"not-infected,not-reached,not-infected",
"--mutator",
"EqualityOperator",
"--kind",
"unit",
]);
assert_eq!(line.command, "mutants");
assert_eq!(
(line.file.as_deref(), line.line),
(Some("src/a.ts"), Some(42))
);
assert_eq!(
line.mutants.statuses,
[
supercov_engine::coverage_index::MutantStatus::NotInfected,
supercov_engine::coverage_index::MutantStatus::NotReached
]
);
assert_eq!(line.mutants.mutator.as_deref(), Some("EqualityOperator"));
// A kind picks the tests whose verdicts are read.
assert_eq!(
line.test_filter().and_then(|filter| filter.kind),
Some("unit".to_owned())
);
let file = request(&["run-1", "mutants", "src/a.ts"]);
assert_eq!((file.file.as_deref(), file.line), (Some("src/a.ts"), None));
let run = request(&["run-1", "mutants"]);
assert_eq!((run.file, run.line), (None, None));
// A strong verdict picks mutants by what a strong pass said, beside
// the weak statuses.
let strong = request(&[
"run-1",
"mutants",
"--status",
"survived,not-infected,Survived",
]);
assert_eq!(strong.mutants.strong_statuses, ["survived"]);
assert_eq!(
strong.mutants.statuses,
[supercov_engine::coverage_index::MutantStatus::NotInfected]
);
for (arguments, message) in [
(
&["run-1", "mutants", "--status", "nope"][..],
"is not a status",
),
(
&["run-1", "mutants", "--fail-on", "survived"],
"is a strong verdict: gate on it with supercov runs <run-id> mutants test --fail-on survived",
),
(
&["run-1", "gaps", "--status", "infected"],
"only supported by: supercov runs <run-id> mutants",
),
(
&["run-1", "mutants", "--stryker-root", "x"],
"--stryker-root requires --stryker",
),
(
&["run-1", "mutants", "--filter", "passed"],
"--filter passed and failed are not supported",
),
(
&[
"run-1",
"mutants",
"--stryker",
"/nonexistent/mutation.json",
],
"Could not read /nonexistent/mutation.json",
),
(
&["run-1", "mutants", "a.ts", "b.ts"],
"Unexpected argument: b.ts",
),
] {
let error = parse_public_query("runs", &args(arguments)).unwrap_err();
assert!(
error.error.message.contains(message),
"{arguments:?}: {}",
error.error.message
);
}
}
/// `--stryker` takes every report after it, as a glob gives them, and
/// stops at an option or a word that is no report.
#[test]
fn one_stryker_option_takes_several_reports() {
let options = parse_options(
"mutants",
&args(&[
"--stryker",
"r/r00.json",
"r/r01.JSON",
"src/a.ts",
"--stryker",
"x.json",
"--json",
]),
false,
)
.unwrap();
assert_eq!(options.stryker, ["r/r00.json", "r/r01.JSON", "x.json"]);
assert_eq!(options.positional, ["src/a.ts"]);
assert!(options.json);
// The first word is a report whatever it is named.
let options = parse_options("mutants", &args(&["--stryker", "reports"]), false).unwrap();
assert_eq!(options.stryker, ["reports"]);
}
#[test]
fn splits_line_locations_without_confusing_an_optional_column() {
let PublicQueryInvocation::Coverage { request, .. } =
parse_public_query("runs", &args(&["run-1", "line", "src/a.ts:12:8"])).unwrap()
else {
panic!("expected coverage invocation");
};
assert_eq!(request.file.as_deref(), Some("src/a.ts"));
assert_eq!(request.line, Some(12));
}
#[test]
fn refuses_to_degrade_a_malformed_instance_query_to_a_listing() {
let error =
parse_public_query("runs", &args(&["run-1", "coverage", "--json"])).unwrap_err();
assert_eq!(error.error.code, ErrorCode::UnknownCommand);
assert_eq!(error.command.as_deref(), Some("coverage.coverage"));
assert_eq!(
error.error.message,
"Unknown run query: coverage. Try supercov runs <run-id> --help."
);
assert!(error.json);
}
#[test]
fn validates_agent_options_before_storage_access() {
let error =
parse_public_query("runs", &args(&["run-1", "gaps", "--limit", "-1", "--json"]))
.unwrap_err();
assert_eq!(error.error.code, ErrorCode::InvalidArgument);
assert_eq!(error.command.as_deref(), Some("coverage.gaps"));
assert_eq!(
error.error.message,
"--limit must be a number of entries, or 0 for all of them"
);
}
/// Each option missing what it needs, or given where it means nothing,
/// is refused with what it needs.
#[test]
fn an_option_missing_its_value_or_out_of_place_says_what_it_needs() {
for (arguments, message) in [
(&["run-1", "--run"][..], "--run requires a run ID"),
(&["run-1", "--kind"], "--kind requires a test kind"),
(&["run-1", "--runner"], "--runner requires a runner name"),
(&["run-1", "--tag", ""], "--tag requires a tag"),
(&["run-1", "--title"], "--title requires text"),
(&["run-1", "--test-file", ""], "--test-file requires"),
(
&["run-1", "files", "--files"],
"--files is only supported by",
),
(
&["run-1", "line", "--from-file"],
"--from-file needs a file",
),
(
&["run-1", "file", "a.rs", "--group", "dir"],
"--group must be decision",
),
(&["run-1", "files", "--group"], "--group must be dir"),
(
&["run-1", "gaps", "--group", "dir"],
"--group is only supported by",
),
(
&["run-1", "file"],
"Usage: supercov runs <run-id> file <source-file>",
),
(
&["run-1", "line", "a.rs:x"],
"Expected <source-file>:<line>",
),
(
&["run-1", "line", "--from-file", "/nonexistent/locations"],
"Could not read /nonexistent/locations",
),
] {
let error = parse_public_query("runs", &args(arguments)).unwrap_err();
assert_eq!(
error.error.code,
ErrorCode::InvalidArgument,
"{arguments:?}"
);
assert!(
error.error.message.contains(message),
"{arguments:?}: {}",
error.error.message
);
}
let error = parse_public_query("diff", &args(&["run-1"])).unwrap_err();
assert_eq!(
error.error.message,
"Usage: supercov diff <older-run> <newer-run>"
);
let error = parse_public_query("diff", &args(&["run-1", "--kind"])).unwrap_err();
assert_eq!(error.error.message, "--kind requires a test kind");
let PublicQueryInvocation::Coverage { request, .. } =
parse_public_query("runs", &args(&["run-1", "minimize", "--target", "90"])).unwrap()
else {
panic!("expected a minimize query");
};
assert_eq!(request.command, "minimize");
assert_eq!(request.max_states, Some(DEFAULT_MAX_STATES));
}
}