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, and per-repo
9//! authored-commit counts.
10//!
11//! Mirrors `sandogasa-gitlab` in shape so downstream tools can
12//! treat the two forges the same way structurally — host-keyed
13//! tokens and identities, optional org/group filter, etc.
14//!
15//! ```no_run
16//! use sandogasa_github::Client;
17//!
18//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
19//! let client = Client::new("https://api.github.com", "ghp_token")?;
20//! let user = client.user_by_username("octocat")?.expect("user exists");
21//! let prs = client.search_pull_requests(
22//!     &format!("type:pr author:{} created:2026-01-01..2026-03-31", user.login),
23//! )?;
24//! for pr in prs {
25//!     println!("{}: {}", pr.number, pr.title);
26//! }
27//! # Ok(())
28//! # }
29//! ```
30
31use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderName, HeaderValue};
32use sandogasa_cli::http;
33use serde::{Deserialize, Serialize};
34
35/// A GitHub user as returned by `/users/{username}`. Only the
36/// fields downstream tools currently consume.
37#[derive(Debug, Clone, Deserialize, Serialize)]
38#[non_exhaustive]
39pub struct User {
40    pub id: u64,
41    pub login: String,
42    /// Public display name (`null` when the user hasn't set one).
43    #[serde(default)]
44    pub name: Option<String>,
45    /// Public email (`null` when the user keeps it private).
46    #[serde(default)]
47    pub email: Option<String>,
48}
49
50/// A repository as returned by event payloads and PR responses.
51#[derive(Debug, Clone, Deserialize, Serialize)]
52#[non_exhaustive]
53pub struct Repository {
54    pub id: u64,
55    /// `owner/name`, e.g. `slopfest/sandogasa`.
56    #[serde(default)]
57    pub full_name: Option<String>,
58    /// For event payloads where `repo.name` already carries the
59    /// `owner/name` form; preserved verbatim.
60    #[serde(default)]
61    pub name: Option<String>,
62}
63
64impl Repository {
65    /// Best-effort `owner/name` extractor. Falls back to `name`
66    /// for event payloads where `repo.full_name` is omitted.
67    pub fn slug(&self) -> Option<&str> {
68        self.full_name.as_deref().or(self.name.as_deref())
69    }
70}
71
72/// A pull request as returned by the Search Issues endpoint
73/// when filtering on `type:pr`. The Search API actually returns
74/// "issue" objects with PR-specific fields populated, so we
75/// shape this around the union of useful fields rather than the
76/// fuller `/repos/{owner}/{repo}/pulls/{number}` model.
77#[derive(Debug, Clone, Deserialize, Serialize)]
78#[non_exhaustive]
79pub struct PullRequest {
80    pub number: u64,
81    pub title: String,
82    pub state: String,
83    /// Set when the PR has been merged. Some search responses
84    /// omit this field for open PRs.
85    #[serde(default)]
86    pub pull_request: Option<PullRequestRef>,
87    pub html_url: String,
88    /// The repo this PR lives in — derived from `html_url` since
89    /// the search response doesn't include a structured `repo`
90    /// object.
91    #[serde(default)]
92    pub repository_url: Option<String>,
93}
94
95impl PullRequest {
96    /// Extract the `owner/name` slug from this PR's HTML URL or
97    /// `repository_url`.
98    pub fn repo_slug(&self) -> Option<String> {
99        // html_url shape: `https://github.com/{owner}/{repo}/pull/N`
100        if let Some(rest) = self
101            .html_url
102            .strip_prefix("https://github.com/")
103            .or_else(|| self.html_url.strip_prefix("https://"))
104        {
105            let parts: Vec<&str> = rest.splitn(4, '/').collect();
106            if parts.len() >= 2 {
107                return Some(format!("{}/{}", parts[0], parts[1]));
108            }
109        }
110        // Fallback: repository_url shape is
111        // `https://api.github.com/repos/{owner}/{repo}`.
112        if let Some(repo) = &self.repository_url
113            && let Some(rest) = repo.split("/repos/").nth(1)
114        {
115            return Some(rest.to_string());
116        }
117        None
118    }
119
120    /// Whether this PR has been merged. The Search API surfaces
121    /// merge state via the optional `pull_request.merged_at`
122    /// field; absence means "not merged".
123    pub fn merged_at(&self) -> Option<&str> {
124        self.pull_request
125            .as_ref()
126            .and_then(|p| p.merged_at.as_deref())
127    }
128}
129
130/// Auxiliary block on a search-result issue when it's actually
131/// a pull request. The Search Issues endpoint signals "is PR"
132/// by populating this; merged state lives here too.
133#[derive(Debug, Clone, Deserialize, Serialize)]
134#[non_exhaustive]
135pub struct PullRequestRef {
136    #[serde(default)]
137    pub merged_at: Option<String>,
138}
139
140/// The fuller pull-request object from `/repos/{owner}/{repo}/pulls/{n}`:
141/// the head and base refs the search result omits, and whether it merged.
142#[derive(Debug, Clone, Deserialize)]
143#[non_exhaustive]
144pub struct PullRequestDetail {
145    pub number: u64,
146    pub state: String,
147    #[serde(default)]
148    pub merged: bool,
149    pub head: GitRef,
150    pub base: GitRef,
151    /// When the PR was opened (RFC 3339).
152    #[serde(default)]
153    pub created_at: Option<String>,
154    /// Who opened it.
155    #[serde(default)]
156    pub user: Option<Login>,
157}
158
159/// An account named only by its login.
160#[derive(Debug, Clone, Deserialize)]
161#[non_exhaustive]
162pub struct Login {
163    pub login: String,
164}
165
166/// A commit from `/pulls/{n}/commits` or `/commits`: the sha, the
167/// message and the author of the commit itself (not the GitHub account).
168#[derive(Debug, Clone, Deserialize)]
169#[non_exhaustive]
170pub struct RepoCommit {
171    pub sha: String,
172    pub commit: CommitBody,
173}
174
175/// The git-level part of a commit.
176#[derive(Debug, Clone, Deserialize)]
177#[non_exhaustive]
178pub struct CommitBody {
179    #[serde(default)]
180    pub message: String,
181    #[serde(default)]
182    pub author: Option<CommitAuthor>,
183}
184
185/// A commit's author as git recorded it.
186#[derive(Debug, Clone, Deserialize)]
187#[non_exhaustive]
188pub struct CommitAuthor {
189    #[serde(default)]
190    pub name: String,
191    #[serde(default)]
192    pub email: String,
193}
194
195impl RepoCommit {
196    /// The message's first line.
197    pub fn title(&self) -> &str {
198        self.commit.message.lines().next().unwrap_or("")
199    }
200}
201
202/// One side of a pull request: the branch name and the commit it points at.
203#[derive(Debug, Clone, Deserialize)]
204#[non_exhaustive]
205pub struct GitRef {
206    #[serde(rename = "ref")]
207    pub ref_name: String,
208    pub sha: String,
209}
210
211/// What `/compare/{base}...{head}` answers: `ahead_by` counts the commits
212/// on head that base lacks, so zero means base already has them all.
213#[derive(Debug, Deserialize)]
214struct CompareResult {
215    #[serde(default)]
216    ahead_by: u64,
217}
218
219/// Wire response wrapper for the Search Issues endpoint.
220#[derive(Debug, Deserialize)]
221struct SearchIssuesResponse {
222    total_count: u64,
223    items: Vec<PullRequest>,
224}
225
226/// One entry from `/users/{username}/events`. Fields are
227/// sparse; we keep just enough to identify the event type,
228/// associated repo, and the actor.
229#[derive(Debug, Clone, Deserialize, Serialize)]
230#[non_exhaustive]
231pub struct Event {
232    pub id: String,
233    /// `"PushEvent"`, `"PullRequestEvent"`,
234    /// `"PullRequestReviewCommentEvent"`, etc.
235    #[serde(rename = "type")]
236    pub event_type: String,
237    pub repo: Repository,
238    pub created_at: String,
239    /// Free-form payload — varies per event type.
240    #[serde(default)]
241    pub payload: serde_json::Value,
242}
243
244/// One entry from `/repos/{owner}/{repo}/git/refs/tags`. The
245/// underlying `object` distinguishes lightweight tags (point
246/// directly to a commit) from annotated tags (point to a Tag
247/// object that carries tagger info).
248#[derive(Debug, Clone, Deserialize, Serialize)]
249#[non_exhaustive]
250pub struct GitTagRef {
251    /// The fully-qualified ref, e.g. `refs/tags/v0.11.0`.
252    #[serde(rename = "ref")]
253    pub ref_name: String,
254    pub object: GitObject,
255}
256
257impl GitTagRef {
258    /// Strip the `refs/tags/` prefix to get just the tag name.
259    pub fn tag_name(&self) -> &str {
260        self.ref_name
261            .strip_prefix("refs/tags/")
262            .unwrap_or(&self.ref_name)
263    }
264}
265
266/// The thing a Git ref points at. `object_type` is `"commit"`
267/// for lightweight tags and `"tag"` for annotated ones.
268#[derive(Debug, Clone, Deserialize, Serialize)]
269#[non_exhaustive]
270pub struct GitObject {
271    #[serde(rename = "type")]
272    pub object_type: String,
273    pub sha: String,
274}
275
276/// An annotated-tag object from
277/// `/repos/{owner}/{repo}/git/tags/{sha}`. Only annotated tags
278/// carry tagger metadata; lightweight tags don't have an
279/// addressable tag object.
280#[derive(Debug, Clone, Deserialize, Serialize)]
281#[non_exhaustive]
282pub struct AnnotatedTag {
283    pub tag: String,
284    pub tagger: Tagger,
285}
286
287/// `name` + `email` + `date` triple stamped on annotated-tag
288/// creation. `date` is ISO 8601 (e.g. `2026-05-15T17:03:15Z`).
289#[derive(Debug, Clone, Deserialize, Serialize)]
290#[non_exhaustive]
291pub struct Tagger {
292    pub name: String,
293    pub email: String,
294    pub date: String,
295}
296
297impl Event {
298    /// Helper for callers walking events to find touched repos —
299    /// returns the `owner/name` slug if available.
300    pub fn repo_slug(&self) -> Option<&str> {
301        self.repo.slug()
302    }
303}
304
305/// Blocking GitHub REST client.
306pub struct Client {
307    http: reqwest::blocking::Client,
308    base_url: String,
309}
310
311impl Client {
312    /// Build a client for `base_url` (typically
313    /// `https://api.github.com`, or a GHES instance's `/api/v3`
314    /// endpoint) authenticated with the given personal access
315    /// token.
316    pub fn new(base_url: &str, token: &str) -> Result<Self, Box<dyn std::error::Error>> {
317        sandogasa_cli::ensure_secure_url(base_url)?;
318        let http = build_http_client(token)?;
319        Ok(Self {
320            http,
321            base_url: base_url.trim_end_matches('/').to_string(),
322        })
323    }
324
325    /// Resolve a username to its full user object. Returns `None`
326    /// when the API responds with 404 (no such user); other
327    /// errors are returned as `Err`.
328    pub fn user_by_username(
329        &self,
330        username: &str,
331    ) -> Result<Option<User>, Box<dyn std::error::Error>> {
332        let url = format!("{}/users/{}", self.base_url, username);
333        let resp = self.http.get(&url).send()?;
334        if resp.status().as_u16() == 404 {
335            return Ok(None);
336        }
337        Ok(Some(http::blocking_json_ok(
338            resp,
339            &format!("GitHub GET {url}"),
340        )?))
341    }
342
343    /// Run the Search Issues endpoint with the caller-supplied
344    /// query string and return every PR across all result pages.
345    ///
346    /// GitHub caps Search results at 1000 items total; if a
347    /// query exceeds that, the caller needs to narrow it (e.g.
348    /// by splitting the date window).
349    pub fn search_pull_requests(
350        &self,
351        query: &str,
352    ) -> Result<Vec<PullRequest>, Box<dyn std::error::Error>> {
353        let mut out: Vec<PullRequest> = Vec::new();
354        let mut page = 1u32;
355        loop {
356            let page_str = page.to_string();
357            let url = format!("{}/search/issues", self.base_url);
358            let resp = self
359                .http
360                .get(&url)
361                .query(&[("q", query), ("per_page", "100"), ("page", &page_str)])
362                .send()?;
363            let batch: SearchIssuesResponse = http::blocking_json_ok(resp, "GitHub search")?;
364            let n = batch.items.len();
365            out.extend(batch.items);
366            if n < 100 || out.len() as u64 >= batch.total_count {
367                break;
368            }
369            page += 1;
370        }
371        Ok(out)
372    }
373
374    /// Paginate through the user-events endpoint up to GitHub's
375    /// 300-event cap. Returns the most recent events first.
376    pub fn user_events(&self, username: &str) -> Result<Vec<Event>, Box<dyn std::error::Error>> {
377        let mut out: Vec<Event> = Vec::new();
378        let mut page = 1u32;
379        loop {
380            let url = format!("{}/users/{}/events", self.base_url, username);
381            let page_str = page.to_string();
382            let resp = self
383                .http
384                .get(&url)
385                .query(&[("per_page", "100"), ("page", &page_str)])
386                .send()?;
387            let batch: Vec<Event> = http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
388            let n = batch.len();
389            out.extend(batch);
390            // GitHub serves at most 300 events / 3 pages of 100.
391            if n < 100 || page >= 3 {
392                break;
393            }
394            page += 1;
395        }
396        Ok(out)
397    }
398
399    /// Count commits in `owner/repo` authored by `author` within
400    /// `[since, until]` (inclusive). Used as a cross-check
401    /// against push-event counts — see the GitLab equivalent
402    /// for the rationale.
403    ///
404    /// 404 and 409 responses are treated as "0 commits" rather
405    /// than errors. 404 means the repo was deleted or made
406    /// private between the events scan and this call; 409 means
407    /// the repo exists but is empty. Either way, a single
408    /// missing repo shouldn't abort the surrounding report.
409    /// The trade-off: real auth failures targeting a single
410    /// repo would also be hidden, but GitHub returns 401/403 for
411    /// those, not 404/409.
412    pub fn count_authored_commits(
413        &self,
414        owner: &str,
415        repo: &str,
416        author: &str,
417        since: chrono::NaiveDate,
418        until: chrono::NaiveDate,
419    ) -> Result<u64, Box<dyn std::error::Error>> {
420        let url = format!("{}/repos/{}/{}/commits", self.base_url, owner, repo);
421        let since_str = format!("{since}T00:00:00Z");
422        let until_str = format!("{until}T23:59:59Z");
423        let mut total: u64 = 0;
424        let mut page = 1u32;
425        loop {
426            let page_str = page.to_string();
427            let query: Vec<(&str, &str)> = vec![
428                ("author", author),
429                ("since", &since_str),
430                ("until", &until_str),
431                ("per_page", "100"),
432                ("page", &page_str),
433            ];
434            let resp = self.http.get(&url).query(&query).send()?;
435            // GitHub returns 409 Conflict for empty repositories
436            // and 404 if the repo was deleted. Treat both as
437            // "no commits" rather than hard errors so a single
438            // gone repo doesn't abort the whole report.
439            if resp.status().as_u16() == 404 || resp.status().as_u16() == 409 {
440                break;
441            }
442            let batch: Vec<serde_json::Value> =
443                http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
444            let n = batch.len() as u64;
445            total += n;
446            if n < 100 {
447                break;
448            }
449            page += 1;
450        }
451        Ok(total)
452    }
453
454    /// List all tag refs for `owner/repo`. Returns an empty list
455    /// on 404 (gone repo) and 409 (empty repo) so callers can
456    /// iterate over many repos without per-repo error handling.
457    pub fn list_tag_refs(
458        &self,
459        owner: &str,
460        repo: &str,
461    ) -> Result<Vec<GitTagRef>, Box<dyn std::error::Error>> {
462        let url = format!("{}/repos/{}/{}/git/refs/tags", self.base_url, owner, repo);
463        let resp = self.http.get(&url).send()?;
464        // 404 = repo gone or no tags ref namespace; 409 = empty repo.
465        if resp.status().as_u16() == 404 || resp.status().as_u16() == 409 {
466            return Ok(Vec::new());
467        }
468        let resp = http::blocking_ok(resp, &format!("GitHub GET {url}"))?;
469        // GitHub returns an object (not an array) when there's
470        // exactly one match. The standard `/git/refs/tags` shape
471        // returns an array for the namespace listing; we only see
472        // the object form when someone queries a single ref. Be
473        // defensive and accept both.
474        let body: serde_json::Value = resp.json()?;
475        if body.is_array() {
476            Ok(serde_json::from_value(body)?)
477        } else {
478            Ok(vec![serde_json::from_value(body)?])
479        }
480    }
481
482    /// Fetch one annotated-tag object by SHA. Use only when the
483    /// matching `GitTagRef.object.object_type == "tag"` —
484    /// lightweight tags (where `object_type == "commit"`) have no
485    /// addressable tag object and this endpoint will 404.
486    pub fn get_annotated_tag(
487        &self,
488        owner: &str,
489        repo: &str,
490        sha: &str,
491    ) -> Result<AnnotatedTag, Box<dyn std::error::Error>> {
492        let url = format!(
493            "{}/repos/{}/{}/git/tags/{}",
494            self.base_url, owner, repo, sha
495        );
496        let resp = self.http.get(&url).send()?;
497        Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
498    }
499
500    /// Fetch the fuller pull-request object for `owner/repo#number` — in
501    /// particular its `head` and `base` refs, which the search result
502    /// omits.
503    pub fn pull_request(
504        &self,
505        owner: &str,
506        repo: &str,
507        number: u64,
508    ) -> Result<PullRequestDetail, Box<dyn std::error::Error>> {
509        let url = format!("{}/repos/{owner}/{repo}/pulls/{number}", self.base_url);
510        let resp = self.http.get(&url).send()?;
511        Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
512    }
513
514    /// The commits a pull request carries, oldest first (one page; a
515    /// PR of more than a hundred commits is not what this is for).
516    pub fn pull_request_commits(
517        &self,
518        owner: &str,
519        repo: &str,
520        number: u64,
521    ) -> Result<Vec<RepoCommit>, Box<dyn std::error::Error>> {
522        let url = format!(
523            "{}/repos/{owner}/{repo}/pulls/{number}/commits",
524            self.base_url
525        );
526        let resp = self.http.get(&url).query(&[("per_page", "100")]).send()?;
527        Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
528    }
529
530    /// Commits on `branch` by `author` (a login or an email) since an
531    /// RFC 3339 instant, newest first; one page of up to a hundred,
532    /// which is plenty for one person's commits on one branch since a
533    /// PR was opened.
534    pub fn branch_commits_by(
535        &self,
536        owner: &str,
537        repo: &str,
538        branch: &str,
539        author: &str,
540        since: &str,
541    ) -> Result<Vec<RepoCommit>, Box<dyn std::error::Error>> {
542        let url = format!("{}/repos/{owner}/{repo}/commits", self.base_url);
543        let resp = self
544            .http
545            .get(&url)
546            .query(&[
547                ("sha", branch),
548                ("author", author),
549                ("since", since),
550                ("per_page", "100"),
551            ])
552            .send()?;
553        Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
554    }
555
556    /// Whether `sha` is already on `branch`: GitHub's compare of the
557    /// branch to the sha reports how many commits the sha is ahead by,
558    /// and zero means the branch has every one of them.
559    pub fn commit_contained(
560        &self,
561        owner: &str,
562        repo: &str,
563        branch: &str,
564        sha: &str,
565    ) -> Result<bool, Box<dyn std::error::Error>> {
566        let url = format!(
567            "{}/repos/{owner}/{repo}/compare/{branch}...{sha}",
568            self.base_url
569        );
570        let resp = self.http.get(&url).send()?;
571        let cmp: CompareResult =
572            http::blocking_json_ok(resp, &format!("GitHub compare {branch}...{sha}"))?;
573        Ok(cmp.ahead_by == 0)
574    }
575}
576
577/// Check whether `token` works against `base_url` by hitting
578/// `/user`. Returns `Ok(true)` for valid tokens, `Ok(false)`
579/// for 401s, and `Err` for other transport / server errors so
580/// callers can distinguish "tried and was rejected" from
581/// "couldn't reach the server".
582pub fn validate_token(base_url: &str, token: &str) -> Result<bool, Box<dyn std::error::Error>> {
583    sandogasa_cli::ensure_secure_url(base_url)?;
584    let http = build_http_client(token)?;
585    let url = format!("{}/user", base_url.trim_end_matches('/'));
586    let resp = http.get(&url).send()?;
587    let status = resp.status();
588    if status.is_success() {
589        return Ok(true);
590    }
591    if status.as_u16() == 401 {
592        return Ok(false);
593    }
594    let text = resp.text().unwrap_or_default();
595    Err(format!("GitHub /user check failed: {status}: {text}").into())
596}
597
598/// Build a reqwest client preconfigured for the GitHub API: the
599/// Bearer token, the recommended JSON Accept header, a User-Agent
600/// (GitHub requires one), and our standard request timeout.
601fn build_http_client(token: &str) -> Result<reqwest::blocking::Client, Box<dyn std::error::Error>> {
602    let mut headers = HeaderMap::new();
603    headers.insert(
604        AUTHORIZATION,
605        HeaderValue::from_str(&format!("Bearer {token}"))?,
606    );
607    headers.insert(
608        ACCEPT,
609        HeaderValue::from_static("application/vnd.github+json"),
610    );
611    headers.insert(
612        HeaderName::from_static("x-github-api-version"),
613        HeaderValue::from_static("2022-11-28"),
614    );
615    Ok(http::blocking_builder(concat!(
616        env!("CARGO_PKG_NAME"),
617        "/",
618        env!("CARGO_PKG_VERSION")
619    ))
620    .default_headers(headers)
621    .build()?)
622}
623
624#[cfg(test)]
625mod tests {
626    use super::*;
627
628    #[test]
629    fn pull_request_reads_head_and_base() {
630        let mut server = mockito::Server::new();
631        let mock = server
632            .mock("GET", "/repos/o/r/pulls/92")
633            .with_status(200)
634            .with_body(
635                r#"{"number": 92, "state": "closed", "merged": false,
636                    "head": {"ref": "fix", "sha": "8b8aa8b"},
637                    "base": {"ref": "main", "sha": "0000000"}}"#,
638            )
639            .create();
640        let client = Client::new(&server.url(), "tok").unwrap();
641        let pr = client.pull_request("o", "r", 92).unwrap();
642        mock.assert();
643        assert_eq!(pr.head.sha, "8b8aa8b");
644        assert_eq!(pr.base.ref_name, "main");
645        assert!(!pr.merged);
646    }
647
648    #[test]
649    fn branch_commits_by_filters_by_author_and_since() {
650        let mut server = mockito::Server::new();
651        let mock = server
652            .mock("GET", "/repos/o/r/commits")
653            .match_query(mockito::Matcher::AllOf(vec![
654                mockito::Matcher::UrlEncoded("sha".into(), "main".into()),
655                mockito::Matcher::UrlEncoded("author".into(), "michel-slm".into()),
656                mockito::Matcher::UrlEncoded("since".into(), "2026-03-04T00:00:00Z".into()),
657            ]))
658            .with_status(200)
659            .with_body(
660                r#"[{"sha": "abc", "commit": {"message": "Ignore it\n\nbody",
661                     "author": {"name": "Michel Lind", "email": "m@example.org"}}}]"#,
662            )
663            .create();
664        let client = Client::new(&server.url(), "tok").unwrap();
665        let commits = client
666            .branch_commits_by("o", "r", "main", "michel-slm", "2026-03-04T00:00:00Z")
667            .unwrap();
668        mock.assert();
669        assert_eq!(commits[0].title(), "Ignore it");
670        assert_eq!(
671            commits[0].commit.author.as_ref().unwrap().name,
672            "Michel Lind"
673        );
674    }
675
676    #[test]
677    fn commit_contained_reads_ahead_by() {
678        // ahead_by == 0 (status "identical" or "behind") → the sha is on
679        // the branch already.
680        let mut server = mockito::Server::new();
681        let mock = server
682            .mock("GET", "/repos/o/r/compare/main...8b8aa8b")
683            .with_status(200)
684            .with_body(r#"{"status": "behind", "ahead_by": 0, "behind_by": 4}"#)
685            .create();
686        let client = Client::new(&server.url(), "tok").unwrap();
687        assert!(
688            client
689                .commit_contained("o", "r", "main", "8b8aa8b")
690                .unwrap()
691        );
692        mock.assert();
693
694        let mut server = mockito::Server::new();
695        server
696            .mock("GET", "/repos/o/r/compare/main...other")
697            .with_status(200)
698            .with_body(r#"{"status": "diverged", "ahead_by": 2, "behind_by": 4}"#)
699            .create();
700        let client = Client::new(&server.url(), "tok").unwrap();
701        assert!(!client.commit_contained("o", "r", "main", "other").unwrap());
702    }
703
704    #[test]
705    fn new_rejects_plaintext_remote() {
706        // A token must not be sent to a plaintext http non-loopback URL.
707        assert!(Client::new("http://api.example.com", "tok").is_err());
708    }
709
710    #[test]
711    fn user_by_username_returns_user() {
712        let mut server = mockito::Server::new();
713        let mock = server
714            .mock("GET", "/users/octocat")
715            .match_header("authorization", "Bearer tok")
716            .with_status(200)
717            .with_body(r#"{"id": 1, "login": "octocat"}"#)
718            .create();
719        let client = Client::new(&server.url(), "tok").unwrap();
720        let user = client.user_by_username("octocat").unwrap().unwrap();
721        assert_eq!(user.id, 1);
722        assert_eq!(user.login, "octocat");
723        mock.assert();
724    }
725
726    #[test]
727    fn user_by_username_404_is_none() {
728        let mut server = mockito::Server::new();
729        let mock = server
730            .mock("GET", "/users/ghost")
731            .with_status(404)
732            .with_body(r#"{"message": "Not Found"}"#)
733            .create();
734        let client = Client::new(&server.url(), "tok").unwrap();
735        assert!(client.user_by_username("ghost").unwrap().is_none());
736        mock.assert();
737    }
738
739    #[test]
740    fn search_pull_requests_paginates() {
741        let mut server = mockito::Server::new();
742        // First page: full 100 items, total_count says 105.
743        let items_page1 = (1..=100)
744            .map(|i| {
745                format!(
746                    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"}}}}"#
747                )
748            })
749            .collect::<Vec<_>>()
750            .join(",");
751        let mock_p1 = server
752            .mock("GET", "/search/issues")
753            .match_query(mockito::Matcher::AllOf(vec![
754                mockito::Matcher::UrlEncoded("page".into(), "1".into()),
755                mockito::Matcher::UrlEncoded("per_page".into(), "100".into()),
756            ]))
757            .with_status(200)
758            .with_body(format!(
759                r#"{{"total_count":105,"incomplete_results":false,"items":[{items_page1}]}}"#
760            ))
761            .create();
762        let mock_p2 = server
763            .mock("GET", "/search/issues")
764            .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
765            .with_status(200)
766            .with_body(
767                r#"{"total_count":105,"incomplete_results":false,"items":[
768                    {"number":101,"title":"x","state":"open","html_url":"https://github.com/o/r/pull/101"},
769                    {"number":102,"title":"y","state":"open","html_url":"https://github.com/o/r/pull/102"},
770                    {"number":103,"title":"z","state":"open","html_url":"https://github.com/o/r/pull/103"},
771                    {"number":104,"title":"w","state":"open","html_url":"https://github.com/o/r/pull/104"},
772                    {"number":105,"title":"v","state":"open","html_url":"https://github.com/o/r/pull/105"}
773                ]}"#,
774            )
775            .create();
776        let client = Client::new(&server.url(), "tok").unwrap();
777        let prs = client
778            .search_pull_requests("type:pr author:octocat")
779            .unwrap();
780        assert_eq!(prs.len(), 105);
781        mock_p1.assert();
782        mock_p2.assert();
783    }
784
785    #[test]
786    fn pull_request_repo_slug_from_html_url() {
787        let pr = PullRequest {
788            number: 42,
789            title: "x".into(),
790            state: "open".into(),
791            pull_request: None,
792            html_url: "https://github.com/slopfest/sandogasa/pull/42".into(),
793            repository_url: None,
794        };
795        assert_eq!(pr.repo_slug().as_deref(), Some("slopfest/sandogasa"));
796    }
797
798    #[test]
799    fn pull_request_repo_slug_from_repository_url() {
800        let pr = PullRequest {
801            number: 42,
802            title: "x".into(),
803            state: "open".into(),
804            pull_request: None,
805            html_url: "https://github.com/o/r/issues/42".into(),
806            repository_url: Some("https://api.github.com/repos/slopfest/sandogasa".into()),
807        };
808        // html_url is consulted first, but works as a fallback path.
809        let pr2 = PullRequest {
810            html_url: "garbage".into(),
811            ..pr
812        };
813        assert_eq!(pr2.repo_slug().as_deref(), Some("slopfest/sandogasa"));
814    }
815
816    #[test]
817    fn pull_request_merged_at_via_helper() {
818        let pr: PullRequest = serde_json::from_str(
819            r#"{"number":1,"title":"t","state":"closed",
820                "html_url":"https://github.com/o/r/pull/1",
821                "pull_request":{"merged_at":"2026-02-01T10:00:00Z"}}"#,
822        )
823        .unwrap();
824        assert_eq!(pr.merged_at(), Some("2026-02-01T10:00:00Z"));
825    }
826
827    #[test]
828    fn user_events_pagination_stops_at_300() {
829        let mut server = mockito::Server::new();
830        // GitHub serves at most 3 pages of events. Page 1 and 2
831        // return full pages, page 3 returns a final 50 to test the
832        // short-page break path.
833        let make_event = |i: u64| {
834            format!(
835                r#"{{"id":"{i}","type":"PushEvent","repo":{{"id":1,"name":"o/r"}},"created_at":"2026-02-15T10:00:00Z"}}"#
836            )
837        };
838        let page1: String = (1..=100).map(make_event).collect::<Vec<_>>().join(",");
839        let page2: String = (101..=200).map(make_event).collect::<Vec<_>>().join(",");
840        let page3: String = (201..=250).map(make_event).collect::<Vec<_>>().join(",");
841        let m1 = server
842            .mock("GET", "/users/octocat/events")
843            .match_query(mockito::Matcher::UrlEncoded("page".into(), "1".into()))
844            .with_status(200)
845            .with_body(format!("[{page1}]"))
846            .create();
847        let m2 = server
848            .mock("GET", "/users/octocat/events")
849            .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
850            .with_status(200)
851            .with_body(format!("[{page2}]"))
852            .create();
853        let m3 = server
854            .mock("GET", "/users/octocat/events")
855            .match_query(mockito::Matcher::UrlEncoded("page".into(), "3".into()))
856            .with_status(200)
857            .with_body(format!("[{page3}]"))
858            .create();
859        let client = Client::new(&server.url(), "tok").unwrap();
860        let events = client.user_events("octocat").unwrap();
861        assert_eq!(events.len(), 250);
862        m1.assert();
863        m2.assert();
864        m3.assert();
865    }
866
867    #[test]
868    fn count_authored_commits_paginates_and_handles_409() {
869        let mut server = mockito::Server::new();
870        let m1 = server
871            .mock("GET", "/repos/o/r/commits")
872            .match_query(mockito::Matcher::UrlEncoded("page".into(), "1".into()))
873            .with_status(200)
874            .with_body(format!("[{}]", vec!["{}"; 100].join(",")))
875            .create();
876        let m2 = server
877            .mock("GET", "/repos/o/r/commits")
878            .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
879            .with_status(200)
880            .with_body("[{},{}]")
881            .create();
882        let client = Client::new(&server.url(), "tok").unwrap();
883        let n = client
884            .count_authored_commits(
885                "o",
886                "r",
887                "octocat",
888                chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(),
889                chrono::NaiveDate::from_ymd_opt(2026, 3, 31).unwrap(),
890            )
891            .unwrap();
892        assert_eq!(n, 102);
893        m1.assert();
894        m2.assert();
895    }
896
897    #[test]
898    fn count_authored_commits_empty_repo_returns_zero() {
899        let mut server = mockito::Server::new();
900        let mock = server
901            .mock("GET", "/repos/o/empty/commits")
902            .match_query(mockito::Matcher::Any)
903            .with_status(409)
904            .with_body(r#"{"message":"Git Repository is empty."}"#)
905            .create();
906        let client = Client::new(&server.url(), "tok").unwrap();
907        let n = client
908            .count_authored_commits(
909                "o",
910                "empty",
911                "x",
912                chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(),
913                chrono::NaiveDate::from_ymd_opt(2026, 3, 31).unwrap(),
914            )
915            .unwrap();
916        assert_eq!(n, 0);
917        mock.assert();
918    }
919
920    #[test]
921    fn validate_token_distinguishes_invalid_from_error() {
922        let mut server = mockito::Server::new();
923        // Valid token.
924        let ok = server
925            .mock("GET", "/user")
926            .match_header("authorization", "Bearer good")
927            .with_status(200)
928            .with_body(r#"{"id": 1, "login": "octocat"}"#)
929            .create();
930        assert!(validate_token(&server.url(), "good").unwrap());
931        ok.assert();
932        // Wrong token → 401.
933        let bad = server
934            .mock("GET", "/user")
935            .match_header("authorization", "Bearer bad")
936            .with_status(401)
937            .with_body(r#"{"message": "Bad credentials"}"#)
938            .create();
939        assert!(!validate_token(&server.url(), "bad").unwrap());
940        bad.assert();
941    }
942
943    #[test]
944    fn repository_slug_prefers_full_name() {
945        let repo = Repository {
946            id: 1,
947            full_name: Some("o/r".into()),
948            name: Some("ignored".into()),
949        };
950        assert_eq!(repo.slug(), Some("o/r"));
951        // Event payloads only ship `name`.
952        let evt_repo = Repository {
953            id: 1,
954            full_name: None,
955            name: Some("o/r".into()),
956        };
957        assert_eq!(evt_repo.slug(), Some("o/r"));
958    }
959}