1use super::{
3 pagination::{Connection, FetchOptions, Tracker},
4 response,
5 types::Language,
6};
7use crate::{GitHubClient, GitHubError, Result};
8use chrono::{DateTime, Utc};
9use futures_util::{Stream, TryStreamExt, stream};
10use serde::{Deserialize, Serialize};
11use serde_json::json;
12
13#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
14pub struct Account {
15 pub node_id: String,
16 pub login: String,
17 pub name: Option<String>,
18 pub avatar_url: String,
19}
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct Viewer {
22 pub account: Account,
23 pub organizations: Vec<Account>,
25}
26#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct RepositorySummary {
29 pub node_id: String,
30 pub name: String,
31 pub name_with_owner: String,
32 pub description: Option<String>,
33 pub url: String,
34 pub is_private: bool,
35 pub is_fork: bool,
36 pub is_archived: bool,
37 pub stargazer_count: u32,
38 pub fork_count: u32,
39 pub pushed_at: Option<DateTime<Utc>>,
40 pub updated_at: DateTime<Utc>,
41 pub primary_language: Option<Language>,
42 pub open_issue_count: u32,
43 pub open_pull_request_count: u32,
44}
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct OwnedRepositories {
47 pub owner: Account,
48 pub repositories: Vec<RepositorySummary>,
49}
50#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct RepositoryPage {
53 pub owner: Account,
54 pub repositories: Vec<RepositorySummary>,
55 pub total_count: usize,
56 pub has_next_page: bool,
57}
58#[derive(Deserialize)]
59#[serde(rename_all = "camelCase")]
60struct AccountDto {
61 id: String,
62 login: String,
63 name: Option<String>,
64 avatar_url: String,
65}
66impl From<AccountDto> for Account {
67 fn from(v: AccountDto) -> Self {
68 Self {
69 node_id: v.id,
70 login: v.login,
71 name: v.name,
72 avatar_url: v.avatar_url,
73 }
74 }
75}
76#[derive(Deserialize)]
77#[serde(rename_all = "camelCase")]
78struct RepositoryDto {
79 id: String,
80 name: String,
81 name_with_owner: String,
82 description: Option<String>,
83 url: String,
84 is_private: bool,
85 is_fork: bool,
86 is_archived: bool,
87 stargazer_count: u32,
88 fork_count: u32,
89 pushed_at: Option<DateTime<Utc>>,
90 updated_at: DateTime<Utc>,
91 primary_language: Option<Language>,
92 issues: Count,
93 pull_requests: Count,
94}
95#[derive(Deserialize)]
96#[serde(rename_all = "camelCase")]
97pub(crate) struct Count {
98 pub total_count: u32,
99}
100impl From<RepositoryDto> for RepositorySummary {
101 fn from(v: RepositoryDto) -> Self {
102 Self {
103 node_id: v.id,
104 name: v.name,
105 name_with_owner: v.name_with_owner,
106 description: v.description,
107 url: v.url,
108 is_private: v.is_private,
109 is_fork: v.is_fork,
110 is_archived: v.is_archived,
111 stargazer_count: v.stargazer_count,
112 fork_count: v.fork_count,
113 pushed_at: v.pushed_at,
114 updated_at: v.updated_at,
115 primary_language: v.primary_language,
116 open_issue_count: v.issues.total_count,
117 open_pull_request_count: v.pull_requests.total_count,
118 }
119 }
120}
121pub(crate) fn require_token(client: &GitHubClient) -> Result<()> {
122 if !client.has_token() {
123 return Err(GitHubError::AuthenticationError(
124 "This operation requires a token".into(),
125 ));
126 }
127 Ok(())
128}
129pub(crate) fn validate_owner(owner: &str) -> Result<()> {
130 if owner.is_empty()
132 || owner.len() > 100
133 || !owner
134 .bytes()
135 .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
136 {
137 return Err(GitHubError::InvalidInput("Invalid owner login".into()));
138 }
139 Ok(())
140}
141pub(crate) async fn query<T: serde::de::DeserializeOwned>(
142 client: &GitHubClient,
143 query: &str,
144 variables: serde_json::Value,
145) -> Result<T> {
146 response::graphql(
147 client
148 .post(client.graphql_url())
149 .json(&json!({"query": query, "variables": variables}))
150 .send()
151 .await?,
152 )
153 .await
154}
155pub(crate) async fn viewer(client: &GitHubClient, options: FetchOptions) -> Result<Viewer> {
156 require_token(client)?;
157 #[derive(Deserialize)]
158 struct Data {
159 viewer: ViewerDto,
160 }
161 #[derive(Deserialize)]
162 struct ViewerDto {
163 #[serde(flatten)]
164 account: AccountDto,
165 organizations: Connection<AccountDto>,
166 }
167 let mut tracker = Tracker::default();
168 let mut result: Option<Viewer> = None;
169 loop {
170 let data: Data = query(
171 client,
172 include_str!("queries/viewer.graphql"),
173 json!({"first": options.page_size, "cursor": tracker.cursor}),
174 )
175 .await?;
176 let account: Account = data.viewer.account.into();
177 if account.node_id.is_empty()
178 || result.as_ref().is_some_and(|v| {
179 v.account.node_id != account.node_id || v.account.login != account.login
180 })
181 {
182 return Err(GitHubError::PaginationError(
183 "Viewer changed during pagination".into(),
184 ));
185 }
186 tracker.accept(&data.viewer.organizations, options, |a| &a.id)?;
187 let result = result.get_or_insert_with(|| Viewer {
188 account,
189 organizations: vec![],
190 });
191 result
192 .organizations
193 .extend(data.viewer.organizations.nodes.into_iter().map(Into::into));
194 if tracker.cursor.is_none() {
195 result.organizations.sort_by(|a, b| a.login.cmp(&b.login));
196 break;
197 }
198 }
199 Ok(result.expect("at least one page"))
200}
201pub(crate) fn repository_pages(
202 client: GitHubClient,
203 login: String,
204 options: FetchOptions,
205) -> impl Stream<Item = Result<RepositoryPage>> + Send {
206 #[derive(Deserialize)]
207 struct Data {
208 #[serde(rename = "repositoryOwner")]
209 owner: Option<OwnerDto>,
210 }
211 #[derive(Deserialize)]
212 struct OwnerDto {
213 #[serde(flatten)]
214 account: AccountDto,
215 repositories: Connection<RepositoryDto>,
216 }
217 stream::try_unfold(
218 (client, login, Tracker::default(), None::<Account>, false),
219 move |(client, login, mut tracker, previous, done)| async move {
220 if done {
221 return Ok(None);
222 }
223 validate_owner(&login)?;
224 require_token(&client)?;
225 let data: Data = query(
226 &client,
227 include_str!("queries/repositories.graphql"),
228 json!({"login": login, "first": options.page_size, "cursor": tracker.cursor}),
229 )
230 .await?;
231 let owner = data
232 .owner
233 .ok_or_else(|| GitHubError::NotFoundError(login.clone()))?;
234 let account: Account = owner.account.into();
235 if account.node_id.is_empty()
236 || !account.login.eq_ignore_ascii_case(&login)
237 || previous.as_ref().is_some_and(|owner| {
238 owner.node_id != account.node_id || owner.login != account.login
239 })
240 || owner.repositories.nodes.iter().any(|r| {
241 !r.name_with_owner
242 .eq_ignore_ascii_case(&format!("{}/{}", account.login, r.name))
243 })
244 {
245 return Err(GitHubError::PaginationError(
246 "Repository owner changed during pagination".into(),
247 ));
248 }
249 tracker.accept(&owner.repositories, options, |r| &r.id)?;
250 let page = RepositoryPage {
251 owner: account.clone(),
252 total_count: owner.repositories.total_count,
253 has_next_page: owner.repositories.page_info.has_next_page,
254 repositories: owner
255 .repositories
256 .nodes
257 .into_iter()
258 .map(Into::into)
259 .collect(),
260 };
261 let done = tracker.cursor.is_none();
262 Ok(Some((page, (client, login, tracker, Some(account), done))))
263 },
264 )
265}
266
267pub(crate) async fn repositories<F>(
268 client: &GitHubClient,
269 login: &str,
270 options: FetchOptions,
271 mut progress: Option<F>,
272) -> Result<OwnedRepositories>
273where
274 F: AsyncFnMut(&RepositoryPage) -> Result<()>,
275{
276 let pages = repository_pages(client.clone(), login.to_owned(), options);
277 futures_util::pin_mut!(pages);
278 let mut result: Option<OwnedRepositories> = None;
279 while let Some(page) = pages.try_next().await? {
280 if let Some(callback) = &mut progress {
281 callback(&page).await?;
282 }
283 let result = result.get_or_insert_with(|| OwnedRepositories {
284 owner: page.owner,
285 repositories: vec![],
286 });
287 result.repositories.extend(page.repositories);
288 }
289 let mut result = result.expect("at least one page");
290 result
291 .repositories
292 .sort_by(|a, b| a.name_with_owner.cmp(&b.name_with_owner));
293 Ok(result)
294}