use std::{ fs, path::{Path, PathBuf}, }; use serde::{Deserialize, Serialize}; use super::error::ConfigError; #[derive(Debug, Serialize, Deserialize)] pub struct Configs { #[serde(default = "default_example_value")] pub example_value: i32, #[serde(default = "default_no_startup_msg")] pub no_startup_message: bool, } /// what the fuck serde why do i need this fn default_example_value() -> i32 { 43 } fn default_no_startup_msg() -> bool { false } pub(super) fn find_config_file() -> Result { let Some(config_path) = dirs::config_dir() else { return Err(ConfigError::NoConfigDir); }; let ron_path = config_path.with_file_name("config.ron"); let json_path = config_path.with_file_name("config.json"); if Path::new(&ron_path).exists() { Ok(ron_path) } else if Path::new(&json_path).exists() { Ok(json_path) } else { Err(ConfigError::NoConfigFileFound) } } impl Configs { pub fn read(p: PathBuf) -> Result { match p.extension().map(|v| v.to_str().unwrap()) { Some("ron") => Ok(serde_json::from_str(&fs::read_to_string(p)?)?), Some("json") => Ok(ron::from_str(&fs::read_to_string(p)?)?), e => Err(ConfigError::UnknownExtension(e.map(|v| v.to_owned()))), } } }