Config files use generic traits

This commit is contained in:
Luke D. Jones
2023-01-06 12:03:12 +13:00
parent 54273cfb60
commit e4f79a3e6f
18 changed files with 314 additions and 333 deletions

View File

@@ -1,12 +1,8 @@
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use log::{error, warn};
use serde_derive::{Deserialize, Serialize};
use crate::config_file_open;
use crate::config_traits::{StdConfig, StdConfigLoad3};
pub static CONFIG_FILE: &str = "/etc/asusd/asusd.conf";
pub static CONFIG_FILE: &str = "asusd.conf";
#[derive(Deserialize, Serialize, Default)]
pub struct Config {
@@ -18,7 +14,7 @@ pub struct Config {
pub bat_command: String,
}
impl Config {
impl StdConfig for Config {
fn new() -> Self {
Config {
bat_charge_limit: 100,
@@ -29,65 +25,13 @@ impl Config {
}
}
/// `load` will attempt to read the config, and panic if the dir is missing
pub fn load() -> Self {
let mut file = config_file_open(CONFIG_FILE);
let mut buf = String::new();
let config;
if let Ok(read_len) = file.read_to_string(&mut buf) {
if read_len == 0 {
config = Self::new();
} else if let Ok(data) = serde_json::from_str(&buf) {
config = data;
} else if let Ok(data) = serde_json::from_str::<Config455>(&buf) {
config = data.into();
} else if let Ok(data) = serde_json::from_str::<Config458>(&buf) {
config = data.into();
} else {
warn!(
"Could not deserialise {}.\nWill rename to {}-old and recreate config",
CONFIG_FILE, CONFIG_FILE
);
let cfg_old = CONFIG_FILE.to_owned() + "-old";
std::fs::rename(CONFIG_FILE, cfg_old).unwrap_or_else(|err| {
panic!(
"Could not rename. Please remove {} then restart service: Error {}",
CONFIG_FILE, err
)
});
config = Self::new();
}
} else {
config = Self::new();
}
config.write();
config
}
pub fn read(&mut self) {
let mut file = OpenOptions::new()
.read(true)
.open(CONFIG_FILE)
.unwrap_or_else(|err| panic!("Error reading {}: {}", CONFIG_FILE, err));
let mut buf = String::new();
if let Ok(l) = file.read_to_string(&mut buf) {
if l == 0 {
warn!("File is empty {}", CONFIG_FILE);
} else {
*self = serde_json::from_str(&buf)
.unwrap_or_else(|_| panic!("Could not deserialise {}", CONFIG_FILE));
}
}
}
pub fn write(&self) {
let mut file = File::create(CONFIG_FILE).expect("Couldn't overwrite config");
let json = serde_json::to_string_pretty(self).expect("Parse config to JSON failed");
file.write_all(json.as_bytes())
.unwrap_or_else(|err| error!("Could not write config: {}", err));
fn file_name() -> &'static str {
CONFIG_FILE
}
}
impl StdConfigLoad3<Config, Config455, Config458> for Config {}
#[derive(Deserialize, Serialize, Default)]
#[serde(default)]
pub struct Config455 {