BasicOIDC/src/utils/string_utils.rs

33 lines
985 B
Rust
Raw Normal View History

use lazy_regex::regex_find;
2022-04-07 16:59:48 +00:00
use rand::distributions::Alphanumeric;
use rand::Rng;
/// Generate a random string of a given size
pub fn rand_str(len: usize) -> String {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.map(char::from)
.take(len)
.collect()
}
/// Parse environment variables
pub fn apply_env_vars(val: &str) -> String {
let mut val = val.to_string();
if let Some(varname_with_wrapper) = regex_find!(r#"\$\{[a-zA-Z0-9_-]+\}"#, &val) {
let varname = varname_with_wrapper.strip_prefix("${").unwrap().strip_suffix('}').unwrap();
let value = match std::env::var(varname) {
Ok(v) => v,
Err(e) => {
log::error!("Failed to find environment variable {}!", varname);
eprintln!("Failed to find environment variable! {:?}", e);
std::process::exit(2);
}
};
val = val.replace(varname_with_wrapper, &value);
}
val
}