Skip to content

Commit

Permalink
feat(parser): Allow users to avoid undefined arg asserts
Browse files Browse the repository at this point in the history
Cargo is an example of a user that heavily relied on using undefined
names because there is a lot of code sharing between commands.  This
allows a path forward for those users that is just painful enough to
discourage overly relying on it in the future :).
  • Loading branch information
epage committed Jan 4, 2022
1 parent 9daefba commit 7e4cd43
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/parse/matches/arg_matches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -993,6 +993,44 @@ impl ArgMatches {
pub fn subcommand_name(&self) -> Option<&str> {
self.subcommand.as_ref().map(|sc| &*sc.name)
}

/// Check if an arg can be queried
///
/// By default, `ArgMatches` functions assert on undefined `Id`s to help catch programmer
/// mistakes. In some context, this doesn't work, so users can use this function to check
/// before they do a query on `ArgMatches`.
#[inline]
#[doc(hidden)]
pub fn is_valid_arg(&self, _id: impl Key) -> bool {
#[cfg(debug_assertions)]
{
let id = Id::from(_id);
id == Id::empty_hash() || self.valid_args.contains(&id)
}
#[cfg(not(debug_assertions))]
{
true
}
}

/// Check if a subcommand can be queried
///
/// By default, `ArgMatches` functions assert on undefined `Id`s to help catch programmer
/// mistakes. In some context, this doesn't work, so users can use this function to check
/// before they do a query on `ArgMatches`.
#[inline]
#[doc(hidden)]
pub fn is_valid_subcommand(&self, _id: impl Key) -> bool {
#[cfg(debug_assertions)]
{
let id = Id::from(_id);
id == Id::empty_hash() || self.valid_subcommands.contains(&id)
}
#[cfg(not(debug_assertions))]
{
true
}
}
}

// Private methods
Expand Down

0 comments on commit 7e4cd43

Please sign in to comment.