From 2223c79e986b7c05b5221d26d0293fe7960551ef Mon Sep 17 00:00:00 2001 From: Dhruvin Shah Date: Tue, 7 Nov 2023 19:02:16 -0500 Subject: [PATCH] Adding support for Github API key resolves MordechaiHadad/bob#157 --- src/cli.rs | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 9543188..02ae9a2 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -8,9 +8,31 @@ use crate::{ use anyhow::Result; use clap::{Args, CommandFactory, Parser}; use clap_complete::Shell; -use reqwest::Client; +use reqwest::{Client, Error}; use tracing::{error, info}; +fn create_reqwest_client() -> Result { + // fetch env variable + let github_token = match std::env::var("GITHUB_TOKEN") { + Ok(token) => token, + Err(_) => String::new(), + }; + + let mut headers = reqwest::header::HeaderMap::new(); + if !github_token.is_empty() { + let auth_header_value = + reqwest::header::HeaderValue::from_str(&format!("Bearer {}", github_token)) + .expect("Invalid header value"); + headers.insert(reqwest::header::AUTHORIZATION, auth_header_value); + } + + let client = reqwest::Client::builder() + .default_headers(headers) + .build()?; + + Ok(client) +} + #[derive(Debug, Parser)] #[command(version)] enum Cli { @@ -76,6 +98,7 @@ pub struct Update { } pub async fn start(config: Config) -> Result<()> { + let client = create_reqwest_client()?; let cli = Cli::parse(); match cli { @@ -83,13 +106,11 @@ pub async fn start(config: Config) -> Result<()> { version, no_install, } => { - let client = Client::new(); let version = super::version::parse_version_type(&client, &version).await?; handlers::use_handler::start(version, !no_install, &client, config).await?; } Cli::Install { version } => { - let client = Client::new(); let mut version = super::version::parse_version_type(&client, &version).await?; match handlers::install_handler::start(&mut version, &client, &config).await? { @@ -108,7 +129,6 @@ pub async fn start(config: Config) -> Result<()> { } } Cli::Sync => { - let client = Client::new(); info!("Starting sync process"); sync_handler::start(&client, config).await?; } @@ -124,7 +144,6 @@ pub async fn start(config: Config) -> Result<()> { } Cli::Update(data) => { if data.version.is_some() || data.all { - let client = Client::new(); update_handler::start(data, &client, config).await?; } else { error!("Please provide a version or use the --all flag");