Fix cli arg precedence and finish config wiring

This commit is contained in:
Thomas Wickham 2021-03-02 21:43:26 +01:00
parent 0b6f482e51
commit 009ffd793b
3 changed files with 33 additions and 14 deletions

View File

@ -1,2 +1,2 @@
# LLDAP configuration
some_text = "ok boomer"
some_text = "ok boomer from toml file"

View File

@ -1,6 +1,7 @@
use anyhow::Result;
use figment::{
providers::{Env, Format, Serialized, Toml},
util::map,
Figment,
};
use serde::{Deserialize, Serialize};
@ -14,24 +15,34 @@ pub struct Configuration {
pub some_text: String,
}
impl Configuration {
fn from_cli(cli_opts: CLIOpts) -> Self {
impl Default for Configuration {
fn default() -> Self {
Configuration {
log_level_verbose: cli_opts.verbose,
log_level_verbose: false,
secret_pepper: String::from("secretsecretpepper"),
some_text: String::new(),
}
}
}
impl Configuration {
fn from_cli(cli_opts: CLIOpts) -> Figment {
let config_opts_from_cli = map! {
"log_level_verbose" => cli_opts.verbose
};
Figment::new().join(Serialized::defaults(config_opts_from_cli))
}
}
pub fn init(cli_opts: CLIOpts) -> Result<Configuration> {
// FIXME cli arguments are less prioritary than toml config file or env... Not good.
let config: Configuration = Figment::from(Serialized::defaults(Configuration::from_cli(
cli_opts.clone(),
)))
.merge(Toml::file(cli_opts.config_file))
.merge(Env::prefixed("LLDAP_"))
.extract()?;
let config_file = cli_opts.config_file.clone();
let config: Configuration = Figment::from(Serialized::defaults(Configuration::default()))
.merge(Toml::file(config_file))
.merge(Env::prefixed("LLDAP_"))
.merge(Configuration::from_cli(cli_opts))
.extract()?;
Ok(config)
}

View File

@ -3,15 +3,23 @@ use anyhow::Context;
use tracing::subscriber::set_global_default;
use tracing_log::LogTracer;
pub fn init(_config: Configuration) -> anyhow::Result<()> {
// TODO: use config.log_level_verbose to set level
pub fn init(config: Configuration) -> anyhow::Result<()> {
let max_log_level = log_level_from_config(config);
let subscriber = tracing_subscriber::fmt()
.with_timer(tracing_subscriber::fmt::time::time())
.with_target(false)
.with_level(true)
.with_max_level(max_log_level)
.finish();
LogTracer::init().context("Failed to set logger")?;
set_global_default(subscriber).context("Failed to set subscriber")?;
Ok(())
}
fn log_level_from_config(config: Configuration) -> tracing::Level {
if config.log_level_verbose {
tracing::Level::DEBUG
} else {
tracing::Level::INFO
}
}