solink_config_template/
lib.rs1#![doc = include_str!("../README.md")]
2
3use std::collections::HashMap;
4
5use new_string_template::template::Template;
6use regex::Regex;
7
8const PATTERN: &str = r"(?mi)\$\{\{\s*([^ \}]+)\s*\}\}";
9
10pub fn replace<T: AsRef<str>>(input: &str, variables: &HashMap<String, T>) -> String {
21 let pattern = Regex::new(PATTERN).unwrap();
22 let template = Template::new(input).with_regex(&pattern);
23
24 template.render_nofail_string(variables)
25}
26
27pub fn replace_str<T: AsRef<str>>(input: &str, variables: &HashMap<&str, T>) -> String {
29 let pattern = Regex::new(PATTERN).unwrap();
30 let template = Template::new(input).with_regex(&pattern);
31
32 template.render_nofail(variables)
33}
34
35#[cfg(test)]
36mod tests {
37 use super::*;
38
39 #[test]
40 fn should_work() {
41 let mut map = HashMap::new();
42 map.insert(String::from("TEST"), String::from("value"));
43
44 assert_eq!(replace("a ${{TEST}} b", &map), String::from("a value b"));
45
46 assert_eq!(
47 replace("a ${{MISSING}} b", &map),
48 String::from("a ${{MISSING}} b")
49 );
50
51 assert_eq!(
52 replace("a ${{TEST}} ${{TEST}} b", &map),
53 String::from("a value value b")
54 );
55
56 assert_eq!(replace("a ${{ TEST }} b", &map), String::from("a value b"));
57 }
58}