Skip to main content

verctl_git/
branches.rs

1use std::env;
2
3use anyhow::{Context, Result, bail};
4use gix::bstr::ByteSlice;
5use gix::remote::Direction;
6use verctl_core::env as github_env;
7
8use crate::remote::configured_default_branch;
9
10pub(crate) fn has_origin(repo: &gix::Repository) -> bool {
11    repo.remote_names()
12        .iter()
13        .any(|name| name.to_str() == Ok("origin"))
14}
15
16pub(crate) fn origin_url_of(repo: &gix::Repository) -> Result<String> {
17    let remote = repo
18        .find_remote("origin")
19        .context("fetch the default branch")?;
20    let url = remote.url(Direction::Fetch).context("origin has no URL")?;
21    Ok(url.to_bstring().to_str_lossy().into_owned())
22}
23
24pub(crate) fn peel_remote(repo: &gix::Repository, name: &str) -> Option<gix::ObjectId> {
25    let mut reference = repo.try_find_reference(name).ok()??;
26    let commit = reference.peel_to_commit().ok()?;
27    Some(commit.id().detach())
28}
29
30pub(crate) fn origin_head_branch(repo: &gix::Repository) -> Option<String> {
31    let reference = repo.try_find_reference("refs/remotes/origin/HEAD").ok()??;
32    let target = reference.target();
33    let target = target.try_name()?.as_bstr().to_str().ok()?;
34    let name = target.trim_start_matches("refs/remotes/origin/");
35    (!name.is_empty()).then(|| name.to_owned())
36}
37
38pub(crate) fn env_base_ref() -> Option<String> {
39    env::var("GITHUB_BASE_REF")
40        .ok()
41        .map(|value| value.trim().to_owned())
42        .filter(|value| !value.is_empty())
43}
44
45/// `GITHUB_BASE_REF` (PR base) then `main` / `master`.
46///
47/// `GITHUB_REF_NAME` is not a candidate: on push it is the branch
48/// being pushed, so `origin/<that branch>` would always match HEAD.
49/// A non-main default on Actions is `origin/HEAD`, which
50/// `ensure_origin_head` fetches and points at
51/// `VERCTL_DEFAULT_BRANCH`.
52#[must_use]
53pub fn default_branch_candidates() -> Vec<String> {
54    candidate_names(env_base_ref().as_deref())
55}
56
57/// The branch releases come from, whatever branch a pull request targets. The
58/// candidates, in order:
59///
60/// 1. `VERCTL_DEFAULT_BRANCH`;
61/// 2. the event's repository default branch
62///    ([`verctl_core::env::event_default_branch`]);
63/// 3. `main` / `master`;
64/// 4. `GITHUB_BASE_REF`.
65///
66/// The event's default covers a default branch with another name, which
67/// Actions leaves without `origin/HEAD`. The pull request's base comes last,
68/// for a run with neither.
69#[must_use]
70pub fn release_branch_candidates() -> Vec<String> {
71    release_candidate_names(
72        configured_default_branch().as_deref(),
73        github_env::event_default_branch().as_deref(),
74        env_base_ref().as_deref(),
75    )
76}
77
78pub(crate) fn release_candidate_names(
79    configured: Option<&str>,
80    event_default: Option<&str>,
81    base: Option<&str>,
82) -> Vec<String> {
83    let mut names = Vec::new();
84    for name in [configured, event_default].into_iter().flatten() {
85        if !name.is_empty() && !names.iter().any(|known| known == name) {
86            names.push(name.to_owned());
87        }
88    }
89    for name in candidate_names(None)
90        .into_iter()
91        .chain(base.map(str::to_owned))
92    {
93        if !name.is_empty() && !names.contains(&name) {
94            names.push(name);
95        }
96    }
97    names
98}
99
100/// The branches a version comparison fetches when they are missing:
101/// `VERCTL_DEFAULT_BRANCH`, then the event's repository default branch, then
102/// `GITHUB_BASE_REF`. The default branch is fetched
103/// even when the pull request targets another branch, so the released
104/// baseline reads the same branch a full clone would. None is set outside
105/// Actions, so a local run fetches nothing.
106#[must_use]
107pub fn comparison_branches() -> Vec<String> {
108    let mut names = Vec::new();
109    let sources = [
110        configured_default_branch(),
111        github_env::event_default_branch(),
112        env_base_ref(),
113    ];
114    for name in sources.into_iter().flatten() {
115        if !name.is_empty() && !names.contains(&name) {
116            names.push(name);
117        }
118    }
119    names
120}
121
122/// Like `default_branch_candidates`, but the caller supplies the base ref and
123/// the environment is not read.
124#[must_use]
125pub fn default_branch_candidates_from(base_ref: Option<&str>) -> Vec<String> {
126    candidate_names(base_ref)
127}
128
129pub(crate) fn candidate_names(base_ref: Option<&str>) -> Vec<String> {
130    let mut names = Vec::new();
131    if let Some(value) = base_ref.map(str::trim).filter(|value| !value.is_empty()) {
132        names.push(value.to_owned());
133    }
134    for stock in ["main", "master"] {
135        if !names.iter().any(|name| name == stock) {
136            names.push(stock.to_owned());
137        }
138    }
139    names
140}
141
142pub(crate) fn default_upstream_commit(
143    repo: &gix::Repository,
144    candidates: &[String],
145) -> Result<Option<gix::ObjectId>> {
146    if let Some(branch) = origin_head_branch(repo) {
147        let name = format!("refs/remotes/origin/{branch}");
148        return match peel_remote(repo, &name) {
149            Some(commit) => Ok(Some(commit)),
150            None => bail!(
151                "cannot resolve the default branch ({name} is missing; fetch the default branch)"
152            ),
153        };
154    }
155    for name in candidates {
156        let reference = format!("refs/remotes/origin/{name}");
157        if let Some(commit) = peel_remote(repo, &reference) {
158            return Ok(Some(commit));
159        }
160    }
161    if has_origin(repo) {
162        bail!(
163            "cannot resolve the default branch (origin exists but origin/HEAD, origin/main, and origin/master are missing; fetch the default branch)"
164        );
165    }
166    Ok(None)
167}