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}
15
16impl Settings {
17    /// Read the contents of a settings file from the model directory.
18    ///
19    /// If the file is not present, default values for settings will be used
20    ///
21    /// # Arguments
22    ///
23    /// * `model_dir` - Folder containing model configuration files
24    ///
25    /// # Returns
26    ///
27    /// The program settings as a `Settings` struct or an error if the file is invalid
28    pub fn from_path<P: AsRef<Path>>(model_dir: P) -> Result<Settings> {
29        let file_path = model_dir.as_ref().join(SETTINGS_FILE_NAME);
30        if !file_path.is_file() {
31            return Ok(Settings::default());
32        }
33
34        read_toml(&file_path)
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41    use std::fs::File;
42    use std::io::Write;
43    use tempfile::tempdir;
44
45    #[test]
46    fn test_settings_from_path_no_file() {
47        let dir = tempdir().unwrap();
48        assert_eq!(
49            Settings::from_path(dir.path()).unwrap(),
50            Settings::default()
51        );
52    }
53
54    #[test]
55    fn test_settings_from_path() {
56        let dir = tempdir().unwrap();
57        {
58            let mut file = File::create(dir.path().join(SETTINGS_FILE_NAME)).unwrap();
59            writeln!(file, "log_level = \"warn\"").unwrap();
60        }
61        assert_eq!(
62            Settings::from_path(dir.path()).unwrap(),
63            Settings {
64                log_level: Some("warn".to_string())
65            }
66        );
67    }
68}