aboutsummaryrefslogtreecommitdiff
path: root/src/executor.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/executor.rs')
-rw-r--r--src/executor.rs67
1 files changed, 46 insertions, 21 deletions
diff --git a/src/executor.rs b/src/executor.rs
index eccab39..54ca491 100644
--- a/src/executor.rs
+++ b/src/executor.rs
@@ -1,12 +1,11 @@
use crate::barbfile::{BarbFile, BarbFilter};
use crate::output::BarbOutput;
-
+use regex::Regex;
use std::collections::HashMap;
-use ureq;
-use ureq::Error as UreqError;
-
use std::fs;
use std::str::FromStr;
+use ureq;
+use ureq::Error as UreqError;
pub struct Context {
vars: HashMap<String, String>,
@@ -30,22 +29,20 @@ impl Context {
}
}
- // Preserved for future reference
- // pub fn get_var(&self, name: String) -> Option<String> {
- // self.vars
- // .get(&name)
- // .map(|val| val.clone())
- // .or_else(|| env::var(name).ok())
- // }
-
fn key_str(&self, key: &String) -> String {
format!("{{{}}}", key)
}
pub fn substitute(&self, string: &String) -> String {
let mut buffer = string.clone();
- for (key, val) in self.vars.iter() {
- buffer = buffer.replace(self.key_str(key).as_str(), val);
+ let re = Regex::new(r"\{([A-Za-z0-9_]+)\}").unwrap();
+
+ for var in re.captures_iter(string) {
+ let key = String::from(&var[1]);
+ buffer = buffer.replace(
+ self.key_str(&key).as_str(),
+ self.vars.get(&key).or(Some(&String::from(""))).unwrap(),
+ );
}
buffer
@@ -150,11 +147,16 @@ impl Executor {
}
}
-// TODO: tests
#[cfg(test)]
-mod tests {
+mod tests_context {
use super::*;
- use std::str::FromStr;
+
+ fn have_vars() -> Vec<(String, String)> {
+ return vec![
+ (String::from("foo"), String::from("bar")),
+ (String::from("bar"), String::from("baz")),
+ ];
+ }
#[test]
fn test_context_key_str() {
@@ -164,20 +166,43 @@ mod tests {
#[test]
fn test_context_substitute() {
- let vars: Vec<(String, String)> = vec![
- (String::from("foo"), String::from("bar")),
- (String::from("bar"), String::from("baz")),
- ];
+ let vars = have_vars();
let ctx = Context::new(vars.into_iter());
assert_eq!(
ctx.substitute(&String::from("blah blah {foo} blah")),
String::from("blah blah bar blah")
);
+ }
+
+ #[test]
+ fn test_context_substitute_multi() {
+ let vars = have_vars();
+ let ctx = Context::new(vars.into_iter());
assert_eq!(
ctx.substitute(&String::from("blah {foo} {bar} blah")),
String::from("blah bar baz blah")
);
+ assert_eq!(
+ ctx.substitute(&String::from("blah {bar} {foo} blah")),
+ String::from("blah baz bar blah")
+ );
+ }
+
+ #[test]
+ fn test_context_substitute_missing() {
+ let vars: Vec<(String, String)> = vec![];
+ let ctx = Context::new(vars.into_iter());
+ assert_eq!(
+ ctx.substitute(&String::from("blah blah {foo} blah")),
+ String::from("blah blah blah")
+ );
}
+}
+
+#[cfg(test)]
+mod tests_make_req {
+ use super::*;
+ use std::str::FromStr;
#[test]
fn test_make_req_simple_get() {