Browse Source

factor out GITHUB_API_TOKEN env variable access

Niko Matsakis 4 years ago
parent
commit
b184748773
3 changed files with 13 additions and 10 deletions
  1. 1 5
      src/actions.rs
  2. 10 0
      src/github.rs
  3. 2 5
      src/main.rs

+ 1 - 5
src/actions.rs

@@ -1,7 +1,6 @@
 use async_trait::async_trait;
 
 use reqwest::Client;
-use std::env;
 use tera::{Context, Tera};
 
 use crate::github::{self, GithubClient, Repository};
@@ -51,10 +50,7 @@ lazy_static! {
 #[async_trait]
 impl<'a> Action for Step<'a> {
     async fn call(&self) -> String {
-        let gh = GithubClient::new(
-            Client::new(),
-            env::var("GITHUB_API_TOKEN").expect("Missing GITHUB_API_TOKEN"),
-        );
+        let gh = GithubClient::new_with_default_token(Client::new());
 
         let mut context = Context::new();
 

+ 10 - 0
src/github.rs

@@ -863,6 +863,12 @@ impl RequestSend for RequestBuilder {
     }
 }
 
+/// Finds the token in the user's environment, panicking if no suitable token
+/// can be found.
+pub fn default_token_from_env() -> String {
+    std::env::var("GITHUB_API_TOKEN").expect("Missing GITHUB_API_TOKEN")
+}
+
 #[derive(Clone)]
 pub struct GithubClient {
     token: String,
@@ -874,6 +880,10 @@ impl GithubClient {
         GithubClient { client, token }
     }
 
+    pub fn new_with_default_token(client: Client) -> Self {
+        Self::new(client, default_token_from_env())
+    }
+
     pub fn raw(&self) -> &Client {
         &self.client
     }

+ 2 - 5
src/main.rs

@@ -179,12 +179,9 @@ async fn run_server(addr: SocketAddr) -> anyhow::Result<()> {
         .context("database migrations")?;
 
     let client = Client::new();
-    let gh = github::GithubClient::new(
-        client.clone(),
-        env::var("GITHUB_API_TOKEN").expect("Missing GITHUB_API_TOKEN"),
-    );
+    let gh = github::GithubClient::new_with_default_token(client.clone());
     let oc = octocrab::OctocrabBuilder::new()
-        .personal_token(env::var("GITHUB_API_TOKEN").expect("Missing GITHUB_API_TOKEN"))
+        .personal_token(github::default_token_from_env())
         .build()
         .expect("Failed to build octograb.");
     let ctx = Arc::new(Context {