Skip to main content

verctl_git/
status.rs

1use std::collections::BTreeSet;
2use std::path::{Path, PathBuf};
3
4use anyhow::{Context, Result, bail};
5use gix::bstr::{BString, ByteSlice};
6use gix::dir::entry::Status;
7use gix::dir::walk::EmissionMode;
8use gix::index::entry::Mode;
9use gix::progress::Discard;
10use gix::status::tree_index::TrackRenames;
11use gix::status::{self, UntrackedFiles, index_worktree};
12use gix::worktree::stack::state::ignore::Source;
13
14use crate::{discover, repo_covering};
15
16/// The working tree that contains `dir`, canonicalized.
17///
18/// The ceiling for an upward file search: nothing above a repository
19/// root belongs to the project inside it.
20#[must_use]
21pub fn workdir_covering(dir: &Path) -> Option<PathBuf> {
22    repo_covering(dir)?
23        .workdir()
24        .and_then(|workdir| workdir.canonicalize().ok())
25}
26
27/// Every path git tracks under `root`, relative to `root` itself.
28///
29/// The list comes from the index instead of a directory walk. Build output,
30/// vendored trees, and anything else gitignored is not part of what this repo
31/// publishes.
32///
33/// The index contains paths from the working tree. `root` is a project inside
34/// it (one repository may contain several), so anything outside `root` is not
35/// this project's. What is left is rebased onto `root`.
36///
37/// A tree with no repository tracks nothing (it cannot serve a file by tag). A
38/// repository whose index cannot be read is an error, never an empty answer.
39///
40/// # Errors
41///
42/// Returns an error when the repository's index cannot be read.
43pub fn tracked(root: &Path) -> Result<Vec<PathBuf>> {
44    let Some(repo) = repo_covering(root) else {
45        return Ok(Vec::new());
46    };
47    let index = repo.index_or_empty().context("git index")?;
48    let project = project_prefix(&repo, root);
49    Ok(index
50        .entries()
51        .iter()
52        .filter_map(|entry| entry.path(&index).to_str().ok().map(PathBuf::from))
53        .filter_map(|path| path.strip_prefix(&project).ok().map(Path::to_path_buf))
54        .collect())
55}
56
57/// Whether the repository is told to ignore `rel`, a path relative to `root`.
58///
59/// Ignoring a file marks it as not part of what the repo publishes. That is
60/// the same fact `tracked` already reads the index for. So an ignored file is
61/// not a forgotten one, and nothing should ask its author to commit it.
62///
63/// A file under an ignored directory is ignored too, as git has it. gix
64/// matches the one path it is given, so each parent directory is checked
65/// first.
66#[must_use]
67pub fn is_ignored(root: &Path, rel: &Path) -> bool {
68    let Some(repo) = repo_covering(root) else {
69        return false;
70    };
71    let path = project_prefix(&repo, root).join(rel);
72    let Ok(index) = repo.index_or_empty() else {
73        return false;
74    };
75    let Ok(mut excludes) = repo.excludes(&index, None, Source::WorktreeThenIdMappingIfNotSkipped)
76    else {
77        return false;
78    };
79    let mut ignored_at = |path: &Path, mode| {
80        excludes
81            .at_path(path, mode)
82            .is_ok_and(|platform| platform.is_excluded())
83    };
84    path.ancestors()
85        .skip(1)
86        .filter(|dir| !dir.as_os_str().is_empty())
87        .any(|dir| ignored_at(dir, Some(Mode::DIR)))
88        || ignored_at(&path, None)
89}
90
91/// Whether a repository covers `root` at all.
92///
93/// `tracked` answers "nothing" both for an empty index and for a tree with no
94/// repository. Those are different states: a file the index does not carry is
95/// untracked only where an index exists to not carry it.
96#[must_use]
97pub fn is_repository(root: &Path) -> bool {
98    repo_covering(root).is_some()
99}
100
101/// Where `root` sits inside the working tree: empty when it is the root.
102pub(crate) fn project_prefix(repo: &gix::Repository, root: &Path) -> PathBuf {
103    let Some(workdir) = repo.workdir().and_then(|dir| dir.canonicalize().ok()) else {
104        return PathBuf::new();
105    };
106    root.canonicalize()
107        .ok()
108        .and_then(|root| root.strip_prefix(&workdir).ok().map(Path::to_path_buf))
109        .unwrap_or_default()
110}
111
112/// with a leading `./`).
113#[must_use]
114pub fn matches_stage(pattern: &str, rel: &str) -> bool {
115    glob::Pattern::new(pattern)
116        .is_ok_and(|compiled| compiled.matches(rel) || compiled.matches(&format!("./{rel}")))
117}
118
119/// Whether `assert_only_allowed` and status lookups inspect gitignored files.
120#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
121pub enum IgnoredFiles {
122    /// Inspect only tracked and untracked files (skip gitignored paths).
123    #[default]
124    Skip,
125    /// Include gitignored files matched by declared `prepare.stage` globs.
126    Include,
127}
128
129/// Fail if the worktree has dirty paths outside `allowed` and `globs`.
130///
131/// Returns dirty paths that match `globs` (modified, untracked, or
132/// deleted files). Directories are skipped. Same `git status` walk as
133/// the unexpected-dirty check; not a filesystem glob. Renames are not
134/// tracked, so a moved file shows as its old and its new path, each of
135/// which must be allowed.
136///
137/// # Errors
138///
139/// Returns an error when `git status` cannot be computed, or when a dirty
140/// path is neither in `allowed` nor matched by `globs`. The latter error lists
141/// those paths. A root outside a repository is not an error and returns an
142/// empty list.
143pub fn assert_only_allowed(
144    root: &Path,
145    allowed: &[PathBuf],
146    globs: &[String],
147    ignored: IgnoredFiles,
148) -> Result<Vec<PathBuf>> {
149    let Ok(repo) = discover(root) else {
150        return Ok(Vec::new());
151    };
152    let dirty = status_paths(&repo, Vec::new(), IgnoredFiles::Skip).context("git status")?;
153    let workdir = repo.workdir().unwrap_or(root);
154    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
155    let workdir = workdir
156        .canonicalize()
157        .unwrap_or_else(|_| workdir.to_path_buf());
158    let mut extra = Vec::new();
159    let mut staged = Vec::new();
160    for rel in &dirty {
161        let abs = workdir.join(rel);
162        if !abs.starts_with(&root) {
163            continue;
164        }
165        if abs.is_dir() {
166            continue;
167        }
168        if allowed
169            .iter()
170            .any(|path| path == &abs || path.ends_with(rel))
171        {
172            continue;
173        }
174        if globs.iter().any(|pattern| matches_stage(pattern, rel)) {
175            staged.push(abs);
176            continue;
177        }
178        extra.push(rel.clone());
179    }
180    if matches!(ignored, IgnoredFiles::Include) && !globs.is_empty() {
181        let patterns = globs
182            .iter()
183            .map(|pattern| pattern.as_str().into())
184            .collect();
185        let ignored =
186            status_paths(&repo, patterns, IgnoredFiles::Include).context("git status (ignored)")?;
187        for rel in &ignored {
188            let abs = workdir.join(rel);
189            if !abs.starts_with(&root) || abs.is_dir() {
190                continue;
191            }
192            if globs.iter().any(|pattern| matches_stage(pattern, rel))
193                && !staged.iter().any(|path| path == &abs)
194            {
195                staged.push(abs);
196            }
197        }
198    }
199    if extra.is_empty() {
200        return Ok(staged);
201    }
202    bail!(
203        "version produced unexpected paths (declare them in prepare.stage): {}",
204        extra.join(", ")
205    );
206}
207
208/// Dirty working-tree file paths under `root`, relative to `root`, using `/`
209/// separators (modified, staged, deleted, or untracked; directories skipped).
210///
211/// Returns an empty set when `root` is not inside a git repository.
212///
213/// # Errors
214///
215/// Returns an error when `git status` cannot be computed.
216pub fn dirty_paths(root: &Path) -> Result<BTreeSet<String>> {
217    let Ok(repo) = discover(root) else {
218        return Ok(BTreeSet::new());
219    };
220    let dirty = status_paths(&repo, Vec::new(), IgnoredFiles::Skip).context("git status")?;
221    let workdir = repo.workdir().unwrap_or(root);
222    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
223    let workdir = workdir
224        .canonicalize()
225        .unwrap_or_else(|_| workdir.to_path_buf());
226    let mut out = BTreeSet::new();
227    for rel in dirty {
228        let abs = workdir.join(&rel);
229        if abs.is_dir() {
230            continue;
231        }
232        let Ok(under_root) = abs.strip_prefix(&root) else {
233            continue;
234        };
235        out.insert(under_root.to_string_lossy().replace('\\', "/"));
236    }
237    Ok(out)
238}
239
240/// The paths `git status` reports, one entry per path, sorted.
241///
242/// With [`IgnoredFiles::Skip`]: staged, modified, deleted, and untracked files,
243/// every untracked file listed on its own. With [`IgnoredFiles::Include`]: only
244/// the ignored files `patterns` select, each listed on its own.
245pub(crate) fn status_paths(
246    repo: &gix::Repository,
247    patterns: Vec<BString>,
248    ignored: IgnoredFiles,
249) -> Result<BTreeSet<String>> {
250    let include_ignored = matches!(ignored, IgnoredFiles::Include);
251    let status = repo
252        .status(Discard)?
253        .untracked_files(UntrackedFiles::Files)
254        .index_worktree_rewrites(None)
255        .tree_index_track_renames(TrackRenames::Disabled);
256    let status = if include_ignored {
257        status.dirwalk_options(|options| options.emit_ignored(Some(EmissionMode::Matching)))
258    } else {
259        status
260    };
261    let mut paths = BTreeSet::new();
262    for item in status.into_iter(patterns)? {
263        let item = item?;
264        let is_ignored = matches!(
265            &item,
266            status::Item::IndexWorktree(index_worktree::Item::DirectoryContents {
267                entry,
268                collapsed_directory_status: _
269            }) if matches!(entry.status, Status::Ignored(_))
270        );
271        if is_ignored == include_ignored {
272            paths.insert(item.location().to_str_lossy().into_owned());
273        }
274    }
275    Ok(paths)
276}