Skip to main content

specfold_core/check/guards/scan/
range.rs

1//! What a guard looks at: the index, the commits about to be pushed, or the whole tree.
2
3use crate::workspace::vcs;
4use anyhow::{Result, anyhow};
5use std::path::Path;
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum GuardRange {
9    Staged,
10    /// A git range such as `origin/main..HEAD`; `None` means upstream..HEAD.
11    Push(Option<String>),
12    All,
13}
14
15impl GuardRange {
16    pub fn parse(s: &str) -> Self {
17        match s {
18            "staged" => GuardRange::Staged,
19            "all" => GuardRange::All,
20            "push" => GuardRange::Push(None),
21            other => GuardRange::Push(Some(other.to_string())),
22        }
23    }
24}
25
26/// Where file contents are read from for a range.
27#[derive(Debug, Clone)]
28pub enum Source {
29    Index,
30    Rev(String),
31    WorkTree,
32}
33
34pub struct Resolved {
35    pub files: Vec<String>,
36    pub source: Source,
37    /// The git range for commit scanning, when there is one.
38    pub commits: Option<String>,
39    /// C231: versions the range's commits wrote that its end no longer has.
40    pub passing: Vec<vcs::Passing>,
41}
42
43/// Every file under `bases` (repository-relative directories; the whole repository when empty):
44/// the untracked ones the ignore files allow, and every tracked one even when an ignore file
45/// matches it, since a tracked file is published. Walking only where a guard looks keeps it cheap.
46fn walk(root: &Path, bases: &[String]) -> Vec<String> {
47    let dirs: Vec<std::path::PathBuf> = match bases {
48        [] => vec![root.to_path_buf()],
49        b => b.iter().map(|p| root.join(p)).filter(|p| p.exists()).collect(),
50    };
51    let Some(walk) = crate::workspace::walk_across(&dirs) else { return vec![] };
52    let mut files: Vec<String> = walk
53        .build()
54        .flatten()
55        .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
56        .filter_map(|e| crate::paths::rel_of(root, e.path()))
57        .collect();
58    let existing = vcs::tracked(root, bases).unwrap_or_default().into_iter().filter(|p| root.join(p).is_file());
59    files.extend(existing);
60    files.sort();
61    files.dedup();
62    files
63}
64
65pub fn resolve(root: &Path, range: &GuardRange, bases: &[String]) -> Result<Resolved> {
66    match range {
67        GuardRange::Staged => Ok(Resolved {
68            files: vcs::staged(root).ok_or_else(|| anyhow!("--staged needs a git repository"))?,
69            source: Source::Index,
70            commits: None,
71            passing: vec![],
72        }),
73        GuardRange::Push(r) => {
74            let r = match r {
75                Some(r) => r.clone(),
76                None => format!(
77                    "{}..HEAD",
78                    vcs::upstream(root).ok_or_else(|| anyhow!("no upstream branch; pass --range <base>..HEAD"))?
79                ),
80            };
81            let files = vcs::changed_in_range(root, &r).ok_or_else(|| anyhow!("cannot read the range {r}"))?;
82            // C230: contents come from the range's end, not from whatever is checked out.
83            let source = Source::Rev(vcs::range_end(&r));
84            Ok(Resolved { files, source, passing: vcs::passing(root, &r), commits: Some(r) })
85        }
86        GuardRange::All => {
87            Ok(Resolved { files: walk(root, bases), source: Source::WorkTree, commits: None, passing: vec![] })
88        }
89    }
90}
91
92pub fn read(root: &Path, source: &Source, path: &str) -> Option<Vec<u8>> {
93    match source {
94        Source::Index => vcs::show_staged(root, path).map(String::into_bytes),
95        Source::Rev(rev) => vcs::show(root, rev, path).map(String::into_bytes),
96        Source::WorkTree => std::fs::read(root.join(path)).ok(),
97    }
98}