From 0252f308183e8ea53988907e7553eda8952ebdc7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 9 May 2024 13:47:22 +0100 Subject: [PATCH] feat: allow users not to provide config option with default values Now, you are able to run the tracler like this: ``` TORRUST_TRACKER_CONFIG="" cargo run ``` Default values will be used for the missing values in the provided configuration. In that case, none of the values have been provided, so it will use default values for all options. --- packages/configuration/src/v1/mod.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 8d5c123fe..25aa587b3 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -239,7 +239,7 @@ use std::fs; use std::net::IpAddr; use std::str::FromStr; -use figment::providers::{Env, Format, Toml}; +use figment::providers::{Env, Format, Serialized, Toml}; use figment::Figment; use serde::{Deserialize, Serialize}; use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; @@ -393,7 +393,7 @@ impl Configuration { /// /// Will return `Err` if the environment variable does not exist or has a bad configuration. pub fn load(info: &Info) -> Result { - let figment = Figment::new() + let figment = Figment::from(Serialized::defaults(Configuration::default())) .merge(Toml::string(&info.tracker_toml)) .merge(Env::prefixed("TORRUST_TRACKER__").split("__")); @@ -523,6 +523,24 @@ mod tests { assert_eq!(contents, default_config_toml()); } + #[test] + fn configuration_should_use_the_default_values_when_an_empty_configuration_is_provided_by_the_user() { + figment::Jail::expect_with(|_jail| { + let empty_configuration = String::new(); + + let info = Info { + tracker_toml: empty_configuration, + api_admin_token: None, + }; + + let configuration = Configuration::load(&info).expect("Could not load configuration from file"); + + assert_eq!(configuration, Configuration::default()); + + Ok(()) + }); + } + #[test] fn configuration_should_be_loaded_from_a_toml_config_file() { figment::Jail::expect_with(|_jail| {