Skip to main content

specfold_core/guards/
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 ignore::WalkBuilder;
6use std::path::Path;
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum GuardRange {
10    Staged,
11    /// A git range such as `origin/main..HEAD`; `None` means upstream..HEAD.
12    Push(Option<String>),
13    All,
14}
15
16impl GuardRange {
17    pub fn parse(s: &str) -> Self {
18        match s {
19            "staged" => GuardRange::Staged,
20            "all" => GuardRange::All,
21            "push" => GuardRange::Push(None),
22            other => GuardRange::Push(Some(other.to_string())),
23        }
24    }
25}
26
27/// Where file contents are read from for a range.
28#[derive(Debug, Clone)]
29pub enum Source {
30    Index,
31    Rev(String),
32    WorkTree,
33}
34
35pub struct Resolved {
36    pub files: Vec<String>,
37    pub source: Source,
38    /// The git range for commit scanning, when there is one.
39    pub commits: Option<String>,
40}
41
42pub fn resolve(root: &Path, range: &GuardRange) -> Result<Resolved> {
43    match range {
44        GuardRange::Staged => Ok(Resolved {
45            files: vcs::staged(root).ok_or_else(|| anyhow!("--staged needs a git repository"))?,
46            source: Source::Index,
47            commits: None,
48        }),
49        GuardRange::Push(r) => {
50            let r = match r {
51                Some(r) => r.clone(),
52                None => format!(
53                    "{}..HEAD",
54                    vcs::upstream(root).ok_or_else(|| anyhow!("no upstream branch; pass --range <base>..HEAD"))?
55                ),
56            };
57            let files = vcs::changed_in_range(root, &r).ok_or_else(|| anyhow!("cannot read the range {r}"))?;
58            Ok(Resolved { files, source: Source::Rev("HEAD".into()), commits: Some(r) })
59        }
60        GuardRange::All => {
61            let files = WalkBuilder::new(root)
62                .hidden(false)
63                .require_git(false)
64                .filter_entry(|e| e.file_name() != ".git")
65                .build()
66                .flatten()
67                .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
68                .filter_map(|e| e.path().strip_prefix(root).ok().map(|p| p.to_string_lossy().replace('\\', "/")))
69                .collect();
70            Ok(Resolved { files, source: Source::WorkTree, commits: None })
71        }
72    }
73}
74
75pub fn read(root: &Path, source: &Source, path: &str) -> Option<Vec<u8>> {
76    match source {
77        Source::Index => vcs::show_staged(root, path).map(String::into_bytes),
78        Source::Rev(rev) => vcs::show(root, rev, path).map(String::into_bytes),
79        Source::WorkTree => std::fs::read(root.join(path)).ok(),
80    }
81}