Skip to content

Commit

Permalink
chore: only attempt to load config from file if it exists (#18)
Browse files Browse the repository at this point in the history
fixes #5
  • Loading branch information
shikhar authored Nov 7, 2024
1 parent e05cc71 commit 993e2fc
Showing 1 changed file with 10 additions and 12 deletions.
22 changes: 10 additions & 12 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,27 +30,25 @@ pub fn config_path() -> Result<PathBuf, S2CliError> {
}

pub fn load_config(path: &Path) -> Result<S2Config, S2ConfigError> {
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::<S2Config>()
.map_err(|_| S2ConfigError::LoadError)
));
}
Ok(builder.build()?.try_deserialize::<S2Config>()?)
}

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(())
}
Expand All @@ -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),
}

0 comments on commit 993e2fc

Please sign in to comment.