1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
use anyhow::{bail, format_err, Context, Result};
use keyring::Entry;
use std::{
    env,
    fmt::{self, Debug},
    fs,
    path::PathBuf,
};

#[cfg(test)]
use std::sync::Once;

mod client;
mod commits;
mod git;
mod pulls;
mod repositories;
mod teams;
mod users;

pub use client::*;
pub use commits::*;
pub use git::*;
pub use pulls::*;
pub use repositories::*;
pub use teams::*;
pub use users::*;

#[cfg(test)]
static LOG: Once = Once::new();

#[cfg(test)]
fn log() {
    LOG.call_once(|| jacklog::init(Some(&"debug")).unwrap());
}

#[cfg(test)]
fn handle() -> String {
    env::var("GITHUB_HANDLE").expect("error reading GITHUB_HANDLE")
}

#[cfg(test)]
fn org() -> String {
    env::var("GITHUB_TEST_ORG").expect("error reading GITHUB_TEST_ORG")
}

#[cfg(test)]
fn repo() -> String {
    env::var("GITHUB_TEST_REPO").expect("error reading GITHUB_TEST_REPO")
}

#[cfg(test)]
fn client() -> Client {
    Client::new(&EnvironmentProvider::try_default().unwrap()).unwrap()
}

#[cfg(test)]
fn gh_client() -> Client {
    Client::new(&GitHubCliProvider::try_new().unwrap()).unwrap()
}

#[derive(Debug)]
pub struct AuthToken(String);

#[derive(Debug)]
pub struct EnvironmentProvider {
    token: String,
}

impl EnvironmentProvider {
    /// Attempt to read credentials from the environment, using the default
    /// `GITHUB_TOKEN` env var.
    ///
    /// To customize the name of the env var, use `try_new` instead.
    ///
    /// # Errors
    ///
    /// Returns an error if the credentials are missing from the environment.
    pub fn try_default() -> Result<Self> {
        Self::try_new("GITHUB_TOKEN")
    }
    /// # Errors
    ///
    /// Returns an error if the credentials are missing from the environment.
    pub fn try_new(var: &str) -> Result<Self> {
        let token = env::var(var).context(format!("{var} not set"))?;

        Ok(Self {
            token,
        })
    }
}

#[derive(Debug)]
pub struct KeychainProvider {
    token: String,
}

impl KeychainProvider {
    pub fn try_new<T: AsRef<str>>(
        service: Option<T>,
        name: Option<T>,
    ) -> Result<Self> {
        let service = match service {
            Some(s) => s.as_ref().to_string(),
            None => "buhtig".to_string(),
        };
        let name = match name {
            Some(n) => n.as_ref().to_string(),
            None => "github-token".to_string(),
        };

        let token =
            Entry::new(&service, &name)
                .get_password()
                .context(format_err!(
                    "missing secret {} for service {} in keyring",
                    name,
                    service
                ))?;

        Ok(Self {
            token,
        })
    }
}

pub trait CredentialsProvider: fmt::Debug {
    fn token(&self) -> String;
}

impl CredentialsProvider for AuthToken {
    fn token(&self) -> String {
        self.0.clone()
    }
}

impl CredentialsProvider for EnvironmentProvider {
    fn token(&self) -> String {
        self.token.clone()
    }
}

impl CredentialsProvider for KeychainProvider {
    fn token(&self) -> String {
        self.token.clone()
    }
}

#[derive(Debug)]
pub enum SortDirection {
    Asc,
    Desc,
}

/*
github.com:
    user: aengelas
    oauth_token: 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
    git_protocol: ssh
*/
#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct GitHubCliProvider {
    oauth_token: String,
}

impl GitHubCliProvider {
    pub fn try_new() -> Result<Self> {
        let path =
            PathBuf::from(env::var("HOME")?).join(".config/gh/hosts.yml");
        let cfg = fs::read_to_string(&path)?;
        let mut cfg: serde_yaml::Mapping = serde_yaml::from_str(&cfg)?;
        let host = cfg.remove("github.com").ok_or_else(|| {
            format_err!("missing host github.com in gh CLI config")
        })?;

        let oauth_token = if let serde_yaml::Value::Mapping(mut m) = host {
            m.remove("oauth_token")
                .ok_or_else(|| format_err!("missing oauth_token field"))?
        } else {
            bail!("missing oauth_token for host github.com in gh CLI config");
        };

        let oauth_token = if let serde_yaml::Value::String(s) = oauth_token {
            s
        } else {
            bail!("oauth_token is not a string");
        };

        Ok(Self {
            oauth_token,
        })
    }
}

impl CredentialsProvider for GitHubCliProvider {
    fn token(&self) -> String {
        self.oauth_token.clone()
    }
}