Skip to main content

sokf_core/report/
collect.rs

1//! `Report` is the result of a run. This module orders it and serialises it
2//! as CLI-4 specifies.
3
4use schemars::JsonSchema;
5use serde::Serialize;
6
7use super::{Finding, FixOp};
8use crate::{Error, Expr, RepoPath, Scope};
9
10// sokf:begin report
11/// `Report` holds the errors, the warnings, and the fixes of a run.
12#[derive(Debug, Clone, Default, PartialEq, Eq)]
13pub struct Report {
14    /// The errors, which `finish` orders by path, then by line.
15    pub errors: Vec<Finding>,
16    /// The warnings, which `finish` orders as it orders the errors.
17    pub warnings: Vec<Finding>,
18    /// The fixes, which `finish` orders with the moves first, then the created
19    /// files, then the rewritten files, each group by path.
20    pub fixes: Vec<FixOp>,
21}
22// sokf:end report
23
24impl Report {
25    /// `push` adds a finding to the errors or to the warnings, according to its
26    /// severity. The report drops the finding's `rule_line`, which the report
27    /// doesn't print and the cache doesn't store, so that a finding read from
28    /// the cache equals the same finding made fresh.
29    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    /// `extend` adds every finding in `findings`, as `push` adds one.
38    pub fn extend(&mut self, findings: impl IntoIterator<Item = Finding>) {
39        for f in findings {
40            self.push(f);
41        }
42    }
43
44    /// `finish` orders the findings by path, then by line, removes duplicate
45    /// findings and fixes, and orders the fixes as CLI-4_AC-6 lists them.
46    // sokf-implements: CLI-4_AC-6
47    // sokf-implements: CLI-4_AC-9
48    #[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        // A report holds one warning that the formatter failed, whatever
62        // the runs whose outputs it gathers said, and the reason that the
63        // formatter doesn't start comes first (CLI-4_AC-49).
64        // A warning that the formatter failed on a file names every file
65        // that it failed on in the same way.
66        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    /// `filter` returns a report of the findings in `scope`. It keeps every
97    /// fix, whatever its path.
98    // sokf-implements: CLI-4_AC-2
99    #[must_use]
100    pub fn filter(&self, scope: &Scope) -> Report {
101        let keep = |list: &[Finding]| -> Vec<Finding> {
102            list.iter()
103                // The warning that the formatter failed explains the stale
104                // blocks of any scope, so every run reports it.
105                .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    /// `has_errors` returns whether the run found an error.
117    pub fn has_errors(&self) -> bool {
118        !self.errors.is_empty()
119    }
120
121    /// `project` serialises the report as JSON and evaluates `expr` against the
122    /// result (CLI-4_AC-14).
123    // sokf-implements: CLI-4_AC-14
124    // sokf-implements: CLI-4_AC-17
125    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
131/// `fix_key` returns the sort key of a fix: first its group (moves, then
132/// created files, then rewritten files), then its path.
133fn 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
141/// `file_of` splits the message of a warning that the formatter failed on a
142/// file into the words before the file and the file in backticks, where the
143/// message ends with one.
144fn 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/// `ValidateReport` is the report that `sokf validate --json` prints. It holds every error,
152/// every warning, and each repair by `--fix` (CLI-4_AC-12).
153// `Report` serialises itself as a `ValidateReport`, and the tool publishes the schema of
154// `ValidateReport`.
155#[derive(Serialize, JsonSchema)]
156#[schemars(title = "sokf validate report")]
157pub struct ValidateReport {
158    /// Every error, ordered by path, then by line.
159    errors: Vec<FindingJson>,
160    /// Every warning, ordered by path, then by line.
161    warnings: Vec<FindingJson>,
162    /// The repairs that `--fix` made: the moves first, then the created files, then the rewritten
163    /// files, with each group ordered by path. The list is empty when the command runs without `--fix`.
164    fixes: Vec<FixJson>,
165    /// The number of errors, warnings, and fixes in the report.
166    summary: SummaryJson,
167}
168
169/// The summary holds the number of errors, warnings, and fixes in the report. The line of counts
170/// of the text output shows the same counts of errors and warnings (CLI-4_AC-31).
171// sokf-implements: CLI-4_AC-31
172#[derive(Serialize, JsonSchema)]
173#[schemars(rename = "Summary")]
174struct SummaryJson {
175    /// The number of errors.
176    errors: usize,
177    /// The number of warnings.
178    warnings: usize,
179    /// The number of repairs that `--fix` made.
180    fixes: usize,
181}
182
183/// One finding.
184#[derive(Serialize, JsonSchema)]
185#[schemars(rename = "Finding")]
186struct FindingJson {
187    /// The path of the file where the finding occurs, relative to the repository root and
188    /// starting with `/`.
189    path: String,
190    /// The line of the finding in the file. It is absent when no line applies.
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    #[schemars(with = "usize")]
193    line: Option<usize>,
194    /// What is wrong, followed in parentheses by the key of the criterion that the file
195    /// breaks, such as `SOKF_FORMAT_53` or `TLMD_152`. When a schema rule raises the finding,
196    /// the id of the schema comes in parentheses before the key. When the finding has the place
197    /// of the rule in the schema, that place comes in the parentheses too.
198    message: String,
199}
200
201/// One repair that `--fix` made.
202#[derive(Serialize, JsonSchema)]
203#[serde(tag = "op", rename_all = "lowercase")]
204#[schemars(rename = "Fix")]
205enum FixJson {
206    /// A file moved to the directory of its lifecycle state.
207    Moved {
208        /// The path before the move.
209        from: String,
210        /// The path after the move.
211        to: String,
212    },
213    /// A file that `--fix` created, such as an index.
214    Created {
215        /// The file.
216        path: String,
217    },
218    /// A file that `--fix` rewrote.
219    Rewrote {
220        /// The file.
221        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
267// sokf-implements: CLI-4_AC-12
268// sokf-implements: CLI-4_AC-13
269impl 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    // sokf-tests: CLI-4_AC-6
375    // sokf-tests: CLI-4_AC-9
376    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    // sokf-tests: CLI-4_AC-12
414    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    // The warnings that the formatter failed on files make one warning that
445    // names every such file, and a warning that it doesn't start comes before
446    // them (CLI-4_AC-49).
447    // sokf-tests: CLI-4_AC-49
448    #[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}