use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use include_dir::Dir;
use text_placeholder::Template;
use crate::MyConfig;
pub fn init_template(dir: &Dir, conf: &MyConfig) -> Result<(), Box<dyn Error>> {
let project_name = conf.name.as_ref().unwrap();
let project_title = conf.title.as_ref().unwrap_or(project_name);
for entry in dir.entries() {
if let Some(x) = entry.as_dir() {
init_template(x, conf)?;
} else {
let file_path = entry.path();
let mut output_path_buf = PathBuf::new();
output_path_buf.push(project_name);
output_path_buf.push(file_path);
let output_path = output_path_buf.to_str().unwrap();
let parent_dir = std::path::Path::new(output_path).parent().unwrap();
fs::create_dir_all(parent_dir)?;
let mut file = File::create(output_path)?;
if let Some(content) = entry.as_file().unwrap().contents_utf8() {
let tt = Template::new_with_placeholder(content, "<%", "%>");
let mut map = HashMap::new();
map.insert("name", project_name.as_str());
map.insert("title", project_title.as_str());
let new_content = tt.fill_with_hashmap(&map);
file.write_all(new_content.as_bytes())?;
} else {
file.write_all(entry.as_file().unwrap().contents())?;
}
}
}
Ok(())
}