use std::fs::{self, OpenOptions};
use std::io::{self, IsTerminal as _, Read as _, Write as _};
use std::path::Path;
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use serde_json::Value;
use crate::report::{self, Finding, Report};
const MAX_EXPLAIN_BYTES: u64 = 16 * 1024 * 1024;
#[derive(Clone, Debug, PartialEq)]
pub struct ExplainedFinding {
pub package: Arc<str>,
pub raw: Value,
}
impl ExplainedFinding {
pub fn id(&self) -> &str {
self.raw.get("id").and_then(Value::as_str).unwrap_or("")
}
pub fn kind(&self) -> &str {
self.raw.get("kind").and_then(Value::as_str).unwrap_or("")
}
pub fn file(&self) -> &str {
self.raw.get("file").and_then(Value::as_str).unwrap_or("")
}
pub fn line(&self) -> usize {
self.raw.get("line").and_then(Value::as_u64).unwrap_or(0) as usize
}
pub fn column(&self) -> usize {
self.raw.get("column").and_then(Value::as_u64).unwrap_or(0) as usize
}
pub fn site(&self) -> String {
format!("{}:{}:{}", self.file(), self.line(), self.column())
}
pub fn line_site(&self) -> String {
format!("{}:{}", self.file(), self.line())
}
pub fn item(&self) -> &str {
self.raw.get("item").and_then(Value::as_str).unwrap_or("")
}
pub fn code(&self) -> &str {
self.raw.get("code").and_then(Value::as_str).unwrap_or("")
}
pub fn ignore_comment(&self) -> String {
if let Some(comment) = self
.raw
.get("likely_equivalent")
.and_then(|v| v.get("ignore_comment"))
.and_then(Value::as_str)
&& !comment.is_empty()
{
return comment.to_string();
}
let kind = match self.kind() {
k @ ("input_gap" | "assertion_gap" | "survivor") => k,
_ => "survivor",
};
let col = self.column();
if col > 0 {
format!("// tmt:ignore[{kind}@{col}] <reason>")
} else {
format!("// tmt:ignore[{kind}] <reason>")
}
}
}
pub fn read_report_input(from: Option<&Path>) -> Result<String> {
if let Some(path) = from {
let mut options = OpenOptions::new();
options.read(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt as _;
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "dragonfly"
))]
const O_NONBLOCK: i32 = 0x0004;
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "dragonfly"
))]
const O_NOFOLLOW: i32 = 0x0100;
#[cfg(all(
target_os = "linux",
any(target_arch = "x86_64", target_arch = "x86", target_arch = "riscv64")
))]
const O_NONBLOCK: i32 = 0o4000;
#[cfg(all(
target_os = "linux",
any(target_arch = "x86_64", target_arch = "x86", target_arch = "riscv64")
))]
const O_NOFOLLOW: i32 = 0o400000;
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
const O_NONBLOCK: i32 = 0o4000;
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
const O_NOFOLLOW: i32 = 0o100000;
#[cfg(not(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "dragonfly",
all(
target_os = "linux",
any(
target_arch = "x86_64",
target_arch = "x86",
target_arch = "aarch64",
target_arch = "riscv64"
)
)
)))]
const O_NONBLOCK: i32 = 0;
#[cfg(not(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "dragonfly",
all(
target_os = "linux",
any(
target_arch = "x86_64",
target_arch = "x86",
target_arch = "aarch64",
target_arch = "riscv64"
)
)
)))]
const O_NOFOLLOW: i32 = 0;
let flags = O_NONBLOCK | O_NOFOLLOW;
if flags != 0 {
options.custom_flags(flags);
} else {
let meta = fs::symlink_metadata(path)
.with_context(|| format!("inspecting {}", path.display()))?;
if !meta.is_file() {
bail!("{} is not a regular file", path.display());
}
}
}
#[cfg(not(unix))]
{
let meta = fs::symlink_metadata(path)
.with_context(|| format!("inspecting {}", path.display()))?;
if !meta.is_file() {
bail!("{} is not a regular file", path.display());
}
}
let file = options
.open(path)
.with_context(|| format!("reading {}", path.display()))?;
let meta = file
.metadata()
.with_context(|| format!("inspecting {}", path.display()))?;
if !meta.is_file() {
bail!("{} is not a regular file", path.display());
}
read_bounded(file, &path.display().to_string())
} else {
let stdin = io::stdin();
if stdin.is_terminal() {
bail!(
"no input file given and stdin is a terminal; pass --from FILE or pipe `cargo tmt --json`"
);
}
read_bounded(stdin.lock(), "stdin")
}
}
fn read_bounded<R: io::Read>(reader: R, label: &str) -> Result<String> {
let mut text = String::new();
reader
.take(MAX_EXPLAIN_BYTES + 1)
.read_to_string(&mut text)
.with_context(|| format!("reading {label}"))?;
let text_len = text.len() as u64;
if text_len > MAX_EXPLAIN_BYTES {
bail!("{label} exceeds maximum report size of {MAX_EXPLAIN_BYTES} bytes");
}
Ok(text)
}
fn collect_findings_from_report_value(mut val: Value, out: &mut Vec<ExplainedFinding>) {
let Some(obj) = val.as_object_mut() else {
return;
};
if let Some(Value::Array(packages)) = obj.remove("packages") {
for pkg in packages {
collect_findings_from_report_value(pkg, out);
}
return;
}
if let Some(mut inner) = obj.remove("report") {
let fallback_pkg = obj
.get("package")
.and_then(Value::as_str)
.unwrap_or_default();
if let Some(inner_obj) = inner.as_object_mut() {
let pkg: Arc<str> = Arc::from(
inner_obj
.get("package")
.and_then(Value::as_str)
.unwrap_or(fallback_pkg),
);
if let Some(Value::Array(findings)) = inner_obj.remove("findings") {
for f in findings {
out.push(ExplainedFinding {
package: Arc::clone(&pkg),
raw: f,
});
}
}
}
return;
}
let pkg: Arc<str> = Arc::from(
obj.get("package")
.and_then(Value::as_str)
.unwrap_or_default(),
);
if let Some(Value::Array(findings)) = obj.remove("findings") {
for f in findings {
out.push(ExplainedFinding {
package: Arc::clone(&pkg),
raw: f,
});
}
}
}
pub fn parse_findings(text: &str) -> Result<Vec<ExplainedFinding>> {
let trimmed = text.trim();
if trimmed.is_empty() {
bail!("report input is empty");
}
if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
let mut out = Vec::new();
collect_findings_from_report_value(value, &mut out);
return Ok(out);
}
let mut out = Vec::new();
for (idx, line) in trimmed.lines().enumerate() {
let line = line.trim();
if line.is_empty() {
continue;
}
let value: Value = serde_json::from_str(line)
.with_context(|| format!("invalid JSON on line {}", idx + 1))?;
collect_findings_from_report_value(value, &mut out);
}
Ok(out)
}
fn distinct_finding_key(f: &ExplainedFinding) -> (&str, Option<&str>, &str, usize, usize) {
let id = f.id();
if id.is_empty() {
(f.package.as_ref(), None, f.kind(), f.line(), f.column())
} else {
(f.package.as_ref(), Some(id), "", 0, 0)
}
}
pub fn resolve_findings<'a>(
findings: &'a [ExplainedFinding],
query: &str,
) -> Result<Vec<&'a ExplainedFinding>> {
let query = query.trim();
if query.is_empty() {
bail!("finding id or site must not be empty");
}
let exact_id: Vec<&ExplainedFinding> = findings.iter().filter(|f| f.id() == query).collect();
if !exact_id.is_empty() {
return Ok(exact_id);
}
let exact_site: Vec<&ExplainedFinding> =
findings.iter().filter(|f| f.site() == query).collect();
if !exact_site.is_empty() {
let distinct_keys: std::collections::BTreeSet<_> =
exact_site.iter().map(|f| distinct_finding_key(f)).collect();
if distinct_keys.len() == 1 {
return Ok(exact_site);
}
return Err(ambiguous_error(query, &exact_site));
}
let exact_line: Vec<&ExplainedFinding> =
findings.iter().filter(|f| f.line_site() == query).collect();
if !exact_line.is_empty() {
let distinct_keys: std::collections::BTreeSet<_> =
exact_line.iter().map(|f| distinct_finding_key(f)).collect();
if distinct_keys.len() == 1 {
return Ok(exact_line);
}
return Err(ambiguous_error(query, &exact_line));
}
let prefix_id: Vec<&ExplainedFinding> = findings
.iter()
.filter(|f| !f.id().is_empty() && f.id().starts_with(query))
.collect();
if !prefix_id.is_empty() {
let distinct_keys: std::collections::BTreeSet<_> =
prefix_id.iter().map(|f| distinct_finding_key(f)).collect();
if distinct_keys.len() == 1 {
return Ok(prefix_id);
}
return Err(ambiguous_error(query, &prefix_id));
}
bail!(
"no finding matching `{}` ({} finding(s) in report)",
report::sanitize_inline(query),
findings.len()
)
}
pub fn resolve_finding<'a>(
findings: &'a [ExplainedFinding],
query: &str,
) -> Result<&'a ExplainedFinding> {
resolve_findings(findings, query).map(|mut list| list.remove(0))
}
fn ambiguous_error(query: &str, matches: &[&ExplainedFinding]) -> anyhow::Error {
let mut msg = format!(
"ambiguous selector `{}` matched {} findings:\n",
report::sanitize_inline(query),
matches.len()
);
for item in matches.iter().take(10) {
let pkg = if item.package.is_empty() {
String::new()
} else {
format!("[{}] ", report::sanitize_inline(&item.package))
};
msg.push_str(&format!(
" - {pkg}{} [{}] {}\n",
report::sanitize_inline(&item.site()),
report::sanitize_inline(item.kind()),
report::sanitize_inline(item.id())
));
}
if matches.len() > 10 {
msg.push_str(&format!(" ... and {} more\n", matches.len() - 10));
}
anyhow::anyhow!(msg.trim_end().to_string())
}
pub fn render_explanation_text(finding: &ExplainedFinding) -> String {
let mut out = String::new();
let kind_label = match finding.kind() {
"input_gap" => "INPUT GAP",
"assertion_gap" => "ASSERTION GAP",
"survivor" if finding.raw.get("change_since").is_some() => "UNTESTED CHANGE",
"survivor" => "SURVIVOR",
other => other,
};
out.push_str(&format!(
"{} {}\n",
report::sanitize_inline(kind_label),
report::sanitize_inline(&finding.site())
));
if !finding.package.is_empty() {
out.push_str(&format!(
" package: {}\n",
report::sanitize_inline(&finding.package)
));
}
if !finding.id().is_empty() {
out.push_str(&format!(
" id: {}\n",
report::sanitize_inline(finding.id())
));
}
if !finding.item().is_empty() {
out.push_str(&format!(
" item: {}\n",
report::sanitize_inline(finding.item())
));
}
out.push_str(&format!(
" code: {}\n",
report::sanitize_inline(finding.code())
));
if let Some(survivors) = finding.raw.get("survivors").and_then(Value::as_array) {
let list: Vec<String> = survivors
.iter()
.filter_map(Value::as_str)
.map(report::sanitize_inline)
.collect();
let total = finding
.raw
.get("survivor_count")
.and_then(|v| v.as_u64().map(u128::from))
.unwrap_or(list.len() as u128)
.max(list.len() as u128);
if !list.is_empty() {
if total > list.len() as u128 {
let more = total - list.len() as u128;
out.push_str(&format!(
" survivors ({total} total, showing {}):\n",
list.len()
));
for s in list {
out.push_str(&format!(" - {s}\n"));
}
out.push_str(&format!(" - (+{more} more)\n"));
} else {
out.push_str(&format!(" survivors ({total}):\n"));
for s in list {
out.push_str(&format!(" - {s}\n"));
}
}
}
}
if let Some(observed) = finding.raw.get("observed").and_then(Value::as_str) {
out.push_str(&format!(
" observed: {}\n",
report::sanitize_inline(observed)
));
}
let has_likely_eq = finding
.raw
.get("likely_equivalent")
.and_then(Value::as_object)
.is_some();
if !has_likely_eq
&& let Some(add_tests) = finding.raw.get("add_tests").and_then(Value::as_array)
{
for item in add_tests.iter().filter_map(Value::as_str) {
out.push_str(&format!(" add test: {}\n", report::sanitize_inline(item)));
}
}
if let Some(tests) = finding.raw.get("tests").and_then(Value::as_array) {
let names: Vec<String> = tests
.iter()
.filter_map(Value::as_str)
.map(report::sanitize_inline)
.collect();
if !names.is_empty() {
out.push_str(&format!(" reaching tests: {}\n", names.join(", ")));
}
}
if let Some(effects) = finding.raw.get("effects").and_then(Value::as_array) {
for effect in effects.iter().filter_map(Value::as_str) {
out.push_str(&format!(" effect: {}\n", report::sanitize_inline(effect)));
}
}
if let Some(advice) = finding.raw.get("advice").and_then(Value::as_str) {
out.push_str(&format!(" advice: {}\n", report::sanitize_inline(advice)));
}
if let Some(witness) = finding.raw.get("witness").and_then(Value::as_object) {
let call = witness.get("call").and_then(Value::as_str).unwrap_or("");
let orig = witness
.get("original")
.and_then(Value::as_str)
.unwrap_or("");
let mutant = witness.get("mutant").and_then(Value::as_str).unwrap_or("");
let assertion = witness
.get("assertion")
.and_then(Value::as_str)
.unwrap_or("");
out.push_str(&format!(
" witness: `{}` (original: {}, mutant: {})\n",
report::sanitize_inline(call),
report::sanitize_inline(orig),
report::sanitize_inline(mutant)
));
if !assertion.is_empty() {
out.push_str(&format!(
" assert: {}\n",
report::sanitize_inline(assertion)
));
}
}
if let Some(eq) = finding
.raw
.get("likely_equivalent")
.and_then(Value::as_object)
&& let Some(reason) = eq.get("reason").and_then(Value::as_str)
{
out.push_str(&format!(
" likely equivalent: {}\n",
report::sanitize_inline(reason)
));
}
out.push_str(&format!(
" suppress: {}\n",
report::sanitize_inline(&finding.ignore_comment())
));
report::sanitize_terminal(&out)
}
pub fn render_explanation_json(finding: &ExplainedFinding) -> String {
let mut obj = finding.raw.clone();
if let Some(map) = obj.as_object_mut() {
if !finding.package.is_empty() {
map.insert(
"package".to_string(),
Value::String(finding.package.to_string()),
);
}
map.insert(
"ignore_comment".to_string(),
Value::String(finding.ignore_comment()),
);
}
serde_json::to_string_pretty(&obj).expect("finding explanation serialises")
}
pub fn render_todo_stubs(reports: &[Report]) -> Option<String> {
let total: usize = reports.iter().map(|r| r.findings.len()).sum();
if total == 0 {
return None;
}
let mut out = String::new();
out.push_str("// Generated by `cargo tmt --emit-todos`.\n");
out.push_str(
"// Fill in each test body and remove `#[ignore = ...]` as you close each gap.\n\n",
);
let mut idx = 0usize;
for rep in reports {
for finding in &rep.findings {
idx += 1;
let at = finding.at();
let stem = sanitize_ident(&at.file);
let fn_name = format!("tmt_todo_{idx:03}_{stem}_l{}_c{}", at.line, at.column);
let summary = format!(
"tmt: {} at {}:{}:{}",
finding.kind(),
report::sanitize_inline(&at.file),
at.line,
at.column
);
out.push_str(&format!(
"// Package: {} | Kind: {} | Location: {}:{}:{}\n",
report::sanitize_inline(&rep.package),
finding.kind(),
report::sanitize_inline(&at.file),
at.line,
at.column,
));
if !at.id.is_empty() {
out.push_str(&format!("// ID: {}\n", report::sanitize_inline(&at.id)));
}
out.push_str(&format!("// Code: {}\n", report::sanitize_inline(&at.code)));
if let Some(eq) = finding.likely_equivalent() {
out.push_str(&format!(
"// Likely equivalent: {}\n// Suppress: {}\n",
report::sanitize_inline(&eq.reason),
report::sanitize_inline(&eq.ignore_comment),
));
} else {
match finding {
Finding::InputGap { add_tests, .. } => {
for hint in add_tests {
out.push_str(&format!(
"// Add test: {}\n",
report::sanitize_inline(hint)
));
}
}
Finding::AssertionGap { tests, witness, .. } => {
if !tests.is_empty() {
out.push_str(&format!(
"// Reaching tests: {}\n",
tests
.iter()
.take(5)
.map(|t| report::sanitize_inline(t))
.collect::<Vec<_>>()
.join(", ")
));
}
if let Some(w) = witness {
out.push_str(&format!(
"// Suggested assertion: {}\n",
report::sanitize_inline(&w.assertion)
));
}
}
Finding::Survivor {
advice, witness, ..
} => {
if let Some(w) = witness {
out.push_str(&format!(
"// Suggested assertion: {}\n",
report::sanitize_inline(&w.assertion)
));
} else if let Some(a) = advice {
out.push_str(&format!("// Advice: {}\n", report::sanitize_inline(a)));
}
}
}
}
out.push_str("#[test]\n");
out.push_str(&format!("#[ignore = {:?}]\n", summary));
out.push_str(&format!("fn {fn_name}() {{\n"));
out.push_str(&format!(" todo!(\"{{}}\", {:?});\n", summary));
out.push_str("}\n\n");
}
}
Some(out)
}
pub fn write_todo_stubs(path: &Path, reports: &[Report]) -> Result<usize> {
let count: usize = reports.iter().map(|r| r.findings.len()).sum();
let Some(content) = render_todo_stubs(reports) else {
return Ok(0);
};
if fs::symlink_metadata(path).is_ok() {
bail!(
"refusing to overwrite existing path `{}` (choose a new file path for --emit-todos)",
path.display()
);
}
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.with_context(|| format!("creating {}", path.display()))?;
file.write_all(content.as_bytes())
.with_context(|| format!("writing {}", path.display()))?;
file.flush()
.with_context(|| format!("flushing {}", path.display()))?;
Ok(count)
}
fn sanitize_ident(path: &str) -> String {
let trimmed = path.strip_suffix(".rs").unwrap_or(path);
let mut out = String::new();
let mut prev_underscore = false;
for ch in trimmed.chars() {
if ch.is_ascii_alphanumeric() {
out.push(ch.to_ascii_lowercase());
prev_underscore = false;
} else if !prev_underscore && !out.is_empty() {
out.push('_');
prev_underscore = true;
}
}
let trimmed = out.trim_matches('_');
if trimmed.is_empty() {
"file".to_string()
} else if trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) {
format!("f_{trimmed}")
} else {
trimmed.to_string()
}
}