summaryrefslogtreecommitdiffstats
path: root/crates/driver/src/template.rs
blob: 1a091edfa050a87ee52fd4f284a97832c93d4951 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use handlebars::Handlebars;
use lazy_static::lazy_static;

use common::error::*;

use crate::args::TaskArgs;

fn escape_sh(s: &str) -> String {
	format!("'{}'", s.replace('\'', "'\\''"))
}

#[derive(Debug)]
pub struct TemplateEngine {
	tpl: Handlebars<'static>,
	tpl_sh: Handlebars<'static>,
}

impl TemplateEngine {
	pub fn new() -> Self {
		let mut tpl = Handlebars::new();
		tpl.set_strict_mode(true);
		tpl.register_escape_fn(handlebars::no_escape);

		let mut tpl_sh = Handlebars::new();
		tpl_sh.set_strict_mode(true);
		tpl_sh.register_escape_fn(escape_sh);

		TemplateEngine { tpl, tpl_sh }
	}

	pub fn eval(&self, input: &str, args: &TaskArgs) -> Result<String> {
		self.tpl.render_template(input, args).map_err(Error::new)
	}

	pub fn eval_sh(&self, input: &str, args: &TaskArgs) -> Result<String> {
		self.tpl_sh.render_template(input, args).map_err(Error::new)
	}
}

lazy_static! {
	pub static ref ENGINE: TemplateEngine = TemplateEngine::new();
}