From d919300b0260f461e7633b64f2b76a779d79a2dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Hru=C5=A1ka?= Date: Fri, 24 Apr 2020 15:39:12 +0200 Subject: [PATCH] add hook to retrieve config file path --- Cargo.toml | 2 +- src/lib.rs | 35 +++++++++++++++++++++++++++++------ 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 17cc38f..267a679 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "clappconfig" -version = "0.1.0" +version = "0.2.0" authors = ["Ondřej Hruška "] edition = "2018" license = "MIT" diff --git a/src/lib.rs b/src/lib.rs index 30919c3..5cf69de 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -48,6 +48,12 @@ pub trait AppConfig: Sized + Serialize + DeserializeOwned + Debug + Default { clap } + /// Called when the config file is resolved, e.g. to store it in Config + /// for later relative path resolution + fn on_config_file_found(&mut self, _path : &PathBuf) { + // + } + /// Configure the config object using args. /// Logging has already been inited and configured. fn configure<'a>(self, _clap: &clap::ArgMatches<'a>) -> Fallible; @@ -119,15 +125,32 @@ pub trait AppConfig: Sized + Serialize + DeserializeOwned + Debug + Default { let filepath = PathBuf::from_str(cfg_file)?; - let config: Self = if filepath.is_file() { - let path = filepath.canonicalize()?; - Self::pre_log_println(format!("Loading config from: {}", path.display())); + let config = if filepath.exists() { + let mut path = filepath.canonicalize()?; + + if path.is_dir() { + path = path.join(cfg_file_name); + } + + if path.exists() { + Self::pre_log_println(format!("Loading config from: {}", path.display())); + + let buf = read_file(&path)?; - let buf = read_file(path)?; - json5::from_str(&buf)? + let mut config: Self = json5::from_str(&buf)?; + config.on_config_file_found(&path); + config + } else { + Self::pre_log_println(format!( + "Config file \"{}\" does not exist, using defaults.", + path.display() + )); + + Self::default() + } } else { Self::pre_log_println(format!( - "Config file \"{}\" does not exist, using defaults.", + "Config path \"{}\" does not exist, using defaults.", cfg_file ));