1use std::env;
4use std::fs;
5use std::path::Path;
6
7pub const DEFAULT_BX_CFG_PATH: &str = "./bx.toml";
8pub const DEFAULT_BONNIE_CFG_PATH: &str = "./bonnie.toml";
9
10pub fn get_cfg() -> Result<String, String> {
11 let path = resolve_cfg_path(
12 env::var("BX_CONF").ok().as_deref(),
13 env::var("BONNIE_CONF").ok().as_deref(),
14 Path::new(DEFAULT_BX_CFG_PATH).exists(),
15 );
16 let cfg_string = fs::read_to_string(&path);
17 match cfg_string {
18 Ok(cfg_string) => Ok(cfg_string),
19 Err(_) => Err(format!("Error reading configuration file at '{}', make sure the file is present in this directory and you have the permissions to read it.", path))
20 }
21}
22
23pub fn resolve_cfg_path(
24 bx_conf: Option<&str>,
25 bonnie_conf: Option<&str>,
26 bx_toml_exists: bool,
27) -> String {
28 if let Some(path) = bx_conf {
29 return path.to_string();
30 }
31 if let Some(path) = bonnie_conf {
32 return path.to_string();
33 }
34 if bx_toml_exists {
35 DEFAULT_BX_CFG_PATH.to_string()
36 } else {
37 DEFAULT_BONNIE_CFG_PATH.to_string()
38 }
39}
40
41#[cfg(test)]
42mod tests {
43 use super::*;
44
45 #[test]
46 fn bx_conf_takes_priority() {
47 let result = resolve_cfg_path(Some("/bx/path"), Some("/bonnie/path"), true);
48 assert_eq!(result, "/bx/path");
49 }
50
51 #[test]
52 fn bonnie_conf_used_when_bx_conf_not_set() {
53 let result = resolve_cfg_path(None, Some("/bonnie/path"), true);
54 assert_eq!(result, "/bonnie/path");
55 }
56
57 #[test]
58 fn bx_toml_used_when_no_env_vars_and_exists() {
59 let result = resolve_cfg_path(None, None, true);
60 assert_eq!(result, DEFAULT_BX_CFG_PATH);
61 }
62
63 #[test]
64 fn bonnie_toml_used_when_no_env_vars_and_bx_toml_missing() {
65 let result = resolve_cfg_path(None, None, false);
66 assert_eq!(result, DEFAULT_BONNIE_CFG_PATH);
67 }
68}