1use std::time::Duration;
2
3use anyhow::{Context, Result};
4use verctl_core::repo::Repo;
5
6use crate::{block, client, lookup_failed};
7
8#[derive(Debug, Clone, PartialEq, Eq)]
10#[non_exhaustive]
11pub struct ActiveRun {
12 pub url: String,
14}
15
16pub fn active_run(
34 token: &str,
35 repo: &Repo,
36 workflow: &str,
37 sha: &str,
38) -> Result<Option<ActiveRun>> {
39 #[derive(serde::Deserialize)]
40 struct Run {
41 html_url: String,
42 head_sha: String,
43 status: Option<String>,
44 }
45 #[derive(serde::Deserialize)]
46 struct Runs {
47 workflow_runs: Vec<Run>,
48 }
49 block(async {
50 let crab = client(token)?;
51 let runs: Runs = crab
52 .get(
53 format!(
54 "/repos/{owner}/{name}/actions/workflows/{workflow}/runs?head_sha={sha}&per_page=100",
55 owner = repo.owner,
56 name = repo.name
57 ),
58 None::<&()>,
59 )
60 .await
61 .map_err(|error| lookup_failed(error, format!("list the runs of {workflow}")))?;
62 Ok(runs
63 .workflow_runs
64 .into_iter()
65 .find(|run| {
66 run.head_sha.eq_ignore_ascii_case(sha) && run.status.as_deref() != Some("completed")
67 })
68 .map(|run| ActiveRun { url: run.html_url }))
69 })
70}
71
72pub fn branch_rule_types(token: &str, repo: &Repo, branch: &str) -> Result<Vec<String>> {
84 #[derive(serde::Deserialize)]
85 struct Rule {
86 #[serde(rename = "type")]
87 rule_name: String,
88 }
89 block(async {
90 let crab = client(token)?;
91 let rules: Vec<Rule> = crab
92 .get(
93 format!(
94 "/repos/{owner}/{name}/rules/branches/{branch}",
95 owner = repo.owner,
96 name = repo.name
97 ),
98 None::<&()>,
99 )
100 .await
101 .with_context(|| format!("read the rules of {branch}"))?;
102 Ok(rules.into_iter().map(|rule| rule.rule_name).collect())
103 })
104}
105
106pub fn fetch_oidc_token(
115 request_url: &str,
116 request_token: &str,
117 audience: &str,
118 url_env_name: &str,
119 timeout: Duration,
120) -> Result<String> {
121 #[derive(serde::Deserialize)]
122 struct Issued {
123 #[serde(rename = "value")]
124 jwt: String,
125 }
126 block(async {
127 let http = reqwest::Client::builder()
128 .user_agent(format!("verctl/{}", env!("CARGO_PKG_VERSION")))
129 .timeout(timeout)
130 .build()
131 .context("HTTP client")?;
132 let separator = if request_url.contains('?') { '&' } else { '?' };
133 let response = http
134 .get(format!("{request_url}{separator}audience={audience}"))
135 .bearer_auth(request_token)
136 .send()
137 .await
138 .and_then(reqwest::Response::error_for_status)
139 .map_err(reqwest::Error::without_url)
140 .with_context(|| format!("request the OIDC token from {url_env_name}"))?;
141 let body = response
142 .bytes()
143 .await
144 .map_err(reqwest::Error::without_url)
145 .with_context(|| format!("read the OIDC token from {url_env_name}"))?;
146 let issued: Issued = serde_json::from_slice(&body)
147 .ok()
148 .with_context(|| format!("the answer of {url_env_name} has no OIDC token"))?;
149 Ok(issued.jwt)
150 })
151}