index : nmrs-tui
A fast, Vim-friendly NetworkManager TUI built in Rust.
about summary refs log tree commit diff
nmrs-tui / src / config.rs
-rw-r--r-- blob 60267558ff440bec634ce99a56350ff590b04d01 1808 bytes (plain)
1
use std::{
2
    fs::{self, File},
3
    io::Write,
4
    path::PathBuf,
5
};
6
7
use ron::ser::{self};
8
use ron::{
9
    de::{self},
10
    ser::PrettyConfig,
11
};
12
use serde::{Deserialize, Serialize};
13
14
#[derive(Deserialize, Serialize)]
15
#[serde(default)]
16
pub struct Config {}
17
18
#[allow(clippy::derivable_impls)]
19
impl Default for Config {
20
    fn default() -> Self {
21
        Self {}
22
    }
23
}
24
25
impl Config {
26
    fn get_path() -> Option<PathBuf> {
27
        dirs::config_dir().map(|mut p| {
28
            p.push("nmrs-tui/config.ron");
29
            p
30
        })
31
    }
32
33
    pub fn load() -> Result<Self, String> {
34
        if let Some(config_path) = Self::get_path()
35
            && config_path.exists()
36
        {
37
            let config_file = File::open(config_path)
38
                .map_err(|e| format!("Failed to open config file: {}", e))?;
39
40
            let config: Self = de::from_reader(config_file)
41
                .map_err(|e| format!("Failed to parse RON config: {}", e))?;
42
            Ok(config)
43
        } else {
44
            Ok(Self::default())
45
        }
46
    }
47
48
    pub fn create(&self) -> Result<(), String> {
49
        let config_path = Self::get_path().ok_or("Cannot find config directory!")?;
50
51
        if let Some(parent) = config_path.parent() {
52
            fs::create_dir_all(parent).map_err(|e| format!("Failed to create directory: {}", e))?;
53
        }
54
55
        let mut config_file =
56
            File::create(config_path).map_err(|e| format!("Failed to create/open file: {}", e))?;
57
58
        let pretty = PrettyConfig::new();
59
        let ron_string = ser::to_string_pretty(self, pretty)
60
            .map_err(|e| format!("Failed to serialize config: {}", e))?;
61
62
        config_file
63
            .write_all(ron_string.as_bytes())
64
            .map_err(|e| format!("Failed to write default config: {}", e))?;
65
        Ok(())
66
    }
67
}