Skip to main content

subspace_core/credentials/
accounts.rs

1//! The github.com accounts Subspace can use: the accounts signed in through
2//! Subspace and gh's accounts, one entry per login.
3
4use super::signed_in::SignedInAccount;
5
6/// The github.com accounts: `logins` holds each login once, compared without
7/// case, with the signed-in accounts first in GitHub's spelling. `active` is
8/// gh's active account.
9#[derive(Debug, Clone, PartialEq, Eq, Default)]
10pub struct GitHubAccounts {
11    pub logins: Vec<String>,
12    pub active: Option<String>,
13    pub signed_in: Vec<SignedInAccount>,
14}
15
16/// Where an account's token comes from, for display.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum AccountSource {
19    /// Signed in through Subspace.
20    SignedIn,
21    /// Signed in through Subspace, but GitHub rejected the token.
22    SignInExpired,
23    /// The gh CLI's account.
24    GitHubCli,
25}
26
27impl AccountSource {
28    pub fn label(self) -> &'static str {
29        match self {
30            Self::SignedIn => "Signed in",
31            Self::SignInExpired => "Sign-in expired",
32            Self::GitHubCli => "GitHub CLI",
33        }
34    }
35}
36
37impl GitHubAccounts {
38    /// The saved account when it is still known, else gh's active account,
39    /// else the first one, in the list's spelling.
40    pub fn pick(&self, saved: Option<&str>) -> Option<String> {
41        let known = |login: &str| {
42            self.logins
43                .iter()
44                .find(|known| known.eq_ignore_ascii_case(login))
45                .cloned()
46        };
47        saved
48            .and_then(known)
49            .or_else(|| self.active.as_deref().and_then(known))
50            .or_else(|| self.active.clone())
51            .or_else(|| self.logins.first().cloned())
52    }
53
54    /// Where `login`'s token comes from. A signed-in account comes first,
55    /// as its token does.
56    pub fn source(&self, login: &str) -> AccountSource {
57        match self
58            .signed_in
59            .iter()
60            .find(|account| account.login.eq_ignore_ascii_case(login))
61        {
62            Some(account) if account.expired => AccountSource::SignInExpired,
63            Some(_) => AccountSource::SignedIn,
64            None => AccountSource::GitHubCli,
65        }
66    }
67
68    /// gh's accounts merged with the signed-in ones; `None` without any.
69    pub(super) fn merge(gh: Option<Self>, signed_in: Vec<SignedInAccount>) -> Option<Self> {
70        let gh = gh.unwrap_or_default();
71        let mut logins: Vec<String> = signed_in
72            .iter()
73            .map(|account| account.login.clone())
74            .collect();
75        for login in gh.logins {
76            if !logins
77                .iter()
78                .any(|known| known.eq_ignore_ascii_case(&login))
79            {
80                logins.push(login);
81            }
82        }
83        let active = gh.active.map(|active| {
84            logins
85                .iter()
86                .find(|login| login.eq_ignore_ascii_case(&active))
87                .cloned()
88                .unwrap_or(active)
89        });
90        (!logins.is_empty()).then_some(Self {
91            logins,
92            active,
93            signed_in,
94        })
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::{AccountSource, GitHubAccounts, SignedInAccount};
101
102    fn signed_in(login: &str, expired: bool) -> SignedInAccount {
103        SignedInAccount {
104            login: login.into(),
105            expired,
106        }
107    }
108
109    #[test]
110    fn the_saved_account_wins_while_it_is_still_known() {
111        let accounts = GitHubAccounts {
112            logins: vec!["Work_corp".into(), "personal".into()],
113            active: Some("personal".into()),
114            signed_in: Vec::new(),
115        };
116        assert_eq!(
117            accounts.pick(Some("work_CORP")).as_deref(),
118            Some("Work_corp")
119        );
120        assert_eq!(accounts.pick(Some("gone")).as_deref(), Some("personal"));
121        assert_eq!(accounts.pick(None).as_deref(), Some("personal"));
122        let no_active = GitHubAccounts {
123            logins: vec!["first".into(), "second".into()],
124            ..GitHubAccounts::default()
125        };
126        assert_eq!(no_active.pick(None).as_deref(), Some("first"));
127        assert_eq!(GitHubAccounts::default().pick(Some("anyone")), None);
128    }
129
130    #[test]
131    fn signed_in_and_gh_accounts_merge_once_in_github_s_spelling() {
132        let gh = GitHubAccounts {
133            logins: vec!["octo-DEV".into(), "mona".into()],
134            active: Some("octo-dev".into()),
135            signed_in: Vec::new(),
136        };
137        let merged = GitHubAccounts::merge(
138            Some(gh),
139            vec![signed_in("Octo-Dev", false), signed_in("hubot", true)],
140        )
141        .unwrap();
142        assert_eq!(merged.logins, ["Octo-Dev", "hubot", "mona"]);
143        assert_eq!(merged.active.as_deref(), Some("Octo-Dev"));
144        assert_eq!(merged.source("octo-dev"), AccountSource::SignedIn);
145        assert_eq!(merged.source("HUBOT"), AccountSource::SignInExpired);
146        assert_eq!(merged.source("mona"), AccountSource::GitHubCli);
147        assert_eq!(AccountSource::GitHubCli.label(), "GitHub CLI");
148    }
149
150    #[test]
151    fn without_gh_the_signed_in_accounts_are_the_accounts() {
152        let merged = GitHubAccounts::merge(None, vec![signed_in("octo-dev", false)]).unwrap();
153        assert_eq!(merged.logins, ["octo-dev"]);
154        assert_eq!(merged.active, None);
155        assert_eq!(merged.pick(None).as_deref(), Some("octo-dev"));
156        assert_eq!(GitHubAccounts::merge(None, Vec::new()), None);
157    }
158}