Skip to content

fix for issue #60 #95

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use source::Source;

use path;
use value::{Value, ValueKind, ValueWithKey};
use file::{File, FileFormat};

#[derive(Clone, Debug)]
enum ConfigKind {
Expand Down Expand Up @@ -49,7 +50,10 @@ pub struct Config {

impl Config {
pub fn new() -> Self {
Config::default()
let mut c = Config::default();
c.merge(File::from_str("", FileFormat::Toml));

c
}

/// Merge in a configuration property source.
Expand Down Expand Up @@ -129,6 +133,25 @@ impl Config {
self.refresh()
}

pub fn set_defaults<T: Serialize + Default>(&mut self, value: T) -> Result<&mut Config>
{
match self.kind{
ConfigKind::Mutable {
ref mut defaults, ..
} => {
let mut serializer = ConfigSerializer::default();
value.serialize(&mut serializer)?;
for (key, val) in serializer.output.collect()?{
defaults.insert(key.parse()?, val);
}
}

ConfigKind::Frozen => return Err(ConfigError::Frozen),
}

self.refresh()
}

pub fn set<T>(&mut self, key: &str, value: T) -> Result<&mut Config>
where
T: Into<Value>,
Expand Down
33 changes: 33 additions & 0 deletions tests/config_defaults.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
extern crate config;

#[macro_use]
extern crate serde_derive;

use config::*;

#[derive(Debug, Serialize, Deserialize)]
pub struct Settings {
pub db_host: String,
}

impl Default for Settings {
fn default() -> Self {
Settings {
db_host: String::from("default"),
}
}
}

impl Settings {
pub fn new() -> Result<Self, ConfigError> {
let mut s = Config::new();
s.set_defaults(Settings::default());
s.try_into()
}
}

#[test]
fn config_with_defaults(){
let mut s = Settings::new().unwrap();
assert_eq!(s.db_host, "default");
}