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#[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
27pub 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#[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#[must_use]
97pub fn is_repository(root: &Path) -> bool {
98 repo_covering(root).is_some()
99}
100
101pub(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#[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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
121pub enum IgnoredFiles {
122 #[default]
124 Skip,
125 Include,
127}
128
129pub 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
208pub 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
240pub(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}