use std::fmt;
use std::time::Duration;
use anyhow::{Context, Result, bail, ensure};
use octocrab::Octocrab;
use octocrab::repos::releases::MakeLatest;
use tokio::time;
use verctl_core::repo::Repo;
use crate::drafts::{self, finalize, open_draft_with, publish_draft_with};
use crate::release_state::{
ReleaseList, ReleaseRecord, find_release, find_release_for, read_tag, require_tag_at,
};
use crate::{asset_upload, block, client, is_not_found};
#[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
})
}
pub(crate) 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, None, head, list).await
})
}
pub fn read_release_for(
token: &str,
repo: &Repo,
tag: &str,
name: &str,
head: &str,
list: &ReleaseList,
) -> Result<ExistingRelease> {
block(async {
let crab = client(token)?;
read_release_with(&crab, repo, tag, Some(name), head, list).await
})
}
pub(crate) async fn read_release_with(
crab: &Octocrab,
repo: &Repo,
tag: &str,
title: Option<&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_for(crab, repo, tag, title, Some(head), list).await? else {
return Ok(ExistingRelease::DraftState(DraftState::Missing));
};
let untagged = release.tag_name != tag;
let at_head =
(named.is_some() && !untagged) || 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
})
}
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
})
}
pub fn write_draft_body(token: &str, repo: &Repo, tag: &str, id: u64, body: &str) -> Result<()> {
block(async {
let crab = client(token)?;
drafts::write_draft_body_with(&crab, repo, tag, id, body).await
})
}
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
})
}
pub(crate) 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
})
}
pub(crate) 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(crate) 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)]
pub(crate) 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
)
}
}