1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use preftool::*;
use std::env;

/// Represents environment variables as a configuration source.
pub struct EnvironmentVariablesConfigurationSource {
  prefix: ConfigKey,
}

impl EnvironmentVariablesConfigurationSource {
  pub fn new() -> Self {
    Self {
      prefix: ConfigKey::empty(),
    }
  }

  pub fn with_prefix<S: Into<ConfigKey>>(prefix: S) -> Self {
    Self {
      prefix: prefix.into(),
    }
  }
}

impl Default for EnvironmentVariablesConfigurationSource {
  fn default() -> Self {
    Self::new()
  }
}

impl ConfigurationSource for EnvironmentVariablesConfigurationSource {
  fn build<B: ConfigurationBuilder>(self, builder: B) -> std::io::Result<B> {
    let prefix = self.prefix.as_ref();
    let mut provider = ConfigurationProviderBuilder::new();
    for (name, value) in env::vars_os().filter_map(|(key, value)| {
      if let Ok(key) = key.into_string() {
        if let Ok(value) = value.into_string() {
          let key: String = ConfigKey::from(key).into();
          if key.starts_with(prefix) {
            Some((key, value))
          } else {
            None
          }
        } else {
          None
        }
      } else {
        None
      }
    }) {
      let key = name[prefix.len()..].replace("__", ":");
      provider.add(key, value);
    }

    Ok(builder.push_provider(provider.build()))
  }
}