verctl-git 0.9.7

Git repository access and history queries for verctl
Documentation
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};

/// The working tree that contains `dir`, canonicalized.
///
/// The ceiling for an upward file search: nothing above a repository
/// root belongs to the project inside it.
#[must_use]
pub fn workdir_covering(dir: &Path) -> Option<PathBuf> {
    repo_covering(dir)?
        .workdir()
        .and_then(|workdir| workdir.canonicalize().ok())
}

/// Every path git tracks under `root`, relative to `root` itself.
///
/// The list comes from the index instead of a directory walk. Build output,
/// vendored trees, and anything else gitignored is not part of what this repo
/// publishes.
///
/// The index contains paths from the working tree. `root` is a project inside
/// it (one repository may contain several), so anything outside `root` is not
/// this project's. What is left is rebased onto `root`.
///
/// A tree with no repository tracks nothing (it cannot serve a file by tag). A
/// repository whose index cannot be read is an error, never an empty answer.
///
/// # Errors
///
/// Returns an error when the repository's index cannot be read.
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())
}

/// Whether the repository is told to ignore `rel`, a path relative to `root`.
///
/// Ignoring a file marks it as not part of what the repo publishes. That is
/// the same fact `tracked` already reads the index for. So an ignored file is
/// not a forgotten one, and nothing should ask its author to commit it.
///
/// A file under an ignored directory is ignored too, as git has it. gix
/// matches the one path it is given, so each parent directory is checked
/// first.
#[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)
}

/// Whether a repository covers `root` at all.
///
/// `tracked` answers "nothing" both for an empty index and for a tree with no
/// repository. Those are different states: a file the index does not carry is
/// untracked only where an index exists to not carry it.
#[must_use]
pub fn is_repository(root: &Path) -> bool {
    repo_covering(root).is_some()
}

/// Where `root` sits inside the working tree: empty when it is the root.
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()
}

/// with a leading `./`).
#[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}")))
}

/// Whether `assert_only_allowed` and status lookups inspect gitignored files.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum IgnoredFiles {
    /// Inspect only tracked and untracked files (skip gitignored paths).
    #[default]
    Skip,
    /// Include gitignored files matched by declared `prepare.stage` globs.
    Include,
}

/// Fail if the worktree has dirty paths outside `allowed` and `globs`.
///
/// Returns dirty paths that match `globs` (modified, untracked, or
/// deleted files). Directories are skipped. Same `git status` walk as
/// the unexpected-dirty check; not a filesystem glob. Renames are not
/// tracked, so a moved file shows as its old and its new path, each of
/// which must be allowed.
///
/// # Errors
///
/// Returns an error when `git status` cannot be computed, or when a dirty
/// path is neither in `allowed` nor matched by `globs`. The latter error lists
/// those paths. A root outside a repository is not an error and returns an
/// empty list.
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(", ")
    );
}

/// Dirty working-tree file paths under `root`, relative to `root`, using `/`
/// separators (modified, staged, deleted, or untracked; directories skipped).
///
/// Returns an empty set when `root` is not inside a git repository.
///
/// # Errors
///
/// Returns an error when `git status` cannot be computed.
pub fn dirty_paths(root: &Path) -> Result<BTreeSet<String>> {
    let Ok(repo) = discover(root) else {
        return Ok(BTreeSet::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 out = BTreeSet::new();
    for rel in dirty {
        let abs = workdir.join(&rel);
        if abs.is_dir() {
            continue;
        }
        let Ok(under_root) = abs.strip_prefix(&root) else {
            continue;
        };
        out.insert(under_root.to_string_lossy().replace('\\', "/"));
    }
    Ok(out)
}

/// The paths `git status` reports, one entry per path, sorted.
///
/// With [`IgnoredFiles::Skip`]: staged, modified, deleted, and untracked files,
/// every untracked file listed on its own. With [`IgnoredFiles::Include`]: only
/// the ignored files `patterns` select, each listed on its own.
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)
}