comtrya_lib/tera_functions/
mod.rs1use tera::{Function, Result, Tera, Value};
2
3pub struct ReadFileContents;
4
5impl Function for ReadFileContents {
6 fn call(&self, args: &std::collections::HashMap<String, Value>) -> Result<Value> {
7 match args.get("path") {
8 Some(value) => match value.as_str() {
9 Some(path) => match std::fs::read_to_string(path) {
10 Ok(content) => Ok(content.trim().into()),
11 Err(err) => Err(err.into()),
12 },
13
14 None => Err(format!(
15 "Path: '{}'. Error: Cannot convert argument 'path' to str",
16 value
17 )
18 .into()),
19 },
20
21 None => Err("Argument 'path' not set".into()),
22 }
23 }
24}
25
26pub fn register_functions(tera: &mut Tera) {
27 tera.register_function("read_file_contents", ReadFileContents);
28}
29
30#[cfg(test)]
31mod test {
32 use super::*;
33 use std::io::Write;
34 use tera::{Context, Tera};
35
36 #[test]
37 fn can_read_from_file() -> anyhow::Result<()> {
38 let mut tera = Tera::default();
39 tera.register_function("read_file_contents", ReadFileContents);
40
41 let mut file = tempfile::NamedTempFile::new()?;
42
43 let file_content = r#"
44FKBR
45KUCI
46SXOE
47
48"#;
49
50 write!(file.as_file_mut(), "{}", file_content)?;
51
52 let template = format!(
53 "{{{{ read_file_contents(path=\"{}\") }}}}",
54 file.path().display()
55 );
56
57 let content = tera.render_str(&template, &Context::new())?;
58
59 let expected_file_content = r#"FKBR
60KUCI
61SXOE"#;
62
63 assert_eq!(expected_file_content, content);
64
65 Ok(())
66 }
67}