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::query,
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    /// All organizations visible to the token, sorted by login.
24    pub organizations: Vec<Account>,
25}
26/// Lightweight inventory metadata, including separate counts of open issues and PRs.
27#[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/// A validated page. Earlier pages remain provisional until the whole call succeeds.
51#[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    // Underscores also accommodate Enterprise Managed User logins.
131    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 viewer(client: &GitHubClient, options: FetchOptions) -> Result<Viewer> {
142    require_token(client)?;
143    #[derive(Deserialize)]
144    struct Data {
145        viewer: ViewerDto,
146    }
147    #[derive(Deserialize)]
148    struct ViewerDto {
149        #[serde(flatten)]
150        account: AccountDto,
151        organizations: Connection<AccountDto>,
152    }
153    let mut tracker = Tracker::default();
154    let mut result: Option<Viewer> = None;
155    loop {
156        let data: Data = query(
157            client,
158            include_str!("queries/viewer.graphql"),
159            json!({"first": options.page_size, "cursor": tracker.cursor}),
160        )
161        .await?;
162        let account: Account = data.viewer.account.into();
163        if account.node_id.is_empty()
164            || result.as_ref().is_some_and(|v| {
165                v.account.node_id != account.node_id || v.account.login != account.login
166            })
167        {
168            return Err(GitHubError::PaginationError(
169                "Viewer changed during pagination".into(),
170            ));
171        }
172        tracker.accept(&data.viewer.organizations, options, |a| &a.id)?;
173        let result = result.get_or_insert_with(|| Viewer {
174            account,
175            organizations: vec![],
176        });
177        result
178            .organizations
179            .extend(data.viewer.organizations.nodes.into_iter().map(Into::into));
180        if tracker.cursor.is_none() {
181            result.organizations.sort_by(|a, b| a.login.cmp(&b.login));
182            break;
183        }
184    }
185    Ok(result.expect("at least one page"))
186}
187pub(crate) fn repository_pages(
188    client: GitHubClient,
189    login: String,
190    options: FetchOptions,
191) -> impl Stream<Item = Result<RepositoryPage>> + Send {
192    #[derive(Deserialize)]
193    struct Data {
194        #[serde(rename = "repositoryOwner")]
195        owner: Option<OwnerDto>,
196    }
197    #[derive(Deserialize)]
198    struct OwnerDto {
199        #[serde(flatten)]
200        account: AccountDto,
201        repositories: Connection<RepositoryDto>,
202    }
203    stream::try_unfold(
204        (client, login, Tracker::default(), None::<Account>, false),
205        move |(client, login, mut tracker, previous, done)| async move {
206            if done {
207                return Ok(None);
208            }
209            // Validate once, when the first page is polled, so errors stay stream items.
210            if previous.is_none() {
211                validate_owner(&login)?;
212                require_token(&client)?;
213            }
214            let data: Data = query(
215                &client,
216                include_str!("queries/repositories.graphql"),
217                json!({"login": login, "first": options.page_size, "cursor": tracker.cursor}),
218            )
219            .await?;
220            let owner = data
221                .owner
222                .ok_or_else(|| GitHubError::NotFoundError(login.clone()))?;
223            let account: Account = owner.account.into();
224            if account.node_id.is_empty()
225                || !account.login.eq_ignore_ascii_case(&login)
226                || previous.as_ref().is_some_and(|owner| {
227                    owner.node_id != account.node_id || owner.login != account.login
228                })
229                || owner.repositories.nodes.iter().any(|r| {
230                    !r.name_with_owner
231                        .eq_ignore_ascii_case(&format!("{}/{}", account.login, r.name))
232                })
233            {
234                return Err(GitHubError::PaginationError(
235                    "Repository owner changed during pagination".into(),
236                ));
237            }
238            tracker.accept(&owner.repositories, options, |r| &r.id)?;
239            let page = RepositoryPage {
240                owner: account.clone(),
241                total_count: owner.repositories.total_count,
242                has_next_page: owner.repositories.page_info.has_next_page,
243                repositories: owner
244                    .repositories
245                    .nodes
246                    .into_iter()
247                    .map(Into::into)
248                    .collect(),
249            };
250            let done = tracker.cursor.is_none();
251            Ok(Some((page, (client, login, tracker, Some(account), done))))
252        },
253    )
254}
255
256pub(crate) async fn repositories<F>(
257    client: &GitHubClient,
258    login: &str,
259    options: FetchOptions,
260    mut progress: Option<F>,
261) -> Result<OwnedRepositories>
262where
263    F: AsyncFnMut(&RepositoryPage) -> Result<()>,
264{
265    let pages = repository_pages(client.clone(), login.to_owned(), options);
266    futures_util::pin_mut!(pages);
267    let mut result: Option<OwnedRepositories> = None;
268    while let Some(page) = pages.try_next().await? {
269        if let Some(callback) = &mut progress {
270            callback(&page).await?;
271        }
272        let result = result.get_or_insert_with(|| OwnedRepositories {
273            owner: page.owner,
274            repositories: vec![],
275        });
276        result.repositories.extend(page.repositories);
277    }
278    let mut result = result.expect("at least one page");
279    result
280        .repositories
281        .sort_by(|a, b| a.name_with_owner.cmp(&b.name_with_owner));
282    Ok(result)
283}