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