Skip to content
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

Integration of my config-rs-maint fork #174

Closed
wants to merge 27 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
2921c53
Remove travis
matthiasbeyer Mar 13, 2021
2d77910
Add srht build configuration
matthiasbeyer Mar 13, 2021
b4c8836
Update README
matthiasbeyer Mar 13, 2021
b416544
Fix test failure
matthiasbeyer Mar 4, 2021
e813eca
Fix expected error message
matthiasbeyer Mar 4, 2021
71adf3d
Update Cargo.toml settings for maintenance fork
matthiasbeyer Mar 13, 2021
fafa2ac
Fix clippy: Use is_empty() instead of comparing to empty string
matthiasbeyer Mar 13, 2021
9f430e8
Add maintenance badge
matthiasbeyer Mar 13, 2021
bd121fa
Fix imports for new crate name
matthiasbeyer Mar 13, 2021
ba7090f
Merge branch 'srht-builds'
matthiasbeyer Mar 13, 2021
b84fed1
Version: 0.11.0
matthiasbeyer Mar 13, 2021
887736d
Merge branch 'prepare-0.11'
matthiasbeyer Mar 13, 2021
ea25d5f
Add a Config::set_once() function to set a value once (and let Config…
matthiasbeyer Mar 9, 2021
e701e00
Add Config::with_merged()
matthiasbeyer Nov 20, 2020
010895c
Update dependency: rust-ini: 0.13 -> 0.16
decathorpe Dec 9, 2020
05b04b8
Merge branch 'add-setter'
matthiasbeyer Mar 14, 2021
9802e2f
Merge branch 'builder'
matthiasbeyer Mar 14, 2021
a3f205d
Merge branch 'update-rust-ini'
matthiasbeyer Mar 14, 2021
48db2a1
Add entry for 0.11.0
matthiasbeyer Mar 14, 2021
c26a941
Rename try_into/try_from
matthiasbeyer Mar 14, 2021
def3702
Merge branch 'config-rs-issue-173'
matthiasbeyer Mar 14, 2021
6c06a1d
Revert "Add entry for 0.11.0"
matthiasbeyer Mar 16, 2021
5754b24
Revert "Version: 0.11.0"
matthiasbeyer Mar 16, 2021
9f58c84
Revert "Fix imports for new crate name"
matthiasbeyer Mar 16, 2021
85faa1d
Revert "Update Cargo.toml settings for maintenance fork"
matthiasbeyer Mar 16, 2021
9f92ab1
Revert "Update README"
matthiasbeyer Mar 16, 2021
8eaeca3
Revert "Add srht build configuration"
matthiasbeyer Mar 16, 2021
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
18 changes: 0 additions & 18 deletions .travis.yml

This file was deleted.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ categories = ["config"]
license = "MIT/Apache-2.0"

[badges]
travis-ci = { repository = "mehcode/config-rs" }
maintenance = { status = "actively-developed" }

[features]
default = ["toml", "json", "yaml", "hjson", "ini"]
Expand All @@ -28,8 +28,8 @@ nom = "5.0.0"
toml = { version = "0.5", optional = true }
serde_json = { version = "1.0.2", optional = true }
yaml-rust = { version = "0.4", optional = true }
serde-hjson = { version = "0.9", optional = true }
rust-ini = { version = "0.13", optional = true }
serde-hjson = { version = "0.9", default-features = false, optional = true }
rust-ini = { version = "0.16", optional = true }

[dev-dependencies]
serde_derive = "1.0.8"
Expand Down
6 changes: 3 additions & 3 deletions examples/glob/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ fn main() {

// Print out our settings (as a HashMap)
println!("\n{:?} \n\n-----------",
settings.try_into::<HashMap<String, String>>().unwrap());
settings.try_deserialize::<HashMap<String, String>>().unwrap());

// Option 2
// --------
Expand All @@ -33,7 +33,7 @@ fn main() {

// Print out our settings (as a HashMap)
println!("\n{:?} \n\n-----------",
settings.try_into::<HashMap<String, String>>().unwrap());
settings.try_deserialize::<HashMap<String, String>>().unwrap());

// Option 3
// --------
Expand All @@ -48,5 +48,5 @@ fn main() {

// Print out our settings (as a HashMap)
println!("\n{:?} \n\n-----------",
settings.try_into::<HashMap<String, String>>().unwrap());
settings.try_deserialize::<HashMap<String, String>>().unwrap());
}
2 changes: 1 addition & 1 deletion examples/hierarchical-env/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,6 @@ impl Settings {
println!("database: {:?}", s.get::<String>("database.url"));

// You can deserialize (and thus freeze) the entire configuration as
s.try_into()
s.try_deserialize()
}
}
2 changes: 1 addition & 1 deletion examples/simple/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ fn main() {

// Print out our settings (as a HashMap)
println!("{:?}",
settings.try_into::<HashMap<String, String>>().unwrap());
settings.try_deserialize::<HashMap<String, String>>().unwrap());
}
2 changes: 1 addition & 1 deletion examples/watch/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ fn show() {
.read()
.unwrap()
.clone()
.try_into::<HashMap<String, String>>()
.try_deserialize::<HashMap<String, String>>()
.unwrap());
}

Expand Down
42 changes: 38 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,28 @@ impl Config {
self.refresh()
}

/// Merge in a configuration property source.
pub fn with_merged<T>(mut self, source: T) -> Result<Self>
where
T: 'static,
T: Source + Send + Sync,
{
match self.kind {
ConfigKind::Mutable {
ref mut sources, ..
} => {
sources.push(Box::new(source));
}

ConfigKind::Frozen => {
return Err(ConfigError::Frozen);
}
}

self.refresh()?;
Ok(self)
}

/// Refresh the configuration cache with fresh
/// data from added sources.
///
Expand Down Expand Up @@ -151,6 +173,18 @@ impl Config {
self.refresh()
}

pub fn set_once(&mut self, key: &str, value: Value) -> Result<()> {
let expr: path::Expression = key.parse()?;

// Traverse the cache using the path to (possibly) retrieve a value
if let Some(ref mut val) = expr.get_mut(&mut self.cache) {
**val = value;
} else {
expr.set(&mut self.cache, value);
}
Ok(())
}

pub fn get<'de, T: Deserialize<'de>>(&self, key: &str) -> Result<T> {
// Parse the key into a path expression
let expr: path::Expression = key.parse()?;
Expand Down Expand Up @@ -193,20 +227,20 @@ impl Config {
}

/// Attempt to deserialize the entire configuration into the requested type.
pub fn try_into<'de, T: Deserialize<'de>>(self) -> Result<T> {
pub fn try_deserialize<'de, T: Deserialize<'de>>(self) -> Result<T> {
T::deserialize(self)
}

/// Attempt to serialize the entire configuration from the given type.
pub fn try_from<T: Serialize>(from: &T) -> Result<Self> {
pub fn try_serialize<T: Serialize>(from: &T) -> Result<Self> {
let mut serializer = ConfigSerializer::default();
from.serialize(&mut serializer)?;
Ok(serializer.output)
}

#[deprecated(since = "0.7.0", note = "please use 'try_into' instead")]
#[deprecated(since = "0.7.0", note = "please use 'try_deserialize' instead")]
pub fn deserialize<'de, T: Deserialize<'de>>(self) -> Result<T> {
self.try_into()
self.try_deserialize()
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ impl Source for Environment {

for (key, value) in env::vars() {
// Treat empty environment variables as unset
if self.ignore_empty && value == "" {
if self.ignore_empty && value.is_empty() {
continue;
}

Expand Down
16 changes: 11 additions & 5 deletions src/file/format/ini.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,23 @@ pub fn parse(
let mut map: HashMap<String, Value> = HashMap::new();
let i = Ini::load_from_str(text)?;
for (sec, prop) in i.iter() {
match *sec {
Some(ref sec) => {
match sec {
Some(sec) => {
let mut sec_map: HashMap<String, Value> = HashMap::new();
for (k, v) in prop.iter() {
sec_map.insert(k.clone(), Value::new(uri, ValueKind::String(v.clone())));
sec_map.insert(
k.to_owned(),
Value::new(uri, ValueKind::String(v.to_owned())),
);
}
map.insert(sec.clone(), Value::new(uri, ValueKind::Table(sec_map)));
map.insert(sec.to_owned(), Value::new(uri, ValueKind::Table(sec_map)));
}
None => {
for (k, v) in prop.iter() {
map.insert(k.clone(), Value::new(uri, ValueKind::String(v.clone())));
map.insert(
k.to_owned(),
Value::new(uri, ValueKind::String(v.to_owned())),
);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -710,9 +710,9 @@ mod test {
int: 1,
seq: vec!["a".to_string(), "b".to_string()],
};
let config = Config::try_from(&test).unwrap();
let config = Config::try_serialize(&test).unwrap();

let actual: Test = config.try_into().unwrap();
let actual: Test = config.try_deserialize().unwrap();
assert_eq!(test, actual);
}
}
14 changes: 7 additions & 7 deletions src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,12 +151,12 @@ impl Value {
}

/// Attempt to deserialize this value into the requested type.
pub fn try_into<'de, T: Deserialize<'de>>(self) -> Result<T> {
pub fn try_deserialize<'de, T: Deserialize<'de>>(self) -> Result<T> {
T::deserialize(self)
}

/// Returns `self` as a bool, if possible.
// FIXME: Should this not be `try_into_*` ?
// FIXME: Should this not be `try_deserialize_*` ?
pub fn into_bool(self) -> Result<bool> {
match self.kind {
ValueKind::Boolean(value) => Ok(value),
Expand Down Expand Up @@ -197,7 +197,7 @@ impl Value {
}

/// Returns `self` into an i64, if possible.
// FIXME: Should this not be `try_into_*` ?
// FIXME: Should this not be `try_deserialize_*` ?
pub fn into_int(self) -> Result<i64> {
match self.kind {
ValueKind::Integer(value) => Ok(value),
Expand Down Expand Up @@ -242,7 +242,7 @@ impl Value {
}

/// Returns `self` into a f64, if possible.
// FIXME: Should this not be `try_into_*` ?
// FIXME: Should this not be `try_deserialize_*` ?
pub fn into_float(self) -> Result<f64> {
match self.kind {
ValueKind::Float(value) => Ok(value),
Expand Down Expand Up @@ -287,7 +287,7 @@ impl Value {
}

/// Returns `self` into a str, if possible.
// FIXME: Should this not be `try_into_*` ?
// FIXME: Should this not be `try_deserialize_*` ?
pub fn into_str(self) -> Result<String> {
match self.kind {
ValueKind::String(value) => Ok(value),
Expand Down Expand Up @@ -316,7 +316,7 @@ impl Value {
}

/// Returns `self` into an array, if possible
// FIXME: Should this not be `try_into_*` ?
// FIXME: Should this not be `try_deserialize_*` ?
pub fn into_array(self) -> Result<Vec<Value>> {
match self.kind {
ValueKind::Array(value) => Ok(value),
Expand Down Expand Up @@ -356,7 +356,7 @@ impl Value {
}

/// If the `Value` is a Table, returns the associated Map.
// FIXME: Should this not be `try_into_*` ?
// FIXME: Should this not be `try_deserialize_*` ?
pub fn into_table(self) -> Result<HashMap<String, Value>> {
match self.kind {
ValueKind::Table(value) => Ok(value),
Expand Down
6 changes: 3 additions & 3 deletions tests/defaults.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ impl Default for Settings {
#[test]
fn set_defaults() {
let c = Config::new();
let s: Settings = c.try_into().expect("Deserialization failed");
let s: Settings = c.try_deserialize().expect("Deserialization failed");

assert_eq!(s.db_host, "default");
}

#[test]
fn try_from_defaults() {
let c = Config::try_from(&Settings::default()).expect("Serialization failed");
let s: Settings = c.try_into().expect("Deserialization failed");
let c = Config::try_serialize(&Settings::default()).expect("Serialization failed");
let s: Settings = c.try_deserialize().expect("Deserialization failed");
assert_eq!(s.db_host, "default");
}
4 changes: 3 additions & 1 deletion tests/empty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ struct Settings {

#[test]
fn empty_deserializes() {
let s: Settings = Config::new().try_into().expect("Deserialization failed");
let s: Settings = Config::new()
.try_deserialize()
.expect("Deserialization failed");
assert_eq!(s.foo, 0);
assert_eq!(s.bar, 0);
}
12 changes: 6 additions & 6 deletions tests/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn test_error_parse() {
assert_eq!(
res.unwrap_err().to_string(),
format!(
"failed to parse datetime for key `error` at line 2 column 9 in {}",
"invalid TOML value, did you mean to use a quoted string? at line 2 column 9 in {}",
path.display()
)
);
Expand Down Expand Up @@ -56,7 +56,7 @@ fn test_error_type_detached() {
let c = make();

let value = c.get::<Value>("boolean_s_parse").unwrap();
let res = value.try_into::<bool>();
let res = value.try_deserialize::<bool>();

assert!(res.is_err());
assert_eq!(
Expand All @@ -76,14 +76,14 @@ fn test_error_enum_de() {
}

let on_v: Value = "on".into();
let on_d = on_v.try_into::<Diode>();
let on_d = on_v.try_deserialize::<Diode>();
assert_eq!(
on_d.unwrap_err().to_string(),
"enum Diode does not have variant constructor on".to_string()
);

let array_v: Value = vec![100, 100].into();
let array_d = array_v.try_into::<Diode>();
let array_d = array_v.try_deserialize::<Diode>();
assert_eq!(
array_d.unwrap_err().to_string(),
"value of enum Diode should be represented by either string or table with exactly one key"
Expand All @@ -97,7 +97,7 @@ fn test_error_enum_de() {
.cloned()
.collect::<std::collections::HashMap<String, Value>>()
.into();
let confused_d = confused_v.try_into::<Diode>();
let confused_d = confused_v.try_deserialize::<Diode>();
assert_eq!(
confused_d.unwrap_err().to_string(),
"value of enum Diode should be represented by either string or table with exactly one key"
Expand All @@ -122,7 +122,7 @@ inner:

let mut cfg = Config::new();
cfg.merge(File::from_str(CFG, FileFormat::Yaml)).unwrap();
let e = cfg.try_into::<Outer>().unwrap_err();
let e = cfg.try_deserialize::<Outer>().unwrap_err();
if let ConfigError::Type {
key: Some(path), ..
} = e
Expand Down
2 changes: 1 addition & 1 deletion tests/file_hjson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ fn test_file() {
let c = make();

// Deserialize the entire file as single struct
let s: Settings = c.try_into().unwrap();
let s: Settings = c.try_deserialize().unwrap();

assert!(s.debug.approx_eq_ulps(&1.0, 2));
assert_eq!(s.production, Some("false".to_string()));
Expand Down
4 changes: 2 additions & 2 deletions tests/file_ini.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ fn make() -> Config {
#[test]
fn test_file() {
let c = make();
let s: Settings = c.try_into().unwrap();
let s: Settings = c.try_deserialize().unwrap();
assert_eq!(
s,
Settings {
Expand Down Expand Up @@ -64,7 +64,7 @@ fn test_error_parse() {
assert_eq!(
res.unwrap_err().to_string(),
format!(
r#"2:0 Expecting "[Some('='), Some(':')]" but found EOF. in {}"#,
r#"2:0 expecting "[Some('='), Some(':')]" but found EOF. in {}"#,
path.display()
)
);
Expand Down
2 changes: 1 addition & 1 deletion tests/file_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ fn test_file() {
let c = make();

// Deserialize the entire file as single struct
let s: Settings = c.try_into().unwrap();
let s: Settings = c.try_deserialize().unwrap();

assert!(s.debug.approx_eq_ulps(&1.0, 2));
assert_eq!(s.production, Some("false".to_string()));
Expand Down
Loading