codegenr_lib/
custom.rs

1use handlebars::Handlebars;
2use std::path::Path;
3
4pub fn handlebars_setup(handlebars: &mut Handlebars, custom_helpers_folders: Vec<String>) -> Result<(), anyhow::Error> {
5  for path in custom_helpers_folders {
6    let p = Path::new(&path);
7    if p.is_file() {
8      handlebars_add_script(handlebars, p)?;
9    } else if p.is_dir() {
10      let pattern = p.join("**/*.rhai");
11      let str_pattern = pattern
12        .to_str()
13        .ok_or_else(|| anyhow::anyhow!("Error converting PathBuf to str."))?;
14      for f in glob::glob(str_pattern)?.flatten() {
15        handlebars_add_script(handlebars, f.as_path())?;
16      }
17    }
18  }
19  Ok(())
20}
21
22pub fn handlebars_add_script(handlebars: &mut Handlebars, script_file: impl AsRef<Path> + Clone) -> Result<(), anyhow::Error> {
23  let name = script_file
24    .as_ref()
25    .file_stem()
26    .ok_or_else(|| anyhow::anyhow!("File path passed has no file stem."))?
27    .to_str()
28    .ok_or_else(|| anyhow::anyhow!("Error converting OsStr to str."))?;
29  handlebars.register_script_helper_file(name, script_file.clone())?;
30  Ok(())
31}
32
33#[cfg(test)]
34mod test {
35  use super::*;
36  use serde_json::json;
37
38  pub fn exec_template(json: serde_json::Value, template: &str) -> String {
39    let mut h = Handlebars::new();
40    handlebars_setup(
41      &mut h,
42      vec!["./_samples/rhai/param_0_len.rhai".into(), "./_samples/rhai/concat.rhai".into()],
43    )
44    .expect("Could not setup handlebars.");
45    h.register_template_string("test", template).expect("Could not register template.");
46    h.render("test", &json).expect("Template render returned an error.")
47  }
48
49  #[test]
50  fn tests() {
51    assert_eq!(exec_template(json!({}), "{{param_0_len \"plop\"}}"), "4");
52    assert_eq!(exec_template(json!({"a": "aa", "b": "bb"}), "{{concat a b}}"), "aabb");
53  }
54}