diff --git a/src/bin/gman/cli.rs b/src/bin/gman/cli.rs index d8432f5..563d2df 100644 --- a/src/bin/gman/cli.rs +++ b/src/bin/gman/cli.rs @@ -323,6 +323,7 @@ pub fn secrets_completer(current: &OsStr) -> Vec { mod tests { use super::*; use crate::cli::generate_files_secret_injections; + use gman::config::get_config_file_path; use gman::config::{Config, RunConfig}; use pretty_assertions::{assert_eq, assert_str_eq}; use serial_test::serial; @@ -436,9 +437,10 @@ mod tests { fn test_run_config_completer_filters_by_prefix() { let td = tempdir().unwrap(); let xdg = td.path().join("xdg"); - let app_dir = xdg.join("gman"); - fs::create_dir_all(&app_dir).unwrap(); unsafe { std_env::set_var("XDG_CONFIG_HOME", &xdg) }; + let cfg_path = get_config_file_path().unwrap(); + let app_dir = cfg_path.parent().unwrap().to_path_buf(); + fs::create_dir_all(&app_dir).unwrap(); let yaml = indoc::indoc! { "--- @@ -471,9 +473,10 @@ mod tests { fn test_provider_completer_lists_matching_providers() { let td = tempdir().unwrap(); let xdg = td.path().join("xdg"); - let app_dir = xdg.join("gman"); - fs::create_dir_all(&app_dir).unwrap(); unsafe { std_env::set_var("XDG_CONFIG_HOME", &xdg) }; + let cfg_path = get_config_file_path().unwrap(); + let app_dir = cfg_path.parent().unwrap().to_path_buf(); + fs::create_dir_all(&app_dir).unwrap(); let yaml = indoc::indoc! { "--- @@ -508,9 +511,10 @@ mod tests { async fn test_secrets_completer_filters_keys_by_prefix() { let td = tempdir().unwrap(); let xdg = td.path().join("xdg"); - let app_dir = xdg.join("gman"); - fs::create_dir_all(&app_dir).unwrap(); unsafe { std_env::set_var("XDG_CONFIG_HOME", &xdg) }; + let cfg_path = get_config_file_path().unwrap(); + let app_dir = cfg_path.parent().unwrap().to_path_buf(); + fs::create_dir_all(&app_dir).unwrap(); let yaml = indoc::indoc! { "--- diff --git a/src/bin/gman/utils.rs b/src/bin/gman/utils.rs index 5fc31c1..587f016 100644 --- a/src/bin/gman/utils.rs +++ b/src/bin/gman/utils.rs @@ -46,7 +46,7 @@ pub fn init_logging_config() -> log4rs::Config { pub fn get_log_path() -> PathBuf { let base_dir = dirs::cache_dir().unwrap_or_else(env::temp_dir); - let log_dir = base_dir.join("gman"); + let log_dir = base_dir.join(env!("CARGO_CRATE_NAME")); let dir = if let Err(e) = fs::create_dir_all(&log_dir) { eprintln!( @@ -77,7 +77,7 @@ pub fn persist_config_file(config: &Config) -> Result<()> { fs::write(&config_path, s) .with_context(|| format!("failed to write {}", config_path.display()))?; } else { - confy::store("gman", "config", config) + confy::store(env!("CARGO_CRATE_NAME"), "config", config) .with_context(|| "failed to save updated config via confy")?; } diff --git a/src/config.rs b/src/config.rs index bda5fa9..86920b6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -21,6 +21,7 @@ //! rc.validate().unwrap(); //! ``` +use crate::calling_app_name; use crate::providers::local::LocalProvider; use crate::providers::{SecretProvider, SupportedProvider}; use anyhow::{Context, Result}; @@ -268,21 +269,18 @@ impl Config { /// Discover the default password file for the local provider. /// - /// On most systems this resolves to `~/.gman_password` when the file - /// exists, otherwise `None`. - pub fn local_provider_password_file() -> Option { - let candidate = dirs::home_dir().map(|p| p.join(".gman_password")); - match candidate { - Some(p) if p.exists() => Some(p), - _ => None, - } + /// On most systems this resolves to `~/._password` + pub fn local_provider_password_file() -> PathBuf { + dirs::home_dir() + .map(|p| p.join(format!(".{}_password", calling_app_name()))) + .expect("unable to determine home directory for local provider password file") } } /// Load and validate the application configuration. /// /// This uses the `confy` crate to load the configuration from a file -/// (e.g. `~/.config/gman/config.yaml`). If the file does +/// (e.g. `~/.config//config.yaml`). If the file does /// not exist, a default configuration is created and saved. /// /// ```no_run @@ -295,7 +293,7 @@ pub fn load_config(interpolate: bool) -> Result { let xdg_path = env::var_os("XDG_CONFIG_HOME").map(PathBuf::from); let mut config: Config = if let Some(base) = xdg_path.as_ref() { - let app_dir = base.join("gman"); + let app_dir = base.join(calling_app_name()); let yml = app_dir.join("config.yml"); let yaml = app_dir.join("config.yaml"); if yml.exists() || yaml.exists() { @@ -327,9 +325,9 @@ pub fn load_config(interpolate: bool) -> Result { ref mut provider_def, } = p.provider_type && provider_def.password_file.is_none() - && let Some(local_password_file) = Config::local_provider_password_file() + && Config::local_provider_password_file().exists() { - provider_def.password_file = Some(local_password_file); + provider_def.password_file = Some(Config::local_provider_password_file()); } }); @@ -337,7 +335,7 @@ pub fn load_config(interpolate: bool) -> Result { } fn load_confy_config(interpolate: bool) -> Result { - let load_path = confy::get_configuration_file_path("gman", "config")?; + let load_path = confy::get_configuration_file_path(&calling_app_name(), "config")?; let mut content = fs::read_to_string(&load_path) .with_context(|| format!("failed to read config file '{}'", load_path.display()))?; if interpolate { @@ -352,7 +350,7 @@ fn load_confy_config(interpolate: bool) -> Result { /// Returns the configuration file path that `confy` will use pub fn get_config_file_path() -> Result { if let Some(base) = env::var_os("XDG_CONFIG_HOME").map(PathBuf::from) { - let dir = base.join("gman"); + let dir = base.join(calling_app_name()); let yml = dir.join("config.yml"); let yaml = dir.join("config.yaml"); if yml.exists() || yaml.exists() { @@ -360,7 +358,10 @@ pub fn get_config_file_path() -> Result { } return Ok(dir.join("config.yml")); } - Ok(confy::get_configuration_file_path("gman", "config")?) + Ok(confy::get_configuration_file_path( + &calling_app_name(), + "config", + )?) } pub fn interpolate_env_vars(s: &str) -> String { diff --git a/src/lib.rs b/src/lib.rs index 631ffeb..8d70f62 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,6 +20,7 @@ //! The `config` and `providers` modules power the CLI. They can be embedded //! in other programs, but many functions interact with the user or the //! filesystem. Prefer `no_run` doctests for those. + use anyhow::{Context, Result, anyhow, bail}; use argon2::{ Algorithm, Argon2, Params, Version, @@ -31,6 +32,7 @@ use chacha20poly1305::{ aead::{Aead, KeyInit, OsRng}, }; use secrecy::{ExposeSecret, SecretString}; +use std::path::PathBuf; use zeroize::Zeroize; /// Configuration structures and helpers used by the CLI and library. pub mod config; @@ -207,6 +209,14 @@ pub fn decrypt_string(password: impl Into, envelope: &str) -> Resu Ok(s) } +pub(crate) fn calling_app_name() -> String { + let exe: PathBuf = std::env::current_exe().expect("unable to get current exe path"); + exe.file_stem() + .and_then(|s| s.to_str()) + .map(|s| s.to_owned()) + .expect("executable name not valid UTF-8") +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/providers/git_sync.rs b/src/providers/git_sync.rs index 68647ea..4edf9dc 100644 --- a/src/providers/git_sync.rs +++ b/src/providers/git_sync.rs @@ -1,3 +1,4 @@ +use crate::calling_app_name; use anyhow::{Context, Result, anyhow}; use chrono::Utc; use dialoguer::Confirm; @@ -25,7 +26,7 @@ pub fn sync_and_push(opts: &SyncOpts<'_>) -> Result<()> { opts.validate() .with_context(|| "invalid git sync options")?; let commit_message = format!("chore: sync @ {}", Utc::now().to_rfc3339()); - let config_dir = confy::get_configuration_file_path("gman", "vault") + let config_dir = confy::get_configuration_file_path(&calling_app_name(), "vault") .with_context(|| "get config dir")? .parent() .map(Path::to_path_buf) @@ -37,7 +38,7 @@ pub fn sync_and_push(opts: &SyncOpts<'_>) -> Result<()> { fs::create_dir_all(&repo_dir).with_context(|| format!("create {}", repo_dir.display()))?; // Move the default vault into the repo dir on first sync so only vault.yml is tracked. - let default_vault = confy::get_configuration_file_path("gman", "vault") + let default_vault = confy::get_configuration_file_path(&calling_app_name(), "vault") .with_context(|| "get default vault path")?; let repo_vault = repo_dir.join("vault.yml"); if default_vault.exists() && !repo_vault.exists() { diff --git a/src/providers/local.rs b/src/providers/local.rs index 9eb7a93..ad2b89e 100644 --- a/src/providers/local.rs +++ b/src/providers/local.rs @@ -13,6 +13,7 @@ use crate::providers::git_sync::{ use crate::providers::{SecretProvider, SupportedProvider}; use crate::{ ARGON_M_COST_KIB, ARGON_P, ARGON_T_COST, HEADER, KDF, KEY_LEN, NONCE_LEN, SALT_LEN, VERSION, + calling_app_name, }; use anyhow::Result; use argon2::{Algorithm, Argon2, Params, Version}; @@ -63,8 +64,13 @@ pub struct LocalProvider { impl Default for LocalProvider { fn default() -> Self { + let password_file = match Config::local_provider_password_file() { + p if p.exists() => Some(p), + _ => None, + }; + Self { - password_file: Config::local_provider_password_file(), + password_file, git_branch: Some("main".into()), git_remote_url: None, git_user_name: None, @@ -286,7 +292,7 @@ impl LocalProvider { let s = serde_yaml::to_string(&cfg)?; fs::write(&path, s).with_context(|| format!("failed to write {}", path.display()))?; } else { - confy::store("gman", "config", &cfg) + confy::store(&calling_app_name(), "config", &cfg) .with_context(|| "failed to save updated config via confy")?; } @@ -335,10 +341,11 @@ fn default_vault_path() -> Result { let xdg_path = env::var_os("XDG_CONFIG_HOME").map(PathBuf::from); if let Some(xdg) = xdg_path { - return Ok(xdg.join("gman").join("vault.yml")); + return Ok(xdg.join(calling_app_name()).join("vault.yml")); } - confy::get_configuration_file_path("gman", "vault").with_context(|| "get config dir") + confy::get_configuration_file_path(&calling_app_name(), "vault") + .with_context(|| "get config dir") } fn base_config_dir() -> Result { @@ -560,7 +567,7 @@ mod tests { fn persist_only_target_local_provider_git_settings() { let td = tempdir().unwrap(); let xdg = td.path().join("xdg"); - let app_dir = xdg.join("gman"); + let app_dir = xdg.join(calling_app_name()); fs::create_dir_all(&app_dir).unwrap(); unsafe { std_env::set_var("XDG_CONFIG_HOME", &xdg); diff --git a/tests/config_tests.rs b/tests/config_tests.rs index 1a3a3ee..2d501b7 100644 --- a/tests/config_tests.rs +++ b/tests/config_tests.rs @@ -252,16 +252,14 @@ mod tests { #[test] fn test_config_local_provider_password_file() { let path = Config::local_provider_password_file(); - let expected_path = dirs::home_dir().map(|p| p.join(".gman_password")); - if let Some(p) = &expected_path { - if !p.exists() { - assert_eq!(path, None); - } else { - assert_eq!(path, expected_path); - } - } else { - assert_eq!(path, None); - } + // Derive expected filename based on current test executable name + let exe = std::env::current_exe().expect("current_exe"); + let stem = exe + .file_stem() + .and_then(|s| s.to_str()) + .expect("utf-8 file stem"); + let expected = dirs::home_dir().map(|p| p.join(format!(".{}_password", stem))); + assert_eq!(Some(path), expected); } #[test] diff --git a/tests/providers/local_tests.rs b/tests/providers/local_tests.rs index 8ca0d7e..cacdbd1 100644 --- a/tests/providers/local_tests.rs +++ b/tests/providers/local_tests.rs @@ -58,10 +58,11 @@ fn test_local_provider_invalid_email() { #[test] fn test_local_provider_default() { let provider = LocalProvider::default(); - assert_eq!( - provider.password_file, - Config::local_provider_password_file() - ); + let expected_pw = { + let p = Config::local_provider_password_file(); + if p.exists() { Some(p) } else { None } + }; + assert_eq!(provider.password_file, expected_pw); assert_eq!(provider.git_branch, Some("main".into())); assert_eq!(provider.git_remote_url, None); assert_eq!(provider.git_user_name, None);