1use crate::template::get_default_template;
2
3use std::fs;
4
5pub fn init(template: Option<String>, cfg_path: &str) -> Result<(), String> {
8 if fs::metadata(cfg_path).is_ok() {
10 Err(String::from("A Bonnie configuration file already exists in this directory. If you want to create a new one, please delete the old one first."))
11 } else {
12 let output;
14 if matches!(template, Some(_)) && fs::metadata(template.as_ref().unwrap()).is_ok() {
15 let template_path = template.unwrap();
16 let contents = fs::read_to_string(&template_path);
18 let contents = match contents {
19 Ok(contents) => contents,
20 Err(_) => return Err(format!("An error occurred while attempting to read the given template file '{}'. Please make sure the file exists and you have the permissions necessary to read from it.", &template_path))
21 };
22 output = fs::write(cfg_path, contents);
23 } else if matches!(template, Some(_)) && fs::metadata(template.as_ref().unwrap()).is_err() {
24 return Err(format!("The given template file at '{}' does not exist or can't be read. Please make sure the file exists and you have the permissions necessary to read from it.", template.as_ref().unwrap()));
26 } else {
27 let template = get_default_template()?;
30 output = fs::write(cfg_path, template);
31 }
32
33 match output {
34 Ok(_) => Ok(()),
35 Err(_) => Err(format!("Error creating new {}, make sure you have the permissions to write to this directory.", cfg_path))
36 }
37 }
38}