diff options
Diffstat (limited to 'src/config.rs')
-rw-r--r-- | src/config.rs | 73 |
1 files changed, 31 insertions, 42 deletions
diff --git a/src/config.rs b/src/config.rs index c4396d4..f7d391f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,48 +1,37 @@ -use std::{net::SocketAddrV4, path::PathBuf}; -use structopt::StructOpt; +use anyhow::{Context, Result}; +use std::{ + collections::HashMap, + env, + fs::File, + io::{BufRead, BufReader}, +}; -lazy_static! { - pub static ref INSTANCE: Config = Config::from_args(); -} - -#[derive(Debug, StructOpt)] -#[structopt(author, about)] -pub struct Config { - #[structopt( - name = "DIR", - required = true, - parse(from_str), - help = "The path to your data directory" - )] - pub data_dir: PathBuf, - - #[structopt( - name = "ADDR", - long = "bind-addr", - required = false, - default_value = "127.0.0.1:5353", - help = "Sets the IP address and port to bind to" - )] - pub bind_addr: SocketAddrV4, +const DEFAULT_RCFILE: &str = "/usr/local/etc/twinhrc"; // TODO: windows users? +const RCFILE: &str = "TWINHRC"; +const PREFIX: &str = "TWINH_"; +pub const LOGLEVEL: &str = "TWINH_LOGLEVEL"; - #[structopt( - long, - short, - multiple = true, - parse(from_occurrences), - help = "Increases log level" - )] - pub verbose: usize, +pub fn init() -> Result<HashMap<String, String>> { + let rcpath = env::var(RCFILE).unwrap_or_else(|_| DEFAULT_RCFILE.to_owned()); + let rcfile = File::open(rcpath).with_context(|| "Failed to open rcfile")?; - #[structopt( - long, - help = "Creates a fresh data directory at DIR and exits; Fails if DIR exists" - )] - pub create_dir: bool, + // read rcfile into config map + let mut config = HashMap::new(); + for line in BufReader::new(rcfile).lines() { + let line = line.with_context(|| "Failed to parse line in rcfile")?; + if !line.starts_with('#') { + if let Some((key, val)) = line.split_once('=') { + config.insert(key.into(), val.into()); + } + } + } - #[structopt(long, help = "Imports CSV car data into the data directory")] - pub import_cars: bool, + // override rcfile config with any present env vars + for (key, val) in env::vars() { + if let Some(key) = key.strip_prefix(PREFIX) { + config.insert(key.into(), val); + } + } - #[structopt(long, help = "Imports CSV parts data into the data directory")] - pub import_parts: bool, + Ok(config) } |