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