From 993e2fcb598f7cb64e3690206ef1ec998e8af78f Mon Sep 17 00:00:00 2001 From: Shikhar Bhushan Date: Wed, 6 Nov 2024 21:34:21 -0500 Subject: [PATCH] chore: only attempt to load config from file if it exists (#18) fixes #5 --- src/config.rs | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/config.rs b/src/config.rs index 7afe035..a2c4357 100644 --- a/src/config.rs +++ b/src/config.rs @@ -30,27 +30,25 @@ pub fn config_path() -> Result { } pub fn load_config(path: &Path) -> Result { - Config::builder() - .add_source(config::File::new( + let mut builder = Config::builder().add_source(config::Environment::with_prefix("S2")); + if path.exists() { + builder = builder.add_source(config::File::new( path.to_str().expect("config path is valid utf8"), FileFormat::Toml, - )) - .add_source(config::Environment::with_prefix("S2")) - .build() - .map_err(|_| S2ConfigError::LoadError)? - .try_deserialize::() - .map_err(|_| S2ConfigError::LoadError) + )); + } + Ok(builder.build()?.try_deserialize::()?) } pub fn create_config(config_path: &PathBuf, auth_token: String) -> Result<(), S2ConfigError> { let cfg = S2Config { auth_token }; if let Some(parent) = config_path.parent() { - std::fs::create_dir_all(parent).map_err(|_| S2ConfigError::WriteError)?; + std::fs::create_dir_all(parent).map_err(S2ConfigError::WriteError)?; } let toml = toml::to_string(&cfg).unwrap(); - std::fs::write(config_path, toml).map_err(|_| S2ConfigError::WriteError)?; + std::fs::write(config_path, toml).map_err(S2ConfigError::WriteError)?; Ok(()) } @@ -64,8 +62,8 @@ pub enum S2ConfigError { #[diagnostic(help( "Did you run `s2-cli config set`? or use `S2_AUTH_TOKEN` environment variable." ))] - LoadError, + LoadError(#[from] config::ConfigError), #[error("Failed to write config file")] - WriteError, + WriteError(#[source] std::io::Error), }