BasicOIDC/src/utils/string_utils.rs

55 lines
1.5 KiB
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
2022-08-20 07:30:36 +00:00
}
#[cfg(test)]
mod test {
use std::env;
use crate::utils::string_utils::apply_env_vars;
const VAR_ONE: &str = "VAR_ONE";
#[test]
fn test_apply_env_var() {
env::set_var(VAR_ONE, "good");
let src = format!("This is ${{{}}}", VAR_ONE);
assert_eq!("This is good", apply_env_vars(&src));
}
const VAR_INVALID: &str = "VAR_INV@LID";
#[test]
fn test_invalid_var_syntax() {
let src = format!("This is ${{{}}}", VAR_INVALID);
assert_eq!(src, apply_env_vars(&src));
}
}