use lazy_regex::regex_find; 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 } #[cfg(test)] mod test { use crate::utils::string_utils::apply_env_vars; use std::env; 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)); } }