FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

add support of hashmap in environment variables by bnjjj · Pull Request #52 · softprops/envy · GitHub

/ envy Public
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .rs  (2) .toml  (1) All 2 file types selected
Only manifest files
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
3 changes: 2 additions & 1 deletion Cargo.toml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ coveralls = { repository = "softprops/envy" }
travis-ci = { repository = "softprops/envy" }

[dependencies]
regex = "1.4.1"
serde = "1.0"

[dev-dependencies]
serde = { version = "1.0", features = ["derive"] }
serde = { version = "1.0", features = ["derive"] }
8 changes: 7 additions & 1 deletion examples/prefixed.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
use std::collections::HashMap;

use serde::Deserialize;

#[derive(Deserialize)]
struct Config {
bar: Option<String>,
foo: HashMap<String, String>, // Must be formatted like "{key:value,key2:value2}"
}

fn main() {
match envy::prefixed("FOO_").from_env::<Config>() {
Ok(config) => println!("provided config.bar {:?}", config.bar),
Ok(config) => println!(
"provided config.bar {:?} and config.foo {:?}",
config.bar, config.foo
),
Err(err) => println!("error parsing config from env: {}", err),
}
}
65 changes: 50 additions & 15 deletions src/lib.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
//! }
//! ```

use regex::Regex;
use serde::de::{
self,
value::{MapDeserializer, SeqDeserializer},
Expand All @@ -75,6 +76,7 @@ struct Vars<Iter>(Iter)
where
Iter: IntoIterator<Item = (String, String)>;

#[derive(Debug)]
struct Val(String, String);

impl<'de> IntoDeserializer<'de, Error> for Val {
Expand All @@ -85,6 +87,7 @@ impl<'de> IntoDeserializer<'de, Error> for Val {
}
}

#[derive(Debug)]
struct VarName(String);

impl<'de> IntoDeserializer<'de, Error> for VarName {
Expand Down Expand Up @@ -191,9 +194,35 @@ impl<'de> de::Deserializer<'de> for Val {
visitor.visit_enum(self.1.into_deserializer())
}

fn deserialize_map<V>(
self,
visitor: V,
) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
let hashmap_reg = Regex::new(r#"(?P<key>[^{=]+)=(?P<value>[^,}]*),?"#).unwrap();
if !self.1.is_empty() && !hashmap_reg.is_match(&self.1)
{
return Err(Error::Custom(format!(
"{} is malformated for a map (must be 'key=value,key2=value2')",
self.0
)));
}

let map = hashmap_reg.captures_iter(&self.1).map(|ref caps| {
(
caps["key"].trim().to_string(),
caps["value"].trim().to_string(),
)
});

visitor.visit_map(MapDeserializer::new(map))
}

serde::forward_to_deserialize_any! {
char str string unit
bytes byte_buf map unit_struct tuple_struct
bytes byte_buf unit_struct tuple_struct
identifier tuple ignored_any
struct
}
Expand Down Expand Up @@ -225,12 +254,11 @@ impl<'de> de::Deserializer<'de> for VarName {

serde::forward_to_deserialize_any! {
char str string unit seq option
bytes byte_buf map unit_struct tuple_struct
identifier tuple ignored_any enum
bytes byte_buf unit_struct tuple_struct
identifier tuple ignored_any enum map
struct bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64
}
}

/// A deserializer for env vars
struct Deserializer<'de, Iter: Iterator<Item = (String, String)>> {
inner: MapDeserializer<'de, Vars<Iter>, Error>,
Expand Down Expand Up @@ -270,9 +298,8 @@ impl<'de, Iter: Iterator<Item = (String, String)>> de::Deserializer<'de>

serde::forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
bytes byte_buf unit_struct tuple_struct
bytes byte_buf unit_struct tuple_struct struct
identifier tuple ignored_any option newtype_struct enum
struct
}
}

Expand Down Expand Up @@ -317,13 +344,10 @@ impl<'a> Prefixed<'a> {
T: de::DeserializeOwned,
Iter: IntoIterator<Item = (String, String)>,
{
crate::from_iter(iter.into_iter().filter_map(|(k, v)| {
if k.starts_with(self.0.as_ref()) {
Some((k.trim_start_matches(self.0.as_ref()).to_owned(), v))
} else {
None
}
}))
crate::from_iter(
iter.into_iter()
.filter_map(|(k, v)| k.strip_prefix(self.0.as_ref()).map(|k| (k.to_string(), v))),
)
}
}

Expand Down Expand Up @@ -397,6 +421,7 @@ mod tests {
size: Size,
provided: Option<String>,
newtype: CustomNewType,
map: Option<HashMap<String, String>>,
}

#[test]
Expand All @@ -421,7 +446,8 @@ mod tests {
debug_mode: false,
size: Size::Small,
provided: Some(String::from("test")),
newtype: CustomNewType(42)
newtype: CustomNewType(42),
map: None,
}
),
Err(e) => panic!("{:#?}", e),
Expand Down Expand Up @@ -465,7 +491,15 @@ mod tests {
(String::from("APP_SIZE"), String::from("small")),
(String::from("APP_PROVIDED"), String::from("test")),
(String::from("APP_NEWTYPE"), String::from("42")),
(
String::from("APP_MAP"),
String::from("key=value, key2=value2"),
),
];
let mut map = HashMap::new();
map.insert(String::from("key"), String::from("value"));
map.insert(String::from("key2"), String::from("value2"));

match prefixed("APP_").from_iter::<_, Foo>(data) {
Ok(actual) => assert_eq!(
actual,
Expand All @@ -478,7 +512,8 @@ mod tests {
debug_mode: false,
size: Size::Small,
provided: Some(String::from("test")),
newtype: CustomNewType(42)
newtype: CustomNewType(42),
map: Some(map)
}
),
Err(e) => panic!("{:#?}", e),
Expand Down

Back | FazBrowse Home | New Git URL