verctl-github 0.9.7

GitHub REST client for verctl releases, pull requests, tags, and branch rules
Documentation
//! GitHub REST client for `verctl` pull requests, Releases, drafts, tags,
//! branch rules, and workflow runs.

use std::{env, io};

use anyhow::{Context, Result};
use octocrab::Octocrab;
use reqwest::header::HeaderValue;
use tokio::runtime::Builder;
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,
};
use verctl_core::lookup;
pub use verctl_core::repo::{Repo, parse_remote, parse_slug};

mod actions;
mod asset_upload;
mod drafts;
mod pulls;
mod release_assets;
mod release_state;
mod releases;

pub use actions::{ActiveRun, active_run, branch_rule_types, fetch_oidc_token};
pub use asset_upload::asset_content_type;
#[cfg(test)]
use drafts::{open_draft_with, publish_draft_with};
pub use pulls::{
    ExistingPr, PullAuthor, close_pr, create_pr, existing_pr, pull_author, pull_labels,
    pull_request_is_version_pr, update_pr,
};
#[cfg(test)]
use pulls::{close_pr_with, pull_author_with};
pub use release_assets::{
    AssetFile, asset_sha256, download_release_assets, upload_release_asset, upload_to_release,
    uploaded_assets,
};
#[cfg(test)]
use release_assets::{
    Target, asset_sha256_with, download_release_assets_with, upload_release_asset_with,
};
pub use release_state::{
    ReleaseList, ReleaseRecord, ReleaseState, release_state, release_state_for,
};
#[cfg(test)]
use release_state::{find_release, release_state_for_with, release_state_with};
pub(crate) use releases::release_error;
pub use releases::{
    DraftState, ExistingRelease, NewRelease, PackageUpload, Stage, TAG_PROOF_DELAYS,
    ensure_release, ensure_vendored_release, open_draft, prove_tag, publish_draft, read_release,
    read_release_for, release_url, write_draft_body,
};
#[cfg(test)]
use releases::{
    ReleaseRefused, ensure_release_with, ensure_vendored_release_with, prove_tag_with,
    read_release_with,
};

/// Actions sets `GITHUB_REPOSITORY`. Locally, `origin` is the contract.
///
/// # Errors
///
/// Returns an error when `GITHUB_REPOSITORY` is set but is not `owner/name`,
/// or, without it, when the `origin` URL cannot be read or is not a GitHub
/// remote. Without `GITHUB_REPOSITORY`, the error is a
/// [`lookup::Unavailable`]: the repository names no GitHub repository to ask.
/// A malformed `GITHUB_REPOSITORY` is a setting to fix, so it stays unmarked.
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)
}

/// The branch a Version PR targets: `GITHUB_REF_NAME`, else
/// `VERCTL_DEFAULT_BRANCH`, else the branch `origin/HEAD` names.
///
/// If none of them is set, the call fails instead of guessing.
/// A repository whose default is not `main` would otherwise get a Version PR
/// against a branch it does not release from.
///
/// # Errors
///
/// Returns an error when none of those three sources names a branch.
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`",
        )
}

/// `error` under `context`, marked as a [`lookup::Unavailable`] when GitHub
/// gave no answer.
/// That covers two cases.
/// The request failed in transport (DNS, connect, a timeout, a connection
/// dropped while the body was read).
/// Or GitHub answered with a 5xx or a rate limit after the retries of
/// octocrab.
/// [`lookup::no_answer`] separates those statuses from the rest.
///
/// Any other answer, such as a 401 or a plain 403, stays an error.
///
/// octocrab 0.54.5 turns every non-2xx answer into `GitHub` with its status
/// and headers, whatever the body contains.
/// Its `map_github_error` falls back to the body text when the body is not
/// GitHub JSON.
/// An HTML 502 from a proxy therefore keeps its status.
///
/// A transport failure reaches octocrab as `Service` from the HTTP client.
/// It also arrives as `Hyper` while octocrab reads a body, alone or inside
/// `Service`.
/// `Service` also carries a request that the client blocks before sending.
/// It counts only when an I/O or body error caused it.
pub(crate) 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
    }
}

pub(crate) fn is_not_found(error: &octocrab::Error) -> bool {
    matches!(error, octocrab::Error::GitHub { source, backtrace: _ } if source.status_code.as_u16() == 404)
}

/// A GitHub client for `token`.
/// It uses the API from `GITHUB_API_URL` when that is set, as on a GitHub
/// Enterprise Server or a test's mock server.
/// Otherwise it uses api.github.com.
pub(crate) 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(crate) 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;