codegenr_lib/
custom.rs

1use glob::PatternError;
2use handlebars::Handlebars;
3use std::path::Path;
4use thiserror::Error;
5
6#[derive(Error, Debug)]
7pub enum CustomError {
8  #[error("Script Error: `{0}`.")]
9  ScriptError(String),
10  #[error("Pattern Error: `{0}`.")]
11  PatternError(#[from] PatternError),
12  #[error("Error converting PathBuf to str.")]
13  PathBufToStrConvert,
14  #[error("File path passed has no file stem.")]
15  NoFileStem,
16  #[error("Couldn't convert OsStr to str.")]
17  OsStrConvertError,
18}
19
20pub fn handlebars_setup(handlebars: &mut Handlebars, custom_helpers_folders: &[String]) -> Result<(), CustomError> {
21  for path in custom_helpers_folders {
22    let p = Path::new(&path);
23    if p.is_file() {
24      handlebars_add_script(handlebars, p)?;
25    } else if p.is_dir() {
26      let pattern = p.join("**/*.rhai");
27      let str_pattern = pattern.to_str().ok_or(CustomError::PathBufToStrConvert)?;
28      for f in glob::glob(str_pattern)?.flatten() {
29        handlebars_add_script(handlebars, f.as_path())?;
30      }
31    }
32  }
33  Ok(())
34}
35
36pub fn handlebars_add_script(handlebars: &mut Handlebars, script_file: impl AsRef<Path> + Clone) -> Result<(), CustomError> {
37  let name = script_file
38    .as_ref()
39    .file_stem()
40    .ok_or(CustomError::NoFileStem)?
41    .to_str()
42    .ok_or(CustomError::OsStrConvertError)?;
43
44  handlebars
45    .register_script_helper_file(name, script_file.clone())
46    .map_err(|script_error| CustomError::ScriptError(format!("{}", script_error)))?;
47
48  Ok(())
49}
50
51#[cfg(test)]
52mod test {
53  use super::*;
54  use serde_json::json;
55
56  pub fn exec_template(json: serde_json::Value, template: &str) -> String {
57    let mut h = Handlebars::new();
58    handlebars_setup(
59      &mut h,
60      &["./_samples/rhai/param_0_len.rhai".into(), "./_samples/rhai/concat.rhai".into()],
61    )
62    .expect("Could not setup handlebars.");
63    h.register_template_string("test", template).expect("Could not register template.");
64    h.render("test", &json).expect("Template render returned an error.")
65  }
66
67  #[test]
68  fn tests() {
69    assert_eq!(exec_template(json!({}), "{{param_0_len \"plop\"}}"), "4");
70    assert_eq!(exec_template(json!({"a": "aa", "b": "bb"}), "{{concat a b}}"), "aabb");
71  }
72}