lib/
init.rs

1use crate::template::get_default_template;
2
3use std::fs;
4
5// Creates a new Bonnie configuration file using a template, or from the default
6// This takes the path to write to (set through 'BONNIE_CONF' or default `./bonnie.toml`)
7pub fn init(template: Option<String>, cfg_path: &str) -> Result<(), String> {
8    // Check if there's already a config file in this directory
9    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        // Check if a template has been given
13        let output;
14        if matches!(template, Some(_)) && fs::metadata(template.as_ref().unwrap()).is_ok() {
15            let template_path = template.unwrap();
16            // We have a valid template file
17            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            // We have a template file that doesn't exist
25            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            // Try to get the default template file from `~/.bonnie/template.toml`
28            // If it's not available, we'll use a pre-programmed default
29            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}