1use schemars::JsonSchema;
5use serde::Serialize;
6
7use super::{Finding, FixOp};
8use crate::{Error, Expr, RepoPath, Scope};
9
10#[derive(Debug, Clone, Default, PartialEq, Eq)]
13pub struct Report {
14 pub errors: Vec<Finding>,
16 pub warnings: Vec<Finding>,
18 pub fixes: Vec<FixOp>,
21}
22impl Report {
25 pub fn push(&mut self, mut finding: Finding) {
30 finding.rule_line = None;
31 match finding.severity {
32 super::Severity::Error => self.errors.push(finding),
33 super::Severity::Warning => self.warnings.push(finding),
34 }
35 }
36
37 pub fn extend(&mut self, findings: impl IntoIterator<Item = Finding>) {
39 for f in findings {
40 self.push(f);
41 }
42 }
43
44 #[must_use]
49 pub fn finish(mut self) -> Self {
50 for list in [&mut self.errors, &mut self.warnings] {
51 list.sort_by(|a, b| {
52 (&a.path, a.line, &a.message, &a.criterion).cmp(&(
53 &b.path,
54 b.line,
55 &b.message,
56 &b.criterion,
57 ))
58 });
59 list.dedup();
60 }
61 let failed = |f: &Finding| f.criterion == crate::compare::WARNING;
67 let mut kept = self
68 .warnings
69 .iter()
70 .filter(|f| failed(f))
71 .min_by_key(|f| !f.message.contains("doesn't start"))
72 .cloned();
73 if let Some(one) = kept.as_mut()
74 && let Some((head, _)) = file_of(&one.message)
75 {
76 let mut files: Vec<String> = self
77 .warnings
78 .iter()
79 .filter(|f| failed(f))
80 .filter_map(|f| file_of(&f.message).filter(|(h, _)| *h == head))
81 .map(|(_, file)| file.to_string())
82 .collect();
83 files.sort();
84 files.dedup();
85 one.message = format!("{head} {}", super::and_list(&files));
86 }
87 self.warnings.retain(|f| !failed(f));
88 self.warnings.extend(kept);
89 self.warnings
90 .sort_by(|a, b| (&a.path, a.line).cmp(&(&b.path, b.line)));
91 self.fixes.sort_by(|a, b| fix_key(a).cmp(&fix_key(b)));
92 self.fixes.dedup();
93 self
94 }
95
96 #[must_use]
100 pub fn filter(&self, scope: &Scope) -> Report {
101 let keep = |list: &[Finding]| -> Vec<Finding> {
102 list.iter()
103 .filter(|f| scope.contains(&f.path) || f.criterion == crate::compare::WARNING)
106 .cloned()
107 .collect()
108 };
109 Report {
110 errors: keep(&self.errors),
111 warnings: keep(&self.warnings),
112 fixes: self.fixes.clone(),
113 }
114 }
115
116 pub fn has_errors(&self) -> bool {
118 !self.errors.is_empty()
119 }
120
121 pub fn project(&self, expr: &Expr) -> crate::Result<serde_json::Value> {
126 let value = serde_json::to_value(self).map_err(|e| Error::Internal(e.to_string()))?;
127 expr.eval(&value)
128 }
129}
130
131fn fix_key(op: &FixOp) -> (u8, &RepoPath) {
134 match op {
135 FixOp::Moved { from, .. } => (0, from),
136 FixOp::Created { path } => (1, path),
137 FixOp::Rewrote { path } => (2, path),
138 }
139}
140
141fn file_of(message: &str) -> Option<(&str, &str)> {
145 let at = message.rfind(" `")?;
146 message
147 .ends_with('`')
148 .then(|| (&message[..at], &message[at + 1..]))
149}
150
151#[derive(Serialize, JsonSchema)]
156#[schemars(title = "sokf validate report")]
157pub struct ValidateReport {
158 errors: Vec<FindingJson>,
160 warnings: Vec<FindingJson>,
162 fixes: Vec<FixJson>,
165 summary: SummaryJson,
167}
168
169#[derive(Serialize, JsonSchema)]
173#[schemars(rename = "Summary")]
174struct SummaryJson {
175 errors: usize,
177 warnings: usize,
179 fixes: usize,
181}
182
183#[derive(Serialize, JsonSchema)]
185#[schemars(rename = "Finding")]
186struct FindingJson {
187 path: String,
190 #[serde(default, skip_serializing_if = "Option::is_none")]
192 #[schemars(with = "usize")]
193 line: Option<usize>,
194 message: String,
199}
200
201#[derive(Serialize, JsonSchema)]
203#[serde(tag = "op", rename_all = "lowercase")]
204#[schemars(rename = "Fix")]
205enum FixJson {
206 Moved {
208 from: String,
210 to: String,
212 },
213 Created {
215 path: String,
217 },
218 Rewrote {
220 path: String,
222 },
223}
224
225impl From<&Finding> for FindingJson {
226 fn from(f: &Finding) -> Self {
227 FindingJson {
228 path: f.path.as_str().to_string(),
229 line: f.line,
230 message: super::message(f),
231 }
232 }
233}
234
235impl From<&FixOp> for FixJson {
236 fn from(op: &FixOp) -> Self {
237 match op {
238 FixOp::Moved { from, to } => FixJson::Moved {
239 from: from.as_str().to_string(),
240 to: to.as_str().to_string(),
241 },
242 FixOp::Created { path } => FixJson::Created {
243 path: path.as_str().to_string(),
244 },
245 FixOp::Rewrote { path } => FixJson::Rewrote {
246 path: path.as_str().to_string(),
247 },
248 }
249 }
250}
251
252impl From<&Report> for ValidateReport {
253 fn from(r: &Report) -> Self {
254 ValidateReport {
255 errors: r.errors.iter().map(FindingJson::from).collect(),
256 warnings: r.warnings.iter().map(FindingJson::from).collect(),
257 fixes: r.fixes.iter().map(FixJson::from).collect(),
258 summary: SummaryJson {
259 errors: r.errors.len(),
260 warnings: r.warnings.len(),
261 fixes: r.fixes.len(),
262 },
263 }
264 }
265}
266
267impl Serialize for Report {
270 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
271 ValidateReport::from(self).serialize(s)
272 }
273}
274
275#[cfg(test)]
276mod tests {
277 use proptest::prelude::*;
278
279 use super::*;
280 use crate::Severity;
281
282 fn p(s: &str) -> RepoPath {
283 RepoPath::parse(s).unwrap()
284 }
285
286 fn finding(path: &str, line: Option<usize>, msg: &str) -> Finding {
287 Finding::error(p(path), line, "SOKF_FORMAT_53", msg)
288 }
289
290 #[test]
291 fn json_has_the_shape_of_the_tool_spec() {
292 let mut r = Report::default();
293 r.push(finding("/knowledge/a.md", Some(41), "x"));
294 r.push(Finding::warning(p("/b.md"), None, "SOKF_VALIDATION_4", "w"));
295 r.fixes.push(FixOp::Rewrote {
296 path: p("/knowledge/a.md"),
297 });
298 r.fixes.push(FixOp::Moved {
299 from: p("/k/open/i.md"),
300 to: p("/k/closed/i.md"),
301 });
302 r.fixes.push(FixOp::Created {
303 path: p("/k/closed/index.md"),
304 });
305 let r = r.finish();
306 let json = serde_json::to_value(&r).unwrap();
307 assert_eq!(
308 json,
309 serde_json::json!({
310 "errors": [{"path": "/knowledge/a.md", "line": 41, "message": "x (SOKF_FORMAT_53)"}],
311 "warnings": [{"path": "/b.md", "message": "w (SOKF_VALIDATION_4)"}],
312 "fixes": [
313 {"op": "moved", "from": "/k/open/i.md", "to": "/k/closed/i.md"},
314 {"op": "created", "path": "/k/closed/index.md"},
315 {"op": "rewrote", "path": "/knowledge/a.md"}
316 ],
317 "summary": {"errors": 1, "warnings": 1, "fixes": 3}
318 })
319 );
320 assert!(r.has_errors());
321 assert!(!Report::default().has_errors());
322 let expr = Expr::compile("errors[].path").unwrap();
323 assert_eq!(
324 r.project(&expr).unwrap(),
325 serde_json::json!(["/knowledge/a.md"])
326 );
327 assert_eq!(
328 r.project(&Expr::compile("length(warnings)").unwrap())
329 .unwrap(),
330 serde_json::json!(1)
331 );
332 }
333
334 #[test]
335 fn filter_keeps_findings_in_scope_and_every_fix() {
336 let mut r = Report::default();
337 r.push(finding("/k/a.md", None, "x"));
338 r.push(finding("/other.md", None, "y"));
339 r.push(Finding::warning(
340 p("/k/b.md"),
341 None,
342 "SOKF_VALIDATION_4",
343 "w",
344 ));
345 r.fixes.push(FixOp::Rewrote {
346 path: p("/other.md"),
347 });
348 let mut scope = Scope::default();
349 scope.dirs.insert(p("/k"));
350 let filtered = r.filter(&scope);
351 assert_eq!(filtered.errors.len(), 1);
352 assert_eq!(filtered.warnings.len(), 1);
353 assert_eq!(filtered.fixes.len(), 1);
354 assert_eq!(r.filter(&Scope::all()), r);
355 }
356
357 fn arb_finding() -> impl Strategy<Value = Finding> {
358 (
359 prop::sample::select(vec!["/a.md", "/b/c.md", "/b/a.md", "/z.md"]),
360 prop::option::of(1usize..50),
361 prop::sample::select(vec!["m1", "m2"]),
362 any::<bool>(),
363 )
364 .prop_map(|(path, line, msg, warn)| {
365 let severity = if warn {
366 Severity::Warning
367 } else {
368 Severity::Error
369 };
370 Finding::new(p(path), line, severity, "SOKF_FORMAT_53", msg)
371 })
372 }
373
374 proptest! {
377 #![proptest_config(crate::proptest_cases::cases(256))]
378
379 #[test]
380 fn finish_orders_by_path_then_line_and_dedups(findings in prop::collection::vec(arb_finding(), 0..12)) {
381 let mut r = Report::default();
382 r.extend(findings.clone());
383 r.fixes.push(FixOp::Rewrote { path: p("/z.md") });
384 r.fixes.push(FixOp::Moved { from: p("/b.md"), to: p("/c.md") });
385 r.fixes.push(FixOp::Rewrote { path: p("/a.md") });
386 r.fixes.push(FixOp::Created { path: p("/z/index.md") });
387 r.fixes.push(FixOp::Moved { from: p("/a.md"), to: p("/c.md") });
388 r.fixes.push(FixOp::Created { path: p("/c/index.md") });
389 let r = r.finish();
390 for list in [&r.errors, &r.warnings] {
391 for w in list.windows(2) {
392 prop_assert!((&w[0].path, w[0].line) <= (&w[1].path, w[1].line));
393 prop_assert_ne!(&w[0], &w[1]);
394 }
395 }
396 prop_assert!(r.errors.iter().all(|f| f.severity == Severity::Error));
397 prop_assert!(r.warnings.iter().all(|f| f.severity == Severity::Warning));
398 let mut expected: Vec<_> = findings.clone();
399 expected.sort();
400 expected.dedup();
401 prop_assert_eq!(r.errors.len() + r.warnings.len(), expected.len());
402 prop_assert_eq!(&r.fixes, &vec![
403 FixOp::Moved { from: p("/a.md"), to: p("/c.md") },
404 FixOp::Moved { from: p("/b.md"), to: p("/c.md") },
405 FixOp::Created { path: p("/c/index.md") },
406 FixOp::Created { path: p("/z/index.md") },
407 FixOp::Rewrote { path: p("/a.md") },
408 FixOp::Rewrote { path: p("/z.md") },
409 ]);
410 }
411 }
412
413 proptest! {
415 #![proptest_config(crate::proptest_cases::cases(256))]
416
417 #[test]
418 fn json_shape_and_finding_round_trip(findings in prop::collection::vec(arb_finding(), 0..6)) {
419 let mut r = Report::default();
420 r.extend(findings.clone());
421 let text = serde_json::to_string(&r).unwrap();
422 let e = text.find("\"errors\":").unwrap();
423 let w = text.find("\"warnings\":").unwrap();
424 let f = text.find("\"fixes\":").unwrap();
425 let sum = text.find("\"summary\":").unwrap();
426 prop_assert!(e < w && w < f && f < sum, "{text}");
427 let json: serde_json::Value = serde_json::from_str(&text).unwrap();
428 let obj = json.as_object().unwrap();
429 prop_assert_eq!(obj.len(), 4);
430 prop_assert_eq!(obj["summary"]["errors"].as_u64(), Some(r.errors.len() as u64));
431 for entry in obj["errors"].as_array().unwrap().iter().chain(obj["warnings"].as_array().unwrap()) {
432 let e = entry.as_object().unwrap();
433 prop_assert!(e.contains_key("path") && e.contains_key("message"));
434 prop_assert!(e["path"].as_str().unwrap().starts_with('/'));
435 prop_assert!(e.keys().all(|k| k == "path" || k == "line" || k == "message"));
436 }
437 for f in findings {
438 let back: Finding = serde_json::from_str(&serde_json::to_string(&f).unwrap()).unwrap();
439 prop_assert_eq!(back, f);
440 }
441 }
442 }
443
444 #[test]
449 fn the_warnings_of_a_formatter_name_every_file_once() {
450 let warning = |message: &str| {
451 super::Finding::warning(
452 crate::RepoPath::parse("/.sokf/config.toml").unwrap(),
453 None,
454 crate::compare::WARNING,
455 message,
456 )
457 };
458 let mut report = Report::default();
459 report
460 .warnings
461 .push(warning("the formatter fmt fails on `/src/b.css`"));
462 report
463 .warnings
464 .push(warning("the formatter fmt fails on `/src/a.css`"));
465 report
466 .warnings
467 .push(warning("the formatter fmt fails on `/src/a.css`"));
468 let report = report.finish();
469 assert_eq!(report.warnings.len(), 1, "{:?}", report.warnings);
470 assert_eq!(
471 report.warnings[0].message,
472 "the formatter fmt fails on `/src/a.css` and `/src/b.css`"
473 );
474 let mut report = Report::default();
475 report
476 .warnings
477 .push(warning("the formatter fmt fails on `/src/b.css`"));
478 report.warnings.push(warning(
479 "the formatter fmt doesn't start: `fmt` names no file",
480 ));
481 let report = report.finish();
482 assert_eq!(report.warnings.len(), 1, "{:?}", report.warnings);
483 assert!(report.warnings[0].message.contains("doesn't start"));
484 }
485}