Skip to content

Commit

Permalink
fix!: Remove lifetime from PossibleValue
Browse files Browse the repository at this point in the history
Another step towards clap-rs#1041

This isn't the long term type for `PossibleValue::help`, I just wanted
to get the lifetime out of the way first before figuring out how help
will work.
  • Loading branch information
epage committed Aug 16, 2022
1 parent 429143a commit bcdf74c
Show file tree
Hide file tree
Showing 21 changed files with 104 additions and 92 deletions.
2 changes: 1 addition & 1 deletion clap_complete/src/generator/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ pub fn flags<'help>(p: &Command<'help>) -> Vec<Arg<'help>> {
}

/// Get the possible values for completion
pub fn possible_values<'help>(a: &Arg<'help>) -> Option<Vec<clap::builder::PossibleValue<'help>>> {
pub fn possible_values(a: &Arg<'_>) -> Option<Vec<clap::builder::PossibleValue>> {
if !a.get_num_args().expect("built").takes_values() {
None
} else {
Expand Down
3 changes: 1 addition & 2 deletions clap_complete/src/shells/bash.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::{fmt::Write as _, io::Write};

use clap::builder::PossibleValue;
use clap::*;

use crate::generator::{utils, Generator};
Expand Down Expand Up @@ -180,7 +179,7 @@ fn vals_for(o: &Arg) -> String {
"$(compgen -W \"{}\" -- \"${{cur}}\")",
vals.iter()
.filter(|pv| !pv.is_hide_set())
.map(PossibleValue::get_name)
.map(|n| n.get_name().as_str())
.collect::<Vec<_>>()
.join(" ")
)
Expand Down
3 changes: 2 additions & 1 deletion clap_complete/src/shells/fish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,8 @@ fn value_completion(option: &Arg) -> String {
Some(format!(
"{}\t{}",
escape_string(value.get_name()).as_str(),
escape_string(value.get_help().unwrap_or_default()).as_str()
escape_string(value.get_help().map(|s| s.as_str()).unwrap_or_default())
.as_str()
))
})
.collect::<Vec<_>>()
Expand Down
2 changes: 1 addition & 1 deletion clap_complete/src/shells/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl ValueEnum for Shell {
]
}

fn to_possible_value<'a>(&self) -> Option<PossibleValue<'a>> {
fn to_possible_value<'a>(&self) -> Option<PossibleValue> {
Some(match self {
Shell::Bash => PossibleValue::new("bash"),
Shell::Elvish => PossibleValue::new("elvish"),
Expand Down
11 changes: 7 additions & 4 deletions clap_complete/src/shells/zsh.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::io::Write;

use clap::builder::PossibleValue;
use clap::*;

use crate::generator::{utils, Generator};
Expand Down Expand Up @@ -375,8 +374,12 @@ fn value_completion(arg: &Arg) -> Option<String> {
} else {
Some(format!(
r#"{name}\:"{tooltip}""#,
name = escape_value(value.get_name()),
tooltip = value.get_help().map(escape_help).unwrap_or_default()
name = escape_value(value.get_name().as_str()),
tooltip = value
.get_help()
.map(|s| s.as_str())
.map(escape_help)
.unwrap_or_default()
))
}
})
Expand All @@ -389,7 +392,7 @@ fn value_completion(arg: &Arg) -> Option<String> {
values
.iter()
.filter(|pv| !pv.is_hide_set())
.map(PossibleValue::get_name)
.map(|n| n.get_name().as_str())
.collect::<Vec<_>>()
.join(" ")
))
Expand Down
17 changes: 6 additions & 11 deletions clap_derive/src/attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ impl Attrs {
quote_spanned!(ident.span()=> {
{
let val: #ty = #val;
clap::ValueEnum::to_possible_value(&val).unwrap().get_name()
clap::ValueEnum::to_possible_value(&val).unwrap().get_name().to_owned()
}
})
} else {
Expand Down Expand Up @@ -544,17 +544,15 @@ impl Attrs {
let val = if parsed.iter().any(|a| matches!(a, ValueEnum(_))) {
quote_spanned!(ident.span()=> {
{
fn iter_to_vals<T>(iterable: impl IntoIterator<Item = T>) -> Vec<&'static str>
fn iter_to_vals<T>(iterable: impl IntoIterator<Item = T>) -> impl Iterator<Item=clap::Str>
where
T: ::std::borrow::Borrow<#inner_type>
{
iterable
.into_iter()
.map(|val| {
clap::ValueEnum::to_possible_value(val.borrow()).unwrap().get_name()
clap::ValueEnum::to_possible_value(val.borrow()).unwrap().get_name().to_owned()
})
.collect()

}

iter_to_vals(#expr)
Expand Down Expand Up @@ -603,7 +601,7 @@ impl Attrs {
quote_spanned!(ident.span()=> {
{
let val: #ty = #val;
clap::ValueEnum::to_possible_value(&val).unwrap().get_name()
clap::ValueEnum::to_possible_value(&val).unwrap().get_name().to_owned()
}
})
} else {
Expand Down Expand Up @@ -648,18 +646,15 @@ impl Attrs {
let val = if parsed.iter().any(|a| matches!(a, ValueEnum(_))) {
quote_spanned!(ident.span()=> {
{
fn iter_to_vals<T>(iterable: impl IntoIterator<Item = T>) -> Vec<&'static ::std::ffi::OsStr>
fn iter_to_vals<T>(iterable: impl IntoIterator<Item = T>) -> impl Iterator<Item=clap::Str>
where
T: ::std::borrow::Borrow<#inner_type>
{
iterable
.into_iter()
.map(|val| {
clap::ValueEnum::to_possible_value(val.borrow()).unwrap().get_name()
clap::ValueEnum::to_possible_value(val.borrow()).unwrap().get_name().to_owned()
})
.map(::std::ffi::OsStr::new)
.collect()

}

iter_to_vals(#expr)
Expand Down
2 changes: 1 addition & 1 deletion clap_derive/src/derives/value_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ fn gen_to_possible_value(lits: &[(TokenStream, Ident)]) -> TokenStream {
let (lit, variant): (Vec<TokenStream>, Vec<Ident>) = lits.iter().cloned().unzip();

quote! {
fn to_possible_value<'a>(&self) -> ::std::option::Option<clap::builder::PossibleValue<'a>> {
fn to_possible_value<'a>(&self) -> ::std::option::Option<clap::builder::PossibleValue> {
match self {
#(Self::#variant => Some(#lit),)*
_ => None
Expand Down
2 changes: 1 addition & 1 deletion clap_derive/src/dummies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ pub fn value_enum(name: &Ident) {
fn from_str(_input: &str, _ignore_case: bool) -> ::std::result::Result<Self, String> {
unimplemented!()
}
fn to_possible_value<'a>(&self) -> ::std::option::Option<clap::builder::PossibleValue<'a>>{
fn to_possible_value<'a>(&self) -> ::std::option::Option<clap::builder::PossibleValue>{
unimplemented!()
}
}
Expand Down
2 changes: 1 addition & 1 deletion examples/tutorial_builder/04_01_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ impl ValueEnum for Mode {
&[Mode::Fast, Mode::Slow]
}

fn to_possible_value<'a>(&self) -> Option<PossibleValue<'a>> {
fn to_possible_value<'a>(&self) -> Option<PossibleValue> {
Some(match self {
Mode::Fast => PossibleValue::new("fast"),
Mode::Slow => PossibleValue::new("slow"),
Expand Down
2 changes: 1 addition & 1 deletion src/builder/arg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3659,7 +3659,7 @@ impl<'help> Arg<'help> {
Some(longs)
}

pub(crate) fn get_possible_values(&self) -> Vec<PossibleValue<'help>> {
pub(crate) fn get_possible_values(&self) -> Vec<PossibleValue> {
if !self.is_takes_value_set() {
vec![]
} else {
Expand Down
64 changes: 28 additions & 36 deletions src/builder/possible_value.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::{borrow::Cow, iter};

use crate::util::eq_ignore_case;
use crate::Str;

/// A possible value of an argument.
///
Expand All @@ -27,14 +28,14 @@ use crate::util::eq_ignore_case;
/// [hide]: PossibleValue::hide()
/// [help]: PossibleValue::help()
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct PossibleValue<'help> {
name: &'help str,
help: Option<&'help str>,
aliases: Vec<&'help str>, // (name, visible)
pub struct PossibleValue {
name: Str,
help: Option<Str>,
aliases: Vec<Str>, // (name, visible)
hide: bool,
}

impl<'help> PossibleValue<'help> {
impl PossibleValue {
/// Create a [`PossibleValue`] with its name.
///
/// The name will be used to decide whether this value was provided by the user to an argument.
Expand All @@ -52,9 +53,9 @@ impl<'help> PossibleValue<'help> {
/// [hidden]: PossibleValue::hide
/// [possible value]: crate::builder::PossibleValuesParser
/// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values()
pub fn new(name: &'help str) -> Self {
pub fn new(name: impl Into<Str>) -> Self {
PossibleValue {
name,
name: name.into(),
..Default::default()
}
}
Expand All @@ -74,8 +75,8 @@ impl<'help> PossibleValue<'help> {
/// ```
#[inline]
#[must_use]
pub fn help(mut self, help: &'help str) -> Self {
self.help = Some(help);
pub fn help(mut self, help: impl Into<Str>) -> Self {
self.help = Some(help.into());
self
}

Expand Down Expand Up @@ -111,8 +112,8 @@ impl<'help> PossibleValue<'help> {
/// # ;
/// ```
#[must_use]
pub fn alias(mut self, name: &'help str) -> Self {
self.aliases.push(name);
pub fn alias(mut self, name: impl Into<Str>) -> Self {
self.aliases.push(name.into());
self
}

Expand All @@ -127,35 +128,32 @@ impl<'help> PossibleValue<'help> {
/// # ;
/// ```
#[must_use]
pub fn aliases<I>(mut self, names: I) -> Self
where
I: IntoIterator<Item = &'help str>,
{
self.aliases.extend(names.into_iter());
pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
self.aliases.extend(names.into_iter().map(|a| a.into()));
self
}
}

/// Reflection
impl<'help> PossibleValue<'help> {
impl PossibleValue {
/// Get the name of the argument value
#[inline]
pub fn get_name(&self) -> &'help str {
self.name
pub fn get_name(&self) -> &Str {
&self.name
}

/// Get the help specified for this argument, if any
#[inline]
pub fn get_help(&self) -> Option<&'help str> {
self.help
pub fn get_help(&self) -> Option<&Str> {
self.help.as_ref()
}

/// Get the help specified for this argument, if any and the argument
/// value is not hidden
#[inline]
pub(crate) fn get_visible_help(&self) -> Option<&'help str> {
pub(crate) fn get_visible_help(&self) -> Option<&str> {
if !self.hide {
self.help
self.help.as_deref()
} else {
None
}
Expand All @@ -174,12 +172,12 @@ impl<'help> PossibleValue<'help> {

/// Get the name if argument value is not hidden, `None` otherwise,
/// but wrapped in quotes if it contains whitespace
pub(crate) fn get_visible_quoted_name(&self) -> Option<Cow<'help, str>> {
pub(crate) fn get_visible_quoted_name(&self) -> Option<Cow<'_, str>> {
if !self.hide {
Some(if self.name.contains(char::is_whitespace) {
format!("{:?}", self.name).into()
} else {
self.name.into()
self.name.as_str().into()
})
} else {
None
Expand All @@ -189,8 +187,8 @@ impl<'help> PossibleValue<'help> {
/// Returns all valid values of the argument value.
///
/// Namely the name and all aliases.
pub fn get_name_and_aliases(&self) -> impl Iterator<Item = &'help str> + '_ {
iter::once(&self.name).chain(&self.aliases).copied()
pub fn get_name_and_aliases(&self) -> impl Iterator<Item = &Str> + '_ {
iter::once(&self.name).chain(self.aliases.iter())
}

/// Tests if the value is valid for this argument value
Expand All @@ -212,21 +210,15 @@ impl<'help> PossibleValue<'help> {
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))
.any(|name| eq_ignore_case(name.as_str(), 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 str> for PossibleValue<'help> {
fn from(s: &'_ &'help str) -> Self {
impl<S: Into<Str>> From<S> for PossibleValue {
fn from(s: S) -> Self {
Self::new(s)
}
}
Loading

0 comments on commit bcdf74c

Please sign in to comment.