manaconf 0.2.1

a layered configuration library
Documentation
use std::collections::HashMap;
use std::{convert::Infallible, iter::FromIterator};

use crate::{Key, KeyBuf, Value, Source};

/// A simplified command line source
///
/// Expects command line parameters in the format 
/// `--component-component-component value`
///
/// For example:
/// The configuration key `some::section::value` would map to the command
/// line parameter `--some-section-value` 
pub struct CommandLineSource {
    values: HashMap<KeyBuf, String>
}

impl CommandLineSource {
    pub fn new() -> CommandLineSource {
        let mut values = HashMap::new();

        let args = std::env::args();
        let mut current_arg = None;
        let mut current_value = None;

        for arg in args {
            if arg.starts_with("--") {
                current_arg = Some(arg[2..].to_string());
                current_value = None;
            } else if current_arg.is_some() {
                current_value = Some(arg);
            }

            if let (true, true) = (current_arg.is_some(), current_value.is_some()) {
                let key = current_arg
                    .take()
                    .map(|s| KeyBuf::from_iter(s.split('-')))
                    .unwrap();

                let value = current_value
                    .take()
                    .unwrap();

                values.insert(key, value);
            }
        }

        CommandLineSource { values }
    }
}

impl Source for CommandLineSource {
    type Error = Infallible;

    fn get_value(&self, key: &Key) -> Result<Option<crate::Value>, Self::Error> {
        let value = self.values
            .get(key)
            .map(|v| Value::String(v.clone()));

        Ok(value)
    }
}