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