Skip to main content

git_workspace/providers/
github.rs

1use crate::providers::{build_agent, create_exclude_regex_set, create_include_regex_set, Provider};
2use crate::repository::Repository;
3use anyhow::{anyhow, bail, Context};
4use clap::ValueEnum;
5use console::style;
6use graphql_client::{GraphQLQuery, Response};
7use serde::{Deserialize, Serialize};
8use serde_json::json;
9use std::env;
10use std::fmt;
11use std::process::Command;
12use url::Url;
13
14// See https://github.com/graphql-rust/graphql-client/blob/master/graphql_client/tests/custom_scalars.rs#L6
15type GitSSHRemote = String;
16#[allow(clippy::upper_case_acronyms)]
17type URI = String;
18
19#[derive(GraphQLQuery)]
20#[graphql(
21    schema_path = "src/providers/graphql/github/schema.graphql",
22    query_path = "src/providers/graphql/github/projects.graphql",
23    response_derives = "Debug"
24)]
25pub struct Repositories;
26
27fn default_env_var() -> String {
28    String::from("GITHUB_TOKEN")
29}
30
31static DEFAULT_GITHUB_URL: &str = "https://api.github.com/graphql";
32
33fn public_github_url() -> String {
34    DEFAULT_GITHUB_URL.to_string()
35}
36
37/// Where the API token comes from.
38///
39/// Configs written before this existed have no `auth_type` key, and fall back to
40/// `EnvVar` — which is what every such config meant.
41#[derive(
42    Deserialize, Serialize, Default, Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd, ValueEnum,
43)]
44#[serde(rename_all = "kebab-case")]
45pub enum GithubAuthType {
46    /// Read the token from the environment variable named by `--env-name`.
47    #[default]
48    EnvVar,
49    /// Ask the Github CLI for a token by running `gh auth token`.
50    GhCli,
51}
52
53#[derive(Deserialize, Serialize, Default, Debug, Eq, Ord, PartialEq, PartialOrd, clap::Parser)]
54#[serde(rename_all = "lowercase")]
55#[command(about = "Add a Github user or organization by name")]
56pub struct GithubProvider {
57    /// The name of the user or organisation to add.
58    pub name: String,
59    #[arg(long = "path", default_value = "github")]
60    /// Clone repositories to a specific base path
61    path: String,
62    #[arg(long = "env-name", short = 'e', default_value = "GITHUB_TOKEN")]
63    #[serde(default = "default_env_var")]
64    /// Environment variable containing the auth token. Unused when --auth-type
65    /// is gh-cli.
66    env_var: String,
67
68    #[arg(long = "auth-type", value_enum, default_value_t = GithubAuthType::EnvVar)]
69    #[serde(default)]
70    /// Where to read the auth token from
71    auth_type: GithubAuthType,
72
73    #[arg(long = "skip-forks")]
74    #[serde(default)]
75    /// Don't clone forked repositories
76    skip_forks: bool,
77
78    #[arg(long = "include")]
79    #[serde(default)]
80    /// Only clone repositories that match these regular expressions. The repository name
81    /// includes the user or organisation name.
82    include: Vec<String>,
83
84    #[arg(long = "auth-http")]
85    #[serde(default)]
86    /// Use HTTP authentication instead of SSH
87    auth_http: bool,
88
89    #[arg(long = "exclude")]
90    #[serde(default)]
91    /// Don't clone repositories that match these regular expressions. The repository name
92    /// includes the user or organisation name.
93    exclude: Vec<String>,
94
95    #[serde(default = "public_github_url")]
96    #[arg(long = "url", default_value = DEFAULT_GITHUB_URL)]
97    /// Github instance URL, if using Github Enterprise this should be
98    /// http(s)://HOSTNAME/api/graphql
99    pub url: String,
100}
101
102impl fmt::Display for GithubProvider {
103    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104        let auth = match self.auth_type {
105            GithubAuthType::EnvVar => {
106                format!("the token stored in {}", style(&self.env_var).green())
107            }
108            GithubAuthType::GhCli => format!("the {} CLI", style("github").green()),
109        };
110        write!(
111            f,
112            "Github user/org {} in directory {}, using {}",
113            style(&self.name.to_lowercase()).green(),
114            style(&self.path.to_lowercase()).green(),
115            auth,
116        )
117    }
118}
119
120impl GithubProvider {
121    /// The token used to authenticate against the API, from whichever source
122    /// `auth_type` selects.
123    fn fetch_token(&self) -> anyhow::Result<String> {
124        match self.auth_type {
125            GithubAuthType::EnvVar => env::var(&self.env_var)
126                .with_context(|| format!("Missing {} environment variable", self.env_var)),
127            GithubAuthType::GhCli => self.fetch_gh_cli_token(),
128        }
129    }
130
131    /// Shell out to `gh auth token`, which reads whatever credentials the user has
132    /// already set up with `gh auth login`.
133    fn fetch_gh_cli_token(&self) -> anyhow::Result<String> {
134        let mut command = Command::new("gh");
135        command.args(["auth", "token"]);
136        // Without an explicit hostname `gh` assumes github.com, which is wrong for
137        // Github Enterprise.
138        if let Some(hostname) = self.hostname() {
139            command.args(["--hostname", &hostname]);
140        }
141
142        let output = command.output().with_context(|| {
143            "Error running `gh`. Is the Github CLI installed and on your PATH? \
144             See https://cli.github.com"
145        })?;
146
147        if !output.status.success() {
148            let stderr = String::from_utf8_lossy(&output.stderr);
149            let stderr = stderr.trim();
150            if stderr.is_empty() {
151                bail!("`gh auth token` exited with {}", output.status);
152            }
153            bail!("`gh auth token` failed: {stderr}");
154        }
155
156        let token = String::from_utf8(output.stdout)
157            .context("`gh auth token` returned a token that is not valid UTF-8")?
158            .trim()
159            .to_string();
160        if token.is_empty() {
161            bail!("`gh auth token` returned an empty token. Run `gh auth login` to authenticate.");
162        }
163        Ok(token)
164    }
165
166    /// The host to pass to `gh --hostname`, derived from the API URL.
167    fn hostname(&self) -> Option<String> {
168        // The public API lives on api.github.com, but `gh` knows it as github.com.
169        if self.url == DEFAULT_GITHUB_URL {
170            return Some("github.com".to_string());
171        }
172        Url::parse(&self.url).ok()?.host_str().map(str::to_string)
173    }
174
175    fn parse_repo(
176        &self,
177        path: &str,
178        repo: &repositories::RepositoriesRepositoryOwnerRepositoriesNodes,
179    ) -> Repository {
180        let default_branch = repo
181            .default_branch_ref
182            .as_ref()
183            .map(|branch| branch.name.clone());
184        let upstream = repo.parent.as_ref().map(|parent| parent.ssh_url.clone());
185
186        Repository::new(
187            format!("{}/{}", path, repo.name_with_owner.clone()),
188            if self.auth_http {
189                repo.url.clone()
190            } else {
191                repo.ssh_url.clone()
192            },
193            default_branch,
194            upstream,
195        )
196    }
197}
198
199impl Provider for GithubProvider {
200    fn correctly_configured(&self) -> bool {
201        match self.auth_type {
202            GithubAuthType::EnvVar if env::var(&self.env_var).is_err() => {
203                println!(
204                    "{}",
205                    style(format!(
206                        "Error: {} environment variable is not defined",
207                        self.env_var
208                    ))
209                    .red()
210                );
211                if self.url == public_github_url() {
212                    println!(
213                        "Create a personal access token here: {}",
214                        style("https://github.com/settings/tokens").green()
215                    );
216                } else {
217                    println!(
218                        "Create a personal access token in your {}.",
219                        style("Github Enterprise server").green()
220                    );
221                }
222
223                println!(
224                    "Then set a {} environment variable with the value",
225                    style(&self.env_var).green()
226                );
227                return false;
228            }
229            GithubAuthType::GhCli => {
230                if let Err(e) = self.fetch_gh_cli_token() {
231                    println!("{}", style(format!("Error: {e:#}")).red());
232                    println!(
233                        "Authenticate with {} and try again.",
234                        style("gh auth login").green()
235                    );
236                    return false;
237                }
238            }
239            GithubAuthType::EnvVar => {}
240        }
241        if self.name.ends_with('/') {
242            println!(
243                "{}",
244                style("Error: Ensure that names do not end in forward slashes").red()
245            );
246            println!("You specified: {}", self.name);
247            return false;
248        }
249        true
250    }
251
252    fn fetch_repositories(&self) -> anyhow::Result<Vec<Repository>> {
253        let github_token = self.fetch_token()?;
254
255        let auth_header = match github_token.as_str() {
256            "none" => "none".to_string(),
257            token => {
258                format!("Bearer {}", token)
259            }
260        };
261
262        let mut repositories = vec![];
263
264        let mut after = None;
265
266        let include_regex_set = create_include_regex_set(&self.include)?;
267        let exclude_regex_set = create_exclude_regex_set(&self.exclude)?;
268
269        // include_forks needs to be None instead of true, as the graphql parameter has three
270        // states: false - no forks, true - only forks, none - all repositories.
271        let include_forks: Option<bool> = if self.skip_forks { Some(false) } else { None };
272
273        let agent = build_agent()?;
274
275        loop {
276            let q = Repositories::build_query(repositories::Variables {
277                login: self.name.to_lowercase(),
278                include_forks,
279                after,
280            });
281            let res = {
282                let max_retries = 3;
283                let mut last_err = None;
284                let mut response = None;
285                for attempt in 0..max_retries {
286                    // Handle the status ourselves so that a failure response can be reported
287                    // along with its body, which explains *why* GitHub rejected the query.
288                    let result = agent
289                        .post(&self.url)
290                        .config()
291                        .http_status_as_error(false)
292                        .build()
293                        .header("Authorization", &auth_header)
294                        .send_json(json!(&q));
295                    match result {
296                        Ok(resp) if resp.status().is_success() => {
297                            response = Some(resp);
298                            break;
299                        }
300                        Ok(mut resp) => {
301                            let status = resp.status().as_u16();
302                            last_err = Some(match resp.body_mut().read_to_string() {
303                                Ok(body) => anyhow!("Got status code {status}. Body: {body}"),
304                                Err(e) => {
305                                    anyhow!("Got status code {status}. Error reading body: {e}")
306                                }
307                            });
308                        }
309                        Err(e) => last_err = Some(e.into()),
310                    }
311                    if attempt < max_retries - 1 {
312                        std::thread::sleep(std::time::Duration::from_secs(1));
313                    }
314                }
315                match response {
316                    Some(resp) => resp,
317                    None => return Err(last_err.unwrap()),
318                }
319            };
320
321            let body = res.into_body().read_to_string()?;
322            let response_data: Response<repositories::ResponseData> = serde_json::from_str(&body)?;
323
324            if let Some(errors) = response_data.errors {
325                let total_errors = errors.len();
326                let combined_errors: Vec<_> = errors
327                    .into_iter()
328                    .map(|e| {
329                        let mut message_str = e.message;
330                        if let Some(path) = e.path {
331                            let path_strings: Vec<String> =
332                                path.iter().map(|p| p.to_string()).collect();
333                            message_str.push_str(format!(" ({})", path_strings.join(".")).as_str());
334                        }
335                        message_str
336                    })
337                    .collect();
338                let combined_message = combined_errors.join("\n");
339                bail!(
340                    "Received {} errors. Errors:\n{}",
341                    total_errors,
342                    combined_message
343                );
344            }
345
346            let response_repositories = response_data
347                .data
348                .with_context(|| format!("Invalid response from GitHub: {}", body))?
349                .repository_owner
350                .with_context(|| format!("Invalid response from GitHub: {}", body))?
351                .repositories;
352
353            repositories.extend(
354                response_repositories
355                    .nodes
356                    .unwrap()
357                    .iter()
358                    .map(|r| r.as_ref().unwrap())
359                    .filter(|r| !r.is_archived)
360                    .filter(|r| include_regex_set.is_match(&r.name_with_owner))
361                    .filter(|r| !exclude_regex_set.is_match(&r.name_with_owner))
362                    .map(|repo| self.parse_repo(&self.path, repo)),
363            );
364
365            if !response_repositories.page_info.has_next_page {
366                break;
367            }
368            after = response_repositories.page_info.end_cursor;
369        }
370
371        Ok(repositories)
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378    use clap::Parser;
379    use toml::toml;
380
381    /// Configs written before `auth_type` existed must keep working untouched.
382    #[test]
383    fn test_deserialize_without_auth_type() {
384        let provider: GithubProvider = toml! {
385            name = "github-group"
386            path = "github"
387            env_var = "MY_TOKEN"
388        }
389        .try_into()
390        .unwrap();
391        assert_eq!(provider.auth_type, GithubAuthType::EnvVar);
392        assert_eq!(provider.env_var, "MY_TOKEN");
393    }
394
395    #[test]
396    fn test_deserialize_without_env_var_or_auth_type() {
397        let provider: GithubProvider = toml! {
398            name = "github-group"
399            path = "github"
400        }
401        .try_into()
402        .unwrap();
403        assert_eq!(provider.auth_type, GithubAuthType::EnvVar);
404        assert_eq!(provider.env_var, default_env_var());
405    }
406
407    #[test]
408    fn test_deserialize_gh_cli_auth_type() {
409        let provider: GithubProvider = toml! {
410            name = "github-group"
411            path = "github"
412            auth_type = "gh-cli"
413        }
414        .try_into()
415        .unwrap();
416        assert_eq!(provider.auth_type, GithubAuthType::GhCli);
417    }
418
419    #[test]
420    fn test_auth_type_round_trips_through_toml() {
421        let provider: GithubProvider = toml! {
422            name = "github-group"
423            path = "github"
424            auth_type = "gh-cli"
425        }
426        .try_into()
427        .unwrap();
428        let serialized = toml::to_string(&provider).unwrap();
429        assert!(serialized.contains(r#"auth_type = "gh-cli""#));
430        assert_eq!(
431            toml::from_str::<GithubProvider>(&serialized).unwrap(),
432            provider
433        );
434    }
435
436    /// Old command lines must keep parsing, and default to the environment variable.
437    #[test]
438    fn test_cli_defaults_to_env_var() {
439        let provider = GithubProvider::parse_from(["github", "some-org"]);
440        assert_eq!(provider.auth_type, GithubAuthType::EnvVar);
441        assert_eq!(provider.env_var, default_env_var());
442    }
443
444    #[test]
445    fn test_cli_env_name_still_works() {
446        let provider = GithubProvider::parse_from(["github", "some-org", "-e", "MY_TOKEN"]);
447        assert_eq!(provider.auth_type, GithubAuthType::EnvVar);
448        assert_eq!(provider.env_var, "MY_TOKEN");
449    }
450
451    #[test]
452    fn test_cli_auth_type_gh_cli() {
453        let provider = GithubProvider::parse_from(["github", "some-org", "--auth-type", "gh-cli"]);
454        assert_eq!(provider.auth_type, GithubAuthType::GhCli);
455    }
456
457    #[test]
458    fn test_cli_rejects_unknown_auth_type() {
459        assert!(
460            GithubProvider::try_parse_from(["github", "some-org", "--auth-type", "nope"]).is_err()
461        );
462    }
463
464    #[test]
465    fn test_hostname() {
466        let hostname =
467            |url: &str| GithubProvider::parse_from(["github", "some-org", "--url", url]).hostname();
468        assert_eq!(hostname(DEFAULT_GITHUB_URL).as_deref(), Some("github.com"));
469        assert_eq!(
470            hostname("https://ghe.example.com/api/graphql").as_deref(),
471            Some("ghe.example.com")
472        );
473        assert_eq!(
474            hostname("https://ghe.example.com:8443/api/graphql").as_deref(),
475            Some("ghe.example.com")
476        );
477        assert_eq!(
478            hostname("https://user:pass@ghe.example.com/api/graphql").as_deref(),
479            Some("ghe.example.com")
480        );
481        // An unparseable URL means no --hostname, so `gh` falls back to its default.
482        assert_eq!(hostname("not a url"), None);
483    }
484}