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 reqwest::header;
9use std::collections::HashSet;
10use std::fmt::Debug;
11use std::path::Path;
12use urlencoding;
13
14impl GhHttp {
15    /// Post a commit status. `state` is one of pending, success, failure, error.
16    pub async fn post_commit_status(
17        &self,
18        repo: &str,
19        sha: &str,
20        state: &str,
21        context: &str,
22        description: &str,
23    ) -> anyhow::Result<()> {
24        let url = format!("{GITHUB_API}/repos/{repo}/statuses/{sha}");
25        let payload = serde_json::json!({
26            "state": state,
27            "context": context,
28            "description": description,
29        });
30        self.post_json_raw(&url, &payload).await?;
31        Ok(())
32    }
33
34    /// Required status checks for a branch from classic protection and from rulesets
35    pub async fn get_required_status_check_contexts(
36        &self,
37        repo: &str,
38        branch: &str,
39    ) -> anyhow::Result<Vec<RequiredStatusCheck>> {
40        let branch = urlencoding::encode(branch);
41        let classic_url = format!(
42            "{}/repos/{repo}/branches/{branch}/protection",
43            self.api_root()
44        );
45        let rules_url = format!("{}/repos/{repo}/rules/branches/{branch}", self.api_root());
46
47        let classic_fut = self.get_json::<serde_json::Value>(&classic_url);
48        let rules_fut = self.get_all_pages::<serde_json::Value>(&rules_url, &[("per_page", "100")]);
49        let (classic_resp, rules_resp) = tokio::join!(classic_fut, rules_fut);
50
51        let classic = match classic_resp {
52            Ok(value) => parse_classic_required_status_checks(&value),
53            Err(e) => {
54                if is_no_branch_protection_error(&e.to_string()) {
55                    Vec::new()
56                } else {
57                    return Err(e);
58                }
59            }
60        };
61
62        let ruleset = match rules_resp {
63            Ok(rules) => parse_ruleset_required_status_checks(&rules),
64            Err(e) => {
65                if has_status(&e.to_string(), 404) {
66                    Vec::new()
67                } else {
68                    return Err(e);
69                }
70            }
71        };
72
73        Ok(merge_required_status_checks(classic, ruleset))
74    }
75
76    /// Get commit status contexts for a SHA.
77    pub async fn get_commit_status_contexts(
78        &self,
79        repo: &str,
80        sha: &str,
81    ) -> anyhow::Result<Vec<(String, String)>> {
82        let url = format!(
83            "{}/repos/{repo}/commits/{sha}/status?per_page=100",
84            self.api_root()
85        );
86        // The /commits/{sha}/status endpoint returns a wrapper object:
87        // { "state": "pending", "total_count": N, "statuses": [...] }
88        // Use get_all_pages_from_wrapper to follow pagination and extract the
89        // `statuses` array across pages so we don't silently truncate at 100.
90        let statuses: Vec<serde_json::Value> =
91            self.get_all_pages_from_wrapper(&url, "statuses").await?;
92
93        Ok(statuses
94            .into_iter()
95            .filter_map(|status| {
96                let context = status.get("context").and_then(|v| v.as_str())?;
97                let state = status.get("state").and_then(|v| v.as_str())?;
98                Some((context.to_string(), state.to_string()))
99            })
100            .collect())
101    }
102
103    pub(super) fn combined_status_state(
104        total: u64,
105        failing: u64,
106        pending: u64,
107        has_workflows: bool,
108        mergeable_state: Option<&str>,
109    ) -> String {
110        if failing > 0 {
111            "failure".to_string()
112        } else if pending > 0 {
113            "pending".to_string()
114        } else if total == 0 && has_workflows {
115            // No check runs yet. If GitHub already reports mergeable_state="clean"
116            // the PR is ready (e.g. all workflows use paths-ignore and skipped this
117            // commit). Treating it as pending would stall auto-merge forever.
118            if mergeable_state == Some("clean") {
119                "success".to_string()
120            } else {
121                "pending".to_string()
122            }
123        } else {
124            "success".to_string()
125        }
126    }
127
128    /// Return `true` when the repository has at least one GitHub Actions workflow.
129    ///
130    /// This is used to distinguish repos that genuinely have no CI configured from
131    /// repos where CI exists but GitHub has not surfaced any runs yet.
132    pub async fn has_workflows(&self, repo: &str) -> anyhow::Result<bool> {
133        let url = format!("{GITHUB_API}/repos/{repo}/actions/workflows?per_page=1");
134        let resp = self.get_json::<serde_json::Value>(&url).await;
135        match resp {
136            Ok(value) => Ok(value
137                .get("workflows")
138                .and_then(|v| v.as_array())
139                .is_some_and(|workflows| !workflows.is_empty())),
140            Err(e) => {
141                let err = e.to_string();
142                if has_status(&err, 404) {
143                    Ok(false)
144                } else {
145                    Err(e)
146                }
147            }
148        }
149    }
150
151    /// True when `.github/workflows` on `branch` has at least one YAML file
152    pub async fn has_workflow_on_branch(&self, repo: &str, branch: &str) -> anyhow::Result<bool> {
153        let branch = urlencoding::encode(branch);
154        let url = format!(
155            "{}/repos/{repo}/contents/.github/workflows?ref={branch}",
156            self.api_root()
157        );
158        match self.get_json::<serde_json::Value>(&url).await {
159            Ok(value) => Ok(value.as_array().is_some_and(|entries| {
160                entries.iter().any(|entry| {
161                    entry
162                        .get("name")
163                        .and_then(|name| name.as_str())
164                        .is_some_and(|name| {
165                            Path::new(name)
166                                .extension()
167                                .and_then(|ext| ext.to_str())
168                                .is_some_and(|ext| {
169                                    ext.eq_ignore_ascii_case("yml")
170                                        || ext.eq_ignore_ascii_case("yaml")
171                                })
172                        })
173                })
174            })),
175            Err(e) => {
176                let err = e.to_string();
177                if has_status(&err, 404) {
178                    Ok(false)
179                } else {
180                    Err(e)
181                }
182            }
183        }
184    }
185
186    /// True when `path` exists on `branch`
187    pub async fn has_file_on_branch(
188        &self,
189        repo: &str,
190        path: &str,
191        branch: &str,
192    ) -> anyhow::Result<bool> {
193        let path = path
194            .split('/')
195            .map(|segment| urlencoding::encode(segment).into_owned())
196            .collect::<Vec<_>>()
197            .join("/");
198        let branch = urlencoding::encode(branch);
199        let url = format!(
200            "{}/repos/{repo}/contents/{path}?ref={branch}",
201            self.api_root()
202        );
203        match self.get_json::<serde_json::Value>(&url).await {
204            Ok(_) => Ok(true),
205            Err(e) => {
206                let err = e.to_string();
207                if has_status(&err, 404) {
208                    Ok(false)
209                } else {
210                    Err(e)
211                }
212            }
213        }
214    }
215
216    /// Create a repository ruleset that requires `checks` on the default branch
217    pub async fn create_required_check_ruleset(
218        &self,
219        repo: &str,
220        checks: &[RequiredStatusCheck],
221    ) -> anyhow::Result<()> {
222        let url = format!("{}/repos/{repo}/rulesets", self.api_root());
223        let payload = required_check_ruleset_payload(checks);
224        self.post_json_raw(&url, &payload).await?;
225        Ok(())
226    }
227
228    /// Id and required checks of the repository ruleset named `name`, if it exists
229    pub async fn get_named_ruleset_required_checks(
230        &self,
231        repo: &str,
232        name: &str,
233    ) -> anyhow::Result<Option<(i64, Vec<RequiredStatusCheck>)>> {
234        let url = format!("{}/repos/{repo}/rulesets", self.api_root());
235        let rulesets: Vec<serde_json::Value> =
236            self.get_all_pages(&url, &[("per_page", "100")]).await?;
237        let Some(id) = rulesets.iter().find_map(|ruleset| {
238            if ruleset.get("name").and_then(|n| n.as_str()) != Some(name) {
239                return None;
240            }
241            ruleset.get("id").and_then(serde_json::Value::as_i64)
242        }) else {
243            return Ok(None);
244        };
245        let url = format!("{}/repos/{repo}/rulesets/{id}", self.api_root());
246        let value: serde_json::Value = self.get_json(&url).await?;
247        let rules = value
248            .get("rules")
249            .and_then(|r| r.as_array())
250            .cloned()
251            .unwrap_or_default();
252        Ok(Some((id, parse_ruleset_required_status_checks(&rules))))
253    }
254
255    /// Replace the required checks on an existing repository ruleset
256    pub async fn update_required_check_ruleset(
257        &self,
258        repo: &str,
259        ruleset_id: i64,
260        checks: &[RequiredStatusCheck],
261    ) -> anyhow::Result<()> {
262        let url = format!("{}/repos/{repo}/rulesets/{ruleset_id}", self.api_root());
263        let payload = required_check_ruleset_payload(checks);
264        self.put_json_raw(&url, &payload).await?;
265        Ok(())
266    }
267
268    /// Get check runs for a PR head SHA.
269    pub async fn get_check_runs(
270        &self,
271        repo: &str,
272        sha: &str,
273    ) -> anyhow::Result<Vec<GitHubCheckRun>> {
274        // Use `filter=latest` so GitHub returns only the most recent check run
275        // per check name. Without this, the API returns all runs (oldest
276        // first) and callers that pick the first match may observe a stale
277        // failed run when a newer run with the same name has succeeded.
278        //
279        // Use `per_page=100` and manual pagination via `get_all_pages_from_wrapper`
280        // because this endpoint returns a *wrapper object* — `{ "total_count": N,
281        // "check_runs": [...] }` — rather than a raw JSON array.  `get_all_pages`
282        // cannot be used here because it calls `serde_json::from_str::<Vec<T>>`
283        // which would fail on an object body.
284        let url = format!(
285            "{}/repos/{repo}/commits/{sha}/check-runs?filter=latest&per_page=100",
286            self.api_root()
287        );
288        self.get_all_pages_from_wrapper(&url, "check_runs").await
289    }
290
291    /// Get annotations for a specific check run.
292    ///
293    /// Returns the list of annotations attached to the check run, including
294    /// billing failure messages ("The job was not started because recent account
295    /// payments have failed …") that GitHub surfaces as annotations rather than
296    /// as a distinct CI conclusion value.
297    pub async fn get_check_run_annotations(
298        &self,
299        repo: &str,
300        check_run_id: u64,
301    ) -> anyhow::Result<Vec<GitHubAnnotation>> {
302        let url = format!("{GITHUB_API}/repos/{repo}/check-runs/{check_run_id}/annotations");
303        self.get_all_pages(&url, &[("per_page", "100")]).await
304    }
305
306    /// Last `lines` lines of the log of an Actions job. A check run id is the job id
307    pub async fn get_job_log_tail(
308        &self,
309        repo: &str,
310        job_id: u64,
311        lines: usize,
312    ) -> anyhow::Result<String> {
313        let url = format!("{GITHUB_API}/repos/{repo}/actions/jobs/{job_id}/logs");
314        let bytes = self.get_bytes(&url).await?;
315        let text = String::from_utf8_lossy(&bytes);
316        let all: Vec<&str> = text.lines().collect();
317        let start = all.len().saturating_sub(lines);
318        Ok(all[start..].join("\n"))
319    }
320
321    /// Get combined CI check status for a git ref
322    ///
323    /// Counts come from [`Self::get_check_runs`], which requests `filter=latest`
324    /// and follows pagination, so a failure or in-progress run past the first page still counts
325    pub async fn get_combined_status(
326        &self,
327        repo: &str,
328        git_ref: &str,
329        has_workflows: bool,
330        mergeable_state: Option<&str>,
331    ) -> anyhow::Result<(String, u64, u64, u64, u64)> {
332        let runs = self.get_check_runs(repo, git_ref).await?;
333        let (total, passing, failing, pending) = Self::count_ci_runs(&runs);
334        let state =
335            Self::combined_status_state(total, failing, pending, has_workflows, mergeable_state);
336
337        Ok((state, total, passing, failing, pending))
338    }
339
340    /// Count CI runs as (total, passing, failing, pending), skipping the review's own checks
341    pub(super) fn count_ci_runs(runs: &[types::GitHubCheckRun]) -> (u64, u64, u64, u64) {
342        let mut total = 0u64;
343        let mut passing = 0u64;
344        let mut failing = 0u64;
345        let mut pending = 0u64;
346
347        for run in runs.iter().filter(|r| !is_own_check(&r.name)) {
348            total += 1;
349            if !run.is_finished() {
350                pending += 1;
351            } else if run.is_passed() {
352                passing += 1;
353            } else {
354                failing += 1;
355            }
356        }
357
358        (total, passing, failing, pending)
359    }
360
361    /// Rerun the latest failed workflow run for a given workflow name and branch.
362    ///
363    /// Finds the most recent failed (or cancelled) run of `workflow_name` on
364    /// `branch` triggered by a `push` event, then calls the GitHub Actions
365    /// rerun endpoint so the **same check run** on the commit flips green.
366    pub async fn rerun_failed_workflow(
367        &self,
368        repo: &str,
369        workflow_name: &str,
370        branch: &str,
371    ) -> anyhow::Result<()> {
372        // List recent runs for this branch, filtered to push events
373        let url = format!(
374            "{GITHUB_API}/repos/{repo}/actions/runs?branch={branch}&event=push&per_page=10"
375        );
376        let resp: serde_json::Value = self.get_json(&url).await?;
377        let runs = resp["workflow_runs"]
378            .as_array()
379            .ok_or_else(|| anyhow::anyhow!("no workflow_runs array in response"))?;
380
381        // Find the latest failed/cancelled run matching the workflow name
382        let run_id = runs
383            .iter()
384            .find(|r| {
385                r["name"].as_str() == Some(workflow_name)
386                    && matches!(r["conclusion"].as_str(), Some("failure" | "cancelled"))
387            })
388            .and_then(|r| r["id"].as_u64())
389            .ok_or_else(|| {
390                anyhow::anyhow!(
391                    "no failed run found for workflow '{workflow_name}' on branch '{branch}'"
392                )
393            })?;
394
395        // POST rerun — no body needed
396        let rerun_url = format!("{GITHUB_API}/repos/{repo}/actions/runs/{run_id}/rerun");
397        let auth = self.auth_header(&rerun_url).await?;
398        let make_req = || {
399            Ok(self
400                .client
401                .post(&rerun_url)
402                .header(header::AUTHORIZATION, auth.clone())
403                .header(header::ACCEPT, "application/vnd.github+json")
404                .header("X-GitHub-Api-Version", "2022-11-28"))
405        };
406        let resp = self.send_with_retries(make_req, false).await?;
407        let status = resp.status();
408        if !status.is_success() {
409            let body = resp.text().await.unwrap_or_default();
410            Self::maybe_record_rate_limit_from_body(status, &body);
411            anyhow::bail!("GitHub API POST rerun {rerun_url} failed ({status}): {body}");
412        }
413
414        Ok(())
415    }
416
417    /// Check the latest automated review comment on a PR.
418    pub async fn get_automated_review_status(
419        &self,
420        repo: &str,
421        pr_number: u64,
422    ) -> anyhow::Result<Option<String>> {
423        let comments = self.list_comments(repo, &pr_number.to_string()).await?;
424
425        // Find the most recent automated review comment authored by a collaborator or the App
426        let app_login = app::bot_login().await;
427        let mut newest: Option<&types::GitHubComment> = None;
428        for c in &comments {
429            if !c.body.starts_with("## Automated Review") {
430                continue;
431            }
432            let trusted = match app_login.as_deref() {
433                Some(app) if app::same_login(&c.user.login, app) => Ok(true),
434                _ => self.is_collaborator(repo, &c.user.login).await,
435            };
436            match trusted {
437                Ok(true) => match newest {
438                    None => newest = Some(c),
439                    Some(prev) => {
440                        if c.created_at > prev.created_at {
441                            newest = Some(c);
442                        }
443                    }
444                },
445                Ok(false) => {
446                    tracing::warn!(
447                        user = %c.user.login,
448                        pr_number,
449                        "ignoring automated review comment from non-collaborator"
450                    );
451                }
452                Err(e) => {
453                    tracing::debug!(
454                        user = %c.user.login,
455                        error = %e,
456                        "failed to check collaborator status, skipping comment"
457                    );
458                }
459            }
460        }
461
462        match newest {
463            Some(c) => {
464                let first_line = c.body.lines().next().unwrap_or("");
465                if first_line.contains("Automated Review \u{2014} Approve") {
466                    Ok(Some("approve".to_string()))
467                } else if first_line.contains("Automated Review \u{2014} Changes Requested") {
468                    Ok(Some("changes_requested".to_string()))
469                } else {
470                    Ok(None)
471                }
472            }
473            None => Ok(None),
474        }
475    }
476}
477
478/// GitHub returns for private repos on the Free plan
479pub(super) fn is_no_branch_protection_error(err: &str) -> bool {
480    has_status(err, 404)
481        || (err.contains("403")
482            && err.contains("Upgrade to GitHub Pro or make this repository public"))
483}
484
485pub(crate) const REQUIRED_CHECK_RULESET_NAME: &str = "orch required checks";
486
487#[derive(Debug, Clone, Copy, PartialEq, Eq)]
488pub(crate) enum RulesetCreateKind {
489    CheckNeverRun,
490    NameTaken,
491    Refused,
492    Retryable,
493    Other,
494}
495
496pub(crate) fn required_check_ruleset_payload(checks: &[RequiredStatusCheck]) -> serde_json::Value {
497    let required: Vec<serde_json::Value> = checks
498        .iter()
499        .map(|check| {
500            if let Some(id) = check.integration_id {
501                serde_json::json!({ "context": check.context, "integration_id": id })
502            } else {
503                serde_json::json!({ "context": check.context })
504            }
505        })
506        .collect();
507    serde_json::json!({
508        "name": REQUIRED_CHECK_RULESET_NAME,
509        "target": "branch",
510        "enforcement": "active",
511        "conditions": {
512            "ref_name": {
513                "include": ["~DEFAULT_BRANCH"],
514                "exclude": []
515            }
516        },
517        "rules": [{
518            "type": "required_status_checks",
519            "parameters": {
520                "strict_required_status_checks_policy": true,
521                "do_not_enforce_on_create": false,
522                "required_status_checks": required
523            }
524        }]
525    })
526}
527
528pub(crate) fn classify_ruleset_create_error(err: &str) -> RulesetCreateKind {
529    let lower = err.to_ascii_lowercase();
530    if lower.contains("already been taken") || lower.contains("name already exists") {
531        return RulesetCreateKind::NameTaken;
532    }
533    if lower.contains("not a valid check")
534        || lower.contains("required to be present is not found")
535        || (lower.contains("422") && lower.contains("status check") && lower.contains("not found"))
536    {
537        return RulesetCreateKind::CheckNeverRun;
538    }
539    if lower.contains("(500")
540        || lower.contains("(502")
541        || lower.contains("(503")
542        || lower.contains("(504")
543        || lower.contains("(429")
544    {
545        return RulesetCreateKind::Retryable;
546    }
547    // "(401" / "(403" is the status token, a 422 body can contain those digits
548    if lower.contains("(403")
549        || lower.contains("(401")
550        || lower.contains("upgrade to github pro")
551        || lower.contains("not accessible")
552    {
553        return RulesetCreateKind::Refused;
554    }
555    // timeout and transport errors never include an HTTP status
556    if !has_http_status_token(&lower) {
557        return RulesetCreateKind::Retryable;
558    }
559    RulesetCreateKind::Other
560}
561
562fn has_http_status_token(err: &str) -> bool {
563    err.match_indices('(').any(|(i, _)| {
564        err.as_bytes()
565            .get(i + 1..i + 4)
566            .is_some_and(|digits| digits.iter().all(u8::is_ascii_digit))
567    })
568}
569
570/// Classic protection prefers `checks` (includes `app_id`) and falls back to `contexts`
571pub(super) fn parse_classic_required_status_checks(
572    value: &serde_json::Value,
573) -> Vec<RequiredStatusCheck> {
574    if let Some(checks) = value
575        .pointer("/required_status_checks/checks")
576        .and_then(|v| v.as_array())
577    {
578        let parsed: Vec<RequiredStatusCheck> =
579            checks.iter().filter_map(parse_classic_check).collect();
580        if !parsed.is_empty() {
581            return parsed;
582        }
583    }
584
585    value
586        .pointer("/required_status_checks/contexts")
587        .and_then(|v| v.as_array())
588        .map(|contexts| {
589            contexts
590                .iter()
591                .filter_map(|context| {
592                    context.as_str().map(|s| RequiredStatusCheck {
593                        context: s.to_string(),
594                        integration_id: None,
595                    })
596                })
597                .collect()
598        })
599        .unwrap_or_default()
600}
601
602fn parse_classic_check(check: &serde_json::Value) -> Option<RequiredStatusCheck> {
603    let context = check.get("context")?.as_str()?.to_string();
604    let integration_id = check
605        .get("app_id")
606        .and_then(serde_json::Value::as_i64)
607        .filter(|&id| id > 0);
608    Some(RequiredStatusCheck {
609        context,
610        integration_id,
611    })
612}
613
614/// Collect `required_status_checks` entries from every active `required_status_checks` rule
615pub(super) fn parse_ruleset_required_status_checks(
616    rules: &[serde_json::Value],
617) -> Vec<RequiredStatusCheck> {
618    let mut out = Vec::new();
619    for rule in rules {
620        if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
621            continue;
622        }
623        let Some(checks) = rule
624            .pointer("/parameters/required_status_checks")
625            .or_else(|| rule.get("required_status_checks"))
626            .and_then(|v| v.as_array())
627        else {
628            continue;
629        };
630        for check in checks {
631            let Some(context) = check.get("context").and_then(|v| v.as_str()) else {
632                continue;
633            };
634            let integration_id = check
635                .get("integration_id")
636                .and_then(serde_json::Value::as_i64)
637                .filter(|&id| id > 0);
638            out.push(RequiredStatusCheck {
639                context: context.to_string(),
640                integration_id,
641            });
642        }
643    }
644    out
645}
646
647pub(super) fn merge_required_status_checks(
648    mut checks: Vec<RequiredStatusCheck>,
649    extra: Vec<RequiredStatusCheck>,
650) -> Vec<RequiredStatusCheck> {
651    checks.extend(extra);
652    let mut seen = HashSet::new();
653    checks.retain(|c| seen.insert((c.context.clone(), c.integration_id)));
654    checks
655}