Skip to main content

orch/github/http/
contents.rs

1//! Reading one file from a repository's default branch through the contents API
2
3use super::{GhHttp, READ_TIMEOUT};
4use reqwest::{StatusCode, header};
5use urlencoding;
6
7/// A file read with `If-None-Match`
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum FileFetch {
10    /// The file has the ETag that was sent. GitHub does not count a 304 against the rate limit
11    NotModified,
12    Found {
13        content: String,
14        etag: Option<String>,
15    },
16    /// The default branch has no such file
17    Missing,
18}
19
20impl GhHttp {
21    /// Read `path` from the default branch of `repo`, sending `etag` so an unchanged file costs no
22    /// quota
23    pub async fn get_file_if_changed(
24        &self,
25        repo: &str,
26        path: &str,
27        etag: Option<&str>,
28    ) -> anyhow::Result<FileFetch> {
29        let encoded = path
30            .split('/')
31            .map(|segment| urlencoding::encode(segment).into_owned())
32            .collect::<Vec<_>>()
33            .join("/");
34        let url = format!("{}/repos/{repo}/contents/{encoded}", self.api_root());
35        Self::check_backoff(&url)?;
36        let auth = self.auth_header(&url).await?;
37        let make_req = || {
38            let mut req = self
39                .client
40                .get(&url)
41                .timeout(READ_TIMEOUT)
42                .header(header::AUTHORIZATION, auth.clone())
43                .header(header::ACCEPT, "application/vnd.github.raw+json")
44                .header("X-GitHub-Api-Version", "2022-11-28");
45            if let Some(etag) = etag {
46                req = req.header(header::IF_NONE_MATCH, etag);
47            }
48            Ok(req)
49        };
50        let resp = self.send_with_retries(make_req, false).await?;
51        let status = resp.status();
52        if status == StatusCode::NOT_MODIFIED {
53            return Ok(FileFetch::NotModified);
54        }
55
56        if status == StatusCode::NOT_FOUND {
57            return Ok(FileFetch::Missing);
58        }
59
60        let etag = resp
61            .headers()
62            .get(header::ETAG)
63            .and_then(|v| v.to_str().ok())
64            .map(ToString::to_string);
65        let body = resp.text().await.unwrap_or_default();
66        if !status.is_success() {
67            Self::maybe_record_rate_limit_from_body(status, &body);
68            anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
69        }
70
71        Ok(FileFetch::Found {
72            content: body,
73            etag,
74        })
75    }
76}