orch-cli 0.118.1

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! Reading one file from a repository's default branch through the contents API

use super::{GhHttp, READ_TIMEOUT};
use reqwest::{StatusCode, header};
use urlencoding;

/// A file read with `If-None-Match`
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileFetch {
    /// The file has the ETag that was sent. GitHub does not count a 304 against the rate limit
    NotModified,
    Found {
        content: String,
        etag: Option<String>,
    },
    /// The default branch has no such file
    Missing,
}

impl GhHttp {
    /// Read `path` from the default branch of `repo`, sending `etag` so an unchanged file costs no
    /// quota
    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,
        })
    }
}