1use super::{GITHUB_API, GhHttp, has_status};
4use crate::github::app;
5use crate::github::types;
6use crate::github::types::is_own_check;
7use crate::github::types::{GitHubAnnotation, GitHubCheckRun, RequiredStatusCheck};
8use crate::github::types::{merge_missing_checks, required_contexts_cover};
9use reqwest::header;
10use std::collections::HashSet;
11use std::fmt::Debug;
12use std::path::Path;
13use urlencoding;
14
15impl GhHttp {
16 pub(crate) async fn apply_required_check_ruleset(
19 &self,
20 repo: &str,
21 checks: &[RequiredStatusCheck],
22 ) -> anyhow::Result<RulesetApply> {
23 let err = match self.create_required_check_ruleset(repo, checks).await {
24 Ok(()) => return Ok(RulesetApply::Applied),
25 Err(e) => e.to_string(),
26 };
27 let kind = classify_ruleset_create_error(&err);
28 if !matches!(kind, RulesetCreateKind::NameTaken) {
29 return Ok(RulesetApply::Failed { err, kind });
30 }
31 let Some((id, existing)) = self
32 .get_named_ruleset_required_checks(repo, REQUIRED_CHECK_RULESET_NAME)
33 .await?
34 else {
35 return Ok(RulesetApply::NameTakenNotFound);
36 };
37 if required_contexts_cover(&existing, checks) {
38 return Ok(RulesetApply::Applied);
39 }
40 let merged = merge_missing_checks(existing, checks);
41 match self.update_required_check_ruleset(repo, id, &merged).await {
42 Ok(()) => Ok(RulesetApply::Applied),
43 Err(e) => {
44 let err = e.to_string();
45 let kind = classify_ruleset_create_error(&err);
46 Ok(RulesetApply::Failed { err, kind })
47 }
48 }
49 }
50
51 pub async fn post_commit_status(
53 &self,
54 repo: &str,
55 sha: &str,
56 state: &str,
57 context: &str,
58 description: &str,
59 ) -> anyhow::Result<()> {
60 let url = format!("{GITHUB_API}/repos/{repo}/statuses/{sha}");
61 let payload = serde_json::json!({
62 "state": state,
63 "context": context,
64 "description": description,
65 });
66 self.post_json_raw(&url, &payload).await?;
67 Ok(())
68 }
69
70 pub async fn get_required_status_check_contexts(
72 &self,
73 repo: &str,
74 branch: &str,
75 ) -> anyhow::Result<Vec<RequiredStatusCheck>> {
76 let branch = urlencoding::encode(branch);
77 let classic_url = format!(
78 "{}/repos/{repo}/branches/{branch}/protection",
79 self.api_root()
80 );
81 let rules_url = format!("{}/repos/{repo}/rules/branches/{branch}", self.api_root());
82
83 let classic_fut = self.get_json::<serde_json::Value>(&classic_url);
84 let rules_fut = self.get_all_pages::<serde_json::Value>(&rules_url, &[("per_page", "100")]);
85 let (classic_resp, rules_resp) = tokio::join!(classic_fut, rules_fut);
86
87 let classic = match classic_resp {
88 Ok(value) => parse_classic_required_status_checks(&value),
89 Err(e) => {
90 if is_no_branch_protection_error(&e.to_string()) {
91 Vec::new()
92 } else {
93 return Err(e);
94 }
95 }
96 };
97
98 let ruleset = match rules_resp {
99 Ok(rules) => parse_ruleset_required_status_checks(&rules),
100 Err(e) => {
101 if has_status(&e.to_string(), 404) {
102 Vec::new()
103 } else {
104 return Err(e);
105 }
106 }
107 };
108
109 Ok(merge_required_status_checks(classic, ruleset))
110 }
111
112 pub async fn get_commit_status_contexts(
114 &self,
115 repo: &str,
116 sha: &str,
117 ) -> anyhow::Result<Vec<(String, String)>> {
118 let url = format!(
119 "{}/repos/{repo}/commits/{sha}/status?per_page=100",
120 self.api_root()
121 );
122 let statuses: Vec<serde_json::Value> =
127 self.get_all_pages_from_wrapper(&url, "statuses").await?;
128
129 Ok(statuses
130 .into_iter()
131 .filter_map(|status| {
132 let context = status.get("context").and_then(|v| v.as_str())?;
133 let state = status.get("state").and_then(|v| v.as_str())?;
134 Some((context.to_string(), state.to_string()))
135 })
136 .collect())
137 }
138
139 pub(super) fn combined_status_state(
140 total: u64,
141 failing: u64,
142 pending: u64,
143 has_workflows: bool,
144 mergeable_state: Option<&str>,
145 ) -> String {
146 if failing > 0 {
147 "failure".to_string()
148 } else if pending > 0 {
149 "pending".to_string()
150 } else if total == 0 && has_workflows {
151 if mergeable_state == Some("clean") {
155 "success".to_string()
156 } else {
157 "pending".to_string()
158 }
159 } else {
160 "success".to_string()
161 }
162 }
163
164 pub async fn has_workflows(&self, repo: &str) -> anyhow::Result<bool> {
169 let url = format!("{GITHUB_API}/repos/{repo}/actions/workflows?per_page=1");
170 let resp = self.get_json::<serde_json::Value>(&url).await;
171 match resp {
172 Ok(value) => Ok(value
173 .get("workflows")
174 .and_then(|v| v.as_array())
175 .is_some_and(|workflows| !workflows.is_empty())),
176 Err(e) => {
177 let err = e.to_string();
178 if has_status(&err, 404) {
179 Ok(false)
180 } else {
181 Err(e)
182 }
183 }
184 }
185 }
186
187 pub async fn has_workflow_on_branch(&self, repo: &str, branch: &str) -> anyhow::Result<bool> {
189 let branch = urlencoding::encode(branch);
190 let url = format!(
191 "{}/repos/{repo}/contents/.github/workflows?ref={branch}",
192 self.api_root()
193 );
194 match self.get_json::<serde_json::Value>(&url).await {
195 Ok(value) => Ok(value.as_array().is_some_and(|entries| {
196 entries.iter().any(|entry| {
197 entry
198 .get("name")
199 .and_then(|name| name.as_str())
200 .is_some_and(|name| {
201 Path::new(name)
202 .extension()
203 .and_then(|ext| ext.to_str())
204 .is_some_and(|ext| {
205 ext.eq_ignore_ascii_case("yml")
206 || ext.eq_ignore_ascii_case("yaml")
207 })
208 })
209 })
210 })),
211 Err(e) => {
212 let err = e.to_string();
213 if has_status(&err, 404) {
214 Ok(false)
215 } else {
216 Err(e)
217 }
218 }
219 }
220 }
221
222 pub async fn has_file_on_branch(
224 &self,
225 repo: &str,
226 path: &str,
227 branch: &str,
228 ) -> anyhow::Result<bool> {
229 let path = path
230 .split('/')
231 .map(|segment| urlencoding::encode(segment).into_owned())
232 .collect::<Vec<_>>()
233 .join("/");
234 let branch = urlencoding::encode(branch);
235 let url = format!(
236 "{}/repos/{repo}/contents/{path}?ref={branch}",
237 self.api_root()
238 );
239 match self.get_json::<serde_json::Value>(&url).await {
240 Ok(_) => Ok(true),
241 Err(e) => {
242 let err = e.to_string();
243 if has_status(&err, 404) {
244 Ok(false)
245 } else {
246 Err(e)
247 }
248 }
249 }
250 }
251
252 pub async fn create_required_check_ruleset(
254 &self,
255 repo: &str,
256 checks: &[RequiredStatusCheck],
257 ) -> anyhow::Result<()> {
258 let url = format!("{}/repos/{repo}/rulesets", self.api_root());
259 let payload = required_check_ruleset_payload(checks);
260 self.post_json_raw(&url, &payload).await?;
261 Ok(())
262 }
263
264 pub async fn get_named_ruleset_required_checks(
266 &self,
267 repo: &str,
268 name: &str,
269 ) -> anyhow::Result<Option<(i64, Vec<RequiredStatusCheck>)>> {
270 let url = format!("{}/repos/{repo}/rulesets", self.api_root());
271 let rulesets: Vec<serde_json::Value> =
272 self.get_all_pages(&url, &[("per_page", "100")]).await?;
273 let Some(id) = rulesets.iter().find_map(|ruleset| {
274 if ruleset.get("name").and_then(|n| n.as_str()) != Some(name) {
275 return None;
276 }
277 ruleset.get("id").and_then(serde_json::Value::as_i64)
278 }) else {
279 return Ok(None);
280 };
281 let url = format!("{}/repos/{repo}/rulesets/{id}", self.api_root());
282 let value: serde_json::Value = self.get_json(&url).await?;
283 let rules = value
284 .get("rules")
285 .and_then(|r| r.as_array())
286 .cloned()
287 .unwrap_or_default();
288 Ok(Some((id, parse_ruleset_required_status_checks(&rules))))
289 }
290
291 pub async fn update_required_check_ruleset(
293 &self,
294 repo: &str,
295 ruleset_id: i64,
296 checks: &[RequiredStatusCheck],
297 ) -> anyhow::Result<()> {
298 let url = format!("{}/repos/{repo}/rulesets/{ruleset_id}", self.api_root());
299 let payload = required_check_ruleset_payload(checks);
300 self.put_json_raw(&url, &payload).await?;
301 Ok(())
302 }
303
304 pub async fn get_check_runs(
306 &self,
307 repo: &str,
308 sha: &str,
309 ) -> anyhow::Result<Vec<GitHubCheckRun>> {
310 let url = format!(
321 "{}/repos/{repo}/commits/{sha}/check-runs?filter=latest&per_page=100",
322 self.api_root()
323 );
324 self.get_all_pages_from_wrapper(&url, "check_runs").await
325 }
326
327 pub async fn get_check_run_annotations(
334 &self,
335 repo: &str,
336 check_run_id: u64,
337 ) -> anyhow::Result<Vec<GitHubAnnotation>> {
338 let url = format!("{GITHUB_API}/repos/{repo}/check-runs/{check_run_id}/annotations");
339 self.get_all_pages(&url, &[("per_page", "100")]).await
340 }
341
342 pub async fn get_job_log_tail(
344 &self,
345 repo: &str,
346 job_id: u64,
347 lines: usize,
348 ) -> anyhow::Result<String> {
349 let url = format!("{GITHUB_API}/repos/{repo}/actions/jobs/{job_id}/logs");
350 let bytes = self.get_bytes(&url).await?;
351 let text = String::from_utf8_lossy(&bytes);
352 let all: Vec<&str> = text.lines().collect();
353 let start = all.len().saturating_sub(lines);
354 Ok(all[start..].join("\n"))
355 }
356
357 pub async fn get_combined_status(
362 &self,
363 repo: &str,
364 git_ref: &str,
365 has_workflows: bool,
366 mergeable_state: Option<&str>,
367 ) -> anyhow::Result<(String, u64, u64, u64, u64)> {
368 let runs = self.get_check_runs(repo, git_ref).await?;
369 let (total, passing, failing, pending) = Self::count_ci_runs(&runs);
370 let state =
371 Self::combined_status_state(total, failing, pending, has_workflows, mergeable_state);
372
373 Ok((state, total, passing, failing, pending))
374 }
375
376 pub(super) fn count_ci_runs(runs: &[types::GitHubCheckRun]) -> (u64, u64, u64, u64) {
378 let mut total = 0u64;
379 let mut passing = 0u64;
380 let mut failing = 0u64;
381 let mut pending = 0u64;
382
383 for run in runs.iter().filter(|r| !is_own_check(&r.name)) {
384 total += 1;
385 if !run.is_finished() {
386 pending += 1;
387 } else if run.is_passed() {
388 passing += 1;
389 } else {
390 failing += 1;
391 }
392 }
393
394 (total, passing, failing, pending)
395 }
396
397 pub async fn rerun_failed_workflow(
403 &self,
404 repo: &str,
405 workflow_name: &str,
406 branch: &str,
407 ) -> anyhow::Result<()> {
408 let url = format!(
410 "{GITHUB_API}/repos/{repo}/actions/runs?branch={branch}&event=push&per_page=10"
411 );
412 let resp: serde_json::Value = self.get_json(&url).await?;
413 let runs = resp["workflow_runs"]
414 .as_array()
415 .ok_or_else(|| anyhow::anyhow!("no workflow_runs array in response"))?;
416
417 let run_id = runs
419 .iter()
420 .find(|r| {
421 r["name"].as_str() == Some(workflow_name)
422 && matches!(r["conclusion"].as_str(), Some("failure" | "cancelled"))
423 })
424 .and_then(|r| r["id"].as_u64())
425 .ok_or_else(|| {
426 anyhow::anyhow!(
427 "no failed run found for workflow '{workflow_name}' on branch '{branch}'"
428 )
429 })?;
430
431 let rerun_url = format!("{GITHUB_API}/repos/{repo}/actions/runs/{run_id}/rerun");
433 let auth = self.auth_header(&rerun_url).await?;
434 let make_req = || {
435 Ok(self
436 .client
437 .post(&rerun_url)
438 .header(header::AUTHORIZATION, auth.clone())
439 .header(header::ACCEPT, "application/vnd.github+json")
440 .header("X-GitHub-Api-Version", "2022-11-28"))
441 };
442 let resp = self.send_with_retries(make_req, false).await?;
443 let status = resp.status();
444 if !status.is_success() {
445 let body = resp.text().await.unwrap_or_default();
446 Self::maybe_record_rate_limit_from_body(status, &body);
447 anyhow::bail!("GitHub API POST rerun {rerun_url} failed ({status}): {body}");
448 }
449
450 Ok(())
451 }
452
453 pub async fn get_automated_review_status(
455 &self,
456 repo: &str,
457 pr_number: u64,
458 ) -> anyhow::Result<Option<String>> {
459 let comments = self.list_comments(repo, &pr_number.to_string()).await?;
460
461 let app_login = app::bot_login().await;
463 let mut newest: Option<&types::GitHubComment> = None;
464 for c in &comments {
465 if !c.body.starts_with("## Automated Review") {
466 continue;
467 }
468 let trusted = match app_login.as_deref() {
469 Some(app) if app::same_login(&c.user.login, app) => Ok(true),
470 _ => self.is_collaborator(repo, &c.user.login).await,
471 };
472 match trusted {
473 Ok(true) => match newest {
474 None => newest = Some(c),
475 Some(prev) => {
476 if c.created_at > prev.created_at {
477 newest = Some(c);
478 }
479 }
480 },
481 Ok(false) => {
482 tracing::warn!(
483 user = %c.user.login,
484 pr_number,
485 "ignoring automated review comment from non-collaborator"
486 );
487 }
488 Err(e) => {
489 tracing::debug!(
490 user = %c.user.login,
491 error = %e,
492 "failed to check collaborator status, skipping comment"
493 );
494 }
495 }
496 }
497
498 match newest {
499 Some(c) => {
500 let first_line = c.body.lines().next().unwrap_or("");
501 if first_line.contains("Automated Review \u{2014} Approve") {
502 Ok(Some("approve".to_string()))
503 } else if first_line.contains("Automated Review \u{2014} Changes Requested") {
504 Ok(Some("changes_requested".to_string()))
505 } else {
506 Ok(None)
507 }
508 }
509 None => Ok(None),
510 }
511 }
512}
513
514pub(super) fn is_no_branch_protection_error(err: &str) -> bool {
516 has_status(err, 404)
517 || (err.contains("403")
518 && err.contains("Upgrade to GitHub Pro or make this repository public"))
519}
520
521pub(crate) const REQUIRED_CHECK_RULESET_NAME: &str = "orch required checks";
522
523#[derive(Debug)]
525pub(crate) enum RulesetApply {
526 Applied,
528 NameTakenNotFound,
530 Failed {
532 err: String,
533 kind: RulesetCreateKind,
534 },
535}
536
537#[derive(Debug, Clone, Copy, PartialEq, Eq)]
538pub(crate) enum RulesetCreateKind {
539 CheckNeverRun,
540 NameTaken,
541 Refused,
542 Retryable,
543 Other,
544}
545
546pub(crate) fn required_check_ruleset_payload(checks: &[RequiredStatusCheck]) -> serde_json::Value {
547 let required: Vec<serde_json::Value> = checks
548 .iter()
549 .map(|check| {
550 if let Some(id) = check.integration_id {
551 serde_json::json!({ "context": check.context, "integration_id": id })
552 } else {
553 serde_json::json!({ "context": check.context })
554 }
555 })
556 .collect();
557 serde_json::json!({
558 "name": REQUIRED_CHECK_RULESET_NAME,
559 "target": "branch",
560 "enforcement": "active",
561 "conditions": {
562 "ref_name": {
563 "include": ["~DEFAULT_BRANCH"],
564 "exclude": []
565 }
566 },
567 "rules": [{
568 "type": "required_status_checks",
569 "parameters": {
570 "strict_required_status_checks_policy": true,
571 "do_not_enforce_on_create": false,
572 "required_status_checks": required
573 }
574 }]
575 })
576}
577
578pub(crate) fn classify_ruleset_create_error(err: &str) -> RulesetCreateKind {
579 let lower = err.to_ascii_lowercase();
580 if lower.contains("already been taken") || lower.contains("name already exists") {
581 return RulesetCreateKind::NameTaken;
582 }
583 if lower.contains("not a valid check")
584 || lower.contains("required to be present is not found")
585 || (lower.contains("422") && lower.contains("status check") && lower.contains("not found"))
586 {
587 return RulesetCreateKind::CheckNeverRun;
588 }
589 if lower.contains("(500")
590 || lower.contains("(502")
591 || lower.contains("(503")
592 || lower.contains("(504")
593 || lower.contains("(429")
594 {
595 return RulesetCreateKind::Retryable;
596 }
597 if lower.contains("(403")
599 || lower.contains("(401")
600 || lower.contains("upgrade to github pro")
601 || lower.contains("not accessible")
602 {
603 return RulesetCreateKind::Refused;
604 }
605 if !has_http_status_token(&lower) {
607 return RulesetCreateKind::Retryable;
608 }
609 RulesetCreateKind::Other
610}
611
612fn has_http_status_token(err: &str) -> bool {
613 err.match_indices('(').any(|(i, _)| {
614 err.as_bytes()
615 .get(i + 1..i + 4)
616 .is_some_and(|digits| digits.iter().all(u8::is_ascii_digit))
617 })
618}
619
620pub(super) fn parse_classic_required_status_checks(
622 value: &serde_json::Value,
623) -> Vec<RequiredStatusCheck> {
624 if let Some(checks) = value
625 .pointer("/required_status_checks/checks")
626 .and_then(|v| v.as_array())
627 {
628 let parsed: Vec<RequiredStatusCheck> =
629 checks.iter().filter_map(parse_classic_check).collect();
630 if !parsed.is_empty() {
631 return parsed;
632 }
633 }
634
635 value
636 .pointer("/required_status_checks/contexts")
637 .and_then(|v| v.as_array())
638 .map(|contexts| {
639 contexts
640 .iter()
641 .filter_map(|context| {
642 context.as_str().map(|s| RequiredStatusCheck {
643 context: s.to_string(),
644 integration_id: None,
645 })
646 })
647 .collect()
648 })
649 .unwrap_or_default()
650}
651
652fn parse_classic_check(check: &serde_json::Value) -> Option<RequiredStatusCheck> {
653 let context = check.get("context")?.as_str()?.to_string();
654 let integration_id = check
655 .get("app_id")
656 .and_then(serde_json::Value::as_i64)
657 .filter(|&id| id > 0);
658 Some(RequiredStatusCheck {
659 context,
660 integration_id,
661 })
662}
663
664pub(super) fn parse_ruleset_required_status_checks(
666 rules: &[serde_json::Value],
667) -> Vec<RequiredStatusCheck> {
668 let mut out = Vec::new();
669 for rule in rules {
670 if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
671 continue;
672 }
673 let Some(checks) = rule
674 .pointer("/parameters/required_status_checks")
675 .or_else(|| rule.get("required_status_checks"))
676 .and_then(|v| v.as_array())
677 else {
678 continue;
679 };
680 for check in checks {
681 let Some(context) = check.get("context").and_then(|v| v.as_str()) else {
682 continue;
683 };
684 let integration_id = check
685 .get("integration_id")
686 .and_then(serde_json::Value::as_i64)
687 .filter(|&id| id > 0);
688 out.push(RequiredStatusCheck {
689 context: context.to_string(),
690 integration_id,
691 });
692 }
693 }
694 out
695}
696
697pub(super) fn merge_required_status_checks(
698 mut checks: Vec<RequiredStatusCheck>,
699 extra: Vec<RequiredStatusCheck>,
700) -> Vec<RequiredStatusCheck> {
701 checks.extend(extra);
702 let mut seen = HashSet::new();
703 checks.retain(|c| seen.insert((c.context.clone(), c.integration_id)));
704 checks
705}