auric-build 0.1.0-rc.2

Codegen module for the `auric` MVC SPA framework
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, inpath: &Path, outpath: &Path) -> anyhow::Result<()> {
        // Find files
        let mut template_files = vec![];
        let walker = globwalk::GlobWalkerBuilder::from_patterns(inpath, &["*.hbs"])
            .max_depth(10)
            .follow_links(true)
            .build()?;
        let root = Path::new(env!("PWD"));
        for maybe_dir_entry in walker {
            let dir_entry = maybe_dir_entry?;
            let name = dir_entry
                .path()
                .strip_prefix(inpath)?
                .display()
                .to_string()
                .replace(".hbs", "")
                .replace("/", ".");
            let path = Path::new("../..").join(dir_entry.path().strip_prefix(root.display().to_string())?);
            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(outpath.parent().unwrap())?;
        std::fs::write(outpath, contents)?;
        Ok(())
    }
}