From 8391a9a03e6ca08fa7bafbd909aa89c1a98730fa Mon Sep 17 00:00:00 2001 From: elkowar <5300871+elkowar@users.noreply.github.com> Date: Tue, 13 Oct 2020 19:32:58 +0200 Subject: [PATCH] Implement env-var expansion (fixes #11) --- src/config/mod.rs | 2 +- src/util.rs | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/config/mod.rs b/src/config/mod.rs index 314b0a8..c83c43c 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -56,7 +56,7 @@ pub struct EwwConfig { impl EwwConfig { pub fn read_from_file>(path: P) -> Result { - let content = std::fs::read_to_string(path)?; + let content = util::replace_env_var_references(std::fs::read_to_string(path)?); let document = roxmltree::Document::parse(&content)?; let result = EwwConfig::from_xml_element(XmlNode::from(document.root_element()).as_element()?.clone()); diff --git a/src/util.rs b/src/util.rs index f2c4142..2b566ed 100644 --- a/src/util.rs +++ b/src/util.rs @@ -5,8 +5,10 @@ use itertools::Itertools; use serde::{Deserialize, Serialize}; use std::{fmt, path::Path}; +/// read an scss file, replace all environment variable references within it and +/// then parse it into css. pub fn parse_scss_from_file>(path: P) -> Result { - let scss_content = std::fs::read_to_string(path)?; + let scss_content = replace_env_var_references(std::fs::read_to_string(path)?); grass::from_string(scss_content, &grass::Options::default()) .map_err(|err| anyhow!("encountered SCSS parsing error: {:?}", err)) } @@ -63,3 +65,17 @@ impl From<(i32, i32)> for Coords { Coords(x, y) } } + +/// Replace all env-var references of the format `"something $foo"` in a string +/// by the actual env-variables. If the env-var isn't found, will replace the +/// reference with an empty string. +pub fn replace_env_var_references(input: String) -> String { + lazy_static::lazy_static! { + static ref ENV_VAR_PATTERN: regex::Regex = regex::Regex::new(r"\$([^\s]*)").unwrap(); + } + ENV_VAR_PATTERN + .replace_all(&input, |var_name: ®ex::Captures| { + std::env::var(var_name.get(1).unwrap().as_str()).unwrap_or_default() + }) + .into_owned() +}