Skip to main content

jouet_github/pr/threads/
mod.rs

1//! Review threads: fetching every thread of a PR, selecting the ones a
2//! listing asks for, and finding when a commit was pushed.
3//!
4//! A thread's handle is the database ID of its first comment. That is the
5//! number in the web UI's `#discussion_r...` links, and it maps to both the
6//! GraphQL thread ID that resolving needs and the comment a reply goes under.
7//! Threads come 100 to a page, as do the comments of each thread, and every
8//! further page is fetched, so nothing is silently left out.
9
10pub mod condense;
11pub mod write;
12
13#[cfg(test)]
14mod tests;
15
16use super::target::{Repo, Target};
17use crate::Client;
18use jouet_output::time;
19use serde::{Deserialize, Serialize};
20use serde_json::{Value, json};
21
22const COMMENT: &str = "fullDatabaseId url createdAt body author { __typename login }";
23const PAGE: &str = "pageInfo { hasNextPage endCursor }";
24
25/// GitHub lists at most this many commits of a PR.
26const MAX_COMMITS: usize = 250;
27
28fn thread_fields() -> String {
29    format!(
30        "id isResolved isOutdated path line startLine originalLine originalStartLine \
31         diffSide startDiffSide comments(first: 100) {{ {PAGE} nodes {{ {COMMENT} }} }}"
32    )
33}
34
35/// The query for a PR's threads, and with `extra` its reviews and
36/// conversation comments.
37pub(crate) fn query() -> String {
38    format!(
39        "query($o: String!, $r: String!, $n: Int!, $extra: Boolean!) {{
40  viewer {{ login }}
41  repository(owner: $o, name: $r) {{ pullRequest(number: $n) {{
42    id number url headRefName headRefOid baseRefOid headRepository {{ nameWithOwner }}
43    reviewThreads(first: 100) {{ {PAGE} nodes {{ {threads} }} }}
44    reviews(first: 100) @include(if: $extra) {{ {PAGE} nodes {{ state {COMMENT} }} }}
45    comments(first: 100) @include(if: $extra) {{ {PAGE} nodes {{ {COMMENT} }} }}
46  }} }}
47}}",
48        threads = thread_fields()
49    )
50}
51
52const BRANCH_QUERY: &str = "query($o: String!, $r: String!, $b: String!) {
53  repository(owner: $o, name: $r) {
54    open: pullRequests(headRefName: $b, states: OPEN, first: 1, orderBy: {field: CREATED_AT, direction: DESC}) { nodes { number } }
55    newest: pullRequests(headRefName: $b, first: 1, orderBy: {field: CREATED_AT, direction: DESC}) { nodes { number } }
56  }
57}";
58
59/// A PR with every review thread, and its reviews and conversation comments
60/// when they were asked for.
61#[derive(Debug, Clone)]
62pub struct PrThreads {
63    pub repo: Repo,
64    pub number: u64,
65    pub(crate) node_id: String,
66    pub head_ref: String,
67    pub head_oid: String,
68    /// The base branch's head, from which the merge base is found.
69    pub base_oid: String,
70    pub head_repo: Option<Repo>,
71    /// The token's user, whose earlier replies a retry must not repeat.
72    pub(crate) viewer: String,
73    pub(crate) threads: Vec<Thread>,
74    /// Review summaries and conversation comments, oldest first.
75    pub(crate) others: Vec<Thread>,
76    /// Comments left out because GitHub sent neither their ID nor a URL that
77    /// holds it. A thread whose first comment is one of them is left out
78    /// whole, since that comment's ID is the thread's handle.
79    pub unreadable: usize,
80}
81
82/// Which side of the diff a thread's lines are on.
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
84#[serde(rename_all = "lowercase")]
85pub enum Side {
86    /// The base version: lines the PR deleted or kept.
87    #[serde(alias = "LEFT")]
88    Left,
89    /// The head version.
90    #[default]
91    #[serde(alias = "RIGHT")]
92    Right,
93}
94
95impl Side {
96    fn is_right(&self) -> bool {
97        *self == Self::Right
98    }
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
102#[serde(rename_all = "snake_case")]
103pub enum Kind {
104    Thread,
105    Review,
106    Comment,
107}
108
109#[derive(Debug, Clone, Serialize)]
110pub struct Thread {
111    pub id: u64,
112    #[serde(skip_serializing_if = "String::is_empty")]
113    pub(crate) node_id: String,
114    pub kind: Kind,
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub path: Option<String>,
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub line: Option<u32>,
119    /// The first line of a multi-line comment, when it is on the same side
120    /// of the diff as `line`.
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub start_line: Option<u32>,
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub original_line: Option<u32>,
125    /// `left` for a comment on the base version's lines (a deleted or
126    /// replaced line), whose numbers are not lines of the head's file.
127    /// Absent for the head's side.
128    #[serde(skip_serializing_if = "Side::is_right")]
129    pub side: Side,
130    #[serde(skip_serializing_if = "is_false")]
131    pub outdated: bool,
132    #[serde(skip_serializing_if = "is_false")]
133    pub resolved: bool,
134    pub author: String,
135    #[serde(skip_serializing_if = "is_false")]
136    pub(crate) is_bot: bool,
137    /// A review's state: `approved`, `changes_requested`, `commented`, ...
138    #[serde(skip_serializing_if = "Option::is_none")]
139    pub state: Option<String>,
140    pub(crate) url: String,
141    pub comments: Vec<Comment>,
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub context: Option<Context>,
144}
145
146#[derive(Debug, Clone, Serialize)]
147pub struct Comment {
148    pub(crate) id: u64,
149    pub author: String,
150    pub(crate) created_at: String,
151    pub body: String,
152    #[serde(skip_serializing_if = "is_false")]
153    pub body_truncated: bool,
154    #[serde(skip_serializing_if = "Option::is_none")]
155    pub suggestion: Option<String>,
156    #[serde(skip)]
157    pub(crate) url: String,
158    /// `created_at` in seconds since the epoch.
159    #[serde(skip)]
160    pub created: i64,
161}
162
163/// Lines of the file around a thread's line.
164#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
165pub struct Context {
166    pub start: u32,
167    pub lines: Vec<String>,
168}
169
170fn is_false(b: &bool) -> bool {
171    !*b
172}
173
174#[derive(Deserialize)]
175#[serde(rename_all = "camelCase")]
176struct RawPr {
177    id: String,
178    number: u64,
179    head_ref_name: String,
180    head_ref_oid: String,
181    base_ref_oid: String,
182    head_repository: Option<NameWithOwner>,
183    review_threads: Page<RawThread>,
184    reviews: Option<Page<RawComment>>,
185    comments: Option<Page<RawComment>>,
186}
187
188#[derive(Deserialize)]
189#[serde(rename_all = "camelCase")]
190struct NameWithOwner {
191    name_with_owner: String,
192}
193
194#[derive(Deserialize)]
195#[serde(rename_all = "camelCase")]
196struct Page<T> {
197    page_info: PageInfo,
198    nodes: Vec<T>,
199}
200
201#[derive(Deserialize)]
202#[serde(rename_all = "camelCase")]
203struct PageInfo {
204    has_next_page: bool,
205    end_cursor: Option<String>,
206}
207
208impl PageInfo {
209    fn next(&self) -> Option<String> {
210        self.end_cursor.clone().filter(|_| self.has_next_page)
211    }
212}
213
214#[derive(Deserialize)]
215#[serde(rename_all = "camelCase")]
216struct RawThread {
217    id: String,
218    is_resolved: bool,
219    is_outdated: bool,
220    path: Option<String>,
221    line: Option<u32>,
222    start_line: Option<u32>,
223    original_line: Option<u32>,
224    original_start_line: Option<u32>,
225    diff_side: Option<Side>,
226    start_diff_side: Option<Side>,
227    comments: Page<RawComment>,
228}
229
230#[derive(Deserialize)]
231#[serde(rename_all = "camelCase")]
232struct RawComment {
233    /// Nullable in GitHub's schema; the URL holds the same ID.
234    full_database_id: Option<String>,
235    url: String,
236    created_at: String,
237    body: String,
238    author: Option<RawAuthor>,
239    #[serde(default)]
240    state: Option<String>,
241}
242
243#[derive(Deserialize)]
244struct RawAuthor {
245    #[serde(rename = "__typename")]
246    typename: String,
247    login: String,
248}
249
250fn parse<T: serde::de::DeserializeOwned>(value: &Value, what: &str) -> Result<T, String> {
251    T::deserialize(value).map_err(|e| format!("GitHub sent {what} jouet could not read: {e}"))
252}
253
254/// Fetches a PR's threads, and with `extra` its reviews and conversation
255/// comments. `None` when the repository or PR does not exist.
256pub fn fetch(
257    client: &mut Client,
258    target: &Target,
259    extra: bool,
260    bots: &[String],
261) -> Result<Option<PrThreads>, String> {
262    let (repo, number) = match target {
263        Target::Number(repo, n) => (repo, *n),
264        Target::Branch(repo, branch) => {
265            let vars = json!({ "o": repo.owner, "r": repo.name, "b": branch });
266            let data = client.graphql(BRANCH_QUERY, &vars)?;
267            let entry = &data["repository"];
268            let open = &entry["open"]["nodes"][0]["number"];
269            let number = if open.is_null() {
270                &entry["newest"]["nodes"][0]["number"]
271            } else {
272                open
273            };
274            match number.as_u64() {
275                Some(n) => (repo, n),
276                None => return Ok(None),
277            }
278        }
279    };
280    let vars = json!({ "o": repo.owner, "r": repo.name, "n": number, "extra": extra });
281    let data = client.graphql(&query(), &vars)?;
282    let mut pages = Pages::default();
283    let Some(mut pr) = read(repo, &data, bots, &mut pages)? else {
284        return Ok(None);
285    };
286    pages.fetch(client, &mut pr, bots)?;
287    pr.others
288        .sort_by_key(|t| t.comments.first().map_or(0, |c| c.created));
289    Ok(Some(pr))
290}
291
292/// Further pages still to fetch: of the PR's threads, reviews and comments
293/// (by the PR's node ID), and of each thread's comments (by thread index).
294#[derive(Default)]
295struct Pages {
296    threads: Option<String>,
297    reviews: Option<String>,
298    comments: Option<String>,
299    thread_comments: Vec<(usize, String)>,
300}
301
302impl Pages {
303    fn fetch(
304        &mut self,
305        client: &mut Client,
306        pr: &mut PrThreads,
307        bots: &[String],
308    ) -> Result<(), String> {
309        let threads = thread_fields();
310        let reviews = format!("state {COMMENT}");
311        loop {
312            let (field, nodes, after) = if let Some(after) = self.threads.take() {
313                ("reviewThreads", threads.as_str(), after)
314            } else if let Some(after) = self.reviews.take() {
315                ("reviews", reviews.as_str(), after)
316            } else if let Some(after) = self.comments.take() {
317                ("comments", COMMENT, after)
318            } else {
319                break;
320            };
321            let q = format!(
322                "query($id: ID!, $c: String!) {{ node(id: $id) {{ ... on PullRequest {{ \
323                 {field}(first: 100, after: $c) {{ {PAGE} nodes {{ {nodes} }} }} }} }} }}"
324            );
325            let data = client.graphql(&q, &json!({ "id": pr.node_id, "c": after }))?;
326            let entry = &data["node"][field];
327            match field {
328                "reviewThreads" => {
329                    let page: Page<RawThread> = parse(entry, "review threads")?;
330                    self.threads = page.page_info.next();
331                    self.add_threads(pr, page.nodes, bots);
332                }
333                _ => {
334                    let page: Page<RawComment> = parse(entry, "comments")?;
335                    let kind = if field == "reviews" {
336                        self.reviews = page.page_info.next();
337                        Kind::Review
338                    } else {
339                        self.comments = page.page_info.next();
340                        Kind::Comment
341                    };
342                    add_others(pr, kind, page.nodes, bots);
343                }
344            }
345        }
346        while let Some((i, after)) = self.thread_comments.pop() {
347            let q = format!(
348                "query($id: ID!, $c: String!) {{ node(id: $id) {{ ... on PullRequestReviewThread {{ \
349                 comments(first: 100, after: $c) {{ {PAGE} nodes {{ {COMMENT} }} }} }} }} }}"
350            );
351            let thread = &mut pr.threads[i];
352            let data = client.graphql(&q, &json!({ "id": thread.node_id, "c": after }))?;
353            let page: Page<RawComment> = parse(&data["node"]["comments"], "thread comments")?;
354            for raw in page.nodes {
355                match comment(raw) {
356                    Some(c) => thread.comments.push(c),
357                    None => pr.unreadable += 1,
358                }
359            }
360            if let Some(next) = page.page_info.next() {
361                self.thread_comments.push((i, next));
362            }
363        }
364        Ok(())
365    }
366
367    fn add_threads(&mut self, pr: &mut PrThreads, raw: Vec<RawThread>, bots: &[String]) {
368        for raw in raw {
369            let total = raw.comments.nodes.len();
370            let mut nodes = raw.comments.nodes.into_iter();
371            // A thread whose comments were all deleted has no handle.
372            let Some(first) = nodes.next() else {
373                continue;
374            };
375            let Some(first) = comment(first) else {
376                pr.unreadable += total;
377                continue;
378            };
379            let mut comments = vec![first];
380            for raw in nodes {
381                match comment(raw) {
382                    Some(c) => comments.push(c),
383                    None => pr.unreadable += 1,
384                }
385            }
386            if let Some(next) = raw.comments.page_info.next() {
387                self.thread_comments.push((pr.threads.len(), next));
388            }
389            let first = &comments[0];
390            pr.threads.push(Thread {
391                id: first.id,
392                node_id: raw.id,
393                kind: Kind::Thread,
394                path: raw.path,
395                line: raw.line,
396                // A range that starts on the other side of the diff has no
397                // first line in `line`'s file.
398                start_line: raw
399                    .start_line
400                    .or(raw.original_start_line.filter(|_| raw.line.is_none()))
401                    .filter(|_| raw.start_diff_side.is_none_or(|s| Some(s) == raw.diff_side)),
402                original_line: raw.original_line,
403                side: raw.diff_side.unwrap_or_default(),
404                outdated: raw.is_outdated,
405                resolved: raw.is_resolved,
406                is_bot: is_bot(&first.author, bots),
407                author: first.author.clone(),
408                state: None,
409                url: first.url.clone(),
410                comments,
411                context: None,
412            });
413        }
414    }
415}
416
417fn read(
418    repo: &Repo,
419    data: &Value,
420    bots: &[String],
421    pages: &mut Pages,
422) -> Result<Option<PrThreads>, String> {
423    let entry = &data["repository"]["pullRequest"];
424    if entry.is_null() {
425        return Ok(None);
426    }
427    let raw: RawPr = parse(entry, "a PR")?;
428    let mut pr = PrThreads {
429        repo: repo.clone(),
430        number: raw.number,
431        node_id: raw.id,
432        head_ref: raw.head_ref_name,
433        head_oid: raw.head_ref_oid,
434        base_oid: raw.base_ref_oid,
435        head_repo: raw
436            .head_repository
437            .and_then(|r| Repo::parse(&r.name_with_owner)),
438        viewer: data["viewer"]["login"]
439            .as_str()
440            .unwrap_or_default()
441            .to_string(),
442        threads: Vec::new(),
443        others: Vec::new(),
444        unreadable: 0,
445    };
446    pages.threads = raw.review_threads.page_info.next();
447    pages.add_threads(&mut pr, raw.review_threads.nodes, bots);
448    if let Some(reviews) = raw.reviews {
449        pages.reviews = reviews.page_info.next();
450        add_others(&mut pr, Kind::Review, reviews.nodes, bots);
451    }
452    if let Some(comments) = raw.comments {
453        pages.comments = comments.page_info.next();
454        add_others(&mut pr, Kind::Comment, comments.nodes, bots);
455    }
456    Ok(Some(pr))
457}
458
459/// Adds review summaries or conversation comments; reviews with no summary
460/// (a bare batch of line comments) are left out.
461fn add_others(pr: &mut PrThreads, kind: Kind, raw: Vec<RawComment>, bots: &[String]) {
462    for raw in raw {
463        if raw.body.trim().is_empty() {
464            continue;
465        }
466        let state = raw.state.as_deref().map(str::to_ascii_lowercase);
467        let Some(c) = comment(raw) else {
468            pr.unreadable += 1;
469            continue;
470        };
471        pr.others.push(Thread {
472            id: c.id,
473            node_id: String::new(),
474            kind,
475            path: None,
476            line: None,
477            start_line: None,
478            original_line: None,
479            side: Side::Right,
480            outdated: false,
481            resolved: false,
482            is_bot: is_bot(&c.author, bots),
483            author: c.author.clone(),
484            state,
485            url: c.url.clone(),
486            comments: vec![c],
487            context: None,
488        });
489    }
490}
491
492/// A comment, or `None` when GitHub sent no ID jouet can read, in
493/// `fullDatabaseId` or in the URL.
494fn comment(raw: RawComment) -> Option<Comment> {
495    let id = raw
496        .full_database_id
497        .as_deref()
498        .and_then(|id| id.parse().ok())
499        .or_else(|| url_id(&raw.url))?;
500    let author = match raw.author {
501        // GraphQL names an app `coderabbitai`; REST and the web UI say
502        // `coderabbitai[bot]`, which is what people filter by.
503        Some(a) if a.typename == "Bot" && !a.login.ends_with("[bot]") => {
504            format!("{}[bot]", a.login)
505        }
506        Some(a) => a.login,
507        None => "ghost".into(),
508    };
509    Some(Comment {
510        id,
511        author,
512        created: time::parse_utc(&raw.created_at).unwrap_or(0),
513        created_at: raw.created_at,
514        body: raw.body,
515        body_truncated: false,
516        suggestion: None,
517        url: raw.url,
518    })
519}
520
521/// The database ID at the end of a comment's URL: `#discussion_r55500`,
522/// `#issuecomment-66601` or `#pullrequestreview-4401`.
523fn url_id(url: &str) -> Option<u64> {
524    let (_, fragment) = url.rsplit_once('#')?;
525    fragment
526        .trim_start_matches(|c: char| !c.is_ascii_digit())
527        .parse()
528        .ok()
529}
530
531pub(crate) fn is_bot(login: &str, bots: &[String]) -> bool {
532    login.ends_with("[bot]") || bots.iter().any(|b| b.eq_ignore_ascii_case(login))
533}
534
535/// Whether `login` names `author`, ignoring case and a missing `[bot]`.
536pub(crate) fn same_login(login: &str, author: &str) -> bool {
537    let bare = |s: &str| s.strip_suffix("[bot]").unwrap_or(s).to_ascii_lowercase();
538    bare(login) == bare(author)
539}
540
541#[derive(Debug, Clone, Copy, PartialEq, Eq)]
542pub enum Status {
543    Unresolved,
544    Resolved,
545    All,
546}
547
548/// Which threads a listing shows. `None` means "either".
549#[derive(Debug, Clone)]
550pub struct Filter {
551    pub status: Status,
552    pub outdated: Option<bool>,
553    pub authors: Vec<String>,
554    pub bots: Option<bool>,
555    pub since: Option<i64>,
556    pub paths: Vec<String>,
557}
558
559#[derive(Debug, Default, PartialEq, Eq, Serialize)]
560pub struct Counts {
561    pub unresolved: usize,
562    pub resolved: usize,
563    /// Unresolved threads whose line has since changed.
564    pub outdated: usize,
565}
566
567pub fn counts(pr: &PrThreads) -> Counts {
568    let mut c = Counts::default();
569    for t in &pr.threads {
570        if t.resolved {
571            c.resolved += 1;
572        } else {
573            c.unresolved += 1;
574            c.outdated += usize::from(t.outdated);
575        }
576    }
577    c
578}
579
580/// The threads (then reviews and comments) a filter keeps, in order.
581pub fn select<'a>(pr: &'a PrThreads, f: &Filter) -> Vec<&'a Thread> {
582    let keep = |t: &&Thread| {
583        let status = t.kind != Kind::Thread
584            || match f.status {
585                Status::Unresolved => !t.resolved,
586                Status::Resolved => t.resolved,
587                Status::All => true,
588            };
589        let outdated = f.outdated.is_none_or(|o| o == t.outdated);
590        let author = f.authors.is_empty() || f.authors.iter().any(|a| same_login(a, &t.author));
591        let bots = f.bots.is_none_or(|b| b == t.is_bot);
592        let since = f
593            .since
594            .is_none_or(|since| t.comments.iter().any(|c| c.created >= since));
595        let path = f.paths.is_empty()
596            || t.path
597                .as_deref()
598                .is_some_and(|p| f.paths.iter().any(|g| path_matches(g, p)));
599        status && outdated && author && bots && since && path
600    };
601    pr.threads.iter().chain(&pr.others).filter(keep).collect()
602}
603
604/// Whether a listing's filter keeps an Entire finding, read the way a
605/// thread is: a stale finding is outdated, an agent's (`agent:...`) a
606/// bot's, and `since` goes by when it was raised. Its status is chosen
607/// when the findings are fetched.
608pub fn keeps_finding(f: &Filter, finding: &crate::entire::Finding) -> bool {
609    let outdated = f.outdated.is_none_or(|o| o == finding.stale);
610    let author = f.authors.is_empty() || f.authors.iter().any(|a| same_login(a, &finding.author));
611    let bots = f
612        .bots
613        .is_none_or(|b| b == finding.author.starts_with("agent:"));
614    let since = f
615        .since
616        .is_none_or(|since| time::parse_utc(&finding.created_at).is_some_and(|t| t >= since));
617    let path = f.paths.is_empty()
618        || finding
619            .path
620            .as_deref()
621            .is_some_and(|p| f.paths.iter().any(|g| path_matches(g, p)));
622    outdated && author && bots && since && path
623}
624
625/// Whether `path` matches a `--path` pattern: a glob over the whole path
626/// (`*` and `?` stay within a directory, `**` crosses them), a directory
627/// holding it, or, for a pattern without `/`, its file name.
628pub(crate) fn path_matches(pattern: &str, path: &str) -> bool {
629    let dir = pattern.trim_end_matches('/');
630    if path
631        .strip_prefix(dir)
632        .is_some_and(|rest| rest.starts_with('/'))
633    {
634        return true;
635    }
636    if !pattern.contains('/') {
637        let name = path.rsplit('/').next().unwrap_or(path);
638        return glob(pattern.as_bytes(), name.as_bytes());
639    }
640    glob(pattern.as_bytes(), path.as_bytes())
641}
642
643fn glob(p: &[u8], s: &[u8]) -> bool {
644    match p {
645        [] => s.is_empty(),
646        [b'*', b'*'] => true,
647        [b'*', b'*', rest @ ..] => {
648            // `**/` matches no directories, or any number of whole ones.
649            let rest = rest.strip_prefix(b"/").unwrap_or(rest);
650            glob(rest, s)
651                || s.iter()
652                    .enumerate()
653                    .any(|(i, &c)| c == b'/' && glob(rest, &s[i + 1..]))
654        }
655        [b'*', rest @ ..] => (0..=s.len())
656            .take_while(|&i| i == 0 || s[i - 1] != b'/')
657            .any(|i| glob(rest, &s[i..])),
658        [b'?', rest @ ..] => s.first().is_some_and(|&c| c != b'/') && glob(rest, &s[1..]),
659        [c, rest @ ..] => s.first() == Some(c) && glob(rest, &s[1..]),
660    }
661}
662
663/// One entry of GitHub's repository activity log.
664#[derive(Debug, Deserialize)]
665pub(crate) struct Activity {
666    pub(crate) after: String,
667    pub(crate) timestamp: String,
668}
669
670/// The commit an `@SHA` names, and when it was pushed to the PR.
671#[derive(Debug, PartialEq, Eq)]
672pub struct Pushed {
673    pub oid: String,
674    pub at: i64,
675    /// Set when the activity log had no push of it, so `at` is the
676    /// commit's own time: earlier than the push, so nothing is missed.
677    pub estimated: bool,
678}
679
680/// Finds when `sha` (a prefix of at least 4 characters) was pushed to the
681/// PR: one of its commits, or a head it had before a force-push. `Err` says
682/// why `sha` names no such commit.
683pub fn pushed_at(client: &mut Client, pr: &PrThreads, sha: &str) -> Result<Pushed, Lookup> {
684    let sha = sha_prefix(sha)?;
685    let commits = commits(client, pr).map_err(Lookup::Remote)?;
686    let repo = pr.head_repo.as_ref().unwrap_or(&pr.repo);
687    let path = format!(
688        "/repos/{repo}/activity?ref={}&per_page=100",
689        encode(&format!("refs/heads/{}", pr.head_ref))
690    );
691    let activity: Vec<Activity> = match client.rest_get(&path) {
692        Ok(Some(v)) => parse(&v, "repository activity").unwrap_or_default(),
693        Ok(None) => Vec::new(),
694        Err(e) => {
695            eprintln!("jouet: could not read the push log of {repo} ({e})");
696            Vec::new()
697        }
698    };
699    pushed_from(&commits, &activity, &sha)
700}
701
702/// `sha` lowercased, when it is at least 4 hex digits.
703pub(crate) fn sha_prefix(sha: &str) -> Result<String, Lookup> {
704    let sha = sha.to_ascii_lowercase();
705    if sha.len() < 4 || !sha.bytes().all(|b| b.is_ascii_hexdigit()) {
706        return Err(Lookup::Usage(format!(
707            "`{sha}` is not a commit SHA (give at least 4 hex digits)"
708        )));
709    }
710    Ok(sha)
711}
712
713/// When the commit `sha` (a lowercase prefix) names reached the PR, from
714/// its commits (oldest first, with their commit times) and a log of pushes.
715pub(crate) fn pushed_from(
716    commits: &[(String, i64)],
717    activity: &[Activity],
718    sha: &str,
719) -> Result<Pushed, Lookup> {
720    let oid = find_commit(commits, activity, sha)?;
721    let oids: Vec<&str> = commits.iter().map(|(o, _)| o.as_str()).collect();
722    Ok(match push_time(activity, &oids, &oid) {
723        Some(at) => Pushed {
724            oid,
725            at,
726            estimated: false,
727        },
728        None => {
729            // Only a PR commit can be missing from the log.
730            let at = commits
731                .iter()
732                .find(|(o, _)| *o == oid)
733                .map_or(0, |(_, at)| *at);
734            Pushed {
735                oid,
736                at,
737                estimated: true,
738            }
739        }
740    })
741}
742
743/// Why an `@SHA` could not be used.
744#[derive(Debug, PartialEq, Eq)]
745pub enum Lookup {
746    NotFound(String),
747    /// Not a SHA, or one naming more than one commit.
748    Usage(String),
749    Remote(String),
750}
751
752/// The PR's commits, oldest first, with their commit times.
753fn commits(client: &mut Client, pr: &PrThreads) -> Result<Vec<(String, i64)>, String> {
754    let q = "query($id: ID!, $c: String) { node(id: $id) { ... on PullRequest { \
755             commits(first: 100, after: $c) { pageInfo { hasNextPage endCursor } \
756             nodes { commit { oid committedDate } } } } } }";
757    let mut out = Vec::new();
758    let mut after: Option<String> = None;
759    loop {
760        let data = client.graphql(q, &json!({ "id": pr.node_id, "c": after }))?;
761        let entry = &data["node"]["commits"];
762        for node in entry["nodes"].as_array().into_iter().flatten() {
763            let commit = &node["commit"];
764            let oid = commit["oid"].as_str().unwrap_or_default().to_string();
765            let at = commit["committedDate"]
766                .as_str()
767                .and_then(time::parse_utc)
768                .unwrap_or(0);
769            out.push((oid, at));
770        }
771        after = entry["pageInfo"]["endCursor"]
772            .as_str()
773            .filter(|_| entry["pageInfo"]["hasNextPage"].as_bool() == Some(true))
774            .map(str::to_string);
775        if after.is_none() || out.len() >= MAX_COMMITS {
776            return Ok(out);
777        }
778    }
779}
780
781/// The one commit `sha` starts: a commit of the PR, or a head the push log
782/// shows it had. `sha` is lowercase hex.
783fn find_commit(
784    commits: &[(String, i64)],
785    activity: &[Activity],
786    sha: &str,
787) -> Result<String, Lookup> {
788    let mut found: Vec<&str> = commits
789        .iter()
790        .map(|(o, _)| o.as_str())
791        .chain(activity.iter().map(|a| a.after.as_str()))
792        .filter(|o| o.starts_with(sha))
793        .collect();
794    found.sort_unstable();
795    found.dedup();
796    match found.as_slice() {
797        [one] => Ok((*one).to_string()),
798        [] => Err(Lookup::NotFound(format!(
799            "{sha} is not a commit of this PR, nor a head it was pushed with"
800        ))),
801        _ => Err(Lookup::Usage(format!(
802            "{sha} matches {} commits of this PR; give more of the SHA",
803            found.len()
804        ))),
805    }
806}
807
808/// When `oid` reached the branch: the earliest push whose new head is `oid`
809/// or a later commit of the PR. `commits` is the PR's commits, oldest first.
810pub(crate) fn push_time(activity: &[Activity], commits: &[&str], oid: &str) -> Option<i64> {
811    let index = commits.iter().position(|c| *c == oid);
812    activity
813        .iter()
814        .filter(|a| {
815            a.after == oid
816                || index.is_some_and(|i| {
817                    commits
818                        .iter()
819                        .position(|c| *c == a.after)
820                        .is_some_and(|j| j >= i)
821                })
822        })
823        .filter_map(|a| time::parse_utc(&a.timestamp))
824        .min()
825}
826
827/// Percent-encodes a query-string value.
828fn encode(s: &str) -> String {
829    let mut out = String::new();
830    for b in s.bytes() {
831        if b.is_ascii_alphanumeric() || b"-_.~/".contains(&b) {
832            out.push(char::from(b));
833        } else {
834            out.push_str(&format!("%{b:02X}"));
835        }
836    }
837    out
838}