src/global/traits/configtrait.rs
79 lines · 2728 bytes
4 symbols in this file
1use serde::{de::DeserializeOwned, Serialize};
2use std::{
3 error::Error,
4 fs::{self, OpenOptions},
5 io::Write,
6};
7
8use crate::{config::WriteConfig, global::functions::paths};
9
10pub const EXTENSION: &str = "yml";
11
12/// Trait for loading, saving config files
13pub trait ConfigTrait {
14 const LABEL: &'static str;
15
16 fn load(write: WriteConfig) -> Result<Box<Self>, Box<dyn Error>>
17 where
18 Self: Serialize + DeserializeOwned + Default + Clone,
19 {
20 let config_path =
21 paths::config_dir().join(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_ng::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
55 match write {
56 WriteConfig::Must => {
57 let mut file = OpenOptions::new()
58 .write(true)
59 .create(true)
60 .truncate(true)
61 .open(&config_path)?;
62 file.write_all(serde_yaml_ng::to_string(&config)?.as_bytes())?
63 }
64 WriteConfig::Try => {
65 if let Ok(mut file) = OpenOptions::new()
66 .write(true)
67 .create(true)
68 .truncate(true)
69 .open(&config_path)
70 {
71 let _ = file.write_all(serde_yaml_ng::to_string(&config)?.as_bytes());
72 }
73 }
74 WriteConfig::Dont => {}
75 }
76
77 Ok(Box::new(config))
78 }
79}