Skip to main content

verctl_git/
remote.rs

1use std::fs::{self, Permissions};
2use std::num::NonZeroU32;
3use std::path::{Path, PathBuf};
4use std::sync::atomic::AtomicBool;
5use std::{env, fmt};
6
7use anyhow::{Context, Result, bail, ensure};
8use gix::bstr::ByteSlice;
9use gix::credentials::helper::Action;
10use gix::credentials::protocol::Outcome;
11use gix::objs::tree::EntryKind;
12use gix::progress::Discard;
13use gix::refs::transaction::{PreviousValue, RefEdit};
14use gix::refs::{FullName, Target};
15use gix::remote::fetch::{Shallow, Tags};
16use gix::remote::{Direction, ref_map};
17use gix::sec::identity::Account;
18
19use crate::branches::{
20    candidate_names, default_upstream_commit, env_base_ref, has_origin, origin_head_branch,
21    origin_url_of, peel_remote,
22};
23use crate::merge_base::files_of;
24use crate::status::project_prefix;
25use crate::{discover, repo_covering};
26
27/// The commit at the default branch's tip, as a full hex SHA. The branch
28/// resolves as for [`crate::files_on_merge_base`]: `origin/HEAD`, or else the
29/// first of `candidates` that `origin` has.
30///
31/// # Errors
32///
33/// Returns an error when no repository covers `root`, when there is no
34/// `origin` remote, or when `origin` has none of those refs.
35pub fn default_tip(root: &Path, candidates: &[String]) -> Result<String> {
36    let repo = repo_covering(root).with_context(|| {
37        format!(
38            "cannot resolve the default branch: no git repository covers {}",
39            root.display()
40        )
41    })?;
42    let tip = default_upstream_commit(&repo, candidates)?.context(
43        "cannot resolve the default branch: there is no `origin` remote; add it and fetch the default branch",
44    )?;
45    Ok(tip.to_string())
46}
47
48/// The URL of the `origin` remote.
49///
50/// # Errors
51///
52/// Returns an error when `root` is not inside a git repository, when there is
53/// no `origin` remote, or when `origin` has no fetch URL.
54pub fn origin_url(root: &Path) -> Result<String> {
55    let repo = discover(root).context("open git repository")?;
56    let remote = repo.find_remote("origin").context("git remote origin")?;
57    let url = remote.url(Direction::Fetch).context("origin has no URL")?;
58    Ok(url.to_bstring().to_str_lossy().into_owned())
59}
60
61/// The branch `origin/HEAD` points at, or `None` when that ref is unset.
62#[must_use]
63pub fn upstream_default_branch(root: &Path) -> Option<String> {
64    origin_head_branch(&discover(root).ok()?)
65}
66
67/// Whether HEAD is off the default-branch history: `None` when the default
68/// branch contains HEAD, or why it does not, naming both commits.
69///
70/// Being off the branch is a finding the caller may allow. A missing fact is
71/// not a finding: a proof that cannot run fails and names the missing fact.
72/// A check that passed by skipping itself would let a release run from any
73/// commit, in exactly the CI shapes where the proof matters.
74///
75/// Each of these fails:
76///
77/// - no repository;
78/// - no HEAD commit;
79/// - no `origin` remote;
80/// - an `origin` with no peelable default-tracking ref;
81/// - a shallow clone that cannot walk the graph.
82///
83/// # Errors
84///
85/// Returns an error when:
86///
87/// - no repository covers `root`;
88/// - HEAD has no commit;
89/// - there is no `origin` remote;
90/// - resolving the default branch ref fails;
91/// - the merge-base cannot be computed, as in a shallow clone.
92pub fn off_default_history(root: &Path) -> Result<Option<String>> {
93    prove_default_history(root, &candidate_names(env_base_ref().as_deref()))
94}
95
96/// Whether `.github/workflows/` at the commit the run executes differs from
97/// the default branch's tip.
98/// It is `None` when the two trees are the same object, and otherwise names
99/// both commits.
100///
101/// Actions runs the workflows of `GITHUB_SHA`.
102/// In a reusable workflow's publish job HEAD is the version commit instead.
103/// So the tree compared is the one at `GITHUB_SHA` when that variable names a
104/// commit in the repository, and HEAD's otherwise.
105///
106/// A retry of an old release commit runs its workflows as they were at that
107/// commit. Steps or permissions changed since can publish to the registry and
108/// then fail to tag, and the registry cannot take a version back.
109///
110/// Equal tree ids prove equal content, so no file is read. A tree that is
111/// missing on both sides counts as equal.
112///
113/// # Errors
114///
115/// Returns an error when no repository covers `root`, HEAD has no commit, or
116/// the default branch ref is missing or cannot be resolved.
117pub fn workflows_differ(root: &Path) -> Result<Option<String>> {
118    workflows_differ_at(root, env_run_sha().as_deref())
119}
120
121/// [`workflows_differ`] with the run's commit given in place of `GITHUB_SHA`.
122pub(crate) fn workflows_differ_at(root: &Path, run_sha: Option<&str>) -> Result<Option<String>> {
123    let repo = repo_covering(root).with_context(|| {
124        format!(
125            "release cannot compare workflows: no git repository covers {}",
126            root.display()
127        )
128    })?;
129    let head = repo
130        .head_commit()
131        .context("release cannot compare workflows: HEAD has no commit")?;
132    let (run, label) = run_sha
133        .and_then(|sha| find_commit_by_hex(&repo, sha))
134        .map_or((head, "HEAD"), |commit| (commit, "GITHUB_SHA"));
135    let upstream = default_upstream_commit(&repo, &candidate_names(env_base_ref().as_deref()))?
136        .context("release cannot compare workflows: there is no `origin` remote")?;
137    let upstream = repo.find_commit(upstream)?;
138    let workflows = |commit: &gix::Commit<'_>| -> Result<Option<gix::ObjectId>> {
139        Ok(commit
140            .tree()?
141            .lookup_entry_by_path(WORKFLOWS)?
142            .map(|entry| entry.object_id()))
143    };
144    if workflows(&run)? == workflows(&upstream)? {
145        return Ok(None);
146    }
147    Ok(Some(format!(
148        "{WORKFLOWS}/ at {label} {run} differs from the default branch at {upstream}",
149        run = run.id(),
150        upstream = upstream.id(),
151    )))
152}
153
154/// The commit a full hex SHA names, or `None` when it is not valid hex or
155/// names no commit in the repository.
156fn find_commit_by_hex<'repo>(
157    repo: &'repo gix::Repository,
158    sha: &str,
159) -> Option<gix::Commit<'repo>> {
160    let id = gix::ObjectId::from_hex(sha.as_bytes()).ok()?;
161    repo.find_commit(id).ok()
162}
163
164fn env_run_sha() -> Option<String> {
165    env::var("GITHUB_SHA")
166        .ok()
167        .map(|value| value.trim().to_owned())
168        .filter(|value| !value.is_empty())
169}
170
171/// Where a repository keeps its GitHub Actions workflows.
172const WORKFLOWS: &str = ".github/workflows";
173
174/// How to fetch `origin/<branch>` when that ref is missing.
175#[non_exhaustive]
176pub enum FetchDefault {
177    /// `git fetch origin`.
178    Origin,
179    /// GitHub HTTPS. Credentials are the callback, never the URL.
180    GitHub {
181        /// Access token for the fetch.
182        token: String,
183        /// The `owner/name` slug.
184        repository: String,
185    },
186}
187
188/// Prints the repository but never the token, so a logged value leaks no
189/// credential.
190impl fmt::Debug for FetchDefault {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        match self {
193            Self::Origin => f.write_str("Origin"),
194            Self::GitHub {
195                repository,
196                token: _,
197            } => f
198                .debug_struct("GitHub")
199                .field("token", &"<redacted>")
200                .field("repository", repository)
201                .finish(),
202        }
203    }
204}
205
206impl FetchDefault {
207    /// `GitHub` when `GITHUB_TOKEN` and `GITHUB_REPOSITORY` are both set and
208    /// non-empty, else `Origin`.
209    #[must_use]
210    pub fn from_env() -> Self {
211        match (env::var("GITHUB_TOKEN"), env::var("GITHUB_REPOSITORY")) {
212            (Ok(token), Ok(repository)) if !token.is_empty() && !repository.is_empty() => {
213                Self::GitHub { token, repository }
214            }
215            _ => Self::Origin,
216        }
217    }
218}
219
220/// HTTPS URL for an `owner/name` slug. No credentials in the URL.
221#[must_use]
222pub fn github_https_url(repository: &str) -> String {
223    format!("https://github.com/{repository}.git")
224}
225
226/// Username GitHub git-over-HTTPS expects. Not an HTTP Bearer scheme.
227#[must_use]
228pub fn github_git_user() -> &'static str {
229    "x-access-token"
230}
231
232/// `VERCTL_DEFAULT_BRANCH` only.
233///
234/// `GITHUB_BASE_REF` is a candidate for `off_default_history` only. It never
235/// names a branch to rewrite `origin/HEAD` with.
236#[must_use]
237pub fn configured_default_branch() -> Option<String> {
238    env::var("VERCTL_DEFAULT_BRANCH")
239        .ok()
240        .map(|value| value.trim().to_owned())
241        .filter(|value| !value.is_empty())
242}
243
244/// Point `origin/HEAD` at `origin/<branch>`. Fetch that one ref only
245/// when it is missing. The fetch gets the branch's history instead of a
246/// depth-1 tip, because `off_default_history` walks parents.
247///
248/// An empty `branch`, no repository, and no `origin` remote are each a no-op.
249///
250/// # Errors
251///
252/// Returns an error when:
253///
254/// - the fetch fails (remote unreachable, credentials rejected, or the branch
255///   absent on the remote);
256/// - `origin/<branch>` is still missing afterwards;
257/// - `origin/HEAD` cannot be updated.
258pub fn ensure_origin_head(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
259    if branch.is_empty() {
260        return Ok(());
261    }
262    let Some(repo) = repo_covering(root) else {
263        return Ok(());
264    };
265    if !has_origin(&repo) {
266        return Ok(());
267    }
268    let remote_ref = format!("refs/remotes/origin/{branch}");
269    if peel_remote(&repo, &remote_ref).is_none() {
270        fetch_one_branch(&repo, branch, fetch, Shallow::NoChange)?;
271    }
272    ensure!(
273        peel_remote(&repo, &remote_ref).is_some(),
274        "cannot resolve the default branch ({remote_ref} is missing; fetch the default branch)"
275    );
276    let target = FullName::try_from(remote_ref.as_str())
277        .context("point origin/HEAD at the default branch")?;
278    let name = FullName::try_from("refs/remotes/origin/HEAD")
279        .context("point origin/HEAD at the default branch")?;
280    repo.edit_reference(RefEdit::update(
281        name,
282        Target::Symbolic(target),
283        PreviousValue::Any,
284        "verctl default branch",
285    ))
286    .context("point origin/HEAD at the default branch")?;
287    Ok(())
288}
289
290/// Points at `VERCTL_DEFAULT_BRANCH` only while it is unset: once set,
291/// [`ensure_full_history`] has run, and a commit still past the boundary is
292/// not on the default branch.
293pub(crate) fn shallow_hint() -> &'static str {
294    if configured_default_branch().is_some() {
295        ""
296    } else {
297        ", or set VERCTL_DEFAULT_BRANCH so verctl fetches it"
298    }
299}
300
301/// Fetch the whole history of `origin/<branch>` when the clone is shallow.
302///
303/// A depth-1 checkout, which is the default of `actions/checkout`, ends at a
304/// commit that has no parents. All of these then stop at the boundary:
305///
306/// - finding the commit that set a version;
307/// - finding a tag's commit;
308/// - proving HEAD is on the default branch.
309///
310/// Fetching the default branch without a depth limit removes that boundary for
311/// every commit on it, the version commit included.
312///
313/// A clone that is not shallow, an empty `branch`, no repository, and no
314/// `origin` remote are each a no-op. The walks then report the boundary.
315///
316/// # Errors
317///
318/// Returns an error when:
319///
320/// - the shallow boundary cannot be read;
321/// - the fetch fails (remote unreachable, credentials rejected, or the branch
322///   absent on the remote).
323pub fn ensure_full_history(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
324    if branch.is_empty() {
325        return Ok(());
326    }
327    let Some(repo) = repo_covering(root) else {
328        return Ok(());
329    };
330    if !has_origin(&repo) || !repo.is_shallow().context("read the shallow boundary")? {
331        return Ok(());
332    }
333    fetch_one_branch(&repo, branch, fetch, Shallow::undo())
334}
335
336/// Fetch `origin/<branch>` so a merge-base with HEAD can be computed: when the
337/// ref is missing, or when the clone is shallow.
338///
339/// A pull request checkout from `actions/checkout` contains only the depth-1
340/// merge ref, with no `origin/<base>` and a parentless HEAD. Undoing the
341/// boundary sends the parents of every commit the clone marks shallow, HEAD
342/// included, so the walk from HEAD reaches the base branch.
343///
344/// A full clone that has the ref, an empty `branch`, no repository, and no
345/// `origin` remote are each a no-op.
346///
347/// # Errors
348///
349/// Returns an error when:
350///
351/// - the shallow boundary cannot be read;
352/// - the fetch fails (remote unreachable, credentials rejected, or the branch
353///   absent on the remote).
354pub fn ensure_comparable(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
355    if branch.is_empty() {
356        return Ok(());
357    }
358    let Some(repo) = repo_covering(root) else {
359        return Ok(());
360    };
361    if !has_origin(&repo) {
362        return Ok(());
363    }
364    let shallow = repo.is_shallow().context("read the shallow boundary")?;
365    let missing = peel_remote(&repo, &format!("refs/remotes/origin/{branch}")).is_none();
366    match (shallow, missing) {
367        (true, _) => fetch_one_branch(&repo, branch, fetch, Shallow::undo()),
368        (false, true) => fetch_one_branch(&repo, branch, fetch, Shallow::NoChange),
369        (false, false) => Ok(()),
370    }
371}
372
373/// Materialize the repository tree at release tag `tag` into `dir`, returning
374/// the path inside `dir` that corresponds to `root`.
375///
376/// Looks up `refs/tags/<tag>` locally first. When absent and the repository
377/// has an `origin` remote, fetches `refs/tags/<tag>` alone through `fetch`
378/// (depth 1 on a shallow clone, `NoChange` on a full clone so full history is
379/// preserved). Regular files keep their executable bit and symlinks are
380/// skipped, matching [`crate::MergeBase::write_to`].
381///
382/// # Errors
383///
384/// Returns an error when `root` is outside a git repository, when `tag` is
385/// empty or exists neither locally nor on `origin`, or when the tree cannot be
386/// read or written.
387pub fn extract_tag_tree(
388    root: &Path,
389    tag: &str,
390    dir: &Path,
391    fetch: &FetchDefault,
392) -> Result<PathBuf> {
393    use std::os::unix::fs::PermissionsExt as _;
394
395    ensure!(!tag.is_empty(), "baseline tag name must not be empty");
396    let repo =
397        discover(root).context("extracting a baseline release tag needs a git repository")?;
398    let mut commit_id = peel_tag_commit(&repo, tag)?;
399    if commit_id.is_none() && has_origin(&repo) {
400        let shallow = if repo.is_shallow().context("read the shallow boundary")? {
401            Shallow::DepthAtRemote(NonZeroU32::MIN)
402        } else {
403            Shallow::NoChange
404        };
405        let spec = format!("+refs/tags/{tag}:refs/tags/{tag}");
406        fetch_one_ref(&repo, &spec, fetch, shallow, "fetch the baseline tag")?;
407        commit_id = peel_tag_commit(&repo, tag)?;
408    }
409    let Some(commit_id) = commit_id else {
410        bail!(
411            "baseline tag {tag} was not found locally or on origin; verctl semver needs the release tag to build locked rustdoc JSON"
412        );
413    };
414    let tree = repo
415        .find_commit(commit_id)
416        .with_context(|| format!("read commit {commit_id} for tag {tag}"))?
417        .tree()
418        .with_context(|| format!("read tree for tag {tag}"))?;
419    let files = files_of(&tree)?;
420    for (rel, (oid, kind)) in files {
421        let mode = match kind {
422            EntryKind::Blob => 0o644,
423            EntryKind::BlobExecutable => 0o755,
424            EntryKind::Link | EntryKind::Tree | EntryKind::Commit => continue,
425        };
426        let path = dir.join(&rel);
427        if let Some(parent) = path.parent() {
428            fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
429        }
430        let blob = repo
431            .find_blob(oid)
432            .with_context(|| format!("read blob {rel} at tag {tag}"))?;
433        fs::write(&path, &blob.data).with_context(|| format!("write {}", path.display()))?;
434        fs::set_permissions(&path, Permissions::from_mode(mode))
435            .with_context(|| format!("chmod {}", path.display()))?;
436    }
437    let prefix = project_prefix(&repo, root);
438    Ok(if prefix.as_os_str().is_empty() {
439        dir.to_path_buf()
440    } else {
441        dir.join(prefix)
442    })
443}
444
445fn peel_tag_commit(repo: &gix::Repository, tag: &str) -> Result<Option<gix::ObjectId>> {
446    let full = format!("refs/tags/{tag}");
447    let Some(mut reference) = repo
448        .try_find_reference(&full)
449        .with_context(|| format!("look up {full}"))?
450    else {
451        return Ok(None);
452    };
453    let commit = reference
454        .peel_to_commit()
455        .with_context(|| format!("tag {tag} does not point to a commit"))?;
456    Ok(Some(commit.id().detach()))
457}
458
459/// Fetches `branch` alone into `origin/<branch>`, through a remote that carries
460/// only that refspec and no tags, so the configured `origin` refspecs cannot
461/// widen the fetch. `shallow` controls what happens to a shallow clone's
462/// boundary.
463fn fetch_one_branch(
464    repo: &gix::Repository,
465    branch: &str,
466    fetch: &FetchDefault,
467    shallow: Shallow,
468) -> Result<()> {
469    let spec = format!("+refs/heads/{branch}:refs/remotes/origin/{branch}");
470    fetch_one_ref(repo, &spec, fetch, shallow, "fetch the default branch")
471}
472
473fn fetch_one_ref(
474    repo: &gix::Repository,
475    spec: &str,
476    fetch: &FetchDefault,
477    shallow: Shallow,
478    context: &str,
479) -> Result<()> {
480    let url = match fetch {
481        FetchDefault::Origin => origin_url_of(repo)?,
482        FetchDefault::GitHub {
483            repository,
484            token: _,
485        } => github_https_url(repository),
486    };
487    let remote = repo
488        .remote_at(url.as_str())
489        .with_context(|| context.to_owned())?
490        .with_fetch_tags(Tags::None)
491        .with_refspecs([spec], Direction::Fetch)
492        .with_context(|| context.to_owned())?;
493    let connection = remote
494        .connect(Direction::Fetch)
495        .with_context(|| format!("git fetch {spec}"))?;
496    let interrupt = AtomicBool::new(false);
497    match fetch {
498        FetchDefault::Origin => connection
499            .prepare_fetch(Discard, ref_map::Options::default())
500            .with_context(|| format!("git fetch {spec}"))?
501            .with_shallow(shallow)
502            .receive(Discard, &interrupt),
503        FetchDefault::GitHub {
504            token,
505            repository: _,
506        } => connection
507            .with_credentials(github_credentials(token))
508            .prepare_fetch(Discard, ref_map::Options::default())
509            .with_context(|| format!("git fetch {spec}"))?
510            .with_shallow(shallow)
511            .receive(Discard, &interrupt),
512    }
513    .with_context(|| format!("git fetch {spec}"))?;
514    Ok(())
515}
516
517/// Answers every credential request with `x-access-token` and `token`, kept in
518/// memory: the token never reaches a URL, a config file, or a helper program.
519fn github_credentials(token: &str) -> impl FnMut(Action) -> gix::Result<Option<Outcome>> + '_ {
520    move |action| match action {
521        Action::Get(context) => Ok(Some(Outcome {
522            identity: Account {
523                username: github_git_user().to_owned(),
524                password: token.to_owned(),
525                oauth_refresh_token: None,
526            },
527            next: context.into(),
528        })),
529        Action::Store(_) | Action::Erase(_) => Ok(None),
530    }
531}
532
533pub(crate) fn prove_default_history(root: &Path, candidates: &[String]) -> Result<Option<String>> {
534    let repo = repo_covering(root).with_context(|| {
535        format!(
536            "release cannot prove HEAD is on the default branch: no git repository covers {}",
537            root.display()
538        )
539    })?;
540    let head = repo
541        .head_commit()
542        .context("release cannot prove HEAD is on the default branch: HEAD has no commit")?
543        .id()
544        .detach();
545    let upstream = default_upstream_commit(&repo, candidates)?.context(
546        "release cannot prove HEAD is on the default branch: there is no `origin` remote; add it and fetch the default branch",
547    )?;
548    if head == upstream {
549        return Ok(None);
550    }
551    match repo.merge_base(head, upstream) {
552        Ok(Some(base)) if base == head => Ok(None),
553        Ok(Some(_) | None) => Ok(Some(format!(
554            "HEAD {head} is not an ancestor of the default branch at {upstream}"
555        ))),
556        Err(error) => Err(error).context(
557            "release cannot prove HEAD is on the default branch (need a full fetch, not a shallow clone)",
558        ),
559    }
560}