verctl-github 0.9.5

GitHub REST client for verctl releases, pull requests, tags, and branch rules
Documentation
use std::cell::OnceCell;

use anyhow::{Context, Result, bail, ensure};
use octocrab::Octocrab;
use octocrab::models::repos::Object;
use octocrab::params::repos::Reference;
use verctl_core::repo::Repo;
use verctl_core::stop;

use crate::{block, client, drafts, is_not_found, lookup_failed};

pub(crate) 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(())
}

/// The commit `tag` names, peeled through an annotated tag, or `None` when
/// GitHub answers 404 for it.
#[expect(
    clippy::wildcard_enum_match_arm,
    reason = "octocrab's ref Object is non_exhaustive, so a catch-all arm is required"
)]
pub(crate) 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)
}

/// What GitHub has for one release tag.
///
/// Not `#[non_exhaustive]`: `verctl-release` constructs fixtures directly.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ReleaseState {
    /// The commit the tag names, peeled through an annotated tag. `None` when
    /// the tag does not exist.
    pub tag: Option<String>,
    /// Whether a Release exists for the tag, draft or published.
    pub release: bool,
    /// Whether that Release is a draft, which `release` publishes after its
    /// uploads.
    pub draft: bool,
    /// Whether GitHub keeps that Release immutable: once published, its
    /// assets and tag cannot change ([immutable releases]).
    ///
    /// [immutable releases]: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases
    pub immutable: bool,
    /// The file names of the Release's assets whose upload completed.
    pub assets: Vec<String>,
    /// The stop record of a draft's body, which the last `release` run that
    /// failed an upload wrote. Display only; a published Release has none.
    pub stop: stop::Record,
}

/// Read the tag and the Release for `tag`, so a plan can tell which parts of a
/// release still need doing.
/// The Release is read even when the tag is missing: a draft has no tag
/// until it is published, so a tagless draft is an incomplete release.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or when GitHub
/// answers a tag or Release lookup with an error other than 404.
/// It also returns one when the tag points at a tree or a blob.
///
/// Only a lookup that GitHub gave no answer to, meaning a transport failure
/// or a 5xx, is a [`verctl_core::lookup::Unavailable`].
/// A 401 from a bad token, a tag on a tree, and a malformed `GITHUB_API_URL`
/// stay unmarked.
///
/// The Releases list comes from `list`, so the lookups of one plan read it
/// once however many tags are missing.
pub fn release_state(
    token: &str,
    repo: &Repo,
    tag: &str,
    list: &ReleaseList,
) -> Result<ReleaseState> {
    block(async {
        let crab = client(token)?;
        release_state_for_with(&crab, repo, tag, None, None, list).await
    })
}

/// Like [`release_state`], also matching an untagged draft Release
/// (`untagged-*`) whose title equals `name` and preferring drafts at `head`.
///
/// # Errors
///
/// Returns an error under the same conditions as [`release_state`].
pub fn release_state_for(
    token: &str,
    repo: &Repo,
    tag: &str,
    name: &str,
    head: &str,
    list: &ReleaseList,
) -> Result<ReleaseState> {
    block(async {
        let crab = client(token)?;
        release_state_for_with(&crab, repo, tag, Some(name), Some(head), list).await
    })
}

#[cfg(test)]
pub(crate) async fn release_state_with(
    crab: &Octocrab,
    repo: &Repo,
    tag: &str,
    list: &ReleaseList,
) -> Result<ReleaseState> {
    release_state_for_with(crab, repo, tag, None, None, list).await
}

pub(crate) async fn release_state_for_with(
    crab: &Octocrab,
    repo: &Repo,
    tag: &str,
    title: Option<&str>,
    head: Option<&str>,
    list: &ReleaseList,
) -> Result<ReleaseState> {
    let tag_sha = read_tag(crab, repo, tag).await?;
    let release = find_release_for(crab, repo, tag, title, head, 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())),
    })
}

/// The part of a Release verctl reads, draft or published.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct ReleaseRecord {
    pub(crate) id: u64,
    pub(crate) html_url: String,
    pub(crate) tag_name: String,
    #[serde(default)]
    pub(crate) name: Option<String>,
    /// The commit or branch the tag is created at when the Release is
    /// published. GitHub reports it for every Release. A server that does not
    /// report it names no commit, so a draft without it is stale.
    #[serde(default)]
    pub(crate) target_commitish: String,
    pub(crate) draft: bool,
    /// Reported by GitHub for every Release. A server that does not report
    /// it keeps the Release mutable.
    #[serde(default)]
    pub(crate) immutable: bool,
    /// The notes. GitHub reports `null` for a Release with none.
    #[serde(default)]
    pub(crate) body: Option<String>,
    #[serde(default)]
    pub(crate) upload_url: String,
    pub(crate) assets: Vec<ForgeAsset>,
}

impl ReleaseRecord {
    /// The Release's id.
    #[must_use]
    pub const fn id(&self) -> u64 {
        self.id
    }

    /// The Release's HTML URL.
    #[must_use]
    pub fn url(&self) -> &str {
        &self.html_url
    }

    /// The names of the assets whose upload completed.
    #[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)]
pub(crate) struct ForgeAsset {
    pub(crate) name: String,
    /// The asset's API URL, which serves the file to a token that can read
    /// the Release, a draft's included. GitHub reports it for every asset.
    #[serde(default)]
    pub(crate) url: String,
    /// `uploaded` once GitHub has the whole file; an upload that broke off
    /// leaves the asset in another state.
    pub(crate) state: String,
    /// `sha256:<hex>` of the stored file. GitHub reports `null` for an asset
    /// it contains no digest for.
    #[serde(default)]
    pub(crate) digest: Option<String>,
}

/// Releases read per page; GitHub's maximum.
const RELEASES_PER_PAGE: usize = 100;

/// Pages of Releases a lookup reads before it stops, so a repository with
/// thousands of Releases costs ten requests instead of one per page.
/// A draft verctl creates is the newest Release, so it is on the first page.
const MAX_RELEASE_PAGES: u32 = 10;

/// The Releases of a repository as `GET /releases` lists them, drafts
/// included, read at most once.
///
/// A run looks up several tags, and a draft has no tag until it is
/// published, so each missing tag would otherwise read the list again, up to
/// ten pages each. The caller has one for the lookups
/// of a run, before it writes anything: a Release the run creates afterwards
/// is not in it.
#[derive(Debug, Default)]
pub struct ReleaseList {
    listed: OnceCell<Vec<ReleaseRecord>>,
}

impl ReleaseList {
    async fn find_for(
        &self,
        crab: &Octocrab,
        repo: &Repo,
        tag: &str,
        title: Option<&str>,
        head: Option<&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(drafts::select_release(listed, tag, title, head))
    }
}

/// Every Release `GET /releases` lists, newest first, which shows drafts to
/// a token with push access ([list releases]), up to [`MAX_RELEASE_PAGES`]
/// pages.
/// A draft verctl creates is the newest Release, so it is on the first page;
/// a draft older than the newest 1000 Releases is not found.
///
/// [list releases]: https://docs.github.com/en/rest/releases/releases#list-releases
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)
}

/// The Release for `tag`, draft or published, or `None`.
///
/// `GET /releases/tags/{tag}` answers for a published Release in one
/// request, even when GitHub serves its new tag a moment later. It returns
/// 404 for a draft ([get a release by tag name]), and only then is the tag
/// looked up in `list`, which a draft is in: a draft has no tag until it is
/// published.
///
/// [get a release by tag name]: https://docs.github.com/en/rest/releases/releases#get-a-release-by-tag-name
pub(crate) async fn find_release(
    crab: &Octocrab,
    repo: &Repo,
    tag: &str,
    list: &ReleaseList,
) -> Result<Option<ReleaseRecord>> {
    find_release_for(crab, repo, tag, None, None, list).await
}

pub(crate) async fn find_release_for(
    crab: &Octocrab,
    repo: &Repo,
    tag: &str,
    title: Option<&str>,
    head: Option<&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_for(crab, repo, tag, title, head).await
}