1use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderName, HeaderValue};
32use sandogasa_cli::http;
33use serde::{Deserialize, Serialize};
34
35#[derive(Debug, Clone, Deserialize, Serialize)]
38#[non_exhaustive]
39pub struct User {
40 pub id: u64,
41 pub login: String,
42 #[serde(default)]
44 pub name: Option<String>,
45 #[serde(default)]
47 pub email: Option<String>,
48}
49
50#[derive(Debug, Clone, Deserialize, Serialize)]
52#[non_exhaustive]
53pub struct Repository {
54 pub id: u64,
55 #[serde(default)]
57 pub full_name: Option<String>,
58 #[serde(default)]
61 pub name: Option<String>,
62}
63
64impl Repository {
65 pub fn slug(&self) -> Option<&str> {
68 self.full_name.as_deref().or(self.name.as_deref())
69 }
70}
71
72#[derive(Debug, Clone, Deserialize, Serialize)]
78#[non_exhaustive]
79pub struct PullRequest {
80 pub number: u64,
81 pub title: String,
82 pub state: String,
83 #[serde(default)]
86 pub pull_request: Option<PullRequestRef>,
87 pub html_url: String,
88 #[serde(default)]
92 pub repository_url: Option<String>,
93}
94
95impl PullRequest {
96 pub fn repo_slug(&self) -> Option<String> {
99 if let Some(rest) = self
101 .html_url
102 .strip_prefix("https://github.com/")
103 .or_else(|| self.html_url.strip_prefix("https://"))
104 {
105 let parts: Vec<&str> = rest.splitn(4, '/').collect();
106 if parts.len() >= 2 {
107 return Some(format!("{}/{}", parts[0], parts[1]));
108 }
109 }
110 if let Some(repo) = &self.repository_url
113 && let Some(rest) = repo.split("/repos/").nth(1)
114 {
115 return Some(rest.to_string());
116 }
117 None
118 }
119
120 pub fn merged_at(&self) -> Option<&str> {
124 self.pull_request
125 .as_ref()
126 .and_then(|p| p.merged_at.as_deref())
127 }
128}
129
130#[derive(Debug, Clone, Deserialize, Serialize)]
134#[non_exhaustive]
135pub struct PullRequestRef {
136 #[serde(default)]
137 pub merged_at: Option<String>,
138}
139
140#[derive(Debug, Clone, Deserialize)]
143#[non_exhaustive]
144pub struct PullRequestDetail {
145 pub number: u64,
146 pub state: String,
147 #[serde(default)]
148 pub merged: bool,
149 pub head: GitRef,
150 pub base: GitRef,
151 #[serde(default)]
153 pub created_at: Option<String>,
154 #[serde(default)]
156 pub user: Option<Login>,
157}
158
159#[derive(Debug, Clone, Deserialize)]
161#[non_exhaustive]
162pub struct Login {
163 pub login: String,
164}
165
166#[derive(Debug, Clone, Deserialize)]
169#[non_exhaustive]
170pub struct RepoCommit {
171 pub sha: String,
172 pub commit: CommitBody,
173}
174
175#[derive(Debug, Clone, Deserialize)]
177#[non_exhaustive]
178pub struct CommitBody {
179 #[serde(default)]
180 pub message: String,
181 #[serde(default)]
182 pub author: Option<CommitAuthor>,
183}
184
185#[derive(Debug, Clone, Deserialize)]
187#[non_exhaustive]
188pub struct CommitAuthor {
189 #[serde(default)]
190 pub name: String,
191 #[serde(default)]
192 pub email: String,
193}
194
195impl RepoCommit {
196 pub fn title(&self) -> &str {
198 self.commit.message.lines().next().unwrap_or("")
199 }
200}
201
202#[derive(Debug, Clone, Deserialize)]
204#[non_exhaustive]
205pub struct GitRef {
206 #[serde(rename = "ref")]
207 pub ref_name: String,
208 pub sha: String,
209}
210
211#[derive(Debug, Deserialize)]
214struct CompareResult {
215 #[serde(default)]
216 ahead_by: u64,
217}
218
219#[derive(Debug, Deserialize)]
221struct SearchIssuesResponse {
222 total_count: u64,
223 items: Vec<PullRequest>,
224}
225
226#[derive(Debug, Clone, Deserialize, Serialize)]
230#[non_exhaustive]
231pub struct Event {
232 pub id: String,
233 #[serde(rename = "type")]
236 pub event_type: String,
237 pub repo: Repository,
238 pub created_at: String,
239 #[serde(default)]
241 pub payload: serde_json::Value,
242}
243
244#[derive(Debug, Clone, Deserialize, Serialize)]
249#[non_exhaustive]
250pub struct GitTagRef {
251 #[serde(rename = "ref")]
253 pub ref_name: String,
254 pub object: GitObject,
255}
256
257impl GitTagRef {
258 pub fn tag_name(&self) -> &str {
260 self.ref_name
261 .strip_prefix("refs/tags/")
262 .unwrap_or(&self.ref_name)
263 }
264}
265
266#[derive(Debug, Clone, Deserialize, Serialize)]
269#[non_exhaustive]
270pub struct GitObject {
271 #[serde(rename = "type")]
272 pub object_type: String,
273 pub sha: String,
274}
275
276#[derive(Debug, Clone, Deserialize, Serialize)]
281#[non_exhaustive]
282pub struct AnnotatedTag {
283 pub tag: String,
284 pub tagger: Tagger,
285}
286
287#[derive(Debug, Clone, Deserialize, Serialize)]
290#[non_exhaustive]
291pub struct Tagger {
292 pub name: String,
293 pub email: String,
294 pub date: String,
295}
296
297impl Event {
298 pub fn repo_slug(&self) -> Option<&str> {
301 self.repo.slug()
302 }
303}
304
305pub struct Client {
307 http: reqwest::blocking::Client,
308 base_url: String,
309}
310
311impl Client {
312 pub fn new(base_url: &str, token: &str) -> Result<Self, Box<dyn std::error::Error>> {
317 sandogasa_cli::ensure_secure_url(base_url)?;
318 let http = build_http_client(token)?;
319 Ok(Self {
320 http,
321 base_url: base_url.trim_end_matches('/').to_string(),
322 })
323 }
324
325 pub fn user_by_username(
329 &self,
330 username: &str,
331 ) -> Result<Option<User>, Box<dyn std::error::Error>> {
332 let url = format!("{}/users/{}", self.base_url, username);
333 let resp = self.http.get(&url).send()?;
334 if resp.status().as_u16() == 404 {
335 return Ok(None);
336 }
337 Ok(Some(http::blocking_json_ok(
338 resp,
339 &format!("GitHub GET {url}"),
340 )?))
341 }
342
343 pub fn search_pull_requests(
350 &self,
351 query: &str,
352 ) -> Result<Vec<PullRequest>, Box<dyn std::error::Error>> {
353 let mut out: Vec<PullRequest> = Vec::new();
354 let mut page = 1u32;
355 loop {
356 let page_str = page.to_string();
357 let url = format!("{}/search/issues", self.base_url);
358 let resp = self
359 .http
360 .get(&url)
361 .query(&[("q", query), ("per_page", "100"), ("page", &page_str)])
362 .send()?;
363 let batch: SearchIssuesResponse = http::blocking_json_ok(resp, "GitHub search")?;
364 let n = batch.items.len();
365 out.extend(batch.items);
366 if n < 100 || out.len() as u64 >= batch.total_count {
367 break;
368 }
369 page += 1;
370 }
371 Ok(out)
372 }
373
374 pub fn user_events(&self, username: &str) -> Result<Vec<Event>, Box<dyn std::error::Error>> {
377 let mut out: Vec<Event> = Vec::new();
378 let mut page = 1u32;
379 loop {
380 let url = format!("{}/users/{}/events", self.base_url, username);
381 let page_str = page.to_string();
382 let resp = self
383 .http
384 .get(&url)
385 .query(&[("per_page", "100"), ("page", &page_str)])
386 .send()?;
387 let batch: Vec<Event> = http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
388 let n = batch.len();
389 out.extend(batch);
390 if n < 100 || page >= 3 {
392 break;
393 }
394 page += 1;
395 }
396 Ok(out)
397 }
398
399 pub fn count_authored_commits(
413 &self,
414 owner: &str,
415 repo: &str,
416 author: &str,
417 since: chrono::NaiveDate,
418 until: chrono::NaiveDate,
419 ) -> Result<u64, Box<dyn std::error::Error>> {
420 let url = format!("{}/repos/{}/{}/commits", self.base_url, owner, repo);
421 let since_str = format!("{since}T00:00:00Z");
422 let until_str = format!("{until}T23:59:59Z");
423 let mut total: u64 = 0;
424 let mut page = 1u32;
425 loop {
426 let page_str = page.to_string();
427 let query: Vec<(&str, &str)> = vec![
428 ("author", author),
429 ("since", &since_str),
430 ("until", &until_str),
431 ("per_page", "100"),
432 ("page", &page_str),
433 ];
434 let resp = self.http.get(&url).query(&query).send()?;
435 if resp.status().as_u16() == 404 || resp.status().as_u16() == 409 {
440 break;
441 }
442 let batch: Vec<serde_json::Value> =
443 http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
444 let n = batch.len() as u64;
445 total += n;
446 if n < 100 {
447 break;
448 }
449 page += 1;
450 }
451 Ok(total)
452 }
453
454 pub fn list_tag_refs(
458 &self,
459 owner: &str,
460 repo: &str,
461 ) -> Result<Vec<GitTagRef>, Box<dyn std::error::Error>> {
462 let url = format!("{}/repos/{}/{}/git/refs/tags", self.base_url, owner, repo);
463 let resp = self.http.get(&url).send()?;
464 if resp.status().as_u16() == 404 || resp.status().as_u16() == 409 {
466 return Ok(Vec::new());
467 }
468 let resp = http::blocking_ok(resp, &format!("GitHub GET {url}"))?;
469 let body: serde_json::Value = resp.json()?;
475 if body.is_array() {
476 Ok(serde_json::from_value(body)?)
477 } else {
478 Ok(vec![serde_json::from_value(body)?])
479 }
480 }
481
482 pub fn get_annotated_tag(
487 &self,
488 owner: &str,
489 repo: &str,
490 sha: &str,
491 ) -> Result<AnnotatedTag, Box<dyn std::error::Error>> {
492 let url = format!(
493 "{}/repos/{}/{}/git/tags/{}",
494 self.base_url, owner, repo, sha
495 );
496 let resp = self.http.get(&url).send()?;
497 Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
498 }
499
500 pub fn pull_request(
504 &self,
505 owner: &str,
506 repo: &str,
507 number: u64,
508 ) -> Result<PullRequestDetail, Box<dyn std::error::Error>> {
509 let url = format!("{}/repos/{owner}/{repo}/pulls/{number}", self.base_url);
510 let resp = self.http.get(&url).send()?;
511 Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
512 }
513
514 pub fn pull_request_commits(
517 &self,
518 owner: &str,
519 repo: &str,
520 number: u64,
521 ) -> Result<Vec<RepoCommit>, Box<dyn std::error::Error>> {
522 let url = format!(
523 "{}/repos/{owner}/{repo}/pulls/{number}/commits",
524 self.base_url
525 );
526 let resp = self.http.get(&url).query(&[("per_page", "100")]).send()?;
527 Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
528 }
529
530 pub fn branch_commits_by(
535 &self,
536 owner: &str,
537 repo: &str,
538 branch: &str,
539 author: &str,
540 since: &str,
541 ) -> Result<Vec<RepoCommit>, Box<dyn std::error::Error>> {
542 let url = format!("{}/repos/{owner}/{repo}/commits", self.base_url);
543 let resp = self
544 .http
545 .get(&url)
546 .query(&[
547 ("sha", branch),
548 ("author", author),
549 ("since", since),
550 ("per_page", "100"),
551 ])
552 .send()?;
553 Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
554 }
555
556 pub fn commit_contained(
560 &self,
561 owner: &str,
562 repo: &str,
563 branch: &str,
564 sha: &str,
565 ) -> Result<bool, Box<dyn std::error::Error>> {
566 let url = format!(
567 "{}/repos/{owner}/{repo}/compare/{branch}...{sha}",
568 self.base_url
569 );
570 let resp = self.http.get(&url).send()?;
571 let cmp: CompareResult =
572 http::blocking_json_ok(resp, &format!("GitHub compare {branch}...{sha}"))?;
573 Ok(cmp.ahead_by == 0)
574 }
575}
576
577pub fn validate_token(base_url: &str, token: &str) -> Result<bool, Box<dyn std::error::Error>> {
583 sandogasa_cli::ensure_secure_url(base_url)?;
584 let http = build_http_client(token)?;
585 let url = format!("{}/user", base_url.trim_end_matches('/'));
586 let resp = http.get(&url).send()?;
587 let status = resp.status();
588 if status.is_success() {
589 return Ok(true);
590 }
591 if status.as_u16() == 401 {
592 return Ok(false);
593 }
594 let text = resp.text().unwrap_or_default();
595 Err(format!("GitHub /user check failed: {status}: {text}").into())
596}
597
598fn build_http_client(token: &str) -> Result<reqwest::blocking::Client, Box<dyn std::error::Error>> {
602 let mut headers = HeaderMap::new();
603 headers.insert(
604 AUTHORIZATION,
605 HeaderValue::from_str(&format!("Bearer {token}"))?,
606 );
607 headers.insert(
608 ACCEPT,
609 HeaderValue::from_static("application/vnd.github+json"),
610 );
611 headers.insert(
612 HeaderName::from_static("x-github-api-version"),
613 HeaderValue::from_static("2022-11-28"),
614 );
615 Ok(http::blocking_builder(concat!(
616 env!("CARGO_PKG_NAME"),
617 "/",
618 env!("CARGO_PKG_VERSION")
619 ))
620 .default_headers(headers)
621 .build()?)
622}
623
624#[cfg(test)]
625mod tests {
626 use super::*;
627
628 #[test]
629 fn pull_request_reads_head_and_base() {
630 let mut server = mockito::Server::new();
631 let mock = server
632 .mock("GET", "/repos/o/r/pulls/92")
633 .with_status(200)
634 .with_body(
635 r#"{"number": 92, "state": "closed", "merged": false,
636 "head": {"ref": "fix", "sha": "8b8aa8b"},
637 "base": {"ref": "main", "sha": "0000000"}}"#,
638 )
639 .create();
640 let client = Client::new(&server.url(), "tok").unwrap();
641 let pr = client.pull_request("o", "r", 92).unwrap();
642 mock.assert();
643 assert_eq!(pr.head.sha, "8b8aa8b");
644 assert_eq!(pr.base.ref_name, "main");
645 assert!(!pr.merged);
646 }
647
648 #[test]
649 fn branch_commits_by_filters_by_author_and_since() {
650 let mut server = mockito::Server::new();
651 let mock = server
652 .mock("GET", "/repos/o/r/commits")
653 .match_query(mockito::Matcher::AllOf(vec![
654 mockito::Matcher::UrlEncoded("sha".into(), "main".into()),
655 mockito::Matcher::UrlEncoded("author".into(), "michel-slm".into()),
656 mockito::Matcher::UrlEncoded("since".into(), "2026-03-04T00:00:00Z".into()),
657 ]))
658 .with_status(200)
659 .with_body(
660 r#"[{"sha": "abc", "commit": {"message": "Ignore it\n\nbody",
661 "author": {"name": "Michel Lind", "email": "m@example.org"}}}]"#,
662 )
663 .create();
664 let client = Client::new(&server.url(), "tok").unwrap();
665 let commits = client
666 .branch_commits_by("o", "r", "main", "michel-slm", "2026-03-04T00:00:00Z")
667 .unwrap();
668 mock.assert();
669 assert_eq!(commits[0].title(), "Ignore it");
670 assert_eq!(
671 commits[0].commit.author.as_ref().unwrap().name,
672 "Michel Lind"
673 );
674 }
675
676 #[test]
677 fn commit_contained_reads_ahead_by() {
678 let mut server = mockito::Server::new();
681 let mock = server
682 .mock("GET", "/repos/o/r/compare/main...8b8aa8b")
683 .with_status(200)
684 .with_body(r#"{"status": "behind", "ahead_by": 0, "behind_by": 4}"#)
685 .create();
686 let client = Client::new(&server.url(), "tok").unwrap();
687 assert!(
688 client
689 .commit_contained("o", "r", "main", "8b8aa8b")
690 .unwrap()
691 );
692 mock.assert();
693
694 let mut server = mockito::Server::new();
695 server
696 .mock("GET", "/repos/o/r/compare/main...other")
697 .with_status(200)
698 .with_body(r#"{"status": "diverged", "ahead_by": 2, "behind_by": 4}"#)
699 .create();
700 let client = Client::new(&server.url(), "tok").unwrap();
701 assert!(!client.commit_contained("o", "r", "main", "other").unwrap());
702 }
703
704 #[test]
705 fn new_rejects_plaintext_remote() {
706 assert!(Client::new("http://api.example.com", "tok").is_err());
708 }
709
710 #[test]
711 fn user_by_username_returns_user() {
712 let mut server = mockito::Server::new();
713 let mock = server
714 .mock("GET", "/users/octocat")
715 .match_header("authorization", "Bearer tok")
716 .with_status(200)
717 .with_body(r#"{"id": 1, "login": "octocat"}"#)
718 .create();
719 let client = Client::new(&server.url(), "tok").unwrap();
720 let user = client.user_by_username("octocat").unwrap().unwrap();
721 assert_eq!(user.id, 1);
722 assert_eq!(user.login, "octocat");
723 mock.assert();
724 }
725
726 #[test]
727 fn user_by_username_404_is_none() {
728 let mut server = mockito::Server::new();
729 let mock = server
730 .mock("GET", "/users/ghost")
731 .with_status(404)
732 .with_body(r#"{"message": "Not Found"}"#)
733 .create();
734 let client = Client::new(&server.url(), "tok").unwrap();
735 assert!(client.user_by_username("ghost").unwrap().is_none());
736 mock.assert();
737 }
738
739 #[test]
740 fn search_pull_requests_paginates() {
741 let mut server = mockito::Server::new();
742 let items_page1 = (1..=100)
744 .map(|i| {
745 format!(
746 r#"{{"number":{i},"title":"PR {i}","state":"closed","html_url":"https://github.com/o/r/pull/{i}","pull_request":{{"merged_at":"2026-02-01T10:00:00Z"}}}}"#
747 )
748 })
749 .collect::<Vec<_>>()
750 .join(",");
751 let mock_p1 = server
752 .mock("GET", "/search/issues")
753 .match_query(mockito::Matcher::AllOf(vec![
754 mockito::Matcher::UrlEncoded("page".into(), "1".into()),
755 mockito::Matcher::UrlEncoded("per_page".into(), "100".into()),
756 ]))
757 .with_status(200)
758 .with_body(format!(
759 r#"{{"total_count":105,"incomplete_results":false,"items":[{items_page1}]}}"#
760 ))
761 .create();
762 let mock_p2 = server
763 .mock("GET", "/search/issues")
764 .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
765 .with_status(200)
766 .with_body(
767 r#"{"total_count":105,"incomplete_results":false,"items":[
768 {"number":101,"title":"x","state":"open","html_url":"https://github.com/o/r/pull/101"},
769 {"number":102,"title":"y","state":"open","html_url":"https://github.com/o/r/pull/102"},
770 {"number":103,"title":"z","state":"open","html_url":"https://github.com/o/r/pull/103"},
771 {"number":104,"title":"w","state":"open","html_url":"https://github.com/o/r/pull/104"},
772 {"number":105,"title":"v","state":"open","html_url":"https://github.com/o/r/pull/105"}
773 ]}"#,
774 )
775 .create();
776 let client = Client::new(&server.url(), "tok").unwrap();
777 let prs = client
778 .search_pull_requests("type:pr author:octocat")
779 .unwrap();
780 assert_eq!(prs.len(), 105);
781 mock_p1.assert();
782 mock_p2.assert();
783 }
784
785 #[test]
786 fn pull_request_repo_slug_from_html_url() {
787 let pr = PullRequest {
788 number: 42,
789 title: "x".into(),
790 state: "open".into(),
791 pull_request: None,
792 html_url: "https://github.com/slopfest/sandogasa/pull/42".into(),
793 repository_url: None,
794 };
795 assert_eq!(pr.repo_slug().as_deref(), Some("slopfest/sandogasa"));
796 }
797
798 #[test]
799 fn pull_request_repo_slug_from_repository_url() {
800 let pr = PullRequest {
801 number: 42,
802 title: "x".into(),
803 state: "open".into(),
804 pull_request: None,
805 html_url: "https://github.com/o/r/issues/42".into(),
806 repository_url: Some("https://api.github.com/repos/slopfest/sandogasa".into()),
807 };
808 let pr2 = PullRequest {
810 html_url: "garbage".into(),
811 ..pr
812 };
813 assert_eq!(pr2.repo_slug().as_deref(), Some("slopfest/sandogasa"));
814 }
815
816 #[test]
817 fn pull_request_merged_at_via_helper() {
818 let pr: PullRequest = serde_json::from_str(
819 r#"{"number":1,"title":"t","state":"closed",
820 "html_url":"https://github.com/o/r/pull/1",
821 "pull_request":{"merged_at":"2026-02-01T10:00:00Z"}}"#,
822 )
823 .unwrap();
824 assert_eq!(pr.merged_at(), Some("2026-02-01T10:00:00Z"));
825 }
826
827 #[test]
828 fn user_events_pagination_stops_at_300() {
829 let mut server = mockito::Server::new();
830 let make_event = |i: u64| {
834 format!(
835 r#"{{"id":"{i}","type":"PushEvent","repo":{{"id":1,"name":"o/r"}},"created_at":"2026-02-15T10:00:00Z"}}"#
836 )
837 };
838 let page1: String = (1..=100).map(make_event).collect::<Vec<_>>().join(",");
839 let page2: String = (101..=200).map(make_event).collect::<Vec<_>>().join(",");
840 let page3: String = (201..=250).map(make_event).collect::<Vec<_>>().join(",");
841 let m1 = server
842 .mock("GET", "/users/octocat/events")
843 .match_query(mockito::Matcher::UrlEncoded("page".into(), "1".into()))
844 .with_status(200)
845 .with_body(format!("[{page1}]"))
846 .create();
847 let m2 = server
848 .mock("GET", "/users/octocat/events")
849 .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
850 .with_status(200)
851 .with_body(format!("[{page2}]"))
852 .create();
853 let m3 = server
854 .mock("GET", "/users/octocat/events")
855 .match_query(mockito::Matcher::UrlEncoded("page".into(), "3".into()))
856 .with_status(200)
857 .with_body(format!("[{page3}]"))
858 .create();
859 let client = Client::new(&server.url(), "tok").unwrap();
860 let events = client.user_events("octocat").unwrap();
861 assert_eq!(events.len(), 250);
862 m1.assert();
863 m2.assert();
864 m3.assert();
865 }
866
867 #[test]
868 fn count_authored_commits_paginates_and_handles_409() {
869 let mut server = mockito::Server::new();
870 let m1 = server
871 .mock("GET", "/repos/o/r/commits")
872 .match_query(mockito::Matcher::UrlEncoded("page".into(), "1".into()))
873 .with_status(200)
874 .with_body(format!("[{}]", vec!["{}"; 100].join(",")))
875 .create();
876 let m2 = server
877 .mock("GET", "/repos/o/r/commits")
878 .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
879 .with_status(200)
880 .with_body("[{},{}]")
881 .create();
882 let client = Client::new(&server.url(), "tok").unwrap();
883 let n = client
884 .count_authored_commits(
885 "o",
886 "r",
887 "octocat",
888 chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(),
889 chrono::NaiveDate::from_ymd_opt(2026, 3, 31).unwrap(),
890 )
891 .unwrap();
892 assert_eq!(n, 102);
893 m1.assert();
894 m2.assert();
895 }
896
897 #[test]
898 fn count_authored_commits_empty_repo_returns_zero() {
899 let mut server = mockito::Server::new();
900 let mock = server
901 .mock("GET", "/repos/o/empty/commits")
902 .match_query(mockito::Matcher::Any)
903 .with_status(409)
904 .with_body(r#"{"message":"Git Repository is empty."}"#)
905 .create();
906 let client = Client::new(&server.url(), "tok").unwrap();
907 let n = client
908 .count_authored_commits(
909 "o",
910 "empty",
911 "x",
912 chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(),
913 chrono::NaiveDate::from_ymd_opt(2026, 3, 31).unwrap(),
914 )
915 .unwrap();
916 assert_eq!(n, 0);
917 mock.assert();
918 }
919
920 #[test]
921 fn validate_token_distinguishes_invalid_from_error() {
922 let mut server = mockito::Server::new();
923 let ok = server
925 .mock("GET", "/user")
926 .match_header("authorization", "Bearer good")
927 .with_status(200)
928 .with_body(r#"{"id": 1, "login": "octocat"}"#)
929 .create();
930 assert!(validate_token(&server.url(), "good").unwrap());
931 ok.assert();
932 let bad = server
934 .mock("GET", "/user")
935 .match_header("authorization", "Bearer bad")
936 .with_status(401)
937 .with_body(r#"{"message": "Bad credentials"}"#)
938 .create();
939 assert!(!validate_token(&server.url(), "bad").unwrap());
940 bad.assert();
941 }
942
943 #[test]
944 fn repository_slug_prefers_full_name() {
945 let repo = Repository {
946 id: 1,
947 full_name: Some("o/r".into()),
948 name: Some("ignored".into()),
949 };
950 assert_eq!(repo.slug(), Some("o/r"));
951 let evt_repo = Repository {
953 id: 1,
954 full_name: None,
955 name: Some("o/r".into()),
956 };
957 assert_eq!(evt_repo.slug(), Some("o/r"));
958 }
959}