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 edda5428d233cc85d453efc43d1c6a5df7d89b92 2963 bytes (plain)
1
use std::{
2
    fs::{self, File},
3
    io::Write,
4
    path::PathBuf,
5
};
6
7
use ron::{
8
    Value,
9
    de::{self},
10
    ser::{self, PrettyConfig},
11
};
12
use serde::{Deserialize, Serialize};
13
14
use crate::ui::Ui;
15
16
const DEFAULT_CONFIG: &str = include_str!("../config.ron");
17
18
#[derive(Deserialize, Serialize)]
19
pub struct Config {
20
    pub ui: Ui,
21
}
22
23
impl Default for Config {
24
    fn default() -> Self {
25
        let config: Self = de::from_str(DEFAULT_CONFIG)
26
            .map_err(|e| format!("Failed to parse default RON config: {}", e))
27
            .unwrap();
28
        config
29
    }
30
}
31
32
impl Config {
33
    fn get_path() -> Option<PathBuf> {
34
        dirs::config_dir().map(|mut p| {
35
            p.push("nmrs-tui/config.ron");
36
            p
37
        })
38
    }
39
40
    pub fn load() -> Result<Self, String> {
41
        let default_value: Value = de::from_str(DEFAULT_CONFIG)
42
            .map_err(|e| format!("Failed to parse default RON config: {}", e))?;
43
44
        let merged = if let Some(config_path) = Self::get_path()
45
            && config_path.exists()
46
        {
47
            let user_str = fs::read_to_string(&config_path)
48
                .map_err(|e| format!("Failed to read config file: {}", e))?;
49
            let user_value: Value = de::from_str(&user_str)
50
                .map_err(|e| format!("Failed to parse RON config: {}", e))?;
51
            Self::merge_ron(default_value, user_value)
52
        } else {
53
            default_value
54
        };
55
        merged
56
            .into_rust()
57
            .map_err(|e| format!("Failed to build config: {}", e))
58
    }
59
60
    pub fn create(&self) -> Result<(), String> {
61
        let config_path = Self::get_path().ok_or("Cannot find config directory!")?;
62
63
        if let Some(parent) = config_path.parent() {
64
            fs::create_dir_all(parent).map_err(|e| format!("Failed to create directory: {}", e))?;
65
        }
66
67
        let mut config_file =
68
            File::create(config_path).map_err(|e| format!("Failed to create/open file: {}", e))?;
69
70
        let pretty = PrettyConfig::new();
71
        let ron_string = ser::to_string_pretty(self, pretty)
72
            .map_err(|e| format!("Failed to serialize config: {}", e))?;
73
74
        config_file
75
            .write_all(ron_string.as_bytes())
76
            .map_err(|e| format!("Failed to write default config: {}", e))?;
77
        Ok(())
78
    }
79
80
    pub fn merge_ron(default: Value, user: Value) -> Value {
81
        match (default, user) {
82
            (Value::Map(mut default_map), Value::Map(user_map)) => {
83
                for (k, v) in user_map.iter() {
84
                    let merged = match default_map.get(k) {
85
                        Some(dv) => Self::merge_ron(dv.clone(), v.clone()),
86
                        None => v.clone(),
87
                    };
88
                    default_map.insert(k.clone(), merged);
89
                }
90
                Value::Map(default_map)
91
            }
92
            // scalars/seqs: user value wins outright
93
            (_, user_value) => user_value,
94
        }
95
    }
96
}