From c173e6b6a768f8b4a32dff7032a9e694de385cd2 Mon Sep 17 00:00:00 2001 From: adamnemecek Date: Mon, 30 Jun 2025 20:57:36 -0700 Subject: [PATCH 1/7] ran `cargo clippy --fix -- -A clippy::all -W clippy::use_self` --- clap_builder/src/builder/arg.rs | 10 ++-- clap_builder/src/builder/arg_group.rs | 6 +- clap_builder/src/builder/command.rs | 30 +++++----- clap_builder/src/builder/os_str.rs | 8 +-- clap_builder/src/builder/possible_value.rs | 2 +- clap_builder/src/builder/resettable.rs | 18 +++--- clap_builder/src/builder/str.rs | 8 +-- clap_builder/src/builder/styled_str.rs | 8 +-- clap_builder/src/builder/value_hint.rs | 26 ++++---- clap_builder/src/builder/value_parser.rs | 60 +++++++++---------- clap_builder/src/derive.rs | 12 ++-- clap_builder/src/error/mod.rs | 12 ++-- clap_builder/src/mkeymap.rs | 12 ++-- clap_builder/src/output/fmt.rs | 2 +- clap_builder/src/parser/arg_matcher.rs | 4 +- clap_builder/src/parser/error.rs | 2 +- .../src/parser/matches/arg_matches.rs | 10 ++-- .../src/parser/matches/matched_arg.rs | 6 +- clap_builder/src/util/graph.rs | 4 +- clap_builder/src/util/id.rs | 4 +- clap_complete/src/aot/shells/shell.rs | 48 +++++++-------- clap_derive/src/attr.rs | 2 +- clap_derive/src/item.rs | 20 +++---- clap_derive/src/utils/spanned.rs | 8 +-- clap_lex/src/ext.rs | 6 +- 25 files changed, 164 insertions(+), 164 deletions(-) diff --git a/clap_builder/src/builder/arg.rs b/clap_builder/src/builder/arg.rs index 60ea2cc3296..1e972dd4d37 100644 --- a/clap_builder/src/builder/arg.rs +++ b/clap_builder/src/builder/arg.rs @@ -120,7 +120,7 @@ impl Arg { /// ``` /// [`Arg::action(ArgAction::Set)`]: Arg::action() pub fn new(id: impl Into) -> Self { - Arg::default().id(id) + Self::default().id(id) } /// Set the identifier used for referencing this argument in the clap API. @@ -4678,14 +4678,14 @@ impl Arg { } } -impl From<&'_ Arg> for Arg { - fn from(a: &Arg) -> Self { +impl From<&'_ Self> for Arg { + fn from(a: &Self) -> Self { a.clone() } } impl PartialEq for Arg { - fn eq(&self, other: &Arg) -> bool { + fn eq(&self, other: &Self) -> bool { self.get_id() == other.get_id() } } @@ -4697,7 +4697,7 @@ impl PartialOrd for Arg { } impl Ord for Arg { - fn cmp(&self, other: &Arg) -> Ordering { + fn cmp(&self, other: &Self) -> Ordering { self.get_id().cmp(other.get_id()) } } diff --git a/clap_builder/src/builder/arg_group.rs b/clap_builder/src/builder/arg_group.rs index 2c07ce4be0c..d8bac0f0081 100644 --- a/clap_builder/src/builder/arg_group.rs +++ b/clap_builder/src/builder/arg_group.rs @@ -110,7 +110,7 @@ impl ArgGroup { /// # ; /// ``` pub fn new(id: impl Into) -> Self { - ArgGroup::default().id(id) + Self::default().id(id) } /// Sets the group name. @@ -548,8 +548,8 @@ impl ArgGroup { } } -impl From<&'_ ArgGroup> for ArgGroup { - fn from(g: &ArgGroup) -> Self { +impl From<&'_ Self> for ArgGroup { + fn from(g: &Self) -> Self { g.clone() } } diff --git a/clap_builder/src/builder/command.rs b/clap_builder/src/builder/command.rs index 448f7395fcc..1d3d8478e84 100644 --- a/clap_builder/src/builder/command.rs +++ b/clap_builder/src/builder/command.rs @@ -479,7 +479,7 @@ impl Command { /// ``` #[inline] #[must_use] - pub fn subcommand(self, subcmd: impl Into) -> Self { + pub fn subcommand(self, subcmd: impl Into) -> Self { let subcmd = subcmd.into(); self.subcommand_internal(subcmd) } @@ -536,7 +536,7 @@ impl Command { /// ) /// # ; /// ``` - pub fn defer(mut self, deferred: fn(Command) -> Command) -> Self { + pub fn defer(mut self, deferred: fn(Self) -> Self) -> Self { self.deferred = Some(deferred); self } @@ -3836,13 +3836,13 @@ impl Command { /// Iterate through the set of subcommands, getting a reference to each. #[inline] - pub fn get_subcommands(&self) -> impl Iterator { + pub fn get_subcommands(&self) -> impl Iterator { self.subcommands.iter() } /// Iterate through the set of subcommands, getting a mutable reference to each. #[inline] - pub fn get_subcommands_mut(&mut self) -> impl Iterator { + pub fn get_subcommands_mut(&mut self) -> impl Iterator { self.subcommands.iter_mut() } @@ -3892,7 +3892,7 @@ impl Command { /// /// This does not recurse through subcommands of subcommands. #[inline] - pub fn find_subcommand(&self, name: impl AsRef) -> Option<&Command> { + pub fn find_subcommand(&self, name: impl AsRef) -> Option<&Self> { let name = name.as_ref(); self.get_subcommands().find(|s| s.aliases_to(name)) } @@ -3905,7 +3905,7 @@ impl Command { pub fn find_subcommand_mut( &mut self, name: impl AsRef, - ) -> Option<&mut Command> { + ) -> Option<&mut Self> { let name = name.as_ref(); self.get_subcommands_mut().find(|s| s.aliases_to(name)) } @@ -4754,12 +4754,12 @@ impl Command { let mut help_subcmd = if expand_help_tree { // Slow code path to recursively clone all other subcommand subtrees under help - let help_subcmd = Command::new("help") + let help_subcmd = Self::new("help") .about(help_about) .global_setting(AppSettings::DisableHelpSubcommand) - .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); + .subcommands(self.get_subcommands().map(Self::_copy_subtree_for_help)); - let mut help_help_subcmd = Command::new("help").about(help_about); + let mut help_help_subcmd = Self::new("help").about(help_about); help_help_subcmd.version = None; help_help_subcmd.long_version = None; help_help_subcmd = help_help_subcmd @@ -4768,7 +4768,7 @@ impl Command { help_subcmd.subcommand(help_help_subcmd) } else { - Command::new("help").about(help_about).arg( + Self::new("help").about(help_about).arg( Arg::new("subcommand") .action(ArgAction::Append) .num_args(..) @@ -4791,12 +4791,12 @@ impl Command { } } - fn _copy_subtree_for_help(&self) -> Command { - let mut cmd = Command::new(self.name.clone()) + fn _copy_subtree_for_help(&self) -> Self { + let mut cmd = Self::new(self.name.clone()) .hide(self.is_hide_set()) .global_setting(AppSettings::DisableHelpFlag) .global_setting(AppSettings::DisableVersionFlag) - .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); + .subcommands(self.get_subcommands().map(Self::_copy_subtree_for_help)); if self.get_about().is_some() { cmd = cmd.about(self.get_about().unwrap().clone()); } @@ -5154,8 +5154,8 @@ impl Index<&'_ Id> for Command { } } -impl From<&'_ Command> for Command { - fn from(cmd: &'_ Command) -> Self { +impl From<&'_ Self> for Command { + fn from(cmd: &'_ Self) -> Self { cmd.clone() } } diff --git a/clap_builder/src/builder/os_str.rs b/clap_builder/src/builder/os_str.rs index a42066e1997..d783205cdff 100644 --- a/clap_builder/src/builder/os_str.rs +++ b/clap_builder/src/builder/os_str.rs @@ -45,8 +45,8 @@ impl OsStr { } } -impl From<&'_ OsStr> for OsStr { - fn from(id: &'_ OsStr) -> Self { +impl From<&'_ Self> for OsStr { + fn from(id: &'_ Self) -> Self { id.clone() } } @@ -303,7 +303,7 @@ impl Default for Inner { } impl PartialEq for Inner { - fn eq(&self, other: &Inner) -> bool { + fn eq(&self, other: &Self) -> bool { self.as_os_str() == other.as_os_str() } } @@ -315,7 +315,7 @@ impl PartialOrd for Inner { } impl Ord for Inner { - fn cmp(&self, other: &Inner) -> std::cmp::Ordering { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.as_os_str().cmp(other.as_os_str()) } } diff --git a/clap_builder/src/builder/possible_value.rs b/clap_builder/src/builder/possible_value.rs index 757dc36ce94..b4092b183c5 100644 --- a/clap_builder/src/builder/possible_value.rs +++ b/clap_builder/src/builder/possible_value.rs @@ -68,7 +68,7 @@ impl PossibleValue { /// [possible value]: crate::builder::PossibleValuesParser /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() pub fn new(name: impl Into) -> Self { - PossibleValue { + Self { name: name.into(), ..Default::default() } diff --git a/clap_builder/src/builder/resettable.rs b/clap_builder/src/builder/resettable.rs index 057274012c7..ce6da65316b 100644 --- a/clap_builder/src/builder/resettable.rs +++ b/clap_builder/src/builder/resettable.rs @@ -140,31 +140,31 @@ impl IntoResettable for Option<&'static str> { } impl IntoResettable for Resettable { - fn into_resettable(self) -> Resettable { + fn into_resettable(self) -> Self { self } } -impl IntoResettable for char { - fn into_resettable(self) -> Resettable { +impl IntoResettable for char { + fn into_resettable(self) -> Resettable { Resettable::Value(self) } } -impl IntoResettable for usize { - fn into_resettable(self) -> Resettable { +impl IntoResettable for usize { + fn into_resettable(self) -> Resettable { Resettable::Value(self) } } -impl IntoResettable for ArgAction { - fn into_resettable(self) -> Resettable { +impl IntoResettable for ArgAction { + fn into_resettable(self) -> Resettable { Resettable::Value(self) } } -impl IntoResettable for ValueHint { - fn into_resettable(self) -> Resettable { +impl IntoResettable for ValueHint { + fn into_resettable(self) -> Resettable { Resettable::Value(self) } } diff --git a/clap_builder/src/builder/str.rs b/clap_builder/src/builder/str.rs index b812def4029..abd2b705c32 100644 --- a/clap_builder/src/builder/str.rs +++ b/clap_builder/src/builder/str.rs @@ -42,8 +42,8 @@ impl Str { } } -impl From<&'_ Str> for Str { - fn from(id: &'_ Str) -> Self { +impl From<&'_ Self> for Str { + fn from(id: &'_ Self) -> Self { id.clone() } } @@ -287,7 +287,7 @@ impl Default for Inner { } impl PartialEq for Inner { - fn eq(&self, other: &Inner) -> bool { + fn eq(&self, other: &Self) -> bool { self.as_str() == other.as_str() } } @@ -299,7 +299,7 @@ impl PartialOrd for Inner { } impl Ord for Inner { - fn cmp(&self, other: &Inner) -> std::cmp::Ordering { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.as_str().cmp(other.as_str()) } } diff --git a/clap_builder/src/builder/styled_str.rs b/clap_builder/src/builder/styled_str.rs index 2b08bf42bea..4cf3cbf8e36 100644 --- a/clap_builder/src/builder/styled_str.rs +++ b/clap_builder/src/builder/styled_str.rs @@ -158,13 +158,13 @@ impl Default for &'_ StyledStr { impl From for StyledStr { fn from(name: String) -> Self { - StyledStr(name) + Self(name) } } impl From<&'_ String> for StyledStr { fn from(name: &'_ String) -> Self { - let mut styled = StyledStr::new(); + let mut styled = Self::new(); styled.push_str(name); styled } @@ -172,7 +172,7 @@ impl From<&'_ String> for StyledStr { impl From<&'static str> for StyledStr { fn from(name: &'static str) -> Self { - let mut styled = StyledStr::new(); + let mut styled = Self::new(); styled.push_str(name); styled } @@ -180,7 +180,7 @@ impl From<&'static str> for StyledStr { impl From<&'_ &'static str> for StyledStr { fn from(name: &'_ &'static str) -> Self { - StyledStr::from(*name) + Self::from(*name) } } diff --git a/clap_builder/src/builder/value_hint.rs b/clap_builder/src/builder/value_hint.rs index 57b75cfc3fd..3a067632cd8 100644 --- a/clap_builder/src/builder/value_hint.rs +++ b/clap_builder/src/builder/value_hint.rs @@ -74,19 +74,19 @@ impl FromStr for ValueHint { type Err = String; fn from_str(s: &str) -> Result::Err> { Ok(match &*s.to_ascii_lowercase() { - "unknown" => ValueHint::Unknown, - "other" => ValueHint::Other, - "anypath" => ValueHint::AnyPath, - "filepath" => ValueHint::FilePath, - "dirpath" => ValueHint::DirPath, - "executablepath" => ValueHint::ExecutablePath, - "commandname" => ValueHint::CommandName, - "commandstring" => ValueHint::CommandString, - "commandwitharguments" => ValueHint::CommandWithArguments, - "username" => ValueHint::Username, - "hostname" => ValueHint::Hostname, - "url" => ValueHint::Url, - "emailaddress" => ValueHint::EmailAddress, + "unknown" => Self::Unknown, + "other" => Self::Other, + "anypath" => Self::AnyPath, + "filepath" => Self::FilePath, + "dirpath" => Self::DirPath, + "executablepath" => Self::ExecutablePath, + "commandname" => Self::CommandName, + "commandstring" => Self::CommandString, + "commandwitharguments" => Self::CommandWithArguments, + "username" => Self::Username, + "hostname" => Self::Hostname, + "url" => Self::Url, + "emailaddress" => Self::EmailAddress, _ => return Err(format!("unknown ValueHint: `{s}`")), }) } diff --git a/clap_builder/src/builder/value_parser.rs b/clap_builder/src/builder/value_parser.rs index 65257275e98..433ed5a4814 100644 --- a/clap_builder/src/builder/value_parser.rs +++ b/clap_builder/src/builder/value_parser.rs @@ -1197,7 +1197,7 @@ pub struct PossibleValuesParser(Vec); impl PossibleValuesParser { /// Verify the value is from an enumerated set of [`PossibleValue`][crate::builder::PossibleValue]. - pub fn new(values: impl Into) -> Self { + pub fn new(values: impl Into) -> Self { values.into() } } @@ -2290,7 +2290,7 @@ impl ValueParserFactory for String { } } impl ValueParserFactory for Box { - type Parser = MapValueParser Box>; + type Parser = MapValueParser Self>; fn value_parser() -> Self::Parser { StringValueParser::new().map(String::into_boxed_str) } @@ -2303,7 +2303,7 @@ impl ValueParserFactory for std::ffi::OsString { } impl ValueParserFactory for Box { type Parser = - MapValueParser Box>; + MapValueParser Self>; fn value_parser() -> Self::Parser { OsStringValueParser::new().map(std::ffi::OsString::into_boxed_os_str) } @@ -2316,7 +2316,7 @@ impl ValueParserFactory for std::path::PathBuf { } impl ValueParserFactory for Box { type Parser = - MapValueParser Box>; + MapValueParser Self>; fn value_parser() -> Self::Parser { PathBufValueParser::new().map(std::path::PathBuf::into_boxed_path) } @@ -2328,61 +2328,61 @@ impl ValueParserFactory for bool { } } impl ValueParserFactory for u8 { - type Parser = RangedI64ValueParser; + type Parser = RangedI64ValueParser; fn value_parser() -> Self::Parser { - let start: i64 = u8::MIN.into(); - let end: i64 = u8::MAX.into(); + let start: i64 = Self::MIN.into(); + let end: i64 = Self::MAX.into(); RangedI64ValueParser::new().range(start..=end) } } impl ValueParserFactory for i8 { - type Parser = RangedI64ValueParser; + type Parser = RangedI64ValueParser; fn value_parser() -> Self::Parser { - let start: i64 = i8::MIN.into(); - let end: i64 = i8::MAX.into(); + let start: i64 = Self::MIN.into(); + let end: i64 = Self::MAX.into(); RangedI64ValueParser::new().range(start..=end) } } impl ValueParserFactory for u16 { - type Parser = RangedI64ValueParser; + type Parser = RangedI64ValueParser; fn value_parser() -> Self::Parser { - let start: i64 = u16::MIN.into(); - let end: i64 = u16::MAX.into(); + let start: i64 = Self::MIN.into(); + let end: i64 = Self::MAX.into(); RangedI64ValueParser::new().range(start..=end) } } impl ValueParserFactory for i16 { - type Parser = RangedI64ValueParser; + type Parser = RangedI64ValueParser; fn value_parser() -> Self::Parser { - let start: i64 = i16::MIN.into(); - let end: i64 = i16::MAX.into(); + let start: i64 = Self::MIN.into(); + let end: i64 = Self::MAX.into(); RangedI64ValueParser::new().range(start..=end) } } impl ValueParserFactory for u32 { - type Parser = RangedI64ValueParser; + type Parser = RangedI64ValueParser; fn value_parser() -> Self::Parser { - let start: i64 = u32::MIN.into(); - let end: i64 = u32::MAX.into(); + let start: i64 = Self::MIN.into(); + let end: i64 = Self::MAX.into(); RangedI64ValueParser::new().range(start..=end) } } impl ValueParserFactory for i32 { - type Parser = RangedI64ValueParser; + type Parser = RangedI64ValueParser; fn value_parser() -> Self::Parser { - let start: i64 = i32::MIN.into(); - let end: i64 = i32::MAX.into(); + let start: i64 = Self::MIN.into(); + let end: i64 = Self::MAX.into(); RangedI64ValueParser::new().range(start..=end) } } impl ValueParserFactory for u64 { - type Parser = RangedU64ValueParser; + type Parser = RangedU64ValueParser; fn value_parser() -> Self::Parser { RangedU64ValueParser::new() } } impl ValueParserFactory for i64 { - type Parser = RangedI64ValueParser; + type Parser = RangedI64ValueParser; fn value_parser() -> Self::Parser { RangedI64ValueParser::new() } @@ -2394,7 +2394,7 @@ where T: Send + Sync + Clone, { type Parser = - MapValueParser<::Parser, fn(T) -> std::num::Saturating>; + MapValueParser<::Parser, fn(T) -> Self>; fn value_parser() -> Self::Parser { T::value_parser().map(std::num::Saturating) } @@ -2405,7 +2405,7 @@ where ::Parser: TypedValueParser, T: Send + Sync + Clone, { - type Parser = MapValueParser<::Parser, fn(T) -> std::num::Wrapping>; + type Parser = MapValueParser<::Parser, fn(T) -> Self>; fn value_parser() -> Self::Parser { T::value_parser().map(std::num::Wrapping) } @@ -2416,9 +2416,9 @@ where ::Parser: TypedValueParser, T: Send + Sync + Clone, { - type Parser = MapValueParser<::Parser, fn(T) -> Box>; + type Parser = MapValueParser<::Parser, fn(T) -> Self>; fn value_parser() -> Self::Parser { - T::value_parser().map(Box::new) + T::value_parser().map(Self::new) } } impl ValueParserFactory for std::sync::Arc @@ -2427,9 +2427,9 @@ where ::Parser: TypedValueParser, T: Send + Sync + Clone, { - type Parser = MapValueParser<::Parser, fn(T) -> std::sync::Arc>; + type Parser = MapValueParser<::Parser, fn(T) -> Self>; fn value_parser() -> Self::Parser { - T::value_parser().map(std::sync::Arc::new) + T::value_parser().map(Self::new) } } diff --git a/clap_builder/src/derive.rs b/clap_builder/src/derive.rs index 06a94015b23..d923059dea0 100644 --- a/clap_builder/src/derive.rs +++ b/clap_builder/src/derive.rs @@ -314,11 +314,11 @@ pub trait ValueEnum: Sized + Clone { impl Parser for Box { fn parse() -> Self { - Box::new(::parse()) + Self::new(::parse()) } fn try_parse() -> Result { - ::try_parse().map(Box::new) + ::try_parse().map(Self::new) } fn parse_from(itr: I) -> Self @@ -326,7 +326,7 @@ impl Parser for Box { I: IntoIterator, It: Into + Clone, { - Box::new(::parse_from(itr)) + Self::new(::parse_from(itr)) } fn try_parse_from(itr: I) -> Result @@ -334,7 +334,7 @@ impl Parser for Box { I: IntoIterator, It: Into + Clone, { - ::try_parse_from(itr).map(Box::new) + ::try_parse_from(itr).map(Self::new) } } @@ -349,10 +349,10 @@ impl CommandFactory for Box { impl FromArgMatches for Box { fn from_arg_matches(matches: &ArgMatches) -> Result { - ::from_arg_matches(matches).map(Box::new) + ::from_arg_matches(matches).map(Self::new) } fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result { - ::from_arg_matches_mut(matches).map(Box::new) + ::from_arg_matches_mut(matches).map(Self::new) } fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> { ::update_from_arg_matches(self, matches) diff --git a/clap_builder/src/error/mod.rs b/clap_builder/src/error/mod.rs index 5e2cc4663ed..a6d19d4d074 100644 --- a/clap_builder/src/error/mod.rs +++ b/clap_builder/src/error/mod.rs @@ -817,13 +817,13 @@ impl Error { impl From for Error { fn from(e: io::Error) -> Self { - Error::raw(ErrorKind::Io, e) + Self::raw(ErrorKind::Io, e) } } impl From for Error { fn from(e: fmt::Error) -> Self { - Error::raw(ErrorKind::Format, e) + Self::raw(ErrorKind::Format, e) } } @@ -862,7 +862,7 @@ pub(crate) enum Message { impl Message { fn format(&mut self, cmd: &Command, usage: Option) { match self { - Message::Raw(s) => { + Self::Raw(s) => { let mut message = String::new(); std::mem::swap(s, &mut message); @@ -875,18 +875,18 @@ impl Message { *self = Self::Formatted(styled); } - Message::Formatted(_) => {} + Self::Formatted(_) => {} } } fn formatted(&self, styles: &Styles) -> Cow<'_, StyledStr> { match self { - Message::Raw(s) => { + Self::Raw(s) => { let styled = format::format_error_message(s, styles, None, None); Cow::Owned(styled) } - Message::Formatted(s) => Cow::Borrowed(s), + Self::Formatted(s) => Cow::Borrowed(s), } } } diff --git a/clap_builder/src/mkeymap.rs b/clap_builder/src/mkeymap.rs index 57df7f0117d..d93ac548c1d 100644 --- a/clap_builder/src/mkeymap.rs +++ b/clap_builder/src/mkeymap.rs @@ -30,14 +30,14 @@ pub(crate) enum KeyType { impl KeyType { pub(crate) fn is_position(&self) -> bool { - matches!(self, KeyType::Position(_)) + matches!(self, Self::Position(_)) } } impl PartialEq for KeyType { fn eq(&self, rhs: &usize) -> bool { match self { - KeyType::Position(x) => x == rhs, + Self::Position(x) => x == rhs, _ => false, } } @@ -46,7 +46,7 @@ impl PartialEq for KeyType { impl PartialEq<&str> for KeyType { fn eq(&self, rhs: &&str) -> bool { match self { - KeyType::Long(l) => l == rhs, + Self::Long(l) => l == rhs, _ => false, } } @@ -55,7 +55,7 @@ impl PartialEq<&str> for KeyType { impl PartialEq for KeyType { fn eq(&self, rhs: &str) -> bool { match self { - KeyType::Long(l) => l == rhs, + Self::Long(l) => l == rhs, _ => false, } } @@ -64,7 +64,7 @@ impl PartialEq for KeyType { impl PartialEq for KeyType { fn eq(&self, rhs: &OsStr) -> bool { match self { - KeyType::Long(l) => l == rhs, + Self::Long(l) => l == rhs, _ => false, } } @@ -73,7 +73,7 @@ impl PartialEq for KeyType { impl PartialEq for KeyType { fn eq(&self, rhs: &char) -> bool { match self { - KeyType::Short(c) => c == rhs, + Self::Short(c) => c == rhs, _ => false, } } diff --git a/clap_builder/src/output/fmt.rs b/clap_builder/src/output/fmt.rs index 77b84ba00d0..3f6f6349052 100644 --- a/clap_builder/src/output/fmt.rs +++ b/clap_builder/src/output/fmt.rs @@ -17,7 +17,7 @@ pub(crate) struct Colorizer { impl Colorizer { pub(crate) fn new(stream: Stream, color_when: ColorChoice) -> Self { - Colorizer { + Self { stream, color_when, content: Default::default(), diff --git a/clap_builder/src/parser/arg_matcher.rs b/clap_builder/src/parser/arg_matcher.rs index 065165d3a49..7f9d438ce63 100644 --- a/clap_builder/src/parser/arg_matcher.rs +++ b/clap_builder/src/parser/arg_matcher.rs @@ -21,7 +21,7 @@ pub(crate) struct ArgMatcher { impl ArgMatcher { pub(crate) fn new(_cmd: &Command) -> Self { - ArgMatcher { + Self { matches: ArgMatches { #[cfg(debug_assertions)] valid_args: { @@ -77,7 +77,7 @@ impl ArgMatcher { } } if let Some(ref mut sc) = self.matches.subcommand { - let mut am = ArgMatcher { + let mut am = Self { matches: mem::take(&mut sc.matches), pending: None, }; diff --git a/clap_builder/src/parser/error.rs b/clap_builder/src/parser/error.rs index fae60116f79..323aa9117f6 100644 --- a/clap_builder/src/parser/error.rs +++ b/clap_builder/src/parser/error.rs @@ -22,7 +22,7 @@ pub enum MatchesError { impl MatchesError { #[cfg_attr(debug_assertions, track_caller)] - pub(crate) fn unwrap(id: &str, r: Result) -> T { + pub(crate) fn unwrap(id: &str, r: Result) -> T { let err = match r { Ok(t) => { return t; diff --git a/clap_builder/src/parser/matches/arg_matches.rs b/clap_builder/src/parser/matches/arg_matches.rs index 056f521a5c8..ecf33d18cb7 100644 --- a/clap_builder/src/parser/matches/arg_matches.rs +++ b/clap_builder/src/parser/matches/arg_matches.rs @@ -919,7 +919,7 @@ impl ArgMatches { /// ``` /// [subcommand]: crate::Command::subcommand #[inline] - pub fn subcommand(&self) -> Option<(&str, &ArgMatches)> { + pub fn subcommand(&self) -> Option<(&str, &Self)> { self.subcommand.as_ref().map(|sc| (&*sc.name, &sc.matches)) } @@ -979,7 +979,7 @@ impl ArgMatches { /// } /// ``` /// [subcommand]: crate::Command::subcommand - pub fn remove_subcommand(&mut self) -> Option<(String, ArgMatches)> { + pub fn remove_subcommand(&mut self) -> Option<(String, Self)> { self.subcommand.take().map(|sc| (sc.name, sc.matches)) } @@ -1023,7 +1023,7 @@ impl ArgMatches { /// /// [subcommand]: crate::Command::subcommand /// [`Command`]: crate::Command - pub fn subcommand_matches(&self, name: &str) -> Option<&ArgMatches> { + pub fn subcommand_matches(&self, name: &str) -> Option<&Self> { self.get_subcommand(name).map(|sc| &sc.matches) } @@ -1464,7 +1464,7 @@ impl ExactSizeIterator for Values {} impl Default for Values { fn default() -> Self { let empty: Vec> = Default::default(); - Values { + Self { iter: empty.into_iter().flatten().map(|_| unreachable!()), len: 0, } @@ -1698,7 +1698,7 @@ impl ExactSizeIterator for Occurrences {} impl Default for Occurrences { fn default() -> Self { let empty: Vec> = Default::default(); - Occurrences { + Self { iter: empty.into_iter().map(|_| unreachable!()), } } diff --git a/clap_builder/src/parser/matches/matched_arg.rs b/clap_builder/src/parser/matches/matched_arg.rs index 20614542a86..69619ff06f6 100644 --- a/clap_builder/src/parser/matches/matched_arg.rs +++ b/clap_builder/src/parser/matches/matched_arg.rs @@ -178,8 +178,8 @@ impl MatchedArg { } impl PartialEq for MatchedArg { - fn eq(&self, other: &MatchedArg) -> bool { - let MatchedArg { + fn eq(&self, other: &Self) -> bool { + let Self { source: self_source, indices: self_indices, type_id: self_type_id, @@ -187,7 +187,7 @@ impl PartialEq for MatchedArg { raw_vals: self_raw_vals, ignore_case: self_ignore_case, } = self; - let MatchedArg { + let Self { source: other_source, indices: other_indices, type_id: other_type_id, diff --git a/clap_builder/src/util/graph.rs b/clap_builder/src/util/graph.rs index d646400b01c..5fd4f6b496a 100644 --- a/clap_builder/src/util/graph.rs +++ b/clap_builder/src/util/graph.rs @@ -6,7 +6,7 @@ struct Child { impl Child { fn new(id: T) -> Self { - Child { + Self { id, children: vec![], } @@ -21,7 +21,7 @@ where T: Sized + PartialEq + Clone, { pub(crate) fn with_capacity(s: usize) -> Self { - ChildGraph(Vec::with_capacity(s)) + Self(Vec::with_capacity(s)) } pub(crate) fn insert(&mut self, req: T) -> usize { diff --git a/clap_builder/src/util/id.rs b/clap_builder/src/util/id.rs index c2bc545eb10..de5e755791d 100644 --- a/clap_builder/src/util/id.rs +++ b/clap_builder/src/util/id.rs @@ -27,8 +27,8 @@ impl Id { } } -impl From<&'_ Id> for Id { - fn from(id: &'_ Id) -> Self { +impl From<&'_ Self> for Id { + fn from(id: &'_ Self) -> Self { id.clone() } } diff --git a/clap_complete/src/aot/shells/shell.rs b/clap_complete/src/aot/shells/shell.rs index 94ef511ef69..4469f6b6cb0 100644 --- a/clap_complete/src/aot/shells/shell.rs +++ b/clap_complete/src/aot/shells/shell.rs @@ -51,21 +51,21 @@ impl FromStr for Shell { impl ValueEnum for Shell { fn value_variants<'a>() -> &'a [Self] { &[ - Shell::Bash, - Shell::Elvish, - Shell::Fish, - Shell::PowerShell, - Shell::Zsh, + Self::Bash, + Self::Elvish, + Self::Fish, + Self::PowerShell, + Self::Zsh, ] } fn to_possible_value(&self) -> Option { Some(match self { - Shell::Bash => PossibleValue::new("bash"), - Shell::Elvish => PossibleValue::new("elvish"), - Shell::Fish => PossibleValue::new("fish"), - Shell::PowerShell => PossibleValue::new("powershell"), - Shell::Zsh => PossibleValue::new("zsh"), + Self::Bash => PossibleValue::new("bash"), + Self::Elvish => PossibleValue::new("elvish"), + Self::Fish => PossibleValue::new("fish"), + Self::PowerShell => PossibleValue::new("powershell"), + Self::Zsh => PossibleValue::new("zsh"), }) } } @@ -73,11 +73,11 @@ impl ValueEnum for Shell { impl Generator for Shell { fn file_name(&self, name: &str) -> String { match self { - Shell::Bash => shells::Bash.file_name(name), - Shell::Elvish => shells::Elvish.file_name(name), - Shell::Fish => shells::Fish.file_name(name), - Shell::PowerShell => shells::PowerShell.file_name(name), - Shell::Zsh => shells::Zsh.file_name(name), + Self::Bash => shells::Bash.file_name(name), + Self::Elvish => shells::Elvish.file_name(name), + Self::Fish => shells::Fish.file_name(name), + Self::PowerShell => shells::PowerShell.file_name(name), + Self::Zsh => shells::Zsh.file_name(name), } } @@ -88,11 +88,11 @@ impl Generator for Shell { fn try_generate(&self, cmd: &clap::Command, buf: &mut dyn std::io::Write) -> Result<(), Error> { match self { - Shell::Bash => shells::Bash.try_generate(cmd, buf), - Shell::Elvish => shells::Elvish.try_generate(cmd, buf), - Shell::Fish => shells::Fish.try_generate(cmd, buf), - Shell::PowerShell => shells::PowerShell.try_generate(cmd, buf), - Shell::Zsh => shells::Zsh.try_generate(cmd, buf), + Self::Bash => shells::Bash.try_generate(cmd, buf), + Self::Elvish => shells::Elvish.try_generate(cmd, buf), + Self::Fish => shells::Fish.try_generate(cmd, buf), + Self::PowerShell => shells::PowerShell.try_generate(cmd, buf), + Self::Zsh => shells::Zsh.try_generate(cmd, buf), } } } @@ -109,7 +109,7 @@ impl Shell { /// assert_eq!(Shell::from_shell_path("/usr/bin/zsh"), Some(Shell::Zsh)); /// assert_eq!(Shell::from_shell_path("/opt/my_custom_shell"), None); /// ``` - pub fn from_shell_path>(path: P) -> Option { + pub fn from_shell_path>(path: P) -> Option { parse_shell_from_path(path.as_ref()) } @@ -135,11 +135,11 @@ impl Shell { /// let mut cmd = build_cli(); /// generate(Shell::from_env().unwrap_or(Shell::Bash), &mut cmd, "myapp", &mut std::io::stdout()); /// ``` - pub fn from_env() -> Option { + pub fn from_env() -> Option { if let Some(env_shell) = std::env::var_os("SHELL") { - Shell::from_shell_path(env_shell) + Self::from_shell_path(env_shell) } else if cfg!(windows) { - Some(Shell::PowerShell) + Some(Self::PowerShell) } else { None } diff --git a/clap_derive/src/attr.rs b/clap_derive/src/attr.rs index 51736c4d1f6..ff418862929 100644 --- a/clap_derive/src/attr.rs +++ b/clap_derive/src/attr.rs @@ -41,7 +41,7 @@ impl ClapAttr { continue; }; for mut attr in - attr.parse_args_with(Punctuated::::parse_terminated)? + attr.parse_args_with(Punctuated::::parse_terminated)? { attr.kind = kind; parsed.push(attr); diff --git a/clap_derive/src/item.rs b/clap_derive/src/item.rs index ab32918e5f4..3d8848cc375 100644 --- a/clap_derive/src/item.rs +++ b/clap_derive/src/item.rs @@ -1223,7 +1223,7 @@ pub(crate) struct Method { impl Method { pub(crate) fn new(name: Ident, args: TokenStream) -> Self { - Method { name, args } + Self { name, args } } fn from_env(ident: Ident, env_var: &str) -> Result, syn::Error> { @@ -1250,7 +1250,7 @@ impl Method { lit = LitStr::new(&edited, lit.span()); } - Ok(Some(Method::new(ident, quote!(#lit)))) + Ok(Some(Self::new(ident, quote!(#lit)))) } pub(crate) fn args(&self) -> &TokenStream { @@ -1260,7 +1260,7 @@ impl Method { impl ToTokens for Method { fn to_tokens(&self, ts: &mut TokenStream) { - let Method { ref name, ref args } = self; + let Self { ref name, ref args } = self; let tokens = quote!( .#name(#args) ); @@ -1294,7 +1294,7 @@ impl Deprecation { impl ToTokens for Deprecation { fn to_tokens(&self, ts: &mut TokenStream) { let tokens = if cfg!(feature = "deprecated") { - let Deprecation { + let Self { span, id, version, @@ -1416,8 +1416,8 @@ impl Name { use CasingStyle::{Camel, Kebab, Lower, Pascal, ScreamingSnake, Snake, Upper, Verbatim}; match self { - Name::Assigned(tokens) => tokens, - Name::Derived(ident) => { + Self::Assigned(tokens) => tokens, + Self::Derived(ident) => { let s = ident.unraw().to_string(); let s = match style { Pascal => s.to_upper_camel_case(), @@ -1438,8 +1438,8 @@ impl Name { use CasingStyle::{Camel, Kebab, Lower, Pascal, ScreamingSnake, Snake, Upper, Verbatim}; match self { - Name::Assigned(tokens) => quote!( (#tokens).chars().next().unwrap() ), - Name::Derived(ident) => { + Self::Assigned(tokens) => quote!( (#tokens).chars().next().unwrap() ), + Self::Derived(ident) => { let s = ident.unraw().to_string(); let s = match style { Pascal => s.to_upper_camel_case(), @@ -1462,8 +1462,8 @@ impl Name { impl ToTokens for Name { fn to_tokens(&self, tokens: &mut TokenStream) { match self { - Name::Assigned(t) => t.to_tokens(tokens), - Name::Derived(ident) => { + Self::Assigned(t) => t.to_tokens(tokens), + Self::Derived(ident) => { let s = ident.unraw().to_string(); quote_spanned!(ident.span()=> #s).to_tokens(tokens); } diff --git a/clap_derive/src/utils/spanned.rs b/clap_derive/src/utils/spanned.rs index 32f566e716c..7910092e6b5 100644 --- a/clap_derive/src/utils/spanned.rs +++ b/clap_derive/src/utils/spanned.rs @@ -13,7 +13,7 @@ pub(crate) struct Sp { impl Sp { pub(crate) fn new(val: T, span: Span) -> Self { - Sp { val, span } + Self { val, span } } pub(crate) fn get(&self) -> &T { @@ -41,7 +41,7 @@ impl DerefMut for Sp { impl From for Sp { fn from(ident: Ident) -> Self { - Sp { + Self { val: ident.to_string(), span: ident.span(), } @@ -50,7 +50,7 @@ impl From for Sp { impl From for Sp { fn from(lit: LitStr) -> Self { - Sp { + Self { val: lit.value(), span: lit.span(), } @@ -59,7 +59,7 @@ impl From for Sp { impl<'a> From> for Sp { fn from(sp: Sp<&'a str>) -> Self { - Sp::new(sp.val.into(), sp.span) + Self::new(sp.val.into(), sp.span) } } diff --git a/clap_lex/src/ext.rs b/clap_lex/src/ext.rs index fe2ac9bb836..fc4506e4096 100644 --- a/clap_lex/src/ext.rs +++ b/clap_lex/src/ext.rs @@ -204,7 +204,7 @@ impl OsStrExt for OsStr { // SAFETY: // - This came from `as_encoded_bytes` // - Since `prefix` is `&str`, any split will be along UTF-8 boundary - unsafe { OsStr::from_encoded_bytes_unchecked(s) } + unsafe { Self::from_encoded_bytes_unchecked(s) } }) } fn starts_with(&self, prefix: &str) -> bool { @@ -231,8 +231,8 @@ impl OsStrExt for OsStr { // - Since `needle` is `&str`, any split will be along UTF-8 boundary unsafe { Some(( - OsStr::from_encoded_bytes_unchecked(first), - OsStr::from_encoded_bytes_unchecked(second), + Self::from_encoded_bytes_unchecked(first), + Self::from_encoded_bytes_unchecked(second), )) } } From cc2c870e1bdc60dfd2728a604063179aa4b40fa4 Mon Sep 17 00:00:00 2001 From: adamnemecek Date: Mon, 30 Jun 2025 20:59:25 -0700 Subject: [PATCH 2/7] refactoring --- clap_complete/src/aot/shells/shell.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/clap_complete/src/aot/shells/shell.rs b/clap_complete/src/aot/shells/shell.rs index 4469f6b6cb0..eeb7d2cb564 100644 --- a/clap_complete/src/aot/shells/shell.rs +++ b/clap_complete/src/aot/shells/shell.rs @@ -60,13 +60,13 @@ impl ValueEnum for Shell { } fn to_possible_value(&self) -> Option { - Some(match self { - Self::Bash => PossibleValue::new("bash"), - Self::Elvish => PossibleValue::new("elvish"), - Self::Fish => PossibleValue::new("fish"), - Self::PowerShell => PossibleValue::new("powershell"), - Self::Zsh => PossibleValue::new("zsh"), - }) + Some(PossibleValue::new(match self { + Self::Bash => "bash", + Self::Elvish => "elvish", + Self::Fish => "fish", + Self::PowerShell => "powershell", + Self::Zsh => "zsh", + })) } } From 8d9de564e7c0d74bcc820614510bc027ae983f4c Mon Sep 17 00:00:00 2001 From: adamnemecek Date: Mon, 30 Jun 2025 21:00:03 -0700 Subject: [PATCH 3/7] cargo fmt --- clap_builder/src/builder/command.rs | 5 +---- clap_builder/src/builder/value_parser.rs | 9 +++------ clap_derive/src/attr.rs | 4 +--- 3 files changed, 5 insertions(+), 13 deletions(-) diff --git a/clap_builder/src/builder/command.rs b/clap_builder/src/builder/command.rs index 1d3d8478e84..2f4e5680985 100644 --- a/clap_builder/src/builder/command.rs +++ b/clap_builder/src/builder/command.rs @@ -3902,10 +3902,7 @@ impl Command { /// /// This does not recurse through subcommands of subcommands. #[inline] - pub fn find_subcommand_mut( - &mut self, - name: impl AsRef, - ) -> Option<&mut Self> { + pub fn find_subcommand_mut(&mut self, name: impl AsRef) -> Option<&mut Self> { let name = name.as_ref(); self.get_subcommands_mut().find(|s| s.aliases_to(name)) } diff --git a/clap_builder/src/builder/value_parser.rs b/clap_builder/src/builder/value_parser.rs index 433ed5a4814..84746bf0a71 100644 --- a/clap_builder/src/builder/value_parser.rs +++ b/clap_builder/src/builder/value_parser.rs @@ -2302,8 +2302,7 @@ impl ValueParserFactory for std::ffi::OsString { } } impl ValueParserFactory for Box { - type Parser = - MapValueParser Self>; + type Parser = MapValueParser Self>; fn value_parser() -> Self::Parser { OsStringValueParser::new().map(std::ffi::OsString::into_boxed_os_str) } @@ -2315,8 +2314,7 @@ impl ValueParserFactory for std::path::PathBuf { } } impl ValueParserFactory for Box { - type Parser = - MapValueParser Self>; + type Parser = MapValueParser Self>; fn value_parser() -> Self::Parser { PathBufValueParser::new().map(std::path::PathBuf::into_boxed_path) } @@ -2393,8 +2391,7 @@ where ::Parser: TypedValueParser, T: Send + Sync + Clone, { - type Parser = - MapValueParser<::Parser, fn(T) -> Self>; + type Parser = MapValueParser<::Parser, fn(T) -> Self>; fn value_parser() -> Self::Parser { T::value_parser().map(std::num::Saturating) } diff --git a/clap_derive/src/attr.rs b/clap_derive/src/attr.rs index ff418862929..3276f755aa9 100644 --- a/clap_derive/src/attr.rs +++ b/clap_derive/src/attr.rs @@ -40,9 +40,7 @@ impl ClapAttr { } else { continue; }; - for mut attr in - attr.parse_args_with(Punctuated::::parse_terminated)? - { + for mut attr in attr.parse_args_with(Punctuated::::parse_terminated)? { attr.kind = kind; parsed.push(attr); } From 5688ad115bb23650432df97c8b78d32b1c439c07 Mon Sep 17 00:00:00 2001 From: adamnemecek Date: Mon, 30 Jun 2025 21:02:01 -0700 Subject: [PATCH 4/7] refactoring --- clap_complete/src/aot/shells/shell.rs | 16 ++++++++-------- clap_complete/src/engine/candidate.rs | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/clap_complete/src/aot/shells/shell.rs b/clap_complete/src/aot/shells/shell.rs index eeb7d2cb564..7d4419f8cf4 100644 --- a/clap_complete/src/aot/shells/shell.rs +++ b/clap_complete/src/aot/shells/shell.rs @@ -150,12 +150,12 @@ impl Shell { // to from_shell_path being generic fn parse_shell_from_path(path: &Path) -> Option { let name = path.file_stem()?.to_str()?; - match name { - "bash" => Some(Shell::Bash), - "zsh" => Some(Shell::Zsh), - "fish" => Some(Shell::Fish), - "elvish" => Some(Shell::Elvish), - "powershell" | "powershell_ise" => Some(Shell::PowerShell), - _ => None, - } + Some(match name { + "bash" => Shell::Bash, + "zsh" => Shell::Zsh, + "fish" => Shell::Fish, + "elvish" => Shell::Elvish, + "powershell" | "powershell_ise" => Shell::PowerShell, + _ => return None, + }) } diff --git a/clap_complete/src/engine/candidate.rs b/clap_complete/src/engine/candidate.rs index af629f0f7c0..8d7196dd468 100644 --- a/clap_complete/src/engine/candidate.rs +++ b/clap_complete/src/engine/candidate.rs @@ -108,6 +108,6 @@ impl CompletionCandidate { impl> From for CompletionCandidate { fn from(s: S) -> Self { - CompletionCandidate::new(s.into()) + Self::new(s.into()) } } From ee28fdcc88ab6386288131209474d6160b8bc881 Mon Sep 17 00:00:00 2001 From: adamnemecek Date: Mon, 30 Jun 2025 21:06:52 -0700 Subject: [PATCH 5/7] refactoring --- clap_builder/src/builder/action.rs | 35 ++++++++++------------------ clap_builder/src/error/context.rs | 37 +++++++++++++++--------------- 2 files changed, 30 insertions(+), 42 deletions(-) diff --git a/clap_builder/src/builder/action.rs b/clap_builder/src/builder/action.rs index 37214f20381..265f31f939b 100644 --- a/clap_builder/src/builder/action.rs +++ b/clap_builder/src/builder/action.rs @@ -359,15 +359,14 @@ impl ArgAction { /// processed. pub fn takes_values(&self) -> bool { match self { - Self::Set => true, - Self::Append => true, - Self::SetTrue => false, - Self::SetFalse => false, - Self::Count => false, - Self::Help => false, - Self::HelpShort => false, - Self::HelpLong => false, - Self::Version => false, + Self::Set | Self::Append => true, + Self::SetTrue + | Self::SetFalse + | Self::Count + | Self::Help + | Self::HelpShort + | Self::HelpLong + | Self::Version => false, } } @@ -432,28 +431,18 @@ impl ArgAction { match self { Self::Set => None, Self::Append => None, - Self::SetTrue => Some(super::ValueParser::bool()), - Self::SetFalse => Some(super::ValueParser::bool()), + Self::SetTrue | Self::SetFalse => Some(super::ValueParser::bool()), Self::Count => Some(crate::value_parser!(u8).into()), - Self::Help => None, - Self::HelpShort => None, - Self::HelpLong => None, - Self::Version => None, + Self::Help | Self::HelpShort | Self::HelpLong | Self::Version => None, } } #[cfg(debug_assertions)] pub(crate) fn value_type_id(&self) -> Option { match self { - Self::Set => None, - Self::Append => None, - Self::SetTrue => None, - Self::SetFalse => None, + Self::Set | Self::Append | Self::SetTrue | Self::SetFalse => None, Self::Count => Some(AnyValueId::of::()), - Self::Help => None, - Self::HelpShort => None, - Self::HelpLong => None, - Self::Version => None, + Self::Help | Self::HelpShort | Self::HelpLong | Self::Version => None, } } } diff --git a/clap_builder/src/error/context.rs b/clap_builder/src/error/context.rs index 045923c4771..114328504f9 100644 --- a/clap_builder/src/error/context.rs +++ b/clap_builder/src/error/context.rs @@ -42,25 +42,24 @@ pub enum ContextKind { impl ContextKind { /// End-user description of the error case, where relevant pub fn as_str(self) -> Option<&'static str> { - match self { - Self::InvalidSubcommand => Some("Invalid Subcommand"), - Self::InvalidArg => Some("Invalid Argument"), - Self::PriorArg => Some("Prior Argument"), - Self::ValidSubcommand => Some("Valid Subcommand"), - Self::ValidValue => Some("Valid Value"), - Self::InvalidValue => Some("Invalid Value"), - Self::ActualNumValues => Some("Actual Number of Values"), - Self::ExpectedNumValues => Some("Expected Number of Values"), - Self::MinValues => Some("Minimum Number of Values"), - Self::SuggestedCommand => Some("Suggested Command"), - Self::SuggestedSubcommand => Some("Suggested Subcommand"), - Self::SuggestedArg => Some("Suggested Argument"), - Self::SuggestedValue => Some("Suggested Value"), - Self::TrailingArg => Some("Trailing Argument"), - Self::Suggested => Some("Suggested"), - Self::Usage => None, - Self::Custom => None, - } + Some(match self { + Self::InvalidSubcommand => "Invalid Subcommand", + Self::InvalidArg => "Invalid Argument", + Self::PriorArg => "Prior Argument", + Self::ValidSubcommand => "Valid Subcommand", + Self::ValidValue => "Valid Value", + Self::InvalidValue => "Invalid Value", + Self::ActualNumValues => "Actual Number of Values", + Self::ExpectedNumValues => "Expected Number of Values", + Self::MinValues => "Minimum Number of Values", + Self::SuggestedCommand => "Suggested Command", + Self::SuggestedSubcommand => "Suggested Subcommand", + Self::SuggestedArg => "Suggested Argument", + Self::SuggestedValue => "Suggested Value", + Self::TrailingArg => "Trailing Argument", + Self::Suggested => "Suggested", + Self::Usage | Self::Custom => return None, + }) } } From 5bee9ba2752f578f80815474964b3085e612748c Mon Sep 17 00:00:00 2001 From: adamnemecek Date: Mon, 30 Jun 2025 21:14:48 -0700 Subject: [PATCH 6/7] refactoring --- clap_builder/src/builder/action.rs | 48 +++++++++++------------------- clap_builder/src/error/kind.rs | 40 ++++++++++++------------- clap_builder/src/util/color.rs | 10 +++---- 3 files changed, 41 insertions(+), 57 deletions(-) diff --git a/clap_builder/src/builder/action.rs b/clap_builder/src/builder/action.rs index 265f31f939b..87eaa9397f0 100644 --- a/clap_builder/src/builder/action.rs +++ b/clap_builder/src/builder/action.rs @@ -373,29 +373,24 @@ impl ArgAction { #[cfg(debug_assertions)] pub(crate) fn max_num_args(&self) -> ValueRange { match self { - Self::Set => ValueRange::FULL, - Self::Append => ValueRange::FULL, - Self::SetTrue => ValueRange::OPTIONAL, - Self::SetFalse => ValueRange::OPTIONAL, - Self::Count => ValueRange::EMPTY, - Self::Help => ValueRange::EMPTY, - Self::HelpShort => ValueRange::EMPTY, - Self::HelpLong => ValueRange::EMPTY, - Self::Version => ValueRange::EMPTY, + Self::Set | Self::Append => ValueRange::FULL, + Self::SetTrue | Self::SetFalse => ValueRange::OPTIONAL, + Self::Count | Self::Help | Self::HelpShort | Self::HelpLong | Self::Version => { + ValueRange::EMPTY + } } } pub(crate) fn default_num_args(&self) -> ValueRange { match self { - Self::Set => ValueRange::SINGLE, - Self::Append => ValueRange::SINGLE, - Self::SetTrue => ValueRange::EMPTY, - Self::SetFalse => ValueRange::EMPTY, - Self::Count => ValueRange::EMPTY, - Self::Help => ValueRange::EMPTY, - Self::HelpShort => ValueRange::EMPTY, - Self::HelpLong => ValueRange::EMPTY, - Self::Version => ValueRange::EMPTY, + Self::Set | Self::Append => ValueRange::SINGLE, + Self::SetTrue + | Self::SetFalse + | Self::Count + | Self::Help + | Self::HelpShort + | Self::HelpLong + | Self::Version => ValueRange::EMPTY, } } @@ -406,31 +401,22 @@ impl ArgAction { Self::SetTrue => Some(std::ffi::OsStr::new("false")), Self::SetFalse => Some(std::ffi::OsStr::new("true")), Self::Count => Some(std::ffi::OsStr::new("0")), - Self::Help => None, - Self::HelpShort => None, - Self::HelpLong => None, - Self::Version => None, + Self::Help | Self::HelpShort | Self::HelpLong | Self::Version => None, } } pub(crate) fn default_missing_value(&self) -> Option<&'static std::ffi::OsStr> { match self { - Self::Set => None, - Self::Append => None, + Self::Set | Self::Append => None, Self::SetTrue => Some(std::ffi::OsStr::new("true")), Self::SetFalse => Some(std::ffi::OsStr::new("false")), - Self::Count => None, - Self::Help => None, - Self::HelpShort => None, - Self::HelpLong => None, - Self::Version => None, + Self::Count | Self::Help | Self::HelpShort | Self::HelpLong | Self::Version => None, } } pub(crate) fn default_value_parser(&self) -> Option { match self { - Self::Set => None, - Self::Append => None, + Self::Set | Self::Append => None, Self::SetTrue | Self::SetFalse => Some(super::ValueParser::bool()), Self::Count => Some(crate::value_parser!(u8).into()), Self::Help | Self::HelpShort | Self::HelpLong | Self::Version => None, diff --git a/clap_builder/src/error/kind.rs b/clap_builder/src/error/kind.rs index 298a4fd3277..9148943eedc 100644 --- a/clap_builder/src/error/kind.rs +++ b/clap_builder/src/error/kind.rs @@ -332,29 +332,27 @@ pub enum ErrorKind { 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("unexpected argument found"), - Self::InvalidSubcommand => Some("unrecognized subcommand"), - Self::NoEquals => Some("equal is needed when assigning values to one of the arguments"), - Self::ValueValidation => Some("invalid value for one of the arguments"), - Self::TooManyValues => Some("unexpected value for an argument found"), - Self::TooFewValues => Some("more values required for an argument"), - Self::WrongNumberOfValues => Some("too many or too few values for an argument"), + Some(match self { + Self::InvalidValue => "one of the values isn't valid for an argument", + Self::UnknownArgument => "unexpected argument found", + Self::InvalidSubcommand => "unrecognized subcommand", + Self::NoEquals => "equal is needed when assigning values to one of the arguments", + Self::ValueValidation => "invalid value for one of the arguments", + Self::TooManyValues => "unexpected value for an argument found", + Self::TooFewValues => "more values required for an argument", + Self::WrongNumberOfValues => "too many or too few values for an argument", Self::ArgumentConflict => { - Some("an argument cannot be used with one or more of the other specified arguments") + "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::InvalidUtf8 => Some("invalid UTF-8 was detected in one or more arguments"), - Self::DisplayHelp => None, - Self::DisplayHelpOnMissingArgumentOrSubcommand => None, - Self::DisplayVersion => None, - Self::Io => None, - Self::Format => None, - } + Self::MissingRequiredArgument => "one or more required arguments were not provided", + Self::MissingSubcommand => "a subcommand is required but one was not provided", + Self::InvalidUtf8 => "invalid UTF-8 was detected in one or more arguments", + Self::DisplayHelp + | Self::DisplayHelpOnMissingArgumentOrSubcommand + | Self::DisplayVersion + | Self::Io + | Self::Format => return None, + }) } } diff --git a/clap_builder/src/util/color.rs b/clap_builder/src/util/color.rs index c1978a38400..622a1e61780 100644 --- a/clap_builder/src/util/color.rs +++ b/clap_builder/src/util/color.rs @@ -99,10 +99,10 @@ impl ValueEnum for ColorChoice { } fn to_possible_value(&self) -> Option { - Some(match self { - Self::Auto => PossibleValue::new("auto"), - Self::Always => PossibleValue::new("always"), - Self::Never => PossibleValue::new("never"), - }) + Some(PossibleValue::new(match self { + Self::Auto => "auto", + Self::Always => "always", + Self::Never => "never", + })) } } From 2fa5db904b2e8e3a192eb30a5080b3805214bfde Mon Sep 17 00:00:00 2001 From: adamnemecek Date: Mon, 30 Jun 2025 21:16:29 -0700 Subject: [PATCH 7/7] refactoring --- clap_builder/src/util/flat_map.rs | 8 ++++---- examples/typed-derive.rs | 16 ++++++++-------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/clap_builder/src/util/flat_map.rs b/clap_builder/src/util/flat_map.rs index 3dce096ef26..05eff2982be 100644 --- a/clap_builder/src/util/flat_map.rs +++ b/clap_builder/src/util/flat_map.rs @@ -154,8 +154,8 @@ pub(crate) enum Entry<'a, K, V> { impl<'a, K: 'a, V: 'a> Entry<'a, K, V> { pub(crate) fn or_insert(self, default: V) -> &'a mut V { match self { - Entry::Occupied(entry) => &mut entry.v.values[entry.index], - Entry::Vacant(entry) => { + Self::Occupied(entry) => &mut entry.v.values[entry.index], + Self::Vacant(entry) => { entry.v.keys.push(entry.key); entry.v.values.push(default); entry.v.values.last_mut().unwrap() @@ -165,8 +165,8 @@ impl<'a, K: 'a, V: 'a> Entry<'a, K, V> { pub(crate) fn or_insert_with V>(self, default: F) -> &'a mut V { match self { - Entry::Occupied(entry) => &mut entry.v.values[entry.index], - Entry::Vacant(entry) => { + Self::Occupied(entry) => &mut entry.v.values[entry.index], + Self::Vacant(entry) => { entry.v.keys.push(entry.key); entry.v.values.push(default()); entry.v.values.last_mut().unwrap() diff --git a/examples/typed-derive.rs b/examples/typed-derive.rs index 28f439b27bb..0666be6d884 100644 --- a/examples/typed-derive.rs +++ b/examples/typed-derive.rs @@ -84,14 +84,14 @@ mod foreign_crate { type Err = String; fn from_str(s: &str) -> Result { - match s { - "trace" => Ok(Self::Trace), - "debug" => Ok(Self::Debug), - "info" => Ok(Self::Info), - "warn" => Ok(Self::Warn), - "error" => Ok(Self::Error), - _ => Err(format!("Unknown log level: {s}")), - } + Ok(match s { + "trace" => Self::Trace, + "debug" => Self::Debug, + "info" => Self::Info, + "warn" => Self::Warn, + "error" => Self::Error, + _ => return Err(format!("Unknown log level: {s}")), + }) } } }