Skip to main content

jouet_github/pr/
status.rs

1//! Fetching the status of many PRs in batched GraphQL queries, and deriving
2//! the reasons each one needs attention.
3//!
4//! A query holds up to 50 lookups, each under its own alias. Check counts
5//! come from GitHub's per-state totals; listing the checks themselves is what
6//! makes a status query slow (50 PRs with their checks can pass GitHub's 10s
7//! timeout), so the names of failing checks are fetched in follow-up queries
8//! only for PRs that have failures. All context pages are then read so older
9//! workflow runs can be distinguished from their replacements. Review threads
10//! come 100 to a page and the rare PR with more is paged the same way.
11
12use super::target::{Repo, Target};
13use crate::Client;
14use crate::entire::{Brief, CHECK, Gate, Gates};
15use crate::forge::Forge;
16use crate::host::Host;
17use jouet_output::time;
18use serde::{Deserialize, Serialize};
19use serde_json::{Map, Value, json};
20use std::fmt::Write as _;
21use std::time::{Duration, Instant};
22
23/// Lookups per query.
24const BATCH: usize = 50;
25/// Pages of check contexts per query: each lists up to 100 checks.
26const CONTEXTS_BATCH: usize = 20;
27/// How long after a push a PR may have no checks before that is reported.
28const CHECKS_GRACE_SECS: i64 = 5 * 60;
29
30const PR_FRAGMENT: &str = "fragment pr on PullRequest {
31  id number title url state isDraft
32  baseRefName headRefName headRefOid
33  repository { nameWithOwner }
34  mergeable mergeStateStatus reviewDecision
35  autoMergeRequest { enabledAt }
36  reviewThreads(first: 100) { ...threads }
37  timelineItems(last: 1, itemTypes: [HEAD_REF_FORCE_PUSHED_EVENT]) {
38    nodes { ... on HeadRefForcePushedEvent { createdAt } }
39  }
40  commits(last: 1) {
41    nodes { commit { committedDate statusCheckRollup { id contexts {
42      checkRunCountsByState { state count }
43      statusContextCountsByState { state count }
44    } }
45    checkSuites(last: 1, filterBy: {checkName: \"Entire Gates\"}) { nodes {
46      checkRuns(last: 1, filterBy: {checkName: \"Entire Gates\"}) {
47        nodes { status conclusion detailsUrl title summary }
48      }
49    } } } }
50  }
51}
52";
53const THREADS_FRAGMENT: &str = "fragment threads on PullRequestReviewThreadConnection {
54  pageInfo { hasNextPage endCursor }
55  nodes { isResolved }
56}
57";
58
59/// One aliased entry in a query.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum Lookup {
62    Pr(Target),
63    /// A page of a GitHub search; `after` is the cursor of the previous page
64    /// and `listed` counts the PRs earlier pages returned.
65    Search {
66        query: String,
67        after: Option<String>,
68        listed: u64,
69    },
70    /// The next page of a PR's review threads, by the PR's node ID.
71    Threads {
72        id: String,
73        after: String,
74    },
75    /// A page of a commit's check contexts, by the rollup's node ID.
76    Contexts {
77        id: String,
78        after: Option<String>,
79    },
80    /// The open PRs the token's user opened in a repository on GitLab or
81    /// Forgejo, which have no search like GitHub's.
82    Mine(Repo),
83}
84
85impl Lookup {
86    /// The repository a lookup is in, when it names one.
87    pub fn repo(&self) -> Option<&Repo> {
88        match self {
89            Self::Pr(target) => Some(target.repo()),
90            Self::Mine(repo) => Some(repo),
91            Self::Search { .. } | Self::Threads { .. } | Self::Contexts { .. } => None,
92        }
93    }
94}
95
96/// Builds the query and variables for a batch of lookups.
97pub(crate) fn query(lookups: &[Lookup]) -> (String, Value) {
98    let mut params = Vec::new();
99    let mut body = String::new();
100    let mut vars = Map::new();
101    let (mut pr, mut threads) = (false, false);
102    for (i, lookup) in lookups.iter().enumerate() {
103        match lookup {
104            Lookup::Pr(Target::Number(repo, n)) => {
105                pr = true;
106                params.extend([
107                    format!("$o{i}: String!"),
108                    format!("$r{i}: String!"),
109                    format!("$n{i}: Int!"),
110                ]);
111                vars.insert(format!("o{i}"), json!(repo.owner));
112                vars.insert(format!("r{i}"), json!(repo.name));
113                vars.insert(format!("n{i}"), json!(n));
114                let _ = writeln!(
115                    body,
116                    "  l{i}: repository(owner: $o{i}, name: $r{i}) {{ pullRequest(number: $n{i}) {{ ...pr }} }}"
117                );
118            }
119            Lookup::Pr(Target::Branch(repo, branch)) => {
120                pr = true;
121                params.extend([
122                    format!("$o{i}: String!"),
123                    format!("$r{i}: String!"),
124                    format!("$b{i}: String!"),
125                ]);
126                vars.insert(format!("o{i}"), json!(repo.owner));
127                vars.insert(format!("r{i}"), json!(repo.name));
128                vars.insert(format!("b{i}"), json!(branch));
129                // The open PR for the branch if there is one, else the newest.
130                let newest = "first: 1, orderBy: {field: CREATED_AT, direction: DESC}";
131                let _ = writeln!(
132                    body,
133                    "  l{i}: repository(owner: $o{i}, name: $r{i}) {{ \
134                     open: pullRequests(headRefName: $b{i}, states: OPEN, {newest}) {{ nodes {{ ...pr }} }} \
135                     newest: pullRequests(headRefName: $b{i}, {newest}) {{ nodes {{ ...pr }} }} }}"
136                );
137            }
138            Lookup::Search { query, after, .. } => {
139                pr = true;
140                params.extend([format!("$q{i}: String!"), format!("$a{i}: String")]);
141                vars.insert(format!("q{i}"), json!(query));
142                vars.insert(format!("a{i}"), json!(after));
143                let _ = writeln!(
144                    body,
145                    "  l{i}: search(query: $q{i}, type: ISSUE, first: {BATCH}, after: $a{i}) {{ \
146                     issueCount pageInfo {{ hasNextPage endCursor }} nodes {{ ... on PullRequest {{ ...pr }} }} }}"
147                );
148            }
149            Lookup::Threads { id, after } => {
150                threads = true;
151                params.extend([format!("$id{i}: ID!"), format!("$c{i}: String!")]);
152                vars.insert(format!("id{i}"), json!(id));
153                vars.insert(format!("c{i}"), json!(after));
154                let _ = writeln!(
155                    body,
156                    "  l{i}: node(id: $id{i}) {{ ... on PullRequest {{ \
157                     reviewThreads(first: 100, after: $c{i}) {{ ...threads }} }} }}"
158                );
159            }
160            Lookup::Contexts { id, after } => {
161                params.extend([format!("$id{i}: ID!"), format!("$c{i}: String")]);
162                vars.insert(format!("id{i}"), json!(id));
163                vars.insert(format!("c{i}"), json!(after));
164                let _ = writeln!(
165                    body,
166                    "  l{i}: node(id: $id{i}) {{ ... on StatusCheckRollup {{ \
167                     contexts(first: 100, after: $c{i}) {{ pageInfo {{ hasNextPage endCursor }} \
168                     nodes {{ ... on CheckRun {{ name status conclusion \
169                       checkSuite {{ branch {{ name }} app {{ slug }} workflowRun {{ event runNumber runAttempt workflow {{ id }} }} }} }} \
170                       ... on StatusContext {{ context state }} }} }} }} }}"
171                );
172            }
173            // Never sent to GitHub, whose `--mine` is a search.
174            Lookup::Mine(_) => {}
175        }
176    }
177    // GraphQL rejects a document that defines a fragment it does not use.
178    let mut query = format!("query({}) {{\n{body}}}\n", params.join(", "));
179    if pr {
180        query.push_str(PR_FRAGMENT);
181    }
182    if pr || threads {
183        query.push_str(THREADS_FRAGMENT);
184    }
185    (query, Value::Object(vars))
186}
187
188// The shapes GitHub returns, as far as jouet reads them.
189
190#[derive(Debug, Deserialize)]
191#[serde(rename_all = "camelCase")]
192struct RawPr {
193    id: String,
194    number: u64,
195    title: String,
196    url: String,
197    state: String,
198    is_draft: bool,
199    base_ref_name: String,
200    head_ref_name: String,
201    head_ref_oid: String,
202    repository: RawRepo,
203    mergeable: String,
204    merge_state_status: String,
205    review_decision: Option<String>,
206    auto_merge_request: Option<Value>,
207    review_threads: RawThreads,
208    timeline_items: Nodes<RawForcePush>,
209    commits: Nodes<RawCommitNode>,
210}
211
212#[derive(Debug, Deserialize)]
213#[serde(rename_all = "camelCase")]
214struct RawRepo {
215    name_with_owner: String,
216}
217
218#[derive(Debug, Deserialize)]
219struct Nodes<T> {
220    nodes: Vec<T>,
221}
222
223#[derive(Debug, Deserialize)]
224#[serde(rename_all = "camelCase")]
225struct PageInfo {
226    has_next_page: bool,
227    end_cursor: Option<String>,
228}
229
230#[derive(Debug, Deserialize)]
231#[serde(rename_all = "camelCase")]
232struct RawThreads {
233    page_info: PageInfo,
234    nodes: Vec<RawThread>,
235}
236
237#[derive(Debug, Deserialize)]
238#[serde(rename_all = "camelCase")]
239struct RawThread {
240    is_resolved: bool,
241}
242
243#[derive(Debug, Deserialize)]
244#[serde(rename_all = "camelCase")]
245struct RawForcePush {
246    created_at: Option<String>,
247}
248
249#[derive(Debug, Deserialize)]
250struct RawCommitNode {
251    commit: RawCommit,
252}
253
254#[derive(Debug, Deserialize)]
255#[serde(rename_all = "camelCase")]
256struct RawCommit {
257    committed_date: String,
258    status_check_rollup: Option<RawRollup>,
259    check_suites: Option<Nodes<RawSuite>>,
260}
261
262/// A check suite holding the Entire Gates check.
263#[derive(Debug, Deserialize)]
264#[serde(rename_all = "camelCase")]
265struct RawSuite {
266    check_runs: Nodes<RawGatesRun>,
267}
268
269#[derive(Debug, Deserialize)]
270#[serde(rename_all = "camelCase")]
271struct RawGatesRun {
272    status: String,
273    conclusion: Option<String>,
274    details_url: Option<String>,
275    title: Option<String>,
276    summary: Option<String>,
277}
278
279#[derive(Debug, Deserialize)]
280struct RawRollup {
281    id: String,
282    contexts: RawCounts,
283}
284
285#[derive(Debug, Deserialize)]
286#[serde(rename_all = "camelCase")]
287struct RawCounts {
288    #[serde(default)]
289    check_run_counts_by_state: Vec<RawCount>,
290    #[serde(default)]
291    status_context_counts_by_state: Vec<RawCount>,
292}
293
294#[derive(Debug, Deserialize)]
295#[serde(rename_all = "camelCase")]
296struct RawContexts {
297    page_info: PageInfo,
298    nodes: Vec<RawContext>,
299}
300
301#[derive(Debug, Deserialize)]
302struct RawCount {
303    state: String,
304    count: u32,
305}
306
307/// A check run (`name`, `conclusion`) or a commit status
308/// (`context`, `state`).
309#[derive(Debug, Clone, Deserialize)]
310#[serde(rename_all = "camelCase")]
311struct RawContext {
312    name: Option<String>,
313    status: Option<String>,
314    conclusion: Option<String>,
315    check_suite: Option<RawCheckSuite>,
316    context: Option<String>,
317    state: Option<String>,
318}
319
320#[derive(Debug, Clone, Deserialize)]
321#[serde(rename_all = "camelCase")]
322struct RawCheckSuite {
323    app: Option<RawApp>,
324    branch: Option<RawBranch>,
325    workflow_run: Option<RawWorkflowRun>,
326}
327
328#[derive(Debug, Clone, Deserialize)]
329struct RawBranch {
330    name: String,
331}
332
333#[derive(Debug, Clone, Deserialize)]
334struct RawApp {
335    slug: String,
336}
337
338#[derive(Debug, Clone, Deserialize)]
339#[serde(rename_all = "camelCase")]
340struct RawWorkflowRun {
341    workflow: Option<RawWorkflow>,
342    event: Option<String>,
343    run_number: Option<u64>,
344    run_attempt: Option<u64>,
345}
346
347#[derive(Debug, Clone, Deserialize)]
348struct RawWorkflow {
349    id: String,
350}
351
352type WorkflowKey<'a> = (&'a str, &'a str, &'a str, &'a str, &'a str);
353
354impl RawContext {
355    fn name_and_state(&self) -> Option<(&str, &str)> {
356        if let Some(name) = self.name.as_deref() {
357            Some((name, self.conclusion.as_deref().or(self.status.as_deref())?))
358        } else {
359            Some((self.context.as_deref()?, self.state.as_deref()?))
360        }
361    }
362
363    // Only group runs when the app and workflow both identify their origin.
364    fn workflow_identity(&self) -> Option<(WorkflowKey<'_>, (u64, u64))> {
365        let suite = self.check_suite.as_ref()?;
366        let run = suite.workflow_run.as_ref()?;
367        Some((
368            (
369                self.name.as_deref()?,
370                suite.app.as_ref()?.slug.as_str(),
371                suite.branch.as_ref()?.name.as_str(),
372                run.event.as_deref()?,
373                run.workflow.as_ref()?.id.as_str(),
374            ),
375            (run.run_number?, run.run_attempt?),
376        ))
377    }
378}
379
380#[derive(Debug, Deserialize)]
381#[serde(rename_all = "camelCase")]
382struct RawSearch {
383    issue_count: u64,
384    page_info: PageInfo,
385    nodes: Vec<Value>,
386}
387
388/// How a check or commit status state counts.
389#[derive(Debug, Clone, Copy, PartialEq, Eq)]
390enum Bucket {
391    Pass,
392    Fail,
393    Pending,
394    Skipped,
395}
396
397/// Buckets GitHub's `CheckRunState`, `CheckConclusionState` and
398/// `StatusState` values the way `gh pr checks` does.
399fn bucket(state: &str) -> Bucket {
400    match state {
401        "SUCCESS" | "COMPLETED" => Bucket::Pass,
402        "FAILURE" | "ERROR" | "CANCELLED" | "TIMED_OUT" | "ACTION_REQUIRED" | "STARTUP_FAILURE" => {
403            Bucket::Fail
404        }
405        "SKIPPED" | "NEUTRAL" | "STALE" => Bucket::Skipped,
406        _ => Bucket::Pending,
407    }
408}
409
410/// A PR as fetched, with what is still needed to finish paging it.
411#[derive(Debug, Clone)]
412pub struct Fetched {
413    id: String,
414    status: PrStatus,
415    threads_after: Option<String>,
416    rollup_id: Option<String>,
417    /// Set while check contexts are still being read: the cursor to list
418    /// them from, `None` for the first page.
419    contexts_after: Option<Option<String>>,
420    contexts: Vec<RawContext>,
421}
422
423impl Fetched {
424    pub fn key(&self) -> (&str, u64) {
425        (&self.status.repo, self.status.number)
426    }
427
428    pub fn status(&self) -> &PrStatus {
429        &self.status
430    }
431
432    pub fn is_open(&self) -> bool {
433        matches!(self.status.state, State::Open | State::Draft)
434    }
435
436    pub fn mergeable_unknown(&self) -> bool {
437        self.status.mergeable == Mergeability::Unknown
438    }
439
440    pub fn target(&self) -> Option<Target> {
441        Some(Target::Number(
442            self.status.repository()?,
443            self.status.number,
444        ))
445    }
446
447    /// A PR read from a forge other than GitHub, which needs no further
448    /// pages.
449    pub(crate) fn new(status: PrStatus) -> Self {
450        Self {
451            id: String::new(),
452            status,
453            threads_after: None,
454            rollup_id: None,
455            contexts_after: None,
456            contexts: Vec::new(),
457        }
458    }
459
460    /// The follow-up lookups this PR still needs.
461    fn pages(&self) -> Vec<Lookup> {
462        let mut pages = Vec::new();
463        if let Some(after) = &self.threads_after {
464            pages.push(Lookup::Threads {
465                id: self.id.clone(),
466                after: after.clone(),
467            });
468        }
469        if let (Some(id), Some(after)) = (&self.rollup_id, &self.contexts_after) {
470            pages.push(Lookup::Contexts {
471                id: id.clone(),
472                after: after.clone(),
473            });
474        }
475        pages
476    }
477
478    fn add_threads(&mut self, threads: RawThreads) {
479        let unresolved = threads.nodes.iter().filter(|t| !t.is_resolved).count();
480        self.status.unresolved_threads += u32::try_from(unresolved).unwrap_or(u32::MAX);
481        self.threads_after = next_cursor(threads.page_info);
482    }
483
484    /// Collects all pages before ignoring superseded workflow runs.
485    fn add_contexts(&mut self, contexts: RawContexts) {
486        self.contexts.extend(contexts.nodes);
487        self.contexts_after = next_cursor(contexts.page_info).map(Some);
488        if self.contexts_after.is_some() {
489            return;
490        }
491        let mut latest = std::collections::HashMap::new();
492        let mut seen = std::collections::HashSet::new();
493        let mut ambiguous = std::collections::HashSet::new();
494        for c in &self.contexts {
495            if let Some((key, id)) = c.workflow_identity() {
496                if !seen.insert((key, id)) {
497                    ambiguous.insert(key);
498                }
499                latest
500                    .entry(key)
501                    .and_modify(|n: &mut (u64, u64)| *n = (*n).max(id))
502                    .or_insert(id);
503            }
504        }
505        let checks = &mut self.status.checks;
506        for c in &self.contexts {
507            let Some((name, state)) = c.name_and_state() else {
508                continue;
509            };
510            let bucket = bucket(state);
511            let superseded = c.workflow_identity().is_some_and(|(key, id)| {
512                !ambiguous.contains(&key) && latest.get(&key).is_some_and(|newest| id < *newest)
513            });
514            if superseded {
515                let count = match bucket {
516                    Bucket::Pass => &mut checks.pass,
517                    Bucket::Fail => &mut checks.fail,
518                    Bucket::Pending => &mut checks.pending,
519                    Bucket::Skipped => &mut checks.skipped,
520                };
521                *count = count.saturating_sub(1);
522            } else if bucket == Bucket::Fail {
523                checks.failing.push(name.to_owned());
524            }
525        }
526    }
527
528    /// The PR as fetched so far, for adding what Entire says.
529    pub(crate) fn status_mut(&mut self) -> &mut PrStatus {
530        &mut self.status
531    }
532
533    pub fn finish(self, now: i64) -> PrStatus {
534        let mut status = self.status;
535        status.attention = attention(&status, now);
536        status
537    }
538}
539
540fn next_cursor(page: PageInfo) -> Option<String> {
541    page.end_cursor.filter(|_| page.has_next_page)
542}
543
544/// What `fetch` found.
545#[derive(Debug, Default)]
546pub struct FetchResult {
547    pub prs: Vec<Fetched>,
548    /// Targets that named no PR, as `owner/repo#N` or `owner/repo:branch`.
549    pub not_found: Vec<String>,
550    /// Searches that matched more PRs than GitHub would list.
551    pub incomplete: Vec<Incomplete>,
552}
553
554/// A search GitHub cut short: it lists at most 1,000 results across all
555/// pages, however many match.
556#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
557pub struct Incomplete {
558    pub query: String,
559    pub matched: u64,
560    pub listed: u64,
561}
562
563/// Fetches every PR the lookups name, following search pages and finishing
564/// each PR's thread and check pages. PRs keep the order they were named in,
565/// and one named twice is reported once.
566pub fn fetch(client: &mut Client, lookups: Vec<Lookup>) -> Result<FetchResult, String> {
567    let mut result = FetchResult::default();
568    let mut queue = lookups;
569    while !queue.is_empty() {
570        let batch: Vec<Lookup> = queue.drain(..queue.len().min(BATCH)).collect();
571        let (q, vars) = query(&batch);
572        let data = client.graphql(&q, &vars)?;
573        queue.extend(read_prs(&batch, &data, &mut result)?);
574    }
575    let mut seen = std::collections::HashSet::new();
576    result
577        .prs
578        .retain(|p| seen.insert((p.status.repo.clone(), p.status.number)));
579    let mut seen = std::collections::HashSet::new();
580    result.not_found.retain(|t| seen.insert(t.clone()));
581    loop {
582        let pages: Vec<(usize, Lookup)> = result
583            .prs
584            .iter()
585            .enumerate()
586            .flat_map(|(i, p)| p.pages().into_iter().map(move |l| (i, l)))
587            .collect();
588        if pages.is_empty() {
589            return Ok(result);
590        }
591        let (threads, contexts): (Vec<_>, Vec<_>) = pages
592            .into_iter()
593            .partition(|(_, l)| matches!(l, Lookup::Threads { .. }));
594        for batch in threads.chunks(BATCH).chain(contexts.chunks(CONTEXTS_BATCH)) {
595            let lookups: Vec<Lookup> = batch.iter().map(|(_, l)| l.clone()).collect();
596            let (q, vars) = query(&lookups);
597            let data = client.graphql(&q, &vars)?;
598            for (i, (pr, lookup)) in batch.iter().enumerate() {
599                read_page(&mut result.prs[*pr], lookup, &data[format!("l{i}")])?;
600            }
601        }
602    }
603}
604
605/// Re-queries open PRs whose mergeable state is still unknown until the
606/// forge settles it or `settle` runs out.
607pub fn settle(host: &mut dyn Host, prs: &mut [Fetched], settle: Duration) -> Result<(), String> {
608    let deadline = Instant::now() + settle;
609    let mut wait = Duration::from_secs(1);
610    let mut announced = false;
611    loop {
612        let unknown: Vec<Target> = prs
613            .iter()
614            .filter(|p| p.is_open() && p.mergeable_unknown())
615            .filter_map(Fetched::target)
616            .collect();
617        let left = deadline.saturating_duration_since(Instant::now());
618        if unknown.is_empty() || left.is_zero() {
619            return Ok(());
620        }
621        if !announced {
622            let names: Vec<String> = unknown.iter().map(Target::to_string).collect();
623            eprintln!(
624                "jouet: waiting up to {}s for {} to compute mergeability of {}",
625                left.as_secs(),
626                host.forge().name(),
627                names.join(", ")
628            );
629            announced = true;
630        }
631        std::thread::sleep(wait.min(left));
632        wait = (wait + Duration::from_secs(1)).min(Duration::from_secs(5));
633        let again = host.fetch(unknown.into_iter().map(Lookup::Pr).collect())?;
634        for fresh in again.prs {
635            if let Some(pr) = prs.iter_mut().find(|p| p.key() == fresh.key()) {
636                *pr = fresh;
637            }
638        }
639    }
640}
641
642/// Reads the PRs a batch of PR and search lookups returned, and returns
643/// the lookups for the next page of each search that has one.
644fn read_prs(
645    batch: &[Lookup],
646    data: &Value,
647    result: &mut FetchResult,
648) -> Result<Vec<Lookup>, String> {
649    let mut more = Vec::new();
650    for (i, lookup) in batch.iter().enumerate() {
651        let entry = &data[format!("l{i}")];
652        match lookup {
653            Lookup::Pr(target) => {
654                let pr = match target {
655                    Target::Number(..) => &entry["pullRequest"],
656                    Target::Branch(..) => {
657                        let open = &entry["open"]["nodes"][0];
658                        if open.is_null() {
659                            &entry["newest"]["nodes"][0]
660                        } else {
661                            open
662                        }
663                    }
664                };
665                if pr.is_null() {
666                    result.not_found.push(target.to_string());
667                } else {
668                    result.prs.push(read_pr(pr)?);
669                }
670            }
671            Lookup::Search { query, listed, .. } => {
672                let search: RawSearch = parse(entry, "search results")?;
673                let mut listed = *listed;
674                for node in search.nodes {
675                    // Issues match `... on PullRequest` as an empty object.
676                    if node.as_object().is_some_and(|o| !o.is_empty()) {
677                        result.prs.push(read_pr(&node)?);
678                    }
679                    listed += 1;
680                }
681                if let Some(after) = next_cursor(search.page_info) {
682                    more.push(Lookup::Search {
683                        query: query.clone(),
684                        after: Some(after),
685                        listed,
686                    });
687                } else if search.issue_count > listed {
688                    result.incomplete.push(Incomplete {
689                        query: query.clone(),
690                        matched: search.issue_count,
691                        listed,
692                    });
693                }
694            }
695            Lookup::Threads { .. } | Lookup::Contexts { .. } | Lookup::Mine(_) => {}
696        }
697    }
698    Ok(more)
699}
700
701fn read_page(pr: &mut Fetched, lookup: &Lookup, entry: &Value) -> Result<(), String> {
702    match lookup {
703        Lookup::Threads { .. } => pr.add_threads(parse(&entry["reviewThreads"], "review threads")?),
704        Lookup::Contexts { after, .. } => {
705            let contexts: RawContexts = parse(&entry["contexts"], "checks")?;
706            if contexts.page_info.has_next_page && contexts.page_info.end_cursor.is_none() {
707                return Err("GitHub omitted the next check contexts cursor".into());
708            }
709            if contexts.page_info.has_next_page
710                && after.is_some()
711                && contexts.page_info.end_cursor == *after
712            {
713                return Err("GitHub repeated a check contexts cursor".into());
714            }
715            pr.add_contexts(contexts);
716        }
717        Lookup::Pr(_) | Lookup::Search { .. } | Lookup::Mine(_) => {}
718    }
719    Ok(())
720}
721
722fn parse<T: serde::de::DeserializeOwned>(value: &Value, what: &str) -> Result<T, String> {
723    T::deserialize(value).map_err(|e| format!("GitHub sent {what} jouet could not read: {e}"))
724}
725
726pub(crate) fn read_pr(value: &Value) -> Result<Fetched, String> {
727    let raw: RawPr = parse(value, "a PR")?;
728    let state = match (raw.state.as_str(), raw.is_draft) {
729        ("MERGED", _) => State::Merged,
730        ("CLOSED", _) => State::Closed,
731        (_, true) => State::Draft,
732        _ => State::Open,
733    };
734    let mergeable = match raw.mergeable.as_str() {
735        "MERGEABLE" => Mergeability::Mergeable,
736        "CONFLICTING" => Mergeability::Conflicting,
737        _ => Mergeability::Unknown,
738    };
739    let commit = raw.commits.nodes.into_iter().next().map(|n| n.commit);
740    // GitHub's API has no push time for a plain push, so this is the later of
741    // the head commit's committer date and the last force push.
742    let force_pushed = raw
743        .timeline_items
744        .nodes
745        .into_iter()
746        .find_map(|n| n.created_at);
747    let pushed_at = [
748        commit.as_ref().map(|c| c.committed_date.clone()),
749        force_pushed,
750    ]
751    .into_iter()
752    .flatten()
753    .max_by_key(|t| time::parse_utc(t));
754    let gates = commit
755        .as_ref()
756        .and_then(|c| c.check_suites.as_ref())
757        .and_then(|s| s.nodes.last())
758        .and_then(|s| s.check_runs.nodes.last())
759        .map(|r| {
760            Gates::parse(
761                &r.status,
762                r.conclusion.as_deref(),
763                r.title.as_deref(),
764                r.summary.as_deref(),
765                r.details_url.as_deref(),
766            )
767        });
768    let mut fetched = Fetched {
769        id: raw.id,
770        status: PrStatus {
771            repo: raw.repository.name_with_owner,
772            number: raw.number,
773            title: raw.title,
774            url: raw.url,
775            state,
776            base: raw.base_ref_name,
777            head: raw.head_ref_name,
778            head_sha: raw.head_ref_oid.chars().take(10).collect(),
779            head_oid: raw.head_ref_oid,
780            forge: None,
781            host: None,
782            pushed_at,
783            mergeable,
784            merge_state: raw.merge_state_status.to_ascii_lowercase(),
785            checks: Checks::default(),
786            review: raw.review_decision.map(|r| r.to_ascii_lowercase()),
787            unresolved_threads: 0,
788            auto_merge: raw.auto_merge_request.is_some_and(|a| !a.is_null()),
789            entire: gates.map(EntireStatus::from),
790            attention: Vec::new(),
791        },
792        threads_after: None,
793        rollup_id: None,
794        contexts_after: None,
795        contexts: Vec::new(),
796    };
797    fetched.add_threads(raw.review_threads);
798    if let Some(rollup) = commit.and_then(|c| c.status_check_rollup) {
799        let counts = rollup
800            .contexts
801            .check_run_counts_by_state
802            .iter()
803            .chain(&rollup.contexts.status_context_counts_by_state);
804        let checks = &mut fetched.status.checks;
805        for c in counts {
806            match bucket(&c.state) {
807                Bucket::Pass => checks.pass += c.count,
808                Bucket::Fail => checks.fail += c.count,
809                Bucket::Pending => checks.pending += c.count,
810                Bucket::Skipped => checks.skipped += c.count,
811            }
812        }
813        fetched.rollup_id = Some(rollup.id);
814        if checks.fail > 0 {
815            fetched.contexts_after = Some(None);
816        }
817    }
818    Ok(fetched)
819}
820
821#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
822#[serde(rename_all = "snake_case")]
823pub enum State {
824    Open,
825    Draft,
826    Merged,
827    Closed,
828}
829
830impl State {
831    pub fn as_str(self) -> &'static str {
832        match self {
833            Self::Open => "open",
834            Self::Draft => "draft",
835            Self::Merged => "merged",
836            Self::Closed => "closed",
837        }
838    }
839}
840
841#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
842#[serde(rename_all = "snake_case")]
843pub enum Mergeability {
844    Mergeable,
845    Conflicting,
846    Unknown,
847}
848
849#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
850pub struct Checks {
851    #[serde(skip_serializing_if = "is_zero")]
852    pub pass: u32,
853    #[serde(skip_serializing_if = "is_zero")]
854    pub fail: u32,
855    #[serde(skip_serializing_if = "is_zero")]
856    pub pending: u32,
857    #[serde(skip_serializing_if = "is_zero")]
858    pub skipped: u32,
859    #[serde(skip_serializing_if = "Vec::is_empty")]
860    pub failing: Vec<String>,
861}
862
863impl Checks {
864    pub fn total(&self) -> u32 {
865        self.pass + self.fail + self.pending + self.skipped
866    }
867
868    fn is_empty(&self) -> bool {
869        self.total() == 0
870    }
871}
872
873#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
874pub struct PrStatus {
875    pub repo: String,
876    /// `gitlab` or `forgejo` for a PR that is not on GitHub.
877    #[serde(skip_serializing_if = "Option::is_none")]
878    pub forge: Option<&'static str>,
879    /// The host of a PR that is not on GitHub, as in [`Repo::host`].
880    #[serde(skip_serializing_if = "Option::is_none")]
881    pub host: Option<String>,
882    pub number: u64,
883    pub title: String,
884    pub url: String,
885    pub state: State,
886    pub base: String,
887    pub head: String,
888    pub head_sha: String,
889    /// The whole head SHA, which the merge and update-branch endpoints
890    /// take as a guard against a push in between.
891    #[serde(skip)]
892    pub head_oid: String,
893    #[serde(skip_serializing_if = "Option::is_none")]
894    pub pushed_at: Option<String>,
895    pub mergeable: Mergeability,
896    pub merge_state: String,
897    #[serde(skip_serializing_if = "Checks::is_empty")]
898    pub checks: Checks,
899    /// GitHub's review decision, lowercased: `approved`,
900    /// `changes_requested` or `review_required`.
901    #[serde(skip_serializing_if = "Option::is_none")]
902    pub review: Option<String>,
903    #[serde(skip_serializing_if = "is_zero")]
904    pub unresolved_threads: u32,
905    #[serde(skip_serializing_if = "std::ops::Not::not")]
906    pub auto_merge: bool,
907    /// The Entire Gates check on the head, when there is one.
908    #[serde(skip_serializing_if = "Option::is_none")]
909    pub entire: Option<EntireStatus>,
910    #[serde(skip_serializing_if = "Vec::is_empty")]
911    pub attention: Vec<Attention>,
912}
913
914/// What Entire says about a PR: its gates, from the check, and when the
915/// findings gate fails and the `entire` CLI could be asked, the open
916/// findings.
917#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
918pub struct EntireStatus {
919    #[serde(flatten)]
920    pub gates: Gates,
921    /// The open, current findings, read when the findings gate fails.
922    #[serde(skip_serializing_if = "Vec::is_empty")]
923    pub findings: Vec<Brief>,
924    /// Entire listed more findings than it let jouet read.
925    #[serde(skip_serializing_if = "std::ops::Not::not")]
926    pub findings_incomplete: bool,
927    /// Why `entire` could not say more, when it was asked and failed.
928    #[serde(skip_serializing_if = "Option::is_none")]
929    pub error: Option<String>,
930    /// Where the gates came from, when not the check's summary.
931    #[serde(skip_serializing_if = "Option::is_none")]
932    pub note: Option<String>,
933}
934
935impl From<Gates> for EntireStatus {
936    fn from(gates: Gates) -> Self {
937        Self {
938            gates,
939            findings: Vec::new(),
940            findings_incomplete: false,
941            error: None,
942            note: None,
943        }
944    }
945}
946
947impl EntireStatus {
948    /// The next thing to fix: the first open finding with its handle and
949    /// location, or the gate's own reason when none could be read.
950    pub fn findings_message(&self) -> String {
951        let Some(first) = self.findings.first() else {
952            return format!("Entire Gates: {}", self.gates.failing_text());
953        };
954        let mut s = format!(
955            "Fix Entire finding [{}] at {}",
956            first.handle, first.location
957        );
958        if let Some(severity) = &first.severity {
959            let _ = write!(s, " ({severity})");
960        }
961        let _ = write!(s, ": {}", first.title);
962        let more = self.findings.len() - 1;
963        if more > 0 || self.findings_incomplete {
964            let _ = write!(
965                s,
966                "; {more}{} more open",
967                if self.findings_incomplete { "+" } else { "" }
968            );
969        }
970        s
971    }
972}
973
974#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
975pub struct Attention {
976    pub code: &'static str,
977    pub message: String,
978}
979
980fn is_zero(n: &u32) -> bool {
981    *n == 0
982}
983
984impl PrStatus {
985    /// The repository, with its host.
986    pub fn repository(&self) -> Option<Repo> {
987        match &self.host {
988            None => Repo::parse(&self.repo),
989            Some(host) => Repo::on(host, &self.repo),
990        }
991    }
992
993    /// The forge the PR is on.
994    pub fn forge_kind(&self) -> Forge {
995        self.repository()
996            .and_then(|r| r.forge())
997            .unwrap_or(Forge::GitHub)
998    }
999
1000    /// `HOST/OWNER/NAME#N`, or `OWNER/NAME#N` on GitHub: what a jouet
1001    /// command takes back.
1002    pub fn name(&self) -> String {
1003        match &self.host {
1004            None => format!("{}#{}", self.repo, self.number),
1005            Some(host) => format!("{host}/{}#{}", self.repo, self.number),
1006        }
1007    }
1008}
1009
1010/// The reasons an open PR needs attention, in a fixed order. Merged and
1011/// closed PRs need none.
1012fn attention(pr: &PrStatus, now: i64) -> Vec<Attention> {
1013    let mut out = Vec::new();
1014    if !matches!(pr.state, State::Open | State::Draft) {
1015        return out;
1016    }
1017    let mut add = |code, message: String| out.push(Attention { code, message });
1018    let forge = pr.forge_kind();
1019    if pr.mergeable == Mergeability::Conflicting {
1020        let message = match forge {
1021            Forge::GitHub => format!(
1022                "Conflicts with {}; pull_request workflows will not run until it is rebased",
1023                pr.base
1024            ),
1025            _ => format!(
1026                "Conflicts with {}; it cannot merge until it is rebased",
1027                pr.base
1028            ),
1029        };
1030        add("conflict", message);
1031    }
1032    // A failing Entire Gates check is reported by its gates below, not as a
1033    // failing check of its own.
1034    let entire = pr.entire.as_ref().filter(|e| e.gates.failed());
1035    let gates_failing = u32::from(entire.is_some() && pr.checks.failing.iter().any(|c| c == CHECK));
1036    let failing: Vec<&str> = pr
1037        .checks
1038        .failing
1039        .iter()
1040        .map(String::as_str)
1041        .filter(|c| entire.is_none() || *c != CHECK)
1042        .collect();
1043    let fail = pr.checks.fail.saturating_sub(gates_failing);
1044    if fail > 0 {
1045        add(
1046            "checks_failing",
1047            format!("{fail} failing: {}", failing.join(", ")),
1048        );
1049    }
1050    if pr.checks.total() == 0
1051        && let Some(pushed) = pr.pushed_at.as_deref().and_then(time::parse_utc)
1052        && now - pushed > CHECKS_GRACE_SECS
1053    {
1054        add(
1055            "checks_missing",
1056            format!(
1057                "No checks registered {} after the last push",
1058                time::age(now - pushed)
1059            ),
1060        );
1061    }
1062    if pr.review.as_deref() == Some("changes_requested") {
1063        add("changes_requested", "A reviewer requested changes".into());
1064    }
1065    match pr.unresolved_threads {
1066        0 => {}
1067        1 => add("unresolved_threads", "1 unresolved review thread".into()),
1068        n => add(
1069            "unresolved_threads",
1070            format!("{n} unresolved review threads"),
1071        ),
1072    }
1073    if let Some(e) = entire {
1074        if e.gates.fails("findings") {
1075            add("entire_findings", e.findings_message());
1076        }
1077        let known = ["checks", "findings", "up_to_date"];
1078        let other: Vec<&Gate> = e
1079            .gates
1080            .failing()
1081            .filter(|g| !known.contains(&g.gate.as_str()))
1082            .collect();
1083        if !other.is_empty() || e.gates.failing().next().is_none() {
1084            add(
1085                "entire_gates",
1086                format!("Entire Gates: {}", e.gates.failing_text()),
1087            );
1088        }
1089    }
1090    if pr.merge_state == "behind" {
1091        add(
1092            "behind_base",
1093            format!("Behind {}; update the branch before it can merge", pr.base),
1094        );
1095    } else if let Some(e) = entire.filter(|e| e.gates.fails("up_to_date"))
1096        && pr.mergeable != Mergeability::Conflicting
1097    {
1098        // Entire may want the branch current where GitHub does not.
1099        let reason = e
1100            .gates
1101            .failing()
1102            .find(|g| g.gate == "up_to_date")
1103            .and_then(|g| g.reason.clone())
1104            .unwrap_or_else(|| "not up to date".into());
1105        add(
1106            "behind_base",
1107            format!(
1108                "Entire Gates: {reason}; update the branch from {} before it can merge",
1109                pr.base
1110            ),
1111        );
1112    }
1113    if pr.state == State::Draft {
1114        add("draft", "The PR is a draft".into());
1115    }
1116    if pr.mergeable == Mergeability::Unknown {
1117        add(
1118            "mergeable_unknown",
1119            format!(
1120                "{} has not finished computing mergeability; run again shortly",
1121                forge.name()
1122            ),
1123        );
1124    }
1125    out
1126}
1127
1128#[cfg(test)]
1129#[path = "status_tests.rs"]
1130mod tests;