Skip to main content

auric_build/
template_importer.rs

1use handlebars::Handlebars;
2use serde::Serialize;
3use std::collections::HashMap;
4use std::path::Path;
5
6const TEMPLATE_RS: &str = include_str!("assets/src/template_importer.rs.hbs");
7
8#[derive(Default)]
9pub struct TemplateImporter {}
10
11#[derive(Clone, Debug, Serialize)]
12struct TemplateFile {
13    name: String,
14    path: String,
15}
16
17impl TemplateImporter {
18    pub fn new() -> Self {
19        Self::default()
20    }
21
22    pub fn generate(&self, root: &Path) -> anyhow::Result<()> {
23        // Find files
24        let templates_path = Path::new("src/templates");
25        let mut template_files = vec![];
26        let walker = globwalk::GlobWalkerBuilder::from_patterns(templates_path, &["*.hbs"])
27            .max_depth(10)
28            .follow_links(true)
29            .build()?;
30        for maybe_dir_entry in walker {
31            let dir_entry = maybe_dir_entry?;
32            let name = dir_entry
33                .path()
34                .display()
35                .to_string()
36                .replace(".hbs", "")
37                .replace("/", ".")
38                .replace("src.templates.", "");
39            let path = Path::new("../..").join(dir_entry.path());
40            template_files.push(TemplateFile {
41                name: name.to_string(),
42                path: path.display().to_string(),
43            });
44        }
45
46        // Generate source file
47        let mut data = HashMap::new();
48        data.insert("templateFiles", template_files);
49        let mut handlebars = Handlebars::new();
50        const TEMPLATE: &str = "generator";
51        handlebars.register_template_string(TEMPLATE, TEMPLATE_RS)?;
52        let contents = handlebars.render(TEMPLATE, &data)?;
53
54        // Write file
55        std::fs::create_dir_all(root.join("src/generated"))?;
56        std::fs::write("src/generated/template_importer.rs", contents)?;
57        Ok(())
58    }
59}