Drew Short
5 years ago
4 changed files with 342 additions and 21 deletions
-
173Cargo.lock
-
4Cargo.toml
-
70src/config.rs
-
116src/main.rs
@ -0,0 +1,70 @@ |
|||
use std::error::Error;
|
|||
use std::ffi::OsString;
|
|||
use std::fs::File;
|
|||
use std::io::{BufReader, BufWriter};
|
|||
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);
|
|||
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;
|
|||
}
|
|||
}
|
Write
Preview
Loading…
Cancel
Save
Reference in new issue