use crate::ci_output::markdown_code_span;
use crate::gate_outcomes::{GateOutcome, GateStatus};
use crate::mutation::{
MutantChange, MutationCompletion, MutationCompletionStatus, MutationIncompleteReason,
MutationScopeKind, MutationStatusCounts,
};
use crate::pr_decision::{PrDecisionAnnotationLevel, PrDecisionConclusion, PrDecisionGate};
pub const MUTATION_SECTION_MAX_CHARS: usize = 6000;
pub const MUTATION_NO_COVERAGE_ITEMS: usize = 10;
pub const MUTATION_MESSAGE_MAX_CHARS: usize = 1000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MutationNotRunReason {
EventRefused,
ForkRefused,
NoChangeScope,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MutationCiState {
Ran,
Failed {
exit_code: i32,
code: String,
message: String,
help: Option<String>,
},
NotRun(MutationNotRunReason),
Interrupted,
Unreadable {
reason: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct MutationCiLocation {
pub file: String,
pub line: u32,
pub function: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MutationHeading {
Comment,
CompactComment,
Review,
Summary,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MutationCiView {
pub state: MutationCiState,
pub scope: Option<MutationScopeKind>,
pub counts: MutationStatusCounts,
pub score: Option<f64>,
pub completion: Option<MutationCompletion>,
pub min_score_gate: Option<GateOutcome>,
pub no_coverage: Vec<MutationCiLocation>,
pub stale_hidden: usize,
pub off_diff_hidden: usize,
pub inline_overflow: usize,
pub root_flag: Option<String>,
pub elapsed_ms: Option<u64>,
pub cache_hits: Option<usize>,
}
impl MutationCiView {
#[must_use]
pub fn new(state: MutationCiState) -> Self {
Self {
state,
scope: None,
counts: MutationStatusCounts::default(),
score: None,
completion: None,
min_score_gate: None,
no_coverage: Vec::new(),
stale_hidden: 0,
off_diff_hidden: 0,
inline_overflow: 0,
root_flag: None,
elapsed_ms: None,
cache_hits: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MutationRunNotice {
pub level: PrDecisionAnnotationLevel,
pub title: &'static str,
pub message: String,
}
#[must_use]
pub fn mutation_scope_was_empty(view: &MutationCiView) -> bool {
matches!(view.state, MutationCiState::Ran)
&& view.counts.total == 0
&& !is_partial(view)
&& view.min_score_gate.is_none()
}
#[must_use]
pub fn render_mutation_section(view: &MutationCiView, heading: MutationHeading) -> String {
let title = match heading {
MutationHeading::Comment | MutationHeading::CompactComment | MutationHeading::Review => {
"#### Mutation testing"
}
MutationHeading::Summary => "## Mutation testing",
};
let body = section_body(view, heading);
let shown = if heading == MutationHeading::Summary {
body.clone()
} else {
collapse_details(view, body.clone())
};
let open = join_paragraphs(title, &body.core, &body.extra);
if open.chars().count() <= MUTATION_SECTION_MAX_CHARS {
return join_paragraphs(title, &shown.core, &shown.extra);
}
join_paragraphs(title, &body.core, &[SHORTENED_SECTION_NOTE.to_owned()])
}
#[must_use]
pub fn mutation_decision_row(view: &MutationCiView) -> PrDecisionGate {
let (status, observed) = decision_outcome(view);
PrDecisionGate {
id: DECISION_ROW_ID.to_owned(),
label: TITLE.to_owned(),
status,
observed,
threshold: None,
scope: decision_scope(view.scope).to_owned(),
}
}
#[must_use]
pub fn survived_description(
operator: &str,
change: Option<&MutantChange>,
function: Option<&str>,
mutant_id: &str,
) -> String {
let token = |value: &str| single_line(value, TOKEN_MAX_CHARS);
let code = |value: &str| markdown_code_span(&token(value));
let action = match change.map(|change| (token(&change.from), token(&change.to))) {
Some((from, to)) if !from.is_empty() && !to.is_empty() => {
format!("Changing {} to {}", code(&from), code(&to))
}
Some((from, _)) if !from.is_empty() => format!("Removing {}", code(&from)),
Some((_, to)) if !to.is_empty() => format!("Adding {}", code(&to)),
_ => format!("A {} change", code(operator)),
};
let place = function
.map(|name| single_line(name, INLINE_VALUE_MAX_CHARS))
.filter(|name| !name.is_empty())
.map_or_else(String::new, |name| {
format!(" in {}", markdown_code_span(&name))
});
format!(
"{action}{place} made no test fail. Mutant {}.",
code(mutant_id)
)
}
#[must_use]
pub fn mutation_run_notice(view: &MutationCiView) -> Option<MutationRunNotice> {
let (level, message) = match &view.state {
MutationCiState::NotRun(_) => return None,
MutationCiState::Ran => {
let completion = view.completion.as_ref().filter(|_| is_partial(view))?;
let reasons = completion
.reasons
.iter()
.map(|reason| reason_text(*reason))
.collect::<Vec<_>>()
.join(", ");
(
PrDecisionAnnotationLevel::Notice,
format!("Partial run: {reasons}. The annotations cover only the mutants that ran."),
)
}
MutationCiState::Failed {
exit_code,
code,
message,
..
} => {
let code = single_line(code, CODE_MAX_CHARS);
let code = if code.is_empty() {
String::new()
} else {
format!(", {code}")
};
let message = cap_chars(&normalize_block(message), MUTATION_MESSAGE_MAX_CHARS);
(
PrDecisionAnnotationLevel::Failure,
format!("Mutation testing failed (exit code {exit_code}{code}): {message}"),
)
}
MutationCiState::Interrupted => (
PrDecisionAnnotationLevel::Failure,
INTERRUPTED_TEXT.to_owned(),
),
MutationCiState::Unreadable { .. } => (
PrDecisionAnnotationLevel::Failure,
format!("Fallow could not read the mutation report ({INVALID_REPORT_CODE})."),
),
};
Some(MutationRunNotice {
level,
title: TITLE,
message,
})
}
const TITLE: &str = "Mutation testing";
const DECISION_ROW_ID: &str = "mutation";
const REPORT_FILE: &str = "fallow-mutation.json";
const INVALID_REPORT_CODE: &str = "FALLOW_MUTATION_REPORT_INVALID";
const SHORTENED_SUFFIX: &str = " ... (shortened)";
const CUT_SUFFIX: &str = "...";
const SHORTENED_SECTION_NOTE: &str =
"The mutation section is shortened. The fallow-mutation.json file of this job has all results.";
const INTERRUPTED_TEXT: &str =
"Mutation testing stopped. A signal stopped the run, and the run wrote no report.";
const FENCE: &str = "````";
const THREE_BACKTICKS: &str = "```";
const THREE_QUOTES: &str = "'''";
const INLINE_VALUE_MAX_CHARS: usize = 512;
const TOKEN_MAX_CHARS: usize = 128;
const CODE_MAX_CHARS: usize = 80;
const FLOOR_EPSILON: f64 = 1e-9;
const PERCENT: f64 = 100.0;
const TENTHS: f64 = 10.0;
const MILLIS_PER_SECOND: u64 = 1000;
const SECONDS_PER_MINUTE: u64 = 60;
const SECONDS_PER_HOUR: u64 = 3600;
#[derive(Clone)]
struct SectionBody {
core: Vec<String>,
extra: Vec<String>,
}
fn collapse_details(view: &MutationCiView, mut body: SectionBody) -> SectionBody {
if !matches!(view.state, MutationCiState::Ran) {
return body;
}
let mut hidden = Vec::new();
if view.counts.total > 0 && body.core.len() > 1 {
hidden.extend(body.core.pop());
}
hidden.append(&mut body.extra);
if hidden.is_empty() {
return body;
}
body.extra = vec![format!(
"<details>\n<summary>Counts and details</summary>\n\n{}\n\n</details>",
hidden.join("\n\n")
)];
body
}
fn join_paragraphs(title: &str, core: &[String], extra: &[String]) -> String {
std::iter::once(title)
.chain(core.iter().map(String::as_str))
.chain(extra.iter().map(String::as_str))
.collect::<Vec<_>>()
.join("\n\n")
}
fn section_body(view: &MutationCiView, heading: MutationHeading) -> SectionBody {
let only = |text: String| SectionBody {
core: vec![text],
extra: Vec::new(),
};
match &view.state {
MutationCiState::Ran => ran_body(view, heading),
MutationCiState::NotRun(reason) => only(not_run_text(*reason).to_owned()),
MutationCiState::Interrupted => only(
"**Mutation testing stopped.** A signal stopped the run, and the run wrote no report."
.to_owned(),
),
MutationCiState::Unreadable { reason } => SectionBody {
core: vec![format!(
"**Fallow could not read the mutation report** ({}).",
markdown_code_span(INVALID_REPORT_CODE)
)],
extra: text_block(reason).into_iter().collect(),
},
MutationCiState::Failed {
exit_code,
code,
message,
help,
} => {
let code = single_line(code, CODE_MAX_CHARS);
let code = if code.is_empty() {
String::new()
} else {
format!(", {}", markdown_code_span(&code))
};
SectionBody {
core: vec![format!(
"**Mutation testing failed** (exit code {exit_code}{code})."
)],
extra: text_block(message)
.into_iter()
.chain(help.as_deref().and_then(text_block))
.collect(),
}
}
}
}
const fn not_run_text(reason: MutationNotRunReason) -> &'static str {
match reason {
MutationNotRunReason::EventRefused => {
"**Mutation testing did not run.** This event can run the code of a fork with the secrets of the base repository. Mutation testing runs only for the pull_request, push, schedule, workflow_dispatch and merge_group events."
}
MutationNotRunReason::ForkRefused => {
"**Mutation testing did not run.** The merge request comes from a fork, and the pipeline runs in the target project."
}
MutationNotRunReason::NoChangeScope => {
"**Mutation testing did not run.** The changed scope needs a pull request diff or a base ref, and this job has neither. Run the job in a pull request, set a base ref, or use the all scope."
}
}
}
fn ran_body(view: &MutationCiView, heading: MutationHeading) -> SectionBody {
let mut core = Vec::new();
if let Some(line) = partial_line(view) {
core.push(line);
}
core.push(headline(view));
if view.counts.total > 0 {
core.push(count_table(view));
}
let facts = match heading {
MutationHeading::Comment | MutationHeading::CompactComment | MutationHeading::Review => {
None
}
MutationHeading::Summary => run_facts_line(view),
};
let extra = [
scope_line(view.scope).map(str::to_owned),
facts,
survivor_explanation(view, heading),
hidden_line(
view.stale_hidden,
"survived mutant is not shown because its file changed after the run.",
"survived mutants are not shown because their file changed after the run.",
),
hidden_line(
view.off_diff_hidden,
"survived mutant is on a line that this change did not add, so it has no finding.",
"survived mutants are on lines that this change did not add, so they have no finding.",
),
hidden_line(
view.inline_overflow,
"more survived mutant is not shown inline. The fallow-mutation.json file of this job lists it.",
"more survived mutants are not shown inline. The fallow-mutation.json file of this job lists them.",
),
no_coverage_details(&view.no_coverage),
inspect_line(view),
]
.into_iter()
.flatten()
.collect();
SectionBody { core, extra }
}
fn is_partial(view: &MutationCiView) -> bool {
view.completion
.as_ref()
.is_some_and(|completion| completion.status == MutationCompletionStatus::Partial)
}
fn partial_line(view: &MutationCiView) -> Option<String> {
let completion = view.completion.as_ref().filter(|_| is_partial(view))?;
let reasons = completion
.reasons
.iter()
.map(|reason| reason_text(*reason))
.collect::<Vec<_>>()
.join(", ");
let mut line = if reasons.is_empty() {
"**Partial run.** The counts cover only the mutants that ran.".to_owned()
} else {
format!("**Partial run:** {reasons}. The counts cover only the mutants that ran.")
};
if completion
.reasons
.contains(&MutationIncompleteReason::TimeBudget)
{
line.push_str(" The next run with the same budget continues from the result cache.");
}
Some(line)
}
const fn reason_text(reason: MutationIncompleteReason) -> &'static str {
match reason {
MutationIncompleteReason::RuntimeError => "some mutants stopped with a runtime error",
MutationIncompleteReason::MutantLimit => "the run reached the mutant limit",
MutationIncompleteReason::SampledOut => "the run tested a sample of the mutants",
MutationIncompleteReason::TimeBudget => "the run reached its time budget",
MutationIncompleteReason::SkippedFiles => "the run skipped some files",
MutationIncompleteReason::UnloadedFiles => "the test runner did not load some files",
MutationIncompleteReason::TestFilesNotDiscovered => "the run found no test files",
MutationIncompleteReason::BaselineFailure => "the tests failed before any change",
MutationIncompleteReason::WorktreeChanged => "files changed during the run",
MutationIncompleteReason::TypecheckFailed => "the type check failed",
MutationIncompleteReason::WorktreeUnchecked => "the run could not check the worktree",
}
}
fn headline(view: &MutationCiView) -> String {
let gate = view.min_score_gate.as_ref();
let minimum = gate.and_then(|gate| gate.threshold).map(minimum_percent);
if let Some(gate) = gate.filter(|gate| gate.status == GateStatus::Fail) {
let observed = gate
.observed
.or_else(|| view.score.map(|score| score * PERCENT));
return match (observed, minimum) {
(Some(observed), Some(minimum)) => format!(
"**Score below the minimum.** The score is {}, and the minimum is {minimum}.",
percent_floor(observed)
),
(None, Some(minimum)) => {
format!("**Score below the minimum.** The minimum is {minimum}.")
}
(_, None) => "**Score below the minimum.**".to_owned(),
};
}
if view.counts.total == 0 {
return "The scope has no mutant.".to_owned();
}
let detected = view.counts.killed.saturating_add(view.counts.timeout);
if view.score.is_none() && (detected > 0 || view.counts.not_killed_by_target > 0) {
let missed = view.counts.not_killed_by_target;
return format!(
"**The target-first kill matrix has no score.** {} {} not killed by a target; pass `--kill-matrix-full` to score each mutant.",
count_noun(missed, "mutant", "mutants"),
if missed == 1 { "was" } else { "were" }
);
}
let Some(score) = view.score else {
return if gate.is_some() {
"**No mutant was counted.** The score gate was skipped.".to_owned()
} else {
"**No mutant was counted.**".to_owned()
};
};
if view.counts.survived > 0 {
let minimum = minimum.map_or_else(String::new, |minimum| format!(" (minimum {minimum})"));
return format!(
"**{} survived.** Score {}{minimum}.",
count_noun(view.counts.survived, "mutant", "mutants"),
score_percent(score)
);
}
"The tests detected each mutant that ran.".to_owned()
}
fn count_table(view: &MutationCiView) -> String {
let counts = &view.counts;
let not_measured = counts
.pending
.saturating_add(counts.runtime_error)
.saturating_add(counts.flaky)
.saturating_add(counts.compile_error)
.saturating_add(counts.not_killed_by_target);
let score = view.score.map_or_else(|| "-".to_owned(), score_percent);
let killed = counts.killed.saturating_add(counts.timeout);
if not_measured == 0 {
return format!(
"| Killed | Survived | No coverage | Score |\n\
| --: | --: | --: | --: |\n\
| {killed} | {} | {} | {score} |",
counts.survived, counts.no_coverage,
);
}
format!(
"| Killed | Survived | No coverage | Not measured | Score |\n\
| --: | --: | --: | --: | --: |\n\
| {killed} | {} | {} | {not_measured} | {score} |",
counts.survived, counts.no_coverage,
)
}
const fn scope_line(scope: Option<MutationScopeKind>) -> Option<&'static str> {
match scope {
Some(MutationScopeKind::Changed) | None => None,
Some(MutationScopeKind::All) => Some("Scope: all files."),
Some(MutationScopeKind::Paths) => Some("Scope: the selected paths."),
}
}
fn run_facts_line(view: &MutationCiView) -> Option<String> {
let elapsed = view
.elapsed_ms
.map(|ms| format!("The run took {}.", duration_text(ms)));
let cache = view.cache_hits.filter(|hits| *hits > 0).map(|hits| {
if hits == 1 {
"1 result came from the cache.".to_owned()
} else {
format!("{hits} results came from the cache.")
}
});
let parts: Vec<String> = elapsed.into_iter().chain(cache).collect();
(!parts.is_empty()).then(|| parts.join(" "))
}
fn duration_text(ms: u64) -> String {
let seconds = ms / MILLIS_PER_SECOND;
if seconds == 0 {
return "less than 1s".to_owned();
}
let hours = seconds / SECONDS_PER_HOUR;
let minutes = seconds % SECONDS_PER_HOUR / SECONDS_PER_MINUTE;
let rest = seconds % SECONDS_PER_MINUTE;
if hours > 0 {
format!("{hours}h {minutes}m {rest}s")
} else if minutes > 0 {
format!("{minutes}m {rest}s")
} else {
format!("{rest}s")
}
}
fn survivor_explanation(view: &MutationCiView, heading: MutationHeading) -> Option<String> {
const FIRST: &str = "A survived mutant is a code change that no test detects.";
const LAST: &str = "Add a test that fails on the change.";
if view.counts.survived == 0 {
return None;
}
let lines = if view.scope == Some(MutationScopeKind::Changed) {
" on the changed lines"
} else {
""
};
let shown = view
.counts
.survived
.saturating_sub(view.stale_hidden.saturating_add(view.off_diff_hidden));
if shown == 0 {
return Some(format!("{FIRST} {LAST}"));
}
Some(match heading {
MutationHeading::Summary | MutationHeading::CompactComment => format!("{FIRST} {LAST}"),
MutationHeading::Comment => {
format!("{FIRST} The **Tests** section above lists the survived mutants{lines}. {LAST}")
}
MutationHeading::Review => {
format!("{FIRST} The inline comments show the survived mutants{lines}. {LAST}")
}
})
}
fn hidden_line(count: usize, singular: &str, plural: &str) -> Option<String> {
match count {
0 => None,
1 => Some(format!("1 {singular}")),
_ => Some(format!("{count} {plural}")),
}
}
fn no_coverage_details(locations: &[MutationCiLocation]) -> Option<String> {
if locations.is_empty() {
return None;
}
let mut sorted = locations.to_vec();
sorted.sort();
sorted.dedup();
let total = sorted.len();
let count = if total > MUTATION_NO_COVERAGE_ITEMS {
format!("{total} lines, the first {MUTATION_NO_COVERAGE_ITEMS} shown")
} else {
count_noun(total, "line", "lines")
};
let items = sorted
.iter()
.take(MUTATION_NO_COVERAGE_ITEMS)
.map(location_item)
.collect::<Vec<_>>()
.join("\n");
Some(format!(
"<details>\n<summary>No test reaches these lines ({count})</summary>\n\n{items}\n\n</details>"
))
}
fn location_item(location: &MutationCiLocation) -> String {
let place = inline_code(&format!("{}:{}", location.file, location.line));
let function = location
.function
.as_deref()
.map(|name| single_line(name, INLINE_VALUE_MAX_CHARS))
.filter(|name| !name.is_empty());
match function {
Some(name) => format!("- {place}, function {}", markdown_code_span(&name)),
None => format!("- {place}"),
}
}
fn inspect_line(view: &MutationCiView) -> Option<String> {
if view.counts.survived.saturating_add(view.counts.no_coverage) == 0 {
return None;
}
let mut command = format!("fallow mutation inspect <mutant-id> --report {REPORT_FILE}");
let root = view
.root_flag
.as_deref()
.map(|root| single_line(root, INLINE_VALUE_MAX_CHARS))
.filter(|root| !root.is_empty() && root != ".");
if let Some(root) = root {
command.push_str(" --root ");
command.push_str(&shell_quote(&root));
}
Some(format!(
"To inspect a mutant, run {} with the report that this job writes.",
markdown_code_span(&command)
))
}
fn shell_quote(value: &str) -> String {
let plain = value
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | '/' | '-' | '@' | '+'));
if plain {
value.to_owned()
} else {
format!("'{}'", value.replace('\'', r"'\''"))
}
}
fn decision_outcome(view: &MutationCiView) -> (PrDecisionConclusion, String) {
let counts = &view.counts;
match &view.state {
MutationCiState::NotRun(_) => (PrDecisionConclusion::Skipped, "not run".to_owned()),
MutationCiState::Failed { .. }
| MutationCiState::Interrupted
| MutationCiState::Unreadable { .. } => {
(PrDecisionConclusion::Failure, "failed".to_owned())
}
MutationCiState::Ran if is_partial(view) => (
PrDecisionConclusion::Neutral,
format!(
"partial: {} of {} mutants ran",
counts.executed(),
counts.total
),
),
MutationCiState::Ran if counts.total == 0 => {
(PrDecisionConclusion::Success, "no mutant".to_owned())
}
MutationCiState::Ran => {
let score = view.score.map_or_else(
|| "no score".to_owned(),
|score| format!("{} score", score_percent(score)),
);
if counts.survived > 0 {
(
PrDecisionConclusion::Neutral,
format!("{score}, {} survived", counts.survived),
)
} else if counts.no_coverage > 0 {
(
PrDecisionConclusion::Neutral,
format!("{score}, {} not covered", counts.no_coverage),
)
} else {
(PrDecisionConclusion::Success, score)
}
}
}
}
const fn decision_scope(scope: Option<MutationScopeKind>) -> &'static str {
match scope {
Some(MutationScopeKind::Changed) => "changed lines",
Some(MutationScopeKind::All) => "all files",
Some(MutationScopeKind::Paths) => "selected paths",
None => "-",
}
}
fn count_noun(count: usize, singular: &str, plural: &str) -> String {
if count == 1 {
format!("1 {singular}")
} else {
format!("{count} {plural}")
}
}
fn score_percent(score: f64) -> String {
percent_floor(score * PERCENT)
}
fn percent_floor(percent: f64) -> String {
let floored = percent.mul_add(TENTHS, FLOOR_EPSILON).floor() / TENTHS;
format!("{floored:.1}%")
}
fn minimum_percent(percent: f64) -> String {
let text = format!("{percent:.2}");
let trimmed = text.trim_end_matches('0').trim_end_matches('.');
format!("{trimmed}%")
}
fn inline_code(value: &str) -> String {
markdown_code_span(&single_line(value, INLINE_VALUE_MAX_CHARS))
}
fn single_line(value: &str, max: usize) -> String {
let flat: String = value
.replace("\r\n", " ")
.chars()
.map(|ch| if ch.is_control() { ' ' } else { ch })
.collect();
let flat = flat.trim();
if flat.chars().count() <= max {
return flat.to_owned();
}
let mut cut: String = flat.chars().take(max).collect();
cut.push_str(CUT_SUFFIX);
cut
}
fn normalize_block(value: &str) -> String {
value
.replace("\r\n", "\n")
.chars()
.map(|ch| match ch {
'\r' => '\n',
'\n' | '\t' => ch,
_ if ch.is_control() => ' ',
_ => ch,
})
.collect::<String>()
.trim()
.to_owned()
}
fn cap_chars(value: &str, max: usize) -> String {
if value.chars().count() <= max {
return value.to_owned();
}
let mut cut: String = value.chars().take(max).collect();
cut.push_str(SHORTENED_SUFFIX);
cut
}
fn text_block(value: &str) -> Option<String> {
let text = normalize_block(value).replace(THREE_BACKTICKS, THREE_QUOTES);
if text.is_empty() {
return None;
}
let text = cap_chars(&text, MUTATION_MESSAGE_MAX_CHARS);
Some(format!("{FENCE}text\n{text}\n{FENCE}"))
}
#[cfg(test)]
#[path = "mutation_ci_tests.rs"]
mod tests;