1use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderName, HeaderValue};
33use sandogasa_cli::http;
34use std::collections::{BTreeMap, BTreeSet};
35
36use serde::{Deserialize, Serialize};
37use serde_json::json;
38
39#[derive(Debug, Clone, Deserialize, Serialize)]
42#[non_exhaustive]
43pub struct User {
44 pub id: u64,
45 pub login: String,
46 #[serde(default)]
48 pub name: Option<String>,
49 #[serde(default)]
51 pub email: Option<String>,
52}
53
54#[derive(Debug, Clone, Deserialize, Serialize)]
56#[non_exhaustive]
57pub struct Repository {
58 pub id: u64,
59 #[serde(default)]
61 pub full_name: Option<String>,
62 #[serde(default)]
65 pub name: Option<String>,
66}
67
68impl Repository {
69 pub fn slug(&self) -> Option<&str> {
72 self.full_name.as_deref().or(self.name.as_deref())
73 }
74}
75
76#[derive(Debug, Clone, Deserialize, Serialize)]
82#[non_exhaustive]
83pub struct PullRequest {
84 pub number: u64,
85 pub title: String,
86 pub state: String,
87 #[serde(default)]
90 pub pull_request: Option<PullRequestRef>,
91 pub html_url: String,
92 #[serde(default)]
96 pub repository_url: Option<String>,
97}
98
99impl PullRequest {
100 pub fn repo_slug(&self) -> Option<String> {
103 if let Some(rest) = self
105 .html_url
106 .strip_prefix("https://github.com/")
107 .or_else(|| self.html_url.strip_prefix("https://"))
108 {
109 let parts: Vec<&str> = rest.splitn(4, '/').collect();
110 if parts.len() >= 2 {
111 return Some(format!("{}/{}", parts[0], parts[1]));
112 }
113 }
114 if let Some(repo) = &self.repository_url
117 && let Some(rest) = repo.split("/repos/").nth(1)
118 {
119 return Some(rest.to_string());
120 }
121 None
122 }
123
124 pub fn merged_at(&self) -> Option<&str> {
128 self.pull_request
129 .as_ref()
130 .and_then(|p| p.merged_at.as_deref())
131 }
132}
133
134#[derive(Debug, Clone, Deserialize, Serialize)]
138#[non_exhaustive]
139pub struct PullRequestRef {
140 #[serde(default)]
141 pub merged_at: Option<String>,
142}
143
144#[derive(Debug, Clone, Deserialize)]
147#[non_exhaustive]
148pub struct PullRequestDetail {
149 pub number: u64,
150 pub state: String,
151 #[serde(default)]
152 pub merged: bool,
153 pub head: GitRef,
154 pub base: GitRef,
155 #[serde(default)]
157 pub created_at: Option<String>,
158 #[serde(default)]
160 pub user: Option<Login>,
161}
162
163#[derive(Debug, Clone, Deserialize)]
165#[non_exhaustive]
166pub struct Login {
167 pub login: String,
168}
169
170#[derive(Debug, Clone, Deserialize)]
173#[non_exhaustive]
174pub struct RepoCommit {
175 pub sha: String,
176 pub commit: CommitBody,
177}
178
179#[derive(Debug, Clone, Deserialize)]
181#[non_exhaustive]
182pub struct CommitBody {
183 #[serde(default)]
184 pub message: String,
185 #[serde(default)]
186 pub author: Option<CommitAuthor>,
187}
188
189#[derive(Debug, Clone, Deserialize)]
191#[non_exhaustive]
192pub struct CommitAuthor {
193 #[serde(default)]
194 pub name: String,
195 #[serde(default)]
196 pub email: String,
197}
198
199impl RepoCommit {
200 pub fn title(&self) -> &str {
202 self.commit.message.lines().next().unwrap_or("")
203 }
204}
205
206#[derive(Debug, Clone, Deserialize)]
208#[non_exhaustive]
209pub struct GitRef {
210 #[serde(rename = "ref")]
211 pub ref_name: String,
212 pub sha: String,
213}
214
215#[derive(Debug, Deserialize)]
218struct CompareResult {
219 #[serde(default)]
220 ahead_by: u64,
221}
222
223#[derive(Debug, Deserialize)]
225struct SearchIssuesResponse {
226 total_count: u64,
227 items: Vec<PullRequest>,
228}
229
230#[derive(Debug, Clone, Deserialize, Serialize)]
234#[non_exhaustive]
235pub struct Event {
236 pub id: String,
237 #[serde(rename = "type")]
240 pub event_type: String,
241 pub repo: Repository,
242 pub created_at: String,
243 #[serde(default)]
246 pub public: bool,
247 #[serde(default)]
249 pub payload: serde_json::Value,
250}
251
252#[derive(Debug, Clone, Deserialize, Serialize)]
257#[non_exhaustive]
258pub struct GitTagRef {
259 #[serde(rename = "ref")]
261 pub ref_name: String,
262 pub object: GitObject,
263}
264
265impl GitTagRef {
266 pub fn tag_name(&self) -> &str {
268 self.ref_name
269 .strip_prefix("refs/tags/")
270 .unwrap_or(&self.ref_name)
271 }
272}
273
274#[derive(Debug, Clone, Deserialize, Serialize)]
277#[non_exhaustive]
278pub struct GitObject {
279 #[serde(rename = "type")]
280 pub object_type: String,
281 pub sha: String,
282}
283
284#[derive(Debug, Clone, Deserialize, Serialize)]
289#[non_exhaustive]
290pub struct AnnotatedTag {
291 pub tag: String,
292 pub tagger: Tagger,
293}
294
295#[derive(Debug, Clone, Deserialize, Serialize)]
298#[non_exhaustive]
299pub struct Tagger {
300 pub name: String,
301 pub email: String,
302 pub date: String,
303}
304
305impl Event {
306 pub fn repo_slug(&self) -> Option<&str> {
309 self.repo.slug()
310 }
311}
312
313#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
315#[non_exhaustive]
316pub struct RepoNode {
317 #[serde(rename = "nameWithOwner")]
319 pub name_with_owner: String,
320 #[serde(rename = "isPrivate")]
321 pub is_private: bool,
322}
323
324#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
326#[non_exhaustive]
327pub struct ItemNode {
328 pub number: u64,
329 pub title: String,
330 pub url: String,
331 pub state: String,
333 pub repository: RepoNode,
334}
335
336#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
338#[non_exhaustive]
339pub struct IssueComment {
340 #[serde(rename = "createdAt")]
342 pub created_at: String,
343 #[serde(rename = "updatedAt")]
344 pub updated_at: String,
345 pub url: String,
346 pub issue: Option<ItemNode>,
348 #[serde(rename = "pullRequest")]
350 pub pull_request: Option<ItemNode>,
351}
352
353#[derive(Debug, Clone, Default, PartialEq, Eq)]
357#[non_exhaustive]
358pub struct Contributions {
359 pub commits: BTreeMap<String, u64>,
361 pub private_repos: BTreeSet<String>,
364 pub reviewed: Vec<ItemNode>,
366 pub unreadable: Unreadable,
369 pub capped: bool,
372 pub restricted: u64,
377}
378
379#[derive(Debug, Clone, Default, PartialEq, Eq)]
381#[non_exhaustive]
382pub struct Comments {
383 pub comments: Vec<IssueComment>,
384 pub unreadable: Unreadable,
387}
388
389#[derive(Debug, Clone, Default)]
391#[non_exhaustive]
392pub struct RecentTags {
393 pub tags: BTreeMap<String, Vec<AnnotatedTag>>,
395 pub failures: Vec<String>,
397}
398
399#[derive(Debug, Clone, Default, PartialEq, Eq)]
401#[non_exhaustive]
402pub struct CommitCounts {
403 pub counts: BTreeMap<String, u64>,
405 pub failures: Vec<String>,
407}
408
409#[derive(Debug, Clone, Default, PartialEq, Eq)]
412#[non_exhaustive]
413pub struct Unreadable {
414 pub count: usize,
415 pub reasons: BTreeSet<String>,
417}
418
419impl Unreadable {
420 fn add(&mut self, count: usize, errors: Option<Vec<GraphqlError>>) {
421 self.count += count;
422 if count > 0 {
423 self.reasons
424 .extend(errors.unwrap_or_default().into_iter().map(|e| e.message));
425 }
426 }
427}
428
429pub struct Client {
431 http: reqwest::blocking::Client,
432 base_url: String,
433}
434
435impl Client {
436 pub fn new(base_url: &str, token: &str) -> Result<Self, Box<dyn std::error::Error>> {
441 sandogasa_cli::ensure_secure_url(base_url)?;
442 let http = build_http_client(token)?;
443 Ok(Self {
444 http,
445 base_url: base_url.trim_end_matches('/').to_string(),
446 })
447 }
448
449 pub fn user_by_username(
453 &self,
454 username: &str,
455 ) -> Result<Option<User>, Box<dyn std::error::Error>> {
456 let url = format!("{}/users/{}", self.base_url, username);
457 let resp = self.http.get(&url).send()?;
458 if resp.status().as_u16() == 404 {
459 return Ok(None);
460 }
461 Ok(Some(http::blocking_json_ok(
462 resp,
463 &format!("GitHub GET {url}"),
464 )?))
465 }
466
467 pub fn search_pull_requests(
474 &self,
475 query: &str,
476 ) -> Result<Vec<PullRequest>, Box<dyn std::error::Error>> {
477 let mut out: Vec<PullRequest> = Vec::new();
478 let mut page = 1u32;
479 loop {
480 let page_str = page.to_string();
481 let url = format!("{}/search/issues", self.base_url);
482 let resp = self
483 .http
484 .get(&url)
485 .query(&[("q", query), ("per_page", "100"), ("page", &page_str)])
486 .send()?;
487 let batch: SearchIssuesResponse = http::blocking_json_ok(resp, "GitHub search")?;
488 let n = batch.items.len();
489 out.extend(batch.items);
490 if n < 100 || out.len() as u64 >= batch.total_count {
491 break;
492 }
493 page += 1;
494 }
495 Ok(out)
496 }
497
498 pub fn user_events(&self, username: &str) -> Result<Vec<Event>, Box<dyn std::error::Error>> {
501 let mut out: Vec<Event> = Vec::new();
502 let mut page = 1u32;
503 loop {
504 let url = format!("{}/users/{}/events", self.base_url, username);
505 let page_str = page.to_string();
506 let resp = self
507 .http
508 .get(&url)
509 .query(&[("per_page", "100"), ("page", &page_str)])
510 .send()?;
511 let batch: Vec<Event> = http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
512 let n = batch.len();
513 out.extend(batch);
514 if n < 100 || page >= 3 {
516 break;
517 }
518 page += 1;
519 }
520 Ok(out)
521 }
522
523 pub fn count_authored_commits(
537 &self,
538 owner: &str,
539 repo: &str,
540 author: &str,
541 since: chrono::NaiveDate,
542 until: chrono::NaiveDate,
543 ) -> Result<u64, Box<dyn std::error::Error>> {
544 let url = format!("{}/repos/{}/{}/commits", self.base_url, owner, repo);
545 let since_str = format!("{since}T00:00:00Z");
546 let until_str = format!("{until}T23:59:59Z");
547 let mut total: u64 = 0;
548 let mut page = 1u32;
549 loop {
550 let page_str = page.to_string();
551 let query: Vec<(&str, &str)> = vec![
552 ("author", author),
553 ("since", &since_str),
554 ("until", &until_str),
555 ("per_page", "100"),
556 ("page", &page_str),
557 ];
558 let resp = self.http.get(&url).query(&query).send()?;
559 if resp.status().as_u16() == 404 || resp.status().as_u16() == 409 {
564 break;
565 }
566 let batch: Vec<serde_json::Value> =
567 http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
568 let n = batch.len() as u64;
569 total += n;
570 if n < 100 {
571 break;
572 }
573 page += 1;
574 }
575 Ok(total)
576 }
577
578 pub fn list_tag_refs(
582 &self,
583 owner: &str,
584 repo: &str,
585 ) -> Result<Vec<GitTagRef>, Box<dyn std::error::Error>> {
586 let url = format!("{}/repos/{}/{}/git/refs/tags", self.base_url, owner, repo);
587 let resp = self.http.get(&url).send()?;
588 if resp.status().as_u16() == 404 || resp.status().as_u16() == 409 {
590 return Ok(Vec::new());
591 }
592 let resp = http::blocking_ok(resp, &format!("GitHub GET {url}"))?;
593 let body: serde_json::Value = resp.json()?;
599 if body.is_array() {
600 Ok(serde_json::from_value(body)?)
601 } else {
602 Ok(vec![serde_json::from_value(body)?])
603 }
604 }
605
606 pub fn get_annotated_tag(
611 &self,
612 owner: &str,
613 repo: &str,
614 sha: &str,
615 ) -> Result<AnnotatedTag, Box<dyn std::error::Error>> {
616 let url = format!(
617 "{}/repos/{}/{}/git/tags/{}",
618 self.base_url, owner, repo, sha
619 );
620 let resp = self.http.get(&url).send()?;
621 Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
622 }
623
624 pub fn pull_request(
628 &self,
629 owner: &str,
630 repo: &str,
631 number: u64,
632 ) -> Result<PullRequestDetail, Box<dyn std::error::Error>> {
633 let url = format!("{}/repos/{owner}/{repo}/pulls/{number}", self.base_url);
634 let resp = self.http.get(&url).send()?;
635 Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
636 }
637
638 pub fn repository_public(
641 &self,
642 owner: &str,
643 repo: &str,
644 ) -> Result<Option<bool>, Box<dyn std::error::Error>> {
645 #[derive(Deserialize)]
646 struct Visibility {
647 private: bool,
648 }
649 let url = format!("{}/repos/{owner}/{repo}", self.base_url);
650 let resp = self.http.get(&url).send()?;
651 if resp.status().as_u16() == 404 {
652 return Ok(None);
653 }
654 let v: Visibility = http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
655 Ok(Some(!v.private))
656 }
657
658 pub fn pull_request_commits(
661 &self,
662 owner: &str,
663 repo: &str,
664 number: u64,
665 ) -> Result<Vec<RepoCommit>, Box<dyn std::error::Error>> {
666 let url = format!(
667 "{}/repos/{owner}/{repo}/pulls/{number}/commits",
668 self.base_url
669 );
670 let resp = self.http.get(&url).query(&[("per_page", "100")]).send()?;
671 Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
672 }
673
674 pub fn branch_commits_by(
679 &self,
680 owner: &str,
681 repo: &str,
682 branch: &str,
683 author: &str,
684 since: &str,
685 ) -> Result<Vec<RepoCommit>, Box<dyn std::error::Error>> {
686 let url = format!("{}/repos/{owner}/{repo}/commits", self.base_url);
687 let resp = self
688 .http
689 .get(&url)
690 .query(&[
691 ("sha", branch),
692 ("author", author),
693 ("since", since),
694 ("per_page", "100"),
695 ])
696 .send()?;
697 Ok(http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?)
698 }
699
700 pub fn commit_contained(
704 &self,
705 owner: &str,
706 repo: &str,
707 branch: &str,
708 sha: &str,
709 ) -> Result<bool, Box<dyn std::error::Error>> {
710 let url = format!(
711 "{}/repos/{owner}/{repo}/compare/{branch}...{sha}",
712 self.base_url
713 );
714 let resp = self.http.get(&url).send()?;
715 let cmp: CompareResult =
716 http::blocking_json_ok(resp, &format!("GitHub compare {branch}...{sha}"))?;
717 Ok(cmp.ahead_by == 0)
718 }
719
720 pub fn contributions(
727 &self,
728 login: &str,
729 from: chrono::NaiveDate,
730 to: chrono::NaiveDate,
731 ) -> Result<Contributions, Box<dyn std::error::Error>> {
732 let mut out = Contributions::default();
733 let mut windows = Vec::new();
737 let mut start = from;
738 while start <= to {
739 let end = (start + chrono::Duration::days(364)).min(to);
740 windows.push((start, end));
741 start = end + chrono::Duration::days(1);
742 }
743 windows.reverse();
744 'windows: while let Some((start, end)) = windows.pop() {
745 let mut after: Option<String> = None;
746 let mut first = true;
747 loop {
748 let answer: GraphqlResponse<ContributionsData> = self.graphql_answer(
749 CONTRIBUTIONS_QUERY,
750 &json!({
751 "login": login,
752 "from": format!("{start}T00:00:00Z"),
753 "to": format!("{end}T23:59:59Z"),
754 "after": after,
755 }),
756 )?;
757 let data = answer
758 .data
759 .ok_or_else(|| graphql_failure(answer.errors.clone()))?;
760 let collection = data
761 .user
762 .ok_or_else(|| format!("no GitHub user {login}"))?
763 .contributions_collection;
764 if first {
765 let named = collection.commit_contributions_by_repository.len();
766 if named >= MAX_REPOSITORIES {
767 if start < end {
768 let half = start + (end - start) / 2;
769 windows.push((half + chrono::Duration::days(1), end));
770 windows.push((start, half));
771 continue 'windows;
772 }
773 out.capped = true;
774 }
775 out.restricted += collection.restricted_contributions_count;
776 for by_repo in collection.commit_contributions_by_repository {
777 let repo = by_repo.repository;
778 if repo.is_private {
779 out.private_repos.insert(repo.name_with_owner.clone());
780 }
781 *out.commits.entry(repo.name_with_owner).or_default() +=
782 by_repo.contributions.total_count;
783 }
784 first = false;
785 }
786 let reviews = collection.pull_request_review_contributions;
787 let withheld = reviews
788 .nodes
789 .iter()
790 .filter(|n| n.as_ref().and_then(|n| n.pull_request.as_ref()).is_none())
791 .count();
792 out.unreadable.add(withheld, answer.errors);
793 for pr in reviews
794 .nodes
795 .into_iter()
796 .flatten()
797 .filter_map(|n| n.pull_request)
798 {
799 if pr.repository.is_private {
800 out.private_repos
801 .insert(pr.repository.name_with_owner.clone());
802 }
803 if !out.reviewed.iter().any(|r| r.url == pr.url) {
804 out.reviewed.push(pr);
805 }
806 }
807 match reviews.page_info.next() {
808 Some(cursor) => after = Some(cursor),
809 None => break,
810 }
811 }
812 }
813 Ok(out)
814 }
815
816 pub fn issue_comments(
821 &self,
822 login: &str,
823 since: chrono::NaiveDate,
824 ) -> Result<Comments, Box<dyn std::error::Error>> {
825 let since = format!("{since}T00:00:00Z");
826 let mut out = Comments::default();
827 let mut after: Option<String> = None;
828 loop {
829 let answer: GraphqlResponse<IssueCommentsData> = self.graphql_answer(
830 ISSUE_COMMENTS_QUERY,
831 &json!({"login": login, "after": after}),
832 )?;
833 let data = answer
834 .data
835 .ok_or_else(|| graphql_failure(answer.errors.clone()))?;
836 let page = data
837 .user
838 .ok_or_else(|| format!("no GitHub user {login}"))?
839 .issue_comments;
840 let mut older = false;
841 let mut withheld = 0;
842 for node in page.nodes {
843 let Some(comment) = node else {
844 withheld += 1;
845 continue;
846 };
847 if comment.updated_at < since {
849 older = true;
850 break;
851 }
852 out.comments.push(comment);
853 }
854 out.unreadable.add(withheld, answer.errors);
857 match page.page_info.next() {
858 Some(cursor) if !older => after = Some(cursor),
859 _ => break,
860 }
861 }
862 Ok(out)
863 }
864
865 pub fn token_login(&self) -> Result<String, Box<dyn std::error::Error>> {
867 let url = format!("{}/user", self.base_url);
868 let resp = self.http.get(&url).send()?;
869 let user: User = http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
870 Ok(user.login)
871 }
872
873 pub fn private_repos_pushed_since(
879 &self,
880 since: chrono::NaiveDate,
881 ) -> Result<Vec<String>, Box<dyn std::error::Error>> {
882 let since = format!("{since}T00:00:00Z");
883 let url = format!("{}/user/repos", self.base_url);
884 let mut out = Vec::new();
885 let mut page = 1u32;
886 loop {
887 let page_str = page.to_string();
888 let resp = self
889 .http
890 .get(&url)
891 .query(&[
892 ("visibility", "private"),
893 ("affiliation", "owner,collaborator,organization_member"),
894 ("sort", "pushed"),
895 ("direction", "desc"),
896 ("per_page", "100"),
897 ("page", &page_str),
898 ])
899 .send()?;
900 let batch: Vec<PushedRepo> =
901 http::blocking_json_ok(resp, &format!("GitHub GET {url}"))?;
902 let n = batch.len();
903 let mut older = false;
904 for repo in batch {
905 let Some(pushed) = repo.pushed_at.as_deref() else {
908 continue;
909 };
910 if pushed < since.as_str() {
912 older = true;
913 break;
914 }
915 out.push(repo.full_name);
916 }
917 if older || n < 100 {
918 break;
919 }
920 page += 1;
921 }
922 Ok(out)
923 }
924
925 pub fn recent_annotated_tags(&self, repos: &[String]) -> RecentTags {
932 let mut out = RecentTags::default();
933 for chunk in repos.chunks(10) {
934 let mut params = Vec::new();
935 let mut fields = Vec::new();
936 let mut variables = serde_json::Map::new();
937 for (i, slug) in chunk.iter().enumerate() {
938 let Some((owner, name)) = slug.split_once('/') else {
939 continue;
940 };
941 params.push(format!("$o{i}: String!, $n{i}: String!"));
942 fields.push(format!(
943 "r{i}: repository(owner: $o{i}, name: $n{i}) {{ {TAG_REFS} }}"
944 ));
945 variables.insert(format!("o{i}"), json!(owner));
946 variables.insert(format!("n{i}"), json!(name));
947 }
948 if fields.is_empty() {
949 continue;
950 }
951 let query = format!("query({}) {{ {} }}", params.join(", "), fields.join(" "));
952 let data = match self
955 .graphql_answer::<BTreeMap<String, Option<TagRepo>>>(
956 &query,
957 &serde_json::Value::Object(variables),
958 )
959 .and_then(|a| a.data.ok_or_else(|| graphql_failure(a.errors)))
960 {
961 Ok(data) => data,
962 Err(e) => {
963 out.failures.push(format!("{}: {e}", chunk.join(", ")));
964 continue;
965 }
966 };
967 for (i, slug) in chunk.iter().enumerate() {
968 let Some(Some(repo)) = data.get(&format!("r{i}")) else {
969 continue;
970 };
971 let tags: Vec<AnnotatedTag> = repo
972 .refs
973 .nodes
974 .iter()
975 .filter_map(|r| {
976 let actor = r.target.as_ref()?.tagger.as_ref()?;
977 Some(AnnotatedTag {
978 tag: r.name.clone(),
979 tagger: actor.tagger()?,
980 })
981 })
982 .collect();
983 out.tags.insert(slug.clone(), tags);
984 }
985 }
986 out
987 }
988
989 pub fn commit_counts(
996 &self,
997 login: &str,
998 repos: &[String],
999 since: chrono::NaiveDate,
1000 until: chrono::NaiveDate,
1001 ) -> Result<CommitCounts, Box<dyn std::error::Error>> {
1002 let mut out = CommitCounts::default();
1003 if repos.is_empty() {
1004 return Ok(out);
1005 }
1006 let answer: GraphqlResponse<UserIdData> =
1007 self.graphql_answer(USER_ID_QUERY, &json!({"login": login}))?;
1008 let id = answer
1009 .data
1010 .ok_or_else(|| graphql_failure(answer.errors))?
1011 .user
1012 .ok_or_else(|| format!("no GitHub user {login}"))?
1013 .id;
1014 for chunk in repos.chunks(25) {
1015 let mut params =
1016 vec!["$id: ID!, $since: GitTimestamp!, $until: GitTimestamp!".to_string()];
1017 let mut fields = Vec::new();
1018 let mut variables = serde_json::Map::new();
1019 variables.insert("id".into(), json!(id));
1020 variables.insert("since".into(), json!(format!("{since}T00:00:00Z")));
1021 variables.insert("until".into(), json!(format!("{until}T23:59:59Z")));
1022 for (i, slug) in chunk.iter().enumerate() {
1023 let Some((owner, name)) = slug.split_once('/') else {
1024 continue;
1025 };
1026 params.push(format!("$o{i}: String!, $n{i}: String!"));
1027 fields.push(format!(
1028 "r{i}: repository(owner: $o{i}, name: $n{i}) {{ {HISTORY} }}"
1029 ));
1030 variables.insert(format!("o{i}"), json!(owner));
1031 variables.insert(format!("n{i}"), json!(name));
1032 }
1033 if fields.is_empty() {
1034 continue;
1035 }
1036 let query = format!("query({}) {{ {} }}", params.join(", "), fields.join(" "));
1037 let data = match self
1038 .graphql_answer::<BTreeMap<String, Option<HistoryRepo>>>(
1039 &query,
1040 &serde_json::Value::Object(variables),
1041 )
1042 .and_then(|a| a.data.ok_or_else(|| graphql_failure(a.errors)))
1043 {
1044 Ok(data) => data,
1045 Err(e) => {
1046 out.failures.push(format!("{}: {e}", chunk.join(", ")));
1047 continue;
1048 }
1049 };
1050 for (i, slug) in chunk.iter().enumerate() {
1051 let count = data
1052 .get(&format!("r{i}"))
1053 .and_then(Option::as_ref)
1054 .and_then(|r| r.default_branch_ref.as_ref())
1055 .and_then(|b| b.target.as_ref())
1056 .and_then(|t| t.history.as_ref())
1057 .map_or(0, |h| h.total_count);
1058 if count > 0 {
1059 out.counts.insert(slug.clone(), count);
1060 }
1061 }
1062 }
1063 Ok(out)
1064 }
1065
1066 fn graphql_answer<T: serde::de::DeserializeOwned>(
1069 &self,
1070 query: &str,
1071 variables: &serde_json::Value,
1072 ) -> Result<GraphqlResponse<T>, Box<dyn std::error::Error>> {
1073 let url = graphql_url(&self.base_url);
1074 let resp = self
1075 .http
1076 .post(&url)
1077 .json(&json!({"query": query, "variables": variables}))
1078 .send()?;
1079 let what = format!("GitHub GraphQL {url}");
1080 let text = http::blocking_ok(resp, &what)?.text()?;
1081 serde_json::from_str(&text)
1084 .map_err(|e| format!("{what}: cannot read the answer: {e}").into())
1085 }
1086}
1087
1088pub fn validate_token(base_url: &str, token: &str) -> Result<bool, Box<dyn std::error::Error>> {
1094 sandogasa_cli::ensure_secure_url(base_url)?;
1095 let http = build_http_client(token)?;
1096 let url = format!("{}/user", base_url.trim_end_matches('/'));
1097 let resp = http.get(&url).send()?;
1098 let status = resp.status();
1099 if status.is_success() {
1100 return Ok(true);
1101 }
1102 if status.as_u16() == 401 {
1103 return Ok(false);
1104 }
1105 let text = resp.text().unwrap_or_default();
1106 Err(format!("GitHub /user check failed: {status}: {text}").into())
1107}
1108
1109fn graphql_failure(errors: Option<Vec<GraphqlError>>) -> Box<dyn std::error::Error> {
1112 let messages: Vec<String> = errors
1113 .unwrap_or_default()
1114 .into_iter()
1115 .map(|e| e.message)
1116 .collect();
1117 if messages.is_empty() {
1118 "GitHub GraphQL: no data in the answer".into()
1119 } else {
1120 format!("GitHub GraphQL: {}", messages.join("; ")).into()
1121 }
1122}
1123
1124fn graphql_url(base: &str) -> String {
1127 match base.strip_suffix("/api/v3") {
1128 Some(host) => format!("{host}/api/graphql"),
1129 None => format!("{base}/graphql"),
1130 }
1131}
1132
1133const MAX_REPOSITORIES: usize = 100;
1135
1136const CONTRIBUTIONS_QUERY: &str = "\
1137query($login: String!, $from: DateTime!, $to: DateTime!, $after: String) {
1138 user(login: $login) {
1139 contributionsCollection(from: $from, to: $to) {
1140 restrictedContributionsCount
1141 commitContributionsByRepository(maxRepositories: 100) {
1142 repository { nameWithOwner isPrivate }
1143 contributions { totalCount }
1144 }
1145 pullRequestReviewContributions(first: 100, after: $after) {
1146 pageInfo { hasNextPage endCursor }
1147 nodes {
1148 pullRequest { number title url state repository { nameWithOwner isPrivate } }
1149 }
1150 }
1151 }
1152 }
1153}";
1154
1155const TAG_REFS: &str = "refs(refPrefix: \"refs/tags/\", first: 50, \
1157 orderBy: {field: TAG_COMMIT_DATE, direction: DESC}) { \
1158 nodes { name target { ... on Tag { tagger { name email date } } } } }";
1159
1160const USER_ID_QUERY: &str = "query($login: String!) { user(login: $login) { id } }";
1161
1162const HISTORY: &str = "defaultBranchRef { target { ... on Commit { \
1165 history(author: {id: $id}, since: $since, until: $until) { totalCount } } } }";
1166
1167const ISSUE_COMMENTS_QUERY: &str = "\
1168query($login: String!, $after: String) {
1169 user(login: $login) {
1170 issueComments(first: 100, after: $after, orderBy: {field: UPDATED_AT, direction: DESC}) {
1171 pageInfo { hasNextPage endCursor }
1172 nodes {
1173 createdAt updatedAt url
1174 issue { number title url state repository { nameWithOwner isPrivate } }
1175 pullRequest { number title url state repository { nameWithOwner isPrivate } }
1176 }
1177 }
1178 }
1179}";
1180
1181#[derive(Deserialize)]
1182struct TagRepo {
1183 refs: TagRefs,
1184}
1185
1186#[derive(Deserialize)]
1187struct TagRefs {
1188 nodes: Vec<TagRefNode>,
1189}
1190
1191#[derive(Deserialize)]
1192struct TagRefNode {
1193 name: String,
1194 target: Option<TagTarget>,
1196}
1197
1198#[derive(Deserialize)]
1199struct TagTarget {
1200 tagger: Option<GitActor>,
1201}
1202
1203#[derive(Deserialize)]
1206struct GitActor {
1207 name: Option<String>,
1208 email: Option<String>,
1209 date: Option<String>,
1210}
1211
1212impl GitActor {
1213 fn tagger(&self) -> Option<Tagger> {
1216 let date = chrono::DateTime::parse_from_rfc3339(self.date.as_deref()?).ok()?;
1217 Some(Tagger {
1218 name: self.name.clone().unwrap_or_default(),
1219 email: self.email.clone().unwrap_or_default(),
1220 date: date.to_utc().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
1221 })
1222 }
1223}
1224
1225#[derive(Deserialize)]
1226struct UserIdData {
1227 user: Option<UserId>,
1228}
1229
1230#[derive(Deserialize)]
1231struct UserId {
1232 id: String,
1233}
1234
1235#[derive(Deserialize)]
1236struct HistoryRepo {
1237 #[serde(rename = "defaultBranchRef")]
1238 default_branch_ref: Option<HistoryBranch>,
1239}
1240
1241#[derive(Deserialize)]
1242struct HistoryBranch {
1243 target: Option<HistoryTarget>,
1244}
1245
1246#[derive(Deserialize)]
1247struct HistoryTarget {
1248 history: Option<Count>,
1249}
1250
1251#[derive(Deserialize)]
1252struct PushedRepo {
1253 full_name: String,
1254 pushed_at: Option<String>,
1255}
1256
1257#[derive(Deserialize)]
1258struct GraphqlResponse<T> {
1259 data: Option<T>,
1260 errors: Option<Vec<GraphqlError>>,
1261}
1262
1263#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
1264struct GraphqlError {
1265 message: String,
1266}
1267
1268#[derive(Deserialize)]
1269struct PageInfo {
1270 #[serde(rename = "hasNextPage")]
1271 has_next_page: bool,
1272 #[serde(rename = "endCursor")]
1273 end_cursor: Option<String>,
1274}
1275
1276impl PageInfo {
1277 fn next(self) -> Option<String> {
1279 self.end_cursor.filter(|_| self.has_next_page)
1280 }
1281}
1282
1283#[derive(Deserialize)]
1284struct ContributionsData {
1285 user: Option<ContributionsUser>,
1286}
1287
1288#[derive(Deserialize)]
1289struct ContributionsUser {
1290 #[serde(rename = "contributionsCollection")]
1291 contributions_collection: Collection,
1292}
1293
1294#[derive(Deserialize)]
1295struct Collection {
1296 #[serde(rename = "restrictedContributionsCount", default)]
1297 restricted_contributions_count: u64,
1298 #[serde(rename = "commitContributionsByRepository")]
1299 commit_contributions_by_repository: Vec<CommitsByRepo>,
1300 #[serde(rename = "pullRequestReviewContributions")]
1301 pull_request_review_contributions: ReviewPage,
1302}
1303
1304#[derive(Deserialize)]
1305struct CommitsByRepo {
1306 repository: RepoNode,
1307 contributions: Count,
1308}
1309
1310#[derive(Deserialize)]
1311struct Count {
1312 #[serde(rename = "totalCount")]
1313 total_count: u64,
1314}
1315
1316#[derive(Deserialize)]
1317struct ReviewPage {
1318 #[serde(rename = "pageInfo")]
1319 page_info: PageInfo,
1320 nodes: Vec<Option<ReviewNode>>,
1322}
1323
1324#[derive(Deserialize)]
1325struct ReviewNode {
1326 #[serde(rename = "pullRequest")]
1327 pull_request: Option<ItemNode>,
1328}
1329
1330#[derive(Deserialize)]
1331struct IssueCommentsData {
1332 user: Option<IssueCommentsUser>,
1333}
1334
1335#[derive(Deserialize)]
1336struct IssueCommentsUser {
1337 #[serde(rename = "issueComments")]
1338 issue_comments: CommentPage,
1339}
1340
1341#[derive(Deserialize)]
1342struct CommentPage {
1343 #[serde(rename = "pageInfo")]
1344 page_info: PageInfo,
1345 nodes: Vec<Option<IssueComment>>,
1347}
1348
1349fn build_http_client(token: &str) -> Result<reqwest::blocking::Client, Box<dyn std::error::Error>> {
1353 let mut headers = HeaderMap::new();
1354 headers.insert(
1355 AUTHORIZATION,
1356 HeaderValue::from_str(&format!("Bearer {token}"))?,
1357 );
1358 headers.insert(
1359 ACCEPT,
1360 HeaderValue::from_static("application/vnd.github+json"),
1361 );
1362 headers.insert(
1363 HeaderName::from_static("x-github-api-version"),
1364 HeaderValue::from_static("2022-11-28"),
1365 );
1366 Ok(http::blocking_builder(concat!(
1367 env!("CARGO_PKG_NAME"),
1368 "/",
1369 env!("CARGO_PKG_VERSION")
1370 ))
1371 .default_headers(headers)
1372 .build()?)
1373}
1374
1375#[cfg(test)]
1376mod tests {
1377 use super::*;
1378
1379 fn day(s: &str) -> chrono::NaiveDate {
1380 chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
1381 }
1382
1383 fn graphql_body(data: serde_json::Value, errors: serde_json::Value) -> String {
1384 json!({"data": data, "errors": errors}).to_string()
1385 }
1386
1387 fn pr(repo: &str, n: u64, private: bool) -> serde_json::Value {
1388 json!({"number": n, "title": "t", "state": "OPEN",
1389 "url": format!("https://github.com/{repo}/pull/{n}"),
1390 "repository": {"nameWithOwner": repo, "isPrivate": private}})
1391 }
1392
1393 #[test]
1394 fn graphql_lives_beside_the_rest_api() {
1395 assert_eq!(
1396 graphql_url("https://api.github.com"),
1397 "https://api.github.com/graphql"
1398 );
1399 assert_eq!(
1400 graphql_url("https://ghe.example.com/api/v3"),
1401 "https://ghe.example.com/api/graphql"
1402 );
1403 }
1404
1405 #[test]
1406 fn contributions_are_read_a_year_and_a_page_at_a_time() {
1407 let mut server = mockito::Server::new();
1408 let collection = |commits: serde_json::Value, reviews: serde_json::Value, next: bool| {
1409 json!({"user": {"contributionsCollection": {
1410 "restrictedContributionsCount": 2,
1411 "commitContributionsByRepository": commits,
1412 "pullRequestReviewContributions": {
1413 "pageInfo": {"hasNextPage": next, "endCursor": if next { "c1" } else { "" }},
1414 "nodes": reviews
1415 }
1416 }}})
1417 };
1418 let commits = json!([
1419 {"repository": {"nameWithOwner": "o/pub", "isPrivate": false},
1420 "contributions": {"totalCount": 3}},
1421 {"repository": {"nameWithOwner": "o/priv", "isPrivate": true},
1422 "contributions": {"totalCount": 1}}
1423 ]);
1424 let first = server
1426 .mock("POST", "/graphql")
1427 .match_body(mockito::Matcher::AllOf(vec![
1428 mockito::Matcher::Regex("2025-01-01T00:00:00Z".into()),
1429 mockito::Matcher::Regex(r#""after":null"#.into()),
1430 ]))
1431 .with_body(graphql_body(
1432 collection(
1433 commits.clone(),
1434 json!([{"pullRequest": pr("o/pub", 1, false)}, null]),
1435 true,
1436 ),
1437 json!([{"message": "`x` forbids access"}]),
1438 ))
1439 .create();
1440 let second = server
1442 .mock("POST", "/graphql")
1443 .match_body(mockito::Matcher::Regex(r#""after":"c1""#.into()))
1444 .with_body(graphql_body(
1445 collection(
1446 commits,
1447 json!([{"pullRequest": pr("o/pub", 1, false)}, {"pullRequest": pr("o/priv", 2, true)}]),
1448 false,
1449 ),
1450 json!(null),
1451 ))
1452 .create();
1453 let year2 = server
1455 .mock("POST", "/graphql")
1456 .match_body(mockito::Matcher::Regex("2026-01-01T00:00:00Z".into()))
1457 .with_body(graphql_body(
1458 collection(
1459 json!([{"repository": {"nameWithOwner": "o/pub", "isPrivate": false},
1460 "contributions": {"totalCount": 4}}]),
1461 json!([]),
1462 false,
1463 ),
1464 json!(null),
1465 ))
1466 .create();
1467 let client = Client::new(&server.url(), "tok").unwrap();
1468 let c = client
1469 .contributions("me", day("2025-01-01"), day("2026-02-01"))
1470 .unwrap();
1471 first.assert();
1472 second.assert();
1473 year2.assert();
1474 assert_eq!(
1475 c.commits,
1476 BTreeMap::from([("o/priv".to_string(), 1), ("o/pub".to_string(), 7)])
1477 );
1478 assert_eq!(c.private_repos, BTreeSet::from(["o/priv".to_string()]));
1479 let reviewed: Vec<u64> = c.reviewed.iter().map(|p| p.number).collect();
1480 assert_eq!(reviewed, [1, 2]);
1481 assert_eq!(c.unreadable.count, 1);
1482 assert_eq!(
1483 c.unreadable.reasons,
1484 BTreeSet::from(["`x` forbids access".to_string()])
1485 );
1486 assert_eq!(c.restricted, 4);
1487 }
1488
1489 #[test]
1490 fn a_window_naming_100_repositories_is_split() {
1491 let mut server = mockito::Server::new();
1492 let repos = |prefix: &str, n: usize| -> serde_json::Value {
1493 (0..n)
1494 .map(|i| {
1495 json!({"repository": {"nameWithOwner": format!("{prefix}/{i}"), "isPrivate": false},
1496 "contributions": {"totalCount": 1}})
1497 })
1498 .collect()
1499 };
1500 let answer = |commits: serde_json::Value| {
1501 graphql_body(
1502 json!({"user": {"contributionsCollection": {
1503 "commitContributionsByRepository": commits,
1504 "pullRequestReviewContributions": {
1505 "pageInfo": {"hasNextPage": false, "endCursor": null}, "nodes": []}
1506 }}}),
1507 json!(null),
1508 )
1509 };
1510 let window = |from: &str, to: &str| {
1511 mockito::Matcher::AllOf(vec![
1512 mockito::Matcher::Regex(format!(r#""from":"{from}T00:00:00Z""#)),
1513 mockito::Matcher::Regex(format!(r#""to":"{to}T23:59:59Z""#)),
1514 ])
1515 };
1516 let both = server
1517 .mock("POST", "/graphql")
1518 .match_body(window("2026-01-01", "2026-01-02"))
1519 .with_body(answer(repos("both", 100)))
1520 .create();
1521 let first = server
1522 .mock("POST", "/graphql")
1523 .match_body(window("2026-01-01", "2026-01-01"))
1524 .with_body(answer(repos("a", 2)))
1525 .create();
1526 let second = server
1528 .mock("POST", "/graphql")
1529 .match_body(window("2026-01-02", "2026-01-02"))
1530 .with_body(answer(repos("b", 100)))
1531 .create();
1532 let client = Client::new(&server.url(), "tok").unwrap();
1533 let c = client
1534 .contributions("me", day("2026-01-01"), day("2026-01-02"))
1535 .unwrap();
1536 both.assert();
1537 first.assert();
1538 second.assert();
1539 assert_eq!(c.commits.len(), 102);
1540 assert!(!c.commits.contains_key("both/0"));
1541 assert!(c.capped);
1542 }
1543
1544 #[test]
1545 fn comments_are_read_back_to_the_day_asked() {
1546 let mut server = mockito::Server::new();
1547 let comment = |at: &str| {
1548 json!({"createdAt": at, "updatedAt": at, "url": "u",
1549 "issue": pr("o/r", 1, false), "pullRequest": null})
1550 };
1551 let mock = server
1552 .mock("POST", "/graphql")
1553 .with_body(graphql_body(
1554 json!({"user": {"issueComments": {
1555 "pageInfo": {"hasNextPage": true, "endCursor": "next"},
1556 "nodes": [comment("2026-02-02T00:00:00Z"), null, comment("2026-01-02T00:00:00Z"), null]
1557 }}}),
1558 json!([{"message": "withheld"}]),
1559 ))
1560 .expect(1)
1561 .create();
1562 let client = Client::new(&server.url(), "tok").unwrap();
1563 let c = client.issue_comments("me", day("2026-02-01")).unwrap();
1564 mock.assert();
1565 assert_eq!(c.comments.len(), 1);
1566 assert_eq!(c.comments[0].issue.as_ref().unwrap().number, 1);
1567 assert_eq!(c.unreadable.count, 1);
1568 let mut server = mockito::Server::new();
1570 server
1571 .mock("POST", "/graphql")
1572 .with_body(graphql_body(json!({"user": null}), json!(null)))
1573 .create();
1574 let client = Client::new(&server.url(), "tok").unwrap();
1575 assert!(client.issue_comments("ghost", day("2026-02-01")).is_err());
1576 let mut server = mockito::Server::new();
1578 server
1579 .mock("POST", "/graphql")
1580 .with_body(graphql_body(json!(null), json!([{"message": "bad query"}])))
1581 .create();
1582 let client = Client::new(&server.url(), "tok").unwrap();
1583 let err = client
1584 .contributions("me", day("2026-01-01"), day("2026-01-02"))
1585 .unwrap_err();
1586 assert_eq!(err.to_string(), "GitHub GraphQL: bad query");
1587 assert_eq!(
1588 graphql_failure(None).to_string(),
1589 "GitHub GraphQL: no data in the answer"
1590 );
1591 }
1592
1593 #[test]
1594 fn private_repos_are_read_until_an_older_push() {
1595 let mut server = mockito::Server::new();
1596 let mock = server
1597 .mock("GET", "/user/repos")
1598 .match_query(mockito::Matcher::AllOf(vec![
1599 mockito::Matcher::UrlEncoded("visibility".into(), "private".into()),
1600 mockito::Matcher::UrlEncoded("sort".into(), "pushed".into()),
1601 mockito::Matcher::UrlEncoded("page".into(), "1".into()),
1602 ]))
1603 .with_body(
1604 json!([
1605 {"full_name": "o/new", "pushed_at": "2026-02-20T00:00:00Z"},
1606 {"full_name": "o/empty", "pushed_at": null},
1607 {"full_name": "o/newer", "pushed_at": "2026-02-10T00:00:00Z"},
1608 {"full_name": "o/old", "pushed_at": "2025-01-01T00:00:00Z"}
1609 ])
1610 .to_string(),
1611 )
1612 .create();
1613 let client = Client::new(&server.url(), "tok").unwrap();
1614 assert_eq!(
1615 client
1616 .private_repos_pushed_since(day("2026-02-01"))
1617 .unwrap(),
1618 ["o/new", "o/newer"]
1619 );
1620 mock.assert();
1621 }
1622
1623 #[test]
1624 fn annotated_tags_are_read_ten_repos_to_a_query() {
1625 let mut server = mockito::Server::new();
1626 let tagger = json!({"name": "Me", "email": null, "date": "2026-02-10T23:30:00-05:00"});
1629 let mock = server
1630 .mock("POST", "/graphql")
1631 .match_body(mockito::Matcher::AllOf(vec![
1632 mockito::Matcher::Regex(r#""o0":"o""#.into()),
1633 mockito::Matcher::Regex(r#""n0":"a""#.into()),
1634 mockito::Matcher::Regex(r#""n1":"gone""#.into()),
1635 ]))
1636 .with_body(graphql_body(
1637 json!({
1638 "r0": {"refs": {"nodes": [
1639 {"name": "v1", "target": {"tagger": tagger}},
1640 {"name": "undated", "target": {"tagger": {"name": "Me", "email": "e", "date": null}}},
1641 {"name": "light", "target": {}}
1642 ]}},
1643 "r1": null
1644 }),
1645 json!([{"message": "Could not resolve to a Repository"}]),
1646 ))
1647 .create();
1648 let client = Client::new(&server.url(), "tok").unwrap();
1649 let recent = client.recent_annotated_tags(&[
1650 "o/a".to_string(),
1651 "o/gone".to_string(),
1652 "bad".to_string(),
1653 ]);
1654 mock.assert();
1655 assert!(recent.failures.is_empty());
1656 assert_eq!(recent.tags.len(), 1);
1657 let tags = &recent.tags["o/a"];
1658 assert_eq!(tags.len(), 1);
1659 assert_eq!(tags[0].tag, "v1");
1660 assert_eq!(tags[0].tagger.email, "");
1661 assert_eq!(tags[0].tagger.date, "2026-02-11T04:30:00Z");
1662 assert!(
1664 client
1665 .recent_annotated_tags(&["bad".to_string()])
1666 .tags
1667 .is_empty()
1668 );
1669 let mut down = mockito::Server::new();
1671 down.mock("POST", "/graphql").with_status(502).create();
1672 let client = Client::new(&down.url(), "tok").unwrap();
1673 let recent = client.recent_annotated_tags(&["o/a".to_string()]);
1674 assert!(recent.tags.is_empty());
1675 assert_eq!(recent.failures.len(), 1);
1676 assert!(
1677 recent.failures[0].starts_with("o/a: "),
1678 "{:?}",
1679 recent.failures
1680 );
1681 }
1682
1683 #[test]
1684 fn commits_are_counted_twenty_five_repos_to_a_query() {
1685 let mut server = mockito::Server::new();
1686 let id = server
1687 .mock("POST", "/graphql")
1688 .match_body(mockito::Matcher::Regex(
1689 "user\\(login: \\$login\\) \\{ id \\}".into(),
1690 ))
1691 .with_body(graphql_body(json!({"user": {"id": "U_1"}}), json!(null)))
1692 .create();
1693 let history =
1694 |n: u64| json!({"defaultBranchRef": {"target": {"history": {"totalCount": n}}}});
1695 let counts = server
1696 .mock("POST", "/graphql")
1697 .match_body(mockito::Matcher::AllOf(vec![
1698 mockito::Matcher::Regex("history\\(author".into()),
1699 mockito::Matcher::Regex(r#""id":"U_1""#.into()),
1700 mockito::Matcher::Regex(r#""since":"2026-02-01T00:00:00Z""#.into()),
1701 ]))
1702 .with_body(graphql_body(
1703 json!({"r0": history(3), "r1": history(0), "r2": null, "r3": {"defaultBranchRef": null}}),
1704 json!([{"message": "Could not resolve"}]),
1705 ))
1706 .create();
1707 let client = Client::new(&server.url(), "tok").unwrap();
1708 let repos: Vec<String> = ["o/a", "o/none", "o/gone", "o/empty"]
1709 .map(String::from)
1710 .into();
1711 let c = client
1712 .commit_counts("me", &repos, day("2026-02-01"), day("2026-02-28"))
1713 .unwrap();
1714 id.assert();
1715 counts.assert();
1716 assert_eq!(c.counts, BTreeMap::from([("o/a".to_string(), 3)]));
1717 assert!(c.failures.is_empty());
1718 assert!(
1720 client
1721 .commit_counts("me", &[], day("2026-02-01"), day("2026-02-28"))
1722 .unwrap()
1723 .counts
1724 .is_empty()
1725 );
1726 }
1727
1728 #[test]
1729 fn the_token_names_its_owner() {
1730 let mut server = mockito::Server::new();
1731 server
1732 .mock("GET", "/user")
1733 .with_body(r#"{"id": 1, "login": "me"}"#)
1734 .create();
1735 let client = Client::new(&server.url(), "tok").unwrap();
1736 assert_eq!(client.token_login().unwrap(), "me");
1737 }
1738
1739 #[test]
1740 fn pull_request_reads_head_and_base() {
1741 let mut server = mockito::Server::new();
1742 let mock = server
1743 .mock("GET", "/repos/o/r/pulls/92")
1744 .with_status(200)
1745 .with_body(
1746 r#"{"number": 92, "state": "closed", "merged": false,
1747 "head": {"ref": "fix", "sha": "8b8aa8b"},
1748 "base": {"ref": "main", "sha": "0000000"}}"#,
1749 )
1750 .create();
1751 let client = Client::new(&server.url(), "tok").unwrap();
1752 let pr = client.pull_request("o", "r", 92).unwrap();
1753 mock.assert();
1754 assert_eq!(pr.head.sha, "8b8aa8b");
1755 assert_eq!(pr.base.ref_name, "main");
1756 assert!(!pr.merged);
1757 }
1758
1759 #[test]
1760 fn branch_commits_by_filters_by_author_and_since() {
1761 let mut server = mockito::Server::new();
1762 let mock = server
1763 .mock("GET", "/repos/o/r/commits")
1764 .match_query(mockito::Matcher::AllOf(vec![
1765 mockito::Matcher::UrlEncoded("sha".into(), "main".into()),
1766 mockito::Matcher::UrlEncoded("author".into(), "michel-slm".into()),
1767 mockito::Matcher::UrlEncoded("since".into(), "2026-03-04T00:00:00Z".into()),
1768 ]))
1769 .with_status(200)
1770 .with_body(
1771 r#"[{"sha": "abc", "commit": {"message": "Ignore it\n\nbody",
1772 "author": {"name": "Michel Lind", "email": "m@example.org"}}}]"#,
1773 )
1774 .create();
1775 let client = Client::new(&server.url(), "tok").unwrap();
1776 let commits = client
1777 .branch_commits_by("o", "r", "main", "michel-slm", "2026-03-04T00:00:00Z")
1778 .unwrap();
1779 mock.assert();
1780 assert_eq!(commits[0].title(), "Ignore it");
1781 assert_eq!(
1782 commits[0].commit.author.as_ref().unwrap().name,
1783 "Michel Lind"
1784 );
1785 }
1786
1787 #[test]
1788 fn commit_contained_reads_ahead_by() {
1789 let mut server = mockito::Server::new();
1792 let mock = server
1793 .mock("GET", "/repos/o/r/compare/main...8b8aa8b")
1794 .with_status(200)
1795 .with_body(r#"{"status": "behind", "ahead_by": 0, "behind_by": 4}"#)
1796 .create();
1797 let client = Client::new(&server.url(), "tok").unwrap();
1798 assert!(
1799 client
1800 .commit_contained("o", "r", "main", "8b8aa8b")
1801 .unwrap()
1802 );
1803 mock.assert();
1804
1805 let mut server = mockito::Server::new();
1806 server
1807 .mock("GET", "/repos/o/r/compare/main...other")
1808 .with_status(200)
1809 .with_body(r#"{"status": "diverged", "ahead_by": 2, "behind_by": 4}"#)
1810 .create();
1811 let client = Client::new(&server.url(), "tok").unwrap();
1812 assert!(!client.commit_contained("o", "r", "main", "other").unwrap());
1813 }
1814
1815 #[test]
1816 fn new_rejects_plaintext_remote() {
1817 assert!(Client::new("http://api.example.com", "tok").is_err());
1819 }
1820
1821 #[test]
1822 fn user_by_username_returns_user() {
1823 let mut server = mockito::Server::new();
1824 let mock = server
1825 .mock("GET", "/users/octocat")
1826 .match_header("authorization", "Bearer tok")
1827 .with_status(200)
1828 .with_body(r#"{"id": 1, "login": "octocat"}"#)
1829 .create();
1830 let client = Client::new(&server.url(), "tok").unwrap();
1831 let user = client.user_by_username("octocat").unwrap().unwrap();
1832 assert_eq!(user.id, 1);
1833 assert_eq!(user.login, "octocat");
1834 mock.assert();
1835 }
1836
1837 #[test]
1838 fn repository_public_reads_the_private_flag() {
1839 let mut server = mockito::Server::new();
1840 let public = server
1841 .mock("GET", "/repos/o/pub")
1842 .with_body(r#"{"id": 1, "private": false}"#)
1843 .create();
1844 let private = server
1845 .mock("GET", "/repos/o/priv")
1846 .with_body(r#"{"id": 2, "private": true}"#)
1847 .create();
1848 let gone = server
1849 .mock("GET", "/repos/o/gone")
1850 .with_status(404)
1851 .create();
1852 let broken = server.mock("GET", "/repos/o/err").with_status(500).create();
1853 let client = Client::new(&server.url(), "tok").unwrap();
1854 assert_eq!(client.repository_public("o", "pub").unwrap(), Some(true));
1855 assert_eq!(client.repository_public("o", "priv").unwrap(), Some(false));
1856 assert_eq!(client.repository_public("o", "gone").unwrap(), None);
1857 assert!(client.repository_public("o", "err").is_err());
1858 for m in [public, private, gone, broken] {
1859 m.assert();
1860 }
1861 }
1862
1863 #[test]
1864 fn user_by_username_404_is_none() {
1865 let mut server = mockito::Server::new();
1866 let mock = server
1867 .mock("GET", "/users/ghost")
1868 .with_status(404)
1869 .with_body(r#"{"message": "Not Found"}"#)
1870 .create();
1871 let client = Client::new(&server.url(), "tok").unwrap();
1872 assert!(client.user_by_username("ghost").unwrap().is_none());
1873 mock.assert();
1874 }
1875
1876 #[test]
1877 fn search_pull_requests_paginates() {
1878 let mut server = mockito::Server::new();
1879 let items_page1 = (1..=100)
1881 .map(|i| {
1882 format!(
1883 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"}}}}"#
1884 )
1885 })
1886 .collect::<Vec<_>>()
1887 .join(",");
1888 let mock_p1 = server
1889 .mock("GET", "/search/issues")
1890 .match_query(mockito::Matcher::AllOf(vec![
1891 mockito::Matcher::UrlEncoded("page".into(), "1".into()),
1892 mockito::Matcher::UrlEncoded("per_page".into(), "100".into()),
1893 ]))
1894 .with_status(200)
1895 .with_body(format!(
1896 r#"{{"total_count":105,"incomplete_results":false,"items":[{items_page1}]}}"#
1897 ))
1898 .create();
1899 let mock_p2 = server
1900 .mock("GET", "/search/issues")
1901 .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
1902 .with_status(200)
1903 .with_body(
1904 r#"{"total_count":105,"incomplete_results":false,"items":[
1905 {"number":101,"title":"x","state":"open","html_url":"https://github.com/o/r/pull/101"},
1906 {"number":102,"title":"y","state":"open","html_url":"https://github.com/o/r/pull/102"},
1907 {"number":103,"title":"z","state":"open","html_url":"https://github.com/o/r/pull/103"},
1908 {"number":104,"title":"w","state":"open","html_url":"https://github.com/o/r/pull/104"},
1909 {"number":105,"title":"v","state":"open","html_url":"https://github.com/o/r/pull/105"}
1910 ]}"#,
1911 )
1912 .create();
1913 let client = Client::new(&server.url(), "tok").unwrap();
1914 let prs = client
1915 .search_pull_requests("type:pr author:octocat")
1916 .unwrap();
1917 assert_eq!(prs.len(), 105);
1918 mock_p1.assert();
1919 mock_p2.assert();
1920 }
1921
1922 #[test]
1923 fn pull_request_repo_slug_from_html_url() {
1924 let pr = PullRequest {
1925 number: 42,
1926 title: "x".into(),
1927 state: "open".into(),
1928 pull_request: None,
1929 html_url: "https://github.com/slopfest/sandogasa/pull/42".into(),
1930 repository_url: None,
1931 };
1932 assert_eq!(pr.repo_slug().as_deref(), Some("slopfest/sandogasa"));
1933 }
1934
1935 #[test]
1936 fn pull_request_repo_slug_from_repository_url() {
1937 let pr = PullRequest {
1938 number: 42,
1939 title: "x".into(),
1940 state: "open".into(),
1941 pull_request: None,
1942 html_url: "https://github.com/o/r/issues/42".into(),
1943 repository_url: Some("https://api.github.com/repos/slopfest/sandogasa".into()),
1944 };
1945 let pr2 = PullRequest {
1947 html_url: "garbage".into(),
1948 ..pr
1949 };
1950 assert_eq!(pr2.repo_slug().as_deref(), Some("slopfest/sandogasa"));
1951 }
1952
1953 #[test]
1954 fn pull_request_merged_at_via_helper() {
1955 let pr: PullRequest = serde_json::from_str(
1956 r#"{"number":1,"title":"t","state":"closed",
1957 "html_url":"https://github.com/o/r/pull/1",
1958 "pull_request":{"merged_at":"2026-02-01T10:00:00Z"}}"#,
1959 )
1960 .unwrap();
1961 assert_eq!(pr.merged_at(), Some("2026-02-01T10:00:00Z"));
1962 }
1963
1964 #[test]
1965 fn user_events_pagination_stops_at_300() {
1966 let mut server = mockito::Server::new();
1967 let make_event = |i: u64| {
1971 format!(
1972 r#"{{"id":"{i}","type":"PushEvent","repo":{{"id":1,"name":"o/r"}},"created_at":"2026-02-15T10:00:00Z"}}"#
1973 )
1974 };
1975 let page1: String = (1..=100).map(make_event).collect::<Vec<_>>().join(",");
1976 let page2: String = (101..=200).map(make_event).collect::<Vec<_>>().join(",");
1977 let page3: String = (201..=250).map(make_event).collect::<Vec<_>>().join(",");
1978 let m1 = server
1979 .mock("GET", "/users/octocat/events")
1980 .match_query(mockito::Matcher::UrlEncoded("page".into(), "1".into()))
1981 .with_status(200)
1982 .with_body(format!("[{page1}]"))
1983 .create();
1984 let m2 = server
1985 .mock("GET", "/users/octocat/events")
1986 .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
1987 .with_status(200)
1988 .with_body(format!("[{page2}]"))
1989 .create();
1990 let m3 = server
1991 .mock("GET", "/users/octocat/events")
1992 .match_query(mockito::Matcher::UrlEncoded("page".into(), "3".into()))
1993 .with_status(200)
1994 .with_body(format!("[{page3}]"))
1995 .create();
1996 let client = Client::new(&server.url(), "tok").unwrap();
1997 let events = client.user_events("octocat").unwrap();
1998 assert_eq!(events.len(), 250);
1999 m1.assert();
2000 m2.assert();
2001 m3.assert();
2002 }
2003
2004 #[test]
2005 fn count_authored_commits_paginates_and_handles_409() {
2006 let mut server = mockito::Server::new();
2007 let m1 = server
2008 .mock("GET", "/repos/o/r/commits")
2009 .match_query(mockito::Matcher::UrlEncoded("page".into(), "1".into()))
2010 .with_status(200)
2011 .with_body(format!("[{}]", vec!["{}"; 100].join(",")))
2012 .create();
2013 let m2 = server
2014 .mock("GET", "/repos/o/r/commits")
2015 .match_query(mockito::Matcher::UrlEncoded("page".into(), "2".into()))
2016 .with_status(200)
2017 .with_body("[{},{}]")
2018 .create();
2019 let client = Client::new(&server.url(), "tok").unwrap();
2020 let n = client
2021 .count_authored_commits(
2022 "o",
2023 "r",
2024 "octocat",
2025 chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(),
2026 chrono::NaiveDate::from_ymd_opt(2026, 3, 31).unwrap(),
2027 )
2028 .unwrap();
2029 assert_eq!(n, 102);
2030 m1.assert();
2031 m2.assert();
2032 }
2033
2034 #[test]
2035 fn count_authored_commits_empty_repo_returns_zero() {
2036 let mut server = mockito::Server::new();
2037 let mock = server
2038 .mock("GET", "/repos/o/empty/commits")
2039 .match_query(mockito::Matcher::Any)
2040 .with_status(409)
2041 .with_body(r#"{"message":"Git Repository is empty."}"#)
2042 .create();
2043 let client = Client::new(&server.url(), "tok").unwrap();
2044 let n = client
2045 .count_authored_commits(
2046 "o",
2047 "empty",
2048 "x",
2049 chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(),
2050 chrono::NaiveDate::from_ymd_opt(2026, 3, 31).unwrap(),
2051 )
2052 .unwrap();
2053 assert_eq!(n, 0);
2054 mock.assert();
2055 }
2056
2057 #[test]
2058 fn validate_token_distinguishes_invalid_from_error() {
2059 let mut server = mockito::Server::new();
2060 let ok = server
2062 .mock("GET", "/user")
2063 .match_header("authorization", "Bearer good")
2064 .with_status(200)
2065 .with_body(r#"{"id": 1, "login": "octocat"}"#)
2066 .create();
2067 assert!(validate_token(&server.url(), "good").unwrap());
2068 ok.assert();
2069 let bad = server
2071 .mock("GET", "/user")
2072 .match_header("authorization", "Bearer bad")
2073 .with_status(401)
2074 .with_body(r#"{"message": "Bad credentials"}"#)
2075 .create();
2076 assert!(!validate_token(&server.url(), "bad").unwrap());
2077 bad.assert();
2078 }
2079
2080 #[test]
2081 fn repository_slug_prefers_full_name() {
2082 let repo = Repository {
2083 id: 1,
2084 full_name: Some("o/r".into()),
2085 name: Some("ignored".into()),
2086 };
2087 assert_eq!(repo.slug(), Some("o/r"));
2088 let evt_repo = Repository {
2090 id: 1,
2091 full_name: None,
2092 name: Some("o/r".into()),
2093 };
2094 assert_eq!(evt_repo.slug(), Some("o/r"));
2095 }
2096}