verctl-github 0.9.6

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

use anyhow::{Context, Result};
use verctl_core::repo::Repo;

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

/// A workflow run that has not ended.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ActiveRun {
    /// The run's page on GitHub.
    pub url: String,
}

/// The first run of the workflow file `workflow` at commit `sha` that has not
/// ended, from `GET /repos/{owner}/{repo}/actions/workflows/{workflow}/runs`
/// with `head_sha` ([list workflow runs]). The first 100 runs of that commit
/// are read, and the commit is checked again on each, so a server that
/// ignores the filter finds no run for another commit.
///
/// A run has not ended unless its `status` is `completed`, so a status GitHub
/// adds later, or none at all, counts as running.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the request or
/// its decoding fails, for example when no workflow file has that name. Only
/// a lookup that GitHub gave no answer to is a
/// [`verctl_core::lookup::Unavailable`].
///
/// [list workflow runs]: https://docs.github.com/en/rest/actions/workflow-runs#list-workflow-runs-for-a-workflow
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 }))
    })
}

/// The `type` of each rule that applies to `branch`, from
/// `GET /repos/{owner}/{repo}/rules/branches/{branch}` ([get rules for a
/// branch]). The list is empty when no rule applies.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the request or
/// its decoding fails, including the 403 and 404 answers of a token that
/// cannot read the rules.
///
/// [get rules for a branch]: https://docs.github.com/en/rest/repos/rules#get-rules-for-a-branch
pub fn branch_rule_types(token: &str, repo: &Repo, branch: &str) -> Result<Vec<String>> {
    #[derive(serde::Deserialize)]
    struct Rule {
        #[serde(rename = "type")]
        rule_name: 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.rule_name).collect())
    })
}

/// Request a GitHub Actions OIDC JWT from `request_url` for `audience`, using
/// bearer `request_token`, without exposing the token or URL query string in
/// any error message.
///
/// # Errors
///
/// Returns an error when the HTTP client cannot be built, the request fails,
/// or the JSON body contains no `value` token field.
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 {
        #[serde(rename = "value")]
        jwt: 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.jwt)
    })
}