src/config/configtrait.rs
64 lines · 2231 bytes
1use serde::{de::DeserializeOwned, Serialize};
2use std::{
3 error::Error,
4 fs::{self, OpenOptions},
5 io::Write,
6};
7
8pub const EXTENSION: &'static str = "yml";
9
10// Trait for loading, saving config files
11pub trait ConfigTrait {
12 const LABEL: &'static str;
13
14 fn load() -> Result<Box<Self>, Box<dyn Error>>
15 where
16 Self: Serialize + DeserializeOwned + Default + Clone,
17 {
18 let mut config_path = home::home_dir().expect("cannot get home directory");
19 config_path.push(".config");
20 config_path.push("youtube-tui");
21 config_path.push(format!("{}.{}", 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(serde_yaml::to_string(&config)?.as_bytes())?;
61
62 Ok(Box::new(config))
63 }
64}