Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Support for GitHub Personal Access Tokens #18

Merged
merged 13 commits into from
Sep 6, 2022
71 changes: 71 additions & 0 deletions src/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
use std::io;

use anyhow::{bail, format_err, Context};
use serde::{Deserialize, Serialize};
use toml_edit::Document;

use crate::config::write_if_not_exists;
use crate::home::Home;

pub static MANIFEST_FILE_NAME: &str = "auth.toml";
sasial-dev marked this conversation as resolved.
Show resolved Hide resolved

static DEFAULT_MANIFEST: &str = r#"
sasial-dev marked this conversation as resolved.
Show resolved Hide resolved
# This file is for auth tokens managed by Aftman, a cross-platform toolchain manager.
# For more information, see https://github.com/LPGhatguy/aftman

# To add a new token, add an entry.
sasial-dev marked this conversation as resolved.
Show resolved Hide resolved
# github = "token"
"#;

#[derive(Debug, Serialize, Deserialize)]
pub struct AuthManifest {
pub github: Option<String>,
}

impl AuthManifest {
/// Create an empty global auth manifest if there isn't one already.
pub fn init(home: &Home) -> anyhow::Result<()> {
let base_dir = home.path();
fs_err::create_dir_all(&base_dir)?;

let manifest_path = base_dir.join(MANIFEST_FILE_NAME);
write_if_not_exists(&manifest_path, DEFAULT_MANIFEST.trim())?;

Ok(())
}

/// Try to load an Aftman manifest from a directory containing an
/// aftman.toml file.
sasial-dev marked this conversation as resolved.
Show resolved Hide resolved
pub fn load(home: &Home) -> anyhow::Result<Option<AuthManifest>> {
let file_path = home.path().join(MANIFEST_FILE_NAME);

let contents = match fs_err::read(&file_path) {
Ok(contents) => contents,
Err(err) => {
if err.kind() == io::ErrorKind::NotFound {
return Ok(None);
}

bail!(err);
}
};

let manifest: AuthManifest = toml::from_slice(&contents)
.with_context(|| format_err!("Invalid manifest at {}", file_path.display()))?;
sasial-dev marked this conversation as resolved.
Show resolved Hide resolved

Ok(Some(manifest))
}

fn add_token(home: &Home, token_type: &String, token: &String) -> anyhow::Result<()> {
sasial-dev marked this conversation as resolved.
Show resolved Hide resolved
let manifest_path = home.path().join(MANIFEST_FILE_NAME);
let content = fs_err::read_to_string(&manifest_path)?;
let mut document: Document = content.parse()?;
document[token_type.as_ref()] = toml_edit::value(token.to_string());

fs_err::write(&manifest_path, document.to_string())?;

log::info!("A {token_type} token has been added globally.");

Ok(())
}
}
4 changes: 4 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod auth;
mod cli;
mod config;
mod dirs;
Expand All @@ -19,6 +20,7 @@ use std::env::{consts::EXE_SUFFIX, current_dir, current_exe};
use anyhow::{bail, format_err, Context};
use structopt::StructOpt;

use crate::auth::AuthManifest;
use crate::cli::Args;
use crate::home::Home;
use crate::manifest::Manifest;
Expand Down Expand Up @@ -63,6 +65,8 @@ fn run() -> anyhow::Result<()> {
}

Manifest::init_global(&home)?;
AuthManifest::init(&home)?;

sasial-dev marked this conversation as resolved.
Show resolved Hide resolved
system_path::init(&home)?;

Args::from_args().run(&home, tool_storage)
Expand Down
15 changes: 11 additions & 4 deletions src/tool_source/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ use std::io::{Cursor, Read, Seek};
use anyhow::Context;
use reqwest::{
blocking::Client,
header::{ACCEPT, USER_AGENT},
header::{ACCEPT, AUTHORIZATION, USER_AGENT},
};
use semver::Version;
use serde::{Deserialize, Serialize};

use crate::auth::AuthManifest;
use crate::home::Home;
use crate::tool_id::ToolId;
use crate::tool_name::ToolName;
use crate::tool_source::Asset;
Expand All @@ -18,20 +20,25 @@ const APP_NAME: &str = "LPGhatguy/aftman";

pub struct GitHubSource {
client: Client,
token: Option<String>,
}

impl GitHubSource {
pub fn new() -> Self {
pub fn new(home: &Home) -> Self {
let token = AuthManifest::load(home).ok();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we load this file in another place? We shouldn't be suppressing errors here with ok(). If we want to load it here, we can change GitHubSource::new to return an anyhow::Result<Self> instead.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've attempted to fix this, but will need some help with borrowing as I'm still new to rust!

Self {
client: Client::new(),
token: token.flatten().map(|t| t.github).flatten(),
sasial-dev marked this conversation as resolved.
Show resolved Hide resolved
}
}

pub fn get_all_releases(&self, name: &ToolName) -> anyhow::Result<Vec<Release>> {
let url = format!("https://api.github.com/repos/{}/releases", name);
let builder = self.client.get(&url).header(USER_AGENT, APP_NAME);
let mut builder = self.client.get(&url).header(USER_AGENT, APP_NAME);

// TODO: Authorization
if let Some(token) = &self.token {
builder = builder.header(AUTHORIZATION, format!("token {}", token));
sasial-dev marked this conversation as resolved.
Show resolved Hide resolved
}
sasial-dev marked this conversation as resolved.
Show resolved Hide resolved

let response_body = builder.send()?.text()?;

Expand Down
4 changes: 2 additions & 2 deletions src/tool_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ impl ToolStorage {
log::info!("Installing tool: {}", spec);

log::debug!("Fetching GitHub releases...");
let github = self.github.get_or_init(GitHubSource::new);
let github = self.github.get_or_init(|| GitHubSource::new(&self.home));
let mut releases = github.get_all_releases(spec.name())?;
releases.sort_by(|a, b| a.version.cmp(&b.version).reverse());

Expand Down Expand Up @@ -232,7 +232,7 @@ impl ToolStorage {
log::info!("Installing tool: {id}");

log::debug!("Fetching GitHub release...");
let github = self.github.get_or_init(GitHubSource::new);
let github = self.github.get_or_init(|| GitHubSource::new(&self.home));
let release = github.get_release(id)?;

let mut compatible_assets = self.get_compatible_assets(&release);
Expand Down