implement loading config from environment

This still has the bug, that envy conflicts with serde's
deny_unknown_fields option.

For the time being use e.g.
```
env -i VAULTWARDEN_URL=https://example.com vaultwarden_ldap
```
This commit is contained in:
Tobias Florek 2021-05-19 09:01:46 +02:00 committed by ViViDboarder
parent 5238bc1b60
commit f25278ea3c
3 changed files with 723 additions and 687 deletions

1360
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -12,3 +12,4 @@ reqwest = "0.9"
serde_json = "1.0"
thiserror = "1.0"
anyhow = "1.0"
envy = "0.4.1"

View File

@ -17,21 +17,46 @@ pub fn get_config_path() -> String {
}
}
/// Reads configuration from file and panics if it can't
// Tries to read configuration from file, failing that from the environment,
// panics if it can't
pub fn read_config() -> Config {
let config_path = get_config_path();
let contents = fs::read_to_string(&config_path).unwrap_or_else(|_| {
panic!("Failed to open config file at {}", config_path);
});
let config: Config = toml::from_str(contents.as_str()).unwrap_or_else(|_| {
panic!("Failed to parse config file at {}", config_path);
});
config
match read_config_from_file() {
Ok(config) => config,
Err(err) => {
println!("{}", err);
match read_config_from_env() {
Ok(config) => config,
Err(err) => panic!("{}", err)
}
}
}
}
#[derive(Deserialize)]
/// Tries to read configuration from file
pub fn read_config_from_file() -> Result<Config, String> {
let config_path = get_config_path();
let contents = fs::read_to_string(&config_path).map_err(|_| {
format!("Failed to open config file at {}", config_path)
})?;
let config: Config = toml::from_str(contents.as_str()).map_err(|_| {
format!("Failed to parse config file at {}", config_path)
})?;
println!("Reading config from file at {}", config_path);
Ok(config)
}
// Tries to read configuration from environment
pub fn read_config_from_env() -> Result<Config, String> {
let config = envy::from_env().map_err(|err| {
format!("error parsing config from env: {}", err)
})?;
println!("Reading config from environment");
Ok(config)
}
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
/// Contains all config values for LDAP syncing
pub struct Config {