use std::cell::OnceCell;
use std::path::{Path, PathBuf};
use std::time::Duration;
use std::{env, fmt, fs, io};
use anyhow::{Context, Result, bail, ensure};
use octocrab::Octocrab;
use octocrab::models::repos::Object;
use octocrab::params::State;
use octocrab::params::repos::Reference;
use octocrab::repos::releases::MakeLatest;
mod asset_upload;
pub use asset_upload::asset_content_type;
use reqwest::header::HeaderValue;
use reqwest::redirect::Policy;
use tokio::runtime::Builder;
use tokio::time;
pub use verctl_core::env::{
default_branch_of, event_default_branch, event_is_merge_group, is_merge_group,
pull_request_number, write_github_output as write_output,
};
pub use verctl_core::repo::{Repo, parse_remote, parse_slug};
use verctl_core::{env as release_env, lookup, stop};
pub fn repo_with(origin_url: impl FnOnce() -> Result<String>) -> Result<Repo> {
if let Ok(slug) = env::var("GITHUB_REPOSITORY")
&& !slug.is_empty()
{
return parse_slug(&slug);
}
origin_url()
.and_then(|url| parse_remote(url.trim()))
.map_err(lookup::unavailable)
}
pub fn base_branch_with(
configured: Option<String>,
upstream: impl FnOnce() -> Option<String>,
) -> Result<String> {
if let Ok(name) = env::var("GITHUB_REF_NAME")
&& !name.is_empty()
{
return Ok(name);
}
configured
.or_else(upstream)
.context(
"cannot tell which branch the Version PR targets: set VERCTL_DEFAULT_BRANCH, or run `git remote set-head origin --auto`",
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExistingPr {
pub url: String,
pub number: u64,
pub base_sha: String,
}
pub fn existing_pr(token: &str, repo: &Repo, head: &str) -> Result<Option<ExistingPr>> {
block(async {
let crab = client(token)?;
let page = crab
.pulls(&repo.owner, &repo.name)
.list()
.state(State::Open)
.head(format!("{}:{head}", repo.owner))
.per_page(1)
.send()
.await
.context("list pull requests")?;
Ok(page.items.into_iter().next().and_then(|pr| {
let url = pr.html_url?.to_string();
Some(ExistingPr {
url,
number: pr.number,
base_sha: pr.base.sha,
})
}))
})
}
pub fn update_pr(token: &str, repo: &Repo, number: u64, title: &str, body: &str) -> Result<String> {
block(async {
let crab = client(token)?;
let pr = crab
.pulls(&repo.owner, &repo.name)
.update(number)
.title(title)
.body(body)
.send()
.await
.context("update pull request")?;
pr.html_url
.map(|url| url.to_string())
.context("updated PR has no html_url")
})
}
pub fn create_pr(
token: &str,
repo: &Repo,
title: &str,
head: &str,
base: &str,
body: &str,
) -> Result<ExistingPr> {
block(async {
let crab = client(token)?;
let pr = crab
.pulls(&repo.owner, &repo.name)
.create(title, head, base)
.body(body)
.send()
.await
.context("create pull request")?;
let url = pr
.html_url
.map(|url| url.to_string())
.context("created PR has no html_url")?;
Ok(ExistingPr {
url,
number: pr.number,
base_sha: pr.base.sha,
})
})
}
pub fn close_pr(token: &str, repo: &Repo, number: u64, comment: &str) -> Result<String> {
block(async {
let crab = client(token)?;
close_pr_with(&crab, repo, number, comment).await
})
}
async fn close_pr_with(crab: &Octocrab, repo: &Repo, number: u64, comment: &str) -> Result<String> {
#[derive(serde::Serialize)]
struct CommentBody<'a> {
body: &'a str,
}
#[derive(serde::Serialize)]
struct CloseState {
state: &'static str,
}
#[derive(serde::Deserialize)]
struct ClosedPull {
html_url: Option<String>,
}
let comment_route = format!(
"/repos/{owner}/{name}/issues/{number}/comments",
owner = repo.owner,
name = repo.name,
);
let _: serde_json::Value = crab
.post(comment_route, Some(&CommentBody { body: comment }))
.await
.with_context(|| format!("comment on pull request #{number}"))?;
let pull_route = format!(
"/repos/{owner}/{name}/pulls/{number}",
owner = repo.owner,
name = repo.name,
);
let closed: ClosedPull = crab
.patch(pull_route, Some(&CloseState { state: "closed" }))
.await
.with_context(|| format!("close pull request #{number}"))?;
closed.html_url.context("closed PR has no html_url")
}
pub fn pull_request_is_version_pr() -> Result<bool> {
let Ok(path) = env::var("GITHUB_EVENT_PATH") else {
return Ok(false);
};
let Ok(raw) = fs::read_to_string(path) else {
return Ok(false);
};
let Some(number) = pull_request_number(&raw) else {
return Ok(false);
};
let token = release_env::env_token().context(
"the version check reads the pull request and needs GITHUB_TOKEN with pull-requests: read",
)?;
let slug = env::var("GITHUB_REPOSITORY").unwrap_or_default();
let repo = parse_slug(&slug)?;
block(async move {
let crab = client(&token)?;
let pr = crab
.pulls(&repo.owner, &repo.name)
.get(number)
.await
.with_context(|| format!("read pull request #{number}"))?;
let same_repo = pr
.head
.repo
.as_ref()
.and_then(|head| head.full_name.as_deref())
.is_some_and(|name| name.eq_ignore_ascii_case(&slug));
Ok(same_repo && pr.head.ref_field == release_env::version_branch(&pr.base.ref_field))
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stage {
Stable,
Candidate,
}
#[derive(Debug, Clone, Copy)]
pub struct NewRelease<'a> {
pub tag: &'a str,
pub name: &'a str,
pub body: &'a str,
pub sha: &'a str,
pub stage: Stage,
pub assets: &'a [String],
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum PackageUpload {
#[default]
Shipped,
Skipped,
}
pub fn ensure_release(
token: &str,
repo: &Repo,
tag: &str,
name: &str,
body: &str,
sha: &str,
upload: PackageUpload,
) -> Result<String> {
let release = NewRelease {
tag,
name,
body,
sha,
stage: Stage::Stable,
assets: &[],
};
block(async {
let crab = client(token)?;
ensure_release_with(&crab, repo, &release, upload).await
})
}
async fn ensure_release_with(
crab: &Octocrab,
repo: &Repo,
release: &NewRelease<'_>,
upload: PackageUpload,
) -> Result<String> {
let NewRelease {
tag,
name,
body,
sha,
stage,
assets: _,
} = *release;
let existing = if read_tag(crab, repo, tag).await?.is_some() {
find_release(crab, repo, tag, &ReleaseList::default()).await?
} else {
None
};
match existing {
Some(found) if !found.draft => {
if matches!(upload, PackageUpload::Shipped) {
require_tag_at(crab, repo, tag, sha).await?;
}
return Ok(found.html_url);
}
Some(draft) => {
require_tag_at(crab, repo, tag, sha).await?;
return finalize(crab, repo, release, &draft).await;
}
None => {}
}
let repos = crab.repos(&repo.owner, &repo.name);
let releases = repos.releases();
let create = releases.create(tag).name(name).body(body);
let create = match stage {
Stage::Stable => create,
Stage::Candidate => create.prerelease(true).make_latest(MakeLatest::False),
};
let created = create
.target_commitish(sha)
.send()
.await
.map_err(|error| release_error(error, tag, sha))?;
require_tag_at(crab, repo, tag, sha).await?;
Ok(created.html_url.to_string())
}
pub const TAG_PROOF_DELAYS: [Duration; 4] = [
Duration::from_secs(1),
Duration::from_secs(2),
Duration::from_secs(4),
Duration::from_secs(8),
];
#[derive(Debug)]
pub enum ExistingRelease {
Published(ReleaseRecord),
DraftState(DraftState),
}
impl ExistingRelease {
#[must_use]
pub fn uploaded(&self) -> Option<Vec<&str>> {
match self {
Self::Published(release) if release.immutable => None,
Self::Published(release) => Some(release.uploaded()),
Self::DraftState(draft) => Some(draft.uploaded()),
}
}
}
#[derive(Debug)]
pub enum DraftState {
Missing,
AtHead(ReleaseRecord),
Stale(ReleaseRecord),
}
impl DraftState {
#[must_use]
pub fn uploaded(&self) -> Vec<&str> {
match self {
Self::AtHead(draft) => draft.uploaded(),
Self::Missing | Self::Stale(_) => Vec::new(),
}
}
}
pub fn read_release(
token: &str,
repo: &Repo,
tag: &str,
head: &str,
list: &ReleaseList,
) -> Result<ExistingRelease> {
block(async {
let crab = client(token)?;
read_release_with(&crab, repo, tag, head, list).await
})
}
async fn read_release_with(
crab: &Octocrab,
repo: &Repo,
tag: &str,
head: &str,
list: &ReleaseList,
) -> Result<ExistingRelease> {
let named = read_tag(crab, repo, tag).await?;
if let Some(named) = &named {
ensure!(
named.eq_ignore_ascii_case(head),
"tag {tag} names {named}, not HEAD {head}"
);
}
let Some(release) = find_release(crab, repo, tag, list).await? else {
return Ok(ExistingRelease::DraftState(DraftState::Missing));
};
let at_head = named.is_some() || release.target_commitish.eq_ignore_ascii_case(head);
if release.draft {
return Ok(ExistingRelease::DraftState(if at_head {
DraftState::AtHead(release)
} else {
DraftState::Stale(release)
}));
}
ensure!(
at_head,
"release {tag} is published at {target}, not HEAD {head}, and GitHub serves no tag {tag}",
target = release.target_commitish
);
Ok(ExistingRelease::Published(release))
}
pub fn open_draft(
token: &str,
repo: &Repo,
release: &NewRelease<'_>,
found: &DraftState,
) -> Result<u64> {
block(async {
let crab = client(token)?;
open_draft_with(&crab, repo, release, found).await
})
}
async fn open_draft_with(
crab: &Octocrab,
repo: &Repo,
release: &NewRelease<'_>,
found: &DraftState,
) -> Result<u64> {
let NewRelease {
tag,
name,
body,
sha,
stage,
assets: _,
} = *release;
let repos = crab.repos(&repo.owner, &repo.name);
let releases = repos.releases();
match found {
DraftState::AtHead(draft) => return Ok(draft.id),
DraftState::Stale(draft) => releases.delete(draft.id).await.with_context(|| {
format!(
"delete the draft release {tag} at {target}",
target = draft.target_commitish
)
})?,
DraftState::Missing => {}
}
let create = releases
.create(tag)
.name(name)
.body(body)
.draft(true)
.target_commitish(sha);
let create = match stage {
Stage::Stable => create,
Stage::Candidate => create.prerelease(true).make_latest(MakeLatest::False),
};
let created = create
.send()
.await
.map_err(|error| release_error(error, tag, sha))?;
Ok(created.id.into_inner())
}
pub fn release_url(token: &str, repo: &Repo, id: u64) -> Result<String> {
block(async {
let crab = client(token)?;
let release: ReleaseRecord = crab
.get(
format!(
"/repos/{owner}/{name}/releases/{id}",
owner = repo.owner,
name = repo.name
),
None::<&()>,
)
.await
.with_context(|| format!("read the release {id}"))?;
Ok(release.url().to_owned())
})
}
pub fn publish_draft(
token: &str,
repo: &Repo,
release: &NewRelease<'_>,
id: u64,
) -> Result<String> {
block(async {
let crab = client(token)?;
publish_draft_with(&crab, repo, release, id).await
})
}
async fn publish_draft_with(
crab: &Octocrab,
repo: &Repo,
release: &NewRelease<'_>,
id: u64,
) -> Result<String> {
let draft: ReleaseRecord = crab
.get(
format!(
"/repos/{owner}/{name}/releases/{id}",
owner = repo.owner,
name = repo.name
),
None::<&()>,
)
.await
.with_context(|| format!("read the draft release {}", release.tag))?;
finalize(crab, repo, release, &draft).await
}
pub fn write_draft_body(token: &str, repo: &Repo, tag: &str, id: u64, body: &str) -> Result<()> {
block(async {
let crab = client(token)?;
crab.repos(&repo.owner, &repo.name)
.releases()
.update(id)
.body(body)
.send()
.await
.with_context(|| format!("write the stop record into the draft release {tag}"))?;
Ok(())
})
}
async fn finalize(
crab: &Octocrab,
repo: &Repo,
release: &NewRelease<'_>,
draft: &ReleaseRecord,
) -> Result<String> {
let uploaded = draft.uploaded();
let missing: Vec<&str> = release
.assets
.iter()
.map(String::as_str)
.filter(|name| !uploaded.contains(name))
.collect();
ensure!(
missing.is_empty(),
"the draft release {tag} lacks {missing}, so it stays a draft; rerun release with them in --assets-dir, or with --skip-assets to publish it without them",
tag = draft.tag_name,
missing = missing.join(", ")
);
let repos = crab.repos(&repo.owner, &repo.name);
let releases = repos.releases();
let update = releases
.update(draft.id)
.name(release.name)
.body(release.body)
.target_commitish(release.sha)
.draft(false);
let update = match release.stage {
Stage::Stable => update.make_latest(MakeLatest::Legacy),
Stage::Candidate => update.prerelease(true).make_latest(MakeLatest::False),
};
let published = update
.send()
.await
.with_context(|| format!("publish the draft release {}", draft.tag_name))?;
Ok(published.html_url.to_string())
}
pub fn prove_tag(
token: &str,
repo: &Repo,
tag: &str,
head: &str,
delays: &[Duration],
) -> Result<()> {
block(async {
let crab = client(token)?;
prove_tag_with(&crab, repo, tag, head, delays).await
})
}
async fn prove_tag_with(
crab: &Octocrab,
repo: &Repo,
tag: &str,
head: &str,
delays: &[Duration],
) -> Result<()> {
let mut waits = delays.iter();
let mut reads = 0_usize;
loop {
reads += 1;
if let Some(named) = read_tag(crab, repo, tag).await? {
ensure!(
named.eq_ignore_ascii_case(head),
"tag {tag} names {named}, not HEAD {head}"
);
return Ok(());
}
let Some(wait) = waits.next() else {
bail!(
"GitHub serves no tag {tag} after {reads} reads, though its Release is published; rerun release to read the tag again"
);
};
time::sleep(*wait).await;
}
}
pub fn ensure_vendored_release(
token: &str,
repo: &Repo,
tag: &str,
body: &str,
sha: &str,
) -> Result<String> {
block(async {
let crab = client(token)?;
ensure_vendored_release_with(&crab, repo, tag, body, sha).await
})
}
async fn ensure_vendored_release_with(
crab: &Octocrab,
repo: &Repo,
tag: &str,
body: &str,
sha: &str,
) -> Result<String> {
let repos = crab.repos(&repo.owner, &repo.name);
let releases = repos.releases();
match releases.get_by_tag(tag).await {
Ok(release) => return Ok(release.html_url.to_string()),
Err(error) if is_not_found(&error) => {}
Err(error) => return Err(error).with_context(|| format!("read release {tag}")),
}
let created = releases
.create(tag)
.name(tag)
.body(body)
.target_commitish(sha)
.make_latest(MakeLatest::False)
.send()
.await;
match created {
Ok(release) => Ok(release.html_url.to_string()),
Err(error) if asset_upload::is_already_exists(&error) => {
let release = releases
.get_by_tag(tag)
.await
.with_context(|| format!("read release {tag}, which another job created"))?;
Ok(release.html_url.to_string())
}
Err(error) => Err(release_error(error, tag, sha)),
}
}
pub fn asset_sha256(token: &str, repo: &Repo, tag: &str, name: &str) -> Result<String> {
block(async {
let crab = client(token)?;
asset_sha256_with(&crab, repo, tag, name).await
})
}
async fn asset_sha256_with(crab: &Octocrab, repo: &Repo, tag: &str, name: &str) -> Result<String> {
let release = upload_target(crab, repo, Target::Tag(tag)).await?;
let asset = release
.assets
.iter()
.find(|asset| asset.name == name)
.with_context(|| format!("release {tag} does not list asset {name}"))?;
asset
.digest
.as_deref()
.and_then(|digest| digest.strip_prefix("sha256:"))
.map(str::to_owned)
.with_context(|| format!("GitHub reports no SHA-256 digest for asset {name} of {tag}"))
}
pub fn uploaded_assets(token: &str, repo: &Repo, tag: &str) -> Result<Vec<String>> {
block(async {
let crab = client(token)?;
let release = upload_target(&crab, repo, Target::Tag(tag)).await?;
Ok(release.uploaded().into_iter().map(str::to_owned).collect())
})
}
#[derive(Debug)]
#[non_exhaustive]
pub struct AssetFile {
pub name: String,
pub path: PathBuf,
pub sha256: String,
}
const DOWNLOAD_TIMEOUT: Duration = Duration::from_mins(5);
pub fn download_release_assets(
token: &str,
repo: &Repo,
tag: &str,
names: &[&str],
dir: &Path,
) -> Result<Vec<AssetFile>> {
block(async {
let crab = client(token)?;
download_release_assets_with(&crab, token, repo, tag, names, dir).await
})
}
async fn download_release_assets_with(
crab: &Octocrab,
token: &str,
repo: &Repo,
tag: &str,
names: &[&str],
dir: &Path,
) -> Result<Vec<AssetFile>> {
let release = upload_target(crab, repo, Target::Tag(tag)).await?;
let http = reqwest::Client::builder()
.redirect(Policy::none())
.user_agent(format!("verctl/{}", env!("CARGO_PKG_VERSION")))
.timeout(DOWNLOAD_TIMEOUT)
.build()
.context("HTTP client")?;
let mut saved = Vec::new();
for name in names {
let asset = release
.assets
.iter()
.find(|asset| asset.name == *name)
.with_context(|| format!("release {tag} does not list asset {name}"))?;
ensure!(
!asset.url.is_empty(),
"GitHub reports no API URL for asset {name} of {tag}"
);
let sha256 = asset
.digest
.as_deref()
.and_then(|digest| digest.strip_prefix("sha256:"))
.map(str::to_owned)
.with_context(|| {
format!("GitHub reports no SHA-256 digest for asset {name} of {tag}")
})?;
let body = download_asset(&http, token, &asset.url)
.await
.with_context(|| format!("download {name} from release {tag}"))?;
let path = dir.join(name);
fs::write(&path, &body).with_context(|| path.display().to_string())?;
saved.push(AssetFile {
name: (*name).to_owned(),
path,
sha256,
});
}
Ok(saved)
}
async fn download_asset(http: &reqwest::Client, token: &str, url: &str) -> Result<bytes::Bytes> {
use reqwest::header::{ACCEPT, LOCATION};
let response = http
.get(url)
.bearer_auth(token)
.header(ACCEPT, "application/octet-stream")
.send()
.await
.with_context(|| format!("GET {url}"))?;
let response = if response.status().is_redirection() {
let location = response
.headers()
.get(LOCATION)
.and_then(|value| value.to_str().ok())
.with_context(|| format!("GET {url}: a redirect with no Location"))?
.to_owned();
http.get(location)
.send()
.await
.map_err(reqwest::Error::without_url)
.with_context(|| format!("GET the storage URL {url} redirects to"))?
} else {
response
};
let response = response
.error_for_status()
.map_err(reqwest::Error::without_url)
.with_context(|| format!("GET {url}"))?;
ensure!(
response.status().is_success(),
"GET {url}: unexpected status {}",
response.status()
);
response
.bytes()
.await
.map_err(reqwest::Error::without_url)
.with_context(|| format!("read {url}"))
}
fn release_error(error: octocrab::Error, tag: &str, sha: &str) -> anyhow::Error {
let forbidden = matches!(
&error,
octocrab::Error::GitHub { source, backtrace: _ } if source.status_code.as_u16() == 403
);
let error = anyhow::Error::new(error).context("create GitHub release");
if forbidden {
error.context(ReleaseRefused {
tag: tag.to_owned(),
sha: sha.to_owned(),
})
} else {
error
}
}
#[derive(Debug)]
struct ReleaseRefused {
tag: String,
sha: String,
}
impl fmt::Display for ReleaseRefused {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"GitHub refused to create {tag} at {sha}. When that commit's .github/workflows differ from the default branch, the Releases API also needs workflows: write, which GITHUB_TOKEN lacks; rerun verctl release at that commit with a token that has it",
tag = self.tag,
sha = self.sha
)
}
}
async fn require_tag_at(crab: &Octocrab, repo: &Repo, tag: &str, sha: &str) -> Result<()> {
let named = read_tag(crab, repo, tag)
.await?
.with_context(|| format!("tag {tag} does not exist"))?;
ensure!(
named.eq_ignore_ascii_case(sha),
"tag {tag} names {named}, not the published commit {sha}"
);
Ok(())
}
#[expect(
clippy::wildcard_enum_match_arm,
reason = "octocrab's ref Object is non_exhaustive, so a catch-all arm is required"
)]
async fn read_tag(crab: &Octocrab, repo: &Repo, tag: &str) -> Result<Option<String>> {
let git_ref = match crab
.repos(&repo.owner, &repo.name)
.get_ref(&Reference::Tag(tag.to_owned()))
.await
{
Ok(git_ref) => git_ref,
Err(error) if is_not_found(&error) => return Ok(None),
Err(error) => return Err(lookup_failed(error, format!("read tag {tag}"))),
};
match git_ref.object {
Object::Commit { sha, url: _ } => Ok(Some(sha)),
Object::Tag {
sha: tag_sha,
url: _,
} => peel_tag(crab, repo, tag, &tag_sha).await.map(Some),
other => bail!("tag {tag} names {other:?}, not a commit"),
}
}
#[derive(serde::Deserialize)]
struct TagTarget {
object: PeeledTarget,
}
#[derive(serde::Deserialize)]
struct PeeledTarget {
sha: String,
}
async fn peel_tag(crab: &Octocrab, repo: &Repo, tag: &str, tag_sha: &str) -> Result<String> {
let peeled: TagTarget = crab
.get(
format!(
"/repos/{owner}/{name}/git/tags/{tag_sha}",
owner = repo.owner,
name = repo.name
),
None::<&()>,
)
.await
.map_err(|error| lookup_failed(error, format!("peel tag {tag}")))?;
Ok(peeled.object.sha)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ReleaseState {
pub tag: Option<String>,
pub release: bool,
pub draft: bool,
pub immutable: bool,
pub assets: Vec<String>,
pub stop: stop::Record,
}
pub fn release_state(
token: &str,
repo: &Repo,
tag: &str,
list: &ReleaseList,
) -> Result<ReleaseState> {
block(async {
let crab = client(token)?;
release_state_with(&crab, repo, tag, list).await
})
}
async fn release_state_with(
crab: &Octocrab,
repo: &Repo,
tag: &str,
list: &ReleaseList,
) -> Result<ReleaseState> {
let tag_sha = read_tag(crab, repo, tag).await?;
let release = find_release(crab, repo, tag, list).await?;
Ok(ReleaseState {
tag: tag_sha,
release: release.is_some(),
draft: release.as_ref().is_some_and(|release| release.draft),
immutable: release.as_ref().is_some_and(|release| release.immutable),
assets: release
.as_ref()
.map_or_default(|release| release.uploaded().into_iter().map(str::to_owned).collect()),
stop: release
.as_ref()
.filter(|release| release.draft)
.map_or_default(|release| stop::read(release.body.as_deref().unwrap_or_default())),
})
}
fn lookup_failed(error: octocrab::Error, context: String) -> anyhow::Error {
let refused = matches!(&error, octocrab::Error::GitHub { source, backtrace: _ }
if lookup::no_answer(
source.status_code.as_u16(),
source
.headers
.as_ref()
.and_then(|headers| headers.get("x-ratelimit-remaining"))
.map(HeaderValue::as_bytes),
));
let body = matches!(
&error,
octocrab::Error::Hyper {
source: _,
backtrace: _
}
);
let service = matches!(
&error,
octocrab::Error::Service {
source: _,
backtrace: _
}
);
let error = anyhow::Error::new(error);
let transport = service
&& error.chain().any(|cause| {
cause.is::<io::Error>()
|| matches!(
cause.downcast_ref::<octocrab::Error>(),
Some(octocrab::Error::Hyper {
source: _,
backtrace: _
})
)
});
let error = error.context(context);
if refused || body || transport {
lookup::unavailable(error)
} else {
error
}
}
fn is_not_found(error: &octocrab::Error) -> bool {
matches!(error, octocrab::Error::GitHub { source, backtrace: _ } if source.status_code.as_u16() == 404)
}
#[derive(Debug, Clone, serde::Deserialize)]
pub struct ReleaseRecord {
id: u64,
html_url: String,
tag_name: String,
#[serde(default)]
target_commitish: String,
draft: bool,
#[serde(default)]
immutable: bool,
#[serde(default)]
body: Option<String>,
#[serde(default)]
upload_url: String,
assets: Vec<ForgeAsset>,
}
impl ReleaseRecord {
#[must_use]
pub const fn id(&self) -> u64 {
self.id
}
#[must_use]
pub fn url(&self) -> &str {
&self.html_url
}
#[must_use]
pub fn uploaded(&self) -> Vec<&str> {
self.assets
.iter()
.filter(|asset| asset.state == "uploaded")
.map(|asset| asset.name.as_str())
.collect()
}
}
#[derive(Debug, Clone, serde::Deserialize)]
struct ForgeAsset {
name: String,
#[serde(default)]
url: String,
state: String,
#[serde(default)]
digest: Option<String>,
}
const RELEASES_PER_PAGE: usize = 100;
const MAX_RELEASE_PAGES: u32 = 10;
#[derive(Debug, Default)]
pub struct ReleaseList {
listed: OnceCell<Vec<ReleaseRecord>>,
}
impl ReleaseList {
async fn find(&self, crab: &Octocrab, repo: &Repo, tag: &str) -> Result<Option<ReleaseRecord>> {
let listed = if let Some(listed) = self.listed.get() {
listed
} else {
let read = list_releases(crab, repo).await?;
self.listed.get_or_init(|| read)
};
Ok(listed
.iter()
.find(|release| release.tag_name == tag)
.cloned())
}
}
async fn list_releases(crab: &Octocrab, repo: &Repo) -> Result<Vec<ReleaseRecord>> {
let mut listed = Vec::new();
for page in 1..=MAX_RELEASE_PAGES {
let releases: Vec<ReleaseRecord> = crab
.get(
format!(
"/repos/{owner}/{name}/releases?per_page={RELEASES_PER_PAGE}&page={page}",
owner = repo.owner,
name = repo.name
),
None::<&()>,
)
.await
.map_err(|error| lookup_failed(error, "list releases".to_owned()))?;
let last = releases.len() < RELEASES_PER_PAGE;
listed.extend(releases);
if last {
break;
}
}
Ok(listed)
}
async fn find_release(
crab: &Octocrab,
repo: &Repo,
tag: &str,
list: &ReleaseList,
) -> Result<Option<ReleaseRecord>> {
let published: Result<ReleaseRecord, _> = crab
.get(
format!(
"/repos/{owner}/{name}/releases/tags/{tag}",
owner = repo.owner,
name = repo.name
),
None::<&()>,
)
.await;
match published {
Ok(found) => return Ok(Some(found)),
Err(error) if is_not_found(&error) => {}
Err(error) => return Err(lookup_failed(error, format!("get release {tag}"))),
}
list.find(crab, repo, tag).await
}
pub fn upload_release_asset(token: &str, repo: &Repo, tag: &str, tarball: &Path) -> Result<String> {
upload(token, repo, Target::Tag(tag), tarball)
}
pub fn upload_to_release(
token: &str,
repo: &Repo,
id: u64,
tag: &str,
tarball: &Path,
) -> Result<String> {
upload(token, repo, Target::Id { id, tag }, tarball)
}
fn upload(token: &str, repo: &Repo, target: Target<'_>, tarball: &Path) -> Result<String> {
let name = tarball
.file_name()
.and_then(|name| name.to_str())
.context("asset name")?
.to_owned();
let body =
bytes::Bytes::from(fs::read(tarball).with_context(|| tarball.display().to_string())?);
block(async {
let crab = client(token)?;
upload_release_asset_with(&crab, repo, target, &name, body, &UPLOAD_SETTLE_DELAYS).await
})
}
const UPLOAD_SETTLE_DELAYS: [Duration; 12] = [Duration::from_secs(5); 12];
#[derive(Debug, Clone, Copy)]
enum Target<'a> {
Tag(&'a str),
Id {
id: u64,
tag: &'a str,
},
}
async fn upload_target(crab: &Octocrab, repo: &Repo, target: Target<'_>) -> Result<ReleaseRecord> {
match target {
Target::Tag(tag) => find_release(crab, repo, tag, &ReleaseList::default())
.await?
.with_context(|| format!("release {tag} does not exist")),
Target::Id { id, tag } => crab
.get(
format!(
"/repos/{owner}/{name}/releases/{id}",
owner = repo.owner,
name = repo.name
),
None::<&()>,
)
.await
.with_context(|| format!("read release {tag} (id {id})")),
}
}
async fn upload_release_asset_with(
crab: &Octocrab,
repo: &Repo,
target: Target<'_>,
name: &str,
body: bytes::Bytes,
settle: &[Duration],
) -> Result<String> {
let tag = match target {
Target::Tag(tag) | Target::Id { tag, id: _ } => tag,
};
let release = upload_target(crab, repo, target).await?;
if release.uploaded().contains(&name) {
return Ok(format!("already {name}"));
}
let uploaded =
asset_upload::post_release_asset(crab, repo, release.id, &release.upload_url, name, body)
.await?;
match uploaded {
Ok(asset) => Ok(asset.browser_download_url.to_string()),
Err(error) if asset_upload::is_already_exists(&error) => {
let mut delays = settle.iter();
loop {
let release = upload_target(crab, repo, target).await?;
let asset = release
.assets
.iter()
.find(|asset| asset.name == name)
.with_context(|| {
format!(
"GitHub reports asset {name} exists, but release {tag} does not list it"
)
})?;
if asset.state == "uploaded" {
return Ok(format!("already {name}"));
}
let Some(delay) = delays.next() else {
bail!(
"release {tag} has asset {name} in state {:?}, not uploaded, after waiting for another upload to finish; delete the asset and rerun",
asset.state
);
};
time::sleep(*delay).await;
}
}
Err(error) => Err(error).context("upload release asset"),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PullAuthor {
pub login: String,
pub kind: String,
pub from_fork: bool,
}
pub fn pull_author(token: &str, repo: &Repo, number: u64) -> Result<PullAuthor> {
block(async {
let crab = client(token)?;
pull_author_with(&crab, repo, number).await
})
}
async fn pull_author_with(crab: &Octocrab, repo: &Repo, number: u64) -> Result<PullAuthor> {
#[derive(serde::Deserialize)]
struct User {
login: String,
#[serde(rename = "type")]
kind: String,
}
#[derive(serde::Deserialize)]
struct HeadRepo {
full_name: String,
}
#[derive(serde::Deserialize)]
struct Head {
repo: Option<HeadRepo>,
}
#[derive(serde::Deserialize)]
struct Pull {
user: User,
head: Head,
}
let route = format!("/repos/{}/{}/pulls/{number}", repo.owner, repo.name);
let pull: Pull = crab
.get(route, None::<&()>)
.await
.with_context(|| format!("read pull request #{number}"))?;
let own = format!("{}/{}", repo.owner, repo.name);
Ok(PullAuthor {
login: pull.user.login,
kind: pull.user.kind,
from_fork: pull
.head
.repo
.is_none_or(|head| !head.full_name.eq_ignore_ascii_case(&own)),
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ActiveRun {
pub url: String,
}
pub fn active_run(
token: &str,
repo: &Repo,
workflow: &str,
sha: &str,
) -> Result<Option<ActiveRun>> {
#[derive(serde::Deserialize)]
struct Run {
html_url: String,
head_sha: String,
status: Option<String>,
}
#[derive(serde::Deserialize)]
struct Runs {
workflow_runs: Vec<Run>,
}
block(async {
let crab = client(token)?;
let runs: Runs = crab
.get(
format!(
"/repos/{owner}/{name}/actions/workflows/{workflow}/runs?head_sha={sha}&per_page=100",
owner = repo.owner,
name = repo.name
),
None::<&()>,
)
.await
.map_err(|error| lookup_failed(error, format!("list the runs of {workflow}")))?;
Ok(runs
.workflow_runs
.into_iter()
.find(|run| {
run.head_sha.eq_ignore_ascii_case(sha) && run.status.as_deref() != Some("completed")
})
.map(|run| ActiveRun { url: run.html_url }))
})
}
pub fn pull_labels(token: &str, repo: &Repo, number: u64) -> Result<Vec<String>> {
#[derive(serde::Deserialize)]
struct Label {
name: String,
}
#[derive(serde::Deserialize)]
struct Pull {
labels: Vec<Label>,
}
block(async {
let crab = client(token)?;
let pull: Pull = crab
.get(
format!(
"/repos/{owner}/{name}/pulls/{number}",
owner = repo.owner,
name = repo.name
),
None::<&()>,
)
.await
.with_context(|| format!("read pull request #{number}"))?;
Ok(pull.labels.into_iter().map(|label| label.name).collect())
})
}
pub fn branch_rule_types(token: &str, repo: &Repo, branch: &str) -> Result<Vec<String>> {
#[derive(serde::Deserialize)]
struct Rule {
#[serde(rename = "type")]
kind: String,
}
block(async {
let crab = client(token)?;
let rules: Vec<Rule> = crab
.get(
format!(
"/repos/{owner}/{name}/rules/branches/{branch}",
owner = repo.owner,
name = repo.name
),
None::<&()>,
)
.await
.with_context(|| format!("read the rules of {branch}"))?;
Ok(rules.into_iter().map(|rule| rule.kind).collect())
})
}
fn client(token: &str) -> Result<Octocrab> {
let mut builder = Octocrab::builder().personal_token(token.to_owned());
if let Ok(base) = env::var("GITHUB_API_URL")
&& !base.is_empty()
{
builder = builder.base_uri(base).context("GITHUB_API_URL")?;
}
builder.build().context("GitHub client")
}
pub fn fetch_oidc_token(
request_url: &str,
request_token: &str,
audience: &str,
url_env_name: &str,
timeout: Duration,
) -> Result<String> {
#[derive(serde::Deserialize)]
struct Issued {
value: String,
}
block(async {
let http = reqwest::Client::builder()
.user_agent(format!("verctl/{}", env!("CARGO_PKG_VERSION")))
.timeout(timeout)
.build()
.context("HTTP client")?;
let separator = if request_url.contains('?') { '&' } else { '?' };
let response = http
.get(format!("{request_url}{separator}audience={audience}"))
.bearer_auth(request_token)
.send()
.await
.and_then(reqwest::Response::error_for_status)
.map_err(reqwest::Error::without_url)
.with_context(|| format!("request the OIDC token from {url_env_name}"))?;
let body = response
.bytes()
.await
.map_err(reqwest::Error::without_url)
.with_context(|| format!("read the OIDC token from {url_env_name}"))?;
let issued: Issued = serde_json::from_slice(&body)
.ok()
.with_context(|| format!("the answer of {url_env_name} has no OIDC token"))?;
Ok(issued.value)
})
}
fn block<F, T>(fut: F) -> Result<T>
where
F: Future<Output = Result<T>>,
{
Builder::new_current_thread()
.enable_all()
.build()
.context("tokio")?
.block_on(fut)
}
#[cfg(test)]
mod tests {
use std::fs;
use std::time::Duration;
use indoc::indoc;
use octocrab::service::middleware::retry::RetryConfig;
use verctl_core::stop::{Record, Stop};
use wiremock::matchers::{body_partial_json, header, method, path, path_regex, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};
use super::{Octocrab, ReleaseList, parse_remote, parse_slug};
#[test]
fn slug_and_remotes() {
let expected = super::Repo {
owner: "victor-software-house".into(),
name: "verctl".into(),
};
assert_eq!(
parse_slug("victor-software-house/verctl").unwrap(),
expected
);
assert_eq!(
parse_remote("https://github.com/victor-software-house/verctl.git").unwrap(),
expected
);
assert_eq!(
parse_remote("git@github.com:victor-software-house/verctl.git").unwrap(),
expected
);
assert_eq!(
parse_remote("ssh://git@github.com/victor-software-house/verctl.git").unwrap(),
expected
);
}
#[test]
fn pull_request_number_reads_only_a_pull_request_event() {
assert_eq!(
super::pull_request_number(r#"{"pull_request":{"number":187,"labels":[]}}"#),
Some(187)
);
assert_eq!(super::pull_request_number("{}"), None);
assert_eq!(super::pull_request_number("not json"), None);
assert_eq!(
super::pull_request_number(r#"{"issue":{"number":187}}"#),
None
);
}
#[test]
fn is_merge_group_reads_only_a_merge_group_event() {
assert!(super::is_merge_group(
r#"{"action":"checks_requested","merge_group":{"head_ref":"refs/heads/gh-readonly-queue/main/pr-7-0000000000000000000000000000000000000001"}}"#
));
assert!(!super::is_merge_group(r#"{"pull_request":{"number":7}}"#));
assert!(!super::is_merge_group(r#"{"merge_group":null}"#));
assert!(!super::is_merge_group("not json"));
}
#[test]
fn default_branch_of_reads_the_event_repository() {
assert_eq!(
super::default_branch_of(
r#"{"pull_request":{"number":1},"repository":{"default_branch":"main"}}"#
),
Some("main".to_owned())
);
assert_eq!(
super::default_branch_of(r#"{"repository":{"default_branch":""}}"#),
None
);
assert_eq!(super::default_branch_of("{}"), None);
assert_eq!(super::default_branch_of("not json"), None);
}
async fn pull_author_from(head: serde_json::Value) -> super::PullAuthor {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/pulls/12")))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"number": 12,
"user": { "login": "octo", "type": "User" },
"head": head
})))
.mount(&server)
.await;
super::pull_author_with(&crab(&server.uri()), &repo(), 12)
.await
.unwrap()
}
#[tokio::test]
async fn a_fork_head_is_a_fork() {
let author =
pull_author_from(serde_json::json!({ "repo": { "full_name": "octo/app" } })).await;
assert_eq!(author.login, "octo");
assert_eq!(author.kind, "User");
assert!(author.from_fork);
}
#[tokio::test]
async fn a_head_in_the_repository_is_not_a_fork() {
let author = pull_author_from(serde_json::json!({
"repo": { "full_name": format!("{OWNER}/{NAME}") }
}))
.await;
assert!(!author.from_fork);
}
#[tokio::test]
async fn a_deleted_fork_is_a_fork() {
let author = pull_author_from(serde_json::json!({ "repo": null })).await;
assert!(author.from_fork);
}
#[test]
fn rejects_non_github() {
parse_remote("https://gitlab.com/acme/app.git").unwrap_err();
}
const OWNER: &str = "acme";
const NAME: &str = "app";
const TAG: &str = "v1.0.0";
const PUBLISHED: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const OTHER: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
const TAG_OBJECT: &str = "cccccccccccccccccccccccccccccccccccccccc";
fn repo() -> super::Repo {
super::Repo {
owner: OWNER.into(),
name: NAME.into(),
}
}
fn crab(uri: &str) -> Octocrab {
Octocrab::builder()
.personal_token("token".to_owned())
.base_uri(uri)
.unwrap()
.build()
.unwrap()
}
fn missing_release() -> Mock {
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
.respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
"message": "Not Found",
"documentation_url": "https://docs.github.com"
})))
}
fn listed_releases(listed: serde_json::Value) -> Mock {
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases")))
.respond_with(ResponseTemplate::new(200).set_body_json(listed))
}
fn no_releases_listed() -> Mock {
listed_releases(serde_json::json!([]))
}
fn existing_release() -> Mock {
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
.respond_with(ResponseTemplate::new(200).set_body_json(release_json("main")))
}
fn draft_json(assets: &[(&str, &str)]) -> serde_json::Value {
let mut json = release_json(PUBLISHED);
json["draft"] = true.into();
json["html_url"] =
format!("https://github.com/{OWNER}/{NAME}/releases/tag/untagged-1").into();
json["assets"] = assets
.iter()
.map(|(name, state)| serde_json::json!({ "name": name, "state": state }))
.collect();
json
}
fn declared() -> Vec<String> {
vec![
"app.pkg".to_owned(),
"app_1.0.0_linux_x64.tar.gz".to_owned(),
]
}
fn with_assets(declared: &[String]) -> super::NewRelease<'_> {
super::NewRelease {
assets: declared,
..stable()
}
}
fn create_tag_ref() -> Mock {
Mock::given(method("POST"))
.and(path(format!("/repos/{OWNER}/{NAME}/git/refs")))
.and(body_partial_json(serde_json::json!({
"ref": format!("refs/tags/{TAG}"),
"sha": PUBLISHED
})))
.respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
"ref": format!("refs/tags/{TAG}"),
"node_id": "R",
"url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/refs/tags/{TAG}"),
"object": {
"type": "commit",
"sha": PUBLISHED,
"url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/commits/{PUBLISHED}")
}
})))
}
fn create_draft() -> Mock {
Mock::given(method("POST"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases")))
.and(body_partial_json(serde_json::json!({
"tag_name": TAG,
"draft": true,
"target_commitish": PUBLISHED
})))
.respond_with(ResponseTemplate::new(201).set_body_json(draft_json(&[])))
}
fn publish_draft() -> wiremock::MockBuilder {
Mock::given(method("PATCH"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/1")))
.and(body_partial_json(serde_json::json!({ "draft": false })))
}
fn create_at_published_sha() -> Mock {
Mock::given(method("POST"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases")))
.and(body_partial_json(serde_json::json!({
"tag_name": TAG,
"target_commitish": PUBLISHED
})))
.respond_with(ResponseTemplate::new(201).set_body_json(release_json("main")))
}
fn stable() -> super::NewRelease<'static> {
super::NewRelease {
tag: TAG,
name: TAG,
body: "notes",
sha: PUBLISHED,
stage: super::Stage::Stable,
assets: &[],
}
}
fn lightweight_tag(sha: &str) -> Mock {
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/git/ref/tags/{TAG}")))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"ref": format!("refs/tags/{TAG}"),
"node_id": "R",
"url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/refs/tags/{TAG}"),
"object": {
"type": "commit",
"sha": sha,
"url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/commits/{sha}")
}
})))
}
fn annotated_tag() -> Mock {
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/git/ref/tags/{TAG}")))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"ref": format!("refs/tags/{TAG}"),
"node_id": "R",
"url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/refs/tags/{TAG}"),
"object": {
"type": "tag",
"sha": TAG_OBJECT,
"url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/tags/{TAG_OBJECT}")
}
})))
}
fn peeled_tag_object(sha: &str) -> Mock {
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/git/tags/{TAG_OBJECT}")))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"node_id": "T",
"tag": TAG,
"sha": TAG_OBJECT,
"url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/tags/{TAG_OBJECT}"),
"message": TAG,
"object": {
"type": "commit",
"sha": sha,
"url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/commits/{sha}")
}
})))
}
fn release_json(target_commitish: &str) -> serde_json::Value {
serde_json::json!({
"url": format!("https://api.github.com/repos/{OWNER}/{NAME}/releases/1"),
"html_url": format!("https://github.com/{OWNER}/{NAME}/releases/tag/{TAG}"),
"assets_url": format!("https://api.github.com/repos/{OWNER}/{NAME}/releases/1/assets"),
"upload_url": format!("https://uploads.github.com/repos/{OWNER}/{NAME}/releases/1/assets{{?name,label}}"),
"tarball_url": format!("https://api.github.com/repos/{OWNER}/{NAME}/tarball/{TAG}"),
"zipball_url": format!("https://api.github.com/repos/{OWNER}/{NAME}/zipball/{TAG}"),
"id": 1,
"node_id": "R",
"tag_name": TAG,
"target_commitish": target_commitish,
"name": TAG,
"body": "notes",
"draft": false,
"prerelease": false,
"created_at": "2026-08-22T00:00:00Z",
"published_at": "2026-08-22T00:00:00Z",
"assets": []
})
}
fn release_with_assets(assets: &[(&str, &str)]) -> Mock {
let mut json = release_json("main");
json["assets"] = assets
.iter()
.map(|(name, state)| serde_json::json!({ "name": name, "state": state }))
.collect();
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
.respond_with(ResponseTemplate::new(200).set_body_json(json))
}
fn missing_tag() -> Mock {
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/git/ref/tags/{TAG}")))
.respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
"message": "Not Found",
"documentation_url": "https://docs.github.com"
})))
}
#[tokio::test]
async fn a_release_never_made_has_no_tag_and_no_release() {
let server = MockServer::start().await;
missing_tag().mount(&server).await;
missing_release().expect(1).mount(&server).await;
no_releases_listed().expect(1).mount(&server).await;
let state =
super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
.await
.unwrap();
assert_eq!(state, super::ReleaseState::default());
}
#[tokio::test]
async fn a_finished_release_names_its_commit_and_assets() {
let server = MockServer::start().await;
lightweight_tag(PUBLISHED).mount(&server).await;
release_with_assets(&[
("app-darwin-arm64.tar.gz", "uploaded"),
("app-linux-x64.tar.gz", "uploaded"),
("app.pkg", "starter"),
])
.mount(&server)
.await;
let state =
super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
.await
.unwrap();
assert_eq!(state.tag.as_deref(), Some(PUBLISHED));
assert!(state.release);
assert!(!state.draft);
assert_eq!(
state.assets,
["app-darwin-arm64.tar.gz", "app-linux-x64.tar.gz"]
);
}
#[tokio::test]
async fn an_immutable_release_is_read_as_immutable() {
let server = MockServer::start().await;
lightweight_tag(PUBLISHED).mount(&server).await;
let mut json = release_json("main");
json["immutable"] = true.into();
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
.respond_with(ResponseTemplate::new(200).set_body_json(json))
.mount(&server)
.await;
let state =
super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
.await
.unwrap();
assert!(
state.release && !state.draft && state.immutable,
"{state:?}"
);
}
#[tokio::test]
async fn a_draft_is_found_through_the_release_list() {
let server = MockServer::start().await;
lightweight_tag(PUBLISHED).mount(&server).await;
missing_release().mount(&server).await;
let mut other = release_json("main");
other["tag_name"] = "v0.9.0".into();
listed_releases(serde_json::json!([
other,
draft_json(&[
("app.pkg", "uploaded"),
("app_1.0.0_linux_x64.tar.gz", "starter")
])
]))
.mount(&server)
.await;
let state =
super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
.await
.unwrap();
assert!(
state.release && state.draft && !state.immutable,
"{state:?}"
);
assert_eq!(state.assets, ["app.pkg"]);
}
#[tokio::test]
async fn a_missing_release_opens_a_draft_at_head_with_no_tag() {
let server = MockServer::start().await;
create_tag_ref().expect(0).mount(&server).await;
create_draft().expect(1).mount(&server).await;
let declared = declared();
let id = super::open_draft_with(
&crab(&server.uri()),
&repo(),
&with_assets(&declared),
&super::DraftState::Missing,
)
.await
.unwrap();
assert_eq!(id, 1);
}
#[tokio::test]
async fn a_release_with_no_assets_is_published_at_once() {
let server = MockServer::start().await;
missing_release().mount(&server).await;
no_releases_listed().mount(&server).await;
lightweight_tag(PUBLISHED).mount(&server).await;
Mock::given(method("POST"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases")))
.and(body_partial_json(serde_json::json!({
"tag_name": TAG,
"target_commitish": PUBLISHED
})))
.and(|request: &wiremock::Request| {
let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
body.get("draft").is_none()
})
.respond_with(ResponseTemplate::new(201).set_body_json(release_json("main")))
.expect(1)
.mount(&server)
.await;
create_tag_ref().expect(0).mount(&server).await;
let url = super::ensure_release_with(
&crab(&server.uri()),
&repo(),
&stable(),
super::PackageUpload::Shipped,
)
.await
.unwrap();
assert!(url.contains(TAG), "{url}");
}
fn draft_by_id(assets: &[(&str, &str)]) -> Mock {
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/1")))
.respond_with(ResponseTemplate::new(200).set_body_json(draft_json(assets)))
}
#[tokio::test]
async fn a_draft_with_every_asset_uploaded_is_published() {
let server = MockServer::start().await;
draft_by_id(&[
("app.pkg", "uploaded"),
("app_1.0.0_linux_x64.tar.gz", "uploaded"),
])
.mount(&server)
.await;
publish_draft()
.and(body_partial_json(serde_json::json!({
"name": TAG,
"body": "notes",
"target_commitish": PUBLISHED,
"make_latest": "legacy"
})))
.respond_with(ResponseTemplate::new(200).set_body_json(release_json(PUBLISHED)))
.expect(1)
.mount(&server)
.await;
let declared = declared();
let url =
super::publish_draft_with(&crab(&server.uri()), &repo(), &with_assets(&declared), 1)
.await
.unwrap();
assert_eq!(
url,
format!("https://github.com/{OWNER}/{NAME}/releases/tag/{TAG}")
);
}
#[tokio::test]
async fn a_candidate_draft_is_published_as_a_prerelease_that_is_never_the_latest() {
let server = MockServer::start().await;
draft_by_id(&[("app.pkg", "uploaded")]).mount(&server).await;
Mock::given(method("PATCH"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/1")))
.and(body_partial_json(serde_json::json!({
"draft": false,
"prerelease": true,
"make_latest": "false"
})))
.respond_with(ResponseTemplate::new(200).set_body_json(release_json(PUBLISHED)))
.expect(1)
.mount(&server)
.await;
let declared = ["app.pkg".to_owned()];
let candidate = super::NewRelease {
stage: super::Stage::Candidate,
..with_assets(&declared)
};
super::publish_draft_with(&crab(&server.uri()), &repo(), &candidate, 1)
.await
.unwrap();
}
#[tokio::test]
async fn a_draft_missing_an_asset_is_not_published_and_names_what_it_lacks() {
let server = MockServer::start().await;
draft_by_id(&[
("app.pkg", "uploaded"),
("app_1.0.0_linux_x64.tar.gz", "starter"),
])
.mount(&server)
.await;
publish_draft()
.respond_with(ResponseTemplate::new(500))
.expect(0)
.mount(&server)
.await;
let declared = declared();
let error =
super::publish_draft_with(&crab(&server.uri()), &repo(), &with_assets(&declared), 1)
.await
.unwrap_err();
let message = format!("{error:#}");
assert!(
message.contains(&format!("{TAG} lacks app_1.0.0_linux_x64.tar.gz")),
"{message}"
);
}
async fn found(server: &MockServer) -> anyhow::Result<super::ExistingRelease> {
super::read_release_with(
&crab(&server.uri()),
&repo(),
TAG,
PUBLISHED,
&ReleaseList::default(),
)
.await
}
#[tokio::test]
async fn a_tag_on_another_commit_fails_before_any_write() {
let server = MockServer::start().await;
missing_release().mount(&server).await;
lightweight_tag(OTHER).mount(&server).await;
listed_releases(serde_json::json!([draft_json(&[])]))
.mount(&server)
.await;
let message = format!("{:#}", found(&server).await.unwrap_err());
assert!(message.contains(OTHER), "{message}");
assert!(message.contains(PUBLISHED), "{message}");
}
#[tokio::test]
async fn a_draft_at_head_is_kept() {
let server = MockServer::start().await;
missing_tag().mount(&server).await;
missing_release().mount(&server).await;
listed_releases(serde_json::json!([draft_json(&[("app.pkg", "uploaded")])]))
.mount(&server)
.await;
let super::ExistingRelease::DraftState(draft @ super::DraftState::AtHead(_)) =
found(&server).await.unwrap()
else {
panic!("a draft at HEAD");
};
assert_eq!(draft.uploaded(), ["app.pkg"]);
}
#[tokio::test]
async fn a_draft_at_another_commit_is_stale() {
let server = MockServer::start().await;
missing_tag().mount(&server).await;
missing_release().mount(&server).await;
let mut stale = draft_json(&[("app.pkg", "uploaded")]);
stale["target_commitish"] = "main".into();
listed_releases(serde_json::json!([stale]))
.mount(&server)
.await;
let super::ExistingRelease::DraftState(draft @ super::DraftState::Stale(_)) =
found(&server).await.unwrap()
else {
panic!("a stale draft");
};
assert_eq!(draft.uploaded(), Vec::<&str>::new());
}
#[tokio::test]
async fn a_release_published_at_head_before_its_tag_is_served_counts_as_published() {
let server = MockServer::start().await;
missing_tag().mount(&server).await;
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
.respond_with(ResponseTemplate::new(200).set_body_json(release_json(PUBLISHED)))
.mount(&server)
.await;
assert!(
matches!(
found(&server).await.unwrap(),
super::ExistingRelease::Published(_)
),
"published at HEAD"
);
}
#[tokio::test]
async fn a_release_published_elsewhere_with_no_tag_fails() {
let server = MockServer::start().await;
missing_tag().mount(&server).await;
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
.respond_with(ResponseTemplate::new(200).set_body_json(release_json(OTHER)))
.mount(&server)
.await;
let message = format!("{:#}", found(&server).await.unwrap_err());
assert!(message.contains(OTHER), "{message}");
assert!(message.contains(PUBLISHED), "{message}");
}
#[tokio::test]
async fn a_stale_draft_is_deleted_and_created_again_at_head() {
let server = MockServer::start().await;
Mock::given(method("DELETE"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/7")))
.respond_with(ResponseTemplate::new(204))
.expect(1)
.mount(&server)
.await;
create_draft().expect(1).mount(&server).await;
let mut stale = draft_json(&[]);
stale["id"] = 7.into();
stale["target_commitish"] = OTHER.into();
let stale = serde_json::from_value(stale).unwrap();
let id = super::open_draft_with(
&crab(&server.uri()),
&repo(),
&stable(),
&super::DraftState::Stale(stale),
)
.await
.unwrap();
assert_eq!(id, 1);
let methods: Vec<String> = server
.received_requests()
.await
.unwrap()
.iter()
.map(|request| request.method.to_string())
.collect();
assert_eq!(methods, ["DELETE", "POST"]);
}
#[tokio::test]
async fn a_forbidden_draft_names_the_workflows_permission() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases")))
.respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({
"message": "Resource not accessible by integration",
"documentation_url": "https://docs.github.com/rest/releases/releases#create-a-release"
})))
.mount(&server)
.await;
let error = super::open_draft_with(
&crab(&server.uri()),
&repo(),
&stable(),
&super::DraftState::Missing,
)
.await
.unwrap_err();
let message = format!("{error:#}");
assert!(message.contains("workflows: write"), "{message}");
assert!(
error.downcast_ref::<super::ReleaseRefused>().is_some(),
"{message}"
);
}
#[tokio::test]
async fn a_draft_at_head_is_used_as_it_is() {
let server = MockServer::start().await;
let draft = serde_json::from_value(draft_json(&[])).unwrap();
let id = super::open_draft_with(
&crab(&server.uri()),
&repo(),
&stable(),
&super::DraftState::AtHead(draft),
)
.await
.unwrap();
assert_eq!(id, 1);
assert_eq!(server.received_requests().await.unwrap().len(), 0);
}
const NO_WAIT: [Duration; 4] = [Duration::ZERO; 4];
async fn reads_of_the_tag(server: &MockServer) -> usize {
server.received_requests().await.unwrap().len()
}
#[tokio::test]
async fn the_tag_proof_reads_again_after_a_404() {
let server = MockServer::start().await;
missing_tag().up_to_n_times(1).mount(&server).await;
lightweight_tag(PUBLISHED).mount(&server).await;
super::prove_tag_with(&crab(&server.uri()), &repo(), TAG, PUBLISHED, &NO_WAIT)
.await
.unwrap();
assert_eq!(reads_of_the_tag(&server).await, 2);
}
#[tokio::test]
async fn the_tag_proof_fails_after_five_404s() {
let server = MockServer::start().await;
missing_tag().mount(&server).await;
let error = super::prove_tag_with(&crab(&server.uri()), &repo(), TAG, PUBLISHED, &NO_WAIT)
.await
.unwrap_err();
let message = format!("{error:#}");
assert!(message.contains(&format!("no tag {TAG}")), "{message}");
assert!(message.contains("after 5 reads"), "{message}");
assert_eq!(reads_of_the_tag(&server).await, 5);
}
#[tokio::test]
async fn the_tag_proof_fails_at_once_on_any_other_error() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/git/ref/tags/{TAG}")))
.respond_with(ResponseTemplate::new(500))
.mount(&server)
.await;
let once = Octocrab::builder()
.personal_token("token".to_owned())
.base_uri(server.uri())
.unwrap()
.add_retry_config(RetryConfig::None)
.build()
.unwrap();
let error = super::prove_tag_with(&once, &repo(), TAG, PUBLISHED, &NO_WAIT)
.await
.unwrap_err();
assert!(
format!("{error:#}").contains(&format!("read tag {TAG}")),
"{error:#}"
);
assert_eq!(reads_of_the_tag(&server).await, 1);
}
#[tokio::test]
async fn the_tag_proof_fails_on_a_tag_at_another_commit() {
let server = MockServer::start().await;
lightweight_tag(OTHER).mount(&server).await;
let error = super::prove_tag_with(&crab(&server.uri()), &repo(), TAG, PUBLISHED, &NO_WAIT)
.await
.unwrap_err();
let message = format!("{error:#}");
assert!(message.contains(OTHER), "{message}");
assert!(message.contains(PUBLISHED), "{message}");
}
fn other_releases(count: usize) -> Vec<serde_json::Value> {
(0..count)
.map(|n| {
let mut json = release_json("main");
json["tag_name"] = format!("v0.0.{n}").into();
json
})
.collect()
}
#[tokio::test]
async fn the_release_list_is_read_page_by_page_until_the_tag_is_found() {
let server = MockServer::start().await;
missing_release().mount(&server).await;
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases")))
.and(query_param("per_page", "100"))
.and(query_param("page", "1"))
.respond_with(ResponseTemplate::new(200).set_body_json(other_releases(100)))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases")))
.and(query_param("per_page", "100"))
.and(query_param("page", "2"))
.respond_with(
ResponseTemplate::new(200).set_body_json(serde_json::json!([draft_json(&[])])),
)
.expect(1)
.mount(&server)
.await;
let found =
super::find_release(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
.await
.unwrap()
.expect("the draft on page 2");
assert!(found.draft);
}
#[tokio::test]
async fn a_tagless_draft_is_an_incomplete_release() {
let server = MockServer::start().await;
missing_tag().mount(&server).await;
missing_release().mount(&server).await;
listed_releases(serde_json::json!([draft_json(&[("app.pkg", "uploaded")])]))
.mount(&server)
.await;
let state =
super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
.await
.unwrap();
assert_eq!(state.tag, None);
assert!(state.release && state.draft, "{state:?}");
assert_eq!(state.assets, ["app.pkg"]);
}
#[tokio::test]
async fn a_drafts_stop_record_is_read() {
let server = MockServer::start().await;
missing_tag().mount(&server).await;
missing_release().mount(&server).await;
let mut draft = draft_json(&[]);
draft["body"] = indoc! {r#"
notes
<!-- verctl:stop {"package":"app","version":"1.0.0","cause":"429 Too Many Requests"} -->
"#}
.into();
listed_releases(serde_json::json!([draft]))
.mount(&server)
.await;
let state =
super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
.await
.unwrap();
assert_eq!(
state.stop,
Record::Read(Stop::new("app", "1.0.0", "429 Too Many Requests", None))
);
}
#[tokio::test]
async fn the_release_list_is_read_for_ten_pages_at_most() {
let server = MockServer::start().await;
missing_release().mount(&server).await;
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases")))
.respond_with(ResponseTemplate::new(200).set_body_json(other_releases(100)))
.expect(10)
.mount(&server)
.await;
let found =
super::find_release(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
.await
.unwrap();
assert!(found.is_none(), "{found:?}");
}
#[tokio::test]
async fn create_tags_the_published_commit_not_the_default_branch() {
let server = MockServer::start().await;
missing_release().mount(&server).await;
no_releases_listed().mount(&server).await;
create_at_published_sha().mount(&server).await;
lightweight_tag(PUBLISHED).mount(&server).await;
let url = super::ensure_release_with(
&crab(&server.uri()),
&repo(),
&stable(),
super::PackageUpload::Shipped,
)
.await
.unwrap();
assert!(url.contains(TAG), "{url}");
}
#[tokio::test]
async fn a_candidate_release_is_a_prerelease_that_is_never_the_latest() {
let server = MockServer::start().await;
missing_release().mount(&server).await;
no_releases_listed().mount(&server).await;
Mock::given(method("POST"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases")))
.and(body_partial_json(serde_json::json!({
"tag_name": TAG,
"prerelease": true,
"make_latest": "false"
})))
.respond_with(ResponseTemplate::new(201).set_body_json(release_json("main")))
.mount(&server)
.await;
lightweight_tag(PUBLISHED).mount(&server).await;
let candidate = super::NewRelease {
stage: super::Stage::Candidate,
..stable()
};
let url = super::ensure_release_with(
&crab(&server.uri()),
&repo(),
&candidate,
super::PackageUpload::Shipped,
)
.await
.unwrap();
assert!(url.contains(TAG), "{url}");
}
#[tokio::test]
async fn a_stable_release_sets_neither_prerelease_nor_latest() {
let server = MockServer::start().await;
missing_release().mount(&server).await;
no_releases_listed().mount(&server).await;
Mock::given(method("POST"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases")))
.and(|request: &wiremock::Request| {
let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
body.get("prerelease").is_none() && body.get("make_latest").is_none()
})
.respond_with(ResponseTemplate::new(201).set_body_json(release_json("main")))
.mount(&server)
.await;
lightweight_tag(PUBLISHED).mount(&server).await;
let url = super::ensure_release_with(
&crab(&server.uri()),
&repo(),
&stable(),
super::PackageUpload::Shipped,
)
.await
.unwrap();
assert!(url.contains(TAG), "{url}");
}
#[tokio::test]
async fn a_forbidden_release_names_the_workflows_permission() {
let server = MockServer::start().await;
missing_release().mount(&server).await;
no_releases_listed().mount(&server).await;
Mock::given(method("POST"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases")))
.respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({
"message": "Resource not accessible by integration",
"documentation_url": "https://docs.github.com/rest/releases/releases#create-a-release"
})))
.mount(&server)
.await;
let error = super::ensure_release_with(
&crab(&server.uri()),
&repo(),
&stable(),
super::PackageUpload::Shipped,
)
.await
.unwrap_err();
let message = format!("{error:#}");
assert!(message.contains("workflows: write"), "{message}");
assert!(message.contains(PUBLISHED), "{message}");
assert!(
error.downcast_ref::<super::ReleaseRefused>().is_some(),
"{message}"
);
}
#[tokio::test]
async fn create_fails_when_the_tag_lands_elsewhere() {
let server = MockServer::start().await;
missing_release().mount(&server).await;
no_releases_listed().mount(&server).await;
create_at_published_sha().mount(&server).await;
lightweight_tag(OTHER).mount(&server).await;
let error = super::ensure_release_with(
&crab(&server.uri()),
&repo(),
&stable(),
super::PackageUpload::Shipped,
)
.await
.unwrap_err();
let message = format!("{error:#}");
assert!(message.contains(OTHER), "{message}");
assert!(message.contains(PUBLISHED), "{message}");
}
#[tokio::test]
async fn existing_release_at_the_published_commit_is_ok() {
let server = MockServer::start().await;
existing_release().mount(&server).await;
lightweight_tag(PUBLISHED).mount(&server).await;
let url = super::ensure_release_with(
&crab(&server.uri()),
&repo(),
&stable(),
super::PackageUpload::Shipped,
)
.await
.unwrap();
assert!(url.contains(TAG), "{url}");
}
#[tokio::test]
async fn existing_release_at_another_commit_fails() {
let server = MockServer::start().await;
existing_release().mount(&server).await;
lightweight_tag(OTHER).mount(&server).await;
let error = super::ensure_release_with(
&crab(&server.uri()),
&repo(),
&stable(),
super::PackageUpload::Shipped,
)
.await
.unwrap_err();
let message = format!("{error:#}");
assert!(message.contains(OTHER), "{message}");
assert!(message.contains(PUBLISHED), "{message}");
}
#[tokio::test]
async fn existing_release_is_kept_when_nothing_under_it_shipped() {
let server = MockServer::start().await;
existing_release().mount(&server).await;
lightweight_tag(OTHER).mount(&server).await;
let url = super::ensure_release_with(
&crab(&server.uri()),
&repo(),
&stable(),
super::PackageUpload::Skipped,
)
.await
.unwrap();
assert!(url.contains(TAG), "{url}");
}
#[tokio::test]
async fn annotated_tag_peels_to_the_commit() {
let server = MockServer::start().await;
existing_release().mount(&server).await;
annotated_tag().mount(&server).await;
peeled_tag_object(PUBLISHED).mount(&server).await;
let url = super::ensure_release_with(
&crab(&server.uri()),
&repo(),
&stable(),
super::PackageUpload::Shipped,
)
.await
.unwrap();
assert!(url.contains(TAG), "{url}");
}
#[tokio::test]
async fn two_missing_tags_read_the_release_list_once() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path_regex(format!(
"^/repos/{OWNER}/{NAME}/git/ref/tags/.+$"
)))
.respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
"message": "Not Found",
"documentation_url": "https://docs.github.com"
})))
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path_regex(format!(
"^/repos/{OWNER}/{NAME}/releases/tags/.+$"
)))
.respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
"message": "Not Found",
"documentation_url": "https://docs.github.com"
})))
.expect(2)
.mount(&server)
.await;
no_releases_listed().expect(1).mount(&server).await;
let list = ReleaseList::default();
let crab = crab(&server.uri());
for tag in ["v1.0.0", "v2.0.0"] {
let state = super::release_state_with(&crab, &repo(), tag, &list)
.await
.unwrap();
assert_eq!(state, super::ReleaseState::default());
}
}
#[tokio::test]
async fn an_upload_goes_to_the_drafts_id_when_two_drafts_share_the_tag() {
let server = MockServer::start().await;
let uri = server.uri();
let mut first = draft_json(&[]);
first["id"] = 1.into();
let mut second = draft_json(&[]);
second["id"] = 2.into();
listed_releases(serde_json::json!([first, second]))
.expect(0)
.mount(&server)
.await;
let mut draft = release_json(PUBLISHED);
draft["id"] = 2.into();
draft["draft"] = true.into();
draft["upload_url"] =
format!("{uri}/upload/repos/{OWNER}/{NAME}/releases/2/assets{{?name,label}}").into();
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/2")))
.respond_with(ResponseTemplate::new(200).set_body_json(draft))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path(format!(
"/upload/repos/{OWNER}/{NAME}/releases/2/assets"
)))
.respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
"url": format!("{uri}/repos/{OWNER}/{NAME}/releases/assets/9"),
"browser_download_url": format!("https://github.com/{OWNER}/{NAME}/releases/download/{TAG}/app.tar.gz"),
"id": 9,
"node_id": "A",
"name": "app.tar.gz",
"label": null,
"state": "uploaded",
"content_type": "application/gzip",
"size": 7,
"digest": null,
"download_count": 0,
"created_at": "2026-11-13T00:00:00Z",
"updated_at": "2026-11-13T00:00:00Z",
"uploader": null
})))
.expect(1)
.mount(&server)
.await;
let url = super::upload_release_asset_with(
&crab(&uri),
&repo(),
super::Target::Id { id: 2, tag: TAG },
"app.tar.gz",
bytes::Bytes::from_static(b"tarball"),
&[Duration::ZERO; 2],
)
.await
.unwrap();
assert!(url.ends_with("/app.tar.gz"), "{url}");
}
#[tokio::test]
async fn asset_uploads_send_content_type_by_extension() {
for (name, expected_type) in [
("app_1.0.0_linux_x64.tar.gz", "application/gzip"),
("app_1.0.0_macos_arm64.zip", "application/zip"),
("App.pkg", "application/octet-stream"),
("App.dmg", "application/x-apple-diskimage"),
(
"app_1.0.0_amd64.deb",
"application/vnd.debian.binary-package",
),
("app-1.0.0.rpm", "application/x-rpm"),
("app-1.0.0.msi", "application/x-msi"),
("packslip.sigstore.json", "application/json"),
("app.tar.gz.sha256", "text/plain; charset=utf-8"),
("App.bin", "application/octet-stream"),
] {
let server = MockServer::start().await;
let uri = server.uri();
let mut draft = release_json(PUBLISHED);
draft["id"] = 2.into();
draft["draft"] = true.into();
draft["upload_url"] =
format!("{uri}/upload/repos/{OWNER}/{NAME}/releases/2/assets{{?name,label}}")
.into();
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/2")))
.respond_with(ResponseTemplate::new(200).set_body_json(draft))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path(format!(
"/upload/repos/{OWNER}/{NAME}/releases/2/assets"
)))
.and(query_param("name", name))
.and(header("content-type", expected_type))
.respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
"url": format!("{uri}/repos/{OWNER}/{NAME}/releases/assets/9"),
"browser_download_url": format!("https://github.com/{OWNER}/{NAME}/releases/download/{TAG}/{name}"),
"id": 9,
"node_id": "A",
"name": name,
"label": null,
"state": "uploaded",
"content_type": expected_type,
"size": 5,
"digest": null,
"download_count": 0,
"created_at": "2026-11-13T00:00:00Z",
"updated_at": "2026-11-13T00:00:00Z",
"uploader": null
})))
.expect(1)
.mount(&server)
.await;
let url = super::upload_release_asset_with(
&crab(&uri),
&repo(),
super::Target::Id { id: 2, tag: TAG },
name,
bytes::Bytes::from_static(b"bytes"),
&[Duration::ZERO; 2],
)
.await
.unwrap();
assert!(url.ends_with(&format!("/{name}")), "{name}: {url}");
}
}
fn upload_target_json(uri: &str, assets: &serde_json::Value) -> Mock {
let mut json = release_json("main");
json["assets"] = assets.clone();
json["upload_url"] =
format!("{uri}/upload/repos/{OWNER}/{NAME}/releases/1/assets{{?name,label}}").into();
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
.respond_with(ResponseTemplate::new(200).set_body_json(json))
}
fn upload_refused(status: u16, body: serde_json::Value) -> Mock {
Mock::given(method("POST"))
.and(path(format!(
"/upload/repos/{OWNER}/{NAME}/releases/1/assets"
)))
.respond_with(ResponseTemplate::new(status).set_body_json(body))
}
fn already_exists() -> serde_json::Value {
serde_json::json!({
"message": "Validation Failed",
"errors": [{ "resource": "ReleaseAsset", "code": "already_exists", "field": "name" }],
"documentation_url": "https://docs.github.com/rest/releases/assets#upload-a-release-asset"
})
}
async fn upload(server: &MockServer) -> anyhow::Result<String> {
super::upload_release_asset_with(
&crab(&server.uri()),
&repo(),
super::Target::Tag(TAG),
"app_1.0.0_linux_x64.tar.gz",
bytes::Bytes::from_static(b"tarball"),
&[Duration::ZERO; 2],
)
.await
}
#[tokio::test]
async fn an_asset_another_run_uploaded_is_already_done() {
let server = MockServer::start().await;
upload_target_json(
&server.uri(),
&serde_json::json!([
{ "name": "app_1.0.0_linux_x64.tar.gz", "state": "uploaded" }
]),
)
.mount(&server)
.await;
upload_refused(422, already_exists())
.expect(0)
.mount(&server)
.await;
assert_eq!(
upload(&server).await.unwrap(),
"already app_1.0.0_linux_x64.tar.gz"
);
}
#[tokio::test]
async fn a_duplicate_waits_for_the_other_upload_to_finish() {
let server = MockServer::start().await;
upload_target_json(
&server.uri(),
&serde_json::json!([
{ "name": "app_1.0.0_linux_x64.tar.gz", "state": "starter" }
]),
)
.up_to_n_times(2)
.mount(&server)
.await;
upload_target_json(
&server.uri(),
&serde_json::json!([
{ "name": "app_1.0.0_linux_x64.tar.gz", "state": "uploaded" }
]),
)
.mount(&server)
.await;
upload_refused(422, already_exists()).mount(&server).await;
assert_eq!(
upload(&server).await.unwrap(),
"already app_1.0.0_linux_x64.tar.gz"
);
}
#[tokio::test]
async fn an_asset_whose_upload_broke_off_fails() {
let server = MockServer::start().await;
upload_target_json(
&server.uri(),
&serde_json::json!([
{ "name": "app_1.0.0_linux_x64.tar.gz", "state": "starter" }
]),
)
.mount(&server)
.await;
upload_refused(422, already_exists()).mount(&server).await;
let error = upload(&server).await.unwrap_err();
assert!(format!("{error:#}").contains("\"starter\""), "{error:#}");
}
#[tokio::test]
async fn another_validation_failure_fails_the_upload() {
let server = MockServer::start().await;
upload_target_json(&server.uri(), &serde_json::json!([]))
.mount(&server)
.await;
upload_refused(
422,
serde_json::json!({
"message": "Validation Failed",
"errors": [{ "resource": "ReleaseAsset", "code": "invalid", "field": "name" }]
}),
)
.mount(&server)
.await;
let error = upload(&server).await.unwrap_err();
assert!(
format!("{error:#}").contains("upload release asset"),
"{error:#}"
);
}
fn create_vendored_release() -> wiremock::MockBuilder {
Mock::given(method("POST"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases")))
.and(body_partial_json(serde_json::json!({
"tag_name": TAG,
"name": TAG,
"body": "Built from upstream.",
"target_commitish": PUBLISHED,
"make_latest": "false"
})))
}
async fn vendored_release(server: &MockServer) -> anyhow::Result<String> {
super::ensure_vendored_release_with(
&crab(&server.uri()),
&repo(),
TAG,
"Built from upstream.",
PUBLISHED,
)
.await
}
#[tokio::test]
async fn a_missing_vendored_release_is_created_and_not_made_latest() {
let server = MockServer::start().await;
missing_release().mount(&server).await;
create_vendored_release()
.respond_with(ResponseTemplate::new(201).set_body_json(release_json(PUBLISHED)))
.expect(1)
.mount(&server)
.await;
let url = vendored_release(&server).await.unwrap();
assert!(url.ends_with(&format!("/releases/tag/{TAG}")), "{url}");
}
#[tokio::test]
async fn an_existing_vendored_release_is_used_wherever_its_tag_points() {
let server = MockServer::start().await;
existing_release().mount(&server).await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(500))
.expect(0)
.mount(&server)
.await;
let url = vendored_release(&server).await.unwrap();
assert!(url.contains(TAG), "{url}");
}
#[tokio::test]
async fn a_vendored_release_another_job_created_first_is_used() {
let server = MockServer::start().await;
missing_release().up_to_n_times(1).mount(&server).await;
existing_release().mount(&server).await;
create_vendored_release()
.respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
"message": "Validation Failed",
"errors": [{ "resource": "Release", "code": "already_exists", "field": "tag_name" }]
})))
.expect(1)
.mount(&server)
.await;
let url = vendored_release(&server).await.unwrap();
assert!(url.contains(TAG), "{url}");
}
async fn sha256_of(server: &MockServer, name: &str) -> anyhow::Result<String> {
super::asset_sha256_with(&crab(&server.uri()), &repo(), TAG, name).await
}
#[tokio::test]
async fn the_checksum_is_the_digest_github_holds() {
let server = MockServer::start().await;
upload_target_json(
&server.uri(),
&serde_json::json!([
{ "name": "lib-1.0.0-linux-x64.tar.gz", "state": "uploaded", "digest": "sha256:abc123" }
]),
)
.mount(&server)
.await;
assert_eq!(
sha256_of(&server, "lib-1.0.0-linux-x64.tar.gz")
.await
.unwrap(),
"abc123"
);
}
#[tokio::test]
async fn an_asset_without_a_digest_has_no_checksum() {
let server = MockServer::start().await;
upload_target_json(
&server.uri(),
&serde_json::json!([
{ "name": "lib-1.0.0-linux-x64.tar.gz", "state": "uploaded", "digest": null }
]),
)
.mount(&server)
.await;
let error = sha256_of(&server, "lib-1.0.0-linux-x64.tar.gz")
.await
.unwrap_err();
assert!(
format!("{error:#}").contains("no SHA-256 digest"),
"{error:#}"
);
}
struct Anonymous;
impl wiremock::Match for Anonymous {
fn matches(&self, request: &wiremock::Request) -> bool {
!request.headers.contains_key("authorization")
}
}
#[tokio::test]
async fn a_draft_asset_downloads_through_the_redirect_without_the_token() {
let server = MockServer::start().await;
let uri = server.uri();
upload_target_json(
&uri,
&serde_json::json!([{
"name": "app.tar.gz",
"state": "uploaded",
"url": format!("{uri}/repos/{OWNER}/{NAME}/releases/assets/9"),
"digest": "sha256:abc123"
}]),
)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/assets/9")))
.and(header("accept", "application/octet-stream"))
.and(header("authorization", "Bearer token"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("location", format!("{uri}/storage/app.tar.gz")),
)
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/storage/app.tar.gz"))
.and(Anonymous)
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"tarball".to_vec()))
.expect(1)
.mount(&server)
.await;
let dir = tempfile::TempDir::new().unwrap();
let saved = super::download_release_assets_with(
&crab(&uri),
"token",
&repo(),
TAG,
&["app.tar.gz"],
dir.path(),
)
.await
.unwrap();
assert_eq!(saved.len(), 1);
assert_eq!(saved[0].name, "app.tar.gz");
assert_eq!(saved[0].sha256, "abc123");
assert_eq!(fs::read(dir.path().join("app.tar.gz")).unwrap(), b"tarball");
}
#[tokio::test]
async fn a_second_redirect_fails_the_download() {
let server = MockServer::start().await;
let uri = server.uri();
upload_target_json(
&uri,
&serde_json::json!([{
"name": "app.tar.gz",
"state": "uploaded",
"url": format!("{uri}/repos/{OWNER}/{NAME}/releases/assets/9"),
"digest": "sha256:abc123"
}]),
)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path(format!("/repos/{OWNER}/{NAME}/releases/assets/9")))
.respond_with(
ResponseTemplate::new(302)
.insert_header("location", format!("{uri}/storage/app.tar.gz")),
)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/storage/app.tar.gz"))
.respond_with(
ResponseTemplate::new(302).insert_header("location", format!("{uri}/elsewhere")),
)
.mount(&server)
.await;
let dir = tempfile::TempDir::new().unwrap();
let error = super::download_release_assets_with(
&crab(&uri),
"token",
&repo(),
TAG,
&["app.tar.gz"],
dir.path(),
)
.await
.unwrap_err();
assert!(
format!("{error:#}").contains("unexpected status 302"),
"{error:#}"
);
assert!(!dir.path().join("app.tar.gz").exists());
}
#[tokio::test]
async fn close_pr_comments_and_closes_pull_request() {
let server = MockServer::start().await;
let expected_url = format!("https://github.com/{OWNER}/{NAME}/pull/42");
Mock::given(method("POST"))
.and(path(format!("/repos/{OWNER}/{NAME}/issues/42/comments")))
.and(body_partial_json(serde_json::json!({
"body": "Closing this Version PR: no pending fragments remain on `main` at abc123."
})))
.respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
"id": 99
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("PATCH"))
.and(path(format!("/repos/{OWNER}/{NAME}/pulls/42")))
.and(body_partial_json(serde_json::json!({
"state": "closed"
})))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"number": 42,
"state": "closed",
"html_url": expected_url,
})))
.expect(1)
.mount(&server)
.await;
let url = super::close_pr_with(
&crab(&server.uri()),
&repo(),
42,
"Closing this Version PR: no pending fragments remain on `main` at abc123.",
)
.await
.unwrap();
assert_eq!(url, expected_url);
}
}