|
| 1 | +use crate::crates_io::CratesIoPublishingConfig; |
| 2 | +use crate::utils::ResponseExt; |
| 3 | +use anyhow::{Context, anyhow}; |
| 4 | +use log::debug; |
| 5 | +use reqwest::blocking::Client; |
| 6 | +use reqwest::header; |
| 7 | +use reqwest::header::{HeaderMap, HeaderValue}; |
| 8 | +use secrecy::{ExposeSecret, SecretString}; |
| 9 | +use serde::Serialize; |
| 10 | +use std::fmt::{Display, Formatter}; |
| 11 | + |
| 12 | +// OpenAPI spec: https://crates.io/api/openapi.json |
| 13 | +const CRATES_IO_BASE_URL: &str = "https://crates.io/api/v1"; |
| 14 | + |
| 15 | +/// Access to the Zulip API |
| 16 | +#[derive(Clone)] |
| 17 | +pub(crate) struct CratesIoApi { |
| 18 | + client: Client, |
| 19 | + token: SecretString, |
| 20 | + dry_run: bool, |
| 21 | +} |
| 22 | + |
| 23 | +impl CratesIoApi { |
| 24 | + pub(crate) fn new(token: SecretString, dry_run: bool) -> Self { |
| 25 | + let mut map = HeaderMap::default(); |
| 26 | + map.insert( |
| 27 | + header::USER_AGENT, |
| 28 | + HeaderValue::from_static(crate::USER_AGENT), |
| 29 | + ); |
| 30 | + |
| 31 | + Self { |
| 32 | + client: reqwest::blocking::ClientBuilder::default() |
| 33 | + .default_headers(map) |
| 34 | + .build() |
| 35 | + .unwrap(), |
| 36 | + token, |
| 37 | + dry_run, |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + /// List existing trusted publishing configurations for a given crate. |
| 42 | + pub(crate) fn list_trusted_publishing_github_configs( |
| 43 | + &self, |
| 44 | + krate: &str, |
| 45 | + ) -> anyhow::Result<Vec<TrustedPublishingGitHubConfig>> { |
| 46 | + #[derive(serde::Deserialize)] |
| 47 | + struct GetTrustedPublishing { |
| 48 | + github_configs: Vec<TrustedPublishingGitHubConfig>, |
| 49 | + } |
| 50 | + |
| 51 | + let response: GetTrustedPublishing = self |
| 52 | + .req::<()>( |
| 53 | + reqwest::Method::GET, |
| 54 | + &format!("/trusted_publishing/github_configs?crate={krate}"), |
| 55 | + None, |
| 56 | + )? |
| 57 | + .error_for_status()? |
| 58 | + .json_annotated()?; |
| 59 | + |
| 60 | + Ok(response.github_configs) |
| 61 | + } |
| 62 | + |
| 63 | + /// Create a new trusted publishing configuration for a given crate. |
| 64 | + pub(crate) fn create_trusted_publishing_github_config( |
| 65 | + &self, |
| 66 | + config: &CratesIoPublishingConfig, |
| 67 | + ) -> anyhow::Result<()> { |
| 68 | + debug!( |
| 69 | + "Creating trusted publishing config for '{}' in repo '{}/{}', workflow file '{}' and environment '{}'", |
| 70 | + config.krate.0, |
| 71 | + config.repo_org, |
| 72 | + config.repo_name, |
| 73 | + config.workflow_file, |
| 74 | + config.environment |
| 75 | + ); |
| 76 | + |
| 77 | + if self.dry_run { |
| 78 | + return Ok(()); |
| 79 | + } |
| 80 | + |
| 81 | + #[derive(serde::Serialize)] |
| 82 | + struct TrustedPublishingGitHubConfigCreate<'a> { |
| 83 | + repository_owner: &'a str, |
| 84 | + repository_name: &'a str, |
| 85 | + #[serde(rename = "crate")] |
| 86 | + krate: &'a str, |
| 87 | + workflow_filename: &'a str, |
| 88 | + environment: Option<&'a str>, |
| 89 | + } |
| 90 | + |
| 91 | + #[derive(serde::Serialize)] |
| 92 | + struct CreateTrustedPublishing<'a> { |
| 93 | + github_config: TrustedPublishingGitHubConfigCreate<'a>, |
| 94 | + } |
| 95 | + |
| 96 | + let request = CreateTrustedPublishing { |
| 97 | + github_config: TrustedPublishingGitHubConfigCreate { |
| 98 | + repository_owner: &config.repo_org, |
| 99 | + repository_name: &config.repo_name, |
| 100 | + krate: &config.krate.0, |
| 101 | + workflow_filename: &config.workflow_file, |
| 102 | + environment: Some(&config.environment), |
| 103 | + }, |
| 104 | + }; |
| 105 | + |
| 106 | + self.req( |
| 107 | + reqwest::Method::POST, |
| 108 | + "/trusted_publishing/github_configs", |
| 109 | + Some(&request), |
| 110 | + )? |
| 111 | + .error_for_status() |
| 112 | + .with_context(|| anyhow!("Cannot created trusted publishing config {config:?}"))?; |
| 113 | + |
| 114 | + Ok(()) |
| 115 | + } |
| 116 | + |
| 117 | + /// Delete a trusted publishing configuration with the given ID. |
| 118 | + pub(crate) fn delete_trusted_publishing_github_config( |
| 119 | + &self, |
| 120 | + id: TrustedPublishingId, |
| 121 | + ) -> anyhow::Result<()> { |
| 122 | + debug!("Deleting trusted publishing with ID {id}"); |
| 123 | + |
| 124 | + if !self.dry_run { |
| 125 | + self.req::<()>( |
| 126 | + reqwest::Method::DELETE, |
| 127 | + &format!("/trusted_publishing/github_configs/{}", id.0), |
| 128 | + None, |
| 129 | + )? |
| 130 | + .error_for_status() |
| 131 | + .with_context(|| anyhow!("Cannot delete trusted publishing config with ID {id}"))?; |
| 132 | + } |
| 133 | + |
| 134 | + Ok(()) |
| 135 | + } |
| 136 | + |
| 137 | + /// Perform a request against the crates.io API |
| 138 | + fn req<T: Serialize>( |
| 139 | + &self, |
| 140 | + method: reqwest::Method, |
| 141 | + path: &str, |
| 142 | + data: Option<&T>, |
| 143 | + ) -> anyhow::Result<reqwest::blocking::Response> { |
| 144 | + let mut req = self |
| 145 | + .client |
| 146 | + .request(method, format!("{CRATES_IO_BASE_URL}{path}")) |
| 147 | + .bearer_auth(self.token.expose_secret()); |
| 148 | + if let Some(data) = data { |
| 149 | + req = req.json(data); |
| 150 | + } |
| 151 | + |
| 152 | + Ok(req.send()?) |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +#[derive(serde::Deserialize, Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] |
| 157 | +pub struct TrustedPublishingId(u64); |
| 158 | + |
| 159 | +impl Display for TrustedPublishingId { |
| 160 | + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { |
| 161 | + self.0.fmt(f) |
| 162 | + } |
| 163 | +} |
| 164 | + |
| 165 | +#[derive(serde::Deserialize, Debug)] |
| 166 | +pub(crate) struct TrustedPublishingGitHubConfig { |
| 167 | + pub(crate) id: TrustedPublishingId, |
| 168 | + pub(crate) repository_owner: String, |
| 169 | + pub(crate) repository_name: String, |
| 170 | + pub(crate) workflow_filename: String, |
| 171 | + pub(crate) environment: Option<String>, |
| 172 | +} |
0 commit comments