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    /// Gitlinks the change adds or moves, each one event (see `Scope.gitlinks`).
29    pub gitlinks: Vec<crate::workspace::vcs::GitlinkMove>,
30    /// W1: a full run's warning counts held against `[ratchet] file`; None when not judged.
31    pub ratchet: Option<super::limits::ratchet::Judged>,
32}
33
34impl Report {
35    /// D2: whether this run judged the baseline key `RULE<TAB>path`. A ranged run reports nothing
36    /// outside its range and no run reports a rule it skipped, so only such entries can be said
37    /// to hold fewer errors now. Plugin rules always run with the rest.
38    pub fn judged(&self, key: &str) -> bool {
39        let (rule, path) = key.split_once('\t').unwrap_or((key, ""));
40        (rule.starts_with("x.") || self.rules_run.contains(&rule))
41            && self.checked_paths.as_ref().is_none_or(|p| p.contains(path))
42    }
43}
44
45pub fn run(c: &Corpus, g: &Graph, range: Range, opts: &Options, sel: &Selection) -> Result<Report> {
46    let t = std::time::Instant::now();
47    let scope = Scope::build(c, g, range)?;
48    let t = crate::trace::phase("scope", t);
49    let ctx = Ctx { corpus: c, graph: g, scope: &scope, opts };
50    let staged = matches!(scope.range, Range::Staged);
51    let rules: Vec<_> = catalog()
52        .into_iter()
53        .filter(|r| {
54            let id = r.info().id;
55            (sel.only.is_empty() || sel.only.iter().any(|o| o == id))
56                && !sel.skip.iter().any(|s| s == id)
57                && (!staged || r.info().on_commit)
58        })
59        .collect();
60    let mut findings: Vec<Finding> = rules
61        .par_iter()
62        .flat_map(|r| {
63            let mut out = vec![];
64            let t = std::time::Instant::now();
65            r.run(&ctx, &mut out);
66            crate::trace::rule(r.info().id, t);
67            out
68        })
69        .collect();
70    let wants_plugins = sel.only.is_empty() || sel.only.iter().any(|o| o.starts_with("x."));
71    if wants_plugins && !c.cfg.raw.plugins.is_empty() && !sel.skip.iter().any(|s| s == "x") {
72        let loaded = plugins::load(&c.cfg);
73        plugins::rules::run(&ctx, &loaded, &mut findings);
74    }
75    let t = crate::trace::phase("rules", t);
76    let mut findings = super::severity::apply(c, findings);
77    crate::trace::phase("severity", t);
78    order(&mut findings);
79    findings.dedup_by(|a, b| a.rule == b.rule && a.path == b.path && a.line == b.line && a.message == b.message);
80    let rules_run: Vec<&'static str> = rules.iter().map(|r| r.info().id).collect();
81    // W1 counts what the other rules found, so it runs after them, on full runs only.
82    let ratchet = if scope.is_all() && rules_run.contains(&"W1") {
83        let mut held = vec![];
84        let j = super::limits::ratchet::findings(c, g, &findings, &rules_run, &mut held);
85        findings.extend(held);
86        order(&mut findings);
87        j
88    } else {
89        None
90    };
91    let docs_checked = if scope.is_all() { c.docs.len() } else { scope.with_neighbours.len() };
92    let checked_paths = (!scope.is_all()).then(|| {
93        let docs =
94            scope.with_neighbours.iter().flat_map(|&i| std::iter::once(&c.docs[i].path).chain(&c.docs[i].chapters));
95        scope.paths.iter().chain(&scope.gone).chain(docs).cloned().collect()
96    });
97    Ok(Report { findings, rules_run, docs_checked, checked_paths, gitlinks: scope.gitlinks.clone(), ratchet })
98}
99
100/// Findings by level, a secret first within its level (it is what to fix before anything else,
101/// and an attachment that changed because of it should not be re-attached first), then by place.
102fn order(findings: &mut [Finding]) {
103    let secret = |f: &Finding| f.rule == "U2" || (f.rule == "U1" && f.message.starts_with("[secrets]"));
104    findings.sort_by(|a, b| {
105        (a.severity, !secret(a), &a.path, a.line, &a.rule).cmp(&(b.severity, !secret(b), &b.path, b.line, &b.rule))
106    });
107}