use std::fmt::Write as _;
use crate::diagnostic::{Applicability, Diagnostic};
use crate::report::Report;
#[must_use]
pub fn text(report: &Report) -> String {
let mut out = header(report);
for diagnostic in &report.diagnostics {
out.push('\n');
out.push_str(&diagnostic_text(diagnostic));
}
out
}
fn header(report: &Report) -> String {
let counts = report.counts();
let mut parts = Vec::new();
for (count, word) in [
(counts.errors, "error"),
(counts.warnings, "warning"),
(counts.hints, "hint"),
] {
if count > 0 {
parts.push(format!(
"{count} {word}{}",
if count == 1 { "" } else { "s" }
));
}
}
let mut line = format!(
"{}: {}, {}",
report.document,
if report.valid { "valid" } else { "invalid" },
if parts.is_empty() {
"no problems".to_owned()
} else {
parts.join(", ")
}
);
if report.omitted > 0 {
let _ = write!(line, "; {} more not shown", report.omitted);
}
if !report.applied.is_empty() {
let _ = write!(
line,
"; {} fix{} applied",
report.applied.len(),
if report.applied.len() == 1 { "" } else { "es" }
);
}
line.push('\n');
line
}
#[must_use]
pub fn diagnostic_text(diagnostic: &Diagnostic) -> String {
let mut out = format!(
"{}[{}] {}",
diagnostic.severity.name(),
diagnostic.code,
diagnostic.path
);
if let Some(span) = diagnostic.span {
let _ = write!(out, " (line {}, column {})", span.line, span.column);
}
if let Some(origin) = &diagnostic.origin {
let _ = write!(out, " from {origin}");
}
out.push('\n');
let _ = writeln!(out, " {}", one_line(&diagnostic.message));
for help in &diagnostic.help {
let _ = writeln!(out, " help: {}", one_line(help));
}
for fix in &diagnostic.fixes {
let kind = match fix.applicability {
Applicability::Certain => "certain",
Applicability::Likely => "likely",
};
let _ = writeln!(out, " fix ({kind}): {}", one_line(&fix.title));
}
if let Some(reference) = &diagnostic.reference {
let _ = writeln!(out, " see: {} {}", reference.topic, reference.definition);
}
if diagnostic.count > 1 {
let others = diagnostic.count - 1;
let listed: Vec<String> = diagnostic.also.iter().map(ToString::to_string).collect();
let _ = write!(
out,
" also at {others} other place{}",
if others == 1 { "" } else { "s" }
);
if !listed.is_empty() {
let _ = write!(out, ": {}", listed.join(", "));
if others > listed.len() {
out.push_str(", ...");
}
}
out.push('\n');
}
out
}
#[must_use]
pub fn diagnostics_text(diagnostics: &[Diagnostic]) -> String {
diagnostics
.iter()
.map(diagnostic_text)
.collect::<Vec<_>>()
.join("\n")
}
fn one_line(text: &str) -> String {
if text.contains(['\n', '\r']) {
text.split(['\n', '\r'])
.filter(|line| !line.is_empty())
.collect::<Vec<_>>()
.join(" ")
} else {
text.to_owned()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::codes::{SHAPE_MISSING_FIELD, SHAPE_UNKNOWN_FIELD};
use crate::diagnostic::{Collector, Edit, Fix, Severity};
use crate::path::Path;
use crate::report::Options;
use crate::tree::Span;
fn root() -> Path {
Path::root("project")
}
fn span() -> Span {
Span {
offset: 120,
length: 9,
line: 37,
column: 23,
}
}
fn report(diagnostics: Vec<Diagnostic>, valid: bool) -> Report {
let mut collected = Collector::default();
collected.extend(diagnostics);
Report::assemble("project", valid, collected, None, &Options::default())
}
#[test]
fn valid_without_problems() {
assert_eq!(text(&report(vec![], true)), "project: valid, no problems\n");
}
#[test]
fn a_diagnostic_with_help_fix_and_reference() {
let path = root().key("visual").key("opactiy");
let diagnostic = Diagnostic::new(
&SHAPE_UNKNOWN_FIELD,
path.clone(),
"VisualProperties has no field \"opactiy\".",
)
.at(Some(span()))
.help("did you mean \"opacity\"?")
.fix(Fix::likely(
"rename \"opactiy\" to \"opacity\"",
vec![Edit::RenameKey {
path,
to: "opacity".into(),
}],
))
.reference("project", "VisualProperties");
assert_eq!(
text(&report(vec![diagnostic], false)),
"project: invalid, 1 error\n\
\n\
error[shape.unknown_field] project.visual.opactiy (line 37, column 23)\n\
\x20 VisualProperties has no field \"opactiy\".\n\
\x20 help: did you mean \"opacity\"?\n\
\x20 fix (likely): rename \"opactiy\" to \"opacity\"\n\
\x20 see: project VisualProperties\n"
);
}
#[test]
fn a_grouped_diagnostic_lists_other_places() {
let diagnostics = (0..5)
.map(|index| {
Diagnostic::new(
&SHAPE_MISSING_FIELD,
root().key("clips").index(index),
"Clip lacks the field \"id\".",
)
})
.collect();
assert_eq!(
text(&report(diagnostics, false)),
"project: invalid, 5 errors\n\
\n\
error[shape.missing_field] project.clips[0]\n\
\x20 Clip lacks the field \"id\".\n\
\x20 also at 4 other places: project.clips[1], project.clips[2], project.clips[3], ...\n"
);
}
#[test]
fn a_reviewer_finding_names_its_origin() {
let diagnostic = Diagnostic::external(
"review.pacing",
Severity::Hint,
3,
root().key("timeline"),
"The cuts come faster than\nthe music.",
)
.origin("reviewer");
assert_eq!(
diagnostics_text(&[diagnostic]),
"hint[review.pacing] project.timeline from reviewer\n\
\x20 The cuts come faster than the music.\n"
);
}
#[test]
fn the_header_counts_omitted_and_applied() {
let mut collected = Collector::new(1);
collected.push(Diagnostic::new(&SHAPE_MISSING_FIELD, root(), "a"));
collected.push(Diagnostic::new(&SHAPE_UNKNOWN_FIELD, root(), "b"));
let mut report = Report::assemble("project", false, collected, None, &Options::default());
report.applied.push(Fix::certain("x", vec![]));
assert!(
text(&report)
.starts_with("project: invalid, 1 error; 1 more not shown; 1 fix applied\n")
);
}
}