muse2/
settings.rs

1//! Code for loading program settings.
2use crate::input::read_toml;
3use anyhow::Result;
4use serde::Deserialize;
5use std::path::Path;
6
7const SETTINGS_FILE_NAME: &str = "settings.toml";
8
9/// Program settings from config file
10#[derive(Debug, Default, Deserialize, PartialEq)]
11pub struct Settings {
12    /// The user's preferred logging level
13    pub log_level: Option<String>,
14    /// Whether to write additional information to CSV files
15    #[serde(default)]
16    pub debug_model: bool,
17}
18
19impl Settings {
20    /// Read the contents of a settings file from the model directory.
21    ///
22    /// If the file is not present, default values for settings will be used
23    ///
24    /// # Arguments
25    ///
26    /// * `model_dir` - Folder containing model configuration files
27    ///
28    /// # Returns
29    ///
30    /// The program settings as a `Settings` struct or an error if the file is invalid
31    pub fn load() -> Result<Settings> {
32        let file_path = Path::new(SETTINGS_FILE_NAME);
33        if !file_path.is_file() {
34            return Ok(Settings::default());
35        }
36
37        read_toml(file_path)
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44    use current_dir::Cwd;
45    use std::fs::File;
46    use std::io::Write;
47    use tempfile::tempdir;
48
49    #[test]
50    fn test_settings_from_path_no_file() {
51        let dir = tempdir().unwrap();
52        let mut cwd = Cwd::mutex().lock().unwrap();
53        cwd.set(dir.path()).unwrap();
54        assert_eq!(Settings::load().unwrap(), Settings::default());
55    }
56
57    #[test]
58    fn test_settings_from_path() {
59        let dir = tempdir().unwrap();
60        let mut cwd = Cwd::mutex().lock().unwrap();
61        cwd.set(dir.path()).unwrap();
62
63        {
64            let mut file = File::create(Path::new(SETTINGS_FILE_NAME)).unwrap();
65            writeln!(file, "log_level = \"warn\"").unwrap();
66        }
67
68        assert_eq!(
69            Settings::load().unwrap(),
70            Settings {
71                log_level: Some("warn".to_string()),
72                debug_model: false
73            }
74        );
75    }
76}