From 1dd0359d4c2f051eb4679bd016c16686265691f3 Mon Sep 17 00:00:00 2001 From: fdai7451 Date: Sat, 21 Jan 2023 18:30:50 +0100 Subject: [PATCH] feat: add env variable resolving to preprocessing --- src/preprocess.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/preprocess.rs b/src/preprocess.rs index 74eedf4..350b909 100644 --- a/src/preprocess.rs +++ b/src/preprocess.rs @@ -4,10 +4,11 @@ use regex::Regex; use std::env; const ENV_SET: Lazy = Lazy::new(|| Regex::new(r#"(?P\w+)=(?P\w*)"#).unwrap()); +const ENV_VARIABLE: Lazy = Lazy::new(|| Regex::new(r"(\\\$|\$(?P\w+))").unwrap()); /// Returns `Ok(Some(...))` if a command should be triggered after calling this functions. If it /// returns `Ok(None)`, do not execute a command. -pub fn preprocess(line: String) -> Result, ShellError> { +pub fn preprocess(mut line: String) -> Result, ShellError> { if let Some(capture) = ENV_SET.captures(&line) { let key = capture.name("key").unwrap().as_str(); let value = capture @@ -18,6 +19,16 @@ pub fn preprocess(line: String) -> Result, ShellError> { return Ok(None); } + for capture in ENV_VARIABLE.captures_iter(&line.clone()) { + let variable_name = capture.name("env").unwrap().as_str(); + if variable_name.is_empty() { + continue; + } + let value = env::var(variable_name).unwrap_or_default(); + + line = ENV_VARIABLE.replacen(&line, 1, &value).to_string(); + } + Ok(Some(line)) }