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 let Some(template_path) = template {
15			if fs::metadata(&template_path).is_ok() {
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 {
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_path));
26			}
27		} else {
28			// Try to get the default template file from `~/.bonnie/template.toml`
29			// If it's not available, we'll use a pre-programmed default
30			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}