preftool_env/
lib.rs

1use preftool::*;
2use std::env;
3
4/// Represents environment variables as a configuration source.
5pub struct EnvironmentVariablesConfigurationSource {
6  prefix: ConfigKey,
7}
8
9impl EnvironmentVariablesConfigurationSource {
10  pub fn new() -> Self {
11    Self {
12      prefix: ConfigKey::empty(),
13    }
14  }
15
16  pub fn with_prefix<S: Into<ConfigKey>>(prefix: S) -> Self {
17    Self {
18      prefix: prefix.into(),
19    }
20  }
21}
22
23impl Default for EnvironmentVariablesConfigurationSource {
24  fn default() -> Self {
25    Self::new()
26  }
27}
28
29impl ConfigurationSource for EnvironmentVariablesConfigurationSource {
30  fn build<B: ConfigurationBuilder>(self, builder: B) -> std::io::Result<B> {
31    let prefix = self.prefix.as_ref();
32    let mut provider = ConfigurationProviderBuilder::new();
33    for (name, value) in env::vars_os().filter_map(|(key, value)| {
34      if let Ok(key) = key.into_string() {
35        if let Ok(value) = value.into_string() {
36          let key: String = ConfigKey::from(key).into();
37          if key.starts_with(prefix) {
38            Some((key, value))
39          } else {
40            None
41          }
42        } else {
43          None
44        }
45      } else {
46        None
47      }
48    }) {
49      let key = name[prefix.len()..].replace("__", ":");
50      provider.add(key, value);
51    }
52
53    Ok(builder.push_provider(provider.build()))
54  }
55}