arbor_cli/util/
app_data.rs

1use std::error::Error;
2use std::fs;
3
4const APP_DATA_DIR_RELATIVE_PATH: &str = ".local/share/arbor";
5
6pub struct AppData {
7    language: String,
8    thread_count: u8,
9    max_suggestion: u8,
10}
11
12impl Default for AppData {
13    fn default() -> Self {
14        Self {
15            language: "en-US".to_string(),
16            thread_count: 2,
17            max_suggestion: 10,
18        }
19    }
20}
21
22impl AppData {
23    pub fn build(
24        language: Option<String>,
25        thread_count: Option<u8>,
26        max_suggestion: Option<u8>,
27    ) -> Result<Self, Box<dyn Error>> {
28        let mut app_data = AppData::default();
29
30        if let Some(lang) = language {
31            app_data.language = lang;
32        }
33
34        if let Some(thread) = thread_count {
35            app_data.thread_count = thread;
36        }
37
38        if let Some(max_sugg) = max_suggestion {
39            app_data.max_suggestion = max_sugg;
40        }
41
42        // Resolve the home directory
43        let home_dir = dirs::home_dir().ok_or("Unable to find home directory")?;
44        let app_data_dir = home_dir.join(APP_DATA_DIR_RELATIVE_PATH);
45
46        // Create the directory if it doesn't exist
47        if !app_data_dir.exists() {
48            fs::create_dir_all(&app_data_dir)?;
49        }
50
51        Ok(app_data)
52    }
53
54    pub fn get_language(&self) -> &str {
55        self.language.as_ref()
56    }
57
58    pub fn get_thread_count(&self) -> u8 {
59        self.thread_count
60    }
61
62    pub fn get_max_suggestion(&self) -> u8 {
63        self.max_suggestion
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70
71    #[test]
72    fn it_builds_app_data() -> Result<(), Box<dyn Error>> {
73        let app_data = AppData::build(None, None, None)?;
74
75        assert_eq!(app_data.get_language(), "en-US".to_string());
76        assert_eq!(app_data.get_thread_count(), 2);
77        assert_eq!(app_data.get_max_suggestion(), 10);
78
79        let app_data = AppData::build(Some("tr-TR".to_string()), Some(4), Some(5))?;
80
81        assert_eq!(app_data.get_language(), "tr-TR".to_string());
82        assert_eq!(app_data.get_thread_count(), 4);
83        assert_eq!(app_data.get_max_suggestion(), 5);
84
85        let home_dir = dirs::home_dir().unwrap();
86        let app_data_dir = home_dir.join(APP_DATA_DIR_RELATIVE_PATH);
87
88        std::fs::remove_dir_all(app_data_dir)?;
89
90        Ok(())
91    }
92}