Merge pull request #4292 from epage/func

refactor: Use getters internally
This commit is contained in:
Ed Page 2022-09-29 15:50:51 -05:00 committed by GitHub
commit 1e2b791049
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 71 additions and 67 deletions

View file

@ -50,7 +50,6 @@ use crate::INTERNAL_ERROR_MSG;
/// // Using a usage string (setting a similar argument to the one above)
/// let input = arg!(-i --input <FILE> "Provides an input file to the program");
/// ```
#[allow(missing_debug_implementations)]
#[derive(Default, Clone)]
pub struct Arg {
pub(crate) id: Id,
@ -3904,7 +3903,7 @@ impl Arg {
/// assert_eq!(arg.is_positional(), false);
/// ```
pub fn is_positional(&self) -> bool {
self.long.is_none() && self.short.is_none()
self.get_long().is_none() && self.get_short().is_none()
}
/// Reports whether [`Arg::required`] is set
@ -4236,7 +4235,7 @@ impl PartialOrd for Arg {
impl Ord for Arg {
fn cmp(&self, other: &Arg) -> Ordering {
self.id.cmp(&other.id)
self.get_id().cmp(other.get_id())
}
}

View file

@ -3502,7 +3502,7 @@ impl Command {
.iter()
.flat_map(|x| x.args.args()),
)
.find(|arg| arg.id == *id)
.find(|arg| arg.get_id() == id)
.expect(
"Command::get_arg_conflicts_with: \
The passed arg conflicts with an arg unknown to the cmd",
@ -3527,7 +3527,11 @@ impl Command {
fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> {
let mut vec = std::vec::Vec::new();
for idx in 0..self.subcommands.len() {
if self.subcommands[idx].args.args().any(|ar| ar.id == arg.id) {
if self.subcommands[idx]
.args
.args()
.any(|ar| ar.get_id() == arg.get_id())
{
vec.push(&self.subcommands[idx]);
vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg));
}
@ -4107,7 +4111,7 @@ impl Command {
let args_missing_help: Vec<Id> = self
.args
.args()
.filter(|arg| arg.help.is_none() && arg.long_help.is_none())
.filter(|arg| arg.get_help().is_none() && arg.get_long_help().is_none())
.map(|arg| arg.get_id().clone())
.collect();
@ -4353,7 +4357,7 @@ impl Command {
}
pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg> {
self.args.args().find(|a| a.id == *arg_id)
self.args.args().find(|a| a.get_id() == arg_id)
}
#[inline]
@ -4413,7 +4417,7 @@ impl Command {
#[cfg(debug_assertions)]
pub(crate) fn id_exists(&self, id: &Id) -> bool {
self.args.args().any(|x| x.id == *id) || self.groups.iter().any(|x| x.id == *id)
self.args.args().any(|x| x.get_id() == id) || self.groups.iter().any(|x| x.id == *id)
}
/// Iterate through the groups this arg is member of.
@ -4443,7 +4447,7 @@ impl Command {
pub(crate) fn required_graph(&self) -> ChildGraph<Id> {
let mut reqs = ChildGraph::with_capacity(5);
for a in self.args.args().filter(|a| a.is_required_set()) {
reqs.insert(a.id.clone());
reqs.insert(a.get_id().clone());
}
for group in &self.groups {
if group.required {
@ -4506,7 +4510,7 @@ impl Command {
for r in arg.requires.iter().filter_map(&func) {
if let Some(req) = self.find(&r) {
if !req.requires.is_empty() {
r_vec.push(&req.id)
r_vec.push(req.get_id())
}
}
args.push(r);
@ -4571,7 +4575,7 @@ impl Command {
// specified by the user is sent through. If hide_short_help is not included,
// then items specified with hidden_short_help will also be hidden.
let should_long = |v: &Arg| {
v.long_help.is_some()
v.get_long_help().is_some()
|| v.is_hide_long_help_set()
|| v.is_hide_short_help_set()
|| v.get_possible_values()

View file

@ -91,7 +91,7 @@ pub(crate) fn assert_app(cmd: &Command) {
}
// Name conflicts
if let Some((first, second)) = cmd.two_args_of(|x| x.id == arg.id) {
if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
panic!(
"Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
cmd.get_name(),
@ -117,7 +117,7 @@ pub(crate) fn assert_app(cmd: &Command) {
// Short conflicts
if let Some(s) = arg.get_short() {
if let Some((first, second)) = cmd.two_args_of(|x| x.short == Some(s)) {
if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
panic!(
"Command {}: Short option names must be unique for each argument, \
but '-{}' is in use by both '{}' and '{}'{}",
@ -133,7 +133,7 @@ pub(crate) fn assert_app(cmd: &Command) {
// Index conflicts
if let Some(idx) = arg.index {
if let Some((first, second)) =
cmd.two_args_of(|x| x.is_positional() && x.index == Some(idx))
cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
{
panic!(
"Command {}: Argument '{}' has the same index as '{}' \
@ -242,13 +242,13 @@ pub(crate) fn assert_app(cmd: &Command) {
if arg.is_last_set() {
assert!(
arg.long.is_none(),
arg.get_long().is_none(),
"Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
cmd.get_name(),
arg.get_id()
);
assert!(
arg.short.is_none(),
arg.get_short().is_none(),
"Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
cmd.get_name(),
arg.get_id()
@ -358,10 +358,12 @@ pub(crate) fn assert_app(cmd: &Command) {
}
fn duplicate_tip(cmd: &Command, first: &Arg, second: &Arg) -> &'static str {
if !cmd.is_disable_help_flag_set() && (first.id == Id::HELP || second.id == Id::HELP) {
if !cmd.is_disable_help_flag_set()
&& (first.get_id() == Id::HELP || second.get_id() == Id::HELP)
{
" (call `cmd.disable_help_flag(true)` to remove the auto-generated `--help`)"
} else if !cmd.is_disable_version_flag_set()
&& (first.id == Id::VERSION || second.id == Id::VERSION)
&& (first.get_id() == Id::VERSION || second.get_id() == Id::VERSION)
{
" (call `cmd.disable_version_flag(true)` to remove the auto-generated `--version`)"
} else {
@ -546,7 +548,7 @@ fn _verify_positionals(cmd: &Command) -> bool {
}
// Next we verify that only the highest index has takes multiple arguments (if any)
let only_highest = |a: &Arg| a.is_multiple() && (a.index.unwrap_or(0) != highest_idx);
let only_highest = |a: &Arg| a.is_multiple() && (a.get_index().unwrap_or(0) != highest_idx);
if cmd.get_positionals().any(only_highest) {
// First we make sure if there is a positional that allows multiple values
// the one before it (second to last) has one of these:
@ -614,7 +616,7 @@ fn _verify_positionals(cmd: &Command) -> bool {
index than a required positional argument by two or more: {:?} \
index {:?}",
p.get_id(),
p.index
p.get_index()
);
} else if p.is_required_set() && !p.is_last_set() {
// Args that .last(true) don't count since they can be required and have
@ -643,7 +645,7 @@ fn _verify_positionals(cmd: &Command) -> bool {
"Found non-required positional argument with a lower \
index than a required positional argument: {:?} index {:?}",
p.get_id(),
p.index
p.get_index()
);
} else if p.is_required_set() && !p.is_last_set() {
// Args that .last(true) don't count since they can be required and have
@ -682,7 +684,7 @@ fn assert_arg(arg: &Arg) {
// Self conflict
// TODO: this check should be recursive
assert!(
!arg.blacklist.iter().any(|x| *x == arg.id),
!arg.blacklist.iter().any(|x| x == arg.get_id()),
"Argument '{}' cannot conflict with itself",
arg.get_id(),
);
@ -731,9 +733,9 @@ fn assert_arg(arg: &Arg) {
arg.is_takes_value_set(),
"Argument '{}` is positional, it must take a value{}",
arg.get_id(),
if arg.id == Id::HELP {
if arg.get_id() == Id::HELP {
" (`mut_arg` no longer works with implicit `--help`)"
} else if arg.id == Id::VERSION {
} else if arg.get_id() == Id::VERSION {
" (`mut_arg` no longer works with implicit `--version`)"
} else {
""

View file

@ -494,7 +494,7 @@ impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
fn long(&mut self, arg: &Arg) {
debug!("HelpTemplate::long");
if let Some(long) = arg.get_long() {
if arg.short.is_some() {
if arg.get_short().is_some() {
self.none(", ");
}
self.literal(format!("--{}", long));
@ -516,7 +516,7 @@ impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
let self_len = display_width(&arg.to_string());
// Since we're writing spaces from the tab point we first need to know if we
// had a long and short, or just short
let padding = if arg.long.is_some() {
let padding = if arg.get_long().is_some() {
// Only account 4 after the val
TAB_WIDTH
} else {
@ -969,7 +969,7 @@ fn option_sort_key(arg: &Arg) -> (usize, String) {
x.to_string()
} else {
let mut s = '{'.to_string();
s.push_str(arg.id.as_str());
s.push_str(arg.get_id().as_str());
s
};
(arg.get_display_order(), key)
@ -1017,7 +1017,7 @@ fn replace_newline_var(styled: &mut StyledStr) {
}
fn longest_filter(arg: &Arg) -> bool {
arg.is_takes_value_set() || arg.long.is_some() || arg.short.is_none()
arg.is_takes_value_set() || arg.get_long().is_some() || arg.get_short().is_none()
}
#[cfg(test)]

View file

@ -170,7 +170,7 @@ impl<'cmd> Usage<'cmd> {
debug!("Usage::needs_options_tag:iter Option is required");
continue;
}
for grp_s in self.cmd.groups_for_arg(&f.id) {
for grp_s in self.cmd.groups_for_arg(f.get_id()) {
debug!("Usage::needs_options_tag:iter:iter: grp_s={:?}", grp_s);
if self.cmd.get_groups().any(|g| g.id == grp_s && g.required) {
debug!("Usage::needs_options_tag:iter:iter: Group is required");

View file

@ -25,8 +25,8 @@ impl ArgMatcher {
matches: ArgMatches {
#[cfg(debug_assertions)]
valid_args: {
let args = _cmd.get_arguments().map(|a| a.id.clone());
let groups = _cmd.get_groups().map(|g| g.id.clone());
let args = _cmd.get_arguments().map(|a| a.get_id().clone());
let groups = _cmd.get_groups().map(|g| g.get_id().clone());
args.chain(groups).collect()
},
#[cfg(debug_assertions)]
@ -130,7 +130,7 @@ impl ArgMatcher {
}
pub(crate) fn start_custom_arg(&mut self, arg: &Arg, source: ValueSource) {
let id = arg.id.clone();
let id = arg.get_id().clone();
debug!(
"ArgMatcher::start_custom_arg: id={:?}, source={:?}",
id, source
@ -153,7 +153,7 @@ impl ArgMatcher {
}
pub(crate) fn start_occurrence_of_arg(&mut self, arg: &Arg) {
let id = arg.id.clone();
let id = arg.get_id().clone();
debug!("ArgMatcher::start_occurrence_of_arg: id={:?}", id);
let ma = self.entry(id).or_insert(MatchedArg::new_arg(arg));
debug_assert_eq!(ma.type_id(), Some(arg.get_value_parser().type_id()));
@ -199,7 +199,7 @@ impl ArgMatcher {
let num_pending = self
.pending
.as_ref()
.and_then(|p| (p.id == o.id).then(|| p.raw_vals.len()))
.and_then(|p| (p.id == *o.get_id()).then(|| p.raw_vals.len()))
.unwrap_or(0);
debug!(
"ArgMatcher::needs_more_vals: o={}, pending={}",

View file

@ -286,7 +286,7 @@ impl<'cmd> Parser<'cmd> {
let arg_values = matcher.pending_values_mut(id, None, trailing_values);
arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
if matcher.needs_more_vals(arg) {
ParseResult::Opt(arg.id.clone())
ParseResult::Opt(arg.get_id().clone())
} else {
ParseResult::ValuesDone
}
@ -308,10 +308,9 @@ impl<'cmd> Parser<'cmd> {
// The last positional argument, or second to last positional
// argument may be set to .multiple_values(true) or `.multiple_occurrences(true)`
let low_index_mults = is_second_to_last
&& self
.cmd
.get_positionals()
.any(|a| a.is_multiple() && (positional_count != a.index.unwrap_or(0)))
&& self.cmd.get_positionals().any(|a| {
a.is_multiple() && (positional_count != a.get_index().unwrap_or(0))
})
&& self
.cmd
.get_positionals()
@ -336,7 +335,7 @@ impl<'cmd> Parser<'cmd> {
if let Some(arg) = self
.cmd
.get_positionals()
.find(|a| a.index == Some(pos_counter))
.find(|a| a.get_index() == Some(pos_counter))
{
// If next value looks like a new_arg or it's a
// subcommand, skip positional argument under current
@ -387,7 +386,7 @@ impl<'cmd> Parser<'cmd> {
trailing_values = true;
}
if matcher.pending_arg_id() != Some(&arg.id) || !arg.is_multiple_values_set() {
if matcher.pending_arg_id() != Some(arg.get_id()) || !arg.is_multiple_values_set() {
ok!(self.resolve_pending(matcher));
}
if let Some(_parse_result) = self.check_terminator(arg, arg_os.to_value_os()) {
@ -397,7 +396,7 @@ impl<'cmd> Parser<'cmd> {
);
} else {
let arg_values = matcher.pending_values_mut(
&arg.id,
arg.get_id(),
Some(Identifier::Index),
trailing_values,
);
@ -409,7 +408,7 @@ impl<'cmd> Parser<'cmd> {
pos_counter += 1;
parse_state = ParseState::ValuesDone;
} else {
parse_state = ParseState::Pos(arg.id.clone());
parse_state = ParseState::Pos(arg.get_id().clone());
}
valid_arg_found = true;
} else if let Some(external_parser) =
@ -637,8 +636,8 @@ impl<'cmd> Parser<'cmd> {
current_positional.get_id()
);
if self.cmd[&current_positional.id].is_allow_hyphen_values_set()
|| (self.cmd[&current_positional.id].is_allow_negative_numbers_set()
if self.cmd[current_positional.get_id()].is_allow_hyphen_values_set()
|| (self.cmd[current_positional.get_id()].is_allow_negative_numbers_set()
&& next.is_number())
{
// If allow hyphen, this isn't a new arg.
@ -784,9 +783,9 @@ impl<'cmd> Parser<'cmd> {
matcher.check_explicit(arg_id, &crate::builder::ArgPredicate::IsPresent)
})
.filter(|&n| {
self.cmd
.find(n)
.map_or(true, |a| !(a.is_hide_set() || required.contains(&a.id)))
self.cmd.find(n).map_or(true, |a| {
!(a.is_hide_set() || required.contains(a.get_id()))
})
})
.cloned()
.collect();
@ -1038,8 +1037,8 @@ impl<'cmd> Parser<'cmd> {
debug!("Parser::parse_opt_value: More arg vals required...");
ok!(self.resolve_pending(matcher));
let trailing_values = false;
matcher.pending_values_mut(&arg.id, Some(ident), trailing_values);
Ok(ParseResult::Opt(arg.id.clone()))
matcher.pending_values_mut(arg.get_id(), Some(ident), trailing_values);
Ok(ParseResult::Opt(arg.get_id().clone()))
}
}
@ -1075,12 +1074,12 @@ impl<'cmd> Parser<'cmd> {
let value_parser = arg.get_value_parser();
let val = ok!(value_parser.parse_ref(self.cmd, Some(arg), &raw_val));
matcher.add_val_to(&arg.id, val, raw_val);
matcher.add_index_to(&arg.id, self.cur_idx.get());
matcher.add_val_to(arg.get_id(), val, raw_val);
matcher.add_index_to(arg.get_id(), self.cur_idx.get());
}
// Increment or create the group "args"
for group in self.cmd.groups_for_arg(&arg.id) {
for group in self.cmd.groups_for_arg(arg.get_id()) {
matcher.add_val_to(
&group,
AnyValue::new(arg.get_id().clone()),
@ -1180,7 +1179,7 @@ impl<'cmd> Parser<'cmd> {
self.cur_idx.set(self.cur_idx.get() + 1);
debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
}
if matcher.remove(&arg.id)
if matcher.remove(arg.get_id())
&& !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
{
return Err(ClapError::argument_conflict(
@ -1223,7 +1222,7 @@ impl<'cmd> Parser<'cmd> {
raw_vals
};
if matcher.remove(&arg.id)
if matcher.remove(arg.get_id())
&& !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
{
return Err(ClapError::argument_conflict(
@ -1244,7 +1243,7 @@ impl<'cmd> Parser<'cmd> {
raw_vals
};
if matcher.remove(&arg.id)
if matcher.remove(arg.get_id())
&& !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
{
return Err(ClapError::argument_conflict(
@ -1269,7 +1268,7 @@ impl<'cmd> Parser<'cmd> {
raw_vals
};
matcher.remove(&arg.id);
matcher.remove(arg.get_id());
self.start_custom_arg(matcher, arg, source);
ok!(self.push_arg_values(arg, raw_vals, matcher));
Ok(ParseResult::ValuesDone)
@ -1366,8 +1365,8 @@ impl<'cmd> Parser<'cmd> {
let mut transitive = Vec::new();
for arg_id in matcher.arg_ids() {
if let Some(overrider) = self.cmd.find(arg_id) {
if overrider.overrides.contains(&arg.id) {
transitive.push(&overrider.id);
if overrider.overrides.contains(arg.get_id()) {
transitive.push(overrider.get_id());
}
}
}
@ -1422,7 +1421,7 @@ impl<'cmd> Parser<'cmd> {
fn add_default_value(&self, arg: &Arg, matcher: &mut ArgMatcher) -> ClapResult<()> {
if !arg.default_vals_ifs.is_empty() {
debug!("Parser::add_default_value: has conditional defaults");
if !matcher.contains(&arg.id) {
if !matcher.contains(arg.get_id()) {
for (id, val, default) in arg.default_vals_ifs.iter() {
let add = if let Some(a) = matcher.get(id) {
match val {
@ -1461,7 +1460,7 @@ impl<'cmd> Parser<'cmd> {
"Parser::add_default_value:iter:{}: has default vals",
arg.get_id()
);
if matcher.contains(&arg.id) {
if matcher.contains(arg.get_id()) {
debug!("Parser::add_default_value:iter:{}: was used", arg.get_id());
// do nothing
} else {
@ -1502,7 +1501,7 @@ impl<'cmd> Parser<'cmd> {
self.remove_overrides(arg, matcher);
}
matcher.start_custom_arg(arg, source);
for group in self.cmd.groups_for_arg(&arg.id) {
for group in self.cmd.groups_for_arg(arg.get_id()) {
matcher.start_custom_group(group, source);
}
}
@ -1514,7 +1513,7 @@ impl<'cmd> Parser<'cmd> {
matcher.start_occurrence_of_arg(arg);
// Increment or create the group "args"
for group in self.cmd.groups_for_arg(&arg.id) {
for group in self.cmd.groups_for_arg(arg.get_id()) {
matcher.start_occurrence_of_group(group);
}
}

View file

@ -34,7 +34,7 @@ impl<'cmd> Validator<'cmd> {
debug!("Validator::validate: needs_val_of={:?}", a);
let o = &self.cmd[&a];
let should_err = if let Some(v) = matcher.args.get(&o.id) {
let should_err = if let Some(v) = matcher.args.get(o.get_id()) {
v.all_val_groups_empty() && o.get_min_vals() != 0
} else {
true
@ -220,11 +220,11 @@ impl<'cmd> Validator<'cmd> {
debug!("Validator::gather_requires:iter:{:?}", name);
if let Some(arg) = self.cmd.find(name) {
let is_relevant = |(val, req_arg): &(ArgPredicate, Id)| -> Option<Id> {
let required = matcher.check_explicit(&arg.id, val);
let required = matcher.check_explicit(arg.get_id(), val);
required.then(|| req_arg.clone())
};
for req in self.cmd.unroll_arg_requires(is_relevant, &arg.id) {
for req in self.cmd.unroll_arg_requires(is_relevant, arg.get_id()) {
self.required.insert(req);
}
} else if let Some(g) = self.cmd.find_group(name) {
@ -374,7 +374,7 @@ impl<'cmd> Validator<'cmd> {
conflicts: &mut Conflicts,
) -> bool {
debug!("Validator::is_missing_required_ok: {}", a.get_id());
let conflicts = conflicts.gather_conflicts(self.cmd, matcher, &a.id);
let conflicts = conflicts.gather_conflicts(self.cmd, matcher, a.get_id());
!conflicts.is_empty()
}