[feat] config file. also: extreme over-engineering
This commit is contained in:
+64
@@ -0,0 +1,64 @@
|
||||
use std::{
|
||||
env,
|
||||
fs::File,
|
||||
io::{BufRead as _, BufReader},
|
||||
path::PathBuf,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use eyre::ContextCompat as _;
|
||||
|
||||
pub(crate) struct Config {
|
||||
pub(crate) netdev: Option<String>,
|
||||
pub(crate) interval: Duration,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
const CONFIG_FILE: &'static str = ".config/pfs/linkspeed";
|
||||
|
||||
pub(crate) fn from_file() -> eyre::Result<Self> {
|
||||
let config_file = PathBuf::from(env::var("HOME")?).join(Self::CONFIG_FILE);
|
||||
|
||||
let mut config = Self::default();
|
||||
|
||||
if let Ok(file) = File::open(&config_file) {
|
||||
let file = BufReader::new(file);
|
||||
|
||||
for line in file.lines() {
|
||||
let line = line?;
|
||||
|
||||
match &line {
|
||||
line if line.starts_with("netdev") => {
|
||||
config.netdev = Some(Self::read_config_value(line)?.to_string());
|
||||
}
|
||||
line if line.starts_with("interval") => {
|
||||
let interval = Self::read_config_value(line)?.parse::<f64>()?;
|
||||
config.interval = Duration::from_secs_f64(interval);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
fn read_config_value(line: &str) -> eyre::Result<&str> {
|
||||
let val = line
|
||||
.split('=')
|
||||
.nth(1)
|
||||
.wrap_err("failed to parse value".to_string())?
|
||||
.trim();
|
||||
|
||||
Ok(val)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Config {
|
||||
netdev: None,
|
||||
interval: Duration::from_secs(1),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user