From 6b145d66f8e343f6c6ee66f7bcda78ed39f49f45 Mon Sep 17 00:00:00 2001 From: glyph Date: Fri, 11 Mar 2022 10:19:00 +0200 Subject: [PATCH] add basic application config and parser --- peach-web/config | 2 ++ peach-web/src/config.rs | 54 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 peach-web/config create mode 100644 peach-web/src/config.rs diff --git a/peach-web/config b/peach-web/config new file mode 100644 index 0000000..aa7ad74 --- /dev/null +++ b/peach-web/config @@ -0,0 +1,2 @@ +disable_auth=false +standalone_mode=true diff --git a/peach-web/src/config.rs b/peach-web/src/config.rs new file mode 100644 index 0000000..00d7239 --- /dev/null +++ b/peach-web/src/config.rs @@ -0,0 +1,54 @@ +// 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). +#[derive(Debug)] +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>(path: P) -> Result { + let file = File::open(path)?; + let mut conf = Config::default(); + + for l in io::BufReader::new(file).lines() { + let line = l?; + if line.len() == 0 { + 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) + } +}