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