1use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderName, HeaderValue};
32use sandogasa_cli::http;
33use serde::{Deserialize, Serialize};
34
35#[derive(Debug, Clone, Deserialize, Serialize)]
38pub struct User {
39 pub id: u64,
40 pub login: String,
41 #[serde(default)]
43 pub name: Option<String>,
44 #[serde(default)]
46 pub email: Option<String>,
47}
48
49#[derive(Debug, Clone, Deserialize, Serialize)]
51pub struct Repository {
52 pub id: u64,
53 #[serde(default)]
55 pub full_name: Option<String>,
56 #[serde(default)]
59 pub name: Option<String>,
60}
61
62impl Repository {
63 pub fn slug(&self) -> Option<&str> {
66 self.full_name.as_deref().or(self.name.as_deref())
67 }
68}
69
70#[derive(Debug, Clone, Deserialize, Serialize)]
76pub struct PullRequest {
77 pub number: u64,
78 pub title: String,
79 pub state: String,
80 #[serde(default)]
83 pub pull_request: Option<PullRequestRef>,
84 pub html_url: String,
85 #[serde(default)]
89 pub repository_url: Option<String>,
90}
91
92impl PullRequest {
93 pub fn repo_slug(&self) -> Option<String> {
96 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 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 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#[derive(Debug, Clone, Deserialize, Serialize)]
131pub struct PullRequestRef {
132 #[serde(default)]
133 pub merged_at: Option<String>,
134}
135
136#[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 #[serde(default)]
148 pub created_at: Option<String>,
149 #[serde(default)]
151 pub user: Option<Login>,
152}
153
154#[derive(Debug, Clone, Deserialize)]
156pub struct Login {
157 pub login: String,
158}
159
160#[derive(Debug, Clone, Deserialize)]
163pub struct RepoCommit {
164 pub sha: String,
165 pub commit: CommitBody,
166}
167
168#[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#[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 pub fn title(&self) -> &str {
189 self.commit.message.lines().next().unwrap_or("")
190 }
191}
192
193#[derive(Debug, Clone, Deserialize)]
195pub struct GitRef {
196 #[serde(rename = "ref")]
197 pub ref_name: String,
198 pub sha: String,
199}
200
201#[derive(Debug, Deserialize)]
204struct CompareResult {
205 #[serde(default)]
206 ahead_by: u64,
207}
208
209#[derive(Debug, Deserialize)]
211struct SearchIssuesResponse {
212 total_count: u64,
213 items: Vec<PullRequest>,
214}
215
216#[derive(Debug, Clone, Deserialize, Serialize)]
220pub struct Event {
221 pub id: String,
222 #[serde(rename = "type")]
225 pub event_type: String,
226 pub repo: Repository,
227 pub created_at: String,
228 #[serde(default)]
230 pub payload: serde_json::Value,
231}
232
233#[derive(Debug, Clone, Deserialize, Serialize)]
238pub struct GitTagRef {
239 #[serde(rename = "ref")]
241 pub ref_name: String,
242 pub object: GitObject,
243}
244
245impl GitTagRef {
246 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#[derive(Debug, Clone, Deserialize, Serialize)]
257pub struct GitObject {
258 #[serde(rename = "type")]
259 pub object_type: String,
260 pub sha: String,
261}
262
263#[derive(Debug, Clone, Deserialize, Serialize)]
268pub struct AnnotatedTag {
269 pub tag: String,
270 pub tagger: Tagger,
271}
272
273#[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 pub fn repo_slug(&self) -> Option<&str> {
286 self.repo.slug()
287 }
288}
289
290pub struct Client {
292 http: reqwest::blocking::Client,
293 base_url: String,
294}
295
296impl Client {
297 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 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 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 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 if n < 100 || page >= 3 {
377 break;
378 }
379 page += 1;
380 }
381 Ok(out)
382 }
383
384 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 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 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 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 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 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 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 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 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 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
562pub 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
583fn 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 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 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 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 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 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 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 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 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}