diff options
Diffstat (limited to '')
-rw-r--r-- | vendor/clap-3.2.20/src/bin/stdio-fixture.rs (renamed from vendor/clap/src/bin/stdio-fixture.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/action.rs (renamed from vendor/clap/src/builder/action.rs) | 8 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/app_settings.rs (renamed from vendor/clap/src/builder/app_settings.rs) | 32 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/arg.rs (renamed from vendor/clap/src/builder/arg.rs) | 20 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/arg_group.rs (renamed from vendor/clap/src/builder/arg_group.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/arg_predicate.rs (renamed from vendor/clap/src/builder/arg_predicate.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/arg_settings.rs (renamed from vendor/clap/src/builder/arg_settings.rs) | 27 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/command.rs (renamed from vendor/clap/src/builder/command.rs) | 106 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/debug_asserts.rs (renamed from vendor/clap/src/builder/debug_asserts.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/macros.rs (renamed from vendor/clap/src/builder/macros.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/mod.rs (renamed from vendor/clap/src/builder/mod.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/possible_value.rs (renamed from vendor/clap/src/builder/possible_value.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/regex.rs (renamed from vendor/clap/src/builder/regex.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/tests.rs (renamed from vendor/clap/src/builder/tests.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/usage_parser.rs (renamed from vendor/clap/src/builder/usage_parser.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/value_hint.rs (renamed from vendor/clap/src/builder/value_hint.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/builder/value_parser.rs (renamed from vendor/clap/src/builder/value_parser.rs) | 2 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/derive.rs (renamed from vendor/clap/src/derive.rs) | 28 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/error/context.rs (renamed from vendor/clap/src/error/context.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/mkeymap.rs (renamed from vendor/clap/src/mkeymap.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/output/fmt.rs (renamed from vendor/clap/src/output/fmt.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/output/help.rs (renamed from vendor/clap/src/output/help.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/output/mod.rs (renamed from vendor/clap/src/output/mod.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/output/usage.rs (renamed from vendor/clap/src/output/usage.rs) | 117 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/parser/arg_matcher.rs (renamed from vendor/clap/src/parser/arg_matcher.rs) | 4 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/parser/features/mod.rs (renamed from vendor/clap/src/parser/features/mod.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/parser/features/suggestions.rs (renamed from vendor/clap/src/parser/features/suggestions.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/parser/matches/any_value.rs (renamed from vendor/clap/src/parser/matches/any_value.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/parser/matches/arg_matches.rs (renamed from vendor/clap/src/parser/matches/arg_matches.rs) | 74 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/parser/matches/matched_arg.rs (renamed from vendor/clap/src/parser/matches/matched_arg.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/parser/matches/mod.rs (renamed from vendor/clap/src/parser/matches/mod.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/parser/matches/value_source.rs (renamed from vendor/clap/src/parser/matches/value_source.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/parser/mod.rs (renamed from vendor/clap/src/parser/mod.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/parser/parser.rs (renamed from vendor/clap/src/parser/parser.rs) | 148 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/parser/validator.rs (renamed from vendor/clap/src/parser/validator.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/util/color.rs (renamed from vendor/clap/src/util/color.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/util/fnv.rs (renamed from vendor/clap/src/util/fnv.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/util/graph.rs (renamed from vendor/clap/src/util/graph.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/util/id.rs (renamed from vendor/clap/src/util/id.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/util/mod.rs (renamed from vendor/clap/src/util/mod.rs) | 0 | ||||
-rw-r--r-- | vendor/clap-3.2.20/src/util/str_to_bool.rs (renamed from vendor/clap/src/util/str_to_bool.rs) | 0 | ||||
-rw-r--r-- | vendor/clap/src/error/kind.rs | 440 | ||||
-rw-r--r-- | vendor/clap/src/error/mod.rs | 1158 | ||||
-rw-r--r-- | vendor/clap/src/lib.rs | 149 | ||||
-rw-r--r-- | vendor/clap/src/macros.rs | 1062 | ||||
-rw-r--r-- | vendor/clap/src/parser/error.rs | 56 |
46 files changed, 359 insertions, 3072 deletions
diff --git a/vendor/clap/src/bin/stdio-fixture.rs b/vendor/clap-3.2.20/src/bin/stdio-fixture.rs index e3f34b41a..e3f34b41a 100644 --- a/vendor/clap/src/bin/stdio-fixture.rs +++ b/vendor/clap-3.2.20/src/bin/stdio-fixture.rs diff --git a/vendor/clap/src/builder/action.rs b/vendor/clap-3.2.20/src/builder/action.rs index ab3314290..71a91a8b1 100644 --- a/vendor/clap/src/builder/action.rs +++ b/vendor/clap-3.2.20/src/builder/action.rs @@ -183,16 +183,16 @@ pub enum ArgAction { /// assert!(matches.contains_id("flag")); /// assert_eq!(matches.occurrences_of("flag"), 0); /// assert_eq!( - /// matches.get_one::<u8>("flag").copied(), - /// Some(2) + /// matches.get_count("flag"), + /// 2 /// ); /// /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); /// assert!(matches.contains_id("flag")); /// assert_eq!(matches.occurrences_of("flag"), 0); /// assert_eq!( - /// matches.get_one::<u8>("flag").copied(), - /// Some(0) + /// matches.get_count("flag"), + /// 0 /// ); /// ``` Count, diff --git a/vendor/clap/src/builder/app_settings.rs b/vendor/clap-3.2.20/src/builder/app_settings.rs index e2d9ba6b1..88bc243c4 100644 --- a/vendor/clap/src/builder/app_settings.rs +++ b/vendor/clap-3.2.20/src/builder/app_settings.rs @@ -400,23 +400,20 @@ pub enum AppSettings { )] NoAutoVersion, - /// Deprecated, replaced with [`AppSettings::AllowHyphenValues`] + /// Deprecated, replaced with [`Command::allow_hyphen_values`] #[cfg_attr( feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `AppSettings::AllowHyphenValues`" - ) + deprecated(since = "3.0.0", note = "Replaced with `Command::allow_hyphen_values`") )] #[doc(hidden)] AllowLeadingHyphen, - /// Deprecated, this is now the default, see [`AppSettings::AllowInvalidUtf8ForExternalSubcommands`] and [`ArgSettings::AllowInvalidUtf8`][crate::ArgSettings::AllowInvalidUtf8] for the opposite. + /// Deprecated, replaced with [`Command::allow_invalid_utf8_for_external_subcommands`] and [`Command::is_allow_invalid_utf8_for_external_subcommands_set`] #[cfg_attr( feature = "deprecated", deprecated( since = "3.0.0", - note = "This is now the default see `AppSettings::AllowInvalidUtf8ForExternalSubcommands` and `ArgSettings::AllowInvalidUtf8` for the opposite." + note = "Replaced with `Command::allow_invalid_utf8_for_external_subcommands` and `Command::is_allow_invalid_utf8_for_external_subcommands_set`" ) )] #[doc(hidden)] @@ -462,42 +459,47 @@ pub enum AppSettings { #[doc(hidden)] ColorNever, - /// Deprecated, replaced with [`AppSettings::DisableHelpFlag`] + /// Deprecated, replaced with [`Command::disable_help_flag`] and [`Command::is_disable_help_flag_set`] #[cfg_attr( feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `AppSettings::DisableHelpFlag`") + deprecated( + since = "3.0.0", + note = "Replaced with `Command::disable_help_flag` and `Command::is_disable_help_flag_set`" + ) )] #[doc(hidden)] DisableHelpFlags, - /// Deprecated, replaced with [`AppSettings::DisableVersionFlag`] + /// Deprecated, replaced with [`Command::disable_version_flag`] and + /// [`Command::is_disable_version_flag_set`] #[cfg_attr( feature = "deprecated", deprecated( since = "3.0.0", - note = "Replaced with `AppSettings::DisableVersionFlag`" + note = "Replaced with `Command::disable_version_flag` and `Command::is_disable_version_flag_set`" ) )] #[doc(hidden)] DisableVersion, - /// Deprecated, replaced with [`AppSettings::PropagateVersion`] + /// Deprecated, replaced with [`Command::propagate_version`] and [`Command::is_propagate_version_set`] #[cfg_attr( feature = "deprecated", deprecated( since = "3.0.0", - note = "Replaced with `AppSettings::PropagateVersion`" + note = "Replaced with `Command::propagate_version` and `Command::is_propagate_version_set`" ) )] #[doc(hidden)] GlobalVersion, - /// Deprecated, replaced with [`AppSettings::HidePossibleValues`] + /// Deprecated, replaced with [`Command::hide_possible_values`] and + /// [`Arg::is_hide_possible_values_set`] #[cfg_attr( feature = "deprecated", deprecated( since = "3.0.0", - note = "Replaced with AppSettings::HidePossibleValues" + note = "Replaced with `Command::hide_possible_values` and `Arg::is_hide_possible_values_set`" ) )] #[doc(hidden)] diff --git a/vendor/clap/src/builder/arg.rs b/vendor/clap-3.2.20/src/builder/arg.rs index 63e88e80e..e9403d0b7 100644 --- a/vendor/clap/src/builder/arg.rs +++ b/vendor/clap-3.2.20/src/builder/arg.rs @@ -4316,6 +4316,16 @@ impl<'help> Arg<'help> { } } + /// Get *all* short aliases for this argument, if any, both visible and hidden. + #[inline] + pub fn get_all_short_aliases(&self) -> Option<Vec<char>> { + if self.short_aliases.is_empty() { + None + } else { + Some(self.short_aliases.iter().map(|(s, _)| s).copied().collect()) + } + } + /// Get the short option name and its visible aliases, if any #[inline] pub fn get_short_and_visible_aliases(&self) -> Option<Vec<char>> { @@ -4351,6 +4361,16 @@ impl<'help> Arg<'help> { } } + /// Get *all* aliases for this argument, if any, both visible and hidden. + #[inline] + pub fn get_all_aliases(&self) -> Option<Vec<&'help str>> { + if self.aliases.is_empty() { + None + } else { + Some(self.aliases.iter().map(|(s, _)| s).copied().collect()) + } + } + /// Get the long option name and its visible aliases, if any #[inline] pub fn get_long_and_visible_aliases(&self) -> Option<Vec<&'help str>> { diff --git a/vendor/clap/src/builder/arg_group.rs b/vendor/clap-3.2.20/src/builder/arg_group.rs index 0fe317109..0fe317109 100644 --- a/vendor/clap/src/builder/arg_group.rs +++ b/vendor/clap-3.2.20/src/builder/arg_group.rs diff --git a/vendor/clap/src/builder/arg_predicate.rs b/vendor/clap-3.2.20/src/builder/arg_predicate.rs index 58eb5494c..58eb5494c 100644 --- a/vendor/clap/src/builder/arg_predicate.rs +++ b/vendor/clap-3.2.20/src/builder/arg_predicate.rs diff --git a/vendor/clap/src/builder/arg_settings.rs b/vendor/clap-3.2.20/src/builder/arg_settings.rs index 3b7faf7bf..ecc064caa 100644 --- a/vendor/clap/src/builder/arg_settings.rs +++ b/vendor/clap-3.2.20/src/builder/arg_settings.rs @@ -50,14 +50,10 @@ pub enum ArgSettings { ) )] MultipleValues, - /// Deprecated, replaced with [`Arg::multiple_occurrences`] and - /// [`Arg::is_multiple_occurrences_set`] + /// Deprecated, replaced with [`Arg::action`] ([Issue #3772](https://github.com/clap-rs/clap/issues/3772)) #[cfg_attr( feature = "deprecated", - deprecated( - since = "3.1.0", - note = "Replaced with `Arg::multiple_occurrences` and `Arg::is_multiple_occurrences_set`" - ) + deprecated(since = "3.1.0", note = "Replaced with `Arg::action` (Issue #3772)") )] MultipleOccurrences, /// Deprecated, see [`ArgSettings::MultipleOccurrences`] (most likely what you want) and @@ -66,18 +62,17 @@ pub enum ArgSettings { feature = "deprecated", deprecated( since = "3.0.0", - note = "Split into `ArgSettings::MultipleOccurrences` (most likely what you want) and `ArgSettings::MultipleValues`" + note = "Split into `Arg::multiple_occurrences` (most likely what you want) and `Arg::multiple_values`" ) )] #[doc(hidden)] Multiple, - /// Deprecated, replaced with [`Arg::forbid_empty_values`] and - /// [`Arg::is_forbid_empty_values_set`] + /// Deprecated, replaced with [`Arg::value_parser(NonEmptyStringValueParser::new())`] #[cfg_attr( feature = "deprecated", deprecated( since = "3.1.0", - note = "Replaced with `Arg::forbid_empty_values` and `Arg::is_forbid_empty_values_set`" + note = "Replaced with `Arg::value_parser(NonEmptyStringValueParser::new())`" ) )] ForbidEmptyValues, @@ -157,12 +152,13 @@ pub enum ArgSettings { ) )] AllowHyphenValues, - /// Deprecated, replaced with [`ArgSettings::AllowHyphenValues`] + /// Deprecated, replaced with [`Arg::allow_hyphen_values`] and + /// [`Arg::is_allow_hyphen_values_set`] #[cfg_attr( feature = "deprecated", deprecated( since = "3.0.0", - note = "Replaced with `ArgSettings::AllowHyphenValues`" + note = "Replaced with `Arg::allow_hyphen_values` and `Arg::is_allow_hyphen_values_set`" ) )] #[doc(hidden)] @@ -203,10 +199,13 @@ pub enum ArgSettings { ) )] IgnoreCase, - /// Deprecated, replaced with [`ArgSettings::IgnoreCase`] + /// Deprecated, replaced with [`Arg::ignore_case`] and [`Arg::is_ignore_case_set`] #[cfg_attr( feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `ArgSettings::IgnoreCase`") + deprecated( + since = "3.0.0", + note = "Replaced with `Arg::ignore_case` and `Arg::is_ignore_case_set`" + ) )] #[doc(hidden)] CaseInsensitive, diff --git a/vendor/clap/src/builder/command.rs b/vendor/clap-3.2.20/src/builder/command.rs index 1fcb64ecc..de59ad8cd 100644 --- a/vendor/clap/src/builder/command.rs +++ b/vendor/clap-3.2.20/src/builder/command.rs @@ -274,6 +274,50 @@ impl<'help> App<'help> { self } + /// Allows one to mutate a [`Command`] after it's been added as a subcommand. + /// + /// This can be useful for modifying auto-generated arguments of nested subcommands with + /// [`Command::mut_arg`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// + /// let mut cmd = Command::new("foo") + /// .subcommand(Command::new("bar")) + /// .mut_subcommand("bar", |subcmd| subcmd.disable_help_flag(true)); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar", "--help"]); + /// + /// // Since we disabled the help flag on the "bar" subcommand, this should err. + /// + /// assert!(res.is_err()); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar"]); + /// assert!(res.is_ok()); + /// ``` + #[must_use] + pub fn mut_subcommand<'a, T, F>(mut self, subcmd_id: T, f: F) -> Self + where + F: FnOnce(App<'help>) -> App<'help>, + T: Into<&'a str>, + { + let subcmd_id: &str = subcmd_id.into(); + let id = Id::from(subcmd_id); + + let pos = self.subcommands.iter().position(|s| s.id == id); + + let subcmd = if let Some(idx) = pos { + self.subcommands.remove(idx) + } else { + App::new(subcmd_id) + }; + + self.subcommands.push(f(subcmd)); + self + } + /// Adds an [`ArgGroup`] to the application. /// /// [`ArgGroup`]s are a family of related arguments. @@ -700,7 +744,7 @@ impl<'help> App<'help> { /// [`io::stdout()`]: std::io::stdout() pub fn print_help(&mut self) -> io::Result<()> { self._build_self(); - let color = self.get_color(); + let color = self.color_help(); let mut c = Colorizer::new(Stream::Stdout, color); let usage = Usage::new(self); @@ -725,7 +769,7 @@ impl<'help> App<'help> { /// [`--help` (long)]: Arg::long_help() pub fn print_long_help(&mut self) -> io::Result<()> { self._build_self(); - let color = self.get_color(); + let color = self.color_help(); let mut c = Colorizer::new(Stream::Stdout, color); let usage = Usage::new(self); @@ -1604,6 +1648,14 @@ impl<'help> App<'help> { /// strings. After this setting is set, this will be *the only* usage string /// displayed to the user! /// + /// **NOTE:** Multiple usage lines may be present in the usage argument, but + /// some rules need to be followed to ensure the usage lines are formatted + /// correctly by the default help formatter: + /// + /// - Do not indent the first usage line. + /// - Indent all subsequent usage lines with four spaces. + /// - The last line must not end with a newline. + /// /// # Examples /// /// ```no_run @@ -1612,6 +1664,20 @@ impl<'help> App<'help> { /// .override_usage("myapp [-clDas] <some_file>") /// # ; /// ``` + /// + /// Or for multiple usage lines: + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .override_usage( + /// "myapp -X [-a] [-b] <file>\n \ + /// myapp -Y [-c] <file1> <file2>\n \ + /// myapp -Z [-d|-e]" + /// ) + /// # ; + /// ``` + /// /// [`ArgMatches::usage`]: ArgMatches::usage() #[must_use] pub fn override_usage<S: Into<&'help str>>(mut self, usage: S) -> Self { @@ -3512,15 +3578,21 @@ impl<'help> App<'help> { if arg.is_global_set() { self.get_global_arg_conflicts_with(arg) } else { - arg.blacklist - .iter() - .map(|id| { - self.args.args().find(|arg| arg.id == *id).expect( - "Command::get_arg_conflicts_with: \ - The passed arg conflicts with an arg unknown to the cmd", - ) - }) - .collect() + let mut result = Vec::new(); + for id in arg.blacklist.iter() { + if let Some(arg) = self.find(id) { + result.push(arg); + } else if let Some(group) = self.find_group(id) { + result.extend( + self.unroll_args_in_group(&group.id) + .iter() + .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)), + ); + } else { + panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd"); + } + } + result } } @@ -4264,7 +4336,8 @@ impl<'help> App<'help> { use std::fmt::Write; let mut mid_string = String::from(" "); - if !self.is_subcommand_negates_reqs_set() { + if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set() + { let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) for s in &reqs { @@ -4347,7 +4420,9 @@ impl<'help> App<'help> { if !self.is_set(AppSettings::BinNameBuilt) { let mut mid_string = String::from(" "); - if !self.is_subcommand_negates_reqs_set() { + if !self.is_subcommand_negates_reqs_set() + && !self.is_args_conflicts_with_subcommands_set() + { let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) for s in &reqs { @@ -5107,3 +5182,8 @@ where _ => None, } } + +#[test] +fn check_auto_traits() { + static_assertions::assert_impl_all!(Command: Send, Sync, Unpin); +} diff --git a/vendor/clap/src/builder/debug_asserts.rs b/vendor/clap-3.2.20/src/builder/debug_asserts.rs index 864b8b479..864b8b479 100644 --- a/vendor/clap/src/builder/debug_asserts.rs +++ b/vendor/clap-3.2.20/src/builder/debug_asserts.rs diff --git a/vendor/clap/src/builder/macros.rs b/vendor/clap-3.2.20/src/builder/macros.rs index 5be4d205e..5be4d205e 100644 --- a/vendor/clap/src/builder/macros.rs +++ b/vendor/clap-3.2.20/src/builder/macros.rs diff --git a/vendor/clap/src/builder/mod.rs b/vendor/clap-3.2.20/src/builder/mod.rs index 4f24c74d3..4f24c74d3 100644 --- a/vendor/clap/src/builder/mod.rs +++ b/vendor/clap-3.2.20/src/builder/mod.rs diff --git a/vendor/clap/src/builder/possible_value.rs b/vendor/clap-3.2.20/src/builder/possible_value.rs index 1c14217a6..1c14217a6 100644 --- a/vendor/clap/src/builder/possible_value.rs +++ b/vendor/clap-3.2.20/src/builder/possible_value.rs diff --git a/vendor/clap/src/builder/regex.rs b/vendor/clap-3.2.20/src/builder/regex.rs index bf3a78e0c..bf3a78e0c 100644 --- a/vendor/clap/src/builder/regex.rs +++ b/vendor/clap-3.2.20/src/builder/regex.rs diff --git a/vendor/clap/src/builder/tests.rs b/vendor/clap-3.2.20/src/builder/tests.rs index 76c8b8785..76c8b8785 100644 --- a/vendor/clap/src/builder/tests.rs +++ b/vendor/clap-3.2.20/src/builder/tests.rs diff --git a/vendor/clap/src/builder/usage_parser.rs b/vendor/clap-3.2.20/src/builder/usage_parser.rs index 85d0d304e..85d0d304e 100644 --- a/vendor/clap/src/builder/usage_parser.rs +++ b/vendor/clap-3.2.20/src/builder/usage_parser.rs diff --git a/vendor/clap/src/builder/value_hint.rs b/vendor/clap-3.2.20/src/builder/value_hint.rs index 7c35d1eb3..7c35d1eb3 100644 --- a/vendor/clap/src/builder/value_hint.rs +++ b/vendor/clap-3.2.20/src/builder/value_hint.rs diff --git a/vendor/clap/src/builder/value_parser.rs b/vendor/clap-3.2.20/src/builder/value_parser.rs index 397537c9f..0492f2782 100644 --- a/vendor/clap/src/builder/value_parser.rs +++ b/vendor/clap-3.2.20/src/builder/value_parser.rs @@ -12,7 +12,7 @@ use crate::parser::AnyValueId; /// use within an application. /// /// See -/// - [`value_parser!`] for automatically selecting an implementation for a given type +/// - [`value_parser!`][crate::value_parser] for automatically selecting an implementation for a given type /// - [`ValueParser::new`] for additional [`TypedValueParser`] that can be used /// /// # Example diff --git a/vendor/clap/src/derive.rs b/vendor/clap-3.2.20/src/derive.rs index bfb7bdfa2..b6ac04df6 100644 --- a/vendor/clap/src/derive.rs +++ b/vendor/clap-3.2.20/src/derive.rs @@ -19,11 +19,9 @@ use std::ffi::OsString; /// /// See also [`Subcommand`] and [`Args`]. /// -/// See the -/// [derive reference](https://github.com/clap-rs/clap/blob/v3.2.5/examples/derive_ref/README.md) -/// for attributes and best practices. +/// See the [derive reference](crate::_derive) for attributes and best practices. /// -/// **NOTE:** Deriving requires the `derive` feature flag +/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] /// /// # Examples /// @@ -156,13 +154,13 @@ pub trait Parser: FromArgMatches + CommandFactory + Sized { .map_err(format_error::<Self>) } - /// Deprecated, `StructOpt::clap` replaced with [`IntoCommand::command`] (derive as part of + /// Deprecated, `StructOpt::clap` replaced with [`CommandFactory::command`] (derive as part of /// [`Parser`]) #[cfg_attr( feature = "deprecated", deprecated( since = "3.0.0", - note = "`StructOpt::clap` is replaced with `IntoCommand::command` (derived as part of `Parser`)" + note = "`StructOpt::clap` is replaced with `CommandFactory::command` (derived as part of `Parser`)" ) )] #[doc(hidden)] @@ -372,11 +370,9 @@ pub trait FromArgMatches: Sized { /// `Args`. /// - `Variant(ChildArgs)`: No attribute is used with enum variants that impl `Args`. /// -/// See the -/// [derive reference](https://github.com/clap-rs/clap/blob/v3.2.5/examples/derive_ref/README.md) -/// for attributes and best practices. +/// See the [derive reference](crate::_derive) for attributes and best practices. /// -/// **NOTE:** Deriving requires the `derive` feature flag +/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] /// /// # Example /// @@ -416,11 +412,9 @@ pub trait Args: FromArgMatches + Sized { /// - `#[clap(flatten)] Variant(SubCmd)`: Attribute can only be used with enum variants that impl /// `Subcommand`. /// -/// See the -/// [derive reference](https://github.com/clap-rs/clap/blob/v3.2.5/examples/derive_ref/README.md) -/// for attributes and best practices. +/// See the [derive reference](crate::_derive) for attributes and best practices. /// -/// **NOTE:** Deriving requires the `derive` feature flag +/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] /// /// # Example /// @@ -460,11 +454,9 @@ pub trait Subcommand: FromArgMatches + Sized { /// - Call [`Arg::possible_values`][crate::Arg::possible_values] /// - Allowing using the `#[clap(default_value_t)]` attribute without implementing `Display`. /// -/// See the -/// [derive reference](https://github.com/clap-rs/clap/blob/v3.2.5/examples/derive_ref/README.md) -/// for attributes and best practices. +/// See the [derive reference](crate::_derive) for attributes and best practices. /// -/// **NOTE:** Deriving requires the `derive` feature flag +/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] /// /// # Example /// diff --git a/vendor/clap/src/error/context.rs b/vendor/clap-3.2.20/src/error/context.rs index 985cd4d70..985cd4d70 100644 --- a/vendor/clap/src/error/context.rs +++ b/vendor/clap-3.2.20/src/error/context.rs diff --git a/vendor/clap/src/mkeymap.rs b/vendor/clap-3.2.20/src/mkeymap.rs index 97ecdda77..97ecdda77 100644 --- a/vendor/clap/src/mkeymap.rs +++ b/vendor/clap-3.2.20/src/mkeymap.rs diff --git a/vendor/clap/src/output/fmt.rs b/vendor/clap-3.2.20/src/output/fmt.rs index dc1f46e08..dc1f46e08 100644 --- a/vendor/clap/src/output/fmt.rs +++ b/vendor/clap-3.2.20/src/output/fmt.rs diff --git a/vendor/clap/src/output/help.rs b/vendor/clap-3.2.20/src/output/help.rs index eb53bfa54..eb53bfa54 100644 --- a/vendor/clap/src/output/help.rs +++ b/vendor/clap-3.2.20/src/output/help.rs diff --git a/vendor/clap/src/output/mod.rs b/vendor/clap-3.2.20/src/output/mod.rs index e32aac26a..e32aac26a 100644 --- a/vendor/clap/src/output/mod.rs +++ b/vendor/clap-3.2.20/src/output/mod.rs diff --git a/vendor/clap/src/output/usage.rs b/vendor/clap-3.2.20/src/output/usage.rs index 7adaf58c6..6f7a2cad4 100644 --- a/vendor/clap/src/output/usage.rs +++ b/vendor/clap-3.2.20/src/output/usage.rs @@ -382,73 +382,64 @@ impl<'help, 'cmd> Usage<'help, 'cmd> { unrolled_reqs ); - let args_in_groups = self - .cmd - .get_groups() - .filter(|gn| required.contains(&gn.id)) - .flat_map(|g| self.cmd.unroll_args_in_group(&g.id)) - .collect::<Vec<_>>(); - - for a in unrolled_reqs - .iter() - .chain(incls.iter()) - .filter(|name| !self.cmd.get_positionals().any(|p| &&p.id == name)) - .filter(|name| !self.cmd.get_groups().any(|g| &&g.id == name)) - .filter(|name| !args_in_groups.contains(name)) - .filter(|name| { - !(matcher.is_some() - && matcher - .as_ref() - .unwrap() - .check_explicit(name, ArgPredicate::IsPresent)) - }) - { - debug!("Usage::get_required_usage_from:iter:{:?}", a); - let arg = self.cmd.find(a).expect(INTERNAL_ERROR_MSG).to_string(); - ret_val.insert(arg); - } - let mut g_vec: Vec<String> = vec![]; - for g in unrolled_reqs - .iter() - .filter(|n| self.cmd.get_groups().any(|g| g.id == **n)) - { - // don't print requirement for required groups that have an arg. - if let Some(m) = matcher { - let have_group_entry = self - .cmd - .unroll_args_in_group(g) - .iter() - .any(|arg| m.check_explicit(arg, ArgPredicate::IsPresent)); - if have_group_entry { - continue; + let mut required_groups_members = IndexSet::new(); + let mut required_opts = IndexSet::new(); + let mut required_groups = IndexSet::new(); + let mut required_positionals = Vec::new(); + for req in unrolled_reqs.iter().chain(incls.iter()) { + if let Some(arg) = self.cmd.find(req) { + let is_present = matcher + .map(|m| m.check_explicit(req, ArgPredicate::IsPresent)) + .unwrap_or(false); + debug!( + "Usage::get_required_usage_from:iter:{:?} arg is_present={}", + req, is_present + ); + if !is_present { + if arg.is_positional() { + if incl_last || !arg.is_last_set() { + required_positionals.push((arg.index.unwrap(), arg.to_string())); + } + } else { + required_opts.insert(arg.to_string()); + } + } + } else { + debug_assert!(self.cmd.find_group(req).is_some()); + let group_members = self.cmd.unroll_args_in_group(req); + let is_present = matcher + .map(|m| { + group_members + .iter() + .any(|arg| m.check_explicit(arg, ArgPredicate::IsPresent)) + }) + .unwrap_or(false); + debug!( + "Usage::get_required_usage_from:iter:{:?} group is_present={}", + req, is_present + ); + if !is_present { + let elem = self.cmd.format_group(req); + required_groups.insert(elem); + required_groups_members.extend( + group_members + .iter() + .flat_map(|id| self.cmd.find(id)) + .map(|arg| arg.to_string()), + ); } - } - - let elem = self.cmd.format_group(g); - if !g_vec.contains(&elem) { - g_vec.push(elem); } } - ret_val.extend(g_vec); - let mut pvec = unrolled_reqs - .iter() - .chain(incls.iter()) - .filter(|a| self.cmd.get_positionals().any(|p| &&p.id == a)) - .filter(|&pos| { - matcher.map_or(true, |m| !m.check_explicit(pos, ArgPredicate::IsPresent)) - }) - .filter_map(|pos| self.cmd.find(pos)) - .filter(|&pos| incl_last || !pos.is_last_set()) - .filter(|pos| !args_in_groups.contains(&pos.id)) - .map(|pos| (pos.index.unwrap(), pos)) - .collect::<Vec<(usize, &Arg)>>(); - pvec.sort_by_key(|(ind, _)| *ind); // sort by index - - for (_, p) in pvec { - debug!("Usage::get_required_usage_from:push:{:?}", p.id); - if !args_in_groups.contains(&p.id) { - ret_val.insert(p.to_string()); + required_opts.retain(|arg| !required_groups_members.contains(arg)); + ret_val.extend(required_opts); + + ret_val.extend(required_groups); + + required_positionals.sort_by_key(|(ind, _)| *ind); // sort by index + for (_, p) in required_positionals { + if !required_groups_members.contains(&p) { + ret_val.insert(p); } } diff --git a/vendor/clap/src/parser/arg_matcher.rs b/vendor/clap-3.2.20/src/parser/arg_matcher.rs index 8d15c5799..22087e722 100644 --- a/vendor/clap/src/parser/arg_matcher.rs +++ b/vendor/clap-3.2.20/src/parser/arg_matcher.rs @@ -74,9 +74,7 @@ impl ArgMatcher { // a default value of `other` myprog would have an existing MatchedArg for // `--global-arg` where the value is `other` let to_update = if let Some(parent_ma) = vals_map.get(global_arg) { - if parent_ma.check_explicit(ArgPredicate::IsPresent) - && !ma.check_explicit(ArgPredicate::IsPresent) - { + if parent_ma.source() > ma.source() { parent_ma } else { ma diff --git a/vendor/clap/src/parser/features/mod.rs b/vendor/clap-3.2.20/src/parser/features/mod.rs index bdeb766ec..bdeb766ec 100644 --- a/vendor/clap/src/parser/features/mod.rs +++ b/vendor/clap-3.2.20/src/parser/features/mod.rs diff --git a/vendor/clap/src/parser/features/suggestions.rs b/vendor/clap-3.2.20/src/parser/features/suggestions.rs index 9e46f3c9e..9e46f3c9e 100644 --- a/vendor/clap/src/parser/features/suggestions.rs +++ b/vendor/clap-3.2.20/src/parser/features/suggestions.rs diff --git a/vendor/clap/src/parser/matches/any_value.rs b/vendor/clap-3.2.20/src/parser/matches/any_value.rs index a9277e75f..a9277e75f 100644 --- a/vendor/clap/src/parser/matches/any_value.rs +++ b/vendor/clap-3.2.20/src/parser/matches/any_value.rs diff --git a/vendor/clap/src/parser/matches/arg_matches.rs b/vendor/clap-3.2.20/src/parser/matches/arg_matches.rs index 17fa63ca6..2585c0219 100644 --- a/vendor/clap/src/parser/matches/arg_matches.rs +++ b/vendor/clap-3.2.20/src/parser/matches/arg_matches.rs @@ -119,6 +119,69 @@ impl ArgMatches { MatchesError::unwrap(&internal_id, self.try_get_one(id)) } + /// Gets the value of a specific [`ArgAction::Count`][crate::ArgAction::Count] flag + /// + /// # Panic + /// + /// If the argument's action is not [`ArgAction::Count`][crate::ArgAction::Count] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::Count) + /// ); + /// + /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); + /// assert_eq!( + /// matches.get_count("flag"), + /// 2 + /// ); + /// ``` + #[track_caller] + pub fn get_count(&self, id: &str) -> u8 { + *self + .get_one::<u8>(id) + .expect("ArgAction::Count is defaulted") + } + + /// Gets the value of a specific [`ArgAction::SetTrue`][crate::ArgAction::SetTrue] or [`ArgAction::SetFalse`][crate::ArgAction::SetFalse] flag + /// + /// # Panic + /// + /// If the argument's action is not [`ArgAction::SetTrue`][crate::ArgAction::SetTrue] or [`ArgAction::SetFalse`][crate::ArgAction::SetFalse] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::SetTrue) + /// ); + /// + /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_flag("flag"), + /// true + /// ); + /// ``` + #[track_caller] + pub fn get_flag(&self, id: &str) -> bool { + *self + .get_one::<bool>(id) + .expect("ArgAction::SetTrue / ArgAction::SetFalse is defaulted") + } + /// Iterate over values of a specific option or positional argument. /// /// i.e. an argument that takes multiple values at runtime. @@ -604,13 +667,13 @@ impl ArgMatches { value.and_then(MatchedArg::source) } - /// Deprecated, replaced with [`ArgAction::Count`][crate::ArgAction] or - /// [`ArgMatches::get_many`]`.len()`. + /// Deprecated, replaced with [`ArgAction::Count`][crate::ArgAction], + /// [`ArgMatches::get_many`]`.len()`, or [`ArgMatches::value_source`]. #[cfg_attr( feature = "deprecated", deprecated( since = "3.2.0", - note = "Replaced with either `ArgAction::Count` or `ArgMatches::get_many(...).len()`" + note = "Replaced with either `ArgAction::Count`, `ArgMatches::get_many(...).len()`, or `ArgMatches::value_source`" ) )] #[cfg_attr(debug_assertions, track_caller)] @@ -1742,6 +1805,11 @@ mod tests { use super::*; #[test] + fn check_auto_traits() { + static_assertions::assert_impl_all!(ArgMatches: Send, Sync, Unpin); + } + + #[test] fn test_default_values() { #![allow(deprecated)] let mut values: Values = Values::default(); diff --git a/vendor/clap/src/parser/matches/matched_arg.rs b/vendor/clap-3.2.20/src/parser/matches/matched_arg.rs index fde6d37f3..fde6d37f3 100644 --- a/vendor/clap/src/parser/matches/matched_arg.rs +++ b/vendor/clap-3.2.20/src/parser/matches/matched_arg.rs diff --git a/vendor/clap/src/parser/matches/mod.rs b/vendor/clap-3.2.20/src/parser/matches/mod.rs index 7b88eeca7..7b88eeca7 100644 --- a/vendor/clap/src/parser/matches/mod.rs +++ b/vendor/clap-3.2.20/src/parser/matches/mod.rs diff --git a/vendor/clap/src/parser/matches/value_source.rs b/vendor/clap-3.2.20/src/parser/matches/value_source.rs index fb762d2af..fb762d2af 100644 --- a/vendor/clap/src/parser/matches/value_source.rs +++ b/vendor/clap-3.2.20/src/parser/matches/value_source.rs diff --git a/vendor/clap/src/parser/mod.rs b/vendor/clap-3.2.20/src/parser/mod.rs index da81648e1..da81648e1 100644 --- a/vendor/clap/src/parser/mod.rs +++ b/vendor/clap-3.2.20/src/parser/mod.rs diff --git a/vendor/clap/src/parser/parser.rs b/vendor/clap-3.2.20/src/parser/parser.rs index fc95dad22..ad2bc6e9c 100644 --- a/vendor/clap/src/parser/parser.rs +++ b/vendor/clap-3.2.20/src/parser/parser.rs @@ -98,77 +98,6 @@ impl<'help, 'cmd> Parser<'help, 'cmd> { arg_os.to_value_os().as_raw_bytes() ); - // Correct pos_counter. - pos_counter = { - let is_second_to_last = pos_counter + 1 == positional_count; - - // 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() - .last() - .map_or(false, |p_name| !p_name.is_last_set()); - - let missing_pos = self.cmd.is_allow_missing_positional_set() - && is_second_to_last - && !trailing_values; - - debug!( - "Parser::get_matches_with: Positional counter...{}", - pos_counter - ); - debug!( - "Parser::get_matches_with: Low index multiples...{:?}", - low_index_mults - ); - - if low_index_mults || missing_pos { - let skip_current = if let Some(n) = raw_args.peek(&args_cursor) { - if let Some(arg) = self - .cmd - .get_positionals() - .find(|a| a.index == Some(pos_counter)) - { - // If next value looks like a new_arg or it's a - // subcommand, skip positional argument under current - // pos_counter(which means current value cannot be a - // positional argument with a value next to it), assume - // current value matches the next arg. - self.is_new_arg(&n, arg) - || self - .possible_subcommand(n.to_value(), valid_arg_found) - .is_some() - } else { - true - } - } else { - true - }; - - if skip_current { - debug!("Parser::get_matches_with: Bumping the positional counter..."); - pos_counter + 1 - } else { - pos_counter - } - } else if trailing_values - && (self.cmd.is_allow_missing_positional_set() || contains_last) - { - // Came to -- and one positional has .last(true) set, so we go immediately - // to the last (highest index) positional - debug!("Parser::get_matches_with: .last(true) and --, setting last pos"); - positional_count - } else { - pos_counter - } - }; - // Has the user already passed '--'? Meaning only positional args follow if !trailing_values { if self.cmd.is_subcommand_precedence_over_arg_set() @@ -376,6 +305,77 @@ impl<'help, 'cmd> Parser<'help, 'cmd> { } } + // Correct pos_counter. + pos_counter = { + let is_second_to_last = pos_counter + 1 == positional_count; + + // 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() + .last() + .map_or(false, |p_name| !p_name.is_last_set()); + + let missing_pos = self.cmd.is_allow_missing_positional_set() + && is_second_to_last + && !trailing_values; + + debug!( + "Parser::get_matches_with: Positional counter...{}", + pos_counter + ); + debug!( + "Parser::get_matches_with: Low index multiples...{:?}", + low_index_mults + ); + + if low_index_mults || missing_pos { + let skip_current = if let Some(n) = raw_args.peek(&args_cursor) { + if let Some(arg) = self + .cmd + .get_positionals() + .find(|a| a.index == Some(pos_counter)) + { + // If next value looks like a new_arg or it's a + // subcommand, skip positional argument under current + // pos_counter(which means current value cannot be a + // positional argument with a value next to it), assume + // current value matches the next arg. + self.is_new_arg(&n, arg) + || self + .possible_subcommand(n.to_value(), valid_arg_found) + .is_some() + } else { + true + } + } else { + true + }; + + if skip_current { + debug!("Parser::get_matches_with: Bumping the positional counter..."); + pos_counter + 1 + } else { + pos_counter + } + } else if trailing_values + && (self.cmd.is_allow_missing_positional_set() || contains_last) + { + // Came to -- and one positional has .last(true) set, so we go immediately + // to the last (highest index) positional + debug!("Parser::get_matches_with: .last(true) and --, setting last pos"); + positional_count + } else { + pos_counter + } + }; + if let Some(arg) = self.cmd.get_keymap().get(&pos_counter) { if arg.is_last_set() && !trailing_values { let _ = self.resolve_pending(matcher); @@ -738,8 +738,10 @@ impl<'help, 'cmd> Parser<'help, 'cmd> { } }; if long_arg.is_empty() { - debug_assert!(long_value.is_none(), "{:?}", long_value); - return Ok(ParseResult::NoArg); + debug_assert!( + long_value.is_some(), + "`--` should be filtered out before this point" + ); } let arg = if let Some(arg) = self.cmd.get_keymap().get(long_arg) { diff --git a/vendor/clap/src/parser/validator.rs b/vendor/clap-3.2.20/src/parser/validator.rs index ebf2b234d..ebf2b234d 100644 --- a/vendor/clap/src/parser/validator.rs +++ b/vendor/clap-3.2.20/src/parser/validator.rs diff --git a/vendor/clap/src/util/color.rs b/vendor/clap-3.2.20/src/util/color.rs index 15c9901a0..15c9901a0 100644 --- a/vendor/clap/src/util/color.rs +++ b/vendor/clap-3.2.20/src/util/color.rs diff --git a/vendor/clap/src/util/fnv.rs b/vendor/clap-3.2.20/src/util/fnv.rs index 4602300a4..4602300a4 100644 --- a/vendor/clap/src/util/fnv.rs +++ b/vendor/clap-3.2.20/src/util/fnv.rs diff --git a/vendor/clap/src/util/graph.rs b/vendor/clap-3.2.20/src/util/graph.rs index d646400b0..d646400b0 100644 --- a/vendor/clap/src/util/graph.rs +++ b/vendor/clap-3.2.20/src/util/graph.rs diff --git a/vendor/clap/src/util/id.rs b/vendor/clap-3.2.20/src/util/id.rs index 63a7e003e..63a7e003e 100644 --- a/vendor/clap/src/util/id.rs +++ b/vendor/clap-3.2.20/src/util/id.rs diff --git a/vendor/clap/src/util/mod.rs b/vendor/clap-3.2.20/src/util/mod.rs index 8adc8db17..8adc8db17 100644 --- a/vendor/clap/src/util/mod.rs +++ b/vendor/clap-3.2.20/src/util/mod.rs diff --git a/vendor/clap/src/util/str_to_bool.rs b/vendor/clap-3.2.20/src/util/str_to_bool.rs index 1fbdc7531..1fbdc7531 100644 --- a/vendor/clap/src/util/str_to_bool.rs +++ b/vendor/clap-3.2.20/src/util/str_to_bool.rs diff --git a/vendor/clap/src/error/kind.rs b/vendor/clap/src/error/kind.rs deleted file mode 100644 index 21256609a..000000000 --- a/vendor/clap/src/error/kind.rs +++ /dev/null @@ -1,440 +0,0 @@ -/// Command line argument parser kind of error -#[derive(Debug, Copy, Clone, PartialEq)] -#[non_exhaustive] -pub enum ErrorKind { - /// Occurs when an [`Arg`][crate::Arg] has a set of possible values, - /// and the user provides a value which isn't in that set. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("speed") - /// .value_parser(["fast", "slow"])) - /// .try_get_matches_from(vec!["prog", "other"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidValue); - /// ``` - InvalidValue, - - /// Occurs when a user provides a flag, option, argument or subcommand which isn't defined. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(arg!(--flag "some flag")) - /// .try_get_matches_from(vec!["prog", "--other"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - UnknownArgument, - - /// Occurs when the user provides an unrecognized [`Subcommand`] which meets the threshold for - /// being similar enough to an existing subcommand. - /// If it doesn't meet the threshold, or the 'suggestions' feature is disabled, - /// the more general [`UnknownArgument`] error is returned. - /// - /// # Examples - /// - #[cfg_attr(not(feature = "suggestions"), doc = " ```no_run")] - #[cfg_attr(feature = "suggestions", doc = " ```")] - /// # use clap::{Command, Arg, ErrorKind, }; - /// let result = Command::new("prog") - /// .subcommand(Command::new("config") - /// .about("Used for configuration") - /// .arg(Arg::new("config_file") - /// .help("The configuration file to use"))) - /// .try_get_matches_from(vec!["prog", "confi"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidSubcommand); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - /// [`UnknownArgument`]: ErrorKind::UnknownArgument - InvalidSubcommand, - - /// Occurs when the user provides an unrecognized [`Subcommand`] which either - /// doesn't meet the threshold for being similar enough to an existing subcommand, - /// or the 'suggestions' feature is disabled. - /// Otherwise the more detailed [`InvalidSubcommand`] error is returned. - /// - /// This error typically happens when passing additional subcommand names to the `help` - /// subcommand. Otherwise, the more general [`UnknownArgument`] error is used. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind, }; - /// let result = Command::new("prog") - /// .subcommand(Command::new("config") - /// .about("Used for configuration") - /// .arg(Arg::new("config_file") - /// .help("The configuration file to use"))) - /// .try_get_matches_from(vec!["prog", "help", "nothing"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::UnrecognizedSubcommand); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - /// [`InvalidSubcommand`]: ErrorKind::InvalidSubcommand - /// [`UnknownArgument`]: ErrorKind::UnknownArgument - UnrecognizedSubcommand, - - /// Occurs when the user provides an empty value for an option that does not allow empty - /// values. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("color") - /// .takes_value(true) - /// .forbid_empty_values(true) - /// .long("color")) - /// .try_get_matches_from(vec!["prog", "--color="]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::EmptyValue); - /// ``` - EmptyValue, - - /// Occurs when the user doesn't use equals for an option that requires equal - /// sign to provide values. - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let res = Command::new("prog") - /// .arg(Arg::new("color") - /// .takes_value(true) - /// .require_equals(true) - /// .long("color")) - /// .try_get_matches_from(vec!["prog", "--color", "red"]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals); - /// ``` - NoEquals, - - /// Occurs when the user provides a value for an argument with a custom validation and the - /// value fails that validation. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// fn is_numeric(val: &str) -> Result<(), String> { - /// match val.parse::<i64>() { - /// Ok(..) => Ok(()), - /// Err(..) => Err(String::from("Value wasn't a number!")), - /// } - /// } - /// - /// let result = Command::new("prog") - /// .arg(Arg::new("num") - /// .validator(is_numeric)) - /// .try_get_matches_from(vec!["prog", "NotANumber"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::ValueValidation); - /// ``` - ValueValidation, - - /// Occurs when a user provides more values for an argument than were defined by setting - /// [`Arg::max_values`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("arg") - /// .max_values(2)) - /// .try_get_matches_from(vec!["prog", "too", "many", "values"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooManyValues); - /// ``` - /// [`Arg::max_values`]: crate::Arg::max_values() - TooManyValues, - - /// Occurs when the user provides fewer values for an argument than were defined by setting - /// [`Arg::min_values`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("some_opt") - /// .long("opt") - /// .min_values(3)) - /// .try_get_matches_from(vec!["prog", "--opt", "too", "few"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooFewValues); - /// ``` - /// [`Arg::min_values`]: crate::Arg::min_values() - TooFewValues, - - /// Occurs when a user provides more occurrences for an argument than were defined by setting - /// [`Arg::max_occurrences`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("verbosity") - /// .short('v') - /// .max_occurrences(2)) - /// .try_get_matches_from(vec!["prog", "-vvv"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooManyOccurrences); - /// ``` - /// [`Arg::max_occurrences`]: crate::Arg::max_occurrences() - TooManyOccurrences, - - /// Occurs when the user provides a different number of values for an argument than what's - /// been defined by setting [`Arg::number_of_values`] or than was implicitly set by - /// [`Arg::value_names`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("some_opt") - /// .long("opt") - /// .takes_value(true) - /// .number_of_values(2)) - /// .try_get_matches_from(vec!["prog", "--opt", "wrong"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::WrongNumberOfValues); - /// ``` - /// - /// [`Arg::number_of_values`]: crate::Arg::number_of_values() - /// [`Arg::value_names`]: crate::Arg::value_names() - WrongNumberOfValues, - - /// Occurs when the user provides two values which conflict with each other and can't be used - /// together. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("debug") - /// .long("debug") - /// .conflicts_with("color")) - /// .arg(Arg::new("color") - /// .long("color")) - /// .try_get_matches_from(vec!["prog", "--debug", "--color"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::ArgumentConflict); - /// ``` - ArgumentConflict, - - /// Occurs when the user does not provide one or more required arguments. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("debug") - /// .required(true)) - /// .try_get_matches_from(vec!["prog"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - MissingRequiredArgument, - - /// Occurs when a subcommand is required (as defined by [`Command::subcommand_required`]), - /// but the user does not provide one. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, ErrorKind}; - /// let err = Command::new("prog") - /// .subcommand_required(true) - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog", - /// ]); - /// assert!(err.is_err()); - /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); - /// # ; - /// ``` - /// - /// [`Command::subcommand_required`]: crate::Command::subcommand_required - MissingSubcommand, - - /// Occurs when the user provides multiple values to an argument which doesn't allow that. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("debug") - /// .long("debug") - /// .multiple_occurrences(false)) - /// .try_get_matches_from(vec!["prog", "--debug", "--debug"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::UnexpectedMultipleUsage); - /// ``` - UnexpectedMultipleUsage, - - /// Occurs when the user provides a value containing invalid UTF-8. - /// - /// To allow arbitrary data - /// - Set [`Arg::allow_invalid_utf8`] for argument values - /// - Set [`Command::allow_invalid_utf8_for_external_subcommands`] for external-subcommand - /// values - /// - /// # Platform Specific - /// - /// Non-Windows platforms only (such as Linux, Unix, OSX, etc.) - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{Command, Arg, ErrorKind}; - /// # use std::os::unix::ffi::OsStringExt; - /// # use std::ffi::OsString; - /// let result = Command::new("prog") - /// .arg(Arg::new("utf8") - /// .short('u') - /// .takes_value(true)) - /// .try_get_matches_from(vec![OsString::from("myprog"), - /// OsString::from("-u"), - /// OsString::from_vec(vec![0xE9])]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidUtf8); - /// ``` - /// - /// [`Arg::allow_invalid_utf8`]: crate::Arg::allow_invalid_utf8 - /// [`Command::allow_invalid_utf8_for_external_subcommands`]: crate::Command::allow_invalid_utf8_for_external_subcommands - InvalidUtf8, - - /// Not a true "error" as it means `--help` or similar was used. - /// The help message will be sent to `stdout`. - /// - /// **Note**: If the help is displayed due to an error (such as missing subcommands) it will - /// be sent to `stderr` instead of `stdout`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .try_get_matches_from(vec!["prog", "--help"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayHelp); - /// ``` - DisplayHelp, - - /// Occurs when either an argument or a [`Subcommand`] is required, as defined by - /// [`Command::arg_required_else_help`] , but the user did not provide - /// one. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind, }; - /// let result = Command::new("prog") - /// .arg_required_else_help(true) - /// .subcommand(Command::new("config") - /// .about("Used for configuration") - /// .arg(Arg::new("config_file") - /// .help("The configuration file to use"))) - /// .try_get_matches_from(vec!["prog"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - /// [`Command::arg_required_else_help`]: crate::Command::arg_required_else_help - DisplayHelpOnMissingArgumentOrSubcommand, - - /// Not a true "error" as it means `--version` or similar was used. - /// The message will be sent to `stdout`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ErrorKind}; - /// let result = Command::new("prog") - /// .version("3.0") - /// .try_get_matches_from(vec!["prog", "--version"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayVersion); - /// ``` - DisplayVersion, - - /// Occurs when using the [`ArgMatches::value_of_t`] and friends to convert an argument value - /// into type `T`, but the argument you requested wasn't used. I.e. you asked for an argument - /// with name `config` to be converted, but `config` wasn't used by the user. - /// - /// [`ArgMatches::value_of_t`]: crate::ArgMatches::value_of_t() - ArgumentNotFound, - - /// Represents an [I/O error]. - /// Can occur when writing to `stderr` or `stdout` or reading a configuration file. - /// - /// [I/O error]: std::io::Error - Io, - - /// Represents a [Format error] (which is a part of [`Display`]). - /// Typically caused by writing to `stderr` or `stdout`. - /// - /// [`Display`]: std::fmt::Display - /// [Format error]: std::fmt::Error - Format, -} - -impl ErrorKind { - /// End-user description of the error case, where relevant - pub fn as_str(self) -> Option<&'static str> { - match self { - Self::InvalidValue => Some("One of the values isn't valid for an argument"), - Self::UnknownArgument => { - Some("Found an argument which wasn't expected or isn't valid in this context") - } - Self::InvalidSubcommand => Some("A subcommand wasn't recognized"), - Self::UnrecognizedSubcommand => Some("A subcommand wasn't recognized"), - Self::EmptyValue => Some("An argument requires a value but none was supplied"), - Self::NoEquals => Some("Equal is needed when assigning values to one of the arguments"), - Self::ValueValidation => Some("Invalid for for one of the arguments"), - Self::TooManyValues => Some("An argument received an unexpected value"), - Self::TooFewValues => Some("An argument requires more values"), - Self::TooManyOccurrences => Some("An argument occurred too many times"), - Self::WrongNumberOfValues => Some("An argument received too many or too few values"), - Self::ArgumentConflict => { - Some("An argument cannot be used with one or more of the other specified arguments") - } - Self::MissingRequiredArgument => { - Some("One or more required arguments were not provided") - } - Self::MissingSubcommand => Some("A subcommand is required but one was not provided"), - Self::UnexpectedMultipleUsage => { - Some("An argument was provided more than once but cannot be used multiple times") - } - Self::InvalidUtf8 => Some("Invalid UTF-8 was detected in one or more arguments"), - Self::DisplayHelp => None, - Self::DisplayHelpOnMissingArgumentOrSubcommand => None, - Self::DisplayVersion => None, - Self::ArgumentNotFound => Some("An argument wasn't found"), - Self::Io => None, - Self::Format => None, - } - } -} - -impl std::fmt::Display for ErrorKind { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.as_str().unwrap_or_default().fmt(f) - } -} diff --git a/vendor/clap/src/error/mod.rs b/vendor/clap/src/error/mod.rs deleted file mode 100644 index df9a84c56..000000000 --- a/vendor/clap/src/error/mod.rs +++ /dev/null @@ -1,1158 +0,0 @@ -//! Error reporting -#![allow(deprecated)] - -// Std -use std::{ - borrow::Cow, - convert::From, - error, - fmt::{self, Debug, Display, Formatter}, - io::{self, BufRead}, - result::Result as StdResult, -}; - -// Internal -use crate::output::fmt::Colorizer; -use crate::output::fmt::Stream; -use crate::parser::features::suggestions; -use crate::util::{color::ColorChoice, safe_exit, SUCCESS_CODE, USAGE_CODE}; -use crate::AppSettings; -use crate::Command; - -mod context; -mod kind; - -pub use context::ContextKind; -pub use context::ContextValue; -pub use kind::ErrorKind; - -/// Short hand for [`Result`] type -/// -/// [`Result`]: std::result::Result -pub type Result<T, E = Error> = StdResult<T, E>; - -/// Command Line Argument Parser Error -/// -/// See [`Command::error`] to create an error. -/// -/// [`Command::error`]: crate::Command::error -#[derive(Debug)] -pub struct Error { - inner: Box<ErrorInner>, - /// Deprecated, replaced with [`Error::kind()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Error::kind()`") - )] - pub kind: ErrorKind, - /// Deprecated, replaced with [`Error::context()`] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `Error::context()`") - )] - pub info: Vec<String>, -} - -#[derive(Debug)] -struct ErrorInner { - kind: ErrorKind, - context: Vec<(ContextKind, ContextValue)>, - message: Option<Message>, - source: Option<Box<dyn error::Error + Send + Sync>>, - help_flag: Option<&'static str>, - color_when: ColorChoice, - wait_on_exit: bool, - backtrace: Option<Backtrace>, -} - -impl Error { - /// Create an unformatted error - /// - /// This is for you need to pass the error up to - /// a place that has access to the `Command` at which point you can call [`Error::format`]. - /// - /// Prefer [`Command::error`] for generating errors. - /// - /// [`Command::error`]: crate::Command::error - pub fn raw(kind: ErrorKind, message: impl std::fmt::Display) -> Self { - Self::new(kind).set_message(message.to_string()) - } - - /// Format the existing message with the Command's context - #[must_use] - pub fn format(mut self, cmd: &mut Command) -> Self { - cmd._build_self(); - let usage = cmd.render_usage(); - if let Some(message) = self.inner.message.as_mut() { - message.format(cmd, usage); - } - self.with_cmd(cmd) - } - - /// Type of error for programmatic processing - pub fn kind(&self) -> ErrorKind { - self.inner.kind - } - - /// Additional information to further qualify the error - pub fn context(&self) -> impl Iterator<Item = (ContextKind, &ContextValue)> { - self.inner.context.iter().map(|(k, v)| (*k, v)) - } - - /// Should the message be written to `stdout` or not? - #[inline] - pub fn use_stderr(&self) -> bool { - self.stream() == Stream::Stderr - } - - pub(crate) fn stream(&self) -> Stream { - match self.kind() { - ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => Stream::Stdout, - _ => Stream::Stderr, - } - } - - /// Prints the error and exits. - /// - /// Depending on the error kind, this either prints to `stderr` and exits with a status of `2` - /// or prints to `stdout` and exits with a status of `0`. - pub fn exit(&self) -> ! { - if self.use_stderr() { - // Swallow broken pipe errors - let _ = self.print(); - - if self.inner.wait_on_exit { - wlnerr!("\nPress [ENTER] / [RETURN] to continue..."); - let mut s = String::new(); - let i = io::stdin(); - i.lock().read_line(&mut s).unwrap(); - } - - safe_exit(USAGE_CODE); - } - - // Swallow broken pipe errors - let _ = self.print(); - safe_exit(SUCCESS_CODE) - } - - /// Prints formatted and colored error to `stdout` or `stderr` according to its error kind - /// - /// # Example - /// ```no_run - /// use clap::Command; - /// - /// match Command::new("Command").try_get_matches() { - /// Ok(matches) => { - /// // do_something - /// }, - /// Err(err) => { - /// err.print().expect("Error writing Error"); - /// // do_something - /// }, - /// }; - /// ``` - pub fn print(&self) -> io::Result<()> { - self.formatted().print() - } - - /// Deprecated, replaced with [`Command::error`] - /// - /// [`Command::error`]: crate::Command::error - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Command::error`") - )] - #[doc(hidden)] - pub fn with_description(description: String, kind: ErrorKind) -> Self { - Error::raw(kind, description) - } - - fn new(kind: ErrorKind) -> Self { - Self { - inner: Box::new(ErrorInner { - kind, - context: Vec::new(), - message: None, - source: None, - help_flag: None, - color_when: ColorChoice::Never, - wait_on_exit: false, - backtrace: Backtrace::new(), - }), - kind, - info: vec![], - } - } - - #[inline(never)] - fn for_app(kind: ErrorKind, cmd: &Command, colorizer: Colorizer, info: Vec<String>) -> Self { - Self::new(kind) - .set_message(colorizer) - .with_cmd(cmd) - .set_info(info) - } - - pub(crate) fn with_cmd(self, cmd: &Command) -> Self { - self.set_wait_on_exit(cmd.is_set(AppSettings::WaitOnError)) - .set_color(cmd.get_color()) - .set_help_flag(get_help_flag(cmd)) - } - - pub(crate) fn set_message(mut self, message: impl Into<Message>) -> Self { - self.inner.message = Some(message.into()); - self - } - - pub(crate) fn set_info(mut self, info: Vec<String>) -> Self { - self.info = info; - self - } - - pub(crate) fn set_source(mut self, source: Box<dyn error::Error + Send + Sync>) -> Self { - self.inner.source = Some(source); - self - } - - pub(crate) fn set_color(mut self, color_when: ColorChoice) -> Self { - self.inner.color_when = color_when; - self - } - - pub(crate) fn set_help_flag(mut self, help_flag: Option<&'static str>) -> Self { - self.inner.help_flag = help_flag; - self - } - - pub(crate) fn set_wait_on_exit(mut self, yes: bool) -> Self { - self.inner.wait_on_exit = yes; - self - } - - /// Does not verify if `ContextKind` is already present - #[inline(never)] - pub(crate) fn insert_context_unchecked( - mut self, - kind: ContextKind, - value: ContextValue, - ) -> Self { - self.inner.context.push((kind, value)); - self - } - - /// Does not verify if `ContextKind` is already present - #[inline(never)] - pub(crate) fn extend_context_unchecked<const N: usize>( - mut self, - context: [(ContextKind, ContextValue); N], - ) -> Self { - self.inner.context.extend(context); - self - } - - #[inline(never)] - fn get_context(&self, kind: ContextKind) -> Option<&ContextValue> { - self.inner - .context - .iter() - .find_map(|(k, v)| (*k == kind).then(|| v)) - } - - pub(crate) fn display_help(cmd: &Command, colorizer: Colorizer) -> Self { - Self::for_app(ErrorKind::DisplayHelp, cmd, colorizer, vec![]) - } - - pub(crate) fn display_help_error(cmd: &Command, colorizer: Colorizer) -> Self { - Self::for_app( - ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand, - cmd, - colorizer, - vec![], - ) - } - - pub(crate) fn display_version(cmd: &Command, colorizer: Colorizer) -> Self { - Self::for_app(ErrorKind::DisplayVersion, cmd, colorizer, vec![]) - } - - pub(crate) fn argument_conflict( - cmd: &Command, - arg: String, - mut others: Vec<String>, - usage: String, - ) -> Self { - let info = others.clone(); - let others = match others.len() { - 0 => ContextValue::None, - 1 => ContextValue::String(others.pop().unwrap()), - _ => ContextValue::Strings(others), - }; - Self::new(ErrorKind::ArgumentConflict) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::PriorArg, others), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn empty_value(cmd: &Command, good_vals: &[&str], arg: String) -> Self { - let info = vec![arg.clone()]; - let mut err = Self::new(ErrorKind::EmptyValue) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([(ContextKind::InvalidArg, ContextValue::String(arg))]); - if !good_vals.is_empty() { - err = err.insert_context_unchecked( - ContextKind::ValidValue, - ContextValue::Strings(good_vals.iter().map(|s| (*s).to_owned()).collect()), - ); - } - err - } - - pub(crate) fn no_equals(cmd: &Command, arg: String, usage: String) -> Self { - let info = vec![arg.clone()]; - Self::new(ErrorKind::NoEquals) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn invalid_value( - cmd: &Command, - bad_val: String, - good_vals: &[&str], - arg: String, - ) -> Self { - let mut info = vec![arg.clone(), bad_val.clone()]; - info.extend(good_vals.iter().map(|s| (*s).to_owned())); - - let suggestion = suggestions::did_you_mean(&bad_val, good_vals.iter()).pop(); - let mut err = Self::new(ErrorKind::InvalidValue) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::InvalidValue, ContextValue::String(bad_val)), - ( - ContextKind::ValidValue, - ContextValue::Strings(good_vals.iter().map(|s| (*s).to_owned()).collect()), - ), - ]); - if let Some(suggestion) = suggestion { - err = err.insert_context_unchecked( - ContextKind::SuggestedValue, - ContextValue::String(suggestion), - ); - } - err - } - - pub(crate) fn invalid_subcommand( - cmd: &Command, - subcmd: String, - did_you_mean: String, - name: String, - usage: String, - ) -> Self { - let info = vec![subcmd.clone()]; - let suggestion = format!("{} -- {}", name, subcmd); - Self::new(ErrorKind::InvalidSubcommand) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidSubcommand, ContextValue::String(subcmd)), - ( - ContextKind::SuggestedSubcommand, - ContextValue::String(did_you_mean), - ), - ( - ContextKind::SuggestedCommand, - ContextValue::String(suggestion), - ), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn unrecognized_subcommand(cmd: &Command, subcmd: String, usage: String) -> Self { - let info = vec![subcmd.clone()]; - Self::new(ErrorKind::UnrecognizedSubcommand) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidSubcommand, ContextValue::String(subcmd)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn missing_required_argument( - cmd: &Command, - required: Vec<String>, - usage: String, - ) -> Self { - let info = required.clone(); - Self::new(ErrorKind::MissingRequiredArgument) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::Strings(required)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn missing_subcommand(cmd: &Command, name: String, usage: String) -> Self { - let info = vec![]; - Self::new(ErrorKind::MissingSubcommand) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidSubcommand, ContextValue::String(name)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn invalid_utf8(cmd: &Command, usage: String) -> Self { - let info = vec![]; - Self::new(ErrorKind::InvalidUtf8) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([(ContextKind::Usage, ContextValue::String(usage))]) - } - - pub(crate) fn too_many_occurrences( - cmd: &Command, - arg: String, - max_occurs: usize, - curr_occurs: usize, - usage: String, - ) -> Self { - let info = vec![arg.clone(), curr_occurs.to_string(), max_occurs.to_string()]; - Self::new(ErrorKind::TooManyOccurrences) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - ( - ContextKind::MaxOccurrences, - ContextValue::Number(max_occurs as isize), - ), - ( - ContextKind::ActualNumValues, - ContextValue::Number(curr_occurs as isize), - ), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn too_many_values(cmd: &Command, val: String, arg: String, usage: String) -> Self { - let info = vec![arg.clone(), val.clone()]; - Self::new(ErrorKind::TooManyValues) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::InvalidValue, ContextValue::String(val)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn too_few_values( - cmd: &Command, - arg: String, - min_vals: usize, - curr_vals: usize, - usage: String, - ) -> Self { - let info = vec![arg.clone(), curr_vals.to_string(), min_vals.to_string()]; - Self::new(ErrorKind::TooFewValues) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - ( - ContextKind::MinValues, - ContextValue::Number(min_vals as isize), - ), - ( - ContextKind::ActualNumValues, - ContextValue::Number(curr_vals as isize), - ), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn value_validation( - arg: String, - val: String, - err: Box<dyn error::Error + Send + Sync>, - ) -> Self { - let info = vec![arg.clone(), val.to_string(), err.to_string()]; - Self::new(ErrorKind::ValueValidation) - .set_info(info) - .set_source(err) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::InvalidValue, ContextValue::String(val)), - ]) - } - - pub(crate) fn wrong_number_of_values( - cmd: &Command, - arg: String, - num_vals: usize, - curr_vals: usize, - usage: String, - ) -> Self { - let info = vec![arg.clone(), curr_vals.to_string(), num_vals.to_string()]; - Self::new(ErrorKind::WrongNumberOfValues) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - ( - ContextKind::ExpectedNumValues, - ContextValue::Number(num_vals as isize), - ), - ( - ContextKind::ActualNumValues, - ContextValue::Number(curr_vals as isize), - ), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn unexpected_multiple_usage(cmd: &Command, arg: String, usage: String) -> Self { - let info = vec![arg.clone()]; - Self::new(ErrorKind::UnexpectedMultipleUsage) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn unknown_argument( - cmd: &Command, - arg: String, - did_you_mean: Option<(String, Option<String>)>, - usage: String, - ) -> Self { - let info = vec![arg.clone()]; - let mut err = Self::new(ErrorKind::UnknownArgument) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::Usage, ContextValue::String(usage)), - ]); - if let Some((flag, sub)) = did_you_mean { - err = err.insert_context_unchecked( - ContextKind::SuggestedArg, - ContextValue::String(format!("--{}", flag)), - ); - if let Some(sub) = sub { - err = err.insert_context_unchecked( - ContextKind::SuggestedSubcommand, - ContextValue::String(sub), - ); - } - } - err - } - - pub(crate) fn unnecessary_double_dash(cmd: &Command, arg: String, usage: String) -> Self { - let info = vec![arg.clone()]; - Self::new(ErrorKind::UnknownArgument) - .with_cmd(cmd) - .set_info(info) - .extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::TrailingArg, ContextValue::Bool(true)), - (ContextKind::Usage, ContextValue::String(usage)), - ]) - } - - pub(crate) fn argument_not_found_auto(arg: String) -> Self { - let info = vec![arg.clone()]; - Self::new(ErrorKind::ArgumentNotFound) - .set_info(info) - .extend_context_unchecked([(ContextKind::InvalidArg, ContextValue::String(arg))]) - } - - fn formatted(&self) -> Cow<'_, Colorizer> { - if let Some(message) = self.inner.message.as_ref() { - message.formatted() - } else { - let mut c = Colorizer::new(self.stream(), self.inner.color_when); - - start_error(&mut c); - - if !self.write_dynamic_context(&mut c) { - if let Some(msg) = self.kind().as_str() { - c.none(msg.to_owned()); - } else if let Some(source) = self.inner.source.as_ref() { - c.none(source.to_string()); - } else { - c.none("Unknown cause"); - } - } - - let usage = self.get_context(ContextKind::Usage); - if let Some(ContextValue::String(usage)) = usage { - put_usage(&mut c, usage); - } - - try_help(&mut c, self.inner.help_flag); - - Cow::Owned(c) - } - } - - #[must_use] - fn write_dynamic_context(&self, c: &mut Colorizer) -> bool { - match self.kind() { - ErrorKind::ArgumentConflict => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let prior_arg = self.get_context(ContextKind::PriorArg); - if let (Some(ContextValue::String(invalid_arg)), Some(prior_arg)) = - (invalid_arg, prior_arg) - { - c.none("The argument '"); - c.warning(invalid_arg); - c.none("' cannot be used with"); - - match prior_arg { - ContextValue::Strings(values) => { - c.none(":"); - for v in values { - c.none("\n "); - c.warning(&**v); - } - } - ContextValue::String(value) => { - c.none(" '"); - c.warning(value); - c.none("'"); - } - _ => { - c.none(" one or more of the other specified arguments"); - } - } - true - } else { - false - } - } - ErrorKind::EmptyValue => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - c.none("The argument '"); - c.warning(invalid_arg); - c.none("' requires a value but none was supplied"); - - let possible_values = self.get_context(ContextKind::ValidValue); - if let Some(ContextValue::Strings(possible_values)) = possible_values { - c.none("\n\t[possible values: "); - if let Some((last, elements)) = possible_values.split_last() { - for v in elements { - c.good(escape(v)); - c.none(", "); - } - c.good(escape(last)); - } - c.none("]"); - } - true - } else { - false - } - } - ErrorKind::NoEquals => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - c.none("Equal sign is needed when assigning values to '"); - c.warning(invalid_arg); - c.none("'."); - true - } else { - false - } - } - ErrorKind::InvalidValue => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let invalid_value = self.get_context(ContextKind::InvalidValue); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::String(invalid_value)), - ) = (invalid_arg, invalid_value) - { - c.none(quote(invalid_value)); - c.none(" isn't a valid value for '"); - c.warning(invalid_arg); - c.none("'"); - - let possible_values = self.get_context(ContextKind::ValidValue); - if let Some(ContextValue::Strings(possible_values)) = possible_values { - c.none("\n\t[possible values: "); - if let Some((last, elements)) = possible_values.split_last() { - for v in elements { - c.good(escape(v)); - c.none(", "); - } - c.good(escape(last)); - } - c.none("]"); - } - - let suggestion = self.get_context(ContextKind::SuggestedValue); - if let Some(ContextValue::String(suggestion)) = suggestion { - c.none("\n\n\tDid you mean "); - c.good(quote(suggestion)); - c.none("?"); - } - true - } else { - false - } - } - ErrorKind::InvalidSubcommand => { - let invalid_sub = self.get_context(ContextKind::InvalidSubcommand); - if let Some(ContextValue::String(invalid_sub)) = invalid_sub { - c.none("The subcommand '"); - c.warning(invalid_sub); - c.none("' wasn't recognized"); - - let valid_sub = self.get_context(ContextKind::SuggestedSubcommand); - if let Some(ContextValue::String(valid_sub)) = valid_sub { - c.none("\n\n\tDid you mean "); - c.good(valid_sub); - c.none("?"); - } - - let suggestion = self.get_context(ContextKind::SuggestedCommand); - if let Some(ContextValue::String(suggestion)) = suggestion { - c.none( - "\n\nIf you believe you received this message in error, try re-running with '", - ); - c.good(suggestion); - c.none("'"); - } - true - } else { - false - } - } - ErrorKind::UnrecognizedSubcommand => { - let invalid_sub = self.get_context(ContextKind::InvalidSubcommand); - if let Some(ContextValue::String(invalid_sub)) = invalid_sub { - c.none("The subcommand '"); - c.warning(invalid_sub); - c.none("' wasn't recognized"); - true - } else { - false - } - } - ErrorKind::MissingRequiredArgument => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::Strings(invalid_arg)) = invalid_arg { - c.none("The following required arguments were not provided:"); - for v in invalid_arg { - c.none("\n "); - c.good(&**v); - } - true - } else { - false - } - } - ErrorKind::MissingSubcommand => { - let invalid_sub = self.get_context(ContextKind::InvalidSubcommand); - if let Some(ContextValue::String(invalid_sub)) = invalid_sub { - c.none("'"); - c.warning(invalid_sub); - c.none("' requires a subcommand but one was not provided"); - true - } else { - false - } - } - ErrorKind::InvalidUtf8 => false, - ErrorKind::TooManyOccurrences => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let actual_num_occurs = self.get_context(ContextKind::ActualNumOccurrences); - let max_occurs = self.get_context(ContextKind::MaxOccurrences); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::Number(actual_num_occurs)), - Some(ContextValue::Number(max_occurs)), - ) = (invalid_arg, actual_num_occurs, max_occurs) - { - let were_provided = Error::singular_or_plural(*actual_num_occurs as usize); - c.none("The argument '"); - c.warning(invalid_arg); - c.none("' allows at most "); - c.warning(max_occurs.to_string()); - c.none(" occurrences but "); - c.warning(actual_num_occurs.to_string()); - c.none(were_provided); - true - } else { - false - } - } - ErrorKind::TooManyValues => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let invalid_value = self.get_context(ContextKind::InvalidValue); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::String(invalid_value)), - ) = (invalid_arg, invalid_value) - { - c.none("The value '"); - c.warning(invalid_value); - c.none("' was provided to '"); - c.warning(invalid_arg); - c.none("' but it wasn't expecting any more values"); - true - } else { - false - } - } - ErrorKind::TooFewValues => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let actual_num_values = self.get_context(ContextKind::ActualNumValues); - let min_values = self.get_context(ContextKind::MinValues); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::Number(actual_num_values)), - Some(ContextValue::Number(min_values)), - ) = (invalid_arg, actual_num_values, min_values) - { - let were_provided = Error::singular_or_plural(*actual_num_values as usize); - c.none("The argument '"); - c.warning(invalid_arg); - c.none("' requires at least "); - c.warning(min_values.to_string()); - c.none(" values but only "); - c.warning(actual_num_values.to_string()); - c.none(were_provided); - true - } else { - false - } - } - ErrorKind::ValueValidation => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let invalid_value = self.get_context(ContextKind::InvalidValue); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::String(invalid_value)), - ) = (invalid_arg, invalid_value) - { - c.none("Invalid value "); - c.warning(quote(invalid_value)); - c.none(" for '"); - c.warning(invalid_arg); - if let Some(source) = self.inner.source.as_deref() { - c.none("': "); - c.none(source.to_string()); - } else { - c.none("'"); - } - true - } else { - false - } - } - ErrorKind::WrongNumberOfValues => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - let actual_num_values = self.get_context(ContextKind::ActualNumValues); - let num_values = self.get_context(ContextKind::ExpectedNumValues); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::Number(actual_num_values)), - Some(ContextValue::Number(num_values)), - ) = (invalid_arg, actual_num_values, num_values) - { - let were_provided = Error::singular_or_plural(*actual_num_values as usize); - c.none("The argument '"); - c.warning(invalid_arg); - c.none("' requires "); - c.warning(num_values.to_string()); - c.none(" values, but "); - c.warning(actual_num_values.to_string()); - c.none(were_provided); - true - } else { - false - } - } - ErrorKind::UnexpectedMultipleUsage => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - c.none("The argument '"); - c.warning(invalid_arg.to_string()); - c.none("' was provided more than once, but cannot be used multiple times"); - true - } else { - false - } - } - ErrorKind::UnknownArgument => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - c.none("Found argument '"); - c.warning(invalid_arg.to_string()); - c.none("' which wasn't expected, or isn't valid in this context"); - - let valid_sub = self.get_context(ContextKind::SuggestedSubcommand); - let valid_arg = self.get_context(ContextKind::SuggestedArg); - match (valid_sub, valid_arg) { - ( - Some(ContextValue::String(valid_sub)), - Some(ContextValue::String(valid_arg)), - ) => { - c.none("\n\n\tDid you mean "); - c.none("to put '"); - c.good(valid_arg); - c.none("' after the subcommand '"); - c.good(valid_sub); - c.none("'?"); - } - (None, Some(ContextValue::String(valid_arg))) => { - c.none("\n\n\tDid you mean '"); - c.good(valid_arg); - c.none("'?"); - } - (_, _) => {} - } - - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - if invalid_arg.starts_with('-') { - c.none(format!( - "\n\n\tIf you tried to supply `{}` as a value rather than a flag, use `-- {}`", - invalid_arg, invalid_arg - )); - } - - let trailing_arg = self.get_context(ContextKind::TrailingArg); - if trailing_arg == Some(&ContextValue::Bool(true)) { - c.none(format!( - "\n\n\tIf you tried to supply `{}` as a subcommand, remove the '--' before it.", - invalid_arg - )); - } - } - true - } else { - false - } - } - ErrorKind::ArgumentNotFound => { - let invalid_arg = self.get_context(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - c.none("The argument '"); - c.warning(invalid_arg.to_string()); - c.none("' wasn't found"); - true - } else { - false - } - } - ErrorKind::DisplayHelp - | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand - | ErrorKind::DisplayVersion - | ErrorKind::Io - | ErrorKind::Format => false, - } - } - - /// Returns the singular or plural form on the verb to be based on the argument's value. - fn singular_or_plural(n: usize) -> &'static str { - if n > 1 { - " were provided" - } else { - " was provided" - } - } -} - -impl From<io::Error> for Error { - fn from(e: io::Error) -> Self { - Error::raw(ErrorKind::Io, e) - } -} - -impl From<fmt::Error> for Error { - fn from(e: fmt::Error) -> Self { - Error::raw(ErrorKind::Format, e) - } -} - -impl error::Error for Error { - #[allow(trivial_casts)] - fn source(&self) -> Option<&(dyn error::Error + 'static)> { - self.inner.source.as_ref().map(|e| e.as_ref() as _) - } -} - -impl Display for Error { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - // Assuming `self.message` already has a trailing newline, from `try_help` or similar - write!(f, "{}", self.formatted())?; - if let Some(backtrace) = self.inner.backtrace.as_ref() { - writeln!(f)?; - writeln!(f, "Backtrace:")?; - writeln!(f, "{}", backtrace)?; - } - Ok(()) - } -} - -fn start_error(c: &mut Colorizer) { - c.error("error:"); - c.none(" "); -} - -fn put_usage(c: &mut Colorizer, usage: impl Into<String>) { - c.none("\n\n"); - c.none(usage); -} - -fn get_help_flag(cmd: &Command) -> Option<&'static str> { - if !cmd.is_disable_help_flag_set() { - Some("--help") - } else if cmd.has_subcommands() && !cmd.is_disable_help_subcommand_set() { - Some("help") - } else { - None - } -} - -fn try_help(c: &mut Colorizer, help: Option<&str>) { - if let Some(help) = help { - c.none("\n\nFor more information try "); - c.good(help); - c.none("\n"); - } else { - c.none("\n"); - } -} - -fn quote(s: impl AsRef<str>) -> String { - let s = s.as_ref(); - format!("{:?}", s) -} - -fn escape(s: impl AsRef<str>) -> String { - let s = s.as_ref(); - if s.contains(char::is_whitespace) { - quote(s) - } else { - s.to_owned() - } -} - -#[derive(Clone, Debug)] -pub(crate) enum Message { - Raw(String), - Formatted(Colorizer), -} - -impl Message { - fn format(&mut self, cmd: &Command, usage: String) { - match self { - Message::Raw(s) => { - let mut c = Colorizer::new(Stream::Stderr, cmd.get_color()); - - let mut message = String::new(); - std::mem::swap(s, &mut message); - start_error(&mut c); - c.none(message); - put_usage(&mut c, usage); - try_help(&mut c, get_help_flag(cmd)); - *self = Self::Formatted(c); - } - Message::Formatted(_) => {} - } - } - - fn formatted(&self) -> Cow<Colorizer> { - match self { - Message::Raw(s) => { - let mut c = Colorizer::new(Stream::Stderr, ColorChoice::Never); - start_error(&mut c); - c.none(s); - Cow::Owned(c) - } - Message::Formatted(c) => Cow::Borrowed(c), - } - } -} - -impl From<String> for Message { - fn from(inner: String) -> Self { - Self::Raw(inner) - } -} - -impl From<Colorizer> for Message { - fn from(inner: Colorizer) -> Self { - Self::Formatted(inner) - } -} - -#[cfg(feature = "debug")] -#[derive(Debug)] -struct Backtrace(backtrace::Backtrace); - -#[cfg(feature = "debug")] -impl Backtrace { - fn new() -> Option<Self> { - Some(Self(backtrace::Backtrace::new())) - } -} - -#[cfg(feature = "debug")] -impl Display for Backtrace { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - // `backtrace::Backtrace` uses `Debug` instead of `Display` - write!(f, "{:?}", self.0) - } -} - -#[cfg(not(feature = "debug"))] -#[derive(Debug)] -struct Backtrace; - -#[cfg(not(feature = "debug"))] -impl Backtrace { - fn new() -> Option<Self> { - None - } -} - -#[cfg(not(feature = "debug"))] -impl Display for Backtrace { - fn fmt(&self, _: &mut Formatter) -> fmt::Result { - Ok(()) - } -} - -#[cfg(test)] -mod tests { - /// Check `clap::Error` impls Send and Sync. - mod clap_error_impl_send_sync { - use crate::Error; - trait Foo: std::error::Error + Send + Sync + 'static {} - impl Foo for Error {} - } -} diff --git a/vendor/clap/src/lib.rs b/vendor/clap/src/lib.rs deleted file mode 100644 index d9a97715f..000000000 --- a/vendor/clap/src/lib.rs +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright â“’ 2015-2016 Kevin B. Knapp and [`clap-rs` contributors](https://github.com/clap-rs/clap/graphs/contributors). -// Licensed under the MIT license -// (see LICENSE or <http://opensource.org/licenses/MIT>) All files in the project carrying such -// notice may not be copied, modified, or distributed except according to those terms. - -#![cfg_attr(docsrs, feature(doc_auto_cfg))] -#![doc(html_logo_url = "https://raw.githubusercontent.com/clap-rs/clap/master/assets/clap.png")] -#![cfg_attr(feature = "derive", doc = include_str!("../README.md"))] -//! <https://github.com/clap-rs/clap> -#![warn( - missing_docs, - missing_debug_implementations, - missing_copy_implementations, - trivial_casts, - unused_allocation, - trivial_numeric_casts, - clippy::single_char_pattern -)] -#![forbid(unsafe_code)] -// HACK https://github.com/rust-lang/rust-clippy/issues/7290 -#![allow(clippy::single_component_path_imports)] -#![allow(clippy::branches_sharing_code)] -// Doesn't allow for debug statements, etc to be unique -#![allow(clippy::if_same_then_else)] - -#[cfg(not(feature = "std"))] -compile_error!("`std` feature is currently required to build `clap`"); - -pub use crate::builder::ArgAction; -pub use crate::builder::Command; -pub use crate::builder::{Arg, ArgGroup}; -pub use crate::error::Error; -pub use crate::parser::ArgMatches; -#[cfg(feature = "color")] -pub use crate::util::color::ColorChoice; -#[cfg(not(feature = "color"))] -#[allow(unused_imports)] -pub(crate) use crate::util::color::ColorChoice; - -pub use crate::derive::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum}; - -#[allow(deprecated)] -pub use crate::builder::App; -pub use crate::builder::{AppFlags, AppSettings, ArgFlags, ArgSettings, PossibleValue, ValueHint}; -pub use crate::error::{ErrorKind, Result}; -#[allow(deprecated)] -pub use crate::parser::{Indices, OsValues, ValueSource, Values}; - -#[cfg(feature = "yaml")] -#[doc(hidden)] -#[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" - ) -)] -#[doc(hidden)] -pub use yaml_rust::YamlLoader; - -#[cfg(feature = "derive")] -#[doc(hidden)] -pub use clap_derive::{self, *}; - -/// Deprecated, replaced with [`CommandFactory`] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `CommandFactory`") -)] -pub use CommandFactory as IntoApp; -/// Deprecated, replaced with [`Parser`] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Parser`") -)] -#[doc(hidden)] -pub use Parser as StructOpt; -/// Deprecated, replaced with [`ValueEnum`] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.2.0", note = "Replaced with `ValueEnum`") -)] -pub use ValueEnum as ArgEnum; - -#[cfg(any(feature = "derive", feature = "cargo"))] -#[doc(hidden)] -pub use once_cell; - -#[macro_use] -#[allow(missing_docs)] -mod macros; - -mod derive; - -#[cfg(feature = "regex")] -pub use crate::builder::RegexRef; - -pub mod builder; -pub mod error; -pub mod parser; - -mod mkeymap; -mod output; -mod util; - -const INTERNAL_ERROR_MSG: &str = "Fatal internal error. Please consider filing a bug \ - report at https://github.com/clap-rs/clap/issues"; -const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point"; - -/// Deprecated, replaced with [`Command::new`], unless you were looking for [Subcommand] -#[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `Command::new` unless you intended the `Subcommand` trait" - ) -)] -#[doc(hidden)] -#[derive(Debug, Copy, Clone)] -pub struct SubCommand {} - -#[allow(deprecated)] -impl SubCommand { - /// Deprecated, replaced with [`Command::new`]. - /// Did you mean Subcommand (lower-case c)? - #[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `Command::new`") - )] - #[doc(hidden)] - pub fn with_name<'help>(name: &str) -> App<'help> { - Command::new(name) - } - - /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? - #[cfg(feature = "yaml")] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" - ) - )] - #[doc(hidden)] - pub fn from_yaml(yaml: &yaml_rust::Yaml) -> App { - #![allow(deprecated)] - Command::from_yaml(yaml) - } -} diff --git a/vendor/clap/src/macros.rs b/vendor/clap/src/macros.rs deleted file mode 100644 index 0b671a37a..000000000 --- a/vendor/clap/src/macros.rs +++ /dev/null @@ -1,1062 +0,0 @@ -/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? -#[cfg(feature = "yaml")] -#[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" - ) -)] -#[doc(hidden)] -#[macro_export] -macro_rules! load_yaml { - ($yaml:expr) => { - &$crate::YamlLoader::load_from_str(include_str!($yaml)).expect("failed to load YAML file") - [0] - }; -} - -/// Deprecated, replaced with [`ArgMatches::value_of_t`][crate::ArgMatches::value_of_t] -#[macro_export] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `ArgMatches::value_of_t`") -)] -#[doc(hidden)] -macro_rules! value_t { - ($m:ident, $v:expr, $t:ty) => { - $crate::value_t!($m.value_of($v), $t) - }; - ($m:ident.value_of($v:expr), $t:ty) => { - $m.value_of_t::<$t>($v) - }; -} - -/// Deprecated, replaced with [`ArgMatches::value_of_t_or_exit`][crate::ArgMatches::value_of_t_or_exit] -#[macro_export] -#[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `ArgMatches::value_of_t_or_exit`" - ) -)] -#[doc(hidden)] -macro_rules! value_t_or_exit { - ($m:ident, $v:expr, $t:ty) => { - value_t_or_exit!($m.value_of($v), $t) - }; - ($m:ident.value_of($v:expr), $t:ty) => { - $m.value_of_t_or_exit::<$t>($v) - }; -} - -/// Deprecated, replaced with [`ArgMatches::values_of_t`][crate::ArgMatches::value_of_t] -#[macro_export] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `ArgMatches::values_of_t`") -)] -#[doc(hidden)] -macro_rules! values_t { - ($m:ident, $v:expr, $t:ty) => { - values_t!($m.values_of($v), $t) - }; - ($m:ident.values_of($v:expr), $t:ty) => { - $m.values_of_t::<$t>($v) - }; -} - -/// Deprecated, replaced with [`ArgMatches::values_of_t_or_exit`][crate::ArgMatches::value_of_t_or_exit] -#[macro_export] -#[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `ArgMatches::values_of_t_or_exit`" - ) -)] -#[doc(hidden)] -macro_rules! values_t_or_exit { - ($m:ident, $v:expr, $t:ty) => { - values_t_or_exit!($m.values_of($v), $t) - }; - ($m:ident.values_of($v:expr), $t:ty) => { - $m.values_of_t_or_exit::<$t>($v) - }; -} - -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `ArgEnum`") -)] -#[doc(hidden)] -#[macro_export] -macro_rules! _clap_count_exprs { - () => { 0 }; - ($e:expr) => { 1 }; - ($e:expr, $($es:expr),+) => { 1 + $crate::_clap_count_exprs!($($es),*) }; -} - -/// Deprecated, replaced with [`ArgEnum`][crate::ArgEnum] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.0.0", note = "Replaced with `ArgEnum`") -)] -#[doc(hidden)] -#[macro_export] -macro_rules! arg_enum { - (@as_item $($i:item)*) => ($($i)*); - (@impls ( $($tts:tt)* ) -> ($e:ident, $($v:ident),+)) => { - $crate::arg_enum!(@as_item - $($tts)* - - impl ::std::str::FromStr for $e { - type Err = String; - - fn from_str(s: &str) -> ::std::result::Result<Self,Self::Err> { - #[allow(deprecated, unused_imports)] - use ::std::ascii::AsciiExt; - match s { - $(stringify!($v) | - _ if s.eq_ignore_ascii_case(stringify!($v)) => Ok($e::$v)),+, - _ => Err({ - let v = vec![ - $(stringify!($v),)+ - ]; - format!("valid values: {}", - v.join(", ")) - }), - } - } - } - impl ::std::fmt::Display for $e { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - match *self { - $($e::$v => write!(f, stringify!($v)),)+ - } - } - } - impl $e { - #[allow(dead_code)] - pub fn variants() -> [&'static str; $crate::_clap_count_exprs!($(stringify!($v)),+)] { - [ - $(stringify!($v),)+ - ] - } - }); - }; - ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - $crate::arg_enum!(@impls - ($(#[$($m),+])+ - pub enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - $crate::arg_enum!(@impls - ($(#[$($m),+])+ - pub enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - $crate::arg_enum!(@impls - ($(#[$($m),+])+ - enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - $crate::arg_enum!(@impls - ($(#[$($m),+])+ - enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - (pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - $crate::arg_enum!(@impls - (pub enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - (pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - $crate::arg_enum!(@impls - (pub enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - (enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - $crate::arg_enum!(@impls - (enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - (enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - $crate::arg_enum!(@impls - (enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; -} - -/// Allows you to pull the version from your Cargo.toml at compile time as -/// `MAJOR.MINOR.PATCH_PKGVERSION_PRE` -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::Command; -/// # fn main() { -/// let m = Command::new("cmd") -/// .version(crate_version!()) -/// .get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! crate_version { - () => { - env!("CARGO_PKG_VERSION") - }; -} - -/// Allows you to pull the authors for the command from your Cargo.toml at -/// compile time in the form: -/// `"author1 lastname <author1@example.com>:author2 lastname <author2@example.com>"` -/// -/// You can replace the colons with a custom separator by supplying a -/// replacement string, so, for example, -/// `crate_authors!(",\n")` would become -/// `"author1 lastname <author1@example.com>,\nauthor2 lastname <author2@example.com>,\nauthor3 lastname <author3@example.com>"` -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::Command; -/// # fn main() { -/// let m = Command::new("cmd") -/// .author(crate_authors!("\n")) -/// .get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! crate_authors { - ($sep:expr) => {{ - static CACHED: clap::once_cell::sync::Lazy<String> = - clap::once_cell::sync::Lazy::new(|| env!("CARGO_PKG_AUTHORS").replace(':', $sep)); - - let s: &'static str = &*CACHED; - s - }}; - () => { - env!("CARGO_PKG_AUTHORS") - }; -} - -/// Allows you to pull the description from your Cargo.toml at compile time. -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::Command; -/// # fn main() { -/// let m = Command::new("cmd") -/// .about(crate_description!()) -/// .get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! crate_description { - () => { - env!("CARGO_PKG_DESCRIPTION") - }; -} - -/// Allows you to pull the name from your Cargo.toml at compile time. -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::Command; -/// # fn main() { -/// let m = Command::new(crate_name!()) -/// .get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! crate_name { - () => { - env!("CARGO_PKG_NAME") - }; -} - -/// Allows you to build the `Command` instance from your Cargo.toml at compile time. -/// -/// **NOTE:** Changing the values in your `Cargo.toml` does not trigger a re-build automatically, -/// and therefore won't change the generated output until you recompile. -/// -/// In some cases you can "trick" the compiler into triggering a rebuild when your -/// `Cargo.toml` is changed by including this in your `src/main.rs` file -/// `include_str!("../Cargo.toml");` -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # fn main() { -/// let m = command!().get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! command { - () => {{ - $crate::command!($crate::crate_name!()) - }}; - ($name:expr) => {{ - let mut cmd = $crate::Command::new($name).version($crate::crate_version!()); - - let author = $crate::crate_authors!(); - if !author.is_empty() { - cmd = cmd.author(author) - } - - let about = $crate::crate_description!(); - if !about.is_empty() { - cmd = cmd.about(about) - } - - cmd - }}; -} - -/// Requires `cargo` feature flag to be enabled. -#[cfg(not(feature = "cargo"))] -#[macro_export] -macro_rules! command { - () => {{ - compile_error!("`cargo` feature flag is required"); - }}; - ($name:expr) => {{ - compile_error!("`cargo` feature flag is required"); - }}; -} - -/// Deprecated, replaced with [`clap::command!`][crate::command] -#[cfg(feature = "cargo")] -#[cfg_attr( - feature = "deprecated", - deprecated(since = "3.1.0", note = "Replaced with `clap::command!") -)] -#[macro_export] -macro_rules! app_from_crate { - () => {{ - let mut cmd = $crate::Command::new($crate::crate_name!()).version($crate::crate_version!()); - - let author = $crate::crate_authors!(", "); - if !author.is_empty() { - cmd = cmd.author(author) - } - - let about = $crate::crate_description!(); - if !about.is_empty() { - cmd = cmd.about(about) - } - - cmd - }}; - ($sep:expr) => {{ - let mut cmd = $crate::Command::new($crate::crate_name!()).version($crate::crate_version!()); - - let author = $crate::crate_authors!($sep); - if !author.is_empty() { - cmd = cmd.author(author) - } - - let about = $crate::crate_description!(); - if !about.is_empty() { - cmd = cmd.about(about) - } - - cmd - }}; -} - -#[doc(hidden)] -#[macro_export] -macro_rules! arg_impl { - ( @string $val:ident ) => { - stringify!($val) - }; - ( @string $val:literal ) => {{ - let ident_or_string_literal: &str = $val; - ident_or_string_literal - }}; - ( @string $val:tt ) => { - ::std::compile_error!("Only identifiers or string literals supported"); - }; - ( @string ) => { - None - }; - - ( @char $val:ident ) => {{ - let ident_or_char_literal = stringify!($val); - debug_assert_eq!( - ident_or_char_literal.len(), - 1, - "Single-letter identifier expected, got {}", - ident_or_char_literal - ); - ident_or_char_literal.chars().next().unwrap() - }}; - ( @char $val:literal ) => {{ - let ident_or_char_literal: char = $val; - ident_or_char_literal - }}; - ( @char ) => {{ - None - }}; - - ( - @arg - ($arg:expr) - --$long:ident - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); - } - - let mut arg = $arg; - let long = $crate::arg_impl! { @string $long }; - if arg.get_id().is_empty() { - arg = arg.id(long); - } - arg.long(long) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - --$long:literal - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); - } - - let mut arg = $arg; - let long = $crate::arg_impl! { @string $long }; - if arg.get_id().is_empty() { - arg = arg.id(long); - } - arg.long(long) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - -$short:ident - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - debug_assert_eq!($arg.get_long(), None, "Short flags should precede long flags"); - debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); - } - - $arg.short($crate::arg_impl! { @char $short }) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - -$short:literal - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - debug_assert_eq!($arg.get_long(), None, "Short flags should precede long flags"); - debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); - } - - $arg.short($crate::arg_impl! { @char $short }) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - <$value_name:ident> - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); - } - debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); - - let mut arg = $arg; - - arg = arg.required(true); - arg = arg.takes_value(true); - - let value_name = $crate::arg_impl! { @string $value_name }; - if arg.get_id().is_empty() { - arg = arg.id(value_name); - } - arg.value_name(value_name) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - <$value_name:literal> - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); - } - debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); - - let mut arg = $arg; - - arg = arg.required(true); - arg = arg.takes_value(true); - - let value_name = $crate::arg_impl! { @string $value_name }; - if arg.get_id().is_empty() { - arg = arg.id(value_name); - } - arg.value_name(value_name) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - [$value_name:ident] - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); - } - debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); - - let mut arg = $arg; - - if arg.get_long().is_none() && arg.get_short().is_none() { - arg = arg.required(false); - } else { - arg = arg.min_values(0).max_values(1); - } - arg = arg.takes_value(true); - - let value_name = $crate::arg_impl! { @string $value_name }; - if arg.get_id().is_empty() { - arg = arg.id(value_name); - } - arg.value_name(value_name) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - [$value_name:literal] - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({ - #[allow(deprecated)] - { - debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); - } - debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); - - let mut arg = $arg; - - if arg.get_long().is_none() && arg.get_short().is_none() { - arg = arg.required(false); - } else { - arg = arg.min_values(0).max_values(1); - } - arg = arg.takes_value(true); - - let value_name = $crate::arg_impl! { @string $value_name }; - if arg.get_id().is_empty() { - arg = arg.id(value_name); - } - arg.value_name(value_name) - }) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - ... - $($tail:tt)* - ) => { - $crate::arg_impl! { - @arg - ({#[allow(deprecated)]{ - $arg.multiple_occurrences(true) - }}) - $($tail)* - } - }; - ( - @arg - ($arg:expr) - $help:literal - ) => { - $arg.help($help) - }; - ( - @arg - ($arg:expr) - ) => { - $arg - }; -} - -/// Create an [`Arg`] from a usage string. -/// -/// Allows creation of basic settings for the [`Arg`]. -/// -/// **NOTE**: Not all settings may be set using the usage string method. Some properties are -/// only available via the builder pattern. -/// -/// # Syntax -/// -/// Usage strings typically following the form: -/// -/// ```notrust -/// [explicit name] [short] [long] [value names] [...] [help string] -/// ``` -/// -/// ### Explicit Name -/// -/// The name may be either a bare-word or a string, followed by a `:`, like `name:` or -/// `"name":`. -/// -/// *Note:* This is an optional field, if it's omitted the argument will use one of the additional -/// fields as the name using the following priority order: -/// -/// 1. Explicit Name -/// 2. Long -/// 3. Value Name -/// -/// See [`Arg::name`][crate::Arg::name]. -/// -/// ### Short -/// -/// A short flag is a `-` followed by either a bare-character or quoted character, like `-f` or -/// `-'f'`. -/// -/// See [`Arg::short`][crate::Arg::short]. -/// -/// ### Long -/// -/// A long flag is a `--` followed by either a bare-word or a string, like `--foo` or -/// `--"foo"`. -/// -/// See [`Arg::long`][crate::Arg::long]. -/// -/// ### Values (Value Notation) -/// -/// This is set by placing bare-word between: -/// - `[]` like `[FOO]` -/// - Positional argument: optional -/// - Named argument: optional value -/// - `<>` like `<FOO>`: required -/// -/// See [`Arg::value_name`][crate::Arg::value_name]. -/// -/// ### `...` -/// -/// `...` (three consecutive dots/periods) specifies that this argument may occur multiple -/// times (not to be confused with multiple values per occurrence). -/// -/// See [`Arg::multiple_occurrences`][crate::Arg::multiple_occurrences]. -/// -/// ### Help String -/// -/// The help string is denoted between a pair of double quotes `""` and may contain any -/// characters. -/// -/// # Examples -/// -/// ```rust -/// # use clap::{Command, Arg, arg}; -/// Command::new("prog") -/// .args(&[ -/// arg!(--config <FILE> "a required file for the configuration and no short"), -/// arg!(-d --debug ... "turns on debugging information and allows multiples"), -/// arg!([input] "an optional input file to use") -/// ]) -/// # ; -/// ``` -/// [`Arg`]: ./struct.Arg.html -#[macro_export] -macro_rules! arg { - ( $name:ident: $($tail:tt)+ ) => { - $crate::arg_impl! { - @arg ($crate::Arg::new($crate::arg_impl! { @string $name })) $($tail)+ - } - }; - ( $($tail:tt)+ ) => {{ - let arg = $crate::arg_impl! { - @arg ($crate::Arg::default()) $($tail)+ - }; - debug_assert!(!arg.get_id().is_empty(), "Without a value or long flag, the `name:` prefix is required"); - arg - }}; -} - -/// Deprecated, replaced with [`clap::Parser`][crate::Parser] and [`clap::arg!`][crate::arg] (Issue clap-rs/clap#2835) -#[cfg_attr( - feature = "deprecated", - deprecated( - since = "3.0.0", - note = "Replaced with `clap::Parser` for a declarative API (Issue clap-rs/clap#2835)" - ) -)] -#[doc(hidden)] -#[macro_export] -macro_rules! clap_app { - (@app ($builder:expr)) => { $builder }; - (@app ($builder:expr) (@arg ($name:expr): $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($builder.arg( - $crate::clap_app!{ @arg ($crate::Arg::new($name)) (-) $($tail)* })) - $($tt)* - } - }; - (@app ($builder:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($builder.arg( - $crate::clap_app!{ @arg ($crate::Arg::new(stringify!($name))) (-) $($tail)* })) - $($tt)* - } - }; - (@app ($builder:expr) (@setting $setting:ident) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($builder.setting($crate::AppSettings::$setting)) - $($tt)* - } - }; -// Treat the application builder as an argument to set its attributes - (@app ($builder:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app ($crate::clap_app!{ @arg ($builder) $($attr)* }) $($tt)* } - }; - (@app ($builder:expr) (@group $name:ident => $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::new(stringify!($name))) $($tail)* }) - $($tt)* - } - }; - (@app ($builder:expr) (@group $name:ident !$ident:ident => $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::new(stringify!($name)).$ident(false)) $($tail)* }) - $($tt)* - } - }; - (@app ($builder:expr) (@group $name:ident +$ident:ident => $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::new(stringify!($name)).$ident(true)) $($tail)* }) - $($tt)* - } - }; -// Handle subcommand creation - (@app ($builder:expr) (@subcommand $name:ident => $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @app - ($builder.subcommand( - $crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)* } - )) - $($tt)* - } - }; -// Yaml like function calls - used for setting various meta directly against the app - (@app ($builder:expr) ($ident:ident: $($v:expr),*) $($tt:tt)*) => { -// $crate::clap_app!{ @app ($builder.$ident($($v),*)) $($tt)* } - $crate::clap_app!{ @app - ($builder.$ident($($v),*)) - $($tt)* - } - }; - -// Add members to group and continue argument handling with the parent builder - (@group ($builder:expr, $group:expr)) => { $builder.group($group) }; - // Treat the group builder as an argument to set its attributes - (@group ($builder:expr, $group:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @group ($builder, $crate::clap_app!{ @arg ($group) (-) $($attr)* }) $($tt)* } - }; - (@group ($builder:expr, $group:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => { - $crate::clap_app!{ @group - ($crate::clap_app!{ @app ($builder) (@arg $name: $($tail)*) }, - $group.arg(stringify!($name))) - $($tt)* - } - }; - -// No more tokens to munch - (@arg ($arg:expr) $modes:tt) => { $arg }; -// Shorthand tokens influenced by the usage_string - (@arg ($arg:expr) $modes:tt --($long:expr) $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.long($long)) $modes $($tail)* } - }; - (@arg ($arg:expr) $modes:tt --$long:ident $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.long(stringify!($long))) $modes $($tail)* } - }; - (@arg ($arg:expr) $modes:tt -$short:ident $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.short(stringify!($short).chars().next().unwrap())) $modes $($tail)* } - }; - (@arg ($arg:expr) (-) <$var:ident> $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value +required $($tail)* } - }; - (@arg ($arg:expr) (+) <$var:ident> $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } - }; - (@arg ($arg:expr) (-) [$var:ident] $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value $($tail)* } - }; - (@arg ($arg:expr) (+) [$var:ident] $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } - }; - (@arg ($arg:expr) $modes:tt ... $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg) $modes +multiple +takes_value $($tail)* } - }; -// Shorthand magic - (@arg ($arg:expr) $modes:tt #{$n:expr, $m:expr} $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg) $modes min_values($n) max_values($m) $($tail)* } - }; - (@arg ($arg:expr) $modes:tt * $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg) $modes +required $($tail)* } - }; -// !foo -> .foo(false) - (@arg ($arg:expr) $modes:tt !$ident:ident $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.$ident(false)) $modes $($tail)* } - }; -// +foo -> .foo(true) - (@arg ($arg:expr) $modes:tt +$ident:ident $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.$ident(true)) $modes $($tail)* } - }; -// Validator - (@arg ($arg:expr) $modes:tt {$fn_:expr} $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.validator($fn_)) $modes $($tail)* } - }; - (@as_expr $expr:expr) => { $expr }; -// Help - (@arg ($arg:expr) $modes:tt $desc:tt) => { $arg.help($crate::clap_app!{ @as_expr $desc }) }; -// Handle functions that need to be called multiple times for each argument - (@arg ($arg:expr) $modes:tt $ident:ident[$($target:ident)*] $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg $( .$ident(stringify!($target)) )*) $modes $($tail)* } - }; -// Inherit builder's functions, e.g. `index(2)`, `requires_if("val", "arg")` - (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr),*) $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } - }; -// Inherit builder's functions with trailing comma, e.g. `index(2,)`, `requires_if("val", "arg",)` - (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr,)*) $($tail:tt)*) => { - $crate::clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } - }; - -// Build a subcommand outside of an app. - (@subcommand $name:ident => $($tail:tt)*) => { - $crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)* } - }; -// Start the magic - (($name:expr) => $($tail:tt)*) => {{ - $crate::clap_app!{ @app ($crate::Command::new($name)) $($tail)*} - }}; - - ($name:ident => $($tail:tt)*) => {{ - $crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)*} - }}; -} - -macro_rules! impl_settings { - ($settings:ident, $flags:ident, - $( - $(#[$inner:ident $($args:tt)*])* - $setting:ident => $flag:path - ),+ - ) => { - impl $flags { - #[allow(dead_code)] - pub(crate) fn empty() -> Self { - $flags(Flags::empty()) - } - - #[allow(dead_code)] - pub(crate) fn insert(&mut self, rhs: Self) { - self.0.insert(rhs.0); - } - - #[allow(dead_code)] - pub(crate) fn remove(&mut self, rhs: Self) { - self.0.remove(rhs.0); - } - - #[allow(dead_code)] - pub(crate) fn set(&mut self, s: $settings) { - #[allow(deprecated)] // some Settings might be deprecated - match s { - $( - $(#[$inner $($args)*])* - $settings::$setting => self.0.insert($flag), - )* - } - } - - #[allow(dead_code)] - pub(crate) fn unset(&mut self, s: $settings) { - #[allow(deprecated)] // some Settings might be deprecated - match s { - $( - $(#[$inner $($args)*])* - $settings::$setting => self.0.remove($flag), - )* - } - } - - #[allow(dead_code)] - pub(crate) fn is_set(&self, s: $settings) -> bool { - #[allow(deprecated)] // some Settings might be deprecated - match s { - $( - $(#[$inner $($args)*])* - $settings::$setting => self.0.contains($flag), - )* - } - } - } - - impl BitOr for $flags { - type Output = Self; - - fn bitor(mut self, rhs: Self) -> Self::Output { - self.0.insert(rhs.0); - self - } - } - - impl From<$settings> for $flags { - fn from(setting: $settings) -> Self { - let mut flags = $flags::empty(); - flags.set(setting); - flags - } - } - - impl BitOr<$settings> for $flags { - type Output = Self; - - fn bitor(mut self, rhs: $settings) -> Self::Output { - self.set(rhs); - self - } - } - - impl BitOr for $settings { - type Output = $flags; - - fn bitor(self, rhs: Self) -> Self::Output { - let mut flags = $flags::empty(); - flags.set(self); - flags.set(rhs); - flags - } - } - } -} - -// Convenience for writing to stderr thanks to https://github.com/BurntSushi -macro_rules! wlnerr { - ($($arg:tt)*) => ({ - use std::io::{Write, stderr}; - writeln!(&mut stderr(), $($arg)*).ok(); - }) -} - -#[cfg(feature = "debug")] -macro_rules! debug { - ($($arg:tt)*) => ({ - let prefix = format!("[{:>w$}] \t", module_path!(), w = 28); - let body = format!($($arg)*); - let mut color = $crate::output::fmt::Colorizer::new($crate::output::fmt::Stream::Stderr, $crate::ColorChoice::Auto); - color.hint(prefix); - color.hint(body); - color.none("\n"); - let _ = color.print(); - }) -} - -#[cfg(not(feature = "debug"))] -macro_rules! debug { - ($($arg:tt)*) => {}; -} diff --git a/vendor/clap/src/parser/error.rs b/vendor/clap/src/parser/error.rs deleted file mode 100644 index bdafa9ae5..000000000 --- a/vendor/clap/src/parser/error.rs +++ /dev/null @@ -1,56 +0,0 @@ -use crate::util::Id; - -/// Violation of [`ArgMatches`][crate::ArgMatches] assumptions -#[derive(Clone, Debug)] -#[allow(missing_copy_implementations)] // We might add non-Copy types in the future -#[non_exhaustive] -pub enum MatchesError { - /// Failed to downcast `AnyValue` to the specified type - #[non_exhaustive] - Downcast { - /// Type for value stored in [`ArgMatches`][crate::ArgMatches] - actual: super::AnyValueId, - /// The target type to downcast to - expected: super::AnyValueId, - }, - /// Argument not defined in [`Command`][crate::Command] - #[non_exhaustive] - UnknownArgument { - // Missing `id` but blocked on a public id type which will hopefully come with `unstable-v4` - }, -} - -impl MatchesError { - #[track_caller] - pub(crate) fn unwrap<T>(id: &Id, r: Result<T, MatchesError>) -> T { - let err = match r { - Ok(t) => { - return t; - } - Err(err) => err, - }; - panic!( - "Mismatch between definition and access of `{:?}`. {}", - id, err - ) - } -} - -impl std::error::Error for MatchesError {} - -impl std::fmt::Display for MatchesError { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - Self::Downcast { actual, expected } => { - writeln!( - f, - "Could not downcast to {:?}, need to downcast to {:?}", - expected, actual - ) - } - Self::UnknownArgument {} => { - writeln!(f, "Unknown argument or group id. Make sure you are using the argument id and not the short or long flags") - } - } - } -} |