verctl-git 0.9.5

Git repository access and history queries for verctl
Documentation
use std::env;

use anyhow::{Context, Result, bail};
use gix::bstr::ByteSlice;
use gix::remote::Direction;
use verctl_core::env as github_env;

use crate::remote::configured_default_branch;

pub(crate) fn has_origin(repo: &gix::Repository) -> bool {
    repo.remote_names()
        .iter()
        .any(|name| name.to_str() == Ok("origin"))
}

pub(crate) fn origin_url_of(repo: &gix::Repository) -> Result<String> {
    let remote = repo
        .find_remote("origin")
        .context("fetch the default branch")?;
    let url = remote.url(Direction::Fetch).context("origin has no URL")?;
    Ok(url.to_bstring().to_str_lossy().into_owned())
}

pub(crate) fn peel_remote(repo: &gix::Repository, name: &str) -> Option<gix::ObjectId> {
    let mut reference = repo.try_find_reference(name).ok()??;
    let commit = reference.peel_to_commit().ok()?;
    Some(commit.id().detach())
}

pub(crate) fn origin_head_branch(repo: &gix::Repository) -> Option<String> {
    let reference = repo.try_find_reference("refs/remotes/origin/HEAD").ok()??;
    let target = reference.target();
    let target = target.try_name()?.as_bstr().to_str().ok()?;
    let name = target.trim_start_matches("refs/remotes/origin/");
    (!name.is_empty()).then(|| name.to_owned())
}

pub(crate) fn env_base_ref() -> Option<String> {
    env::var("GITHUB_BASE_REF")
        .ok()
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty())
}

/// `GITHUB_BASE_REF` (PR base) then `main` / `master`.
///
/// `GITHUB_REF_NAME` is not a candidate: on push it is the branch
/// being pushed, so `origin/<that branch>` would always match HEAD.
/// A non-main default on Actions is `origin/HEAD`, which
/// `ensure_origin_head` fetches and points at
/// `VERCTL_DEFAULT_BRANCH`.
#[must_use]
pub fn default_branch_candidates() -> Vec<String> {
    candidate_names(env_base_ref().as_deref())
}

/// The branch releases come from, whatever branch a pull request targets. The
/// candidates, in order:
///
/// 1. `VERCTL_DEFAULT_BRANCH`;
/// 2. the event's repository default branch
///    ([`verctl_core::env::event_default_branch`]);
/// 3. `main` / `master`;
/// 4. `GITHUB_BASE_REF`.
///
/// The event's default covers a default branch with another name, which
/// Actions leaves without `origin/HEAD`. The pull request's base comes last,
/// for a run with neither.
#[must_use]
pub fn release_branch_candidates() -> Vec<String> {
    release_candidate_names(
        configured_default_branch().as_deref(),
        github_env::event_default_branch().as_deref(),
        env_base_ref().as_deref(),
    )
}

pub(crate) fn release_candidate_names(
    configured: Option<&str>,
    event_default: Option<&str>,
    base: Option<&str>,
) -> Vec<String> {
    let mut names = Vec::new();
    for name in [configured, event_default].into_iter().flatten() {
        if !name.is_empty() && !names.iter().any(|known| known == name) {
            names.push(name.to_owned());
        }
    }
    for name in candidate_names(None)
        .into_iter()
        .chain(base.map(str::to_owned))
    {
        if !name.is_empty() && !names.contains(&name) {
            names.push(name);
        }
    }
    names
}

/// The branches a version comparison fetches when they are missing:
/// `VERCTL_DEFAULT_BRANCH`, then the event's repository default branch, then
/// `GITHUB_BASE_REF`. The default branch is fetched
/// even when the pull request targets another branch, so the released
/// baseline reads the same branch a full clone would. None is set outside
/// Actions, so a local run fetches nothing.
#[must_use]
pub fn comparison_branches() -> Vec<String> {
    let mut names = Vec::new();
    let sources = [
        configured_default_branch(),
        github_env::event_default_branch(),
        env_base_ref(),
    ];
    for name in sources.into_iter().flatten() {
        if !name.is_empty() && !names.contains(&name) {
            names.push(name);
        }
    }
    names
}

/// Like `default_branch_candidates`, but the caller supplies the base ref and
/// the environment is not read.
#[must_use]
pub fn default_branch_candidates_from(base_ref: Option<&str>) -> Vec<String> {
    candidate_names(base_ref)
}

pub(crate) fn candidate_names(base_ref: Option<&str>) -> Vec<String> {
    let mut names = Vec::new();
    if let Some(value) = base_ref.map(str::trim).filter(|value| !value.is_empty()) {
        names.push(value.to_owned());
    }
    for stock in ["main", "master"] {
        if !names.iter().any(|name| name == stock) {
            names.push(stock.to_owned());
        }
    }
    names
}

pub(crate) fn default_upstream_commit(
    repo: &gix::Repository,
    candidates: &[String],
) -> Result<Option<gix::ObjectId>> {
    if let Some(branch) = origin_head_branch(repo) {
        let name = format!("refs/remotes/origin/{branch}");
        return match peel_remote(repo, &name) {
            Some(commit) => Ok(Some(commit)),
            None => bail!(
                "cannot resolve the default branch ({name} is missing; fetch the default branch)"
            ),
        };
    }
    for name in candidates {
        let reference = format!("refs/remotes/origin/{name}");
        if let Some(commit) = peel_remote(repo, &reference) {
            return Ok(Some(commit));
        }
    }
    if has_origin(repo) {
        bail!(
            "cannot resolve the default branch (origin exists but origin/HEAD, origin/main, and origin/master are missing; fetch the default branch)"
        );
    }
    Ok(None)
}