use anyhow::Result;
use htl::testing::FileReport;
use serde::Serialize;
pub use htl::Diagnostic;
const NO_RULE: &str = "(no rule)";
#[derive(Default)]
struct RuleTally {
count: usize,
fixable: usize,
unsafe_fixable: usize,
}
pub struct Out {
pub json: bool,
diagnostics: Vec<Diagnostic>,
tally: std::collections::BTreeMap<String, RuleTally>,
statistics_only: bool,
}
impl Out {
pub fn new(json: bool, statistics_only: bool) -> Self {
Self {
json,
diagnostics: Vec::new(),
tally: Default::default(),
statistics_only,
}
}
pub fn take(&mut self) -> Vec<Diagnostic> {
std::mem::take(&mut self.diagnostics)
}
pub fn rules_said(&self) -> impl Iterator<Item = &str> {
self.tally
.keys()
.map(String::as_str)
.filter(|&r| r != NO_RULE)
}
pub fn statistics(&self) -> Vec<RuleStatistic> {
let mut rows: Vec<RuleStatistic> = self
.tally
.iter()
.map(|(rule, t)| RuleStatistic {
rule: rule.clone(),
count: t.count,
fixable: t.fixable,
unsafe_fixable: t.unsafe_fixable,
})
.collect();
rows.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.rule.cmp(&b.rule)));
rows
}
}
#[derive(Serialize, Debug, PartialEq, Eq)]
pub struct RuleStatistic {
pub rule: String,
pub count: usize,
pub fixable: usize,
pub unsafe_fixable: usize,
}
impl htl::project::Output for Out {
fn diagnostic(&mut self, d: &Diagnostic) {
let key = d.rule.clone().unwrap_or_else(|| NO_RULE.to_string());
let t = self.tally.entry(key).or_default();
t.count += 1;
match d.fix.as_ref().map(|f| f.applicability.as_str()) {
Some("safe") | Some("suggest") => t.fixable += 1,
Some("unsafe") => t.unsafe_fixable += 1,
_ => {}
}
if self.statistics_only {
return;
}
let severity = d.severity;
if self.json {
self.diagnostics.push(d.clone());
} else if let Some(by) = &d.required_by {
eprintln!("{severity}: {d}\n (required by {by})");
} else {
let text = d;
match d.fix.as_ref().map(|f| f.applicability.as_str()) {
Some("safe") | Some("suggest") => {
eprintln!("{severity}: {text} (fixable: htl fix)")
}
Some("unsafe") => eprintln!("{severity}: {text} (fixable: htl fix --unsafe)"),
_ => eprintln!("{severity}: {text}"),
}
}
}
}
#[derive(Serialize, Debug)]
pub struct CheckReport {
pub files: usize,
pub patched: usize,
pub diagnostics: Vec<Diagnostic>,
pub summary: CheckSummary,
#[serde(skip_serializing_if = "Option::is_none")]
pub statistics: Option<Vec<RuleStatistic>>,
}
#[derive(Serialize, Debug)]
pub struct CheckSummary {
pub errors: usize,
pub warnings: usize,
pub lints: usize,
pub denied: usize,
pub strict: bool,
pub ok: bool,
pub cached: bool,
pub replayed: usize,
}
#[derive(Serialize, Debug)]
pub struct TestCase {
pub name: String,
pub ok: bool,
pub ms: f64,
}
#[derive(Serialize, Debug)]
pub struct TestFile {
pub path: String,
pub ok: bool,
pub diagnostics: Vec<Diagnostic>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
pub file_level: bool,
pub passed: usize,
pub failed: usize,
pub failures: Vec<String>,
pub tests: Vec<TestCase>,
pub duration_ms: f64,
pub snapshots_written: Vec<String>,
pub snapshots_updated: Vec<String>,
}
fn spelled(paths: &[String]) -> Vec<String> {
paths
.iter()
.map(|p| htl::diagnostic::display_path(std::path::Path::new(p)))
.collect()
}
impl TestFile {
pub fn from_report(rep: &FileReport, diagnostics: Vec<Diagnostic>) -> Self {
Self {
path: htl::diagnostic::display_path(&rep.path),
ok: rep.ok(),
diagnostics,
error: rep.error.clone(),
file_level: rep.file_level,
passed: rep.passed,
failed: rep.failed,
failures: rep.failures.clone(),
tests: rep
.tests
.iter()
.map(|t| TestCase {
name: t.name.clone(),
ok: t.ok,
ms: t.ms,
})
.collect(),
duration_ms: rep.duration_ms,
snapshots_written: spelled(&rep.snapshots_written),
snapshots_updated: spelled(&rep.snapshots_updated),
}
}
}
#[derive(Serialize, Debug)]
pub struct TestSummary {
pub files: usize,
pub files_run: usize,
pub passed: usize,
pub failed: usize,
pub files_with_errors: usize,
pub replayed: usize,
pub duration_ms: f64,
pub ok: bool,
pub seed: u64,
}
pub use htl::project::CoverageReport;
#[derive(Serialize, Debug)]
pub struct TestReport {
pub files: Vec<TestFile>,
pub summary: TestSummary,
#[serde(skip_serializing_if = "Option::is_none")]
pub coverage: Option<CoverageReport>,
}
#[derive(Serialize, Debug)]
pub struct FixApplied {
pub file: String,
pub line: usize,
pub rule: String,
pub applicability: &'static str,
pub pass: usize,
}
#[derive(Serialize, Debug)]
pub struct FixSkipped {
pub file: String,
pub line: usize,
pub rule: String,
pub reason: String,
}
#[derive(Serialize, Debug)]
pub struct FixFile {
pub path: String,
pub changed: bool,
pub deferred: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub reverted: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub oscillation: Option<String>,
pub diagnostics: Vec<Diagnostic>,
}
#[derive(Serialize, Debug)]
pub struct FixReport {
pub dry_run: bool,
pub applied: Vec<FixApplied>,
pub skipped: Vec<FixSkipped>,
pub files: Vec<FixFile>,
pub summary: FixSummary,
pub diagnostics: Vec<Diagnostic>,
}
#[derive(Serialize, Debug)]
pub struct FixSummary {
pub files: usize,
pub files_changed: usize,
pub applied: usize,
pub skipped: usize,
pub deferred: usize,
pub reverted: usize,
pub errors_remaining: usize,
pub warnings: usize,
pub lints: usize,
pub denied: usize,
pub strict: bool,
pub ok: bool,
}
pub fn emit<T: Serialize>(v: &T) -> Result<()> {
println!("{}", serde_json::to_string_pretty(v)?);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use htl::project::Output as _;
#[test]
fn an_unclassified_error_is_tallied_under_no_rule() {
let mut out = Out::new(false, false);
out.diagnostic(&Diagnostic::new(
htl::Severity::Error,
"a.tl",
1,
1,
"generate failed: boom",
None,
));
assert_eq!(
out.statistics(),
vec![RuleStatistic {
rule: NO_RULE.to_string(),
count: 1,
fixable: 0,
unsafe_fixable: 0,
}]
);
assert_eq!(out.rules_said().collect::<Vec<_>>(), Vec::<&str>::new());
}
}