use std::fs::{self, Permissions};
use std::num::NonZeroU32;
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool;
use std::{env, fmt};
use anyhow::{Context, Result, bail, ensure};
use gix::bstr::ByteSlice;
use gix::credentials::helper::Action;
use gix::credentials::protocol::Outcome;
use gix::objs::tree::EntryKind;
use gix::progress::Discard;
use gix::refs::transaction::{PreviousValue, RefEdit};
use gix::refs::{FullName, Target};
use gix::remote::fetch::{Shallow, Tags};
use gix::remote::{Direction, ref_map};
use gix::sec::identity::Account;
use crate::branches::{
candidate_names, default_upstream_commit, env_base_ref, has_origin, origin_head_branch,
origin_url_of, peel_remote,
};
use crate::merge_base::files_of;
use crate::status::project_prefix;
use crate::{discover, repo_covering};
pub fn default_tip(root: &Path, candidates: &[String]) -> Result<String> {
let repo = repo_covering(root).with_context(|| {
format!(
"cannot resolve the default branch: no git repository covers {}",
root.display()
)
})?;
let tip = default_upstream_commit(&repo, candidates)?.context(
"cannot resolve the default branch: there is no `origin` remote; add it and fetch the default branch",
)?;
Ok(tip.to_string())
}
pub fn origin_url(root: &Path) -> Result<String> {
let repo = discover(root).context("open git repository")?;
let remote = repo.find_remote("origin").context("git remote origin")?;
let url = remote.url(Direction::Fetch).context("origin has no URL")?;
Ok(url.to_bstring().to_str_lossy().into_owned())
}
#[must_use]
pub fn upstream_default_branch(root: &Path) -> Option<String> {
origin_head_branch(&discover(root).ok()?)
}
pub fn off_default_history(root: &Path) -> Result<Option<String>> {
prove_default_history(root, &candidate_names(env_base_ref().as_deref()))
}
pub fn workflows_differ(root: &Path) -> Result<Option<String>> {
workflows_differ_at(root, env_run_sha().as_deref())
}
pub(crate) fn workflows_differ_at(root: &Path, run_sha: Option<&str>) -> Result<Option<String>> {
let repo = repo_covering(root).with_context(|| {
format!(
"release cannot compare workflows: no git repository covers {}",
root.display()
)
})?;
let head = repo
.head_commit()
.context("release cannot compare workflows: HEAD has no commit")?;
let (run, label) = run_sha
.and_then(|sha| find_commit_by_hex(&repo, sha))
.map_or((head, "HEAD"), |commit| (commit, "GITHUB_SHA"));
let upstream = default_upstream_commit(&repo, &candidate_names(env_base_ref().as_deref()))?
.context("release cannot compare workflows: there is no `origin` remote")?;
let upstream = repo.find_commit(upstream)?;
let workflows = |commit: &gix::Commit<'_>| -> Result<Option<gix::ObjectId>> {
Ok(commit
.tree()?
.lookup_entry_by_path(WORKFLOWS)?
.map(|entry| entry.object_id()))
};
if workflows(&run)? == workflows(&upstream)? {
return Ok(None);
}
Ok(Some(format!(
"{WORKFLOWS}/ at {label} {run} differs from the default branch at {upstream}",
run = run.id(),
upstream = upstream.id(),
)))
}
fn find_commit_by_hex<'repo>(
repo: &'repo gix::Repository,
sha: &str,
) -> Option<gix::Commit<'repo>> {
let id = gix::ObjectId::from_hex(sha.as_bytes()).ok()?;
repo.find_commit(id).ok()
}
fn env_run_sha() -> Option<String> {
env::var("GITHUB_SHA")
.ok()
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
}
const WORKFLOWS: &str = ".github/workflows";
#[non_exhaustive]
pub enum FetchDefault {
Origin,
GitHub {
token: String,
repository: String,
},
}
impl fmt::Debug for FetchDefault {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Origin => f.write_str("Origin"),
Self::GitHub {
repository,
token: _,
} => f
.debug_struct("GitHub")
.field("token", &"<redacted>")
.field("repository", repository)
.finish(),
}
}
}
impl FetchDefault {
#[must_use]
pub fn from_env() -> Self {
match (env::var("GITHUB_TOKEN"), env::var("GITHUB_REPOSITORY")) {
(Ok(token), Ok(repository)) if !token.is_empty() && !repository.is_empty() => {
Self::GitHub { token, repository }
}
_ => Self::Origin,
}
}
}
#[must_use]
pub fn github_https_url(repository: &str) -> String {
format!("https://github.com/{repository}.git")
}
#[must_use]
pub fn github_git_user() -> &'static str {
"x-access-token"
}
#[must_use]
pub fn configured_default_branch() -> Option<String> {
env::var("VERCTL_DEFAULT_BRANCH")
.ok()
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
}
pub fn ensure_origin_head(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
if branch.is_empty() {
return Ok(());
}
let Some(repo) = repo_covering(root) else {
return Ok(());
};
if !has_origin(&repo) {
return Ok(());
}
let remote_ref = format!("refs/remotes/origin/{branch}");
if peel_remote(&repo, &remote_ref).is_none() {
fetch_one_branch(&repo, branch, fetch, Shallow::NoChange)?;
}
ensure!(
peel_remote(&repo, &remote_ref).is_some(),
"cannot resolve the default branch ({remote_ref} is missing; fetch the default branch)"
);
let target = FullName::try_from(remote_ref.as_str())
.context("point origin/HEAD at the default branch")?;
let name = FullName::try_from("refs/remotes/origin/HEAD")
.context("point origin/HEAD at the default branch")?;
repo.edit_reference(RefEdit::update(
name,
Target::Symbolic(target),
PreviousValue::Any,
"verctl default branch",
))
.context("point origin/HEAD at the default branch")?;
Ok(())
}
pub(crate) fn shallow_hint() -> &'static str {
if configured_default_branch().is_some() {
""
} else {
", or set VERCTL_DEFAULT_BRANCH so verctl fetches it"
}
}
pub fn ensure_full_history(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
if branch.is_empty() {
return Ok(());
}
let Some(repo) = repo_covering(root) else {
return Ok(());
};
if !has_origin(&repo) || !repo.is_shallow().context("read the shallow boundary")? {
return Ok(());
}
fetch_one_branch(&repo, branch, fetch, Shallow::undo())
}
pub fn ensure_comparable(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
if branch.is_empty() {
return Ok(());
}
let Some(repo) = repo_covering(root) else {
return Ok(());
};
if !has_origin(&repo) {
return Ok(());
}
let shallow = repo.is_shallow().context("read the shallow boundary")?;
let missing = peel_remote(&repo, &format!("refs/remotes/origin/{branch}")).is_none();
match (shallow, missing) {
(true, _) => fetch_one_branch(&repo, branch, fetch, Shallow::undo()),
(false, true) => fetch_one_branch(&repo, branch, fetch, Shallow::NoChange),
(false, false) => Ok(()),
}
}
pub fn extract_tag_tree(
root: &Path,
tag: &str,
dir: &Path,
fetch: &FetchDefault,
) -> Result<PathBuf> {
use std::os::unix::fs::PermissionsExt as _;
ensure!(!tag.is_empty(), "baseline tag name must not be empty");
let repo =
discover(root).context("extracting a baseline release tag needs a git repository")?;
let mut commit_id = peel_tag_commit(&repo, tag)?;
if commit_id.is_none() && has_origin(&repo) {
let shallow = if repo.is_shallow().context("read the shallow boundary")? {
Shallow::DepthAtRemote(NonZeroU32::MIN)
} else {
Shallow::NoChange
};
let spec = format!("+refs/tags/{tag}:refs/tags/{tag}");
fetch_one_ref(&repo, &spec, fetch, shallow, "fetch the baseline tag")?;
commit_id = peel_tag_commit(&repo, tag)?;
}
let Some(commit_id) = commit_id else {
bail!(
"baseline tag {tag} was not found locally or on origin; verctl semver needs the release tag to build locked rustdoc JSON"
);
};
let tree = repo
.find_commit(commit_id)
.with_context(|| format!("read commit {commit_id} for tag {tag}"))?
.tree()
.with_context(|| format!("read tree for tag {tag}"))?;
let files = files_of(&tree)?;
for (rel, (oid, kind)) in files {
let mode = match kind {
EntryKind::Blob => 0o644,
EntryKind::BlobExecutable => 0o755,
EntryKind::Link | EntryKind::Tree | EntryKind::Commit => continue,
};
let path = dir.join(&rel);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
}
let blob = repo
.find_blob(oid)
.with_context(|| format!("read blob {rel} at tag {tag}"))?;
fs::write(&path, &blob.data).with_context(|| format!("write {}", path.display()))?;
fs::set_permissions(&path, Permissions::from_mode(mode))
.with_context(|| format!("chmod {}", path.display()))?;
}
let prefix = project_prefix(&repo, root);
Ok(if prefix.as_os_str().is_empty() {
dir.to_path_buf()
} else {
dir.join(prefix)
})
}
fn peel_tag_commit(repo: &gix::Repository, tag: &str) -> Result<Option<gix::ObjectId>> {
let full = format!("refs/tags/{tag}");
let Some(mut reference) = repo
.try_find_reference(&full)
.with_context(|| format!("look up {full}"))?
else {
return Ok(None);
};
let commit = reference
.peel_to_commit()
.with_context(|| format!("tag {tag} does not point to a commit"))?;
Ok(Some(commit.id().detach()))
}
fn fetch_one_branch(
repo: &gix::Repository,
branch: &str,
fetch: &FetchDefault,
shallow: Shallow,
) -> Result<()> {
let spec = format!("+refs/heads/{branch}:refs/remotes/origin/{branch}");
fetch_one_ref(repo, &spec, fetch, shallow, "fetch the default branch")
}
fn fetch_one_ref(
repo: &gix::Repository,
spec: &str,
fetch: &FetchDefault,
shallow: Shallow,
context: &str,
) -> Result<()> {
let url = match fetch {
FetchDefault::Origin => origin_url_of(repo)?,
FetchDefault::GitHub {
repository,
token: _,
} => github_https_url(repository),
};
let remote = repo
.remote_at(url.as_str())
.with_context(|| context.to_owned())?
.with_fetch_tags(Tags::None)
.with_refspecs([spec], Direction::Fetch)
.with_context(|| context.to_owned())?;
let connection = remote
.connect(Direction::Fetch)
.with_context(|| format!("git fetch {spec}"))?;
let interrupt = AtomicBool::new(false);
match fetch {
FetchDefault::Origin => connection
.prepare_fetch(Discard, ref_map::Options::default())
.with_context(|| format!("git fetch {spec}"))?
.with_shallow(shallow)
.receive(Discard, &interrupt),
FetchDefault::GitHub {
token,
repository: _,
} => connection
.with_credentials(github_credentials(token))
.prepare_fetch(Discard, ref_map::Options::default())
.with_context(|| format!("git fetch {spec}"))?
.with_shallow(shallow)
.receive(Discard, &interrupt),
}
.with_context(|| format!("git fetch {spec}"))?;
Ok(())
}
fn github_credentials(token: &str) -> impl FnMut(Action) -> gix::Result<Option<Outcome>> + '_ {
move |action| match action {
Action::Get(context) => Ok(Some(Outcome {
identity: Account {
username: github_git_user().to_owned(),
password: token.to_owned(),
oauth_refresh_token: None,
},
next: context.into(),
})),
Action::Store(_) | Action::Erase(_) => Ok(None),
}
}
pub(crate) fn prove_default_history(root: &Path, candidates: &[String]) -> Result<Option<String>> {
let repo = repo_covering(root).with_context(|| {
format!(
"release cannot prove HEAD is on the default branch: no git repository covers {}",
root.display()
)
})?;
let head = repo
.head_commit()
.context("release cannot prove HEAD is on the default branch: HEAD has no commit")?
.id()
.detach();
let upstream = default_upstream_commit(&repo, candidates)?.context(
"release cannot prove HEAD is on the default branch: there is no `origin` remote; add it and fetch the default branch",
)?;
if head == upstream {
return Ok(None);
}
match repo.merge_base(head, upstream) {
Ok(Some(base)) if base == head => Ok(None),
Ok(Some(_) | None) => Ok(Some(format!(
"HEAD {head} is not an ancestor of the default branch at {upstream}"
))),
Err(error) => Err(error).context(
"release cannot prove HEAD is on the default branch (need a full fetch, not a shallow clone)",
),
}
}