Skip to main content

verctl_git/
lib.rs

1//! Git repository access, commit history, tree reads, fetch, and push for
2//! `verctl`.
3
4use std::path::Path;
5
6use anyhow::{Context, Result};
7use gix::open;
8use gix::sec::trust::{DefaultForLevel, Mapping};
9use gix::sec::{Permission, Trust};
10#[cfg(test)]
11use verctl_test_support as test_git;
12
13mod branches;
14mod commit;
15mod history;
16mod merge_base;
17mod remote;
18mod status;
19
20#[cfg(test)]
21use branches::{candidate_names, release_candidate_names};
22pub use branches::{
23    comparison_branches, default_branch_candidates, default_branch_candidates_from,
24    release_branch_candidates,
25};
26use commit::fallback_identity;
27pub use commit::{PushOutcome, commit_branch_and_push};
28#[cfg(test)]
29use commit::{absolute_workdir, push, workdir_rel, write_commit_on_branch};
30pub use history::{
31    AddedBy, Deleted, VersionCommit, added_by, added_by_from, candidate_deletions,
32    pull_request_number, tagged_commit, tagged_commit_from,
33};
34pub use merge_base::{MergeBase, file_at, files_named_at, files_on_merge_base, read_optional};
35pub use remote::{
36    FetchDefault, configured_default_branch, default_tip, ensure_comparable, ensure_full_history,
37    ensure_origin_head, extract_tag_tree, github_git_user, github_https_url, off_default_history,
38    origin_url, upstream_default_branch, workflows_differ,
39};
40#[cfg(test)]
41use remote::{prove_default_history, workflows_differ_at};
42pub use status::{
43    IgnoredFiles, assert_only_allowed, dirty_paths, is_ignored, is_repository, matches_stage,
44    tracked, workdir_covering,
45};
46
47/// The checked-out branch, or `None` for a detached HEAD or no repository.
48#[must_use]
49pub fn current_branch(root: &Path) -> Option<String> {
50    let repo = repo_covering(root)?;
51    repo.head_id().ok()?;
52    let name = repo.head_name().ok()??;
53    Some(name.shorten().to_string())
54}
55
56/// The commit HEAD names, as a full hex SHA.
57///
58/// # Errors
59///
60/// Returns an error when `root` is not inside a git repository, or when HEAD
61/// names no commit, as in a repository with no commits.
62pub fn head_sha(root: &Path) -> Result<String> {
63    let repo = discover(root).context("release needs a git repository to name the tag")?;
64    let commit = repo
65        .head_commit()
66        .context("release needs HEAD to name the tag")?;
67    Ok(commit.id().to_string())
68}
69
70/// Whether `HEAD` contains commit `sha` (either equal to `HEAD` or an ancestor
71/// of `HEAD`).
72///
73/// Returns `Ok(false)` when `sha` is absent from the local object store or is
74/// not an ancestor of `HEAD`.
75///
76/// # Errors
77///
78/// Returns an error when `root` is not inside a git repository, `HEAD` cannot
79/// be read, `sha` is not a valid commit hex id, or the ancestry walk fails.
80pub fn head_contains_commit(root: &Path, sha: &str) -> Result<bool> {
81    let repo = discover(root).context("checking commit ancestry needs a git repository")?;
82    let head = repo
83        .head_commit()
84        .context("checking commit ancestry needs HEAD")?
85        .id();
86    let target =
87        gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
88    if head == target {
89        return Ok(true);
90    }
91    if repo.find_commit(target).is_err() {
92        return Ok(false);
93    }
94    let base = repo.merge_base(head, target).with_context(|| {
95        format!("cannot tell whether HEAD contains commit {sha}; fetch the full history")
96    })?;
97    Ok(base.is_some_and(|base| base == target))
98}
99
100/// The repository that covers `dir`, searching upward, as it is on disk.
101///
102/// A git hook exports repository-local variables for its own git process.
103/// pre-commit sets `GIT_INDEX_FILE` to a temporary index, given as a path
104/// relative to git's working directory, and may set `GIT_DIR` and
105/// `GIT_WORK_TREE`. verctl ignores them, as libgit2 did, so a command behaves
106/// the same inside a hook and outside one.
107///
108/// gix's catch-all permission for `GIT_*` variables is denied, which drops
109/// those overrides. Identity and HTTP variables keep their own permissions.
110/// `GIT_DIR` is never read, because discovery starts from `dir` instead of the
111/// environment. Nothing in this module writes the index.
112///
113/// Fetches and branch updates write reflog entries, which gix refuses without
114/// a committer. A CI runner often has no git identity configured, so
115/// `fallback_identity` fills that gap. A configured identity still wins.
116pub(crate) fn discover(dir: &Path) -> Result<gix::Repository> {
117    let mapping = Mapping {
118        full: open_options(Trust::Full),
119        reduced: open_options(Trust::Reduced),
120    };
121    let repo = gix::ThreadSafeRepository::discover_opts(
122        dir,
123        gix::discover::upwards::Options::default(),
124        mapping,
125    )
126    .with_context(|| format!("no git repository covers {}", dir.display()))?;
127    let mut repo = repo.to_thread_local();
128    let (name, email) = fallback_identity();
129    repo.committer_or_set_fallback(name.as_str(), email.as_str())
130        .context("set the reflog identity")?;
131    Ok(repo)
132}
133
134/// gix's defaults for `trust`, without the repository-local `GIT_*` overrides.
135fn open_options(trust: Trust) -> open::Options {
136    let mut options = open::Options::default_for_level(trust);
137    options.permissions.env.git_prefix = Permission::Deny;
138    options
139}
140
141pub(crate) fn repo_covering(root: &Path) -> Option<gix::Repository> {
142    let repo = discover(root).ok()?;
143    let workdir = repo.workdir()?.canonicalize().ok()?;
144    let root = root.canonicalize().ok()?;
145    root.starts_with(workdir).then_some(repo)
146}
147
148#[cfg(test)]
149mod tests;