src/traits/config.rs

46 lines · 1374 bytes

 1use serde::{de::DeserializeOwned, Serialize};
 2use std::{
 3    error::Error,
 4    fs::{self, rename},
 5    io::Write,
 6};
 7
 8pub trait ConfigItem<'a> {
 9    type Struct: Serialize + DeserializeOwned + Clone + Default;
10    const FILE_NAME: &'static str;
11
12    fn load() -> Result<Self::Struct, Box<dyn Error>>
13    where
14        Self: Sized,
15    {
16        let mut config_path = home::home_dir().expect("Cannot get your home directory");
17        let mut config = Self::Struct::default();
18        config_path.push(".config");
19        config_path.push("youtube-tui");
20        config_path.push(Self::FILE_NAME);
21
22        if config_path.exists() {
23            let content = fs::read_to_string(config_path.as_os_str())?;
24            match serde_yaml::from_str(&content) {
25                Ok(config_from_str) => config = config_from_str,
26                Err(_) => {
27                    let mut new_path = config_path.clone();
28                    new_path.pop();
29                    new_path.push(format!("{}.old", Self::FILE_NAME));
30
31                    rename(&config_path, &new_path)?;
32                }
33            }
34        }
35
36        let mut file = fs::OpenOptions::new()
37            .write(true)
38            .truncate(true)
39            .create(true)
40            .open(config_path.as_os_str())?;
41
42        write!(file, "{}", serde_yaml::to_string(&config)?)?;
43
44        Ok(config)
45    }
46}