peach-workspace/peach-web/src/config.rs

55 lines
1.4 KiB
Rust
Raw Normal View History

// Kind thanks to Alex Wennerberg (https://alexwennerberg.com/) for writing
// this code and offered it under the 0BSD (BDS 0-Clause) license.
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
// Ini-like key=value configuration with global config only (no subsections).
2022-03-11 12:27:40 +00:00
#[derive(Debug, PartialEq)]
pub struct Config {
pub disable_auth: bool,
pub standalone_mode: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
disable_auth: false,
standalone_mode: true,
}
}
}
impl Config {
pub fn match_kv(&mut self, key: &str, value: &str) {
match key {
"disable_auth" => self.disable_auth = value.parse().unwrap(),
"standalone_mode" => self.standalone_mode = value.parse().unwrap(),
_ => {}
}
}
}
impl Config {
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config, std::io::Error> {
let file = File::open(path)?;
let mut conf = Config::default();
for l in io::BufReader::new(file).lines() {
let line = l?;
if line.is_empty() {
continue;
}
if let Some(i) = line.find('=') {
let key = &line[..i];
let value = &line[i + 1..];
conf.match_kv(key, value);
} else {
// panic!("Invalid config")
}
}
Ok(conf)
}
}