use serde::{Deserialize, Serialize};
use crate::diagnostic::{Collector, Diagnostic, Fix, Severity};
use crate::render;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(default, deny_unknown_fields)]
pub struct Options {
pub fix: bool,
pub text: bool,
pub excerpt: bool,
pub limit: usize,
}
impl Default for Options {
fn default() -> Self {
Self {
fix: false,
text: false,
excerpt: false,
limit: DEFAULT_LIMIT,
}
}
}
pub const DEFAULT_LIMIT: usize = 50;
pub const MAX_EXCERPT_BYTES: usize = 400;
pub const MAX_ALSO: usize = 3;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Report {
pub document: String,
pub valid: bool,
pub diagnostics: Vec<Diagnostic>,
pub omitted: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fixed: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub applied: Vec<Fix>,
}
pub const REPORT_SCHEMA_ID: &str = "https://alpha2.sh/schema/diagnostics.v1.json";
#[cfg(feature = "schema")]
#[must_use]
pub fn report_json_schema() -> schemars::Schema {
let mut schema = schemars::generate::SchemaSettings::draft2020_12()
.for_serialize()
.into_generator()
.into_root_schema_for::<Report>();
schema.insert("$id".to_owned(), REPORT_SCHEMA_ID.into());
schema.insert("title".to_owned(), "alpha2 diagnostics report".into());
schema
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Counts {
pub errors: usize,
pub warnings: usize,
pub hints: usize,
}
impl Report {
#[must_use]
pub fn assemble(
document: &str,
valid: bool,
collected: Collector,
source: Option<&str>,
options: &Options,
) -> Self {
let (mut diagnostics, dropped) = collected.into_parts();
order(&mut diagnostics);
let mut diagnostics = group(diagnostics);
let omitted = dropped + diagnostics.len().saturating_sub(options.limit);
diagnostics.truncate(options.limit);
if options.excerpt
&& let Some(source) = source
{
for diagnostic in &mut diagnostics {
diagnostic.excerpt = diagnostic.span.and_then(|span| excerpt(source, span));
}
}
let mut report = Self {
document: document.to_owned(),
valid,
diagnostics,
omitted,
text: None,
fixed: None,
applied: Vec::new(),
};
if options.text {
report.text = Some(render::text(&report));
}
report
}
#[must_use]
pub fn counts(&self) -> Counts {
let mut counts = Counts::default();
for diagnostic in &self.diagnostics {
let slot = match diagnostic.severity {
Severity::Error => &mut counts.errors,
Severity::Warning => &mut counts.warnings,
Severity::Hint => &mut counts.hints,
};
*slot += diagnostic.count;
}
counts
}
#[must_use]
pub fn has_errors(&self) -> bool {
self.diagnostics.iter().any(Diagnostic::is_error)
}
}
pub fn order(diagnostics: &mut [Diagnostic]) {
diagnostics.sort_by_key(|diagnostic| {
(
diagnostic.span.map_or(usize::MAX, |span| span.offset),
diagnostic.severity,
)
});
}
#[must_use]
pub fn group(diagnostics: Vec<Diagnostic>) -> Vec<Diagnostic> {
let mut groups: Vec<Diagnostic> = Vec::with_capacity(diagnostics.len());
let mut keys: std::collections::HashMap<(String, String, String), usize> =
std::collections::HashMap::new();
for diagnostic in diagnostics {
let key = (
diagnostic.code.clone(),
without_indexes(&diagnostic.message),
diagnostic.path.starred(),
);
if let Some(&index) = keys.get(&key) {
let first = &mut groups[index];
first.count += diagnostic.count;
for path in std::iter::once(diagnostic.path).chain(diagnostic.also) {
if first.also.len() < MAX_ALSO {
first.also.push(path);
}
}
} else {
keys.insert(key, groups.len());
groups.push(diagnostic);
}
}
groups
}
fn without_indexes(message: &str) -> String {
let mut out = String::with_capacity(message.len());
let mut chars = message.chars().peekable();
while let Some(char) = chars.next() {
out.push(char);
if char == '[' && chars.peek().is_some_and(char::is_ascii_digit) {
while chars.peek().is_some_and(char::is_ascii_digit) {
chars.next();
}
out.push('*');
}
}
out
}
#[must_use]
pub fn excerpt(source: &str, span: crate::tree::Span) -> Option<String> {
let text = source.get(span.offset..span.end())?;
if text.len() <= MAX_EXCERPT_BYTES {
return Some(text.to_owned());
}
let mut end = MAX_EXCERPT_BYTES;
while !text.is_char_boundary(end) {
end -= 1;
}
Some(text[..end].to_owned())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::codes::{SHAPE_MISSING_FIELD, SHAPE_UNKNOWN_FIELD};
use crate::path::Path;
use crate::tree::Span;
fn span(offset: usize) -> Span {
Span {
offset,
length: 1,
line: 1,
column: u32::try_from(offset + 1).unwrap(),
}
}
#[test]
fn orders_by_place_then_severity() {
let root = Path::root("doc");
let mut collected = Collector::default();
collected.push(Diagnostic::new(&SHAPE_UNKNOWN_FIELD, root.key("b"), "b").at(Some(span(9))));
collected.push(Diagnostic::new(
&SHAPE_UNKNOWN_FIELD,
root.key("none"),
"none",
));
collected.push(Diagnostic::new(&SHAPE_UNKNOWN_FIELD, root.key("a"), "a").at(Some(span(2))));
let report = Report::assemble("doc", false, collected, None, &Options::default());
let paths: Vec<String> = report
.diagnostics
.iter()
.map(|diagnostic| diagnostic.path.to_string())
.collect();
assert_eq!(paths, ["doc.a", "doc.b", "doc.none"]);
}
#[test]
fn groups_one_problem_over_a_list_and_caps() {
let root = Path::root("doc");
let mut collected = Collector::new(6);
for index in 0..8 {
collected.push(
Diagnostic::new(
&SHAPE_MISSING_FIELD,
root.key("items").index(index),
format!("items[{index}] lacks id"),
)
.at(Some(span(index * 10))),
);
}
let options = Options {
limit: 1,
..Options::default()
};
let report = Report::assemble("doc", false, collected, None, &options);
assert_eq!(report.diagnostics.len(), 1);
assert_eq!(report.diagnostics[0].count, 6);
assert_eq!(report.diagnostics[0].also.len(), MAX_ALSO);
assert_eq!(report.omitted, 2);
assert_eq!(report.counts().errors, 6);
}
#[test]
fn excerpt_cuts_at_a_character_boundary() {
let source = "\u{e9}".repeat(300);
let span = Span {
offset: 0,
length: source.len(),
line: 1,
column: 1,
};
let cut = excerpt(&source, span).unwrap();
assert_eq!(cut.len(), MAX_EXCERPT_BYTES);
}
}