Skip to main content

orch/github/http/
checks.rs

1//! Status check, ruleset, check run and workflow calls
2
3use 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    /// Create orch's required-check ruleset. When a ruleset already has the name, add the checks
17    /// it lacks to that one instead
18    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    /// Post a commit status. `state` is one of pending, success, failure, error.
52    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    /// Required status checks for a branch from classic protection and from rulesets
71    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    /// Get commit status contexts for a SHA.
113    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        // The /commits/{sha}/status endpoint returns a wrapper object:
123        // { "state": "pending", "total_count": N, "statuses": [...] }
124        // Use get_all_pages_from_wrapper to follow pagination and extract the
125        // `statuses` array across pages so we don't silently truncate at 100.
126        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            // No check runs yet. If GitHub already reports mergeable_state="clean"
152            // the PR is ready (e.g. all workflows use paths-ignore and skipped this
153            // commit). Treating it as pending would stall auto-merge forever.
154            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    /// Return `true` when the repository has at least one GitHub Actions workflow.
165    ///
166    /// This is used to distinguish repos that genuinely have no CI configured from
167    /// repos where CI exists but GitHub has not surfaced any runs yet.
168    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    /// True when `.github/workflows` on `branch` has at least one YAML file
188    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    /// True when `path` exists on `branch`
223    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    /// Create a repository ruleset that requires `checks` on the default branch
253    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    /// Id and required checks of the repository ruleset named `name`, if it exists
265    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    /// Replace the required checks on an existing repository ruleset
292    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    /// Get check runs for a PR head SHA.
305    pub async fn get_check_runs(
306        &self,
307        repo: &str,
308        sha: &str,
309    ) -> anyhow::Result<Vec<GitHubCheckRun>> {
310        // Use `filter=latest` so GitHub returns only the most recent check run
311        // per check name. Without this, the API returns all runs (oldest
312        // first) and callers that pick the first match may observe a stale
313        // failed run when a newer run with the same name has succeeded.
314        //
315        // Use `per_page=100` and manual pagination via `get_all_pages_from_wrapper`
316        // because this endpoint returns a *wrapper object* — `{ "total_count": N,
317        // "check_runs": [...] }` — rather than a raw JSON array.  `get_all_pages`
318        // cannot be used here because it calls `serde_json::from_str::<Vec<T>>`
319        // which would fail on an object body.
320        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    /// Get annotations for a specific check run.
328    ///
329    /// Returns the list of annotations attached to the check run, including
330    /// billing failure messages ("The job was not started because recent account
331    /// payments have failed …") that GitHub surfaces as annotations rather than
332    /// as a distinct CI conclusion value.
333    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    /// Last `lines` lines of the log of an Actions job. A check run id is the job id
343    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    /// Get combined CI check status for a git ref
358    ///
359    /// Counts come from [`Self::get_check_runs`], which requests `filter=latest`
360    /// and follows pagination, so a failure or in-progress run past the first page still counts
361    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    /// Count CI runs as (total, passing, failing, pending), skipping the review's own checks
377    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    /// Rerun the latest failed workflow run for a given workflow name and branch.
398    ///
399    /// Finds the most recent failed (or cancelled) run of `workflow_name` on
400    /// `branch` triggered by a `push` event, then calls the GitHub Actions
401    /// rerun endpoint so the **same check run** on the commit flips green.
402    pub async fn rerun_failed_workflow(
403        &self,
404        repo: &str,
405        workflow_name: &str,
406        branch: &str,
407    ) -> anyhow::Result<()> {
408        // List recent runs for this branch, filtered to push events
409        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        // Find the latest failed/cancelled run matching the workflow name
418        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        // POST rerun — no body needed
432        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    /// Check the latest automated review comment on a PR.
454    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        // Find the most recent automated review comment authored by a collaborator or the App
462        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
514/// GitHub returns for private repos on the Free plan
515pub(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/// What applying orch's required-check ruleset came to
524#[derive(Debug)]
525pub(crate) enum RulesetApply {
526    /// The ruleset requires every needed check
527    Applied,
528    /// A ruleset has the name but none was found by it
529    NameTakenNotFound,
530    /// GitHub refused the write, `kind` says why
531    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    // "(401" / "(403" is the status token, a 422 body can contain those digits
598    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    // timeout and transport errors never include an HTTP status
606    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
620/// Classic protection prefers `checks` (includes `app_id`) and falls back to `contexts`
621pub(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
664/// Collect `required_status_checks` entries from every active `required_status_checks` rule
665pub(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}