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

feat: add initial gh auth token sync capability #33

Merged
merged 1 commit into from
Oct 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use crate::{constants::ST_CFG_FILE_NAME, errors::StResult};
use nu_ansi_term::Color;
use serde::{Deserialize, Serialize};
use std::{fs, io, path::PathBuf};
use std::{fs, io, path::PathBuf, process::Command};
use thiserror::Error;

pub(crate) const DEFAULT_CONFIG_PRETTY: &str = r#"# GitHub personal access token. Used for pushing branches to GitHub remotes as well as querying
Expand All @@ -25,8 +25,9 @@ pub struct StConfig {
impl StConfig {
/// Loads the configuration from disk.
pub fn try_load() -> Result<Option<Self>, StConfigError> {
// Load the default config file from disk
let config_path = PathBuf::from(env!("HOME")).join(ST_CFG_FILE_NAME);
match std::fs::read_to_string(&config_path) {
let file_config = match std::fs::read_to_string(config_path) {
Ok(contents) => match toml::from_str(&contents) {
Ok(config) => Ok(Some(config)),
Err(e) => Err(StConfigError::FailedToLoad(io::Error::new(
Expand All @@ -35,6 +36,30 @@ impl StConfig {
))),
},
Err(_) => Ok(None),
};

// If file config failed or doesn't exist, attempt to get the token from gh CLI
if let Ok(None) = file_config {
// Try to get token from gh CLI
match Command::new("gh").args(["auth", "token"]).output() {
Ok(output) => {
if output.status.success() {
if let Ok(token) = String::from_utf8(output.stdout) {
let token = token.trim().to_string();
if !token.is_empty() {
// Create new config with the token
return Ok(Some(Self {
github_token: token,
}));
}
}
}
Ok(None)
}
Err(_) => Ok(None),
}
} else {
file_config
}
}

Expand Down