Skip to content
Open
Show file tree
Hide file tree
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
713 changes: 679 additions & 34 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ path = "src/main.rs"

[dependencies]
clap = "4.5.37"
keyring = { version = "3.6.3", default-features = false, features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] }
reqwest = { version = "0.12.15", default-features = false, features = ["blocking", "json", "rustls-tls"] }
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
toml = "0.8.23"

[dev-dependencies]
assert_cmd = "2.0.16"
Expand Down
5 changes: 3 additions & 2 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ impl AuthService {
.client
.fetch_current_user(&token)
.map_err(map_auth_error)?;
self.config
let saved_source = self
.config
.save_token(&token)
.map_err(CommandError::config)?;

Expand All @@ -73,7 +74,7 @@ impl AuthService {
EXIT_OK,
AuthState {
authenticated: true,
source: "config",
source: saved_source.as_str(),
username: Some(username),
logged_out: false,
},
Expand Down
94 changes: 29 additions & 65 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
use std::env;
use std::fs;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};
use crate::credentials::{
CredentialError, CredentialStore, ResolvedToken, TokenSource, credential_store_for_process,
};

const CONFIG_DIR_NAME: &str = "gitee";
const FALLBACK_CONFIG_DIR_NAME: &str = ".gitee";

pub struct ConfigStore {
config_dir: PathBuf,
credentials: Box<dyn CredentialStore>,
}

impl ConfigStore {
pub fn from_env() -> Self {
let config_dir = config_dir();
Self {
config_dir: config_dir(),
credentials: credential_store_for_process(&config_dir),
config_dir,
}
}

Expand All @@ -29,93 +33,53 @@ impl ConfigStore {
}
}

let config = self.load_config()?;
Ok(config.map(|config| ResolvedToken {
token: config.token,
source: TokenSource::Config,
}))
Ok(self
.credentials
.load_token()
.map_err(ConfigError::store)?
.map(|token| ResolvedToken {
token,
source: self.credentials.token_source(),
}))
}

pub fn save_token(&self, token: &str) -> Result<(), ConfigError> {
fs::create_dir_all(&self.config_dir).map_err(ConfigError::Io)?;

let contents = toml::to_string(&ConfigFile {
token: token.to_string(),
})
.map_err(ConfigError::TomlSerialize)?;

fs::write(self.config_path_buf(), contents).map_err(ConfigError::Io)
pub fn save_token(&self, token: &str) -> Result<TokenSource, ConfigError> {
self.credentials
.save_token(token)
.map_err(ConfigError::store)?;
Ok(self.credentials.token_source())
}

pub fn clear_token(&self) -> Result<(), ConfigError> {
let path = self.config_path_buf();
if !path.exists() {
return Ok(());
}

fs::remove_file(path).map_err(ConfigError::Io)
self.credentials.clear_token().map_err(ConfigError::store)
}

pub fn config_path(&self) -> String {
self.config_path_buf().display().to_string()
}

fn load_config(&self) -> Result<Option<ConfigFile>, ConfigError> {
let path = self.config_path_buf();
if !path.exists() {
return Ok(None);
}

let contents = fs::read_to_string(path).map_err(ConfigError::Io)?;
let config = toml::from_str::<ConfigFile>(&contents).map_err(ConfigError::Toml)?;
Ok(Some(config))
}

fn config_path_buf(&self) -> PathBuf {
self.config_dir.join("config.toml")
}
}

pub struct ResolvedToken {
pub token: String,
pub source: TokenSource,
}

pub enum TokenSource {
Env,
Config,
}

impl TokenSource {
pub fn as_str(&self) -> &'static str {
match self {
Self::Env => "env",
Self::Config => "config",
}
}
}

#[derive(Deserialize, Serialize)]
struct ConfigFile {
token: String,
}

pub enum ConfigError {
Io(std::io::Error),
Toml(toml::de::Error),
TomlSerialize(toml::ser::Error),
Store(CredentialError),
}

impl std::fmt::Display for ConfigError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(err) => write!(f, "{err}"),
Self::Toml(err) => write!(f, "{err}"),
Self::TomlSerialize(err) => write!(f, "{err}"),
Self::Store(err) => write!(f, "{err}"),
}
}
}

impl ConfigError {
fn store(error: CredentialError) -> Self {
Self::Store(error)
}
}

fn config_dir() -> PathBuf {
if let Ok(path) = env::var("GITEE_CONFIG_DIR") {
let path = path.trim();
Expand Down
215 changes: 215 additions & 0 deletions src/credentials.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
use std::env;
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};

use keyring::{Entry, Error as KeyringError};

const KEYRING_SERVICE_NAME: &str = "gitee-cli:gitee.com";
const KEYRING_ACCOUNT_NAME: &str = "default";

#[derive(Clone, Copy)]
pub enum TokenSource {
Env,
Keyring,
}

impl TokenSource {
pub fn as_str(&self) -> &'static str {
match self {
Self::Env => "env",
Self::Keyring => "keyring",
}
}
}

pub struct ResolvedToken {
pub token: String,
pub source: TokenSource,
}

pub trait CredentialStore {
fn load_token(&self) -> Result<Option<String>, CredentialError>;
fn save_token(&self, token: &str) -> Result<(), CredentialError>;
fn clear_token(&self) -> Result<(), CredentialError>;
fn token_source(&self) -> TokenSource;
}

pub fn credential_store_for_process(config_dir: &Path) -> Box<dyn CredentialStore> {
if let Some(path) = synthetic_test_credential_path(config_dir) {
return Box::new(FileCredentialStore::new(path, TokenSource::Keyring));
}

Box::new(KeyringCredentialStore::new())
}

pub enum CredentialError {
Io(std::io::Error),
Keyring(KeyringError),
}

impl std::fmt::Display for CredentialError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(err) => write!(f, "{err}"),
Self::Keyring(err) => write!(f, "{err}"),
}
}
}

struct KeyringCredentialStore {
service_name: &'static str,
account_name: &'static str,
}

impl KeyringCredentialStore {
fn new() -> Self {
Self {
service_name: KEYRING_SERVICE_NAME,
account_name: KEYRING_ACCOUNT_NAME,
}
}

fn entry(&self) -> Result<Entry, CredentialError> {
Entry::new(self.service_name, self.account_name).map_err(CredentialError::Keyring)
}
}

impl CredentialStore for KeyringCredentialStore {
fn load_token(&self) -> Result<Option<String>, CredentialError> {
match self.entry()?.get_password() {
Ok(token) => Ok(Some(token)),
Err(KeyringError::NoEntry) => Ok(None),
Err(err) => Err(CredentialError::Keyring(err)),
}
}

fn save_token(&self, token: &str) -> Result<(), CredentialError> {
self.entry()?
.set_password(token)
.map_err(CredentialError::Keyring)
}

fn clear_token(&self) -> Result<(), CredentialError> {
match self.entry()?.delete_credential() {
Ok(()) => Ok(()),
Err(KeyringError::NoEntry) => Ok(()),
Err(err) => Err(CredentialError::Keyring(err)),
}
}

fn token_source(&self) -> TokenSource {
TokenSource::Keyring
}
}

struct FileCredentialStore {
path: PathBuf,
source: TokenSource,
}

impl FileCredentialStore {
fn new(path: PathBuf, source: TokenSource) -> Self {
Self { path, source }
}
}

impl CredentialStore for FileCredentialStore {
fn load_token(&self) -> Result<Option<String>, CredentialError> {
match fs::read_to_string(&self.path) {
Ok(token) => {
let token = token.trim().to_string();
if token.is_empty() {
return Ok(None);
}
Ok(Some(token))
}
Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
Err(err) => Err(CredentialError::Io(err)),
}
}

fn save_token(&self, token: &str) -> Result<(), CredentialError> {
if let Some(parent) = self.path.parent() {
fs::create_dir_all(parent).map_err(CredentialError::Io)?;
}
fs::write(&self.path, token).map_err(CredentialError::Io)
}

fn clear_token(&self) -> Result<(), CredentialError> {
match fs::remove_file(&self.path) {
Ok(()) => Ok(()),
Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
Err(err) => Err(CredentialError::Io(err)),
}
}

fn token_source(&self) -> TokenSource {
self.source
}
}

fn synthetic_test_credential_path(config_dir: &Path) -> Option<PathBuf> {
if !running_under_test_harness() {
return None;
}

if env::var_os("GITEE_CONFIG_DIR").is_some() {
return Some(config_dir.join(".gitee-test-store/credentials.token"));
}

if let Some(home_dir) = home_dir() {
return Some(home_dir.join(".gitee-test-store/credentials.token"));
}

if let Ok(current_dir) = env::current_dir() {
return Some(current_dir.join(".gitee-test-store/credentials.token"));
}

Some(
env::temp_dir()
.join("gitee-cli-test-store")
.join(sanitize_path_component(&config_dir.display().to_string()))
.join("credentials.token"),
)
}

fn running_under_test_harness() -> bool {
env::var_os("CARGO_BIN_EXE_gitee").is_some() || env::var_os("CARGO_TARGET_TMPDIR").is_some()
}

fn sanitize_path_component(value: &str) -> String {
value
.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-' | '_') {
ch
} else {
'_'
}
})
.collect()
}

fn home_dir() -> Option<PathBuf> {
if let Ok(path) = env::var("HOME") {
let path = path.trim();
if !path.is_empty() {
return Some(PathBuf::from(path));
}
}

if let Ok(path) = env::var("USERPROFILE") {
let path = path.trim();
if !path.is_empty() {
return Some(PathBuf::from(path));
}
}

match (env::var("HOMEDRIVE"), env::var("HOMEPATH")) {
(Ok(drive), Ok(path)) if !drive.trim().is_empty() && !path.trim().is_empty() => {
Some(PathBuf::from(format!("{}{}", drive.trim(), path.trim())))
}
_ => None,
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ pub mod auth;
pub mod cli;
pub mod command;
pub mod config;
pub mod credentials;
pub mod gitee_api;
pub mod issue;
pub mod pr;
Expand Down
Loading