use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use gix::bstr::{BString, ByteSlice};
use gix::dir::entry::Status;
use gix::dir::walk::EmissionMode;
use gix::index::entry::Mode;
use gix::progress::Discard;
use gix::status::tree_index::TrackRenames;
use gix::status::{self, UntrackedFiles, index_worktree};
use gix::worktree::stack::state::ignore::Source;
use crate::{discover, repo_covering};
#[must_use]
pub fn workdir_covering(dir: &Path) -> Option<PathBuf> {
repo_covering(dir)?
.workdir()
.and_then(|workdir| workdir.canonicalize().ok())
}
pub fn tracked(root: &Path) -> Result<Vec<PathBuf>> {
let Some(repo) = repo_covering(root) else {
return Ok(Vec::new());
};
let index = repo.index_or_empty().context("git index")?;
let project = project_prefix(&repo, root);
Ok(index
.entries()
.iter()
.filter_map(|entry| entry.path(&index).to_str().ok().map(PathBuf::from))
.filter_map(|path| path.strip_prefix(&project).ok().map(Path::to_path_buf))
.collect())
}
#[must_use]
pub fn is_ignored(root: &Path, rel: &Path) -> bool {
let Some(repo) = repo_covering(root) else {
return false;
};
let path = project_prefix(&repo, root).join(rel);
let Ok(index) = repo.index_or_empty() else {
return false;
};
let Ok(mut excludes) = repo.excludes(&index, None, Source::WorktreeThenIdMappingIfNotSkipped)
else {
return false;
};
let mut ignored_at = |path: &Path, mode| {
excludes
.at_path(path, mode)
.is_ok_and(|platform| platform.is_excluded())
};
path.ancestors()
.skip(1)
.filter(|dir| !dir.as_os_str().is_empty())
.any(|dir| ignored_at(dir, Some(Mode::DIR)))
|| ignored_at(&path, None)
}
#[must_use]
pub fn is_repository(root: &Path) -> bool {
repo_covering(root).is_some()
}
pub(crate) fn project_prefix(repo: &gix::Repository, root: &Path) -> PathBuf {
let Some(workdir) = repo.workdir().and_then(|dir| dir.canonicalize().ok()) else {
return PathBuf::new();
};
root.canonicalize()
.ok()
.and_then(|root| root.strip_prefix(&workdir).ok().map(Path::to_path_buf))
.unwrap_or_default()
}
#[must_use]
pub fn matches_stage(pattern: &str, rel: &str) -> bool {
glob::Pattern::new(pattern)
.is_ok_and(|compiled| compiled.matches(rel) || compiled.matches(&format!("./{rel}")))
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum IgnoredFiles {
#[default]
Skip,
Include,
}
pub fn assert_only_allowed(
root: &Path,
allowed: &[PathBuf],
globs: &[String],
ignored: IgnoredFiles,
) -> Result<Vec<PathBuf>> {
let Ok(repo) = discover(root) else {
return Ok(Vec::new());
};
let dirty = status_paths(&repo, Vec::new(), IgnoredFiles::Skip).context("git status")?;
let workdir = repo.workdir().unwrap_or(root);
let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let workdir = workdir
.canonicalize()
.unwrap_or_else(|_| workdir.to_path_buf());
let mut extra = Vec::new();
let mut staged = Vec::new();
for rel in &dirty {
let abs = workdir.join(rel);
if !abs.starts_with(&root) {
continue;
}
if abs.is_dir() {
continue;
}
if allowed
.iter()
.any(|path| path == &abs || path.ends_with(rel))
{
continue;
}
if globs.iter().any(|pattern| matches_stage(pattern, rel)) {
staged.push(abs);
continue;
}
extra.push(rel.clone());
}
if matches!(ignored, IgnoredFiles::Include) && !globs.is_empty() {
let patterns = globs
.iter()
.map(|pattern| pattern.as_str().into())
.collect();
let ignored =
status_paths(&repo, patterns, IgnoredFiles::Include).context("git status (ignored)")?;
for rel in &ignored {
let abs = workdir.join(rel);
if !abs.starts_with(&root) || abs.is_dir() {
continue;
}
if globs.iter().any(|pattern| matches_stage(pattern, rel))
&& !staged.iter().any(|path| path == &abs)
{
staged.push(abs);
}
}
}
if extra.is_empty() {
return Ok(staged);
}
bail!(
"version produced unexpected paths (declare them in prepare.stage): {}",
extra.join(", ")
);
}
pub(crate) fn status_paths(
repo: &gix::Repository,
patterns: Vec<BString>,
ignored: IgnoredFiles,
) -> Result<BTreeSet<String>> {
let include_ignored = matches!(ignored, IgnoredFiles::Include);
let status = repo
.status(Discard)?
.untracked_files(UntrackedFiles::Files)
.index_worktree_rewrites(None)
.tree_index_track_renames(TrackRenames::Disabled);
let status = if include_ignored {
status.dirwalk_options(|options| options.emit_ignored(Some(EmissionMode::Matching)))
} else {
status
};
let mut paths = BTreeSet::new();
for item in status.into_iter(patterns)? {
let item = item?;
let is_ignored = matches!(
&item,
status::Item::IndexWorktree(index_worktree::Item::DirectoryContents {
entry,
collapsed_directory_status: _
}) if matches!(entry.status, Status::Ignored(_))
);
if is_ignored == include_ignored {
paths.insert(item.location().to_str_lossy().into_owned());
}
}
Ok(paths)
}