auric-build 0.1.0

Codegen module for the `auric` MVC SPA framework
Documentation
use handlebars::Handlebars;
use serde::Serialize;
use std::collections::HashMap;
use std::path::Path;

const TEMPLATE_RS: &str = include_str!("assets/src/template_importer.rs.hbs");

#[derive(Default)]
pub struct TemplateImporter {}

#[derive(Clone, Debug, Serialize)]
struct TemplateFile {
    name: String,
    path: String,
}

impl TemplateImporter {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn generate(&self, root: &Path) -> anyhow::Result<()> {
        // Find files
        let templates_path = Path::new("src/templates");
        let mut template_files = vec![];
        let walker = globwalk::GlobWalkerBuilder::from_patterns(templates_path, &["*.hbs"])
            .max_depth(10)
            .follow_links(true)
            .build()?;
        for maybe_dir_entry in walker {
            let dir_entry = maybe_dir_entry?;
            let name = dir_entry
                .path()
                .display()
                .to_string()
                .replace(".hbs", "")
                .replace("/", ".")
                .replace("src.templates.", "");
            let path = Path::new("../..").join(dir_entry.path());
            template_files.push(TemplateFile {
                name: name.to_string(),
                path: path.display().to_string(),
            });
        }

        // Generate source file
        let mut data = HashMap::new();
        data.insert("templateFiles", template_files);
        let mut handlebars = Handlebars::new();
        const TEMPLATE: &str = "generator";
        handlebars.register_template_string(TEMPLATE, TEMPLATE_RS)?;
        let contents = handlebars.render(TEMPLATE, &data)?;

        // Write file
        std::fs::create_dir_all(root.join("src/generated"))?;
        std::fs::write("src/generated/template_importer.rs", contents)?;
        Ok(())
    }
}