use super::Trace;
use crate::error::GenerateError;
use std::collections::HashMap;
fn to_trace(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
fn not_processed(map: HashMap<Vec<String>, MayBeProcessed>) -> impl Iterator<Item = Vec<String>> {
map.into_iter().filter_map(
|(key, processed)| {
if processed.0 { None } else { Some(key) }
},
)
}
#[derive(Debug, Clone)]
struct MayBeProcessed(bool);
impl MayBeProcessed {
fn new() -> Self {
MayBeProcessed(false)
}
fn process(&mut self) {
self.0 = true;
}
}
#[derive(Clone)]
pub struct Config {
ignore: HashMap<Vec<String>, MayBeProcessed>,
custom: HashMap<Vec<String>, MayBeProcessed>,
strict: bool,
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
impl Config {
pub fn new() -> Self {
Config {
strict: true,
ignore: Default::default(),
custom: Default::default(),
}
}
pub fn ignore(mut self, ids: &[&str]) -> Self {
self.ignore.insert(to_trace(ids), MayBeProcessed::new());
self
}
pub(crate) fn is_ignored(&mut self, prev: &[Trace], id: &str) -> bool {
let mut key: Vec<_> = prev.iter().map(|t| t.cmd_id.to_string()).collect();
key.push(id.to_string());
if let Some(t) = self.ignore.get_mut(&key) {
t.process();
true
} else {
false
}
}
pub fn make_custom(mut self, ids: &[&str]) -> Self {
self.custom.insert(to_trace(ids), MayBeProcessed::new());
self
}
pub(crate) fn is_custom(&mut self, prev: &[Trace], id: &str) -> bool {
let mut key: Vec<_> = prev.iter().map(|t| t.cmd_id.to_string()).collect();
key.push(id.to_string());
if let Some(t) = self.custom.get_mut(&key) {
t.process();
true
} else {
false
}
}
pub(crate) fn check_unprocessed_config(self) -> Result<(), GenerateError> {
let Config {
strict: _,
ignore,
custom,
} = self;
let it = not_processed(ignore).chain(not_processed(custom));
let mut it = it.peekable();
if it.peek().is_none() {
return Ok(());
}
Err(GenerateError::UnprocessedConfigObj(
it.map(|x| x.to_vec()).collect(),
))
}
pub fn strict(mut self, yes: bool) -> Self {
self.strict = yes;
self
}
pub fn is_strict(&self) -> bool {
self.strict
}
}