Skip to main content

orch/github/
types.rs

1//! GitHub API response types — deserialized from `gh api` JSON output.
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct GitHubIssue {
7    pub number: u64,
8    /// GitHub database id, the value the dependencies API calls issue_id
9    #[serde(default)]
10    pub id: u64,
11    pub title: String,
12    pub body: Option<String>,
13    pub state: String,
14    pub labels: Vec<GitHubLabel>,
15    pub user: GitHubUser,
16    pub created_at: String,
17    pub updated_at: String,
18    pub html_url: String,
19    pub node_id: Option<String>,
20    /// Present when the item is actually a pull request (GitHub API returns PRs in /issues).
21    pub pull_request: Option<serde_json::Value>,
22    /// Author's relationship to the repo: OWNER, MEMBER, COLLABORATOR, CONTRIBUTOR,
23    /// FIRST_TIME_CONTRIBUTOR, FIRST_TIMER, MANNEQUIN, NONE.
24    #[serde(default)]
25    pub author_association: Option<String>,
26    /// `completed`, `not_planned`, `duplicate`, `reopened`, or absent
27    #[serde(default)]
28    pub state_reason: Option<String>,
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct GitHubLabel {
33    pub name: String,
34    pub color: Option<String>,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct GitHubUser {
39    pub login: String,
40}
41
42/// Pull request details from the GitHub API.
43/// The `mergeable` field indicates if the PR can be merged:
44/// - `true` - PR can be merged
45/// - `false` - PR has merge conflicts (CONFLICTING)
46/// - `null` - GitHub is still computing mergeability
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct GitHubPullRequest {
49    pub number: u64,
50    pub title: String,
51    pub body: Option<String>,
52    pub state: String,
53    pub head: GitHubBranchRef,
54    pub base: GitHubBranchRef,
55    pub mergeable: Option<bool>,
56    pub mergeable_state: Option<String>,
57    pub merged: Option<bool>,
58    pub html_url: String,
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct GitHubCheckRun {
63    pub id: u64,
64    pub name: String,
65    pub status: String,
66    pub conclusion: Option<String>,
67    /// GitHub App that posted the run, used to match a ruleset `integration_id`
68    #[serde(default)]
69    pub app: Option<GitHubApp>,
70}
71
72impl GitHubCheckRun {
73    pub(crate) fn is_finished(&self) -> bool {
74        check_run_is_finished(&self.status, self.conclusion.as_deref())
75    }
76
77    pub(crate) fn is_passed(&self) -> bool {
78        check_conclusion_passed(self.conclusion.as_deref())
79    }
80}
81
82/// `action_required` is completed on GitHub but still needs a person
83pub(crate) fn check_run_is_finished(status: &str, conclusion: Option<&str>) -> bool {
84    status == "completed" && conclusion.is_some_and(|c| c != "action_required")
85}
86
87pub(crate) fn check_conclusion_passed(conclusion: Option<&str>) -> bool {
88    matches!(conclusion, Some("success" | "neutral" | "skipped"))
89}
90
91/// The GitHub App that created a check run (`check_run.app`)
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct GitHubApp {
94    pub id: i64,
95}
96
97/// A required status check from classic branch protection or a ruleset
98#[derive(Debug, Clone, PartialEq, Eq, Hash)]
99pub struct RequiredStatusCheck {
100    pub context: String,
101    /// GitHub App that must post this check. `None` means any app's check with this name counts
102    pub integration_id: Option<i64>,
103}
104
105/// A check run annotation returned by the GitHub Checks API.
106///
107/// Annotations appear on the "Annotations" tab of a check run in the GitHub UI.
108/// GitHub uses annotations for job-level messages, including billing failures
109/// ("The job was not started because recent account payments have failed …").
110#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct GitHubAnnotation {
112    pub annotation_level: Option<String>,
113    pub message: Option<String>,
114    pub title: Option<String>,
115    pub path: Option<String>,
116    pub start_line: Option<u64>,
117}
118
119#[derive(Debug, Clone, Serialize, Deserialize)]
120pub struct GitHubBranchRef {
121    #[serde(rename = "ref")]
122    pub ref_: String,
123    pub sha: String,
124    /// The repository the branch lives in, a fork when the PR comes from one
125    #[serde(default)]
126    pub repo: Option<GitHubRepoRef>,
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct GitHubRepoRef {
131    pub full_name: String,
132}
133
134#[derive(Debug, Clone, Serialize, Deserialize)]
135pub struct GitHubComment {
136    pub id: u64,
137    pub body: String,
138    pub user: GitHubUser,
139    pub created_at: String,
140    pub updated_at: Option<String>,
141    pub html_url: Option<String>,
142    /// Present when fetched from the repo-level /issues/comments endpoint.
143    /// Format: https://api.github.com/repos/owner/repo/issues/123
144    pub issue_url: Option<String>,
145    /// Author's relationship to the repo for comment payloads when present.
146    /// This field is present on repo-level comment endpoints and may be
147    /// missing for some GraphQL-derived nodes. See `author_association` on
148    /// issues for the corresponding field.
149    #[serde(default)]
150    pub author_association: Option<String>,
151}
152
153/// Extract issue/PR number from a GitHub API URL.
154///
155/// Parses the trailing numeric segment from URLs like:
156/// `https://api.github.com/repos/owner/repo/issues/123`
157pub fn extract_issue_number_from_url(url: &str) -> Option<String> {
158    url.rsplit('/')
159        .next()
160        .filter(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
161        .map(String::from)
162}
163
164/// PR review state - "APPROVED", "CHANGES_REQUESTED", "COMMENTED", "DISMISSED"
165#[derive(Debug, Clone, Serialize, Deserialize)]
166pub struct GitHubReview {
167    pub id: u64,
168    pub user: GitHubUser,
169    pub body: Option<String>,
170    pub state: String,
171    pub html_url: Option<String>,
172    pub submitted_at: String,
173    pub commit_id: Option<String>,
174}
175
176/// PR review comment on a specific line of code.
177#[derive(Debug, Clone, Serialize, Deserialize)]
178pub struct GitHubReviewComment {
179    pub id: u64,
180    pub user: GitHubUser,
181    pub body: String,
182    pub path: String,
183    pub line: Option<u32>,
184    pub original_line: Option<u32>,
185    pub commit_id: String,
186    pub original_commit_id: String,
187    pub html_url: String,
188    pub created_at: String,
189    pub updated_at: String,
190    pub in_reply_to_id: Option<u64>,
191    pub diff_hunk: Option<String>,
192}
193
194/// A PR review with its associated comments.
195#[derive(Debug, Clone)]
196pub struct PullRequestReview {
197    pub review: GitHubReview,
198    pub comments: Vec<GitHubReviewComment>,
199}
200
201impl PullRequestReview {
202    /// Get actionable comments (non-empty, not replies).
203    pub fn actionable_comments(&self) -> Vec<&GitHubReviewComment> {
204        self.comments
205            .iter()
206            .filter(|c| !c.body.trim().is_empty() && c.in_reply_to_id.is_none())
207            .collect()
208    }
209}
210
211/// One issue that blocks another, from `GET .../dependencies/blocked_by`.
212///
213/// The REST endpoint is GA since 2025-08-21. No preview media type.
214/// Callers send `X-GitHub-Api-Version: 2026-03-10`
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct BlockedByIssue {
217    pub github_id: i64,
218    pub repo: String,
219    pub number: i64,
220    pub state: String,
221    pub state_reason: Option<String>,
222}
223
224/// Result of reading native blocked-by links.
225///
226/// `Native` is the GitHub blocked-by list, including when it is empty.
227/// `Unavailable` means the API is missing or forbidden, so the native list is empty.
228/// `Failed` means the read did not succeed, so stored rows stay as they are.
229/// `Unreachable` is a `Failed` caused by a transport error, so every other read in the pass would fail too
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub enum BlockedByFetch {
232    Native(Vec<BlockedByIssue>),
233    Unavailable,
234    Failed(String),
235    Unreachable(String),
236}
237
238#[cfg(test)]
239impl PullRequestReview {
240    /// Check if this review requests changes (test helper).
241    pub fn requests_changes(&self) -> bool {
242        self.review.state == "CHANGES_REQUESTED"
243    }
244}
245
246/// A single issue found during review.
247#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
248pub struct ReviewIssue {
249    /// File path.
250    pub file: String,
251    /// Line number (optional).
252    pub line: Option<u32>,
253    /// Severity: "error" | "warning"
254    pub severity: String,
255    /// Description of the issue.
256    pub description: String,
257}
258
259/// Checks that report the review itself, so they never hold one back
260const REVIEW_OWN_CHECKS: &[&str] = &["review-gate", "orch/review"];
261
262pub(crate) fn is_own_check(name: &str) -> bool {
263    REVIEW_OWN_CHECKS.contains(&name)
264}
265
266/// Parse a PR number from a GitHub PR URL.
267///
268/// Validates that the URL matches the expected GitHub PR URL format
269/// (`https://github.com/<owner>/<repo>/pull/<number>`) before extracting the
270/// number. Returns `Err` with a descriptive message for any URL that doesn't
271/// conform to this structure, including URLs with wrong domains, missing
272/// `/pull/` segments, or non-numeric trailing components.
273///
274/// The extracted segment is stripped of any query string (`?`) or hash
275/// fragment (`#`) before parsing so that URLs like
276/// `https://github.com/owner/repo/pull/42?tab=files` are handled correctly.
277pub(crate) fn parse_pr_number_from_url(url: &str) -> Result<u64, String> {
278    let url = url.trim();
279    if url.is_empty() {
280        return Err("URL is empty".to_string());
281    }
282    if !url.starts_with("https://github.com/") {
283        return Err(format!(
284            "URL does not start with 'https://github.com/': {url}"
285        ));
286    }
287    if !url.contains("/pull/") {
288        return Err(format!("URL missing '/pull/' segment: {url}"));
289    }
290    let last_segment = url
291        .trim_end_matches('/')
292        .rsplit('/')
293        .next()
294        .ok_or_else(|| format!("No segment after '/pull/' in URL: {url}"))?;
295    let number_part = last_segment
296        .split(['?', '#'])
297        .next()
298        .filter(|s| !s.is_empty())
299        .ok_or_else(|| format!("PR number segment is empty in URL: {url}"))?;
300    let pr_num: u64 = number_part.parse().map_err(|_| {
301        format!("PR number is not a valid positive integer: '{number_part}' in URL: {url}")
302    })?;
303    if pr_num == 0 {
304        return Err(format!("PR number cannot be zero in URL: {url}"));
305    }
306    Ok(pr_num)
307}
308
309pub(crate) fn required_contexts_cover(
310    required: &[RequiredStatusCheck],
311    needed: &[RequiredStatusCheck],
312) -> bool {
313    needed.iter().all(|check| {
314        required
315            .iter()
316            .any(|existing| existing.context == check.context)
317    })
318}
319
320pub(crate) fn merge_missing_checks(
321    mut existing: Vec<RequiredStatusCheck>,
322    needed: &[RequiredStatusCheck],
323) -> Vec<RequiredStatusCheck> {
324    for check in needed {
325        if !existing.iter().any(|e| e.context == check.context) {
326            existing.push(check.clone());
327        }
328    }
329    existing
330}
331
332/// The second parent of a merge of `approved` with another commit, the commit to check against the base
333pub(crate) fn base_merge_parent<'a>(approved: &str, parents: &'a [String]) -> Option<&'a str> {
334    match parents {
335        [first, second] if first == approved => Some(second.as_str()),
336        _ => None,
337    }
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343
344    #[test]
345    fn action_required_is_not_finished() {
346        assert!(!check_run_is_finished("completed", Some("action_required")));
347        assert!(check_run_is_finished("completed", Some("success")));
348        assert!(check_run_is_finished("completed", Some("failure")));
349        assert!(check_run_is_finished("completed", Some("skipped")));
350        assert!(!check_run_is_finished("completed", None));
351        assert!(!check_run_is_finished("in_progress", None));
352        assert!(!check_run_is_finished("waiting", None));
353        assert!(!check_conclusion_passed(Some("action_required")));
354        assert!(check_conclusion_passed(Some("success")));
355        assert!(check_conclusion_passed(Some("skipped")));
356        assert!(!check_conclusion_passed(Some("failure")));
357    }
358
359    #[test]
360    fn test_github_review_deserialization() {
361        let json = r#"{
362            "id": 789,
363            "user": {"login": "reviewer"},
364            "body": "Please fix this",
365            "state": "CHANGES_REQUESTED",
366            "html_url": "https://github.com/test/repo/pull/123#pullrequestreview-789",
367            "submitted_at": "2024-01-01T12:00:00Z",
368            "commit_id": "abc123"
369        }"#;
370
371        let review: GitHubReview = serde_json::from_str(json).unwrap();
372        assert_eq!(review.id, 789);
373        assert_eq!(review.user.login, "reviewer");
374        assert_eq!(review.body, Some("Please fix this".to_string()));
375        assert_eq!(review.state, "CHANGES_REQUESTED");
376        assert_eq!(review.submitted_at, "2024-01-01T12:00:00Z");
377        assert_eq!(review.commit_id, Some("abc123".to_string()));
378    }
379
380    #[test]
381    fn test_github_review_comment_deserialization() {
382        let json = r#"{
383            "id": 101112,
384            "user": {"login": "reviewer"},
385            "body": "This line needs fixing",
386            "path": "src/main.rs",
387            "line": 42,
388            "original_line": 42,
389            "commit_id": "abc123",
390            "original_commit_id": "abc123",
391            "html_url": "https://github.com/test/repo/pull/123#discussion_r101112",
392            "created_at": "2024-01-01T12:00:00Z",
393            "updated_at": "2024-01-01T12:00:00Z",
394            "in_reply_to_id": null,
395            "diff_hunk": "@@ -40,5 +40,5 @@ fn main() {\n     let x = 1;\n-    let y = 2;\n+    let y = 3;"
396        }"#;
397
398        let comment: GitHubReviewComment = serde_json::from_str(json).unwrap();
399        assert_eq!(comment.id, 101_112);
400        assert_eq!(comment.user.login, "reviewer");
401        assert_eq!(comment.body, "This line needs fixing");
402        assert_eq!(comment.path, "src/main.rs");
403        assert_eq!(comment.line, Some(42));
404        assert_eq!(comment.commit_id, "abc123");
405        assert_eq!(comment.in_reply_to_id, None);
406        assert!(comment.diff_hunk.is_some());
407    }
408
409    #[test]
410    fn github_check_run_deserializes_app_id() {
411        let json = r#"{
412            "id": 4,
413            "name": "ci/test",
414            "status": "completed",
415            "conclusion": "success",
416            "app": { "id": 42, "slug": "shipcheck", "name": "shipcheck" }
417        }"#;
418        let run: GitHubCheckRun = serde_json::from_str(json).unwrap();
419        assert_eq!(run.name, "ci/test");
420        assert_eq!(run.app.unwrap().id, 42);
421    }
422
423    #[test]
424    fn github_check_run_deserializes_without_app() {
425        let json = r#"{
426            "id": 4,
427            "name": "ci/test",
428            "status": "completed",
429            "conclusion": "success"
430        }"#;
431        let run: GitHubCheckRun = serde_json::from_str(json).unwrap();
432        assert!(run.app.is_none());
433    }
434
435    #[test]
436    fn test_github_branch_ref_deserialization() {
437        let json = r#"{
438            "ref": "main",
439            "sha": "abc123"
440        }"#;
441
442        let branch_ref: GitHubBranchRef = serde_json::from_str(json).unwrap();
443        assert_eq!(branch_ref.ref_, "main");
444        assert_eq!(branch_ref.sha, "abc123");
445    }
446
447    #[test]
448    fn test_pull_request_review_requests_changes() {
449        let review = PullRequestReview {
450            review: GitHubReview {
451                id: 1,
452                user: GitHubUser {
453                    login: "reviewer".to_string(),
454                },
455                body: Some("Please fix".to_string()),
456                state: "CHANGES_REQUESTED".to_string(),
457                html_url: None,
458                submitted_at: "2024-01-01T00:00:00Z".to_string(),
459                commit_id: None,
460            },
461            comments: vec![],
462        };
463
464        assert!(review.requests_changes());
465    }
466
467    #[test]
468    fn test_pull_request_review_approved() {
469        let review = PullRequestReview {
470            review: GitHubReview {
471                id: 1,
472                user: GitHubUser {
473                    login: "reviewer".to_string(),
474                },
475                body: Some("LGTM".to_string()),
476                state: "APPROVED".to_string(),
477                html_url: None,
478                submitted_at: "2024-01-01T00:00:00Z".to_string(),
479                commit_id: None,
480            },
481            comments: vec![],
482        };
483
484        assert!(!review.requests_changes());
485    }
486
487    #[test]
488    fn test_pull_request_review_actionable_comments() {
489        let review = PullRequestReview {
490            review: GitHubReview {
491                id: 1,
492                user: GitHubUser {
493                    login: "reviewer".to_string(),
494                },
495                body: None,
496                state: "CHANGES_REQUESTED".to_string(),
497                html_url: None,
498                submitted_at: "2024-01-01T00:00:00Z".to_string(),
499                commit_id: None,
500            },
501            comments: vec![
502                GitHubReviewComment {
503                    id: 1,
504                    user: GitHubUser {
505                        login: "reviewer".to_string(),
506                    },
507                    body: "Fix this".to_string(),
508                    path: "src/main.rs".to_string(),
509                    line: Some(10),
510                    original_line: Some(10),
511                    commit_id: "abc".to_string(),
512                    original_commit_id: "abc".to_string(),
513                    html_url: "url".to_string(),
514                    created_at: "2024-01-01T00:00:00Z".to_string(),
515                    updated_at: "2024-01-01T00:00:00Z".to_string(),
516                    in_reply_to_id: None,
517                    diff_hunk: None,
518                },
519                GitHubReviewComment {
520                    id: 2,
521                    user: GitHubUser {
522                        login: "reviewer".to_string(),
523                    },
524                    body: String::new(), // Empty - not actionable
525                    path: "src/lib.rs".to_string(),
526                    line: Some(20),
527                    original_line: Some(20),
528                    commit_id: "abc".to_string(),
529                    original_commit_id: "abc".to_string(),
530                    html_url: "url".to_string(),
531                    created_at: "2024-01-01T00:00:00Z".to_string(),
532                    updated_at: "2024-01-01T00:00:00Z".to_string(),
533                    in_reply_to_id: None,
534                    diff_hunk: None,
535                },
536                GitHubReviewComment {
537                    id: 3,
538                    user: GitHubUser {
539                        login: "reviewer".to_string(),
540                    },
541                    body: "Reply to this".to_string(),
542                    path: "src/lib.rs".to_string(),
543                    line: Some(30),
544                    original_line: Some(30),
545                    commit_id: "abc".to_string(),
546                    original_commit_id: "abc".to_string(),
547                    html_url: "url".to_string(),
548                    created_at: "2024-01-01T00:00:00Z".to_string(),
549                    updated_at: "2024-01-01T00:00:00Z".to_string(),
550                    in_reply_to_id: Some(1), // Reply - not actionable as standalone
551                    diff_hunk: None,
552                },
553            ],
554        };
555
556        let actionable = review.actionable_comments();
557        assert_eq!(actionable.len(), 1);
558        assert_eq!(actionable[0].id, 1);
559        assert_eq!(actionable[0].body, "Fix this");
560    }
561
562    #[test]
563    fn extract_issue_number_from_url_works() {
564        assert_eq!(
565            extract_issue_number_from_url("https://api.github.com/repos/owner/repo/issues/123"),
566            Some("123".into())
567        );
568    }
569
570    #[test]
571    fn extract_issue_number_from_url_empty() {
572        assert_eq!(extract_issue_number_from_url(""), None);
573    }
574}