src/global/traits/configtrait.rs

64 lines · 2173 bytes

 1use home::home_dir;
 2use serde::{de::DeserializeOwned, Serialize};
 3use std::{
 4    error::Error,
 5    fs::{self, OpenOptions},
 6    io::Write,
 7};
 8
 9const EXTENSION: &str = "yml";
10
11/// Trait for loading, saving config files
12pub trait ConfigTrait {
13    const LABEL: &'static str;
14
15    fn load() -> Result<Box<Self>, Box<dyn Error>>
16    where
17        Self: Serialize + DeserializeOwned + Default + Clone,
18    {
19        let home_dir = home_dir().unwrap();
20        let config_path =
21            home_dir.join(format!(".config/youtube-tui/{}.{}", Self::LABEL, EXTENSION));
22
23        // The config struct
24        let config: Self = {
25            || -> Result<Self, Box<dyn Error>> {
26                let content = match fs::read_to_string(&config_path) {
27                    Ok(content) => content,
28                    // If the config file does not exist returns Self::defult()
29                    Err(_) => return Ok(Self::default()),
30                };
31
32                match serde_yaml::from_str::<Self>(&content) {
33                    Ok(config) => Ok(config),
34                    // If there is error parsing the json file, create a backup with current time and returns
35                    // Self::default()
36                    Err(_) => {
37                        let mut new_path = config_path.clone();
38                        new_path.pop();
39                        new_path.push(format!(
40                            "{}-{}.{}",
41                            Self::LABEL,
42                            chrono::offset::Local::now(),
43                            EXTENSION
44                        ));
45                        fs::rename(&config_path, &new_path)?;
46                        Ok(Self::default())
47                    }
48                }
49            }
50        }()?;
51
52        // Overwrites the old config file with added options (if any),
53        // but it also removes things like comments in the old config file
54        let mut file = OpenOptions::new()
55            .write(true)
56            .create(true)
57            .truncate(true)
58            .open(&config_path)?;
59
60        file.write_all(serde_yaml::to_string(&config)?.as_bytes())?;
61
62        Ok(Box::new(config))
63    }
64}