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)] pub no_startup_message: bool, } /// what the fuck serde why do i need this fn default_example_value() -> i32 { 43 } /// Find the location of a config file and check if there is, in fact, a file 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().expect("config path to be UTF-8")) { 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(str::to_string))), } } }