use std::collections::HashMap;
use std::{convert::Infallible, iter::FromIterator};
use crate::{Key, KeyBuf, Value, Source};
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)
}
}