lib/
get_cfg.rs

1// This file contains logic to get the actual configuration itself
2
3use std::env;
4use std::fs;
5
6// This can be changed by the user with the `BONNIE_CONF` environment variable
7pub const DEFAULT_BONNIE_CFG_PATH: &str = "./bonnie.toml";
8
9// Extracts the config from the TOML file at the given path
10pub fn get_cfg() -> Result<String, String> {
11    // Get the path of the config
12    let path = get_cfg_path()?;
13    let cfg_string = fs::read_to_string(&path);
14    match cfg_string {
15		Ok(cfg_string) => Ok(cfg_string),
16		Err(_) => Err(format!("Error reading Bonnie configuration file at '{}', make sure the file is present in this directory and you have the permissions to read it.", path))
17	}
18}
19
20// Gets the path to the config file based on given environment variables
21// This will return an error if the `BONNIE_CONF` environment variable is set, but is invalid
22fn get_cfg_path() -> Result<String, String> {
23    // Get the `BONNIE_CONF` variable
24    let given_path = env::var("BONNIE_CONF");
25    match given_path {
26        Ok(path) => Ok(path),
27        Err(env::VarError::NotUnicode(_)) => Err(String::from("The path to your Bonnie configuration file given in the 'BONNIE_CONF' environment variable contained invalid characters. Please make sure it only contains valid Unicode.")),
28        Err(env::VarError::NotPresent) => Ok(DEFAULT_BONNIE_CFG_PATH.to_string()) // If the env var wasn't found, then use the default
29    }
30}