Skip to main content

sandogasa_github/
lib.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3//! HTTP client for the GitHub REST API.
4//!
5//! Scoped to the surface `sandogasa-report` needs for activity
6//! reports: user identity lookup, token validation, paginated
7//! user events (to find which repos a user touched in a window),
8//! the Search API for pull requests, per-repo authored-commit
9//! counts, and through GraphQL, a user's contributions over a period
10//! and their comments on issues and pull requests.
11//!
12//! Mirrors `sandogasa-gitlab` in shape so downstream tools can
13//! treat the two forges the same way structurally — host-keyed
14//! tokens and identities, optional org/group filter, etc.
15//!
16//! ```no_run
17//! use sandogasa_github::Client;
18//!
19//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
20//! let client = Client::new("https://api.github.com", "ghp_token")?;
21//! let user = client.user_by_username("octocat")?.expect("user exists");
22//! let prs = client.search_pull_requests(
23//!     &format!("type:pr author:{} created:2026-01-01..2026-03-31", user.login),
24//! )?;
25//! for pr in prs {
26//!     println!("{}: {}", pr.number, pr.title);
27//! }
28//! # Ok(())
29//! # }
30//! ```
31
32use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderName, HeaderValue};
33use sandogasa_cli::http;
34use std::collections::{BTreeMap, BTreeSet};
35
36use serde::{Deserialize, Serialize};
37use serde_json::json;
38
39/// A GitHub user as returned by `/users/{username}`. Only the
40/// fields downstream tools currently consume.
41#[derive(Debug, Clone, Deserialize, Serialize)]
42#[non_exhaustive]
43pub struct User {
44    pub id: u64,
45    pub login: String,
46    /// Public display name (`null` when the user hasn't set one).
47    #[serde(default)]
48    pub name: Option<String>,
49    /// Public email (`null` when the user keeps it private).
50    #[serde(default)]
51    pub email: Option<String>,
52}
53
54/// A repository as returned by event payloads and PR responses.
55#[derive(Debug, Clone, Deserialize, Serialize)]
56#[non_exhaustive]
57pub struct Repository {
58    pub id: u64,
59    /// `owner/name`, e.g. `slopfest/sandogasa`.
60    #[serde(default)]
61    pub full_name: Option<String>,
62    /// For event payloads where `repo.name` already carries the
63    /// `owner/name` form; preserved verbatim.
64    #[serde(default)]
65    pub name: Option<String>,
66}
67
68impl Repository {
69    /// Best-effort `owner/name` extractor. Falls back to `name`
70    /// for event payloads where `repo.full_name` is omitted.
71    pub fn slug(&self) -> Option<&str> {
72        self.full_name.as_deref().or(self.name.as_deref())
73    }
74}
75
76/// A pull request as returned by the Search Issues endpoint
77/// when filtering on `type:pr`. The Search API actually returns
78/// "issue" objects with PR-specific fields populated, so we
79/// shape this around the union of useful fields rather than the
80/// fuller `/repos/{owner}/{repo}/pulls/{number}` model.
81#[derive(Debug, Clone, Deserialize, Serialize)]
82#[non_exhaustive]
83pub struct PullRequest {
84    pub number: u64,
85    pub title: String,
86    pub state: String,
87    /// Set when the PR has been merged. Some search responses
88    /// omit this field for open PRs.
89    #[serde(default)]
90    pub pull_request: Option<PullRequestRef>,
91    pub html_url: String,
92    /// The repo this PR lives in — derived from `html_url` since
93    /// the search response doesn't include a structured `repo`
94    /// object.
95    #[serde(default)]
96    pub repository_url: Option<String>,
97}
98
99impl PullRequest {
100    /// Extract the `owner/name` slug from this PR's HTML URL or
101    /// `repository_url`.
102    pub fn repo_slug(&self) -> Option<String> {
103        // html_url shape: `https://github.com/{owner}/{repo}/pull/N`
104        if let Some(rest) = self
105            .html_url
106            .strip_prefix("https://github.com/")
107            .or_else(|| self.html_url.strip_prefix("https://"))
108        {
109            let parts: Vec<&str> = rest.splitn(4, '/').collect();
110            if parts.len() >= 2 {
111                return Some(format!("{}/{}", parts[0], parts[1]));
112            }
113        }
114        // Fallback: repository_url shape is
115        // `https://api.github.com/repos/{owner}/{repo}`.
116        if let Some(repo) = &self.repository_url
117            && let Some(rest) = repo.split("/repos/").nth(1)
118        {
119            return Some(rest.to_string());
120        }
121        None
122    }
123
124    /// Whether this PR has been merged. The Search API surfaces
125    /// merge state via the optional `pull_request.merged_at`
126    /// field; absence means "not merged".
127    pub fn merged_at(&self) -> Option<&str> {
128        self.pull_request
129            .as_ref()
130            .and_then(|p| p.merged_at.as_deref())
131    }
132}
133
134/// Auxiliary block on a search-result issue when it's actually
135/// a pull request. The Search Issues endpoint signals "is PR"
136/// by populating this; merged state lives here too.
137#[derive(Debug, Clone, Deserialize, Serialize)]
138#[non_exhaustive]
139pub struct PullRequestRef {
140    #[serde(default)]
141    pub merged_at: Option<String>,
142}
143
144/// The fuller pull-request object from `/repos/{owner}/{repo}/pulls/{n}`:
145/// the head and base refs the search result omits, and whether it merged.
146#[derive(Debug, Clone, Deserialize)]
147#[non_exhaustive]
148pub struct PullRequestDetail {
149    pub number: u64,
150    pub state: String,
151    #[serde(default)]
152    pub merged: bool,
153    pub head: GitRef,
154    pub base: GitRef,
155    /// When the PR was opened (RFC 3339).
156    #[serde(default)]
157    pub created_at: Option<String>,
158    /// Who opened it.
159    #[serde(default)]
160    pub user: Option<Login>,
161}
162
163/// An account named only by its login.
164#[derive(Debug, Clone, Deserialize)]
165#[non_exhaustive]
166pub struct Login {
167    pub login: String,
168}
169
170/// A commit from `/pulls/{n}/commits` or `/commits`: the sha, the
171/// message and the author of the commit itself (not the GitHub account).
172#[derive(Debug, Clone, Deserialize)]
173#[non_exhaustive]
174pub struct RepoCommit {
175    pub sha: String,
176    pub commit: CommitBody,
177}
178
179/// The git-level part of a commit.
180#[derive(Debug, Clone, Deserialize)]
181#[non_exhaustive]
182pub struct CommitBody {
183    #[serde(default)]
184    pub message: String,
185    #[serde(default)]
186    pub author: Option<CommitAuthor>,
187}
188
189/// A commit's author as git recorded it.
190#[derive(Debug, Clone, Deserialize)]
191#[non_exhaustive]
192pub struct CommitAuthor {
193    #[serde(default)]
194    pub name: String,
195    #[serde(default)]
196    pub email: String,
197    /// When git recorded it (ISO 8601), if the forge said.
198    #[serde(default)]
199    pub date: Option<String>,
200}
201
202impl RepoCommit {
203    /// The message's first line.
204    pub fn title(&self) -> &str {
205        self.commit.message.lines().next().unwrap_or("")
206    }
207}
208
209/// One side of a pull request: the branch name and the commit it points at.
210#[derive(Debug, Clone, Deserialize)]
211#[non_exhaustive]
212pub struct GitRef {
213    #[serde(rename = "ref")]
214    pub ref_name: String,
215    pub sha: String,
216}
217
218/// What `/compare/{base}...{head}` answers: `ahead_by` counts the commits
219/// on head that base lacks, so zero means base already has them all.
220#[derive(Debug, Deserialize)]
221struct CompareResult {
222    #[serde(default)]
223    ahead_by: u64,
224}
225
226/// Wire response wrapper for the Search Issues endpoint.
227#[derive(Debug, Deserialize)]
228struct SearchIssuesResponse {
229    total_count: u64,
230    items: Vec<PullRequest>,
231}
232
233/// One entry from `/users/{username}/events`. Fields are
234/// sparse; we keep just enough to identify the event type,
235/// associated repo, and the actor.
236#[derive(Debug, Clone, Deserialize, Serialize)]
237#[non_exhaustive]
238pub struct Event {
239    pub id: String,
240    /// `"PushEvent"`, `"PullRequestEvent"`,
241    /// `"PullRequestReviewCommentEvent"`, etc.
242    #[serde(rename = "type")]
243    pub event_type: String,
244    pub repo: Repository,
245    pub created_at: String,
246    /// Whether the event happened in a public repository. GitHub sets
247    /// it on every event; a missing value reads as private.
248    #[serde(default)]
249    pub public: bool,
250    /// Free-form payload — varies per event type.
251    #[serde(default)]
252    pub payload: serde_json::Value,
253}
254
255/// One entry from `/repos/{owner}/{repo}/git/refs/tags`. The
256/// underlying `object` distinguishes lightweight tags (point
257/// directly to a commit) from annotated tags (point to a Tag
258/// object that carries tagger info).
259#[derive(Debug, Clone, Deserialize, Serialize)]
260#[non_exhaustive]
261pub struct GitTagRef {
262    /// The fully-qualified ref, e.g. `refs/tags/v0.11.0`.
263    #[serde(rename = "ref")]
264    pub ref_name: String,
265    pub object: GitObject,
266}
267
268impl GitTagRef {
269    /// Strip the `refs/tags/` prefix to get just the tag name.
270    pub fn tag_name(&self) -> &str {
271        self.ref_name
272            .strip_prefix("refs/tags/")
273            .unwrap_or(&self.ref_name)
274    }
275}
276
277/// The thing a Git ref points at. `object_type` is `"commit"`
278/// for lightweight tags and `"tag"` for annotated ones.
279#[derive(Debug, Clone, Deserialize, Serialize)]
280#[non_exhaustive]
281pub struct GitObject {
282    #[serde(rename = "type")]
283    pub object_type: String,
284    pub sha: String,
285}
286
287/// An annotated-tag object from
288/// `/repos/{owner}/{repo}/git/tags/{sha}`. Only annotated tags
289/// carry tagger metadata; lightweight tags don't have an
290/// addressable tag object.
291#[derive(Debug, Clone, Deserialize, Serialize)]
292#[non_exhaustive]
293pub struct AnnotatedTag {
294    pub tag: String,
295    pub tagger: Tagger,
296}
297
298/// `name` + `email` + `date` triple stamped on annotated-tag
299/// creation. `date` is ISO 8601 (e.g. `2026-05-15T17:03:15Z`).
300#[derive(Debug, Clone, Deserialize, Serialize)]
301#[non_exhaustive]
302pub struct Tagger {
303    pub name: String,
304    pub email: String,
305    pub date: String,
306}
307
308impl Event {
309    /// Helper for callers walking events to find touched repos —
310    /// returns the `owner/name` slug if available.
311    pub fn repo_slug(&self) -> Option<&str> {
312        self.repo.slug()
313    }
314}
315
316/// A repository as GraphQL names it.
317#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
318#[non_exhaustive]
319pub struct RepoNode {
320    /// `owner/name`.
321    #[serde(rename = "nameWithOwner")]
322    pub name_with_owner: String,
323    #[serde(rename = "isPrivate")]
324    pub is_private: bool,
325}
326
327/// An issue or pull request as GraphQL gives it.
328#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
329#[non_exhaustive]
330pub struct ItemNode {
331    pub number: u64,
332    pub title: String,
333    pub url: String,
334    /// `OPEN` or `CLOSED`, and for a pull request `MERGED`.
335    pub state: String,
336    pub repository: RepoNode,
337}
338
339/// A comment of the user's on an issue or a pull request.
340#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
341#[non_exhaustive]
342pub struct IssueComment {
343    /// When it was written, RFC 3339 (`2026-11-18T15:11:37Z`).
344    #[serde(rename = "createdAt")]
345    pub created_at: String,
346    #[serde(rename = "updatedAt")]
347    pub updated_at: String,
348    pub url: String,
349    /// The issue, or the pull request taken as one.
350    pub issue: Option<ItemNode>,
351    /// The pull request, when the comment is on one.
352    #[serde(rename = "pullRequest")]
353    pub pull_request: Option<ItemNode>,
354}
355
356/// What a user contributed over a period, as GitHub's contribution
357/// graph counts it: commits on a repository's default branch (or
358/// `gh-pages`), and pull requests reviewed.
359#[derive(Debug, Clone, Default, PartialEq, Eq)]
360#[non_exhaustive]
361pub struct Contributions {
362    /// Per repository (`owner/name`), the commits made.
363    pub commits: BTreeMap<String, u64>,
364    /// The repositories among them, and among `reviewed`'s, that are
365    /// private.
366    pub private_repos: BTreeSet<String>,
367    /// The pull requests reviewed, each once.
368    pub reviewed: Vec<ItemNode>,
369    /// Reviews left out because the token cannot read them, and
370    /// GitHub's reasons.
371    pub unreadable: Unreadable,
372    /// Whether a single day named the most repositories GitHub gives
373    /// (100), so some may be missing.
374    pub capped: bool,
375    /// Contributions GitHub counts in private repositories without
376    /// naming them. An organization that refuses the token's kind
377    /// (classic personal access tokens, for some) leaves its
378    /// contributions out altogether, uncounted.
379    pub restricted: u64,
380}
381
382/// A user's comments on issues and pull requests.
383#[derive(Debug, Clone, Default, PartialEq, Eq)]
384#[non_exhaustive]
385pub struct Comments {
386    pub comments: Vec<IssueComment>,
387    /// Comments left out because the token cannot read them, and
388    /// GitHub's reasons.
389    pub unreadable: Unreadable,
390}
391
392/// Repositories' recent annotated tags, and the queries that failed.
393#[derive(Debug, Clone, Default)]
394#[non_exhaustive]
395pub struct RecentTags {
396    /// Per repository (`owner/name`), its annotated tags.
397    pub tags: BTreeMap<String, Vec<AnnotatedTag>>,
398    /// Per failed query, the repositories it asked about and why.
399    pub failures: Vec<String>,
400}
401
402/// Commits per repository, and the queries that failed.
403#[derive(Debug, Clone, Default, PartialEq, Eq)]
404#[non_exhaustive]
405pub struct CommitCounts {
406    /// Per repository (`owner/name`) with any, the commits.
407    pub counts: BTreeMap<String, u64>,
408    /// Per failed query, the repositories it asked about and why.
409    pub failures: Vec<String>,
410}
411
412/// Items GitHub withheld from an answer, such as those in an
413/// organization that refuses classic personal access tokens.
414#[derive(Debug, Clone, Default, PartialEq, Eq)]
415#[non_exhaustive]
416pub struct Unreadable {
417    pub count: usize,
418    /// GitHub's messages, each once.
419    pub reasons: BTreeSet<String>,
420}
421
422impl Unreadable {
423    fn add(&mut self, count: usize, errors: Option<Vec<GraphqlError>>) {
424        self.count += count;
425        if count > 0 {
426            self.reasons
427                .extend(errors.unwrap_or_default().into_iter().map(|e| e.message));
428        }
429    }
430}
431
432/// Blocking GitHub REST client.
433pub struct Client {
434    http: reqwest::blocking::Client,
435    base_url: String,
436}
437
438impl Client {
439    /// Build a client for `base_url` (typically
440    /// `https://api.github.com`, or a GHES instance's `/api/v3`
441    /// endpoint) authenticated with the given personal access
442    /// token.
443    pub fn new(base_url: &str, token: &str) -> Result<Self, Box<dyn std::error::Error>> {
444        sandogasa_cli::ensure_secure_url(base_url)?;
445        let http = build_http_client(token)?;
446        Ok(Self {
447            http,
448            base_url: base_url.trim_end_matches('/').to_string(),
449        })
450    }
451
452    /// Resolve a username to its full user object. Returns `None`
453    /// when the API responds with 404 (no such user); other
454    /// errors are returned as `Err`.
455    pub fn user_by_username(
456        &self,
457        username: &str,
458    ) -> Result<Option<User>, Box<dyn std::error::Error>> {
459        let url = format!("{}/users/{}", self.base_url, username);
460        let resp = self.http.get(&url).send()?;
461        if resp.status().as_u16() == 404 {
462            return Ok(None);
463        }
464        Ok(Some(http::blocking_json_ok(
465            resp,
466            &format!("GitHub GET {url}"),
467        )?))
468    }
469
470    /// Run the Search Issues endpoint with the caller-supplied
471    /// query string and return every PR across all result pages.
472    ///
473    /// GitHub caps Search results at 1000 items total; if a
474    /// query exceeds that, the caller needs to narrow it (e.g.
475    /// by splitting the date window).
476    pub fn search_pull_requests(
477        &self,
478        query: &str,
479    ) -> Result<Vec<PullRequest>, Box<dyn std::error::Error>> {
480        let mut out: Vec<PullRequest> = Vec::new();
481        let mut page = 1u32;
482        loop {
483            let page_str = page.to_string();
484            let url = format!("{}/search/issues", self.base_url);
485            let resp = self
486                .http
487                .get(&url)
488                .query(&[("q", query), ("per_page", "100"), ("page", &page_str)])
489                .send()?;
490            let batch: SearchIssuesResponse = http::blocking_json_ok(resp, "GitHub search")?;
491            let n = batch.items.len();
492            out.extend(batch.items);
493            if n < 100 || out.len() as u64 >= batch.total_count {
494                break;
495            }
496            page += 1;
497        }
498        Ok(out)
499    }
500
501    /// Paginate through the user-events endpoint up to GitHub's
502    /// 300-event cap. Returns the most recent events first.
503    pub fn user_events(&self, username: &str) -> Result<Vec<Event>, Box<dyn std::error::Error>> {
504        let mut out: Vec<Event> = Vec::new();
505        let mut page = 1u32;
506        loop {
507            let url = format!("{}/users/{}/events", self.base_url, username);
508            let page_str = page.to_string();
509            let resp = self
510                .http
511                .get(&url)
512                .query(&[("per_page", "100"), ("page", &page_str)])
513                .send()?;
514            let batch: Vec<Event> = http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
515            let n = batch.len();
516            out.extend(batch);
517            // GitHub serves at most 300 events / 3 pages of 100.
518            if n < 100 || page >= 3 {
519                break;
520            }
521            page += 1;
522        }
523        Ok(out)
524    }
525
526    /// Count commits in `owner/repo` authored by `author` within
527    /// `[since, until]` (inclusive). Used as a cross-check
528    /// against push-event counts — see the GitLab equivalent
529    /// for the rationale.
530    ///
531    /// 404 and 409 responses are treated as "0 commits" rather
532    /// than errors. 404 means the repo was deleted or made
533    /// private between the events scan and this call; 409 means
534    /// the repo exists but is empty. Either way, a single
535    /// missing repo shouldn't abort the surrounding report.
536    /// The trade-off: real auth failures targeting a single
537    /// repo would also be hidden, but GitHub returns 401/403 for
538    /// those, not 404/409.
539    pub fn count_authored_commits(
540        &self,
541        owner: &str,
542        repo: &str,
543        author: &str,
544        since: chrono::NaiveDate,
545        until: chrono::NaiveDate,
546    ) -> Result<u64, Box<dyn std::error::Error>> {
547        let url = format!("{}/repos/{}/{}/commits", self.base_url, owner, repo);
548        let since_str = format!("{since}T00:00:00Z");
549        let until_str = format!("{until}T23:59:59Z");
550        let mut total: u64 = 0;
551        let mut page = 1u32;
552        loop {
553            let page_str = page.to_string();
554            let query: Vec<(&str, &str)> = vec![
555                ("author", author),
556                ("since", &since_str),
557                ("until", &until_str),
558                ("per_page", "100"),
559                ("page", &page_str),
560            ];
561            let resp = self.http.get(&url).query(&query).send()?;
562            // GitHub returns 409 Conflict for empty repositories
563            // and 404 if the repo was deleted. Treat both as
564            // "no commits" rather than hard errors so a single
565            // gone repo doesn't abort the whole report.
566            if resp.status().as_u16() == 404 || resp.status().as_u16() == 409 {
567                break;
568            }
569            let batch: Vec<serde_json::Value> =
570                http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
571            let n = batch.len() as u64;
572            total += n;
573            if n < 100 {
574                break;
575            }
576            page += 1;
577        }
578        Ok(total)
579    }
580
581    /// List all tag refs for `owner/repo`. Returns an empty list
582    /// on 404 (gone repo) and 409 (empty repo) so callers can
583    /// iterate over many repos without per-repo error handling.
584    pub fn list_tag_refs(
585        &self,
586        owner: &str,
587        repo: &str,
588    ) -> Result<Vec<GitTagRef>, Box<dyn std::error::Error>> {
589        let url = format!("{}/repos/{}/{}/git/refs/tags", self.base_url, owner, repo);
590        let resp = self.http.get(&url).send()?;
591        // 404 = repo gone or no tags ref namespace; 409 = empty repo.
592        if resp.status().as_u16() == 404 || resp.status().as_u16() == 409 {
593            return Ok(Vec::new());
594        }
595        let resp = http::blocking_ok(resp, &format!("GitHub GET {url}"))?;
596        // GitHub returns an object (not an array) when there's
597        // exactly one match. The standard `/git/refs/tags` shape
598        // returns an array for the namespace listing; we only see
599        // the object form when someone queries a single ref. Be
600        // defensive and accept both.
601        let body: serde_json::Value = resp.json()?;
602        if body.is_array() {
603            Ok(serde_json::from_value(body)?)
604        } else {
605            Ok(vec![serde_json::from_value(body)?])
606        }
607    }
608
609    /// Fetch one annotated-tag object by SHA. Use only when the
610    /// matching `GitTagRef.object.object_type == "tag"` —
611    /// lightweight tags (where `object_type == "commit"`) have no
612    /// addressable tag object and this endpoint will 404.
613    pub fn get_annotated_tag(
614        &self,
615        owner: &str,
616        repo: &str,
617        sha: &str,
618    ) -> Result<AnnotatedTag, Box<dyn std::error::Error>> {
619        let url = format!(
620            "{}/repos/{}/{}/git/tags/{}",
621            self.base_url, owner, repo, sha
622        );
623        let resp = self.http.get(&url).send()?;
624        Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
625    }
626
627    /// Fetch the fuller pull-request object for `owner/repo#number` — in
628    /// particular its `head` and `base` refs, which the search result
629    /// omits.
630    pub fn pull_request(
631        &self,
632        owner: &str,
633        repo: &str,
634        number: u64,
635    ) -> Result<PullRequestDetail, Box<dyn std::error::Error>> {
636        let url = format!("{}/repos/{owner}/{repo}/pulls/{number}", self.base_url);
637        let resp = self.http.get(&url).send()?;
638        Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
639    }
640
641    /// Whether `owner/repo` is public now: `Some(false)` for a private
642    /// repository, `None` when it is gone or the token cannot see it.
643    pub fn repository_public(
644        &self,
645        owner: &str,
646        repo: &str,
647    ) -> Result<Option<bool>, Box<dyn std::error::Error>> {
648        #[derive(Deserialize)]
649        struct Visibility {
650            private: bool,
651        }
652        let url = format!("{}/repos/{owner}/{repo}", self.base_url);
653        let resp = self.http.get(&url).send()?;
654        if resp.status().as_u16() == 404 {
655            return Ok(None);
656        }
657        let v: Visibility = http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
658        Ok(Some(!v.private))
659    }
660
661    /// The commits a pull request carries, oldest first (one page; a
662    /// PR of more than a hundred commits is not what this is for).
663    pub fn pull_request_commits(
664        &self,
665        owner: &str,
666        repo: &str,
667        number: u64,
668    ) -> Result<Vec<RepoCommit>, Box<dyn std::error::Error>> {
669        let url = format!(
670            "{}/repos/{owner}/{repo}/pulls/{number}/commits",
671            self.base_url
672        );
673        let resp = self.http.get(&url).query(&[("per_page", "100")]).send()?;
674        Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
675    }
676
677    /// Commits on `branch` by `author` (a login or an email) since an
678    /// RFC 3339 instant, newest first; one page of up to a hundred,
679    /// which is plenty for one person's commits on one branch since a
680    /// PR was opened.
681    pub fn branch_commits_by(
682        &self,
683        owner: &str,
684        repo: &str,
685        branch: &str,
686        author: &str,
687        since: &str,
688    ) -> Result<Vec<RepoCommit>, Box<dyn std::error::Error>> {
689        let url = format!("{}/repos/{owner}/{repo}/commits", self.base_url);
690        let resp = self
691            .http
692            .get(&url)
693            .query(&[
694                ("sha", branch),
695                ("author", author),
696                ("since", since),
697                ("per_page", "100"),
698            ])
699            .send()?;
700        Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
701    }
702
703    /// Whether `sha` is already on `branch`: GitHub's compare of the
704    /// branch to the sha reports how many commits the sha is ahead by,
705    /// and zero means the branch has every one of them.
706    pub fn commit_contained(
707        &self,
708        owner: &str,
709        repo: &str,
710        branch: &str,
711        sha: &str,
712    ) -> Result<bool, Box<dyn std::error::Error>> {
713        let url = format!(
714            "{}/repos/{owner}/{repo}/compare/{branch}...{sha}",
715            self.base_url
716        );
717        let resp = self.http.get(&url).send()?;
718        let cmp: CompareResult =
719            http::blocking_json_ok(resp, &format!("GitHub compare {branch}...{sha}"))?;
720        Ok(cmp.ahead_by == 0)
721    }
722
723    /// What `login` contributed from `from` to `to` (both included):
724    /// the repositories committed to with a count each, and the pull
725    /// requests reviewed. GitHub answers for at most a year at a time,
726    /// so a longer period is asked a year at a time; reviews come 100
727    /// to a request. Private repositories are included where the token
728    /// can read them.
729    pub fn contributions(
730        &self,
731        login: &str,
732        from: chrono::NaiveDate,
733        to: chrono::NaiveDate,
734    ) -> Result<Contributions, Box<dyn std::error::Error>> {
735        let mut out = Contributions::default();
736        // Windows of a year at most, newest asked last; one that names
737        // the most repositories GitHub gives (100) is split in two, so
738        // none goes missing.
739        let mut windows = Vec::new();
740        let mut start = from;
741        while start <= to {
742            let end = (start + chrono::Duration::days(364)).min(to);
743            windows.push((start, end));
744            start = end + chrono::Duration::days(1);
745        }
746        windows.reverse();
747        'windows: while let Some((start, end)) = windows.pop() {
748            let mut after: Option<String> = None;
749            let mut first = true;
750            loop {
751                let answer: GraphqlResponse<ContributionsData> = self.graphql_answer(
752                    CONTRIBUTIONS_QUERY,
753                    &json!({
754                        "login": login,
755                        "from": format!("{start}T00:00:00Z"),
756                        "to": format!("{end}T23:59:59Z"),
757                        "after": after,
758                    }),
759                )?;
760                let data = answer
761                    .data
762                    .ok_or_else(|| graphql_failure(answer.errors.clone()))?;
763                let collection = data
764                    .user
765                    .ok_or_else(|| format!("no GitHub user {login}"))?
766                    .contributions_collection;
767                if first {
768                    let named = collection.commit_contributions_by_repository.len();
769                    if named >= MAX_REPOSITORIES {
770                        if start < end {
771                            let half = start + (end - start) / 2;
772                            windows.push((half + chrono::Duration::days(1), end));
773                            windows.push((start, half));
774                            continue 'windows;
775                        }
776                        out.capped = true;
777                    }
778                    out.restricted += collection.restricted_contributions_count;
779                    for by_repo in collection.commit_contributions_by_repository {
780                        let repo = by_repo.repository;
781                        if repo.is_private {
782                            out.private_repos.insert(repo.name_with_owner.clone());
783                        }
784                        *out.commits.entry(repo.name_with_owner).or_default() +=
785                            by_repo.contributions.total_count;
786                    }
787                    first = false;
788                }
789                let reviews = collection.pull_request_review_contributions;
790                let withheld = reviews
791                    .nodes
792                    .iter()
793                    .filter(|n| n.as_ref().and_then(|n| n.pull_request.as_ref()).is_none())
794                    .count();
795                out.unreadable.add(withheld, answer.errors);
796                for pr in reviews
797                    .nodes
798                    .into_iter()
799                    .flatten()
800                    .filter_map(|n| n.pull_request)
801                {
802                    if pr.repository.is_private {
803                        out.private_repos
804                            .insert(pr.repository.name_with_owner.clone());
805                    }
806                    if !out.reviewed.iter().any(|r| r.url == pr.url) {
807                        out.reviewed.push(pr);
808                    }
809                }
810                match reviews.page_info.next() {
811                    Some(cursor) => after = Some(cursor),
812                    None => break,
813                }
814            }
815        }
816        Ok(out)
817    }
818
819    /// `login`'s comments on issues and pull requests edited on or
820    /// after `since`, newest edit first, read 100 to a request until
821    /// they are older. A comment written in a period is at least as new,
822    /// so the caller can filter on `created_at`.
823    pub fn issue_comments(
824        &self,
825        login: &str,
826        since: chrono::NaiveDate,
827    ) -> Result<Comments, Box<dyn std::error::Error>> {
828        let since = format!("{since}T00:00:00Z");
829        let mut out = Comments::default();
830        let mut after: Option<String> = None;
831        loop {
832            let answer: GraphqlResponse<IssueCommentsData> = self.graphql_answer(
833                ISSUE_COMMENTS_QUERY,
834                &json!({"login": login, "after": after}),
835            )?;
836            let data = answer
837                .data
838                .ok_or_else(|| graphql_failure(answer.errors.clone()))?;
839            let page = data
840                .user
841                .ok_or_else(|| format!("no GitHub user {login}"))?
842                .issue_comments;
843            let mut older = false;
844            let mut withheld = 0;
845            for node in page.nodes {
846                let Some(comment) = node else {
847                    withheld += 1;
848                    continue;
849                };
850                // RFC 3339 in UTC compares as text.
851                if comment.updated_at < since {
852                    older = true;
853                    break;
854                }
855                out.comments.push(comment);
856            }
857            // Only those before the first older comment: the rest are
858            // older too, as far as anyone can tell.
859            out.unreadable.add(withheld, answer.errors);
860            match page.page_info.next() {
861                Some(cursor) if !older => after = Some(cursor),
862                _ => break,
863            }
864        }
865        Ok(out)
866    }
867
868    /// The current `owner/name` of each repository in `repos` (given
869    /// as `owner/name`), following transfers and renames as GitHub
870    /// does, or `None` for one GitHub does not find (which includes a
871    /// private one the token cannot see). Any other error, such as an
872    /// organization refusing the token, fails the whole lookup, so a
873    /// refused repository is never taken for a missing one. One GraphQL
874    /// request per hundred repositories.
875    pub fn current_repo_names(
876        &self,
877        repos: &[String],
878    ) -> Result<BTreeMap<String, Option<String>>, Box<dyn std::error::Error>> {
879        let mut out = BTreeMap::new();
880        for chunk in repos.chunks(100) {
881            let mut params = Vec::new();
882            let mut fields = Vec::new();
883            let mut variables = serde_json::Map::new();
884            let mut asked = Vec::new();
885            for (i, repo) in chunk.iter().enumerate() {
886                let Some((owner, name)) = repo.split_once('/') else {
887                    out.insert(repo.clone(), None);
888                    continue;
889                };
890                params.push(format!("$o{i}: String!, $n{i}: String!"));
891                fields.push(format!(
892                    "r{i}: repository(owner: $o{i}, name: $n{i}) {{ nameWithOwner }}"
893                ));
894                variables.insert(format!("o{i}"), json!(owner));
895                variables.insert(format!("n{i}"), json!(name));
896                asked.push((i, repo));
897            }
898            if asked.is_empty() {
899                continue;
900            }
901            let query = format!("query({}) {{ {} }}", params.join(", "), fields.join(" "));
902            // A repository that is not found is an error beside the
903            // others' data, so the answer is read even with errors.
904            let answer: GraphqlResponse<BTreeMap<String, Option<RepoName>>> =
905                self.graphql_answer(&query, &serde_json::Value::Object(variables))?;
906            let refused: Vec<GraphqlError> = answer
907                .errors
908                .clone()
909                .unwrap_or_default()
910                .into_iter()
911                .filter(|e| e.kind.as_deref() != Some("NOT_FOUND"))
912                .collect();
913            if !refused.is_empty() {
914                return Err(graphql_failure(Some(refused)));
915            }
916            let Some(data) = answer.data else {
917                return Err(graphql_failure(answer.errors));
918            };
919            for (i, repo) in asked {
920                let current = data
921                    .get(&format!("r{i}"))
922                    .cloned()
923                    .flatten()
924                    .map(|r| r.name_with_owner);
925                out.insert(repo.clone(), current);
926            }
927        }
928        Ok(out)
929    }
930
931    /// The login of the token's owner (`/user`).
932    pub fn token_login(&self) -> Result<String, Box<dyn std::error::Error>> {
933        let url = format!("{}/user", self.base_url);
934        let resp = self.http.get(&url).send()?;
935        let user: User = http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
936        Ok(user.login)
937    }
938
939    /// The private repositories the token can read (its owner's, its
940    /// collaborations and its organizations') pushed to on or after
941    /// `since`, as `owner/name`, newest push first. GitHub's
942    /// contributions count private repositories' commits only as a
943    /// number, without the repositories, so a report finds them here.
944    pub fn private_repos_pushed_since(
945        &self,
946        since: chrono::NaiveDate,
947    ) -> Result<Vec<String>, Box<dyn std::error::Error>> {
948        let since = format!("{since}T00:00:00Z");
949        let url = format!("{}/user/repos", self.base_url);
950        let mut out = Vec::new();
951        let mut page = 1u32;
952        loop {
953            let page_str = page.to_string();
954            let resp = self
955                .http
956                .get(&url)
957                .query(&[
958                    ("visibility", "private"),
959                    ("affiliation", "owner,collaborator,organization_member"),
960                    ("sort", "pushed"),
961                    ("direction", "desc"),
962                    ("per_page", "100"),
963                    ("page", &page_str),
964                ])
965                .send()?;
966            let batch: Vec<PushedRepo> =
967                http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
968            let n = batch.len();
969            let mut older = false;
970            for repo in batch {
971                // Never pushed to: nothing to count, wherever GitHub
972                // sorts it.
973                let Some(pushed) = repo.pushed_at.as_deref() else {
974                    continue;
975                };
976                // RFC 3339 in UTC compares as text.
977                if pushed < since.as_str() {
978                    older = true;
979                    break;
980                }
981                out.push(repo.full_name);
982            }
983            if older || n < 100 {
984                break;
985            }
986            page += 1;
987        }
988        Ok(out)
989    }
990
991    /// Each of `repos`' (`owner/name`) annotated tags among its 50
992    /// newest, by the date of the commit tagged, with who tagged it and
993    /// when (in UTC). Ten repositories go to a query. A repository the
994    /// token cannot read is left out, and a query that fails is
995    /// recorded in [`RecentTags::failures`] while the others count; a
996    /// tag made for an old commit can fall outside the 50.
997    pub fn recent_annotated_tags(&self, repos: &[String]) -> RecentTags {
998        let mut out = RecentTags::default();
999        for chunk in repos.chunks(10) {
1000            let mut params = Vec::new();
1001            let mut fields = Vec::new();
1002            let mut variables = serde_json::Map::new();
1003            for (i, slug) in chunk.iter().enumerate() {
1004                let Some((owner, name)) = slug.split_once('/') else {
1005                    continue;
1006                };
1007                params.push(format!("$o{i}: String!, $n{i}: String!"));
1008                fields.push(format!(
1009                    "r{i}: repository(owner: $o{i}, name: $n{i}) {{ {TAG_REFS} }}"
1010                ));
1011                variables.insert(format!("o{i}"), json!(owner));
1012                variables.insert(format!("n{i}"), json!(name));
1013            }
1014            if fields.is_empty() {
1015                continue;
1016            }
1017            let query = format!("query({}) {{ {} }}", params.join(", "), fields.join(" "));
1018            // A repository that cannot be read comes back null, with an
1019            // error beside the others' data.
1020            let data = match self
1021                .graphql_answer::<BTreeMap<String, Option<TagRepo>>>(
1022                    &query,
1023                    &serde_json::Value::Object(variables),
1024                )
1025                .and_then(|a| a.data.ok_or_else(|| graphql_failure(a.errors)))
1026            {
1027                Ok(data) => data,
1028                Err(e) => {
1029                    out.failures.push(format!("{}: {e}", chunk.join(", ")));
1030                    continue;
1031                }
1032            };
1033            for (i, slug) in chunk.iter().enumerate() {
1034                let Some(Some(repo)) = data.get(&format!("r{i}")) else {
1035                    continue;
1036                };
1037                let tags: Vec<AnnotatedTag> = repo
1038                    .refs
1039                    .nodes
1040                    .iter()
1041                    .filter_map(|r| {
1042                        let actor = r.target.as_ref()?.tagger.as_ref()?;
1043                        Some(AnnotatedTag {
1044                            tag: r.name.clone(),
1045                            tagger: actor.tagger()?,
1046                        })
1047                    })
1048                    .collect();
1049                out.tags.insert(slug.clone(), tags);
1050            }
1051        }
1052        out
1053    }
1054
1055    /// The commits `login` authored from `since` to `until` (both
1056    /// included) on each of `repos`' (`owner/name`) default branch, as
1057    /// GitHub links commits to the account: 25 repositories to a query,
1058    /// after one asking for the account's id. Repositories without any
1059    /// are left out; one the token cannot read too. A query that fails
1060    /// is recorded in [`CommitCounts::failures`] while the others count.
1061    pub fn commit_counts(
1062        &self,
1063        login: &str,
1064        repos: &[String],
1065        since: chrono::NaiveDate,
1066        until: chrono::NaiveDate,
1067    ) -> Result<CommitCounts, Box<dyn std::error::Error>> {
1068        let mut out = CommitCounts::default();
1069        if repos.is_empty() {
1070            return Ok(out);
1071        }
1072        let answer: GraphqlResponse<UserIdData> =
1073            self.graphql_answer(USER_ID_QUERY, &json!({"login": login}))?;
1074        let id = answer
1075            .data
1076            .ok_or_else(|| graphql_failure(answer.errors))?
1077            .user
1078            .ok_or_else(|| format!("no GitHub user {login}"))?
1079            .id;
1080        for chunk in repos.chunks(25) {
1081            let mut params =
1082                vec!["$id: ID!, $since: GitTimestamp!, $until: GitTimestamp!".to_string()];
1083            let mut fields = Vec::new();
1084            let mut variables = serde_json::Map::new();
1085            variables.insert("id".into(), json!(id));
1086            variables.insert("since".into(), json!(format!("{since}T00:00:00Z")));
1087            variables.insert("until".into(), json!(format!("{until}T23:59:59Z")));
1088            for (i, slug) in chunk.iter().enumerate() {
1089                let Some((owner, name)) = slug.split_once('/') else {
1090                    continue;
1091                };
1092                params.push(format!("$o{i}: String!, $n{i}: String!"));
1093                fields.push(format!(
1094                    "r{i}: repository(owner: $o{i}, name: $n{i}) {{ {HISTORY} }}"
1095                ));
1096                variables.insert(format!("o{i}"), json!(owner));
1097                variables.insert(format!("n{i}"), json!(name));
1098            }
1099            if fields.is_empty() {
1100                continue;
1101            }
1102            let query = format!("query({}) {{ {} }}", params.join(", "), fields.join(" "));
1103            let data = match self
1104                .graphql_answer::<BTreeMap<String, Option<HistoryRepo>>>(
1105                    &query,
1106                    &serde_json::Value::Object(variables),
1107                )
1108                .and_then(|a| a.data.ok_or_else(|| graphql_failure(a.errors)))
1109            {
1110                Ok(data) => data,
1111                Err(e) => {
1112                    out.failures.push(format!("{}: {e}", chunk.join(", ")));
1113                    continue;
1114                }
1115            };
1116            for (i, slug) in chunk.iter().enumerate() {
1117                let count = data
1118                    .get(&format!("r{i}"))
1119                    .and_then(Option::as_ref)
1120                    .and_then(|r| r.default_branch_ref.as_ref())
1121                    .and_then(|b| b.target.as_ref())
1122                    .and_then(|t| t.history.as_ref())
1123                    .map_or(0, |h| h.total_count);
1124                if count > 0 {
1125                    out.counts.insert(slug.clone(), count);
1126                }
1127            }
1128        }
1129        Ok(out)
1130    }
1131
1132    /// The whole answer to a GraphQL query, errors included, for a
1133    /// caller that can use partial data.
1134    fn graphql_answer<T: serde::de::DeserializeOwned>(
1135        &self,
1136        query: &str,
1137        variables: &serde_json::Value,
1138    ) -> Result<GraphqlResponse<T>, Box<dyn std::error::Error>> {
1139        let url = graphql_url(&self.base_url);
1140        let resp = self
1141            .http
1142            .post(&url)
1143            .json(&json!({"query": query, "variables": variables}))
1144            .send()?;
1145        let what = format!("GitHub GraphQL {url}");
1146        let text = http::blocking_ok(resp, &what)?.text()?;
1147        // Decoded here rather than by reqwest, whose error does not say
1148        // which field did not fit.
1149        serde_json::from_str(&text)
1150            .map_err(|e| format!("{what}: cannot read the answer: {e}").into())
1151    }
1152}
1153
1154/// Check whether `token` works against `base_url` by hitting
1155/// `/user`. Returns `Ok(true)` for valid tokens, `Ok(false)`
1156/// for 401s, and `Err` for other transport / server errors so
1157/// callers can distinguish "tried and was rejected" from
1158/// "couldn't reach the server".
1159pub fn validate_token(base_url: &str, token: &str) -> Result<bool, Box<dyn std::error::Error>> {
1160    sandogasa_cli::ensure_secure_url(base_url)?;
1161    let http = build_http_client(token)?;
1162    let url = format!("{}/user", base_url.trim_end_matches('/'));
1163    let resp = http.get(&url).send()?;
1164    let status = resp.status();
1165    if status.is_success() {
1166        return Ok(true);
1167    }
1168    if status.as_u16() == 401 {
1169        return Ok(false);
1170    }
1171    let text = resp.text().unwrap_or_default();
1172    Err(format!("GitHub /user check failed: {status}: {text}").into())
1173}
1174
1175/// An error for a GraphQL answer without data: GitHub's messages, if
1176/// any.
1177fn graphql_failure(errors: Option<Vec<GraphqlError>>) -> Box<dyn std::error::Error> {
1178    let messages: Vec<String> = errors
1179        .unwrap_or_default()
1180        .into_iter()
1181        .map(|e| e.message)
1182        .collect();
1183    if messages.is_empty() {
1184        "GitHub GraphQL: no data in the answer".into()
1185    } else {
1186        format!("GitHub GraphQL: {}", messages.join("; ")).into()
1187    }
1188}
1189
1190/// The GraphQL endpoint for a REST base: `https://api.github.com/graphql`,
1191/// or a GHES instance's `/api/graphql` for its `/api/v3`.
1192fn graphql_url(base: &str) -> String {
1193    match base.strip_suffix("/api/v3") {
1194        Some(host) => format!("{host}/api/graphql"),
1195        None => format!("{base}/graphql"),
1196    }
1197}
1198
1199/// The most repositories `commitContributionsByRepository` names.
1200const MAX_REPOSITORIES: usize = 100;
1201
1202const CONTRIBUTIONS_QUERY: &str = "\
1203query($login: String!, $from: DateTime!, $to: DateTime!, $after: String) {
1204  user(login: $login) {
1205    contributionsCollection(from: $from, to: $to) {
1206      restrictedContributionsCount
1207      commitContributionsByRepository(maxRepositories: 100) {
1208        repository { nameWithOwner isPrivate }
1209        contributions { totalCount }
1210      }
1211      pullRequestReviewContributions(first: 100, after: $after) {
1212        pageInfo { hasNextPage endCursor }
1213        nodes {
1214          pullRequest { number title url state repository { nameWithOwner isPrivate } }
1215        }
1216      }
1217    }
1218  }
1219}";
1220
1221/// A repository's 50 newest tags and, for an annotated one, its tagger.
1222const TAG_REFS: &str = "refs(refPrefix: \"refs/tags/\", first: 50, \
1223    orderBy: {field: TAG_COMMIT_DATE, direction: DESC}) { \
1224    nodes { name target { ... on Tag { tagger { name email date } } } } }";
1225
1226const USER_ID_QUERY: &str = "query($login: String!) { user(login: $login) { id } }";
1227
1228/// The commits by `$id` from `$since` to `$until` on a repository's
1229/// default branch.
1230const HISTORY: &str = "defaultBranchRef { target { ... on Commit { \
1231    history(author: {id: $id}, since: $since, until: $until) { totalCount } } } }";
1232
1233const ISSUE_COMMENTS_QUERY: &str = "\
1234query($login: String!, $after: String) {
1235  user(login: $login) {
1236    issueComments(first: 100, after: $after, orderBy: {field: UPDATED_AT, direction: DESC}) {
1237      pageInfo { hasNextPage endCursor }
1238      nodes {
1239        createdAt updatedAt url
1240        issue { number title url state repository { nameWithOwner isPrivate } }
1241        pullRequest { number title url state repository { nameWithOwner isPrivate } }
1242      }
1243    }
1244  }
1245}";
1246
1247#[derive(Deserialize)]
1248struct TagRepo {
1249    refs: TagRefs,
1250}
1251
1252#[derive(Deserialize)]
1253struct TagRefs {
1254    nodes: Vec<TagRefNode>,
1255}
1256
1257#[derive(Deserialize)]
1258struct TagRefNode {
1259    name: String,
1260    /// `{}` for a lightweight tag's commit, which has no tagger.
1261    target: Option<TagTarget>,
1262}
1263
1264#[derive(Deserialize)]
1265struct TagTarget {
1266    tagger: Option<GitActor>,
1267}
1268
1269/// A tagger as GraphQL gives it: any field may be null, and the date
1270/// is in the tagger's own time zone.
1271#[derive(Deserialize)]
1272struct GitActor {
1273    name: Option<String>,
1274    email: Option<String>,
1275    date: Option<String>,
1276}
1277
1278impl GitActor {
1279    /// The tagger, its date in UTC as REST gives it; none without a
1280    /// readable date.
1281    fn tagger(&self) -> Option<Tagger> {
1282        let date = chrono::DateTime::parse_from_rfc3339(self.date.as_deref()?).ok()?;
1283        Some(Tagger {
1284            name: self.name.clone().unwrap_or_default(),
1285            email: self.email.clone().unwrap_or_default(),
1286            date: date.to_utc().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
1287        })
1288    }
1289}
1290
1291#[derive(Deserialize)]
1292struct UserIdData {
1293    user: Option<UserId>,
1294}
1295
1296#[derive(Deserialize)]
1297struct UserId {
1298    id: String,
1299}
1300
1301#[derive(Deserialize)]
1302struct HistoryRepo {
1303    #[serde(rename = "defaultBranchRef")]
1304    default_branch_ref: Option<HistoryBranch>,
1305}
1306
1307#[derive(Deserialize)]
1308struct HistoryBranch {
1309    target: Option<HistoryTarget>,
1310}
1311
1312#[derive(Deserialize)]
1313struct HistoryTarget {
1314    history: Option<Count>,
1315}
1316
1317#[derive(Deserialize)]
1318struct PushedRepo {
1319    full_name: String,
1320    pushed_at: Option<String>,
1321}
1322
1323#[derive(Deserialize)]
1324struct GraphqlResponse<T> {
1325    data: Option<T>,
1326    errors: Option<Vec<GraphqlError>>,
1327}
1328
1329/// A repository's current name, as GraphQL answers it.
1330#[derive(Debug, Clone, Deserialize)]
1331#[serde(rename_all = "camelCase")]
1332struct RepoName {
1333    name_with_owner: String,
1334}
1335
1336#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
1337struct GraphqlError {
1338    message: String,
1339    /// GitHub's kind of error, such as `NOT_FOUND` or `FORBIDDEN`.
1340    #[serde(rename = "type", default)]
1341    kind: Option<String>,
1342}
1343
1344#[derive(Deserialize)]
1345struct PageInfo {
1346    #[serde(rename = "hasNextPage")]
1347    has_next_page: bool,
1348    #[serde(rename = "endCursor")]
1349    end_cursor: Option<String>,
1350}
1351
1352impl PageInfo {
1353    /// The cursor of the next page, if there is one.
1354    fn next(self) -> Option<String> {
1355        self.end_cursor.filter(|_| self.has_next_page)
1356    }
1357}
1358
1359#[derive(Deserialize)]
1360struct ContributionsData {
1361    user: Option<ContributionsUser>,
1362}
1363
1364#[derive(Deserialize)]
1365struct ContributionsUser {
1366    #[serde(rename = "contributionsCollection")]
1367    contributions_collection: Collection,
1368}
1369
1370#[derive(Deserialize)]
1371struct Collection {
1372    #[serde(rename = "restrictedContributionsCount", default)]
1373    restricted_contributions_count: u64,
1374    #[serde(rename = "commitContributionsByRepository")]
1375    commit_contributions_by_repository: Vec<CommitsByRepo>,
1376    #[serde(rename = "pullRequestReviewContributions")]
1377    pull_request_review_contributions: ReviewPage,
1378}
1379
1380#[derive(Deserialize)]
1381struct CommitsByRepo {
1382    repository: RepoNode,
1383    contributions: Count,
1384}
1385
1386#[derive(Deserialize)]
1387struct Count {
1388    #[serde(rename = "totalCount")]
1389    total_count: u64,
1390}
1391
1392#[derive(Deserialize)]
1393struct ReviewPage {
1394    #[serde(rename = "pageInfo")]
1395    page_info: PageInfo,
1396    /// `null` where the token cannot read the review.
1397    nodes: Vec<Option<ReviewNode>>,
1398}
1399
1400#[derive(Deserialize)]
1401struct ReviewNode {
1402    #[serde(rename = "pullRequest")]
1403    pull_request: Option<ItemNode>,
1404}
1405
1406#[derive(Deserialize)]
1407struct IssueCommentsData {
1408    user: Option<IssueCommentsUser>,
1409}
1410
1411#[derive(Deserialize)]
1412struct IssueCommentsUser {
1413    #[serde(rename = "issueComments")]
1414    issue_comments: CommentPage,
1415}
1416
1417#[derive(Deserialize)]
1418struct CommentPage {
1419    #[serde(rename = "pageInfo")]
1420    page_info: PageInfo,
1421    /// `null` where the token cannot read the comment.
1422    nodes: Vec<Option<IssueComment>>,
1423}
1424
1425/// Build a reqwest client preconfigured for the GitHub API: the
1426/// Bearer token, the recommended JSON Accept header, a User-Agent
1427/// (GitHub requires one), and our standard request timeout.
1428fn build_http_client(token: &str) -> Result<reqwest::blocking::Client, Box<dyn std::error::Error>> {
1429    let mut headers = HeaderMap::new();
1430    headers.insert(
1431        AUTHORIZATION,
1432        HeaderValue::from_str(&format!("Bearer {token}"))?,
1433    );
1434    headers.insert(
1435        ACCEPT,
1436        HeaderValue::from_static("application/vnd.github+json"),
1437    );
1438    headers.insert(
1439        HeaderName::from_static("x-github-api-version"),
1440        HeaderValue::from_static("2022-11-28"),
1441    );
1442    Ok(http::blocking_builder(concat!(
1443        env!("CARGO_PKG_NAME"),
1444        "/",
1445        env!("CARGO_PKG_VERSION")
1446    ))
1447    .default_headers(headers)
1448    .build()?)
1449}
1450
1451#[cfg(test)]
1452mod tests {
1453    use super::*;
1454
1455    fn day(s: &str) -> chrono::NaiveDate {
1456        chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
1457    }
1458
1459    fn graphql_body(data: serde_json::Value, errors: serde_json::Value) -> String {
1460        json!({"data": data, "errors": errors}).to_string()
1461    }
1462
1463    fn pr(repo: &str, n: u64, private: bool) -> serde_json::Value {
1464        json!({"number": n, "title": "t", "state": "OPEN",
1465               "url": format!("https://github.com/{repo}/pull/{n}"),
1466               "repository": {"nameWithOwner": repo, "isPrivate": private}})
1467    }
1468
1469    #[test]
1470    fn graphql_lives_beside_the_rest_api() {
1471        assert_eq!(
1472            graphql_url("https://api.github.com"),
1473            "https://api.github.com/graphql"
1474        );
1475        assert_eq!(
1476            graphql_url("https://ghe.example.com/api/v3"),
1477            "https://ghe.example.com/api/graphql"
1478        );
1479    }
1480
1481    #[test]
1482    fn contributions_are_read_a_year_and_a_page_at_a_time() {
1483        let mut server = mockito::Server::new();
1484        let collection = |commits: serde_json::Value, reviews: serde_json::Value, next: bool| {
1485            json!({"user": {"contributionsCollection": {
1486                "restrictedContributionsCount": 2,
1487                "commitContributionsByRepository": commits,
1488                "pullRequestReviewContributions": {
1489                    "pageInfo": {"hasNextPage": next, "endCursor": if next { "c1" } else { "" }},
1490                    "nodes": reviews
1491                }
1492            }}})
1493        };
1494        let commits = json!([
1495            {"repository": {"nameWithOwner": "o/pub", "isPrivate": false},
1496             "contributions": {"totalCount": 3}},
1497            {"repository": {"nameWithOwner": "o/priv", "isPrivate": true},
1498             "contributions": {"totalCount": 1}}
1499        ]);
1500        // First year, first page of reviews: one withheld.
1501        let first = server
1502            .mock("POST", "/graphql")
1503            .match_body(mockito::Matcher::AllOf(vec![
1504                mockito::Matcher::Regex("2025-01-01T00:00:00Z".into()),
1505                mockito::Matcher::Regex(r#""after":null"#.into()),
1506            ]))
1507            .with_body(graphql_body(
1508                collection(
1509                    commits.clone(),
1510                    json!([{"pullRequest": pr("o/pub", 1, false)}, null]),
1511                    true,
1512                ),
1513                json!([{"message": "`x` forbids access"}]),
1514            ))
1515            .create();
1516        // Its second page: the commits are not counted again.
1517        let second = server
1518            .mock("POST", "/graphql")
1519            .match_body(mockito::Matcher::Regex(r#""after":"c1""#.into()))
1520            .with_body(graphql_body(
1521                collection(
1522                    commits,
1523                    json!([{"pullRequest": pr("o/pub", 1, false)}, {"pullRequest": pr("o/priv", 2, true)}]),
1524                    false,
1525                ),
1526                json!(null),
1527            ))
1528            .create();
1529        // The second year starts the day after the first ends.
1530        let year2 = server
1531            .mock("POST", "/graphql")
1532            .match_body(mockito::Matcher::Regex("2026-01-01T00:00:00Z".into()))
1533            .with_body(graphql_body(
1534                collection(
1535                    json!([{"repository": {"nameWithOwner": "o/pub", "isPrivate": false},
1536                            "contributions": {"totalCount": 4}}]),
1537                    json!([]),
1538                    false,
1539                ),
1540                json!(null),
1541            ))
1542            .create();
1543        let client = Client::new(&server.url(), "tok").unwrap();
1544        let c = client
1545            .contributions("me", day("2025-01-01"), day("2026-02-01"))
1546            .unwrap();
1547        first.assert();
1548        second.assert();
1549        year2.assert();
1550        assert_eq!(
1551            c.commits,
1552            BTreeMap::from([("o/priv".to_string(), 1), ("o/pub".to_string(), 7)])
1553        );
1554        assert_eq!(c.private_repos, BTreeSet::from(["o/priv".to_string()]));
1555        let reviewed: Vec<u64> = c.reviewed.iter().map(|p| p.number).collect();
1556        assert_eq!(reviewed, [1, 2]);
1557        assert_eq!(c.unreadable.count, 1);
1558        assert_eq!(
1559            c.unreadable.reasons,
1560            BTreeSet::from(["`x` forbids access".to_string()])
1561        );
1562        assert_eq!(c.restricted, 4);
1563    }
1564
1565    #[test]
1566    fn a_window_naming_100_repositories_is_split() {
1567        let mut server = mockito::Server::new();
1568        let repos = |prefix: &str, n: usize| -> serde_json::Value {
1569            (0..n)
1570                .map(|i| {
1571                    json!({"repository": {"nameWithOwner": format!("{prefix}/{i}"), "isPrivate": false},
1572                           "contributions": {"totalCount": 1}})
1573                })
1574                .collect()
1575        };
1576        let answer = |commits: serde_json::Value| {
1577            graphql_body(
1578                json!({"user": {"contributionsCollection": {
1579                    "commitContributionsByRepository": commits,
1580                    "pullRequestReviewContributions": {
1581                        "pageInfo": {"hasNextPage": false, "endCursor": null}, "nodes": []}
1582                }}}),
1583                json!(null),
1584            )
1585        };
1586        let window = |from: &str, to: &str| {
1587            mockito::Matcher::AllOf(vec![
1588                mockito::Matcher::Regex(format!(r#""from":"{from}T00:00:00Z""#)),
1589                mockito::Matcher::Regex(format!(r#""to":"{to}T23:59:59Z""#)),
1590            ])
1591        };
1592        let both = server
1593            .mock("POST", "/graphql")
1594            .match_body(window("2026-01-01", "2026-01-02"))
1595            .with_body(answer(repos("both", 100)))
1596            .create();
1597        let first = server
1598            .mock("POST", "/graphql")
1599            .match_body(window("2026-01-01", "2026-01-01"))
1600            .with_body(answer(repos("a", 2)))
1601            .create();
1602        // A single day at the limit cannot be split: counted, and capped.
1603        let second = server
1604            .mock("POST", "/graphql")
1605            .match_body(window("2026-01-02", "2026-01-02"))
1606            .with_body(answer(repos("b", 100)))
1607            .create();
1608        let client = Client::new(&server.url(), "tok").unwrap();
1609        let c = client
1610            .contributions("me", day("2026-01-01"), day("2026-01-02"))
1611            .unwrap();
1612        both.assert();
1613        first.assert();
1614        second.assert();
1615        assert_eq!(c.commits.len(), 102);
1616        assert!(!c.commits.contains_key("both/0"));
1617        assert!(c.capped);
1618    }
1619
1620    #[test]
1621    fn comments_are_read_back_to_the_day_asked() {
1622        let mut server = mockito::Server::new();
1623        let comment = |at: &str| {
1624            json!({"createdAt": at, "updatedAt": at, "url": "u",
1625                   "issue": pr("o/r", 1, false), "pullRequest": null})
1626        };
1627        let mock = server
1628            .mock("POST", "/graphql")
1629            .with_body(graphql_body(
1630                json!({"user": {"issueComments": {
1631                    "pageInfo": {"hasNextPage": true, "endCursor": "next"},
1632                    "nodes": [comment("2026-02-02T00:00:00Z"), null, comment("2026-01-02T00:00:00Z"), null]
1633                }}}),
1634                json!([{"message": "withheld"}]),
1635            ))
1636            .expect(1)
1637            .create();
1638        let client = Client::new(&server.url(), "tok").unwrap();
1639        let c = client.issue_comments("me", day("2026-02-01")).unwrap();
1640        mock.assert();
1641        assert_eq!(c.comments.len(), 1);
1642        assert_eq!(c.comments[0].issue.as_ref().unwrap().number, 1);
1643        assert_eq!(c.unreadable.count, 1);
1644        // A user GitHub does not know is an error.
1645        let mut server = mockito::Server::new();
1646        server
1647            .mock("POST", "/graphql")
1648            .with_body(graphql_body(json!({"user": null}), json!(null)))
1649            .create();
1650        let client = Client::new(&server.url(), "tok").unwrap();
1651        assert!(client.issue_comments("ghost", day("2026-02-01")).is_err());
1652        // No data at all: GitHub's message.
1653        let mut server = mockito::Server::new();
1654        server
1655            .mock("POST", "/graphql")
1656            .with_body(graphql_body(json!(null), json!([{"message": "bad query"}])))
1657            .create();
1658        let client = Client::new(&server.url(), "tok").unwrap();
1659        let err = client
1660            .contributions("me", day("2026-01-01"), day("2026-01-02"))
1661            .unwrap_err();
1662        assert_eq!(err.to_string(), "GitHub GraphQL: bad query");
1663        assert_eq!(
1664            graphql_failure(None).to_string(),
1665            "GitHub GraphQL: no data in the answer"
1666        );
1667    }
1668
1669    #[test]
1670    fn private_repos_are_read_until_an_older_push() {
1671        let mut server = mockito::Server::new();
1672        let mock = server
1673            .mock("GET", "/user/repos")
1674            .match_query(mockito::Matcher::AllOf(vec![
1675                mockito::Matcher::UrlEncoded("visibility".into(), "private".into()),
1676                mockito::Matcher::UrlEncoded("sort".into(), "pushed".into()),
1677                mockito::Matcher::UrlEncoded("page".into(), "1".into()),
1678            ]))
1679            .with_body(
1680                json!([
1681                    {"full_name": "o/new", "pushed_at": "2026-02-20T00:00:00Z"},
1682                    {"full_name": "o/empty", "pushed_at": null},
1683                    {"full_name": "o/newer", "pushed_at": "2026-02-10T00:00:00Z"},
1684                    {"full_name": "o/old", "pushed_at": "2025-01-01T00:00:00Z"}
1685                ])
1686                .to_string(),
1687            )
1688            .create();
1689        let client = Client::new(&server.url(), "tok").unwrap();
1690        assert_eq!(
1691            client
1692                .private_repos_pushed_since(day("2026-02-01"))
1693                .unwrap(),
1694            ["o/new", "o/newer"]
1695        );
1696        mock.assert();
1697    }
1698
1699    #[test]
1700    fn annotated_tags_are_read_ten_repos_to_a_query() {
1701        let mut server = mockito::Server::new();
1702        // In the tagger's time zone: 2026-02-10T23:30-05:00 is the 11th
1703        // in UTC.
1704        let tagger = json!({"name": "Me", "email": null, "date": "2026-02-10T23:30:00-05:00"});
1705        let mock = server
1706            .mock("POST", "/graphql")
1707            .match_body(mockito::Matcher::AllOf(vec![
1708                mockito::Matcher::Regex(r#""o0":"o""#.into()),
1709                mockito::Matcher::Regex(r#""n0":"a""#.into()),
1710                mockito::Matcher::Regex(r#""n1":"gone""#.into()),
1711            ]))
1712            .with_body(graphql_body(
1713                json!({
1714                    "r0": {"refs": {"nodes": [
1715                        {"name": "v1", "target": {"tagger": tagger}},
1716                        {"name": "undated", "target": {"tagger": {"name": "Me", "email": "e", "date": null}}},
1717                        {"name": "light", "target": {}}
1718                    ]}},
1719                    "r1": null
1720                }),
1721                json!([{"message": "Could not resolve to a Repository"}]),
1722            ))
1723            .create();
1724        let client = Client::new(&server.url(), "tok").unwrap();
1725        let recent = client.recent_annotated_tags(&[
1726            "o/a".to_string(),
1727            "o/gone".to_string(),
1728            "bad".to_string(),
1729        ]);
1730        mock.assert();
1731        assert!(recent.failures.is_empty());
1732        assert_eq!(recent.tags.len(), 1);
1733        let tags = &recent.tags["o/a"];
1734        assert_eq!(tags.len(), 1);
1735        assert_eq!(tags[0].tag, "v1");
1736        assert_eq!(tags[0].tagger.email, "");
1737        assert_eq!(tags[0].tagger.date, "2026-02-11T04:30:00Z");
1738        // Nothing to ask about: no request.
1739        assert!(
1740            client
1741                .recent_annotated_tags(&["bad".to_string()])
1742                .tags
1743                .is_empty()
1744        );
1745        // A failed query is recorded; the others still count.
1746        let mut down = mockito::Server::new();
1747        down.mock("POST", "/graphql").with_status(502).create();
1748        let client = Client::new(&down.url(), "tok").unwrap();
1749        let recent = client.recent_annotated_tags(&["o/a".to_string()]);
1750        assert!(recent.tags.is_empty());
1751        assert_eq!(recent.failures.len(), 1);
1752        assert!(
1753            recent.failures[0].starts_with("o/a: "),
1754            "{:?}",
1755            recent.failures
1756        );
1757    }
1758
1759    #[test]
1760    fn commits_are_counted_twenty_five_repos_to_a_query() {
1761        let mut server = mockito::Server::new();
1762        let id = server
1763            .mock("POST", "/graphql")
1764            .match_body(mockito::Matcher::Regex(
1765                "user\\(login: \\$login\\) \\{ id \\}".into(),
1766            ))
1767            .with_body(graphql_body(json!({"user": {"id": "U_1"}}), json!(null)))
1768            .create();
1769        let history =
1770            |n: u64| json!({"defaultBranchRef": {"target": {"history": {"totalCount": n}}}});
1771        let counts = server
1772            .mock("POST", "/graphql")
1773            .match_body(mockito::Matcher::AllOf(vec![
1774                mockito::Matcher::Regex("history\\(author".into()),
1775                mockito::Matcher::Regex(r#""id":"U_1""#.into()),
1776                mockito::Matcher::Regex(r#""since":"2026-02-01T00:00:00Z""#.into()),
1777            ]))
1778            .with_body(graphql_body(
1779                json!({"r0": history(3), "r1": history(0), "r2": null, "r3": {"defaultBranchRef": null}}),
1780                json!([{"message": "Could not resolve"}]),
1781            ))
1782            .create();
1783        let client = Client::new(&server.url(), "tok").unwrap();
1784        let repos: Vec<String> = ["o/a", "o/none", "o/gone", "o/empty"]
1785            .map(String::from)
1786            .into();
1787        let c = client
1788            .commit_counts("me", &repos, day("2026-02-01"), day("2026-02-28"))
1789            .unwrap();
1790        id.assert();
1791        counts.assert();
1792        assert_eq!(c.counts, BTreeMap::from([("o/a".to_string(), 3)]));
1793        assert!(c.failures.is_empty());
1794        // No repositories: no request at all.
1795        assert!(
1796            client
1797                .commit_counts("me", &[], day("2026-02-01"), day("2026-02-28"))
1798                .unwrap()
1799                .counts
1800                .is_empty()
1801        );
1802    }
1803
1804    #[test]
1805    fn the_token_names_its_owner() {
1806        let mut server = mockito::Server::new();
1807        server
1808            .mock("GET", "/user")
1809            .with_body(r#"{"id": 1, "login": "me"}"#)
1810            .create();
1811        let client = Client::new(&server.url(), "tok").unwrap();
1812        assert_eq!(client.token_login().unwrap(), "me");
1813    }
1814
1815    #[test]
1816    fn pull_request_reads_head_and_base() {
1817        let mut server = mockito::Server::new();
1818        let mock = server
1819            .mock("GET", "/repos/o/r/pulls/92")
1820            .with_status(200)
1821            .with_body(
1822                r#"{"number": 92, "state": "closed", "merged": false,
1823                    "head": {"ref": "fix", "sha": "8b8aa8b"},
1824                    "base": {"ref": "main", "sha": "0000000"}}"#,
1825            )
1826            .create();
1827        let client = Client::new(&server.url(), "tok").unwrap();
1828        let pr = client.pull_request("o", "r", 92).unwrap();
1829        mock.assert();
1830        assert_eq!(pr.head.sha, "8b8aa8b");
1831        assert_eq!(pr.base.ref_name, "main");
1832        assert!(!pr.merged);
1833    }
1834
1835    #[test]
1836    fn branch_commits_by_filters_by_author_and_since() {
1837        let mut server = mockito::Server::new();
1838        let mock = server
1839            .mock("GET", "/repos/o/r/commits")
1840            .match_query(mockito::Matcher::AllOf(vec![
1841                mockito::Matcher::UrlEncoded("sha".into(), "main".into()),
1842                mockito::Matcher::UrlEncoded("author".into(), "michel-slm".into()),
1843                mockito::Matcher::UrlEncoded("since".into(), "2026-03-04T00:00:00Z".into()),
1844            ]))
1845            .with_status(200)
1846            .with_body(
1847                r#"[{"sha": "abc", "commit": {"message": "Ignore it\n\nbody",
1848                     "author": {"name": "Michel Lind", "email": "m@example.org"}}}]"#,
1849            )
1850            .create();
1851        let client = Client::new(&server.url(), "tok").unwrap();
1852        let commits = client
1853            .branch_commits_by("o", "r", "main", "michel-slm", "2026-03-04T00:00:00Z")
1854            .unwrap();
1855        mock.assert();
1856        assert_eq!(commits[0].title(), "Ignore it");
1857        assert_eq!(
1858            commits[0].commit.author.as_ref().unwrap().name,
1859            "Michel Lind"
1860        );
1861    }
1862
1863    #[test]
1864    fn commit_contained_reads_ahead_by() {
1865        // ahead_by == 0 (status "identical" or "behind") → the sha is on
1866        // the branch already.
1867        let mut server = mockito::Server::new();
1868        let mock = server
1869            .mock("GET", "/repos/o/r/compare/main...8b8aa8b")
1870            .with_status(200)
1871            .with_body(r#"{"status": "behind", "ahead_by": 0, "behind_by": 4}"#)
1872            .create();
1873        let client = Client::new(&server.url(), "tok").unwrap();
1874        assert!(
1875            client
1876                .commit_contained("o", "r", "main", "8b8aa8b")
1877                .unwrap()
1878        );
1879        mock.assert();
1880
1881        let mut server = mockito::Server::new();
1882        server
1883            .mock("GET", "/repos/o/r/compare/main...other")
1884            .with_status(200)
1885            .with_body(r#"{"status": "diverged", "ahead_by": 2, "behind_by": 4}"#)
1886            .create();
1887        let client = Client::new(&server.url(), "tok").unwrap();
1888        assert!(!client.commit_contained("o", "r", "main", "other").unwrap());
1889    }
1890
1891    #[test]
1892    fn new_rejects_plaintext_remote() {
1893        // A token must not be sent to a plaintext http non-loopback URL.
1894        assert!(Client::new("http://api.example.com", "tok").is_err());
1895    }
1896
1897    #[test]
1898    fn user_by_username_returns_user() {
1899        let mut server = mockito::Server::new();
1900        let mock = server
1901            .mock("GET", "/users/octocat")
1902            .match_header("authorization", "Bearer tok")
1903            .with_status(200)
1904            .with_body(r#"{"id": 1, "login": "octocat"}"#)
1905            .create();
1906        let client = Client::new(&server.url(), "tok").unwrap();
1907        let user = client.user_by_username("octocat").unwrap().unwrap();
1908        assert_eq!(user.id, 1);
1909        assert_eq!(user.login, "octocat");
1910        mock.assert();
1911    }
1912
1913    #[test]
1914    fn repository_public_reads_the_private_flag() {
1915        let mut server = mockito::Server::new();
1916        let public = server
1917            .mock("GET", "/repos/o/pub")
1918            .with_body(r#"{"id": 1, "private": false}"#)
1919            .create();
1920        let private = server
1921            .mock("GET", "/repos/o/priv")
1922            .with_body(r#"{"id": 2, "private": true}"#)
1923            .create();
1924        let gone = server
1925            .mock("GET", "/repos/o/gone")
1926            .with_status(404)
1927            .create();
1928        let broken = server.mock("GET", "/repos/o/err").with_status(500).create();
1929        let client = Client::new(&server.url(), "tok").unwrap();
1930        assert_eq!(client.repository_public("o", "pub").unwrap(), Some(true));
1931        assert_eq!(client.repository_public("o", "priv").unwrap(), Some(false));
1932        assert_eq!(client.repository_public("o", "gone").unwrap(), None);
1933        assert!(client.repository_public("o", "err").is_err());
1934        for m in [public, private, gone, broken] {
1935            m.assert();
1936        }
1937    }
1938
1939    #[test]
1940    fn user_by_username_404_is_none() {
1941        let mut server = mockito::Server::new();
1942        let mock = server
1943            .mock("GET", "/users/ghost")
1944            .with_status(404)
1945            .with_body(r#"{"message": "Not Found"}"#)
1946            .create();
1947        let client = Client::new(&server.url(), "tok").unwrap();
1948        assert!(client.user_by_username("ghost").unwrap().is_none());
1949        mock.assert();
1950    }
1951
1952    #[test]
1953    fn search_pull_requests_paginates() {
1954        let mut server = mockito::Server::new();
1955        // First page: full 100 items, total_count says 105.
1956        let items_page1 = (1..=100)
1957            .map(|i| {
1958                format!(
1959                    r#"{{"number":{i},"title":"PR {i}","state":"closed","html_url":"https://github.com/o/r/pull/{i}","pull_request":{{"merged_at":"2026-02-01T10:00:00Z"}}}}"#
1960                )
1961            })
1962            .collect::<Vec<_>>()
1963            .join(",");
1964        let mock_p1 = server
1965            .mock("GET", "/search/issues")
1966            .match_query(mockito::Matcher::AllOf(vec![
1967                mockito::Matcher::UrlEncoded("page".into(), "1".into()),
1968                mockito::Matcher::UrlEncoded("per_page".into(), "100".into()),
1969            ]))
1970            .with_status(200)
1971            .with_body(format!(
1972                r#"{{"total_count":105,"incomplete_results":false,"items":[{items_page1}]}}"#
1973            ))
1974            .create();
1975        let mock_p2 = server
1976            .mock("GET", "/search/issues")
1977            .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
1978            .with_status(200)
1979            .with_body(
1980                r#"{"total_count":105,"incomplete_results":false,"items":[
1981                    {"number":101,"title":"x","state":"open","html_url":"https://github.com/o/r/pull/101"},
1982                    {"number":102,"title":"y","state":"open","html_url":"https://github.com/o/r/pull/102"},
1983                    {"number":103,"title":"z","state":"open","html_url":"https://github.com/o/r/pull/103"},
1984                    {"number":104,"title":"w","state":"open","html_url":"https://github.com/o/r/pull/104"},
1985                    {"number":105,"title":"v","state":"open","html_url":"https://github.com/o/r/pull/105"}
1986                ]}"#,
1987            )
1988            .create();
1989        let client = Client::new(&server.url(), "tok").unwrap();
1990        let prs = client
1991            .search_pull_requests("type:pr author:octocat")
1992            .unwrap();
1993        assert_eq!(prs.len(), 105);
1994        mock_p1.assert();
1995        mock_p2.assert();
1996    }
1997
1998    #[test]
1999    fn pull_request_repo_slug_from_html_url() {
2000        let pr = PullRequest {
2001            number: 42,
2002            title: "x".into(),
2003            state: "open".into(),
2004            pull_request: None,
2005            html_url: "https://github.com/slopfest/sandogasa/pull/42".into(),
2006            repository_url: None,
2007        };
2008        assert_eq!(pr.repo_slug().as_deref(), Some("slopfest/sandogasa"));
2009    }
2010
2011    #[test]
2012    fn pull_request_repo_slug_from_repository_url() {
2013        let pr = PullRequest {
2014            number: 42,
2015            title: "x".into(),
2016            state: "open".into(),
2017            pull_request: None,
2018            html_url: "https://github.com/o/r/issues/42".into(),
2019            repository_url: Some("https://api.github.com/repos/slopfest/sandogasa".into()),
2020        };
2021        // html_url is consulted first, but works as a fallback path.
2022        let pr2 = PullRequest {
2023            html_url: "garbage".into(),
2024            ..pr
2025        };
2026        assert_eq!(pr2.repo_slug().as_deref(), Some("slopfest/sandogasa"));
2027    }
2028
2029    #[test]
2030    fn pull_request_merged_at_via_helper() {
2031        let pr: PullRequest = serde_json::from_str(
2032            r#"{"number":1,"title":"t","state":"closed",
2033                "html_url":"https://github.com/o/r/pull/1",
2034                "pull_request":{"merged_at":"2026-02-01T10:00:00Z"}}"#,
2035        )
2036        .unwrap();
2037        assert_eq!(pr.merged_at(), Some("2026-02-01T10:00:00Z"));
2038    }
2039
2040    #[test]
2041    fn user_events_pagination_stops_at_300() {
2042        let mut server = mockito::Server::new();
2043        // GitHub serves at most 3 pages of events. Page 1 and 2
2044        // return full pages, page 3 returns a final 50 to test the
2045        // short-page break path.
2046        let make_event = |i: u64| {
2047            format!(
2048                r#"{{"id":"{i}","type":"PushEvent","repo":{{"id":1,"name":"o/r"}},"created_at":"2026-02-15T10:00:00Z"}}"#
2049            )
2050        };
2051        let page1: String = (1..=100).map(make_event).collect::<Vec<_>>().join(",");
2052        let page2: String = (101..=200).map(make_event).collect::<Vec<_>>().join(",");
2053        let page3: String = (201..=250).map(make_event).collect::<Vec<_>>().join(",");
2054        let m1 = server
2055            .mock("GET", "/users/octocat/events")
2056            .match_query(mockito::Matcher::UrlEncoded("page".into(), "1".into()))
2057            .with_status(200)
2058            .with_body(format!("[{page1}]"))
2059            .create();
2060        let m2 = server
2061            .mock("GET", "/users/octocat/events")
2062            .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
2063            .with_status(200)
2064            .with_body(format!("[{page2}]"))
2065            .create();
2066        let m3 = server
2067            .mock("GET", "/users/octocat/events")
2068            .match_query(mockito::Matcher::UrlEncoded("page".into(), "3".into()))
2069            .with_status(200)
2070            .with_body(format!("[{page3}]"))
2071            .create();
2072        let client = Client::new(&server.url(), "tok").unwrap();
2073        let events = client.user_events("octocat").unwrap();
2074        assert_eq!(events.len(), 250);
2075        m1.assert();
2076        m2.assert();
2077        m3.assert();
2078    }
2079
2080    #[test]
2081    fn count_authored_commits_paginates_and_handles_409() {
2082        let mut server = mockito::Server::new();
2083        let m1 = server
2084            .mock("GET", "/repos/o/r/commits")
2085            .match_query(mockito::Matcher::UrlEncoded("page".into(), "1".into()))
2086            .with_status(200)
2087            .with_body(format!("[{}]", vec!["{}"; 100].join(",")))
2088            .create();
2089        let m2 = server
2090            .mock("GET", "/repos/o/r/commits")
2091            .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
2092            .with_status(200)
2093            .with_body("[{},{}]")
2094            .create();
2095        let client = Client::new(&server.url(), "tok").unwrap();
2096        let n = client
2097            .count_authored_commits(
2098                "o",
2099                "r",
2100                "octocat",
2101                chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(),
2102                chrono::NaiveDate::from_ymd_opt(2026, 3, 31).unwrap(),
2103            )
2104            .unwrap();
2105        assert_eq!(n, 102);
2106        m1.assert();
2107        m2.assert();
2108    }
2109
2110    #[test]
2111    fn count_authored_commits_empty_repo_returns_zero() {
2112        let mut server = mockito::Server::new();
2113        let mock = server
2114            .mock("GET", "/repos/o/empty/commits")
2115            .match_query(mockito::Matcher::Any)
2116            .with_status(409)
2117            .with_body(r#"{"message":"Git Repository is empty."}"#)
2118            .create();
2119        let client = Client::new(&server.url(), "tok").unwrap();
2120        let n = client
2121            .count_authored_commits(
2122                "o",
2123                "empty",
2124                "x",
2125                chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(),
2126                chrono::NaiveDate::from_ymd_opt(2026, 3, 31).unwrap(),
2127            )
2128            .unwrap();
2129        assert_eq!(n, 0);
2130        mock.assert();
2131    }
2132
2133    #[test]
2134    fn validate_token_distinguishes_invalid_from_error() {
2135        let mut server = mockito::Server::new();
2136        // Valid token.
2137        let ok = server
2138            .mock("GET", "/user")
2139            .match_header("authorization", "Bearer good")
2140            .with_status(200)
2141            .with_body(r#"{"id": 1, "login": "octocat"}"#)
2142            .create();
2143        assert!(validate_token(&server.url(), "good").unwrap());
2144        ok.assert();
2145        // Wrong token → 401.
2146        let bad = server
2147            .mock("GET", "/user")
2148            .match_header("authorization", "Bearer bad")
2149            .with_status(401)
2150            .with_body(r#"{"message": "Bad credentials"}"#)
2151            .create();
2152        assert!(!validate_token(&server.url(), "bad").unwrap());
2153        bad.assert();
2154    }
2155
2156    #[test]
2157    fn repository_slug_prefers_full_name() {
2158        let repo = Repository {
2159            id: 1,
2160            full_name: Some("o/r".into()),
2161            name: Some("ignored".into()),
2162        };
2163        assert_eq!(repo.slug(), Some("o/r"));
2164        // Event payloads only ship `name`.
2165        let evt_repo = Repository {
2166            id: 1,
2167            full_name: None,
2168            name: Some("o/r".into()),
2169        };
2170        assert_eq!(evt_repo.slug(), Some("o/r"));
2171    }
2172
2173    #[test]
2174    fn moved_repositories_answer_their_current_names_in_one_request() {
2175        let mut server = mockito::Server::new();
2176        let m = server
2177            .mock("POST", "/graphql")
2178            .match_body(mockito::Matcher::AllOf(vec![
2179                mockito::Matcher::Regex(r#""o0":"old""#.into()),
2180                mockito::Matcher::Regex(r#""n2":"gone""#.into()),
2181            ]))
2182            .with_body(graphql_body(
2183                json!({"r0": {"nameWithOwner": "new/moved"},
2184                       "r1": {"nameWithOwner": "same/repo"},
2185                       "r2": null}),
2186                json!([{"type": "NOT_FOUND", "message": "Could not resolve"}]),
2187            ))
2188            .expect(1)
2189            .create();
2190        let client = Client::new(&server.url(), "tok").unwrap();
2191        let names = client
2192            .current_repo_names(&[
2193                "old/moved".to_string(),
2194                "same/repo".to_string(),
2195                "old/gone".to_string(),
2196                "no-slash".to_string(),
2197            ])
2198            .unwrap();
2199        m.assert();
2200        assert_eq!(names["old/moved"].as_deref(), Some("new/moved"));
2201        assert_eq!(names["same/repo"].as_deref(), Some("same/repo"));
2202        assert_eq!(names["old/gone"], None);
2203        assert_eq!(names["no-slash"], None);
2204    }
2205
2206    #[test]
2207    fn a_name_lookup_without_data_is_an_error() {
2208        let mut server = mockito::Server::new();
2209        server
2210            .mock("POST", "/graphql")
2211            .with_body(graphql_body(
2212                json!(null),
2213                json!([{"message": "Bad credentials"}]),
2214            ))
2215            .create();
2216        let client = Client::new(&server.url(), "tok").unwrap();
2217        let err = client
2218            .current_repo_names(&["a/b".to_string()])
2219            .unwrap_err()
2220            .to_string();
2221        assert!(err.contains("Bad credentials"), "{err}");
2222        // A repository refused rather than missing fails the lookup.
2223        let mut server = mockito::Server::new();
2224        server
2225            .mock("POST", "/graphql")
2226            .with_body(graphql_body(
2227                json!({"r0": null}),
2228                json!([{"type": "FORBIDDEN", "message": "SAML enforcement"}]),
2229            ))
2230            .create();
2231        let client = Client::new(&server.url(), "tok").unwrap();
2232        let err = client
2233            .current_repo_names(&["org/r".to_string()])
2234            .unwrap_err()
2235            .to_string();
2236        assert!(err.contains("SAML enforcement"), "{err}");
2237        // Nothing to ask makes no request.
2238        assert!(client.current_repo_names(&[]).unwrap().is_empty());
2239    }
2240}