Update Rust crate clap_complete to v4
This PR contains the following updates:
| Package | Type | Update | Change |
|---|---|---|---|
| clap_complete | build-dependencies | major | 3.2.5 -> 4.0.3 |
Release Notes
clap-rs/clap
v4.0.3
Fixes
- (error) Quote literals consistently
- (error) Stylize escape (
--) suggestions - (error) Format help flag as a literal
v4.0.2
Fixes
- (parser)
SetFalseshould conflict with itself likeSetTrueandSet - (parser) Allow one-off overrides
v4.0.1
Fixes
- (derive) Allow
#[command(skip)]to also work with enum variants with a value
v4.0.0
Highlights
Arg::num_args(range)
Clap has had several ways for controlling how many values will be captured without always being clear on how they interacted, including
Arg::multiple_values(true)Arg::number_of_values(4)Arg::min_values(2)Arg::max_values(20)Arg::takes_value(true)
These have now all been collapsed into Arg::num_args which accepts both
single values and ranges of values. num_args controls how many raw arguments
on the command line will be captured as values per occurrence and independent
of value delimiters.
See Issue 2688 for more background.
Polishing Help
Clap strives to give a polished CLI experience out of the box with little
ceremony. With some feedback that has accumulated over time, we took this
release as an opportunity to re-evaluate our --help output to make sure it is
meeting that goal.
In doing this evaluation, we wanted to keep in mind:
- Whether other CLIs had ideas that make sense to apply
- Providing an experience that fits within the rest of applications and works across all shells
Before:
git
A fictional versioning CLI
USAGE:
git <SUBCOMMAND>
OPTIONS:
-h, --help Print help information
SUBCOMMANDS:
add adds things
clone Clones repos
help Print this message or the help of the given subcommand(s)
push pushes things
stash
After:
A fictional versioning CLI
Usage: git <COMMAND>
Commands:
clone Clones repos
push pushes things
add adds things
stash
help Print this message or the help of the given subcommand(s)
Options:
-h, --help Print help information
- name/version header was removed because we couldn't justify the space it occupied when
- Usage already includes the name
--versionis available for showing the same thing (if the program has a version set)
- Usage was dropped to one line to save space
- Focus is put on the subcommands
- Headings are now Title case
- The more general term "command" is used rather than being explicit about being "subcommands"
- The output is more dense with the expectation that it won't affect legibility but will allow more content
- We've moved to a more neutral palette for highlighting elements (not highlighted above)
In talking to users, we found some that liked clap's man-like experience.
When deviating from this, we are making the assumption that those are more
power users and that the majority of users wouldn't look as favorably on being
consistent with man.
See Issue 4132 for more background.
More Dynamicism
Clap's API has focused on &str for performance but this can make
dealing with owned data difficult, like #[arg(default_value_t)] generating a
String from the default value.
Additionally, to avoid ArgMatches from borrowing (and for some features we
decided to forgo), clap took the &str argument IDs and hashed them. This
prevented us from providing a usable API for iterating over existing arguments.
Now clap has switched to a string newtype that gives us the flexibility to
decide whether to use &'static str, Cow<'static, str> for fast dynamic behavior, or
Box<str> for dynamic behavior with small binary size.
As an extension of that work, you can now call ArgMatches::ids to iterate
over the arguments and groups that were found when parsing. The newtype Id
was used to prevent some classes of bugs and to make it easier to understand
when opaque Ids are used vs user-visible strings.
Clearing Out Deprecations
Instead of doing all development on clap 4.0.0, we implemented a lot of new features during clap 3's development, deprecating the old API while introducing the new API, including:
- Replacing the implicit behavior for args when parsing them with
ArgAction - Replacing various one-off forms of value validation with the
ValueParserAPI- Allowing derives to automatically do the right thing for
PathBuf(allowing invalid UTF-8)
- Allowing derives to automatically do the right thing for
- Replacing
AppSettingsandArgSettingsenums with getters/setters - Clarifying terms and making them more consistent
Migrating
Steps:
- Upgrade to v3 if you haven't already
- Add CLI tests (including example below),
-hand--helpoutput at a minimum (recommendation: trycmd for snapshot testing) - If using Builder API: Explicitly set the
arg.action(ArgAction::...)on each argument (StoreValuefor options andIncOccurrencesfor flags) - Run
cargo check --features clap/deprecatedand resolve all deprecation warnings - Upgrade to v4
- Update feature flags
- If
default-features = false, runcargo add clap -F help,usage,error-context - Run
cargo add clap -F wrap_helpunless you want to hard code line wraps
- Resolve compiler errors
- Resolve behavior changes (see "subtle changes" under BREAKING CHANGES)
- At your leisure: resolve new deprecation notices
Example test (derive):
#[derive(clap::Parser)]
struct Cli {
...
}
#[test]
fn verify_cli() {
use clap::CommandFactory;
Cli::command().debug_assert()
}
Example test (builder):
fn cli() -> clap::Command {
...
}
#[test]
fn verify_cli() {
cli().debug_assert();
}
Note: the idiomatic / recommended way of specifying different types of args in the Builder API has changed:
Before
.arg(Arg::new("flag").long("flag")) # --flag
.arg(Arg::new("option").long("option").takes_value(true)) # --option <option>
After:
.arg(Arg::new("flag").long("flag").action(ArgAction::SetTrue)) # --flag
.arg(Arg::new("option").long("option")) # --option <option>
In particular, num_args (the replacement for takes_value) will default appropriately
from the ArgAction and generally only needs to be set explicitly for the
other num_args use cases.
Breaking Changes
Subtle changes (i.e. compiler won't catch):
arg!now sets one of (#3795):ArgAction::SetTrue, requiringArgMatches::get_flaginstead ofArgMatches::is_presentArgAction::Count, requiringArgMatches::get_countinstead ofArgMatches::occurrences_ofArgAction::Set, requiringArgMatches::get_oneinstead ofArgMatches::value_ofArgAction::Append, requiringArgMatches::get_manyinstead ofArgMatches::values_of
ArgAction::Set,ArgAction::SetTrue, andArg::Action::SetFalsenow conflict by default to be likeArgAction::StoreValueandArgAction::IncOccurrences, requiringcmd.args_override_self(true)to override instead (#4261)- By default, an
Args default action isArgAction::Set, rather thanArgAction::IncOccurrenceto reduce confusing magic through consistency (#2687, #4032, see also #3977) mut_argcan no longer be used to customize help and version arguments, instead disable them (Command::disable_help_flag,Command::disable_version_flag) and provide your own (#4056)- Removed lifetimes from
Command,Arg,ArgGroup, andPossibleValue, assuming'static.stringfeature flag will enable support forStrings (#1041, #2150, #4223) arg!(--flag <value>)is now optional, instead of required. Add.required(true)at the end to restore the original behavior (#4206)- Added default feature flags,
help,usageanderror-context, requiring adding them back in ifdefault-features = false(#4236) - (parser) Always fill in
""argument for external subcommands to make it easier to distinguish them from built-in commands (#3263) - (parser) Short flags now have higher precedence than hyphen values with
Arg::allow_hyphen_values, to be consistent withCommand::allow_hyphen_values(#4187) - (parser)
Arg::value_terminatormust be its own argument on the CLI rather than being in a delimited list (#4025) - (help) Line wrapping of help is now behind the existing
wrap_helpfeature flag, either enable it or hard code your wraps (#4258) - (help) Make
DeriveDisplayOrderthe default and removed the setting. To sort help, setnext_display_order(None)(#2808) - (help) Subcommand display order respects
Command::next_display_orderinstead ofDeriveDisplayOrderand using its own initial display order value (#2808) - (help) Subcommands are now listed before arguments. To get the old behavior, see
Command::help_template(#4132) - (help) Help headings are now title cased, making any user-provided help headings inconsistent. To get the old behavior, see
Command::help_template,Arg::help_heading, andCommand::subcommand_help_heading(#4132) - (help) "Command" is used as the section heading for subcommands and
COMMANDfor the value name. To get the old behavior, seeCommand::subcommand_help_headingandArg::subcommand_value_name(#4132, #4155) - (help) Whitespace in help output is now trimmed to ensure consistency regardless of how well a template matches the users needs. (#4132, #4156)
- (help) name/version/author are removed by default from help output. To get the old behavior, see
Command::help_template. (#4132, #4160) - (help) Indentation for second-line usage changed. (#4132, #4188)
- (env) Parse
--helpand--versionlike anyArgAction::SetTrueflag (#3776) - (derive) Leave
Arg::idasverbatimcasing, requiring updating of string references to other args like inconflicts_withorrequires(#3282) - (derive) Doc comments for
ValueEnumvariants will now show up in--help(#3312) - (derive) When deriving
Args, andArgGroupis created using the type's name, reserving it for future use (#2621, #4209) - (derive)
next_help_headingcan now leak out of a#[clap(flatten)], like all other command settings (#4222)
Easier to catch changes:
- Looking up a group in
ArgMatchesnow returns the argIds, rather than the values to reduce overhead and offer more flexibility. (#4072) - Changed
Arg::number_of_values(average-across-occurrences) toArg::num_args(per-occurrence) (raw CLI args, not parsed values) (#2688, #4023) - Replace
Arg::min_values(across all occurrences) withArg::num_args(N..)(per occurrence) to reduce confusion over different value count APIs (#4023) - Replace
Arg::max_values(across all occurrences) withArg::num_args(1..=M)(per occurrence) to reduce confusion over different value count APIs (#4023) - Replace
Arg::multiple_values(true)withArg::num_args(1..)andArg::multiple_values(false)withArg::num_args(0)to reduce confusion over different value count APIs (#4023) - Replace
Arg::takes_value(true)withArg::num_args(1)andArg::takes_value(false)withArg::num_args(0)to reduce confusion over different value count APIs - Remove
Arg::require_value_delimiter, either users could useArg::value_delimiteror implement a custom parser withTypedValueParseras it was mostly to makemultiple_values(true)act likemultiple_values(false)and isn't needed anymore (#4026) Arg::new("help")andArg::new("version")no longer implicitly disable the built-in flags and be copied to all subcommands, instead disable the built-in flags (Command::disable_help_flag,Command::disable_version_flag) and mark the custom flags asglobal(true). (#4056)Arg::short('h')no longer implicitly disables the short flag for help, instead disable the built-in flags (Command::disable_help_flag,Command::disable_version_flag) provide your ownArg::new("help").long("help").action(ArgAction::Help).global(true). (#4056)ArgAction::SetTrueandArgAction::SetFalsenow prioritizeArg::default_missing_valueover their standard behavior (#4000)- Changed
Arg::requires_ifsandArg::default_value*_ifs*to taking anArgPredicate, removing ambiguity withNonewhen accepting owned and borrowed types (#4084) - Removed
PartialEqandEqfromCommandso we could change external subcommands to use aValueParser(#3990) - Various
Arg,Command, andArgGroupcalls were switched from accepting&[]to[]viaIntoIteratorto be more flexible (#4072) Arg::short_aliasesand other builder functions that took&[]need the&dropped (#4081)ErrorKindandResultmoved into theerrormoduleErrorKind::EmptyValuereplaced withErrorKind::InvalidValueto remove an unnecessary special case (#3676, #3968)ErrorKind::UnrecognizedSubcommandreplaced withErrorKind::InvalidSubcommandto remove an unnecessary special case (#3676)- Changed the default type of
allow_external_subcommandsfromStringtoOsStringas that is less likely to cause bugs in user applications (#3990) - (help)
Command::render_usagenow returns aStyledStr(#4248) - (derive) Changed the default for arguments from
parsetovalue_parser, removingparsesupport (#3827, #3981)#[clap(value_parser)]and#[clap(action)]are now redundant
- (derive)
subcommand_required(true).arg_required_else_help(true)is set instead ofSubcommandRequiredElseHelpto give more meaningful errors when subcommands are missing and to reduce redundancy (#3280) - (derive) Remove
arg_enumattribute in favor ofvalue_enumto match the new name (we didn't have support in v3 to mark it deprecated) (#4127) - (parser) Assert when the CLI looksup an unknown args when external subcommand support is enabled to help catch bugs (#3703)
- (assert) Sometimes
Arg::default_missing_valuedidn't requirenum_args(0..=N), now it does (#4023) - (assert) Leading dashes in
Arg::longare no longer allowed (#3691) - (assert) Disallow more
value_namesthannum_args(#2695) - (assert) Always enforce that version is specified when the
ArgAction::Versionis used - (assert) Add missing
#[track_caller]s to make it easier to debug asserts - (assert) Ensure
overrides_withIDs are valid - (assert) Ensure no self-
overrides_withnow that Actions replace it - (assert) Ensure subcommand names are not duplicated
- (assert) Assert on
mut_argreceiving an invalid arg ID ormut_subcommandreceiving an invalid command name
Compatibility
MSRV is now 1.60.0
Deprecated
Arg::use_value_delimiterin favor ofArg::value_delimiterto avoid having multiple ways of doing the same thingArg::requires_allin favor ofArg::requires_ifsnow that it takes anArgPredicateto avoid having multiple ways of doing the same thingArg::number_of_valuesin favor ofArg::num_argsto clarify semantic differencesdefault_value_os,default_values_os,default_value_if_os, anddefault_value_ifs_osas the non_osvariants now accept either astror anOsStr(#4141)Arg::env_osin favor ofArg::envCommand::dont_collapse_args_in_usageis now the default (#4151)Command::trailing_var_argin favor ofArg::trailing_var_argto make it clearer which arg it is meant to apply to (#4187)Command::allow_hyphen_valuesin favor ofArg::allow_hyphen_valuesto make it clearer which arg it is meant to apply to (#4187)Command::allow_negative_numbersin favor ofArg::allow_negative_numbersto make it clearer which arg it is meant to apply to (#4187)- (help) Deprecated
Command::write_helpandCommand::write_long_helpin favor ofCommand::render_helpandCommand::render_long_help(#4248) - (derive)
structoptandclapattributes in favor of the more specificcommand,arg, andvalueto open the door for more features and clarify relationship to the builder (#1807, #4180) - (derive)
#[clap(value_parser)]and#[clap(action)]defaulted attributes (its the default) (#3976)
Behavior Changes
- (help) With
wrap_helpfeature, if the terminal size cannot be determined,LINESandCOLUMNSvariables are used (#4186)
Features
Arg::num_argsnow accepts ranges, allowing setting both the minimum and maximum number of values per occurrence (#2688, #4023)- Allow non-bool
value_parsers forArgAction::SetTrue/ArgAction::SetFalse(#4092) - Add
From<&OsStr>,From<OsString>,From<&str>, andFrom<String>tovalue_parser!(#4257) - Allow resetting most builder methods
- Can now pass runtime generated data to
Command,Arg,ArgGroup,PossibleValue, etc without managing lifetimes with thestringfeature flag (#2150, #4223) - New default
error-context,helpandusagefeature flags that can be turned off for smaller binaries (#4236) - Added
StyledStr::ansi()toDisplaywith ANSI escape codes (#4248) - (error)
Error::applyfor changing the formatter for dropping binary size (#4111) - (error)
Error::renderfor formatting the error into aStyledStr - (help) Show
PossibleValue::helpin long help (--help) (#3312) - (help) New
{tab}variable forCommand::help_template(#4161) - (help)
Command::render_helpandCommand::render_long_helpfor formatting the error into aStyledStr(#3873, #4248) - (help)
Command::render_usagenow returns aStyledStr(#4248)
Fixes
- Verify
requiredis not used with conditional required settings (#3660) - Replaced
cmd.allow_invalid_for_utf8_external_subcommandswithcmd.external_subcommand_value_parser(#3733) Arg::default_missing_valuenow applies per occurrence rather than if a value is missing across all occurrences (#3998)arg!(--long [value])to accept0..=1per occurrence rather than across all occurrences, making it safe to use withArgAction::Append(#4001)- Allow
OsStrs forArg::{required_if_eq,required_if_eq_any,required_if_eq_all}(#4084) - (help) With
wrap_helpfeature, if the terminal size cannot be determined,LINESandCOLUMNSvariables are used (#4186) - (help) Use
Command::display_namein the help title rather thanCommand::bin_name - (help) Show when a flag is
ArgAction::Countby adding an...(#4003) - (help) Use a more neutral palette for coloring (#4132, #4117)
- (help) Don't rely on ALL CAPS for help headers (#4132, #4123)
- (help) List subcommands first, focusing the emphasis on them (#4132, #4125)
- (help) Do not include global args in
cmd help help(#4131) - (help) Use
[positional]in list when relevant (#4144) - (help) Show all
[positional]in usage (#4151) - (help) Polish up subcommands by referring to them as commands (#4132, #4155)
- (help) Trim extra whitespace to avoid artifacts from different uses of templates (#4132, #4156)
- (help) Hint to the user the difference between
-h/--helpwhen applicable (#4132, #4159) - (help) Shorten help by eliding name/version/author (#4132, #4160)
- (help) When short help is long enough to activate
next_line_help, don't add blank lines (#4132, #4190) - (help) Make help output more dense (reducing horizontal whitespace) (#4132, #4192)
- (help) Separate subcommand flags with "," like option flags (#4232, #4235)
- (help) Quote the suggested help flag (#4220)
- (version) Use
Command::display_namerather thanCommand::bin_name(#3966) - (parser) Always fill in
""argument for external subcommands (#3263) - (parser) Short flags now have higher precedence than hyphen values with
Arg::allow_hyphen_values, likeCommand::allow_hyphen_values(#4187) - (parser) Prefer
InvalidSubcommandoverUnknownArgumentin more cases (#4219) - (derive) Detect escaped external subcommands that look like built-in subcommands (#3703)
- (derive) Leave
Arg::idasverbatimcasing (#3282) - (derive) Default to
#[clap(value_parser, action)]instead of#[clap(parse)](#3827)
Configuration
📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
- [ ] If you want to rebase/retry this PR, click this checkbox.
This PR has been generated by Mend Renovate. View repository job log here.