Skip to main content

solink_config_template/
lib.rs

1#![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
10/// This is a simple templating engine for replacing variables in a YAML file
11/// with environment variables and other custom variables.
12///
13/// This is intended for use on supervisor config and unit files, but it works
14/// on the whole file as a big string and could theoretically be used for anything.
15///
16/// Given a text like "value: ${{FOO}}", this will replace the `${{FOO}}` portion
17/// with the FOO value in the given `variables` HashMap.
18///
19/// If any variables are unrecognized, they will be left unmodified.
20pub 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
27/// Same as `replace`, but uses a `HashMap<&str, T>`.
28pub 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}