summaryrefslogblamecommitdiff
path: root/src/config.rs
blob: f7d391fd70d514a106a510820735492be484f354 (plain) (tree)
1
2
3
4
5
6
7
8






                              
 



                                                                              
 


                                                                                
 









                                                                           
 





                                                       
 
              
 
use anyhow::{Context, Result};
use std::{
    collections::HashMap,
    env,
    fs::File,
    io::{BufRead, BufReader},
};

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";

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")?;

    // 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());
            }
        }
    }

    // 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);
        }
    }

    Ok(config)
}