You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.4 KiB
56 lines
1.4 KiB
use std::error::Error;
|
|
use std::ffi::OsString;
|
|
use std::fs::File;
|
|
use std::io::BufReader;
|
|
use std::path::Path;
|
|
use std::process::exit;
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::from_reader;
|
|
|
|
#[derive(Serialize, Deserialize, Debug)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Config {
|
|
pub save_directory: Option<String>,
|
|
}
|
|
|
|
pub struct ConfigManager {
|
|
config_path: OsString,
|
|
pub config: Config,
|
|
}
|
|
|
|
fn read_config<P: AsRef<Path>>(path: P) -> Result<Config, Box<dyn Error>> {
|
|
if path.as_ref().exists() {
|
|
let file = File::open(path)?;
|
|
let reader = BufReader::new(file);
|
|
let result: Config = from_reader(reader)?;
|
|
Ok(result)
|
|
} else {
|
|
Ok(Config {
|
|
save_directory: Some(String::from("tmp")),
|
|
})
|
|
}
|
|
}
|
|
|
|
impl ConfigManager {
|
|
pub fn new(config_path: &Path) -> ConfigManager {
|
|
let mut config = ConfigManager {
|
|
config_path: OsString::from(config_path.as_os_str()),
|
|
config: Config {
|
|
save_directory: None,
|
|
},
|
|
};
|
|
config.load();
|
|
config
|
|
}
|
|
|
|
fn load(&mut self) {
|
|
match read_config(&self.config_path) {
|
|
Err(e) => {
|
|
println!("Failed to read config file {:#?}: {}", &self.config_path, e);
|
|
exit(1);
|
|
}
|
|
Ok(config) => self.config = config,
|
|
}
|
|
}
|
|
}
|