LINE1 10 20 30 40 50 60 70 80 901use anyhow::{anyhow, Context, Result};2use reqwest::Client;3use serde::Deserialize;45use crate::cache::{Project, Repo, StatusOption};67pub struct GitHubClient {8 client: Client,9 token: String,10}1112#[derive(Debug)]13pub struct CreatedIssue {14 pub number: u64,15 pub html_url: String,16 pub node_id: String,17}1819pub struct StatusField {20 pub field_id: String,21 pub options: Vec<StatusOption>,22}2324impl GitHubClient {25 pub fn new(token: &str) -> Self {26 let client = Client::builder()27 .user_agent("pike")28 .build()29 .expect("Failed to create HTTP client");30 Self {31 client,32 token: token.to_string(),33 }34 }3536 fn auth_header(&self) -> String {37 format!("Bearer {}", self.token)38 }3940 pub async fn list_org_repos(&self, org: &str) -> Result<Vec<Repo>> {41 let mut all_repos: Vec<Repo> = Vec::new();42 let mut page = 1u32;4344 loop {45 let url = format!(46 "https://api.github.com/orgs/{org}/repos?per_page=100&page={page}"47 );48 let resp = self49 .client50 .get(&url)51 .header("Authorization", self.auth_header())52 .header("Accept", "application/vnd.github+json")53 .send()54 .await55 .context("Failed to fetch org repos")?;5657 let status = resp.status();58 if !status.is_success() {59 let body = resp.text().await.unwrap_or_default();60 return Err(anyhow!("GitHub API error ({status}): {body}"));61 }6263 let repos_raw: Vec<RepoResponse> = resp64 .json()65 .await66 .context("Failed to parse repo list response")?;6768 let count = repos_raw.len();69 all_repos.extend(repos_raw.into_iter().map(|r| Repo {70 name: r.name,71 full_name: r.full_name,72 }));7374 if count < 100 {75 break;76 }77 page += 1;78 }7980 Ok(all_repos)81 }8283 pub async fn create_issue(84 &self,85 owner_repo: &str,86 title: &str,87 body: &str,88 ) -> Result<CreatedIssue> {89 let url = format!("https://api.github.com/repos/{owner_repo}/issues");90 let body_json = serde_json::json!({91 "title": title,92 "body": body,93 });9495 let resp = self96 .client97 .post(&url)98 .header("Authorization", self.auth_header())99 .header("Accept", "application/vnd.github+json")100 .json(&body_json)101 .send()102 .await103 .context("Failed to create issue")?;104105 let status = resp.status();106 if !status.is_success() {107 let body = resp.text().await.unwrap_or_default();108 return Err(anyhow!("GitHub API error ({status}): {body}"));109 }110111 let issue: CreateIssueResponse = resp112 .json()113 .await114 .context("Failed to parse create issue response")?;115116 Ok(CreatedIssue {117 number: issue.number,118 html_url: issue.html_url,119 node_id: issue.node_id,120 })121 }122123 pub async fn list_org_projects(&self, org: &str) -> Result<Vec<Project>> {124 let query = r#"125 query($login: String!) {126 organization(login: $login) {127 projectsV2(first: 100) {128 nodes {129 id130 title131 }132 }133 }134 }135 "#;136137 let resp = self138 .graphql_request(query, serde_json::json!({ "login": org }))139 .await?;140141 let org_data = resp142 .get("organization")143 .ok_or_else(|| anyhow!("No organization found in response"))?;144 let nodes = org_data145 .get("projectsV2")146 .and_then(|p| p.get("nodes"))147 .and_then(|n| n.as_array())148 .ok_or_else(|| anyhow!("No projects found in response"))?;149150 let mut projects = Vec::new();151 for node in nodes {152 let id = node["id"].as_str().unwrap_or("").to_string();153 let title = node["title"].as_str().unwrap_or("").to_string();154 if !id.is_empty() {155 projects.push(Project {156 id,157 title,158 status_field_id: String::new(),159 status_options: Vec::new(),160 });161 }162 }163164 for project in &mut projects {165 match self.get_project_status_field(&project.id).await {166 Ok(status) => {167 project.status_field_id = status.field_id;168 project.status_options = status.options;169 }170 Err(_) => continue,171 }172 }173174 Ok(projects)175 }176177 pub async fn get_project_status_field(&self, project_id: &str) -> Result<StatusField> {178 let query = r#"179 query($id: ID!) {180 node(id: $id) {181 ... on ProjectV2 {182 fields(first: 20) {183 nodes {184 ... on ProjectV2SingleSelectField {185 id186 name187 options {188 id189 name190 }191 }192 }193 }194 }195 }196 }197 "#;198199 let resp = self200 .graphql_request(query, serde_json::json!({ "id": project_id }))201 .await?;202203 let node = resp204 .get("node")205 .ok_or_else(|| anyhow!("No node found in response"))?;206 let fields = node207 .get("fields")208 .and_then(|f| f.get("nodes"))209 .and_then(|n| n.as_array())210 .ok_or_else(|| anyhow!("No fields found in project"))?;211212 for field in fields {213 let name = field["name"].as_str().unwrap_or("");214 if name.eq_ignore_ascii_case("status") {215 let field_id = field["id"].as_str().unwrap_or("").to_string();216 let options = field217 .get("options")218 .and_then(|o| o.as_array())219 .map(|arr| {220 arr.iter()221 .filter_map(|opt| {222 let id = opt["id"].as_str()?;223 let name = opt["name"].as_str()?;224 Some(StatusOption {225 id: id.to_string(),226 name: name.to_string(),227 })228 })229 .collect::<Vec<_>>()230 })231 .unwrap_or_default();232233 return Ok(StatusField { field_id, options });234 }235 }236237 Ok(StatusField {238 field_id: String::new(),239 options: Vec::new(),240 })241 }242243 pub async fn add_issue_to_project(244 &self,245 project_id: &str,246 issue_node_id: &str,247 ) -> Result<String> {248 let query = r#"249 mutation($projectId: ID!, $contentId: ID!) {250 addProjectV2ItemById(input: {projectId: $projectId, contentId: $contentId}) {251 item {252 id253 }254 }255 }256 "#;257258 let resp = self259 .graphql_request(260 query,261 serde_json::json!({262 "projectId": project_id,263 "contentId": issue_node_id,264 }),265 )266 .await?;267268 let item_id = resp269 .get("addProjectV2ItemById")270 .and_then(|r| r.get("item"))271 .and_then(|i| i.get("id"))272 .and_then(|id| id.as_str())273 .ok_or_else(|| anyhow!("Failed to get item ID from response"))?274 .to_string();275276 Ok(item_id)277 }278279 pub async fn set_issue_status(280 &self,281 project_id: &str,282 item_id: &str,283 field_id: &str,284 option_id: &str,285 ) -> Result<()> {286 let query = r#"287 mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {288 updateProjectV2ItemFieldValue(289 input: {290 projectId: $projectId,291 itemId: $itemId,292 fieldId: $fieldId,293 value: { singleSelectOptionId: $optionId }294 }295 ) {296 projectV2Item {297 id298 }299 }300 }301 "#;302303 self.graphql_request(304 query,305 serde_json::json!({306 "projectId": project_id,307 "itemId": item_id,308 "fieldId": field_id,309 "optionId": option_id,310 }),311 )312 .await?;313314 Ok(())315 }316317 async fn graphql_request(318 &self,319 query: &str,320 variables: serde_json::Value,321 ) -> Result<serde_json::Value> {322 let body = serde_json::json!({323 "query": query,324 "variables": variables,325 });326327 let resp = self328 .client329 .post("https://api.github.com/graphql")330 .header("Authorization", self.auth_header())331 .header("Content-Type", "application/json")332 .json(&body)333 .send()334 .await335 .context("Failed to send GraphQL request")?;336337 let status = resp.status();338 if !status.is_success() {339 let text = resp.text().await.unwrap_or_default();340 return Err(anyhow!("GitHub GraphQL API error ({status}): {text}"));341 }342343 let full: serde_json::Value = resp344 .json()345 .await346 .context("Failed to parse GraphQL response")?;347348 if let Some(errors) = full.get("errors") {349 return Err(anyhow!("GitHub GraphQL errors: {errors}"));350 }351352 full.get("data")353 .cloned()354 .ok_or_else(|| anyhow!("No data in GraphQL response"))355 }356}357358#[derive(Deserialize)]359struct RepoResponse {360 name: String,361 full_name: String,362}363364#[derive(Deserialize)]365struct CreateIssueResponse {366 number: u64,367 html_url: String,368 node_id: String,369}370371#[cfg(test)]372mod tests {373 use super::*;374375 #[test]376 fn repo_response_deserialize() {377 let json = r#"{"name": "pike", "full_name": "anomalyco/pike", "private": false}"#;378 let repo: RepoResponse = serde_json::from_str(json).unwrap();379 assert_eq!(repo.name, "pike");380 assert_eq!(repo.full_name, "anomalyco/pike");381 }382383 #[test]384 fn create_issue_response_deserialize() {385 let json = r#"{386 "number": 42,387 "html_url": "https://github.com/anomalyco/pike/issues/42",388 "node_id": "I_kwDO123456",389 "title": "Bug"390 }"#;391 let issue: CreateIssueResponse = serde_json::from_str(json).unwrap();392 assert_eq!(issue.number, 42);393 assert_eq!(issue.html_url, "https://github.com/anomalyco/pike/issues/42");394 assert_eq!(issue.node_id, "I_kwDO123456");395 }396397 #[test]398 fn graphql_request_body_structure() {399 let query = "query { viewer { login } }";400 let variables = serde_json::json!({ "login": "test" });401 let body = serde_json::json!({402 "query": query,403 "variables": variables,404 });405406 assert_eq!(body["query"], query);407 assert_eq!(body["variables"]["login"], "test");408 }409410 #[test]411 fn parse_graphql_projects_response() {412 let data = serde_json::json!({413 "organization": {414 "projectsV2": {415 "nodes": [416 { "id": "PVT_1", "title": "Roadmap" },417 { "id": "PVT_2", "title": "Backlog" }418 ]419 }420 }421 });422423 let nodes = data["organization"]["projectsV2"]["nodes"].as_array().unwrap();424 assert_eq!(nodes.len(), 2);425 assert_eq!(nodes[0]["id"], "PVT_1");426 assert_eq!(nodes[1]["title"], "Backlog");427 }428429 #[test]430 fn parse_graphql_status_field_response() {431 let data = serde_json::json!({432 "node": {433 "fields": {434 "nodes": [435 {436 "id": "PVTFL_status",437 "name": "Status",438 "options": [439 { "id": "opt1", "name": "Todo" },440 { "id": "opt2", "name": "Done" }441 ]442 },443 {444 "id": "PVTFL_priority",445 "name": "Priority",446 "options": [447 { "id": "opt3", "name": "High" }448 ]449 }450 ]451 }452 }453 });454455 let fields = data["node"]["fields"]["nodes"].as_array().unwrap();456 let status_field = fields457 .iter()458 .find(|f| f["name"].as_str().unwrap_or("").eq_ignore_ascii_case("status"))459 .unwrap();460461 assert_eq!(status_field["id"], "PVTFL_status");462 let options = status_field["options"].as_array().unwrap();463 assert_eq!(options.len(), 2);464 assert_eq!(options[0]["name"], "Todo");465 }466467 #[test]468 fn created_issue_fields() {469 let issue = CreatedIssue {470 number: 7,471 html_url: "https://github.com/org/repo/issues/7".to_string(),472 node_id: "node_123".to_string(),473 };474 assert_eq!(issue.number, 7);475 assert_eq!(issue.html_url, "https://github.com/org/repo/issues/7");476 assert_eq!(issue.node_id, "node_123");477 }478}