use super::{GhHttp, READ_TIMEOUT};
use reqwest::{StatusCode, header};
use urlencoding;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileFetch {
NotModified,
Found {
content: String,
etag: Option<String>,
},
Missing,
}
impl GhHttp {
pub async fn get_file_if_changed(
&self,
repo: &str,
path: &str,
etag: Option<&str>,
) -> anyhow::Result<FileFetch> {
let encoded = path
.split('/')
.map(|segment| urlencoding::encode(segment).into_owned())
.collect::<Vec<_>>()
.join("/");
let url = format!("{}/repos/{repo}/contents/{encoded}", self.api_root());
Self::check_backoff(&url)?;
let auth = self.auth_header(&url).await?;
let make_req = || {
let mut req = self
.client
.get(&url)
.timeout(READ_TIMEOUT)
.header(header::AUTHORIZATION, auth.clone())
.header(header::ACCEPT, "application/vnd.github.raw+json")
.header("X-GitHub-Api-Version", "2022-11-28");
if let Some(etag) = etag {
req = req.header(header::IF_NONE_MATCH, etag);
}
Ok(req)
};
let resp = self.send_with_retries(make_req, false).await?;
let status = resp.status();
if status == StatusCode::NOT_MODIFIED {
return Ok(FileFetch::NotModified);
}
if status == StatusCode::NOT_FOUND {
return Ok(FileFetch::Missing);
}
let etag = resp
.headers()
.get(header::ETAG)
.and_then(|v| v.to_str().ok())
.map(ToString::to_string);
let body = resp.text().await.unwrap_or_default();
if !status.is_success() {
Self::maybe_record_rate_limit_from_body(status, &body);
anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
}
Ok(FileFetch::Found {
content: body,
etag,
})
}
}