Skip to main content

github_rust/github/
accounts.rs

1//! Authenticated account and owned-repository collections.
2use super::{
3    pagination::{Connection, FetchOptions, Tracker},
4    response,
5    types::Language,
6};
7use crate::{GitHubClient, GitHubError, Result};
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10use serde_json::json;
11
12#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
13pub struct Account {
14    pub node_id: String,
15    pub login: String,
16    pub name: Option<String>,
17    pub avatar_url: String,
18}
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct Viewer {
21    pub account: Account,
22    /// All organizations visible to the token, sorted by login.
23    pub organizations: Vec<Account>,
24}
25/// Lightweight inventory metadata, including separate counts of open issues and PRs.
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct RepositorySummary {
28    pub node_id: String,
29    pub name: String,
30    pub name_with_owner: String,
31    pub description: Option<String>,
32    pub url: String,
33    pub is_private: bool,
34    pub is_fork: bool,
35    pub is_archived: bool,
36    pub stargazer_count: u32,
37    pub fork_count: u32,
38    pub pushed_at: Option<DateTime<Utc>>,
39    pub updated_at: DateTime<Utc>,
40    pub primary_language: Option<Language>,
41    pub open_issue_count: u32,
42    pub open_pull_request_count: u32,
43}
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct OwnedRepositories {
46    pub owner: Account,
47    pub repositories: Vec<RepositorySummary>,
48}
49/// A validated page. Earlier pages remain provisional until the whole call succeeds.
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct RepositoryPage {
52    pub owner: Account,
53    pub repositories: Vec<RepositorySummary>,
54    pub total_count: usize,
55    pub has_next_page: bool,
56}
57#[derive(Deserialize)]
58#[serde(rename_all = "camelCase")]
59struct AccountDto {
60    id: String,
61    login: String,
62    name: Option<String>,
63    avatar_url: String,
64}
65impl From<AccountDto> for Account {
66    fn from(v: AccountDto) -> Self {
67        Self {
68            node_id: v.id,
69            login: v.login,
70            name: v.name,
71            avatar_url: v.avatar_url,
72        }
73    }
74}
75#[derive(Deserialize)]
76#[serde(rename_all = "camelCase")]
77struct RepositoryDto {
78    id: String,
79    name: String,
80    name_with_owner: String,
81    description: Option<String>,
82    url: String,
83    is_private: bool,
84    is_fork: bool,
85    is_archived: bool,
86    stargazer_count: u32,
87    fork_count: u32,
88    pushed_at: Option<DateTime<Utc>>,
89    updated_at: DateTime<Utc>,
90    primary_language: Option<Language>,
91    issues: Count,
92    pull_requests: Count,
93}
94#[derive(Deserialize)]
95#[serde(rename_all = "camelCase")]
96pub(crate) struct Count {
97    pub total_count: u32,
98}
99impl From<RepositoryDto> for RepositorySummary {
100    fn from(v: RepositoryDto) -> Self {
101        Self {
102            node_id: v.id,
103            name: v.name,
104            name_with_owner: v.name_with_owner,
105            description: v.description,
106            url: v.url,
107            is_private: v.is_private,
108            is_fork: v.is_fork,
109            is_archived: v.is_archived,
110            stargazer_count: v.stargazer_count,
111            fork_count: v.fork_count,
112            pushed_at: v.pushed_at,
113            updated_at: v.updated_at,
114            primary_language: v.primary_language,
115            open_issue_count: v.issues.total_count,
116            open_pull_request_count: v.pull_requests.total_count,
117        }
118    }
119}
120pub(crate) fn require_token(client: &GitHubClient) -> Result<()> {
121    if !client.has_token() {
122        return Err(GitHubError::AuthenticationError(
123            "This operation requires a token".into(),
124        ));
125    }
126    Ok(())
127}
128pub(crate) fn validate_owner(owner: &str) -> Result<()> {
129    // Underscores also accommodate Enterprise Managed User logins.
130    if owner.is_empty()
131        || owner.len() > 100
132        || !owner
133            .bytes()
134            .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
135    {
136        return Err(GitHubError::InvalidInput("Invalid owner login".into()));
137    }
138    Ok(())
139}
140pub(crate) async fn query<T: serde::de::DeserializeOwned>(
141    client: &GitHubClient,
142    query: &str,
143    variables: serde_json::Value,
144) -> Result<T> {
145    response::graphql(
146        client
147            .post(client.graphql_url())
148            .json(&json!({"query": query, "variables": variables}))
149            .send()
150            .await?,
151    )
152    .await
153}
154pub(crate) async fn viewer(client: &GitHubClient, options: FetchOptions) -> Result<Viewer> {
155    require_token(client)?;
156    #[derive(Deserialize)]
157    struct Data {
158        viewer: ViewerDto,
159    }
160    #[derive(Deserialize)]
161    struct ViewerDto {
162        #[serde(flatten)]
163        account: AccountDto,
164        organizations: Connection<AccountDto>,
165    }
166    let mut tracker = Tracker::default();
167    let mut result: Option<Viewer> = None;
168    loop {
169        let data: Data = query(
170            client,
171            include_str!("queries/viewer.graphql"),
172            json!({"first": options.page_size, "cursor": tracker.cursor}),
173        )
174        .await?;
175        let account: Account = data.viewer.account.into();
176        if account.node_id.is_empty()
177            || result.as_ref().is_some_and(|v| {
178                v.account.node_id != account.node_id || v.account.login != account.login
179            })
180        {
181            return Err(GitHubError::PaginationError(
182                "Viewer changed during pagination".into(),
183            ));
184        }
185        tracker.accept(&data.viewer.organizations, options, |a| &a.id)?;
186        let result = result.get_or_insert_with(|| Viewer {
187            account,
188            organizations: vec![],
189        });
190        result
191            .organizations
192            .extend(data.viewer.organizations.nodes.into_iter().map(Into::into));
193        if tracker.cursor.is_none() {
194            result.organizations.sort_by(|a, b| a.login.cmp(&b.login));
195            break;
196        }
197    }
198    Ok(result.expect("at least one page"))
199}
200pub(crate) async fn repositories<F>(
201    client: &GitHubClient,
202    login: &str,
203    options: FetchOptions,
204    mut progress: Option<F>,
205) -> Result<OwnedRepositories>
206where
207    F: AsyncFnMut(&RepositoryPage) -> Result<()>,
208{
209    validate_owner(login)?;
210    require_token(client)?;
211    #[derive(Deserialize)]
212    struct Data {
213        #[serde(rename = "repositoryOwner")]
214        owner: Option<OwnerDto>,
215    }
216    #[derive(Deserialize)]
217    struct OwnerDto {
218        #[serde(flatten)]
219        account: AccountDto,
220        repositories: Connection<RepositoryDto>,
221    }
222    let mut tracker = Tracker::default();
223    let mut result: Option<OwnedRepositories> = None;
224    loop {
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.into()))?;
234        let account: Account = owner.account.into();
235        if account.node_id.is_empty()
236            || !account.login.eq_ignore_ascii_case(login)
237            || result.as_ref().is_some_and(|r| {
238                r.owner.node_id != account.node_id || r.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 result = result.get_or_insert_with(|| OwnedRepositories {
262            owner: account,
263            repositories: vec![],
264        });
265        if let Some(callback) = &mut progress {
266            callback(&page).await?;
267        }
268        result.repositories.extend(page.repositories);
269        if tracker.cursor.is_none() {
270            result
271                .repositories
272                .sort_by(|a, b| a.name_with_owner.cmp(&b.name_with_owner));
273            break;
274        }
275    }
276    Ok(result.expect("at least one page"))
277}