diff options
author | Conrad Ludgate <conrad.ludgate@truelayer.com> | 2022-02-24 09:28:03 +0000 |
---|---|---|
committer | Conrad Ludgate <conrad.ludgate@truelayer.com> | 2022-02-24 10:20:46 +0000 |
commit | e8985eacc7de0fb1916ab20a7bb40b9851c0f7da (patch) | |
tree | 56170583fcf6c912f5f6a9ef5a04ba02861ee782 | |
parent | 30d87a311929f5382cb4ecd1de62f20d2dddfb86 (diff) |
add prefix separator support
-rw-r--r-- | src/env.rs | 17 | ||||
-rw-r--r-- | tests/env.rs | 13 |
2 files changed, 28 insertions, 2 deletions
@@ -16,6 +16,9 @@ pub struct Environment { /// For example, the key `CONFIG_DEBUG` would become `DEBUG` with a prefix of `config`. prefix: Option<String>, + /// Optional character sequence that separates the prefix from the rest of the key + prefix_separator: Option<String>, + /// Optional character sequence that separates each key segment in an environment key pattern. /// Consider a nested configuration such as `redis.password`, a separator of `_` would allow /// an environment key of `REDIS_PASSWORD` to match. @@ -84,6 +87,12 @@ impl Environment { } #[must_use] + pub fn prefix_separator(mut self, s: &str) -> Self { + self.prefix_separator = Some(s.into()); + self + } + + #[must_use] pub fn separator(mut self, s: &str) -> Self { self.separator = Some(s.into()); self @@ -120,13 +129,17 @@ impl Source for Environment { let uri: String = "the environment".into(); let separator = self.separator.as_deref().unwrap_or(""); - let group_separator = self.separator.as_deref().unwrap_or("_"); + let prefix_separator = match (self.prefix_separator.as_deref(), self.separator.as_deref()) { + (Some(pre), _) => pre, + (None, Some(sep)) => sep, + (None, None) => "_", + }; // Define a prefix pattern to test and exclude from keys let prefix_pattern = self .prefix .as_ref() - .map(|prefix| format!("{}{}", prefix, group_separator).to_lowercase()); + .map(|prefix| format!("{}{}", prefix, prefix_separator).to_lowercase()); let collector = |(key, value): (String, String)| { // Treat empty environment variables as unset diff --git a/tests/env.rs b/tests/env.rs index edd8dff..90852e0 100644 --- a/tests/env.rs +++ b/tests/env.rs @@ -86,6 +86,19 @@ fn test_custom_separator_behavior() { } #[test] +fn test_custom_prefix_separator_behavior() { + env::set_var("C-B.A", "abc"); + + let environment = Environment::with_prefix("C") + .separator(".") + .prefix_separator("-"); + + assert!(environment.collect().unwrap().contains_key("b.a")); + + env::remove_var("C-B.A"); +} + +#[test] fn test_parse_int() { // using a struct in an enum here to make serde use `deserialize_any` #[derive(Deserialize, Debug)] |