Diffstat (limited to 'src/config.rs')
1 file changed, 45 insertions(+), 13 deletions(-)
@@ -4,21 +4,31 @@
path::PathBuf,
};
use ron::ser::{self};
use ron::{
Value,
ser::{self},
};
use ron::{
de::{self},
ser::PrettyConfig,
};
use serde::{Deserialize, Serialize};
use crate::ui::Ui;
const DEFAULT_CONFIG: &str = include_str!("../config.ron");
#[derive(Deserialize, Serialize)]
#[serde(default)]
pub struct Config {}
pub struct Config {
pub ui: Ui,
}
#[allow(clippy::derivable_impls)]
impl Default for Config {
fn default() -> Self {
Self {}
let config: Self = de::from_str(DEFAULT_CONFIG)
.map_err(|e| format!("Failed to parse default RON config: {}", e))
.unwrap();
config
}
}
@@ -31,18 +41,23 @@
}
pub fn load() -> Result<Self, String> {
if let Some(config_path) = Self::get_path()
let default_value: Value = de::from_str(DEFAULT_CONFIG)
.map_err(|e| format!("Failed to parse default RON config: {}", e))?;
let merged = if let Some(config_path) = Self::get_path()
&& config_path.exists()
{
let config_file = File::open(config_path)
.map_err(|e| format!("Failed to open config file: {}", e))?;
let config: Self = de::from_reader(config_file)
let user_str = fs::read_to_string(&config_path)
.map_err(|e| format!("Failed to read config file: {}", e))?;
let user_value: Value = de::from_str(&user_str)
.map_err(|e| format!("Failed to parse RON config: {}", e))?;
Ok(config)
Self::merge_ron(default_value, user_value)
} else {
Ok(Self::default())
}
default_value
};
merged
.into_rust()
.map_err(|e| format!("Failed to build config: {}", e))
}
pub fn create(&self) -> Result<(), String> {
@@ -63,5 +78,22 @@
.write_all(ron_string.as_bytes())
.map_err(|e| format!("Failed to write default config: {}", e))?;
Ok(())
}
pub fn merge_ron(default: Value, user: Value) -> Value {
match (default, user) {
(Value::Map(mut default_map), Value::Map(user_map)) => {
for (k, v) in user_map.iter() {
let merged = match default_map.get(k) {
Some(dv) => Self::merge_ron(dv.clone(), v.clone()),
None => v.clone(),
};
default_map.insert(k.clone(), merged);
}
Value::Map(default_map)
}
// scalars/seqs: user value wins outright
(_, user_value) => user_value,
}
}
}