use crate::github::types::{CommitResponse, GhContribConfig, Repository, API_BASE_URL, PER_PAGE};
use anyhow::{bail, Context, Result};
use base64::Engine;
#[derive(Debug, serde::Deserialize)]
struct ReadmeResponse {
content: String,
#[allow(dead_code)]
encoding: String,
}
pub async fn fetch_repositories(config: &GhContribConfig) -> Result<Vec<Repository>> {
let url = format!("{API_BASE_URL}/user/repos?per_page={PER_PAGE}&type=all");
do_request(config, &url).await
}
pub async fn fetch_commits(
config: &GhContribConfig,
repo_name: &str,
) -> Result<Vec<CommitResponse>> {
let since = format!("{}T00:00:00Z", config.since);
let until = format!("{}T23:59:59Z", config.until);
let url = format!(
"{API_BASE_URL}/repos/{}/{repo_name}/commits?author={}&since={since}&until={until}&per_page={PER_PAGE}",
config.username, config.username
);
do_request(config, &url).await
}
pub async fn fetch_readme(config: &GhContribConfig, repo_name: &str) -> Result<String> {
let url = format!(
"{API_BASE_URL}/repos/{}/{repo_name}/readme",
config.username
);
let response = build_request(config, &url)?
.send()
.await
.with_context(|| format!("fetching README for {repo_name}"))?;
let status = response.status();
let body = response.text().await.unwrap_or_default();
if !status.is_success() {
bail!("API returned {status}: {body}");
}
let readme_response: ReadmeResponse =
serde_json::from_str(&body).context("parsing README response")?;
let content_clean: String = readme_response
.content
.chars()
.filter(|c| !c.is_whitespace())
.collect();
let decoded = base64::engine::general_purpose::STANDARD
.decode(&content_clean)
.context("decoding README base64 content")?;
String::from_utf8(decoded).context("converting README to UTF-8")
}
async fn do_request<T: serde::de::DeserializeOwned>(
config: &GhContribConfig,
url: &str,
) -> Result<T> {
let response = build_request(config, url)?
.send()
.await
.with_context(|| format!("requesting {url}"))?;
let status = response.status();
let body = response.text().await.unwrap_or_default();
if !status.is_success() {
bail!("API returned {status}: {body}");
}
serde_json::from_str(&body).context("parsing JSON response")
}
fn build_request(config: &GhContribConfig, url: &str) -> Result<reqwest::RequestBuilder> {
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
.context("creating HTTP client")?;
Ok(client
.get(url)
.header("Authorization", format!("token {}", config.token))
.header("Accept", "application/vnd.github+json")
.header("User-Agent", config.username.clone()))
}