specfold_core/check/
runner.rs1use super::context::{Ctx, Options};
4use super::finding::Finding;
5use super::rules::catalog;
6use super::scope::{Range, Scope};
7use crate::corpus::Corpus;
8use crate::graph::Graph;
9use crate::plugins;
10use anyhow::Result;
11use rayon::prelude::*;
12
13#[derive(Debug, Clone, Default)]
14pub struct Selection {
15 pub only: Vec<String>,
17 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 pub checked_paths: Option<std::collections::BTreeSet<String>>,
28}
29
30impl Report {
31 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 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}