iowo/crates/app/src/config/config_file.rs

53 lines
1.4 KiB
Rust
Raw Normal View History

2024-01-15 09:03:55 +01:00
use std::{
fs,
path::{Path, PathBuf},
};
use serde::{Deserialize, Serialize};
use super::error::ConfigError;
2024-01-15 09:03:55 +01:00
#[derive(Debug, Serialize, Deserialize)]
pub struct Configs {
#[serde(default = "default_example_value")]
pub example_value: i32,
2024-01-19 09:51:48 +01:00
#[serde(default)]
2024-01-15 09:03:55 +01:00
pub no_startup_message: bool,
}
/// what the fuck serde why do i need this
fn default_example_value() -> i32 {
2024-01-15 09:03:55 +01:00
43
}
2024-01-19 09:51:48 +01:00
/// Find the location of a config file and check if there is, in fact, a file
pub(super) fn find_config_file() -> Result<PathBuf, ConfigError> {
let Some(config_path) = dirs::config_dir() else {
return Err(ConfigError::NoConfigDir);
};
2024-01-15 09:03:55 +01:00
let ron_path = config_path.with_file_name("config.ron");
let json_path = config_path.with_file_name("config.json");
2024-01-15 09:03:55 +01:00
if Path::new(&ron_path).exists() {
Ok(ron_path)
} else if Path::new(&json_path).exists() {
Ok(json_path)
} else {
Err(ConfigError::NoConfigFileFound)
2024-01-15 09:03:55 +01:00
}
}
2024-01-15 09:03:55 +01:00
impl Configs {
pub fn read(p: PathBuf) -> Result<Self, ConfigError> {
2024-01-20 21:47:33 +01:00
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)?)?),
2024-01-20 21:47:33 +01:00
e => Err(ConfigError::UnknownExtension(e.map(str::to_string))),
2024-01-15 09:03:55 +01:00
}
}
}