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/// Default production base URL for the GitHub REST API.
36pub const DEFAULT_BASE_URL: &str = "https://api.github.com";
37
38/// A GitHub user as returned by `/users/{username}`. Only the
39/// fields downstream tools currently consume.
40#[derive(Debug, Clone, Deserialize, Serialize)]
41pub struct User {
42    pub id: u64,
43    pub login: String,
44    /// Public display name (`null` when the user hasn't set one).
45    #[serde(default)]
46    pub name: Option<String>,
47    /// Public email (`null` when the user keeps it private).
48    #[serde(default)]
49    pub email: Option<String>,
50}
51
52/// A repository as returned by event payloads and PR responses.
53#[derive(Debug, Clone, Deserialize, Serialize)]
54pub struct Repository {
55    pub id: u64,
56    /// `owner/name`, e.g. `slopfest/sandogasa`.
57    #[serde(default)]
58    pub full_name: Option<String>,
59    /// For event payloads where `repo.name` already carries the
60    /// `owner/name` form; preserved verbatim.
61    #[serde(default)]
62    pub name: Option<String>,
63    /// Web URL (when present on PR results).
64    #[serde(default)]
65    pub html_url: 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)]
82pub struct PullRequest {
83    pub number: u64,
84    pub title: String,
85    pub state: String,
86    /// Set when the PR has been merged. Some search responses
87    /// omit this field for open PRs.
88    #[serde(default)]
89    pub pull_request: Option<PullRequestRef>,
90    pub html_url: String,
91    /// The repo this PR lives in — derived from `html_url` since
92    /// the search response doesn't include a structured `repo`
93    /// object.
94    #[serde(default)]
95    pub repository_url: Option<String>,
96}
97
98impl PullRequest {
99    /// Extract the `owner/name` slug from this PR's HTML URL or
100    /// `repository_url`.
101    pub fn repo_slug(&self) -> Option<String> {
102        // html_url shape: `https://github.com/{owner}/{repo}/pull/N`
103        if let Some(rest) = self
104            .html_url
105            .strip_prefix("https://github.com/")
106            .or_else(|| self.html_url.strip_prefix("https://"))
107        {
108            let parts: Vec<&str> = rest.splitn(4, '/').collect();
109            if parts.len() >= 2 {
110                return Some(format!("{}/{}", parts[0], parts[1]));
111            }
112        }
113        // Fallback: repository_url shape is
114        // `https://api.github.com/repos/{owner}/{repo}`.
115        if let Some(repo) = &self.repository_url
116            && let Some(rest) = repo.split("/repos/").nth(1)
117        {
118            return Some(rest.to_string());
119        }
120        None
121    }
122
123    /// Whether this PR has been merged. The Search API surfaces
124    /// merge state via the optional `pull_request.merged_at`
125    /// field; absence means "not merged".
126    pub fn merged_at(&self) -> Option<&str> {
127        self.pull_request
128            .as_ref()
129            .and_then(|p| p.merged_at.as_deref())
130    }
131}
132
133/// Auxiliary block on a search-result issue when it's actually
134/// a pull request. The Search Issues endpoint signals "is PR"
135/// by populating this; merged state lives here too.
136#[derive(Debug, Clone, Deserialize, Serialize)]
137pub struct PullRequestRef {
138    #[serde(default)]
139    pub merged_at: Option<String>,
140}
141
142/// Wire response wrapper for the Search Issues endpoint.
143#[derive(Debug, Deserialize)]
144struct SearchIssuesResponse {
145    total_count: u64,
146    items: Vec<PullRequest>,
147}
148
149/// One entry from `/users/{username}/events`. Fields are
150/// sparse; we keep just enough to identify the event type,
151/// associated repo, and the actor.
152#[derive(Debug, Clone, Deserialize, Serialize)]
153pub struct Event {
154    pub id: String,
155    /// `"PushEvent"`, `"PullRequestEvent"`,
156    /// `"PullRequestReviewCommentEvent"`, etc.
157    #[serde(rename = "type")]
158    pub event_type: String,
159    pub repo: Repository,
160    pub created_at: String,
161    /// Free-form payload — varies per event type.
162    #[serde(default)]
163    pub payload: serde_json::Value,
164}
165
166/// One entry from `/repos/{owner}/{repo}/git/refs/tags`. The
167/// underlying `object` distinguishes lightweight tags (point
168/// directly to a commit) from annotated tags (point to a Tag
169/// object that carries tagger info).
170#[derive(Debug, Clone, Deserialize, Serialize)]
171pub struct GitTagRef {
172    /// The fully-qualified ref, e.g. `refs/tags/v0.11.0`.
173    #[serde(rename = "ref")]
174    pub ref_name: String,
175    pub object: GitObject,
176}
177
178impl GitTagRef {
179    /// Strip the `refs/tags/` prefix to get just the tag name.
180    pub fn tag_name(&self) -> &str {
181        self.ref_name
182            .strip_prefix("refs/tags/")
183            .unwrap_or(&self.ref_name)
184    }
185}
186
187/// The thing a Git ref points at. `object_type` is `"commit"`
188/// for lightweight tags and `"tag"` for annotated ones.
189#[derive(Debug, Clone, Deserialize, Serialize)]
190pub struct GitObject {
191    #[serde(rename = "type")]
192    pub object_type: String,
193    pub sha: String,
194}
195
196/// An annotated-tag object from
197/// `/repos/{owner}/{repo}/git/tags/{sha}`. Only annotated tags
198/// carry tagger metadata; lightweight tags don't have an
199/// addressable tag object.
200#[derive(Debug, Clone, Deserialize, Serialize)]
201pub struct AnnotatedTag {
202    pub tag: String,
203    pub tagger: Tagger,
204}
205
206/// `name` + `email` + `date` triple stamped on annotated-tag
207/// creation. `date` is ISO 8601 (e.g. `2026-05-15T17:03:15Z`).
208#[derive(Debug, Clone, Deserialize, Serialize)]
209pub struct Tagger {
210    pub name: String,
211    pub email: String,
212    pub date: String,
213}
214
215impl Event {
216    /// Helper for callers walking events to find touched repos —
217    /// returns the `owner/name` slug if available.
218    pub fn repo_slug(&self) -> Option<&str> {
219        self.repo.slug()
220    }
221}
222
223/// Blocking GitHub REST client.
224pub struct Client {
225    http: reqwest::blocking::Client,
226    base_url: String,
227}
228
229impl Client {
230    /// Build a client for `base_url` (typically
231    /// `https://api.github.com`, or a GHES instance's `/api/v3`
232    /// endpoint) authenticated with the given personal access
233    /// token.
234    pub fn new(base_url: &str, token: &str) -> Result<Self, Box<dyn std::error::Error>> {
235        sandogasa_cli::ensure_secure_url(base_url)?;
236        let http = build_http_client(token)?;
237        Ok(Self {
238            http,
239            base_url: base_url.trim_end_matches('/').to_string(),
240        })
241    }
242
243    /// Resolve a username to its full user object. Returns `None`
244    /// when the API responds with 404 (no such user); other
245    /// errors are returned as `Err`.
246    pub fn user_by_username(
247        &self,
248        username: &str,
249    ) -> Result<Option<User>, Box<dyn std::error::Error>> {
250        let url = format!("{}/users/{}", self.base_url, username);
251        let resp = self.http.get(&url).send()?;
252        if resp.status().as_u16() == 404 {
253            return Ok(None);
254        }
255        Ok(Some(http::blocking_json_ok(
256            resp,
257            &format!("GitHub GET {url}"),
258        )?))
259    }
260
261    /// Run the Search Issues endpoint with the caller-supplied
262    /// query string and return every PR across all result pages.
263    ///
264    /// GitHub caps Search results at 1000 items total; if a
265    /// query exceeds that, the caller needs to narrow it (e.g.
266    /// by splitting the date window).
267    pub fn search_pull_requests(
268        &self,
269        query: &str,
270    ) -> Result<Vec<PullRequest>, Box<dyn std::error::Error>> {
271        let mut out: Vec<PullRequest> = Vec::new();
272        let mut page = 1u32;
273        loop {
274            let page_str = page.to_string();
275            let url = format!("{}/search/issues", self.base_url);
276            let resp = self
277                .http
278                .get(&url)
279                .query(&[("q", query), ("per_page", "100"), ("page", &page_str)])
280                .send()?;
281            let batch: SearchIssuesResponse = http::blocking_json_ok(resp, "GitHub search")?;
282            let n = batch.items.len();
283            out.extend(batch.items);
284            if n < 100 || out.len() as u64 >= batch.total_count {
285                break;
286            }
287            page += 1;
288        }
289        Ok(out)
290    }
291
292    /// Paginate through the user-events endpoint up to GitHub's
293    /// 300-event cap. Returns the most recent events first.
294    pub fn user_events(&self, username: &str) -> Result<Vec<Event>, Box<dyn std::error::Error>> {
295        let mut out: Vec<Event> = Vec::new();
296        let mut page = 1u32;
297        loop {
298            let url = format!("{}/users/{}/events", self.base_url, username);
299            let page_str = page.to_string();
300            let resp = self
301                .http
302                .get(&url)
303                .query(&[("per_page", "100"), ("page", &page_str)])
304                .send()?;
305            let batch: Vec<Event> = http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
306            let n = batch.len();
307            out.extend(batch);
308            // GitHub serves at most 300 events / 3 pages of 100.
309            if n < 100 || page >= 3 {
310                break;
311            }
312            page += 1;
313        }
314        Ok(out)
315    }
316
317    /// Count commits in `owner/repo` authored by `author` within
318    /// `[since, until]` (inclusive). Used as a cross-check
319    /// against push-event counts — see the GitLab equivalent
320    /// for the rationale.
321    ///
322    /// 404 and 409 responses are treated as "0 commits" rather
323    /// than errors. 404 means the repo was deleted or made
324    /// private between the events scan and this call; 409 means
325    /// the repo exists but is empty. Either way, a single
326    /// missing repo shouldn't abort the surrounding report.
327    /// The trade-off: real auth failures targeting a single
328    /// repo would also be hidden, but GitHub returns 401/403 for
329    /// those, not 404/409.
330    pub fn count_authored_commits(
331        &self,
332        owner: &str,
333        repo: &str,
334        author: &str,
335        since: chrono::NaiveDate,
336        until: chrono::NaiveDate,
337    ) -> Result<u64, Box<dyn std::error::Error>> {
338        let url = format!("{}/repos/{}/{}/commits", self.base_url, owner, repo);
339        let since_str = format!("{since}T00:00:00Z");
340        let until_str = format!("{until}T23:59:59Z");
341        let mut total: u64 = 0;
342        let mut page = 1u32;
343        loop {
344            let page_str = page.to_string();
345            let query: Vec<(&str, &str)> = vec![
346                ("author", author),
347                ("since", &since_str),
348                ("until", &until_str),
349                ("per_page", "100"),
350                ("page", &page_str),
351            ];
352            let resp = self.http.get(&url).query(&query).send()?;
353            // GitHub returns 409 Conflict for empty repositories
354            // and 404 if the repo was deleted. Treat both as
355            // "no commits" rather than hard errors so a single
356            // gone repo doesn't abort the whole report.
357            if resp.status().as_u16() == 404 || resp.status().as_u16() == 409 {
358                break;
359            }
360            let batch: Vec<serde_json::Value> =
361                http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
362            let n = batch.len() as u64;
363            total += n;
364            if n < 100 {
365                break;
366            }
367            page += 1;
368        }
369        Ok(total)
370    }
371
372    /// List all tag refs for `owner/repo`. Returns an empty list
373    /// on 404 (gone repo) and 409 (empty repo) so callers can
374    /// iterate over many repos without per-repo error handling.
375    pub fn list_tag_refs(
376        &self,
377        owner: &str,
378        repo: &str,
379    ) -> Result<Vec<GitTagRef>, Box<dyn std::error::Error>> {
380        let url = format!("{}/repos/{}/{}/git/refs/tags", self.base_url, owner, repo);
381        let resp = self.http.get(&url).send()?;
382        // 404 = repo gone or no tags ref namespace; 409 = empty repo.
383        if resp.status().as_u16() == 404 || resp.status().as_u16() == 409 {
384            return Ok(Vec::new());
385        }
386        let resp = http::blocking_ok(resp, &format!("GitHub GET {url}"))?;
387        // GitHub returns an object (not an array) when there's
388        // exactly one match. The standard `/git/refs/tags` shape
389        // returns an array for the namespace listing; we only see
390        // the object form when someone queries a single ref. Be
391        // defensive and accept both.
392        let body: serde_json::Value = resp.json()?;
393        if body.is_array() {
394            Ok(serde_json::from_value(body)?)
395        } else {
396            Ok(vec![serde_json::from_value(body)?])
397        }
398    }
399
400    /// Fetch one annotated-tag object by SHA. Use only when the
401    /// matching `GitTagRef.object.object_type == "tag"` —
402    /// lightweight tags (where `object_type == "commit"`) have no
403    /// addressable tag object and this endpoint will 404.
404    pub fn get_annotated_tag(
405        &self,
406        owner: &str,
407        repo: &str,
408        sha: &str,
409    ) -> Result<AnnotatedTag, Box<dyn std::error::Error>> {
410        let url = format!(
411            "{}/repos/{}/{}/git/tags/{}",
412            self.base_url, owner, repo, sha
413        );
414        let resp = self.http.get(&url).send()?;
415        Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
416    }
417}
418
419/// Check whether `token` works against `base_url` by hitting
420/// `/user`. Returns `Ok(true)` for valid tokens, `Ok(false)`
421/// for 401s, and `Err` for other transport / server errors so
422/// callers can distinguish "tried and was rejected" from
423/// "couldn't reach the server".
424pub fn validate_token(base_url: &str, token: &str) -> Result<bool, Box<dyn std::error::Error>> {
425    sandogasa_cli::ensure_secure_url(base_url)?;
426    let http = build_http_client(token)?;
427    let url = format!("{}/user", base_url.trim_end_matches('/'));
428    let resp = http.get(&url).send()?;
429    let status = resp.status();
430    if status.is_success() {
431        return Ok(true);
432    }
433    if status.as_u16() == 401 {
434        return Ok(false);
435    }
436    let text = resp.text().unwrap_or_default();
437    Err(format!("GitHub /user check failed: {status}: {text}").into())
438}
439
440/// Build a reqwest client preconfigured for the GitHub API: the
441/// Bearer token, the recommended JSON Accept header, a User-Agent
442/// (GitHub requires one), and our standard request timeout.
443fn build_http_client(token: &str) -> Result<reqwest::blocking::Client, Box<dyn std::error::Error>> {
444    let mut headers = HeaderMap::new();
445    headers.insert(
446        AUTHORIZATION,
447        HeaderValue::from_str(&format!("Bearer {token}"))?,
448    );
449    headers.insert(
450        ACCEPT,
451        HeaderValue::from_static("application/vnd.github+json"),
452    );
453    headers.insert(
454        HeaderName::from_static("x-github-api-version"),
455        HeaderValue::from_static("2022-11-28"),
456    );
457    Ok(http::blocking_builder(concat!(
458        env!("CARGO_PKG_NAME"),
459        "/",
460        env!("CARGO_PKG_VERSION")
461    ))
462    .default_headers(headers)
463    .build()?)
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469
470    #[test]
471    fn new_rejects_plaintext_remote() {
472        // A token must not be sent to a plaintext http non-loopback URL.
473        assert!(Client::new("http://api.example.com", "tok").is_err());
474    }
475
476    #[test]
477    fn user_by_username_returns_user() {
478        let mut server = mockito::Server::new();
479        let mock = server
480            .mock("GET", "/users/octocat")
481            .match_header("authorization", "Bearer tok")
482            .with_status(200)
483            .with_body(r#"{"id": 1, "login": "octocat"}"#)
484            .create();
485        let client = Client::new(&server.url(), "tok").unwrap();
486        let user = client.user_by_username("octocat").unwrap().unwrap();
487        assert_eq!(user.id, 1);
488        assert_eq!(user.login, "octocat");
489        mock.assert();
490    }
491
492    #[test]
493    fn user_by_username_404_is_none() {
494        let mut server = mockito::Server::new();
495        let mock = server
496            .mock("GET", "/users/ghost")
497            .with_status(404)
498            .with_body(r#"{"message": "Not Found"}"#)
499            .create();
500        let client = Client::new(&server.url(), "tok").unwrap();
501        assert!(client.user_by_username("ghost").unwrap().is_none());
502        mock.assert();
503    }
504
505    #[test]
506    fn search_pull_requests_paginates() {
507        let mut server = mockito::Server::new();
508        // First page: full 100 items, total_count says 105.
509        let items_page1 = (1..=100)
510            .map(|i| {
511                format!(
512                    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"}}}}"#
513                )
514            })
515            .collect::<Vec<_>>()
516            .join(",");
517        let mock_p1 = server
518            .mock("GET", "/search/issues")
519            .match_query(mockito::Matcher::AllOf(vec![
520                mockito::Matcher::UrlEncoded("page".into(), "1".into()),
521                mockito::Matcher::UrlEncoded("per_page".into(), "100".into()),
522            ]))
523            .with_status(200)
524            .with_body(format!(
525                r#"{{"total_count":105,"incomplete_results":false,"items":[{items_page1}]}}"#
526            ))
527            .create();
528        let mock_p2 = server
529            .mock("GET", "/search/issues")
530            .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
531            .with_status(200)
532            .with_body(
533                r#"{"total_count":105,"incomplete_results":false,"items":[
534                    {"number":101,"title":"x","state":"open","html_url":"https://github.com/o/r/pull/101"},
535                    {"number":102,"title":"y","state":"open","html_url":"https://github.com/o/r/pull/102"},
536                    {"number":103,"title":"z","state":"open","html_url":"https://github.com/o/r/pull/103"},
537                    {"number":104,"title":"w","state":"open","html_url":"https://github.com/o/r/pull/104"},
538                    {"number":105,"title":"v","state":"open","html_url":"https://github.com/o/r/pull/105"}
539                ]}"#,
540            )
541            .create();
542        let client = Client::new(&server.url(), "tok").unwrap();
543        let prs = client
544            .search_pull_requests("type:pr author:octocat")
545            .unwrap();
546        assert_eq!(prs.len(), 105);
547        mock_p1.assert();
548        mock_p2.assert();
549    }
550
551    #[test]
552    fn pull_request_repo_slug_from_html_url() {
553        let pr = PullRequest {
554            number: 42,
555            title: "x".into(),
556            state: "open".into(),
557            pull_request: None,
558            html_url: "https://github.com/slopfest/sandogasa/pull/42".into(),
559            repository_url: None,
560        };
561        assert_eq!(pr.repo_slug().as_deref(), Some("slopfest/sandogasa"));
562    }
563
564    #[test]
565    fn pull_request_repo_slug_from_repository_url() {
566        let pr = PullRequest {
567            number: 42,
568            title: "x".into(),
569            state: "open".into(),
570            pull_request: None,
571            html_url: "https://github.com/o/r/issues/42".into(),
572            repository_url: Some("https://api.github.com/repos/slopfest/sandogasa".into()),
573        };
574        // html_url is consulted first, but works as a fallback path.
575        let pr2 = PullRequest {
576            html_url: "garbage".into(),
577            ..pr
578        };
579        assert_eq!(pr2.repo_slug().as_deref(), Some("slopfest/sandogasa"));
580    }
581
582    #[test]
583    fn pull_request_merged_at_via_helper() {
584        let pr: PullRequest = serde_json::from_str(
585            r#"{"number":1,"title":"t","state":"closed",
586                "html_url":"https://github.com/o/r/pull/1",
587                "pull_request":{"merged_at":"2026-02-01T10:00:00Z"}}"#,
588        )
589        .unwrap();
590        assert_eq!(pr.merged_at(), Some("2026-02-01T10:00:00Z"));
591    }
592
593    #[test]
594    fn user_events_pagination_stops_at_300() {
595        let mut server = mockito::Server::new();
596        // GitHub serves at most 3 pages of events. Page 1 and 2
597        // return full pages, page 3 returns a final 50 to test the
598        // short-page break path.
599        let make_event = |i: u64| {
600            format!(
601                r#"{{"id":"{i}","type":"PushEvent","repo":{{"id":1,"name":"o/r"}},"created_at":"2026-02-15T10:00:00Z"}}"#
602            )
603        };
604        let page1: String = (1..=100).map(make_event).collect::<Vec<_>>().join(",");
605        let page2: String = (101..=200).map(make_event).collect::<Vec<_>>().join(",");
606        let page3: String = (201..=250).map(make_event).collect::<Vec<_>>().join(",");
607        let m1 = server
608            .mock("GET", "/users/octocat/events")
609            .match_query(mockito::Matcher::UrlEncoded("page".into(), "1".into()))
610            .with_status(200)
611            .with_body(format!("[{page1}]"))
612            .create();
613        let m2 = server
614            .mock("GET", "/users/octocat/events")
615            .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
616            .with_status(200)
617            .with_body(format!("[{page2}]"))
618            .create();
619        let m3 = server
620            .mock("GET", "/users/octocat/events")
621            .match_query(mockito::Matcher::UrlEncoded("page".into(), "3".into()))
622            .with_status(200)
623            .with_body(format!("[{page3}]"))
624            .create();
625        let client = Client::new(&server.url(), "tok").unwrap();
626        let events = client.user_events("octocat").unwrap();
627        assert_eq!(events.len(), 250);
628        m1.assert();
629        m2.assert();
630        m3.assert();
631    }
632
633    #[test]
634    fn count_authored_commits_paginates_and_handles_409() {
635        let mut server = mockito::Server::new();
636        let m1 = server
637            .mock("GET", "/repos/o/r/commits")
638            .match_query(mockito::Matcher::UrlEncoded("page".into(), "1".into()))
639            .with_status(200)
640            .with_body(format!("[{}]", vec!["{}"; 100].join(",")))
641            .create();
642        let m2 = server
643            .mock("GET", "/repos/o/r/commits")
644            .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
645            .with_status(200)
646            .with_body("[{},{}]")
647            .create();
648        let client = Client::new(&server.url(), "tok").unwrap();
649        let n = client
650            .count_authored_commits(
651                "o",
652                "r",
653                "octocat",
654                chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(),
655                chrono::NaiveDate::from_ymd_opt(2026, 3, 31).unwrap(),
656            )
657            .unwrap();
658        assert_eq!(n, 102);
659        m1.assert();
660        m2.assert();
661    }
662
663    #[test]
664    fn count_authored_commits_empty_repo_returns_zero() {
665        let mut server = mockito::Server::new();
666        let mock = server
667            .mock("GET", "/repos/o/empty/commits")
668            .match_query(mockito::Matcher::Any)
669            .with_status(409)
670            .with_body(r#"{"message":"Git Repository is empty."}"#)
671            .create();
672        let client = Client::new(&server.url(), "tok").unwrap();
673        let n = client
674            .count_authored_commits(
675                "o",
676                "empty",
677                "x",
678                chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(),
679                chrono::NaiveDate::from_ymd_opt(2026, 3, 31).unwrap(),
680            )
681            .unwrap();
682        assert_eq!(n, 0);
683        mock.assert();
684    }
685
686    #[test]
687    fn validate_token_distinguishes_invalid_from_error() {
688        let mut server = mockito::Server::new();
689        // Valid token.
690        let ok = server
691            .mock("GET", "/user")
692            .match_header("authorization", "Bearer good")
693            .with_status(200)
694            .with_body(r#"{"id": 1, "login": "octocat"}"#)
695            .create();
696        assert!(validate_token(&server.url(), "good").unwrap());
697        ok.assert();
698        // Wrong token → 401.
699        let bad = server
700            .mock("GET", "/user")
701            .match_header("authorization", "Bearer bad")
702            .with_status(401)
703            .with_body(r#"{"message": "Bad credentials"}"#)
704            .create();
705        assert!(!validate_token(&server.url(), "bad").unwrap());
706        bad.assert();
707    }
708
709    #[test]
710    fn repository_slug_prefers_full_name() {
711        let repo = Repository {
712            id: 1,
713            full_name: Some("o/r".into()),
714            name: Some("ignored".into()),
715            html_url: None,
716        };
717        assert_eq!(repo.slug(), Some("o/r"));
718        // Event payloads only ship `name`.
719        let evt_repo = Repository {
720            id: 1,
721            full_name: None,
722            name: Some("o/r".into()),
723            html_url: None,
724        };
725        assert_eq!(evt_repo.slug(), Some("o/r"));
726    }
727}