Skip to main content

specfold_core/check/
runner.rs

1//! Runs the selected rules and orders their findings.
2
3use super::context::{Ctx, Options};
4use super::finding::Finding;
5use super::rules::catalog;
6use super::scope::{Range, Scope};
7use crate::corpus::Corpus;
8use crate::corpus::graph::Graph;
9use crate::plugins;
10use anyhow::Result;
11use rayon::prelude::*;
12
13#[derive(Debug, Clone, Default)]
14pub struct Selection {
15    /// Only these rule ids; empty means all.
16    pub only: Vec<String>,
17    /// Skip these rule ids.
18    pub skip: Vec<String>,
19}
20
21pub struct Report {
22    pub findings: Vec<Finding>,
23    pub rules_run: Vec<&'static str>,
24    pub docs_checked: usize,
25    /// D2: the paths a ranged or staged run looked at (changed files and the files of the
26    /// documents it checked); `None` for a full run, which looks at everything.
27    pub checked_paths: Option<std::collections::BTreeSet<String>>,
28}
29
30impl Report {
31    /// D2: whether this run judged the baseline key `RULE<TAB>path`. A ranged run reports nothing
32    /// outside its range and no run reports a rule it skipped, so only such entries can be said
33    /// to hold fewer errors now. Plugin rules always run with the rest.
34    pub fn judged(&self, key: &str) -> bool {
35        let (rule, path) = key.split_once('\t').unwrap_or((key, ""));
36        (rule.starts_with("x.") || self.rules_run.contains(&rule))
37            && self.checked_paths.as_ref().is_none_or(|p| p.contains(path))
38    }
39}
40
41pub fn run(c: &Corpus, g: &Graph, range: Range, opts: &Options, sel: &Selection) -> Result<Report> {
42    let t = std::time::Instant::now();
43    let scope = Scope::build(c, g, range)?;
44    let t = crate::trace::phase("scope", t);
45    let ctx = Ctx { corpus: c, graph: g, scope: &scope, opts };
46    let staged = matches!(scope.range, Range::Staged);
47    let rules: Vec<_> = catalog()
48        .into_iter()
49        .filter(|r| {
50            let id = r.info().id;
51            (sel.only.is_empty() || sel.only.iter().any(|o| o == id))
52                && !sel.skip.iter().any(|s| s == id)
53                && (!staged || r.info().on_commit)
54        })
55        .collect();
56    let mut findings: Vec<Finding> = rules
57        .par_iter()
58        .flat_map(|r| {
59            let mut out = vec![];
60            let t = std::time::Instant::now();
61            r.run(&ctx, &mut out);
62            crate::trace::rule(r.info().id, t);
63            out
64        })
65        .collect();
66    let wants_plugins = sel.only.is_empty() || sel.only.iter().any(|o| o.starts_with("x."));
67    if wants_plugins && !c.cfg.raw.plugins.is_empty() && !sel.skip.iter().any(|s| s == "x") {
68        let loaded = plugins::load(&c.cfg);
69        plugins::rules::run(&ctx, &loaded, &mut findings);
70    }
71    let t = crate::trace::phase("rules", t);
72    let mut findings = super::severity::apply(c, findings);
73    crate::trace::phase("severity", t);
74    // A secret comes first among findings of its level: it is what to fix before anything else,
75    // and an attachment that changed because of it (E1) should not be re-attached first.
76    let secret = |f: &Finding| f.rule == "U2" || (f.rule == "U1" && f.message.starts_with("[secrets]"));
77    findings.sort_by(|a, b| {
78        (a.severity, !secret(a), &a.path, a.line, &a.rule).cmp(&(b.severity, !secret(b), &b.path, b.line, &b.rule))
79    });
80    findings.dedup_by(|a, b| a.rule == b.rule && a.path == b.path && a.line == b.line && a.message == b.message);
81    let docs_checked = if scope.is_all() { c.docs.len() } else { scope.with_neighbours.len() };
82    let checked_paths = (!scope.is_all()).then(|| {
83        let docs =
84            scope.with_neighbours.iter().flat_map(|&i| std::iter::once(&c.docs[i].path).chain(&c.docs[i].chapters));
85        scope.paths.iter().chain(&scope.gone).chain(docs).cloned().collect()
86    });
87    Ok(Report { findings, rules_run: rules.iter().map(|r| r.info().id).collect(), docs_checked, checked_paths })
88}