Fix GitHub api requests

This commit is contained in:
Michael Pfaff 2022-06-10 12:42:38 -04:00
parent 3ab0c2dc7b
commit 2c9b81aba6
Signed by: michael
GPG Key ID: CF402C4A012AA9D4
1 changed files with 51 additions and 18 deletions

View File

@ -6,6 +6,8 @@ use tokio::io::AsyncWriteExt;
use crate::Context;
const USER_AGENT_STR: &'static str = "Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0";
/// A sequential pipeline of [`Step`]s.
#[derive(Debug, Clone)]
pub struct Pipeline<'a> {
@ -84,24 +86,7 @@ impl<'a> Step<'a> {
.into_diagnostic()
.wrap_err("Invalid url for download step.")?,
RemoteResource::GitHubArtifact { repo, pattern } => {
const FETCH_META_ERROR_MSG: &'static str =
"Fetching the latest release metadata from GitHub failed.";
let url = url::Url::parse(&format!(
"https://api.github.com/repos/{repo}/releases/latest"
))
.into_diagnostic()
.wrap_err("Invalid GitHub repo for download step.")?;
let mut release: GitHubRelease = ctx
.reqwest
.get(url)
.send()
.await
.into_diagnostic()
.wrap_err(FETCH_META_ERROR_MSG)?
.json()
.await
.into_diagnostic()
.wrap_err(FETCH_META_ERROR_MSG)?;
let mut release = fetch_latest_release(&ctx.reqwest, repo).await?;
let pattern = ramhorns::Template::new(*pattern)
.into_diagnostic()
.wrap_err("Invalid pattern for artifact matching in download step.")?;
@ -122,6 +107,7 @@ impl<'a> Step<'a> {
let mut resp = ctx
.reqwest
.get(url)
.header("User-Agent", USER_AGENT_STR)
.send()
.await
.into_diagnostic()
@ -333,3 +319,50 @@ async fn mkdir_all(path: impl AsRef<Path>) -> Result<()> {
.into_diagnostic()
.wrap_err("Creating directory and any missing parents failed.")
}
async fn fetch_latest_release<'a, 'b>(
reqwest: &'b reqwest::Client,
repo: &'b str,
) -> Result<GitHubRelease<'a>> {
const FETCH_META_ERROR_MSG: &'static str =
"Fetching the latest release metadata from GitHub failed.";
let url = url::Url::parse(&format!(
"https://api.github.com/repos/{repo}/releases/latest"
))
.into_diagnostic()
.wrap_err("Invalid GitHub repo for download step.")?;
let mut resp = reqwest
.get(url)
.header("User-Agent", USER_AGENT_STR)
.send()
.await
.into_diagnostic()
.wrap_err(FETCH_META_ERROR_MSG)?;
let body = resp.text().await
.into_diagnostic()
.wrap_err(FETCH_META_ERROR_MSG)?;
let release: GitHubRelease = serde_json::from_str(&body)
.into_diagnostic()
.wrap_err_with(|| format!("{}: {}", FETCH_META_ERROR_MSG, body))?;
Ok(release)
}
#[cfg(test)]
mod tests {
#[test]
fn decode_latest_release() {
tokio::runtime::Builder::new_current_thread()
.enable_io()
.build()
.unwrap()
.block_on(async move {
let body = super::fetch_latest_release(
&reqwest::Client::new(),
"notepad-plus-plus/notepad-plus-plus",
)
.await
.unwrap();
assert_eq!(body.meta.draft, false);
});
}
}