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.
70 lines
1.8 KiB
70 lines
1.8 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::ser::Error as SerdeError;
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::{from_reader, to_writer_pretty};
|
|
|
|
#[derive(Serialize, Deserialize, Debug)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Config {
|
|
pub save_directory: Option<String>,
|
|
pub downloaded: Vec<String>,
|
|
}
|
|
|
|
pub struct ConfigManager {
|
|
config_path: OsString,
|
|
pub config: Config,
|
|
}
|
|
|
|
fn read_config<P: AsRef<Path>>(path: P) -> Result<Config, Box<dyn Error>> {
|
|
let file = File::open(path)?;
|
|
let reader = BufReader::new(file);
|
|
let result: Config = from_reader(reader)?;
|
|
Ok(result)
|
|
}
|
|
|
|
fn save_config<P: AsRef<Path>>(path: P, config: &Config) -> serde_json::Result<()> {
|
|
match File::create(path) {
|
|
Err(e) => Err(serde_json::Error::custom(e)),
|
|
Ok(file) => to_writer_pretty(file, config),
|
|
}
|
|
}
|
|
|
|
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,
|
|
downloaded: vec![],
|
|
},
|
|
};
|
|
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,
|
|
}
|
|
}
|
|
|
|
pub fn save(&mut self, config: Config) {
|
|
match save_config(&self.config_path, &config) {
|
|
Err(e) => {
|
|
println!("Unexpected error saving config: {}", e);
|
|
}
|
|
Ok(_) => (),
|
|
}
|
|
self.config = config;
|
|
}
|
|
}
|