verctl-git 0.9.7

Git repository access and history queries for verctl
Documentation
//! Git repository access, commit history, tree reads, fetch, and push for
//! `verctl`.

use std::path::Path;

use anyhow::{Context, Result};
use gix::open;
use gix::sec::trust::{DefaultForLevel, Mapping};
use gix::sec::{Permission, Trust};
#[cfg(test)]
use verctl_test_support as test_git;

mod branches;
mod commit;
mod history;
mod merge_base;
mod remote;
mod status;

#[cfg(test)]
use branches::{candidate_names, release_candidate_names};
pub use branches::{
    comparison_branches, default_branch_candidates, default_branch_candidates_from,
    release_branch_candidates,
};
use commit::fallback_identity;
pub use commit::{PushOutcome, commit_branch_and_push};
#[cfg(test)]
use commit::{absolute_workdir, push, workdir_rel, write_commit_on_branch};
pub use history::{
    AddedBy, Deleted, VersionCommit, added_by, added_by_from, candidate_deletions,
    pull_request_number, tagged_commit, tagged_commit_from,
};
pub use merge_base::{MergeBase, file_at, files_named_at, files_on_merge_base, read_optional};
pub use remote::{
    FetchDefault, configured_default_branch, default_tip, ensure_comparable, ensure_full_history,
    ensure_origin_head, extract_tag_tree, github_git_user, github_https_url, off_default_history,
    origin_url, upstream_default_branch, workflows_differ,
};
#[cfg(test)]
use remote::{prove_default_history, workflows_differ_at};
pub use status::{
    IgnoredFiles, assert_only_allowed, dirty_paths, is_ignored, is_repository, matches_stage,
    tracked, workdir_covering,
};

/// The checked-out branch, or `None` for a detached HEAD or no repository.
#[must_use]
pub fn current_branch(root: &Path) -> Option<String> {
    let repo = repo_covering(root)?;
    repo.head_id().ok()?;
    let name = repo.head_name().ok()??;
    Some(name.shorten().to_string())
}

/// The commit HEAD names, as a full hex SHA.
///
/// # Errors
///
/// Returns an error when `root` is not inside a git repository, or when HEAD
/// names no commit, as in a repository with no commits.
pub fn head_sha(root: &Path) -> Result<String> {
    let repo = discover(root).context("release needs a git repository to name the tag")?;
    let commit = repo
        .head_commit()
        .context("release needs HEAD to name the tag")?;
    Ok(commit.id().to_string())
}

/// Whether `HEAD` contains commit `sha` (either equal to `HEAD` or an ancestor
/// of `HEAD`).
///
/// Returns `Ok(false)` when `sha` is absent from the local object store or is
/// not an ancestor of `HEAD`.
///
/// # Errors
///
/// Returns an error when `root` is not inside a git repository, `HEAD` cannot
/// be read, `sha` is not a valid commit hex id, or the ancestry walk fails.
pub fn head_contains_commit(root: &Path, sha: &str) -> Result<bool> {
    let repo = discover(root).context("checking commit ancestry needs a git repository")?;
    let head = repo
        .head_commit()
        .context("checking commit ancestry needs HEAD")?
        .id();
    let target =
        gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
    if head == target {
        return Ok(true);
    }
    if repo.find_commit(target).is_err() {
        return Ok(false);
    }
    let base = repo.merge_base(head, target).with_context(|| {
        format!("cannot tell whether HEAD contains commit {sha}; fetch the full history")
    })?;
    Ok(base.is_some_and(|base| base == target))
}

/// The repository that covers `dir`, searching upward, as it is on disk.
///
/// A git hook exports repository-local variables for its own git process.
/// pre-commit sets `GIT_INDEX_FILE` to a temporary index, given as a path
/// relative to git's working directory, and may set `GIT_DIR` and
/// `GIT_WORK_TREE`. verctl ignores them, as libgit2 did, so a command behaves
/// the same inside a hook and outside one.
///
/// gix's catch-all permission for `GIT_*` variables is denied, which drops
/// those overrides. Identity and HTTP variables keep their own permissions.
/// `GIT_DIR` is never read, because discovery starts from `dir` instead of the
/// environment. Nothing in this module writes the index.
///
/// Fetches and branch updates write reflog entries, which gix refuses without
/// a committer. A CI runner often has no git identity configured, so
/// `fallback_identity` fills that gap. A configured identity still wins.
pub(crate) fn discover(dir: &Path) -> Result<gix::Repository> {
    let mapping = Mapping {
        full: open_options(Trust::Full),
        reduced: open_options(Trust::Reduced),
    };
    let repo = gix::ThreadSafeRepository::discover_opts(
        dir,
        gix::discover::upwards::Options::default(),
        mapping,
    )
    .with_context(|| format!("no git repository covers {}", dir.display()))?;
    let mut repo = repo.to_thread_local();
    let (name, email) = fallback_identity();
    repo.committer_or_set_fallback(name.as_str(), email.as_str())
        .context("set the reflog identity")?;
    Ok(repo)
}

/// gix's defaults for `trust`, without the repository-local `GIT_*` overrides.
fn open_options(trust: Trust) -> open::Options {
    let mut options = open::Options::default_for_level(trust);
    options.permissions.env.git_prefix = Permission::Deny;
    options
}

pub(crate) fn repo_covering(root: &Path) -> Option<gix::Repository> {
    let repo = discover(root).ok()?;
    let workdir = repo.workdir()?.canonicalize().ok()?;
    let root = root.canonicalize().ok()?;
    root.starts_with(workdir).then_some(repo)
}

#[cfg(test)]
mod tests;