1use super::token;
12use super::types::GitHubUser;
13use super::types::{
14 GitHubAnnotation, GitHubCheckRun, GitHubComment, GitHubIssue, GitHubPullRequest, GitHubReview,
15 GitHubReviewComment, RequiredStatusCheck,
16};
17use crate::backends::BlockedByFetch;
18use crate::backends::BlockedByIssue;
19use crate::config;
20use crate::engine::cooldown as engine_cooldown;
21use crate::engine::cooldown;
22use crate::github::types;
23use crate::security;
24use anyhow::Context;
25use reqwest::{Client, Response, StatusCode, header};
26use serde::Serialize;
27use serde::de::DeserializeOwned;
28use std::any;
29use std::cmp::Reverse;
30use std::collections::HashMap;
31use std::collections::HashSet;
32use std::fmt;
33use std::fmt::Debug;
34use std::fmt::Formatter;
35use std::fmt::Write as _;
36use std::path::Path;
37use std::sync::LazyLock;
38use std::sync::{
39 Arc, Mutex, OnceLock,
40 atomic::{AtomicU64, Ordering},
41};
42use std::time as std_time;
43use std::time::SystemTime;
44use std::time::{Duration, Instant};
45use tokio::runtime::Handle;
46use tokio::time;
47use urlencoding;
48
49#[cfg(not(test))]
50const GITHUB_API: &str = "https://api.github.com";
51#[cfg(test)]
53const GITHUB_API: &str = "http://127.0.0.1:9";
54
55#[derive(Debug, serde::Deserialize)]
56struct BlockedByPayload {
57 #[serde(default)]
58 id: i64,
59 number: i64,
60 #[serde(default)]
61 state: String,
62 #[serde(default)]
63 state_reason: Option<String>,
64 #[serde(default)]
65 repository: Option<BlockedByRepoPayload>,
66}
67
68#[derive(Debug, serde::Deserialize)]
69struct BlockedByRepoPayload {
70 full_name: String,
71}
72
73pub(crate) fn is_full_commit_sha(sha: &str) -> bool {
74 let len = sha.len();
75 (len == 40 || len == 64) && sha.bytes().all(|b| b.is_ascii_hexdigit())
76}
77
78fn repo_from_url(url: &str) -> Option<String> {
81 let rest = url.split_once("/repos/")?.1;
82 let mut parts = rest.split(['/', '?']);
83 let owner = parts.next().filter(|s| !s.is_empty())?;
84 let name = parts.next().filter(|s| !s.is_empty())?;
85 Some(format!("{owner}/{name}"))
86}
87
88pub(crate) fn redact_posted_body(body: &str) -> String {
89 if !security::has_leaks(body) {
90 return body.to_string();
91 }
92 let leaks = security::scan(body);
93 let rules: Vec<&str> = leaks.iter().map(|leak| leak.rule).collect();
94 let warning = format!(
95 "\n\n> ⚠️ **Security Notice**: {} potential secret(s) detected and redacted: {}",
96 leaks.len(),
97 rules.join(", ")
98 );
99 format!("{}{warning}", security::redact(body))
100}
101
102fn merge_pr_body(head_sha: &str) -> serde_json::Value {
103 serde_json::json!({
104 "merge_method": "squash",
105 "sha": head_sha,
106 })
107}
108
109fn parse_positive_issue_number(number: &str) -> anyhow::Result<i64> {
110 let parsed = number
111 .parse::<i64>()
112 .with_context(|| format!("invalid issue number: {number}"))?;
113 if parsed <= 0 {
114 anyhow::bail!("invalid issue number: {number}");
115 }
116 Ok(parsed)
117}
118
119struct RateLimit {
123 remaining: Option<u32>,
125 reset_at: Option<u64>,
127 backoff_until: Option<Instant>,
129 backoff_delay: Duration,
130 backoff_base: Duration,
131 backoff_max: Duration,
132 throttle_threshold: u32,
135}
136
137impl RateLimit {
138 fn new() -> Self {
139 let base = config::get("gh.backoff.base_seconds")
140 .ok()
141 .and_then(|v| v.parse::<u64>().ok())
142 .unwrap_or(30);
143 let max = config::get("gh.backoff.max_seconds")
144 .ok()
145 .and_then(|v| v.parse::<u64>().ok())
146 .unwrap_or(900);
147 let threshold = config::get("gh.rate_limit.throttle_threshold")
148 .ok()
149 .and_then(|v| v.parse::<u32>().ok())
150 .unwrap_or(200);
151
152 Self {
153 remaining: None,
154 reset_at: None,
155 backoff_until: None,
156 backoff_delay: Duration::ZERO,
157 backoff_base: Duration::from_secs(base),
158 backoff_max: Duration::from_secs(max),
159 throttle_threshold: threshold,
160 }
161 }
162
163 fn update_from_headers(&mut self, headers: &header::HeaderMap) {
165 if let Some(v) = headers.get("x-ratelimit-remaining") {
166 self.remaining = v.to_str().ok().and_then(|s| s.parse().ok());
167 }
168 if let Some(v) = headers.get("x-ratelimit-reset") {
169 self.reset_at = v.to_str().ok().and_then(|s| s.parse().ok());
170 }
171 }
172
173 fn record_success(&mut self) {
175 if self.backoff_delay > Duration::ZERO {
176 tracing::info!("GitHub backoff cleared after successful API call");
177 }
178 self.backoff_delay = Duration::ZERO;
179 self.backoff_until = None;
180 }
181
182 fn record_rate_limit(&mut self) {
184 METRIC_RATE_LIMIT_HITS.fetch_add(1, Ordering::Relaxed);
185
186 if let Some(reset_epoch) = self.reset_at {
188 match SystemTime::now().duration_since(std_time::UNIX_EPOCH) {
189 Ok(since_epoch) => {
190 let now_epoch = since_epoch.as_secs();
191 if reset_epoch > now_epoch {
192 let wait_secs = reset_epoch - now_epoch + 1;
193 self.backoff_delay = Duration::from_secs(wait_secs);
194 self.backoff_until = Some(Instant::now() + self.backoff_delay);
195 tracing::warn!(
196 wait_secs,
197 "GitHub rate limit hit, waiting until reset time"
198 );
199 return;
200 }
201 }
202 Err(e) => {
203 tracing::error!(
204 error = %e,
205 "System clock is before UNIX epoch; ignoring reset_at and falling back to exponential backoff"
206 );
207 }
208 }
209 }
210
211 self.backoff_delay = if self.backoff_delay.is_zero() {
213 self.backoff_base
214 } else {
215 (self.backoff_delay * 2).min(self.backoff_max)
216 };
217 self.backoff_until = Some(Instant::now() + self.backoff_delay);
218 tracing::warn!(
219 delay_secs = self.backoff_delay.as_secs(),
220 "GitHub rate limit hit, backing off (no reset header)"
221 );
222 }
223
224 fn backoff_remaining(&self) -> Option<Duration> {
226 if let Some(until) = self.backoff_until {
227 let now = Instant::now();
228 if now < until {
229 return Some(until - now);
230 }
231 }
232 None
233 }
234
235 fn proactive_wait_duration(&self) -> Option<Duration> {
242 if self.backoff_remaining().is_some() {
244 return None;
245 }
246 if let Some(remaining) = self.remaining
247 && remaining < self.throttle_threshold
248 && let Some(reset_epoch) = self.reset_at
249 {
250 let now_epoch = SystemTime::now()
251 .duration_since(std_time::UNIX_EPOCH)
252 .unwrap_or_default()
253 .as_secs();
254 if now_epoch < reset_epoch {
255 return Some(Duration::from_secs(reset_epoch - now_epoch + 1));
256 }
257 }
258 None
259 }
260
261 fn is_active(&self) -> Option<Duration> {
263 self.backoff_remaining()
264 .or_else(|| self.proactive_wait_duration())
265 }
266}
267
268static REST_RATE_LIMIT: LazyLock<Mutex<RateLimit>> = LazyLock::new(|| Mutex::new(RateLimit::new()));
271
272static GRAPHQL_RATE_LIMIT: LazyLock<Mutex<RateLimit>> =
274 LazyLock::new(|| Mutex::new(RateLimit::new()));
275
276static METRIC_RATE_LIMIT_HITS: AtomicU64 = AtomicU64::new(0);
280static METRIC_PROACTIVE_THROTTLES: AtomicU64 = AtomicU64::new(0);
282static METRIC_5XX_HITS: AtomicU64 = AtomicU64::new(0);
284
285fn check_rate_limit_backoff(cell: &Mutex<RateLimit>, api: &str) -> anyhow::Result<()> {
295 let Some(remaining) = cell.lock().ok().and_then(|rl| rl.is_active()) else {
296 return Ok(());
297 };
298 METRIC_PROACTIVE_THROTTLES.fetch_add(1, Ordering::Relaxed);
299 anyhow::bail!(
300 "GitHub {} API rate-limited, skipping call for {}s",
301 api,
302 remaining.as_secs()
303 );
304}
305
306static CALL_COUNTS: LazyLock<Mutex<HashMap<(String, String), u64>>> =
308 LazyLock::new(|| Mutex::new(HashMap::new()));
309
310fn count_api_call(url: &str) {
313 let path = url.split('?').next().unwrap_or(url);
314 let key = match path.split_once("/repos/") {
315 Some((_, rest)) => {
316 let mut parts = rest.split('/');
317 let project = format!(
318 "{}/{}",
319 parts.next().unwrap_or(""),
320 parts.next().unwrap_or("")
321 );
322 (project, parts.next().unwrap_or("repo").to_string())
323 }
324 None if path.ends_with("/graphql") => ("-".to_string(), "graphql".to_string()),
325 None => ("-".to_string(), "other".to_string()),
326 };
327 if let Ok(mut counts) = CALL_COUNTS.lock() {
328 *counts.entry(key).or_insert(0) += 1;
329 }
330}
331
332pub fn drain_call_counts() -> Vec<(String, String, u64)> {
334 let mut rows: Vec<_> = CALL_COUNTS
335 .lock()
336 .map(|mut c| c.drain().map(|((p, k), n)| (p, k, n)).collect())
337 .unwrap_or_default();
338 rows.sort_by_key(|r| Reverse(r.2));
339 rows
340}
341
342struct CachedPage {
346 etag: String,
347 body: String,
348 next: Option<String>,
350}
351
352static PAGE_CACHE: LazyLock<Mutex<HashMap<String, CachedPage>>> =
360 LazyLock::new(|| Mutex::new(HashMap::new()));
361
362const PAGE_CACHE_MAX: usize = 64;
365
366fn page_cache_key<T>(url: &str, query: Option<&[(&str, &str)]>) -> Option<String> {
370 let mut key = String::from(any::type_name::<T>());
371 key.push(' ');
372 key.push_str(url);
373 if let Some(q) = query {
374 for (i, (k, v)) in q.iter().enumerate() {
375 key.push(if i == 0 { '?' } else { '&' });
376 key.push_str(k);
377 key.push('=');
378 key.push_str(v);
379 }
380 }
381 if key.contains("since=") {
382 return None;
383 }
384 Some(key)
385}
386
387fn page_cache_etag(key: &str) -> Option<String> {
388 PAGE_CACHE.lock().ok()?.get(key).map(|c| c.etag.clone())
389}
390
391fn page_cache_hit(key: &str) -> Option<(String, Option<String>)> {
393 let cache = PAGE_CACHE.lock().ok()?;
394 let entry = cache.get(key)?;
395 Some((entry.body.clone(), entry.next.clone()))
396}
397
398fn page_cache_store(key: String, etag: String, body: String, next: Option<String>) {
399 let Ok(mut cache) = PAGE_CACHE.lock() else {
400 return;
401 };
402 if cache.len() >= PAGE_CACHE_MAX && !cache.contains_key(&key) {
405 cache.clear();
406 }
407 cache.insert(key, CachedPage { etag, body, next });
408}
409
410fn maybe_record_body_rate_limit(cell: &Mutex<RateLimit>, status: StatusCode, body: &str) {
413 if status == StatusCode::FORBIDDEN {
414 let lower = body.to_lowercase();
415 if (lower.contains("rate limit")
416 || lower.contains("abuse detection")
417 || lower.contains("secondary rate"))
418 && let Ok(mut rl) = cell.lock()
419 {
420 rl.record_rate_limit();
421 }
422 }
423}
424
425fn record_response_for_limiter(cell: &Mutex<RateLimit>, resp: &Response) {
427 if let Ok(mut rl) = cell.lock() {
428 rl.update_from_headers(resp.headers());
429 if resp.status() == StatusCode::TOO_MANY_REQUESTS {
432 rl.record_rate_limit();
433 } else if resp.status().is_success() || resp.status() == StatusCode::NOT_MODIFIED {
434 rl.record_success();
435 }
436 }
437 let status = resp.status();
439 if status.is_server_error() {
440 METRIC_5XX_HITS.fetch_add(1, Ordering::Relaxed);
441 if Handle::try_current().is_ok() {
442 tokio::spawn(async move {
443 cooldown::record_github_5xx().await;
444 });
445 }
446 }
447}
448
449#[derive(Clone)]
456pub struct GhHttp {
457 client: Client,
458 token_resolver: Arc<token::TokenResolver>,
459 app: Option<Arc<super::app::AppAuth>>,
461 owner_only: bool,
463 cached_username: OnceLock<String>,
464 #[cfg(test)]
465 api_base: Option<String>,
466}
467
468impl Debug for GhHttp {
469 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
470 f.debug_struct("GhHttp")
471 .field("owner_only", &self.owner_only)
472 .finish_non_exhaustive()
473 }
474}
475
476impl GhHttp {
477 pub fn new() -> anyhow::Result<Self> {
485 let client = Client::builder()
486 .user_agent("orch/0.1 (reqwest)")
487 .pool_max_idle_per_host(4)
488 .timeout(Duration::from_secs(30))
489 .build()
490 .map_err(|e| anyhow::anyhow!("failed to build HTTP client (TLS init): {e}"))?;
491
492 Ok(Self {
493 client,
494 token_resolver: token::shared(),
495 app: None,
496 owner_only: false,
497 cached_username: OnceLock::new(),
498 #[cfg(test)]
499 api_base: None,
500 })
501 }
502
503 pub fn owner() -> anyhow::Result<Self> {
506 let mut gh = Self::new()?;
507 gh.owner_only = true;
508 Ok(gh)
509 }
510
511 #[cfg(test)]
512 pub(crate) fn for_test(api_base: String, app: Option<Arc<super::app::AppAuth>>) -> Self {
513 Self {
514 client: Client::new(),
515 token_resolver: Arc::new(token::TokenResolver::default_env()),
516 app,
517 owner_only: false,
518 cached_username: OnceLock::new(),
519 api_base: Some(api_base),
520 }
521 }
522
523 #[cfg_attr(
524 not(test),
525 expect(
526 clippy::unused_self,
527 reason = "only the test build reads the api base override"
528 )
529 )]
530 fn api_root(&self) -> &str {
531 #[cfg(test)]
532 if let Some(base) = &self.api_base {
533 return base;
534 }
535 GITHUB_API
536 }
537
538 pub fn is_rate_limited() -> Option<Duration> {
543 REST_RATE_LIMIT.lock().ok().and_then(|rl| rl.is_active())
544 }
545
546 fn check_backoff(url: &str) -> anyhow::Result<()> {
548 count_api_call(url);
549 check_rate_limit_backoff(&REST_RATE_LIMIT, "REST")
550 }
551
552 fn check_graphql_backoff(url: &str) -> anyhow::Result<()> {
554 count_api_call(url);
555 check_rate_limit_backoff(&GRAPHQL_RATE_LIMIT, "GraphQL")
556 }
557
558 fn record_response(resp: &Response) {
559 record_response_for_limiter(&REST_RATE_LIMIT, resp);
560 }
561
562 fn record_graphql_response(resp: &Response) {
563 record_response_for_limiter(&GRAPHQL_RATE_LIMIT, resp);
564 }
565
566 fn maybe_record_rate_limit_from_body(status: StatusCode, body: &str) {
568 maybe_record_body_rate_limit(&REST_RATE_LIMIT, status, body);
569 }
570
571 fn maybe_record_graphql_rate_limit_from_body(status: StatusCode, body: &str) {
573 maybe_record_body_rate_limit(&GRAPHQL_RATE_LIMIT, status, body);
574 }
575
576 fn record_success() {
577 if let Ok(mut rl) = REST_RATE_LIMIT.lock() {
578 rl.record_success();
579 }
580 }
581
582 fn app(&self) -> Option<Arc<super::app::AppAuth>> {
585 if self.owner_only {
586 return None;
587 }
588
589 self.app.clone()
592 }
593
594 async fn auth_header(&self, url: &str) -> anyhow::Result<String> {
597 if let (Some(app), Some(repo)) = (self.app(), repo_from_url(url)) {
598 match app.token_for_repo(&repo).await {
599 Ok(Some(token)) => return Ok(format!("Bearer {token}")),
600 Ok(None) => {}
601 Err(e) => {
602 tracing::warn!(error = %e, repo, "GitHub App token unavailable, using the owner token");
603 }
604 }
605 }
606 match self.token_resolver.get_token().await? {
607 Some(token) if !token.is_empty() => Ok(format!("Bearer {token}")),
608 _ => anyhow::bail!("No GitHub token available — run `gh auth login` or set GH_TOKEN"),
609 }
610 }
611
612 async fn send_with_retries<F>(
615 &self,
616 mut make_req: F,
617 is_graphql: bool,
618 ) -> anyhow::Result<Response>
619 where
620 F: FnMut() -> anyhow::Result<reqwest::RequestBuilder>,
621 {
622 if engine_cooldown::is_agent_in_cooldown("github:5xx") {
624 if let Some(until) = engine_cooldown::cooldown_until("github:5xx") {
625 let now = chrono::Utc::now().timestamp();
626 let remaining = if until > now { until - now } else { 0 };
627 anyhow::bail!("GitHub API transient 5xx circuit-breaker active for {remaining}s");
628 }
629 anyhow::bail!("GitHub API transient 5xx circuit-breaker active");
630 }
631
632 let attempts = config::get("gh.5xx.retry_attempts")
634 .ok()
635 .and_then(|v| v.parse::<u32>().ok())
636 .unwrap_or(3);
637 let base_secs = config::get("gh.5xx.base_backoff_seconds")
638 .ok()
639 .and_then(|v| v.parse::<u64>().ok())
640 .unwrap_or(1);
641 let max_secs = config::get("gh.5xx.max_backoff_seconds")
642 .ok()
643 .and_then(|v| v.parse::<u64>().ok())
644 .unwrap_or(30);
645 let circuit_cooldown_secs = config::get("gh.5xx.circuit_breaker_cooldown_seconds")
646 .ok()
647 .and_then(|v| v.parse::<u64>().ok())
648 .unwrap_or(300);
649
650 let mut last_err: Option<anyhow::Error> = None;
651 let mut auth_override: Option<String> = None;
654 let mut auth_retried = false;
655 for attempt in 0..attempts {
656 let mut req = make_req()?;
657 if let Some(auth) = &auth_override {
658 req = req.header(header::AUTHORIZATION, auth.clone());
659 }
660 let resp_result = req.send().await;
661
662 match resp_result {
663 Ok(resp) => {
664 if is_graphql {
666 Self::record_graphql_response(&resp);
667 } else {
668 Self::record_response(&resp);
669 }
670
671 if resp.status() == StatusCode::UNAUTHORIZED {
672 let resp_url = resp.url().to_string();
673 let status = resp.status();
674 let body = resp.text().await.unwrap_or_default();
675 if body.contains("Bad credentials") && !auth_retried {
676 tracing::warn!(
677 "GitHub API 401 Bad credentials — clearing cached token and re-resolving"
678 );
679 self.token_resolver.clear_cache().await;
680 if let Some(app) = self.app() {
681 app.invalidate();
682 }
683 match self.auth_header(&resp_url).await {
684 Ok(new_auth) => {
685 auth_retried = true;
686 auth_override = Some(new_auth);
687 }
688 Err(e) => {
689 last_err = Some(
690 e.context("GitHub token re-resolution failed after 401"),
691 );
692 break;
693 }
694 }
695 continue;
697 }
698 if auth_retried {
699 self.token_resolver.clear_cache().await;
702 anyhow::bail!(
703 "GitHub authentication failed ({status}): token re-resolved after cache clear but still rejected"
704 );
705 }
706 anyhow::bail!("GitHub API request failed ({status}): {body}");
707 }
708
709 if resp.status().is_server_error() {
711 let status = resp.status();
712 let headers = resp.headers().clone();
713 let body = resp.text().await.unwrap_or_default();
714 let req_id = headers
715 .get("x-github-request-id")
716 .and_then(|v| v.to_str().ok())
717 .unwrap_or("<none>");
718 let snippet: String = body.chars().take(400).collect();
719 tracing::warn!(
720 status = %status,
721 request_id = %req_id,
722 attempt,
723 "GitHub server error (5xx) — attempt {attempt}: {snippet}"
724 );
725
726 last_err = Some(anyhow::anyhow!(
727 "GitHub API server error ({status}) request_id={req_id}: {snippet}"
728 ));
729
730 if attempt + 1 < attempts {
731 let exp = 1u64.checked_shl(attempt.min(63)).unwrap_or(u64::MAX);
734 let mut backoff = base_secs.saturating_mul(exp);
735 if backoff > max_secs {
736 backoff = max_secs;
737 }
738 let jitter_ms = u64::from(attempt) * 100;
740 let sleep_dur = Duration::from_secs(backoff)
741 + Duration::from_millis(jitter_ms.min(1000));
742 time::sleep(sleep_dur).await;
743 continue;
744 }
745 tracing::warn!(
747 "GitHub API 5xx persisted after {} attempts — setting circuit-breaker for {}s",
748 attempts,
749 circuit_cooldown_secs
750 );
751 engine_cooldown::set_agent_cooldown("github:5xx", circuit_cooldown_secs)
752 .await;
753 break;
754 }
755
756 return Ok(resp);
758 }
759 Err(e) => {
760 tracing::warn!(err = %e, attempt, "HTTP request failed to send (transport error, GitHub not reached), will retry if attempts remain");
767 last_err = Some(anyhow::anyhow!(
768 "HTTP request failed to send (transport error): {e}"
769 ));
770 if attempt + 1 < attempts {
771 let exp = 1u64.checked_shl(attempt.min(63)).unwrap_or(u64::MAX);
773 let backoff = base_secs.saturating_mul(exp);
774 let sleep_dur = Duration::from_secs(backoff)
775 + Duration::from_millis((u64::from(attempt) * 100).min(1000));
776 time::sleep(sleep_dur).await;
777 continue;
778 }
779 tracing::warn!(
783 "HTTP request failed to send after {} attempts (transport error, GitHub not reached) — not tripping the github:5xx circuit-breaker",
784 attempts
785 );
786 break;
787 }
788 }
789 }
790
791 Err(last_err.unwrap_or_else(|| anyhow::anyhow!("unexpected send_with_retries failure")))
792 }
793
794 async fn get_json<T: DeserializeOwned>(&self, url: &str) -> anyhow::Result<T> {
796 Self::check_backoff(url)?;
797 let auth = self.auth_header(url).await?;
798 let make_req = || {
800 Ok(self
801 .client
802 .get(url)
803 .header(header::AUTHORIZATION, auth.clone())
804 .header(header::ACCEPT, "application/vnd.github+json")
805 .header("X-GitHub-Api-Version", "2022-11-28"))
806 };
807 let resp = self.send_with_retries(make_req, false).await?;
808 let status = resp.status();
809 if !status.is_success() {
810 let body = resp.text().await.unwrap_or_default();
811 Self::maybe_record_rate_limit_from_body(status, &body);
812 anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
813 }
814 let body = resp.text().await?;
815 serde_json::from_str(&body)
816 .with_context(|| format!("failed to parse GitHub API response from GET {url}: {body}"))
817 }
818
819 async fn get_bytes(&self, url: &str) -> anyhow::Result<Vec<u8>> {
821 Self::check_backoff(url)?;
822 let auth = self.auth_header(url).await?;
823 let make_req = || {
824 Ok(self
825 .client
826 .get(url)
827 .header(header::AUTHORIZATION, auth.clone())
828 .header(header::ACCEPT, "application/vnd.github+json")
829 .header("X-GitHub-Api-Version", "2022-11-28"))
830 };
831 let resp = self.send_with_retries(make_req, false).await?;
832 let status = resp.status();
833 if !status.is_success() {
834 let body = resp.text().await.unwrap_or_default();
835 Self::maybe_record_rate_limit_from_body(status, &body);
836 anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
837 }
838 Ok(resp.bytes().await?.to_vec())
839 }
840
841 async fn get_with_query<T: DeserializeOwned>(
843 &self,
844 url: &str,
845 query: &[(&str, &str)],
846 ) -> anyhow::Result<T> {
847 Self::check_backoff(url)?;
848 let auth = self.auth_header(url).await?;
849 let make_req = || {
850 Ok(self
851 .client
852 .get(url)
853 .query(query)
854 .header(header::AUTHORIZATION, auth.clone())
855 .header(header::ACCEPT, "application/vnd.github+json")
856 .header("X-GitHub-Api-Version", "2022-11-28"))
857 };
858 let resp = self.send_with_retries(make_req, false).await?;
859 let status = resp.status();
860 if !status.is_success() {
861 let body = resp.text().await.unwrap_or_default();
862 Self::maybe_record_rate_limit_from_body(status, &body);
863 anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
864 }
865 let body = resp.text().await?;
866 serde_json::from_str(&body)
867 .with_context(|| format!("failed to parse GitHub API response from GET {url}: {body}"))
868 }
869
870 async fn post_json_raw(&self, url: &str, body: &serde_json::Value) -> anyhow::Result<String> {
872 Self::check_backoff(url)?;
873 let auth = self.auth_header(url).await?;
874 let make_req = || {
875 Ok(self
876 .client
877 .post(url)
878 .json(body)
879 .header(header::AUTHORIZATION, auth.clone())
880 .header(header::ACCEPT, "application/vnd.github+json")
881 .header("X-GitHub-Api-Version", "2022-11-28"))
882 };
883 let resp = self.send_with_retries(make_req, false).await?;
884 let status = resp.status();
885 let text_res = resp.text().await;
886 if !status.is_success() {
887 let text = text_res.unwrap_or_default();
888 Self::maybe_record_rate_limit_from_body(status, &text);
889 anyhow::bail!("GitHub API POST {url} failed ({status}): {text}");
890 }
891 let text = text_res?;
892 Ok(text)
893 }
894
895 async fn post_json<T: DeserializeOwned>(
897 &self,
898 url: &str,
899 body: &serde_json::Value,
900 ) -> anyhow::Result<T> {
901 let text = self.post_json_raw(url, body).await?;
902 Ok(serde_json::from_str(&text)?)
903 }
904
905 async fn patch_json_raw(&self, url: &str, body: &serde_json::Value) -> anyhow::Result<String> {
907 Self::check_backoff(url)?;
908 let auth = self.auth_header(url).await?;
909 let make_req = || {
910 Ok(self
911 .client
912 .patch(url)
913 .json(body)
914 .header(header::AUTHORIZATION, auth.clone())
915 .header(header::ACCEPT, "application/vnd.github+json")
916 .header("X-GitHub-Api-Version", "2022-11-28"))
917 };
918 let resp = self.send_with_retries(make_req, false).await?;
919 let status = resp.status();
920 let text_res = resp.text().await;
921 if !status.is_success() {
922 let text = text_res.unwrap_or_default();
923 Self::maybe_record_rate_limit_from_body(status, &text);
924 anyhow::bail!("GitHub API PATCH {url} failed ({status}): {text}");
925 }
926 let text = text_res?;
927 Ok(text)
928 }
929
930 async fn delete(&self, url: &str) -> anyhow::Result<StatusCode> {
932 Self::check_backoff(url)?;
933 let auth = self.auth_header(url).await?;
934 let make_req = || {
935 Ok(self
936 .client
937 .delete(url)
938 .header(header::AUTHORIZATION, auth.clone())
939 .header(header::ACCEPT, "application/vnd.github+json")
940 .header("X-GitHub-Api-Version", "2022-11-28"))
941 };
942 let resp = self.send_with_retries(make_req, false).await?;
943 let status = resp.status();
944 if !status.is_success() && status != StatusCode::NOT_FOUND {
945 let body = resp.text().await.unwrap_or_default();
946 Self::maybe_record_rate_limit_from_body(status, &body);
947 anyhow::bail!("GitHub API DELETE {url} failed ({status}): {body}");
948 }
949 Ok(status)
950 }
951
952 async fn get_all_pages<T: DeserializeOwned>(
957 &self,
958 url: &str,
959 query: &[(&str, &str)],
960 ) -> anyhow::Result<Vec<T>> {
961 const MAX_JSON_DECODE_RETRIES: u32 = 2;
962 const JSON_DECODE_RETRY_BACKOFF_MS: u64 = 200;
963 Self::check_backoff(url)?;
964 let mut all: Vec<T> = Vec::new();
965 let mut next_url: Option<String> = None;
966 let mut is_first = true;
967
968 loop {
969 let (request_url, request_query) = if is_first {
970 is_first = false;
971 (url, Some(query))
972 } else {
973 let Some(u) = next_url.as_ref() else { break };
974 (u.as_str(), None)
975 };
976
977 let cache_key = page_cache_key::<T>(request_url, request_query);
978 let mut cached_etag = cache_key.as_deref().and_then(page_cache_etag);
979 let mut decode_attempt = 0;
980 let (page, next) = loop {
981 let auth = self.auth_header(request_url).await?;
982 let mut req = self
983 .client
984 .get(request_url)
985 .header(header::AUTHORIZATION, auth)
986 .header(header::ACCEPT, "application/vnd.github+json")
987 .header("X-GitHub-Api-Version", "2022-11-28");
988 if let Some(q) = request_query {
989 req = req.query(q);
990 }
991 if let Some(etag) = &cached_etag {
992 req = req.header(header::IF_NONE_MATCH, etag.clone());
993 }
994
995 let make_req = || {
996 req.try_clone()
997 .ok_or_else(|| anyhow::anyhow!("request clone failed"))
998 };
999 let resp = self.send_with_retries(make_req, false).await?;
1000 let status = resp.status();
1001 let next_from_headers = parse_link_next(resp.headers());
1002 let etag = resp
1003 .headers()
1004 .get(header::ETAG)
1005 .and_then(|v| v.to_str().ok())
1006 .map(ToString::to_string);
1007 let content_type = resp
1008 .headers()
1009 .get(header::CONTENT_TYPE)
1010 .and_then(|v| v.to_str().ok())
1011 .map_or_else(|| "<missing>".to_string(), ToString::to_string);
1012
1013 if status == StatusCode::NOT_MODIFIED {
1014 if let Some((body, next)) = cache_key.as_deref().and_then(page_cache_hit) {
1015 break (serde_json::from_str::<Vec<T>>(&body)?, next);
1016 }
1017 cached_etag = None;
1022 continue;
1023 }
1024
1025 if !status.is_success() {
1026 let body = resp.text().await.unwrap_or_default();
1027 Self::maybe_record_rate_limit_from_body(status, &body);
1028 anyhow::bail!("GitHub API GET (paginated) failed ({status}): {body}");
1029 }
1030
1031 let text = resp.text().await?;
1032 match serde_json::from_str::<Vec<T>>(&text) {
1033 Ok(page) => {
1034 if let (Some(key), Some(etag)) = (cache_key.clone(), etag) {
1035 page_cache_store(key, etag, text, next_from_headers.clone());
1036 }
1037 break (page, next_from_headers);
1038 }
1039 Err(err) => {
1040 let snippet: String = text.chars().take(200).collect();
1041 let decode_error = anyhow::anyhow!(
1042 "GitHub API GET (paginated) JSON decode failed ({status}, content-type={content_type}): {snippet}"
1043 )
1044 .context(err);
1045 if decode_attempt < MAX_JSON_DECODE_RETRIES {
1046 decode_attempt += 1;
1047 tracing::warn!(
1048 attempt = decode_attempt,
1049 max_attempts = MAX_JSON_DECODE_RETRIES,
1050 status = %status,
1051 content_type,
1052 err = %decode_error,
1053 "json decode failed; retrying paginated GET"
1054 );
1055 time::sleep(Duration::from_millis(
1056 JSON_DECODE_RETRY_BACKOFF_MS * u64::from(decode_attempt),
1057 ))
1058 .await;
1059 continue;
1060 }
1061 return Err(decode_error);
1062 }
1063 }
1064 };
1065
1066 next_url = next;
1067 all.extend(page);
1068
1069 if next_url.is_none() {
1070 break;
1071 }
1072 }
1073
1074 Ok(all)
1075 }
1076
1077 async fn get_all_pages_from_wrapper<T: DeserializeOwned>(
1088 &self,
1089 url: &str,
1090 array_field: &str,
1091 ) -> anyhow::Result<Vec<T>> {
1092 Self::check_backoff(url)?;
1093 let mut all: Vec<T> = Vec::new();
1094 let mut current_url: String = url.to_string();
1095
1096 loop {
1097 let auth = self.auth_header(¤t_url).await?;
1098 let make_req = || {
1099 self.client
1100 .get(¤t_url)
1101 .header(header::AUTHORIZATION, auth.clone())
1102 .header(header::ACCEPT, "application/vnd.github+json")
1103 .header("X-GitHub-Api-Version", "2022-11-28")
1104 .try_clone()
1105 .ok_or_else(|| anyhow::anyhow!("request clone failed"))
1106 };
1107 let resp = self.send_with_retries(make_req, false).await?;
1108 let status = resp.status();
1109 let next = parse_link_next(resp.headers());
1110
1111 if !status.is_success() {
1112 let body = resp.text().await.unwrap_or_default();
1113 Self::maybe_record_rate_limit_from_body(status, &body);
1114 anyhow::bail!(
1115 "GitHub API GET (wrapped paginated) {current_url} failed ({status}): {body}"
1116 );
1117 }
1118
1119 let body = resp.text().await?;
1120 let wrapper: serde_json::Value = serde_json::from_str(&body).with_context(|| {
1121 format!("failed to parse wrapper response from {current_url}: {body}")
1122 })?;
1123 let items = wrapper
1124 .get(array_field)
1125 .and_then(|v| v.as_array())
1126 .cloned()
1127 .unwrap_or_default();
1128
1129 for item in items {
1130 match serde_json::from_value::<T>(item) {
1131 Ok(v) => all.push(v),
1132 Err(e) => {
1133 tracing::warn!(
1134 field = array_field,
1135 err = %e,
1136 "skipping item that failed to deserialize in wrapped pagination"
1137 );
1138 }
1139 }
1140 }
1141
1142 match next {
1143 Some(next_url) => current_url = next_url,
1144 None => break,
1145 }
1146 }
1147
1148 Ok(all)
1149 }
1150
1151 async fn graphql_request(
1153 &self,
1154 query: &str,
1155 extra_headers: &[(&str, &str)],
1156 variables: Option<serde_json::Value>,
1157 ) -> anyhow::Result<serde_json::Value> {
1158 self.graphql_request_to_url(
1159 &format!("{GITHUB_API}/graphql"),
1160 query,
1161 extra_headers,
1162 variables,
1163 )
1164 .await
1165 }
1166
1167 async fn graphql_request_to_url(
1168 &self,
1169 url: &str,
1170 query: &str,
1171 extra_headers: &[(&str, &str)],
1172 variables: Option<serde_json::Value>,
1173 ) -> anyhow::Result<serde_json::Value> {
1174 Self::check_graphql_backoff(url)?;
1175 let body = if let Some(vars) = variables {
1176 serde_json::json!({ "query": query, "variables": vars })
1177 } else {
1178 serde_json::json!({ "query": query })
1179 };
1180 let auth = self.auth_header(url).await?;
1181 let mut req = self
1182 .client
1183 .post(url)
1184 .json(&body)
1185 .header(header::AUTHORIZATION, auth)
1186 .header(header::ACCEPT, "application/vnd.github+json")
1187 .header("X-GitHub-Api-Version", "2022-11-28");
1188
1189 for (k, v) in extra_headers {
1190 req = req.header(*k, *v);
1191 }
1192
1193 let make_req = || {
1195 req.try_clone()
1196 .ok_or_else(|| anyhow::anyhow!("graphql request clone failed"))
1197 };
1198 let resp = self.send_with_retries(make_req, true).await?;
1199 let status = resp.status();
1200 let text_res = resp.text().await;
1201 if !status.is_success() {
1202 let text = text_res.unwrap_or_default();
1203 Self::maybe_record_graphql_rate_limit_from_body(status, &text);
1204 anyhow::bail!("GitHub GraphQL failed ({status}): {text}");
1205 }
1206 let text = text_res?;
1207 let json: serde_json::Value = serde_json::from_str(&text)?;
1208 if let Some(errors) = json.get("errors").and_then(|e| e.as_array())
1210 && !errors.is_empty()
1211 {
1212 let messages: Vec<&str> = errors
1213 .iter()
1214 .filter_map(|e| e.get("message").and_then(|m| m.as_str()))
1215 .collect();
1216 if json.get("data").is_none() || json["data"].is_null() {
1217 anyhow::bail!("GitHub GraphQL errors: {}", messages.join("; "));
1219 }
1220 tracing::warn!(errors = ?messages, "GitHub GraphQL returned partial errors");
1222 }
1223 Ok(json)
1224 }
1225
1226 pub async fn graphql_with_vars(
1229 &self,
1230 query: &str,
1231 variables: serde_json::Value,
1232 ) -> anyhow::Result<serde_json::Value> {
1233 self.graphql_request(query, &[], Some(variables)).await
1234 }
1235
1236 pub async fn graphql_with_headers(
1237 &self,
1238 query: &str,
1239 headers: &[&str],
1240 ) -> anyhow::Result<serde_json::Value> {
1241 let pairs: Vec<(&str, &str)> = headers.iter().filter_map(|h| h.split_once(':')).collect();
1243 self.graphql_request(query, &pairs, None).await
1244 }
1245
1246 pub async fn graphql_with_headers_and_vars(
1247 &self,
1248 query: &str,
1249 headers: &[&str],
1250 variables: serde_json::Value,
1251 ) -> anyhow::Result<serde_json::Value> {
1252 let pairs: Vec<(&str, &str)> = headers.iter().filter_map(|h| h.split_once(':')).collect();
1253 self.graphql_request(query, &pairs, Some(variables)).await
1254 }
1255
1256 pub async fn auth_status(&self) -> anyhow::Result<()> {
1261 match self
1262 .get_json::<serde_json::Value>(&format!("{GITHUB_API}/user"))
1263 .await
1264 {
1265 Ok(_) => Ok(()),
1266 Err(e) => {
1267 let err_str = e.to_string();
1268
1269 if err_str.contains("401") || err_str.contains("Bad credentials") {
1271 anyhow::bail!(
1272 "GitHub authentication failed: Invalid or expired token. \
1273 Check your GH_TOKEN/GITHUB_TOKEN environment variables, \
1274 or gh.auth configuration in ~/.orch/config.yml. \
1275 Run `orch auth check` to verify your setup."
1276 );
1277 }
1278
1279 if err_str.contains("403") && err_str.contains("rate limit") {
1280 anyhow::bail!(
1281 "GitHub API rate limited. Wait before retrying, \
1282 or check your token's rate limit quota."
1283 );
1284 }
1285
1286 Err(e)
1287 }
1288 }
1289 }
1290
1291 pub async fn create_issue(
1293 &self,
1294 repo: &str,
1295 title: &str,
1296 body: &str,
1297 labels: &[String],
1298 ) -> anyhow::Result<GitHubIssue> {
1299 let url = format!("{GITHUB_API}/repos/{repo}/issues");
1300 let payload = serde_json::json!({
1301 "title": title,
1302 "body": body,
1303 "labels": labels,
1304 });
1305 self.post_json(&url, &payload).await
1306 }
1307
1308 pub async fn update_issue(
1312 &self,
1313 repo: &str,
1314 number: u64,
1315 title: &str,
1316 body: &str,
1317 labels: &[String],
1318 ) -> anyhow::Result<GitHubIssue> {
1319 let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}");
1320 let payload = serde_json::json!({
1321 "title": title,
1322 "body": body,
1323 "labels": labels,
1324 });
1325 let text = self.patch_json_raw(&url, &payload).await?;
1326 serde_json::from_str(&text)
1327 .with_context(|| format!("failed to parse issue update response: {text}"))
1328 }
1329
1330 pub async fn list_blocked_by(
1338 &self,
1339 repo: &str,
1340 issue_number: u64,
1341 ) -> anyhow::Result<BlockedByFetch> {
1342 let mut next = Some(format!(
1343 "{GITHUB_API}/repos/{repo}/issues/{issue_number}/dependencies/blocked_by?per_page=100"
1344 ));
1345 let mut found = Vec::new();
1346 while let Some(url) = next.take() {
1347 let resp = match self
1348 .dependency_request(&url, reqwest::Method::GET, None)
1349 .await
1350 {
1351 Ok(resp) => resp,
1352 Err(err) => {
1353 let message = err.to_string();
1354 if message.contains("(transport error)") {
1356 return Ok(BlockedByFetch::Unreachable(message));
1357 }
1358 return Ok(BlockedByFetch::Failed(message));
1359 }
1360 };
1361 let status = resp.status();
1362 if status == StatusCode::NOT_FOUND || status == StatusCode::FORBIDDEN {
1363 let body = resp.text().await.unwrap_or_default();
1364 if status == StatusCode::FORBIDDEN
1365 && body.to_ascii_lowercase().contains("rate limit")
1366 {
1367 Self::maybe_record_rate_limit_from_body(status, &body);
1368 return Ok(BlockedByFetch::Failed(body));
1369 }
1370 return Ok(BlockedByFetch::Unavailable);
1371 }
1372 if !status.is_success() {
1373 let body = resp.text().await.unwrap_or_default();
1374 Self::maybe_record_rate_limit_from_body(status, &body);
1375 return Ok(BlockedByFetch::Failed(format!("{status}: {body}")));
1376 }
1377 Self::record_success();
1378 let page_next = parse_link_next(resp.headers());
1379 let body = resp.text().await.unwrap_or_default();
1380 let page: Vec<BlockedByPayload> = match serde_json::from_str(&body) {
1381 Ok(page) => page,
1382 Err(err) => {
1383 return Ok(BlockedByFetch::Failed(format!(
1384 "blocked_by parse failed: {err}"
1385 )));
1386 }
1387 };
1388 for item in page {
1389 if item.number <= 0 {
1390 continue;
1391 }
1392 let item_repo = item
1393 .repository
1394 .as_ref()
1395 .map(|r| r.full_name.clone())
1396 .filter(|name| !name.is_empty())
1397 .unwrap_or_else(|| repo.to_string());
1398 found.push(BlockedByIssue {
1399 github_id: item.id,
1400 repo: item_repo,
1401 number: item.number,
1402 state: item.state,
1403 state_reason: item.state_reason,
1404 });
1405 }
1406 next = page_next;
1407 }
1408 Ok(BlockedByFetch::Native(found))
1409 }
1410
1411 pub async fn add_blocked_by(
1415 &self,
1416 repo: &str,
1417 issue_number: u64,
1418 blocking_issue_id: i64,
1419 ) -> anyhow::Result<()> {
1420 let url =
1421 format!("{GITHUB_API}/repos/{repo}/issues/{issue_number}/dependencies/blocked_by");
1422 let resp = self
1423 .dependency_request(
1424 &url,
1425 reqwest::Method::POST,
1426 Some(serde_json::json!({ "issue_id": blocking_issue_id })),
1427 )
1428 .await?;
1429 let status = resp.status();
1430 if status.is_success() {
1431 Self::record_success();
1432 return Ok(());
1433 }
1434 let body = resp.text().await.unwrap_or_default();
1435 if body.to_ascii_lowercase().contains("already") {
1436 return Ok(());
1437 }
1438 Self::maybe_record_rate_limit_from_body(status, &body);
1439 anyhow::bail!("add blocked_by failed ({status}): {body}")
1440 }
1441
1442 pub async fn remove_blocked_by(
1444 &self,
1445 repo: &str,
1446 number: u64,
1447 blocking_issue_id: u64,
1448 ) -> anyhow::Result<()> {
1449 let url = format!(
1450 "{GITHUB_API}/repos/{repo}/issues/{number}/dependencies/blocked_by/{blocking_issue_id}"
1451 );
1452 self.delete(&url).await?;
1453 Ok(())
1454 }
1455
1456 async fn dependency_request(
1458 &self,
1459 url: &str,
1460 method: reqwest::Method,
1461 body: Option<serde_json::Value>,
1462 ) -> anyhow::Result<Response> {
1463 Self::check_backoff(url)?;
1464 let auth = self.auth_header(url).await?;
1465 let make_req = || {
1466 let mut req = self
1467 .client
1468 .request(method.clone(), url)
1469 .header(header::AUTHORIZATION, auth.clone())
1470 .header(header::ACCEPT, "application/vnd.github+json")
1471 .header("X-GitHub-Api-Version", "2026-03-10");
1472 if let Some(ref payload) = body {
1473 req = req.json(payload);
1474 }
1475 Ok(req)
1476 };
1477 self.send_with_retries(make_req, false).await
1478 }
1479
1480 pub async fn get_issue(&self, repo: &str, number: &str) -> anyhow::Result<GitHubIssue> {
1482 self.get_json(&format!("{}/repos/{repo}/issues/{number}", self.api_root()))
1483 .await
1484 }
1485
1486 pub async fn is_pull_request(&self, repo: &str, number: &str) -> bool {
1488 self.get_issue(repo, number)
1489 .await
1490 .is_ok_and(|i| i.pull_request.is_some())
1491 }
1492
1493 pub async fn list_issues(&self, repo: &str, label: &str) -> anyhow::Result<Vec<GitHubIssue>> {
1495 self.list_issues_with_state(repo, label, "open").await
1496 }
1497
1498 pub async fn list_issues_with_state(
1502 &self,
1503 repo: &str,
1504 label: &str,
1505 state: &str,
1506 ) -> anyhow::Result<Vec<GitHubIssue>> {
1507 let url = format!("{GITHUB_API}/repos/{repo}/issues");
1508 let mut query = vec![("state", state), ("per_page", "100")];
1510 if !label.is_empty() {
1511 query.push(("labels", label));
1512 }
1513 let all: Vec<GitHubIssue> = self.get_all_pages(&url, &query).await?;
1514 Ok(all
1516 .into_iter()
1517 .filter(|i| i.pull_request.is_none())
1518 .collect())
1519 }
1520
1521 pub async fn list_issues_closed_since(
1525 &self,
1526 repo: &str,
1527 label: &str,
1528 since: &str,
1529 ) -> anyhow::Result<Vec<GitHubIssue>> {
1530 let url = format!("{GITHUB_API}/repos/{repo}/issues");
1531 let all: Vec<GitHubIssue> = self
1532 .get_all_pages(
1533 &url,
1534 &[
1535 ("labels", label),
1536 ("state", "closed"),
1537 ("since", since),
1538 ("per_page", "100"),
1539 ],
1540 )
1541 .await?;
1542 Ok(all
1543 .into_iter()
1544 .filter(|i| i.pull_request.is_none())
1545 .collect())
1546 }
1547
1548 pub async fn list_closed_issues_since(
1550 &self,
1551 repo: &str,
1552 since: &str,
1553 ) -> anyhow::Result<Vec<GitHubIssue>> {
1554 let url = format!("{GITHUB_API}/repos/{repo}/issues");
1555 let all: Vec<GitHubIssue> = self
1556 .get_all_pages(
1557 &url,
1558 &[("state", "closed"), ("since", since), ("per_page", "100")],
1559 )
1560 .await?;
1561 Ok(all
1562 .into_iter()
1563 .filter(|i| i.pull_request.is_none())
1564 .collect())
1565 }
1566
1567 pub async fn list_all_open_issues(&self, repo: &str) -> anyhow::Result<Vec<GitHubIssue>> {
1572 let url = format!("{GITHUB_API}/repos/{repo}/issues");
1573 let params = [("state", "open"), ("per_page", "100")];
1574 let all: Vec<GitHubIssue> = self.get_all_pages(&url, ¶ms).await?;
1575 Ok(all
1577 .into_iter()
1578 .filter(|i| i.pull_request.is_none())
1579 .collect())
1580 }
1581
1582 pub async fn list_open_pulls(&self, repo: &str) -> anyhow::Result<Vec<serde_json::Value>> {
1585 let url = format!("{GITHUB_API}/repos/{repo}/pulls");
1586 let all: Vec<serde_json::Value> = self
1587 .get_all_pages(&url, &[("state", "open"), ("per_page", "100")])
1588 .await?;
1589 Ok(all)
1590 }
1591
1592 pub async fn list_all_issues(&self, repo: &str) -> anyhow::Result<Vec<GitHubIssue>> {
1596 let url = format!("{GITHUB_API}/repos/{repo}/issues");
1597 let all: Vec<GitHubIssue> = self
1598 .get_all_pages(&url, &[("state", "all"), ("per_page", "100")])
1599 .await?;
1600 Ok(all
1602 .into_iter()
1603 .filter(|i| i.pull_request.is_none())
1604 .collect())
1605 }
1606
1607 pub async fn add_labels(
1609 &self,
1610 repo: &str,
1611 number: &str,
1612 labels: &[String],
1613 ) -> anyhow::Result<()> {
1614 let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}/labels");
1615 let payload = serde_json::json!({ "labels": labels });
1616 self.post_json_raw(&url, &payload).await?;
1617 Ok(())
1618 }
1619
1620 pub async fn ensure_label(
1622 &self,
1623 repo: &str,
1624 name: &str,
1625 color: &str,
1626 description: &str,
1627 ) -> anyhow::Result<()> {
1628 let encoded = urlencoding::encode(name);
1629 let get_url = format!("{GITHUB_API}/repos/{repo}/labels/{encoded}");
1630
1631 match self.get_bytes(&get_url).await {
1633 Ok(_) => return Ok(()),
1634 Err(e) if e.to_string().contains("404") => {
1635 tracing::debug!(repo, name, "ensure_label: label not found, creating");
1636 }
1637 Err(e) => {
1638 tracing::warn!(repo, name, err = %e, "ensure_label: GET failed, attempting create");
1639 }
1640 }
1641
1642 let create_url = format!("{GITHUB_API}/repos/{repo}/labels");
1644 let payload = serde_json::json!({
1645 "name": name,
1646 "color": color,
1647 "description": description,
1648 });
1649
1650 match self.post_json_raw(&create_url, &payload).await {
1651 Ok(_) => {
1652 Self::record_success();
1653 }
1654 Err(e) => {
1655 let msg = e.to_string();
1656 if msg.contains("422")
1657 || msg.contains("already_exists")
1658 || msg.contains("Unprocessable")
1659 {
1660 tracing::debug!(repo, name, "ensure_label: label already exists (race)");
1661 return Ok(());
1662 }
1663 tracing::warn!(repo, name, err = %msg, "ensure_label: create failed, continuing");
1665 }
1666 }
1667 Ok(())
1668 }
1669
1670 pub async fn remove_label(&self, repo: &str, number: &str, label: &str) -> anyhow::Result<()> {
1672 let encoded = urlencoding::encode(label);
1673 let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}/labels/{encoded}");
1674 match self.delete(&url).await {
1675 Ok(_) => Ok(()),
1676 Err(e) if e.to_string().contains("404") => {
1677 tracing::debug!(repo, number, label, "label already removed (404)");
1678 Ok(())
1679 }
1680 Err(e) => Err(e),
1681 }
1682 }
1683
1684 pub async fn add_comment(&self, repo: &str, number: &str, body: &str) -> anyhow::Result<()> {
1686 let body = redact_posted_body(body);
1687 let url = format!("{}/repos/{repo}/issues/{number}/comments", self.api_root());
1688 let payload = serde_json::json!({ "body": body });
1689 self.post_json_raw(&url, &payload).await?;
1690 Ok(())
1691 }
1692
1693 pub async fn post_commit_status(
1695 &self,
1696 repo: &str,
1697 sha: &str,
1698 state: &str,
1699 context: &str,
1700 description: &str,
1701 ) -> anyhow::Result<()> {
1702 let url = format!("{GITHUB_API}/repos/{repo}/statuses/{sha}");
1703 let payload = serde_json::json!({
1704 "state": state,
1705 "context": context,
1706 "description": description,
1707 });
1708 self.post_json_raw(&url, &payload).await?;
1709 Ok(())
1710 }
1711
1712 pub async fn add_reaction(
1716 &self,
1717 repo: &str,
1718 number: &str,
1719 content: &str,
1720 ) -> anyhow::Result<()> {
1721 let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}/reactions");
1722 let payload = serde_json::json!({ "content": content });
1723 self.post_json_raw(&url, &payload).await?;
1724 Ok(())
1725 }
1726
1727 pub async fn add_comment_reaction(
1731 &self,
1732 repo: &str,
1733 comment_id: &str,
1734 content: &str,
1735 ) -> anyhow::Result<()> {
1736 let url = format!("{GITHUB_API}/repos/{repo}/issues/comments/{comment_id}/reactions");
1737 let payload = serde_json::json!({ "content": content });
1738 self.post_json_raw(&url, &payload).await?;
1739 Ok(())
1740 }
1741
1742 pub async fn list_comments(
1744 &self,
1745 repo: &str,
1746 number: &str,
1747 ) -> anyhow::Result<Vec<GitHubComment>> {
1748 let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}/comments");
1749 self.get_all_pages(&url, &[("per_page", "100")]).await
1750 }
1751
1752 pub async fn is_pr_merged(&self, repo: &str, branch: &str) -> anyhow::Result<bool> {
1754 let owner = repo
1755 .split('/')
1756 .next()
1757 .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
1758 let head = format!("{owner}:{branch}");
1759
1760 let url = format!("{GITHUB_API}/repos/{repo}/pulls");
1761 let prs: Vec<serde_json::Value> = self
1762 .get_with_query(
1763 &url,
1764 &[("head", &head), ("state", "closed"), ("per_page", "1")],
1765 )
1766 .await?;
1767
1768 if prs.is_empty() {
1769 return Ok(false);
1770 }
1771 let merged_at = prs[0].get("merged_at");
1772 Ok(merged_at.is_some_and(|v| !v.is_null()))
1773 }
1774
1775 pub async fn get_closed_pr_state(
1788 &self,
1789 repo: &str,
1790 branch: &str,
1791 ) -> anyhow::Result<Option<(u64, bool, String)>> {
1792 let owner = repo
1793 .split('/')
1794 .next()
1795 .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
1796 let head = format!("{owner}:{branch}");
1797
1798 let url = format!("{GITHUB_API}/repos/{repo}/pulls");
1799 let prs: Vec<serde_json::Value> = self
1800 .get_with_query(
1801 &url,
1802 &[("head", &head), ("state", "closed"), ("per_page", "5")],
1803 )
1804 .await?;
1805
1806 if prs.is_empty() {
1807 return Ok(None);
1808 }
1809
1810 for pr in prs {
1813 let pr_branch = pr
1814 .get("head")
1815 .and_then(|h| h.get("ref"))
1816 .and_then(|r| r.as_str())
1817 .unwrap_or("");
1818
1819 if pr_branch != branch {
1820 tracing::debug!(
1821 repo,
1822 branch,
1823 pr_branch,
1824 "skipping PR with mismatched head ref"
1825 );
1826 continue;
1827 }
1828
1829 let pr_number = pr
1830 .get("number")
1831 .and_then(serde_json::Value::as_u64)
1832 .ok_or_else(|| anyhow::anyhow!("PR missing number field"))?;
1833
1834 let merged_at = pr.get("merged_at");
1835 let merged = merged_at.is_some_and(|v| !v.is_null());
1836 let state = pr
1837 .get("state")
1838 .and_then(|v| v.as_str())
1839 .unwrap_or("closed")
1840 .to_string();
1841
1842 return Ok(Some((pr_number, merged, state)));
1843 }
1844
1845 Ok(None)
1847 }
1848
1849 pub async fn batch_is_pr_merged_by_branch(
1854 &self,
1855 repo: &str,
1856 branches: &[String],
1857 ) -> anyhow::Result<HashMap<String, bool>> {
1858 if branches.is_empty() {
1859 return Ok(HashMap::new());
1860 }
1861
1862 let (owner, name) = repo
1863 .split_once('/')
1864 .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
1865
1866 let mut var_defs = String::new();
1870 let mut aliases = String::new();
1871 let mut vars = serde_json::json!({ "owner": owner, "name": name });
1872 for (i, branch) in branches.iter().enumerate() {
1873 let _ = write!(var_defs, ", $b{i}: String!");
1874 let _ = write!(
1875 aliases,
1876 r"b{i}: pullRequests(headRefName: $b{i}, states: [MERGED], last: 1) {{ nodes {{ merged }} }} "
1877 );
1878 vars[format!("b{i}")] = serde_json::Value::String(branch.clone());
1879 }
1880
1881 let query = format!(
1882 r"query($owner: String!, $name: String!{var_defs}) {{
1883 repository(owner: $owner, name: $name) {{ {aliases} }}
1884 }}"
1885 );
1886
1887 let resp = self.graphql_with_vars(&query, vars).await?;
1888
1889 if let Some(errors) = resp.get("errors").and_then(|e| e.as_array())
1891 && !errors.is_empty()
1892 {
1893 let messages: Vec<&str> = errors
1894 .iter()
1895 .filter_map(|e| e.get("message").and_then(|m| m.as_str()))
1896 .collect();
1897 tracing::warn!(
1898 repo,
1899 errors = ?messages,
1900 "GraphQL returned errors in batch PR merge check"
1901 );
1902 }
1903
1904 Self::parse_batch_pr_merged_response(&resp, branches)
1905 }
1906
1907 fn parse_batch_pr_merged_response(
1908 resp: &serde_json::Value,
1909 branches: &[String],
1910 ) -> anyhow::Result<HashMap<String, bool>> {
1911 let repo_data = resp.pointer("/data/repository").ok_or_else(|| {
1912 let error_msg = resp
1914 .get("errors")
1915 .and_then(|e| e.as_array())
1916 .and_then(|arr| arr.first())
1917 .and_then(|e| e.get("message"))
1918 .and_then(|m| m.as_str())
1919 .unwrap_or("no error details");
1920 anyhow::anyhow!("missing /data/repository in GraphQL response: {error_msg}")
1921 })?;
1922
1923 let mut result = HashMap::new();
1924 for (i, branch) in branches.iter().enumerate() {
1925 let alias = format!("b{i}");
1926 let merged = repo_data
1927 .get(&alias)
1928 .and_then(|v| v.get("nodes"))
1929 .and_then(|nodes| nodes.as_array())
1930 .and_then(|arr| arr.first())
1931 .and_then(|node| node.get("merged"))
1932 .and_then(serde_json::Value::as_bool)
1933 .unwrap_or(false);
1934 result.insert(branch.clone(), merged);
1935 }
1936
1937 Ok(result)
1938 }
1939
1940 pub async fn get_mentions(
1942 &self,
1943 repo: &str,
1944 since: &str,
1945 ) -> anyhow::Result<Vec<GitHubComment>> {
1946 let url = format!("{}/repos/{repo}/issues/comments", self.api_root());
1947 self.get_all_pages(&url, &[("since", since), ("per_page", "100")])
1948 .await
1949 }
1950
1951 pub async fn get_issue_comments(
1953 &self,
1954 repo: &str,
1955 issue_number: u64,
1956 ) -> anyhow::Result<Vec<GitHubComment>> {
1957 let url = format!(
1958 "{}/repos/{repo}/issues/{issue_number}/comments",
1959 self.api_root()
1960 );
1961 self.get_all_pages(&url, &[("per_page", "100")]).await
1962 }
1963
1964 pub async fn get_whoami(&self) -> anyhow::Result<String> {
1966 if let Some(cached) = self.cached_username.get() {
1967 return Ok(cached.clone());
1968 }
1969
1970 let mut owner = self.clone();
1972 owner.owner_only = true;
1973 let user: serde_json::Value = owner.get_json(&format!("{GITHUB_API}/user")).await?;
1974 let username = user
1975 .get("login")
1976 .and_then(|v| v.as_str())
1977 .map(String::from)
1978 .ok_or_else(|| anyhow::anyhow!("failed to get current user"))?;
1979
1980 let _ = self.cached_username.set(username.clone());
1981 Ok(username)
1982 }
1983
1984 pub async fn get_pr_number(&self, repo: &str, branch: &str) -> anyhow::Result<Option<u64>> {
1986 let owner = repo
1987 .split('/')
1988 .next()
1989 .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
1990 let head = format!("{owner}:{branch}");
1991
1992 let url = format!("{GITHUB_API}/repos/{repo}/pulls");
1993 let prs: Vec<serde_json::Value> = self
1994 .get_with_query(
1995 &url,
1996 &[("head", &head), ("state", "open"), ("per_page", "1")],
1997 )
1998 .await?;
1999
2000 if prs.is_empty() {
2001 return Ok(None);
2002 }
2003 prs[0]
2004 .get("number")
2005 .and_then(serde_json::Value::as_u64)
2006 .ok_or_else(|| anyhow::anyhow!("PR missing number field"))
2007 .map(Some)
2008 }
2009
2010 pub async fn create_pr(
2021 &self,
2022 repo: &str,
2023 title: &str,
2024 body: &str,
2025 head: &str,
2026 base: &str,
2027 ) -> anyhow::Result<String> {
2028 #[derive(Serialize)]
2029 struct CreatePullRequest<'a> {
2030 title: &'a str,
2031 body: &'a str,
2032 head: &'a str,
2033 base: &'a str,
2034 }
2035
2036 let body = redact_posted_body(body);
2037 let url = format!("{}/repos/{repo}/pulls", self.api_root());
2038 Self::check_backoff(&url)?;
2039
2040 let payload = CreatePullRequest {
2041 title,
2042 body: &body,
2043 head,
2044 base,
2045 };
2046
2047 let auth = self.auth_header(&url).await?;
2048 let make_req = || {
2049 Ok(self
2050 .client
2051 .post(&url)
2052 .header(header::AUTHORIZATION, auth.clone())
2053 .header(header::ACCEPT, "application/vnd.github+json")
2054 .header(header::USER_AGENT, "orch")
2055 .header("X-GitHub-Api-Version", "2022-11-28")
2056 .json(&payload))
2057 };
2058 let response = self.send_with_retries(make_req, false).await?;
2059 let status = response.status();
2060 let text = response.text().await.unwrap_or_default();
2061 if !status.is_success() {
2062 Self::maybe_record_rate_limit_from_body(status, &text);
2063 anyhow::bail!("GitHub API POST {url} failed ({status}): {text}");
2064 }
2065
2066 let pr: serde_json::Value = serde_json::from_str(&text)?;
2067 pr.get("html_url")
2068 .and_then(|v| v.as_str())
2069 .map(String::from)
2070 .ok_or_else(|| anyhow::anyhow!("failed to get PR URL from response: {pr:?}"))
2071 }
2072
2073 pub async fn get_default_branch(&self, repo: &str) -> anyhow::Result<String> {
2078 let url = format!("{}/repos/{repo}", self.api_root());
2079 let resp: serde_json::Value = self.get_json(&url).await?;
2080 resp.get("default_branch")
2081 .and_then(|v| v.as_str())
2082 .map(String::from)
2083 .ok_or_else(|| anyhow::anyhow!("default_branch missing from repo response"))
2084 }
2085
2086 pub async fn get_pr(&self, repo: &str, pr_number: u64) -> anyhow::Result<GitHubPullRequest> {
2089 let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}");
2090 self.get_json(&url).await
2091 }
2092
2093 pub async fn batch_get_pr_states(
2098 &self,
2099 repo: &str,
2100 pr_numbers: &[u64],
2101 ) -> anyhow::Result<HashMap<u64, (bool, String)>> {
2102 const CHUNK_SIZE: usize = 50;
2104
2105 if pr_numbers.is_empty() {
2106 return Ok(HashMap::new());
2107 }
2108
2109 let (owner, name) = repo
2110 .split_once('/')
2111 .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
2112
2113 let mut result = HashMap::new();
2114
2115 for chunk in pr_numbers.chunks(CHUNK_SIZE) {
2116 let aliases: String = chunk
2117 .iter()
2118 .map(|n| format!("pr{n}: pullRequest(number: {n}) {{ merged state }}"))
2119 .collect::<Vec<_>>()
2120 .join("\n ");
2121
2122 let query = format!(
2123 r"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"
2124 );
2125
2126 let resp = self
2127 .graphql_with_vars(&query, serde_json::json!({ "owner": owner, "name": name }))
2128 .await?;
2129 let repo_data = resp
2130 .pointer("/data/repository")
2131 .ok_or_else(|| anyhow::anyhow!("missing /data/repository in GraphQL response"))?;
2132
2133 for n in chunk {
2134 if let Some(pr) = repo_data.get(format!("pr{n}")) {
2135 let merged = pr
2136 .get("merged")
2137 .and_then(serde_json::Value::as_bool)
2138 .unwrap_or(false);
2139 let state = pr
2140 .get("state")
2141 .and_then(|v| v.as_str())
2142 .unwrap_or("UNKNOWN")
2143 .to_lowercase();
2144 result.insert(*n, (merged, state));
2145 }
2146 }
2147 }
2148
2149 Ok(result)
2150 }
2151
2152 pub async fn batch_get_issue_states(
2157 &self,
2158 repo: &str,
2159 issue_numbers: &[u64],
2160 caller_context: &str,
2161 ) -> anyhow::Result<HashMap<String, (String, Vec<String>)>> {
2162 const CHUNK_SIZE: usize = 50;
2164
2165 if issue_numbers.is_empty() {
2166 return Ok(HashMap::new());
2167 }
2168
2169 let (valid_issue_numbers, invalid_issue_numbers) =
2170 sanitize_github_issue_numbers(issue_numbers);
2171 if !invalid_issue_numbers.is_empty() {
2172 tracing::warn!(
2173 repo,
2174 caller_context,
2175 invalid_issue_numbers = ?invalid_issue_numbers,
2176 total_supplied = issue_numbers.len(),
2177 "dropping invalid GitHub issue numbers before batch issue-state GraphQL query"
2178 );
2179 }
2180 if valid_issue_numbers.is_empty() {
2181 return Ok(HashMap::new());
2182 }
2183
2184 let (owner, name) = repo
2185 .split_once('/')
2186 .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
2187
2188 let mut result = HashMap::new();
2189
2190 for chunk in valid_issue_numbers.chunks(CHUNK_SIZE) {
2191 let aliases: String = chunk
2192 .iter()
2193 .map(|n| {
2194 format!("issue{n}: issue(number: {n}) {{ state labels(first: 100) {{ nodes {{ name }} }} }}")
2195 })
2196 .collect::<Vec<_>>()
2197 .join(" ");
2198
2199 let query = format!(
2200 r"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"
2201 );
2202
2203 let resp = self
2204 .graphql_with_vars(&query, serde_json::json!({ "owner": owner, "name": name }))
2205 .await?;
2206 let repo_data = resp
2207 .pointer("/data/repository")
2208 .ok_or_else(|| anyhow::anyhow!("missing /data/repository in GraphQL response"))?;
2209
2210 for n in chunk {
2211 if let Some(issue) = repo_data.get(format!("issue{n}")) {
2212 let state = issue
2213 .get("state")
2214 .and_then(|v| v.as_str())
2215 .unwrap_or("UNKNOWN")
2216 .to_lowercase();
2217 let labels: Vec<String> = issue
2218 .pointer("/labels/nodes")
2219 .and_then(|v| v.as_array())
2220 .map(|arr| {
2221 arr.iter()
2222 .filter_map(|l| {
2223 l.get("name").and_then(|nm| nm.as_str()).map(String::from)
2224 })
2225 .collect()
2226 })
2227 .unwrap_or_default();
2228 result.insert(n.to_string(), (state, labels));
2229 }
2230 }
2231 }
2232 Ok(result)
2233 }
2234
2235 pub async fn get_required_status_check_contexts(
2237 &self,
2238 repo: &str,
2239 branch: &str,
2240 ) -> anyhow::Result<Vec<RequiredStatusCheck>> {
2241 let branch = urlencoding::encode(branch);
2242 let classic_url = format!(
2243 "{}/repos/{repo}/branches/{branch}/protection",
2244 self.api_root()
2245 );
2246 let rules_url = format!("{}/repos/{repo}/rules/branches/{branch}", self.api_root());
2247
2248 let classic_fut = self.get_json::<serde_json::Value>(&classic_url);
2249 let rules_fut = self.get_all_pages::<serde_json::Value>(&rules_url, &[("per_page", "100")]);
2250 let (classic_resp, rules_resp) = tokio::join!(classic_fut, rules_fut);
2251
2252 let classic = match classic_resp {
2253 Ok(value) => parse_classic_required_status_checks(&value),
2254 Err(e) => {
2255 if is_no_branch_protection_error(&e.to_string()) {
2256 Vec::new()
2257 } else {
2258 return Err(e);
2259 }
2260 }
2261 };
2262
2263 let ruleset = match rules_resp {
2264 Ok(rules) => parse_ruleset_required_status_checks(&rules),
2265 Err(e) => {
2266 if e.to_string().contains("404") {
2267 Vec::new()
2268 } else {
2269 return Err(e);
2270 }
2271 }
2272 };
2273
2274 Ok(merge_required_status_checks(classic, ruleset))
2275 }
2276
2277 pub async fn get_commit_status_contexts(
2279 &self,
2280 repo: &str,
2281 sha: &str,
2282 ) -> anyhow::Result<Vec<(String, String)>> {
2283 let url = format!(
2284 "{}/repos/{repo}/commits/{sha}/status?per_page=100",
2285 self.api_root()
2286 );
2287 let statuses: Vec<serde_json::Value> =
2292 self.get_all_pages_from_wrapper(&url, "statuses").await?;
2293
2294 Ok(statuses
2295 .into_iter()
2296 .filter_map(|status| {
2297 let context = status.get("context").and_then(|v| v.as_str())?;
2298 let state = status.get("state").and_then(|v| v.as_str())?;
2299 Some((context.to_string(), state.to_string()))
2300 })
2301 .collect())
2302 }
2303
2304 fn combined_status_state(
2305 total: u64,
2306 failing: u64,
2307 pending: u64,
2308 has_workflows: bool,
2309 mergeable_state: Option<&str>,
2310 ) -> String {
2311 if failing > 0 {
2312 "failure".to_string()
2313 } else if pending > 0 {
2314 "pending".to_string()
2315 } else if total == 0 && has_workflows {
2316 if mergeable_state == Some("clean") {
2320 "success".to_string()
2321 } else {
2322 "pending".to_string()
2323 }
2324 } else {
2325 "success".to_string()
2326 }
2327 }
2328
2329 pub async fn has_workflows(&self, repo: &str) -> anyhow::Result<bool> {
2334 let url = format!("{GITHUB_API}/repos/{repo}/actions/workflows?per_page=1");
2335 let resp = self.get_json::<serde_json::Value>(&url).await;
2336 match resp {
2337 Ok(value) => Ok(value
2338 .get("workflows")
2339 .and_then(|v| v.as_array())
2340 .is_some_and(|workflows| !workflows.is_empty())),
2341 Err(e) => {
2342 let err = e.to_string();
2343 if err.contains("404") {
2344 Ok(false)
2345 } else {
2346 Err(e)
2347 }
2348 }
2349 }
2350 }
2351
2352 pub async fn has_workflow_on_branch(&self, repo: &str, branch: &str) -> anyhow::Result<bool> {
2354 let branch = urlencoding::encode(branch);
2355 let url = format!(
2356 "{}/repos/{repo}/contents/.github/workflows?ref={branch}",
2357 self.api_root()
2358 );
2359 match self.get_json::<serde_json::Value>(&url).await {
2360 Ok(value) => Ok(value.as_array().is_some_and(|entries| {
2361 entries.iter().any(|entry| {
2362 entry
2363 .get("name")
2364 .and_then(|name| name.as_str())
2365 .is_some_and(|name| {
2366 Path::new(name)
2367 .extension()
2368 .and_then(|ext| ext.to_str())
2369 .is_some_and(|ext| {
2370 ext.eq_ignore_ascii_case("yml")
2371 || ext.eq_ignore_ascii_case("yaml")
2372 })
2373 })
2374 })
2375 })),
2376 Err(e) => {
2377 let err = e.to_string();
2378 if err.contains("404") {
2379 Ok(false)
2380 } else {
2381 Err(e)
2382 }
2383 }
2384 }
2385 }
2386
2387 pub async fn has_file_on_branch(
2389 &self,
2390 repo: &str,
2391 path: &str,
2392 branch: &str,
2393 ) -> anyhow::Result<bool> {
2394 let path = path
2395 .split('/')
2396 .map(|segment| urlencoding::encode(segment).into_owned())
2397 .collect::<Vec<_>>()
2398 .join("/");
2399 let branch = urlencoding::encode(branch);
2400 let url = format!(
2401 "{}/repos/{repo}/contents/{path}?ref={branch}",
2402 self.api_root()
2403 );
2404 match self.get_json::<serde_json::Value>(&url).await {
2405 Ok(_) => Ok(true),
2406 Err(e) => {
2407 let err = e.to_string();
2408 if err.contains("404") {
2409 Ok(false)
2410 } else {
2411 Err(e)
2412 }
2413 }
2414 }
2415 }
2416
2417 pub async fn get_branch_sha(&self, repo: &str, branch: &str) -> anyhow::Result<String> {
2419 let encoded = urlencoding::encode(branch);
2420 let url = format!("{}/repos/{repo}/branches/{encoded}", self.api_root());
2421 let resp: serde_json::Value = self.get_json(&url).await?;
2422 resp.pointer("/commit/sha")
2423 .and_then(|v| v.as_str())
2424 .map(String::from)
2425 .ok_or_else(|| anyhow::anyhow!("branch {branch} has no commit sha"))
2426 }
2427
2428 pub async fn create_required_check_ruleset(
2430 &self,
2431 repo: &str,
2432 checks: &[RequiredStatusCheck],
2433 ) -> anyhow::Result<()> {
2434 let url = format!("{}/repos/{repo}/rulesets", self.api_root());
2435 let payload = required_check_ruleset_payload(checks);
2436 self.post_json_raw(&url, &payload).await?;
2437 Ok(())
2438 }
2439
2440 pub async fn get_check_runs(
2442 &self,
2443 repo: &str,
2444 sha: &str,
2445 ) -> anyhow::Result<Vec<GitHubCheckRun>> {
2446 let url = format!(
2457 "{}/repos/{repo}/commits/{sha}/check-runs?filter=latest&per_page=100",
2458 self.api_root()
2459 );
2460 self.get_all_pages_from_wrapper(&url, "check_runs").await
2461 }
2462
2463 pub async fn get_check_run_annotations(
2470 &self,
2471 repo: &str,
2472 check_run_id: u64,
2473 ) -> anyhow::Result<Vec<GitHubAnnotation>> {
2474 let url = format!("{GITHUB_API}/repos/{repo}/check-runs/{check_run_id}/annotations");
2475 self.get_all_pages(&url, &[("per_page", "100")]).await
2476 }
2477
2478 pub async fn get_pr_reviews(
2480 &self,
2481 repo: &str,
2482 pr_number: u64,
2483 ) -> anyhow::Result<Vec<GitHubReview>> {
2484 let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}/reviews");
2485 self.get_all_pages(&url, &[("per_page", "100")]).await
2486 }
2487
2488 pub async fn get_commit_timestamp(&self, repo: &str, sha: &str) -> anyhow::Result<String> {
2493 let url = format!("{GITHUB_API}/repos/{repo}/commits/{sha}");
2494 let value: serde_json::Value = self.get_json(&url).await?;
2495 value
2496 .pointer("/commit/committer/date")
2497 .and_then(|v| v.as_str())
2498 .map(ToString::to_string)
2499 .ok_or_else(|| anyhow::anyhow!("commit {sha} has no committer date"))
2500 }
2501
2502 pub async fn update_pr_body(
2504 &self,
2505 repo: &str,
2506 pr_number: u64,
2507 body: &str,
2508 ) -> anyhow::Result<()> {
2509 let body = redact_posted_body(body);
2510 let url = format!("{}/repos/{repo}/pulls/{pr_number}", self.api_root());
2511 let payload = serde_json::json!({ "body": body });
2512 self.patch_json_raw(&url, &payload).await?;
2513 Ok(())
2514 }
2515
2516 pub async fn close_pr(&self, repo: &str, pr_number: u64) -> anyhow::Result<()> {
2518 let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}");
2519 let payload = serde_json::json!({ "state": "closed" });
2520 self.patch_json_raw(&url, &payload).await?;
2521 Ok(())
2522 }
2523
2524 pub async fn compare_behind_by(
2529 &self,
2530 repo: &str,
2531 base: &str,
2532 head_sha: &str,
2533 ) -> anyhow::Result<u64> {
2534 let url = format!("{GITHUB_API}/repos/{repo}/compare/{base}...{head_sha}");
2535 let body: serde_json::Value = self.get_json(&url).await?;
2536 parse_behind_by(&body)
2537 }
2538
2539 pub async fn commit_meta(&self, repo: &str, sha: &str) -> anyhow::Result<CommitMeta> {
2541 let url = format!("{GITHUB_API}/repos/{repo}/commits/{sha}");
2542 let value: serde_json::Value = self.get_json(&url).await?;
2543 Ok(parse_commit_meta(&value))
2544 }
2545
2546 pub async fn branch_contains(
2548 &self,
2549 repo: &str,
2550 branch: &str,
2551 sha: &str,
2552 ) -> anyhow::Result<bool> {
2553 let url = format!("{GITHUB_API}/repos/{repo}/compare/{branch}...{sha}");
2554 let body: serde_json::Value = self.get_json(&url).await?;
2555 body.get("ahead_by")
2556 .and_then(serde_json::Value::as_u64)
2557 .map(|ahead| ahead == 0)
2558 .ok_or_else(|| anyhow::anyhow!("compare response has no numeric ahead_by field"))
2559 }
2560
2561 pub async fn close_issue(&self, repo: &str, number: &str) -> anyhow::Result<()> {
2563 let url = format!("{GITHUB_API}/repos/{repo}/issues/{number}");
2564 let payload = serde_json::json!({ "state": "closed" });
2565 self.patch_json_raw(&url, &payload).await?;
2566 Ok(())
2567 }
2568
2569 pub async fn reopen_issue(&self, repo: &str, number: &str) -> anyhow::Result<()> {
2571 let url = format!("{}/repos/{repo}/issues/{number}", self.api_root());
2572 let payload = serde_json::json!({ "state": "open" });
2573 self.patch_json_raw(&url, &payload).await?;
2574 Ok(())
2575 }
2576
2577 pub async fn is_collaborator(&self, repo: &str, username: &str) -> anyhow::Result<bool> {
2579 let url = format!("{GITHUB_API}/repos/{repo}/collaborators/{username}");
2580 Self::check_backoff(&url)?;
2581 let auth = self.auth_header(&url).await?;
2582 let make_req = || {
2583 Ok(self
2584 .client
2585 .get(&url)
2586 .header(header::AUTHORIZATION, auth.clone())
2587 .header(header::ACCEPT, "application/vnd.github+json")
2588 .header("X-GitHub-Api-Version", "2022-11-28"))
2589 };
2590 let resp = self.send_with_retries(make_req, false).await?;
2591 let status = resp.status();
2592 if status == StatusCode::NO_CONTENT {
2593 Ok(true)
2594 } else if status == StatusCode::NOT_FOUND {
2595 Ok(false)
2596 } else {
2597 let body = resp.text().await.unwrap_or_default();
2598 anyhow::bail!("GitHub API collaborator check failed ({status}): {body}");
2599 }
2600 }
2601
2602 pub async fn add_sub_issue(
2604 &self,
2605 parent_node_id: &str,
2606 child_node_id: &str,
2607 ) -> anyhow::Result<()> {
2608 let query = format!(
2609 r#"mutation {{
2610 addSubIssue(input: {{issueId: "{parent_node_id}", subIssueId: "{child_node_id}"}}) {{
2611 issue {{ number }}
2612 subIssue {{ number }}
2613 }}
2614 }}"#
2615 );
2616 self.graphql_with_headers(&query, &["GraphQL-Features:sub_issues"])
2617 .await?;
2618 Ok(())
2619 }
2620
2621 pub async fn link_issue_to_branch(
2633 &self,
2634 repo: &str,
2635 issue_number: u64,
2636 branch: &str,
2637 ) -> anyhow::Result<String> {
2638 let parts: Vec<&str> = repo.split('/').collect();
2639 if parts.len() != 2 {
2640 anyhow::bail!("invalid repo format: expected 'owner/repo', got '{repo}'");
2641 }
2642 let (owner, repo_name) = (parts[0], parts[1]);
2643
2644 let query = r"query($owner: String!, $name: String!, $number: Int!) {
2646 repository(owner: $owner, name: $name) {
2647 id
2648 issue(number: $number) {
2649 id
2650 }
2651 }
2652 }";
2653 let vars = serde_json::json!({
2654 "owner": owner,
2655 "name": repo_name,
2656 "number": issue_number,
2657 });
2658
2659 let result = self.graphql_with_vars(query, vars).await?;
2660
2661 let repo_id = result
2662 .pointer("/data/repository/id")
2663 .and_then(|v| v.as_str())
2664 .ok_or_else(|| anyhow::anyhow!("failed to get repository node ID"))?;
2665
2666 let issue_id = result
2667 .pointer("/data/repository/issue/id")
2668 .and_then(|v| v.as_str())
2669 .ok_or_else(|| anyhow::anyhow!("failed to get issue node ID"))?;
2670
2671 let branch_query = r"query($owner: String!, $name: String!, $ref: String!) {
2673 repository(owner: $owner, name: $name) {
2674 ref(qualifiedName: $ref) {
2675 target {
2676 oid
2677 }
2678 }
2679 }
2680 }";
2681 let branch_vars = serde_json::json!({
2682 "owner": owner,
2683 "name": repo_name,
2684 "ref": format!("refs/heads/{}", branch),
2685 });
2686
2687 let branch_result = self.graphql_with_vars(branch_query, branch_vars).await?;
2688 let branch_oid = branch_result
2689 .pointer("/data/repository/ref/target/oid")
2690 .and_then(|v| v.as_str());
2691
2692 let branch_oid = if let Some(oid) = branch_oid {
2695 oid.to_string()
2696 } else {
2697 let default_query = r"query($owner: String!, $name: String!) {
2699 repository(owner: $owner, name: $name) {
2700 defaultBranchRef {
2701 target {
2702 oid
2703 }
2704 }
2705 }
2706 }";
2707 let default_vars = serde_json::json!({
2708 "owner": owner,
2709 "name": repo_name,
2710 });
2711 let default_result = self.graphql_with_vars(default_query, default_vars).await?;
2712 match default_result
2713 .pointer("/data/repository/defaultBranchRef/target/oid")
2714 .and_then(|v| v.as_str())
2715 {
2716 Some(oid) => {
2717 tracing::debug!(
2718 repo,
2719 issue_number,
2720 branch,
2721 "branch not found, using default branch OID to create and link"
2722 );
2723 oid.to_string()
2724 }
2725 None => {
2726 return Ok(format!("unlinked:{branch}"));
2727 }
2728 }
2729 };
2730
2731 let mutation = r"mutation($issueId: ID!, $repositoryId: ID!, $name: String!, $oid: GitObjectID!) {
2734 createLinkedBranch(input: {
2735 issueId: $issueId
2736 repositoryId: $repositoryId
2737 name: $name
2738 oid: $oid
2739 }) {
2740 linkedBranch {
2741 id
2742 ref {
2743 name
2744 }
2745 }
2746 }
2747 }";
2748 let mutation_vars = serde_json::json!({
2749 "issueId": issue_id,
2750 "repositoryId": repo_id,
2751 "name": branch,
2752 "oid": branch_oid,
2753 });
2754
2755 let link_result = self.graphql_with_vars(mutation, mutation_vars).await;
2756
2757 match link_result {
2758 Ok(result) => {
2759 let linked_branch_id = result
2760 .pointer("/data/createLinkedBranch/linkedBranch/id")
2761 .and_then(|v| v.as_str())
2762 .map(String::from);
2763
2764 if let Some(id) = linked_branch_id {
2765 tracing::info!(
2766 repo,
2767 issue_number,
2768 branch,
2769 "linked issue to branch via GraphQL API"
2770 );
2771 Ok(id)
2772 } else {
2773 let errors = result
2775 .get("errors")
2776 .and_then(|e| e.as_array())
2777 .cloned()
2778 .unwrap_or_default();
2779
2780 if errors.iter().any(|e| {
2781 e.get("message")
2782 .and_then(|m| m.as_str())
2783 .is_some_and(|m| m.contains("already"))
2784 }) {
2785 tracing::debug!(
2786 repo,
2787 issue_number,
2788 branch,
2789 "issue already linked to branch"
2790 );
2791 Ok(format!("already_linked:{branch}"))
2792 } else {
2793 anyhow::bail!("failed to link issue to branch: {result:?}")
2794 }
2795 }
2796 }
2797 Err(e) => {
2798 let err_str = format!("{e}");
2800 if err_str.contains("already") || err_str.contains("existing") {
2801 tracing::debug!(
2802 repo,
2803 issue_number,
2804 branch,
2805 "issue already linked to branch (error check)"
2806 );
2807 Ok(format!("already_linked:{branch}"))
2808 } else {
2809 Err(e)
2810 }
2811 }
2812 }
2813 }
2814
2815 pub async fn merge_pr(
2818 &self,
2819 repo: &str,
2820 pr_number: u64,
2821 delete_branch: bool,
2822 head_sha: &str,
2823 ) -> anyhow::Result<()> {
2824 if !is_full_commit_sha(head_sha) {
2825 anyhow::bail!("merge_pr requires the full head sha, got {head_sha:?}");
2826 }
2827 let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}/merge");
2828 Self::check_backoff(&url)?;
2829 let payload = merge_pr_body(head_sha);
2830 let auth = self.auth_header(&url).await?;
2831 let make_req = || {
2832 Ok(self
2833 .client
2834 .put(&url)
2835 .json(&payload)
2836 .header(header::AUTHORIZATION, auth.clone())
2837 .header(header::ACCEPT, "application/vnd.github+json")
2838 .header("X-GitHub-Api-Version", "2022-11-28"))
2839 };
2840 let resp = self.send_with_retries(make_req, false).await?;
2841 let status = resp.status();
2842 if !status.is_success() {
2843 let body = resp.text().await.unwrap_or_default();
2844 anyhow::bail!("GitHub PR merge failed ({status}): {body}");
2845 }
2846 Self::record_success();
2847
2848 if delete_branch {
2850 let pr: serde_json::Value = self
2852 .get_json(&format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}"))
2853 .await?;
2854 if let Some(ref_name) = pr.pointer("/head/ref").and_then(|v| v.as_str()) {
2855 let del_url = format!("{GITHUB_API}/repos/{repo}/git/refs/heads/{ref_name}");
2856 if let Err(e) = self.delete(&del_url).await {
2857 let err_str = e.to_string();
2858 if err_str.contains("Reference does not exist") {
2859 tracing::debug!(
2860 ref_name,
2861 "branch already gone (GitHub auto-deleted on merge)"
2862 );
2863 } else {
2864 tracing::warn!(ref_name, err = %e, "failed to delete branch after merge");
2865 }
2866 }
2867 }
2868 }
2869 Ok(())
2870 }
2871
2872 pub async fn update_pr_branch(&self, repo: &str, pr_number: u64) -> anyhow::Result<()> {
2878 let url = format!("{GITHUB_API}/repos/{repo}/pulls/{pr_number}/update-branch");
2879 Self::check_backoff(&url)?;
2880 let auth = self.auth_header(&url).await?;
2881 let make_req = || {
2882 Ok(self
2883 .client
2884 .put(&url)
2885 .header(header::AUTHORIZATION, auth.clone())
2886 .header(header::ACCEPT, "application/vnd.github+json")
2887 .header("X-GitHub-Api-Version", "2022-11-28"))
2888 };
2889 let resp = self.send_with_retries(make_req, false).await?;
2890 let status = resp.status();
2891 if !status.is_success() {
2892 let body = resp.text().await.unwrap_or_default();
2893 Self::maybe_record_rate_limit_from_body(status, &body);
2894 anyhow::bail!("GitHub PR update-branch failed ({status}): {body}");
2895 }
2896 Self::record_success();
2897 Ok(())
2898 }
2899
2900 pub async fn enable_auto_merge(&self, repo: &str, pr_number: u64) -> anyhow::Result<()> {
2904 let parts: Vec<&str> = repo.split('/').collect();
2905 if parts.len() != 2 {
2906 anyhow::bail!("invalid repo format: {repo}");
2907 }
2908 let (owner, repo_name) = (parts[0], parts[1]);
2909
2910 let pr_query = r"query($owner: String!, $name: String!, $number: Int!) {
2912 repository(owner: $owner, name: $name) {
2913 pullRequest(number: $number) { id }
2914 }
2915 }";
2916 let body = self
2917 .graphql_with_vars(
2918 pr_query,
2919 serde_json::json!({
2920 "owner": owner,
2921 "name": repo_name,
2922 "number": pr_number,
2923 }),
2924 )
2925 .await?;
2926 let pr_id = body
2927 .pointer("/data/repository/pullRequest/id")
2928 .and_then(|v| v.as_str())
2929 .ok_or_else(|| anyhow::anyhow!("could not get PR node ID"))?
2930 .to_string();
2931
2932 let mutation = r"mutation($prId: ID!) {
2934 enablePullRequestAutoMerge(input: {pullRequestId: $prId, mergeMethod: SQUASH}) {
2935 pullRequest { autoMergeRequest { enabledAt } }
2936 }
2937 }";
2938 let body = self
2939 .graphql_with_vars(mutation, serde_json::json!({ "prId": pr_id }))
2940 .await?;
2941 if let Some(errors) = body.get("errors") {
2942 anyhow::bail!("enable auto-merge GraphQL error: {errors}");
2943 }
2944
2945 tracing::info!(repo, pr_number, "auto-merge enabled on PR");
2946 Ok(())
2947 }
2948
2949 pub async fn get_sub_issues(&self, repo: &str, number: &str) -> anyhow::Result<Vec<u64>> {
2951 let parts: Vec<&str> = repo.split('/').collect();
2952 if parts.len() != 2 {
2953 anyhow::bail!("invalid repo format: expected 'owner/repo', got '{repo}'");
2954 }
2955 let (owner, repo_name) = (parts[0], parts[1]);
2956 let number = match parse_positive_issue_number(number) {
2957 Ok(number) => number,
2958 Err(e) => {
2959 tracing::debug!(repo, issue = number, ?e, "skipping sub-issues lookup");
2960 return Ok(Vec::new());
2961 }
2962 };
2963
2964 let mut all_numbers: Vec<u64> = Vec::new();
2965 let mut cursor: Option<String> = None;
2966 let page_size = 100;
2967 let max_pages = 50;
2968 let mut page_count = 0;
2969
2970 loop {
2971 page_count += 1;
2972 if page_count > max_pages {
2973 tracing::warn!(
2974 repo,
2975 number,
2976 "get_sub_issues hit max page limit ({max_pages})"
2977 );
2978 break;
2979 }
2980
2981 let (query, vars) = if let Some(ref c) = cursor {
2982 (
2983 r"query($owner: String!, $name: String!, $number: Int!, $first: Int!, $after: String!) {
2984 repository(owner: $owner, name: $name) {
2985 issue(number: $number) {
2986 subIssues(first: $first, after: $after) {
2987 nodes { number }
2988 pageInfo { hasNextPage endCursor }
2989 }
2990 }
2991 }
2992 }",
2993 serde_json::json!({
2994 "owner": owner,
2995 "name": repo_name,
2996 "number": number,
2997 "first": page_size,
2998 "after": c,
2999 }),
3000 )
3001 } else {
3002 (
3003 r"query($owner: String!, $name: String!, $number: Int!, $first: Int!) {
3004 repository(owner: $owner, name: $name) {
3005 issue(number: $number) {
3006 subIssues(first: $first) {
3007 nodes { number }
3008 pageInfo { hasNextPage endCursor }
3009 }
3010 }
3011 }
3012 }",
3013 serde_json::json!({
3014 "owner": owner,
3015 "name": repo_name,
3016 "number": number,
3017 "first": page_size,
3018 }),
3019 )
3020 };
3021
3022 let result = self
3023 .graphql_with_headers_and_vars(query, &["GraphQL-Features:sub_issues"], vars)
3024 .await?;
3025
3026 let sub_issues_data = result
3027 .get("data")
3028 .and_then(|d| d.get("repository"))
3029 .and_then(|r| r.get("issue"))
3030 .and_then(|i| i.get("subIssues"));
3031
3032 let nodes = sub_issues_data
3033 .and_then(|s| s.get("nodes"))
3034 .and_then(|n| n.as_array());
3035
3036 match nodes {
3037 Some(nodes) => {
3038 let numbers: Vec<u64> = nodes
3039 .iter()
3040 .filter_map(|n| n.get("number").and_then(serde_json::Value::as_u64))
3041 .collect();
3042 all_numbers.extend(numbers);
3043 }
3044 None => break,
3045 }
3046
3047 let page_info = sub_issues_data.and_then(|s| s.get("pageInfo"));
3048 let has_next = page_info
3049 .and_then(|p| p.get("hasNextPage"))
3050 .and_then(serde_json::Value::as_bool)
3051 .unwrap_or(false);
3052
3053 if !has_next {
3054 break;
3055 }
3056
3057 cursor = page_info
3058 .and_then(|p| p.get("endCursor"))
3059 .and_then(|c| c.as_str())
3060 .map(ToString::to_string);
3061 }
3062
3063 Ok(all_numbers)
3064 }
3065
3066 pub async fn get_combined_status(
3068 &self,
3069 repo: &str,
3070 git_ref: &str,
3071 has_workflows: bool,
3072 mergeable_state: Option<&str>,
3073 ) -> anyhow::Result<(String, u64, u64, u64, u64)> {
3074 let url = format!("{GITHUB_API}/repos/{repo}/commits/{git_ref}/check-runs");
3075 let resp: serde_json::Value = self.get_json(&url).await?;
3076
3077 let runs = resp
3078 .get("check_runs")
3079 .and_then(|v| v.as_array())
3080 .cloned()
3081 .unwrap_or_default();
3082
3083 let mut passing = 0u64;
3084 let mut failing = 0u64;
3085 let mut pending = 0u64;
3086
3087 for run in &runs {
3088 let conclusion = run.get("conclusion").and_then(|v| v.as_str()).unwrap_or("");
3089 let status = run
3090 .get("status")
3091 .and_then(|v| v.as_str())
3092 .unwrap_or("queued");
3093
3094 match status {
3095 "completed" => {
3096 if conclusion.is_empty() {
3097 pending += 1;
3098 } else if matches!(conclusion, "success" | "neutral" | "skipped") {
3099 passing += 1;
3100 } else {
3101 failing += 1;
3102 }
3103 }
3104 _ => pending += 1,
3105 }
3106 }
3107
3108 let total = runs.len() as u64;
3109 let state =
3110 Self::combined_status_state(total, failing, pending, has_workflows, mergeable_state);
3111
3112 Ok((state, total, passing, failing, pending))
3113 }
3114
3115 pub async fn rerun_failed_workflow(
3121 &self,
3122 repo: &str,
3123 workflow_name: &str,
3124 branch: &str,
3125 ) -> anyhow::Result<()> {
3126 let url = format!(
3128 "{GITHUB_API}/repos/{repo}/actions/runs?branch={branch}&event=push&per_page=10"
3129 );
3130 let resp: serde_json::Value = self.get_json(&url).await?;
3131 let runs = resp["workflow_runs"]
3132 .as_array()
3133 .ok_or_else(|| anyhow::anyhow!("no workflow_runs array in response"))?;
3134
3135 let run_id = runs
3137 .iter()
3138 .find(|r| {
3139 r["name"].as_str() == Some(workflow_name)
3140 && matches!(r["conclusion"].as_str(), Some("failure" | "cancelled"))
3141 })
3142 .and_then(|r| r["id"].as_u64())
3143 .ok_or_else(|| {
3144 anyhow::anyhow!(
3145 "no failed run found for workflow '{workflow_name}' on branch '{branch}'"
3146 )
3147 })?;
3148
3149 let rerun_url = format!("{GITHUB_API}/repos/{repo}/actions/runs/{run_id}/rerun");
3151 let auth = self.auth_header(&rerun_url).await?;
3152 let make_req = || {
3153 Ok(self
3154 .client
3155 .post(&rerun_url)
3156 .header(header::AUTHORIZATION, auth.clone())
3157 .header(header::ACCEPT, "application/vnd.github+json")
3158 .header("X-GitHub-Api-Version", "2022-11-28"))
3159 };
3160 let resp = self.send_with_retries(make_req, false).await?;
3161 let status = resp.status();
3162 if !status.is_success() {
3163 let body = resp.text().await.unwrap_or_default();
3164 Self::maybe_record_rate_limit_from_body(status, &body);
3165 anyhow::bail!("GitHub API POST rerun {rerun_url} failed ({status}): {body}");
3166 }
3167
3168 Ok(())
3169 }
3170
3171 pub async fn batch_fetch_pr_review_data(
3177 &self,
3178 repo: &str,
3179 pr_numbers: &[u64],
3180 ) -> anyhow::Result<HashMap<u64, PrReviewBatchData>> {
3181 if pr_numbers.is_empty() {
3182 return Ok(HashMap::new());
3183 }
3184
3185 let (owner, name) = repo
3186 .split_once('/')
3187 .ok_or_else(|| anyhow::anyhow!("invalid repo format: {repo}"))?;
3188
3189 let aliases: String = pr_numbers
3191 .iter()
3192 .map(|&n| build_pr_review_alias(n))
3193 .collect::<Vec<_>>()
3194 .join("\n");
3195
3196 let query = format!(
3197 r"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"
3198 );
3199
3200 let resp = self
3201 .graphql_with_vars(&query, serde_json::json!({ "owner": owner, "name": name }))
3202 .await?;
3203 let repo_data = resp
3204 .pointer("/data/repository")
3205 .ok_or_else(|| anyhow::anyhow!("missing /data/repository in GraphQL response"))?;
3206
3207 let mut result = HashMap::new();
3208 for &n in pr_numbers {
3209 let Some(pr_data) = repo_data.get(format!("pr{n}")) else {
3210 continue;
3211 };
3212
3213 let merged = pr_data
3214 .get("merged")
3215 .and_then(serde_json::Value::as_bool)
3216 .unwrap_or(false);
3217 let mergeable = match pr_data.get("mergeable").and_then(|v| v.as_str()) {
3218 Some("MERGEABLE") => Some(true),
3219 Some("CONFLICTING") => Some(false),
3220 _ => None, };
3222
3223 let mut reviews: Vec<GitHubReview> = pr_data
3224 .pointer("/reviews/nodes")
3225 .and_then(|v| v.as_array())
3226 .map(|nodes| nodes.iter().filter_map(parse_graphql_review).collect())
3227 .unwrap_or_default();
3228
3229 if connection_has_next_page(pr_data.pointer("/reviews/pageInfo")) {
3230 tracing::warn!(
3231 pr_number = n,
3232 fetched = reviews.len(),
3233 "batch review fetch truncated reviews connection at first page"
3234 );
3235 }
3236
3237 reviews.sort_by(|a, b| a.submitted_at.cmp(&b.submitted_at));
3241
3242 let mut review_comments: Vec<GitHubReviewComment> = pr_data
3243 .pointer("/reviewThreads/nodes")
3244 .and_then(|v| v.as_array())
3245 .map(|threads| {
3246 threads
3247 .iter()
3248 .filter_map(|thread| {
3249 thread
3250 .pointer("/comments/nodes")
3251 .and_then(|v| v.as_array())
3252 .map(|nodes| {
3253 nodes
3254 .iter()
3255 .filter_map(parse_graphql_review_comment)
3256 .collect::<Vec<_>>()
3257 })
3258 })
3259 .flatten()
3260 .collect()
3261 })
3262 .unwrap_or_default();
3263
3264 if connection_has_next_page(pr_data.pointer("/reviewThreads/pageInfo")) {
3265 tracing::warn!(
3266 pr_number = n,
3267 fetched_threads = pr_data
3268 .pointer("/reviewThreads/nodes")
3269 .and_then(|v| v.as_array())
3270 .map_or(0, Vec::len),
3271 "batch review fetch truncated reviewThreads connection at first page"
3272 );
3273 }
3274 if pr_data
3275 .pointer("/reviewThreads/nodes")
3276 .and_then(|v| v.as_array())
3277 .is_some_and(|threads| {
3278 threads.iter().any(|thread| {
3279 connection_has_next_page(thread.pointer("/comments/pageInfo"))
3280 })
3281 })
3282 {
3283 tracing::warn!(
3284 pr_number = n,
3285 "batch review fetch truncated one or more review thread comment connections"
3286 );
3287 }
3288
3289 review_comments.sort_by(|a, b| a.created_at.cmp(&b.created_at));
3292
3293 let mut issue_comments: Vec<GitHubComment> = pr_data
3294 .pointer("/comments/nodes")
3295 .and_then(|v| v.as_array())
3296 .map(|nodes| {
3297 nodes
3298 .iter()
3299 .filter_map(parse_graphql_issue_comment)
3300 .collect()
3301 })
3302 .unwrap_or_default();
3303
3304 if let Some(cursor) = connection_end_cursor(pr_data.pointer("/comments/pageInfo")) {
3305 issue_comments.extend(
3306 self.fetch_pr_issue_comments_after(owner, name, n, Some(cursor))
3307 .await?,
3308 );
3309 }
3310
3311 issue_comments.sort_by(|a, b| a.created_at.cmp(&b.created_at));
3316
3317 result.insert(
3318 n,
3319 PrReviewBatchData {
3320 merged,
3321 head_sha: pr_data
3322 .get("headRefOid")
3323 .and_then(|v| v.as_str())
3324 .unwrap_or_default()
3325 .to_string(),
3326 mergeable,
3327 reviews,
3328 review_comments,
3329 issue_comments,
3330 },
3331 );
3332 }
3333
3334 Ok(result)
3335 }
3336
3337 async fn fetch_pr_issue_comments_after(
3338 &self,
3339 owner: &str,
3340 name: &str,
3341 pr_number: u64,
3342 mut cursor: Option<String>,
3343 ) -> anyhow::Result<Vec<GitHubComment>> {
3344 let mut comments = Vec::new();
3345 let mut page_count = 0;
3346 let max_pages = 50;
3347
3348 while let Some(current_cursor) = cursor.take() {
3349 page_count += 1;
3350 if page_count > max_pages {
3351 tracing::warn!(
3352 pr_number,
3353 fetched = comments.len(),
3354 "stopping PR issue comment pagination after max page limit"
3355 );
3356 break;
3357 }
3358
3359 let (query, vars) =
3360 build_pr_issue_comments_page_query(owner, name, pr_number, ¤t_cursor);
3361 let resp = self.graphql_with_vars(&query, vars).await?;
3362 let comments_data = resp
3363 .pointer("/data/repository/pullRequest/comments")
3364 .ok_or_else(|| {
3365 anyhow::anyhow!(
3366 "missing /data/repository/pullRequest/comments in GraphQL response"
3367 )
3368 })?;
3369
3370 comments.extend(
3371 comments_data
3372 .get("nodes")
3373 .and_then(|v| v.as_array())
3374 .into_iter()
3375 .flatten()
3376 .filter_map(parse_graphql_issue_comment),
3377 );
3378
3379 cursor = connection_end_cursor(comments_data.get("pageInfo"));
3380 }
3381
3382 Ok(comments)
3383 }
3384
3385 pub async fn get_automated_review_status(
3387 &self,
3388 repo: &str,
3389 pr_number: u64,
3390 ) -> anyhow::Result<Option<String>> {
3391 let comments = self.list_comments(repo, &pr_number.to_string()).await?;
3392
3393 let app_login = super::app::bot_login().await;
3395 let mut newest: Option<&types::GitHubComment> = None;
3396 for c in &comments {
3397 if !c.body.starts_with("## Automated Review") {
3398 continue;
3399 }
3400 let trusted = match app_login.as_deref() {
3401 Some(app) if super::app::same_login(&c.user.login, app) => Ok(true),
3402 _ => self.is_collaborator(repo, &c.user.login).await,
3403 };
3404 match trusted {
3405 Ok(true) => match newest {
3406 None => newest = Some(c),
3407 Some(prev) => {
3408 if c.created_at > prev.created_at {
3409 newest = Some(c);
3410 }
3411 }
3412 },
3413 Ok(false) => {
3414 tracing::warn!(
3415 user = %c.user.login,
3416 pr_number,
3417 "ignoring automated review comment from non-collaborator"
3418 );
3419 }
3420 Err(e) => {
3421 tracing::debug!(
3422 user = %c.user.login,
3423 error = %e,
3424 "failed to check collaborator status, skipping comment"
3425 );
3426 }
3427 }
3428 }
3429
3430 match newest {
3431 Some(c) => {
3432 let first_line = c.body.lines().next().unwrap_or("");
3433 if first_line.contains("Automated Review \u{2014} Approve") {
3434 Ok(Some("approve".to_string()))
3435 } else if first_line.contains("Automated Review \u{2014} Changes Requested") {
3436 Ok(Some("changes_requested".to_string()))
3437 } else {
3438 Ok(None)
3439 }
3440 }
3441 None => Ok(None),
3442 }
3443 }
3444}
3445
3446#[derive(Debug, Default, PartialEq)]
3452pub struct CommitMeta {
3453 pub parents: Vec<String>,
3454 pub author_login: Option<String>,
3455 pub committer_login: Option<String>,
3456}
3457
3458fn parse_commit_meta(commit: &serde_json::Value) -> CommitMeta {
3459 let login = |field: &str| {
3460 commit
3461 .pointer(&format!("/{field}/login"))
3462 .and_then(|v| v.as_str())
3463 .map(String::from)
3464 };
3465 CommitMeta {
3466 parents: commit
3467 .get("parents")
3468 .and_then(|p| p.as_array())
3469 .map(|parents| {
3470 parents
3471 .iter()
3472 .filter_map(|p| p.get("sha").and_then(|s| s.as_str()).map(String::from))
3473 .collect()
3474 })
3475 .unwrap_or_default(),
3476 author_login: login("author"),
3477 committer_login: login("committer"),
3478 }
3479}
3480
3481fn parse_behind_by(body: &serde_json::Value) -> anyhow::Result<u64> {
3482 body.get("behind_by")
3483 .and_then(serde_json::Value::as_u64)
3484 .ok_or_else(|| anyhow::anyhow!("compare response has no numeric behind_by field"))
3485}
3486
3487fn is_no_branch_protection_error(err: &str) -> bool {
3490 err.contains("404")
3491 || (err.contains("403")
3492 && err.contains("Upgrade to GitHub Pro or make this repository public"))
3493}
3494
3495pub(crate) const REQUIRED_CHECK_RULESET_NAME: &str = "orch required checks";
3496
3497#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3498pub(crate) enum RulesetCreateKind {
3499 CheckNeverRun,
3500 NameTaken,
3501 Refused,
3502 Retryable,
3503 Other,
3504}
3505
3506pub(crate) fn required_check_ruleset_payload(checks: &[RequiredStatusCheck]) -> serde_json::Value {
3507 let required: Vec<serde_json::Value> = checks
3508 .iter()
3509 .map(|check| {
3510 if let Some(id) = check.integration_id {
3511 serde_json::json!({ "context": check.context, "integration_id": id })
3512 } else {
3513 serde_json::json!({ "context": check.context })
3514 }
3515 })
3516 .collect();
3517 serde_json::json!({
3518 "name": REQUIRED_CHECK_RULESET_NAME,
3519 "target": "branch",
3520 "enforcement": "active",
3521 "conditions": {
3522 "ref_name": {
3523 "include": ["~DEFAULT_BRANCH"],
3524 "exclude": []
3525 }
3526 },
3527 "rules": [{
3528 "type": "required_status_checks",
3529 "parameters": {
3530 "strict_required_status_checks_policy": true,
3531 "do_not_enforce_on_create": false,
3532 "required_status_checks": required
3533 }
3534 }]
3535 })
3536}
3537
3538pub(crate) fn classify_ruleset_create_error(err: &str) -> RulesetCreateKind {
3539 let lower = err.to_ascii_lowercase();
3540 if lower.contains("already been taken") || lower.contains("name already exists") {
3541 return RulesetCreateKind::NameTaken;
3542 }
3543 if lower.contains("not a valid check")
3544 || lower.contains("required to be present is not found")
3545 || (lower.contains("422") && lower.contains("status check") && lower.contains("not found"))
3546 {
3547 return RulesetCreateKind::CheckNeverRun;
3548 }
3549 if lower.contains("(500")
3550 || lower.contains("(502")
3551 || lower.contains("(503")
3552 || lower.contains("(504")
3553 {
3554 return RulesetCreateKind::Retryable;
3555 }
3556 if lower.contains("403")
3557 || lower.contains("401")
3558 || lower.contains("upgrade to github pro")
3559 || lower.contains("not accessible")
3560 {
3561 return RulesetCreateKind::Refused;
3562 }
3563 RulesetCreateKind::Other
3564}
3565
3566fn parse_classic_required_status_checks(value: &serde_json::Value) -> Vec<RequiredStatusCheck> {
3568 if let Some(checks) = value
3569 .pointer("/required_status_checks/checks")
3570 .and_then(|v| v.as_array())
3571 {
3572 let parsed: Vec<RequiredStatusCheck> =
3573 checks.iter().filter_map(parse_classic_check).collect();
3574 if !parsed.is_empty() {
3575 return parsed;
3576 }
3577 }
3578
3579 value
3580 .pointer("/required_status_checks/contexts")
3581 .and_then(|v| v.as_array())
3582 .map(|contexts| {
3583 contexts
3584 .iter()
3585 .filter_map(|context| {
3586 context.as_str().map(|s| RequiredStatusCheck {
3587 context: s.to_string(),
3588 integration_id: None,
3589 })
3590 })
3591 .collect()
3592 })
3593 .unwrap_or_default()
3594}
3595
3596fn parse_classic_check(check: &serde_json::Value) -> Option<RequiredStatusCheck> {
3597 let context = check.get("context")?.as_str()?.to_string();
3598 let integration_id = check
3599 .get("app_id")
3600 .and_then(serde_json::Value::as_i64)
3601 .filter(|&id| id > 0);
3602 Some(RequiredStatusCheck {
3603 context,
3604 integration_id,
3605 })
3606}
3607
3608fn parse_ruleset_required_status_checks(rules: &[serde_json::Value]) -> Vec<RequiredStatusCheck> {
3610 let mut out = Vec::new();
3611 for rule in rules {
3612 if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
3613 continue;
3614 }
3615 let Some(checks) = rule
3616 .pointer("/parameters/required_status_checks")
3617 .or_else(|| rule.get("required_status_checks"))
3618 .and_then(|v| v.as_array())
3619 else {
3620 continue;
3621 };
3622 for check in checks {
3623 let Some(context) = check.get("context").and_then(|v| v.as_str()) else {
3624 continue;
3625 };
3626 let integration_id = check
3627 .get("integration_id")
3628 .and_then(serde_json::Value::as_i64)
3629 .filter(|&id| id > 0);
3630 out.push(RequiredStatusCheck {
3631 context: context.to_string(),
3632 integration_id,
3633 });
3634 }
3635 }
3636 out
3637}
3638
3639fn merge_required_status_checks(
3640 mut checks: Vec<RequiredStatusCheck>,
3641 extra: Vec<RequiredStatusCheck>,
3642) -> Vec<RequiredStatusCheck> {
3643 checks.extend(extra);
3644 let mut seen = HashSet::new();
3645 checks.retain(|c| seen.insert((c.context.clone(), c.integration_id)));
3646 checks
3647}
3648
3649fn sanitize_github_issue_numbers(issue_numbers: &[u64]) -> (Vec<u64>, Vec<u64>) {
3650 let mut valid = Vec::with_capacity(issue_numbers.len());
3651 let mut invalid = Vec::new();
3652 for &issue_number in issue_numbers {
3653 if issue_number == 0 {
3654 invalid.push(issue_number);
3655 } else {
3656 valid.push(issue_number);
3657 }
3658 }
3659 (valid, invalid)
3660}
3661
3662#[derive(Debug, Clone)]
3666pub struct RateLimitMetrics {
3667 pub hits: u64,
3669 pub skipped_calls: u64,
3671 pub rest_remaining: Option<u32>,
3673 pub rest_reset_at: Option<u64>,
3675 pub graphql_remaining: Option<u32>,
3677 pub five_xx_hits: u64,
3679}
3680
3681pub fn rate_limit_metrics() -> RateLimitMetrics {
3683 let (rest_remaining, rest_reset_at) = REST_RATE_LIMIT
3684 .lock()
3685 .ok()
3686 .map_or((None, None), |rl| (rl.remaining, rl.reset_at));
3687 let graphql_remaining = GRAPHQL_RATE_LIMIT.lock().ok().and_then(|rl| rl.remaining);
3688 RateLimitMetrics {
3689 hits: METRIC_RATE_LIMIT_HITS.load(Ordering::Relaxed),
3690 skipped_calls: METRIC_PROACTIVE_THROTTLES.load(Ordering::Relaxed),
3691 rest_remaining,
3692 rest_reset_at,
3693 graphql_remaining,
3694 five_xx_hits: METRIC_5XX_HITS.load(Ordering::Relaxed),
3695 }
3696}
3697
3698fn parse_link_next(headers: &header::HeaderMap) -> Option<String> {
3702 let link = headers.get("link")?.to_str().ok()?;
3703 for part in link.split(',') {
3704 let part = part.trim();
3705 if part.contains("rel=\"next\"") {
3706 let start = part.find('<')? + 1;
3708 let end = part.find('>')?;
3709 if start >= end {
3710 return None;
3711 }
3712 return Some(part[start..end].to_string());
3713 }
3714 }
3715 None
3716}
3717
3718pub fn status_label_color(label: &str) -> &'static str {
3720 match label {
3721 "status:new" => "0e8a16",
3722 "status:routed" => "1d76db",
3723 "status:in_progress" => "fbca04",
3724 "status:done" => "6f42c1",
3725 "status:blocked" => "d73a4a",
3726 "status:in_review" => "0075ca",
3727 "status:approved" => "2ea44f",
3728 "status:needs_review" => "e4e669",
3729 "status:waiting" => "5319e7",
3730 _ => "c5def5",
3731 }
3732}
3733
3734#[derive(Debug, Clone, Default)]
3738pub struct PrReviewBatchData {
3739 pub merged: bool,
3741 pub head_sha: String,
3743 pub mergeable: Option<bool>,
3745 pub reviews: Vec<GitHubReview>,
3747 pub review_comments: Vec<GitHubReviewComment>,
3749 pub issue_comments: Vec<GitHubComment>,
3751}
3752
3753fn build_pr_review_alias(n: u64) -> String {
3756 format!(
3757 r"pr{n}: pullRequest(number: {n}) {{
3758 merged
3759 mergeable
3760 headRefOid
3761 reviews(first: 50) {{
3762 nodes {{
3763 databaseId
3764 author {{ login }}
3765 body
3766 state
3767 url
3768 submittedAt
3769 commit {{ oid }}
3770 }}
3771 pageInfo {{ hasNextPage }}
3772 }}
3773 reviewThreads(first: 50) {{
3774 nodes {{
3775 comments(first: 20) {{
3776 nodes {{
3777 databaseId
3778 author {{ login }}
3779 body
3780 path
3781 line
3782 originalLine
3783 commit {{ oid }}
3784 originalCommit {{ oid }}
3785 url
3786 createdAt
3787 updatedAt
3788 replyTo {{ databaseId }}
3789 diffHunk
3790 }}
3791 pageInfo {{ hasNextPage }}
3792 }}
3793 }}
3794 pageInfo {{ hasNextPage }}
3795 }}
3796 comments(first: 50) {{
3797 nodes {{
3798 databaseId
3799 author {{ login }}
3800 body
3801 createdAt
3802 updatedAt
3803 url
3804 }}
3805 pageInfo {{ hasNextPage endCursor }}
3806 }}
3807}}"
3808 )
3809}
3810
3811fn build_pr_issue_comments_page_query(
3812 owner: &str,
3813 name: &str,
3814 pr_number: u64,
3815 after_cursor: &str,
3816) -> (String, serde_json::Value) {
3817 let query = r"query($owner: String!, $name: String!, $number: Int!, $after: String!) {
3818 repository(owner: $owner, name: $name) {
3819 pullRequest(number: $number) {
3820 comments(first: 100, after: $after) {
3821 nodes {
3822 databaseId
3823 author { login }
3824 body
3825 createdAt
3826 updatedAt
3827 url
3828 }
3829 pageInfo { hasNextPage endCursor }
3830 }
3831 }
3832 }
3833}"
3834 .to_string();
3835 let vars = serde_json::json!({
3836 "owner": owner,
3837 "name": name,
3838 "number": pr_number,
3839 "after": after_cursor,
3840 });
3841 (query, vars)
3842}
3843
3844fn connection_has_next_page(page_info: Option<&serde_json::Value>) -> bool {
3845 page_info
3846 .and_then(|v| v.get("hasNextPage"))
3847 .and_then(serde_json::Value::as_bool)
3848 .unwrap_or(false)
3849}
3850
3851fn connection_end_cursor(page_info: Option<&serde_json::Value>) -> Option<String> {
3852 if !connection_has_next_page(page_info) {
3853 return None;
3854 }
3855
3856 page_info
3857 .and_then(|v| v.get("endCursor"))
3858 .and_then(|v| v.as_str())
3859 .map(str::to_owned)
3860}
3861
3862fn parse_graphql_review(node: &serde_json::Value) -> Option<GitHubReview> {
3863 Some(GitHubReview {
3864 id: node.get("databaseId").and_then(serde_json::Value::as_u64)?,
3865 user: GitHubUser {
3866 login: node
3867 .pointer("/author/login")
3868 .and_then(|v| v.as_str())?
3869 .to_string(),
3870 },
3871 body: node.get("body").and_then(|v| v.as_str()).map(String::from),
3872 state: node.get("state").and_then(|v| v.as_str())?.to_string(),
3873 html_url: node.get("url").and_then(|v| v.as_str()).map(String::from),
3874 submitted_at: node
3875 .get("submittedAt")
3876 .and_then(|v| v.as_str())
3877 .unwrap_or("")
3878 .to_string(),
3879 commit_id: node
3880 .pointer("/commit/oid")
3881 .and_then(|v| v.as_str())
3882 .map(String::from),
3883 })
3884}
3885
3886fn parse_graphql_review_comment(node: &serde_json::Value) -> Option<GitHubReviewComment> {
3887 Some(GitHubReviewComment {
3888 id: node.get("databaseId").and_then(serde_json::Value::as_u64)?,
3889 user: GitHubUser {
3890 login: node
3891 .pointer("/author/login")
3892 .and_then(|v| v.as_str())?
3893 .to_string(),
3894 },
3895 body: node.get("body").and_then(|v| v.as_str())?.to_string(),
3896 path: node
3897 .get("path")
3898 .and_then(|v| v.as_str())
3899 .unwrap_or("")
3900 .to_string(),
3901 line: node
3902 .get("line")
3903 .and_then(serde_json::Value::as_u64)
3904 .and_then(|v| u32::try_from(v).ok()),
3905 original_line: node
3906 .get("originalLine")
3907 .and_then(serde_json::Value::as_u64)
3908 .and_then(|v| u32::try_from(v).ok()),
3909 commit_id: node
3910 .pointer("/commit/oid")
3911 .and_then(|v| v.as_str())
3912 .unwrap_or("")
3913 .to_string(),
3914 original_commit_id: node
3915 .pointer("/originalCommit/oid")
3916 .and_then(|v| v.as_str())
3917 .unwrap_or("")
3918 .to_string(),
3919 html_url: node
3920 .get("url")
3921 .and_then(|v| v.as_str())
3922 .unwrap_or("")
3923 .to_string(),
3924 created_at: node
3925 .get("createdAt")
3926 .and_then(|v| v.as_str())
3927 .unwrap_or("")
3928 .to_string(),
3929 updated_at: node
3930 .get("updatedAt")
3931 .and_then(|v| v.as_str())
3932 .unwrap_or("")
3933 .to_string(),
3934 in_reply_to_id: node
3935 .pointer("/replyTo/databaseId")
3936 .and_then(serde_json::Value::as_u64),
3937 diff_hunk: node
3938 .get("diffHunk")
3939 .and_then(|v| v.as_str())
3940 .map(String::from),
3941 })
3942}
3943
3944fn parse_graphql_issue_comment(node: &serde_json::Value) -> Option<GitHubComment> {
3945 Some(GitHubComment {
3946 id: node.get("databaseId").and_then(serde_json::Value::as_u64)?,
3947 body: node.get("body").and_then(|v| v.as_str())?.to_string(),
3948 user: GitHubUser {
3949 login: node
3950 .pointer("/author/login")
3951 .and_then(|v| v.as_str())?
3952 .to_string(),
3953 },
3954 created_at: node
3955 .get("createdAt")
3956 .and_then(|v| v.as_str())
3957 .unwrap_or("")
3958 .to_string(),
3959 updated_at: node
3960 .get("updatedAt")
3961 .and_then(|v| v.as_str())
3962 .map(String::from),
3963 html_url: node.get("url").and_then(|v| v.as_str()).map(String::from),
3964 issue_url: None,
3965 author_association: None,
3966 })
3967}
3968
3969#[cfg(test)]
3970mod tests {
3971 mod leak_redaction;
3973
3974 use std::env;
3975
3976 use super::*;
3977 use crate::github::token::TokenResolver;
3978 use tokio::io::{AsyncReadExt, AsyncWriteExt};
3979 use tokio::net::TcpListener;
3980
3981 #[test]
3982 fn repo_from_url_names_the_repository_or_nothing() {
3983 let api = "https://api.github.com";
3984 assert_eq!(
3985 repo_from_url(&format!("{api}/repos/me/a/pulls/9")).as_deref(),
3986 Some("me/a")
3987 );
3988 assert_eq!(
3989 repo_from_url(&format!("{api}/repos/org/b?per_page=1")).as_deref(),
3990 Some("org/b")
3991 );
3992 assert_eq!(
3993 repo_from_url(&format!("{api}/repos/org/b")).as_deref(),
3994 Some("org/b")
3995 );
3996 assert_eq!(repo_from_url(&format!("{api}/graphql")), None);
3997 assert_eq!(repo_from_url(&format!("{api}/user")), None);
3998 assert_eq!(repo_from_url(&format!("{api}/repos/only-owner")), None);
3999 }
4000
4001 #[test]
4002 fn no_branch_protection_errors() {
4003 let free_plan = "GitHub API GET https://api.github.com/repos/o/r/branches/main/protection failed (403 Forbidden): {\"message\":\"Upgrade to GitHub Pro or make this repository public to enable this feature.\"}";
4004 assert!(is_no_branch_protection_error(free_plan));
4005 assert!(is_no_branch_protection_error(
4006 "failed (404 Not Found): {\"message\":\"Branch not protected\"}"
4007 ));
4008 assert!(!is_no_branch_protection_error(
4009 "failed (403 Forbidden): {\"message\":\"Resource not accessible\"}"
4010 ));
4011 }
4012
4013 #[test]
4014 fn required_check_ruleset_payload_targets_the_default_branch() {
4015 let payload = required_check_ruleset_payload(&[
4016 RequiredStatusCheck {
4017 context: "test".to_string(),
4018 integration_id: Some(15368),
4019 },
4020 RequiredStatusCheck {
4021 context: "lint".to_string(),
4022 integration_id: None,
4023 },
4024 ]);
4025 assert_eq!(payload["name"], REQUIRED_CHECK_RULESET_NAME);
4026 assert_eq!(payload["target"], "branch");
4027 assert_eq!(
4028 payload["conditions"]["ref_name"]["include"],
4029 serde_json::json!(["~DEFAULT_BRANCH"])
4030 );
4031 assert_eq!(
4032 payload["rules"][0]["parameters"]["strict_required_status_checks_policy"],
4033 true
4034 );
4035 assert_eq!(
4036 payload["rules"][0]["parameters"]["required_status_checks"],
4037 serde_json::json!([
4038 { "context": "test", "integration_id": 15368 },
4039 { "context": "lint" }
4040 ])
4041 );
4042 }
4043
4044 #[test]
4045 fn classify_ruleset_create_error_splits_retry_from_refuse() {
4046 assert_eq!(
4047 classify_ruleset_create_error(
4048 "GitHub API POST https://api.github.com/repos/o/r/rulesets failed (422 Unprocessable Entity): {\"message\":\"Name has already been taken\"}"
4049 ),
4050 RulesetCreateKind::NameTaken
4051 );
4052 assert_eq!(
4053 classify_ruleset_create_error(
4054 "failed (422 Unprocessable Entity): Status check required to be present is not found"
4055 ),
4056 RulesetCreateKind::CheckNeverRun
4057 );
4058 assert_eq!(
4059 classify_ruleset_create_error("failed (422): ci/test was not a valid check"),
4060 RulesetCreateKind::CheckNeverRun
4061 );
4062 assert_eq!(
4063 classify_ruleset_create_error(
4064 "GitHub API POST /rulesets failed (403 Forbidden): {\"message\":\"Upgrade to GitHub Pro or make this repository public to enable this feature.\"}"
4065 ),
4066 RulesetCreateKind::Refused
4067 );
4068 assert_eq!(
4069 classify_ruleset_create_error("failed (500 Internal Server Error): boom"),
4070 RulesetCreateKind::Retryable
4071 );
4072 }
4073
4074 #[test]
4075 fn parse_classic_required_status_checks_reads_checks_app_id() {
4076 let value = serde_json::json!({
4077 "required_status_checks": {
4078 "contexts": ["ci/test"],
4079 "checks": [{ "context": "ci/test", "app_id": 42 }]
4080 }
4081 });
4082 assert_eq!(
4083 parse_classic_required_status_checks(&value),
4084 vec![RequiredStatusCheck {
4085 context: "ci/test".to_string(),
4086 integration_id: Some(42),
4087 }]
4088 );
4089 }
4090
4091 #[test]
4092 fn parse_classic_required_status_checks_falls_back_to_contexts() {
4093 let value = serde_json::json!({
4094 "required_status_checks": {
4095 "contexts": ["ci/test", "lint"]
4096 }
4097 });
4098 assert_eq!(
4099 parse_classic_required_status_checks(&value),
4100 vec![
4101 RequiredStatusCheck {
4102 context: "ci/test".to_string(),
4103 integration_id: None,
4104 },
4105 RequiredStatusCheck {
4106 context: "lint".to_string(),
4107 integration_id: None,
4108 }
4109 ]
4110 );
4111 }
4112
4113 #[test]
4114 fn parse_classic_required_status_checks_empty_when_unprotected() {
4115 let checks = parse_classic_required_status_checks(&serde_json::json!({}));
4116 assert!(checks.is_empty(), "{checks:?}");
4117 }
4118
4119 #[test]
4120 fn parse_ruleset_required_status_checks_reads_integration_id() {
4121 let rules = vec![
4122 serde_json::json!({ "type": "pull_request" }),
4123 serde_json::json!({
4124 "type": "required_status_checks",
4125 "parameters": {
4126 "required_status_checks": [
4127 { "context": "ci/test", "integration_id": 42 },
4128 { "context": "lint" }
4129 ]
4130 }
4131 }),
4132 ];
4133 assert_eq!(
4134 parse_ruleset_required_status_checks(&rules),
4135 vec![
4136 RequiredStatusCheck {
4137 context: "ci/test".to_string(),
4138 integration_id: Some(42),
4139 },
4140 RequiredStatusCheck {
4141 context: "lint".to_string(),
4142 integration_id: None,
4143 }
4144 ]
4145 );
4146 }
4147
4148 #[test]
4149 fn parse_ruleset_required_status_checks_treats_zero_integration_id_as_any_app() {
4150 let rules = vec![serde_json::json!({
4151 "type": "required_status_checks",
4152 "parameters": {
4153 "required_status_checks": [{ "context": "ci/test", "integration_id": 0 }]
4154 }
4155 })];
4156 assert_eq!(
4157 parse_ruleset_required_status_checks(&rules),
4158 vec![RequiredStatusCheck {
4159 context: "ci/test".to_string(),
4160 integration_id: None,
4161 }]
4162 );
4163 }
4164
4165 #[test]
4166 fn merge_required_status_checks_dedupes_identical_pairs() {
4167 let classic = vec![RequiredStatusCheck {
4168 context: "ci/test".to_string(),
4169 integration_id: None,
4170 }];
4171 let ruleset = vec![
4172 RequiredStatusCheck {
4173 context: "ci/test".to_string(),
4174 integration_id: None,
4175 },
4176 RequiredStatusCheck {
4177 context: "ci/test".to_string(),
4178 integration_id: Some(42),
4179 },
4180 ];
4181 assert_eq!(
4182 merge_required_status_checks(classic, ruleset),
4183 vec![
4184 RequiredStatusCheck {
4185 context: "ci/test".to_string(),
4186 integration_id: None,
4187 },
4188 RequiredStatusCheck {
4189 context: "ci/test".to_string(),
4190 integration_id: Some(42),
4191 }
4192 ]
4193 );
4194 }
4195
4196 #[test]
4197 fn parse_commit_meta_reads_parents_in_order_and_logins() {
4198 let merge = serde_json::json!({
4199 "parents": [{"sha": "approved"}, {"sha": "base"}],
4200 "author": {"login": "owner"},
4201 "committer": {"login": "web-flow"},
4202 });
4203 let meta = parse_commit_meta(&merge);
4204 assert_eq!(meta.parents, vec!["approved", "base"]);
4205 assert_eq!(meta.author_login.as_deref(), Some("owner"));
4206 assert_eq!(meta.committer_login.as_deref(), Some("web-flow"));
4207 assert_eq!(
4208 parse_commit_meta(&serde_json::json!({})),
4209 CommitMeta::default()
4210 );
4211 }
4212
4213 #[test]
4214 fn parse_behind_by_reads_compare_status() {
4215 let behind = serde_json::json!({"status": "behind", "behind_by": 3, "ahead_by": 0});
4217 assert_eq!(parse_behind_by(&behind).unwrap(), 3);
4218 let diverged = serde_json::json!({"status": "diverged", "behind_by": 1, "ahead_by": 2});
4219 assert_eq!(parse_behind_by(&diverged).unwrap(), 1);
4220 let ahead = serde_json::json!({"status": "ahead", "behind_by": 0, "ahead_by": 2});
4221 assert_eq!(parse_behind_by(&ahead).unwrap(), 0);
4222 assert!(parse_behind_by(&serde_json::json!({"status": "ahead"})).is_err());
4224 }
4225
4226 async fn spawn_truncated_body_server(body_prefix: &'static str) -> String {
4227 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
4228 let addr = listener.local_addr().unwrap();
4229
4230 tokio::spawn(async move {
4231 let (mut socket, _) = listener.accept().await.unwrap();
4232 let mut buf = [0u8; 4096];
4233 let _ = socket.read(&mut buf).await;
4234
4235 let declared_len = body_prefix.len() + 32;
4236 let response = format!(
4237 "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {declared_len}\r\nconnection: close\r\n\r\n{body_prefix}"
4238 );
4239 socket.write_all(response.as_bytes()).await.unwrap();
4240 socket.shutdown().await.unwrap();
4241 });
4242
4243 format!("http://{addr}")
4244 }
4245
4246 #[test]
4247 fn merge_pr_body_pins_the_head_sha() {
4248 let sha = "0123456789abcdef0123456789abcdef01234567";
4249 let body = merge_pr_body(sha);
4250 assert_eq!(body["merge_method"], "squash");
4251 assert_eq!(body["sha"], sha);
4252 assert!(is_full_commit_sha(sha));
4253 assert!(!is_full_commit_sha("abc"));
4254 assert!(!is_full_commit_sha(""));
4255 }
4256
4257 fn test_client() -> GhHttp {
4258 GhHttp {
4259 client: reqwest::Client::new(),
4260 token_resolver: Arc::new(TokenResolver::default_env()),
4261 app: None,
4262 owner_only: false,
4263 cached_username: OnceLock::new(),
4264 api_base: None,
4265 }
4266 }
4267
4268 #[test]
4273 fn gh_http_new_returns_ok() {
4274 let result = GhHttp::new();
4275 assert!(
4276 result.is_ok(),
4277 "GhHttp::new() must not panic and must return Ok; got: {:?}",
4278 result.err()
4279 );
4280 }
4281
4282 #[test]
4283 fn batch_get_issue_states_query_includes_labels_pagination() {
4284 let issue_numbers = [1u64, 2, 3];
4285
4286 let aliases: String = issue_numbers
4287 .iter()
4288 .map(|n| {
4289 format!("issue{n}: issue(number: {n}) {{ state labels(first: 100) {{ nodes {{ name }} }} }}")
4290 })
4291 .collect::<Vec<_>>()
4292 .join(" ");
4293
4294 let query = format!(
4295 r"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) {{ {aliases} }} }}"
4296 );
4297 assert!(query.contains("$owner"));
4298 assert!(query.contains("$name"));
4299 assert!(query.contains("issue1: issue(number: 1)"));
4300 assert!(query.contains("issue3: issue(number: 3)"));
4301 assert!(query.contains("labels(first: 100)"));
4302 }
4303
4304 #[test]
4305 fn parse_positive_issue_number_accepts_positive_values() {
4306 assert_eq!(parse_positive_issue_number("42").unwrap(), 42);
4307 }
4308
4309 #[test]
4310 fn parse_positive_issue_number_rejects_zero() {
4311 let err = parse_positive_issue_number("0").unwrap_err().to_string();
4312 assert!(err.contains("invalid issue number: 0"));
4313 }
4314
4315 #[test]
4316 fn parse_positive_issue_number_rejects_internal_ids() {
4317 let err = parse_positive_issue_number("internal:5")
4318 .unwrap_err()
4319 .to_string();
4320 assert!(err.contains("invalid issue number: internal:5"));
4321 }
4322
4323 #[test]
4324 fn pr_review_batch_query_includes_page_info_for_nested_connections() {
4325 let query = build_pr_review_alias(42);
4326
4327 assert!(query.contains("reviews(first: 50)"));
4328 assert!(query.contains("reviews(first: 50) {\n nodes"));
4329 assert!(query.contains("pageInfo { hasNextPage }"));
4330 assert!(query.contains("reviewThreads(first: 50)"));
4331 assert!(query.contains("comments(first: 20)"));
4332 assert!(query.contains("pageInfo { hasNextPage endCursor }"));
4333 assert!(query.contains("updatedAt"));
4334 }
4335
4336 #[test]
4337 fn pr_issue_comments_page_query_uses_cursor_pagination() {
4338 let (query, vars) = build_pr_issue_comments_page_query("owner", "repo", 42, "cursor123");
4339
4340 assert!(query.contains("pullRequest(number: $number)"));
4341 assert!(query.contains("comments(first: 100, after: $after)"));
4342 assert!(query.contains("pageInfo { hasNextPage endCursor }"));
4343 assert!(query.contains("updatedAt"));
4344 assert_eq!(vars["owner"], "owner");
4345 assert_eq!(vars["name"], "repo");
4346 assert_eq!(vars["number"], 42);
4347 assert_eq!(vars["after"], "cursor123");
4348 }
4349
4350 #[test]
4351 fn connection_end_cursor_only_returns_cursor_when_more_pages_exist() {
4352 let page_info = serde_json::json!({
4353 "hasNextPage": true,
4354 "endCursor": "cursor123"
4355 });
4356 assert_eq!(
4357 connection_end_cursor(Some(&page_info)),
4358 Some("cursor123".to_string())
4359 );
4360
4361 let final_page = serde_json::json!({
4362 "hasNextPage": false,
4363 "endCursor": "cursor456"
4364 });
4365 assert_eq!(connection_end_cursor(Some(&final_page)), None);
4366 }
4367
4368 #[test]
4369 fn status_label_colors_match_bash_palette() {
4370 assert_eq!(status_label_color("status:new"), "0e8a16");
4371 assert_eq!(status_label_color("status:routed"), "1d76db");
4372 assert_eq!(status_label_color("status:in_progress"), "fbca04");
4373 assert_eq!(status_label_color("status:done"), "6f42c1");
4374 assert_eq!(status_label_color("status:blocked"), "d73a4a");
4375 assert_eq!(status_label_color("status:in_review"), "0075ca");
4376 assert_eq!(status_label_color("status:needs_review"), "e4e669");
4377 }
4378
4379 #[test]
4380 fn unknown_label_gets_default_color() {
4381 assert_eq!(status_label_color("agent:claude"), "c5def5");
4382 assert_eq!(status_label_color("enhancement"), "c5def5");
4383 assert_eq!(status_label_color(""), "c5def5");
4384 }
4385
4386 #[test]
4387 fn parse_link_next_finds_next_url() {
4388 let mut headers = header::HeaderMap::new();
4389 headers.insert(
4390 "link",
4391 "<https://api.github.com/repos/foo/bar/issues?page=2>; rel=\"next\", <https://api.github.com/repos/foo/bar/issues?page=5>; rel=\"last\""
4392 .parse()
4393 .unwrap(),
4394 );
4395 assert_eq!(
4396 parse_link_next(&headers),
4397 Some("https://api.github.com/repos/foo/bar/issues?page=2".to_string())
4398 );
4399 }
4400
4401 #[test]
4402 fn parse_link_next_none_when_no_next() {
4403 let mut headers = header::HeaderMap::new();
4404 headers.insert(
4405 "link",
4406 "<https://api.github.com/repos/foo/bar/issues?page=1>; rel=\"prev\""
4407 .parse()
4408 .unwrap(),
4409 );
4410 assert_eq!(parse_link_next(&headers), None);
4411 }
4412
4413 #[test]
4414 fn parse_link_next_none_when_missing() {
4415 let headers = header::HeaderMap::new();
4416 assert_eq!(parse_link_next(&headers), None);
4417 }
4418
4419 #[test]
4420 fn parse_link_next_none_when_malformed() {
4421 let mut headers = header::HeaderMap::new();
4422 headers.insert("link", "garbage; rel=\"next\"".parse().unwrap());
4424 assert_eq!(parse_link_next(&headers), None);
4425 }
4426
4427 #[test]
4428 fn parse_link_next_none_when_gt_before_lt() {
4429 let mut headers = header::HeaderMap::new();
4430 headers.insert("link", ">junk; rel=\"next\"; <url>".parse().unwrap());
4431 assert_eq!(parse_link_next(&headers), None); }
4433
4434 #[test]
4435 fn parse_link_next_none_when_empty_url() {
4436 let mut headers = header::HeaderMap::new();
4437 headers.insert("link", "<>; rel=\"next\"".parse().unwrap());
4438 assert_eq!(parse_link_next(&headers), None);
4439 }
4440
4441 fn make_rl(base_secs: u64, max_secs: u64) -> RateLimit {
4442 RateLimit {
4443 remaining: None,
4444 reset_at: None,
4445 backoff_until: None,
4446 backoff_delay: Duration::ZERO,
4447 backoff_base: Duration::from_secs(base_secs),
4448 backoff_max: Duration::from_secs(max_secs),
4449 throttle_threshold: 10,
4450 }
4451 }
4452
4453 #[test]
4454 fn rate_limit_inactive_by_default() {
4455 let rl = make_rl(30, 900);
4456 assert!(rl.is_active().is_none());
4457 }
4458
4459 #[test]
4460 fn rate_limit_backoff_activates() {
4461 let mut rl = make_rl(5, 60);
4462 rl.record_rate_limit();
4463 assert!(rl.is_active().is_some());
4464 assert_eq!(rl.backoff_delay, Duration::from_secs(5));
4465 }
4466
4467 #[test]
4468 fn rate_limit_backoff_doubles() {
4469 let mut rl = make_rl(5, 60);
4470 rl.record_rate_limit();
4471 assert_eq!(rl.backoff_delay, Duration::from_secs(5));
4472 rl.record_rate_limit();
4473 assert_eq!(rl.backoff_delay, Duration::from_secs(10));
4474 rl.record_rate_limit();
4475 assert_eq!(rl.backoff_delay, Duration::from_secs(20));
4476 }
4477
4478 #[test]
4479 fn rate_limit_backoff_caps_at_max() {
4480 let mut rl = make_rl(30, 60);
4481 rl.record_rate_limit(); rl.record_rate_limit(); rl.record_rate_limit(); assert_eq!(rl.backoff_delay, Duration::from_secs(60));
4485 }
4486
4487 #[test]
4488 fn rate_limit_success_resets() {
4489 let mut rl = make_rl(5, 60);
4490 rl.record_rate_limit();
4491 assert!(rl.is_active().is_some());
4492 rl.record_success();
4493 assert!(rl.is_active().is_none());
4494 assert_eq!(rl.backoff_delay, Duration::ZERO);
4495 }
4496
4497 #[test]
4498 fn page_cache_key_separates_types_and_queries() {
4499 let a = page_cache_key::<GitHubIssue>("/issues", Some(&[("state", "open")])).unwrap();
4500 let b = page_cache_key::<GitHubIssue>("/issues", Some(&[("state", "closed")])).unwrap();
4501 let c = page_cache_key::<serde_json::Value>("/issues", Some(&[("state", "open")])).unwrap();
4502 assert_ne!(a, b);
4503 assert_ne!(a, c);
4504 assert_eq!(
4505 a,
4506 page_cache_key::<GitHubIssue>("/issues", Some(&[("state", "open")])).unwrap()
4507 );
4508 }
4509
4510 #[test]
4512 fn page_cache_key_skips_since_filtered_requests() {
4513 assert!(
4514 page_cache_key::<GitHubIssue>(
4515 "/issues",
4516 Some(&[("state", "closed"), ("since", "2026-10-01T00:00:00Z")])
4517 )
4518 .is_none()
4519 );
4520 assert!(
4522 page_cache_key::<GitHubIssue>("/issues?since=2026-10-01T00:00:00Z&page=2", None)
4523 .is_none()
4524 );
4525 }
4526
4527 #[test]
4530 fn low_quota_fails_fast_instead_of_waiting_for_reset() {
4531 let mut rl = make_rl(30, 900);
4532 rl.remaining = Some(0);
4533 rl.reset_at = Some(
4534 SystemTime::now()
4535 .duration_since(std_time::UNIX_EPOCH)
4536 .unwrap()
4537 .as_secs()
4538 + 3600,
4539 );
4540 let cell = Mutex::new(rl);
4541
4542 let start = Instant::now();
4543 let err = check_rate_limit_backoff(&cell, "REST").unwrap_err();
4544 assert!(
4545 start.elapsed() < Duration::from_secs(1),
4546 "check blocked for {:?}",
4547 start.elapsed()
4548 );
4549 assert!(err.to_string().contains("rate-limited"), "{err}");
4550 }
4551
4552 #[test]
4554 fn healthy_quota_passes_the_check() {
4555 let mut rl = make_rl(30, 900);
4556 rl.remaining = Some(4000);
4557 rl.reset_at = Some(u64::MAX / 2);
4558 let cell = Mutex::new(rl);
4559 assert!(check_rate_limit_backoff(&cell, "REST").is_ok());
4560 }
4561
4562 #[test]
4563 fn rate_limit_proactive_pause() {
4564 let mut rl = make_rl(30, 900);
4565 rl.remaining = Some(0);
4567 let future_epoch = SystemTime::now()
4568 .duration_since(std_time::UNIX_EPOCH)
4569 .unwrap()
4570 .as_secs()
4571 + 60;
4572 rl.reset_at = Some(future_epoch);
4573 let pause = rl.is_active();
4574 assert!(pause.is_some());
4575 assert!(pause.unwrap().as_secs() <= 62);
4577 }
4578
4579 #[test]
4580 fn rate_limit_proactive_pause_threshold() {
4581 let mut rl = make_rl(30, 900);
4582 rl.remaining = Some(15);
4584 let future_epoch = SystemTime::now()
4585 .duration_since(std_time::UNIX_EPOCH)
4586 .unwrap()
4587 .as_secs()
4588 + 60;
4589 rl.reset_at = Some(future_epoch);
4590 assert!(rl.is_active().is_none());
4591
4592 rl.remaining = Some(5);
4594 assert!(rl.is_active().is_some());
4595 }
4596
4597 #[test]
4598 fn combined_status_state_treats_empty_checks_as_pending_when_workflows_exist() {
4599 assert_eq!(
4601 GhHttp::combined_status_state(0, 0, 0, true, None),
4602 "pending"
4603 );
4604 assert_eq!(
4606 GhHttp::combined_status_state(0, 0, 0, false, None),
4607 "success"
4608 );
4609 assert_eq!(
4611 GhHttp::combined_status_state(3, 1, 0, true, None),
4612 "failure"
4613 );
4614 assert_eq!(
4616 GhHttp::combined_status_state(0, 0, 0, true, Some("clean")),
4617 "success"
4618 );
4619 assert_eq!(
4621 GhHttp::combined_status_state(0, 0, 0, true, Some("dirty")),
4622 "pending"
4623 );
4624 }
4625
4626 #[test]
4627 fn batch_is_pr_merged_by_branch_errors_when_repository_data_missing() {
4628 let resp = serde_json::json!({
4629 "data": {},
4630 "errors": [{ "message": "Something went wrong" }],
4631 });
4632
4633 let err_text = GhHttp::parse_batch_pr_merged_response(&resp, &["branch".to_string()])
4634 .unwrap_err()
4635 .to_string();
4636 assert!(err_text.contains("missing /data/repository in GraphQL response"));
4637 assert!(err_text.contains("Something went wrong"));
4638 }
4639
4640 #[test]
4641 fn rate_limit_uses_reset_at_for_backoff() {
4642 let mut rl = make_rl(30, 900);
4643 let future_epoch = SystemTime::now()
4645 .duration_since(std_time::UNIX_EPOCH)
4646 .unwrap()
4647 .as_secs()
4648 + 45;
4649 rl.reset_at = Some(future_epoch);
4650 rl.record_rate_limit();
4651 assert!(rl.backoff_delay.as_secs() >= 45);
4653 assert!(rl.backoff_delay.as_secs() <= 47);
4654 }
4655
4656 #[tokio::test]
4657 async fn send_with_retries_propagates_make_req_error() {
4658 let guard = env::var_os("GH_TOKEN");
4659 unsafe { env::set_var("GH_TOKEN", "test_token") };
4661 let gh = test_client();
4662 let result = gh
4663 .send_with_retries(
4664 || Err(anyhow::anyhow!("simulated request clone failure")),
4665 false,
4666 )
4667 .await;
4668 assert!(result.is_err());
4669 let err = result.unwrap_err().to_string();
4670 assert_eq!(err, "simulated request clone failure");
4671 match guard {
4672 Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
4674 None => unsafe { env::remove_var("GH_TOKEN") },
4676 }
4677 }
4678
4679 #[tokio::test]
4685 async fn send_with_retries_transport_error_does_not_trip_5xx_breaker() {
4686 let guard = env::var_os("GH_TOKEN");
4687 unsafe { env::set_var("GH_TOKEN", "test_token") };
4689
4690 let addr = {
4694 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
4695 listener.local_addr().unwrap()
4696 };
4697 let url = format!("http://{addr}/");
4698
4699 let gh = test_client();
4700 let make_req = || Ok(gh.client.get(&url));
4701 let result = gh.send_with_retries(make_req, false).await;
4702
4703 assert!(result.is_err());
4704 assert!(
4705 !cooldown::is_agent_in_cooldown("github:5xx"),
4706 "transport error must not trip the github:5xx circuit breaker"
4707 );
4708 assert!(cooldown::cooldown_until("github:5xx").is_none());
4709
4710 match guard {
4711 Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
4713 None => unsafe { env::remove_var("GH_TOKEN") },
4715 }
4716 }
4717
4718 #[tokio::test]
4719 async fn post_json_raw_propagates_body_read_errors_on_success() {
4720 let guard = env::var_os("GH_TOKEN");
4721 unsafe { env::set_var("GH_TOKEN", "test_token") };
4723 let server_url = spawn_truncated_body_server("{").await;
4724 let gh = test_client();
4725
4726 let result = gh
4727 .post_json_raw(
4728 &format!("{server_url}/post"),
4729 &serde_json::json!({"ok": true}),
4730 )
4731 .await;
4732
4733 let err = result.unwrap_err().to_string();
4734 assert!(
4735 !err.contains("EOF while parsing a value"),
4736 "should surface the body read error, got: {err}"
4737 );
4738 assert!(
4739 err.contains("error decoding response body")
4740 || err.contains("request or response body error")
4741 || err.contains("end of file before message length reached"),
4742 "expected a transport/body read error, got: {err}"
4743 );
4744
4745 match guard {
4746 Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
4748 None => unsafe { env::remove_var("GH_TOKEN") },
4750 }
4751 }
4752
4753 #[tokio::test]
4754 async fn patch_json_raw_propagates_body_read_errors_on_success() {
4755 let guard = env::var_os("GH_TOKEN");
4756 unsafe { env::set_var("GH_TOKEN", "test_token") };
4758 let server_url = spawn_truncated_body_server("{").await;
4759 let gh = test_client();
4760
4761 let result = gh
4762 .patch_json_raw(
4763 &format!("{server_url}/patch"),
4764 &serde_json::json!({"ok": true}),
4765 )
4766 .await;
4767
4768 let err = result.unwrap_err().to_string();
4769 assert!(
4770 !err.contains("EOF while parsing a value"),
4771 "should surface the body read error, got: {err}"
4772 );
4773 assert!(
4774 err.contains("error decoding response body")
4775 || err.contains("request or response body error")
4776 || err.contains("end of file before message length reached"),
4777 "expected a transport/body read error, got: {err}"
4778 );
4779
4780 match guard {
4781 Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
4783 None => unsafe { env::remove_var("GH_TOKEN") },
4785 }
4786 }
4787
4788 #[tokio::test]
4789 async fn graphql_request_propagates_body_read_errors_on_success() {
4790 let guard = env::var_os("GH_TOKEN");
4791 unsafe { env::set_var("GH_TOKEN", "test_token") };
4793 let server_url = spawn_truncated_body_server("{").await;
4794 let gh = test_client();
4795 let query = "query { viewer { login } }";
4796
4797 let result = gh
4798 .graphql_request_to_url(
4799 &format!("{server_url}/graphql"),
4800 query,
4801 &[],
4802 Some(serde_json::json!({"k": "v"})),
4803 )
4804 .await;
4805
4806 let err = result.unwrap_err().to_string();
4807 assert!(
4808 !err.contains("EOF while parsing a value"),
4809 "should surface the body read error, got: {err}"
4810 );
4811 assert!(
4812 err.contains("error decoding response body")
4813 || err.contains("request or response body error")
4814 || err.contains("end of file before message length reached"),
4815 "expected a transport/body read error, got: {err}"
4816 );
4817
4818 match guard {
4819 Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
4821 None => unsafe { env::remove_var("GH_TOKEN") },
4823 }
4824 }
4825
4826 #[cfg(test)]
4829 mod pagination {
4830 use super::super::*;
4831 use crate::github::token::TokenResolver;
4832 use std::env;
4833 use std::ffi::OsString;
4834 use std::sync::Arc;
4835 use std::time;
4836 use std::time::SystemTime;
4837 use wiremock::matchers::{method, path};
4838 use wiremock::{Match, Mock, MockServer, Request, ResponseTemplate, matchers};
4839
4840 struct NotMatcher<M>(M);
4843
4844 impl<M: Match> Match for NotMatcher<M> {
4845 fn matches(&self, request: &Request) -> bool {
4846 !self.0.matches(request)
4847 }
4848 }
4849
4850 struct EnvVarGuard {
4851 key: &'static str,
4852 previous: Option<OsString>,
4853 }
4854
4855 impl EnvVarGuard {
4856 fn set(key: &'static str, value: &str) -> Self {
4857 let previous = env::var_os(key);
4858 unsafe { env::set_var(key, value) };
4860 Self { key, previous }
4861 }
4862 }
4863
4864 impl Drop for EnvVarGuard {
4865 fn drop(&mut self) {
4866 match self.previous.take() {
4867 Some(value) => unsafe { env::set_var(self.key, value) },
4869 None => unsafe { env::remove_var(self.key) },
4871 }
4872 }
4873 }
4874
4875 fn make_client() -> (GhHttp, EnvVarGuard) {
4878 let guard = EnvVarGuard::set("GH_TOKEN", "test_token");
4880 let client = GhHttp {
4881 client: reqwest::Client::new(),
4882 token_resolver: Arc::new(TokenResolver::default_env()),
4883 app: None,
4884 owner_only: false,
4885 cached_username: OnceLock::new(),
4886 api_base: None,
4887 };
4888 (client, guard)
4889 }
4890
4891 #[tokio::test]
4892 async fn get_all_pages_single_page() {
4893 let server = MockServer::start().await;
4894
4895 Mock::given(method("GET"))
4896 .and(path("/items"))
4897 .respond_with(
4898 ResponseTemplate::new(200)
4899 .set_body_json(serde_json::json!([{"id": 1}, {"id": 2}])),
4900 )
4901 .expect(1)
4902 .mount(&server)
4903 .await;
4904
4905 let (gh, _guard) = make_client();
4906 let url = format!("{}/items", server.uri());
4907 let result: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
4908
4909 assert_eq!(result.len(), 2);
4910 assert_eq!(result[0]["id"], 1);
4911 assert_eq!(result[1]["id"], 2);
4912 }
4913
4914 #[tokio::test]
4915 async fn get_all_pages_follows_link_next() {
4916 let server = MockServer::start().await;
4917
4918 Mock::given(method("GET"))
4920 .and(path("/items"))
4921 .respond_with(
4922 ResponseTemplate::new(200)
4923 .set_body_json(serde_json::json!([{"id": 1}]))
4924 .insert_header(
4925 "Link",
4926 format!("<{}/items/page2>; rel=\"next\"", server.uri()),
4927 ),
4928 )
4929 .expect(1)
4930 .mount(&server)
4931 .await;
4932
4933 Mock::given(method("GET"))
4935 .and(path("/items/page2"))
4936 .respond_with(
4937 ResponseTemplate::new(200)
4938 .set_body_json(serde_json::json!([{"id": 2}, {"id": 3}])),
4939 )
4940 .expect(1)
4941 .mount(&server)
4942 .await;
4943
4944 let (gh, _guard) = make_client();
4945 let url = format!("{}/items", server.uri());
4946 let result: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
4947
4948 assert_eq!(result.len(), 3);
4949 assert_eq!(result[0]["id"], 1);
4950 assert_eq!(result[1]["id"], 2);
4951 assert_eq!(result[2]["id"], 3);
4952 }
4953
4954 #[tokio::test]
4955 async fn get_all_pages_stops_when_link_header_absent_on_subsequent_page() {
4956 let server = MockServer::start().await;
4959
4960 Mock::given(method("GET"))
4961 .and(path("/items"))
4962 .respond_with(
4963 ResponseTemplate::new(200)
4964 .set_body_json(serde_json::json!([{"id": 1}]))
4965 .insert_header(
4966 "Link",
4967 format!("<{}/items/page2>; rel=\"next\"", server.uri()),
4968 ),
4969 )
4970 .expect(1)
4971 .mount(&server)
4972 .await;
4973
4974 Mock::given(method("GET"))
4976 .and(path("/items/page2"))
4977 .respond_with(
4978 ResponseTemplate::new(200).set_body_json(serde_json::json!([{"id": 2}])),
4979 )
4980 .expect(1)
4981 .mount(&server)
4982 .await;
4983
4984 let (gh, _guard) = make_client();
4985 let url = format!("{}/items", server.uri());
4986 let result: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
4987
4988 assert_eq!(result.len(), 2);
4990 }
4991
4992 #[tokio::test]
4993 async fn get_all_pages_stops_on_malformed_link_header() {
4994 let server = MockServer::start().await;
4997
4998 Mock::given(method("GET"))
4999 .and(path("/items"))
5000 .respond_with(
5001 ResponseTemplate::new(200)
5002 .set_body_json(serde_json::json!([{"id": 1}]))
5003 .insert_header("Link", "garbage; rel=\"next\""),
5004 )
5005 .expect(1)
5006 .mount(&server)
5007 .await;
5008
5009 let (gh, _guard) = make_client();
5010 let url = format!("{}/items", server.uri());
5011 let result: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
5012
5013 assert_eq!(result.len(), 1);
5015 }
5016
5017 #[tokio::test]
5018 async fn get_all_pages_returns_error_on_malformed_json_body() {
5019 let server = MockServer::start().await;
5020
5021 Mock::given(method("GET"))
5022 .and(path("/items"))
5023 .respond_with(ResponseTemplate::new(200).set_body_string("not valid json"))
5024 .expect(3)
5025 .mount(&server)
5026 .await;
5027
5028 let (gh, _guard) = make_client();
5029 let url = format!("{}/items", server.uri());
5030 let result = gh.get_all_pages::<serde_json::Value>(&url, &[]).await;
5031
5032 assert!(result.is_err());
5033 let err = result.unwrap_err().to_string();
5034 assert!(
5035 err.contains("JSON decode failed") || err.contains("expected ident"),
5036 "error should mention JSON decode or serde error: {err}"
5037 );
5038 }
5039
5040 struct GlobalStateGuard;
5045
5046 impl Drop for GlobalStateGuard {
5047 fn drop(&mut self) {
5048 if let Ok(mut rl) = REST_RATE_LIMIT.lock() {
5049 *rl = RateLimit::new();
5050 }
5051 if let Ok(mut cache) = PAGE_CACHE.lock() {
5052 cache.clear();
5053 }
5054 }
5055 }
5056
5057 #[tokio::test]
5058 async fn get_all_pages_replays_body_on_304() {
5059 let _reset = GlobalStateGuard;
5060 let server = MockServer::start().await;
5061
5062 Mock::given(method("GET"))
5064 .and(path("/issues"))
5065 .and(matchers::header_exists("authorization"))
5066 .and(NotMatcher(matchers::header_exists("if-none-match")))
5067 .respond_with(
5068 ResponseTemplate::new(200)
5069 .set_body_json(serde_json::json!([{"number": 1}]))
5070 .insert_header("ETag", "\"abc123\""),
5071 )
5072 .expect(1)
5073 .mount(&server)
5074 .await;
5075
5076 Mock::given(method("GET"))
5078 .and(path("/issues"))
5079 .and(matchers::header("if-none-match", "\"abc123\""))
5080 .respond_with(ResponseTemplate::new(304))
5081 .expect(1)
5082 .mount(&server)
5083 .await;
5084
5085 let (gh, _guard) = make_client();
5086 let url = format!("{}/issues", server.uri());
5087
5088 let first: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
5089 let second: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
5090
5091 assert_eq!(first, second);
5092 assert_eq!(second.len(), 1);
5093 assert_eq!(second[0]["number"], 1);
5094 }
5095
5096 #[tokio::test]
5097 async fn exhausted_quota_skips_further_calls_until_reset() {
5098 let _reset = GlobalStateGuard;
5099 let server = MockServer::start().await;
5100
5101 let reset_at = SystemTime::now()
5102 .duration_since(time::UNIX_EPOCH)
5103 .unwrap()
5104 .as_secs()
5105 + 600;
5106
5107 Mock::given(method("GET"))
5110 .and(path("/issues"))
5111 .respond_with(
5112 ResponseTemplate::new(200)
5113 .set_body_json(serde_json::json!([{"number": 1}]))
5114 .insert_header("x-ratelimit-remaining", "0")
5115 .insert_header("x-ratelimit-reset", reset_at.to_string().as_str()),
5116 )
5117 .expect(1)
5118 .mount(&server)
5119 .await;
5120
5121 let (gh, _guard) = make_client();
5122 let url = format!("{}/issues", server.uri());
5123
5124 let first: Vec<serde_json::Value> = gh.get_all_pages(&url, &[]).await.unwrap();
5125 assert_eq!(first.len(), 1);
5126
5127 let start = Instant::now();
5129 let err = gh
5130 .get_all_pages::<serde_json::Value>(&url, &[("state", "open")])
5131 .await
5132 .unwrap_err();
5133 assert!(
5134 start.elapsed() < Duration::from_secs(1),
5135 "call blocked for {:?} instead of failing fast",
5136 start.elapsed()
5137 );
5138 assert!(err.to_string().contains("rate-limited"), "{err}");
5139
5140 let m = rate_limit_metrics();
5142 assert_eq!(m.rest_remaining, Some(0));
5143 assert_eq!(m.rest_reset_at, Some(reset_at));
5144 assert!(GhHttp::is_rate_limited().is_some());
5145
5146 }
5148
5149 #[tokio::test]
5152 async fn get_all_pages_from_wrapper_single_page() {
5153 let server = MockServer::start().await;
5156
5157 Mock::given(method("GET"))
5158 .and(path("/check-runs"))
5159 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5160 "total_count": 2,
5161 "check_runs": [{"id": 1, "name": "build"}, {"id": 2, "name": "test"}]
5162 })))
5163 .expect(1)
5164 .mount(&server)
5165 .await;
5166
5167 let (gh, _guard) = make_client();
5168 let url = format!("{}/check-runs", server.uri());
5169 let result: Vec<serde_json::Value> = gh
5170 .get_all_pages_from_wrapper(&url, "check_runs")
5171 .await
5172 .unwrap();
5173
5174 assert_eq!(result.len(), 2);
5175 assert_eq!(result[0]["id"], 1);
5176 assert_eq!(result[1]["id"], 2);
5177 }
5178
5179 #[tokio::test]
5180 async fn get_all_pages_from_wrapper_follows_link_next() {
5181 let server = MockServer::start().await;
5183
5184 Mock::given(method("GET"))
5185 .and(path("/check-runs"))
5186 .respond_with(
5187 ResponseTemplate::new(200)
5188 .set_body_json(serde_json::json!({
5189 "total_count": 3,
5190 "check_runs": [{"id": 1, "name": "build"}]
5191 }))
5192 .insert_header(
5193 "Link",
5194 format!("<{}/check-runs/page2>; rel=\"next\"", server.uri()),
5195 ),
5196 )
5197 .expect(1)
5198 .mount(&server)
5199 .await;
5200
5201 Mock::given(method("GET"))
5202 .and(path("/check-runs/page2"))
5203 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5204 "total_count": 3,
5205 "check_runs": [{"id": 2, "name": "lint"}, {"id": 3, "name": "test"}]
5206 })))
5207 .expect(1)
5208 .mount(&server)
5209 .await;
5210
5211 let (gh, _guard) = make_client();
5212 let url = format!("{}/check-runs", server.uri());
5213 let result: Vec<serde_json::Value> = gh
5214 .get_all_pages_from_wrapper(&url, "check_runs")
5215 .await
5216 .unwrap();
5217
5218 assert_eq!(result.len(), 3);
5219 assert_eq!(result[0]["id"], 1);
5220 assert_eq!(result[1]["id"], 2);
5221 assert_eq!(result[2]["id"], 3);
5222 }
5223
5224 #[tokio::test]
5225 async fn get_all_pages_from_wrapper_empty_field_returns_empty_vec() {
5226 let server = MockServer::start().await;
5229
5230 Mock::given(method("GET"))
5231 .and(path("/check-runs"))
5232 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5233 "total_count": 0,
5234 "check_runs": []
5235 })))
5236 .expect(1)
5237 .mount(&server)
5238 .await;
5239
5240 let (gh, _guard) = make_client();
5241 let url = format!("{}/check-runs", server.uri());
5242 let result: Vec<serde_json::Value> = gh
5243 .get_all_pages_from_wrapper(&url, "check_runs")
5244 .await
5245 .unwrap();
5246
5247 assert_eq!(result.len(), 0);
5248 }
5249
5250 #[tokio::test]
5251 async fn get_all_pages_from_wrapper_error_on_non_success_status() {
5252 let server = MockServer::start().await;
5253
5254 Mock::given(method("GET"))
5255 .and(path("/check-runs"))
5256 .respond_with(ResponseTemplate::new(422).set_body_string("Unprocessable Entity"))
5257 .expect(1)
5258 .mount(&server)
5259 .await;
5260
5261 let (gh, _guard) = make_client();
5262 let url = format!("{}/check-runs", server.uri());
5263 let result = gh
5264 .get_all_pages_from_wrapper::<serde_json::Value>(&url, "check_runs")
5265 .await;
5266
5267 assert!(result.is_err());
5268 let err = result.unwrap_err().to_string();
5269 assert!(
5270 err.contains("422") || err.contains("failed"),
5271 "error should indicate failure: {err}"
5272 );
5273 }
5274 }
5275
5276 #[cfg(test)]
5279 mod auth_retry {
5280 use super::test_client;
5281 use crate::github::token;
5282 use std::env;
5283 use std::sync::Arc;
5284 use std::sync::atomic::{AtomicUsize, Ordering};
5285 use wiremock::matchers::method;
5286 use wiremock::{Mock, MockServer, Request, ResponseTemplate};
5287
5288 fn bad_credentials() -> ResponseTemplate {
5289 ResponseTemplate::new(401).set_body_json(serde_json::json!({
5290 "message": "Bad credentials",
5291 "status": 401
5292 }))
5293 }
5294
5295 #[expect(
5296 clippy::await_holding_lock,
5297 reason = "the env lock stays held across the awaits so tests do not race on GH_TOKEN"
5298 )]
5299 #[tokio::test]
5300 async fn retries_once_with_fresh_token_after_401() {
5301 let _env_guard = token::ENV_LOCK.lock().unwrap();
5302 let prev = env::var_os("GH_TOKEN");
5303 unsafe { env::set_var("GH_TOKEN", "bad_token") };
5305
5306 let server = MockServer::start().await;
5307 let hits = Arc::new(AtomicUsize::new(0));
5308 let hits_in_handler = Arc::clone(&hits);
5309 Mock::given(method("GET"))
5310 .respond_with(move |_req: &Request| {
5311 if hits_in_handler.fetch_add(1, Ordering::SeqCst) == 0 {
5312 unsafe { env::set_var("GH_TOKEN", "good_token") };
5316 bad_credentials()
5317 } else {
5318 ResponseTemplate::new(200).set_body_json(serde_json::json!({ "ok": true }))
5319 }
5320 })
5321 .mount(&server)
5322 .await;
5323
5324 let gh = test_client();
5325 let result: anyhow::Result<serde_json::Value> =
5326 gh.get_json(&format!("{}/x", server.uri())).await;
5327
5328 match prev {
5329 Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
5331 None => unsafe { env::remove_var("GH_TOKEN") },
5333 }
5334
5335 assert!(
5336 result.is_ok(),
5337 "retry with re-resolved token should succeed: {:?}",
5338 result.err()
5339 );
5340 assert_eq!(hits.load(Ordering::SeqCst), 2, "exactly one retry expected");
5341 }
5342
5343 #[expect(
5344 clippy::await_holding_lock,
5345 reason = "the env lock stays held across the awaits so tests do not race on GH_TOKEN"
5346 )]
5347 #[tokio::test]
5348 async fn double_401_bails_with_distinct_auth_error() {
5349 let _env_guard = token::ENV_LOCK.lock().unwrap();
5350 let prev = env::var_os("GH_TOKEN");
5351 unsafe { env::set_var("GH_TOKEN", "bad_token") };
5353
5354 let server = MockServer::start().await;
5355 let hits = Arc::new(AtomicUsize::new(0));
5356 let hits_in_handler = Arc::clone(&hits);
5357 Mock::given(method("GET"))
5358 .respond_with(move |_req: &Request| {
5359 hits_in_handler.fetch_add(1, Ordering::SeqCst);
5360 bad_credentials()
5361 })
5362 .mount(&server)
5363 .await;
5364
5365 let gh = test_client();
5366 let result: anyhow::Result<serde_json::Value> =
5367 gh.get_json(&format!("{}/x", server.uri())).await;
5368
5369 match prev {
5370 Some(v) => unsafe { env::set_var("GH_TOKEN", v) },
5372 None => unsafe { env::remove_var("GH_TOKEN") },
5374 }
5375
5376 let err = result.expect_err("persisting 401 must fail").to_string();
5377 assert!(
5378 err.contains("token re-resolved after cache clear but still rejected"),
5379 "expected distinct auth-failure error, got: {err}"
5380 );
5381 assert_eq!(
5382 hits.load(Ordering::SeqCst),
5383 2,
5384 "must retry exactly once, not loop"
5385 );
5386 }
5387 }
5388
5389 #[cfg(test)]
5390 mod contents_and_rulesets {
5391 use super::super::*;
5392 use std::env;
5393 use std::ffi::OsString;
5394 use wiremock::matchers::{method, path, query_param};
5395 use wiremock::{Mock, MockServer, ResponseTemplate};
5396
5397 struct EnvVarGuard {
5398 key: &'static str,
5399 previous: Option<OsString>,
5400 }
5401
5402 impl EnvVarGuard {
5403 fn set(key: &'static str, value: &str) -> Self {
5404 let previous = env::var_os(key);
5405 unsafe { env::set_var(key, value) };
5407 Self { key, previous }
5408 }
5409 }
5410
5411 impl Drop for EnvVarGuard {
5412 fn drop(&mut self) {
5413 match self.previous.take() {
5414 Some(value) => unsafe { env::set_var(self.key, value) },
5416 None => unsafe { env::remove_var(self.key) },
5418 }
5419 }
5420 }
5421
5422 fn client(server: &MockServer) -> (GhHttp, EnvVarGuard) {
5423 let guard = EnvVarGuard::set("GH_TOKEN", "test_token");
5424 (GhHttp::for_test(server.uri(), None), guard)
5425 }
5426
5427 #[tokio::test]
5428 async fn has_workflow_on_branch_is_false_when_the_directory_is_missing() {
5429 let server = MockServer::start().await;
5430 Mock::given(method("GET"))
5431 .and(path("/repos/o/r/contents/.github/workflows"))
5432 .and(query_param("ref", "main"))
5433 .respond_with(ResponseTemplate::new(404).set_body_string("Not Found"))
5434 .mount(&server)
5435 .await;
5436 let (gh, _guard) = client(&server);
5437 assert!(!gh.has_workflow_on_branch("o/r", "main").await.unwrap());
5438 }
5439
5440 #[tokio::test]
5441 async fn has_workflow_on_branch_is_true_when_a_yaml_file_exists() {
5442 let server = MockServer::start().await;
5443 Mock::given(method("GET"))
5444 .and(path("/repos/o/r/contents/.github/workflows"))
5445 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
5446 { "name": "ci.yml", "type": "file" }
5447 ])))
5448 .mount(&server)
5449 .await;
5450 let (gh, _guard) = client(&server);
5451 assert!(gh.has_workflow_on_branch("o/r", "main").await.unwrap());
5452 }
5453
5454 #[tokio::test]
5455 async fn has_file_on_branch_is_false_on_404() {
5456 let server = MockServer::start().await;
5457 Mock::given(method("GET"))
5458 .and(path("/repos/o/r/contents/shipcheck.toml"))
5459 .respond_with(ResponseTemplate::new(404).set_body_string("Not Found"))
5460 .mount(&server)
5461 .await;
5462 let (gh, _guard) = client(&server);
5463 assert!(
5464 !gh.has_file_on_branch("o/r", "shipcheck.toml", "main")
5465 .await
5466 .unwrap()
5467 );
5468 }
5469
5470 #[tokio::test]
5471 async fn create_required_check_ruleset_posts_the_payload() {
5472 let server = MockServer::start().await;
5473 Mock::given(method("POST"))
5474 .and(path("/repos/o/r/rulesets"))
5475 .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
5476 "id": 1,
5477 "name": REQUIRED_CHECK_RULESET_NAME
5478 })))
5479 .expect(1)
5480 .mount(&server)
5481 .await;
5482 let (gh, _guard) = client(&server);
5483 gh.create_required_check_ruleset(
5484 "o/r",
5485 &[RequiredStatusCheck {
5486 context: "test".to_string(),
5487 integration_id: Some(15368),
5488 }],
5489 )
5490 .await
5491 .unwrap();
5492 }
5493
5494 #[tokio::test]
5495 async fn get_branch_sha_reads_commit_sha() {
5496 let server = MockServer::start().await;
5497 Mock::given(method("GET"))
5498 .and(path("/repos/o/r/branches/main"))
5499 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
5500 "name": "main",
5501 "commit": { "sha": "abc123" }
5502 })))
5503 .mount(&server)
5504 .await;
5505 let (gh, _guard) = client(&server);
5506 assert_eq!(gh.get_branch_sha("o/r", "main").await.unwrap(), "abc123");
5507 }
5508 }
5509}