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 let Some(template_path) = template {
15 if fs::metadata(&template_path).is_ok() {
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 {
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_path));
26 }
27 } else {
28 let template = get_default_template()?;
31 output = fs::write(cfg_path, template);
32 }
33
34 match output {
35 Ok(_) => Ok(()),
36 Err(_) => Err(format!("Error creating new {}, make sure you have the permissions to write to this directory.", cfg_path))
37 }
38 }
39}