use std::{borrow::Cow, iter};
use crate::util::eq_ignore_case;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct PossibleValue<'help> {
name: &'help str,
help: Option<&'help str>,
aliases: Vec<&'help str>, hide: bool,
}
impl<'help> PossibleValue<'help> {
pub fn new(name: &'help str) -> Self {
PossibleValue {
name,
..Default::default()
}
}
#[inline]
#[must_use]
pub fn help(mut self, help: &'help str) -> Self {
self.help = Some(help);
self
}
#[inline]
#[must_use]
pub fn hide(mut self, yes: bool) -> Self {
self.hide = yes;
self
}
#[must_use]
pub fn alias(mut self, name: &'help str) -> Self {
self.aliases.push(name);
self
}
#[must_use]
pub fn aliases<I>(mut self, names: I) -> Self
where
I: IntoIterator<Item = &'help str>,
{
self.aliases.extend(names.into_iter());
self
}
}
impl<'help> PossibleValue<'help> {
#[inline]
pub fn get_name(&self) -> &'help str {
self.name
}
#[inline]
pub fn get_help(&self) -> Option<&'help str> {
self.help
}
#[inline]
#[cfg(feature = "unstable-v4")]
pub(crate) fn get_visible_help(&self) -> Option<&'help str> {
if !self.hide {
self.help
} else {
None
}
}
#[inline]
#[deprecated(since = "3.1.0", note = "Replaced with `PossibleValue::is_hide_set`")]
pub fn is_hidden(&self) -> bool {
self.is_hide_set()
}
#[inline]
pub fn is_hide_set(&self) -> bool {
self.hide
}
pub(crate) fn should_show_help(&self) -> bool {
!self.hide && self.help.is_some()
}
#[deprecated(
since = "3.1.4",
note = "Use `PossibleValue::is_hide_set` and `PossibleValue::get_name`"
)]
pub fn get_visible_name(&self) -> Option<&'help str> {
if self.hide {
None
} else {
Some(self.name)
}
}
pub(crate) fn get_visible_quoted_name(&self) -> Option<Cow<'help, str>> {
if !self.hide {
Some(if self.name.contains(char::is_whitespace) {
format!("{:?}", self.name).into()
} else {
self.name.into()
})
} else {
None
}
}
pub fn get_name_and_aliases(&self) -> impl Iterator<Item = &'help str> + '_ {
iter::once(&self.name).chain(&self.aliases).copied()
}
pub fn matches(&self, value: &str, ignore_case: bool) -> bool {
if ignore_case {
self.get_name_and_aliases()
.any(|name| eq_ignore_case(name, value))
} else {
self.get_name_and_aliases().any(|name| name == value)
}
}
}
impl<'help> From<&'help str> for PossibleValue<'help> {
fn from(s: &'help str) -> Self {
Self::new(s)
}
}
impl<'help> From<&'help &'help str> for PossibleValue<'help> {
fn from(s: &'help &'help str) -> Self {
Self::new(s)
}
}