use crate::evaluator::Value;
use crate::messages;
use crate::model::ClarItem;
use antex::{ColorMode, Text};
#[derive(Debug)]
pub struct ClarMatches {
app: String,
description: Option<String>,
values: Vec<Value>,
items: Vec<ClarItem>,
cm: ColorMode,
}
impl ClarMatches {
pub(crate) fn new(
app: String,
description: Option<String>,
values: Vec<Value>,
items: Vec<ClarItem>,
cm: ColorMode,
) -> Self {
ClarMatches {
app,
description,
values,
items,
cm,
}
}
pub fn raw_values(&self) -> &[Value] {
&self.values
}
pub fn is_present(&self, path: impl AsRef<str>) -> bool {
let name = path.as_ref();
self
.values
.iter()
.any(|value| value.path() == name && value.is_present())
}
pub fn is_short(&self, name: impl AsRef<str>) -> bool {
let name = name.as_ref();
self
.values
.iter()
.any(|v| matches!(v, Value::ShortOption(option_name, _) if option_name == name))
}
pub fn is_long(&self, name: impl AsRef<str>) -> bool {
let name = name.as_ref();
self
.values
.iter()
.any(|v| matches!(v, Value::LongOption(option_name, _) if option_name == name))
}
pub fn get_count(&self, name: impl AsRef<str>) -> usize {
let name = name.as_ref();
self
.values
.iter()
.filter(|value| value.path() == name && value.is_present())
.count()
}
pub fn get_values(&self, name: impl AsRef<str>) -> Vec<Option<String>> {
let name = name.as_ref();
let mut values = self
.values
.iter()
.filter(|v| v.path() == name)
.flat_map(|v| v.value())
.collect::<Vec<Option<String>>>();
if values.is_empty()
&& let value @ Some(_) = self.default_value(name)
{
values.push(value);
}
values
}
pub fn get_paths(&self) -> Vec<String> {
self.values.iter().map(|value| value.path().to_string()).collect()
}
pub fn get_help(&self) -> Text {
messages::get_help(&self.app, &self.description, &self.items, false, self.cm)
}
pub fn get_help_long(&self) -> Text {
messages::get_help(&self.app, &self.description, &self.items, true, self.cm)
}
pub fn get_help_command(&self, path: impl AsRef<str>) -> Text {
messages::get_help_command(&self.app, path.as_ref(), &self.items, false, self.cm)
}
pub fn get_help_long_command(&self, path: impl AsRef<str>) -> Text {
messages::get_help_command(&self.app, path.as_ref(), &self.items, true, self.cm)
}
fn default_value(&self, name: impl AsRef<str>) -> Option<String> {
let name = name.as_ref();
for item in &self.items {
match item {
ClarItem::Options(options) => {
for option in options {
if option.get_name() == name && option.get_takes_value().is_some() {
return option.get_default_value().clone();
}
}
}
ClarItem::Arguments(arguments) => {
for argument in arguments {
if argument.get_name() == name {
return argument.get_default_value().clone();
}
}
}
_ => {}
}
}
None
}
}