Skip to main content

specfold_core/check/
scope.rs

1//! Which documents a run looks at: all of them, or the ones touched by a change and the
2//! documents that point at them.
3
4use crate::corpus::Corpus;
5use crate::corpus::graph::Graph;
6use crate::workspace::vcs;
7use anyhow::{Result, anyhow};
8use std::collections::BTreeSet;
9
10#[derive(Debug, Clone)]
11pub enum Range {
12    /// Everything.
13    All,
14    /// The index (pre-commit).
15    Staged,
16    /// Working tree and untracked files against a base revision (pre-push).
17    Changed(String),
18    /// What one commit changed (`<sha>^..<sha>`), judged on the files as they are now (C3).
19    Commit(String),
20    /// These repository files, documents or not, as they are on disk or in an overlay
21    /// (`spec check --path`); nothing is compared with a revision.
22    Paths(Vec<String>),
23}
24
25#[derive(Debug, Clone)]
26pub struct Scope {
27    pub range: Range,
28    /// Changed repository paths; empty for `All`.
29    pub paths: BTreeSet<String>,
30    /// The part of `paths` inside submodules whose gitlink the change moves; the outer index
31    /// cannot show them, so a staged run reads them from the submodule's checkout.
32    pub in_submodules: BTreeSet<String>,
33    /// Indices of documents whose own files changed.
34    pub touched: BTreeSet<usize>,
35    /// `touched` plus documents that link to them.
36    pub with_neighbours: BTreeSet<usize>,
37    /// The revision to compare against for transition checks.
38    pub base: Option<String>,
39    /// Paths the change deletes or renames away; they are not in `paths`.
40    pub gone: BTreeSet<String>,
41    /// Moved gitlinks whose submodule objects are missing; they stand for the whole directory.
42    pub submodules_missing: Vec<String>,
43    /// Gitlinks the change adds (a split, when outer files moved into one) or bumps, each read
44    /// as one event: files moved unchanged into a new gitlink are in neither `paths` nor `gone`.
45    pub gitlinks: Vec<vcs::GitlinkMove>,
46}
47
48/// The slug a document file carries: `sot/cart.sot.md` and `sot/cart/index.md` give `cart`.
49fn slug_of(p: &str) -> Option<&str> {
50    let mut parts = p.rsplit('/');
51    let file = parts.next()?;
52    let stem = file.split('.').next()?;
53    if stem == "index" || stem == "README" { parts.next() } else { Some(stem) }
54}
55
56/// Documents with a relation or link that now resolves to nothing and names a deleted slug or path.
57fn dangling(c: &Corpus, g: &Graph, slugs: &BTreeSet<&str>) -> Vec<usize> {
58    use crate::corpus::graph::{DOC_RELATIONS, Resolution};
59    let names = |t: &str| {
60        let t = t.split('#').next().unwrap_or(t).trim_end_matches('/');
61        let last = t.rsplit(['/', ':']).next().unwrap_or(t);
62        slugs.contains(last) || slug_of(t).is_some_and(|s| slugs.contains(s))
63    };
64    let missing = |t: &str| names(t) && matches!(g.resolve(t), Resolution::Missing);
65    let mut out = vec![];
66    for (i, d) in c.docs.iter().enumerate() {
67        let rel = d.rel().into_iter().filter(|(k, _)| DOC_RELATIONS.contains(&k.as_str())).flat_map(|(_, ts)| ts);
68        let mut targets = rel.chain(d.links.iter().map(|l| l.item.clone()));
69        if targets.any(|t| missing(&t)) {
70            out.push(i);
71        }
72    }
73    out
74}
75
76impl Scope {
77    pub fn build(c: &Corpus, g: &Graph, range: Range) -> Result<Self> {
78        let root = &c.cfg.spec_home;
79        let (mut paths, sub, base): (BTreeSet<String>, vcs::Expansion, _) = match &range {
80            Range::All => (BTreeSet::new(), vcs::Expansion::default(), None),
81            Range::Staged => {
82                let p = vcs::staged(root).ok_or_else(|| anyhow!("--staged needs a git repository"))?;
83                let sub = vcs::expand_submodules(root, vcs::Side::Staged);
84                (p.into_iter().collect(), sub, Some("HEAD".to_string()))
85            }
86            Range::Changed(base) => {
87                let p = vcs::changed_since(root, base).ok_or_else(|| anyhow!("cannot diff against {base}"))?;
88                let sub = vcs::expand_submodules(root, vcs::Side::Since(base));
89                (p.into_iter().collect(), sub, Some(base.clone()))
90            }
91            Range::Commit(sha) => {
92                let r = vcs::commit_diff(root, sha);
93                let p = vcs::changed_in_range(root, &r)
94                    .ok_or_else(|| anyhow!("cannot read commit {sha}; next: git log --oneline"))?;
95                (p.into_iter().collect(), vcs::Expansion::default(), Some(vcs::parent_or_empty(root, sha)))
96            }
97            Range::Paths(named) => (named.iter().cloned().collect(), vcs::Expansion::default(), None),
98        };
99        // C1: a moved pointer whose inside was read is not itself a change.
100        for g in &sub.expanded {
101            paths.remove(g);
102        }
103        let in_submodules: BTreeSet<String> = sub.files.into_iter().collect();
104        paths.extend(in_submodules.iter().cloned());
105        let mut gone: BTreeSet<String> = match &range {
106            Range::All | Range::Paths(_) => BTreeSet::new(),
107            Range::Staged => vcs::gone(root, None).unwrap_or_default().into_iter().collect(),
108            Range::Changed(base) => vcs::gone(root, Some(base)).unwrap_or_default().into_iter().collect(),
109            Range::Commit(sha) => {
110                vcs::gone(root, Some(&vcs::commit_diff(root, sha))).unwrap_or_default().into_iter().collect()
111            }
112        };
113        // A path that now lies inside a gitlink the change adds was moved there, not removed.
114        for m in sub.moves.iter().filter(|m| m.old.is_none()) {
115            for p in m.moved.iter().chain(&m.changed) {
116                gone.remove(p);
117            }
118        }
119        let mut touched = BTreeSet::new();
120        if !matches!(range, Range::All) {
121            for (i, d) in c.docs.iter().enumerate() {
122                let own = std::iter::once(&d.path).chain(&d.chapters).chain(&d.bundle_files);
123                if own.into_iter().any(|p| paths.contains(p)) {
124                    touched.insert(i);
125                }
126            }
127        }
128        let mut with_neighbours = touched.clone();
129        for &i in &touched {
130            for e in g.edges_to(i) {
131                with_neighbours.insert(e.from);
132            }
133        }
134        // N2: a deleted document is no longer in the corpus, so its citers cannot be found
135        // through edges; one pass over every link finds the ones that now point nowhere.
136        let slugs: BTreeSet<&str> = gone.iter().filter(|p| p.ends_with(".md")).filter_map(|p| slug_of(p)).collect();
137        if !slugs.is_empty() {
138            with_neighbours.extend(dangling(c, g, &slugs));
139        }
140        Ok(Scope {
141            range,
142            paths,
143            in_submodules,
144            touched,
145            with_neighbours,
146            base,
147            gone,
148            submodules_missing: sub.missing,
149            gitlinks: sub.moves,
150        })
151    }
152
153    pub fn is_all(&self) -> bool {
154        matches!(self.range, Range::All)
155    }
156
157    /// Whether checks about document `i` itself run.
158    pub fn covers(&self, i: usize) -> bool {
159        self.is_all() || self.touched.contains(&i)
160    }
161
162    /// Whether checks about links from document `i` run (they may break when a target moves).
163    pub fn covers_links(&self, i: usize) -> bool {
164        self.is_all() || self.with_neighbours.contains(&i)
165    }
166
167    pub fn covers_path(&self, p: &str) -> bool {
168        self.is_all() || self.paths.contains(p)
169    }
170}