use std::time::Duration;
use anyhow::{Context, Result};
use verctl_core::repo::Repo;
use crate::{block, client, lookup_failed};
#[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 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())
})
}
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)
})
}