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<()> {
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(),
});
}
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)?;
std::fs::create_dir_all(root.join("src/generated"))?;
std::fs::write("src/generated/template_importer.rs", contents)?;
Ok(())
}
}