2019-09-26 08:30:58 +00:00
|
|
|
use std::env;
|
|
|
|
|
2019-11-07 03:38:30 +00:00
|
|
|
use super::{Context, Module, SegmentConfig};
|
2019-09-26 08:30:58 +00:00
|
|
|
|
2019-10-15 11:34:48 +00:00
|
|
|
use crate::config::RootModuleConfig;
|
|
|
|
use crate::configs::env_var::EnvVarConfig;
|
|
|
|
|
2019-09-26 08:30:58 +00:00
|
|
|
/// Creates a module with the value of the chosen environment variable
|
|
|
|
///
|
|
|
|
/// Will display the environment variable's value if all of the following criteria are met:
|
|
|
|
/// - env_var.disabled is absent or false
|
|
|
|
/// - env_var.variable is defined
|
|
|
|
/// - a variable named as the value of env_var.variable is defined
|
|
|
|
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
|
|
|
|
let mut module = context.new_module("env_var");
|
2019-10-15 11:34:48 +00:00
|
|
|
let config: EnvVarConfig = EnvVarConfig::try_load(module.config);
|
2019-09-26 08:30:58 +00:00
|
|
|
|
2019-10-15 11:34:48 +00:00
|
|
|
let env_value = get_env_value(config.variable?, config.default)?;
|
2019-09-26 08:30:58 +00:00
|
|
|
|
2019-10-15 11:34:48 +00:00
|
|
|
module.set_style(config.style);
|
|
|
|
module.get_prefix().set_value("with ");
|
2019-09-26 08:30:58 +00:00
|
|
|
|
2019-10-15 11:34:48 +00:00
|
|
|
if let Some(symbol) = config.symbol {
|
|
|
|
module.create_segment("symbol", &symbol);
|
|
|
|
}
|
2019-09-26 08:30:58 +00:00
|
|
|
|
2019-10-15 11:34:48 +00:00
|
|
|
// TODO: Use native prefix and suffix instead of stacking custom ones together with env_value.
|
2019-11-07 03:38:30 +00:00
|
|
|
let env_var_stacked = format!("{}{}{}", config.prefix, env_value, config.suffix);
|
|
|
|
module.create_segment("env_var", &SegmentConfig::new(&env_var_stacked));
|
2019-09-26 08:30:58 +00:00
|
|
|
|
|
|
|
Some(module)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_env_value(name: &str, default: Option<&str>) -> Option<String> {
|
|
|
|
match env::var_os(name) {
|
|
|
|
Some(os_value) => match os_value.into_string() {
|
|
|
|
Ok(value) => Some(value),
|
|
|
|
Err(_error) => None,
|
|
|
|
},
|
|
|
|
None => default.map(|value| value.to_owned()),
|
|
|
|
}
|
|
|
|
}
|