src/global/traits/configtrait.rs

81 lines · 2764 bytes

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