src/app/config/config.rs
76 lines · 1864 bytes
1use std::{
2 error::Error,
3 fs::{self, OpenOptions},
4 io::Write,
5};
6
7use super::{commands::CommandsConfig, MainConfig};
8
9#[derive(Clone, Debug)]
10pub struct Config {
11 pub commands: CommandsConfig,
12 pub main: MainConfig,
13}
14
15impl Default for Config {
16 fn default() -> Self {
17 Self {
18 commands: CommandsConfig::default(),
19 main: MainConfig::default(),
20 }
21 }
22}
23
24impl Config {
25 pub fn load() -> Result<Self, Box<dyn Error>> {
26 let mut commands = CommandsConfig::default();
27 let mut main = MainConfig::default();
28
29 let mut config = home::home_dir().expect("Cannot get your home directory");
30 config.push(".config");
31 config.push("youtube-tui");
32
33 config.push("commands.yml");
34
35 if config.exists() {
36 let content = fs::read_to_string(config.as_os_str())?;
37 commands = serde_yaml::from_str(&content)?;
38 } else {
39 let mut file = OpenOptions::new()
40 .write(true)
41 .truncate(true)
42 .create(true)
43 .open(config.as_os_str())?;
44
45 write!(file, "{}", serde_yaml::to_string(&commands)?)?;
46 }
47
48 config.pop();
49 config.push("main.yml");
50
51 if config.exists() {
52 let content = fs::read_to_string(config.as_os_str())?;
53 main = serde_yaml::from_str(&content)?;
54 } else {
55 let mut file = OpenOptions::new()
56 .write(true)
57 .truncate(true)
58 .create(true)
59 .open(config.as_os_str())?;
60
61 write!(file, "{}", serde_yaml::to_string(&main)?)?;
62 }
63
64 Ok(Self { main, commands })
65 }
66}
67
68pub struct EnvVar {
69 pub url: Option<String>,
70}
71
72impl Default for EnvVar {
73 fn default() -> Self {
74 Self { url: None }
75 }
76}