Documentation
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(())
}