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