aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndroid Build Coastguard Worker <android-build-coastguard-worker@google.com>2023-07-07 04:53:37 +0000
committerAndroid Build Coastguard Worker <android-build-coastguard-worker@google.com>2023-07-07 04:53:37 +0000
commitbec330ecdf7632a6da326020ae89205a32430d07 (patch)
tree023dd32e3b28457d86f866764c19e619196c684f
parent24d52563a8c6f76af650a7cfa02934b69749444b (diff)
parent46c83e0266cf762268a276eba75d7871f040a945 (diff)
downloadclap-aml_ips_341611000.tar.gz
Snap for 10453563 from 46c83e0266cf762268a276eba75d7871f040a945 to mainline-ipsec-releaseaml_ips_341611000aml_ips_341510000aml_ips_340914280aml_ips_340914200aml_ips_340914000
Change-Id: I84c122c7e01de9938b279fa49bb0974a1eb56719
-rw-r--r--.azure-pipelines.yml61
-rw-r--r--.cargo_vcs_info.json7
-rw-r--r--.clog.toml14
-rw-r--r--.github/CONTRIBUTING.md115
-rw-r--r--.github/ISSUE_TEMPLATE.md46
-rw-r--r--.travis.yml66
-rw-r--r--3.2.23/.cargo_vcs_info.json6
-rw-r--r--3.2.23/Android.bp63
-rw-r--r--3.2.23/Cargo.toml470
l---------3.2.23/LICENSE1
-rw-r--r--3.2.23/LICENSE-APACHE201
-rw-r--r--3.2.23/LICENSE-MIT21
-rw-r--r--3.2.23/METADATA20
-rw-r--r--3.2.23/MODULE_LICENSE_APACHE2 (renamed from MODULE_LICENSE_MIT)0
-rw-r--r--3.2.23/OWNERS1
-rw-r--r--3.2.23/README.md43
-rw-r--r--3.2.23/cargo2android.json7
-rw-r--r--3.2.23/examples/cargo-example-derive.md43
-rw-r--r--3.2.23/examples/cargo-example-derive.rs20
-rw-r--r--3.2.23/examples/cargo-example.md43
-rw-r--r--3.2.23/examples/cargo-example.rs19
-rw-r--r--3.2.23/examples/demo.md19
-rw-r--r--3.2.23/examples/demo.rs22
-rw-r--r--3.2.23/examples/derive_ref/augment_args.rs27
-rw-r--r--3.2.23/examples/derive_ref/augment_subcommands.rs21
-rw-r--r--3.2.23/examples/derive_ref/custom-bool.md47
-rw-r--r--3.2.23/examples/derive_ref/custom-bool.rs32
-rw-r--r--3.2.23/examples/derive_ref/flatten_hand_args.rs81
-rw-r--r--3.2.23/examples/derive_ref/hand_subcommand.rs81
-rw-r--r--3.2.23/examples/derive_ref/interop_tests.md256
-rw-r--r--3.2.23/examples/escaped-positional-derive.md63
-rw-r--r--3.2.23/examples/escaped-positional-derive.rs25
-rw-r--r--3.2.23/examples/escaped-positional.md63
-rw-r--r--3.2.23/examples/escaped-positional.rs36
-rw-r--r--3.2.23/examples/git-derive.md138
-rw-r--r--3.2.23/examples/git-derive.rs105
-rw-r--r--3.2.23/examples/git.md136
-rw-r--r--3.2.23/examples/git.rs101
-rw-r--r--3.2.23/examples/multicall-busybox.md42
-rw-r--r--3.2.23/examples/multicall-busybox.rs48
-rw-r--r--3.2.23/examples/multicall-hostname.md10
-rw-r--r--3.2.23/examples/multicall-hostname.rs17
-rw-r--r--3.2.23/examples/pacman.md85
-rw-r--r--3.2.23/examples/pacman.rs111
-rw-r--r--3.2.23/examples/repl.rs92
-rw-r--r--3.2.23/examples/tutorial_builder/01_quick.md37
-rw-r--r--3.2.23/examples/tutorial_builder/01_quick.rs63
-rw-r--r--3.2.23/examples/tutorial_builder/02_app_settings.md19
-rw-r--r--3.2.23/examples/tutorial_builder/02_app_settings.rs19
-rw-r--r--3.2.23/examples/tutorial_builder/02_apps.md19
-rw-r--r--3.2.23/examples/tutorial_builder/02_apps.rs20
-rw-r--r--3.2.23/examples/tutorial_builder/02_crate.md18
-rw-r--r--3.2.23/examples/tutorial_builder/02_crate.rs18
-rw-r--r--3.2.23/examples/tutorial_builder/03_01_flag_bool.md23
-rw-r--r--3.2.23/examples/tutorial_builder/03_01_flag_bool.rs14
-rw-r--r--3.2.23/examples/tutorial_builder/03_01_flag_count.md23
-rw-r--r--3.2.23/examples/tutorial_builder/03_01_flag_count.rs9
-rw-r--r--3.2.23/examples/tutorial_builder/03_02_option.md32
-rw-r--r--3.2.23/examples/tutorial_builder/03_02_option.rs9
-rw-r--r--3.2.23/examples/tutorial_builder/03_03_positional.md22
-rw-r--r--3.2.23/examples/tutorial_builder/03_03_positional.rs9
-rw-r--r--3.2.23/examples/tutorial_builder/03_04_subcommands.md64
-rw-r--r--3.2.23/examples/tutorial_builder/03_04_subcommands.rs22
-rw-r--r--3.2.23/examples/tutorial_builder/03_05_default_values.md22
-rw-r--r--3.2.23/examples/tutorial_builder/03_05_default_values.rs14
-rw-r--r--3.2.23/examples/tutorial_builder/04_01_enum.md29
-rw-r--r--3.2.23/examples/tutorial_builder/04_01_enum.rs66
-rw-r--r--3.2.23/examples/tutorial_builder/04_01_possible.md29
-rw-r--r--3.2.23/examples/tutorial_builder/04_01_possible.rs26
-rw-r--r--3.2.23/examples/tutorial_builder/04_02_parse.md31
-rw-r--r--3.2.23/examples/tutorial_builder/04_02_parse.rs17
-rw-r--r--3.2.23/examples/tutorial_builder/04_02_validate.md31
-rw-r--r--3.2.23/examples/tutorial_builder/04_02_validate.rs36
-rw-r--r--3.2.23/examples/tutorial_builder/04_03_relations.md58
-rw-r--r--3.2.23/examples/tutorial_builder/04_03_relations.rs80
-rw-r--r--3.2.23/examples/tutorial_builder/04_04_custom.md57
-rw-r--r--3.2.23/examples/tutorial_builder/04_04_custom.rs88
-rw-r--r--3.2.23/examples/tutorial_builder/05_01_assert.rs25
-rw-r--r--3.2.23/examples/tutorial_derive/01_quick.md37
-rw-r--r--3.2.23/examples/tutorial_derive/01_quick.rs69
-rw-r--r--3.2.23/examples/tutorial_derive/02_app_settings.md19
-rw-r--r--3.2.23/examples/tutorial_derive/02_app_settings.rs19
-rw-r--r--3.2.23/examples/tutorial_derive/02_apps.md19
-rw-r--r--3.2.23/examples/tutorial_derive/02_apps.rs20
-rw-r--r--3.2.23/examples/tutorial_derive/02_crate.md18
-rw-r--r--3.2.23/examples/tutorial_derive/02_crate.rs17
-rw-r--r--3.2.23/examples/tutorial_derive/03_01_flag_bool.md23
-rw-r--r--3.2.23/examples/tutorial_derive/03_01_flag_bool.rs14
-rw-r--r--3.2.23/examples/tutorial_derive/03_01_flag_count.md23
-rw-r--r--3.2.23/examples/tutorial_derive/03_01_flag_count.rs14
-rw-r--r--3.2.23/examples/tutorial_derive/03_02_option.md32
-rw-r--r--3.2.23/examples/tutorial_derive/03_02_option.rs14
-rw-r--r--3.2.23/examples/tutorial_derive/03_03_positional.md22
-rw-r--r--3.2.23/examples/tutorial_derive/03_03_positional.rs14
-rw-r--r--3.2.23/examples/tutorial_derive/03_04_subcommands.md64
-rw-r--r--3.2.23/examples/tutorial_derive/03_04_subcommands.rs30
-rw-r--r--3.2.23/examples/tutorial_derive/03_04_subcommands_alt.rs33
-rw-r--r--3.2.23/examples/tutorial_derive/03_05_default_values.md22
-rw-r--r--3.2.23/examples/tutorial_derive/03_05_default_values.rs14
-rw-r--r--3.2.23/examples/tutorial_derive/04_01_enum.md29
-rw-r--r--3.2.23/examples/tutorial_derive/04_01_enum.rs28
-rw-r--r--3.2.23/examples/tutorial_derive/04_02_parse.md31
-rw-r--r--3.2.23/examples/tutorial_derive/04_02_parse.rs15
-rw-r--r--3.2.23/examples/tutorial_derive/04_02_validate.md31
-rw-r--r--3.2.23/examples/tutorial_derive/04_02_validate.rs34
-rw-r--r--3.2.23/examples/tutorial_derive/04_03_relations.md58
-rw-r--r--3.2.23/examples/tutorial_derive/04_03_relations.rs72
-rw-r--r--3.2.23/examples/tutorial_derive/04_04_custom.md57
-rw-r--r--3.2.23/examples/tutorial_derive/04_04_custom.rs93
-rw-r--r--3.2.23/examples/tutorial_derive/05_01_assert.rs21
-rw-r--r--3.2.23/examples/typed-derive.md84
-rw-r--r--3.2.23/examples/typed-derive.rs44
-rw-r--r--3.2.23/patches/Android.bp.diff35
-rw-r--r--3.2.23/src/_cookbook/cargo_example.rs7
-rw-r--r--3.2.23/src/_cookbook/cargo_example_derive0
-rw-r--r--3.2.23/src/_cookbook/cargo_example_derive.rs7
-rw-r--r--3.2.23/src/_cookbook/escaped_positional.rs7
-rw-r--r--3.2.23/src/_cookbook/escaped_positional_derive.rs7
-rw-r--r--3.2.23/src/_cookbook/git.rs7
-rw-r--r--3.2.23/src/_cookbook/git_derive.rs7
-rw-r--r--3.2.23/src/_cookbook/mod.rs55
-rw-r--r--3.2.23/src/_cookbook/multicall_busybox.rs7
-rw-r--r--3.2.23/src/_cookbook/multicall_hostname.rs7
-rw-r--r--3.2.23/src/_cookbook/pacman.rs7
-rw-r--r--3.2.23/src/_cookbook/repl.rs5
-rw-r--r--3.2.23/src/_cookbook/typed_derive.rs7
-rw-r--r--3.2.23/src/_derive/_tutorial.rs205
-rw-r--r--3.2.23/src/_derive/mod.rs510
-rw-r--r--3.2.23/src/_faq.rs95
-rw-r--r--3.2.23/src/_features.rs27
-rw-r--r--3.2.23/src/_tutorial.rs204
-rw-r--r--3.2.23/src/bin/stdio-fixture.rs14
-rw-r--r--3.2.23/src/builder/action.rs345
-rw-r--r--3.2.23/src/builder/app_settings.rs1308
-rw-r--r--3.2.23/src/builder/arg.rs5618
-rw-r--r--3.2.23/src/builder/arg_group.rs641
-rw-r--r--3.2.23/src/builder/arg_predicate.rs14
-rw-r--r--3.2.23/src/builder/arg_settings.rs684
-rw-r--r--3.2.23/src/builder/command.rs5201
-rw-r--r--3.2.23/src/builder/debug_asserts.rs851
-rw-r--r--3.2.23/src/builder/macros.rs (renamed from src/args/macros.rs)81
-rw-r--r--3.2.23/src/builder/mod.rs61
-rw-r--r--3.2.23/src/builder/possible_value.rs259
-rw-r--r--3.2.23/src/builder/regex.rs88
-rw-r--r--3.2.23/src/builder/tests.rs56
-rw-r--r--3.2.23/src/builder/usage_parser.rs1277
-rw-r--r--3.2.23/src/builder/value_hint.rs95
-rw-r--r--3.2.23/src/builder/value_parser.rs2186
-rw-r--r--3.2.23/src/derive.rs577
-rw-r--r--3.2.23/src/error/context.rs55
-rw-r--r--3.2.23/src/error/kind.rs440
-rw-r--r--3.2.23/src/error/mod.rs1153
-rw-r--r--3.2.23/src/lib.rs232
-rw-r--r--3.2.23/src/macros.rs1058
-rw-r--r--3.2.23/src/mkeymap.rs193
-rw-r--r--3.2.23/src/output/fmt.rs158
-rw-r--r--3.2.23/src/output/help.rs1176
-rw-r--r--3.2.23/src/output/mod.rs7
-rw-r--r--3.2.23/src/output/usage.rs449
-rw-r--r--3.2.23/src/parser/arg_matcher.rs280
-rw-r--r--3.2.23/src/parser/error.rs67
-rw-r--r--3.2.23/src/parser/features/mod.rs1
-rw-r--r--3.2.23/src/parser/features/suggestions.rs105
-rw-r--r--3.2.23/src/parser/matches/any_value.rs112
-rw-r--r--3.2.23/src/parser/matches/arg_matches.rs1980
-rw-r--r--3.2.23/src/parser/matches/matched_arg.rs240
-rw-r--r--3.2.23/src/parser/matches/mod.rs17
-rw-r--r--3.2.23/src/parser/matches/value_source.rs11
-rw-r--r--3.2.23/src/parser/mod.rs27
-rw-r--r--3.2.23/src/parser/parser.rs1729
-rw-r--r--3.2.23/src/parser/validator.rs692
-rw-r--r--3.2.23/src/util/color.rs62
-rw-r--r--3.2.23/src/util/fnv.rs46
-rw-r--r--3.2.23/src/util/graph.rs49
-rw-r--r--3.2.23/src/util/id.rs92
-rw-r--r--3.2.23/src/util/mod.rs40
-rw-r--r--3.2.23/src/util/str_to_bool.rs21
-rw-r--r--Android.bp55
-rw-r--r--CHANGELOG.md2890
-rw-r--r--CONTRIBUTORS.md91
-rw-r--r--Cargo.toml533
-rw-r--r--Cargo.toml.orig384
l---------LICENSE2
-rw-r--r--LICENSE-APACHE201
-rw-r--r--LICENSE-MIT2
-rw-r--r--METADATA14
-rw-r--r--MODULE_LICENSE_APACHE20
l---------NOTICE1
-rw-r--r--OWNERS2
-rw-r--r--README.md553
-rw-r--r--SPONSORS.md17
-rw-r--r--TEST_MAPPING48
-rw-r--r--cargo2android.json9
-rw-r--r--clap-test.rs86
-rw-r--r--examples/README.md16
-rw-r--r--examples/cargo-example-derive.md38
-rw-r--r--examples/cargo-example-derive.rs20
-rw-r--r--examples/cargo-example.md38
-rw-r--r--examples/cargo-example.rs18
-rw-r--r--examples/demo.md17
-rw-r--r--examples/demo.rs22
-rw-r--r--examples/derive_ref/augment_args.rs27
-rw-r--r--examples/derive_ref/augment_subcommands.rs21
-rw-r--r--examples/derive_ref/flatten_hand_args.rs91
-rw-r--r--examples/derive_ref/hand_subcommand.rs79
-rw-r--r--examples/derive_ref/interop_tests.md248
-rw-r--r--examples/escaped-positional-derive.md60
-rw-r--r--examples/escaped-positional-derive.rs25
-rw-r--r--examples/escaped-positional.md60
-rw-r--r--examples/escaped-positional.rs32
-rw-r--r--examples/find.md45
-rw-r--r--examples/find.rs99
-rw-r--r--examples/git-derive.md159
-rw-r--r--examples/git-derive.rs164
-rw-r--r--examples/git.md157
-rw-r--r--examples/git.rs137
-rw-r--r--examples/multicall-busybox.md39
-rw-r--r--examples/multicall-busybox.rs47
-rw-r--r--examples/multicall-hostname.md10
-rw-r--r--examples/multicall-hostname.rs17
-rw-r--r--examples/pacman.md79
-rw-r--r--examples/pacman.rs111
-rw-r--r--examples/repl.rs92
-rw-r--r--examples/tutorial_builder/01_quick.md35
-rw-r--r--examples/tutorial_builder/01_quick.rs60
-rw-r--r--examples/tutorial_builder/02_app_settings.md17
-rw-r--r--examples/tutorial_builder/02_app_settings.rs18
-rw-r--r--examples/tutorial_builder/02_apps.md16
-rw-r--r--examples/tutorial_builder/02_apps.rs20
-rw-r--r--examples/tutorial_builder/02_crate.md16
-rw-r--r--examples/tutorial_builder/02_crate.rs18
-rw-r--r--examples/tutorial_builder/03_01_flag_bool.md26
-rw-r--r--examples/tutorial_builder/03_01_flag_bool.rs14
-rw-r--r--examples/tutorial_builder/03_01_flag_count.md21
-rw-r--r--examples/tutorial_builder/03_01_flag_count.rs14
-rw-r--r--examples/tutorial_builder/03_02_option.md30
-rw-r--r--examples/tutorial_builder/03_02_option.rs9
-rw-r--r--examples/tutorial_builder/03_02_option_mult.md30
-rw-r--r--examples/tutorial_builder/03_02_option_mult.rs14
-rw-r--r--examples/tutorial_builder/03_03_positional.md20
-rw-r--r--examples/tutorial_builder/03_03_positional.rs9
-rw-r--r--examples/tutorial_builder/03_03_positional_mult.md23
-rw-r--r--examples/tutorial_builder/03_03_positional_mult.rs15
-rw-r--r--examples/tutorial_builder/03_04_subcommands.md58
-rw-r--r--examples/tutorial_builder/03_04_subcommands.rs22
-rw-r--r--examples/tutorial_builder/03_05_default_values.md20
-rw-r--r--examples/tutorial_builder/03_05_default_values.rs18
-rw-r--r--examples/tutorial_builder/04_01_enum.md47
-rw-r--r--examples/tutorial_builder/04_01_enum.rs66
-rw-r--r--examples/tutorial_builder/04_01_possible.md27
-rw-r--r--examples/tutorial_builder/04_01_possible.rs26
-rw-r--r--examples/tutorial_builder/04_02_parse.md29
-rw-r--r--examples/tutorial_builder/04_02_parse.rs17
-rw-r--r--examples/tutorial_builder/04_02_validate.md29
-rw-r--r--examples/tutorial_builder/04_02_validate.rs36
-rw-r--r--examples/tutorial_builder/04_03_relations.md53
-rw-r--r--examples/tutorial_builder/04_03_relations.rs78
-rw-r--r--examples/tutorial_builder/04_04_custom.md52
-rw-r--r--examples/tutorial_builder/04_04_custom.rs84
-rw-r--r--examples/tutorial_builder/05_01_assert.rs25
-rw-r--r--examples/tutorial_derive/01_quick.md35
-rw-r--r--examples/tutorial_derive/01_quick.rs68
-rw-r--r--examples/tutorial_derive/02_app_settings.md17
-rw-r--r--examples/tutorial_derive/02_app_settings.rs18
-rw-r--r--examples/tutorial_derive/02_apps.md16
-rw-r--r--examples/tutorial_derive/02_apps.rs20
-rw-r--r--examples/tutorial_derive/02_crate.md16
-rw-r--r--examples/tutorial_derive/02_crate.rs17
-rw-r--r--examples/tutorial_derive/03_01_flag_bool.md26
-rw-r--r--examples/tutorial_derive/03_01_flag_bool.rs14
-rw-r--r--examples/tutorial_derive/03_01_flag_count.md21
-rw-r--r--examples/tutorial_derive/03_01_flag_count.rs14
-rw-r--r--examples/tutorial_derive/03_02_option.md30
-rw-r--r--examples/tutorial_derive/03_02_option.rs14
-rw-r--r--examples/tutorial_derive/03_02_option_mult.md30
-rw-r--r--examples/tutorial_derive/03_02_option_mult.rs14
-rw-r--r--examples/tutorial_derive/03_03_positional.md20
-rw-r--r--examples/tutorial_derive/03_03_positional.rs13
-rw-r--r--examples/tutorial_derive/03_03_positional_mult.md23
-rw-r--r--examples/tutorial_derive/03_03_positional_mult.rs13
-rw-r--r--examples/tutorial_derive/03_04_subcommands.md58
-rw-r--r--examples/tutorial_derive/03_04_subcommands.rs27
-rw-r--r--examples/tutorial_derive/03_04_subcommands_alt.rs32
-rw-r--r--examples/tutorial_derive/03_05_default_values.md20
-rw-r--r--examples/tutorial_derive/03_05_default_values.rs14
-rw-r--r--examples/tutorial_derive/04_01_enum.md47
-rw-r--r--examples/tutorial_derive/04_01_enum.rs32
-rw-r--r--examples/tutorial_derive/04_02_parse.md29
-rw-r--r--examples/tutorial_derive/04_02_parse.rs15
-rw-r--r--examples/tutorial_derive/04_02_validate.md29
-rw-r--r--examples/tutorial_derive/04_02_validate.rs34
-rw-r--r--examples/tutorial_derive/04_03_relations.md53
-rw-r--r--examples/tutorial_derive/04_03_relations.rs72
-rw-r--r--examples/tutorial_derive/04_04_custom.md52
-rw-r--r--examples/tutorial_derive/04_04_custom.rs91
-rw-r--r--examples/tutorial_derive/05_01_assert.rs20
-rw-r--r--examples/typed-derive.md131
-rw-r--r--examples/typed-derive.rs102
-rw-r--r--justfile39
-rw-r--r--patches/Android.bp.diff22
-rw-r--r--src/_cookbook/cargo_example.rs7
-rw-r--r--src/_cookbook/cargo_example_derive.rs7
-rw-r--r--src/_cookbook/escaped_positional.rs7
-rw-r--r--src/_cookbook/escaped_positional_derive.rs7
-rw-r--r--src/_cookbook/find.rs7
-rw-r--r--src/_cookbook/git.rs7
-rw-r--r--src/_cookbook/git_derive.rs7
-rw-r--r--src/_cookbook/mod.rs61
-rw-r--r--src/_cookbook/multicall_busybox.rs7
-rw-r--r--src/_cookbook/multicall_hostname.rs7
-rw-r--r--src/_cookbook/pacman.rs7
-rw-r--r--src/_cookbook/repl.rs5
-rw-r--r--src/_cookbook/typed_derive.rs7
-rw-r--r--src/_derive/_tutorial.rs226
-rw-r--r--src/_derive/mod.rs480
-rw-r--r--src/_faq.rs95
-rw-r--r--src/_features.rs29
-rw-r--r--src/_tutorial.rs222
-rw-r--r--src/app/help.rs1034
-rw-r--r--src/app/meta.rs35
-rw-r--r--src/app/mod.rs1904
-rw-r--r--src/app/parser.rs2241
-rw-r--r--src/app/settings.rs1192
-rw-r--r--src/app/usage.rs495
-rw-r--r--src/app/validator.rs583
-rw-r--r--src/args/any_arg.rs131
-rw-r--r--src/args/arg.rs3959
-rw-r--r--src/args/arg_builder/base.rs48
-rw-r--r--src/args/arg_builder/flag.rs211
-rw-r--r--src/args/arg_builder/mod.rs13
-rw-r--r--src/args/arg_builder/option.rs290
-rw-r--r--src/args/arg_builder/positional.rs280
-rw-r--r--src/args/arg_builder/switched.rs40
-rw-r--r--src/args/arg_builder/valued.rs67
-rw-r--r--src/args/arg_matcher.rs269
-rw-r--r--src/args/arg_matches.rs998
-rw-r--r--src/args/group.rs638
-rw-r--r--src/args/matched_arg.rs29
-rw-r--r--src/args/mod.rs21
-rw-r--r--src/args/settings.rs237
-rw-r--r--src/args/subcommand.rs72
-rw-r--r--src/bin/stdio-fixture.rs15
-rw-r--r--src/builder/action.rs344
-rw-r--r--src/builder/app_settings.rs172
-rw-r--r--src/builder/arg.rs4648
-rw-r--r--src/builder/arg_group.rs596
-rw-r--r--src/builder/arg_predicate.rs19
-rw-r--r--src/builder/arg_settings.rs145
-rw-r--r--src/builder/command.rs4705
-rw-r--r--src/builder/debug_asserts.rs876
-rw-r--r--src/builder/mod.rs60
-rw-r--r--src/builder/os_str.rs336
-rw-r--r--src/builder/possible_value.rs234
-rw-r--r--src/builder/range.rs283
-rw-r--r--src/builder/resettable.rs211
-rw-r--r--src/builder/str.rs310
-rw-r--r--src/builder/styled_str.rs349
-rw-r--r--src/builder/tests.rs56
-rw-r--r--src/builder/value_hint.rs95
-rw-r--r--src/builder/value_parser.rs2435
-rw-r--r--src/completions/bash.rs222
-rw-r--r--src/completions/elvish.rs128
-rw-r--r--src/completions/fish.rs103
-rw-r--r--src/completions/macros.rs28
-rw-r--r--src/completions/mod.rs182
-rw-r--r--src/completions/powershell.rs166
-rw-r--r--src/completions/shell.rs56
-rw-r--r--src/completions/zsh.rs485
-rw-r--r--src/derive.rs471
-rw-r--r--src/error/context.rs114
-rw-r--r--src/error/format.rs468
-rw-r--r--src/error/kind.rs348
-rw-r--r--src/error/mod.rs876
-rw-r--r--src/errors.rs918
-rw-r--r--src/fmt.rs194
-rw-r--r--src/lib.rs714
-rw-r--r--src/macros.rs1504
-rw-r--r--src/map.rs88
-rw-r--r--src/mkeymap.rs177
-rw-r--r--src/osstringext.rs200
-rw-r--r--src/output/fmt.rs90
-rw-r--r--src/output/help.rs43
-rw-r--r--src/output/help_template.rs1065
-rw-r--r--src/output/mod.rs23
-rw-r--r--src/output/textwrap/core.rs158
-rw-r--r--src/output/textwrap/mod.rs122
-rw-r--r--src/output/textwrap/word_separators.rs91
-rw-r--r--src/output/textwrap/wrap_algorithms.rs44
-rw-r--r--src/output/usage.rs441
-rw-r--r--src/parser/arg_matcher.rs248
-rw-r--r--src/parser/error.rs61
-rw-r--r--src/parser/features/mod.rs1
-rw-r--r--src/parser/features/suggestions.rs167
-rw-r--r--src/parser/matches/any_value.rs112
-rw-r--r--src/parser/matches/arg_matches.rs1967
-rw-r--r--src/parser/matches/matched_arg.rs225
-rw-r--r--src/parser/matches/mod.rs16
-rw-r--r--src/parser/matches/value_source.rs17
-rw-r--r--src/parser/mod.rs27
-rw-r--r--src/parser/parser.rs1642
-rw-r--r--src/parser/validator.rs562
-rw-r--r--src/strext.rs16
-rw-r--r--src/suggestions.rs147
-rw-r--r--src/usage_parser.rs1358
-rw-r--r--src/util/color.rs103
-rw-r--r--src/util/flat_map.rs254
-rw-r--r--src/util/flat_set.rs107
-rw-r--r--src/util/graph.rs49
-rw-r--r--src/util/id.rs164
-rw-r--r--src/util/mod.rs44
-rw-r--r--src/util/str_to_bool.rs21
411 files changed, 69414 insertions, 24772 deletions
diff --git a/.azure-pipelines.yml b/.azure-pipelines.yml
deleted file mode 100644
index 464b792..0000000
--- a/.azure-pipelines.yml
+++ /dev/null
@@ -1,61 +0,0 @@
-name: $(Build.BuildId)
-trigger:
- # Always build master
- - v2-master
-pr:
- # Enable building pull requests.
- - v2-master
-stages:
- - stage: Testing
- jobs:
- - job:
- variables:
- rust: 1.36.0
- strategy:
- matrix:
- Windows 32-bit (MSVC):
- image: vs2017-win2016
- target: i686-pc-windows-msvc
- Windows 64-bit (MSVC):
- image: vs2017-win2016
- target: x86_64-pc-windows-msvc
- Windows 32-bit (MinGW):
- image: vs2017-win2016
- target: i686-pc-windows-gnu
- Windows 64-bit (MinGW):
- image: vs2017-win2016
- target: x86_64-pc-windows-gnu
- pool:
- vmImage: $(image)
- steps:
- - checkout: self
- fetchDepth: 1
- path: clap
- displayName: Checkout repository
- - task: Cache@2
- inputs:
- key: cargo | "$(rust)" | $(target) | Cargo.toml
- path: C:\Rust\.cargo
- displayName: Caching cargo
- - task: Cache@2
- inputs:
- key: compiled | "$(rust)" | $(target) | Cargo.toml
- path: target
- displayName: Caching compiled
- - script: rustup default $(rust)-$(target)
- displayName: Install rust
- - script: cargo test --no-default-features
- displayName: Test without default features
- env:
- RUST_BACKTRACE: full
- - script: cargo test --features "yaml unstable"
- displayName: Test with most features
- env:
- RUST_BACKTRACE: full
- - script: |
- rmdir /Q /S C:\Rust\.cargo\registry\src
- rmdir /Q /S target\.rustc_info.json
- rmdir /Q /S target\debug\examples
- rmdir /Q /S target\debug\incremental
- displayName: Cleaning for cache
- continueOnError: true
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
index ff4eb04..382d047 100644
--- a/.cargo_vcs_info.json
+++ b/.cargo_vcs_info.json
@@ -1,5 +1,6 @@
{
"git": {
- "sha1": "33bebeda52b52c6f643b4ed6fa880671ba0ab80a"
- }
-}
+ "sha1": "f931de694a5478d7e4bd424613e6699f7d4f4e9f"
+ },
+ "path_in_vcs": ""
+} \ No newline at end of file
diff --git a/.clog.toml b/.clog.toml
deleted file mode 100644
index 301dd92..0000000
--- a/.clog.toml
+++ /dev/null
@@ -1,14 +0,0 @@
-[clog]
-repository = "https://github.com/kbknapp/clap-rs"
-outfile = "CHANGELOG.md"
-from-latest-tag = true
-
-[sections]
-Performance = ["perf"]
-Improvements = ["impr", "im", "imp"]
-Documentation = ["docs"]
-Deprecations = ["depr"]
-Examples = ["examples"]
-"New Settings" = ["setting", "settings"]
-"API Additions" = ["add", "api"]
-"New Sponsor" = ["sponsor"]
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
deleted file mode 100644
index 2c6f752..0000000
--- a/.github/CONTRIBUTING.md
+++ /dev/null
@@ -1,115 +0,0 @@
-# How to Contribute
-
-Contributions are always welcome! And there is a multitude of ways in which you can help depending on what you like to do, or are good at. Anything from documentation, code cleanup, issue completion, new features, you name it, even filing issues is contributing and greatly appreciated!
-
-Another really great way to help is if you find an interesting, or helpful way in which to use `clap`. You can either add it to the [examples/](examples) directory, or file an issue and tell me. I'm all about giving credit where credit is due :)
-
-### Testing Code
-
-To test with all features both enabled and disabled, you can run these commands:
-
-```sh
-$ cargo test --no-default-features
-$ cargo test --features "yaml unstable"
-```
-
-Alternatively, if you have [`just`](https://github.com/casey/just) installed you can run the prebuilt recipes. *Not* using `just` is perfectly fine as well, it simply bundles commands automatically.
-
-For example, to test the code, as above simply run:
-
-```sh
-$ just run-tests
-```
-
-From here on, I will list the appropriate `cargo` command as well as the `just` command.
-
-Sometimes it's helpful to only run a subset of the tests, which can be done via:
-
-```sh
-$ cargo test --test <test_name>
-
-# Or
-
-$ just run-test <test_name>
-```
-
-### Linting Code
-
-During the CI process `clap` runs against many different lints using [`clippy`](https://github.com/rust-lang-nursery/rust-clippy). In order to check if these lints pass on your own computer prior to submitting a PR you'll need a nightly compiler.
-
-In order to check the code for lints run either:
-
-```sh
-$ rustup override add nightly
-$ cargo build --features lints
-$ rustup override remove
-
-# Or
-
-$ just lint
-```
-
-### Debugging Code
-
-Another helpful technique is to see the `clap` debug output while developing features. In order to see the debug output while running the full test suite or individual tests, run:
-
-```sh
-$ cargo test --features debug
-
-# Or for individual tests
-$ cargo test --test <test_name> --features debug
-
-# The corresponding just command for individual debugging tests is:
-$ just debug <test_name>
-```
-
-### Commit Messages
-
-I use a [conventional](https://github.com/ajoslin/conventional-changelog/blob/a5505865ff3dd710cf757f50530e73ef0ca641da/conventions/angular.md) changelog format so I can update my changelog automatically using [clog](https://github.com/clog-tool/clog-cli)
-
- * Please format your commit subject line using the following format: `TYPE(COMPONENT): MESSAGE` where `TYPE` is one of the following:
- - `api` - An addition to the API
- - `setting` - A new `AppSettings` variant
- - `feat` - A new feature of an existing API
- - `imp` - An improvement to an existing feature/API
- - `perf` - A performance improvement
- - `docs` - Changes to documentation only
- - `tests` - Changes to the testing framework or tests only
- - `fix` - A bug fix
- - `refactor` - Code functionality doesn't change, but underlying structure may
- - `style` - Stylistic changes only, no functionality changes
- - `wip` - A work in progress commit (Should typically be `git rebase`'ed away)
- - `chore` - Catch all or things that have to do with the build system, etc
- - `examples` - Changes to existing example, or a new example
- * The `COMPONENT` is optional, and may be a single file, directory, or logical component. Parenthesis can be omitted if you are opting not to use the `COMPONENT`.
-
-### Tests and Documentation
-
-1. Create tests for your changes
-2. **Ensure the tests are passing.** Run the tests (`cargo test --features "yaml unstable"`), alternatively `just run-tests` if you have `just` installed.
-3. **Optional** Run the lints (`cargo build --features lints`) (requires a nightly compiler), alternatively `just lint`
-4. Ensure your changes contain documentation if adding new APIs or features.
-
-### Preparing the PR
-
-1. `git rebase` into concise commits and remove `--fixup`s or `wip` commits (`git rebase -i HEAD~NUM` where `NUM` is number of commits back to start the rebase)
-2. Push your changes back to your fork (`git push origin $your-branch`)
-3. Create a pull request against `master`! (You can also create the pull request first, and we'll merge when ready. This a good way to discuss proposed changes.)
-
-### Other ways to contribute
-
-Another really great way to help is if you find an interesting, or helpful way in which to use `clap`. You can either add it to the [examples/](../examples) directory, or file an issue and tell me. I'm all about giving credit where credit is due :)
-
-### Goals
-
-There are a few goals of `clap` that I'd like to maintain throughout contributions. If your proposed changes break, or go against any of these goals we'll discuss the changes further before merging (but will *not* be ignored, all contributes are welcome!). These are by no means hard-and-fast rules, as I'm no expert and break them myself from time to time (even if by mistake or ignorance :P).
-
-* Remain backwards compatible when possible
- - If backwards compatibility *must* be broken, use deprecation warnings if at all possible before removing legacy code
- - This does not apply for security concerns
-* Parse arguments quickly
- - Parsing of arguments shouldn't slow down usage of the main program
- - This is also true of generating help and usage information (although *slightly* less stringent, as the program is about to exit)
-* Try to be cognizant of memory usage
- - Once parsing is complete, the memory footprint of `clap` should be low since the main program is the star of the show
-* `panic!` on *developer* error, exit gracefully on *end-user* error
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
deleted file mode 100644
index 5f94a2c..0000000
--- a/.github/ISSUE_TEMPLATE.md
+++ /dev/null
@@ -1,46 +0,0 @@
-<!--
-Please use the following template to assist with creating an issue and to ensure a speedy resolution. If an area is not applicable, feel free to delete the area or mark with `N/A`
--->
-
-### Rust Version
-
-* Use the output of `rustc -V`
-
-### Affected Version of clap
-
-* Can be found in Cargo.lock of your project (i.e. `grep clap Cargo.lock`)
-
-### Bug or Feature Request Summary
-
-
-### Expected Behavior Summary
-
-
-### Actual Behavior Summary
-
-
-### Steps to Reproduce the issue
-
-
-### Sample Code or Link to Sample Code
-
-
-### Debug output
-
-Compile clap with cargo features `"debug"` such as:
-
-```toml
-[dependencies]
-clap = { version = "2", features = ["debug"] }
-```
-
-<details>
-<summary> Debug Output </summary>
-<pre>
-<code>
-
-Paste Debug Output Here
-
-</code>
-</pre>
-</details>
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index f3cf7b7..0000000
--- a/.travis.yml
+++ /dev/null
@@ -1,66 +0,0 @@
-os: linux
-language: rust
-cache: cargo
-before_cache:
- - find target/debug -type f -maxdepth 1 -delete
- - rm -rf target/.rustc_info.json
- - rm -rf target/debug/examples
- - rm -rf target/debug/incremental
- - rm -rf target/tests/target/debug/incremental
- - rm -rf target/tests/target/debug/deps/{clap*, trybuild*}
- - rm -rf target/debug/{deps,.fingerpint}/clap*
- - find target/debug/deps -name "clap*" -exec rm -rf {} +
- - ls -1 examples/ | sed -e 's/\.rs$//' | xargs -I "{{}}" find target/debug/deps -name "{{}}*" -exec rm -rf {} +
- - ls -1 tests/ | sed -e 's/\.rs$//' | xargs -I "{{}}" find target/debug/deps -name "{{}}*" -exec rm -rf {} +
-rust: stable
-branches:
- only:
- # Always build master & Enable building pull requests.
- - v2-master
-jobs:
- allow_failures:
- - rust: nightly
- - env:
- - SHARD=coverage
- fast_finish: true
- include:
- - os: osx
- rust: 1.36.0
- - rust: 1.36.0
- - {}
- - rust: beta
- - rust: nightly
- - env:
- - SHARD=lint
- before_script:
- - rustup component add clippy
- - rustup component add rustfmt
- script:
- - echo "Checking codebase with Clippy release `cargo clippy --version`."
- - cargo clippy --lib --features "yaml unstable"
- - cargo clippy --tests --examples --features "yaml unstable"
- - cargo fmt -- --check
- - rust: nightly
- env:
- - SHARD=bench
- script:
- - cargo bench
- - env:
- - SHARD=coverage
- addons:
- apt:
- packages:
- - libssl-dev
- - cmake
- - pkg-config
- - zlib1g-dev
- update: true
- before_script:
- - cargo install cargo-tarpaulin
- script:
- - cargo tarpaulin --features "yaml unstable" --ciserver travis-ci --coveralls $TRAVIS_JOB_ID
-script:
- - cargo test --no-default-features
- - cargo test --features yaml unstable
-notifications:
- email: false
diff --git a/3.2.23/.cargo_vcs_info.json b/3.2.23/.cargo_vcs_info.json
new file mode 100644
index 0000000..fd5f0ca
--- /dev/null
+++ b/3.2.23/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "08f8d6ca30a2b9f73ec981e55560585dea0f6709"
+ },
+ "path_in_vcs": ""
+} \ No newline at end of file
diff --git a/3.2.23/Android.bp b/3.2.23/Android.bp
new file mode 100644
index 0000000..db4e9eb
--- /dev/null
+++ b/3.2.23/Android.bp
@@ -0,0 +1,63 @@
+// This file is generated by cargo2android.py --config cargo2android.json.
+// Do not modify this file as changes will be overridden on upgrade.
+
+
+
+package {
+ default_applicable_licenses: ["external_rust_crates_clap_3.2.23_license"],
+}
+
+// Added automatically by a large-scale-change that took the approach of
+// 'apply every license found to every target'. While this makes sure we respect
+// every license restriction, it may not be entirely correct.
+//
+// e.g. GPL in an MIT project might only apply to the contrib/ directory.
+//
+// Please consider splitting the single license below into multiple licenses,
+// taking care not to lose any license_kind information, and overriding the
+// default license using the 'licenses: [...]' property on targets as needed.
+//
+// For unused files, consider creating a 'fileGroup' with "//visibility:private"
+// to attach the license to, and including a comment whether the files may be
+// used in the current project.
+//
+// large-scale-change included anything that looked like it might be a license
+// text as a license_text. e.g. LICENSE, NOTICE, COPYING etc.
+//
+// Please consider removing redundant or irrelevant files from 'license_text:'.
+// See: http://go/android-license-faq
+license {
+ name: "external_rust_crates_clap_3.2.23_license",
+ visibility: [":__subpackages__"],
+ license_kinds: [
+ "SPDX-license-identifier-Apache-2.0",
+ "SPDX-license-identifier-MIT",
+ ],
+ license_text: [
+ "LICENSE-APACHE",
+ "LICENSE-MIT",
+ ],
+}
+
+rust_library {
+ name: "libclap_3.2.23",
+ host_supported: true,
+ crate_name: "clap",
+ cargo_env_compat: true,
+ cargo_pkg_version: "3.2.23",
+ srcs: ["src/lib.rs"],
+ edition: "2021",
+ features: ["std"],
+ rustlibs: [
+ "libbitflags-1.3.2",
+ "libclap_lex",
+ "libindexmap",
+ "libtextwrap",
+ ],
+ apex_available: [
+ "//apex_available:platform",
+ "//apex_available:anyapex",
+ ],
+ vendor_available: true,
+ product_available: true,
+}
diff --git a/3.2.23/Cargo.toml b/3.2.23/Cargo.toml
new file mode 100644
index 0000000..9ee1361
--- /dev/null
+++ b/3.2.23/Cargo.toml
@@ -0,0 +1,470 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+rust-version = "1.56.1"
+name = "clap"
+version = "3.2.23"
+include = [
+ "build.rs",
+ "src/**/*",
+ "Cargo.toml",
+ "LICENSE*",
+ "README.md",
+ "benches/**/*",
+ "examples/**/*",
+]
+description = "A simple to use, efficient, and full-featured Command Line Argument Parser"
+readme = "README.md"
+keywords = [
+ "argument",
+ "cli",
+ "arg",
+ "parser",
+ "parse",
+]
+categories = ["command-line-interface"]
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/clap-rs/clap"
+
+[package.metadata.docs.rs]
+features = ["unstable-doc"]
+rustdoc-args = [
+ "--cfg",
+ "docsrs",
+]
+cargo-args = [
+ "-Zunstable-options",
+ "-Zrustdoc-scrape-examples=examples",
+]
+
+[package.metadata.playground]
+features = ["unstable-doc"]
+
+[package.metadata.release]
+shared-version = true
+tag-name = "v{{version}}"
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = "Unreleased"
+replace = "{{version}}"
+min = 1
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = '\.\.\.HEAD'
+replace = "...{{tag_name}}"
+exactly = 1
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = "ReleaseDate"
+replace = "{{date}}"
+min = 1
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = "<!-- next-header -->"
+replace = """
+<!-- next-header -->
+## [Unreleased] - ReleaseDate
+"""
+exactly = 1
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = "<!-- next-url -->"
+replace = """
+<!-- next-url -->
+[Unreleased]: https://github.com/clap-rs/clap/compare/{{tag_name}}...HEAD"""
+exactly = 1
+
+[profile.bench]
+lto = true
+codegen-units = 1
+
+[profile.test]
+opt-level = 1
+
+[lib]
+bench = false
+
+[[example]]
+name = "demo"
+required-features = ["derive"]
+
+[[example]]
+name = "cargo-example"
+required-features = ["cargo"]
+
+[[example]]
+name = "cargo-example-derive"
+required-features = ["derive"]
+
+[[example]]
+name = "escaped-positional"
+required-features = ["cargo"]
+
+[[example]]
+name = "escaped-positional-derive"
+required-features = ["derive"]
+
+[[example]]
+name = "git-derive"
+required-features = ["derive"]
+
+[[example]]
+name = "typed-derive"
+required-features = ["derive"]
+
+[[example]]
+name = "busybox"
+path = "examples/multicall-busybox.rs"
+
+[[example]]
+name = "hostname"
+path = "examples/multicall-hostname.rs"
+
+[[example]]
+name = "repl"
+path = "examples/repl.rs"
+
+[[example]]
+name = "01_quick"
+path = "examples/tutorial_builder/01_quick.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "02_apps"
+path = "examples/tutorial_builder/02_apps.rs"
+
+[[example]]
+name = "02_crate"
+path = "examples/tutorial_builder/02_crate.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "02_app_settings"
+path = "examples/tutorial_builder/02_app_settings.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_01_flag_bool"
+path = "examples/tutorial_builder/03_01_flag_bool.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_01_flag_count"
+path = "examples/tutorial_builder/03_01_flag_count.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_02_option"
+path = "examples/tutorial_builder/03_02_option.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_03_positional"
+path = "examples/tutorial_builder/03_03_positional.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_04_subcommands"
+path = "examples/tutorial_builder/03_04_subcommands.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_05_default_values"
+path = "examples/tutorial_builder/03_05_default_values.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_01_possible"
+path = "examples/tutorial_builder/04_01_possible.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_01_enum"
+path = "examples/tutorial_builder/04_01_enum.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_02_parse"
+path = "examples/tutorial_builder/04_02_parse.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_02_validate"
+path = "examples/tutorial_builder/04_02_validate.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_03_relations"
+path = "examples/tutorial_builder/04_03_relations.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_04_custom"
+path = "examples/tutorial_builder/04_04_custom.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "05_01_assert"
+path = "examples/tutorial_builder/05_01_assert.rs"
+test = true
+required-features = ["cargo"]
+
+[[example]]
+name = "01_quick_derive"
+path = "examples/tutorial_derive/01_quick.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "02_apps_derive"
+path = "examples/tutorial_derive/02_apps.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "02_crate_derive"
+path = "examples/tutorial_derive/02_crate.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "02_app_settings_derive"
+path = "examples/tutorial_derive/02_app_settings.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_01_flag_bool_derive"
+path = "examples/tutorial_derive/03_01_flag_bool.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_01_flag_count_derive"
+path = "examples/tutorial_derive/03_01_flag_count.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_02_option_derive"
+path = "examples/tutorial_derive/03_02_option.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_03_positional_derive"
+path = "examples/tutorial_derive/03_03_positional.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_04_subcommands_derive"
+path = "examples/tutorial_derive/03_04_subcommands.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_04_subcommands_alt_derive"
+path = "examples/tutorial_derive/03_04_subcommands_alt.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_05_default_values_derive"
+path = "examples/tutorial_derive/03_05_default_values.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_01_enum_derive"
+path = "examples/tutorial_derive/04_01_enum.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_02_parse_derive"
+path = "examples/tutorial_derive/04_02_parse.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_02_validate_derive"
+path = "examples/tutorial_derive/04_02_validate.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_03_relations_derive"
+path = "examples/tutorial_derive/04_03_relations.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_04_custom_derive"
+path = "examples/tutorial_derive/04_04_custom.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "05_01_assert_derive"
+path = "examples/tutorial_derive/05_01_assert.rs"
+test = true
+required-features = ["derive"]
+
+[[example]]
+name = "custom-bool"
+path = "examples/derive_ref/custom-bool.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "interop_augment_args"
+path = "examples/derive_ref/augment_args.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "interop_augment_subcommands"
+path = "examples/derive_ref/augment_subcommands.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "interop_hand_subcommand"
+path = "examples/derive_ref/hand_subcommand.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "interop_flatten_hand_args"
+path = "examples/derive_ref/flatten_hand_args.rs"
+required-features = ["derive"]
+
+[dependencies.atty]
+version = "0.2"
+optional = true
+
+[dependencies.backtrace]
+version = "0.3"
+optional = true
+
+[dependencies.bitflags]
+version = "1.2"
+
+[dependencies.clap_derive]
+version = "=3.2.18"
+optional = true
+
+[dependencies.clap_lex]
+version = "0.2.2"
+
+[dependencies.indexmap]
+version = "1.0"
+
+[dependencies.once_cell]
+version = "1.12.0"
+optional = true
+
+[dependencies.regex]
+version = "1.0"
+optional = true
+
+[dependencies.strsim]
+version = "0.10"
+optional = true
+
+[dependencies.termcolor]
+version = "1.1.1"
+optional = true
+
+[dependencies.terminal_size]
+version = "0.2.1"
+optional = true
+
+[dependencies.textwrap]
+version = "0.16"
+features = []
+default-features = false
+
+[dependencies.unicase]
+version = "2.6"
+optional = true
+
+[dependencies.yaml-rust]
+version = "0.4.1"
+optional = true
+
+[dev-dependencies.humantime]
+version = "2"
+
+[dev-dependencies.regex]
+version = "1.0"
+
+[dev-dependencies.rustversion]
+version = "1"
+
+[dev-dependencies.shlex]
+version = "1.1.0"
+
+[dev-dependencies.snapbox]
+version = "0.2.9"
+
+[dev-dependencies.static_assertions]
+version = "1.1.0"
+
+[dev-dependencies.trybuild]
+version = "1.0.18"
+
+[dev-dependencies.trycmd]
+version = "0.13"
+features = [
+ "color-auto",
+ "diff",
+ "examples",
+]
+default-features = false
+
+[features]
+cargo = ["once_cell"]
+color = [
+ "atty",
+ "termcolor",
+]
+debug = [
+ "clap_derive/debug",
+ "backtrace",
+]
+default = [
+ "std",
+ "color",
+ "suggestions",
+]
+deprecated = ["clap_derive/deprecated"]
+derive = [
+ "clap_derive",
+ "once_cell",
+]
+env = []
+std = ["indexmap/std"]
+suggestions = ["strsim"]
+unicode = [
+ "textwrap/unicode-width",
+ "unicase",
+]
+unstable-doc = [
+ "derive",
+ "cargo",
+ "wrap_help",
+ "yaml",
+ "env",
+ "unicode",
+ "regex",
+ "unstable-replace",
+ "unstable-grouped",
+]
+unstable-grouped = []
+unstable-replace = []
+unstable-v4 = [
+ "clap_derive/unstable-v4",
+ "deprecated",
+]
+wrap_help = [
+ "terminal_size",
+ "textwrap/terminal_size",
+]
+yaml = ["yaml-rust"]
diff --git a/3.2.23/LICENSE b/3.2.23/LICENSE
new file mode 120000
index 0000000..6b579aa
--- /dev/null
+++ b/3.2.23/LICENSE
@@ -0,0 +1 @@
+LICENSE-APACHE \ No newline at end of file
diff --git a/3.2.23/LICENSE-APACHE b/3.2.23/LICENSE-APACHE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/3.2.23/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/3.2.23/LICENSE-MIT b/3.2.23/LICENSE-MIT
new file mode 100644
index 0000000..7b05b84
--- /dev/null
+++ b/3.2.23/LICENSE-MIT
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2015-2022 Kevin B. Knapp and Clap Contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/3.2.23/METADATA b/3.2.23/METADATA
new file mode 100644
index 0000000..cb02825
--- /dev/null
+++ b/3.2.23/METADATA
@@ -0,0 +1,20 @@
+name: "clap"
+description: "A simple to use, efficient, and full-featured Command Line Argument Parser"
+third_party {
+ url {
+ type: HOMEPAGE
+ value: "https://crates.io/crates/clap"
+ }
+ url {
+ type: ARCHIVE
+ value: "https://static.crates.io/crates/clap/clap-3.2.23.crate"
+ }
+ version: "3.2.23"
+ # Dual-licensed, using the least restrictive per go/thirdpartylicenses#same.
+ license_type: NOTICE
+ last_upgrade_date {
+ year: 2023
+ month: 3
+ day: 6
+ }
+}
diff --git a/MODULE_LICENSE_MIT b/3.2.23/MODULE_LICENSE_APACHE2
index e69de29..e69de29 100644
--- a/MODULE_LICENSE_MIT
+++ b/3.2.23/MODULE_LICENSE_APACHE2
diff --git a/3.2.23/OWNERS b/3.2.23/OWNERS
new file mode 100644
index 0000000..45dc4dd
--- /dev/null
+++ b/3.2.23/OWNERS
@@ -0,0 +1 @@
+include platform/prebuilts/rust:master:/OWNERS
diff --git a/3.2.23/README.md b/3.2.23/README.md
new file mode 100644
index 0000000..eea6ba6
--- /dev/null
+++ b/3.2.23/README.md
@@ -0,0 +1,43 @@
+# clap
+
+> **Command Line Argument Parser for Rust**
+
+[![Crates.io](https://img.shields.io/crates/v/clap?style=flat-square)](https://crates.io/crates/clap)
+[![Crates.io](https://img.shields.io/crates/d/clap?style=flat-square)](https://crates.io/crates/clap)
+[![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](LICENSE-APACHE)
+[![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](LICENSE-MIT)
+[![Build Status](https://img.shields.io/github/workflow/status/clap-rs/clap/CI/staging?style=flat-square)](https://github.com/clap-rs/clap/actions/workflows/ci.yml?query=branch%3Astaging)
+[![Coverage Status](https://img.shields.io/coveralls/github/clap-rs/clap/master?style=flat-square)](https://coveralls.io/github/clap-rs/clap?branch=master)
+[![Contributors](https://img.shields.io/github/contributors/clap-rs/clap?style=flat-square)](https://github.com/clap-rs/clap/graphs/contributors)
+
+Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT).
+
+## About
+
+Create your command-line parser, with all of the bells and whistles, declaratively or procedurally.
+
+For more details, see:
+- [docs.rs](https://docs.rs/clap/latest/clap/)
+- [examples](examples/)
+
+## Sponsors
+
+<!-- omit in TOC -->
+### Gold
+
+[![](https://opencollective.com/clap/tiers/gold.svg?avatarHeight=36&width=600)](https://opencollective.com/clap)
+
+<!-- omit in TOC -->
+### Silver
+
+[![](https://opencollective.com/clap/tiers/silver.svg?avatarHeight=36&width=600)](https://opencollective.com/clap)
+
+<!-- omit in TOC -->
+### Bronze
+
+[![](https://opencollective.com/clap/tiers/bronze.svg?avatarHeight=36&width=600)](https://opencollective.com/clap)
+
+<!-- omit in TOC -->
+### Backer
+
+[![](https://opencollective.com/clap/tiers/backer.svg?avatarHeight=36&width=600)](https://opencollective.com/clap)
diff --git a/3.2.23/cargo2android.json b/3.2.23/cargo2android.json
new file mode 100644
index 0000000..f99d1f0
--- /dev/null
+++ b/3.2.23/cargo2android.json
@@ -0,0 +1,7 @@
+{
+ "patch": "patches/Android.bp.diff",
+ "device": true,
+ "features": "std",
+ "run": true,
+ "tests": true
+}
diff --git a/3.2.23/examples/cargo-example-derive.md b/3.2.23/examples/cargo-example-derive.md
new file mode 100644
index 0000000..2c7a11b
--- /dev/null
+++ b/3.2.23/examples/cargo-example-derive.md
@@ -0,0 +1,43 @@
+For more on creating a custom subcommand, see [the cargo
+book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands).
+The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in
+mimicking cargo's interface.
+
+The help looks like:
+```console
+$ cargo-example-derive --help
+cargo
+
+USAGE:
+ cargo <SUBCOMMAND>
+
+OPTIONS:
+ -h, --help Print help information
+
+SUBCOMMANDS:
+ example-derive A simple to use, efficient, and full-featured Command Line Argument Parser
+ help Print this message or the help of the given subcommand(s)
+
+$ cargo-example-derive example-derive --help
+cargo-example-derive [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ cargo example-derive [OPTIONS]
+
+OPTIONS:
+ -h, --help Print help information
+ --manifest-path <MANIFEST_PATH>
+ -V, --version Print version information
+
+```
+
+Then to directly invoke the command, run:
+```console
+$ cargo-example-derive example-derive
+None
+
+$ cargo-example-derive example-derive --manifest-path Cargo.toml
+Some("Cargo.toml")
+
+```
diff --git a/3.2.23/examples/cargo-example-derive.rs b/3.2.23/examples/cargo-example-derive.rs
new file mode 100644
index 0000000..f0aad29
--- /dev/null
+++ b/3.2.23/examples/cargo-example-derive.rs
@@ -0,0 +1,20 @@
+use clap::Parser;
+
+#[derive(Parser)] // requires `derive` feature
+#[clap(name = "cargo")]
+#[clap(bin_name = "cargo")]
+enum Cargo {
+ ExampleDerive(ExampleDerive),
+}
+
+#[derive(clap::Args)]
+#[clap(author, version, about, long_about = None)]
+struct ExampleDerive {
+ #[clap(long, value_parser)]
+ manifest_path: Option<std::path::PathBuf>,
+}
+
+fn main() {
+ let Cargo::ExampleDerive(args) = Cargo::parse();
+ println!("{:?}", args.manifest_path);
+}
diff --git a/3.2.23/examples/cargo-example.md b/3.2.23/examples/cargo-example.md
new file mode 100644
index 0000000..6fb6a3c
--- /dev/null
+++ b/3.2.23/examples/cargo-example.md
@@ -0,0 +1,43 @@
+For more on creating a custom subcommand, see [the cargo
+book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands).
+The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in
+mimicking cargo's interface.
+
+The help looks like:
+```console
+$ cargo-example --help
+cargo
+
+USAGE:
+ cargo <SUBCOMMAND>
+
+OPTIONS:
+ -h, --help Print help information
+
+SUBCOMMANDS:
+ example A simple to use, efficient, and full-featured Command Line Argument Parser
+ help Print this message or the help of the given subcommand(s)
+
+$ cargo-example example --help
+cargo-example [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ cargo example [OPTIONS]
+
+OPTIONS:
+ -h, --help Print help information
+ --manifest-path <PATH>
+ -V, --version Print version information
+
+```
+
+Then to directly invoke the command, run:
+```console
+$ cargo-example example
+None
+
+$ cargo-example example --manifest-path Cargo.toml
+Some("Cargo.toml")
+
+```
diff --git a/3.2.23/examples/cargo-example.rs b/3.2.23/examples/cargo-example.rs
new file mode 100644
index 0000000..d9a909f
--- /dev/null
+++ b/3.2.23/examples/cargo-example.rs
@@ -0,0 +1,19 @@
+fn main() {
+ let cmd = clap::Command::new("cargo")
+ .bin_name("cargo")
+ .subcommand_required(true)
+ .subcommand(
+ clap::command!("example").arg(
+ clap::arg!(--"manifest-path" <PATH>)
+ .required(false)
+ .value_parser(clap::value_parser!(std::path::PathBuf)),
+ ),
+ );
+ let matches = cmd.get_matches();
+ let matches = match matches.subcommand() {
+ Some(("example", matches)) => matches,
+ _ => unreachable!("clap should ensure we don't get here"),
+ };
+ let manifest_path = matches.get_one::<std::path::PathBuf>("manifest-path");
+ println!("{:?}", manifest_path);
+}
diff --git a/3.2.23/examples/demo.md b/3.2.23/examples/demo.md
new file mode 100644
index 0000000..93ee49c
--- /dev/null
+++ b/3.2.23/examples/demo.md
@@ -0,0 +1,19 @@
+```console
+$ demo --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ demo[EXE] [OPTIONS] --name <NAME>
+
+OPTIONS:
+ -c, --count <COUNT> Number of times to greet [default: 1]
+ -h, --help Print help information
+ -n, --name <NAME> Name of the person to greet
+ -V, --version Print version information
+
+$ demo --name Me
+Hello Me!
+
+```
+*(version number and `.exe` extension on windows replaced by placeholders)*
diff --git a/3.2.23/examples/demo.rs b/3.2.23/examples/demo.rs
new file mode 100644
index 0000000..a7cecfb
--- /dev/null
+++ b/3.2.23/examples/demo.rs
@@ -0,0 +1,22 @@
+use clap::Parser;
+
+/// Simple program to greet a person
+#[derive(Parser, Debug)]
+#[clap(author, version, about, long_about = None)]
+struct Args {
+ /// Name of the person to greet
+ #[clap(short, long, value_parser)]
+ name: String,
+
+ /// Number of times to greet
+ #[clap(short, long, value_parser, default_value_t = 1)]
+ count: u8,
+}
+
+fn main() {
+ let args = Args::parse();
+
+ for _ in 0..args.count {
+ println!("Hello {}!", args.name)
+ }
+}
diff --git a/3.2.23/examples/derive_ref/augment_args.rs b/3.2.23/examples/derive_ref/augment_args.rs
new file mode 100644
index 0000000..3105569
--- /dev/null
+++ b/3.2.23/examples/derive_ref/augment_args.rs
@@ -0,0 +1,27 @@
+use clap::{arg, Args, Command, FromArgMatches as _};
+
+#[derive(Args, Debug)]
+struct DerivedArgs {
+ #[clap(short, long, action)]
+ derived: bool,
+}
+
+fn main() {
+ let cli = Command::new("CLI").arg(arg!(-b - -built).action(clap::ArgAction::SetTrue));
+ // Augment built args with derived args
+ let cli = DerivedArgs::augment_args(cli);
+
+ let matches = cli.get_matches();
+ println!("Value of built: {:?}", matches.get_flag("built"));
+ println!(
+ "Value of derived via ArgMatches: {:?}",
+ matches.get_flag("derived")
+ );
+
+ // Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches.
+ // This is the main benefit of using derived arguments.
+ let derived_matches = DerivedArgs::from_arg_matches(&matches)
+ .map_err(|err| err.exit())
+ .unwrap();
+ println!("Value of derived: {:#?}", derived_matches);
+}
diff --git a/3.2.23/examples/derive_ref/augment_subcommands.rs b/3.2.23/examples/derive_ref/augment_subcommands.rs
new file mode 100644
index 0000000..199da98
--- /dev/null
+++ b/3.2.23/examples/derive_ref/augment_subcommands.rs
@@ -0,0 +1,21 @@
+use clap::{Command, FromArgMatches as _, Parser, Subcommand as _};
+
+#[derive(Parser, Debug)]
+enum Subcommands {
+ Derived {
+ #[clap(short, long, action)]
+ derived_flag: bool,
+ },
+}
+
+fn main() {
+ let cli = Command::new("Built CLI");
+ // Augment with derived subcommands
+ let cli = Subcommands::augment_subcommands(cli);
+
+ let matches = cli.get_matches();
+ let derived_subcommands = Subcommands::from_arg_matches(&matches)
+ .map_err(|err| err.exit())
+ .unwrap();
+ println!("Derived subcommands: {:#?}", derived_subcommands);
+}
diff --git a/3.2.23/examples/derive_ref/custom-bool.md b/3.2.23/examples/derive_ref/custom-bool.md
new file mode 100644
index 0000000..619f9ba
--- /dev/null
+++ b/3.2.23/examples/derive_ref/custom-bool.md
@@ -0,0 +1,47 @@
+*Jump to [source](custom-bool.rs)*
+
+Example of overriding the magic `bool` behavior
+
+```console
+$ custom-bool --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ custom-bool[EXE] [OPTIONS] --foo <FOO> <BOOM>
+
+ARGS:
+ <BOOM> [possible values: true, false]
+
+OPTIONS:
+ --bar <BAR> [default: false]
+ --foo <FOO> [possible values: true, false]
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ custom-bool
+? failed
+error: The following required arguments were not provided:
+ --foo <FOO>
+ <BOOM>
+
+USAGE:
+ custom-bool[EXE] [OPTIONS] --foo <FOO> <BOOM>
+
+For more information try --help
+
+$ custom-bool --foo true false
+[examples/derive_ref/custom-bool.rs:31] opt = Opt {
+ foo: true,
+ bar: false,
+ boom: false,
+}
+
+$ custom-bool --foo true --bar true false
+[examples/derive_ref/custom-bool.rs:31] opt = Opt {
+ foo: true,
+ bar: true,
+ boom: false,
+}
+
+```
diff --git a/3.2.23/examples/derive_ref/custom-bool.rs b/3.2.23/examples/derive_ref/custom-bool.rs
new file mode 100644
index 0000000..d3c321e
--- /dev/null
+++ b/3.2.23/examples/derive_ref/custom-bool.rs
@@ -0,0 +1,32 @@
+use clap::Parser;
+
+#[derive(Parser, Debug, PartialEq)]
+#[clap(author, version, about, long_about = None)]
+struct Opt {
+ // Default parser for `Set` is FromStr::from_str.
+ // `impl FromStr for bool` parses `true` or `false` so this
+ // works as expected.
+ #[clap(long, action = clap::ArgAction::Set)]
+ foo: bool,
+
+ // Of course, this could be done with an explicit parser function.
+ #[clap(long, action = clap::ArgAction::Set, value_parser = true_or_false, default_value_t)]
+ bar: bool,
+
+ // `bool` can be positional only with explicit `action` annotation
+ #[clap(action = clap::ArgAction::Set)]
+ boom: bool,
+}
+
+fn true_or_false(s: &str) -> Result<bool, &'static str> {
+ match s {
+ "true" => Ok(true),
+ "false" => Ok(false),
+ _ => Err("expected `true` or `false`"),
+ }
+}
+
+fn main() {
+ let opt = Opt::parse();
+ dbg!(opt);
+}
diff --git a/3.2.23/examples/derive_ref/flatten_hand_args.rs b/3.2.23/examples/derive_ref/flatten_hand_args.rs
new file mode 100644
index 0000000..c10e0b2
--- /dev/null
+++ b/3.2.23/examples/derive_ref/flatten_hand_args.rs
@@ -0,0 +1,81 @@
+use clap::error::Error;
+use clap::{Arg, ArgAction, ArgMatches, Args, Command, FromArgMatches, Parser};
+
+#[derive(Debug)]
+struct CliArgs {
+ foo: bool,
+ bar: bool,
+ quuz: Option<String>,
+}
+
+impl FromArgMatches for CliArgs {
+ fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
+ let mut matches = matches.clone();
+ Self::from_arg_matches_mut(&mut matches)
+ }
+ fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error> {
+ Ok(Self {
+ foo: matches.get_flag("foo"),
+ bar: matches.get_flag("bar"),
+ quuz: matches.remove_one::<String>("quuz"),
+ })
+ }
+ fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
+ let mut matches = matches.clone();
+ self.update_from_arg_matches_mut(&mut matches)
+ }
+ fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> {
+ self.foo |= matches.get_flag("foo");
+ self.bar |= matches.get_flag("bar");
+ if let Some(quuz) = matches.remove_one::<String>("quuz") {
+ self.quuz = Some(quuz);
+ }
+ Ok(())
+ }
+}
+
+impl Args for CliArgs {
+ fn augment_args(cmd: Command<'_>) -> Command<'_> {
+ cmd.arg(
+ Arg::new("foo")
+ .short('f')
+ .long("foo")
+ .action(ArgAction::SetTrue),
+ )
+ .arg(
+ Arg::new("bar")
+ .short('b')
+ .long("bar")
+ .action(ArgAction::SetTrue),
+ )
+ .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
+ }
+ fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> {
+ cmd.arg(
+ Arg::new("foo")
+ .short('f')
+ .long("foo")
+ .action(ArgAction::SetTrue),
+ )
+ .arg(
+ Arg::new("bar")
+ .short('b')
+ .long("bar")
+ .action(ArgAction::SetTrue),
+ )
+ .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true))
+ }
+}
+
+#[derive(Parser, Debug)]
+struct Cli {
+ #[clap(short, long, action)]
+ top_level: bool,
+ #[clap(flatten)]
+ more_args: CliArgs,
+}
+
+fn main() {
+ let args = Cli::parse();
+ println!("{:#?}", args);
+}
diff --git a/3.2.23/examples/derive_ref/hand_subcommand.rs b/3.2.23/examples/derive_ref/hand_subcommand.rs
new file mode 100644
index 0000000..e9423bd
--- /dev/null
+++ b/3.2.23/examples/derive_ref/hand_subcommand.rs
@@ -0,0 +1,81 @@
+use clap::error::{Error, ErrorKind};
+use clap::{ArgMatches, Args as _, Command, FromArgMatches, Parser, Subcommand};
+
+#[derive(Parser, Debug)]
+struct AddArgs {
+ #[clap(value_parser)]
+ name: Vec<String>,
+}
+#[derive(Parser, Debug)]
+struct RemoveArgs {
+ #[clap(short, long, action)]
+ force: bool,
+ #[clap(value_parser)]
+ name: Vec<String>,
+}
+
+#[derive(Debug)]
+enum CliSub {
+ Add(AddArgs),
+ Remove(RemoveArgs),
+}
+
+impl FromArgMatches for CliSub {
+ fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
+ match matches.subcommand() {
+ Some(("add", args)) => Ok(Self::Add(AddArgs::from_arg_matches(args)?)),
+ Some(("remove", args)) => Ok(Self::Remove(RemoveArgs::from_arg_matches(args)?)),
+ Some((_, _)) => Err(Error::raw(
+ ErrorKind::UnrecognizedSubcommand,
+ "Valid subcommands are `add` and `remove`",
+ )),
+ None => Err(Error::raw(
+ ErrorKind::MissingSubcommand,
+ "Valid subcommands are `add` and `remove`",
+ )),
+ }
+ }
+ fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
+ match matches.subcommand() {
+ Some(("add", args)) => *self = Self::Add(AddArgs::from_arg_matches(args)?),
+ Some(("remove", args)) => *self = Self::Remove(RemoveArgs::from_arg_matches(args)?),
+ Some((_, _)) => {
+ return Err(Error::raw(
+ ErrorKind::UnrecognizedSubcommand,
+ "Valid subcommands are `add` and `remove`",
+ ))
+ }
+ None => (),
+ };
+ Ok(())
+ }
+}
+
+impl Subcommand for CliSub {
+ fn augment_subcommands(cmd: Command<'_>) -> Command<'_> {
+ cmd.subcommand(AddArgs::augment_args(Command::new("add")))
+ .subcommand(RemoveArgs::augment_args(Command::new("remove")))
+ .subcommand_required(true)
+ }
+ fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_> {
+ cmd.subcommand(AddArgs::augment_args(Command::new("add")))
+ .subcommand(RemoveArgs::augment_args(Command::new("remove")))
+ .subcommand_required(true)
+ }
+ fn has_subcommand(name: &str) -> bool {
+ matches!(name, "add" | "remove")
+ }
+}
+
+#[derive(Parser, Debug)]
+struct Cli {
+ #[clap(short, long, action)]
+ top_level: bool,
+ #[clap(subcommand)]
+ subcommand: CliSub,
+}
+
+fn main() {
+ let args = Cli::parse();
+ println!("{:#?}", args);
+}
diff --git a/3.2.23/examples/derive_ref/interop_tests.md b/3.2.23/examples/derive_ref/interop_tests.md
new file mode 100644
index 0000000..746fe18
--- /dev/null
+++ b/3.2.23/examples/derive_ref/interop_tests.md
@@ -0,0 +1,256 @@
+Following are tests for the interop examples in this directory.
+
+## Augment Args
+
+```console
+$ interop_augment_args
+Value of built: false
+Value of derived via ArgMatches: false
+Value of derived: DerivedArgs {
+ derived: false,
+}
+
+```
+
+```console
+$ interop_augment_args -b --derived
+Value of built: true
+Value of derived via ArgMatches: true
+Value of derived: DerivedArgs {
+ derived: true,
+}
+
+```
+
+```console
+$ interop_augment_args -d --built
+Value of built: true
+Value of derived via ArgMatches: true
+Value of derived: DerivedArgs {
+ derived: true,
+}
+
+```
+
+```console
+$ interop_augment_args --unknown
+? failed
+error: Found argument '--unknown' which wasn't expected, or isn't valid in this context
+
+ If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown`
+
+USAGE:
+ interop_augment_args[EXE] [OPTIONS]
+
+For more information try --help
+
+```
+
+## Augment Subcommands
+
+```console
+$ interop_augment_subcommands
+? failed
+error: A subcommand is required but one was not provided.
+```
+
+```console
+$ interop_augment_subcommands derived
+Derived subcommands: Derived {
+ derived_flag: false,
+}
+
+```
+
+```console
+$ interop_augment_subcommands derived --derived-flag
+Derived subcommands: Derived {
+ derived_flag: true,
+}
+
+```
+
+```console
+$ interop_augment_subcommands derived --unknown
+? failed
+error: Found argument '--unknown' which wasn't expected, or isn't valid in this context
+
+ If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown`
+
+USAGE:
+ interop_augment_subcommands[EXE] derived [OPTIONS]
+
+For more information try --help
+
+```
+
+```console
+$ interop_augment_subcommands unknown
+? failed
+error: Found argument 'unknown' which wasn't expected, or isn't valid in this context
+
+USAGE:
+ interop_augment_subcommands[EXE] [SUBCOMMAND]
+
+For more information try --help
+
+```
+
+## Hand-Implemented Subcommand
+
+```console
+$ interop_hand_subcommand
+? failed
+error: 'interop_hand_subcommand[EXE]' requires a subcommand but one was not provided
+
+USAGE:
+ interop_hand_subcommand[EXE] [OPTIONS] <SUBCOMMAND>
+
+For more information try --help
+
+```
+
+```console
+$ interop_hand_subcommand add
+Cli {
+ top_level: false,
+ subcommand: Add(
+ AddArgs {
+ name: [],
+ },
+ ),
+}
+
+```
+
+```console
+$ interop_hand_subcommand add a b c
+Cli {
+ top_level: false,
+ subcommand: Add(
+ AddArgs {
+ name: [
+ "a",
+ "b",
+ "c",
+ ],
+ },
+ ),
+}
+
+```
+
+```console
+$ interop_hand_subcommand add --unknown
+? failed
+error: Found argument '--unknown' which wasn't expected, or isn't valid in this context
+
+ If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown`
+
+USAGE:
+ interop_hand_subcommand[EXE] add [NAME]...
+
+For more information try --help
+
+```
+
+```console
+$ interop_hand_subcommand remove
+Cli {
+ top_level: false,
+ subcommand: Remove(
+ RemoveArgs {
+ force: false,
+ name: [],
+ },
+ ),
+}
+
+```
+
+```console
+$ interop_hand_subcommand remove --force a b c
+Cli {
+ top_level: false,
+ subcommand: Remove(
+ RemoveArgs {
+ force: true,
+ name: [
+ "a",
+ "b",
+ "c",
+ ],
+ },
+ ),
+}
+
+```
+
+```console
+$ interop_hand_subcommand unknown
+? failed
+error: Found argument 'unknown' which wasn't expected, or isn't valid in this context
+
+USAGE:
+ interop_hand_subcommand[EXE] [OPTIONS] <SUBCOMMAND>
+
+For more information try --help
+
+```
+
+## Flatten Hand-Implemented Args
+
+```console
+$ interop_flatten_hand_args
+Cli {
+ top_level: false,
+ more_args: CliArgs {
+ foo: false,
+ bar: false,
+ quuz: None,
+ },
+}
+
+```
+
+```console
+$ interop_flatten_hand_args -f --bar
+Cli {
+ top_level: false,
+ more_args: CliArgs {
+ foo: true,
+ bar: true,
+ quuz: None,
+ },
+}
+
+```
+
+```console
+$ interop_flatten_hand_args --quuz abc
+Cli {
+ top_level: false,
+ more_args: CliArgs {
+ foo: false,
+ bar: false,
+ quuz: Some(
+ "abc",
+ ),
+ },
+}
+
+```
+
+```console
+$ interop_flatten_hand_args --unknown
+? failed
+error: Found argument '--unknown' which wasn't expected, or isn't valid in this context
+
+ If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown`
+
+USAGE:
+ interop_flatten_hand_args[EXE] [OPTIONS]
+
+For more information try --help
+
+```
diff --git a/3.2.23/examples/escaped-positional-derive.md b/3.2.23/examples/escaped-positional-derive.md
new file mode 100644
index 0000000..fa39a2c
--- /dev/null
+++ b/3.2.23/examples/escaped-positional-derive.md
@@ -0,0 +1,63 @@
+**This requires enabling the [`derive` feature flag][crate::_features].**
+
+You can use `--` to escape further arguments.
+
+Let's see what this looks like in the help:
+```console
+$ escaped-positional-derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ escaped-positional-derive[EXE] [OPTIONS] [-- <SLOP>...]
+
+ARGS:
+ <SLOP>...
+
+OPTIONS:
+ -f
+ -h, --help Print help information
+ -p <PEAR>
+ -V, --version Print version information
+
+```
+
+Here is a baseline without any arguments:
+```console
+$ escaped-positional-derive
+-f used: false
+-p's value: None
+'slops' values: []
+
+```
+
+Notice that we can't pass positional arguments before `--`:
+```console
+$ escaped-positional-derive foo bar
+? failed
+error: Found argument 'foo' which wasn't expected, or isn't valid in this context
+
+USAGE:
+ escaped-positional-derive[EXE] [OPTIONS] [-- <SLOP>...]
+
+For more information try --help
+
+```
+
+But you can after:
+```console
+$ escaped-positional-derive -f -p=bob -- sloppy slop slop
+-f used: true
+-p's value: Some("bob")
+'slops' values: ["sloppy", "slop", "slop"]
+
+```
+
+As mentioned, the parser will directly pass everything through:
+```console
+$ escaped-positional-derive -- -f -p=bob sloppy slop slop
+-f used: false
+-p's value: None
+'slops' values: ["-f", "-p=bob", "sloppy", "slop", "slop"]
+
+```
diff --git a/3.2.23/examples/escaped-positional-derive.rs b/3.2.23/examples/escaped-positional-derive.rs
new file mode 100644
index 0000000..fd8fde4
--- /dev/null
+++ b/3.2.23/examples/escaped-positional-derive.rs
@@ -0,0 +1,25 @@
+use clap::Parser;
+
+#[derive(Parser)] // requires `derive` feature
+#[clap(author, version, about, long_about = None)]
+struct Cli {
+ #[clap(short = 'f', action)]
+ eff: bool,
+
+ #[clap(short = 'p', value_name = "PEAR", value_parser)]
+ pea: Option<String>,
+
+ #[clap(last = true, value_parser)]
+ slop: Vec<String>,
+}
+
+fn main() {
+ let args = Cli::parse();
+
+ // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`...
+ println!("-f used: {:?}", args.eff); // -f used: true
+ println!("-p's value: {:?}", args.pea); // -p's value: Some("bob")
+ println!("'slops' values: {:?}", args.slop); // 'slops' values: Some(["sloppy", "slop", "slop"])
+
+ // Continued program logic goes here...
+}
diff --git a/3.2.23/examples/escaped-positional.md b/3.2.23/examples/escaped-positional.md
new file mode 100644
index 0000000..987b261
--- /dev/null
+++ b/3.2.23/examples/escaped-positional.md
@@ -0,0 +1,63 @@
+**This requires enabling the [`cargo` feature flag][crate::_features].**
+
+You can use `--` to escape further arguments.
+
+Let's see what this looks like in the help:
+```console
+$ escaped-positional --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ escaped-positional[EXE] [OPTIONS] [-- <SLOP>...]
+
+ARGS:
+ <SLOP>...
+
+OPTIONS:
+ -f
+ -h, --help Print help information
+ -p <PEAR>
+ -V, --version Print version information
+
+```
+
+Here is a baseline without any arguments:
+```console
+$ escaped-positional
+-f used: false
+-p's value: None
+'slops' values: []
+
+```
+
+Notice that we can't pass positional arguments before `--`:
+```console
+$ escaped-positional foo bar
+? failed
+error: Found argument 'foo' which wasn't expected, or isn't valid in this context
+
+USAGE:
+ escaped-positional[EXE] [OPTIONS] [-- <SLOP>...]
+
+For more information try --help
+
+```
+
+But you can after:
+```console
+$ escaped-positional -f -p=bob -- sloppy slop slop
+-f used: true
+-p's value: Some("bob")
+'slops' values: ["sloppy", "slop", "slop"]
+
+```
+
+As mentioned, the parser will directly pass everything through:
+```console
+$ escaped-positional -- -f -p=bob sloppy slop slop
+-f used: false
+-p's value: None
+'slops' values: ["-f", "-p=bob", "sloppy", "slop", "slop"]
+
+```
diff --git a/3.2.23/examples/escaped-positional.rs b/3.2.23/examples/escaped-positional.rs
new file mode 100644
index 0000000..fdcb930
--- /dev/null
+++ b/3.2.23/examples/escaped-positional.rs
@@ -0,0 +1,36 @@
+use clap::{arg, command, value_parser, ArgAction};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(arg!(eff: -f).action(ArgAction::SetTrue))
+ .arg(
+ arg!(pea: -p <PEAR>)
+ .required(false)
+ .value_parser(value_parser!(String)),
+ )
+ .arg(
+ // Indicates that `slop` is only accessible after `--`.
+ arg!(slop: [SLOP])
+ .multiple_values(true)
+ .last(true)
+ .value_parser(value_parser!(String)),
+ )
+ .get_matches();
+
+ // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`...
+
+ // -f used: true
+ println!("-f used: {:?}", matches.get_flag("eff"));
+ // -p's value: Some("bob")
+ println!("-p's value: {:?}", matches.get_one::<String>("pea"));
+ // 'slops' values: Some(["sloppy", "slop", "slop"])
+ println!(
+ "'slops' values: {:?}",
+ matches
+ .get_many::<String>("slop")
+ .map(|vals| vals.collect::<Vec<_>>())
+ .unwrap_or_default()
+ );
+
+ // Continued program logic goes here...
+}
diff --git a/3.2.23/examples/git-derive.md b/3.2.23/examples/git-derive.md
new file mode 100644
index 0000000..aa1ca6d
--- /dev/null
+++ b/3.2.23/examples/git-derive.md
@@ -0,0 +1,138 @@
+**This requires enabling the [`derive` feature flag][crate::_features].**
+
+Git is an example of several common subcommand patterns.
+
+Help:
+```console
+$ git-derive
+? failed
+git
+A fictional versioning CLI
+
+USAGE:
+ git-derive[EXE] <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
+
+$ git-derive help
+git
+A fictional versioning CLI
+
+USAGE:
+ git-derive[EXE] <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
+
+$ git-derive help add
+git-derive[EXE]-add
+adds things
+
+USAGE:
+ git-derive[EXE] add <PATH>...
+
+ARGS:
+ <PATH>... Stuff to add
+
+OPTIONS:
+ -h, --help Print help information
+
+```
+
+A basic argument:
+```console
+$ git-derive add
+? failed
+git-derive[EXE]-add
+adds things
+
+USAGE:
+ git-derive[EXE] add <PATH>...
+
+ARGS:
+ <PATH>... Stuff to add
+
+OPTIONS:
+ -h, --help Print help information
+
+$ git-derive add Cargo.toml Cargo.lock
+Adding ["Cargo.toml", "Cargo.lock"]
+
+```
+
+Default subcommand:
+```console
+$ git-derive stash -h
+git-derive[EXE]-stash
+
+USAGE:
+ git-derive[EXE] stash [OPTIONS]
+ git-derive[EXE] stash <SUBCOMMAND>
+
+OPTIONS:
+ -h, --help Print help information
+ -m, --message <MESSAGE>
+
+SUBCOMMANDS:
+ apply
+ help Print this message or the help of the given subcommand(s)
+ pop
+ push
+
+$ git-derive stash push -h
+git-derive[EXE]-stash-push
+
+USAGE:
+ git-derive[EXE] stash push [OPTIONS]
+
+OPTIONS:
+ -h, --help Print help information
+ -m, --message <MESSAGE>
+
+$ git-derive stash pop -h
+git-derive[EXE]-stash-pop
+
+USAGE:
+ git-derive[EXE] stash pop [STASH]
+
+ARGS:
+ <STASH>
+
+OPTIONS:
+ -h, --help Print help information
+
+$ git-derive stash -m "Prototype"
+Pushing StashPush { message: Some("Prototype") }
+
+$ git-derive stash pop
+Popping None
+
+$ git-derive stash push -m "Prototype"
+Pushing StashPush { message: Some("Prototype") }
+
+$ git-derive stash pop
+Popping None
+
+```
+
+External subcommands:
+```console
+$ git-derive custom-tool arg1 --foo bar
+Calling out to "custom-tool" with ["arg1", "--foo", "bar"]
+
+```
diff --git a/3.2.23/examples/git-derive.rs b/3.2.23/examples/git-derive.rs
new file mode 100644
index 0000000..ac500dd
--- /dev/null
+++ b/3.2.23/examples/git-derive.rs
@@ -0,0 +1,105 @@
+use std::ffi::OsString;
+use std::path::PathBuf;
+
+use clap::{Args, Parser, Subcommand};
+
+/// A fictional versioning CLI
+#[derive(Debug, Parser)] // requires `derive` feature
+#[clap(name = "git")]
+#[clap(about = "A fictional versioning CLI", long_about = None)]
+struct Cli {
+ #[clap(subcommand)]
+ command: Commands,
+}
+
+#[derive(Debug, Subcommand)]
+enum Commands {
+ /// Clones repos
+ #[clap(arg_required_else_help = true)]
+ Clone {
+ /// The remote to clone
+ #[clap(value_parser)]
+ remote: String,
+ },
+ /// pushes things
+ #[clap(arg_required_else_help = true)]
+ Push {
+ /// The remote to target
+ #[clap(value_parser)]
+ remote: String,
+ },
+ /// adds things
+ #[clap(arg_required_else_help = true)]
+ Add {
+ /// Stuff to add
+ #[clap(required = true, value_parser)]
+ path: Vec<PathBuf>,
+ },
+ Stash(Stash),
+ #[clap(external_subcommand)]
+ External(Vec<OsString>),
+}
+
+#[derive(Debug, Args)]
+#[clap(args_conflicts_with_subcommands = true)]
+struct Stash {
+ #[clap(subcommand)]
+ command: Option<StashCommands>,
+
+ #[clap(flatten)]
+ push: StashPush,
+}
+
+#[derive(Debug, Subcommand)]
+enum StashCommands {
+ Push(StashPush),
+ Pop {
+ #[clap(value_parser)]
+ stash: Option<String>,
+ },
+ Apply {
+ #[clap(value_parser)]
+ stash: Option<String>,
+ },
+}
+
+#[derive(Debug, Args)]
+struct StashPush {
+ #[clap(short, long, value_parser)]
+ message: Option<String>,
+}
+
+fn main() {
+ let args = Cli::parse();
+
+ match args.command {
+ Commands::Clone { remote } => {
+ println!("Cloning {}", remote);
+ }
+ Commands::Push { remote } => {
+ println!("Pushing to {}", remote);
+ }
+ Commands::Add { path } => {
+ println!("Adding {:?}", path);
+ }
+ Commands::Stash(stash) => {
+ let stash_cmd = stash.command.unwrap_or(StashCommands::Push(stash.push));
+ match stash_cmd {
+ StashCommands::Push(push) => {
+ println!("Pushing {:?}", push);
+ }
+ StashCommands::Pop { stash } => {
+ println!("Popping {:?}", stash);
+ }
+ StashCommands::Apply { stash } => {
+ println!("Applying {:?}", stash);
+ }
+ }
+ }
+ Commands::External(args) => {
+ println!("Calling out to {:?} with {:?}", &args[0], &args[1..]);
+ }
+ }
+
+ // Continued program logic goes here...
+}
diff --git a/3.2.23/examples/git.md b/3.2.23/examples/git.md
new file mode 100644
index 0000000..9e41341
--- /dev/null
+++ b/3.2.23/examples/git.md
@@ -0,0 +1,136 @@
+Git is an example of several common subcommand patterns.
+
+Help:
+```console
+$ git
+? failed
+git
+A fictional versioning CLI
+
+USAGE:
+ git[EXE] <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
+
+$ git help
+git
+A fictional versioning CLI
+
+USAGE:
+ git[EXE] <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
+
+$ git help add
+git[EXE]-add
+adds things
+
+USAGE:
+ git[EXE] add <PATH>...
+
+ARGS:
+ <PATH>... Stuff to add
+
+OPTIONS:
+ -h, --help Print help information
+
+```
+
+A basic argument:
+```console
+$ git add
+? failed
+git[EXE]-add
+adds things
+
+USAGE:
+ git[EXE] add <PATH>...
+
+ARGS:
+ <PATH>... Stuff to add
+
+OPTIONS:
+ -h, --help Print help information
+
+$ git add Cargo.toml Cargo.lock
+Adding ["Cargo.toml", "Cargo.lock"]
+
+```
+
+Default subcommand:
+```console
+$ git stash -h
+git[EXE]-stash
+
+USAGE:
+ git[EXE] stash [OPTIONS]
+ git[EXE] stash <SUBCOMMAND>
+
+OPTIONS:
+ -h, --help Print help information
+ -m, --message <MESSAGE>
+
+SUBCOMMANDS:
+ apply
+ help Print this message or the help of the given subcommand(s)
+ pop
+ push
+
+$ git stash push -h
+git[EXE]-stash-push
+
+USAGE:
+ git[EXE] stash push [OPTIONS]
+
+OPTIONS:
+ -h, --help Print help information
+ -m, --message <MESSAGE>
+
+$ git stash pop -h
+git[EXE]-stash-pop
+
+USAGE:
+ git[EXE] stash pop [STASH]
+
+ARGS:
+ <STASH>
+
+OPTIONS:
+ -h, --help Print help information
+
+$ git stash -m "Prototype"
+Pushing Some("Prototype")
+
+$ git stash pop
+Popping None
+
+$ git stash push -m "Prototype"
+Pushing Some("Prototype")
+
+$ git stash pop
+Popping None
+
+```
+
+External subcommands:
+```console
+$ git custom-tool arg1 --foo bar
+Calling out to "custom-tool" with ["arg1", "--foo", "bar"]
+
+```
diff --git a/3.2.23/examples/git.rs b/3.2.23/examples/git.rs
new file mode 100644
index 0000000..e56f427
--- /dev/null
+++ b/3.2.23/examples/git.rs
@@ -0,0 +1,101 @@
+use std::ffi::OsString;
+use std::path::PathBuf;
+
+use clap::{arg, Command};
+
+fn cli() -> Command<'static> {
+ Command::new("git")
+ .about("A fictional versioning CLI")
+ .subcommand_required(true)
+ .arg_required_else_help(true)
+ .allow_external_subcommands(true)
+ .allow_invalid_utf8_for_external_subcommands(true)
+ .subcommand(
+ Command::new("clone")
+ .about("Clones repos")
+ .arg(arg!(<REMOTE> "The remote to clone"))
+ .arg_required_else_help(true),
+ )
+ .subcommand(
+ Command::new("push")
+ .about("pushes things")
+ .arg(arg!(<REMOTE> "The remote to target"))
+ .arg_required_else_help(true),
+ )
+ .subcommand(
+ Command::new("add")
+ .about("adds things")
+ .arg_required_else_help(true)
+ .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
+ )
+ .subcommand(
+ Command::new("stash")
+ .args_conflicts_with_subcommands(true)
+ .args(push_args())
+ .subcommand(Command::new("push").args(push_args()))
+ .subcommand(Command::new("pop").arg(arg!([STASH])))
+ .subcommand(Command::new("apply").arg(arg!([STASH]))),
+ )
+}
+
+fn push_args() -> Vec<clap::Arg<'static>> {
+ vec![arg!(-m --message <MESSAGE>).required(false)]
+}
+
+fn main() {
+ let matches = cli().get_matches();
+
+ match matches.subcommand() {
+ Some(("clone", sub_matches)) => {
+ println!(
+ "Cloning {}",
+ sub_matches.get_one::<String>("REMOTE").expect("required")
+ );
+ }
+ Some(("push", sub_matches)) => {
+ println!(
+ "Pushing to {}",
+ sub_matches.get_one::<String>("REMOTE").expect("required")
+ );
+ }
+ Some(("add", sub_matches)) => {
+ let paths = sub_matches
+ .get_many::<PathBuf>("PATH")
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>();
+ println!("Adding {:?}", paths);
+ }
+ Some(("stash", sub_matches)) => {
+ let stash_command = sub_matches.subcommand().unwrap_or(("push", sub_matches));
+ match stash_command {
+ ("apply", sub_matches) => {
+ let stash = sub_matches.get_one::<String>("STASH");
+ println!("Applying {:?}", stash);
+ }
+ ("pop", sub_matches) => {
+ let stash = sub_matches.get_one::<String>("STASH");
+ println!("Popping {:?}", stash);
+ }
+ ("push", sub_matches) => {
+ let message = sub_matches.get_one::<String>("message");
+ println!("Pushing {:?}", message);
+ }
+ (name, _) => {
+ unreachable!("Unsupported subcommand `{}`", name)
+ }
+ }
+ }
+ Some((ext, sub_matches)) => {
+ let args = sub_matches
+ .get_many::<OsString>("")
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>();
+ println!("Calling out to {:?} with {:?}", ext, args);
+ }
+ _ => unreachable!(), // If all subcommands are defined above, anything else is unreachabe!()
+ }
+
+ // Continued program logic goes here...
+}
diff --git a/3.2.23/examples/multicall-busybox.md b/3.2.23/examples/multicall-busybox.md
new file mode 100644
index 0000000..5ca2cad
--- /dev/null
+++ b/3.2.23/examples/multicall-busybox.md
@@ -0,0 +1,42 @@
+See the documentation for [`Command::multicall`][crate::App::multicall] for rationale.
+
+This example omits every command except true and false,
+which are the most trivial to implement,
+```console
+$ busybox true
+? 0
+
+$ busybox false
+? 1
+
+```
+*Note: without the links setup, we can't demonstrate the multicall behavior*
+
+But includes the `--install` option as an example of why it can be useful
+for the main program to take arguments that aren't applet subcommands.
+```console
+$ busybox --install
+? failed
+...
+
+```
+
+Though users must pass something:
+```console
+$ busybox
+? failed
+busybox
+
+USAGE:
+ busybox [OPTIONS] [APPLET]
+
+OPTIONS:
+ -h, --help Print help information
+ --install <install> Install hardlinks for all subcommands in path
+
+APPLETS:
+ false does nothing unsuccessfully
+ help Print this message or the help of the given subcommand(s)
+ true does nothing successfully
+
+```
diff --git a/3.2.23/examples/multicall-busybox.rs b/3.2.23/examples/multicall-busybox.rs
new file mode 100644
index 0000000..2e7f976
--- /dev/null
+++ b/3.2.23/examples/multicall-busybox.rs
@@ -0,0 +1,48 @@
+use std::path::PathBuf;
+use std::process::exit;
+
+use clap::{value_parser, Arg, Command};
+
+fn applet_commands() -> [Command<'static>; 2] {
+ [
+ Command::new("true").about("does nothing successfully"),
+ Command::new("false").about("does nothing unsuccessfully"),
+ ]
+}
+
+fn main() {
+ let cmd = Command::new(env!("CARGO_CRATE_NAME"))
+ .multicall(true)
+ .subcommand(
+ Command::new("busybox")
+ .arg_required_else_help(true)
+ .subcommand_value_name("APPLET")
+ .subcommand_help_heading("APPLETS")
+ .arg(
+ Arg::new("install")
+ .long("install")
+ .help("Install hardlinks for all subcommands in path")
+ .exclusive(true)
+ .takes_value(true)
+ .default_missing_value("/usr/local/bin")
+ .value_parser(value_parser!(PathBuf))
+ .use_value_delimiter(false),
+ )
+ .subcommands(applet_commands()),
+ )
+ .subcommands(applet_commands());
+
+ let matches = cmd.get_matches();
+ let mut subcommand = matches.subcommand();
+ if let Some(("busybox", cmd)) = subcommand {
+ if cmd.contains_id("install") {
+ unimplemented!("Make hardlinks to the executable here");
+ }
+ subcommand = cmd.subcommand();
+ }
+ match subcommand {
+ Some(("false", _)) => exit(1),
+ Some(("true", _)) => exit(0),
+ _ => unreachable!("parser should ensure only valid subcommand names are used"),
+ }
+}
diff --git a/3.2.23/examples/multicall-hostname.md b/3.2.23/examples/multicall-hostname.md
new file mode 100644
index 0000000..d22b85f
--- /dev/null
+++ b/3.2.23/examples/multicall-hostname.md
@@ -0,0 +1,10 @@
+See the documentation for [`Command::multicall`][crate::App::multicall] for rationale.
+
+This example omits the implementation of displaying address config
+
+```console
+$ hostname
+www
+
+```
+*Note: without the links setup, we can't demonstrate the multicall behavior*
diff --git a/3.2.23/examples/multicall-hostname.rs b/3.2.23/examples/multicall-hostname.rs
new file mode 100644
index 0000000..b57680a
--- /dev/null
+++ b/3.2.23/examples/multicall-hostname.rs
@@ -0,0 +1,17 @@
+use clap::Command;
+
+fn main() {
+ let cmd = Command::new(env!("CARGO_CRATE_NAME"))
+ .multicall(true)
+ .arg_required_else_help(true)
+ .subcommand_value_name("APPLET")
+ .subcommand_help_heading("APPLETS")
+ .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
+ .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
+
+ match cmd.get_matches().subcommand_name() {
+ Some("hostname") => println!("www"),
+ Some("dnsdomainname") => println!("example.com"),
+ _ => unreachable!("parser should ensure only valid subcommand names are used"),
+ }
+}
diff --git a/3.2.23/examples/pacman.md b/3.2.23/examples/pacman.md
new file mode 100644
index 0000000..b8ddd09
--- /dev/null
+++ b/3.2.23/examples/pacman.md
@@ -0,0 +1,85 @@
+[`pacman`](https://wiki.archlinux.org/index.php/pacman) defines subcommands via flags.
+
+Here, `-S` is a short flag subcommand:
+```console
+$ pacman -S package
+Installing package...
+
+```
+
+Here `--sync` is a long flag subcommand:
+```console
+$ pacman --sync package
+Installing package...
+
+```
+
+Now the short flag subcommand (`-S`) with a long flag:
+```console
+$ pacman -S --search name
+Searching for name...
+
+```
+
+And the various forms of short flags that work:
+```console
+$ pacman -S -s name
+Searching for name...
+
+$ pacman -Ss name
+Searching for name...
+
+```
+*(users can "stack" short subcommands with short flags or with other short flag subcommands)*
+
+In the help, this looks like:
+```console
+$ pacman -h
+pacman 5.2.1
+Pacman Development Team
+package manager utility
+
+USAGE:
+ pacman[EXE] <SUBCOMMAND>
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+SUBCOMMANDS:
+ help Print this message or the help of the given subcommand(s)
+ query -Q --query Query the package database.
+ sync -S --sync Synchronize packages.
+
+$ pacman -S -h
+pacman[EXE]-sync
+Synchronize packages.
+
+USAGE:
+ pacman[EXE] {sync|--sync|-S} [OPTIONS] [--] [package]...
+
+ARGS:
+ <package>... packages
+
+OPTIONS:
+ -h, --help Print help information
+ -i, --info view package information
+ -s, --search <search>... search remote repositories for matching strings
+
+```
+
+And errors:
+```console
+$ pacman -S -s foo -i bar
+? failed
+error: The argument '--search <search>...' cannot be used with '--info'
+
+USAGE:
+ pacman[EXE] {sync|--sync|-S} --search <search>... <package>...
+
+For more information try --help
+
+```
+
+**NOTE:** Keep in mind that subcommands, flags, and long flags are *case sensitive*: `-Q` and `-q` are different flags/subcommands. For example, you can have both `-Q` subcommand and `-q` flag, and they will be properly disambiguated.
+Let's make a quick program to illustrate.
diff --git a/3.2.23/examples/pacman.rs b/3.2.23/examples/pacman.rs
new file mode 100644
index 0000000..aee7cd8
--- /dev/null
+++ b/3.2.23/examples/pacman.rs
@@ -0,0 +1,111 @@
+use clap::{Arg, ArgAction, Command};
+
+fn main() {
+ let matches = Command::new("pacman")
+ .about("package manager utility")
+ .version("5.2.1")
+ .subcommand_required(true)
+ .arg_required_else_help(true)
+ .author("Pacman Development Team")
+ // Query subcommand
+ //
+ // Only a few of its arguments are implemented below.
+ .subcommand(
+ Command::new("query")
+ .short_flag('Q')
+ .long_flag("query")
+ .about("Query the package database.")
+ .arg(
+ Arg::new("search")
+ .short('s')
+ .long("search")
+ .help("search locally installed packages for matching strings")
+ .conflicts_with("info")
+ .takes_value(true)
+ .multiple_values(true),
+ )
+ .arg(
+ Arg::new("info")
+ .long("info")
+ .short('i')
+ .conflicts_with("search")
+ .help("view package information")
+ .takes_value(true)
+ .multiple_values(true),
+ ),
+ )
+ // Sync subcommand
+ //
+ // Only a few of its arguments are implemented below.
+ .subcommand(
+ Command::new("sync")
+ .short_flag('S')
+ .long_flag("sync")
+ .about("Synchronize packages.")
+ .arg(
+ Arg::new("search")
+ .short('s')
+ .long("search")
+ .conflicts_with("info")
+ .takes_value(true)
+ .multiple_values(true)
+ .help("search remote repositories for matching strings"),
+ )
+ .arg(
+ Arg::new("info")
+ .long("info")
+ .conflicts_with("search")
+ .short('i')
+ .action(ArgAction::SetTrue)
+ .help("view package information"),
+ )
+ .arg(
+ Arg::new("package")
+ .help("packages")
+ .required_unless_present("search")
+ .takes_value(true)
+ .multiple_values(true),
+ ),
+ )
+ .get_matches();
+
+ match matches.subcommand() {
+ Some(("sync", sync_matches)) => {
+ if sync_matches.contains_id("search") {
+ let packages: Vec<_> = sync_matches
+ .get_many::<String>("search")
+ .expect("contains_id")
+ .map(|s| s.as_str())
+ .collect();
+ let values = packages.join(", ");
+ println!("Searching for {}...", values);
+ return;
+ }
+
+ let packages: Vec<_> = sync_matches
+ .get_many::<String>("package")
+ .expect("is present")
+ .map(|s| s.as_str())
+ .collect();
+ let values = packages.join(", ");
+
+ if sync_matches.get_flag("info") {
+ println!("Retrieving info for {}...", values);
+ } else {
+ println!("Installing {}...", values);
+ }
+ }
+ Some(("query", query_matches)) => {
+ if let Some(packages) = query_matches.get_many::<String>("info") {
+ let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
+ println!("Retrieving info for {}...", comma_sep);
+ } else if let Some(queries) = query_matches.get_many::<String>("search") {
+ let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
+ println!("Searching Locally for {}...", comma_sep);
+ } else {
+ println!("Displaying all locally installed packages...");
+ }
+ }
+ _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
+ }
+}
diff --git a/3.2.23/examples/repl.rs b/3.2.23/examples/repl.rs
new file mode 100644
index 0000000..c509ade
--- /dev/null
+++ b/3.2.23/examples/repl.rs
@@ -0,0 +1,92 @@
+use std::io::Write;
+
+use clap::Command;
+
+fn main() -> Result<(), String> {
+ loop {
+ let line = readline()?;
+ let line = line.trim();
+ if line.is_empty() {
+ continue;
+ }
+
+ match respond(line) {
+ Ok(quit) => {
+ if quit {
+ break;
+ }
+ }
+ Err(err) => {
+ write!(std::io::stdout(), "{}", err).map_err(|e| e.to_string())?;
+ std::io::stdout().flush().map_err(|e| e.to_string())?;
+ }
+ }
+ }
+
+ Ok(())
+}
+
+fn respond(line: &str) -> Result<bool, String> {
+ let args = shlex::split(line).ok_or("error: Invalid quoting")?;
+ let matches = cli()
+ .try_get_matches_from(&args)
+ .map_err(|e| e.to_string())?;
+ match matches.subcommand() {
+ Some(("ping", _matches)) => {
+ write!(std::io::stdout(), "Pong").map_err(|e| e.to_string())?;
+ std::io::stdout().flush().map_err(|e| e.to_string())?;
+ }
+ Some(("quit", _matches)) => {
+ write!(std::io::stdout(), "Exiting ...").map_err(|e| e.to_string())?;
+ std::io::stdout().flush().map_err(|e| e.to_string())?;
+ return Ok(true);
+ }
+ Some((name, _matches)) => unimplemented!("{}", name),
+ None => unreachable!("subcommand required"),
+ }
+
+ Ok(false)
+}
+
+fn cli() -> Command<'static> {
+ // strip out usage
+ const PARSER_TEMPLATE: &str = "\
+ {all-args}
+ ";
+ // strip out name/version
+ const APPLET_TEMPLATE: &str = "\
+ {about-with-newline}\n\
+ {usage-heading}\n {usage}\n\
+ \n\
+ {all-args}{after-help}\
+ ";
+
+ Command::new("repl")
+ .multicall(true)
+ .arg_required_else_help(true)
+ .subcommand_required(true)
+ .subcommand_value_name("APPLET")
+ .subcommand_help_heading("APPLETS")
+ .help_template(PARSER_TEMPLATE)
+ .subcommand(
+ Command::new("ping")
+ .about("Get a response")
+ .help_template(APPLET_TEMPLATE),
+ )
+ .subcommand(
+ Command::new("quit")
+ .alias("exit")
+ .about("Quit the REPL")
+ .help_template(APPLET_TEMPLATE),
+ )
+}
+
+fn readline() -> Result<String, String> {
+ write!(std::io::stdout(), "$ ").map_err(|e| e.to_string())?;
+ std::io::stdout().flush().map_err(|e| e.to_string())?;
+ let mut buffer = String::new();
+ std::io::stdin()
+ .read_line(&mut buffer)
+ .map_err(|e| e.to_string())?;
+ Ok(buffer)
+}
diff --git a/3.2.23/examples/tutorial_builder/01_quick.md b/3.2.23/examples/tutorial_builder/01_quick.md
new file mode 100644
index 0000000..4a9e3fc
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/01_quick.md
@@ -0,0 +1,37 @@
+```console
+$ 01_quick --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 01_quick[EXE] [OPTIONS] [name] [SUBCOMMAND]
+
+ARGS:
+ <name> Optional name to operate on
+
+OPTIONS:
+ -c, --config <FILE> Sets a custom config file
+ -d, --debug Turn debugging information on
+ -h, --help Print help information
+ -V, --version Print version information
+
+SUBCOMMANDS:
+ help Print this message or the help of the given subcommand(s)
+ test does testing things
+
+```
+
+By default, the program does nothing:
+```console
+$ 01_quick
+Debug mode is off
+
+```
+
+But you can mix and match the various features
+```console
+$ 01_quick -dd test
+Debug mode is on
+Not printing testing lists...
+
+```
diff --git a/3.2.23/examples/tutorial_builder/01_quick.rs b/3.2.23/examples/tutorial_builder/01_quick.rs
new file mode 100644
index 0000000..393d6ae
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/01_quick.rs
@@ -0,0 +1,63 @@
+use std::path::PathBuf;
+
+use clap::{arg, command, value_parser, ArgAction, Command};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(arg!([name] "Optional name to operate on"))
+ .arg(
+ arg!(
+ -c --config <FILE> "Sets a custom config file"
+ )
+ // We don't have syntax yet for optional options, so manually calling `required`
+ .required(false)
+ .value_parser(value_parser!(PathBuf)),
+ )
+ .arg(
+ arg!(
+ -d --debug "Turn debugging information on"
+ )
+ .action(ArgAction::Count),
+ )
+ .subcommand(
+ Command::new("test")
+ .about("does testing things")
+ .arg(arg!(-l --list "lists test values").action(ArgAction::SetTrue)),
+ )
+ .get_matches();
+
+ // You can check the value provided by positional arguments, or option arguments
+ if let Some(name) = matches.get_one::<String>("name") {
+ println!("Value for name: {}", name);
+ }
+
+ if let Some(config_path) = matches.get_one::<PathBuf>("config") {
+ println!("Value for config: {}", config_path.display());
+ }
+
+ // You can see how many times a particular flag or argument occurred
+ // Note, only flags can have multiple occurrences
+ match matches
+ .get_one::<u8>("debug")
+ .expect("Count's are defaulted")
+ {
+ 0 => println!("Debug mode is off"),
+ 1 => println!("Debug mode is kind of on"),
+ 2 => println!("Debug mode is on"),
+ _ => println!("Don't be crazy"),
+ }
+
+ // You can check for the existence of subcommands, and if found use their
+ // matches just as you would the top level cmd
+ if let Some(matches) = matches.subcommand_matches("test") {
+ // "$ myapp test" was run
+ if *matches.get_one::<bool>("list").expect("defaulted by clap") {
+ // "$ myapp test -l" was run
+ println!("Printing testing lists...");
+ } else {
+ println!("Not printing testing lists...");
+ }
+ }
+
+ // Continued program logic goes here...
+}
diff --git a/3.2.23/examples/tutorial_builder/02_app_settings.md b/3.2.23/examples/tutorial_builder/02_app_settings.md
new file mode 100644
index 0000000..247843b
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/02_app_settings.md
@@ -0,0 +1,19 @@
+```console
+$ 02_app_settings --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 02_app_settings[EXE] --two <VALUE> --one <VALUE>
+
+OPTIONS:
+ --two <VALUE>
+ --one <VALUE>
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 02_app_settings --one -1 --one -3 --two 10
+two: "10"
+one: "-3"
+
+```
diff --git a/3.2.23/examples/tutorial_builder/02_app_settings.rs b/3.2.23/examples/tutorial_builder/02_app_settings.rs
new file mode 100644
index 0000000..5f374d7
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/02_app_settings.rs
@@ -0,0 +1,19 @@
+use clap::{arg, command, AppSettings, ArgAction};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .global_setting(AppSettings::DeriveDisplayOrder)
+ .allow_negative_numbers(true)
+ .arg(arg!(--two <VALUE>).action(ArgAction::Set))
+ .arg(arg!(--one <VALUE>).action(ArgAction::Set))
+ .get_matches();
+
+ println!(
+ "two: {:?}",
+ matches.get_one::<String>("two").expect("required")
+ );
+ println!(
+ "one: {:?}",
+ matches.get_one::<String>("one").expect("required")
+ );
+}
diff --git a/3.2.23/examples/tutorial_builder/02_apps.md b/3.2.23/examples/tutorial_builder/02_apps.md
new file mode 100644
index 0000000..8504b5f
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/02_apps.md
@@ -0,0 +1,19 @@
+```console
+$ 02_apps --help
+MyApp 1.0
+Kevin K. <kbknapp@gmail.com>
+Does awesome things
+
+USAGE:
+ 02_apps[EXE] --two <VALUE> --one <VALUE>
+
+OPTIONS:
+ -h, --help Print help information
+ --one <VALUE>
+ --two <VALUE>
+ -V, --version Print version information
+
+$ 02_apps --version
+MyApp 1.0
+
+```
diff --git a/3.2.23/examples/tutorial_builder/02_apps.rs b/3.2.23/examples/tutorial_builder/02_apps.rs
new file mode 100644
index 0000000..db9da18
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/02_apps.rs
@@ -0,0 +1,20 @@
+use clap::{arg, Command};
+
+fn main() {
+ let matches = Command::new("MyApp")
+ .version("1.0")
+ .author("Kevin K. <kbknapp@gmail.com>")
+ .about("Does awesome things")
+ .arg(arg!(--two <VALUE>))
+ .arg(arg!(--one <VALUE>))
+ .get_matches();
+
+ println!(
+ "two: {:?}",
+ matches.get_one::<String>("two").expect("required")
+ );
+ println!(
+ "one: {:?}",
+ matches.get_one::<String>("one").expect("required")
+ );
+}
diff --git a/3.2.23/examples/tutorial_builder/02_crate.md b/3.2.23/examples/tutorial_builder/02_crate.md
new file mode 100644
index 0000000..f76e0d6
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/02_crate.md
@@ -0,0 +1,18 @@
+```console
+$ 02_crate --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 02_crate[EXE] --two <VALUE> --one <VALUE>
+
+OPTIONS:
+ -h, --help Print help information
+ --one <VALUE>
+ --two <VALUE>
+ -V, --version Print version information
+
+$ 02_crate --version
+clap [..]
+
+```
diff --git a/3.2.23/examples/tutorial_builder/02_crate.rs b/3.2.23/examples/tutorial_builder/02_crate.rs
new file mode 100644
index 0000000..8a1722f
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/02_crate.rs
@@ -0,0 +1,18 @@
+use clap::{arg, command};
+
+fn main() {
+ // requires `cargo` feature, reading name, version, author, and description from `Cargo.toml`
+ let matches = command!()
+ .arg(arg!(--two <VALUE>))
+ .arg(arg!(--one <VALUE>))
+ .get_matches();
+
+ println!(
+ "two: {:?}",
+ matches.get_one::<String>("two").expect("required")
+ );
+ println!(
+ "one: {:?}",
+ matches.get_one::<String>("one").expect("required")
+ );
+}
diff --git a/3.2.23/examples/tutorial_builder/03_01_flag_bool.md b/3.2.23/examples/tutorial_builder/03_01_flag_bool.md
new file mode 100644
index 0000000..b0ee2a1
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/03_01_flag_bool.md
@@ -0,0 +1,23 @@
+```console
+$ 03_01_flag_bool --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_01_flag_bool[EXE] [OPTIONS]
+
+OPTIONS:
+ -h, --help Print help information
+ -v, --verbose
+ -V, --version Print version information
+
+$ 03_01_flag_bool
+verbose: false
+
+$ 03_01_flag_bool --verbose
+verbose: true
+
+$ 03_01_flag_bool --verbose --verbose
+verbose: true
+
+```
diff --git a/3.2.23/examples/tutorial_builder/03_01_flag_bool.rs b/3.2.23/examples/tutorial_builder/03_01_flag_bool.rs
new file mode 100644
index 0000000..03f2f17
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/03_01_flag_bool.rs
@@ -0,0 +1,14 @@
+use clap::{command, Arg, ArgAction};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(
+ Arg::new("verbose")
+ .short('v')
+ .long("verbose")
+ .action(ArgAction::SetTrue),
+ )
+ .get_matches();
+
+ println!("verbose: {:?}", matches.get_flag("verbose"));
+}
diff --git a/3.2.23/examples/tutorial_builder/03_01_flag_count.md b/3.2.23/examples/tutorial_builder/03_01_flag_count.md
new file mode 100644
index 0000000..ca4bcd6
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/03_01_flag_count.md
@@ -0,0 +1,23 @@
+```console
+$ 03_01_flag_count --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_01_flag_count[EXE] [OPTIONS]
+
+OPTIONS:
+ -h, --help Print help information
+ -v, --verbose
+ -V, --version Print version information
+
+$ 03_01_flag_count
+verbose: 0
+
+$ 03_01_flag_count --verbose
+verbose: 1
+
+$ 03_01_flag_count --verbose --verbose
+verbose: 2
+
+```
diff --git a/3.2.23/examples/tutorial_builder/03_01_flag_count.rs b/3.2.23/examples/tutorial_builder/03_01_flag_count.rs
new file mode 100644
index 0000000..7f23649
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/03_01_flag_count.rs
@@ -0,0 +1,9 @@
+use clap::{arg, command, ArgAction};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(arg!(-v - -verbose).action(ArgAction::Count))
+ .get_matches();
+
+ println!("verbose: {:?}", matches.get_count("verbose"));
+}
diff --git a/3.2.23/examples/tutorial_builder/03_02_option.md b/3.2.23/examples/tutorial_builder/03_02_option.md
new file mode 100644
index 0000000..6198bcc
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/03_02_option.md
@@ -0,0 +1,32 @@
+```console
+$ 03_02_option --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_02_option[EXE] [OPTIONS]
+
+OPTIONS:
+ -h, --help Print help information
+ -n, --name <NAME>
+ -V, --version Print version information
+
+$ 03_02_option
+name: None
+
+$ 03_02_option --name bob
+name: Some("bob")
+
+$ 03_02_option --name=bob
+name: Some("bob")
+
+$ 03_02_option -n bob
+name: Some("bob")
+
+$ 03_02_option -n=bob
+name: Some("bob")
+
+$ 03_02_option -nbob
+name: Some("bob")
+
+```
diff --git a/3.2.23/examples/tutorial_builder/03_02_option.rs b/3.2.23/examples/tutorial_builder/03_02_option.rs
new file mode 100644
index 0000000..1882445
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/03_02_option.rs
@@ -0,0 +1,9 @@
+use clap::{arg, command};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(arg!(-n --name <NAME>).required(false))
+ .get_matches();
+
+ println!("name: {:?}", matches.get_one::<String>("name"));
+}
diff --git a/3.2.23/examples/tutorial_builder/03_03_positional.md b/3.2.23/examples/tutorial_builder/03_03_positional.md
new file mode 100644
index 0000000..a3d7b8c
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/03_03_positional.md
@@ -0,0 +1,22 @@
+```console
+$ 03_03_positional --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_03_positional[EXE] [NAME]
+
+ARGS:
+ <NAME>
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 03_03_positional
+NAME: None
+
+$ 03_03_positional bob
+NAME: Some("bob")
+
+```
diff --git a/3.2.23/examples/tutorial_builder/03_03_positional.rs b/3.2.23/examples/tutorial_builder/03_03_positional.rs
new file mode 100644
index 0000000..0c3a5f0
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/03_03_positional.rs
@@ -0,0 +1,9 @@
+use clap::{arg, command};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(arg!([NAME]))
+ .get_matches();
+
+ println!("NAME: {:?}", matches.get_one::<String>("NAME"));
+}
diff --git a/3.2.23/examples/tutorial_builder/03_04_subcommands.md b/3.2.23/examples/tutorial_builder/03_04_subcommands.md
new file mode 100644
index 0000000..8f9efa9
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/03_04_subcommands.md
@@ -0,0 +1,64 @@
+```console
+$ 03_04_subcommands help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_04_subcommands[EXE] <SUBCOMMAND>
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+SUBCOMMANDS:
+ add Adds files to myapp
+ help Print this message or the help of the given subcommand(s)
+
+$ 03_04_subcommands help add
+03_04_subcommands[EXE]-add [..]
+Adds files to myapp
+
+USAGE:
+ 03_04_subcommands[EXE] add [NAME]
+
+ARGS:
+ <NAME>
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 03_04_subcommands add bob
+'myapp add' was used, name is: Some("bob")
+
+```
+
+Because we set [`Command::arg_required_else_help`][crate::Command::arg_required_else_help]:
+```console
+$ 03_04_subcommands
+? failed
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_04_subcommands[EXE] <SUBCOMMAND>
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+SUBCOMMANDS:
+ add Adds files to myapp
+ help Print this message or the help of the given subcommand(s)
+
+```
+
+Because we set [`Command::propagate_version`][crate::Command::propagate_version]:
+```console
+$ 03_04_subcommands --version
+clap [..]
+
+$ 03_04_subcommands add --version
+03_04_subcommands[EXE]-add [..]
+
+```
diff --git a/3.2.23/examples/tutorial_builder/03_04_subcommands.rs b/3.2.23/examples/tutorial_builder/03_04_subcommands.rs
new file mode 100644
index 0000000..fbe2380
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/03_04_subcommands.rs
@@ -0,0 +1,22 @@
+use clap::{arg, command, Command};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .propagate_version(true)
+ .subcommand_required(true)
+ .arg_required_else_help(true)
+ .subcommand(
+ Command::new("add")
+ .about("Adds files to myapp")
+ .arg(arg!([NAME])),
+ )
+ .get_matches();
+
+ match matches.subcommand() {
+ Some(("add", sub_matches)) => println!(
+ "'myapp add' was used, name is: {:?}",
+ sub_matches.get_one::<String>("NAME")
+ ),
+ _ => unreachable!("Exhausted list of subcommands and subcommand_required prevents `None`"),
+ }
+}
diff --git a/3.2.23/examples/tutorial_builder/03_05_default_values.md b/3.2.23/examples/tutorial_builder/03_05_default_values.md
new file mode 100644
index 0000000..7b6c030
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/03_05_default_values.md
@@ -0,0 +1,22 @@
+```console
+$ 03_05_default_values --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_05_default_values[EXE] [NAME]
+
+ARGS:
+ <NAME> [default: alice]
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 03_05_default_values
+NAME: "alice"
+
+$ 03_05_default_values bob
+NAME: "bob"
+
+```
diff --git a/3.2.23/examples/tutorial_builder/03_05_default_values.rs b/3.2.23/examples/tutorial_builder/03_05_default_values.rs
new file mode 100644
index 0000000..cb3e383
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/03_05_default_values.rs
@@ -0,0 +1,14 @@
+use clap::{arg, command};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(arg!([NAME]).default_value("alice"))
+ .get_matches();
+
+ println!(
+ "NAME: {:?}",
+ matches
+ .get_one::<String>("NAME")
+ .expect("default ensures there is always a value")
+ );
+}
diff --git a/3.2.23/examples/tutorial_builder/04_01_enum.md b/3.2.23/examples/tutorial_builder/04_01_enum.md
new file mode 100644
index 0000000..282b1e6
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/04_01_enum.md
@@ -0,0 +1,29 @@
+```console
+$ 04_01_enum --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 04_01_enum[EXE] <MODE>
+
+ARGS:
+ <MODE> What mode to run the program in [possible values: fast, slow]
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 04_01_enum fast
+Hare
+
+$ 04_01_enum slow
+Tortoise
+
+$ 04_01_enum medium
+? failed
+error: "medium" isn't a valid value for '<MODE>'
+ [possible values: fast, slow]
+
+For more information try --help
+
+```
diff --git a/3.2.23/examples/tutorial_builder/04_01_enum.rs b/3.2.23/examples/tutorial_builder/04_01_enum.rs
new file mode 100644
index 0000000..e8cf70f
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/04_01_enum.rs
@@ -0,0 +1,66 @@
+use clap::{arg, builder::PossibleValue, command, value_parser, ValueEnum};
+
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
+enum Mode {
+ Fast,
+ Slow,
+}
+
+// Can also be derived] with feature flag `derive`
+impl ValueEnum for Mode {
+ fn value_variants<'a>() -> &'a [Self] {
+ &[Mode::Fast, Mode::Slow]
+ }
+
+ fn to_possible_value<'a>(&self) -> Option<PossibleValue<'a>> {
+ Some(match self {
+ Mode::Fast => PossibleValue::new("fast"),
+ Mode::Slow => PossibleValue::new("slow"),
+ })
+ }
+}
+
+impl std::fmt::Display for Mode {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ self.to_possible_value()
+ .expect("no values are skipped")
+ .get_name()
+ .fmt(f)
+ }
+}
+
+impl std::str::FromStr for Mode {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ for variant in Self::value_variants() {
+ if variant.to_possible_value().unwrap().matches(s, false) {
+ return Ok(*variant);
+ }
+ }
+ Err(format!("Invalid variant: {}", s))
+ }
+}
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(
+ arg!(<MODE>)
+ .help("What mode to run the program in")
+ .value_parser(value_parser!(Mode)),
+ )
+ .get_matches();
+
+ // Note, it's safe to call unwrap() because the arg is required
+ match matches
+ .get_one::<Mode>("MODE")
+ .expect("'MODE' is required and parsing will fail if its missing")
+ {
+ Mode::Fast => {
+ println!("Hare");
+ }
+ Mode::Slow => {
+ println!("Tortoise");
+ }
+ }
+}
diff --git a/3.2.23/examples/tutorial_builder/04_01_possible.md b/3.2.23/examples/tutorial_builder/04_01_possible.md
new file mode 100644
index 0000000..2909bfb
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/04_01_possible.md
@@ -0,0 +1,29 @@
+```console
+$ 04_01_possible --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 04_01_possible[EXE] <MODE>
+
+ARGS:
+ <MODE> What mode to run the program in [possible values: fast, slow]
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 04_01_possible fast
+Hare
+
+$ 04_01_possible slow
+Tortoise
+
+$ 04_01_possible medium
+? failed
+error: "medium" isn't a valid value for '<MODE>'
+ [possible values: fast, slow]
+
+For more information try --help
+
+```
diff --git a/3.2.23/examples/tutorial_builder/04_01_possible.rs b/3.2.23/examples/tutorial_builder/04_01_possible.rs
new file mode 100644
index 0000000..3da7aca
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/04_01_possible.rs
@@ -0,0 +1,26 @@
+use clap::{arg, command};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(
+ arg!(<MODE>)
+ .help("What mode to run the program in")
+ .value_parser(["fast", "slow"]),
+ )
+ .get_matches();
+
+ // Note, it's safe to call unwrap() because the arg is required
+ match matches
+ .get_one::<String>("MODE")
+ .expect("'MODE' is required and parsing will fail if its missing")
+ .as_str()
+ {
+ "fast" => {
+ println!("Hare");
+ }
+ "slow" => {
+ println!("Tortoise");
+ }
+ _ => unreachable!(),
+ }
+}
diff --git a/3.2.23/examples/tutorial_builder/04_02_parse.md b/3.2.23/examples/tutorial_builder/04_02_parse.md
new file mode 100644
index 0000000..605bf4b
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/04_02_parse.md
@@ -0,0 +1,31 @@
+```console
+$ 04_02_parse --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 04_02_parse[EXE] <PORT>
+
+ARGS:
+ <PORT> Network port to use
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 04_02_parse 22
+PORT = 22
+
+$ 04_02_parse foobar
+? failed
+error: Invalid value "foobar" for '<PORT>': invalid digit found in string
+
+For more information try --help
+
+$ 04_02_parse_derive 0
+? failed
+error: Invalid value "0" for '<PORT>': 0 is not in 1..=65535
+
+For more information try --help
+
+```
diff --git a/3.2.23/examples/tutorial_builder/04_02_parse.rs b/3.2.23/examples/tutorial_builder/04_02_parse.rs
new file mode 100644
index 0000000..13f41a1
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/04_02_parse.rs
@@ -0,0 +1,17 @@
+use clap::{arg, command, value_parser};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(
+ arg!(<PORT>)
+ .help("Network port to use")
+ .value_parser(value_parser!(u16).range(1..)),
+ )
+ .get_matches();
+
+ // Note, it's safe to call unwrap() because the arg is required
+ let port: u16 = *matches
+ .get_one::<u16>("PORT")
+ .expect("'PORT' is required and parsing will fail if its missing");
+ println!("PORT = {}", port);
+}
diff --git a/3.2.23/examples/tutorial_builder/04_02_validate.md b/3.2.23/examples/tutorial_builder/04_02_validate.md
new file mode 100644
index 0000000..a317a8e
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/04_02_validate.md
@@ -0,0 +1,31 @@
+```console
+$ 04_02_validate --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 04_02_validate[EXE] <PORT>
+
+ARGS:
+ <PORT> Network port to use
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 04_02_validate 22
+PORT = 22
+
+$ 04_02_validate foobar
+? failed
+error: Invalid value "foobar" for '<PORT>': `foobar` isn't a port number
+
+For more information try --help
+
+$ 04_02_validate 0
+? failed
+error: Invalid value "0" for '<PORT>': Port not in range 1-65535
+
+For more information try --help
+
+```
diff --git a/3.2.23/examples/tutorial_builder/04_02_validate.rs b/3.2.23/examples/tutorial_builder/04_02_validate.rs
new file mode 100644
index 0000000..ea2f32e
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/04_02_validate.rs
@@ -0,0 +1,36 @@
+use std::ops::RangeInclusive;
+
+use clap::{arg, command};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(
+ arg!(<PORT>)
+ .help("Network port to use")
+ .value_parser(port_in_range),
+ )
+ .get_matches();
+
+ // Note, it's safe to call unwrap() because the arg is required
+ let port: u16 = *matches
+ .get_one::<u16>("PORT")
+ .expect("'PORT' is required and parsing will fail if its missing");
+ println!("PORT = {}", port);
+}
+
+const PORT_RANGE: RangeInclusive<usize> = 1..=65535;
+
+fn port_in_range(s: &str) -> Result<u16, String> {
+ let port: usize = s
+ .parse()
+ .map_err(|_| format!("`{}` isn't a port number", s))?;
+ if PORT_RANGE.contains(&port) {
+ Ok(port as u16)
+ } else {
+ Err(format!(
+ "Port not in range {}-{}",
+ PORT_RANGE.start(),
+ PORT_RANGE.end()
+ ))
+ }
+}
diff --git a/3.2.23/examples/tutorial_builder/04_03_relations.md b/3.2.23/examples/tutorial_builder/04_03_relations.md
new file mode 100644
index 0000000..3ea3363
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/04_03_relations.md
@@ -0,0 +1,58 @@
+```console
+$ 04_03_relations --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 04_03_relations[EXE] [OPTIONS] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]
+
+ARGS:
+ <INPUT_FILE> some regular input
+
+OPTIONS:
+ -c <CONFIG>
+ -h, --help Print help information
+ --major auto inc major
+ --minor auto inc minor
+ --patch auto inc patch
+ --set-ver <VER> set version manually
+ --spec-in <SPEC_IN> some special input argument
+ -V, --version Print version information
+
+$ 04_03_relations
+? failed
+error: The following required arguments were not provided:
+ <--set-ver <VER>|--major|--minor|--patch>
+
+USAGE:
+ 04_03_relations[EXE] [OPTIONS] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]
+
+For more information try --help
+
+$ 04_03_relations --major
+Version: 2.2.3
+
+$ 04_03_relations --major --minor
+? failed
+error: The argument '--major' cannot be used with '--minor'
+
+USAGE:
+ 04_03_relations[EXE] <--set-ver <VER>|--major|--minor|--patch>
+
+For more information try --help
+
+$ 04_03_relations --major -c config.toml
+? failed
+error: The following required arguments were not provided:
+ <INPUT_FILE|--spec-in <SPEC_IN>>
+
+USAGE:
+ 04_03_relations[EXE] -c <CONFIG> <--set-ver <VER>|--major|--minor|--patch> <INPUT_FILE|--spec-in <SPEC_IN>>
+
+For more information try --help
+
+$ 04_03_relations --major -c config.toml --spec-in input.txt
+Version: 2.2.3
+Doing work using input input.txt and config config.toml
+
+```
diff --git a/3.2.23/examples/tutorial_builder/04_03_relations.rs b/3.2.23/examples/tutorial_builder/04_03_relations.rs
new file mode 100644
index 0000000..8e26d3e
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/04_03_relations.rs
@@ -0,0 +1,80 @@
+use std::path::PathBuf;
+
+use clap::{arg, command, value_parser, ArgAction, ArgGroup};
+
+fn main() {
+ // Create application like normal
+ let matches = command!() // requires `cargo` feature
+ // Add the version arguments
+ .arg(arg!(--"set-ver" <VER> "set version manually").required(false))
+ .arg(arg!(--major "auto inc major").action(ArgAction::SetTrue))
+ .arg(arg!(--minor "auto inc minor").action(ArgAction::SetTrue))
+ .arg(arg!(--patch "auto inc patch").action(ArgAction::SetTrue))
+ // Create a group, make it required, and add the above arguments
+ .group(
+ ArgGroup::new("vers")
+ .required(true)
+ .args(&["set-ver", "major", "minor", "patch"]),
+ )
+ // Arguments can also be added to a group individually, these two arguments
+ // are part of the "input" group which is not required
+ .arg(
+ arg!([INPUT_FILE] "some regular input")
+ .value_parser(value_parser!(PathBuf))
+ .group("input"),
+ )
+ .arg(
+ arg!(--"spec-in" <SPEC_IN> "some special input argument")
+ .required(false)
+ .value_parser(value_parser!(PathBuf))
+ .group("input"),
+ )
+ // Now let's assume we have a -c [config] argument which requires one of
+ // (but **not** both) the "input" arguments
+ .arg(
+ arg!(config: -c <CONFIG>)
+ .required(false)
+ .value_parser(value_parser!(PathBuf))
+ .requires("input"),
+ )
+ .get_matches();
+
+ // Let's assume the old version 1.2.3
+ let mut major = 1;
+ let mut minor = 2;
+ let mut patch = 3;
+
+ // See if --set-ver was used to set the version manually
+ let version = if let Some(ver) = matches.get_one::<String>("set-ver") {
+ ver.to_owned()
+ } else {
+ // Increment the one requested (in a real program, we'd reset the lower numbers)
+ let (maj, min, pat) = (
+ matches.get_flag("major"),
+ matches.get_flag("minor"),
+ matches.get_flag("patch"),
+ );
+ match (maj, min, pat) {
+ (true, _, _) => major += 1,
+ (_, true, _) => minor += 1,
+ (_, _, true) => patch += 1,
+ _ => unreachable!(),
+ };
+ format!("{}.{}.{}", major, minor, patch)
+ };
+
+ println!("Version: {}", version);
+
+ // Check for usage of -c
+ if matches.contains_id("config") {
+ let input = matches
+ .get_one::<PathBuf>("INPUT_FILE")
+ .unwrap_or_else(|| matches.get_one::<PathBuf>("spec-in").unwrap())
+ .display();
+ println!(
+ "Doing work using input {} and config {}",
+ input,
+ matches.get_one::<PathBuf>("config").unwrap().display()
+ );
+ }
+}
diff --git a/3.2.23/examples/tutorial_builder/04_04_custom.md b/3.2.23/examples/tutorial_builder/04_04_custom.md
new file mode 100644
index 0000000..26a3df1
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/04_04_custom.md
@@ -0,0 +1,57 @@
+```console
+$ 04_04_custom --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]
+
+ARGS:
+ <INPUT_FILE> some regular input
+
+OPTIONS:
+ -c <CONFIG>
+ -h, --help Print help information
+ --major auto inc major
+ --minor auto inc minor
+ --patch auto inc patch
+ --set-ver <VER> set version manually
+ --spec-in <SPEC_IN> some special input argument
+ -V, --version Print version information
+
+$ 04_04_custom
+? failed
+error: Can only modify one version field
+
+USAGE:
+ 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]
+
+For more information try --help
+
+$ 04_04_custom --major
+Version: 2.2.3
+
+$ 04_04_custom --major --minor
+? failed
+error: Can only modify one version field
+
+USAGE:
+ 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]
+
+For more information try --help
+
+$ 04_04_custom --major -c config.toml
+? failed
+Version: 2.2.3
+error: INPUT_FILE or --spec-in is required when using --config
+
+USAGE:
+ 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]
+
+For more information try --help
+
+$ 04_04_custom --major -c config.toml --spec-in input.txt
+Version: 2.2.3
+Doing work using input input.txt and config config.toml
+
+```
diff --git a/3.2.23/examples/tutorial_builder/04_04_custom.rs b/3.2.23/examples/tutorial_builder/04_04_custom.rs
new file mode 100644
index 0000000..fb40b2f
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/04_04_custom.rs
@@ -0,0 +1,88 @@
+use std::path::PathBuf;
+
+use clap::{arg, command, value_parser, ArgAction, ErrorKind};
+
+fn main() {
+ // Create application like normal
+ let mut cmd = command!() // requires `cargo` feature
+ // Add the version arguments
+ .arg(arg!(--"set-ver" <VER> "set version manually").required(false))
+ .arg(arg!(--major "auto inc major").action(ArgAction::SetTrue))
+ .arg(arg!(--minor "auto inc minor").action(ArgAction::SetTrue))
+ .arg(arg!(--patch "auto inc patch").action(ArgAction::SetTrue))
+ // Arguments can also be added to a group individually, these two arguments
+ // are part of the "input" group which is not required
+ .arg(arg!([INPUT_FILE] "some regular input").value_parser(value_parser!(PathBuf)))
+ .arg(
+ arg!(--"spec-in" <SPEC_IN> "some special input argument")
+ .required(false)
+ .value_parser(value_parser!(PathBuf)),
+ )
+ // Now let's assume we have a -c [config] argument which requires one of
+ // (but **not** both) the "input" arguments
+ .arg(
+ arg!(config: -c <CONFIG>)
+ .required(false)
+ .value_parser(value_parser!(PathBuf)),
+ );
+ let matches = cmd.get_matches_mut();
+
+ // Let's assume the old version 1.2.3
+ let mut major = 1;
+ let mut minor = 2;
+ let mut patch = 3;
+
+ // See if --set-ver was used to set the version manually
+ let version = if let Some(ver) = matches.get_one::<String>("set-ver") {
+ if matches.get_flag("major") || matches.get_flag("minor") || matches.get_flag("patch") {
+ cmd.error(
+ ErrorKind::ArgumentConflict,
+ "Can't do relative and absolute version change",
+ )
+ .exit();
+ }
+ ver.to_string()
+ } else {
+ // Increment the one requested (in a real program, we'd reset the lower numbers)
+ let (maj, min, pat) = (
+ matches.get_flag("major"),
+ matches.get_flag("minor"),
+ matches.get_flag("patch"),
+ );
+ match (maj, min, pat) {
+ (true, false, false) => major += 1,
+ (false, true, false) => minor += 1,
+ (false, false, true) => patch += 1,
+ _ => {
+ cmd.error(
+ ErrorKind::ArgumentConflict,
+ "Can only modify one version field",
+ )
+ .exit();
+ }
+ };
+ format!("{}.{}.{}", major, minor, patch)
+ };
+
+ println!("Version: {}", version);
+
+ // Check for usage of -c
+ if matches.contains_id("config") {
+ let input = matches
+ .get_one::<PathBuf>("INPUT_FILE")
+ .or_else(|| matches.get_one::<PathBuf>("spec-in"))
+ .unwrap_or_else(|| {
+ cmd.error(
+ ErrorKind::MissingRequiredArgument,
+ "INPUT_FILE or --spec-in is required when using --config",
+ )
+ .exit()
+ })
+ .display();
+ println!(
+ "Doing work using input {} and config {}",
+ input,
+ matches.get_one::<PathBuf>("config").unwrap().display()
+ );
+ }
+}
diff --git a/3.2.23/examples/tutorial_builder/05_01_assert.rs b/3.2.23/examples/tutorial_builder/05_01_assert.rs
new file mode 100644
index 0000000..4b92542
--- /dev/null
+++ b/3.2.23/examples/tutorial_builder/05_01_assert.rs
@@ -0,0 +1,25 @@
+use clap::{arg, command, value_parser};
+
+fn main() {
+ let matches = cmd().get_matches();
+
+ // Note, it's safe to call unwrap() because the arg is required
+ let port: usize = *matches
+ .get_one::<usize>("PORT")
+ .expect("'PORT' is required and parsing will fail if its missing");
+ println!("PORT = {}", port);
+}
+
+fn cmd() -> clap::Command<'static> {
+ command!() // requires `cargo` feature
+ .arg(
+ arg!(<PORT>)
+ .help("Network port to use")
+ .value_parser(value_parser!(usize)),
+ )
+}
+
+#[test]
+fn verify_cmd() {
+ cmd().debug_assert();
+}
diff --git a/3.2.23/examples/tutorial_derive/01_quick.md b/3.2.23/examples/tutorial_derive/01_quick.md
new file mode 100644
index 0000000..6f70d2c
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/01_quick.md
@@ -0,0 +1,37 @@
+```console
+$ 01_quick_derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 01_quick_derive[EXE] [OPTIONS] [NAME] [SUBCOMMAND]
+
+ARGS:
+ <NAME> Optional name to operate on
+
+OPTIONS:
+ -c, --config <FILE> Sets a custom config file
+ -d, --debug Turn debugging information on
+ -h, --help Print help information
+ -V, --version Print version information
+
+SUBCOMMANDS:
+ help Print this message or the help of the given subcommand(s)
+ test does testing things
+
+```
+
+By default, the program does nothing:
+```console
+$ 01_quick_derive
+Debug mode is off
+
+```
+
+But you can mix and match the various features
+```console
+$ 01_quick_derive -dd test
+Debug mode is on
+Not printing testing lists...
+
+```
diff --git a/3.2.23/examples/tutorial_derive/01_quick.rs b/3.2.23/examples/tutorial_derive/01_quick.rs
new file mode 100644
index 0000000..2c20310
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/01_quick.rs
@@ -0,0 +1,69 @@
+use std::path::PathBuf;
+
+use clap::{Parser, Subcommand};
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+struct Cli {
+ /// Optional name to operate on
+ #[clap(value_parser)]
+ name: Option<String>,
+
+ /// Sets a custom config file
+ #[clap(short, long, value_parser, value_name = "FILE")]
+ config: Option<PathBuf>,
+
+ /// Turn debugging information on
+ #[clap(short, long, action = clap::ArgAction::Count)]
+ debug: u8,
+
+ #[clap(subcommand)]
+ command: Option<Commands>,
+}
+
+#[derive(Subcommand)]
+enum Commands {
+ /// does testing things
+ Test {
+ /// lists test values
+ #[clap(short, long, action)]
+ list: bool,
+ },
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ // You can check the value provided by positional arguments, or option arguments
+ if let Some(name) = cli.name.as_deref() {
+ println!("Value for name: {}", name);
+ }
+
+ if let Some(config_path) = cli.config.as_deref() {
+ println!("Value for config: {}", config_path.display());
+ }
+
+ // You can see how many times a particular flag or argument occurred
+ // Note, only flags can have multiple occurrences
+ match cli.debug {
+ 0 => println!("Debug mode is off"),
+ 1 => println!("Debug mode is kind of on"),
+ 2 => println!("Debug mode is on"),
+ _ => println!("Don't be crazy"),
+ }
+
+ // You can check for the existence of subcommands, and if found use their
+ // matches just as you would the top level cmd
+ match &cli.command {
+ Some(Commands::Test { list }) => {
+ if *list {
+ println!("Printing testing lists...");
+ } else {
+ println!("Not printing testing lists...");
+ }
+ }
+ None => {}
+ }
+
+ // Continued program logic goes here...
+}
diff --git a/3.2.23/examples/tutorial_derive/02_app_settings.md b/3.2.23/examples/tutorial_derive/02_app_settings.md
new file mode 100644
index 0000000..ee16c66
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/02_app_settings.md
@@ -0,0 +1,19 @@
+```console
+$ 02_app_settings_derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 02_app_settings_derive[EXE] --two <TWO> --one <ONE>
+
+OPTIONS:
+ --two <TWO>
+ --one <ONE>
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 02_app_settings_derive --one -1 --one -3 --two 10
+two: "10"
+one: "-3"
+
+```
diff --git a/3.2.23/examples/tutorial_derive/02_app_settings.rs b/3.2.23/examples/tutorial_derive/02_app_settings.rs
new file mode 100644
index 0000000..6a06929
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/02_app_settings.rs
@@ -0,0 +1,19 @@
+use clap::{AppSettings, Parser};
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+#[clap(allow_negative_numbers = true)]
+#[clap(global_setting(AppSettings::DeriveDisplayOrder))]
+struct Cli {
+ #[clap(long, value_parser)]
+ two: String,
+ #[clap(long, value_parser)]
+ one: String,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("two: {:?}", cli.two);
+ println!("one: {:?}", cli.one);
+}
diff --git a/3.2.23/examples/tutorial_derive/02_apps.md b/3.2.23/examples/tutorial_derive/02_apps.md
new file mode 100644
index 0000000..0141581
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/02_apps.md
@@ -0,0 +1,19 @@
+```console
+$ 02_apps_derive --help
+MyApp 1.0
+Kevin K. <kbknapp@gmail.com>
+Does awesome things
+
+USAGE:
+ 02_apps_derive[EXE] --two <TWO> --one <ONE>
+
+OPTIONS:
+ -h, --help Print help information
+ --one <ONE>
+ --two <TWO>
+ -V, --version Print version information
+
+$ 02_apps_derive --version
+MyApp 1.0
+
+```
diff --git a/3.2.23/examples/tutorial_derive/02_apps.rs b/3.2.23/examples/tutorial_derive/02_apps.rs
new file mode 100644
index 0000000..b97ce1e
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/02_apps.rs
@@ -0,0 +1,20 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[clap(name = "MyApp")]
+#[clap(author = "Kevin K. <kbknapp@gmail.com>")]
+#[clap(version = "1.0")]
+#[clap(about = "Does awesome things", long_about = None)]
+struct Cli {
+ #[clap(long, value_parser)]
+ two: String,
+ #[clap(long, value_parser)]
+ one: String,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("two: {:?}", cli.two);
+ println!("one: {:?}", cli.one);
+}
diff --git a/3.2.23/examples/tutorial_derive/02_crate.md b/3.2.23/examples/tutorial_derive/02_crate.md
new file mode 100644
index 0000000..92c8207
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/02_crate.md
@@ -0,0 +1,18 @@
+```console
+$ 02_crate_derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 02_crate_derive[EXE] --two <TWO> --one <ONE>
+
+OPTIONS:
+ -h, --help Print help information
+ --one <ONE>
+ --two <TWO>
+ -V, --version Print version information
+
+$ 02_crate_derive --version
+clap [..]
+
+```
diff --git a/3.2.23/examples/tutorial_derive/02_crate.rs b/3.2.23/examples/tutorial_derive/02_crate.rs
new file mode 100644
index 0000000..5576f99
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/02_crate.rs
@@ -0,0 +1,17 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)] // Read from `Cargo.toml`
+struct Cli {
+ #[clap(long, value_parser)]
+ two: String,
+ #[clap(long, value_parser)]
+ one: String,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("two: {:?}", cli.two);
+ println!("one: {:?}", cli.one);
+}
diff --git a/3.2.23/examples/tutorial_derive/03_01_flag_bool.md b/3.2.23/examples/tutorial_derive/03_01_flag_bool.md
new file mode 100644
index 0000000..0baaa10
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/03_01_flag_bool.md
@@ -0,0 +1,23 @@
+```console
+$ 03_01_flag_bool_derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_01_flag_bool_derive[EXE] [OPTIONS]
+
+OPTIONS:
+ -h, --help Print help information
+ -v, --verbose
+ -V, --version Print version information
+
+$ 03_01_flag_bool_derive
+verbose: false
+
+$ 03_01_flag_bool_derive --verbose
+verbose: true
+
+$ 03_01_flag_bool_derive --verbose --verbose
+verbose: true
+
+```
diff --git a/3.2.23/examples/tutorial_derive/03_01_flag_bool.rs b/3.2.23/examples/tutorial_derive/03_01_flag_bool.rs
new file mode 100644
index 0000000..de677d8
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/03_01_flag_bool.rs
@@ -0,0 +1,14 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+struct Cli {
+ #[clap(short, long, action)]
+ verbose: bool,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("verbose: {:?}", cli.verbose);
+}
diff --git a/3.2.23/examples/tutorial_derive/03_01_flag_count.md b/3.2.23/examples/tutorial_derive/03_01_flag_count.md
new file mode 100644
index 0000000..3d5a530
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/03_01_flag_count.md
@@ -0,0 +1,23 @@
+```console
+$ 03_01_flag_count_derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_01_flag_count_derive[EXE] [OPTIONS]
+
+OPTIONS:
+ -h, --help Print help information
+ -v, --verbose
+ -V, --version Print version information
+
+$ 03_01_flag_count_derive
+verbose: 0
+
+$ 03_01_flag_count_derive --verbose
+verbose: 1
+
+$ 03_01_flag_count_derive --verbose --verbose
+verbose: 2
+
+```
diff --git a/3.2.23/examples/tutorial_derive/03_01_flag_count.rs b/3.2.23/examples/tutorial_derive/03_01_flag_count.rs
new file mode 100644
index 0000000..680f7f5
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/03_01_flag_count.rs
@@ -0,0 +1,14 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+struct Cli {
+ #[clap(short, long, action = clap::ArgAction::Count)]
+ verbose: u8,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("verbose: {:?}", cli.verbose);
+}
diff --git a/3.2.23/examples/tutorial_derive/03_02_option.md b/3.2.23/examples/tutorial_derive/03_02_option.md
new file mode 100644
index 0000000..84ff7fa
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/03_02_option.md
@@ -0,0 +1,32 @@
+```console
+$ 03_02_option_derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_02_option_derive[EXE] [OPTIONS]
+
+OPTIONS:
+ -h, --help Print help information
+ -n, --name <NAME>
+ -V, --version Print version information
+
+$ 03_02_option_derive
+name: None
+
+$ 03_02_option_derive --name bob
+name: Some("bob")
+
+$ 03_02_option_derive --name=bob
+name: Some("bob")
+
+$ 03_02_option_derive -n bob
+name: Some("bob")
+
+$ 03_02_option_derive -n=bob
+name: Some("bob")
+
+$ 03_02_option_derive -nbob
+name: Some("bob")
+
+```
diff --git a/3.2.23/examples/tutorial_derive/03_02_option.rs b/3.2.23/examples/tutorial_derive/03_02_option.rs
new file mode 100644
index 0000000..75b67af
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/03_02_option.rs
@@ -0,0 +1,14 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+struct Cli {
+ #[clap(short, long, value_parser)]
+ name: Option<String>,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("name: {:?}", cli.name.as_deref());
+}
diff --git a/3.2.23/examples/tutorial_derive/03_03_positional.md b/3.2.23/examples/tutorial_derive/03_03_positional.md
new file mode 100644
index 0000000..7281fe3
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/03_03_positional.md
@@ -0,0 +1,22 @@
+```console
+$ 03_03_positional_derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_03_positional_derive[EXE] [NAME]
+
+ARGS:
+ <NAME>
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 03_03_positional_derive
+name: None
+
+$ 03_03_positional_derive bob
+name: Some("bob")
+
+```
diff --git a/3.2.23/examples/tutorial_derive/03_03_positional.rs b/3.2.23/examples/tutorial_derive/03_03_positional.rs
new file mode 100644
index 0000000..7478951
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/03_03_positional.rs
@@ -0,0 +1,14 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+struct Cli {
+ #[clap(value_parser)]
+ name: Option<String>,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("name: {:?}", cli.name.as_deref());
+}
diff --git a/3.2.23/examples/tutorial_derive/03_04_subcommands.md b/3.2.23/examples/tutorial_derive/03_04_subcommands.md
new file mode 100644
index 0000000..02f96e3
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/03_04_subcommands.md
@@ -0,0 +1,64 @@
+```console
+$ 03_04_subcommands_derive help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_04_subcommands_derive[EXE] <SUBCOMMAND>
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+SUBCOMMANDS:
+ add Adds files to myapp
+ help Print this message or the help of the given subcommand(s)
+
+$ 03_04_subcommands_derive help add
+03_04_subcommands_derive[EXE]-add [..]
+Adds files to myapp
+
+USAGE:
+ 03_04_subcommands_derive[EXE] add [NAME]
+
+ARGS:
+ <NAME>
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 03_04_subcommands_derive add bob
+'myapp add' was used, name is: Some("bob")
+
+```
+
+Because we used `command: Commands` instead of `command: Option<Commands>`:
+```console
+$ 03_04_subcommands_derive
+? failed
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_04_subcommands_derive[EXE] <SUBCOMMAND>
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+SUBCOMMANDS:
+ add Adds files to myapp
+ help Print this message or the help of the given subcommand(s)
+
+```
+
+Because we added `#[clap(propagate_version = true)]`:
+```console
+$ 03_04_subcommands_derive --version
+clap [..]
+
+$ 03_04_subcommands_derive add --version
+03_04_subcommands_derive[EXE]-add [..]
+
+```
diff --git a/3.2.23/examples/tutorial_derive/03_04_subcommands.rs b/3.2.23/examples/tutorial_derive/03_04_subcommands.rs
new file mode 100644
index 0000000..62a45a9
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/03_04_subcommands.rs
@@ -0,0 +1,30 @@
+use clap::{Parser, Subcommand};
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+#[clap(propagate_version = true)]
+struct Cli {
+ #[clap(subcommand)]
+ command: Commands,
+}
+
+#[derive(Subcommand)]
+enum Commands {
+ /// Adds files to myapp
+ Add {
+ #[clap(value_parser)]
+ name: Option<String>,
+ },
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ // You can check for the existence of subcommands, and if found use their
+ // matches just as you would the top level cmd
+ match &cli.command {
+ Commands::Add { name } => {
+ println!("'myapp add' was used, name is: {:?}", name)
+ }
+ }
+}
diff --git a/3.2.23/examples/tutorial_derive/03_04_subcommands_alt.rs b/3.2.23/examples/tutorial_derive/03_04_subcommands_alt.rs
new file mode 100644
index 0000000..b612493
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/03_04_subcommands_alt.rs
@@ -0,0 +1,33 @@
+use clap::{Args, Parser, Subcommand};
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+#[clap(propagate_version = true)]
+struct Cli {
+ #[clap(subcommand)]
+ command: Commands,
+}
+
+#[derive(Subcommand)]
+enum Commands {
+ /// Adds files to myapp
+ Add(Add),
+}
+
+#[derive(Args)]
+struct Add {
+ #[clap(value_parser)]
+ name: Option<String>,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ // You can check for the existence of subcommands, and if found use their
+ // matches just as you would the top level cmd
+ match &cli.command {
+ Commands::Add(name) => {
+ println!("'myapp add' was used, name is: {:?}", name.name)
+ }
+ }
+}
diff --git a/3.2.23/examples/tutorial_derive/03_05_default_values.md b/3.2.23/examples/tutorial_derive/03_05_default_values.md
new file mode 100644
index 0000000..f7315e7
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/03_05_default_values.md
@@ -0,0 +1,22 @@
+```console
+$ 03_05_default_values_derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 03_05_default_values_derive[EXE] [NAME]
+
+ARGS:
+ <NAME> [default: alice]
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 03_05_default_values_derive
+name: "alice"
+
+$ 03_05_default_values_derive bob
+name: "bob"
+
+```
diff --git a/3.2.23/examples/tutorial_derive/03_05_default_values.rs b/3.2.23/examples/tutorial_derive/03_05_default_values.rs
new file mode 100644
index 0000000..10a1ec8
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/03_05_default_values.rs
@@ -0,0 +1,14 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+struct Cli {
+ #[clap(default_value_t = String::from("alice"), value_parser)]
+ name: String,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("name: {:?}", cli.name);
+}
diff --git a/3.2.23/examples/tutorial_derive/04_01_enum.md b/3.2.23/examples/tutorial_derive/04_01_enum.md
new file mode 100644
index 0000000..2523af9
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/04_01_enum.md
@@ -0,0 +1,29 @@
+```console
+$ 04_01_enum_derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 04_01_enum_derive[EXE] <MODE>
+
+ARGS:
+ <MODE> What mode to run the program in [possible values: fast, slow]
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 04_01_enum_derive fast
+Hare
+
+$ 04_01_enum_derive slow
+Tortoise
+
+$ 04_01_enum_derive medium
+? failed
+error: "medium" isn't a valid value for '<MODE>'
+ [possible values: fast, slow]
+
+For more information try --help
+
+```
diff --git a/3.2.23/examples/tutorial_derive/04_01_enum.rs b/3.2.23/examples/tutorial_derive/04_01_enum.rs
new file mode 100644
index 0000000..1ac9842
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/04_01_enum.rs
@@ -0,0 +1,28 @@
+use clap::{Parser, ValueEnum};
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+struct Cli {
+ /// What mode to run the program in
+ #[clap(arg_enum, value_parser)]
+ mode: Mode,
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
+enum Mode {
+ Fast,
+ Slow,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ match cli.mode {
+ Mode::Fast => {
+ println!("Hare");
+ }
+ Mode::Slow => {
+ println!("Tortoise");
+ }
+ }
+}
diff --git a/3.2.23/examples/tutorial_derive/04_02_parse.md b/3.2.23/examples/tutorial_derive/04_02_parse.md
new file mode 100644
index 0000000..6079ef1
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/04_02_parse.md
@@ -0,0 +1,31 @@
+```console
+$ 04_02_parse_derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 04_02_parse_derive[EXE] <PORT>
+
+ARGS:
+ <PORT> Network port to use
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 04_02_parse_derive 22
+PORT = 22
+
+$ 04_02_parse_derive foobar
+? failed
+error: Invalid value "foobar" for '<PORT>': invalid digit found in string
+
+For more information try --help
+
+$ 04_02_parse_derive 0
+? failed
+error: Invalid value "0" for '<PORT>': 0 is not in 1..=65535
+
+For more information try --help
+
+```
diff --git a/3.2.23/examples/tutorial_derive/04_02_parse.rs b/3.2.23/examples/tutorial_derive/04_02_parse.rs
new file mode 100644
index 0000000..6336a9c
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/04_02_parse.rs
@@ -0,0 +1,15 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+struct Cli {
+ /// Network port to use
+ #[clap(value_parser = clap::value_parser!(u16).range(1..))]
+ port: u16,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("PORT = {}", cli.port);
+}
diff --git a/3.2.23/examples/tutorial_derive/04_02_validate.md b/3.2.23/examples/tutorial_derive/04_02_validate.md
new file mode 100644
index 0000000..cc43440
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/04_02_validate.md
@@ -0,0 +1,31 @@
+```console
+$ 04_02_validate_derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 04_02_validate_derive[EXE] <PORT>
+
+ARGS:
+ <PORT> Network port to use
+
+OPTIONS:
+ -h, --help Print help information
+ -V, --version Print version information
+
+$ 04_02_validate_derive 22
+PORT = 22
+
+$ 04_02_validate_derive foobar
+? failed
+error: Invalid value "foobar" for '<PORT>': `foobar` isn't a port number
+
+For more information try --help
+
+$ 04_02_validate_derive 0
+? failed
+error: Invalid value "0" for '<PORT>': Port not in range 1-65535
+
+For more information try --help
+
+```
diff --git a/3.2.23/examples/tutorial_derive/04_02_validate.rs b/3.2.23/examples/tutorial_derive/04_02_validate.rs
new file mode 100644
index 0000000..7dac79c
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/04_02_validate.rs
@@ -0,0 +1,34 @@
+use std::ops::RangeInclusive;
+
+use clap::Parser;
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+struct Cli {
+ /// Network port to use
+ #[clap(value_parser = port_in_range)]
+ port: u16,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("PORT = {}", cli.port);
+}
+
+const PORT_RANGE: RangeInclusive<usize> = 1..=65535;
+
+fn port_in_range(s: &str) -> Result<u16, String> {
+ let port: usize = s
+ .parse()
+ .map_err(|_| format!("`{}` isn't a port number", s))?;
+ if PORT_RANGE.contains(&port) {
+ Ok(port as u16)
+ } else {
+ Err(format!(
+ "Port not in range {}-{}",
+ PORT_RANGE.start(),
+ PORT_RANGE.end()
+ ))
+ }
+}
diff --git a/3.2.23/examples/tutorial_derive/04_03_relations.md b/3.2.23/examples/tutorial_derive/04_03_relations.md
new file mode 100644
index 0000000..4f5703d
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/04_03_relations.md
@@ -0,0 +1,58 @@
+```console
+$ 04_03_relations_derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 04_03_relations_derive[EXE] [OPTIONS] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]
+
+ARGS:
+ <INPUT_FILE> some regular input
+
+OPTIONS:
+ -c <CONFIG>
+ -h, --help Print help information
+ --major auto inc major
+ --minor auto inc minor
+ --patch auto inc patch
+ --set-ver <VER> set version manually
+ --spec-in <SPEC_IN> some special input argument
+ -V, --version Print version information
+
+$ 04_03_relations_derive
+? failed
+error: The following required arguments were not provided:
+ <--set-ver <VER>|--major|--minor|--patch>
+
+USAGE:
+ 04_03_relations_derive[EXE] [OPTIONS] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]
+
+For more information try --help
+
+$ 04_03_relations_derive --major
+Version: 2.2.3
+
+$ 04_03_relations_derive --major --minor
+? failed
+error: The argument '--major' cannot be used with '--minor'
+
+USAGE:
+ 04_03_relations_derive[EXE] <--set-ver <VER>|--major|--minor|--patch>
+
+For more information try --help
+
+$ 04_03_relations_derive --major -c config.toml
+? failed
+error: The following required arguments were not provided:
+ <INPUT_FILE|--spec-in <SPEC_IN>>
+
+USAGE:
+ 04_03_relations_derive[EXE] -c <CONFIG> <--set-ver <VER>|--major|--minor|--patch> <INPUT_FILE|--spec-in <SPEC_IN>>
+
+For more information try --help
+
+$ 04_03_relations_derive --major -c config.toml --spec-in input.txt
+Version: 2.2.3
+Doing work using input input.txt and config config.toml
+
+```
diff --git a/3.2.23/examples/tutorial_derive/04_03_relations.rs b/3.2.23/examples/tutorial_derive/04_03_relations.rs
new file mode 100644
index 0000000..37efe95
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/04_03_relations.rs
@@ -0,0 +1,72 @@
+use clap::{ArgGroup, Parser};
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+#[clap(group(
+ ArgGroup::new("vers")
+ .required(true)
+ .args(&["set-ver", "major", "minor", "patch"]),
+ ))]
+struct Cli {
+ /// set version manually
+ #[clap(long, value_name = "VER", value_parser)]
+ set_ver: Option<String>,
+
+ /// auto inc major
+ #[clap(long, action)]
+ major: bool,
+
+ /// auto inc minor
+ #[clap(long, action)]
+ minor: bool,
+
+ /// auto inc patch
+ #[clap(long, action)]
+ patch: bool,
+
+ /// some regular input
+ #[clap(group = "input", value_parser)]
+ input_file: Option<String>,
+
+ /// some special input argument
+ #[clap(long, group = "input", value_parser)]
+ spec_in: Option<String>,
+
+ #[clap(short, requires = "input", value_parser)]
+ config: Option<String>,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ // Let's assume the old version 1.2.3
+ let mut major = 1;
+ let mut minor = 2;
+ let mut patch = 3;
+
+ // See if --set_ver was used to set the version manually
+ let version = if let Some(ver) = cli.set_ver.as_deref() {
+ ver.to_string()
+ } else {
+ // Increment the one requested (in a real program, we'd reset the lower numbers)
+ let (maj, min, pat) = (cli.major, cli.minor, cli.patch);
+ match (maj, min, pat) {
+ (true, _, _) => major += 1,
+ (_, true, _) => minor += 1,
+ (_, _, true) => patch += 1,
+ _ => unreachable!(),
+ };
+ format!("{}.{}.{}", major, minor, patch)
+ };
+
+ println!("Version: {}", version);
+
+ // Check for usage of -c
+ if let Some(config) = cli.config.as_deref() {
+ let input = cli
+ .input_file
+ .as_deref()
+ .unwrap_or_else(|| cli.spec_in.as_deref().unwrap());
+ println!("Doing work using input {} and config {}", input, config);
+ }
+}
diff --git a/3.2.23/examples/tutorial_derive/04_04_custom.md b/3.2.23/examples/tutorial_derive/04_04_custom.md
new file mode 100644
index 0000000..0f19bfe
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/04_04_custom.md
@@ -0,0 +1,57 @@
+```console
+$ 04_04_custom_derive --help
+clap [..]
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+USAGE:
+ 04_04_custom_derive[EXE] [OPTIONS] [INPUT_FILE]
+
+ARGS:
+ <INPUT_FILE> some regular input
+
+OPTIONS:
+ -c <CONFIG>
+ -h, --help Print help information
+ --major auto inc major
+ --minor auto inc minor
+ --patch auto inc patch
+ --set-ver <VER> set version manually
+ --spec-in <SPEC_IN> some special input argument
+ -V, --version Print version information
+
+$ 04_04_custom_derive
+? failed
+error: Can only modify one version field
+
+USAGE:
+ clap [OPTIONS] [INPUT_FILE]
+
+For more information try --help
+
+$ 04_04_custom_derive --major
+Version: 2.2.3
+
+$ 04_04_custom_derive --major --minor
+? failed
+error: Can only modify one version field
+
+USAGE:
+ clap [OPTIONS] [INPUT_FILE]
+
+For more information try --help
+
+$ 04_04_custom_derive --major -c config.toml
+? failed
+Version: 2.2.3
+error: INPUT_FILE or --spec-in is required when using --config
+
+USAGE:
+ clap [OPTIONS] [INPUT_FILE]
+
+For more information try --help
+
+$ 04_04_custom_derive --major -c config.toml --spec-in input.txt
+Version: 2.2.3
+Doing work using input input.txt and config config.toml
+
+```
diff --git a/3.2.23/examples/tutorial_derive/04_04_custom.rs b/3.2.23/examples/tutorial_derive/04_04_custom.rs
new file mode 100644
index 0000000..454d489
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/04_04_custom.rs
@@ -0,0 +1,93 @@
+use clap::{CommandFactory, ErrorKind, Parser};
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+struct Cli {
+ /// set version manually
+ #[clap(long, value_name = "VER", value_parser)]
+ set_ver: Option<String>,
+
+ /// auto inc major
+ #[clap(long, action)]
+ major: bool,
+
+ /// auto inc minor
+ #[clap(long, action)]
+ minor: bool,
+
+ /// auto inc patch
+ #[clap(long, action)]
+ patch: bool,
+
+ /// some regular input
+ #[clap(value_parser)]
+ input_file: Option<String>,
+
+ /// some special input argument
+ #[clap(long, value_parser)]
+ spec_in: Option<String>,
+
+ #[clap(short, value_parser)]
+ config: Option<String>,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ // Let's assume the old version 1.2.3
+ let mut major = 1;
+ let mut minor = 2;
+ let mut patch = 3;
+
+ // See if --set-ver was used to set the version manually
+ let version = if let Some(ver) = cli.set_ver.as_deref() {
+ if cli.major || cli.minor || cli.patch {
+ let mut cmd = Cli::command();
+ cmd.error(
+ ErrorKind::ArgumentConflict,
+ "Can't do relative and absolute version change",
+ )
+ .exit();
+ }
+ ver.to_string()
+ } else {
+ // Increment the one requested (in a real program, we'd reset the lower numbers)
+ let (maj, min, pat) = (cli.major, cli.minor, cli.patch);
+ match (maj, min, pat) {
+ (true, false, false) => major += 1,
+ (false, true, false) => minor += 1,
+ (false, false, true) => patch += 1,
+ _ => {
+ let mut cmd = Cli::command();
+ cmd.error(
+ ErrorKind::ArgumentConflict,
+ "Can only modify one version field",
+ )
+ .exit();
+ }
+ };
+ format!("{}.{}.{}", major, minor, patch)
+ };
+
+ println!("Version: {}", version);
+
+ // Check for usage of -c
+ if let Some(config) = cli.config.as_deref() {
+ // todo: remove `#[allow(clippy::or_fun_call)]` lint when MSRV is bumped.
+ #[allow(clippy::or_fun_call)]
+ let input = cli
+ .input_file
+ .as_deref()
+ // 'or' is preferred to 'or_else' here since `Option::as_deref` is 'const'
+ .or(cli.spec_in.as_deref())
+ .unwrap_or_else(|| {
+ let mut cmd = Cli::command();
+ cmd.error(
+ ErrorKind::MissingRequiredArgument,
+ "INPUT_FILE or --spec-in is required when using --config",
+ )
+ .exit()
+ });
+ println!("Doing work using input {} and config {}", input, config);
+ }
+}
diff --git a/3.2.23/examples/tutorial_derive/05_01_assert.rs b/3.2.23/examples/tutorial_derive/05_01_assert.rs
new file mode 100644
index 0000000..66dca72
--- /dev/null
+++ b/3.2.23/examples/tutorial_derive/05_01_assert.rs
@@ -0,0 +1,21 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[clap(author, version, about, long_about = None)]
+struct Cli {
+ /// Network port to use
+ #[clap(value_parser)]
+ port: u16,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("PORT = {}", cli.port);
+}
+
+#[test]
+fn verify_cli() {
+ use clap::CommandFactory;
+ Cli::command().debug_assert()
+}
diff --git a/3.2.23/examples/typed-derive.md b/3.2.23/examples/typed-derive.md
new file mode 100644
index 0000000..9c7615c
--- /dev/null
+++ b/3.2.23/examples/typed-derive.md
@@ -0,0 +1,84 @@
+**This requires enabling the [`derive` feature flag][crate::_features].**
+
+Help:
+```console
+$ typed-derive --help
+clap
+
+USAGE:
+ typed-derive[EXE] [OPTIONS]
+
+OPTIONS:
+ --bind <BIND> Handle IP addresses
+ -D <DEFINES> Hand-written parser for tuples
+ -h, --help Print help information
+ -I <DIR> Allow invalid UTF-8 paths
+ -O <OPTIMIZATION> Implicitly using `std::str::FromStr`
+ --sleep <SLEEP> Allow human-readable durations
+
+```
+
+Optimization-level (number)
+```console
+$ typed-derive -O 1
+Args { optimization: Some(1), include: None, bind: None, sleep: None, defines: [] }
+
+$ typed-derive -O plaid
+? failed
+error: Invalid value "plaid" for '-O <OPTIMIZATION>': invalid digit found in string
+
+For more information try --help
+
+```
+
+Include (path)
+```console
+$ typed-derive -I../hello
+Args { optimization: None, include: Some("../hello"), bind: None, sleep: None, defines: [] }
+
+```
+
+IP Address
+```console
+$ typed-derive --bind 192.0.0.1
+Args { optimization: None, include: None, bind: Some(192.0.0.1), sleep: None, defines: [] }
+
+$ typed-derive --bind localhost
+? failed
+error: Invalid value "localhost" for '--bind <BIND>': invalid IP address syntax
+
+For more information try --help
+
+```
+
+Time
+```console
+$ typed-derive --sleep 10s
+Args { optimization: None, include: None, bind: None, sleep: Some(Duration(10s)), defines: [] }
+
+$ typed-derive --sleep forever
+? failed
+error: Invalid value "forever" for '--sleep <SLEEP>': expected number at 0
+
+For more information try --help
+
+```
+
+Defines (key-value pairs)
+```console
+$ typed-derive -D Foo=10 -D Alice=30
+Args { optimization: None, include: None, bind: None, sleep: None, defines: [("Foo", 10), ("Alice", 30)] }
+
+$ typed-derive -D Foo
+? failed
+error: Invalid value "Foo" for '-D <DEFINES>': invalid KEY=value: no `=` found in `Foo`
+
+For more information try --help
+
+$ typed-derive -D Foo=Bar
+? failed
+error: Invalid value "Foo=Bar" for '-D <DEFINES>': invalid digit found in string
+
+For more information try --help
+
+```
diff --git a/3.2.23/examples/typed-derive.rs b/3.2.23/examples/typed-derive.rs
new file mode 100644
index 0000000..3108402
--- /dev/null
+++ b/3.2.23/examples/typed-derive.rs
@@ -0,0 +1,44 @@
+use clap::Parser;
+use std::error::Error;
+
+#[derive(Parser, Debug)] // requires `derive` feature
+struct Args {
+ /// Implicitly using `std::str::FromStr`
+ #[clap(short = 'O', value_parser)]
+ optimization: Option<usize>,
+
+ /// Allow invalid UTF-8 paths
+ #[clap(short = 'I', value_parser, value_name = "DIR", value_hint = clap::ValueHint::DirPath)]
+ include: Option<std::path::PathBuf>,
+
+ /// Handle IP addresses
+ #[clap(long, value_parser)]
+ bind: Option<std::net::IpAddr>,
+
+ /// Allow human-readable durations
+ #[clap(long, value_parser)]
+ sleep: Option<humantime::Duration>,
+
+ /// Hand-written parser for tuples
+ #[clap(short = 'D', value_parser = parse_key_val::<String, i32>)]
+ defines: Vec<(String, i32)>,
+}
+
+/// Parse a single key-value pair
+fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>>
+where
+ T: std::str::FromStr,
+ T::Err: Error + Send + Sync + 'static,
+ U: std::str::FromStr,
+ U::Err: Error + Send + Sync + 'static,
+{
+ let pos = s
+ .find('=')
+ .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?;
+ Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
+}
+
+fn main() {
+ let args = Args::parse();
+ println!("{:?}", args);
+}
diff --git a/3.2.23/patches/Android.bp.diff b/3.2.23/patches/Android.bp.diff
new file mode 100644
index 0000000..b79bef0
--- /dev/null
+++ b/3.2.23/patches/Android.bp.diff
@@ -0,0 +1,35 @@
+diff --git a/3.2.23/Android.bp b/3.2.23/Android.bp
+index 0593d09..0e1e5ea 100644
+--- a/3.2.23/Android.bp
++++ b/3.2.23/Android.bp
+@@ -4,7 +4,7 @@
+
+
+ rust_library {
+- name: "libclap",
++ name: "libclap_3.2.23",
+ host_supported: true,
+ crate_name: "clap",
+ cargo_env_compat: true,
+@@ -23,21 +23,3 @@ rust_library {
+ "//apex_available:anyapex",
+ ],
+ }
+-
+-rust_binary {
+- name: "stdio_fixture",
+- host_supported: true,
+- crate_name: "stdio_fixture",
+- cargo_env_compat: true,
+- cargo_pkg_version: "3.2.23",
+- srcs: ["src/bin/stdio-fixture.rs"],
+- edition: "2021",
+- features: ["std"],
+- rustlibs: [
+- "libbitflags",
+- "libclap",
+- "libclap_lex",
+- "libindexmap",
+- "libtextwrap",
+- ],
+-}
diff --git a/3.2.23/src/_cookbook/cargo_example.rs b/3.2.23/src/_cookbook/cargo_example.rs
new file mode 100644
index 0000000..ec5d582
--- /dev/null
+++ b/3.2.23/src/_cookbook/cargo_example.rs
@@ -0,0 +1,7 @@
+//! # Example: cargo subcommand (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/cargo-example.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/cargo-example.md")]
diff --git a/3.2.23/src/_cookbook/cargo_example_derive b/3.2.23/src/_cookbook/cargo_example_derive
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/3.2.23/src/_cookbook/cargo_example_derive
diff --git a/3.2.23/src/_cookbook/cargo_example_derive.rs b/3.2.23/src/_cookbook/cargo_example_derive.rs
new file mode 100644
index 0000000..d49f956
--- /dev/null
+++ b/3.2.23/src/_cookbook/cargo_example_derive.rs
@@ -0,0 +1,7 @@
+//! # Example: cargo subcommand (Derive API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/cargo-example-derive.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/cargo-example-derive.md")]
diff --git a/3.2.23/src/_cookbook/escaped_positional.rs b/3.2.23/src/_cookbook/escaped_positional.rs
new file mode 100644
index 0000000..99a3f83
--- /dev/null
+++ b/3.2.23/src/_cookbook/escaped_positional.rs
@@ -0,0 +1,7 @@
+//! # Example (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/escaped-positional.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/escaped-positional.md")]
diff --git a/3.2.23/src/_cookbook/escaped_positional_derive.rs b/3.2.23/src/_cookbook/escaped_positional_derive.rs
new file mode 100644
index 0000000..e6f99ad
--- /dev/null
+++ b/3.2.23/src/_cookbook/escaped_positional_derive.rs
@@ -0,0 +1,7 @@
+//! # Example (Derive API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/escaped-positional-derive.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/escaped-positional-derive.md")]
diff --git a/3.2.23/src/_cookbook/git.rs b/3.2.23/src/_cookbook/git.rs
new file mode 100644
index 0000000..03a926c
--- /dev/null
+++ b/3.2.23/src/_cookbook/git.rs
@@ -0,0 +1,7 @@
+//! # Example: git-like CLI (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/git.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/git.md")]
diff --git a/3.2.23/src/_cookbook/git_derive.rs b/3.2.23/src/_cookbook/git_derive.rs
new file mode 100644
index 0000000..d311973
--- /dev/null
+++ b/3.2.23/src/_cookbook/git_derive.rs
@@ -0,0 +1,7 @@
+//! # Example: git-like CLI (Derive API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/git-derive.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/git-derive.md")]
diff --git a/3.2.23/src/_cookbook/mod.rs b/3.2.23/src/_cookbook/mod.rs
new file mode 100644
index 0000000..1a78ed1
--- /dev/null
+++ b/3.2.23/src/_cookbook/mod.rs
@@ -0,0 +1,55 @@
+// Contributing
+//
+// New examples:
+// - Building: They must be added to `Cargo.toml` with the appropriate `required-features`.
+// - Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax
+// - Link the `.md` file from here
+
+//! # Documentation: Cookbook
+//!
+//! Typed arguments: [derive][typed_derive]
+//! - Topics:
+//! - Custom `parse()`
+//!
+//! Custom cargo command: [builder][cargo_example], [derive][cargo_example_derive]
+//! - Topics:
+//! - Subcommands
+//! - Cargo plugins
+//!
+//! git-like interface: [builder][git], [derive][git_derive]
+//! - Topics:
+//! - Subcommands
+//! - External subcommands
+//! - Optional subcommands
+//! - Default subcommands
+//!
+//! pacman-like interface: [builder][pacman]
+//! - Topics:
+//! - Flag subcommands
+//! - Conflicting arguments
+//!
+//! Escaped positionals with `--`: [builder][escaped_positional], [derive][escaped_positional_derive]
+//!
+//! Multi-call
+//! - busybox: [builder][multicall_busybox]
+//! - Topics:
+//! - Subcommands
+//! - hostname: [builder][multicall_hostname]
+//! - Topics:
+//! - Subcommands
+//!
+//! repl: [builder][repl]
+//! - Topics:
+//! - Read-Eval-Print Loops / Custom command lines
+
+pub mod cargo_example;
+pub mod cargo_example_derive;
+pub mod escaped_positional;
+pub mod escaped_positional_derive;
+pub mod git;
+pub mod git_derive;
+pub mod multicall_busybox;
+pub mod multicall_hostname;
+pub mod pacman;
+pub mod repl;
+pub mod typed_derive;
diff --git a/3.2.23/src/_cookbook/multicall_busybox.rs b/3.2.23/src/_cookbook/multicall_busybox.rs
new file mode 100644
index 0000000..e3384d6
--- /dev/null
+++ b/3.2.23/src/_cookbook/multicall_busybox.rs
@@ -0,0 +1,7 @@
+//! # Example: busybox-like CLI (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/multicall-busybox.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/multicall-busybox.md")]
diff --git a/3.2.23/src/_cookbook/multicall_hostname.rs b/3.2.23/src/_cookbook/multicall_hostname.rs
new file mode 100644
index 0000000..9777654
--- /dev/null
+++ b/3.2.23/src/_cookbook/multicall_hostname.rs
@@ -0,0 +1,7 @@
+//! # Example: hostname-like CLI (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/multicall-hostname.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/multicall-hostname.md")]
diff --git a/3.2.23/src/_cookbook/pacman.rs b/3.2.23/src/_cookbook/pacman.rs
new file mode 100644
index 0000000..880c581
--- /dev/null
+++ b/3.2.23/src/_cookbook/pacman.rs
@@ -0,0 +1,7 @@
+//! # Example: pacman-like CLI (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/pacman.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/pacman.md")]
diff --git a/3.2.23/src/_cookbook/repl.rs b/3.2.23/src/_cookbook/repl.rs
new file mode 100644
index 0000000..549ec82
--- /dev/null
+++ b/3.2.23/src/_cookbook/repl.rs
@@ -0,0 +1,5 @@
+//! # Example: Command REPL (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/repl.rs")]
+//! ```
diff --git a/3.2.23/src/_cookbook/typed_derive.rs b/3.2.23/src/_cookbook/typed_derive.rs
new file mode 100644
index 0000000..a5fd15f
--- /dev/null
+++ b/3.2.23/src/_cookbook/typed_derive.rs
@@ -0,0 +1,7 @@
+//! # Example: Custom Types (Derive API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/typed-derive.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/typed-derive.md")]
diff --git a/3.2.23/src/_derive/_tutorial.rs b/3.2.23/src/_derive/_tutorial.rs
new file mode 100644
index 0000000..abd57ce
--- /dev/null
+++ b/3.2.23/src/_derive/_tutorial.rs
@@ -0,0 +1,205 @@
+// Contributing
+//
+// New example code:
+// - Please update the corresponding section in the derive tutorial
+// - Building: They must be added to `Cargo.toml` with the appropriate `required-features`.
+// - Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax
+//
+// See also the general CONTRIBUTING
+
+//! # Documentation: Derive Tutorial
+//!
+//! 1. [Quick Start](#quick-start)
+//! 2. [Configuring the Parser](#configuring-the-parser)
+//! 3. [Adding Arguments](#adding-arguments)
+//! 1. [Positionals](#positionals)
+//! 2. [Options](#options)
+//! 3. [Flags](#flags)
+//! 4. [Subcommands](#subcommands)
+//! 5. [Defaults](#defaults)
+//! 4. Validation
+//! 1. [Enumerated values](#enumerated-values)
+//! 2. [Validated values](#validated-values)
+//! 3. [Argument Relations](#argument-relations)
+//! 4. [Custom Validation](#custom-validation)
+//! 5. [Testing](#testing)
+//!
+//! See also
+//! - [FAQ: When should I use the builder vs derive APIs?][crate::_faq#when-should-i-use-the-builder-vs-derive-apis]
+//! - The [cookbook][crate::_cookbook] for more application-focused examples
+//!
+//! ## Quick Start
+//!
+//! You can create an application declaratively with a `struct` and some
+//! attributes. **This requires enabling the [`derive` feature flag][crate::_features].**
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/01_quick.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/tutorial_derive/01_quick.md")]
+//!
+//! ## Configuring the Parser
+//!
+//! You use derive [`Parser`][crate::Parser] to start building a parser.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/02_apps.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/tutorial_derive/02_apps.md")]
+//!
+//! You can use `#[clap(author, version, about)]` attribute defaults to fill these fields in from your `Cargo.toml` file.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/02_crate.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/02_crate.md")]
+//!
+//! You can use attributes to change the application level behavior of clap. Any [`Command`][crate::Command]] builder function can be used as an attribute.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/02_app_settings.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/02_app_settings.md")]
+//!
+//! ## Adding Arguments
+//!
+//! ### Positionals
+//!
+//! You can have users specify values by their position on the command-line:
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_03_positional.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/03_03_positional.md")]
+//!
+//! ### Options
+//!
+//! You can name your arguments with a flag:
+//! - Order doesn't matter
+//! - They can be optional
+//! - Intent is clearer
+//!
+//! The `#[clap(short = 'n')]` and `#[clap(long = "name")]` attributes that define
+//! the flags are [`Arg`][crate::Args] methods that are derived from the field name when no value
+//! is specified (`#[clap(short)]` and `#[clap(long)]`).
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_02_option.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/03_02_option.md")]
+//!
+//! ### Flags
+//!
+//! Flags can also be switches that can be on/off. This is enabled via the
+//! `#[clap(action = ArgAction::SetTrue)]` attribute though this is implied when the field is a
+//! `bool`.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_bool.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_bool.md")]
+//!
+//! Or counted with `#[clap(action = clap::ArgAction::Count)]`:
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_count.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_count.md")]
+//!
+//! ### Subcommands
+//!
+//! Subcommands are derived with `#[derive(Subcommand)]` and be added via `#[clap(subcommand)]` attribute. Each
+//! instance of a [Subcommand][crate::Subcommand] can have its own version, author(s), Args, and even its own
+//! subcommands.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_04_subcommands.rs")]
+//! ```
+//! We used a struct-variant to define the `add` subcommand.
+//! Alternatively, you can use a struct for your subcommand's arguments:
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_04_subcommands_alt.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/tutorial_derive/03_04_subcommands.md")]
+//!
+//! ### Defaults
+//!
+//! We've previously showed that arguments can be [`required`][crate::Arg::required] or optional.
+//! When optional, you work with a `Option` and can `unwrap_or`. Alternatively, you can
+//! set `#[clap(default_value_t)]`.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_05_default_values.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/03_05_default_values.md")]
+//!
+//! ## Validation
+//!
+//! ### Enumerated values
+//!
+//! If you have arguments of specific values you want to test for, you can derive
+//! [`ValueEnum`][crate::ValueEnum].
+//!
+//! This allows you specify the valid values for that argument. If the user does not use one of
+//! those specific values, they will receive a graceful exit with error message informing them
+//! of the mistake, and what the possible valid values are
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/04_01_enum.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/04_01_enum.md")]
+//!
+//! ### Validated values
+//!
+//! More generally, you can validate and parse into any data type.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/04_02_parse.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/04_02_parse.md")]
+//!
+//! A custom parser can be used to improve the error messages or provide additional validation:
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/04_02_validate.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/04_02_validate.md")]
+//!
+//! ### Argument Relations
+//!
+//! You can declare dependencies or conflicts between [`Arg`][crate::Arg]s or even
+//! [`ArgGroup`][crate::ArgGroup]s.
+//!
+//! [`ArgGroup`][crate::ArgGroup]s make it easier to declare relations instead of having to list
+//! each individually, or when you want a rule to apply "any but not all" arguments.
+//!
+//! Perhaps the most common use of [`ArgGroup`][crate::ArgGroup]s is to require one and *only* one
+//! argument to be present out of a given set. Imagine that you had multiple arguments, and you
+//! want one of them to be required, but making all of them required isn't feasible because perhaps
+//! they conflict with each other.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/04_03_relations.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/04_03_relations.md")]
+//!
+//! ### Custom Validation
+//!
+//! As a last resort, you can create custom errors with the basics of clap's formatting.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/04_04_custom.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/04_04_custom.md")]
+//!
+//! ## Testing
+//!
+//! clap reports most development errors as `debug_assert!`s. Rather than checking every
+//! subcommand, you should have a test that calls
+//! [`Command::debug_assert`][crate::App::debug_assert]:
+//! ```rust,no_run
+#![doc = include_str!("../../examples/tutorial_derive/05_01_assert.rs")]
+//! ```
diff --git a/3.2.23/src/_derive/mod.rs b/3.2.23/src/_derive/mod.rs
new file mode 100644
index 0000000..fc9f35d
--- /dev/null
+++ b/3.2.23/src/_derive/mod.rs
@@ -0,0 +1,510 @@
+//! # Documentation: Derive Reference
+//!
+//! 1. [Overview](#overview)
+//! 2. [Attributes](#attributes)
+//! 1. [Terminology](#terminology)
+//! 2. [Command Attributes](#command-attributes)
+//! 3. [Arg Attributes](#arg-attributes)
+//! 4. [ValueEnum Attributes](#valueenum-attributes)
+//! 5. [Possible Value Attributes](#possible-value-attributes)
+//! 3. [Arg Types](#arg-types)
+//! 4. [Doc Comments](#doc-comments)
+//! 5. [Mixing Builder and Derive APIs](#mixing-builder-and-derive-apis)
+//! 6. [Tips](#tips)
+//!
+//! ## Overview
+//!
+//! To derive `clap` types, you need to enable the [`derive` feature flag][crate::_features].
+//!
+//! Example:
+//! ```rust
+#![doc = include_str!("../../examples/demo.rs")]
+//! ```
+//!
+//! Let's start by breaking down the anatomy of the derive attributes:
+//! ```rust
+//! use clap::{Parser, Args, Subcommand, ValueEnum};
+//!
+//! /// Doc comment
+//! #[derive(Parser)]
+//! #[clap(APP ATTRIBUTE)]
+//! struct Cli {
+//! /// Doc comment
+//! #[clap(ARG ATTRIBUTE)]
+//! field: UserType,
+//!
+//! #[clap(value_enum, ARG ATTRIBUTE...)]
+//! field: EnumValues,
+//!
+//! #[clap(flatten)]
+//! delegate: Struct,
+//!
+//! #[clap(subcommand)]
+//! command: Command,
+//! }
+//!
+//! /// Doc comment
+//! #[derive(Args)]
+//! #[clap(PARENT APP ATTRIBUTE)]
+//! struct Struct {
+//! /// Doc comment
+//! #[clap(ARG ATTRIBUTE)]
+//! field: UserType,
+//! }
+//!
+//! /// Doc comment
+//! #[derive(Subcommand)]
+//! #[clap(PARENT APP ATTRIBUTE)]
+//! enum Command {
+//! /// Doc comment
+//! #[clap(APP ATTRIBUTE)]
+//! Variant1(Struct),
+//!
+//! /// Doc comment
+//! #[clap(APP ATTRIBUTE)]
+//! Variant2 {
+//! /// Doc comment
+//! #[clap(ARG ATTRIBUTE)]
+//! field: UserType,
+//! }
+//! }
+//!
+//! /// Doc comment
+//! #[derive(ValueEnum)]
+//! #[clap(VALUE ENUM ATTRIBUTE)]
+//! enum EnumValues {
+//! /// Doc comment
+//! #[clap(POSSIBLE VALUE ATTRIBUTE)]
+//! Variant1,
+//! }
+//!
+//! fn main() {
+//! let cli = Cli::parse();
+//! }
+//! ```
+//!
+//! Traits:
+//! - [`Parser`][crate::Parser] parses arguments into a `struct` (arguments) or `enum` (subcommands).
+//! - [`Args`][crate::Args] allows defining a set of re-usable arguments that get merged into their parent container.
+//! - [`Subcommand`][crate::Subcommand] defines available subcommands.
+//! - Subcommand arguments can be defined in a struct-variant or automatically flattened with a tuple-variant.
+//! - [`ValueEnum`][crate::ValueEnum] allows parsing a value directly into an `enum`, erroring on unsupported values.
+//! - The derive doesn't work on enums that contain non-unit variants, unless they are skipped
+//!
+//! *See also the [derive tutorial][crate::_derive::_tutorial] and [cookbook][crate::_cookbook]*
+//!
+//! ## Attributes
+//!
+//! ### Terminology
+//!
+//! **Raw attributes** are forwarded directly to the underlying [`clap` builder][crate::builder]. Any
+//! [`Command`][crate::Command], [`Arg`][crate::Arg], or [`PossibleValue`][crate::PossibleValue] method can be used as an attribute.
+//!
+//! Raw attributes come in two different syntaxes:
+//! ```rust,ignore
+//! #[clap(
+//! global = true, // name = arg form, neat for one-arg methods
+//! required_if_eq("out", "file") // name(arg1, arg2, ...) form.
+//! )]
+//! ```
+//!
+//! - `method = arg` can only be used for methods which take only one argument.
+//! - `method(arg1, arg2)` can be used with any method.
+//!
+//! As long as `method_name` is not one of the magical methods it will be
+//! translated into a mere method call.
+//!
+//! **Magic attributes** have post-processing done to them, whether that is
+//! - Providing of defaults
+//! - Special behavior is triggered off of it
+//!
+//! Magic attributes are more constrained in the syntax they support, usually just
+//! `<attr> = <value>` though some use `<attr>(<value>)` instead. See the specific
+//! magic attributes documentation for details. This allows users to access the
+//! raw behavior of an attribute via `<attr>(<value>)` syntax.
+//!
+//! **NOTE:** Some attributes are inferred from [Arg Types](#arg-types) and [Doc
+//! Comments](#doc-comments). Explicit attributes take precedence over inferred
+//! attributes.
+//!
+//! ### Command Attributes
+//!
+//! These correspond to a [`Command`][crate::Command] which is used for both top-level parsers and
+//! when defining subcommands.
+//!
+//! **Raw attributes:** Any [`Command` method][crate::Command] can also be used as an attribute,
+//! see [Terminology](#terminology) for syntax.
+//! - e.g. `#[clap(arg_required_else_help(true))]` would translate to `cmd.arg_required_else_help(true)`
+//!
+//! **Magic attributes:**
+//! - `name = <expr>`: [`Command::name`][crate::App::name]
+//! - When not present: [crate `name`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-name-field) (if on [`Parser`][crate::Parser] container), variant name (if on [`Subcommand`][crate::Subcommand] variant)
+//! - `version [= <expr>]`: [`Command::version`][crate::App::version]
+//! - When not present: no version set
+//! - Without `<expr>`: defaults to [crate `version`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field)
+//! - `author [= <expr>]`: [`Command::author`][crate::App::author]
+//! - When not present: no author set
+//! - Without `<expr>`: defaults to [crate `authors`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field)
+//! - `about [= <expr>]`: [`Command::about`][crate::App::about]
+//! - When not present: [Doc comment summary](#doc-comments)
+//! - Without `<expr>`: [crate `description`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-description-field) ([`Parser`][crate::Parser] container)
+//! - **TIP:** When a doc comment is also present, you most likely want to add
+//! `#[clap(long_about = None)]` to clear the doc comment so only [`about`][crate::App::about]
+//! gets shown with both `-h` and `--help`.
+//! - `long_about = <expr>`: [`Command::long_about`][crate::App::long_about]
+//! - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing
+//! - `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to [`about`][crate::App::about] / [`long_about`][crate::App::long_about]
+//! - `next_display_order`: [`Command::next_display_order`][crate::App::next_display_order]
+//! - `next_help_heading`: [`Command::next_help_heading`][crate::App::next_help_heading]
+//! - When `flatten`ing [`Args`][crate::Args], this is scoped to just the args in this struct and any struct `flatten`ed into it
+//! - `rename_all = <string_literal>`: Override default field / variant name case conversion for [`Command::name`][crate::Command::name] / [`Arg::id`][crate::Arg::id]
+//! - When not present: `"kebab-case"`
+//! - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"`
+//! - `rename_all_env = <string_literal>`: Override default field name case conversion for env variables for [`Arg::env`][crate::Arg::env]
+//! - When not present: `"SCREAMING_SNAKE_CASE"`
+//! - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"`
+//!
+//! And for [`Subcommand`][crate::Subcommand] variants:
+//! - `skip`: Ignore this variant
+//! - `flatten`: Delegates to the variant for more subcommands (must implement
+//! [`Subcommand`][crate::Subcommand])
+//! - `subcommand`: Nest subcommands under the current set of subcommands (must implement
+//! [`Subcommand`][crate::Subcommand])
+//! - `external_subcommand`: [`Command::allow_external_subcommand(true)`][crate::App::allow_external_subcommands]
+//! - Variant must be either `Variant(Vec<String>)` or `Variant(Vec<OsString>)`
+//!
+//! ### Arg Attributes
+//!
+//! These correspond to a [`Arg`][crate::Arg].
+//!
+//! **Raw attributes:** Any [`Arg` method][crate::Arg] can also be used as an attribute, see [Terminology](#terminology) for syntax.
+//! - e.g. `#[clap(max_values(3))]` would translate to `arg.max_values(3)`
+//!
+//! **Magic attributes**:
+//! - `id = <expr>`: [`Arg::id`][crate::Arg::id]
+//! - When not present: case-converted field name is used
+//! - `name = <expr>`: [`Arg::id`][crate::Arg::id]
+//! - **Deprecated:** use `id`
+//! - `value_parser [= <expr>]`: [`Arg::value_parser`][crate::Arg::value_parser]
+//! - When not present: will auto-select an implementation based on the field type using
+//! [`value_parser!][crate::value_parser!]
+//! - When present but defaulted: opt-in to clap v4 semantics
+//! - Env parsing is now dependent on inferred parser
+//! - `PathBuf` will implicitly skip UTF-8 validation (before it required specifying
+//! `try_from_os_str`)
+//! - When present, implies `#[clap(action)]`
+//! - To register a custom type's [`ValueParser`][crate::builder::ValueParser], implement [`ValueParserFactory`][crate::builder::ValueParserFactory]
+//! - `action [= <expr>]`: [`Arg::action`][crate::Arg::action]
+//! - When not present: will auto-select an action based on the field type
+//! - When present but defaulted: opt-in to clap v4 semantics
+//! - When present, implies `#[clap(value_parser)]`
+//! - `args_override_self` is forced on for single flags
+//! - `help = <expr>`: [`Arg::help`][crate::Arg::help]
+//! - When not present: [Doc comment summary](#doc-comments)
+//! - `long_help = <expr>`: [`Arg::long_help`][crate::Arg::long_help]
+//! - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing
+//! - `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to [`help`][crate::Arg::help] / [`long_help`][crate::Arg::long_help]
+//! - `short [= <char>]`: [`Arg::short`][crate::Arg::short]
+//! - When not present: no short set
+//! - Without `<char>`: defaults to first character in the case-converted field name
+//! - `long [= <str>]`: [`Arg::long`][crate::Arg::long]
+//! - When not present: no long set
+//! - Without `<str>`: defaults to the case-converted field name
+//! - `env [= <str>]`: [`Arg::env`][crate::Arg::env] (needs [`env` feature][crate::_features] enabled)
+//! - When not present: no env set
+//! - Without `<str>`: defaults to the case-converted field name
+//! - `flatten`: Delegates to the field for more arguments (must implement [`Args`][crate::Args])
+//! - Only [`next_help_heading`][crate::Command::next_help_heading] can be used with `flatten`. See
+//! [clap-rs/clap#3269](https://github.com/clap-rs/clap/issues/3269) for why
+//! arg attributes are not generally supported.
+//! - **Tip:** Though we do apply a flattened [`Args`][crate::Args]'s Parent Command Attributes, this
+//! makes reuse harder. Generally prefer putting the cmd attributes on the
+//! [`Parser`][crate::Parser] or on the flattened field.
+//! - `subcommand`: Delegates definition of subcommands to the field (must implement
+//! [`Subcommand`][crate::Subcommand])
+//! - When `Option<T>`, the subcommand becomes optional
+//! - `from_global`: Read a [`Arg::global`][crate::Arg::global] argument (raw attribute), regardless of what subcommand you are in
+//! - `parse(<kind> [= <function>])`: [`Arg::validator`][crate::Arg::validator] and [`ArgMatches::values_of_t`][crate::ArgMatches::values_of_t]
+//! - **Deprecated:**
+//! - Use `value_parser(...)` for `from_str`, `try_from_str`, `from_os_str`, and `try_from_os_str`
+//! - Use `action(ArgAction::Count` for `from_occurrences`
+//! - Use `action(ArgAction::SetTrue` for `from_flag`
+//! - Default: `try_from_str`
+//! - Warning: for `Path` / `OsString`, be sure to use `try_from_os_str`
+//! - See [Arg Types](#arg-types) for more details
+//! - `value_enum`: Parse the value using the [`ValueEnum`][crate::ValueEnum]
+//! - `skip [= <expr>]`: Ignore this field, filling in with `<expr>`
+//! - Without `<expr>`: fills the field with `Default::default()`
+//! - `default_value = <str>`: [`Arg::default_value`][crate::Arg::default_value] and [`Arg::required(false)`][crate::Arg::required]
+//! - `default_value_t [= <expr>]`: [`Arg::default_value`][crate::Arg::default_value] and [`Arg::required(false)`][crate::Arg::required]
+//! - Requires `std::fmt::Display` or `#[clap(value_enum)]`
+//! - Without `<expr>`, relies on `Default::default()`
+//! - `default_values_t = <expr>`: [`Arg::default_values`][crate::Arg::default_values] and [`Arg::required(false)`][crate::Arg::required]
+//! - Requires field arg to be of type `Vec<T>` and `T` to implement `std::fmt::Display` or `#[clap(value_enum)]`
+//! - `<expr>` must implement `IntoIterator<T>`
+//! - `default_value_os_t [= <expr>]`: [`Arg::default_value_os`][crate::Arg::default_value_os] and [`Arg::required(false)`][crate::Arg::required]
+//! - Requires `std::convert::Into<OsString>` or `#[clap(value_enum)]`
+//! - Without `<expr>`, relies on `Default::default()`
+//! - `default_values_os_t = <expr>`: [`Arg::default_values_os`][crate::Arg::default_values_os] and [`Arg::required(false)`][crate::Arg::required]
+//! - Requires field arg to be of type `Vec<T>` and `T` to implement `std::convert::Into<OsString>` or `#[clap(value_enum)]`
+//! - `<expr>` must implement `IntoIterator<T>`
+//!
+//! ### ValueEnum Attributes
+//!
+//! - `rename_all = <string_literal>`: Override default field / variant name case conversion for [`PossibleValue::new`][crate::PossibleValue]
+//! - When not present: `"kebab-case"`
+//! - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"`
+//!
+//! ### Possible Value Attributes
+//!
+//! These correspond to a [`PossibleValue`][crate::PossibleValue].
+//!
+//! **Raw attributes:** Any [`PossibleValue` method][crate::PossibleValue] can also be used as an attribute, see [Terminology](#terminology) for syntax.
+//! - e.g. `#[clap(alias("foo"))]` would translate to `pv.alias("foo")`
+//!
+//! **Magic attributes**:
+//! - `name = <expr>`: [`PossibleValue::new`][crate::PossibleValue::new]
+//! - When not present: case-converted field name is used
+//! - `help = <expr>`: [`PossibleValue::help`][crate::PossibleValue::help]
+//! - When not present: [Doc comment summary](#doc-comments)
+//!
+//! ## Arg Types
+//!
+//! `clap` assumes some intent based on the type used:
+//!
+//! | Type | Effect | Implies |
+//! |---------------------|--------------------------------------|------------------------------------------------------------------|
+//! | `bool` | flag | `#[clap(parse(from_flag))]` |
+//! | `Option<T>` | optional argument | `.takes_value(true).required(false)` |
+//! | `Option<Option<T>>` | optional value for optional argument | `.takes_value(true).required(false).min_values(0).max_values(1)` |
+//! | `T` | required argument | `.takes_value(true).required(!has_default)` |
+//! | `Vec<T>` | `0..` occurrences of argument | `.takes_value(true).required(false).multiple_occurrences(true)` |
+//! | `Option<Vec<T>>` | `0..` occurrences of argument | `.takes_value(true).required(false).multiple_occurrences(true)` |
+//!
+//! Notes:
+//! - For custom type behavior, you can override the implied attributes/settings and/or set additional ones
+//! - For example, see [custom-bool](./custom-bool.md)
+//! - `Option<Vec<T>>` will be `None` instead of `vec![]` if no arguments are provided.
+//! - This gives the user some flexibility in designing their argument, like with `min_values(0)`
+//!
+//! You can then support your custom type with `#[clap(parse(<kind> [= <function>]))]`:
+//!
+//! | `<kind>` | Signature | Default `<function>` |
+//! |--------------------------|---------------------------------------|---------------------------------|
+//! | `from_str` | `fn(&str) -> T` | `::std::convert::From::from` |
+//! | `try_from_str` (default) | `fn(&str) -> Result<T, E>` | `::std::str::FromStr::from_str` |
+//! | `from_os_str` | `fn(&OsStr) -> T` | `::std::convert::From::from` |
+//! | `try_from_os_str` | `fn(&OsStr) -> Result<T, E>` | (no default function) |
+//! | `from_occurrences` | `fn(u64) -> T` | `value as T` |
+//! | `from_flag` | `fn(bool) -> T` | `::std::convert::From::from` |
+//!
+//! Notes:
+//! - `from_os_str`:
+//! - Implies `arg.takes_value(true).allow_invalid_utf8(true)`
+//! - `try_from_os_str`:
+//! - Implies `arg.takes_value(true).allow_invalid_utf8(true)`
+//! - `from_occurrences`:
+//! - Implies `arg.takes_value(false).multiple_occurrences(true)`
+//! - Reads from `clap::ArgMatches::occurrences_of` rather than a `get_one` function
+//! - Note: operations on values, like `default_value`, are unlikely to do what you want
+//! - `from_flag`
+//! - Implies `arg.takes_value(false)`
+//! - Reads from `clap::ArgMatches::is_present` rather than a `get_one` function
+//! - Note: operations on values, like `default_value`, are unlikely to do what you want
+//!
+//! **Warning:**
+//! - To support non-UTF8 paths, you should use `#[clap(value_parser)]` otherwise
+//! `clap` will parse it as a `String` which will fail on some paths.
+//!
+//! ## Doc Comments
+//!
+//! In clap, help messages for the whole binary can be specified
+//! via [`Command::about`][crate::App::about] and [`Command::long_about`][crate::App::long_about] while help messages
+//! for individual arguments can be specified via [`Arg::help`][crate::Arg::help] and [`Arg::long_help`][crate::Arg::long_help].
+//!
+//! `long_*` variants are used when user calls the program with
+//! `--help` and "short" variants are used with `-h` flag.
+//!
+//! ```rust
+//! # use clap::Parser;
+//!
+//! #[derive(Parser)]
+//! #[clap(about = "I am a program and I work, just pass `-h`", long_about = None)]
+//! struct Foo {
+//! #[clap(short, help = "Pass `-h` and you'll see me!")]
+//! bar: String,
+//! }
+//! ```
+//!
+//! For convenience, doc comments can be used instead of raw methods
+//! (this example works exactly like the one above):
+//!
+//! ```rust
+//! # use clap::Parser;
+//!
+//! #[derive(Parser)]
+//! /// I am a program and I work, just pass `-h`
+//! struct Foo {
+//! /// Pass `-h` and you'll see me!
+//! bar: String,
+//! }
+//! ```
+//!
+//! **NOTE:** Attributes have priority over doc comments!
+//!
+//! **Top level doc comments always generate `Command::about/long_about` calls!**
+//! If you really want to use the `Command::about/long_about` methods (you likely don't),
+//! use the `about` / `long_about` attributes to override the calls generated from
+//! the doc comment. To clear `long_about`, you can use
+//! `#[clap(long_about = None)]`.
+//!
+//! **TIP:** Set `#![deny(missing_docs)]` to catch missing `--help` documentation at compile time.
+//!
+//! ### Pre-processing
+//!
+//! ```rust
+//! # use clap::Parser;
+//! #[derive(Parser)]
+//! /// Hi there, I'm Robo!
+//! ///
+//! /// I like beeping, stumbling, eating your electricity,
+//! /// and making records of you singing in a shower.
+//! /// Pay up, or I'll upload it to youtube!
+//! struct Robo {
+//! /// Call my brother SkyNet.
+//! ///
+//! /// I am artificial superintelligence. I won't rest
+//! /// until I'll have destroyed humanity. Enjoy your
+//! /// pathetic existence, you mere mortals.
+//! #[clap(long, action)]
+//! kill_all_humans: bool,
+//! }
+//! ```
+//!
+//! A doc comment consists of three parts:
+//! - Short summary
+//! - A blank line (whitespace only)
+//! - Detailed description, all the rest
+//!
+//! The summary corresponds with `Command::about` / `Arg::help`. When a blank line is
+//! present, the whole doc comment will be passed to `Command::long_about` /
+//! `Arg::long_help`. Or in other words, a doc may result in just a `Command::about` /
+//! `Arg::help` or `Command::about` / `Arg::help` and `Command::long_about` /
+//! `Arg::long_help`
+//!
+//! In addition, when `verbatim_doc_comment` is not present, `clap` applies some preprocessing, including:
+//!
+//! - Strip leading and trailing whitespace from every line, if present.
+//!
+//! - Strip leading and trailing blank lines, if present.
+//!
+//! - Interpret each group of non-empty lines as a word-wrapped paragraph.
+//!
+//! We replace newlines within paragraphs with spaces to allow the output
+//! to be re-wrapped to the terminal width.
+//!
+//! - Strip any excess blank lines so that there is exactly one per paragraph break.
+//!
+//! - If the first paragraph ends in exactly one period,
+//! remove the trailing period (i.e. strip trailing periods but not trailing ellipses).
+//!
+//! Sometimes you don't want this preprocessing to apply, for example the comment contains
+//! some ASCII art or markdown tables, you would need to preserve LFs along with
+//! blank lines and the leading/trailing whitespace. When you pass use the
+//! `verbatim_doc_comment` magic attribute, you preserve
+//! them.
+//!
+//! **Note:** Keep in mind that `verbatim_doc_comment` will *still*
+//! - Remove one leading space from each line, even if this attribute is present,
+//! to allow for a space between `///` and the content.
+//! - Remove leading and trailing blank lines
+//!
+//! ## Mixing Builder and Derive APIs
+//!
+//! The builder and derive APIs do not live in isolation. They can work together, which is
+//! especially helpful if some arguments can be specified at compile-time while others must be
+//! specified at runtime.
+//!
+//! ### Using derived arguments in a builder application
+//!
+//! When using the derive API, you can `#[clap(flatten)]` a struct deriving `Args` into a struct
+//! deriving `Args` or `Parser`. This example shows how you can augment a `Command` instance
+//! created using the builder API with `Args` created using the derive API.
+//!
+//! It uses the [`Args::augment_args`][crate::Args::augment_args] method to add the arguments to
+//! the `Command` instance.
+//!
+//! Crates such as [clap-verbosity-flag](https://github.com/rust-cli/clap-verbosity-flag) provide
+//! structs that implement `Args`. Without the technique shown in this example, it would not be
+//! possible to use such crates with the builder API.
+//!
+//! For example:
+//! ```rust
+#![doc = include_str!("../../examples/derive_ref/augment_args.rs")]
+//! ```
+//!
+//! ### Using derived subcommands in a builder application
+//!
+//! When using the derive API, you can use `#[clap(subcommand)]` inside the struct to add
+//! subcommands. The type of the field is usually an enum that derived `Parser`. However, you can
+//! also add the subcommands in that enum to a `Command` instance created with the builder API.
+//!
+//! It uses the [`Subcommand::augment_subcommands`][crate::Subcommand::augment_subcommands] method
+//! to add the subcommands to the `Command` instance.
+//!
+//! For example:
+//! ```rust
+#![doc = include_str!("../../examples/derive_ref/augment_subcommands.rs")]
+//! ```
+//!
+//! ### Adding hand-implemented subcommands to a derived application
+//!
+//! When using the derive API, you can use `#[clap(subcommand)]` inside the struct to add
+//! subcommands. The type of the field is usually an enum that derived `Parser`. However, you can
+//! also implement the `Subcommand` trait manually on this enum (or any other type) and it can
+//! still be used inside the struct created with the derive API. The implementation of the
+//! `Subcommand` trait will use the builder API to add the subcommands to the `Command` instance
+//! created behind the scenes for you by the derive API.
+//!
+//! Notice how in the previous example we used
+//! [`augment_subcommands`][crate::Subcommand::augment_subcommands] on an enum that derived
+//! `Parser`, whereas now we implement
+//! [`augment_subcommands`][crate::Subcommand::augment_subcommands] ourselves, but the derive API
+//! calls it automatically since we used the `#[clap(subcommand)]` attribute.
+//!
+//! For example:
+//! ```rust
+#![doc = include_str!("../../examples/derive_ref/hand_subcommand.rs")]
+//! ```
+//!
+//! ### Flattening hand-implemented args into a derived application
+//!
+//! When using the derive API, you can use `#[clap(flatten)]` inside the struct to add arguments as
+//! if they were added directly to the containing struct. The type of the field is usually an
+//! struct that derived `Args`. However, you can also implement the `Args` trait manually on this
+//! struct (or any other type) and it can still be used inside the struct created with the derive
+//! API. The implementation of the `Args` trait will use the builder API to add the arguments to
+//! the `Command` instance created behind the scenes for you by the derive API.
+//!
+//! Notice how in the previous example we used [`augment_args`][crate::Args::augment_args] on the
+//! struct that derived `Parser`, whereas now we implement
+//! [`augment_args`][crate::Args::augment_args] ourselves, but the derive API calls it
+//! automatically since we used the `#[clap(flatten)]` attribute.
+//!
+//! For example:
+//! ```rust
+#![doc = include_str!("../../examples/derive_ref/flatten_hand_args.rs")]
+//! ```
+//!
+//! ## Tips
+//!
+//! - To get access to a [`Command`][crate::Command] call
+//! [`CommandFactory::command`][crate::CommandFactory::command] (implemented when deriving
+//! [`Parser`][crate::Parser])
+//! - Proactively check for bad [`Command`][crate::Command] configurations by calling
+//! [`Command::debug_assert`][crate::App::debug_assert] in a test
+//! ([example](../tutorial_derive/05_01_assert.rs))
+
+pub mod _tutorial;
+#[doc(inline)]
+pub use crate::_cookbook;
diff --git a/3.2.23/src/_faq.rs b/3.2.23/src/_faq.rs
new file mode 100644
index 0000000..661a7e7
--- /dev/null
+++ b/3.2.23/src/_faq.rs
@@ -0,0 +1,95 @@
+//! # Documentation: FAQ
+//!
+//! 1. [Comparisons](#comparisons)
+//! 1. [How does `clap` compare to structopt?](#how-does-clap-compare-to-structopt)
+//! 2. [What are some reasons to use `clap`? (The Pitch)](#what-are-some-reasons-to-use-clap-the-pitch)
+//! 3. [What are some reasons *not* to use `clap`? (The Anti Pitch)](#what-are-some-reasons-not-to-use-clap-the-anti-pitch)
+//! 4. [Reasons to use `clap`](#reasons-to-use-clap)
+//! 2. [How many approaches are there to create a parser?](#how-many-approaches-are-there-to-create-a-parser)
+//! 3. [When should I use the builder vs derive APIs?](#when-should-i-use-the-builder-vs-derive-apis)
+//! 4. [Why is there a default subcommand of help?](#why-is-there-a-default-subcommand-of-help)
+//!
+//! ### Comparisons
+//!
+//! First, let me say that these comparisons are highly subjective, and not meant
+//! in a critical or harsh manner. All the argument parsing libraries out there (to
+//! include `clap`) have their own strengths and weaknesses. Sometimes it just
+//! comes down to personal taste when all other factors are equal. When in doubt,
+//! try them all and pick one that you enjoy :) There's plenty of room in the Rust
+//! community for multiple implementations!
+//!
+//! For less detailed but more broad comparisons, see
+//! [argparse-benchmarks](https://github.com/rust-cli/argparse-benchmarks-rs).
+//!
+//! #### How does `clap` compare to [structopt](https://github.com/TeXitoi/structopt)?
+//!
+//! Simple! `clap` *is* `structopt`. `structopt` started as a derive API built on
+//! top of clap v2. With clap v3, we've forked structopt and integrated it
+//! directly into clap. structopt is in
+//! [maintenance mode](https://github.com/TeXitoi/structopt/issues/516#issuecomment-989566094)
+//! with the release of `clap_derive`.
+//!
+//! The benefits of integrating `structopt` and `clap` are:
+//! - Easier cross-linking in documentation
+//! - [Documentation parity](../examples)
+//! - Tighter design feedback loop, ensuring all new features are designed with
+//! derives in mind and easier to change `clap` in response to `structopt` bugs.
+//! - Clearer endorsement of `structopt`
+//!
+//! See also
+//! - [`clap` v3 CHANGELOG](../CHANGELOG.md#300---2021-12-31)
+//! - [`structopt` migration guide](../CHANGELOG.md#migrate-structopt)
+//!
+//! #### What are some reasons to use `clap`? (The Pitch)
+//!
+//! `clap` is as fast, and as lightweight as possible while still giving all the features you'd expect from a modern argument parser. In fact, for the amount and type of features `clap` offers it remains about as fast as `getopts`. If you use `clap` when just need some simple arguments parsed, you'll find it's a walk in the park. `clap` also makes it possible to represent extremely complex, and advanced requirements, without too much thought. `clap` aims to be intuitive, easy to use, and fully capable for wide variety use cases and needs.
+//!
+//! #### What are some reasons *not* to use `clap`? (The Anti Pitch)
+//!
+//! Depending on the style in which you choose to define the valid arguments, `clap` can be very verbose. `clap` also offers so many finetuning knobs and dials, that learning everything can seem overwhelming. I strive to keep the simple cases simple, but when turning all those custom dials it can get complex. `clap` is also opinionated about parsing. Even though so much can be tweaked and tuned with `clap` (and I'm adding more all the time), there are still certain features which `clap` implements in specific ways which may be contrary to some users use-cases.
+//!
+//! #### Reasons to use `clap`
+//!
+//! * You want all the nice CLI features your users may expect, yet you don't want to implement them all yourself. You'd like to focus your application, not argument parsing.
+//! * In addition to the point above; you don't want to sacrifice performance to get all those nice features
+//! * You have complex requirements/conflicts between your various valid args.
+//! * You want to use subcommands (although other libraries also support subcommands, they are not nearly as feature rich as those provided by `clap`)
+//! * You want some sort of custom validation built into the argument parsing process, instead of as part of your application (which allows for earlier failures, better error messages, more cohesive experience, etc.)
+//!
+//! ### How many approaches are there to create a parser?
+//!
+//! The following APIs are supported:
+//! - [Derive][crate::_derive::_tutorial]
+//! - [Builder][crate::_tutorial]
+//!
+//! Previously, we supported:
+//! - [YAML](https://github.com/clap-rs/clap/issues/3087)
+//! - [docopt](http://docopt.org/)-inspired [usage parser](https://github.com/clap-rs/clap/issues/3086)
+//! - [`clap_app!`](https://github.com/clap-rs/clap/issues/2835)
+//!
+//! There are also experiments with other APIs:
+//! - [fncmd](https://github.com/yuhr/fncmd): function attribute
+//! - [clap-serde](https://github.com/aobatact/clap-serde): create an `Command` from a deserializer
+//!
+//! ### When should I use the builder vs derive APIs?
+//!
+//! Our default answer is to use the [Derive API][crate::_derive::_tutorial]:
+//! - Easier to read, write, and modify
+//! - Easier to keep the argument declaration and reading of argument in sync
+//! - Easier to reuse, e.g. [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag)
+//!
+//! The [Builder API][crate::_tutorial] is a lower-level API that someone might want to use for
+//! - Faster compile times if you aren't already using other procedural macros
+//! - More flexibility, e.g. you can look up an [arguments values][crate::ArgMatches::get_many],
+//! their [ordering with other arguments][crate::ArgMatches::indices_of], and [what set
+//! them][crate::ArgMatches::value_source]. The Derive API can only report values and not
+//! indices of or other data.
+//!
+//! You can [interop between Derive and Builder APIs][crate::_derive#mixing-builder-and-derive-apis].
+//!
+//! ### Why is there a default subcommand of help?
+//!
+//! There is only a default subcommand of `help` when other subcommands have been defined manually. So it's opt-in(ish), being that you only get a `help` subcommand if you're actually using subcommands.
+//!
+//! Also, if the user defined a `help` subcommand themselves, the auto-generated one wouldn't be added (meaning it's only generated if the user hasn't defined one themselves).
+//!
diff --git a/3.2.23/src/_features.rs b/3.2.23/src/_features.rs
new file mode 100644
index 0000000..923134c
--- /dev/null
+++ b/3.2.23/src/_features.rs
@@ -0,0 +1,27 @@
+//! ## Documentation: Feature Flags
+//!
+//! Available [compile-time feature flags](https://doc.rust-lang.org/cargo/reference/features.html#dependency-features)
+//!
+//! #### Default Features
+//!
+//! * **std**: _Not Currently Used._ Placeholder for supporting `no_std` environments in a backwards compatible manner.
+//! * **color**: Turns on colored error messages.
+//! * **suggestions**: Turns on the `Did you mean '--myoption'?` feature for when users make typos.
+//!
+//! #### Optional features
+//!
+//! * **deprecated**: Guided experience to prepare for next breaking release (at different stages of development, this may become default)
+//! * **derive**: Enables the custom derive (i.e. `#[derive(Parser)]`). Without this you must use one of the other methods of creating a `clap` CLI listed above.
+//! * **cargo**: Turns on macros that read values from [`CARGO_*` environment variables](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates).
+//! * **env**: Turns on the usage of environment variables during parsing.
+//! * **regex**: Enables regex validators.
+//! * **unicode**: Turns on support for unicode characters (including emoji) in arguments and help messages.
+//! * **wrap_help**: Turns on the help text wrapping feature, based on the terminal size.
+//!
+//! #### Experimental features
+//!
+//! **Warning:** These may contain breaking changes between minor releases.
+//!
+//! * **unstable-replace**: Enable [`Command::replace`](https://github.com/clap-rs/clap/issues/2836)
+//! * **unstable-grouped**: Enable [`ArgMatches::grouped_values_of`](https://github.com/clap-rs/clap/issues/2924)
+//! * **unstable-v4**: Preview features which will be stable on the v4.0 release
diff --git a/3.2.23/src/_tutorial.rs b/3.2.23/src/_tutorial.rs
new file mode 100644
index 0000000..9dbfc68
--- /dev/null
+++ b/3.2.23/src/_tutorial.rs
@@ -0,0 +1,204 @@
+// Contributing
+//
+// New example code:
+// - Please update the corresponding section in the derive tutorial
+// - Building: They must be added to `Cargo.toml` with the appropriate `required-features`.
+// - Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax
+//
+// See also the general CONTRIBUTING
+
+//! # Documentation: Builder Tutorial
+//!
+//! 1. [Quick Start](#quick-start)
+//! 2. [Configuring the Parser](#configuring-the-parser)
+//! 3. [Adding Arguments](#adding-arguments)
+//! 1. [Positionals](#positionals)
+//! 2. [Options](#options)
+//! 3. [Flags](#flags)
+//! 4. [Subcommands](#subcommands)
+//! 5. [Defaults](#defaults)
+//! 4. Validation
+//! 1. [Enumerated values](#enumerated-values)
+//! 2. [Validated values](#validated-values)
+//! 3. [Argument Relations](#argument-relations)
+//! 4. [Custom Validation](#custom-validation)
+//! 5. [Testing](#testing)
+//!
+//! See also
+//! - [FAQ: When should I use the builder vs derive APIs?][crate::_faq#when-should-i-use-the-builder-vs-derive-apis]
+//! - The [cookbook][crate::_cookbook] for more application-focused examples
+//!
+//! ## Quick Start
+//!
+//! You can create an application with several arguments using usage strings.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/01_quick.rs")]
+//! ```
+//!
+#![doc = include_str!("../examples/tutorial_builder/01_quick.md")]
+//!
+//! ## Configuring the Parser
+//!
+//! You use [`Command`][crate::Command] to start building a parser.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/02_apps.rs")]
+//! ```
+//!
+#![doc = include_str!("../examples/tutorial_builder/02_apps.md")]
+//!
+//! You can use [`command!()`][crate::command!] to fill these fields in from your `Cargo.toml`
+//! file. **This requires the [`cargo` feature flag][crate::_features].**
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/02_crate.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/02_crate.md")]
+//!
+//! You can use [`Command`][crate::Command] methods to change the application level behavior of
+//! clap.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/02_app_settings.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/02_app_settings.md")]
+//!
+//! ## Adding Arguments
+//!
+//! ### Positionals
+//!
+//! You can have users specify values by their position on the command-line:
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_03_positional.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_03_positional.md")]
+//!
+//! ### Options
+//!
+//! You can name your arguments with a flag:
+//! - Order doesn't matter
+//! - They can be optional
+//! - Intent is clearer
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_02_option.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_02_option.md")]
+//!
+//! ### Flags
+//!
+//! Flags can also be switches that can be on/off:
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_01_flag_bool.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_01_flag_bool.md")]
+//!
+//! Or counted.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_01_flag_count.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_01_flag_count.md")]
+//!
+//! ### Subcommands
+//!
+//! Subcommands are defined as [`Command`][crate::Command]s that get added via
+//! [`Command::subcommand`][crate::Command::subcommand]. Each instance of a Subcommand can have its
+//! own version, author(s), Args, and even its own subcommands.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_04_subcommands.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_04_subcommands.md")]
+//!
+//! ### Defaults
+//!
+//! We've previously showed that arguments can be [`required`][crate::Arg::required] or optional.
+//! When optional, you work with a `Option` and can `unwrap_or`. Alternatively, you can set
+//! [`Arg::default_value`][crate::Arg::default_value].
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_05_default_values.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_05_default_values.md")]
+//!
+//! ## Validation
+//!
+//! ### Enumerated values
+//!
+//! If you have arguments of specific values you want to test for, you can use the
+//! [`PossibleValuesParser`][crate::builder::PossibleValuesParser] or [`Arg::value_parser(["val1",
+//! ...])`][crate::Arg::value_parser] for short.
+//!
+//! This allows you specify the valid values for that argument. If the user does not use one of
+//! those specific values, they will receive a graceful exit with error message informing them
+//! of the mistake, and what the possible valid values are
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/04_01_possible.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/04_01_possible.md")]
+//!
+//! When enabling the [`derive` feature][crate::_features], you can use
+//! [`ValueEnum`][crate::ValueEnum] to take care of the boiler plate for you, giving the same
+//! results.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/04_01_enum.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/04_01_enum.md")]
+//!
+//! ### Validated values
+//!
+//! More generally, you can validate and parse into any data type.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/04_02_parse.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/04_02_parse.md")]
+//!
+//! A custom parser can be used to improve the error messages or provide additional validation:
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/04_02_validate.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/04_02_validate.md")]
+//!
+//! ### Argument Relations
+//!
+//! You can declare dependencies or conflicts between [`Arg`][crate::Arg]s or even
+//! [`ArgGroup`][crate::ArgGroup]s.
+//!
+//! [`ArgGroup`][crate::ArgGroup]s make it easier to declare relations instead of having to list
+//! each individually, or when you want a rule to apply "any but not all" arguments.
+//!
+//! Perhaps the most common use of [`ArgGroup`][crate::ArgGroup]s is to require one and *only* one
+//! argument to be present out of a given set. Imagine that you had multiple arguments, and you
+//! want one of them to be required, but making all of them required isn't feasible because perhaps
+//! they conflict with each other.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/04_03_relations.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/04_03_relations.md")]
+//!
+//! ### Custom Validation
+//!
+//! As a last resort, you can create custom errors with the basics of clap's formatting.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/04_04_custom.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/04_04_custom.md")]
+//!
+//! ## Testing
+//!
+//! clap reports most development errors as `debug_assert!`s. Rather than checking every
+//! subcommand, you should have a test that calls
+//! [`Command::debug_assert`][crate::App::debug_assert]:
+//! ```rust,no_run
+#![doc = include_str!("../examples/tutorial_builder/05_01_assert.rs")]
+//! ```
diff --git a/3.2.23/src/bin/stdio-fixture.rs b/3.2.23/src/bin/stdio-fixture.rs
new file mode 100644
index 0000000..e3f34b4
--- /dev/null
+++ b/3.2.23/src/bin/stdio-fixture.rs
@@ -0,0 +1,14 @@
+fn main() {
+ let cmd = clap::Command::new("stdio-fixture")
+ .version("1.0")
+ .long_version("1.0 - a2132c")
+ .arg_required_else_help(true)
+ .subcommand(clap::Command::new("more"))
+ .arg(
+ clap::Arg::new("verbose")
+ .long("verbose")
+ .help("log")
+ .long_help("more log"),
+ );
+ cmd.get_matches();
+}
diff --git a/3.2.23/src/builder/action.rs b/3.2.23/src/builder/action.rs
new file mode 100644
index 0000000..acbfc5c
--- /dev/null
+++ b/3.2.23/src/builder/action.rs
@@ -0,0 +1,345 @@
+/// Behavior of arguments when they are encountered while parsing
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::Command;
+/// # use clap::Arg;
+/// let cmd = Command::new("mycmd")
+/// .arg(
+/// Arg::new("special-help")
+/// .short('?')
+/// .action(clap::ArgAction::Help)
+/// );
+///
+/// // Existing help still exists
+/// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err();
+/// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
+///
+/// // New help available
+/// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err();
+/// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
+/// ```
+#[derive(Clone, Debug)]
+#[non_exhaustive]
+#[allow(missing_copy_implementations)] // In the future, we may accept `Box<dyn ...>`
+pub enum ArgAction {
+ /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("flag")
+ /// .long("flag")
+ /// .action(clap::ArgAction::Set)
+ /// );
+ ///
+ /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(matches.occurrences_of("flag"), 0);
+ /// assert_eq!(
+ /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(),
+ /// vec!["value"]
+ /// );
+ /// ```
+ Set,
+ /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("flag")
+ /// .long("flag")
+ /// .action(clap::ArgAction::Append)
+ /// );
+ ///
+ /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value1", "--flag", "value2"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(matches.occurrences_of("flag"), 0);
+ /// assert_eq!(
+ /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(),
+ /// vec!["value1", "value2"]
+ /// );
+ /// ```
+ Append,
+ /// Deprecated, replaced with [`ArgAction::Set`] or [`ArgAction::Append`]
+ ///
+ /// Builder: Instead of `arg.action(ArgAction::StoreValue)`,
+ /// - Use `arg.action(ArgAction::Set)` for single-occurrence arguments
+ /// - Use `arg.action(ArgAction::Append)` for multiple-occurrence arguments
+ ///
+ /// Derive: opt-in to the new behavior with `#[clap(action)]`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `ArgAction::Set` or `ArgAction::Append`
+
+Derive: opt-in to the new behavior with `#[clap(action)]`
+
+Builder: Instead of `arg.action(ArgAction::StoreValue)`,
+- Use `arg.action(ArgAction::Set)` for single-occurrence arguments
+- Use `arg.action(ArgAction::Append)` for multiple-occurrence arguments
+"
+ )
+ )]
+ StoreValue,
+ /// Deprecated, replaced with [`ArgAction::SetTrue`] or [`ArgAction::Count`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `ArgAction::SetTrue` or `ArgAction::Count`
+
+Derive: opt-in to the new behavior with `#[clap(action)]`
+
+Builder: Instead of `arg.action(ArgAction::IncOccurrence)`,
+- Use `arg.action(ArgAction::SetTrue)` if you just care if its set, then switch `matches.is_present` to `matches.get_flag`
+- Use `arg.action(ArgAction::Count)` if you care how many times its set, then switch `matches.occurrences_of` to `matches.get_count`
+"
+ )
+ )]
+ IncOccurrence,
+ /// When encountered, act as if `"true"` was encountered on the command-line
+ ///
+ /// If no [`default_value`][super::Arg::default_value] is set, it will be `false`.
+ ///
+ /// No value is allowed. To optionally accept a value, see
+ /// [`Arg::default_missing_value`][super::Arg::default_missing_value]
+ ///
+ /// # 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.occurrences_of("flag"), 0);
+ /// assert_eq!(
+ /// matches.get_one::<bool>("flag").copied(),
+ /// Some(true)
+ /// );
+ ///
+ /// 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::<bool>("flag").copied(),
+ /// Some(false)
+ /// );
+ /// ```
+ SetTrue,
+ /// When encountered, act as if `"false"` was encountered on the command-line
+ ///
+ /// If no [`default_value`][super::Arg::default_value] is set, it will be `true`.
+ ///
+ /// No value is allowed. To optionally accept a value, see
+ /// [`Arg::default_missing_value`][super::Arg::default_missing_value]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("flag")
+ /// .long("flag")
+ /// .action(clap::ArgAction::SetFalse)
+ /// );
+ ///
+ /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(matches.occurrences_of("flag"), 0);
+ /// assert_eq!(
+ /// matches.get_one::<bool>("flag").copied(),
+ /// Some(false)
+ /// );
+ ///
+ /// 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::<bool>("flag").copied(),
+ /// Some(true)
+ /// );
+ /// ```
+ SetFalse,
+ /// When encountered, increment a `u8` counter
+ ///
+ /// If no [`default_value`][super::Arg::default_value] is set, it will be `0`.
+ ///
+ /// No value is allowed. To optionally accept a value, see
+ /// [`Arg::default_missing_value`][super::Arg::default_missing_value]
+ ///
+ /// # 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!(matches.contains_id("flag"));
+ /// assert_eq!(matches.occurrences_of("flag"), 0);
+ /// assert_eq!(
+ /// 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_count("flag"),
+ /// 0
+ /// );
+ /// ```
+ Count,
+ /// When encountered, display [`Command::print_help`][super::App::print_help]
+ ///
+ /// Depending on the flag, [`Command::print_long_help`][super::App::print_long_help] may be shown
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("special-help")
+ /// .short('?')
+ /// .action(clap::ArgAction::Help)
+ /// );
+ ///
+ /// // Existing help still exists
+ /// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err();
+ /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
+ ///
+ /// // New help available
+ /// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err();
+ /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
+ /// ```
+ Help,
+ /// When encountered, display [`Command::version`][super::App::version]
+ ///
+ /// Depending on the flag, [`Command::long_version`][super::App::long_version] may be shown
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// let cmd = Command::new("mycmd")
+ /// .version("1.0.0")
+ /// .arg(
+ /// Arg::new("special-version")
+ /// .long("special-version")
+ /// .action(clap::ArgAction::Version)
+ /// );
+ ///
+ /// // Existing help still exists
+ /// let err = cmd.clone().try_get_matches_from(["mycmd", "--version"]).unwrap_err();
+ /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion);
+ ///
+ /// // New help available
+ /// let err = cmd.try_get_matches_from(["mycmd", "--special-version"]).unwrap_err();
+ /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion);
+ /// ```
+ Version,
+}
+
+impl ArgAction {
+ /// Returns whether this action accepts values on the command-line
+ ///
+ /// [`default_values`][super::Arg::default_values] and [`env`][super::Arg::env] may still be
+ /// processed.
+ pub fn takes_values(&self) -> bool {
+ match self {
+ Self::Set => true,
+ Self::Append => true,
+ #[allow(deprecated)]
+ Self::StoreValue => true,
+ #[allow(deprecated)]
+ Self::IncOccurrence => false,
+ Self::SetTrue => false,
+ Self::SetFalse => false,
+ Self::Count => false,
+ Self::Help => false,
+ Self::Version => false,
+ }
+ }
+
+ pub(crate) fn default_value(&self) -> Option<&'static std::ffi::OsStr> {
+ match self {
+ Self::Set => None,
+ Self::Append => None,
+ #[allow(deprecated)]
+ Self::StoreValue => None,
+ #[allow(deprecated)]
+ Self::IncOccurrence => None,
+ 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::Version => None,
+ }
+ }
+
+ pub(crate) fn default_value_parser(&self) -> Option<super::ValueParser> {
+ match self {
+ Self::Set => None,
+ Self::Append => None,
+ #[allow(deprecated)]
+ Self::StoreValue => None,
+ #[allow(deprecated)]
+ Self::IncOccurrence => None,
+ Self::SetTrue => Some(super::ValueParser::bool()),
+ Self::SetFalse => Some(super::ValueParser::bool()),
+ Self::Count => Some(crate::value_parser!(u8).into()),
+ Self::Help => None,
+ Self::Version => None,
+ }
+ }
+
+ #[cfg(debug_assertions)]
+ pub(crate) fn value_type_id(&self) -> Option<crate::parser::AnyValueId> {
+ use crate::parser::AnyValueId;
+
+ match self {
+ Self::Set => None,
+ Self::Append => None,
+ #[allow(deprecated)]
+ Self::StoreValue => None,
+ #[allow(deprecated)]
+ Self::IncOccurrence => None,
+ Self::SetTrue => Some(AnyValueId::of::<bool>()),
+ Self::SetFalse => Some(AnyValueId::of::<bool>()),
+ Self::Count => Some(AnyValueId::of::<CountType>()),
+ Self::Help => None,
+ Self::Version => None,
+ }
+ }
+}
+
+pub(crate) type CountType = u8;
diff --git a/3.2.23/src/builder/app_settings.rs b/3.2.23/src/builder/app_settings.rs
new file mode 100644
index 0000000..570d23d
--- /dev/null
+++ b/3.2.23/src/builder/app_settings.rs
@@ -0,0 +1,1308 @@
+#![allow(deprecated)]
+
+// Std
+use std::ops::BitOr;
+#[cfg(feature = "yaml")]
+use std::str::FromStr;
+
+#[allow(unused)]
+use crate::Arg;
+#[allow(unused)]
+use crate::Command;
+
+// Third party
+use bitflags::bitflags;
+
+#[doc(hidden)]
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+pub struct AppFlags(Flags);
+
+impl Default for AppFlags {
+ fn default() -> Self {
+ AppFlags(Flags::COLOR_AUTO)
+ }
+}
+
+/// Application level settings, which affect how [`Command`] operates
+///
+/// **NOTE:** When these settings are used, they apply only to current command, and are *not*
+/// propagated down or up through child or parent subcommands
+///
+/// [`Command`]: crate::Command
+#[derive(Debug, PartialEq, Copy, Clone)]
+#[non_exhaustive]
+pub enum AppSettings {
+ /// Deprecated, replaced with [`Command::ignore_errors`]
+ ///
+ /// Derive: replace `#[clap(setting = IgnoreErrors)]` with `#[clap(ignore_errors = true)]`
+ ///
+ /// Builder: replace `cmd.setting(IgnoreErrors)` with `cmd.ignore_errors = true`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::ignore_errors`
+
+Derive: replace `#[clap(setting = IgnoreErrors)]` with `#[clap(ignore_errors = true)]`
+
+Builder: replace `cmd.setting(IgnoreErrors)` with `cmd.ignore_errors(true)`
+"
+ )
+ )]
+ IgnoreErrors,
+
+ /// Deprecated, replace
+ /// ```rust,no_run
+ /// let cmd = clap::Command::new("cmd")
+ /// .global_setting(clap::AppSettings::WaitOnError)
+ /// .arg(clap::arg!(--flag));
+ /// let m = cmd.get_matches();
+ /// ```
+ /// with
+ /// ```rust
+ /// let cmd = clap::Command::new("cmd")
+ /// .arg(clap::arg!(--flag));
+ /// let m = match cmd.try_get_matches() {
+ /// Ok(m) => m,
+ /// Err(err) => {
+ /// if err.use_stderr() {
+ /// let _ = err.print();
+ ///
+ /// eprintln!("\nPress [ENTER] / [RETURN] to continue...");
+ /// use std::io::BufRead;
+ /// let mut s = String::new();
+ /// let i = std::io::stdin();
+ /// i.lock().read_line(&mut s).unwrap();
+ ///
+ /// std::process::exit(2);
+ /// } else {
+ /// let _ = err.print();
+ /// std::process::exit(0);
+ /// }
+ /// }
+ /// };
+ /// ```
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "See documentation for how to hand-implement this"
+ )
+ )]
+ WaitOnError,
+
+ /// Deprecated, replaced with [`Command::allow_hyphen_values`] and
+ /// [`Arg::is_allow_hyphen_values_set`]
+ ///
+ /// Derive: replace `#[clap(setting = AllowHyphenValues)]` with `#[clap(allow_hyphen_values = true)]`
+ ///
+ /// Builder: replace `cmd.setting(AllowHyphenValues)` with `cmd.allow_hyphen_values(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::allow_hyphen_values` and `Arg::is_allow_hyphen_values_set`
+
+Derive: replace `#[clap(setting = AllowHyphenValues)]` with `#[clap(allow_hyphen_values = true)]`
+
+Builder: replace `cmd.setting(AllowHyphenValues)` with `cmd.allow_hyphen_values(true)`
+"
+ )
+ )]
+ AllowHyphenValues,
+
+ /// Deprecated, replaced with [`Command::allow_negative_numbers`] and
+ /// [`Command::is_allow_negative_numbers_set`]
+ ///
+ /// Derive: replace `#[clap(setting = AllowNegativeNumbers)]` with `#[clap(allow_negative_numbers = true)]`
+ ///
+ /// Builder: replace `cmd.setting(AllowNegativeNumbers)` with `cmd.allow_negative_numbers(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::allow_negative_numbers` and `Command::is_allow_negative_numbers_set`
+
+Derive: replace `#[clap(setting = AllowNegativeNumbers)]` with `#[clap(allow_negative_numbers = true)]`
+
+Builder: replace `cmd.setting(AllowNegativeNumbers)` with `cmd.allow_negative_numbers(true)`
+"
+ )
+ )]
+ AllowNegativeNumbers,
+
+ /// Deprecated, replaced with [`ArgAction::Set`][super::ArgAction::Set]
+ ///
+ /// The new actions (`ArgAction::Set`, `ArgAction::SetTrue`) do this by default.
+ ///
+ /// See `ArgAction::StoreValue` and `ArgAction::IncOccurrence` for how to migrate
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `Arg::action(ArgAction::...)`
+
+The new actions (`ArgAction::Set`, `ArgAction::SetTrue`) do this by default.
+
+See `ArgAction::StoreValue` and `ArgAction::IncOccurrence` for how to migrate
+"
+ )
+ )]
+ AllArgsOverrideSelf,
+
+ /// Deprecated, replaced with [`Command::allow_missing_positional`] and
+ /// [`Command::is_allow_missing_positional_set`]
+ ///
+ /// Derive: replace `#[clap(setting = AllowMissingPositional)]` with `#[clap(allow_missing_positional = true)]`
+ ///
+ /// Builder: replace `cmd.setting(AllowMissingPositional)` with `cmd.allow_missing_positional(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::allow_missing_positional` and `Command::is_allow_missing_positional_set`
+
+Derive: replace `#[clap(setting = AllowMissingPositional)]` with `#[clap(allow_missing_positional = true)]`
+
+Builder: replace `cmd.setting(AllowMissingPositional)` with `cmd.allow_missing_positional(true)`
+"
+ )
+ )]
+ AllowMissingPositional,
+
+ /// Deprecated, replaced with [`Command::trailing_var_arg`] and [`Command::is_trailing_var_arg_set`]
+ ///
+ /// Derive: replace `#[clap(setting = TrailingVarArg)]` with `#[clap(trailing_var_arg = true)]`
+ ///
+ /// Builder: replace `cmd.setting(TrailingVarArg)` with `cmd.trailing_var_arg(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::trailing_var_arg` and `Command::is_trailing_var_arg_set`
+
+Derive: replace `#[clap(setting = TrailingVarArg)]` with `#[clap(trailing_var_arg = true)]`
+
+Builder: replace `cmd.setting(TrailingVarArg)` with `cmd.trailing_var_arg(true)`
+"
+ )
+ )]
+ TrailingVarArg,
+
+ /// Deprecated, replaced with [`Command::dont_delimit_trailing_values`] and
+ /// [`Command::is_dont_delimit_trailing_values_set`]
+ ///
+ /// Derive: replace `#[clap(setting = DontDelimitTrailingValues)]` with `#[clap(dont_delimit_trailing_values = true)]`
+ ///
+ /// Builder: replace `cmd.setting(DontDelimitTrailingValues)` with `cmd.dont_delimit_trailing_values(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::dont_delimit_trailing_values` and `Command::is_dont_delimit_trailing_values_set`
+
+Derive: replace `#[clap(setting = DontDelimitTrailingValues)]` with `#[clap(dont_delimit_trailing_values = true)]`
+
+Builder: replace `cmd.setting(DontDelimitTrailingValues)` with `cmd.dont_delimit_trailing_values(true)`
+"
+ )
+ )]
+ DontDelimitTrailingValues,
+
+ /// Deprecated, replaced with [`Command::infer_long_args`]
+ ///
+ /// Derive: replace `#[clap(setting = InferLongArgs)]` with `#[clap(infer_long_args = true)]`
+ ///
+ /// Builder: replace `cmd.setting(InferLongArgs)` with `cmd.infer_long_args(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::infer_long_args`
+
+Derive: replace `#[clap(setting = InferLongArgs)]` with `#[clap(infer_long_args = true)]`
+
+Builder: replace `cmd.setting(InferLongArgs)` with `cmd.infer_long_args(true)`
+"
+ )
+ )]
+ InferLongArgs,
+
+ /// Deprecated, replaced with [`Command::infer_subcommands`]
+ ///
+ /// Derive: replace `#[clap(setting = InferSubcommands)]` with `#[clap(infer_subcommands = true)]`
+ ///
+ /// Builder: replace `cmd.setting(InferSubcommands)` with `cmd.infer_subcommands(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::infer_subcommands`
+
+Derive: replace `#[clap(setting = InferSubcommands)]` with `#[clap(infer_subcommands = true)]`
+
+Builder: replace `cmd.setting(InferSubcommands)` with `cmd.infer_subcommands(true)`
+"
+ )
+ )]
+ InferSubcommands,
+
+ /// Deprecated, replaced with [`Command::subcommand_required`] and
+ /// [`Command::is_subcommand_required_set`]
+ ///
+ /// Derive: replace `#[clap(setting = SubcommandRequired)]` with `#[clap(subcommand_required = true)]`
+ ///
+ /// Builder: replace `cmd.setting(SubcommandRequired)` with `cmd.subcommand_required(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::subcommand_required` and `Command::is_subcommand_required_set`
+
+Derive: replace `#[clap(setting = SubcommandRequired)]` with `#[clap(subcommand_required = true)]`
+
+Builder: replace `cmd.setting(SubcommandRequired)` with `cmd.subcommand_required(true)`
+"
+ )
+ )]
+ SubcommandRequired,
+
+ /// Deprecated, replaced with [`Command::subcommand_required`] combined with
+ /// [`Command::arg_required_else_help`].
+ ///
+ /// Derive: replace `#[clap(setting = SubcommandRequiredElseHelp)]` with `#[clap(subcommand_required = true, arg_required_else_help = true)]`
+ ///
+ /// Builder: replace `cmd.setting(SubcommandRequiredElseHelp)` with `cmd.subcommand_required(true).arg_required_else_help(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::subcommand_required` combined with `Command::arg_required_else_help`
+
+Derive: replace `#[clap(setting = SubcommandRequiredElseHelp)]` with `#[clap(subcommand_required = true, arg_required_else_help = true)]`
+
+Builder: replace `cmd.setting(SubcommandRequiredElseHelp)` with `cmd.subcommand_required(true).arg_required_else_help(true)`
+"
+ )
+ )]
+ SubcommandRequiredElseHelp,
+
+ /// Deprecated, replaced with [`Command::allow_external_subcommands`] and
+ /// [`Command::is_allow_external_subcommands_set`]
+ ///
+ /// Derive: replace `#[clap(setting = AllowExternalSubcommands)]` with `#[clap(allow_external_subcommands = true)]`
+ ///
+ /// Builder: replace `cmd.setting(AllowExternalSubcommands)` with `cmd.allow_external_subcommands(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::allow_external_subcommands` and `Command::is_allow_external_subcommands_set`
+
+Derive: replace `#[clap(setting = AllowExternalSubcommands)]` with `#[clap(allow_external_subcommands = true)]`
+
+Builder: replace `cmd.setting(AllowExternalSubcommands)` with `cmd.allow_external_subcommands(true)`
+"
+ )
+ )]
+ AllowExternalSubcommands,
+
+ /// Deprecated, replaced with [`Command::multicall`] and [`Command::is_multicall_set`]
+ ///
+ /// Derive: replace `#[clap(setting = Multicall)]` with `#[clap(multicall = true)]`
+ ///
+ /// Builder: replace `cmd.setting(Multicall)` with `cmd.multicall(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::multicall` and `Command::is_multicall_set`
+
+Derive: replace `#[clap(setting = Multicall)]` with `#[clap(multicall = true)]`
+
+Builder: replace `cmd.setting(Multicall)` with `cmd.multicall(true)`
+"
+ )
+ )]
+ Multicall,
+
+ /// Deprecated, replaced with [`Command::allow_invalid_utf8_for_external_subcommands`] and [`Command::is_allow_invalid_utf8_for_external_subcommands_set`]
+ ///
+ /// Derive: replace `#[clap(setting = AllowInvalidUtf8ForExternalSubcommands)]` with `#[clap(allow_invalid_utf8_for_external_subcommands = true)]`
+ ///
+ /// Builder: replace `cmd.setting(AllowInvalidUtf8ForExternalSubcommands)` with `cmd.allow_invalid_utf8_for_external_subcommands(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::allow_invalid_utf8_for_external_subcommands` and `Command::is_allow_invalid_utf8_for_external_subcommands_set`
+
+Derive: replace `#[clap(setting = AllowInvalidUtf8ForExternalSubcommands)]` with `#[clap(allow_invalid_utf8_for_external_subcommands = true)]`
+
+Builder: replace `cmd.setting(AllowInvalidUtf8ForExternalSubcommands)` with `cmd.allow_invalid_utf8_for_external_subcommands(true)`
+"
+ )
+ )]
+ AllowInvalidUtf8ForExternalSubcommands,
+
+ /// Deprecated, this is now the default
+ ///
+ /// Derive: remove `#[clap(setting = UseLongFormatForHelpSubcommand)]`
+ ///
+ /// Builder: remove `cmd.setting(UseLongFormatForHelpSubcommand)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "This is now the default
+
+Derive: remove `#[clap(setting = UseLongFormatForHelpSubcommand)]`
+
+Builder: remove `cmd.setting(UseLongFormatForHelpSubcommand)`
+"
+ )
+ )]
+ UseLongFormatForHelpSubcommand,
+
+ /// Deprecated, replaced with [`Command::subcommand_negates_reqs`] and
+ /// [`Command::is_subcommand_negates_reqs_set`]
+ ///
+ /// Derive: replace `#[clap(setting = SubcommandsNegateReqs)]` with `#[clap(subcommand_negates_reqs = true)]`
+ ///
+ /// Builder: replace `cmd.setting(SubcommandsNegateReqs)` with `cmd.subcommand_negates_reqs(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::subcommand_negates_reqs` and `Command::is_subcommand_negates_reqs_set`
+
+Derive: replace `#[clap(setting = SubcommandsNegateReqs)]` with `#[clap(subcommand_negates_reqs = true)]`
+
+Builder: replace `cmd.setting(SubcommandsNegateReqs)` with `cmd.subcommand_negates_reqs(true)`
+"
+ )
+ )]
+ SubcommandsNegateReqs,
+
+ /// Deprecated, replaced with [`Command::args_conflicts_with_subcommands`] and
+ /// [`Command::is_args_conflicts_with_subcommands_set`]
+ ///
+ /// Derive: replace `#[clap(setting = ArgsNegateSubcommands)]` with `#[clap(args_conflicts_with_subcommands = true)]`
+ ///
+ /// Builder: replace `cmd.setting(ArgsNegateSubcommands)` with `cmd.args_conflicts_with_subcommands(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::args_conflicts_with_subcommands` and `Command::is_args_conflicts_with_subcommands_set`
+
+Derive: replace `#[clap(setting = ArgsNegateSubcommands)]` with `#[clap(args_conflicts_with_subcommands = true)]`
+
+Builder: replace `cmd.setting(ArgsNegateSubcommands)` with `cmd.args_conflicts_with_subcommands(true)`
+"
+ )
+ )]
+ ArgsNegateSubcommands,
+
+ /// Deprecated, replaced with [`Command::subcommand_precedence_over_arg`] and
+ /// [`Command::is_subcommand_precedence_over_arg_set`]
+ ///
+ /// Derive: replace `#[clap(setting = SubcommandPrecedenceOverArg)]` with `#[clap(subcommand_precedence_over_arg = true)]`
+ ///
+ /// Builder: replace `cmd.setting(SubcommandPrecedenceOverArg)` with `cmd.subcommand_precedence_over_arg(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::subcommand_precedence_over_arg` and `Command::is_subcommand_precedence_over_arg_set`
+
+Derive: replace `#[clap(setting = SubcommandPrecedenceOverArg)]` with `#[clap(subcommand_precedence_over_arg = true)]`
+
+Builder: replace `cmd.setting(SubcommandPrecedenceOverArg)` with `cmd.subcommand_precedence_over_arg(true)`
+"
+ )
+ )]
+ SubcommandPrecedenceOverArg,
+
+ /// Deprecated, replaced with [`Command::arg_required_else_help`] and
+ /// [`Command::is_arg_required_else_help_set`]
+ ///
+ /// Derive: replace `#[clap(setting = ArgRequiredElseHelp)]` with `#[clap(arg_required_else_help = true)]`
+ ///
+ /// Builder: replace `cmd.setting(ArgRequiredElseHelp)` with `cmd.arg_required_else_help(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::arg_required_else_help` and `Command::is_arg_required_else_help_set`
+
+Derive: replace `#[clap(setting = ArgRequiredElseHelp)]` with `#[clap(arg_required_else_help = true)]`
+
+Builder: replace `cmd.setting(ArgRequiredElseHelp)` with `cmd.arg_required_else_help(true)`
+"
+ )
+ )]
+ ArgRequiredElseHelp,
+
+ /// Displays the arguments and [`subcommands`] in the help message in the order that they were
+ /// declared in, and not alphabetically which is the default.
+ ///
+ /// To override the declaration order, see [`Arg::display_order`] and [`Command::display_order`].
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, AppSettings};
+ /// Command::new("myprog")
+ /// .global_setting(AppSettings::DeriveDisplayOrder)
+ /// .get_matches();
+ /// ```
+ ///
+ /// [`subcommands`]: crate::Command::subcommand()
+ /// [`Arg::display_order`]: crate::Arg::display_order
+ /// [`Command::display_order`]: crate::Command::display_order
+ DeriveDisplayOrder,
+
+ /// Deprecated, replaced with [`Command::dont_collapse_args_in_usage`] and
+ /// [`Command::is_dont_collapse_args_in_usage_set`]
+ ///
+ /// Derive: replace `#[clap(setting = DontCollapseArgsInUsage)]` with `#[clap(dont_collapse_args_in_usage = true)]`
+ ///
+ /// Builder: replace `cmd.setting(DontCollapseArgsInUsage)` with `cmd.dont_collapse_args_in_usage(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::dont_collapse_args_in_usage` and `Command::is_dont_collapse_args_in_usage_set`
+
+Derive: replace `#[clap(setting = DontCollapseArgsInUsage)]` with `#[clap(dont_collapse_args_in_usage = true)]`
+
+Builder: replace `cmd.setting(DontCollapseArgsInUsage)` with `cmd.dont_collapse_args_in_usage(true)`
+"
+ )
+ )]
+ DontCollapseArgsInUsage,
+
+ /// Deprecated, replaced with [`Command::next_line_help`] and [`Command::is_next_line_help_set`]
+ ///
+ /// Derive: replace `#[clap(setting = NextLineHelp)]` with `#[clap(next_line_help = true)]`
+ ///
+ /// Builder: replace `cmd.setting(NextLineHelp)` with `cmd.next_line_help(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::next_line_help` and `Command::is_next_line_help_set`
+
+Derive: replace `#[clap(setting = NextLineHelp)]` with `#[clap(next_line_help = true)]`
+
+Builder: replace `cmd.setting(NextLineHelp)` with `cmd.next_line_help(true)`
+"
+ )
+ )]
+ NextLineHelp,
+
+ /// Deprecated, replaced with [`Command::disable_colored_help`] and
+ /// [`Command::is_disable_colored_help_set`]
+ ///
+ /// Derive: replace `#[clap(setting = DisableColoredHelp)]` with `#[clap(disable_colored_help = true)]`
+ ///
+ /// Builder: replace `cmd.setting(DisableColoredHelp)` with `cmd.disable_colored_help(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::disable_colored_help` and `Command::is_disable_colored_help_set`
+
+Derive: replace `#[clap(setting = DisableColoredHelp)]` with `#[clap(disable_colored_help = true)]`
+
+Builder: replace `cmd.setting(DisableColoredHelp)` with `cmd.disable_colored_help(true)`
+"
+ )
+ )]
+ DisableColoredHelp,
+
+ /// Deprecated, replaced with [`Command::disable_help_flag`] and [`Command::is_disable_help_flag_set`]
+ ///
+ /// Derive: replace `#[clap(setting = DisableHelpFlag)]` with `#[clap(disable_help_flag = true)]`
+ ///
+ /// Builder: replace `cmd.setting(DisableHelpFlag)` with `cmd.disable_help_flag(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::disable_help_flag` and `Command::is_disable_help_flag_set`
+
+Derive: replace `#[clap(setting = DisableHelpFlag)]` with `#[clap(disable_help_flag = true)]`
+
+Builder: replace `cmd.setting(DisableHelpFlag)` with `cmd.disable_help_flag(true)`
+"
+ )
+ )]
+ DisableHelpFlag,
+
+ /// Deprecated, replaced with [`Command::disable_help_subcommand`] and
+ /// [`Command::is_disable_help_subcommand_set`]
+ ///
+ /// Derive: replace `#[clap(setting = DisableHelpSubcommand)]` with `#[clap(disable_help_subcommand = true)]`
+ ///
+ /// Builder: replace `cmd.setting(DisableHelpSubcommand)` with `cmd.disable_help_subcommand(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::disable_help_subcommand` and `Command::is_disable_help_subcommand_set`
+
+Derive: replace `#[clap(setting = DisableHelpSubcommand)]` with `#[clap(disable_help_subcommand = true)]`
+
+Builder: replace `cmd.setting(DisableHelpSubcommand)` with `cmd.disable_help_subcommand(true)`
+"
+ )
+ )]
+ DisableHelpSubcommand,
+
+ /// Deprecated, replaced with [`Command::disable_version_flag`] and
+ /// [`Command::is_disable_version_flag_set`]
+ ///
+ /// Derive: replace `#[clap(setting = DisableVersionFlag)]` with `#[clap(disable_version_flag = true)]`
+ ///
+ /// Builder: replace `cmd.setting(DisableVersionFlag)` with `cmd.disable_version_flag(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::disable_version_flag` and `Command::is_disable_version_flag_set`
+
+Derive: replace `#[clap(setting = DisableVersionFlag)]` with `#[clap(disable_version_flag = true)]`
+
+Builder: replace `cmd.setting(DisableVersionFlag)` with `cmd.disable_version_flag(true)`
+"
+ )
+ )]
+ DisableVersionFlag,
+
+ /// Deprecated, replaced with [`Command::propagate_version`] and [`Command::is_propagate_version_set`]
+ ///
+ /// Derive: replace `#[clap(setting = PropagateVersion)]` with `#[clap(propagate_version = true)]`
+ ///
+ /// Builder: replace `cmd.setting(PropagateVersion)` with `cmd.propagate_version(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::propagate_version` and `Command::is_propagate_version_set`
+
+Derive: replace `#[clap(setting = PropagateVersion)]` with `#[clap(propagate_version = true)]`
+
+Builder: replace `cmd.setting(PropagateVersion)` with `cmd.propagate_version(true)`
+"
+ )
+ )]
+ PropagateVersion,
+
+ /// Deprecated, replaced with [`Command::hide`] and [`Command::is_hide_set`]
+ ///
+ /// Derive: replace `#[clap(setting = Hidden)]` with `#[clap(hide = true)]`
+ ///
+ /// Builder: replace `cmd.setting(Hidden)` with `cmd.hide(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::hide` and `Command::is_hide_set`
+
+Derive: replace `#[clap(setting = Hidden)]` with `#[clap(hide = true)]`
+
+Builder: replace `cmd.setting(Hidden)` with `cmd.hide(true)`
+"
+ )
+ )]
+ Hidden,
+
+ /// Deprecated, replaced with [`Command::hide_possible_values`] and
+ /// [`Arg::is_hide_possible_values_set`]
+ ///
+ /// Derive: replace `#[clap(setting = HidePossibleValues)]` with `#[clap(hide_possible_values = true)]`
+ ///
+ /// Builder: replace `cmd.setting(HidePossibleValues)` with `cmd.hide_possible_values(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::hide_possible_values` and `Arg::is_hide_possible_values_set`
+
+Derive: replace `#[clap(setting = HidePossibleValues)]` with `#[clap(hide_possible_values = true)]`
+
+Builder: replace `cmd.setting(HidePossibleValues)` with `cmd.hide_possible_values(true)`
+"
+ )
+ )]
+ HidePossibleValues,
+
+ /// Deprecated, replaced with [`Command::help_expected`]
+ ///
+ /// Derive: replace `#[clap(setting = HelpExpected)]` with `#[clap(help_expected = true)]`
+ ///
+ /// Builder: replace `cmd.setting(HelpExpected)` with `cmd.help_expected(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::help_expected`
+
+Derive: replace `#[clap(setting = HelpExpected)]` with `#[clap(help_expected = true)]`
+
+Builder: replace `cmd.setting(HelpExpected)` with `cmd.help_expected(true)`
+"
+ )
+ )]
+ HelpExpected,
+
+ /// Deprecated, replaced with [`Command::no_binary_name`]
+ ///
+ /// Derive: replace `#[clap(setting = NoBinaryName)]` with `#[clap(no_binary_name = true)]`
+ ///
+ /// Builder: replace `cmd.setting(NoBinaryName)` with `cmd.no_binary_name(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Command::no_binary_name`
+
+Derive: replace `#[clap(setting = NoBinaryName)]` with `#[clap(no_binary_name = true)]`
+
+Builder: replace `cmd.setting(NoBinaryName)` with `cmd.no_binary_name(true)`
+"
+ )
+ )]
+ NoBinaryName,
+
+ /// Deprecated, replaced with [`Arg::action`][super::Arg::action]
+ ///
+ /// Derive: replace `#[clap(setting = NoAutoHelp)]` with setting an explicit action on your help argument
+ ///
+ /// Builder: replace `cmd.setting(NoAutoHelp)` with setting an explicit action on your help argument
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `Arg::action`
+
+Derive: replace `#[clap(setting = NoAutoHelp)]` with setting an explicit action on your help argument
+
+Builder: replace `cmd.setting(NoAutoHelp)` with setting an explicit action on your help argument
+"
+ )
+ )]
+ NoAutoHelp,
+
+ /// Deprecated, replaced with [`Arg::action`][super::Arg::action]
+ ///
+ /// Derive: replace `#[clap(setting = NoAutoVersion)]` with setting an explicit action on your version argument
+ ///
+ /// Builder: replace `cmd.setting(NoAutoVersion)` with setting an explicit action on your version argument
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `Arg::action`
+
+Derive: replace `#[clap(setting = NoAutoVersion)]` with setting an explicit action on your version argument
+
+Builder: replace `cmd.setting(NoAutoVersion)` with setting an explicit action on your version argument
+"
+ )
+ )]
+ NoAutoVersion,
+
+ /// Deprecated, replaced with [`Command::allow_hyphen_values`]
+ ///
+ /// Derive: replace `#[clap(setting = AllowLeadingHyphen)]` with `#[clap(allow_hyphen_values = true)]`
+ ///
+ /// Builder: replace `cmd.setting(AllowLeadingHyphen)` with `cmd.allow_hyphen_values(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `Command::allow_hyphen_values`
+
+Derive: replace `#[clap(setting = AllowLeadingHyphen)]` with `#[clap(allow_hyphen_values = true)]`
+
+Builder: replace `cmd.setting(AllowLeadingHyphen)` with `cmd.allow_hyphen_values(true)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ AllowLeadingHyphen,
+
+ /// Deprecated, replaced with [`Command::allow_invalid_utf8_for_external_subcommands`] and [`Command::is_allow_invalid_utf8_for_external_subcommands_set`]
+ ///
+ /// Derive: replace `#[clap(setting = StrictUtf8)]` with `#[clap(allow_invalid_utf8_for_external_subcommands = true)]`
+ ///
+ /// Builder: replace `cmd.setting(StrictUtf8)` with `cmd.allow_invalid_utf8_for_external_subcommands(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `Command::allow_invalid_utf8_for_external_subcommands` and `Command::is_allow_invalid_utf8_for_external_subcommands_set`
+
+Derive: replace `#[clap(setting = StrictUtf8)]` with `#[clap(allow_invalid_utf8_for_external_subcommands = true)]`
+
+Builder: replace `cmd.setting(StrictUtf8)` with `cmd.allow_invalid_utf8_for_external_subcommands(true)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ StrictUtf8,
+
+ /// Deprecated, this is now the default
+ ///
+ /// Derive: remove `#[clap(setting = UnifiedHelpMessage)]`
+ ///
+ /// Builder: remove `cmd.setting(UnifiedHelpMessage)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "This is now the default
+
+Derive: remove `#[clap(setting = UnifiedHelpMessage)]`
+
+Builder: remove `cmd.setting(UnifiedHelpMessage)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ UnifiedHelpMessage,
+
+ /// Deprecated, this is now the default
+ ///
+ /// Derive: remove `#[clap(setting = ColoredHelp)]`
+ ///
+ /// Builder: remove `cmd.setting(ColoredHelp)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "This is now the default
+
+Derive: remove `#[clap(setting = ColoredHelp)]`
+
+Builder: remove `cmd.setting(ColoredHelp)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ ColoredHelp,
+
+ /// Deprecated, see [`Command::color`][crate::Command::color]
+ ///
+ /// Derive: replace `#[clap(setting = ColorAuto)]` with `#[clap(color = ColorChoice::Auto)]``
+ ///
+ /// Builder: replace `cmd.setting(ColorAuto)` with `cmd.color(Color::Auto)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `Command::color`
+
+Derive: replace `#[clap(setting = ColorAuto)]` with `#[clap(color = ColorChoice::Auto)]``
+
+Builder: replace `cmd.setting(ColorAuto)` with `cmd.color(Color::Auto)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ ColorAuto,
+
+ /// Deprecated, replaced with [`Command::color`][crate::Command::color]
+ ///
+ /// Derive: replace `#[clap(setting = ColorAlways)]` with `#[clap(color = ColorChoice::Always)]``
+ ///
+ /// Builder: replace `cmd.setting(ColorAlways)` with `cmd.color(Color::Always)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `Command::color`
+
+Derive: replace `#[clap(setting = ColorAlways)]` with `#[clap(color = ColorChoice::Always)]``
+
+Builder: replace `cmd.setting(ColorAlways)` with `cmd.color(Color::Always)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ ColorAlways,
+
+ /// Deprecated, replaced with [`Command::color`][crate::Command::color]
+ ///
+ /// Derive: replace `#[clap(setting = ColorNever)]` with `#[clap(color = ColorChoice::Never)]``
+ ///
+ /// Builder: replace `cmd.setting(ColorNever)` with `cmd.color(Color::Never)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `Command::color`
+
+Derive: replace `#[clap(setting = ColorNever)]` with `#[clap(color = ColorChoice::Never)]``
+
+Builder: replace `cmd.setting(ColorNever)` with `cmd.color(Color::Never)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ ColorNever,
+
+ /// Deprecated, replaced with [`Command::disable_help_flag`] and [`Command::is_disable_help_flag_set`]
+ ///
+ /// Derive: replace `#[clap(setting = DisableHelpFlags)]` with `#[clap(disable_help_flag = true)]`
+ ///
+ /// Builder: replace `cmd.setting(DisableHelpFlags)` with `cmd.disable_help_flag(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `Command::disable_help_flag` and `Command::is_disable_help_flag_set`
+
+Derive: replace `#[clap(setting = DisableHelpFlags)]` with `#[clap(disable_help_flag = true)]`
+
+Builder: replace `cmd.setting(DisableHelpFlags)` with `cmd.disable_help_flag(true)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ DisableHelpFlags,
+
+ /// Deprecated, replaced with [`Command::disable_version_flag`] and
+ /// [`Command::is_disable_version_flag_set`]
+ ///
+ /// Derive: replace `#[clap(setting = DisableVersion)]` with `#[clap(disable_version_flag = true)]`
+ ///
+ /// Builder: replace `cmd.setting(DisableVersion)` with `cmd.disable_version_flag(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `Command::disable_version_flag` and `Command::is_disable_version_flag_set`
+
+Derive: replace `#[clap(setting = DisableVersion)]` with `#[clap(disable_version_flag = true)]`
+
+Builder: replace `cmd.setting(DisableVersion)` with `cmd.disable_version_flag(true)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ DisableVersion,
+
+ /// Deprecated, replaced with [`Command::propagate_version`] and [`Command::is_propagate_version_set`]
+ ///
+ /// Derive: replace `#[clap(setting = GlobalVersion)]` with `#[clap(propagate_version = true)]`
+ ///
+ /// Builder: replace `cmd.setting(GlobalVersion)` with `cmd.propagate_version(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `Command::propagate_version` and `Command::is_propagate_version_set`
+
+Derive: replace `#[clap(setting = GlobalVersion)]` with `#[clap(propagate_version = true)]`
+
+Builder: replace `cmd.setting(GlobalVersion)` with `cmd.propagate_version(true)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ GlobalVersion,
+
+ /// Deprecated, replaced with [`Command::hide_possible_values`] and
+ /// [`Arg::is_hide_possible_values_set`]
+ ///
+ /// Derive: replace `#[clap(setting = HidePossibleValuesInHelp)]` with `#[clap(hide_possible_values = true)]`
+ ///
+ /// Builder: replace `cmd.setting(HidePossibleValuesInHelp)` with `cmd.hide_possible_values(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `Command::hide_possible_values` and `Arg::is_hide_possible_values_set`
+
+Derive: replace `#[clap(setting = HidePossibleValuesInHelp)]` with `#[clap(hide_possible_values = true)]`
+
+Builder: replace `cmd.setting(HidePossibleValuesInHelp)` with `cmd.hide_possible_values(true)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ HidePossibleValuesInHelp,
+
+ /// Deprecated, this is now the default
+ ///
+ /// Derive: remove `#[clap(setting = UnifiedHelp)]`
+ ///
+ /// Builder: remove `cmd.setting(UnifiedHelp)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "This is now the default
+
+Derive: remove `#[clap(setting = UnifiedHelp)]`
+
+Builder: remove `cmd.setting(UnifiedHelp)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ UnifiedHelp,
+
+ /// If the cmd is already built, used for caching.
+ #[doc(hidden)]
+ Built,
+
+ /// If the cmd's bin name is already built, used for caching.
+ #[doc(hidden)]
+ BinNameBuilt,
+}
+
+bitflags! {
+ struct Flags: u64 {
+ const SC_NEGATE_REQS = 1;
+ const SC_REQUIRED = 1 << 1;
+ const ARG_REQUIRED_ELSE_HELP = 1 << 2;
+ const PROPAGATE_VERSION = 1 << 3;
+ const DISABLE_VERSION_FOR_SC = 1 << 4;
+ const WAIT_ON_ERROR = 1 << 6;
+ const SC_REQUIRED_ELSE_HELP = 1 << 7;
+ const NO_AUTO_HELP = 1 << 8;
+ const NO_AUTO_VERSION = 1 << 9;
+ const DISABLE_VERSION_FLAG = 1 << 10;
+ const HIDDEN = 1 << 11;
+ const TRAILING_VARARG = 1 << 12;
+ const NO_BIN_NAME = 1 << 13;
+ const ALLOW_UNK_SC = 1 << 14;
+ const SC_UTF8_NONE = 1 << 15;
+ const LEADING_HYPHEN = 1 << 16;
+ const NO_POS_VALUES = 1 << 17;
+ const NEXT_LINE_HELP = 1 << 18;
+ const DERIVE_DISP_ORDER = 1 << 19;
+ const DISABLE_COLORED_HELP = 1 << 20;
+ const COLOR_ALWAYS = 1 << 21;
+ const COLOR_AUTO = 1 << 22;
+ const COLOR_NEVER = 1 << 23;
+ const DONT_DELIM_TRAIL = 1 << 24;
+ const ALLOW_NEG_NUMS = 1 << 25;
+ const DISABLE_HELP_SC = 1 << 27;
+ const DONT_COLLAPSE_ARGS = 1 << 28;
+ const ARGS_NEGATE_SCS = 1 << 29;
+ const PROPAGATE_VALS_DOWN = 1 << 30;
+ const ALLOW_MISSING_POS = 1 << 31;
+ const TRAILING_VALUES = 1 << 32;
+ const BUILT = 1 << 33;
+ const BIN_NAME_BUILT = 1 << 34;
+ const VALID_ARG_FOUND = 1 << 35;
+ const INFER_SUBCOMMANDS = 1 << 36;
+ const CONTAINS_LAST = 1 << 37;
+ const ARGS_OVERRIDE_SELF = 1 << 38;
+ const HELP_REQUIRED = 1 << 39;
+ const SUBCOMMAND_PRECEDENCE_OVER_ARG = 1 << 40;
+ const DISABLE_HELP_FLAG = 1 << 41;
+ const USE_LONG_FORMAT_FOR_HELP_SC = 1 << 42;
+ const INFER_LONG_ARGS = 1 << 43;
+ const IGNORE_ERRORS = 1 << 44;
+ const MULTICALL = 1 << 45;
+ const NO_OP = 0;
+ }
+}
+
+impl_settings! { AppSettings, AppFlags,
+ ArgRequiredElseHelp
+ => Flags::ARG_REQUIRED_ELSE_HELP,
+ SubcommandPrecedenceOverArg
+ => Flags::SUBCOMMAND_PRECEDENCE_OVER_ARG,
+ ArgsNegateSubcommands
+ => Flags::ARGS_NEGATE_SCS,
+ AllowExternalSubcommands
+ => Flags::ALLOW_UNK_SC,
+ StrictUtf8
+ => Flags::NO_OP,
+ AllowInvalidUtf8ForExternalSubcommands
+ => Flags::SC_UTF8_NONE,
+ AllowHyphenValues
+ => Flags::LEADING_HYPHEN,
+ AllowLeadingHyphen
+ => Flags::LEADING_HYPHEN,
+ AllowNegativeNumbers
+ => Flags::ALLOW_NEG_NUMS,
+ AllowMissingPositional
+ => Flags::ALLOW_MISSING_POS,
+ UnifiedHelpMessage
+ => Flags::NO_OP,
+ ColoredHelp
+ => Flags::NO_OP,
+ ColorAlways
+ => Flags::COLOR_ALWAYS,
+ ColorAuto
+ => Flags::COLOR_AUTO,
+ ColorNever
+ => Flags::COLOR_NEVER,
+ DontDelimitTrailingValues
+ => Flags::DONT_DELIM_TRAIL,
+ DontCollapseArgsInUsage
+ => Flags::DONT_COLLAPSE_ARGS,
+ DeriveDisplayOrder
+ => Flags::DERIVE_DISP_ORDER,
+ DisableColoredHelp
+ => Flags::DISABLE_COLORED_HELP,
+ DisableHelpSubcommand
+ => Flags::DISABLE_HELP_SC,
+ DisableHelpFlag
+ => Flags::DISABLE_HELP_FLAG,
+ DisableHelpFlags
+ => Flags::DISABLE_HELP_FLAG,
+ DisableVersionFlag
+ => Flags::DISABLE_VERSION_FLAG,
+ DisableVersion
+ => Flags::DISABLE_VERSION_FLAG,
+ PropagateVersion
+ => Flags::PROPAGATE_VERSION,
+ GlobalVersion
+ => Flags::PROPAGATE_VERSION,
+ HidePossibleValues
+ => Flags::NO_POS_VALUES,
+ HidePossibleValuesInHelp
+ => Flags::NO_POS_VALUES,
+ HelpExpected
+ => Flags::HELP_REQUIRED,
+ Hidden
+ => Flags::HIDDEN,
+ Multicall
+ => Flags::MULTICALL,
+ NoAutoHelp
+ => Flags::NO_AUTO_HELP,
+ NoAutoVersion
+ => Flags::NO_AUTO_VERSION,
+ NoBinaryName
+ => Flags::NO_BIN_NAME,
+ SubcommandsNegateReqs
+ => Flags::SC_NEGATE_REQS,
+ SubcommandRequired
+ => Flags::SC_REQUIRED,
+ SubcommandRequiredElseHelp
+ => Flags::SC_REQUIRED_ELSE_HELP,
+ UseLongFormatForHelpSubcommand
+ => Flags::USE_LONG_FORMAT_FOR_HELP_SC,
+ TrailingVarArg
+ => Flags::TRAILING_VARARG,
+ UnifiedHelp => Flags::NO_OP,
+ NextLineHelp
+ => Flags::NEXT_LINE_HELP,
+ IgnoreErrors
+ => Flags::IGNORE_ERRORS,
+ WaitOnError
+ => Flags::WAIT_ON_ERROR,
+ Built
+ => Flags::BUILT,
+ BinNameBuilt
+ => Flags::BIN_NAME_BUILT,
+ InferSubcommands
+ => Flags::INFER_SUBCOMMANDS,
+ AllArgsOverrideSelf
+ => Flags::ARGS_OVERRIDE_SELF,
+ InferLongArgs
+ => Flags::INFER_LONG_ARGS
+}
+
+/// 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")]
+impl FromStr for AppSettings {
+ type Err = String;
+ fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
+ #[allow(deprecated)]
+ #[allow(unreachable_patterns)]
+ match &*s.to_ascii_lowercase() {
+ "argrequiredelsehelp" => Ok(AppSettings::ArgRequiredElseHelp),
+ "subcommandprecedenceoverarg" => Ok(AppSettings::SubcommandPrecedenceOverArg),
+ "argsnegatesubcommands" => Ok(AppSettings::ArgsNegateSubcommands),
+ "allowexternalsubcommands" => Ok(AppSettings::AllowExternalSubcommands),
+ "strictutf8" => Ok(AppSettings::StrictUtf8),
+ "allowinvalidutf8forexternalsubcommands" => {
+ Ok(AppSettings::AllowInvalidUtf8ForExternalSubcommands)
+ }
+ "allowhyphenvalues" => Ok(AppSettings::AllowHyphenValues),
+ "allowleadinghyphen" => Ok(AppSettings::AllowLeadingHyphen),
+ "allownegativenumbers" => Ok(AppSettings::AllowNegativeNumbers),
+ "allowmissingpositional" => Ok(AppSettings::AllowMissingPositional),
+ "unifiedhelpmessage" => Ok(AppSettings::UnifiedHelpMessage),
+ "coloredhelp" => Ok(AppSettings::ColoredHelp),
+ "coloralways" => Ok(AppSettings::ColorAlways),
+ "colorauto" => Ok(AppSettings::ColorAuto),
+ "colornever" => Ok(AppSettings::ColorNever),
+ "dontdelimittrailingvalues" => Ok(AppSettings::DontDelimitTrailingValues),
+ "dontcollapseargsinusage" => Ok(AppSettings::DontCollapseArgsInUsage),
+ "derivedisplayorder" => Ok(AppSettings::DeriveDisplayOrder),
+ "disablecoloredhelp" => Ok(AppSettings::DisableColoredHelp),
+ "disablehelpsubcommand" => Ok(AppSettings::DisableHelpSubcommand),
+ "disablehelpflag" => Ok(AppSettings::DisableHelpFlag),
+ "disablehelpflags" => Ok(AppSettings::DisableHelpFlags),
+ "disableversionflag" => Ok(AppSettings::DisableVersionFlag),
+ "disableversion" => Ok(AppSettings::DisableVersion),
+ "propagateversion" => Ok(AppSettings::PropagateVersion),
+ "propagateversion" => Ok(AppSettings::GlobalVersion),
+ "hidepossiblevalues" => Ok(AppSettings::HidePossibleValues),
+ "hidepossiblevaluesinhelp" => Ok(AppSettings::HidePossibleValuesInHelp),
+ "helpexpected" => Ok(AppSettings::HelpExpected),
+ "hidden" => Ok(AppSettings::Hidden),
+ "noautohelp" => Ok(AppSettings::NoAutoHelp),
+ "noautoversion" => Ok(AppSettings::NoAutoVersion),
+ "nobinaryname" => Ok(AppSettings::NoBinaryName),
+ "subcommandsnegatereqs" => Ok(AppSettings::SubcommandsNegateReqs),
+ "subcommandrequired" => Ok(AppSettings::SubcommandRequired),
+ "subcommandrequiredelsehelp" => Ok(AppSettings::SubcommandRequiredElseHelp),
+ "uselongformatforhelpsubcommand" => Ok(AppSettings::UseLongFormatForHelpSubcommand),
+ "trailingvararg" => Ok(AppSettings::TrailingVarArg),
+ "unifiedhelp" => Ok(AppSettings::UnifiedHelp),
+ "nextlinehelp" => Ok(AppSettings::NextLineHelp),
+ "ignoreerrors" => Ok(AppSettings::IgnoreErrors),
+ "waitonerror" => Ok(AppSettings::WaitOnError),
+ "built" => Ok(AppSettings::Built),
+ "binnamebuilt" => Ok(AppSettings::BinNameBuilt),
+ "infersubcommands" => Ok(AppSettings::InferSubcommands),
+ "allargsoverrideself" => Ok(AppSettings::AllArgsOverrideSelf),
+ "inferlongargs" => Ok(AppSettings::InferLongArgs),
+ _ => Err(format!("unknown AppSetting: `{}`", s)),
+ }
+ }
+}
+
+#[cfg(test)]
+mod test {
+ #[allow(clippy::cognitive_complexity)]
+ #[test]
+ #[cfg(feature = "yaml")]
+ fn app_settings_fromstr() {
+ use super::AppSettings;
+
+ assert_eq!(
+ "disablehelpflag".parse::<AppSettings>().unwrap(),
+ AppSettings::DisableHelpFlag
+ );
+ assert_eq!(
+ "argsnegatesubcommands".parse::<AppSettings>().unwrap(),
+ AppSettings::ArgsNegateSubcommands
+ );
+ assert_eq!(
+ "argrequiredelsehelp".parse::<AppSettings>().unwrap(),
+ AppSettings::ArgRequiredElseHelp
+ );
+ assert_eq!(
+ "subcommandprecedenceoverarg"
+ .parse::<AppSettings>()
+ .unwrap(),
+ AppSettings::SubcommandPrecedenceOverArg
+ );
+ assert_eq!(
+ "allowexternalsubcommands".parse::<AppSettings>().unwrap(),
+ AppSettings::AllowExternalSubcommands
+ );
+ assert_eq!(
+ "allowinvalidutf8forexternalsubcommands"
+ .parse::<AppSettings>()
+ .unwrap(),
+ AppSettings::AllowInvalidUtf8ForExternalSubcommands
+ );
+ assert_eq!(
+ "allowhyphenvalues".parse::<AppSettings>().unwrap(),
+ AppSettings::AllowHyphenValues
+ );
+ assert_eq!(
+ "allownegativenumbers".parse::<AppSettings>().unwrap(),
+ AppSettings::AllowNegativeNumbers
+ );
+ assert_eq!(
+ "disablehelpsubcommand".parse::<AppSettings>().unwrap(),
+ AppSettings::DisableHelpSubcommand
+ );
+ assert_eq!(
+ "disableversionflag".parse::<AppSettings>().unwrap(),
+ AppSettings::DisableVersionFlag
+ );
+ assert_eq!(
+ "dontcollapseargsinusage".parse::<AppSettings>().unwrap(),
+ AppSettings::DontCollapseArgsInUsage
+ );
+ assert_eq!(
+ "dontdelimittrailingvalues".parse::<AppSettings>().unwrap(),
+ AppSettings::DontDelimitTrailingValues
+ );
+ assert_eq!(
+ "derivedisplayorder".parse::<AppSettings>().unwrap(),
+ AppSettings::DeriveDisplayOrder
+ );
+ assert_eq!(
+ "disablecoloredhelp".parse::<AppSettings>().unwrap(),
+ AppSettings::DisableColoredHelp
+ );
+ assert_eq!(
+ "propagateversion".parse::<AppSettings>().unwrap(),
+ AppSettings::PropagateVersion
+ );
+ assert_eq!(
+ "hidden".parse::<AppSettings>().unwrap(),
+ AppSettings::Hidden
+ );
+ assert_eq!(
+ "hidepossiblevalues".parse::<AppSettings>().unwrap(),
+ AppSettings::HidePossibleValues
+ );
+ assert_eq!(
+ "helpexpected".parse::<AppSettings>().unwrap(),
+ AppSettings::HelpExpected
+ );
+ assert_eq!(
+ "nobinaryname".parse::<AppSettings>().unwrap(),
+ AppSettings::NoBinaryName
+ );
+ assert_eq!(
+ "nextlinehelp".parse::<AppSettings>().unwrap(),
+ AppSettings::NextLineHelp
+ );
+ assert_eq!(
+ "subcommandsnegatereqs".parse::<AppSettings>().unwrap(),
+ AppSettings::SubcommandsNegateReqs
+ );
+ assert_eq!(
+ "subcommandrequired".parse::<AppSettings>().unwrap(),
+ AppSettings::SubcommandRequired
+ );
+ assert_eq!(
+ "subcommandrequiredelsehelp".parse::<AppSettings>().unwrap(),
+ AppSettings::SubcommandRequiredElseHelp
+ );
+ assert_eq!(
+ "uselongformatforhelpsubcommand"
+ .parse::<AppSettings>()
+ .unwrap(),
+ AppSettings::UseLongFormatForHelpSubcommand
+ );
+ assert_eq!(
+ "trailingvararg".parse::<AppSettings>().unwrap(),
+ AppSettings::TrailingVarArg
+ );
+ assert_eq!(
+ "waitonerror".parse::<AppSettings>().unwrap(),
+ AppSettings::WaitOnError
+ );
+ assert_eq!("built".parse::<AppSettings>().unwrap(), AppSettings::Built);
+ assert_eq!(
+ "binnamebuilt".parse::<AppSettings>().unwrap(),
+ AppSettings::BinNameBuilt
+ );
+ assert_eq!(
+ "infersubcommands".parse::<AppSettings>().unwrap(),
+ AppSettings::InferSubcommands
+ );
+ assert!("hahahaha".parse::<AppSettings>().is_err());
+ }
+}
diff --git a/3.2.23/src/builder/arg.rs b/3.2.23/src/builder/arg.rs
new file mode 100644
index 0000000..fb42d87
--- /dev/null
+++ b/3.2.23/src/builder/arg.rs
@@ -0,0 +1,5618 @@
+#![allow(deprecated)]
+
+// Std
+use std::{
+ borrow::Cow,
+ cmp::{Ord, Ordering},
+ error::Error,
+ ffi::OsStr,
+ fmt::{self, Display, Formatter},
+ str,
+ sync::{Arc, Mutex},
+};
+#[cfg(feature = "env")]
+use std::{env, ffi::OsString};
+
+#[cfg(feature = "yaml")]
+use yaml_rust::Yaml;
+
+// Internal
+use crate::builder::usage_parser::UsageParser;
+use crate::builder::ArgPredicate;
+use crate::util::{Id, Key};
+use crate::ArgAction;
+use crate::PossibleValue;
+use crate::ValueHint;
+use crate::INTERNAL_ERROR_MSG;
+use crate::{ArgFlags, ArgSettings};
+
+#[cfg(feature = "regex")]
+use crate::builder::RegexRef;
+
+/// The abstract representation of a command line argument. Used to set all the options and
+/// relationships that define a valid argument for the program.
+///
+/// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options
+/// manually, or using a usage string which is far less verbose but has fewer options. You can also
+/// use a combination of the two methods to achieve the best of both worlds.
+///
+/// - [Basic API][crate::Arg#basic-api]
+/// - [Value Handling][crate::Arg#value-handling]
+/// - [Help][crate::Arg#help-1]
+/// - [Advanced Argument Relations][crate::Arg#advanced-argument-relations]
+/// - [Reflection][crate::Arg#reflection]
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::{Arg, arg};
+/// // Using the traditional builder pattern and setting each option manually
+/// let cfg = Arg::new("config")
+/// .short('c')
+/// .long("config")
+/// .takes_value(true)
+/// .value_name("FILE")
+/// .help("Provides a config file to myprog");
+/// // Using a usage string (setting a similar argument to the one above)
+/// let input = arg!(-i --input <FILE> "Provides an input file to the program");
+/// ```
+#[allow(missing_debug_implementations)]
+#[derive(Default, Clone)]
+pub struct Arg<'help> {
+ pub(crate) id: Id,
+ pub(crate) provider: ArgProvider,
+ pub(crate) name: &'help str,
+ pub(crate) help: Option<&'help str>,
+ pub(crate) long_help: Option<&'help str>,
+ pub(crate) action: Option<ArgAction>,
+ pub(crate) value_parser: Option<super::ValueParser>,
+ pub(crate) blacklist: Vec<Id>,
+ pub(crate) settings: ArgFlags,
+ pub(crate) overrides: Vec<Id>,
+ pub(crate) groups: Vec<Id>,
+ pub(crate) requires: Vec<(ArgPredicate<'help>, Id)>,
+ pub(crate) r_ifs: Vec<(Id, &'help str)>,
+ pub(crate) r_ifs_all: Vec<(Id, &'help str)>,
+ pub(crate) r_unless: Vec<Id>,
+ pub(crate) r_unless_all: Vec<Id>,
+ pub(crate) short: Option<char>,
+ pub(crate) long: Option<&'help str>,
+ pub(crate) aliases: Vec<(&'help str, bool)>, // (name, visible)
+ pub(crate) short_aliases: Vec<(char, bool)>, // (name, visible)
+ pub(crate) disp_ord: DisplayOrder,
+ pub(crate) possible_vals: Vec<PossibleValue<'help>>,
+ pub(crate) val_names: Vec<&'help str>,
+ pub(crate) num_vals: Option<usize>,
+ pub(crate) max_occurs: Option<usize>,
+ pub(crate) max_vals: Option<usize>,
+ pub(crate) min_vals: Option<usize>,
+ pub(crate) validator: Option<Arc<Mutex<Validator<'help>>>>,
+ pub(crate) validator_os: Option<Arc<Mutex<ValidatorOs<'help>>>>,
+ pub(crate) val_delim: Option<char>,
+ pub(crate) default_vals: Vec<&'help OsStr>,
+ pub(crate) default_vals_ifs: Vec<(Id, ArgPredicate<'help>, Option<&'help OsStr>)>,
+ pub(crate) default_missing_vals: Vec<&'help OsStr>,
+ #[cfg(feature = "env")]
+ pub(crate) env: Option<(&'help OsStr, Option<OsString>)>,
+ pub(crate) terminator: Option<&'help str>,
+ pub(crate) index: Option<usize>,
+ pub(crate) help_heading: Option<Option<&'help str>>,
+ pub(crate) value_hint: Option<ValueHint>,
+}
+
+/// # Basic API
+impl<'help> Arg<'help> {
+ /// Create a new [`Arg`] with a unique name.
+ ///
+ /// The name is used to check whether or not the argument was used at
+ /// runtime, get values, set relationships with other args, etc..
+ ///
+ /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::takes_value(true)`])
+ /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also
+ /// be displayed when the user prints the usage/help information of the program.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("config")
+ /// # ;
+ /// ```
+ /// [`Arg::takes_value(true)`]: Arg::takes_value()
+ pub fn new<S: Into<&'help str>>(n: S) -> Self {
+ Arg::default().name(n)
+ }
+
+ /// Set the identifier used for referencing this argument in the clap API.
+ ///
+ /// See [`Arg::new`] for more details.
+ #[must_use]
+ pub fn id<S: Into<&'help str>>(mut self, n: S) -> Self {
+ let name = n.into();
+ self.id = Id::from(&*name);
+ self.name = name;
+ self
+ }
+
+ /// Deprecated, replaced with [`Arg::id`] to avoid confusion with [`Arg::value_name`]
+ ///
+ /// Builder: replaced `arg.name(...)` with `arg.id(...)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::id` to avoid confusion with `Arg::value_name`
+
+Builder: replaced `arg.name(...)` with `arg.id(...)`
+"
+ )
+ )]
+ pub fn name<S: Into<&'help str>>(self, n: S) -> Self {
+ self.id(n)
+ }
+
+ /// Sets the short version of the argument without the preceding `-`.
+ ///
+ /// By default `V` and `h` are used by the auto-generated `version` and `help` arguments,
+ /// respectively. You may use the uppercase `V` or lowercase `h` for your own arguments, in
+ /// which case `clap` simply will not assign those to the auto-generated
+ /// `version` or `help` arguments.
+ ///
+ /// # Examples
+ ///
+ /// When calling `short`, use a single valid UTF-8 character which will allow using the
+ /// argument via a single hyphen (`-`) such as `-c`:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("config")
+ /// .short('c')
+ /// .takes_value(true))
+ /// .get_matches_from(vec![
+ /// "prog", "-c", "file.toml"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("config").map(String::as_str), Some("file.toml"));
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn short(mut self, s: char) -> Self {
+ assert!(s != '-', "short option name cannot be `-`");
+
+ self.short = Some(s);
+ self
+ }
+
+ /// Sets the long version of the argument without the preceding `--`.
+ ///
+ /// By default `version` and `help` are used by the auto-generated `version` and `help`
+ /// arguments, respectively. You may use the word `version` or `help` for the long form of your
+ /// own arguments, in which case `clap` simply will not assign those to the auto-generated
+ /// `version` or `help` arguments.
+ ///
+ /// **NOTE:** Any leading `-` characters will be stripped
+ ///
+ /// # Examples
+ ///
+ /// To set `long` use a word containing valid UTF-8. If you supply a double leading
+ /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however,
+ /// will *not* be stripped (i.e. `config-file` is allowed).
+ ///
+ /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config`
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .takes_value(true))
+ /// .get_matches_from(vec![
+ /// "prog", "--config", "file.toml"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("cfg").map(String::as_str), Some("file.toml"));
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn long(mut self, l: &'help str) -> Self {
+ #[cfg(feature = "unstable-v4")]
+ {
+ self.long = Some(l);
+ }
+ #[cfg(not(feature = "unstable-v4"))]
+ {
+ self.long = Some(l.trim_start_matches(|c| c == '-'));
+ }
+ self
+ }
+
+ /// Add an alias, which functions as a hidden long flag.
+ ///
+ /// This is more efficient, and easier than creating multiple hidden arguments as one only
+ /// needs to check for the existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .long("test")
+ /// .alias("alias")
+ /// .takes_value(true))
+ /// .get_matches_from(vec![
+ /// "prog", "--alias", "cool"
+ /// ]);
+ /// assert!(m.contains_id("test"));
+ /// assert_eq!(m.value_of("test"), Some("cool"));
+ /// ```
+ #[must_use]
+ pub fn alias<S: Into<&'help str>>(mut self, name: S) -> Self {
+ self.aliases.push((name.into(), false));
+ self
+ }
+
+ /// Add an alias, which functions as a hidden short flag.
+ ///
+ /// This is more efficient, and easier than creating multiple hidden arguments as one only
+ /// needs to check for the existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .short('t')
+ /// .short_alias('e')
+ /// .takes_value(true))
+ /// .get_matches_from(vec![
+ /// "prog", "-e", "cool"
+ /// ]);
+ /// assert!(m.contains_id("test"));
+ /// assert_eq!(m.value_of("test"), Some("cool"));
+ /// ```
+ #[must_use]
+ pub fn short_alias(mut self, name: char) -> Self {
+ assert!(name != '-', "short alias name cannot be `-`");
+
+ self.short_aliases.push((name, false));
+ self
+ }
+
+ /// Add aliases, which function as hidden long flags.
+ ///
+ /// This is more efficient, and easier than creating multiple hidden subcommands as one only
+ /// needs to check for the existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .long("test")
+ /// .aliases(&["do-stuff", "do-tests", "tests"])
+ /// .action(ArgAction::SetTrue)
+ /// .help("the file to add")
+ /// .required(false))
+ /// .get_matches_from(vec![
+ /// "prog", "--do-tests"
+ /// ]);
+ /// assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);
+ /// ```
+ #[must_use]
+ pub fn aliases(mut self, names: &[&'help str]) -> Self {
+ self.aliases.extend(names.iter().map(|&x| (x, false)));
+ self
+ }
+
+ /// Add aliases, which functions as a hidden short flag.
+ ///
+ /// This is more efficient, and easier than creating multiple hidden subcommands as one only
+ /// needs to check for the existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .short('t')
+ /// .short_aliases(&['e', 's'])
+ /// .action(ArgAction::SetTrue)
+ /// .help("the file to add")
+ /// .required(false))
+ /// .get_matches_from(vec![
+ /// "prog", "-s"
+ /// ]);
+ /// assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);
+ /// ```
+ #[must_use]
+ pub fn short_aliases(mut self, names: &[char]) -> Self {
+ for s in names {
+ assert!(s != &'-', "short alias name cannot be `-`");
+ self.short_aliases.push((*s, false));
+ }
+ self
+ }
+
+ /// Add an alias, which functions as a visible long flag.
+ ///
+ /// Like [`Arg::alias`], except that they are visible inside the help message.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .visible_alias("something-awesome")
+ /// .long("test")
+ /// .takes_value(true))
+ /// .get_matches_from(vec![
+ /// "prog", "--something-awesome", "coffee"
+ /// ]);
+ /// assert!(m.contains_id("test"));
+ /// assert_eq!(m.value_of("test"), Some("coffee"));
+ /// ```
+ /// [`Command::alias`]: Arg::alias()
+ #[must_use]
+ pub fn visible_alias<S: Into<&'help str>>(mut self, name: S) -> Self {
+ self.aliases.push((name.into(), true));
+ self
+ }
+
+ /// Add an alias, which functions as a visible short flag.
+ ///
+ /// Like [`Arg::short_alias`], except that they are visible inside the help message.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .long("test")
+ /// .visible_short_alias('t')
+ /// .takes_value(true))
+ /// .get_matches_from(vec![
+ /// "prog", "-t", "coffee"
+ /// ]);
+ /// assert!(m.contains_id("test"));
+ /// assert_eq!(m.value_of("test"), Some("coffee"));
+ /// ```
+ #[must_use]
+ pub fn visible_short_alias(mut self, name: char) -> Self {
+ assert!(name != '-', "short alias name cannot be `-`");
+
+ self.short_aliases.push((name, true));
+ self
+ }
+
+ /// Add aliases, which function as visible long flags.
+ ///
+ /// Like [`Arg::aliases`], except that they are visible inside the help message.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .long("test")
+ /// .action(ArgAction::SetTrue)
+ /// .visible_aliases(&["something", "awesome", "cool"]))
+ /// .get_matches_from(vec![
+ /// "prog", "--awesome"
+ /// ]);
+ /// assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);
+ /// ```
+ /// [`Command::aliases`]: Arg::aliases()
+ #[must_use]
+ pub fn visible_aliases(mut self, names: &[&'help str]) -> Self {
+ self.aliases.extend(names.iter().map(|n| (*n, true)));
+ self
+ }
+
+ /// Add aliases, which function as visible short flags.
+ ///
+ /// Like [`Arg::short_aliases`], except that they are visible inside the help message.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .long("test")
+ /// .action(ArgAction::SetTrue)
+ /// .visible_short_aliases(&['t', 'e']))
+ /// .get_matches_from(vec![
+ /// "prog", "-t"
+ /// ]);
+ /// assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);
+ /// ```
+ #[must_use]
+ pub fn visible_short_aliases(mut self, names: &[char]) -> Self {
+ for n in names {
+ assert!(n != &'-', "short alias name cannot be `-`");
+ self.short_aliases.push((*n, true));
+ }
+ self
+ }
+
+ /// Specifies the index of a positional argument **starting at** 1.
+ ///
+ /// **NOTE:** The index refers to position according to **other positional argument**. It does
+ /// not define position in the argument list as a whole.
+ ///
+ /// **NOTE:** You can optionally leave off the `index` method, and the index will be
+ /// assigned in order of evaluation. Utilizing the `index` method allows for setting
+ /// indexes out of order
+ ///
+ /// **NOTE:** This is only meant to be used for positional arguments and shouldn't to be used
+ /// with [`Arg::short`] or [`Arg::long`].
+ ///
+ /// **NOTE:** When utilized with [`Arg::multiple_values(true)`], only the **last** positional argument
+ /// may be defined as multiple (i.e. with the highest index)
+ ///
+ /// # Panics
+ ///
+ /// [`Command`] will [`panic!`] if indexes are skipped (such as defining `index(1)` and `index(3)`
+ /// but not `index(2)`, or a positional argument is defined as multiple and is not the highest
+ /// index
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("config")
+ /// .index(1)
+ /// # ;
+ /// ```
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("mode")
+ /// .index(1))
+ /// .arg(Arg::new("debug")
+ /// .long("debug"))
+ /// .get_matches_from(vec![
+ /// "prog", "--debug", "fast"
+ /// ]);
+ ///
+ /// assert!(m.contains_id("mode"));
+ /// assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional"
+ /// // *not* first argument
+ /// ```
+ /// [`Arg::short`]: Arg::short()
+ /// [`Arg::long`]: Arg::long()
+ /// [`Arg::multiple_values(true)`]: Arg::multiple_values()
+ /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
+ /// [`Command`]: crate::Command
+ #[inline]
+ #[must_use]
+ pub fn index(mut self, idx: usize) -> Self {
+ self.index = Some(idx);
+ self
+ }
+
+ /// This arg is the last, or final, positional argument (i.e. has the highest
+ /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args --
+ /// last_arg`).
+ ///
+ /// Even, if no other arguments are left to parse, if the user omits the `--` syntax
+ /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also
+ /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with
+ /// the `--` syntax is otherwise not possible.
+ ///
+ /// **NOTE:** This will change the usage string to look like `$ prog [OPTIONS] [-- <ARG>]` if
+ /// `ARG` is marked as `.last(true)`.
+ ///
+ /// **NOTE:** This setting will imply [`crate::Command::dont_collapse_args_in_usage`] because failing
+ /// to set this can make the usage string very confusing.
+ ///
+ /// **NOTE**: This setting only applies to positional arguments, and has no effect on OPTIONS
+ ///
+ /// **NOTE:** Setting this requires [`Arg::takes_value`]
+ ///
+ /// **CAUTION:** Using this setting *and* having child subcommands is not
+ /// recommended with the exception of *also* using
+ /// [`crate::Command::args_conflicts_with_subcommands`]
+ /// (or [`crate::Command::subcommand_negates_reqs`] if the argument marked `Last` is also
+ /// marked [`Arg::required`])
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("args")
+ /// .takes_value(true)
+ /// .last(true)
+ /// # ;
+ /// ```
+ ///
+ /// Setting `last` ensures the arg has the highest [index] of all positional args
+ /// and requires that the `--` syntax be used to access it early.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("first"))
+ /// .arg(Arg::new("second"))
+ /// .arg(Arg::new("third")
+ /// .takes_value(true)
+ /// .last(true))
+ /// .try_get_matches_from(vec![
+ /// "prog", "one", "--", "three"
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// let m = res.unwrap();
+ /// assert_eq!(m.value_of("third"), Some("three"));
+ /// assert!(m.value_of("second").is_none());
+ /// ```
+ ///
+ /// Even if the positional argument marked `Last` is the only argument left to parse,
+ /// failing to use the `--` syntax results in an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("first"))
+ /// .arg(Arg::new("second"))
+ /// .arg(Arg::new("third")
+ /// .takes_value(true)
+ /// .last(true))
+ /// .try_get_matches_from(vec![
+ /// "prog", "one", "two", "three"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
+ /// ```
+ /// [index]: Arg::index()
+ /// [`UnknownArgument`]: crate::ErrorKind::UnknownArgument
+ #[inline]
+ #[must_use]
+ pub fn last(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::Last)
+ } else {
+ self.unset_setting(ArgSettings::Last)
+ }
+ }
+
+ /// Specifies that the argument must be present.
+ ///
+ /// Required by default means it is required, when no other conflicting rules or overrides have
+ /// been evaluated. Conflicting rules take precedence over being required.
+ ///
+ /// **Pro tip:** Flags (i.e. not positional, or arguments that take values) shouldn't be
+ /// required by default. This is because if a flag were to be required, it should simply be
+ /// implied. No additional information is required from user. Flags by their very nature are
+ /// simply boolean on/off switches. The only time a user *should* be required to use a flag
+ /// is if the operation is destructive in nature, and the user is essentially proving to you,
+ /// "Yes, I know what I'm doing."
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required(true)
+ /// # ;
+ /// ```
+ ///
+ /// Setting required requires that the argument be used at runtime.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required(true)
+ /// .takes_value(true)
+ /// .long("config"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "file.conf",
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// ```
+ ///
+ /// Setting required and then *not* supplying that argument at runtime is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required(true)
+ /// .takes_value(true)
+ /// .long("config"))
+ /// .try_get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn required(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::Required)
+ } else {
+ self.unset_setting(ArgSettings::Required)
+ }
+ }
+
+ /// Sets an argument that is required when this one is present
+ ///
+ /// i.e. when using this argument, the following argument *must* be present.
+ ///
+ /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .requires("input")
+ /// # ;
+ /// ```
+ ///
+ /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the
+ /// defining argument is used. If the defining argument isn't used, the other argument isn't
+ /// required
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .requires("input")
+ /// .long("config"))
+ /// .arg(Arg::new("input"))
+ /// .try_get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required
+ /// ```
+ ///
+ /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .requires("input")
+ /// .long("config"))
+ /// .arg(Arg::new("input"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "file.conf"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [`Arg::requires(name)`]: Arg::requires()
+ /// [Conflicting]: Arg::conflicts_with()
+ /// [override]: Arg::overrides_with()
+ #[must_use]
+ pub fn requires<T: Key>(mut self, arg_id: T) -> Self {
+ self.requires.push((ArgPredicate::IsPresent, arg_id.into()));
+ self
+ }
+
+ /// This argument must be passed alone; it conflicts with all other arguments.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .exclusive(true)
+ /// # ;
+ /// ```
+ ///
+ /// Setting an exclusive argument and having any other arguments present at runtime
+ /// is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("exclusive")
+ /// .takes_value(true)
+ /// .exclusive(true)
+ /// .long("exclusive"))
+ /// .arg(Arg::new("debug")
+ /// .long("debug"))
+ /// .arg(Arg::new("input"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--exclusive", "file.conf", "file.txt"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn exclusive(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::Exclusive)
+ } else {
+ self.unset_setting(ArgSettings::Exclusive)
+ }
+ }
+
+ /// Specifies that an argument can be matched to all child [`Subcommand`]s.
+ ///
+ /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however
+ /// their values once a user uses them will be propagated back up to parents. In effect, this
+ /// means one should *define* all global arguments at the top level, however it doesn't matter
+ /// where the user *uses* the global argument.
+ ///
+ /// # Examples
+ ///
+ /// Assume an application with two subcommands, and you'd like to define a
+ /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't
+ /// want to clutter the source with three duplicate [`Arg`] definitions.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("verb")
+ /// .long("verbose")
+ /// .short('v')
+ /// .action(ArgAction::SetTrue)
+ /// .global(true))
+ /// .subcommand(Command::new("test"))
+ /// .subcommand(Command::new("do-stuff"))
+ /// .get_matches_from(vec![
+ /// "prog", "do-stuff", "--verbose"
+ /// ]);
+ ///
+ /// assert_eq!(m.subcommand_name(), Some("do-stuff"));
+ /// let sub_m = m.subcommand_matches("do-stuff").unwrap();
+ /// assert_eq!(*sub_m.get_one::<bool>("verb").expect("defaulted by clap"), true);
+ /// ```
+ ///
+ /// [`Subcommand`]: crate::Subcommand
+ #[inline]
+ #[must_use]
+ pub fn global(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::Global)
+ } else {
+ self.unset_setting(ArgSettings::Global)
+ }
+ }
+
+ /// Deprecated, replaced with [`Arg::action`] ([Issue #3772](https://github.com/clap-rs/clap/issues/3772))
+ #[inline]
+ #[must_use]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `Arg::action` (Issue #3772)
+
+Builder: replace `arg.multiple_occurrences(true)` with `arg.action(ArgAction::Append)` when taking a value and `arg.action(ArgAction::Count)` with `matches.get_count` when not
+"
+ )
+ )]
+ pub fn multiple_occurrences(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::MultipleOccurrences)
+ } else {
+ self.unset_setting(ArgSettings::MultipleOccurrences)
+ }
+ }
+
+ /// Deprecated, for flags, this is replaced with `RangedI64ValueParser::range`
+ ///
+ /// Derive: `#[clap(action = ArgAction::Count, value_parser = value_parser!(u8).range(..max))]`
+ ///
+ /// Builder: `arg.action(ArgAction::Count).value_parser(value_parser!(u8).range(..max))`
+ #[inline]
+ #[must_use]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "For flags, this is replaced with `RangedI64ValueParser::range`
+
+Derive: `#[clap(action = ArgAction::Count, value_parser = value_parser!(u8).range(..max))]`
+
+Builder: `arg.action(ArgAction::Count).value_parser(value_parser!(u8).range(..max))`
+"
+ )
+ )]
+ pub fn max_occurrences(mut self, qty: usize) -> Self {
+ self.max_occurs = Some(qty);
+ if qty > 1 {
+ self.multiple_occurrences(true)
+ } else {
+ self
+ }
+ }
+
+ /// Check if the [`ArgSettings`] variant is currently set on the argument.
+ ///
+ /// [`ArgSettings`]: crate::ArgSettings
+ #[inline]
+ pub fn is_set(&self, s: ArgSettings) -> bool {
+ self.settings.is_set(s)
+ }
+
+ /// Apply a setting to the argument.
+ ///
+ /// See [`ArgSettings`] for a full list of possibilities and examples.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Arg, ArgSettings};
+ /// Arg::new("config")
+ /// .setting(ArgSettings::Required)
+ /// .setting(ArgSettings::TakesValue)
+ /// # ;
+ /// ```
+ ///
+ /// ```no_run
+ /// # use clap::{Arg, ArgSettings};
+ /// Arg::new("config")
+ /// .setting(ArgSettings::Required | ArgSettings::TakesValue)
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn setting<F>(mut self, setting: F) -> Self
+ where
+ F: Into<ArgFlags>,
+ {
+ self.settings.insert(setting.into());
+ self
+ }
+
+ /// Remove a setting from the argument.
+ ///
+ /// See [`ArgSettings`] for a full list of possibilities and examples.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Arg, ArgSettings};
+ /// Arg::new("config")
+ /// .unset_setting(ArgSettings::Required)
+ /// .unset_setting(ArgSettings::TakesValue)
+ /// # ;
+ /// ```
+ ///
+ /// ```no_run
+ /// # use clap::{Arg, ArgSettings};
+ /// Arg::new("config")
+ /// .unset_setting(ArgSettings::Required | ArgSettings::TakesValue)
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn unset_setting<F>(mut self, setting: F) -> Self
+ where
+ F: Into<ArgFlags>,
+ {
+ self.settings.remove(setting.into());
+ self
+ }
+}
+
+/// # Value Handling
+impl<'help> Arg<'help> {
+ /// Specifies that the argument takes a value at run time.
+ ///
+ /// **NOTE:** values for arguments may be specified in any of the following methods
+ ///
+ /// - Using a space such as `-o value` or `--option value`
+ /// - Using an equals and no space such as `-o=value` or `--option=value`
+ /// - Use a short and no space such as `-ovalue`
+ ///
+ /// **NOTE:** By default, args which allow [multiple values] are delimited by commas, meaning
+ /// `--option=val1,val2,val3` is three values for the `--option` argument. If you wish to
+ /// change the delimiter to another character you can use [`Arg::value_delimiter(char)`],
+ /// alternatively you can turn delimiting values **OFF** by using
+ /// [`Arg::use_value_delimiter(false)`][Arg::use_value_delimiter]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("mode")
+ /// .long("mode")
+ /// .takes_value(true))
+ /// .get_matches_from(vec![
+ /// "prog", "--mode", "fast"
+ /// ]);
+ ///
+ /// assert!(m.contains_id("mode"));
+ /// assert_eq!(m.value_of("mode"), Some("fast"));
+ /// ```
+ /// [`Arg::value_delimiter(char)`]: Arg::value_delimiter()
+ /// [multiple values]: Arg::multiple_values
+ #[inline]
+ #[must_use]
+ pub fn takes_value(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::TakesValue)
+ } else {
+ self.unset_setting(ArgSettings::TakesValue)
+ }
+ }
+
+ /// Specify the behavior when parsing an argument
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("flag")
+ /// .long("flag")
+ /// .action(clap::ArgAction::Set)
+ /// );
+ ///
+ /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(matches.occurrences_of("flag"), 0);
+ /// assert_eq!(
+ /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(),
+ /// vec!["value"]
+ /// );
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn action(mut self, action: ArgAction) -> Self {
+ self.action = Some(action);
+ self
+ }
+
+ /// Specify the type of the argument.
+ ///
+ /// This allows parsing and validating a value before storing it into
+ /// [`ArgMatches`][crate::ArgMatches].
+ ///
+ /// See also
+ /// - [`value_parser!`][crate::value_parser!] for auto-selecting a value parser for a given type
+ /// - [`BoolishValueParser`][crate::builder::BoolishValueParser], and [`FalseyValueParser`][crate::builder::FalseyValueParser] for alternative `bool` implementations
+ /// - [`NonEmptyStringValueParser`][crate::builder::NonEmptyStringValueParser] for basic validation for strings
+ /// - [`RangedI64ValueParser`][crate::builder::RangedI64ValueParser] and [`RangedU64ValueParser`][crate::builder::RangedU64ValueParser] for numeric ranges
+ /// - [`EnumValueParser`][crate::builder::EnumValueParser] and [`PossibleValuesParser`][crate::builder::PossibleValuesParser] for static enumerated values
+ /// - or any other [`TypedValueParser`][crate::builder::TypedValueParser] implementation
+ ///
+ /// ```rust
+ /// let mut cmd = clap::Command::new("raw")
+ /// .arg(
+ /// clap::Arg::new("color")
+ /// .long("color")
+ /// .value_parser(["always", "auto", "never"])
+ /// .default_value("auto")
+ /// )
+ /// .arg(
+ /// clap::Arg::new("hostname")
+ /// .long("hostname")
+ /// .value_parser(clap::builder::NonEmptyStringValueParser::new())
+ /// .takes_value(true)
+ /// .required(true)
+ /// )
+ /// .arg(
+ /// clap::Arg::new("port")
+ /// .long("port")
+ /// .value_parser(clap::value_parser!(u16).range(3000..))
+ /// .takes_value(true)
+ /// .required(true)
+ /// );
+ ///
+ /// let m = cmd.try_get_matches_from_mut(
+ /// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"]
+ /// ).unwrap();
+ ///
+ /// let color: &String = m.get_one("color")
+ /// .expect("default");
+ /// assert_eq!(color, "auto");
+ ///
+ /// let hostname: &String = m.get_one("hostname")
+ /// .expect("required");
+ /// assert_eq!(hostname, "rust-lang.org");
+ ///
+ /// let port: u16 = *m.get_one("port")
+ /// .expect("required");
+ /// assert_eq!(port, 3001);
+ /// ```
+ pub fn value_parser(mut self, parser: impl Into<super::ValueParser>) -> Self {
+ self.value_parser = Some(parser.into());
+ self
+ }
+
+ /// Specifies that the argument may have an unknown number of values
+ ///
+ /// Without any other settings, this argument may appear only *once*.
+ ///
+ /// For example, `--opt val1 val2` is allowed, but `--opt val1 val2 --opt val3` is not.
+ ///
+ /// **NOTE:** Setting this requires [`Arg::takes_value`].
+ ///
+ /// **WARNING:**
+ ///
+ /// Setting `multiple_values` for an argument that takes a value, but with no other details can
+ /// be dangerous in some circumstances. Because multiple values are allowed,
+ /// `--option val1 val2 val3` is perfectly valid. Be careful when designing a CLI where
+ /// positional arguments are *also* expected as `clap` will continue parsing *values* until one
+ /// of the following happens:
+ ///
+ /// - It reaches the [maximum number of values]
+ /// - It reaches a [specific number of values]
+ /// - It finds another flag or option (i.e. something that starts with a `-`)
+ /// - It reaches a [value terminator][Arg::value_terminator] is reached
+ ///
+ /// Alternatively, [require a delimiter between values][Arg::require_delimiter].
+ ///
+ /// **WARNING:**
+ ///
+ /// When using args with `multiple_values` and [`subcommands`], one needs to consider the
+ /// possibility of an argument value being the same as a valid subcommand. By default `clap` will
+ /// parse the argument in question as a value *only if* a value is possible at that moment.
+ /// Otherwise it will be parsed as a subcommand. In effect, this means using `multiple_values` with no
+ /// additional parameters and a value that coincides with a subcommand name, the subcommand
+ /// cannot be called unless another argument is passed between them.
+ ///
+ /// As an example, consider a CLI with an option `--ui-paths=<paths>...` and subcommand `signer`
+ ///
+ /// The following would be parsed as values to `--ui-paths`.
+ ///
+ /// ```text
+ /// $ program --ui-paths path1 path2 signer
+ /// ```
+ ///
+ /// This is because `--ui-paths` accepts multiple values. `clap` will continue parsing values
+ /// until another argument is reached and it knows `--ui-paths` is done parsing.
+ ///
+ /// By adding additional parameters to `--ui-paths` we can solve this issue. Consider adding
+ /// [`Arg::number_of_values(1)`] or using *only* [`ArgAction::Append`]. The following are all
+ /// valid, and `signer` is parsed as a subcommand in the first case, but a value in the second
+ /// case.
+ ///
+ /// ```text
+ /// $ program --ui-paths path1 signer
+ /// $ program --ui-paths path1 --ui-paths signer signer
+ /// ```
+ ///
+ /// # Examples
+ ///
+ /// An example with options
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("file")
+ /// .takes_value(true)
+ /// .multiple_values(true)
+ /// .short('F'))
+ /// .get_matches_from(vec![
+ /// "prog", "-F", "file1", "file2", "file3"
+ /// ]);
+ ///
+ /// assert!(m.contains_id("file"));
+ /// let files: Vec<_> = m.values_of("file").unwrap().collect();
+ /// assert_eq!(files, ["file1", "file2", "file3"]);
+ /// ```
+ ///
+ /// Although `multiple_values` has been specified, we cannot use the argument more than once.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("file")
+ /// .takes_value(true)
+ /// .multiple_values(true)
+ /// .short('F'))
+ /// .try_get_matches_from(vec![
+ /// "prog", "-F", "file1", "-F", "file2", "-F", "file3"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnexpectedMultipleUsage)
+ /// ```
+ ///
+ /// A common mistake is to define an option which allows multiple values, and a positional
+ /// argument.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("file")
+ /// .takes_value(true)
+ /// .multiple_values(true)
+ /// .short('F'))
+ /// .arg(Arg::new("word"))
+ /// .get_matches_from(vec![
+ /// "prog", "-F", "file1", "file2", "file3", "word"
+ /// ]);
+ ///
+ /// assert!(m.contains_id("file"));
+ /// let files: Vec<_> = m.values_of("file").unwrap().collect();
+ /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?!
+ /// assert!(!m.contains_id("word")); // but we clearly used word!
+ /// ```
+ ///
+ /// The problem is `clap` doesn't know when to stop parsing values for "files". This is further
+ /// compounded by if we'd said `word -F file1 file2` it would have worked fine, so it would
+ /// appear to only fail sometimes...not good!
+ ///
+ /// A solution for the example above is to limit how many values with a [maximum], or [specific]
+ /// number, or to say [`ArgAction::Append`] is ok, but multiple values is not.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("file")
+ /// .takes_value(true)
+ /// .action(ArgAction::Append)
+ /// .short('F'))
+ /// .arg(Arg::new("word"))
+ /// .get_matches_from(vec![
+ /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word"
+ /// ]);
+ ///
+ /// assert!(m.contains_id("file"));
+ /// let files: Vec<_> = m.values_of("file").unwrap().collect();
+ /// assert_eq!(files, ["file1", "file2", "file3"]);
+ /// assert!(m.contains_id("word"));
+ /// assert_eq!(m.value_of("word"), Some("word"));
+ /// ```
+ ///
+ /// As a final example, let's fix the above error and get a pretty message to the user :)
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("file")
+ /// .takes_value(true)
+ /// .action(ArgAction::Append)
+ /// .short('F'))
+ /// .arg(Arg::new("word"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "-F", "file1", "file2", "file3", "word"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
+ /// ```
+ ///
+ /// [`subcommands`]: crate::Command::subcommand()
+ /// [`Arg::number_of_values(1)`]: Arg::number_of_values()
+ /// [maximum number of values]: Arg::max_values()
+ /// [specific number of values]: Arg::number_of_values()
+ /// [maximum]: Arg::max_values()
+ /// [specific]: Arg::number_of_values()
+ #[inline]
+ #[must_use]
+ pub fn multiple_values(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::MultipleValues)
+ } else {
+ self.unset_setting(ArgSettings::MultipleValues)
+ }
+ }
+
+ /// The number of values allowed for this argument.
+ ///
+ /// For example, if you had a
+ /// `-f <file>` argument where you wanted exactly 3 'files' you would set
+ /// `.number_of_values(3)`, and this argument wouldn't be satisfied unless the user provided
+ /// 3 and only 3 values.
+ ///
+ /// **NOTE:** Does *not* require [`Arg::multiple_occurrences(true)`] to be set. Setting
+ /// [`Arg::multiple_occurrences(true)`] would allow `-f <file> <file> <file> -f <file> <file> <file>` where
+ /// as *not* setting it would only allow one occurrence of this argument.
+ ///
+ /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] and [`Arg::multiple_values(true)`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("file")
+ /// .short('f')
+ /// .number_of_values(3);
+ /// ```
+ ///
+ /// Not supplying the correct number of values is an error
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("file")
+ /// .takes_value(true)
+ /// .number_of_values(2)
+ /// .short('F'))
+ /// .try_get_matches_from(vec![
+ /// "prog", "-F", "file1"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::WrongNumberOfValues);
+ /// ```
+ /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences()
+ #[inline]
+ #[must_use]
+ pub fn number_of_values(mut self, qty: usize) -> Self {
+ self.num_vals = Some(qty);
+ self.takes_value(true).multiple_values(true)
+ }
+
+ /// The *maximum* number of values are for this argument.
+ ///
+ /// For example, if you had a
+ /// `-f <file>` argument where you wanted up to 3 'files' you would set `.max_values(3)`, and
+ /// this argument would be satisfied if the user provided, 1, 2, or 3 values.
+ ///
+ /// **NOTE:** This does *not* implicitly set [`Arg::multiple_occurrences(true)`]. This is because
+ /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single
+ /// occurrence with multiple values. For positional arguments this **does** set
+ /// [`Arg::multiple_occurrences(true)`] because there is no way to determine the difference between multiple
+ /// occurrences and multiple values.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("file")
+ /// .short('f')
+ /// .max_values(3);
+ /// ```
+ ///
+ /// Supplying less than the maximum number of values is allowed
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("file")
+ /// .takes_value(true)
+ /// .max_values(3)
+ /// .short('F'))
+ /// .try_get_matches_from(vec![
+ /// "prog", "-F", "file1", "file2"
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// let m = res.unwrap();
+ /// let files: Vec<_> = m.values_of("file").unwrap().collect();
+ /// assert_eq!(files, ["file1", "file2"]);
+ /// ```
+ ///
+ /// Supplying more than the maximum number of values is an error
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("file")
+ /// .takes_value(true)
+ /// .max_values(2)
+ /// .short('F'))
+ /// .try_get_matches_from(vec![
+ /// "prog", "-F", "file1", "file2", "file3"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
+ /// ```
+ /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences()
+ #[inline]
+ #[must_use]
+ pub fn max_values(mut self, qty: usize) -> Self {
+ self.max_vals = Some(qty);
+ self.takes_value(true).multiple_values(true)
+ }
+
+ /// The *minimum* number of values for this argument.
+ ///
+ /// For example, if you had a
+ /// `-f <file>` argument where you wanted at least 2 'files' you would set
+ /// `.min_values(2)`, and this argument would be satisfied if the user provided, 2 or more
+ /// values.
+ ///
+ /// **NOTE:** This does not implicitly set [`Arg::multiple_occurrences(true)`]. This is because
+ /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single
+ /// occurrence with multiple values. For positional arguments this **does** set
+ /// [`Arg::multiple_occurrences(true)`] because there is no way to determine the difference between multiple
+ /// occurrences and multiple values.
+ ///
+ /// **NOTE:** Passing a non-zero value is not the same as specifying [`Arg::required(true)`].
+ /// This is due to min and max validation only being performed for present arguments,
+ /// marking them as required will thus perform validation and a min value of 1
+ /// is unnecessary, ignored if not required.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("file")
+ /// .short('f')
+ /// .min_values(3);
+ /// ```
+ ///
+ /// Supplying more than the minimum number of values is allowed
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("file")
+ /// .takes_value(true)
+ /// .min_values(2)
+ /// .short('F'))
+ /// .try_get_matches_from(vec![
+ /// "prog", "-F", "file1", "file2", "file3"
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// let m = res.unwrap();
+ /// let files: Vec<_> = m.values_of("file").unwrap().collect();
+ /// assert_eq!(files, ["file1", "file2", "file3"]);
+ /// ```
+ ///
+ /// Supplying less than the minimum number of values is an error
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("file")
+ /// .takes_value(true)
+ /// .min_values(2)
+ /// .short('F'))
+ /// .try_get_matches_from(vec![
+ /// "prog", "-F", "file1"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::TooFewValues);
+ /// ```
+ /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences()
+ /// [`Arg::required(true)`]: Arg::required()
+ #[inline]
+ #[must_use]
+ pub fn min_values(mut self, qty: usize) -> Self {
+ self.min_vals = Some(qty);
+ self.takes_value(true).multiple_values(true)
+ }
+
+ /// Placeholder for the argument's value in the help message / usage.
+ ///
+ /// This name is cosmetic only; the name is **not** used to access arguments.
+ /// This setting can be very helpful when describing the type of input the user should be
+ /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to
+ /// use all capital letters for the value name.
+ ///
+ /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("cfg")
+ /// .long("config")
+ /// .value_name("FILE")
+ /// # ;
+ /// ```
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("config")
+ /// .long("config")
+ /// .value_name("FILE")
+ /// .help("Some help text"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ /// Running the above program produces the following output
+ ///
+ /// ```text
+ /// valnames
+ ///
+ /// USAGE:
+ /// valnames [OPTIONS]
+ ///
+ /// OPTIONS:
+ /// --config <FILE> Some help text
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ /// [option]: Arg::takes_value()
+ /// [positional]: Arg::index()
+ /// [`Arg::takes_value(true)`]: Arg::takes_value()
+ #[inline]
+ #[must_use]
+ pub fn value_name(self, name: &'help str) -> Self {
+ self.value_names(&[name])
+ }
+
+ /// Placeholders for the argument's values in the help message / usage.
+ ///
+ /// These names are cosmetic only, used for help and usage strings only. The names are **not**
+ /// used to access arguments. The values of the arguments are accessed in numeric order (i.e.
+ /// if you specify two names `one` and `two` `one` will be the first matched value, `two` will
+ /// be the second).
+ ///
+ /// This setting can be very helpful when describing the type of input the user should be
+ /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to
+ /// use all capital letters for the value name.
+ ///
+ /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or
+ /// multiple value names in order to not throw off the help text alignment of all options.
+ ///
+ /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] and [`Arg::multiple_values(true)`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("speed")
+ /// .short('s')
+ /// .value_names(&["fast", "slow"]);
+ /// ```
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("io")
+ /// .long("io-files")
+ /// .value_names(&["INFILE", "OUTFILE"]))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// Running the above program produces the following output
+ ///
+ /// ```text
+ /// valnames
+ ///
+ /// USAGE:
+ /// valnames [OPTIONS]
+ ///
+ /// OPTIONS:
+ /// -h, --help Print help information
+ /// --io-files <INFILE> <OUTFILE> Some help text
+ /// -V, --version Print version information
+ /// ```
+ /// [`Arg::next_line_help(true)`]: Arg::next_line_help()
+ /// [`Arg::number_of_values`]: Arg::number_of_values()
+ /// [`Arg::takes_value(true)`]: Arg::takes_value()
+ /// [`Arg::multiple_values(true)`]: Arg::multiple_values()
+ #[must_use]
+ pub fn value_names(mut self, names: &[&'help str]) -> Self {
+ self.val_names = names.to_vec();
+ self.takes_value(true)
+ }
+
+ /// Provide the shell a hint about how to complete this argument.
+ ///
+ /// See [`ValueHint`][crate::ValueHint] for more information.
+ ///
+ /// **NOTE:** implicitly sets [`Arg::takes_value(true)`].
+ ///
+ /// For example, to take a username as argument:
+ ///
+ /// ```
+ /// # use clap::{Arg, ValueHint};
+ /// Arg::new("user")
+ /// .short('u')
+ /// .long("user")
+ /// .value_hint(ValueHint::Username);
+ /// ```
+ ///
+ /// To take a full command line and its arguments (for example, when writing a command wrapper):
+ ///
+ /// ```
+ /// # use clap::{Command, Arg, ValueHint};
+ /// Command::new("prog")
+ /// .trailing_var_arg(true)
+ /// .arg(
+ /// Arg::new("command")
+ /// .takes_value(true)
+ /// .multiple_values(true)
+ /// .value_hint(ValueHint::CommandWithArguments)
+ /// );
+ /// ```
+ #[must_use]
+ pub fn value_hint(mut self, value_hint: ValueHint) -> Self {
+ self.value_hint = Some(value_hint);
+ self.takes_value(true)
+ }
+
+ /// Deprecated, replaced with [`Arg::value_parser(...)`]
+ ///
+ /// Derive: replace `#[clap(validator = ...)]` with `#[clap(value_parser = ...)]`
+ ///
+ /// Builder: replace `arg.validator(...)` with `arg.value_parser(...)` and `matches.value_of` with
+ /// `matches.get_one::<T>` or `matches.values_of` with `matches.get_many::<T>`
+ #[inline]
+ #[must_use]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `Arg::value_parser(...)`
+
+Derive: replace `#[clap(validator = <fn>)]` with `#[clap(value_parser = <fn>)]`
+
+Builder: replace `arg.validator(<fn>)` with `arg.value_parser(<fn>)` and `matches.value_of` with
+`matches.get_one::<T>` or `matches.values_of` with `matches.get_many::<T>`
+"
+ )
+ )]
+ pub fn validator<F, O, E>(mut self, mut f: F) -> Self
+ where
+ F: FnMut(&str) -> Result<O, E> + Send + 'help,
+ E: Into<Box<dyn Error + Send + Sync + 'static>>,
+ {
+ self.validator = Some(Arc::new(Mutex::new(move |s: &str| {
+ f(s).map(|_| ()).map_err(|e| e.into())
+ })));
+ self
+ }
+
+ /// Deprecated, replaced with [`Arg::value_parser(...)`]
+ #[must_use]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `Arg::value_parser(...)`
+
+Derive: replace `#[clap(validator = <fn>)]` with `#[clap(value_parser = <TypedValueParser>)]`
+
+Builder: replace `arg.validator(<fn>)` with `arg.value_parser(<TypedValueParser>)` and `matches.value_of_os` with
+`matches.get_one::<T>` or `matches.values_of_os` with `matches.get_many::<T>`
+"
+ )
+ )]
+ pub fn validator_os<F, O, E>(mut self, mut f: F) -> Self
+ where
+ F: FnMut(&OsStr) -> Result<O, E> + Send + 'help,
+ E: Into<Box<dyn Error + Send + Sync + 'static>>,
+ {
+ self.validator_os = Some(Arc::new(Mutex::new(move |s: &OsStr| {
+ f(s).map(|_| ()).map_err(|e| e.into())
+ })));
+ self
+ }
+
+ /// Deprecated in [Issue #3743](https://github.com/clap-rs/clap/issues/3743), replaced with [`Arg::value_parser(...)`]
+ ///
+ /// Derive: replace `#[clap(validator_regex = ...)]` with `#[clap(value_parser = |s: &str| regex.is_match(s).then(|| s.to_owned()).ok_or_else(|| ...))]`
+ ///
+ /// Builder: replace `arg.validator_regex(...)` with `arg.value_parser(|s: &str| regex.is_match(s).then(|| s.to_owned()).ok_or_else(|| ...))`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Deprecated in Issue #3743; replaced with `Arg::value_parser(...)`
+
+Derive: replace `#[clap(validator_regex = ...)]` with `#[clap(value_parser = |s: &str| regex.is_match(s).then(|| s.to_owned()).ok_or_else(|| ...))]`
+
+Builder: replace `arg.validator_regex(...)` with `arg.value_parser(|s: &str| regex.is_match(s).then(|| s.to_owned()).ok_or_else(|| ...))`
+"
+ )
+ )]
+ #[cfg(feature = "regex")]
+ #[must_use]
+ pub fn validator_regex(
+ self,
+ regex: impl Into<RegexRef<'help>>,
+ err_message: &'help str,
+ ) -> Self {
+ let regex = regex.into();
+ self.validator(move |s: &str| {
+ if regex.is_match(s) {
+ Ok(())
+ } else {
+ Err(err_message)
+ }
+ })
+ }
+
+ /// Deprecated, replaced with [`Arg::value_parser(PossibleValuesParser::new(...))`]
+ ///
+ /// Derive: replace `#[clap(possible_value = <1>, possible_value = <2>, ...)]` with `#[clap(value_parser = [<1>, <2>])]`.
+ /// If the field is not a `String`, instead do `#[clap(value_parser = PossibleValueParser::new([<1>, <2>]).map(T::from_str))]`
+ ///
+ /// Builder: replace `arg.possible_value(<1>).possible_value(<2>) with `arg.value_parser([<1>, <2>])`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `Arg::value_parser(PossibleValuesParser::new(...)).takes_value(true)`
+
+Derive: replace `#[clap(possible_value = <1>, possible_value = <2>, ...)]` with `#[clap(value_parser = [<1>, <2>])]`.
+If the field is not a `String`, instead do `#[clap(value_parser = PossibleValueParser::new([<1>, <2>]).map(T::from_str))]`
+
+Builder: replace `arg.possible_value(<1>).possible_value(<2>) with `arg.value_parser([<1>, <2>])`
+"
+ )
+ )]
+ #[must_use]
+ pub fn possible_value<T>(mut self, value: T) -> Self
+ where
+ T: Into<PossibleValue<'help>>,
+ {
+ self.possible_vals.push(value.into());
+ self.takes_value(true)
+ }
+
+ /// Deprecated, replaced with [`Arg::value_parser(PossibleValuesParser::new(...))`]
+ ///
+ /// Derive: replace `#[clap(possible_values = [<1>, <2>])]` with `#[clap(value_parser = [<1>, <2>])]`.
+ /// If the field is not a `String`, instead do `#[clap(value_parser = PossibleValueParser::new([<1>, <2>]).map(T::from_str))]`
+ ///
+ /// Builder: replace `arg.possible_values([<1>, <2>) with `arg.value_parser([<1>, <2>])`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `Arg::value_parser(PossibleValuesParser::new(...)).takes_value(true)`
+
+Derive: replace `#[clap(possible_values = [<1>, <2>])]` with `#[clap(value_parser = [<1>, <2>])]`.
+If the field is not a `String`, instead do `#[clap(value_parser = PossibleValueParser::new([<1>, <2>]).map(T::from_str))]`
+
+Builder: replace `arg.possible_values([<1>, <2>) with `arg.value_parser([<1>, <2>])`
+"
+ )
+ )]
+ #[must_use]
+ pub fn possible_values<I, T>(mut self, values: I) -> Self
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<PossibleValue<'help>>,
+ {
+ self.possible_vals
+ .extend(values.into_iter().map(|value| value.into()));
+ self.takes_value(true)
+ }
+
+ /// Match values against [`Arg::possible_values`] without matching case.
+ ///
+ /// When other arguments are conditionally required based on the
+ /// value of a case-insensitive argument, the equality check done
+ /// by [`Arg::required_if_eq`], [`Arg::required_if_eq_any`], or
+ /// [`Arg::required_if_eq_all`] is case-insensitive.
+ ///
+ ///
+ /// **NOTE:** Setting this requires [`Arg::takes_value`]
+ ///
+ /// **NOTE:** To do unicode case folding, enable the `unicode` feature flag.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("pv")
+ /// .arg(Arg::new("option")
+ /// .long("option")
+ /// .takes_value(true)
+ /// .ignore_case(true)
+ /// .value_parser(["test123"]))
+ /// .get_matches_from(vec![
+ /// "pv", "--option", "TeSt123",
+ /// ]);
+ ///
+ /// assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123"));
+ /// ```
+ ///
+ /// This setting also works when multiple values can be defined:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("pv")
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .long("option")
+ /// .takes_value(true)
+ /// .ignore_case(true)
+ /// .multiple_values(true)
+ /// .value_parser(["test123", "test321"]))
+ /// .get_matches_from(vec![
+ /// "pv", "--option", "TeSt123", "teST123", "tESt321"
+ /// ]);
+ ///
+ /// let matched_vals = m.values_of("option").unwrap().collect::<Vec<_>>();
+ /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]);
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn ignore_case(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::IgnoreCase)
+ } else {
+ self.unset_setting(ArgSettings::IgnoreCase)
+ }
+ }
+
+ /// Allows values which start with a leading hyphen (`-`)
+ ///
+ /// **NOTE:** Setting this requires [`Arg::takes_value`]
+ ///
+ /// **WARNING**: Take caution when using this setting combined with
+ /// [`Arg::multiple_values`], as this becomes ambiguous `$ prog --arg -- -- val`. All
+ /// three `--, --, val` will be values when the user may have thought the second `--` would
+ /// constitute the normal, "Only positional args follow" idiom. To fix this, consider using
+ /// [`Arg::multiple_occurrences`] which only allows a single value at a time.
+ ///
+ /// **WARNING**: When building your CLIs, consider the effects of allowing leading hyphens and
+ /// the user passing in a value that matches a valid short. For example, `prog -opt -F` where
+ /// `-F` is supposed to be a value, yet `-F` is *also* a valid short for another arg.
+ /// Care should be taken when designing these args. This is compounded by the ability to "stack"
+ /// short args. I.e. if `-val` is supposed to be a value, but `-v`, `-a`, and `-l` are all valid
+ /// shorts.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("pat")
+ /// .takes_value(true)
+ /// .allow_hyphen_values(true)
+ /// .long("pattern"))
+ /// .get_matches_from(vec![
+ /// "prog", "--pattern", "-file"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("pat"), Some("-file"));
+ /// ```
+ ///
+ /// Not setting `Arg::allow_hyphen_values(true)` and supplying a value which starts with a
+ /// hyphen is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("pat")
+ /// .takes_value(true)
+ /// .long("pattern"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--pattern", "-file"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
+ /// ```
+ /// [`Arg::number_of_values(1)`]: Arg::number_of_values()
+ #[inline]
+ #[must_use]
+ pub fn allow_hyphen_values(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::AllowHyphenValues)
+ } else {
+ self.unset_setting(ArgSettings::AllowHyphenValues)
+ }
+ }
+
+ /// Deprecated, replaced with [`value_parser`][Arg::value_parser]
+ ///
+ /// Derive: replace `#[clap(allow_invalid_utf8 = true)]` with `#[clap(action)]` (which opts-in to the
+ /// new clap v4 behavior which gets the type via `value_parser!`)
+ ///
+ /// Builder: replace `arg.allow_invalid_utf8(true)` with `arg.value_parser(value_parser!(T))` where
+ /// `T` is the type of interest, like `OsString` or `PathBuf`, and `matches.value_of_os` with
+ /// `matches.get_one::<T>` or `matches.values_of_os` with `matches.get_many::<T>`
+ #[inline]
+ #[must_use]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `value_parser`
+
+Derive: replace `#[clap(allow_invalid_utf8 = true)]` with `#[clap(action)]` (which opts-in to the
+new clap v4 behavior which gets the type via `value_parser!`)
+
+Builder: replace `arg.allow_invalid_utf8(true)` with `arg.value_parser(value_parser!(T))` where
+`T` is the type of interest, like `OsString` or `PathBuf`, and `matches.value_of_os` with
+`matches.get_one::<T>` or `matches.values_of_os` with `matches.get_many::<T>`
+"
+ )
+ )]
+ pub fn allow_invalid_utf8(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::AllowInvalidUtf8)
+ } else {
+ self.unset_setting(ArgSettings::AllowInvalidUtf8)
+ }
+ }
+
+ /// Deprecated, replaced with [`Arg::value_parser(NonEmptyStringValueParser::new())`]
+ ///
+ /// Derive: replace `#[clap(forbid_empty_values = true)]` with `#[clap(value_parser = NonEmptyStringValueParser::new())]`
+ ///
+ /// Builder: replace `arg.forbid_empty_values(true)` with `arg.value_parser(NonEmptyStringValueParser::new())`
+ #[inline]
+ #[must_use]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `Arg::value_parser(NonEmptyStringValueParser::new())`
+
+Derive: replace `#[clap(forbid_empty_values = true)]` with `#[clap(value_parser = NonEmptyStringValueParser::new())]`
+
+Builder: replace `arg.forbid_empty_values(true)` with `arg.value_parser(NonEmptyStringValueParser::new())`
+"
+ )
+ )]
+ pub fn forbid_empty_values(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::ForbidEmptyValues)
+ } else {
+ self.unset_setting(ArgSettings::ForbidEmptyValues)
+ }
+ }
+
+ /// Requires that options use the `--option=val` syntax
+ ///
+ /// i.e. an equals between the option and associated value.
+ ///
+ /// **NOTE:** Setting this requires [`Arg::takes_value`]
+ ///
+ /// # Examples
+ ///
+ /// Setting `require_equals` requires that the option have an equals sign between
+ /// it and the associated value.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .require_equals(true)
+ /// .long("config"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config=file.conf"
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// ```
+ ///
+ /// Setting `require_equals` and *not* supplying the equals will cause an
+ /// error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .require_equals(true)
+ /// .long("config"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "file.conf"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals);
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn require_equals(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::RequireEquals)
+ } else {
+ self.unset_setting(ArgSettings::RequireEquals)
+ }
+ }
+
+ /// Specifies that an argument should allow grouping of multiple values via a
+ /// delimiter.
+ ///
+ /// i.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`,
+ /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the
+ /// value delimiter for all arguments that accept values (options and positional arguments)
+ ///
+ /// **NOTE:** When this setting is used, it will default [`Arg::value_delimiter`]
+ /// to the comma `,`.
+ ///
+ /// **NOTE:** Implicitly sets [`Arg::takes_value`]
+ ///
+ /// # Examples
+ ///
+ /// The following example shows the default behavior.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let delims = Command::new("prog")
+ /// .arg(Arg::new("option")
+ /// .long("option")
+ /// .use_value_delimiter(true)
+ /// .takes_value(true))
+ /// .get_matches_from(vec![
+ /// "prog", "--option=val1,val2,val3",
+ /// ]);
+ ///
+ /// assert!(delims.contains_id("option"));
+ /// assert_eq!(delims.values_of("option").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
+ /// ```
+ /// The next example shows the difference when turning delimiters off. This is the default
+ /// behavior
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let nodelims = Command::new("prog")
+ /// .arg(Arg::new("option")
+ /// .long("option")
+ /// .takes_value(true))
+ /// .get_matches_from(vec![
+ /// "prog", "--option=val1,val2,val3",
+ /// ]);
+ ///
+ /// assert!(nodelims.contains_id("option"));
+ /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3");
+ /// ```
+ /// [`Arg::value_delimiter`]: Arg::value_delimiter()
+ #[inline]
+ #[must_use]
+ pub fn use_value_delimiter(mut self, yes: bool) -> Self {
+ if yes {
+ if self.val_delim.is_none() {
+ self.val_delim = Some(',');
+ }
+ self.takes_value(true)
+ .setting(ArgSettings::UseValueDelimiter)
+ } else {
+ self.val_delim = None;
+ self.unset_setting(ArgSettings::UseValueDelimiter)
+ }
+ }
+
+ /// Deprecated, replaced with [`Arg::use_value_delimiter`]
+ ///
+ /// Derive: replace `#[clap(use_delimiter = true)]` with `#[clap(use_value_delimiter = true)]`
+ ///
+ /// Builder: replace `arg.use_delimiter(true)` with `arg.use_value_delimiter(true)`
+ #[inline]
+ #[must_use]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::use_value_delimiter`
+
+Derive: replace `#[clap(use_delimiter = true)]` with `#[clap(use_value_delimiter = true)]`
+
+Builder: replace `arg.use_delimiter(true)` with `arg.use_value_delimiter(true)`
+"
+ )
+ )]
+ pub fn use_delimiter(self, yes: bool) -> Self {
+ self.use_value_delimiter(yes)
+ }
+
+ /// Separator between the arguments values, defaults to `,` (comma).
+ ///
+ /// **NOTE:** implicitly sets [`Arg::use_value_delimiter(true)`]
+ ///
+ /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("config")
+ /// .short('c')
+ /// .long("config")
+ /// .value_delimiter(';'))
+ /// .get_matches_from(vec![
+ /// "prog", "--config=val1;val2;val3"
+ /// ]);
+ ///
+ /// assert_eq!(m.values_of("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"])
+ /// ```
+ /// [`Arg::use_value_delimiter(true)`]: Arg::use_value_delimiter()
+ /// [`Arg::takes_value(true)`]: Arg::takes_value()
+ #[inline]
+ #[must_use]
+ pub fn value_delimiter(mut self, d: char) -> Self {
+ self.val_delim = Some(d);
+ self.takes_value(true).use_value_delimiter(true)
+ }
+
+ /// Specifies that *multiple values* may only be set using the delimiter.
+ ///
+ /// This means if an option is encountered, and no delimiter is found, it is assumed that no
+ /// additional values for that option follow. This is unlike the default, where it is generally
+ /// assumed that more values will follow regardless of whether or not a delimiter is used.
+ ///
+ /// **NOTE:** The default is `false`.
+ ///
+ /// **NOTE:** Setting this requires [`Arg::use_value_delimiter`] and
+ /// [`Arg::takes_value`]
+ ///
+ /// **NOTE:** It's a good idea to inform the user that use of a delimiter is required, either
+ /// through help text or other means.
+ ///
+ /// # Examples
+ ///
+ /// These examples demonstrate what happens when `require_delimiter(true)` is used. Notice
+ /// everything works in this first example, as we use a delimiter, as expected.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let delims = Command::new("prog")
+ /// .arg(Arg::new("opt")
+ /// .short('o')
+ /// .takes_value(true)
+ /// .use_value_delimiter(true)
+ /// .require_delimiter(true)
+ /// .multiple_values(true))
+ /// .get_matches_from(vec![
+ /// "prog", "-o", "val1,val2,val3",
+ /// ]);
+ ///
+ /// assert!(delims.contains_id("opt"));
+ /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
+ /// ```
+ ///
+ /// In this next example, we will *not* use a delimiter. Notice it's now an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("opt")
+ /// .short('o')
+ /// .takes_value(true)
+ /// .use_value_delimiter(true)
+ /// .require_delimiter(true))
+ /// .try_get_matches_from(vec![
+ /// "prog", "-o", "val1", "val2", "val3",
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// let err = res.unwrap_err();
+ /// assert_eq!(err.kind(), ErrorKind::UnknownArgument);
+ /// ```
+ ///
+ /// What's happening is `-o` is getting `val1`, and because delimiters are required yet none
+ /// were present, it stops parsing `-o`. At this point it reaches `val2` and because no
+ /// positional arguments have been defined, it's an error of an unexpected argument.
+ ///
+ /// In this final example, we contrast the above with `clap`'s default behavior where the above
+ /// is *not* an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let delims = Command::new("prog")
+ /// .arg(Arg::new("opt")
+ /// .short('o')
+ /// .takes_value(true)
+ /// .multiple_values(true))
+ /// .get_matches_from(vec![
+ /// "prog", "-o", "val1", "val2", "val3",
+ /// ]);
+ ///
+ /// assert!(delims.contains_id("opt"));
+ /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn require_value_delimiter(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::RequireDelimiter)
+ } else {
+ self.unset_setting(ArgSettings::RequireDelimiter)
+ }
+ }
+
+ /// Deprecated, replaced with [`Arg::require_value_delimiter`]
+ ///
+ /// Derive: replace `#[clap(require_delimiter = true)]` with `#[clap(require_value_delimiter = true)]`
+ ///
+ /// Builder: replace `arg.require_delimiter(true)` with `arg.require_value_delimiter(true)`
+ #[inline]
+ #[must_use]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::require_value_delimiter`
+
+Derive: replace `#[clap(require_delimiter = true)]` with `#[clap(require_value_delimiter = true)]`
+
+Builder: replace `arg.require_delimiter(true)` with `arg.require_value_delimiter(true)`
+"
+ )
+ )]
+ pub fn require_delimiter(self, yes: bool) -> Self {
+ self.require_value_delimiter(yes)
+ }
+
+ /// Sentinel to **stop** parsing multiple values of a give argument.
+ ///
+ /// By default when
+ /// one sets [`multiple_values(true)`] on an argument, clap will continue parsing values for that
+ /// argument until it reaches another valid argument, or one of the other more specific settings
+ /// for multiple values is used (such as [`min_values`], [`max_values`] or
+ /// [`number_of_values`]).
+ ///
+ /// **NOTE:** This setting only applies to [options] and [positional arguments]
+ ///
+ /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one
+ /// of the values
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("vals")
+ /// .takes_value(true)
+ /// .multiple_values(true)
+ /// .value_terminator(";")
+ /// # ;
+ /// ```
+ ///
+ /// The following example uses two arguments, a sequence of commands, and the location in which
+ /// to perform them
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cmds")
+ /// .takes_value(true)
+ /// .multiple_values(true)
+ /// .allow_hyphen_values(true)
+ /// .value_terminator(";"))
+ /// .arg(Arg::new("location"))
+ /// .get_matches_from(vec![
+ /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap"
+ /// ]);
+ /// let cmds: Vec<_> = m.values_of("cmds").unwrap().collect();
+ /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]);
+ /// assert_eq!(m.value_of("location"), Some("/home/clap"));
+ /// ```
+ /// [options]: Arg::takes_value()
+ /// [positional arguments]: Arg::index()
+ /// [`multiple_values(true)`]: Arg::multiple_values()
+ /// [`min_values`]: Arg::min_values()
+ /// [`number_of_values`]: Arg::number_of_values()
+ /// [`max_values`]: Arg::max_values()
+ #[inline]
+ #[must_use]
+ pub fn value_terminator(mut self, term: &'help str) -> Self {
+ self.terminator = Some(term);
+ self.takes_value(true)
+ }
+
+ /// Consume all following arguments.
+ ///
+ /// Do not be parse them individually, but rather pass them in entirety.
+ ///
+ /// It is worth noting that setting this requires all values to come after a `--` to indicate
+ /// they should all be captured. For example:
+ ///
+ /// ```text
+ /// --foo something -- -v -v -v -b -b -b --baz -q -u -x
+ /// ```
+ ///
+ /// Will result in everything after `--` to be considered one raw argument. This behavior
+ /// may not be exactly what you are expecting and using [`crate::Command::trailing_var_arg`]
+ /// may be more appropriate.
+ ///
+ /// **NOTE:** Implicitly sets [`Arg::takes_value(true)`] [`Arg::multiple_values(true)`],
+ /// [`Arg::allow_hyphen_values(true)`], and [`Arg::last(true)`] when set to `true`.
+ ///
+ /// [`Arg::takes_value(true)`]: Arg::takes_value()
+ /// [`Arg::multiple_values(true)`]: Arg::multiple_values()
+ /// [`Arg::allow_hyphen_values(true)`]: Arg::allow_hyphen_values()
+ /// [`Arg::last(true)`]: Arg::last()
+ #[inline]
+ #[must_use]
+ pub fn raw(self, yes: bool) -> Self {
+ self.takes_value(yes)
+ .multiple_values(yes)
+ .allow_hyphen_values(yes)
+ .last(yes)
+ }
+
+ /// Value for the argument when not present.
+ ///
+ /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`]
+ /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified.
+ ///
+ /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::contains_id`] will
+ /// still return `true`. If you wish to determine whether the argument was used at runtime or
+ /// not, consider [`ArgMatches::value_source`][crate::ArgMatches::value_source].
+ ///
+ /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly
+ /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg
+ /// at runtime. `Arg::default_value_if` however only takes effect when the user has not provided
+ /// a value at runtime **and** these other conditions are met as well. If you have set
+ /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide this arg
+ /// at runtime, nor were the conditions met for `Arg::default_value_if`, the `Arg::default_value`
+ /// will be applied.
+ ///
+ /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
+ ///
+ /// # Examples
+ ///
+ /// First we use the default value without providing any value at runtime.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ValueSource};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("opt")
+ /// .long("myopt")
+ /// .default_value("myval"))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("opt"), Some("myval"));
+ /// assert!(m.contains_id("opt"));
+ /// assert_eq!(m.value_source("opt"), Some(ValueSource::DefaultValue));
+ /// ```
+ ///
+ /// Next we provide a value at runtime to override the default.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ValueSource};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("opt")
+ /// .long("myopt")
+ /// .default_value("myval"))
+ /// .get_matches_from(vec![
+ /// "prog", "--myopt=non_default"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("opt"), Some("non_default"));
+ /// assert!(m.contains_id("opt"));
+ /// assert_eq!(m.value_source("opt"), Some(ValueSource::CommandLine));
+ /// ```
+ /// [`ArgMatches::occurrences_of`]: crate::ArgMatches::occurrences_of()
+ /// [`ArgMatches::value_of`]: crate::ArgMatches::value_of()
+ /// [`Arg::takes_value(true)`]: Arg::takes_value()
+ /// [`ArgMatches::contains_id`]: crate::ArgMatches::contains_id()
+ /// [`Arg::default_value_if`]: Arg::default_value_if()
+ #[inline]
+ #[must_use]
+ pub fn default_value(self, val: &'help str) -> Self {
+ self.default_values_os(&[OsStr::new(val)])
+ }
+
+ /// Value for the argument when not present.
+ ///
+ /// See [`Arg::default_value`].
+ ///
+ /// [`Arg::default_value`]: Arg::default_value()
+ /// [`OsStr`]: std::ffi::OsStr
+ #[inline]
+ #[must_use]
+ pub fn default_value_os(self, val: &'help OsStr) -> Self {
+ self.default_values_os(&[val])
+ }
+
+ /// Value for the argument when not present.
+ ///
+ /// See [`Arg::default_value`].
+ ///
+ /// [`Arg::default_value`]: Arg::default_value()
+ #[inline]
+ #[must_use]
+ pub fn default_values(self, vals: &[&'help str]) -> Self {
+ let vals_vec: Vec<_> = vals.iter().map(|val| OsStr::new(*val)).collect();
+ self.default_values_os(&vals_vec[..])
+ }
+
+ /// Value for the argument when not present.
+ ///
+ /// See [`Arg::default_values`].
+ ///
+ /// [`Arg::default_values`]: Arg::default_values()
+ /// [`OsStr`]: std::ffi::OsStr
+ #[inline]
+ #[must_use]
+ pub fn default_values_os(mut self, vals: &[&'help OsStr]) -> Self {
+ self.default_vals = vals.to_vec();
+ self.takes_value(true)
+ }
+
+ /// Value for the argument when the flag is present but no value is specified.
+ ///
+ /// This configuration option is often used to give the user a shortcut and allow them to
+ /// efficiently specify an option argument without requiring an explicitly value. The `--color`
+ /// argument is a common example. By, supplying an default, such as `default_missing_value("always")`,
+ /// the user can quickly just add `--color` to the command line to produce the desired color output.
+ ///
+ /// **NOTE:** using this configuration option requires the use of the `.min_values(0)` and the
+ /// `.require_equals(true)` configuration option. These are required in order to unambiguously
+ /// determine what, if any, value was supplied for the argument.
+ ///
+ /// # Examples
+ ///
+ /// For POSIX style `--color`:
+ /// ```rust
+ /// # use clap::{Command, Arg, ValueSource};
+ /// fn cli() -> Command<'static> {
+ /// Command::new("prog")
+ /// .arg(Arg::new("color").long("color")
+ /// .value_name("WHEN")
+ /// .value_parser(["always", "auto", "never"])
+ /// .default_value("auto")
+ /// .min_values(0)
+ /// .require_equals(true)
+ /// .default_missing_value("always")
+ /// .help("Specify WHEN to colorize output.")
+ /// )
+ /// }
+ ///
+ /// // first, we'll provide no arguments
+ /// let m = cli().get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ /// assert_eq!(m.value_of("color"), Some("auto"));
+ /// assert_eq!(m.value_source("color"), Some(ValueSource::DefaultValue));
+ ///
+ /// // next, we'll provide a runtime value to override the default (as usually done).
+ /// let m = cli().get_matches_from(vec![
+ /// "prog", "--color=never"
+ /// ]);
+ /// assert_eq!(m.value_of("color"), Some("never"));
+ /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));
+ ///
+ /// // finally, we will use the shortcut and only provide the argument without a value.
+ /// let m = cli().get_matches_from(vec![
+ /// "prog", "--color"
+ /// ]);
+ /// assert_eq!(m.value_of("color"), Some("always"));
+ /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));
+ /// ```
+ ///
+ /// For bool literals:
+ /// ```rust
+ /// # use clap::{Command, Arg, ValueSource, value_parser};
+ /// fn cli() -> Command<'static> {
+ /// Command::new("prog")
+ /// .arg(Arg::new("create").long("create")
+ /// .value_name("BOOL")
+ /// .value_parser(value_parser!(bool))
+ /// .min_values(0)
+ /// .require_equals(true)
+ /// .default_missing_value("true")
+ /// )
+ /// }
+ ///
+ /// // first, we'll provide no arguments
+ /// let m = cli().get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ /// assert_eq!(m.get_one::<bool>("create").copied(), None);
+ ///
+ /// // next, we'll provide a runtime value to override the default (as usually done).
+ /// let m = cli().get_matches_from(vec![
+ /// "prog", "--create=false"
+ /// ]);
+ /// assert_eq!(m.get_one::<bool>("create").copied(), Some(false));
+ /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));
+ ///
+ /// // finally, we will use the shortcut and only provide the argument without a value.
+ /// let m = cli().get_matches_from(vec![
+ /// "prog", "--create"
+ /// ]);
+ /// assert_eq!(m.get_one::<bool>("create").copied(), Some(true));
+ /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));
+ /// ```
+ ///
+ /// [`ArgMatches::value_of`]: ArgMatches::value_of()
+ /// [`Arg::takes_value(true)`]: Arg::takes_value()
+ /// [`Arg::default_value`]: Arg::default_value()
+ #[inline]
+ #[must_use]
+ pub fn default_missing_value(self, val: &'help str) -> Self {
+ self.default_missing_values_os(&[OsStr::new(val)])
+ }
+
+ /// Value for the argument when the flag is present but no value is specified.
+ ///
+ /// See [`Arg::default_missing_value`].
+ ///
+ /// [`Arg::default_missing_value`]: Arg::default_missing_value()
+ /// [`OsStr`]: std::ffi::OsStr
+ #[inline]
+ #[must_use]
+ pub fn default_missing_value_os(self, val: &'help OsStr) -> Self {
+ self.default_missing_values_os(&[val])
+ }
+
+ /// Value for the argument when the flag is present but no value is specified.
+ ///
+ /// See [`Arg::default_missing_value`].
+ ///
+ /// [`Arg::default_missing_value`]: Arg::default_missing_value()
+ #[inline]
+ #[must_use]
+ pub fn default_missing_values(self, vals: &[&'help str]) -> Self {
+ let vals_vec: Vec<_> = vals.iter().map(|val| OsStr::new(*val)).collect();
+ self.default_missing_values_os(&vals_vec[..])
+ }
+
+ /// Value for the argument when the flag is present but no value is specified.
+ ///
+ /// See [`Arg::default_missing_values`].
+ ///
+ /// [`Arg::default_missing_values`]: Arg::default_missing_values()
+ /// [`OsStr`]: std::ffi::OsStr
+ #[inline]
+ #[must_use]
+ pub fn default_missing_values_os(mut self, vals: &[&'help OsStr]) -> Self {
+ self.default_missing_vals = vals.to_vec();
+ self.takes_value(true)
+ }
+
+ /// Read from `name` environment variable when argument is not present.
+ ///
+ /// If it is not present in the environment, then default
+ /// rules will apply.
+ ///
+ /// If user sets the argument in the environment:
+ /// - When [`Arg::takes_value(true)`] is not set, the flag is considered raised.
+ /// - When [`Arg::takes_value(true)`] is set, [`ArgMatches::value_of`] will
+ /// return value of the environment variable.
+ ///
+ /// If user doesn't set the argument in the environment:
+ /// - When [`Arg::takes_value(true)`] is not set, the flag is considered off.
+ /// - When [`Arg::takes_value(true)`] is set, [`ArgMatches::value_of`] will
+ /// return the default specified.
+ ///
+ /// # Examples
+ ///
+ /// In this example, we show the variable coming from the environment:
+ ///
+ /// ```rust
+ /// # use std::env;
+ /// # use clap::{Command, Arg};
+ ///
+ /// env::set_var("MY_FLAG", "env");
+ ///
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .env("MY_FLAG")
+ /// .takes_value(true))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("flag"), Some("env"));
+ /// ```
+ ///
+ /// In this example, because [`Arg::takes_value(false)`] (by default),
+ /// `prog` is a flag that accepts an optional, case-insensitive boolean literal.
+ /// A `false` literal is `n`, `no`, `f`, `false`, `off` or `0`.
+ /// An absent environment variable will also be considered as `false`.
+ /// Anything else will considered as `true`.
+ ///
+ /// ```rust
+ /// # use std::env;
+ /// # use clap::{Command, Arg};
+ ///
+ /// env::set_var("TRUE_FLAG", "true");
+ /// env::set_var("FALSE_FLAG", "0");
+ ///
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("true_flag")
+ /// .long("true_flag")
+ /// .env("TRUE_FLAG"))
+ /// .arg(Arg::new("false_flag")
+ /// .long("false_flag")
+ /// .env("FALSE_FLAG"))
+ /// .arg(Arg::new("absent_flag")
+ /// .long("absent_flag")
+ /// .env("ABSENT_FLAG"))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert!(m.is_present("true_flag"));
+ /// assert_eq!(m.value_of("true_flag"), None);
+ /// assert!(!m.is_present("false_flag"));
+ /// assert!(!m.is_present("absent_flag"));
+ /// ```
+ ///
+ /// In this example, we show the variable coming from an option on the CLI:
+ ///
+ /// ```rust
+ /// # use std::env;
+ /// # use clap::{Command, Arg};
+ ///
+ /// env::set_var("MY_FLAG", "env");
+ ///
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .env("MY_FLAG")
+ /// .takes_value(true))
+ /// .get_matches_from(vec![
+ /// "prog", "--flag", "opt"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("flag"), Some("opt"));
+ /// ```
+ ///
+ /// In this example, we show the variable coming from the environment even with the
+ /// presence of a default:
+ ///
+ /// ```rust
+ /// # use std::env;
+ /// # use clap::{Command, Arg};
+ ///
+ /// env::set_var("MY_FLAG", "env");
+ ///
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .env("MY_FLAG")
+ /// .takes_value(true)
+ /// .default_value("default"))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("flag"), Some("env"));
+ /// ```
+ ///
+ /// In this example, we show the use of multiple values in a single environment variable:
+ ///
+ /// ```rust
+ /// # use std::env;
+ /// # use clap::{Command, Arg};
+ ///
+ /// env::set_var("MY_FLAG_MULTI", "env1,env2");
+ ///
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .env("MY_FLAG_MULTI")
+ /// .takes_value(true)
+ /// .multiple_values(true)
+ /// .use_value_delimiter(true))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert_eq!(m.values_of("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]);
+ /// ```
+ /// [`ArgMatches::value_of`]: crate::ArgMatches::value_of()
+ /// [`Arg::takes_value(true)`]: Arg::takes_value()
+ /// [`Arg::use_value_delimiter(true)`]: Arg::use_value_delimiter()
+ #[cfg(feature = "env")]
+ #[inline]
+ #[must_use]
+ pub fn env(self, name: &'help str) -> Self {
+ self.env_os(OsStr::new(name))
+ }
+
+ /// Read from `name` environment variable when argument is not present.
+ ///
+ /// See [`Arg::env`].
+ #[cfg(feature = "env")]
+ #[inline]
+ #[must_use]
+ pub fn env_os(mut self, name: &'help OsStr) -> Self {
+ self.env = Some((name, env::var_os(name)));
+ self
+ }
+}
+
+/// # Help
+impl<'help> Arg<'help> {
+ /// Sets the description of the argument for short help (`-h`).
+ ///
+ /// Typically, this is a short (one line) description of the arg.
+ ///
+ /// If [`Arg::long_help`] is not specified, this message will be displayed for `--help`.
+ ///
+ /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise
+ ///
+ /// # Examples
+ ///
+ /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
+ /// include a newline in the help text and have the following text be properly aligned with all
+ /// the other help text.
+ ///
+ /// Setting `help` displays a short message to the side of the argument when the user passes
+ /// `-h` or `--help` (by default).
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .help("Some help text describing the --config arg"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays
+ ///
+ /// ```notrust
+ /// helptest
+ ///
+ /// USAGE:
+ /// helptest [OPTIONS]
+ ///
+ /// OPTIONS:
+ /// --config Some help text describing the --config arg
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ /// [`Arg::long_help`]: Arg::long_help()
+ #[inline]
+ #[must_use]
+ pub fn help(mut self, h: impl Into<Option<&'help str>>) -> Self {
+ self.help = h.into();
+ self
+ }
+
+ /// Sets the description of the argument for long help (`--help`).
+ ///
+ /// Typically this a more detailed (multi-line) message
+ /// that describes the arg.
+ ///
+ /// If [`Arg::help`] is not specified, this message will be displayed for `-h`.
+ ///
+ /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise
+ ///
+ /// # Examples
+ ///
+ /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
+ /// include a newline in the help text and have the following text be properly aligned with all
+ /// the other help text.
+ ///
+ /// Setting `help` displays a short message to the side of the argument when the user passes
+ /// `-h` or `--help` (by default).
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .long_help(
+ /// "The config file used by the myprog must be in JSON format
+ /// with only valid keys and may not contain other nonsense
+ /// that cannot be read by this program. Obviously I'm going on
+ /// and on, so I'll stop now."))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays
+ ///
+ /// ```text
+ /// prog
+ ///
+ /// USAGE:
+ /// prog [OPTIONS]
+ ///
+ /// OPTIONS:
+ /// --config
+ /// The config file used by the myprog must be in JSON format
+ /// with only valid keys and may not contain other nonsense
+ /// that cannot be read by this program. Obviously I'm going on
+ /// and on, so I'll stop now.
+ ///
+ /// -h, --help
+ /// Print help information
+ ///
+ /// -V, --version
+ /// Print version information
+ /// ```
+ /// [`Arg::help`]: Arg::help()
+ #[inline]
+ #[must_use]
+ pub fn long_help(mut self, h: impl Into<Option<&'help str>>) -> Self {
+ self.long_help = h.into();
+ self
+ }
+
+ /// Allows custom ordering of args within the help message.
+ ///
+ /// Args with a lower value will be displayed first in the help message. This is helpful when
+ /// one would like to emphasise frequently used args, or prioritize those towards the top of
+ /// the list. Args with duplicate display orders will be displayed in alphabetical order.
+ ///
+ /// **NOTE:** The default is 999 for all arguments.
+ ///
+ /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in
+ /// [index] order.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("a") // Typically args are grouped alphabetically by name.
+ /// // Args without a display_order have a value of 999 and are
+ /// // displayed alphabetically with all other 999 valued args.
+ /// .long("long-option")
+ /// .short('o')
+ /// .takes_value(true)
+ /// .help("Some help and text"))
+ /// .arg(Arg::new("b")
+ /// .long("other-option")
+ /// .short('O')
+ /// .takes_value(true)
+ /// .display_order(1) // In order to force this arg to appear *first*
+ /// // all we have to do is give it a value lower than 999.
+ /// // Any other args with a value of 1 will be displayed
+ /// // alphabetically with this one...then 2 values, then 3, etc.
+ /// .help("I should be first!"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays the following help message
+ ///
+ /// ```text
+ /// cust-ord
+ ///
+ /// USAGE:
+ /// cust-ord [OPTIONS]
+ ///
+ /// OPTIONS:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// -O, --other-option <b> I should be first!
+ /// -o, --long-option <a> Some help and text
+ /// ```
+ /// [positional arguments]: Arg::index()
+ /// [index]: Arg::index()
+ #[inline]
+ #[must_use]
+ pub fn display_order(mut self, ord: usize) -> Self {
+ self.disp_ord.set_explicit(ord);
+ self
+ }
+
+ /// Override the [current] help section.
+ ///
+ /// [current]: crate::Command::help_heading
+ #[inline]
+ #[must_use]
+ pub fn help_heading<O>(mut self, heading: O) -> Self
+ where
+ O: Into<Option<&'help str>>,
+ {
+ self.help_heading = Some(heading.into());
+ self
+ }
+
+ /// Render the [help][Arg::help] on the line after the argument.
+ ///
+ /// This can be helpful for arguments with very long or complex help messages.
+ /// This can also be helpful for arguments with very long flag names, or many/long value names.
+ ///
+ /// **NOTE:** To apply this setting to all arguments and subcommands, consider using
+ /// [`crate::Command::next_line_help`]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("opt")
+ /// .long("long-option-flag")
+ /// .short('o')
+ /// .takes_value(true)
+ /// .next_line_help(true)
+ /// .value_names(&["value1", "value2"])
+ /// .help("Some really long help and complex\n\
+ /// help that makes more sense to be\n\
+ /// on a line after the option"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays the following help message
+ ///
+ /// ```text
+ /// nlh
+ ///
+ /// USAGE:
+ /// nlh [OPTIONS]
+ ///
+ /// OPTIONS:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// -o, --long-option-flag <value1> <value2>
+ /// Some really long help and complex
+ /// help that makes more sense to be
+ /// on a line after the option
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn next_line_help(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::NextLineHelp)
+ } else {
+ self.unset_setting(ArgSettings::NextLineHelp)
+ }
+ }
+
+ /// Do not display the argument in help message.
+ ///
+ /// **NOTE:** This does **not** hide the argument from usage strings on error
+ ///
+ /// # Examples
+ ///
+ /// Setting `Hidden` will hide the argument when displaying help text
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .hide(true)
+ /// .help("Some help text describing the --config arg"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays
+ ///
+ /// ```text
+ /// helptest
+ ///
+ /// USAGE:
+ /// helptest [OPTIONS]
+ ///
+ /// OPTIONS:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn hide(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::Hidden)
+ } else {
+ self.unset_setting(ArgSettings::Hidden)
+ }
+ }
+
+ /// Do not display the [possible values][crate::builder::ValueParser::possible_values] in the help message.
+ ///
+ /// This is useful for args with many values, or ones which are explained elsewhere in the
+ /// help text.
+ ///
+ /// **NOTE:** Setting this requires [`Arg::takes_value`]
+ ///
+ /// To set this for all arguments, see
+ /// [`Command::hide_possible_values`][crate::Command::hide_possible_values].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("mode")
+ /// .long("mode")
+ /// .value_parser(["fast", "slow"])
+ /// .takes_value(true)
+ /// .hide_possible_values(true));
+ /// ```
+ /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of
+ /// the help text would be omitted.
+ #[inline]
+ #[must_use]
+ pub fn hide_possible_values(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::HidePossibleValues)
+ } else {
+ self.unset_setting(ArgSettings::HidePossibleValues)
+ }
+ }
+
+ /// Do not display the default value of the argument in the help message.
+ ///
+ /// This is useful when default behavior of an arg is explained elsewhere in the help text.
+ ///
+ /// **NOTE:** Setting this requires [`Arg::takes_value`]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("connect")
+ /// .arg(Arg::new("host")
+ /// .long("host")
+ /// .default_value("localhost")
+ /// .takes_value(true)
+ /// .hide_default_value(true));
+ ///
+ /// ```
+ ///
+ /// If we were to run the above program with `--help` the `[default: localhost]` portion of
+ /// the help text would be omitted.
+ #[inline]
+ #[must_use]
+ pub fn hide_default_value(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::HideDefaultValue)
+ } else {
+ self.unset_setting(ArgSettings::HideDefaultValue)
+ }
+ }
+
+ /// Do not display in help the environment variable name.
+ ///
+ /// This is useful when the variable option is explained elsewhere in the help text.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("mode")
+ /// .long("mode")
+ /// .env("MODE")
+ /// .takes_value(true)
+ /// .hide_env(true));
+ /// ```
+ ///
+ /// If we were to run the above program with `--help` the `[env: MODE]` portion of the help
+ /// text would be omitted.
+ #[cfg(feature = "env")]
+ #[inline]
+ #[must_use]
+ pub fn hide_env(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::HideEnv)
+ } else {
+ self.unset_setting(ArgSettings::HideEnv)
+ }
+ }
+
+ /// Do not display in help any values inside the associated ENV variables for the argument.
+ ///
+ /// This is useful when ENV vars contain sensitive values.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("connect")
+ /// .arg(Arg::new("host")
+ /// .long("host")
+ /// .env("CONNECT")
+ /// .takes_value(true)
+ /// .hide_env_values(true));
+ ///
+ /// ```
+ ///
+ /// If we were to run the above program with `$ CONNECT=super_secret connect --help` the
+ /// `[default: CONNECT=super_secret]` portion of the help text would be omitted.
+ #[cfg(feature = "env")]
+ #[inline]
+ #[must_use]
+ pub fn hide_env_values(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::HideEnvValues)
+ } else {
+ self.unset_setting(ArgSettings::HideEnvValues)
+ }
+ }
+
+ /// Hides an argument from short help (`-h`).
+ ///
+ /// **NOTE:** This does **not** hide the argument from usage strings on error
+ ///
+ /// **NOTE:** Setting this option will cause next-line-help output style to be used
+ /// when long help (`--help`) is called.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("debug")
+ /// .hide_short_help(true);
+ /// ```
+ ///
+ /// Setting `hide_short_help(true)` will hide the argument when displaying short help text
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .hide_short_help(true)
+ /// .help("Some help text describing the --config arg"))
+ /// .get_matches_from(vec![
+ /// "prog", "-h"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays
+ ///
+ /// ```text
+ /// helptest
+ ///
+ /// USAGE:
+ /// helptest [OPTIONS]
+ ///
+ /// OPTIONS:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ ///
+ /// However, when --help is called
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .hide_short_help(true)
+ /// .help("Some help text describing the --config arg"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// Then the following would be displayed
+ ///
+ /// ```text
+ /// helptest
+ ///
+ /// USAGE:
+ /// helptest [OPTIONS]
+ ///
+ /// OPTIONS:
+ /// --config Some help text describing the --config arg
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn hide_short_help(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::HiddenShortHelp)
+ } else {
+ self.unset_setting(ArgSettings::HiddenShortHelp)
+ }
+ }
+
+ /// Hides an argument from long help (`--help`).
+ ///
+ /// **NOTE:** This does **not** hide the argument from usage strings on error
+ ///
+ /// **NOTE:** Setting this option will cause next-line-help output style to be used
+ /// when long help (`--help`) is called.
+ ///
+ /// # Examples
+ ///
+ /// Setting `hide_long_help(true)` will hide the argument when displaying long help text
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .hide_long_help(true)
+ /// .help("Some help text describing the --config arg"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays
+ ///
+ /// ```text
+ /// helptest
+ ///
+ /// USAGE:
+ /// helptest [OPTIONS]
+ ///
+ /// OPTIONS:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ ///
+ /// However, when -h is called
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .hide_long_help(true)
+ /// .help("Some help text describing the --config arg"))
+ /// .get_matches_from(vec![
+ /// "prog", "-h"
+ /// ]);
+ /// ```
+ ///
+ /// Then the following would be displayed
+ ///
+ /// ```text
+ /// helptest
+ ///
+ /// USAGE:
+ /// helptest [OPTIONS]
+ ///
+ /// OPTIONS:
+ /// --config Some help text describing the --config arg
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn hide_long_help(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::HiddenLongHelp)
+ } else {
+ self.unset_setting(ArgSettings::HiddenLongHelp)
+ }
+ }
+}
+
+/// # Advanced Argument Relations
+impl<'help> Arg<'help> {
+ /// The name of the [`ArgGroup`] the argument belongs to.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("debug")
+ /// .long("debug")
+ /// .group("mode")
+ /// # ;
+ /// ```
+ ///
+ /// Multiple arguments can be a member of a single group and then the group checked as if it
+ /// was one of said arguments.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("debug")
+ /// .long("debug")
+ /// .group("mode"))
+ /// .arg(Arg::new("verbose")
+ /// .long("verbose")
+ /// .group("mode"))
+ /// .get_matches_from(vec![
+ /// "prog", "--debug"
+ /// ]);
+ /// assert!(m.contains_id("mode"));
+ /// ```
+ ///
+ /// [`ArgGroup`]: crate::ArgGroup
+ #[must_use]
+ pub fn group<T: Key>(mut self, group_id: T) -> Self {
+ self.groups.push(group_id.into());
+ self
+ }
+
+ /// The names of [`ArgGroup`]'s the argument belongs to.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("debug")
+ /// .long("debug")
+ /// .groups(&["mode", "verbosity"])
+ /// # ;
+ /// ```
+ ///
+ /// Arguments can be members of multiple groups and then the group checked as if it
+ /// was one of said arguments.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("debug")
+ /// .long("debug")
+ /// .groups(&["mode", "verbosity"]))
+ /// .arg(Arg::new("verbose")
+ /// .long("verbose")
+ /// .groups(&["mode", "verbosity"]))
+ /// .get_matches_from(vec![
+ /// "prog", "--debug"
+ /// ]);
+ /// assert!(m.contains_id("mode"));
+ /// assert!(m.contains_id("verbosity"));
+ /// ```
+ ///
+ /// [`ArgGroup`]: crate::ArgGroup
+ #[must_use]
+ pub fn groups<T: Key>(mut self, group_ids: &[T]) -> Self {
+ self.groups.extend(group_ids.iter().map(Id::from));
+ self
+ }
+
+ /// Specifies the value of the argument if `arg` has been used at runtime.
+ ///
+ /// If `val` is set to `None`, `arg` only needs to be present. If `val` is set to `"some-val"`
+ /// then `arg` must be present at runtime **and** have the value `val`.
+ ///
+ /// If `default` is set to `None`, `default_value` will be removed.
+ ///
+ /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly
+ /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg
+ /// at runtime. This setting however only takes effect when the user has not provided a value at
+ /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value`
+ /// and `Arg::default_value_if`, and the user **did not** provide this arg at runtime, nor were
+ /// the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be applied.
+ ///
+ /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
+ ///
+ /// # Examples
+ ///
+ /// First we use the default value only if another arg is present at runtime.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_if("flag", None, Some("default")))
+ /// .get_matches_from(vec![
+ /// "prog", "--flag"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("other"), Some("default"));
+ /// ```
+ ///
+ /// Next we run the same test, but without providing `--flag`.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_if("flag", None, Some("default")))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("other"), None);
+ /// ```
+ ///
+ /// Now lets only use the default value if `--opt` contains the value `special`.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("opt")
+ /// .takes_value(true)
+ /// .long("opt"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_if("opt", Some("special"), Some("default")))
+ /// .get_matches_from(vec![
+ /// "prog", "--opt", "special"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("other"), Some("default"));
+ /// ```
+ ///
+ /// We can run the same test and provide any value *other than* `special` and we won't get a
+ /// default value.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("opt")
+ /// .takes_value(true)
+ /// .long("opt"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_if("opt", Some("special"), Some("default")))
+ /// .get_matches_from(vec![
+ /// "prog", "--opt", "hahaha"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("other"), None);
+ /// ```
+ ///
+ /// If we want to unset the default value for an Arg based on the presence or
+ /// value of some other Arg.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value("default")
+ /// .default_value_if("flag", None, None))
+ /// .get_matches_from(vec![
+ /// "prog", "--flag"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("other"), None);
+ /// ```
+ /// [`Arg::takes_value(true)`]: Arg::takes_value()
+ /// [`Arg::default_value`]: Arg::default_value()
+ #[must_use]
+ pub fn default_value_if<T: Key>(
+ self,
+ arg_id: T,
+ val: Option<&'help str>,
+ default: Option<&'help str>,
+ ) -> Self {
+ self.default_value_if_os(arg_id, val.map(OsStr::new), default.map(OsStr::new))
+ }
+
+ /// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`]
+ /// only using [`OsStr`]s instead.
+ ///
+ /// [`Arg::default_value_if`]: Arg::default_value_if()
+ /// [`OsStr`]: std::ffi::OsStr
+ #[must_use]
+ pub fn default_value_if_os<T: Key>(
+ mut self,
+ arg_id: T,
+ val: Option<&'help OsStr>,
+ default: Option<&'help OsStr>,
+ ) -> Self {
+ self.default_vals_ifs
+ .push((arg_id.into(), val.into(), default));
+ self.takes_value(true)
+ }
+
+ /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`].
+ ///
+ /// The method takes a slice of tuples in the `(arg, Option<val>, default)` format.
+ ///
+ /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first
+ /// if multiple conditions are true, the first one found will be applied and the ultimate value.
+ ///
+ /// # Examples
+ ///
+ /// First we use the default value only if another arg is present at runtime.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag"))
+ /// .arg(Arg::new("opt")
+ /// .long("opt")
+ /// .takes_value(true))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_ifs(&[
+ /// ("flag", None, Some("default")),
+ /// ("opt", Some("channal"), Some("chan")),
+ /// ]))
+ /// .get_matches_from(vec![
+ /// "prog", "--opt", "channal"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("other"), Some("chan"));
+ /// ```
+ ///
+ /// Next we run the same test, but without providing `--flag`.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_ifs(&[
+ /// ("flag", None, Some("default")),
+ /// ("opt", Some("channal"), Some("chan")),
+ /// ]))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("other"), None);
+ /// ```
+ ///
+ /// We can also see that these values are applied in order, and if more than one condition is
+ /// true, only the first evaluated "wins"
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag"))
+ /// .arg(Arg::new("opt")
+ /// .long("opt")
+ /// .takes_value(true))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_ifs(&[
+ /// ("flag", None, Some("default")),
+ /// ("opt", Some("channal"), Some("chan")),
+ /// ]))
+ /// .get_matches_from(vec![
+ /// "prog", "--opt", "channal", "--flag"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("other"), Some("default"));
+ /// ```
+ /// [`Arg::takes_value(true)`]: Arg::takes_value()
+ /// [`Arg::default_value_if`]: Arg::default_value_if()
+ #[must_use]
+ pub fn default_value_ifs<T: Key>(
+ mut self,
+ ifs: &[(T, Option<&'help str>, Option<&'help str>)],
+ ) -> Self {
+ for (arg, val, default) in ifs {
+ self = self.default_value_if_os(arg, val.map(OsStr::new), default.map(OsStr::new));
+ }
+ self
+ }
+
+ /// Provides multiple conditional default values in the exact same manner as
+ /// [`Arg::default_value_ifs`] only using [`OsStr`]s instead.
+ ///
+ /// [`Arg::default_value_ifs`]: Arg::default_value_ifs()
+ /// [`OsStr`]: std::ffi::OsStr
+ #[must_use]
+ pub fn default_value_ifs_os<T: Key>(
+ mut self,
+ ifs: &[(T, Option<&'help OsStr>, Option<&'help OsStr>)],
+ ) -> Self {
+ for (arg, val, default) in ifs {
+ self = self.default_value_if_os(arg, *val, *default);
+ }
+ self
+ }
+
+ /// Set this arg as [required] as long as the specified argument is not present at runtime.
+ ///
+ /// **Pro Tip:** Using `Arg::required_unless_present` implies [`Arg::required`] and is therefore not
+ /// mandatory to also set.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required_unless_present("debug")
+ /// # ;
+ /// ```
+ ///
+ /// In the following example, the required argument is *not* provided,
+ /// but it's not an error because the `unless` arg has been supplied.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_unless_present("dbg")
+ /// .takes_value(true)
+ /// .long("config"))
+ /// .arg(Arg::new("dbg")
+ /// .long("debug"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--debug"
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// ```
+ ///
+ /// Setting `Arg::required_unless_present(name)` and *not* supplying `name` or this arg is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_unless_present("dbg")
+ /// .takes_value(true)
+ /// .long("config"))
+ /// .arg(Arg::new("dbg")
+ /// .long("debug"))
+ /// .try_get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [required]: Arg::required()
+ #[must_use]
+ pub fn required_unless_present<T: Key>(mut self, arg_id: T) -> Self {
+ self.r_unless.push(arg_id.into());
+ self
+ }
+
+ /// Sets this arg as [required] unless *all* of the specified arguments are present at runtime.
+ ///
+ /// In other words, parsing will succeed only if user either
+ /// * supplies the `self` arg.
+ /// * supplies *all* of the `names` arguments.
+ ///
+ /// **NOTE:** If you wish for this argument to only be required unless *any of* these args are
+ /// present see [`Arg::required_unless_present_any`]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required_unless_present_all(&["cfg", "dbg"])
+ /// # ;
+ /// ```
+ ///
+ /// In the following example, the required argument is *not* provided, but it's not an error
+ /// because *all* of the `names` args have been supplied.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_unless_present_all(&["dbg", "infile"])
+ /// .takes_value(true)
+ /// .long("config"))
+ /// .arg(Arg::new("dbg")
+ /// .long("debug"))
+ /// .arg(Arg::new("infile")
+ /// .short('i')
+ /// .takes_value(true))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--debug", "-i", "file"
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// ```
+ ///
+ /// Setting [`Arg::required_unless_present_all(names)`] and *not* supplying
+ /// either *all* of `unless` args or the `self` arg is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_unless_present_all(&["dbg", "infile"])
+ /// .takes_value(true)
+ /// .long("config"))
+ /// .arg(Arg::new("dbg")
+ /// .long("debug"))
+ /// .arg(Arg::new("infile")
+ /// .short('i')
+ /// .takes_value(true))
+ /// .try_get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [required]: Arg::required()
+ /// [`Arg::required_unless_present_any`]: Arg::required_unless_present_any()
+ /// [`Arg::required_unless_present_all(names)`]: Arg::required_unless_present_all()
+ #[must_use]
+ pub fn required_unless_present_all<T, I>(mut self, names: I) -> Self
+ where
+ I: IntoIterator<Item = T>,
+ T: Key,
+ {
+ self.r_unless_all.extend(names.into_iter().map(Id::from));
+ self
+ }
+
+ /// Sets this arg as [required] unless *any* of the specified arguments are present at runtime.
+ ///
+ /// In other words, parsing will succeed only if user either
+ /// * supplies the `self` arg.
+ /// * supplies *one or more* of the `unless` arguments.
+ ///
+ /// **NOTE:** If you wish for this argument to be required unless *all of* these args are
+ /// present see [`Arg::required_unless_present_all`]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required_unless_present_any(&["cfg", "dbg"])
+ /// # ;
+ /// ```
+ ///
+ /// Setting [`Arg::required_unless_present_any(names)`] requires that the argument be used at runtime
+ /// *unless* *at least one of* the args in `names` are present. In the following example, the
+ /// required argument is *not* provided, but it's not an error because one the `unless` args
+ /// have been supplied.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_unless_present_any(&["dbg", "infile"])
+ /// .takes_value(true)
+ /// .long("config"))
+ /// .arg(Arg::new("dbg")
+ /// .long("debug"))
+ /// .arg(Arg::new("infile")
+ /// .short('i')
+ /// .takes_value(true))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--debug"
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// ```
+ ///
+ /// Setting [`Arg::required_unless_present_any(names)`] and *not* supplying *at least one of* `names`
+ /// or this arg is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_unless_present_any(&["dbg", "infile"])
+ /// .takes_value(true)
+ /// .long("config"))
+ /// .arg(Arg::new("dbg")
+ /// .long("debug"))
+ /// .arg(Arg::new("infile")
+ /// .short('i')
+ /// .takes_value(true))
+ /// .try_get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [required]: Arg::required()
+ /// [`Arg::required_unless_present_any(names)`]: Arg::required_unless_present_any()
+ /// [`Arg::required_unless_present_all`]: Arg::required_unless_present_all()
+ #[must_use]
+ pub fn required_unless_present_any<T, I>(mut self, names: I) -> Self
+ where
+ I: IntoIterator<Item = T>,
+ T: Key,
+ {
+ self.r_unless.extend(names.into_iter().map(Id::from));
+ self
+ }
+
+ /// This argument is [required] only if the specified `arg` is present at runtime and its value
+ /// equals `val`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required_if_eq("other_arg", "value")
+ /// # ;
+ /// ```
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .required_if_eq("other", "special")
+ /// .long("config"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .takes_value(true))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--other", "not-special"
+ /// ]);
+ ///
+ /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required
+ ///
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .required_if_eq("other", "special")
+ /// .long("config"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .takes_value(true))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--other", "special"
+ /// ]);
+ ///
+ /// // We did use --other=special so "cfg" had become required but was missing.
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ ///
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .required_if_eq("other", "special")
+ /// .long("config"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .takes_value(true))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--other", "SPECIAL"
+ /// ]);
+ ///
+ /// // By default, the comparison is case-sensitive, so "cfg" wasn't required
+ /// assert!(res.is_ok());
+ ///
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .required_if_eq("other", "special")
+ /// .long("config"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .ignore_case(true)
+ /// .takes_value(true))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--other", "SPECIAL"
+ /// ]);
+ ///
+ /// // However, case-insensitive comparisons can be enabled. This typically occurs when using Arg::possible_values().
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [`Arg::requires(name)`]: Arg::requires()
+ /// [Conflicting]: Arg::conflicts_with()
+ /// [required]: Arg::required()
+ #[must_use]
+ pub fn required_if_eq<T: Key>(mut self, arg_id: T, val: &'help str) -> Self {
+ self.r_ifs.push((arg_id.into(), val));
+ self
+ }
+
+ /// Specify this argument is [required] based on multiple conditions.
+ ///
+ /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become
+ /// valid if one of the specified `arg`'s value equals its corresponding `val`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required_if_eq_any(&[
+ /// ("extra", "val"),
+ /// ("option", "spec")
+ /// ])
+ /// # ;
+ /// ```
+ ///
+ /// Setting `Arg::required_if_eq_any(&[(arg, val)])` makes this arg required if any of the `arg`s
+ /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is
+ /// anything other than `val`, this argument isn't required.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_if_eq_any(&[
+ /// ("extra", "val"),
+ /// ("option", "spec")
+ /// ])
+ /// .takes_value(true)
+ /// .long("config"))
+ /// .arg(Arg::new("extra")
+ /// .takes_value(true)
+ /// .long("extra"))
+ /// .arg(Arg::new("option")
+ /// .takes_value(true)
+ /// .long("option"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--option", "other"
+ /// ]);
+ ///
+ /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required
+ /// ```
+ ///
+ /// Setting `Arg::required_if_eq_any(&[(arg, val)])` and having any of the `arg`s used with its
+ /// value of `val` but *not* using this arg is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_if_eq_any(&[
+ /// ("extra", "val"),
+ /// ("option", "spec")
+ /// ])
+ /// .takes_value(true)
+ /// .long("config"))
+ /// .arg(Arg::new("extra")
+ /// .takes_value(true)
+ /// .long("extra"))
+ /// .arg(Arg::new("option")
+ /// .takes_value(true)
+ /// .long("option"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--option", "spec"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [`Arg::requires(name)`]: Arg::requires()
+ /// [Conflicting]: Arg::conflicts_with()
+ /// [required]: Arg::required()
+ #[must_use]
+ pub fn required_if_eq_any<T: Key>(mut self, ifs: &[(T, &'help str)]) -> Self {
+ self.r_ifs
+ .extend(ifs.iter().map(|(id, val)| (Id::from_ref(id), *val)));
+ self
+ }
+
+ /// Specify this argument is [required] based on multiple conditions.
+ ///
+ /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become
+ /// valid if every one of the specified `arg`'s value equals its corresponding `val`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required_if_eq_all(&[
+ /// ("extra", "val"),
+ /// ("option", "spec")
+ /// ])
+ /// # ;
+ /// ```
+ ///
+ /// Setting `Arg::required_if_eq_all(&[(arg, val)])` makes this arg required if all of the `arg`s
+ /// are used at runtime and every value is equal to its corresponding `val`. If the `arg`'s value is
+ /// anything other than `val`, this argument isn't required.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_if_eq_all(&[
+ /// ("extra", "val"),
+ /// ("option", "spec")
+ /// ])
+ /// .takes_value(true)
+ /// .long("config"))
+ /// .arg(Arg::new("extra")
+ /// .takes_value(true)
+ /// .long("extra"))
+ /// .arg(Arg::new("option")
+ /// .takes_value(true)
+ /// .long("option"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--option", "spec"
+ /// ]);
+ ///
+ /// assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required
+ /// ```
+ ///
+ /// Setting `Arg::required_if_eq_all(&[(arg, val)])` and having all of the `arg`s used with its
+ /// value of `val` but *not* using this arg is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_if_eq_all(&[
+ /// ("extra", "val"),
+ /// ("option", "spec")
+ /// ])
+ /// .takes_value(true)
+ /// .long("config"))
+ /// .arg(Arg::new("extra")
+ /// .takes_value(true)
+ /// .long("extra"))
+ /// .arg(Arg::new("option")
+ /// .takes_value(true)
+ /// .long("option"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--extra", "val", "--option", "spec"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [required]: Arg::required()
+ #[must_use]
+ pub fn required_if_eq_all<T: Key>(mut self, ifs: &[(T, &'help str)]) -> Self {
+ self.r_ifs_all
+ .extend(ifs.iter().map(|(id, val)| (Id::from_ref(id), *val)));
+ self
+ }
+
+ /// Require another argument if this arg was present at runtime and its value equals to `val`.
+ ///
+ /// This method takes `value, another_arg` pair. At runtime, clap will check
+ /// if this arg (`self`) is present and its value equals to `val`.
+ /// If it does, `another_arg` will be marked as required.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .requires_if("val", "arg")
+ /// # ;
+ /// ```
+ ///
+ /// Setting `Arg::requires_if(val, arg)` requires that the `arg` be used at runtime if the
+ /// defining argument's value is equal to `val`. If the defining argument is anything other than
+ /// `val`, the other argument isn't required.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .requires_if("my.cfg", "other")
+ /// .long("config"))
+ /// .arg(Arg::new("other"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "some.cfg"
+ /// ]);
+ ///
+ /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required
+ /// ```
+ ///
+ /// Setting `Arg::requires_if(val, arg)` and setting the value to `val` but *not* supplying
+ /// `arg` is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .requires_if("my.cfg", "input")
+ /// .long("config"))
+ /// .arg(Arg::new("input"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "my.cfg"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [`Arg::requires(name)`]: Arg::requires()
+ /// [Conflicting]: Arg::conflicts_with()
+ /// [override]: Arg::overrides_with()
+ #[must_use]
+ pub fn requires_if<T: Key>(mut self, val: &'help str, arg_id: T) -> Self {
+ self.requires
+ .push((ArgPredicate::Equals(OsStr::new(val)), arg_id.into()));
+ self
+ }
+
+ /// Allows multiple conditional requirements.
+ ///
+ /// The requirement will only become valid if this arg's value equals `val`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .requires_ifs(&[
+ /// ("val", "arg"),
+ /// ("other_val", "arg2"),
+ /// ])
+ /// # ;
+ /// ```
+ ///
+ /// Setting `Arg::requires_ifs(&["val", "arg"])` requires that the `arg` be used at runtime if the
+ /// defining argument's value is equal to `val`. If the defining argument's value is anything other
+ /// than `val`, `arg` isn't required.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .requires_ifs(&[
+ /// ("special.conf", "opt"),
+ /// ("other.conf", "other"),
+ /// ])
+ /// .long("config"))
+ /// .arg(Arg::new("opt")
+ /// .long("option")
+ /// .takes_value(true))
+ /// .arg(Arg::new("other"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "special.conf"
+ /// ]);
+ ///
+ /// assert!(res.is_err()); // We used --config=special.conf so --option <val> is required
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [`Arg::requires(name)`]: Arg::requires()
+ /// [Conflicting]: Arg::conflicts_with()
+ /// [override]: Arg::overrides_with()
+ #[must_use]
+ pub fn requires_ifs<T: Key>(mut self, ifs: &[(&'help str, T)]) -> Self {
+ self.requires.extend(
+ ifs.iter()
+ .map(|(val, arg)| (ArgPredicate::Equals(OsStr::new(*val)), Id::from(arg))),
+ );
+ self
+ }
+
+ /// Require these arguments names when this one is presen
+ ///
+ /// i.e. when using this argument, the following arguments *must* be present.
+ ///
+ /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required
+ /// by default.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .requires_all(&["input", "output"])
+ /// # ;
+ /// ```
+ ///
+ /// Setting `Arg::requires_all(&[arg, arg2])` requires that all the arguments be used at
+ /// runtime if the defining argument is used. If the defining argument isn't used, the other
+ /// argument isn't required
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .requires("input")
+ /// .long("config"))
+ /// .arg(Arg::new("input"))
+ /// .arg(Arg::new("output"))
+ /// .try_get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required
+ /// ```
+ ///
+ /// Setting `Arg::requires_all(&[arg, arg2])` and *not* supplying all the arguments is an
+ /// error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .requires_all(&["input", "output"])
+ /// .long("config"))
+ /// .arg(Arg::new("input"))
+ /// .arg(Arg::new("output"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "file.conf", "in.txt"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// // We didn't use output
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [Conflicting]: Arg::conflicts_with()
+ /// [override]: Arg::overrides_with()
+ #[must_use]
+ pub fn requires_all<T: Key>(mut self, names: &[T]) -> Self {
+ self.requires
+ .extend(names.iter().map(|s| (ArgPredicate::IsPresent, s.into())));
+ self
+ }
+
+ /// This argument is mutually exclusive with the specified argument.
+ ///
+ /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
+ /// only need to be set for one of the two arguments, they do not need to be set for each.
+ ///
+ /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
+ /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not
+ /// need to also do B.conflicts_with(A))
+ ///
+ /// **NOTE:** [`Arg::conflicts_with_all(names)`] allows specifying an argument which conflicts with more than one argument.
+ ///
+ /// **NOTE** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .conflicts_with("debug")
+ /// # ;
+ /// ```
+ ///
+ /// Setting conflicting argument, and having both arguments present at runtime is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .conflicts_with("debug")
+ /// .long("config"))
+ /// .arg(Arg::new("debug")
+ /// .long("debug"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--debug", "--config", "file.conf"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
+ /// ```
+ ///
+ /// [`Arg::conflicts_with_all(names)`]: Arg::conflicts_with_all()
+ /// [`Arg::exclusive(true)`]: Arg::exclusive()
+ #[must_use]
+ pub fn conflicts_with<T: Key>(mut self, arg_id: T) -> Self {
+ self.blacklist.push(arg_id.into());
+ self
+ }
+
+ /// This argument is mutually exclusive with the specified arguments.
+ ///
+ /// See [`Arg::conflicts_with`].
+ ///
+ /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
+ /// only need to be set for one of the two arguments, they do not need to be set for each.
+ ///
+ /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
+ /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need
+ /// need to also do B.conflicts_with(A))
+ ///
+ /// **NOTE:** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .conflicts_with_all(&["debug", "input"])
+ /// # ;
+ /// ```
+ ///
+ /// Setting conflicting argument, and having any of the arguments present at runtime with a
+ /// conflicting argument is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .takes_value(true)
+ /// .conflicts_with_all(&["debug", "input"])
+ /// .long("config"))
+ /// .arg(Arg::new("debug")
+ /// .long("debug"))
+ /// .arg(Arg::new("input"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "file.conf", "file.txt"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
+ /// ```
+ /// [`Arg::conflicts_with`]: Arg::conflicts_with()
+ /// [`Arg::exclusive(true)`]: Arg::exclusive()
+ #[must_use]
+ pub fn conflicts_with_all(mut self, names: &[&str]) -> Self {
+ self.blacklist.extend(names.iter().copied().map(Id::from));
+ self
+ }
+
+ /// Sets an overridable argument.
+ ///
+ /// i.e. this argument and the following argument
+ /// will override each other in POSIX style (whichever argument was specified at runtime
+ /// **last** "wins")
+ ///
+ /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
+ /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
+ ///
+ /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with`].
+ ///
+ /// **WARNING:** Positional arguments and options which accept
+ /// [`Arg::multiple_occurrences`] cannot override themselves (or we
+ /// would never be able to advance to the next positional). If a positional
+ /// argument or option with one of the [`Arg::multiple_occurrences`]
+ /// settings lists itself as an override, it is simply ignored.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, arg};
+ /// let m = Command::new("prog")
+ /// .arg(arg!(-f --flag "some flag")
+ /// .conflicts_with("debug"))
+ /// .arg(arg!(-d --debug "other flag"))
+ /// .arg(arg!(-c --color "third flag")
+ /// .overrides_with("flag"))
+ /// .get_matches_from(vec![
+ /// "prog", "-f", "-d", "-c"]);
+ /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color
+ ///
+ /// assert!(m.is_present("color"));
+ /// assert!(m.is_present("debug")); // even though flag conflicts with debug, it's as if flag
+ /// // was never used because it was overridden with color
+ /// assert!(!m.is_present("flag"));
+ /// ```
+ /// Care must be taken when using this setting, and having an arg override with itself. This
+ /// is common practice when supporting things like shell aliases, config files, etc.
+ /// However, when combined with multiple values, it can get dicy.
+ /// Here is how clap handles such situations:
+ ///
+ /// When a flag overrides itself, it's as if the flag was only ever used once (essentially
+ /// preventing a "Unexpected multiple usage" error):
+ ///
+ /// ```rust
+ /// # use clap::{Command, arg};
+ /// let m = Command::new("posix")
+ /// .arg(arg!(--flag "some flag").overrides_with("flag"))
+ /// .get_matches_from(vec!["posix", "--flag", "--flag"]);
+ /// assert!(m.is_present("flag"));
+ /// ```
+ ///
+ /// Making an arg [`Arg::multiple_occurrences`] and override itself
+ /// is essentially meaningless. Therefore clap ignores an override of self
+ /// if it's a flag and it already accepts multiple occurrences.
+ ///
+ /// ```
+ /// # use clap::{Command, arg};
+ /// let m = Command::new("posix")
+ /// .arg(arg!(--flag ... "some flag").overrides_with("flag"))
+ /// .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]);
+ /// assert!(m.is_present("flag"));
+ /// ```
+ ///
+ /// Now notice with options (which *do not* set
+ /// [`Arg::multiple_occurrences`]), it's as if only the last
+ /// occurrence happened.
+ ///
+ /// ```
+ /// # use clap::{Command, arg};
+ /// let m = Command::new("posix")
+ /// .arg(arg!(--opt <val> "some option").overrides_with("opt"))
+ /// .get_matches_from(vec!["", "--opt=some", "--opt=other"]);
+ /// assert!(m.is_present("opt"));
+ /// assert_eq!(m.value_of("opt"), Some("other"));
+ /// ```
+ ///
+ /// This will also work when [`Arg::multiple_values`] is enabled:
+ ///
+ /// ```
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("posix")
+ /// .arg(
+ /// Arg::new("opt")
+ /// .long("opt")
+ /// .takes_value(true)
+ /// .multiple_values(true)
+ /// .overrides_with("opt")
+ /// )
+ /// .get_matches_from(vec!["", "--opt", "1", "2", "--opt", "3", "4", "5"]);
+ /// assert!(m.is_present("opt"));
+ /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["3", "4", "5"]);
+ /// ```
+ ///
+ /// Just like flags, options with [`Arg::multiple_occurrences`] set
+ /// will ignore the "override self" setting.
+ ///
+ /// ```
+ /// # use clap::{Command, arg};
+ /// let m = Command::new("posix")
+ /// .arg(arg!(--opt <val> ... "some option")
+ /// .multiple_values(true)
+ /// .overrides_with("opt"))
+ /// .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]);
+ /// assert!(m.is_present("opt"));
+ /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["first", "over", "other", "val"]);
+ /// ```
+ #[must_use]
+ pub fn overrides_with<T: Key>(mut self, arg_id: T) -> Self {
+ self.overrides.push(arg_id.into());
+ self
+ }
+
+ /// Sets multiple mutually overridable arguments by name.
+ ///
+ /// i.e. this argument and the following argument will override each other in POSIX style
+ /// (whichever argument was specified at runtime **last** "wins")
+ ///
+ /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
+ /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
+ ///
+ /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with_all`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, arg};
+ /// let m = Command::new("prog")
+ /// .arg(arg!(-f --flag "some flag")
+ /// .conflicts_with("color"))
+ /// .arg(arg!(-d --debug "other flag"))
+ /// .arg(arg!(-c --color "third flag")
+ /// .overrides_with_all(&["flag", "debug"]))
+ /// .get_matches_from(vec![
+ /// "prog", "-f", "-d", "-c"]);
+ /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color
+ ///
+ /// assert!(m.is_present("color")); // even though flag conflicts with color, it's as if flag
+ /// // and debug were never used because they were overridden
+ /// // with color
+ /// assert!(!m.is_present("debug"));
+ /// assert!(!m.is_present("flag"));
+ /// ```
+ #[must_use]
+ pub fn overrides_with_all<T: Key>(mut self, names: &[T]) -> Self {
+ self.overrides.extend(names.iter().map(Id::from));
+ self
+ }
+}
+
+/// # Reflection
+impl<'help> Arg<'help> {
+ /// Get the name of the argument
+ #[inline]
+ pub fn get_id(&self) -> &'help str {
+ self.name
+ }
+
+ /// Deprecated, replaced with [`Arg::get_id`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.1.0", note = "Replaced with `Arg::get_id`")
+ )]
+ pub fn get_name(&self) -> &'help str {
+ self.get_id()
+ }
+
+ /// Get the help specified for this argument, if any
+ #[inline]
+ pub fn get_help(&self) -> Option<&'help str> {
+ self.help
+ }
+
+ /// Get the long help specified for this argument, if any
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// let arg = Arg::new("foo").long_help("long help");
+ /// assert_eq!(Some("long help"), arg.get_long_help());
+ /// ```
+ ///
+ #[inline]
+ pub fn get_long_help(&self) -> Option<&'help str> {
+ self.long_help
+ }
+
+ /// Get the help heading specified for this argument, if any
+ #[inline]
+ pub fn get_help_heading(&self) -> Option<&'help str> {
+ self.help_heading.unwrap_or_default()
+ }
+
+ /// Get the short option name for this argument, if any
+ #[inline]
+ pub fn get_short(&self) -> Option<char> {
+ self.short
+ }
+
+ /// Get visible short aliases for this argument, if any
+ #[inline]
+ pub fn get_visible_short_aliases(&self) -> Option<Vec<char>> {
+ if self.short_aliases.is_empty() {
+ None
+ } else {
+ Some(
+ self.short_aliases
+ .iter()
+ .filter_map(|(c, v)| if *v { Some(c) } else { None })
+ .copied()
+ .collect(),
+ )
+ }
+ }
+
+ /// 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>> {
+ let mut shorts = match self.short {
+ Some(short) => vec![short],
+ None => return None,
+ };
+ if let Some(aliases) = self.get_visible_short_aliases() {
+ shorts.extend(aliases);
+ }
+ Some(shorts)
+ }
+
+ /// Get the long option name for this argument, if any
+ #[inline]
+ pub fn get_long(&self) -> Option<&'help str> {
+ self.long
+ }
+
+ /// Get visible aliases for this argument, if any
+ #[inline]
+ pub fn get_visible_aliases(&self) -> Option<Vec<&'help str>> {
+ if self.aliases.is_empty() {
+ None
+ } else {
+ Some(
+ self.aliases
+ .iter()
+ .filter_map(|(s, v)| if *v { Some(s) } else { None })
+ .copied()
+ .collect(),
+ )
+ }
+ }
+
+ /// 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>> {
+ let mut longs = match self.long {
+ Some(long) => vec![long],
+ None => return None,
+ };
+ if let Some(aliases) = self.get_visible_aliases() {
+ longs.extend(aliases);
+ }
+ Some(longs)
+ }
+
+ /// Deprecated, replaced with [`Arg::get_value_parser().possible_values()`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `Arg::get_value_parser().possible_values()`"
+ )
+ )]
+ pub fn get_possible_values(&self) -> Option<&[PossibleValue<'help>]> {
+ if self.possible_vals.is_empty() {
+ None
+ } else {
+ Some(&self.possible_vals)
+ }
+ }
+
+ pub(crate) fn get_possible_values2(&self) -> Vec<PossibleValue<'help>> {
+ #![allow(deprecated)]
+ if !self.is_takes_value_set() {
+ vec![]
+ } else if let Some(pvs) = self.get_possible_values() {
+ // Check old first in case the user explicitly set possible values and the derive inferred
+ // a `ValueParser` with some.
+ pvs.to_vec()
+ } else {
+ self.get_value_parser()
+ .possible_values()
+ .map(|pvs| pvs.collect())
+ .unwrap_or_default()
+ }
+ }
+
+ /// Get the names of values for this argument.
+ #[inline]
+ pub fn get_value_names(&self) -> Option<&[&'help str]> {
+ if self.val_names.is_empty() {
+ None
+ } else {
+ Some(&self.val_names)
+ }
+ }
+
+ /// Get the number of values for this argument.
+ #[inline]
+ pub fn get_num_vals(&self) -> Option<usize> {
+ self.num_vals
+ }
+
+ /// Get the delimiter between multiple values
+ #[inline]
+ pub fn get_value_delimiter(&self) -> Option<char> {
+ self.val_delim
+ }
+
+ /// Get the index of this argument, if any
+ #[inline]
+ pub fn get_index(&self) -> Option<usize> {
+ self.index
+ }
+
+ /// Get the value hint of this argument
+ pub fn get_value_hint(&self) -> ValueHint {
+ self.value_hint.unwrap_or_else(|| {
+ if self.is_takes_value_set() {
+ let type_id = self.get_value_parser().type_id();
+ if type_id == crate::parser::AnyValueId::of::<std::path::PathBuf>() {
+ ValueHint::AnyPath
+ } else {
+ ValueHint::default()
+ }
+ } else {
+ ValueHint::default()
+ }
+ })
+ }
+
+ /// Deprecated, replaced with [`Arg::is_global_set`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.1.0", note = "Replaced with `Arg::is_global_set`")
+ )]
+ pub fn get_global(&self) -> bool {
+ self.is_global_set()
+ }
+
+ /// Get the environment variable name specified for this argument, if any
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use std::ffi::OsStr;
+ /// # use clap::Arg;
+ /// let arg = Arg::new("foo").env("ENVIRONMENT");
+ /// assert_eq!(Some(OsStr::new("ENVIRONMENT")), arg.get_env());
+ /// ```
+ #[cfg(feature = "env")]
+ pub fn get_env(&self) -> Option<&OsStr> {
+ self.env.as_ref().map(|x| x.0)
+ }
+
+ /// Get the default values specified for this argument, if any
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// let arg = Arg::new("foo").default_value("default value");
+ /// assert_eq!(&["default value"], arg.get_default_values());
+ /// ```
+ pub fn get_default_values(&self) -> &[&OsStr] {
+ &self.default_vals
+ }
+
+ /// Checks whether this argument is a positional or not.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use clap::Arg;
+ /// let arg = Arg::new("foo");
+ /// assert_eq!(true, arg.is_positional());
+ ///
+ /// let arg = Arg::new("foo").long("foo");
+ /// assert_eq!(false, arg.is_positional());
+ /// ```
+ pub fn is_positional(&self) -> bool {
+ self.long.is_none() && self.short.is_none()
+ }
+
+ /// Reports whether [`Arg::required`] is set
+ pub fn is_required_set(&self) -> bool {
+ self.is_set(ArgSettings::Required)
+ }
+
+ /// Report whether [`Arg::multiple_values`] is set
+ pub fn is_multiple_values_set(&self) -> bool {
+ self.is_set(ArgSettings::MultipleValues)
+ }
+
+ /// [`Arg::multiple_occurrences`] is going away ([Issue #3772](https://github.com/clap-rs/clap/issues/3772))
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.2.0", note = "`multiple_occurrences` away (Issue #3772)")
+ )]
+ pub fn is_multiple_occurrences_set(&self) -> bool {
+ self.is_set(ArgSettings::MultipleOccurrences)
+ }
+
+ /// Report whether [`Arg::is_takes_value_set`] is set
+ pub fn is_takes_value_set(&self) -> bool {
+ self.is_set(ArgSettings::TakesValue)
+ }
+
+ /// Report whether [`Arg::allow_hyphen_values`] is set
+ pub fn is_allow_hyphen_values_set(&self) -> bool {
+ self.is_set(ArgSettings::AllowHyphenValues)
+ }
+
+ /// Deprecated, replaced with [`Arg::get_value_parser()`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.2.0", note = "Replaced with `Arg::get_value_parser()`")
+ )]
+ pub fn is_forbid_empty_values_set(&self) -> bool {
+ self.is_set(ArgSettings::ForbidEmptyValues)
+ }
+
+ /// Deprecated, replaced with [`Arg::get_value_parser()`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.2.0", note = "Replaced with `Arg::get_value_parser()`")
+ )]
+ pub fn is_allow_invalid_utf8_set(&self) -> bool {
+ self.is_set(ArgSettings::AllowInvalidUtf8)
+ }
+
+ /// Behavior when parsing the argument
+ pub fn get_action(&self) -> &super::ArgAction {
+ const DEFAULT: super::ArgAction = super::ArgAction::StoreValue;
+ self.action.as_ref().unwrap_or(&DEFAULT)
+ }
+
+ /// Configured parser for argument values
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// let cmd = clap::Command::new("raw")
+ /// .arg(
+ /// clap::Arg::new("port")
+ /// .value_parser(clap::value_parser!(usize))
+ /// );
+ /// let value_parser = cmd.get_arguments()
+ /// .find(|a| a.get_id() == "port").unwrap()
+ /// .get_value_parser();
+ /// println!("{:?}", value_parser);
+ /// ```
+ pub fn get_value_parser(&self) -> &super::ValueParser {
+ if let Some(value_parser) = self.value_parser.as_ref() {
+ value_parser
+ } else if self.is_allow_invalid_utf8_set() {
+ static DEFAULT: super::ValueParser = super::ValueParser::os_string();
+ &DEFAULT
+ } else {
+ static DEFAULT: super::ValueParser = super::ValueParser::string();
+ &DEFAULT
+ }
+ }
+
+ /// Report whether [`Arg::global`] is set
+ pub fn is_global_set(&self) -> bool {
+ self.is_set(ArgSettings::Global)
+ }
+
+ /// Report whether [`Arg::next_line_help`] is set
+ pub fn is_next_line_help_set(&self) -> bool {
+ self.is_set(ArgSettings::NextLineHelp)
+ }
+
+ /// Report whether [`Arg::hide`] is set
+ pub fn is_hide_set(&self) -> bool {
+ self.is_set(ArgSettings::Hidden)
+ }
+
+ /// Report whether [`Arg::hide_default_value`] is set
+ pub fn is_hide_default_value_set(&self) -> bool {
+ self.is_set(ArgSettings::HideDefaultValue)
+ }
+
+ /// Report whether [`Arg::hide_possible_values`] is set
+ pub fn is_hide_possible_values_set(&self) -> bool {
+ self.is_set(ArgSettings::HidePossibleValues)
+ }
+
+ /// Report whether [`Arg::hide_env`] is set
+ #[cfg(feature = "env")]
+ pub fn is_hide_env_set(&self) -> bool {
+ self.is_set(ArgSettings::HideEnv)
+ }
+
+ /// Report whether [`Arg::hide_env_values`] is set
+ #[cfg(feature = "env")]
+ pub fn is_hide_env_values_set(&self) -> bool {
+ self.is_set(ArgSettings::HideEnvValues)
+ }
+
+ /// Report whether [`Arg::hide_short_help`] is set
+ pub fn is_hide_short_help_set(&self) -> bool {
+ self.is_set(ArgSettings::HiddenShortHelp)
+ }
+
+ /// Report whether [`Arg::hide_long_help`] is set
+ pub fn is_hide_long_help_set(&self) -> bool {
+ self.is_set(ArgSettings::HiddenLongHelp)
+ }
+
+ /// Report whether [`Arg::use_value_delimiter`] is set
+ pub fn is_use_value_delimiter_set(&self) -> bool {
+ self.is_set(ArgSettings::UseValueDelimiter)
+ }
+
+ /// Report whether [`Arg::require_value_delimiter`] is set
+ pub fn is_require_value_delimiter_set(&self) -> bool {
+ self.is_set(ArgSettings::RequireDelimiter)
+ }
+
+ /// Report whether [`Arg::require_equals`] is set
+ pub fn is_require_equals_set(&self) -> bool {
+ self.is_set(ArgSettings::RequireEquals)
+ }
+
+ /// Reports whether [`Arg::exclusive`] is set
+ pub fn is_exclusive_set(&self) -> bool {
+ self.is_set(ArgSettings::Exclusive)
+ }
+
+ /// Reports whether [`Arg::last`] is set
+ pub fn is_last_set(&self) -> bool {
+ self.is_set(ArgSettings::Last)
+ }
+
+ /// Reports whether [`Arg::ignore_case`] is set
+ pub fn is_ignore_case_set(&self) -> bool {
+ self.is_set(ArgSettings::IgnoreCase)
+ }
+}
+
+/// # Deprecated
+impl<'help> Arg<'help> {
+ /// Deprecated, replaced with [`Arg::new`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `Arg::new`")
+ )]
+ #[doc(hidden)]
+ pub fn with_name<S: Into<&'help str>>(n: S) -> Self {
+ Self::new(n)
+ }
+
+ /// 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(y: &'help Yaml) -> Self {
+ #![allow(deprecated)]
+ let yaml_file_hash = y.as_hash().expect("YAML file must be a hash");
+ // We WANT this to panic on error...so expect() is good.
+ let (name_yaml, yaml) = yaml_file_hash
+ .iter()
+ .next()
+ .expect("There must be one arg in the YAML file");
+ let name_str = name_yaml.as_str().expect("Arg name must be a string");
+ let mut a = Arg::new(name_str);
+
+ for (k, v) in yaml.as_hash().expect("Arg must be a hash") {
+ a = match k.as_str().expect("Arg fields must be strings") {
+ "short" => yaml_to_char!(a, v, short),
+ "long" => yaml_to_str!(a, v, long),
+ "aliases" => yaml_vec_or_str!(a, v, alias),
+ "help" => yaml_to_str!(a, v, help),
+ "long_help" => yaml_to_str!(a, v, long_help),
+ "required" => yaml_to_bool!(a, v, required),
+ "required_if" => yaml_tuple2!(a, v, required_if_eq),
+ "required_ifs" => yaml_tuple2!(a, v, required_if_eq),
+ "takes_value" => yaml_to_bool!(a, v, takes_value),
+ "index" => yaml_to_usize!(a, v, index),
+ "global" => yaml_to_bool!(a, v, global),
+ "multiple" => yaml_to_bool!(a, v, multiple),
+ "hidden" => yaml_to_bool!(a, v, hide),
+ "next_line_help" => yaml_to_bool!(a, v, next_line_help),
+ "group" => yaml_to_str!(a, v, group),
+ "number_of_values" => yaml_to_usize!(a, v, number_of_values),
+ "max_values" => yaml_to_usize!(a, v, max_values),
+ "min_values" => yaml_to_usize!(a, v, min_values),
+ "value_name" => yaml_to_str!(a, v, value_name),
+ "use_delimiter" => yaml_to_bool!(a, v, use_delimiter),
+ "allow_hyphen_values" => yaml_to_bool!(a, v, allow_hyphen_values),
+ "last" => yaml_to_bool!(a, v, last),
+ "require_delimiter" => yaml_to_bool!(a, v, require_delimiter),
+ "value_delimiter" => yaml_to_char!(a, v, value_delimiter),
+ "required_unless" => yaml_to_str!(a, v, required_unless_present),
+ "display_order" => yaml_to_usize!(a, v, display_order),
+ "default_value" => yaml_to_str!(a, v, default_value),
+ "default_value_if" => yaml_tuple3!(a, v, default_value_if),
+ "default_value_ifs" => yaml_tuple3!(a, v, default_value_if),
+ #[cfg(feature = "env")]
+ "env" => yaml_to_str!(a, v, env),
+ "value_names" => yaml_vec_or_str!(a, v, value_name),
+ "groups" => yaml_vec_or_str!(a, v, group),
+ "requires" => yaml_vec_or_str!(a, v, requires),
+ "requires_if" => yaml_tuple2!(a, v, requires_if),
+ "requires_ifs" => yaml_tuple2!(a, v, requires_if),
+ "conflicts_with" => yaml_vec_or_str!(a, v, conflicts_with),
+ "overrides_with" => yaml_to_str!(a, v, overrides_with),
+ "possible_values" => yaml_vec_or_str!(a, v, possible_value),
+ "case_insensitive" => yaml_to_bool!(a, v, ignore_case),
+ "required_unless_one" => yaml_vec!(a, v, required_unless_present_any),
+ "required_unless_all" => yaml_vec!(a, v, required_unless_present_all),
+ s => {
+ panic!(
+ "Unknown setting '{}' in YAML file for arg '{}'",
+ s, name_str
+ )
+ }
+ }
+ }
+
+ a
+ }
+
+ /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!].
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!")
+ )]
+ #[doc(hidden)]
+ pub fn from_usage(u: &'help str) -> Self {
+ UsageParser::from_usage(u).parse()
+ }
+
+ /// Deprecated, replaced with [`Arg::required_unless_present`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `Arg::required_unless_present`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn required_unless<T: Key>(self, arg_id: T) -> Self {
+ self.required_unless_present(arg_id)
+ }
+
+ /// Deprecated, replaced with [`Arg::required_unless_present_all`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `Arg::required_unless_present_all`"
+ )
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn required_unless_all<T, I>(self, names: I) -> Self
+ where
+ I: IntoIterator<Item = T>,
+ T: Key,
+ {
+ self.required_unless_present_all(names)
+ }
+
+ /// Deprecated, replaced with [`Arg::required_unless_present_any`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `Arg::required_unless_present_any`"
+ )
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn required_unless_one<T, I>(self, names: I) -> Self
+ where
+ I: IntoIterator<Item = T>,
+ T: Key,
+ {
+ self.required_unless_present_any(names)
+ }
+
+ /// Deprecated, replaced with [`Arg::required_if_eq`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `Arg::required_if_eq`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn required_if<T: Key>(self, arg_id: T, val: &'help str) -> Self {
+ self.required_if_eq(arg_id, val)
+ }
+
+ /// Deprecated, replaced with [`Arg::required_if_eq_any`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `Arg::required_if_eq_any`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn required_ifs<T: Key>(self, ifs: &[(T, &'help str)]) -> Self {
+ self.required_if_eq_any(ifs)
+ }
+
+ /// Deprecated, replaced with [`Arg::hide`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `Arg::hide`")
+ )]
+ #[doc(hidden)]
+ #[inline]
+ #[must_use]
+ pub fn hidden(self, yes: bool) -> Self {
+ self.hide(yes)
+ }
+
+ /// Deprecated, replaced with [`Arg::ignore_case`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `Arg::ignore_case`")
+ )]
+ #[doc(hidden)]
+ #[inline]
+ #[must_use]
+ pub fn case_insensitive(self, yes: bool) -> Self {
+ self.ignore_case(yes)
+ }
+
+ /// Deprecated, replaced with [`Arg::forbid_empty_values`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `Arg::forbid_empty_values`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn empty_values(self, yes: bool) -> Self {
+ self.forbid_empty_values(!yes)
+ }
+
+ /// Deprecated, replaced with [`Arg::multiple_occurrences`] (most likely what you want) and
+ /// [`Arg::multiple_values`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Split into `Arg::multiple_occurrences` (most likely what you want) and `Arg::multiple_values`"
+ )
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn multiple(self, yes: bool) -> Self {
+ self.multiple_occurrences(yes).multiple_values(yes)
+ }
+
+ /// Deprecated, replaced with [`Arg::hide_short_help`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `Arg::hide_short_help`")
+ )]
+ #[doc(hidden)]
+ #[inline]
+ #[must_use]
+ pub fn hidden_short_help(self, yes: bool) -> Self {
+ self.hide_short_help(yes)
+ }
+
+ /// Deprecated, replaced with [`Arg::hide_long_help`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `Arg::hide_long_help`")
+ )]
+ #[doc(hidden)]
+ #[inline]
+ #[must_use]
+ pub fn hidden_long_help(self, yes: bool) -> Self {
+ self.hide_long_help(yes)
+ }
+
+ /// Deprecated, replaced with [`Arg::setting`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `Arg::setting`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn set(self, s: ArgSettings) -> Self {
+ self.setting(s)
+ }
+
+ /// Deprecated, replaced with [`Arg::unset_setting`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `Arg::unset_setting`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn unset(self, s: ArgSettings) -> Self {
+ self.unset_setting(s)
+ }
+}
+
+/// # Internally used only
+impl<'help> Arg<'help> {
+ pub(crate) fn _build(&mut self) {
+ if self.is_positional() {
+ self.settings.set(ArgSettings::TakesValue);
+ }
+ if let Some(action) = self.action.as_ref() {
+ if let Some(default_value) = action.default_value() {
+ if self.default_vals.is_empty() {
+ self.default_vals = vec![default_value];
+ }
+ }
+ if action.takes_values() {
+ self.settings.set(ArgSettings::TakesValue);
+ } else {
+ self.settings.unset(ArgSettings::TakesValue);
+ }
+ match action {
+ ArgAction::StoreValue
+ | ArgAction::IncOccurrence
+ | ArgAction::Help
+ | ArgAction::Version => {}
+ ArgAction::Set
+ | ArgAction::Append
+ | ArgAction::SetTrue
+ | ArgAction::SetFalse
+ | ArgAction::Count => {
+ if !self.is_positional() {
+ self.settings.set(ArgSettings::MultipleOccurrences);
+ }
+ }
+ }
+ }
+
+ if self.value_parser.is_none() {
+ if let Some(default) = self.action.as_ref().and_then(|a| a.default_value_parser()) {
+ self.value_parser = Some(default);
+ } else if self.is_allow_invalid_utf8_set() {
+ self.value_parser = Some(super::ValueParser::os_string());
+ } else {
+ self.value_parser = Some(super::ValueParser::string());
+ }
+ }
+
+ if (self.is_use_value_delimiter_set() || self.is_require_value_delimiter_set())
+ && self.val_delim.is_none()
+ {
+ self.val_delim = Some(',');
+ }
+
+ let val_names_len = self.val_names.len();
+
+ if val_names_len > 1 {
+ self.settings.set(ArgSettings::MultipleValues);
+
+ if self.num_vals.is_none() {
+ self.num_vals = Some(val_names_len);
+ }
+ }
+
+ let self_id = self.id.clone();
+ if self.is_positional() || self.is_multiple_occurrences_set() {
+ // Remove self-overrides where they don't make sense.
+ //
+ // We can evaluate switching this to a debug assert at a later time (though it will
+ // require changing propagation of `AllArgsOverrideSelf`). Being conservative for now
+ // due to where we are at in the release.
+ self.overrides.retain(|e| *e != self_id);
+ }
+ }
+
+ pub(crate) fn generated(mut self) -> Self {
+ self.provider = ArgProvider::Generated;
+ self
+ }
+
+ pub(crate) fn longest_filter(&self) -> bool {
+ self.is_takes_value_set() || self.long.is_some() || self.short.is_none()
+ }
+
+ // Used for positionals when printing
+ pub(crate) fn multiple_str(&self) -> &str {
+ let mult_vals = self.val_names.len() > 1;
+ if (self.is_multiple_values_set() || self.is_multiple_occurrences_set()) && !mult_vals {
+ "..."
+ } else {
+ ""
+ }
+ }
+
+ // Used for positionals when printing
+ pub(crate) fn name_no_brackets(&self) -> Cow<str> {
+ debug!("Arg::name_no_brackets:{}", self.name);
+ let delim = if self.is_require_value_delimiter_set() {
+ self.val_delim.expect(INTERNAL_ERROR_MSG)
+ } else {
+ ' '
+ }
+ .to_string();
+ if !self.val_names.is_empty() {
+ debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names);
+
+ if self.val_names.len() > 1 {
+ Cow::Owned(
+ self.val_names
+ .iter()
+ .map(|n| format!("<{}>", n))
+ .collect::<Vec<_>>()
+ .join(&*delim),
+ )
+ } else {
+ Cow::Borrowed(self.val_names.get(0).expect(INTERNAL_ERROR_MSG))
+ }
+ } else {
+ debug!("Arg::name_no_brackets: just name");
+ Cow::Borrowed(self.name)
+ }
+ }
+
+ /// Either multiple values or occurrences
+ pub(crate) fn is_multiple(&self) -> bool {
+ self.is_multiple_values_set() | self.is_multiple_occurrences_set()
+ }
+
+ pub(crate) fn get_display_order(&self) -> usize {
+ self.disp_ord.get_explicit()
+ }
+}
+
+impl<'help> From<&'_ Arg<'help>> for Arg<'help> {
+ fn from(a: &Arg<'help>) -> Self {
+ a.clone()
+ }
+}
+
+impl<'help> PartialEq for Arg<'help> {
+ fn eq(&self, other: &Arg<'help>) -> bool {
+ self.name == other.name
+ }
+}
+
+impl<'help> PartialOrd for Arg<'help> {
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+impl<'help> Ord for Arg<'help> {
+ fn cmp(&self, other: &Arg) -> Ordering {
+ self.name.cmp(other.name)
+ }
+}
+
+impl<'help> Eq for Arg<'help> {}
+
+impl<'help> Display for Arg<'help> {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ // Write the name such --long or -l
+ if let Some(l) = self.long {
+ write!(f, "--{}", l)?;
+ } else if let Some(s) = self.short {
+ write!(f, "-{}", s)?;
+ }
+ let mut need_closing_bracket = false;
+ if !self.is_positional() && self.is_takes_value_set() {
+ let is_optional_val = self.min_vals == Some(0);
+ let sep = if self.is_require_equals_set() {
+ if is_optional_val {
+ need_closing_bracket = true;
+ "[="
+ } else {
+ "="
+ }
+ } else if is_optional_val {
+ need_closing_bracket = true;
+ " ["
+ } else {
+ " "
+ };
+ f.write_str(sep)?;
+ }
+ if self.is_takes_value_set() || self.is_positional() {
+ display_arg_val(self, |s, _| f.write_str(s))?;
+ }
+ if need_closing_bracket {
+ f.write_str("]")?;
+ }
+
+ Ok(())
+ }
+}
+
+impl<'help> fmt::Debug for Arg<'help> {
+ fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
+ let mut ds = f.debug_struct("Arg");
+
+ #[allow(unused_mut)]
+ let mut ds = ds
+ .field("id", &self.id)
+ .field("provider", &self.provider)
+ .field("name", &self.name)
+ .field("help", &self.help)
+ .field("long_help", &self.long_help)
+ .field("action", &self.action)
+ .field("value_parser", &self.value_parser)
+ .field("blacklist", &self.blacklist)
+ .field("settings", &self.settings)
+ .field("overrides", &self.overrides)
+ .field("groups", &self.groups)
+ .field("requires", &self.requires)
+ .field("r_ifs", &self.r_ifs)
+ .field("r_unless", &self.r_unless)
+ .field("short", &self.short)
+ .field("long", &self.long)
+ .field("aliases", &self.aliases)
+ .field("short_aliases", &self.short_aliases)
+ .field("disp_ord", &self.disp_ord)
+ .field("possible_vals", &self.possible_vals)
+ .field("val_names", &self.val_names)
+ .field("num_vals", &self.num_vals)
+ .field("max_vals", &self.max_vals)
+ .field("min_vals", &self.min_vals)
+ .field(
+ "validator",
+ &self.validator.as_ref().map_or("None", |_| "Some(FnMut)"),
+ )
+ .field(
+ "validator_os",
+ &self.validator_os.as_ref().map_or("None", |_| "Some(FnMut)"),
+ )
+ .field("val_delim", &self.val_delim)
+ .field("default_vals", &self.default_vals)
+ .field("default_vals_ifs", &self.default_vals_ifs)
+ .field("terminator", &self.terminator)
+ .field("index", &self.index)
+ .field("help_heading", &self.help_heading)
+ .field("value_hint", &self.value_hint)
+ .field("default_missing_vals", &self.default_missing_vals);
+
+ #[cfg(feature = "env")]
+ {
+ ds = ds.field("env", &self.env);
+ }
+
+ ds.finish()
+ }
+}
+
+type Validator<'a> = dyn FnMut(&str) -> Result<(), Box<dyn Error + Send + Sync>> + Send + 'a;
+type ValidatorOs<'a> = dyn FnMut(&OsStr) -> Result<(), Box<dyn Error + Send + Sync>> + Send + 'a;
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub(crate) enum ArgProvider {
+ Generated,
+ GeneratedMutated,
+ User,
+}
+
+impl Default for ArgProvider {
+ fn default() -> Self {
+ ArgProvider::User
+ }
+}
+
+/// Write the values such as <name1> <name2>
+pub(crate) fn display_arg_val<F, T, E>(arg: &Arg, mut write: F) -> Result<(), E>
+where
+ F: FnMut(&str, bool) -> Result<T, E>,
+{
+ let mult_val = arg.is_multiple_values_set();
+ let mult_occ = arg.is_multiple_occurrences_set();
+ let delim = if arg.is_require_value_delimiter_set() {
+ arg.val_delim.expect(INTERNAL_ERROR_MSG)
+ } else {
+ ' '
+ }
+ .to_string();
+ if !arg.val_names.is_empty() {
+ // If have val_name.
+ match (arg.val_names.len(), arg.num_vals) {
+ (1, Some(num_vals)) => {
+ // If single value name with multiple num_of_vals, display all
+ // the values with the single value name.
+ let arg_name = format!("<{}>", arg.val_names.get(0).unwrap());
+ for n in 1..=num_vals {
+ write(&arg_name, true)?;
+ if n != num_vals {
+ write(&delim, false)?;
+ }
+ }
+ }
+ (num_val_names, _) => {
+ // If multiple value names, display them sequentially(ignore num of vals).
+ let mut it = arg.val_names.iter().peekable();
+ while let Some(val) = it.next() {
+ write(&format!("<{}>", val), true)?;
+ if it.peek().is_some() {
+ write(&delim, false)?;
+ }
+ }
+ if (num_val_names == 1 && mult_val)
+ || (arg.is_positional() && mult_occ)
+ || num_val_names < arg.num_vals.unwrap_or(0)
+ {
+ write("...", true)?;
+ }
+ }
+ }
+ } else if let Some(num_vals) = arg.num_vals {
+ // If number_of_values is specified, display the value multiple times.
+ let arg_name = format!("<{}>", arg.name);
+ for n in 1..=num_vals {
+ write(&arg_name, true)?;
+ if n != num_vals {
+ write(&delim, false)?;
+ }
+ }
+ } else if arg.is_positional() {
+ // Value of positional argument with no num_vals and val_names.
+ write(&format!("<{}>", arg.name), true)?;
+
+ if mult_val || mult_occ {
+ write("...", true)?;
+ }
+ } else {
+ // value of flag argument with no num_vals and val_names.
+ write(&format!("<{}>", arg.name), true)?;
+ if mult_val {
+ write("...", true)?;
+ }
+ }
+ Ok(())
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
+pub(crate) enum DisplayOrder {
+ None,
+ Implicit(usize),
+ Explicit(usize),
+}
+
+impl DisplayOrder {
+ pub(crate) fn set_explicit(&mut self, explicit: usize) {
+ *self = Self::Explicit(explicit)
+ }
+
+ pub(crate) fn set_implicit(&mut self, implicit: usize) {
+ *self = (*self).max(Self::Implicit(implicit))
+ }
+
+ pub(crate) fn make_explicit(&mut self) {
+ match *self {
+ Self::None | Self::Explicit(_) => {}
+ Self::Implicit(disp) => self.set_explicit(disp),
+ }
+ }
+
+ pub(crate) fn get_explicit(self) -> usize {
+ match self {
+ Self::None | Self::Implicit(_) => 999,
+ Self::Explicit(disp) => disp,
+ }
+ }
+}
+
+impl Default for DisplayOrder {
+ fn default() -> Self {
+ Self::None
+ }
+}
+
+// Flags
+#[cfg(test)]
+mod test {
+ use super::Arg;
+
+ #[test]
+ fn flag_display() {
+ let mut f = Arg::new("flg").multiple_occurrences(true);
+ f.long = Some("flag");
+
+ assert_eq!(f.to_string(), "--flag");
+
+ let mut f2 = Arg::new("flg");
+ f2.short = Some('f');
+
+ assert_eq!(f2.to_string(), "-f");
+ }
+
+ #[test]
+ fn flag_display_single_alias() {
+ let mut f = Arg::new("flg");
+ f.long = Some("flag");
+ f.aliases = vec![("als", true)];
+
+ assert_eq!(f.to_string(), "--flag")
+ }
+
+ #[test]
+ fn flag_display_multiple_aliases() {
+ let mut f = Arg::new("flg");
+ f.short = Some('f');
+ f.aliases = vec![
+ ("alias_not_visible", false),
+ ("f2", true),
+ ("f3", true),
+ ("f4", true),
+ ];
+ assert_eq!(f.to_string(), "-f");
+ }
+
+ #[test]
+ fn flag_display_single_short_alias() {
+ let mut f = Arg::new("flg");
+ f.short = Some('a');
+ f.short_aliases = vec![('b', true)];
+
+ assert_eq!(f.to_string(), "-a")
+ }
+
+ #[test]
+ fn flag_display_multiple_short_aliases() {
+ let mut f = Arg::new("flg");
+ f.short = Some('a');
+ f.short_aliases = vec![('b', false), ('c', true), ('d', true), ('e', true)];
+ assert_eq!(f.to_string(), "-a");
+ }
+
+ // Options
+
+ #[test]
+ fn option_display_multiple_occurrences() {
+ let o = Arg::new("opt")
+ .long("option")
+ .takes_value(true)
+ .multiple_occurrences(true);
+
+ assert_eq!(o.to_string(), "--option <opt>");
+ }
+
+ #[test]
+ fn option_display_multiple_values() {
+ let o = Arg::new("opt")
+ .long("option")
+ .takes_value(true)
+ .multiple_values(true);
+
+ assert_eq!(o.to_string(), "--option <opt>...");
+ }
+
+ #[test]
+ fn option_display2() {
+ let o2 = Arg::new("opt").short('o').value_names(&["file", "name"]);
+
+ assert_eq!(o2.to_string(), "-o <file> <name>");
+ }
+
+ #[test]
+ fn option_display3() {
+ let o2 = Arg::new("opt")
+ .short('o')
+ .takes_value(true)
+ .multiple_values(true)
+ .value_names(&["file", "name"]);
+
+ assert_eq!(o2.to_string(), "-o <file> <name>");
+ }
+
+ #[test]
+ fn option_display_single_alias() {
+ let o = Arg::new("opt")
+ .takes_value(true)
+ .long("option")
+ .visible_alias("als");
+
+ assert_eq!(o.to_string(), "--option <opt>");
+ }
+
+ #[test]
+ fn option_display_multiple_aliases() {
+ let o = Arg::new("opt")
+ .long("option")
+ .takes_value(true)
+ .visible_aliases(&["als2", "als3", "als4"])
+ .alias("als_not_visible");
+
+ assert_eq!(o.to_string(), "--option <opt>");
+ }
+
+ #[test]
+ fn option_display_single_short_alias() {
+ let o = Arg::new("opt")
+ .takes_value(true)
+ .short('a')
+ .visible_short_alias('b');
+
+ assert_eq!(o.to_string(), "-a <opt>");
+ }
+
+ #[test]
+ fn option_display_multiple_short_aliases() {
+ let o = Arg::new("opt")
+ .short('a')
+ .takes_value(true)
+ .visible_short_aliases(&['b', 'c', 'd'])
+ .short_alias('e');
+
+ assert_eq!(o.to_string(), "-a <opt>");
+ }
+
+ // Positionals
+
+ #[test]
+ fn positional_display_multiple_values() {
+ let p = Arg::new("pos")
+ .index(1)
+ .takes_value(true)
+ .multiple_values(true);
+
+ assert_eq!(p.to_string(), "<pos>...");
+ }
+
+ #[test]
+ fn positional_display_multiple_occurrences() {
+ let p = Arg::new("pos")
+ .index(1)
+ .takes_value(true)
+ .multiple_occurrences(true);
+
+ assert_eq!(p.to_string(), "<pos>...");
+ }
+
+ #[test]
+ fn positional_display_required() {
+ let p2 = Arg::new("pos").index(1).required(true);
+
+ assert_eq!(p2.to_string(), "<pos>");
+ }
+
+ #[test]
+ fn positional_display_val_names() {
+ let p2 = Arg::new("pos").index(1).value_names(&["file1", "file2"]);
+
+ assert_eq!(p2.to_string(), "<file1> <file2>");
+ }
+
+ #[test]
+ fn positional_display_val_names_req() {
+ let p2 = Arg::new("pos")
+ .index(1)
+ .required(true)
+ .value_names(&["file1", "file2"]);
+
+ assert_eq!(p2.to_string(), "<file1> <file2>");
+ }
+}
diff --git a/3.2.23/src/builder/arg_group.rs b/3.2.23/src/builder/arg_group.rs
new file mode 100644
index 0000000..76a310e
--- /dev/null
+++ b/3.2.23/src/builder/arg_group.rs
@@ -0,0 +1,641 @@
+// Internal
+use crate::util::{Id, Key};
+
+#[cfg(feature = "yaml")]
+use yaml_rust::Yaml;
+
+/// Family of related [arguments].
+///
+/// By placing arguments in a logical group, you can create easier requirement and
+/// exclusion rules instead of having to list each argument individually, or when you want a rule
+/// to apply "any but not all" arguments.
+///
+/// For instance, you can make an entire `ArgGroup` required. If [`ArgGroup::multiple(true)`] is
+/// set, this means that at least one argument from that group must be present. If
+/// [`ArgGroup::multiple(false)`] is set (the default), one and *only* one must be present.
+///
+/// You can also do things such as name an entire `ArgGroup` as a [conflict] or [requirement] for
+/// another argument, meaning any of the arguments that belong to that group will cause a failure
+/// if present, or must be present respectively.
+///
+/// Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be
+/// present out of a given set. Imagine that you had multiple arguments, and you want one of them
+/// to be required, but making all of them required isn't feasible because perhaps they conflict
+/// with each other. For example, lets say that you were building an application where one could
+/// set a given version number by supplying a string with an option argument, i.e.
+/// `--set-ver v1.2.3`, you also wanted to support automatically using a previous version number
+/// and simply incrementing one of the three numbers. So you create three flags `--major`,
+/// `--minor`, and `--patch`. All of these arguments shouldn't be used at one time but you want to
+/// specify that *at least one* of them is used. For this, you can create a group.
+///
+/// Finally, you may use `ArgGroup`s to pull a value from a group of arguments when you don't care
+/// exactly which argument was actually used at runtime.
+///
+/// # Examples
+///
+/// The following example demonstrates using an `ArgGroup` to ensure that one, and only one, of
+/// the arguments from the specified group is present at runtime.
+///
+/// ```rust
+/// # use clap::{Command, arg, ArgGroup, ErrorKind};
+/// let result = Command::new("cmd")
+/// .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
+/// .arg(arg!(--major "auto increase major"))
+/// .arg(arg!(--minor "auto increase minor"))
+/// .arg(arg!(--patch "auto increase patch"))
+/// .group(ArgGroup::new("vers")
+/// .args(&["set-ver", "major", "minor", "patch"])
+/// .required(true))
+/// .try_get_matches_from(vec!["cmd", "--major", "--patch"]);
+/// // Because we used two args in the group it's an error
+/// assert!(result.is_err());
+/// let err = result.unwrap_err();
+/// assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
+/// ```
+/// This next example shows a passing parse of the same scenario
+///
+/// ```rust
+/// # use clap::{Command, arg, ArgGroup};
+/// let result = Command::new("cmd")
+/// .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
+/// .arg(arg!(--major "auto increase major"))
+/// .arg(arg!(--minor "auto increase minor"))
+/// .arg(arg!(--patch "auto increase patch"))
+/// .group(ArgGroup::new("vers")
+/// .args(&["set-ver", "major", "minor","patch"])
+/// .required(true))
+/// .try_get_matches_from(vec!["cmd", "--major"]);
+/// assert!(result.is_ok());
+/// let matches = result.unwrap();
+/// // We may not know which of the args was used, so we can test for the group...
+/// assert!(matches.contains_id("vers"));
+/// // we could also alternatively check each arg individually (not shown here)
+/// ```
+/// [`ArgGroup::multiple(true)`]: ArgGroup::multiple()
+///
+/// [`ArgGroup::multiple(false)`]: ArgGroup::multiple()
+/// [arguments]: crate::Arg
+/// [conflict]: crate::Arg::conflicts_with()
+/// [requirement]: crate::Arg::requires()
+#[derive(Default, Debug, PartialEq, Eq)]
+pub struct ArgGroup<'help> {
+ pub(crate) id: Id,
+ pub(crate) name: &'help str,
+ pub(crate) args: Vec<Id>,
+ pub(crate) required: bool,
+ pub(crate) requires: Vec<Id>,
+ pub(crate) conflicts: Vec<Id>,
+ pub(crate) multiple: bool,
+}
+
+impl<'help> ArgGroup<'help> {
+ pub(crate) fn with_id(id: Id) -> Self {
+ ArgGroup {
+ id,
+ ..ArgGroup::default()
+ }
+ }
+
+ /// Create a `ArgGroup` using a unique name.
+ ///
+ /// The name will be used to get values from the group or refer to the group inside of conflict
+ /// and requirement rules.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, ArgGroup};
+ /// ArgGroup::new("config")
+ /// # ;
+ /// ```
+ pub fn new<S: Into<&'help str>>(n: S) -> Self {
+ ArgGroup::default().id(n)
+ }
+
+ /// Sets the group name.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, ArgGroup};
+ /// ArgGroup::default().name("config")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn id<S: Into<&'help str>>(mut self, n: S) -> Self {
+ self.name = n.into();
+ self.id = Id::from(self.name);
+ self
+ }
+
+ /// Deprecated, replaced with [`ArgGroup::id`]
+ ///
+ /// Builder: replaced `group.name(...)` with `group.id(...)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `ArgGroup::id`
+
+Builder: replaced `group.name(...)` with `group.id(...)`
+"
+ )
+ )]
+ pub fn name<S: Into<&'help str>>(self, n: S) -> Self {
+ self.id(n)
+ }
+
+ /// Adds an [argument] to this group by name
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f'))
+ /// .arg(Arg::new("color")
+ /// .short('c'))
+ /// .group(ArgGroup::new("req_flags")
+ /// .arg("flag")
+ /// .arg("color"))
+ /// .get_matches_from(vec!["myprog", "-f"]);
+ /// // maybe we don't know which of the two flags was used...
+ /// assert!(m.contains_id("req_flags"));
+ /// // but we can also check individually if needed
+ /// assert!(m.contains_id("flag"));
+ /// ```
+ /// [argument]: crate::Arg
+ #[must_use]
+ pub fn arg<T: Key>(mut self, arg_id: T) -> Self {
+ self.args.push(arg_id.into());
+ self
+ }
+
+ /// Adds multiple [arguments] to this group by name
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f'))
+ /// .arg(Arg::new("color")
+ /// .short('c'))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(&["flag", "color"]))
+ /// .get_matches_from(vec!["myprog", "-f"]);
+ /// // maybe we don't know which of the two flags was used...
+ /// assert!(m.contains_id("req_flags"));
+ /// // but we can also check individually if needed
+ /// assert!(m.contains_id("flag"));
+ /// ```
+ /// [arguments]: crate::Arg
+ #[must_use]
+ pub fn args<T: Key>(mut self, ns: &[T]) -> Self {
+ for n in ns {
+ self = self.arg(n);
+ }
+ self
+ }
+
+ /// Allows more than one of the [`Arg`]s in this group to be used. (Default: `false`)
+ ///
+ /// # Examples
+ ///
+ /// Notice in this example we use *both* the `-f` and `-c` flags which are both part of the
+ /// group
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f'))
+ /// .arg(Arg::new("color")
+ /// .short('c'))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(&["flag", "color"])
+ /// .multiple(true))
+ /// .get_matches_from(vec!["myprog", "-f", "-c"]);
+ /// // maybe we don't know which of the two flags was used...
+ /// assert!(m.contains_id("req_flags"));
+ /// ```
+ /// In this next example, we show the default behavior (i.e. `multiple(false)) which will throw
+ /// an error if more than one of the args in the group was used.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, ErrorKind};
+ /// let result = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f'))
+ /// .arg(Arg::new("color")
+ /// .short('c'))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(&["flag", "color"]))
+ /// .try_get_matches_from(vec!["myprog", "-f", "-c"]);
+ /// // Because we used both args in the group it's an error
+ /// assert!(result.is_err());
+ /// let err = result.unwrap_err();
+ /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
+ /// ```
+ ///
+ /// [`Arg`]: crate::Arg
+ #[inline]
+ #[must_use]
+ pub fn multiple(mut self, yes: bool) -> Self {
+ self.multiple = yes;
+ self
+ }
+
+ /// Require an argument from the group to be present when parsing.
+ ///
+ /// This is unless conflicting with another argument. A required group will be displayed in
+ /// the usage string of the application in the format `<arg|arg2|arg3>`.
+ ///
+ /// **NOTE:** This setting only applies to the current [`Command`] / [`Subcommand`]s, and not
+ /// globally.
+ ///
+ /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with
+ /// `ArgGroup::required(true)` states, "One and *only one* arg must be used from this group.
+ /// Use of more than one arg is an error." Vice setting `ArgGroup::multiple(true)` which
+ /// states, '*At least* one arg from this group must be used. Using multiple is OK."
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, ErrorKind};
+ /// let result = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f'))
+ /// .arg(Arg::new("color")
+ /// .short('c'))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(&["flag", "color"])
+ /// .required(true))
+ /// .try_get_matches_from(vec!["myprog"]);
+ /// // Because we didn't use any of the args in the group, it's an error
+ /// assert!(result.is_err());
+ /// let err = result.unwrap_err();
+ /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ ///
+ /// [`Subcommand`]: crate::Subcommand
+ /// [`ArgGroup::multiple`]: ArgGroup::multiple()
+ /// [`Command`]: crate::Command
+ #[inline]
+ #[must_use]
+ pub fn required(mut self, yes: bool) -> Self {
+ self.required = yes;
+ self
+ }
+
+ /// Specify an argument or group that must be present when this group is.
+ ///
+ /// This is not to be confused with a [required group]. Requirement rules function just like
+ /// [argument requirement rules], you can name other arguments or groups that must be present
+ /// when any one of the arguments from this group is used.
+ ///
+ /// **NOTE:** The name provided may be an argument or group name
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, ErrorKind};
+ /// let result = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f'))
+ /// .arg(Arg::new("color")
+ /// .short('c'))
+ /// .arg(Arg::new("debug")
+ /// .short('d'))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(&["flag", "color"])
+ /// .requires("debug"))
+ /// .try_get_matches_from(vec!["myprog", "-c"]);
+ /// // because we used an arg from the group, and the group requires "-d" to be used, it's an
+ /// // error
+ /// assert!(result.is_err());
+ /// let err = result.unwrap_err();
+ /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [required group]: ArgGroup::required()
+ /// [argument requirement rules]: crate::Arg::requires()
+ #[must_use]
+ pub fn requires<T: Key>(mut self, id: T) -> Self {
+ self.requires.push(id.into());
+ self
+ }
+
+ /// Specify arguments or groups that must be present when this group is.
+ ///
+ /// This is not to be confused with a [required group]. Requirement rules function just like
+ /// [argument requirement rules], you can name other arguments or groups that must be present
+ /// when one of the arguments from this group is used.
+ ///
+ /// **NOTE:** The names provided may be an argument or group name
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, ErrorKind};
+ /// let result = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f'))
+ /// .arg(Arg::new("color")
+ /// .short('c'))
+ /// .arg(Arg::new("debug")
+ /// .short('d'))
+ /// .arg(Arg::new("verb")
+ /// .short('v'))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(&["flag", "color"])
+ /// .requires_all(&["debug", "verb"]))
+ /// .try_get_matches_from(vec!["myprog", "-c", "-d"]);
+ /// // because we used an arg from the group, and the group requires "-d" and "-v" to be used,
+ /// // yet we only used "-d" it's an error
+ /// assert!(result.is_err());
+ /// let err = result.unwrap_err();
+ /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [required group]: ArgGroup::required()
+ /// [argument requirement rules]: crate::Arg::requires_all()
+ #[must_use]
+ pub fn requires_all(mut self, ns: &[&'help str]) -> Self {
+ for n in ns {
+ self = self.requires(n);
+ }
+ self
+ }
+
+ /// Specify an argument or group that must **not** be present when this group is.
+ ///
+ /// Exclusion (aka conflict) rules function just like [argument exclusion rules], you can name
+ /// other arguments or groups that must *not* be present when one of the arguments from this
+ /// group are used.
+ ///
+ /// **NOTE:** The name provided may be an argument, or group name
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, ErrorKind};
+ /// let result = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f'))
+ /// .arg(Arg::new("color")
+ /// .short('c'))
+ /// .arg(Arg::new("debug")
+ /// .short('d'))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(&["flag", "color"])
+ /// .conflicts_with("debug"))
+ /// .try_get_matches_from(vec!["myprog", "-c", "-d"]);
+ /// // because we used an arg from the group, and the group conflicts with "-d", it's an error
+ /// assert!(result.is_err());
+ /// let err = result.unwrap_err();
+ /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
+ /// ```
+ /// [argument exclusion rules]: crate::Arg::conflicts_with()
+ #[must_use]
+ pub fn conflicts_with<T: Key>(mut self, id: T) -> Self {
+ self.conflicts.push(id.into());
+ self
+ }
+
+ /// Specify arguments or groups that must **not** be present when this group is.
+ ///
+ /// Exclusion rules function just like [argument exclusion rules], you can name other arguments
+ /// or groups that must *not* be present when one of the arguments from this group are used.
+ ///
+ /// **NOTE:** The names provided may be an argument, or group name
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, ErrorKind};
+ /// let result = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f'))
+ /// .arg(Arg::new("color")
+ /// .short('c'))
+ /// .arg(Arg::new("debug")
+ /// .short('d'))
+ /// .arg(Arg::new("verb")
+ /// .short('v'))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(&["flag", "color"])
+ /// .conflicts_with_all(&["debug", "verb"]))
+ /// .try_get_matches_from(vec!["myprog", "-c", "-v"]);
+ /// // because we used an arg from the group, and the group conflicts with either "-v" or "-d"
+ /// // it's an error
+ /// assert!(result.is_err());
+ /// let err = result.unwrap_err();
+ /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
+ /// ```
+ ///
+ /// [argument exclusion rules]: crate::Arg::conflicts_with_all()
+ #[must_use]
+ pub fn conflicts_with_all(mut self, ns: &[&'help str]) -> Self {
+ for n in ns {
+ self = self.conflicts_with(n);
+ }
+ self
+ }
+
+ /// Deprecated, replaced with [`ArgGroup::new`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `ArgGroup::new`")
+ )]
+ #[doc(hidden)]
+ pub fn with_name<S: Into<&'help str>>(n: S) -> Self {
+ Self::new(n)
+ }
+
+ /// 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 = "Maybe clap::Parser would fit your use case? (Issue #3087)"
+ )
+ )]
+ #[doc(hidden)]
+ pub fn from_yaml(yaml: &'help Yaml) -> Self {
+ Self::from(yaml)
+ }
+}
+
+impl<'help> From<&'_ ArgGroup<'help>> for ArgGroup<'help> {
+ fn from(g: &ArgGroup<'help>) -> Self {
+ ArgGroup {
+ id: g.id.clone(),
+ name: g.name,
+ required: g.required,
+ args: g.args.clone(),
+ requires: g.requires.clone(),
+ conflicts: g.conflicts.clone(),
+ multiple: g.multiple,
+ }
+ }
+}
+
+/// 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")]
+impl<'help> From<&'help Yaml> for ArgGroup<'help> {
+ /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case?
+ fn from(y: &'help Yaml) -> Self {
+ let b = y.as_hash().expect("ArgGroup::from::<Yaml> expects a table");
+ // We WANT this to panic on error...so expect() is good.
+ let mut a = ArgGroup::default();
+ let group_settings = if b.len() == 1 {
+ let name_yaml = b.keys().next().expect("failed to get name");
+ let name_str = name_yaml
+ .as_str()
+ .expect("failed to convert arg YAML name to str");
+ a.name = name_str;
+ a.id = Id::from(&a.name);
+ b.get(name_yaml)
+ .expect("failed to get name_str")
+ .as_hash()
+ .expect("failed to convert to a hash")
+ } else {
+ b
+ };
+
+ for (k, v) in group_settings {
+ a = match k.as_str().unwrap() {
+ "required" => a.required(v.as_bool().unwrap()),
+ "multiple" => a.multiple(v.as_bool().unwrap()),
+ "args" => yaml_vec_or_str!(a, v, arg),
+ "arg" => {
+ if let Some(ys) = v.as_str() {
+ a = a.arg(ys);
+ }
+ a
+ }
+ "requires" => yaml_vec_or_str!(a, v, requires),
+ "conflicts_with" => yaml_vec_or_str!(a, v, conflicts_with),
+ "name" => {
+ if let Some(ys) = v.as_str() {
+ a = a.id(ys);
+ }
+ a
+ }
+ s => panic!(
+ "Unknown ArgGroup setting '{}' in YAML file for \
+ ArgGroup '{}'",
+ s, a.name
+ ),
+ }
+ }
+
+ a
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::ArgGroup;
+ #[cfg(feature = "yaml")]
+ use yaml_rust::YamlLoader;
+
+ #[test]
+ fn groups() {
+ let g = ArgGroup::new("test")
+ .arg("a1")
+ .arg("a4")
+ .args(&["a2", "a3"])
+ .required(true)
+ .conflicts_with("c1")
+ .conflicts_with_all(&["c2", "c3"])
+ .conflicts_with("c4")
+ .requires("r1")
+ .requires_all(&["r2", "r3"])
+ .requires("r4");
+
+ let args = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()];
+ let reqs = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()];
+ let confs = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()];
+
+ assert_eq!(g.args, args);
+ assert_eq!(g.requires, reqs);
+ assert_eq!(g.conflicts, confs);
+ }
+
+ #[test]
+ fn test_from() {
+ let g = ArgGroup::new("test")
+ .arg("a1")
+ .arg("a4")
+ .args(&["a2", "a3"])
+ .required(true)
+ .conflicts_with("c1")
+ .conflicts_with_all(&["c2", "c3"])
+ .conflicts_with("c4")
+ .requires("r1")
+ .requires_all(&["r2", "r3"])
+ .requires("r4");
+
+ let args = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()];
+ let reqs = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()];
+ let confs = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()];
+
+ let g2 = ArgGroup::from(&g);
+ assert_eq!(g2.args, args);
+ assert_eq!(g2.requires, reqs);
+ assert_eq!(g2.conflicts, confs);
+ }
+
+ #[cfg(feature = "yaml")]
+ #[test]
+ fn test_yaml() {
+ let g_yaml = "name: test
+args:
+- a1
+- a4
+- a2
+- a3
+conflicts_with:
+- c1
+- c2
+- c3
+- c4
+requires:
+- r1
+- r2
+- r3
+- r4";
+ let yaml = &YamlLoader::load_from_str(g_yaml).expect("failed to load YAML file")[0];
+ let g = ArgGroup::from(yaml);
+ let args = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()];
+ let reqs = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()];
+ let confs = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()];
+ assert_eq!(g.args, args);
+ assert_eq!(g.requires, reqs);
+ assert_eq!(g.conflicts, confs);
+ }
+
+ // This test will *fail to compile* if ArgGroup is not Send + Sync
+ #[test]
+ fn arg_group_send_sync() {
+ fn foo<T: Send + Sync>(_: T) {}
+ foo(ArgGroup::new("test"))
+ }
+}
+
+impl Clone for ArgGroup<'_> {
+ fn clone(&self) -> Self {
+ ArgGroup {
+ id: self.id.clone(),
+ name: self.name,
+ required: self.required,
+ args: self.args.clone(),
+ requires: self.requires.clone(),
+ conflicts: self.conflicts.clone(),
+ multiple: self.multiple,
+ }
+ }
+}
diff --git a/3.2.23/src/builder/arg_predicate.rs b/3.2.23/src/builder/arg_predicate.rs
new file mode 100644
index 0000000..58eb549
--- /dev/null
+++ b/3.2.23/src/builder/arg_predicate.rs
@@ -0,0 +1,14 @@
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub(crate) enum ArgPredicate<'help> {
+ IsPresent,
+ Equals(&'help std::ffi::OsStr),
+}
+
+impl<'help> From<Option<&'help std::ffi::OsStr>> for ArgPredicate<'help> {
+ fn from(other: Option<&'help std::ffi::OsStr>) -> Self {
+ match other {
+ Some(other) => Self::Equals(other),
+ None => Self::IsPresent,
+ }
+ }
+}
diff --git a/3.2.23/src/builder/arg_settings.rs b/3.2.23/src/builder/arg_settings.rs
new file mode 100644
index 0000000..1598d04
--- /dev/null
+++ b/3.2.23/src/builder/arg_settings.rs
@@ -0,0 +1,684 @@
+#![allow(deprecated)]
+
+// Std
+use std::ops::BitOr;
+#[cfg(feature = "yaml")]
+use std::str::FromStr;
+
+// Third party
+use bitflags::bitflags;
+
+#[allow(unused)]
+use crate::Arg;
+
+#[doc(hidden)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ArgFlags(Flags);
+
+impl Default for ArgFlags {
+ fn default() -> Self {
+ Self::empty()
+ }
+}
+
+/// Various settings that apply to arguments and may be set, unset, and checked via getter/setter
+/// methods [`Arg::setting`], [`Arg::unset_setting`], and [`Arg::is_set`]. This is what the
+/// [`Arg`] methods which accept a `bool` use internally.
+///
+/// [`Arg`]: crate::Arg
+/// [`Arg::setting`]: crate::Arg::setting()
+/// [`Arg::unset_setting`]: crate::Arg::unset_setting()
+/// [`Arg::is_set`]: crate::Arg::is_set()
+#[derive(Debug, PartialEq, Copy, Clone)]
+#[non_exhaustive]
+pub enum ArgSettings {
+ /// Deprecated, replaced with [`Arg::required`] and [`Arg::is_required_set`]
+ ///
+ /// Derive: replace `#[clap(setting = Required)]` with `#[clap(required = true)]`
+ ///
+ /// Builder: replace `arg.setting(Required)` with `arg.required(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::required` and `Arg::is_required_set`
+
+Derive: replace `#[clap(setting = Required)]` with `#[clap(required = true)]`
+
+Builder: replace `arg.setting(Required)` with `arg.required(true)`
+"
+ )
+ )]
+ Required,
+ /// Deprecated, replaced with [`Arg::multiple_values`] and [`Arg::is_multiple_values_set`]
+ ///
+ /// Derive: replace `#[clap(setting = MultipleValues)]` with `#[clap(multiple_values = true)]`
+ ///
+ /// Builder: replace `arg.setting(MultipleValues)` with `arg.multiple_values(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::multiple_values` and `Arg::`is_multiple_values_set`
+
+Derive: replace `#[clap(setting = MultipleValues)]` with `#[clap(multiple_values = true)]`
+
+Builder: replace `arg.setting(MultipleValues)` with `arg.multiple_values(true)`
+"
+ )
+ )]
+ MultipleValues,
+ /// 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::action` (Issue #3772)
+
+Builder: replace `arg.setting(MultipleOccurrences)` with `arg.action(ArgAction::Append)` when taking a value and `arg.action(ArgAction::Count)` with `matches.get_count` when not
+"
+ )
+ )]
+ MultipleOccurrences,
+ /// Deprecated, see [`ArgSettings::MultipleOccurrences`] (most likely what you want) and
+ /// [`ArgSettings::MultipleValues`]
+ ///
+ /// Derive: replace `#[clap(setting = Multiple)]` with `#[clap(multiple_values = true, multiple_occurrences = true)]`
+ ///
+ /// Builder: replace `arg.setting(Multiple)` with `arg.multiple_values(true).multiple_occurrences(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Split into `Arg::multiple_occurrences` (most likely what you want) and `Arg::multiple_values`
+
+Derive: replace `#[clap(setting = Multiple)]` with `#[clap(multiple_values = true, multiple_occurrences = true)]`
+
+Builder: replace `arg.setting(Multiple)` with `arg.multiple_values(true).multiple_occurrences(true)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ Multiple,
+ /// Deprecated, replaced with [`Arg::value_parser(NonEmptyStringValueParser::new())`]
+ ///
+ /// Derive: replace `#[clap(setting = ForbidEmptyValues)]` with `#[clap(value_parser = NonEmptyStringValueParser::new())]`
+ ///
+ /// Builder: replace `arg.setting(Multiple)` with `arg.value_parser(NonEmptyStringValueParser::new())`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::value_parser(NonEmptyStringValueParser::new())`
+
+Derive: replace `#[clap(setting = ForbidEmptyValues)]` with `#[clap(value_parser = NonEmptyStringValueParser::new())]`
+
+Builder: replace `arg.setting(Multiple)` with `arg.value_parser(NonEmptyStringValueParser::new())`
+"
+ )
+ )]
+ ForbidEmptyValues,
+ /// Deprecated, replaced with [`Arg::global`] and [`Arg::is_global_set`]
+ ///
+ /// Derive: replace `#[clap(setting = Global)]` with `#[clap(global = true)]`
+ ///
+ /// Builder: replace `arg.setting(Global)` with `arg.global(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::global` and `Arg::is_global_set`
+
+Derive: replace `#[clap(setting = Global)]` with `#[clap(global = true)]`
+
+Builder: replace `arg.setting(Global)` with `arg.global(true)`
+"
+ )
+ )]
+ Global,
+ /// Deprecated, replaced with [`Arg::hide`] and [`Arg::is_hide_set`]
+ ///
+ /// Derive: replace `#[clap(setting = Hidden)]` with `#[clap(hide = true)]`
+ ///
+ /// Builder: replace `arg.setting(Hidden)` with `arg.hide(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::hide` and `Arg::is_hide_set`
+
+Derive: replace `#[clap(setting = Hidden)]` with `#[clap(hide = true)]`
+
+Builder: replace `arg.setting(Hidden)` with `arg.hide(true)`
+"
+ )
+ )]
+ Hidden,
+ /// Deprecated, replaced with [`Arg::takes_value`] and [`Arg::is_takes_value_set`]
+ ///
+ /// Derive: this setting shouldn't be needed
+ ///
+ /// Builder: replace `arg.setting(TakesValue)` with `arg.takes_value(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::takes_value` and `Arg::is_takes_value_set`
+
+Derive: this setting shouldn't be needed
+
+Builder: replace `arg.setting(TakesValue)` with `arg.takes_value(true)`
+"
+ )
+ )]
+ TakesValue,
+ /// Deprecated, replaced with [`Arg::use_value_delimiter`] and
+ /// [`Arg::is_use_value_delimiter_set`]
+ ///
+ /// Derive: replace `#[clap(setting = UseValueDelimiter)]` with `#[clap(use_value_delimiter = true)]`
+ ///
+ /// Builder: replace `arg.setting(UseValueDelimiter)` with `arg.use_value_delimiter(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::use_value_delimiter` and `Arg::is_use_value_delimiter_set`
+
+Derive: replace `#[clap(setting = UseValueDelimiter)]` with `#[clap(use_value_delimiter = true)]`
+
+Builder: replace `arg.setting(UseValueDelimiter)` with `arg.use_value_delimiter(true)`
+"
+ )
+ )]
+ UseValueDelimiter,
+ /// Deprecated, replaced with [`Arg::next_line_help`] and [`Arg::is_next_line_help_set`]
+ ///
+ /// Derive: replace `#[clap(setting = NextLineHelp)]` with `#[clap(next_line_help = true)]`
+ ///
+ /// Builder: replace `arg.setting(NextLineHelp)` with `arg.next_line_help(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::next_line_help` and `Arg::is_next_line_help_set`
+
+Derive: replace `#[clap(setting = NextLineHelp)]` with `#[clap(next_line_help = true)]`
+
+Builder: replace `arg.setting(NextLineHelp)` with `arg.next_line_help(true)`
+"
+ )
+ )]
+ NextLineHelp,
+ /// Deprecated, replaced with [`Arg::require_value_delimiter`] and
+ /// [`Arg::is_require_value_delimiter_set`]
+ ///
+ /// Derive: replace `#[clap(setting = RequireDelimiter)]` with `#[clap(require_value_delimiter = true)]`
+ ///
+ /// Builder: replace `arg.setting(RequireDelimiter)` with `arg.require_value_delimiter(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::require_value_delimiter` and `Arg::is_require_value_delimiter_set`
+
+Derive: replace `#[clap(setting = RequireDelimiter)]` with `#[clap(require_value_delimiter = true)]`
+
+Builder: replace `arg.setting(RequireDelimiter)` with `arg.require_value_delimiter(true)`
+"
+ )
+ )]
+ RequireDelimiter,
+ /// Deprecated, replaced with [`Arg::hide_possible_values`] and
+ /// [`Arg::is_hide_possible_values_set`]
+ ///
+ /// Derive: replace `#[clap(setting = HidePossibleValues)]` with `#[clap(hide_possible_values = true)]`
+ ///
+ /// Builder: replace `arg.setting(HidePossibleValues)` with `arg.hide_possible_values(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::hide_possible_values` and `Arg::is_hide_possible_values_set`
+
+Derive: replace `#[clap(setting = HidePossibleValues)]` with `#[clap(hide_possible_values = true)]`
+
+Builder: replace `arg.setting(HidePossibleValues)` with `arg.hide_possible_values(true)`
+"
+ )
+ )]
+ HidePossibleValues,
+ /// Deprecated, replaced with [`Arg::allow_hyphen_values`] and
+ /// [`Arg::is_allow_hyphen_values_set`]
+ ///
+ /// Derive: replace `#[clap(setting = AllowHyphenValues)]` with `#[clap(allow_hyphen_values = true)]`
+ ///
+ /// Builder: replace `arg.setting(AllowHyphenValues)` with `arg.allow_hyphen_values(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::allow_hyphen_values` and `Arg::is_allow_hyphen_values_set`
+
+Derive: replace `#[clap(setting = AllowHyphenValues)]` with `#[clap(allow_hyphen_values = true)]`
+
+Builder: replace `arg.setting(AllowHyphenValues)` with `arg.allow_hyphen_values(true)`
+"
+ )
+ )]
+ AllowHyphenValues,
+ /// Deprecated, replaced with [`Arg::allow_hyphen_values`] and
+ /// [`Arg::is_allow_hyphen_values_set`]
+ ///
+ /// Derive: replace `#[clap(setting = AllowLeadingHyphen)]` with `#[clap(allow_hyphen_values = true)]`
+ ///
+ /// Builder: replace `arg.setting(AllowLeadingHyphen)` with `arg.allow_hyphen_values(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `Arg::allow_hyphen_values` and `Arg::is_allow_hyphen_values_set`
+
+Derive: replace `#[clap(setting = AllowLeadingHyphen)]` with `#[clap(allow_hyphen_values = true)]`
+
+Builder: replace `arg.setting(AllowLeadingHyphen)` with `arg.allow_hyphen_values(true)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ AllowLeadingHyphen,
+ /// Deprecated, replaced with [`Arg::require_equals`] and [`Arg::is_require_equals_set`]
+ ///
+ /// Derive: replace `#[clap(setting = RequireEquals)]` with `#[clap(require_equals = true)]`
+ ///
+ /// Builder: replace `arg.setting(RequireEquals)` with `arg.require_equals(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::require_equals` and `Arg::is_require_equals_set`
+
+Derive: replace `#[clap(setting = RequireEquals)]` with `#[clap(require_equals = true)]`
+
+Builder: replace `arg.setting(RequireEquals)` with `arg.require_equals(true)`
+"
+ )
+ )]
+ RequireEquals,
+ /// Deprecated, replaced with [`Arg::last`] and [`Arg::is_last_set`]
+ ///
+ /// Derive: replace `#[clap(setting = Last)]` with `#[clap(last = true)]`
+ ///
+ /// Builder: replace `arg.setting(Last)` with `arg.last(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::last` and `Arg::is_last_set`
+
+Derive: replace `#[clap(setting = Last)]` with `#[clap(last = true)]`
+
+Builder: replace `arg.setting(Last)` with `arg.last(true)`
+"
+ )
+ )]
+ Last,
+ /// Deprecated, replaced with [`Arg::hide_default_value`] and [`Arg::is_hide_default_value_set`]
+ ///
+ /// Derive: replace `#[clap(setting = HideDefaultValue)]` with `#[clap(hide_default_value = true)]`
+ ///
+ /// Builder: replace `arg.setting(HideDefaultValue)` with `arg.hide_default_value(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::hide_default_value` and `Arg::is_hide_default_value_set`
+
+Derive: replace `#[clap(setting = HideDefaultValue)]` with `#[clap(hide_default_value = true)]`
+
+Builder: replace `arg.setting(HideDefaultValue)` with `arg.hide_default_value(true)`
+"
+ )
+ )]
+ HideDefaultValue,
+ /// Deprecated, replaced with [`Arg::ignore_case`] and [`Arg::is_ignore_case_set`]
+ ///
+ /// Derive: replace `#[clap(setting = IgnoreCase)]` with `#[clap(ignore_case = true)]`
+ ///
+ /// Builder: replace `arg.setting(IgnoreCase)` with `arg.ignore_case(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::ignore_case` and `Arg::is_ignore_case_set`
+
+Derive: replace `#[clap(setting = IgnoreCase)]` with `#[clap(ignore_case = true)]`
+
+Builder: replace `arg.setting(IgnoreCase)` with `arg.ignore_case(true)`
+"
+ )
+ )]
+ IgnoreCase,
+ /// Deprecated, replaced with [`Arg::ignore_case`] and [`Arg::is_ignore_case_set`]
+ ///
+ /// Derive: replace `#[clap(setting = CaseInsensitive)]` with `#[clap(ignore_case = true)]`
+ ///
+ /// Builder: replace `arg.setting(CaseInsensitive)` with `arg.ignore_case(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `Arg::ignore_case` and `Arg::is_ignore_case_set`
+
+Derive: replace `#[clap(setting = CaseInsensitive)]` with `#[clap(ignore_case = true)]`
+
+Builder: replace `arg.setting(CaseInsensitive)` with `arg.ignore_case(true)`
+"
+ )
+ )]
+ #[doc(hidden)]
+ CaseInsensitive,
+ /// Deprecated, replaced with [`Arg::hide_env`] and [`Arg::is_hide_env_set`]
+ ///
+ /// Derive: replace `#[clap(setting = HideEnv)]` with `#[clap(hide_env = true)]`
+ ///
+ /// Builder: replace `arg.setting(HideEnv)` with `arg.hide_env(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::hide_env` and `Arg::is_hide_env_set`
+
+Derive: replace `#[clap(setting = HideEnv)]` with `#[clap(hide_env = true)]`
+
+Builder: replace `arg.setting(HideEnv)` with `arg.hide_env(true)`
+"
+ )
+ )]
+ #[cfg(feature = "env")]
+ HideEnv,
+ /// Deprecated, replaced with [`Arg::hide_env_values`] and [`Arg::is_hide_env_values_set`]
+ ///
+ /// Derive: replace `#[clap(setting = HideEnvValues)]` with `#[clap(hide_env_values = true)]`
+ ///
+ /// Builder: replace `arg.setting(HideEnvValues)` with `arg.hide_env_values(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::hide_env_values` and `Arg::is_hide_env_values_set`
+
+Derive: replace `#[clap(setting = HideEnvValues)]` with `#[clap(hide_env_values = true)]`
+
+Builder: replace `arg.setting(HideEnvValues)` with `arg.hide_env_values(true)`
+"
+ )
+ )]
+ #[cfg(feature = "env")]
+ HideEnvValues,
+ /// Deprecated, replaced with [`Arg::hide_short_help`] and [`Arg::is_hide_short_help_set`]
+ ///
+ /// Derive: replace `#[clap(setting = HiddenShortHelp)]` with `#[clap(hide_short_help = true)]`
+ ///
+ /// Builder: replace `arg.setting(HiddenShortHelp)` with `arg.hide_short_help(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::hide_short_help` and `Arg::is_hide_short_help_set`
+
+Derive: replace `#[clap(setting = HiddenShortHelp)]` with `#[clap(hide_short_help = true)]`
+
+Builder: replace `arg.setting(HiddenShortHelp)` with `arg.hide_short_help(true)`
+"
+ )
+ )]
+ HiddenShortHelp,
+ /// Deprecated, replaced with [`Arg::hide_long_help`] and [`Arg::is_hide_long_help_set`]
+ ///
+ /// Derive: replace `#[clap(setting = HiddenLongHelp)]` with `#[clap(hide_long_help = true)]`
+ ///
+ /// Builder: replace `arg.setting(HiddenLongHelp)` with `arg.hide_long_help(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::hide_long_help` and `Arg::is_hide_long_help_set`
+
+Derive: replace `#[clap(setting = HiddenLongHelp)]` with `#[clap(hide_long_help = true)]`
+
+Builder: replace `arg.setting(HiddenLongHelp)` with `arg.hide_long_help(true)`
+"
+ )
+ )]
+ HiddenLongHelp,
+ /// Deprecated, replaced with [`Arg::value_parser`]
+ ///
+ /// Derive: replace `#[clap(setting = AllowInvalidUtf8)]` with `#[clap(action)]` (which opts-in to the
+ /// new clap v4 behavior which gets the type via `value_parser!`)
+ ///
+ /// Builder: replace `arg.setting(AllowInvalidUtf8)` with `arg.value_parser(value_parser!(T))` where
+ /// `T` is the type of interest, like `OsString` or `PathBuf`, and `matches.value_of_os` with
+ /// `matches.get_one::<T>` or `matches.values_of_os` with `matches.get_many::<T>`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `value_parser`
+
+Derive: replace `#[clap(setting = AllowInvalidUtf8)]` with `#[clap(action)]` (which opts-in to the
+new clap v4 behavior which gets the type via `value_parser!`)
+
+Builder: replace `arg.setting(AllowInvalidUtf8)` with `arg.value_parser(value_parser!(T))` where
+`T` is the type of interest, like `OsString` or `PathBuf`, and `matches.value_of_os` with
+`matches.get_one::<T>` or `matches.values_of_os` with `matches.get_many::<T>`
+"
+ )
+ )]
+ AllowInvalidUtf8,
+ /// Deprecated, replaced with [`Arg::exclusive`] and [`Arg::is_exclusive_set`]
+ ///
+ /// Derive: replace `#[clap(setting = Exclusive)]` with `#[clap(exclusive = true)]`
+ ///
+ /// Builder: replace `arg.setting(Exclusive)` with `arg.exclusive(true)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `Arg::exclusive` and `Arg::is_exclusive_set`
+
+Derive: replace `#[clap(setting = Exclusive)]` with `#[clap(exclusive = true)]`
+
+Builder: replace `arg.setting(Exclusive)` with `arg.exclusive(true)`
+"
+ )
+ )]
+ Exclusive,
+}
+
+bitflags! {
+ struct Flags: u32 {
+ const REQUIRED = 1;
+ const MULTIPLE_OCC = 1 << 1;
+ const NO_EMPTY_VALS = 1 << 2;
+ const GLOBAL = 1 << 3;
+ const HIDDEN = 1 << 4;
+ const TAKES_VAL = 1 << 5;
+ const USE_DELIM = 1 << 6;
+ const NEXT_LINE_HELP = 1 << 7;
+ const REQ_DELIM = 1 << 9;
+ const DELIM_NOT_SET = 1 << 10;
+ const HIDE_POS_VALS = 1 << 11;
+ const ALLOW_TAC_VALS = 1 << 12;
+ const REQUIRE_EQUALS = 1 << 13;
+ const LAST = 1 << 14;
+ const HIDE_DEFAULT_VAL = 1 << 15;
+ const CASE_INSENSITIVE = 1 << 16;
+ #[cfg(feature = "env")]
+ const HIDE_ENV_VALS = 1 << 17;
+ const HIDDEN_SHORT_H = 1 << 18;
+ const HIDDEN_LONG_H = 1 << 19;
+ const MULTIPLE_VALS = 1 << 20;
+ const MULTIPLE = Self::MULTIPLE_OCC.bits | Self::MULTIPLE_VALS.bits;
+ #[cfg(feature = "env")]
+ const HIDE_ENV = 1 << 21;
+ const UTF8_NONE = 1 << 22;
+ const EXCLUSIVE = 1 << 23;
+ const NO_OP = 0;
+ }
+}
+
+impl_settings! { ArgSettings, ArgFlags,
+ Required => Flags::REQUIRED,
+ MultipleOccurrences => Flags::MULTIPLE_OCC,
+ MultipleValues => Flags::MULTIPLE_VALS,
+ Multiple => Flags::MULTIPLE,
+ ForbidEmptyValues => Flags::NO_EMPTY_VALS,
+ Global => Flags::GLOBAL,
+ Hidden => Flags::HIDDEN,
+ TakesValue => Flags::TAKES_VAL,
+ UseValueDelimiter => Flags::USE_DELIM,
+ NextLineHelp => Flags::NEXT_LINE_HELP,
+ RequireDelimiter => Flags::REQ_DELIM,
+ HidePossibleValues => Flags::HIDE_POS_VALS,
+ AllowHyphenValues => Flags::ALLOW_TAC_VALS,
+ AllowLeadingHyphen => Flags::ALLOW_TAC_VALS,
+ RequireEquals => Flags::REQUIRE_EQUALS,
+ Last => Flags::LAST,
+ IgnoreCase => Flags::CASE_INSENSITIVE,
+ CaseInsensitive => Flags::CASE_INSENSITIVE,
+ #[cfg(feature = "env")]
+ HideEnv => Flags::HIDE_ENV,
+ #[cfg(feature = "env")]
+ HideEnvValues => Flags::HIDE_ENV_VALS,
+ HideDefaultValue => Flags::HIDE_DEFAULT_VAL,
+ HiddenShortHelp => Flags::HIDDEN_SHORT_H,
+ HiddenLongHelp => Flags::HIDDEN_LONG_H,
+ AllowInvalidUtf8 => Flags::UTF8_NONE,
+ Exclusive => Flags::EXCLUSIVE
+}
+
+/// 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")]
+impl FromStr for ArgSettings {
+ type Err = String;
+ fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
+ #[allow(deprecated)]
+ #[allow(unreachable_patterns)]
+ match &*s.to_ascii_lowercase() {
+ "required" => Ok(ArgSettings::Required),
+ "multipleoccurrences" => Ok(ArgSettings::MultipleOccurrences),
+ "multiplevalues" => Ok(ArgSettings::MultipleValues),
+ "multiple" => Ok(ArgSettings::Multiple),
+ "forbidemptyvalues" => Ok(ArgSettings::ForbidEmptyValues),
+ "global" => Ok(ArgSettings::Global),
+ "hidden" => Ok(ArgSettings::Hidden),
+ "takesvalue" => Ok(ArgSettings::TakesValue),
+ "usevaluedelimiter" => Ok(ArgSettings::UseValueDelimiter),
+ "nextlinehelp" => Ok(ArgSettings::NextLineHelp),
+ "requiredelimiter" => Ok(ArgSettings::RequireDelimiter),
+ "hidepossiblevalues" => Ok(ArgSettings::HidePossibleValues),
+ "allowhyphenvalues" => Ok(ArgSettings::AllowHyphenValues),
+ "allowleadinghypyhen" => Ok(ArgSettings::AllowLeadingHyphen),
+ "requireequals" => Ok(ArgSettings::RequireEquals),
+ "last" => Ok(ArgSettings::Last),
+ "ignorecase" => Ok(ArgSettings::IgnoreCase),
+ "caseinsensitive" => Ok(ArgSettings::CaseInsensitive),
+ #[cfg(feature = "env")]
+ "hideenv" => Ok(ArgSettings::HideEnv),
+ #[cfg(feature = "env")]
+ "hideenvvalues" => Ok(ArgSettings::HideEnvValues),
+ "hidedefaultvalue" => Ok(ArgSettings::HideDefaultValue),
+ "hiddenshorthelp" => Ok(ArgSettings::HiddenShortHelp),
+ "hiddenlonghelp" => Ok(ArgSettings::HiddenLongHelp),
+ "allowinvalidutf8" => Ok(ArgSettings::AllowInvalidUtf8),
+ "exclusive" => Ok(ArgSettings::Exclusive),
+ _ => Err(format!("unknown AppSetting: `{}`", s)),
+ }
+ }
+}
+
+#[cfg(test)]
+mod test {
+ #[test]
+ #[cfg(feature = "yaml")]
+ fn arg_settings_fromstr() {
+ use super::ArgSettings;
+
+ assert_eq!(
+ "allowhyphenvalues".parse::<ArgSettings>().unwrap(),
+ ArgSettings::AllowHyphenValues
+ );
+ assert_eq!(
+ "forbidemptyvalues".parse::<ArgSettings>().unwrap(),
+ ArgSettings::ForbidEmptyValues
+ );
+ assert_eq!(
+ "hidepossiblevalues".parse::<ArgSettings>().unwrap(),
+ ArgSettings::HidePossibleValues
+ );
+ assert_eq!(
+ "hidden".parse::<ArgSettings>().unwrap(),
+ ArgSettings::Hidden
+ );
+ assert_eq!(
+ "nextlinehelp".parse::<ArgSettings>().unwrap(),
+ ArgSettings::NextLineHelp
+ );
+ assert_eq!(
+ "requiredelimiter".parse::<ArgSettings>().unwrap(),
+ ArgSettings::RequireDelimiter
+ );
+ assert_eq!(
+ "required".parse::<ArgSettings>().unwrap(),
+ ArgSettings::Required
+ );
+ assert_eq!(
+ "takesvalue".parse::<ArgSettings>().unwrap(),
+ ArgSettings::TakesValue
+ );
+ assert_eq!(
+ "usevaluedelimiter".parse::<ArgSettings>().unwrap(),
+ ArgSettings::UseValueDelimiter
+ );
+ assert_eq!(
+ "requireequals".parse::<ArgSettings>().unwrap(),
+ ArgSettings::RequireEquals
+ );
+ assert_eq!("last".parse::<ArgSettings>().unwrap(), ArgSettings::Last);
+ assert_eq!(
+ "hidedefaultvalue".parse::<ArgSettings>().unwrap(),
+ ArgSettings::HideDefaultValue
+ );
+ assert_eq!(
+ "ignorecase".parse::<ArgSettings>().unwrap(),
+ ArgSettings::IgnoreCase
+ );
+ #[cfg(feature = "env")]
+ assert_eq!(
+ "hideenv".parse::<ArgSettings>().unwrap(),
+ ArgSettings::HideEnv
+ );
+ #[cfg(feature = "env")]
+ assert_eq!(
+ "hideenvvalues".parse::<ArgSettings>().unwrap(),
+ ArgSettings::HideEnvValues
+ );
+ assert_eq!(
+ "hiddenshorthelp".parse::<ArgSettings>().unwrap(),
+ ArgSettings::HiddenShortHelp
+ );
+ assert_eq!(
+ "hiddenlonghelp".parse::<ArgSettings>().unwrap(),
+ ArgSettings::HiddenLongHelp
+ );
+ assert_eq!(
+ "allowinvalidutf8".parse::<ArgSettings>().unwrap(),
+ ArgSettings::AllowInvalidUtf8
+ );
+ assert_eq!(
+ "exclusive".parse::<ArgSettings>().unwrap(),
+ ArgSettings::Exclusive
+ );
+ assert!("hahahaha".parse::<ArgSettings>().is_err());
+ }
+}
diff --git a/3.2.23/src/builder/command.rs b/3.2.23/src/builder/command.rs
new file mode 100644
index 0000000..3194bb0
--- /dev/null
+++ b/3.2.23/src/builder/command.rs
@@ -0,0 +1,5201 @@
+#![allow(deprecated)]
+
+// Std
+use std::collections::HashMap;
+use std::env;
+use std::ffi::OsString;
+use std::fmt;
+use std::io;
+use std::ops::Index;
+use std::path::Path;
+
+// Third Party
+#[cfg(feature = "yaml")]
+use yaml_rust::Yaml;
+
+// Internal
+use crate::builder::app_settings::{AppFlags, AppSettings};
+use crate::builder::arg_settings::ArgSettings;
+use crate::builder::{arg::ArgProvider, Arg, ArgGroup, ArgPredicate};
+use crate::error::ErrorKind;
+use crate::error::Result as ClapResult;
+use crate::mkeymap::MKeyMap;
+use crate::output::fmt::Stream;
+use crate::output::{fmt::Colorizer, Help, HelpWriter, Usage};
+use crate::parser::{ArgMatcher, ArgMatches, Parser};
+use crate::util::ChildGraph;
+use crate::util::{color::ColorChoice, Id, Key};
+use crate::PossibleValue;
+use crate::{Error, INTERNAL_ERROR_MSG};
+
+#[cfg(debug_assertions)]
+use crate::builder::debug_asserts::assert_app;
+
+/// Build a command-line interface.
+///
+/// This includes defining arguments, subcommands, parser behavior, and help output.
+/// Once all configuration is complete,
+/// the [`Command::get_matches`] family of methods starts the runtime-parsing
+/// process. These methods then return information about the user supplied
+/// arguments (or lack thereof).
+///
+/// When deriving a [`Parser`][crate::Parser], you can use
+/// [`CommandFactory::command`][crate::CommandFactory::command] to access the
+/// `Command`.
+///
+/// - [Basic API][crate::App#basic-api]
+/// - [Application-wide Settings][crate::App#application-wide-settings]
+/// - [Command-specific Settings][crate::App#command-specific-settings]
+/// - [Subcommand-specific Settings][crate::App#subcommand-specific-settings]
+/// - [Reflection][crate::App#reflection]
+///
+/// # Examples
+///
+/// ```no_run
+/// # use clap::{Command, Arg};
+/// let m = Command::new("My Program")
+/// .author("Me, me@mail.com")
+/// .version("1.0.2")
+/// .about("Explains in brief what the program does")
+/// .arg(
+/// Arg::new("in_file")
+/// )
+/// .after_help("Longer explanation to appear after the options when \
+/// displaying the help information from --help or -h")
+/// .get_matches();
+///
+/// // Your program logic starts here...
+/// ```
+/// [`App::get_matches`]: Command::get_matches()
+pub type Command<'help> = App<'help>;
+
+/// Deprecated, replaced with [`Command`]
+#[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.1.0", note = "Replaced with `Command`")
+)]
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct App<'help> {
+ id: Id,
+ name: String,
+ long_flag: Option<&'help str>,
+ short_flag: Option<char>,
+ display_name: Option<String>,
+ bin_name: Option<String>,
+ author: Option<&'help str>,
+ version: Option<&'help str>,
+ long_version: Option<&'help str>,
+ about: Option<&'help str>,
+ long_about: Option<&'help str>,
+ before_help: Option<&'help str>,
+ before_long_help: Option<&'help str>,
+ after_help: Option<&'help str>,
+ after_long_help: Option<&'help str>,
+ aliases: Vec<(&'help str, bool)>, // (name, visible)
+ short_flag_aliases: Vec<(char, bool)>, // (name, visible)
+ long_flag_aliases: Vec<(&'help str, bool)>, // (name, visible)
+ usage_str: Option<&'help str>,
+ usage_name: Option<String>,
+ help_str: Option<&'help str>,
+ disp_ord: Option<usize>,
+ term_w: Option<usize>,
+ max_w: Option<usize>,
+ template: Option<&'help str>,
+ settings: AppFlags,
+ g_settings: AppFlags,
+ args: MKeyMap<'help>,
+ subcommands: Vec<App<'help>>,
+ replacers: HashMap<&'help str, &'help [&'help str]>,
+ groups: Vec<ArgGroup<'help>>,
+ current_help_heading: Option<&'help str>,
+ current_disp_ord: Option<usize>,
+ subcommand_value_name: Option<&'help str>,
+ subcommand_heading: Option<&'help str>,
+}
+
+/// # Basic API
+impl<'help> App<'help> {
+ /// Creates a new instance of an `Command`.
+ ///
+ /// It is common, but not required, to use binary name as the `name`. This
+ /// name will only be displayed to the user when they request to print
+ /// version or help and usage information.
+ ///
+ /// See also [`command!`](crate::command!) and [`crate_name!`](crate::crate_name!).
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("My Program")
+ /// # ;
+ /// ```
+ pub fn new<S: Into<String>>(name: S) -> Self {
+ /// The actual implementation of `new`, non-generic to save code size.
+ ///
+ /// If we don't do this rustc will unnecessarily generate multiple versions
+ /// of this code.
+ fn new_inner<'help>(name: String) -> App<'help> {
+ App {
+ id: Id::from(&*name),
+ name,
+ ..Default::default()
+ }
+ .arg(
+ Arg::new("help")
+ .long("help")
+ .help("Print help information")
+ .global(true)
+ .generated(),
+ )
+ .arg(
+ Arg::new("version")
+ .long("version")
+ .help("Print version information")
+ .global(true)
+ .generated(),
+ )
+ }
+
+ new_inner(name.into())
+ }
+
+ /// Adds an [argument] to the list of valid possibilities.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, arg, Arg};
+ /// Command::new("myprog")
+ /// // Adding a single "flag" argument with a short and help text, using Arg::new()
+ /// .arg(
+ /// Arg::new("debug")
+ /// .short('d')
+ /// .help("turns on debugging mode")
+ /// )
+ /// // Adding a single "option" argument with a short, a long, and help text using the less
+ /// // verbose Arg::from()
+ /// .arg(
+ /// arg!(-c --config <CONFIG> "Optionally sets a config file to use")
+ /// )
+ /// # ;
+ /// ```
+ /// [argument]: Arg
+ #[must_use]
+ pub fn arg<A: Into<Arg<'help>>>(mut self, a: A) -> Self {
+ let mut arg = a.into();
+ if let Some(current_disp_ord) = self.current_disp_ord.as_mut() {
+ if !arg.is_positional() && arg.provider != ArgProvider::Generated {
+ let current = *current_disp_ord;
+ arg.disp_ord.set_implicit(current);
+ *current_disp_ord = current + 1;
+ }
+ }
+
+ arg.help_heading.get_or_insert(self.current_help_heading);
+ self.args.push(arg);
+ self
+ }
+
+ /// Adds multiple [arguments] to the list of valid possibilities.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, arg, Arg};
+ /// Command::new("myprog")
+ /// .args(&[
+ /// arg!("[debug] -d 'turns on debugging info'"),
+ /// Arg::new("input").help("the input file to use")
+ /// ])
+ /// # ;
+ /// ```
+ /// [arguments]: Arg
+ #[must_use]
+ pub fn args<I, T>(mut self, args: I) -> Self
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<Arg<'help>>,
+ {
+ let args = args.into_iter();
+ let (lower, _) = args.size_hint();
+ self.args.reserve(lower);
+
+ for arg in args {
+ self = self.arg(arg);
+ }
+ self
+ }
+
+ /// Allows one to mutate an [`Arg`] after it's been added to a [`Command`].
+ ///
+ /// This can be useful for modifying the auto-generated help or version arguments.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ ///
+ /// let mut cmd = Command::new("foo")
+ /// .arg(Arg::new("bar")
+ /// .short('b'))
+ /// .mut_arg("bar", |a| a.short('B'));
+ ///
+ /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]);
+ ///
+ /// // Since we changed `bar`'s short to "B" this should err as there
+ /// // is no `-b` anymore, only `-B`
+ ///
+ /// assert!(res.is_err());
+ ///
+ /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]);
+ /// assert!(res.is_ok());
+ /// ```
+ #[must_use]
+ pub fn mut_arg<T, F>(mut self, arg_id: T, f: F) -> Self
+ where
+ F: FnOnce(Arg<'help>) -> Arg<'help>,
+ T: Key + Into<&'help str>,
+ {
+ let arg_id: &str = arg_id.into();
+ let id = Id::from(arg_id);
+
+ let mut a = self.args.remove_by_name(&id).unwrap_or_else(|| Arg {
+ id,
+ name: arg_id,
+ ..Arg::default()
+ });
+
+ if a.provider == ArgProvider::Generated {
+ a.provider = ArgProvider::GeneratedMutated;
+ }
+
+ self.args.push(f(a));
+ 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.
+ /// By placing them in a logical group, you can build easier requirement and exclusion rules.
+ ///
+ /// Example use cases:
+ /// - Make an entire [`ArgGroup`] required, meaning that one (and *only*
+ /// one) argument from that group must be present at runtime.
+ /// - Name an [`ArgGroup`] as a conflict to another argument.
+ /// Meaning any of the arguments that belong to that group will cause a failure if present with
+ /// the conflicting argument.
+ /// - Ensure exclusion between arguments.
+ /// - Extract a value from a group instead of determining exactly which argument was used.
+ ///
+ /// # Examples
+ ///
+ /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one,
+ /// of the arguments from the specified group is present at runtime.
+ ///
+ /// ```no_run
+ /// # use clap::{Command, arg, ArgGroup};
+ /// Command::new("cmd")
+ /// .arg(arg!("--set-ver [ver] 'set the version manually'"))
+ /// .arg(arg!("--major 'auto increase major'"))
+ /// .arg(arg!("--minor 'auto increase minor'"))
+ /// .arg(arg!("--patch 'auto increase patch'"))
+ /// .group(ArgGroup::new("vers")
+ /// .args(&["set-ver", "major", "minor","patch"])
+ /// .required(true))
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn group<G: Into<ArgGroup<'help>>>(mut self, group: G) -> Self {
+ self.groups.push(group.into());
+ self
+ }
+
+ /// Adds multiple [`ArgGroup`]s to the [`Command`] at once.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, arg, ArgGroup};
+ /// Command::new("cmd")
+ /// .arg(arg!("--set-ver [ver] 'set the version manually'"))
+ /// .arg(arg!("--major 'auto increase major'"))
+ /// .arg(arg!("--minor 'auto increase minor'"))
+ /// .arg(arg!("--patch 'auto increase patch'"))
+ /// .arg(arg!("-c [FILE] 'a config file'"))
+ /// .arg(arg!("-i [IFACE] 'an interface'"))
+ /// .groups(&[
+ /// ArgGroup::new("vers")
+ /// .args(&["set-ver", "major", "minor","patch"])
+ /// .required(true),
+ /// ArgGroup::new("input")
+ /// .args(&["c", "i"])
+ /// ])
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn groups<I, T>(mut self, groups: I) -> Self
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<ArgGroup<'help>>,
+ {
+ for g in groups.into_iter() {
+ self = self.group(g.into());
+ }
+ self
+ }
+
+ /// Adds a subcommand to the list of valid possibilities.
+ ///
+ /// Subcommands are effectively sub-[`Command`]s, because they can contain their own arguments,
+ /// subcommands, version, usage, etc. They also function just like [`Command`]s, in that they get
+ /// their own auto generated help, version, and usage.
+ ///
+ /// A subcommand's [`Command::name`] will be used for:
+ /// - The argument the user passes in
+ /// - Programmatically looking up the subcommand
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, arg};
+ /// Command::new("myprog")
+ /// .subcommand(Command::new("config")
+ /// .about("Controls configuration features")
+ /// .arg(arg!("<config> 'Required configuration file to use'")))
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn subcommand<S: Into<App<'help>>>(mut self, subcmd: S) -> Self {
+ self.subcommands.push(subcmd.into());
+ self
+ }
+
+ /// Adds multiple subcommands to the list of valid possibilities.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, };
+ /// # Command::new("myprog")
+ /// .subcommands( vec![
+ /// Command::new("config").about("Controls configuration functionality")
+ /// .arg(Arg::new("config_file")),
+ /// Command::new("debug").about("Controls debug functionality")])
+ /// # ;
+ /// ```
+ /// [`IntoIterator`]: std::iter::IntoIterator
+ #[must_use]
+ pub fn subcommands<I, T>(mut self, subcmds: I) -> Self
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<App<'help>>,
+ {
+ for subcmd in subcmds.into_iter() {
+ self.subcommands.push(subcmd.into());
+ }
+ self
+ }
+
+ /// Catch problems earlier in the development cycle.
+ ///
+ /// Most error states are handled as asserts under the assumption they are programming mistake
+ /// and not something to handle at runtime. Rather than relying on tests (manual or automated)
+ /// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those
+ /// asserts in a way convenient for running as a test.
+ ///
+ /// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive
+ /// testing of your CLI.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// fn cmd() -> Command<'static> {
+ /// Command::new("foo")
+ /// .arg(
+ /// Arg::new("bar").short('b').action(ArgAction::SetTrue)
+ /// )
+ /// }
+ ///
+ /// #[test]
+ /// fn verify_app() {
+ /// cmd().debug_assert();
+ /// }
+ ///
+ /// fn main() {
+ /// let m = cmd().get_matches_from(vec!["foo", "-b"]);
+ /// println!("{}", *m.get_one::<bool>("bar").expect("defaulted by clap"));
+ /// }
+ /// ```
+ pub fn debug_assert(mut self) {
+ self._build_all();
+ }
+
+ /// Custom error message for post-parsing validation
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, ErrorKind};
+ /// let mut cmd = Command::new("myprog");
+ /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case");
+ /// ```
+ pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error {
+ Error::raw(kind, message).format(self)
+ }
+
+ /// Parse [`env::args_os`], exiting on failure.
+ ///
+ /// # Panics
+ ///
+ /// If contradictory arguments or settings exist.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let matches = Command::new("myprog")
+ /// // Args and options go here...
+ /// .get_matches();
+ /// ```
+ /// [`env::args_os`]: std::env::args_os()
+ /// [`App::try_get_matches_from_mut`]: Command::try_get_matches_from_mut()
+ #[inline]
+ pub fn get_matches(self) -> ArgMatches {
+ self.get_matches_from(&mut env::args_os())
+ }
+
+ /// Parse [`env::args_os`], exiting on failure.
+ ///
+ /// Like [`App::get_matches`] but doesn't consume the `Command`.
+ ///
+ /// # Panics
+ ///
+ /// If contradictory arguments or settings exist.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let mut cmd = Command::new("myprog")
+ /// // Args and options go here...
+ /// ;
+ /// let matches = cmd.get_matches_mut();
+ /// ```
+ /// [`env::args_os`]: std::env::args_os()
+ /// [`App::get_matches`]: Command::get_matches()
+ pub fn get_matches_mut(&mut self) -> ArgMatches {
+ self.try_get_matches_from_mut(&mut env::args_os())
+ .unwrap_or_else(|e| e.exit())
+ }
+
+ /// Parse [`env::args_os`], returning a [`clap::Result`] on failure.
+ ///
+ /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
+ /// used. It will return a [`clap::Error`], where the [`kind`] is a
+ /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call
+ /// [`Error::exit`] or perform a [`std::process::exit`].
+ ///
+ /// # Panics
+ ///
+ /// If contradictory arguments or settings exist.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let matches = Command::new("myprog")
+ /// // Args and options go here...
+ /// .try_get_matches()
+ /// .unwrap_or_else(|e| e.exit());
+ /// ```
+ /// [`env::args_os`]: std::env::args_os()
+ /// [`Error::exit`]: crate::Error::exit()
+ /// [`std::process::exit`]: std::process::exit()
+ /// [`clap::Result`]: Result
+ /// [`clap::Error`]: crate::Error
+ /// [`kind`]: crate::Error
+ /// [`ErrorKind::DisplayHelp`]: crate::ErrorKind::DisplayHelp
+ /// [`ErrorKind::DisplayVersion`]: crate::ErrorKind::DisplayVersion
+ #[inline]
+ pub fn try_get_matches(self) -> ClapResult<ArgMatches> {
+ // Start the parsing
+ self.try_get_matches_from(&mut env::args_os())
+ }
+
+ /// Parse the specified arguments, exiting on failure.
+ ///
+ /// **NOTE:** The first argument will be parsed as the binary name unless
+ /// [`Command::no_binary_name`] is used.
+ ///
+ /// # Panics
+ ///
+ /// If contradictory arguments or settings exist.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
+ ///
+ /// let matches = Command::new("myprog")
+ /// // Args and options go here...
+ /// .get_matches_from(arg_vec);
+ /// ```
+ /// [`App::get_matches`]: Command::get_matches()
+ /// [`clap::Result`]: Result
+ /// [`Vec`]: std::vec::Vec
+ pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ self.try_get_matches_from_mut(itr).unwrap_or_else(|e| {
+ drop(self);
+ e.exit()
+ })
+ }
+
+ /// Parse the specified arguments, returning a [`clap::Result`] on failure.
+ ///
+ /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
+ /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
+ /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
+ /// perform a [`std::process::exit`] yourself.
+ ///
+ /// **NOTE:** The first argument will be parsed as the binary name unless
+ /// [`Command::no_binary_name`] is used.
+ ///
+ /// # Panics
+ ///
+ /// If contradictory arguments or settings exist.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
+ ///
+ /// let matches = Command::new("myprog")
+ /// // Args and options go here...
+ /// .try_get_matches_from(arg_vec)
+ /// .unwrap_or_else(|e| e.exit());
+ /// ```
+ /// [`App::get_matches_from`]: Command::get_matches_from()
+ /// [`App::try_get_matches`]: Command::try_get_matches()
+ /// [`Error::exit`]: crate::Error::exit()
+ /// [`std::process::exit`]: std::process::exit()
+ /// [`clap::Error`]: crate::Error
+ /// [`Error::exit`]: crate::Error::exit()
+ /// [`kind`]: crate::Error
+ /// [`ErrorKind::DisplayHelp`]: crate::ErrorKind::DisplayHelp
+ /// [`ErrorKind::DisplayVersion`]: crate::ErrorKind::DisplayVersion
+ /// [`clap::Result`]: Result
+ pub fn try_get_matches_from<I, T>(mut self, itr: I) -> ClapResult<ArgMatches>
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ self.try_get_matches_from_mut(itr)
+ }
+
+ /// Parse the specified arguments, returning a [`clap::Result`] on failure.
+ ///
+ /// Like [`App::try_get_matches_from`] but doesn't consume the `Command`.
+ ///
+ /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
+ /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
+ /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
+ /// perform a [`std::process::exit`] yourself.
+ ///
+ /// **NOTE:** The first argument will be parsed as the binary name unless
+ /// [`Command::no_binary_name`] is used.
+ ///
+ /// # Panics
+ ///
+ /// If contradictory arguments or settings exist.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
+ ///
+ /// let mut cmd = Command::new("myprog");
+ /// // Args and options go here...
+ /// let matches = cmd.try_get_matches_from_mut(arg_vec)
+ /// .unwrap_or_else(|e| e.exit());
+ /// ```
+ /// [`App::try_get_matches_from`]: Command::try_get_matches_from()
+ /// [`clap::Result`]: Result
+ /// [`clap::Error`]: crate::Error
+ /// [`kind`]: crate::Error
+ pub fn try_get_matches_from_mut<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches>
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ let mut raw_args = clap_lex::RawArgs::new(itr.into_iter());
+ let mut cursor = raw_args.cursor();
+
+ if self.settings.is_set(AppSettings::Multicall) {
+ if let Some(argv0) = raw_args.next_os(&mut cursor) {
+ let argv0 = Path::new(&argv0);
+ if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) {
+ // Stop borrowing command so we can get another mut ref to it.
+ let command = command.to_owned();
+ debug!(
+ "Command::try_get_matches_from_mut: Parsed command {} from argv",
+ command
+ );
+
+ debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it");
+ raw_args.insert(&cursor, &[&command]);
+ debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name");
+ self.name.clear();
+ self.bin_name = None;
+ return self._do_parse(&mut raw_args, cursor);
+ }
+ }
+ };
+
+ // Get the name of the program (argument 1 of env::args()) and determine the
+ // actual file
+ // that was used to execute the program. This is because a program called
+ // ./target/release/my_prog -a
+ // will have two arguments, './target/release/my_prog', '-a' but we don't want
+ // to display
+ // the full path when displaying help messages and such
+ if !self.settings.is_set(AppSettings::NoBinaryName) {
+ if let Some(name) = raw_args.next_os(&mut cursor) {
+ let p = Path::new(name);
+
+ if let Some(f) = p.file_name() {
+ if let Some(s) = f.to_str() {
+ if self.bin_name.is_none() {
+ self.bin_name = Some(s.to_owned());
+ }
+ }
+ }
+ }
+ }
+
+ self._do_parse(&mut raw_args, cursor)
+ }
+
+ /// Prints the short help message (`-h`) to [`io::stdout()`].
+ ///
+ /// See also [`Command::print_long_help`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// let mut cmd = Command::new("myprog");
+ /// cmd.print_help();
+ /// ```
+ /// [`io::stdout()`]: std::io::stdout()
+ pub fn print_help(&mut self) -> io::Result<()> {
+ self._build_self();
+ let color = self.color_help();
+
+ let mut c = Colorizer::new(Stream::Stdout, color);
+ let usage = Usage::new(self);
+ Help::new(HelpWriter::Buffer(&mut c), self, &usage, false).write_help()?;
+ c.print()
+ }
+
+ /// Prints the long help message (`--help`) to [`io::stdout()`].
+ ///
+ /// See also [`Command::print_help`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// let mut cmd = Command::new("myprog");
+ /// cmd.print_long_help();
+ /// ```
+ /// [`io::stdout()`]: std::io::stdout()
+ /// [`BufWriter`]: std::io::BufWriter
+ /// [`-h` (short)]: Arg::help()
+ /// [`--help` (long)]: Arg::long_help()
+ pub fn print_long_help(&mut self) -> io::Result<()> {
+ self._build_self();
+ let color = self.color_help();
+
+ let mut c = Colorizer::new(Stream::Stdout, color);
+ let usage = Usage::new(self);
+ Help::new(HelpWriter::Buffer(&mut c), self, &usage, true).write_help()?;
+ c.print()
+ }
+
+ /// Writes the short help message (`-h`) to a [`io::Write`] object.
+ ///
+ /// See also [`Command::write_long_help`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// use std::io;
+ /// let mut cmd = Command::new("myprog");
+ /// let mut out = io::stdout();
+ /// cmd.write_help(&mut out).expect("failed to write to stdout");
+ /// ```
+ /// [`io::Write`]: std::io::Write
+ /// [`-h` (short)]: Arg::help()
+ /// [`--help` (long)]: Arg::long_help()
+ pub fn write_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> {
+ self._build_self();
+
+ let usage = Usage::new(self);
+ Help::new(HelpWriter::Normal(w), self, &usage, false).write_help()?;
+ w.flush()
+ }
+
+ /// Writes the long help message (`--help`) to a [`io::Write`] object.
+ ///
+ /// See also [`Command::write_help`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// use std::io;
+ /// let mut cmd = Command::new("myprog");
+ /// let mut out = io::stdout();
+ /// cmd.write_long_help(&mut out).expect("failed to write to stdout");
+ /// ```
+ /// [`io::Write`]: std::io::Write
+ /// [`-h` (short)]: Arg::help()
+ /// [`--help` (long)]: Arg::long_help()
+ pub fn write_long_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> {
+ self._build_self();
+
+ let usage = Usage::new(self);
+ Help::new(HelpWriter::Normal(w), self, &usage, true).write_help()?;
+ w.flush()
+ }
+
+ /// Version message rendered as if the user ran `-V`.
+ ///
+ /// See also [`Command::render_long_version`].
+ ///
+ /// ### Coloring
+ ///
+ /// This function does not try to color the message nor it inserts any [ANSI escape codes].
+ ///
+ /// ### Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// use std::io;
+ /// let cmd = Command::new("myprog");
+ /// println!("{}", cmd.render_version());
+ /// ```
+ /// [`io::Write`]: std::io::Write
+ /// [`-V` (short)]: Command::version()
+ /// [`--version` (long)]: Command::long_version()
+ /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
+ pub fn render_version(&self) -> String {
+ self._render_version(false)
+ }
+
+ /// Version message rendered as if the user ran `--version`.
+ ///
+ /// See also [`Command::render_version`].
+ ///
+ /// ### Coloring
+ ///
+ /// This function does not try to color the message nor it inserts any [ANSI escape codes].
+ ///
+ /// ### Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// use std::io;
+ /// let cmd = Command::new("myprog");
+ /// println!("{}", cmd.render_long_version());
+ /// ```
+ /// [`io::Write`]: std::io::Write
+ /// [`-V` (short)]: Command::version()
+ /// [`--version` (long)]: Command::long_version()
+ /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
+ pub fn render_long_version(&self) -> String {
+ self._render_version(true)
+ }
+
+ /// Usage statement
+ ///
+ /// ### Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// use std::io;
+ /// let mut cmd = Command::new("myprog");
+ /// println!("{}", cmd.render_usage());
+ /// ```
+ pub fn render_usage(&mut self) -> String {
+ // If there are global arguments, or settings we need to propagate them down to subcommands
+ // before parsing incase we run into a subcommand
+ self._build_self();
+
+ Usage::new(self).create_usage_with_title(&[])
+ }
+}
+
+/// # Application-wide Settings
+///
+/// These settings will apply to the top-level command and all subcommands, by default. Some
+/// settings can be overridden in subcommands.
+impl<'help> App<'help> {
+ /// Specifies that the parser should not assume the first argument passed is the binary name.
+ ///
+ /// This is normally the case when using a "daemon" style mode. For shells / REPLs, see
+ /// [`Command::multicall`][App::multicall].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, arg};
+ /// let m = Command::new("myprog")
+ /// .no_binary_name(true)
+ /// .arg(arg!(<cmd> ... "commands to run"))
+ /// .get_matches_from(vec!["command", "set"]);
+ ///
+ /// let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect();
+ /// assert_eq!(cmds, ["command", "set"]);
+ /// ```
+ /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut()
+ #[inline]
+ pub fn no_binary_name(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::NoBinaryName)
+ } else {
+ self.unset_global_setting(AppSettings::NoBinaryName)
+ }
+ }
+
+ /// Try not to fail on parse errors, like missing option values.
+ ///
+ /// **Note:** Make sure you apply it as `global_setting` if you want this setting
+ /// to be propagated to subcommands and sub-subcommands!
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, arg};
+ /// let cmd = Command::new("cmd")
+ /// .ignore_errors(true)
+ /// .arg(arg!(-c --config <FILE> "Sets a custom config file").required(false))
+ /// .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file").required(false))
+ /// .arg(arg!(f: -f "Flag"));
+ ///
+ /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]);
+ ///
+ /// assert!(r.is_ok(), "unexpected error: {:?}", r);
+ /// let m = r.unwrap();
+ /// assert_eq!(m.value_of("config"), Some("file"));
+ /// assert!(m.is_present("f"));
+ /// assert_eq!(m.value_of("stuff"), None);
+ /// ```
+ #[inline]
+ pub fn ignore_errors(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::IgnoreErrors)
+ } else {
+ self.unset_global_setting(AppSettings::IgnoreErrors)
+ }
+ }
+
+ /// Deprecated, replaced with [`ArgAction::Set`][super::ArgAction::Set]
+ ///
+ /// The new actions (`ArgAction::Set`, `ArgAction::SetTrue`) do this by default.
+ ///
+ /// See `ArgAction::StoreValue` and `ArgAction::IncOccurrence` for how to migrate
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `Arg::action(ArgAction::...)`
+
+The new actions (`ArgAction::Set`, `ArgAction::SetTrue`) do this by default.
+
+See `ArgAction::StoreValue` and `ArgAction::IncOccurrence` for how to migrate
+"
+ )
+ )]
+ pub fn args_override_self(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::AllArgsOverrideSelf)
+ } else {
+ self.unset_global_setting(AppSettings::AllArgsOverrideSelf)
+ }
+ }
+
+ /// Disables the automatic delimiting of values after `--` or when [`Command::trailing_var_arg`]
+ /// was used.
+ ///
+ /// **NOTE:** The same thing can be done manually by setting the final positional argument to
+ /// [`Arg::use_value_delimiter(false)`]. Using this setting is safer, because it's easier to locate
+ /// when making changes.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .dont_delimit_trailing_values(true)
+ /// .get_matches();
+ /// ```
+ ///
+ /// [`Arg::use_value_delimiter(false)`]: crate::Arg::use_value_delimiter()
+ #[inline]
+ pub fn dont_delimit_trailing_values(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::DontDelimitTrailingValues)
+ } else {
+ self.unset_global_setting(AppSettings::DontDelimitTrailingValues)
+ }
+ }
+
+ /// Sets when to color output.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// **NOTE:** Default behaviour is [`ColorChoice::Auto`].
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, ColorChoice};
+ /// Command::new("myprog")
+ /// .color(ColorChoice::Never)
+ /// .get_matches();
+ /// ```
+ /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto
+ #[cfg(feature = "color")]
+ #[inline]
+ #[must_use]
+ pub fn color(self, color: ColorChoice) -> Self {
+ #![allow(deprecated)]
+ let cmd = self
+ .unset_global_setting(AppSettings::ColorAuto)
+ .unset_global_setting(AppSettings::ColorAlways)
+ .unset_global_setting(AppSettings::ColorNever);
+ match color {
+ ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto),
+ ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways),
+ ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever),
+ }
+ }
+
+ /// Sets the terminal width at which to wrap help messages.
+ ///
+ /// Using `0` will ignore terminal widths and use source formatting.
+ ///
+ /// Defaults to current terminal width when `wrap_help` feature flag is enabled. If the flag
+ /// is disabled or it cannot be determined, the default is 100.
+ ///
+ /// **NOTE:** This setting applies globally and *not* on a per-command basis.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .term_width(80)
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn term_width(mut self, width: usize) -> Self {
+ self.term_w = Some(width);
+ self
+ }
+
+ /// Sets the maximum terminal width at which to wrap help messages.
+ ///
+ /// This only applies when setting the current terminal width. See [`Command::term_width`] for
+ /// more details.
+ ///
+ /// Using `0` will ignore terminal widths and use source formatting.
+ ///
+ /// **NOTE:** This setting applies globally and *not* on a per-command basis.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .max_term_width(100)
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn max_term_width(mut self, w: usize) -> Self {
+ self.max_w = Some(w);
+ self
+ }
+
+ /// Disables `-V` and `--version` flag.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, ErrorKind};
+ /// let res = Command::new("myprog")
+ /// .disable_version_flag(true)
+ /// .try_get_matches_from(vec![
+ /// "myprog", "-V"
+ /// ]);
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
+ /// ```
+ #[inline]
+ pub fn disable_version_flag(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::DisableVersionFlag)
+ } else {
+ self.unset_global_setting(AppSettings::DisableVersionFlag)
+ }
+ }
+
+ /// Specifies to use the version of the current command for all [`subcommands`].
+ ///
+ /// Defaults to `false`; subcommands have independent version strings from their parents.
+ ///
+ /// **Note:** Make sure you apply it as `global_setting` if you want this setting
+ /// to be propagated to subcommands and sub-subcommands!
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .version("v1.1")
+ /// .propagate_version(true)
+ /// .subcommand(Command::new("test"))
+ /// .get_matches();
+ /// // running `$ myprog test --version` will display
+ /// // "myprog-test v1.1"
+ /// ```
+ ///
+ /// [`subcommands`]: crate::Command::subcommand()
+ #[inline]
+ pub fn propagate_version(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::PropagateVersion)
+ } else {
+ self.unset_global_setting(AppSettings::PropagateVersion)
+ }
+ }
+
+ /// Places the help string for all arguments and subcommands on the line after them.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .next_line_help(true)
+ /// .get_matches();
+ /// ```
+ #[inline]
+ pub fn next_line_help(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::NextLineHelp)
+ } else {
+ self.unset_global_setting(AppSettings::NextLineHelp)
+ }
+ }
+
+ /// Disables `-h` and `--help` flag.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, ErrorKind};
+ /// let res = Command::new("myprog")
+ /// .disable_help_flag(true)
+ /// .try_get_matches_from(vec![
+ /// "myprog", "-h"
+ /// ]);
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
+ /// ```
+ #[inline]
+ pub fn disable_help_flag(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::DisableHelpFlag)
+ } else {
+ self.unset_global_setting(AppSettings::DisableHelpFlag)
+ }
+ }
+
+ /// Disables the `help` [`subcommand`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, ErrorKind};
+ /// let res = Command::new("myprog")
+ /// .disable_help_subcommand(true)
+ /// // Normally, creating a subcommand causes a `help` subcommand to automatically
+ /// // be generated as well
+ /// .subcommand(Command::new("test"))
+ /// .try_get_matches_from(vec![
+ /// "myprog", "help"
+ /// ]);
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
+ /// ```
+ ///
+ /// [`subcommand`]: crate::Command::subcommand()
+ #[inline]
+ pub fn disable_help_subcommand(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::DisableHelpSubcommand)
+ } else {
+ self.unset_global_setting(AppSettings::DisableHelpSubcommand)
+ }
+ }
+
+ /// Disables colorized help messages.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .disable_colored_help(true)
+ /// .get_matches();
+ /// ```
+ #[inline]
+ pub fn disable_colored_help(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::DisableColoredHelp)
+ } else {
+ self.unset_global_setting(AppSettings::DisableColoredHelp)
+ }
+ }
+
+ /// Panic if help descriptions are omitted.
+ ///
+ /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at
+ /// compile-time with `#![deny(missing_docs)]`
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .help_expected(true)
+ /// .arg(
+ /// Arg::new("foo").help("It does foo stuff")
+ /// // As required via `help_expected`, a help message was supplied
+ /// )
+ /// # .get_matches();
+ /// ```
+ ///
+ /// # Panics
+ ///
+ /// ```rust,no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myapp")
+ /// .help_expected(true)
+ /// .arg(
+ /// Arg::new("foo")
+ /// // Someone forgot to put .about("...") here
+ /// // Since the setting `help_expected` is activated, this will lead to
+ /// // a panic (if you are in debug mode)
+ /// )
+ /// # .get_matches();
+ ///```
+ #[inline]
+ pub fn help_expected(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::HelpExpected)
+ } else {
+ self.unset_global_setting(AppSettings::HelpExpected)
+ }
+ }
+
+ /// Disables the automatic collapsing of positional args into `[ARGS]` inside the usage string.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .dont_collapse_args_in_usage(true)
+ /// .get_matches();
+ /// ```
+ #[inline]
+ pub fn dont_collapse_args_in_usage(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::DontCollapseArgsInUsage)
+ } else {
+ self.unset_global_setting(AppSettings::DontCollapseArgsInUsage)
+ }
+ }
+
+ /// Tells `clap` *not* to print possible values when displaying help information.
+ ///
+ /// This can be useful if there are many values, or they are explained elsewhere.
+ ///
+ /// To set this per argument, see
+ /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values].
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ #[inline]
+ pub fn hide_possible_values(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::HidePossibleValues)
+ } else {
+ self.unset_global_setting(AppSettings::HidePossibleValues)
+ }
+ }
+
+ /// Allow partial matches of long arguments or their [aliases].
+ ///
+ /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and
+ /// `--test`.
+ ///
+ /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match
+ /// `--te` to `--test` there could not also be another argument or alias `--temp` because both
+ /// start with `--te`
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// [aliases]: crate::Command::aliases()
+ #[inline]
+ pub fn infer_long_args(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::InferLongArgs)
+ } else {
+ self.unset_global_setting(AppSettings::InferLongArgs)
+ }
+ }
+
+ /// Allow partial matches of [subcommand] names and their [aliases].
+ ///
+ /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and
+ /// `test`.
+ ///
+ /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te`
+ /// to `test` there could not also be a subcommand or alias `temp` because both start with `te`
+ ///
+ /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when
+ /// designing CLIs which allow inferred subcommands and have potential positional/free
+ /// arguments whose values could start with the same characters as subcommands. If this is the
+ /// case, it's recommended to use settings such as [`Command::args_conflicts_with_subcommands`] in
+ /// conjunction with this setting.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .infer_subcommands(true)
+ /// .subcommand(Command::new("test"))
+ /// .get_matches_from(vec![
+ /// "prog", "te"
+ /// ]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ ///
+ /// [subcommand]: crate::Command::subcommand()
+ /// [positional/free arguments]: crate::Arg::index()
+ /// [aliases]: crate::Command::aliases()
+ #[inline]
+ pub fn infer_subcommands(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::InferSubcommands)
+ } else {
+ self.unset_global_setting(AppSettings::InferSubcommands)
+ }
+ }
+}
+
+/// # Command-specific Settings
+///
+/// These apply only to the current command and are not inherited by subcommands.
+impl<'help> App<'help> {
+ /// (Re)Sets the program's name.
+ ///
+ /// See [`Command::new`] for more details.
+ ///
+ /// # Examples
+ ///
+ /// ```ignore
+ /// # use clap::{Command, load_yaml};
+ /// let yaml = load_yaml!("cmd.yaml");
+ /// let cmd = Command::from(yaml)
+ /// .name(crate_name!());
+ ///
+ /// // continued logic goes here, such as `cmd.get_matches()` etc.
+ /// ```
+ #[must_use]
+ pub fn name<S: Into<String>>(mut self, name: S) -> Self {
+ self.name = name.into();
+ self
+ }
+
+ /// Overrides the runtime-determined name of the binary for help and error messages.
+ ///
+ /// This should only be used when absolutely necessary, such as when the binary name for your
+ /// application is misleading, or perhaps *not* how the user should invoke your program.
+ ///
+ /// **Pro-tip:** When building things such as third party `cargo`
+ /// subcommands, this setting **should** be used!
+ ///
+ /// **NOTE:** This *does not* change or set the name of the binary file on
+ /// disk. It only changes what clap thinks the name is for the purposes of
+ /// error or help messages.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("My Program")
+ /// .bin_name("my_binary")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn bin_name<S: Into<String>>(mut self, name: S) -> Self {
+ self.bin_name = Some(name.into());
+ self
+ }
+
+ /// Overrides the runtime-determined display name of the program for help and error messages.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("My Program")
+ /// .display_name("my_program")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn display_name<S: Into<String>>(mut self, name: S) -> Self {
+ self.display_name = Some(name.into());
+ self
+ }
+
+ /// Sets the author(s) for the help message.
+ ///
+ /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to
+ /// automatically set your application's author(s) to the same thing as your
+ /// crate at compile time.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .author("Me, me@mymain.com")
+ /// # ;
+ /// ```
+ /// [`crate_authors!`]: ./macro.crate_authors!.html
+ #[must_use]
+ pub fn author<S: Into<&'help str>>(mut self, author: S) -> Self {
+ self.author = Some(author.into());
+ self
+ }
+
+ /// Sets the program's description for the short help (`-h`).
+ ///
+ /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`.
+ ///
+ /// **NOTE:** Only `Command::about` (short format) is used in completion
+ /// script generation in order to be concise.
+ ///
+ /// See also [`crate_description!`](crate::crate_description!).
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .about("Does really amazing things for great people")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn about<O: Into<Option<&'help str>>>(mut self, about: O) -> Self {
+ self.about = about.into();
+ self
+ }
+
+ /// Sets the program's description for the long help (`--help`).
+ ///
+ /// If [`Command::about`] is not specified, this message will be displayed for `-h`.
+ ///
+ /// **NOTE:** Only [`Command::about`] (short format) is used in completion
+ /// script generation in order to be concise.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .long_about(
+ /// "Does really amazing things to great people. Now let's talk a little
+ /// more in depth about how this subcommand really works. It may take about
+ /// a few lines of text, but that's ok!")
+ /// # ;
+ /// ```
+ /// [`App::about`]: Command::about()
+ #[must_use]
+ pub fn long_about<O: Into<Option<&'help str>>>(mut self, long_about: O) -> Self {
+ self.long_about = long_about.into();
+ self
+ }
+
+ /// Free-form help text for after auto-generated short help (`-h`).
+ ///
+ /// This is often used to describe how to use the arguments, caveats to be noted, or license
+ /// and contact information.
+ ///
+ /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .after_help("Does really amazing things for great people... but be careful with -R!")
+ /// # ;
+ /// ```
+ ///
+ #[must_use]
+ pub fn after_help<S: Into<&'help str>>(mut self, help: S) -> Self {
+ self.after_help = Some(help.into());
+ self
+ }
+
+ /// Free-form help text for after auto-generated long help (`--help`).
+ ///
+ /// This is often used to describe how to use the arguments, caveats to be noted, or license
+ /// and contact information.
+ ///
+ /// If [`Command::after_help`] is not specified, this message will be displayed for `-h`.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .after_long_help("Does really amazing things to great people... but be careful with -R, \
+ /// like, for real, be careful with this!")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn after_long_help<S: Into<&'help str>>(mut self, help: S) -> Self {
+ self.after_long_help = Some(help.into());
+ self
+ }
+
+ /// Free-form help text for before auto-generated short help (`-h`).
+ ///
+ /// This is often used for header, copyright, or license information.
+ ///
+ /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .before_help("Some info I'd like to appear before the help info")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn before_help<S: Into<&'help str>>(mut self, help: S) -> Self {
+ self.before_help = Some(help.into());
+ self
+ }
+
+ /// Free-form help text for before auto-generated long help (`--help`).
+ ///
+ /// This is often used for header, copyright, or license information.
+ ///
+ /// If [`Command::before_help`] is not specified, this message will be displayed for `-h`.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .before_long_help("Some verbose and long info I'd like to appear before the help info")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn before_long_help<S: Into<&'help str>>(mut self, help: S) -> Self {
+ self.before_long_help = Some(help.into());
+ self
+ }
+
+ /// Sets the version for the short version (`-V`) and help messages.
+ ///
+ /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`.
+ ///
+ /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
+ /// automatically set your application's version to the same thing as your
+ /// crate at compile time.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .version("v0.1.24")
+ /// # ;
+ /// ```
+ /// [`crate_version!`]: ./macro.crate_version!.html
+ #[must_use]
+ pub fn version<S: Into<&'help str>>(mut self, ver: S) -> Self {
+ self.version = Some(ver.into());
+ self
+ }
+
+ /// Sets the version for the long version (`--version`) and help messages.
+ ///
+ /// If [`Command::version`] is not specified, this message will be displayed for `-V`.
+ ///
+ /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
+ /// automatically set your application's version to the same thing as your
+ /// crate at compile time.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .long_version(
+ /// "v0.1.24
+ /// commit: abcdef89726d
+ /// revision: 123
+ /// release: 2
+ /// binary: myprog")
+ /// # ;
+ /// ```
+ /// [`crate_version!`]: ./macro.crate_version!.html
+ #[must_use]
+ pub fn long_version<S: Into<&'help str>>(mut self, ver: S) -> Self {
+ self.long_version = Some(ver.into());
+ self
+ }
+
+ /// Overrides the `clap` generated usage string for help and error messages.
+ ///
+ /// **NOTE:** Using this setting disables `clap`s "context-aware" usage
+ /// 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
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .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 {
+ self.usage_str = Some(usage.into());
+ self
+ }
+
+ /// Overrides the `clap` generated help message (both `-h` and `--help`).
+ ///
+ /// This should only be used when the auto-generated message does not suffice.
+ ///
+ /// **NOTE:** This **only** replaces the help message for the current
+ /// command, meaning if you are using subcommands, those help messages will
+ /// still be auto-generated unless you specify a [`Command::override_help`] for
+ /// them as well.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myapp")
+ /// .override_help("myapp v1.0\n\
+ /// Does awesome things\n\
+ /// (C) me@mail.com\n\n\
+ ///
+ /// USAGE: myapp <opts> <command>\n\n\
+ ///
+ /// Options:\n\
+ /// -h, --help Display this message\n\
+ /// -V, --version Display version info\n\
+ /// -s <stuff> Do something with stuff\n\
+ /// -v Be verbose\n\n\
+ ///
+ /// Commands:\n\
+ /// help Print this message\n\
+ /// work Do some work")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn override_help<S: Into<&'help str>>(mut self, help: S) -> Self {
+ self.help_str = Some(help.into());
+ self
+ }
+
+ /// Sets the help template to be used, overriding the default format.
+ ///
+ /// **NOTE:** The template system is by design very simple. Therefore, the
+ /// tags have to be written in the lowercase and without spacing.
+ ///
+ /// Tags are given inside curly brackets.
+ ///
+ /// Valid tags are:
+ ///
+ /// * `{name}` - Display name for the (sub-)command.
+ /// * `{bin}` - Binary name.
+ /// * `{version}` - Version number.
+ /// * `{author}` - Author information.
+ /// * `{author-with-newline}` - Author followed by `\n`.
+ /// * `{author-section}` - Author preceded and followed by `\n`.
+ /// * `{about}` - General description (from [`Command::about`] or
+ /// [`Command::long_about`]).
+ /// * `{about-with-newline}` - About followed by `\n`.
+ /// * `{about-section}` - About preceded and followed by '\n'.
+ /// * `{usage-heading}` - Automatically generated usage heading.
+ /// * `{usage}` - Automatically generated or given usage string.
+ /// * `{all-args}` - Help for all arguments (options, flags, positional
+ /// arguments, and subcommands) including titles.
+ /// * `{options}` - Help for options.
+ /// * `{positionals}` - Help for positional arguments.
+ /// * `{subcommands}` - Help for subcommands.
+ /// * `{after-help}` - Help from [`App::after_help`] or [`Command::after_long_help`].
+ /// * `{before-help}` - Help from [`App::before_help`] or [`Command::before_long_help`].
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .version("1.0")
+ /// .help_template("{bin} ({version}) - {usage}")
+ /// # ;
+ /// ```
+ /// [`App::about`]: Command::about()
+ /// [`App::long_about`]: Command::long_about()
+ /// [`App::after_help`]: Command::after_help()
+ /// [`App::after_long_help`]: Command::after_long_help()
+ /// [`App::before_help`]: Command::before_help()
+ /// [`App::before_long_help`]: Command::before_long_help()
+ #[must_use]
+ pub fn help_template<S: Into<&'help str>>(mut self, s: S) -> Self {
+ self.template = Some(s.into());
+ self
+ }
+
+ /// Apply a setting for the current command or subcommand.
+ ///
+ /// See [`Command::global_setting`] to apply a setting to this command and all subcommands.
+ ///
+ /// See [`AppSettings`] for a full list of possibilities and examples.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, AppSettings};
+ /// Command::new("myprog")
+ /// .setting(AppSettings::SubcommandRequired)
+ /// .setting(AppSettings::AllowLeadingHyphen)
+ /// # ;
+ /// ```
+ /// or
+ /// ```no_run
+ /// # use clap::{Command, AppSettings};
+ /// Command::new("myprog")
+ /// .setting(AppSettings::SubcommandRequired | AppSettings::AllowLeadingHyphen)
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn setting<F>(mut self, setting: F) -> Self
+ where
+ F: Into<AppFlags>,
+ {
+ self.settings.insert(setting.into());
+ self
+ }
+
+ /// Remove a setting for the current command or subcommand.
+ ///
+ /// See [`AppSettings`] for a full list of possibilities and examples.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, AppSettings};
+ /// Command::new("myprog")
+ /// .unset_setting(AppSettings::SubcommandRequired)
+ /// .setting(AppSettings::AllowLeadingHyphen)
+ /// # ;
+ /// ```
+ /// or
+ /// ```no_run
+ /// # use clap::{Command, AppSettings};
+ /// Command::new("myprog")
+ /// .unset_setting(AppSettings::SubcommandRequired | AppSettings::AllowLeadingHyphen)
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn unset_setting<F>(mut self, setting: F) -> Self
+ where
+ F: Into<AppFlags>,
+ {
+ self.settings.remove(setting.into());
+ self
+ }
+
+ /// Apply a setting for the current command and all subcommands.
+ ///
+ /// See [`Command::setting`] to apply a setting only to this command.
+ ///
+ /// See [`AppSettings`] for a full list of possibilities and examples.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, AppSettings};
+ /// Command::new("myprog")
+ /// .global_setting(AppSettings::AllowNegativeNumbers)
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn global_setting(mut self, setting: AppSettings) -> Self {
+ self.settings.set(setting);
+ self.g_settings.set(setting);
+ self
+ }
+
+ /// Remove a setting and stop propagating down to subcommands.
+ ///
+ /// See [`AppSettings`] for a full list of possibilities and examples.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, AppSettings};
+ /// Command::new("myprog")
+ /// .unset_global_setting(AppSettings::AllowNegativeNumbers)
+ /// # ;
+ /// ```
+ /// [global]: Command::global_setting()
+ #[inline]
+ #[must_use]
+ pub fn unset_global_setting(mut self, setting: AppSettings) -> Self {
+ self.settings.unset(setting);
+ self.g_settings.unset(setting);
+ self
+ }
+
+ /// Deprecated, replaced with [`Command::next_help_heading`]
+ #[inline]
+ #[must_use]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.1.0", note = "Replaced with `App::next_help_heading`")
+ )]
+ pub fn help_heading<O>(self, heading: O) -> Self
+ where
+ O: Into<Option<&'help str>>,
+ {
+ self.next_help_heading(heading)
+ }
+
+ /// Set the default section heading for future args.
+ ///
+ /// This will be used for any arg that hasn't had [`Arg::help_heading`] called.
+ ///
+ /// This is useful if the default `OPTIONS` or `ARGS` headings are
+ /// not specific enough for one's use case.
+ ///
+ /// For subcommands, see [`Command::subcommand_help_heading`]
+ ///
+ /// [`App::arg`]: Command::arg()
+ /// [`Arg::help_heading`]: crate::Arg::help_heading()
+ #[inline]
+ #[must_use]
+ pub fn next_help_heading<O>(mut self, heading: O) -> Self
+ where
+ O: Into<Option<&'help str>>,
+ {
+ self.current_help_heading = heading.into();
+ self
+ }
+
+ /// Change the starting value for assigning future display orders for ags.
+ ///
+ /// This will be used for any arg that hasn't had [`Arg::display_order`] called.
+ #[inline]
+ #[must_use]
+ pub fn next_display_order(mut self, disp_ord: impl Into<Option<usize>>) -> Self {
+ self.current_disp_ord = disp_ord.into();
+ self
+ }
+
+ /// Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands.
+ ///
+ /// **Note:** This is gated behind [`unstable-replace`](https://github.com/clap-rs/clap/issues/2836)
+ ///
+ /// When this method is used, `name` is removed from the CLI, and `target`
+ /// is inserted in its place. Parsing continues as if the user typed
+ /// `target` instead of `name`.
+ ///
+ /// This can be used to create "shortcuts" for subcommands, or if a
+ /// particular argument has the semantic meaning of several other specific
+ /// arguments and values.
+ ///
+ /// # Examples
+ ///
+ /// We'll start with the "subcommand short" example. In this example, let's
+ /// assume we have a program with a subcommand `module` which can be invoked
+ /// via `cmd module`. Now let's also assume `module` also has a subcommand
+ /// called `install` which can be invoked `cmd module install`. If for some
+ /// reason users needed to be able to reach `cmd module install` via the
+ /// short-hand `cmd install`, we'd have several options.
+ ///
+ /// We *could* create another sibling subcommand to `module` called
+ /// `install`, but then we would need to manage another subcommand and manually
+ /// dispatch to `cmd module install` handling code. This is error prone and
+ /// tedious.
+ ///
+ /// We could instead use [`Command::replace`] so that, when the user types `cmd
+ /// install`, `clap` will replace `install` with `module install` which will
+ /// end up getting parsed as if the user typed the entire incantation.
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// let m = Command::new("cmd")
+ /// .subcommand(Command::new("module")
+ /// .subcommand(Command::new("install")))
+ /// .replace("install", &["module", "install"])
+ /// .get_matches_from(vec!["cmd", "install"]);
+ ///
+ /// assert!(m.subcommand_matches("module").is_some());
+ /// assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some());
+ /// ```
+ ///
+ /// Now let's show an argument example!
+ ///
+ /// Let's assume we have an application with two flags `--save-context` and
+ /// `--save-runtime`. But often users end up needing to do *both* at the
+ /// same time. We can add a third flag `--save-all` which semantically means
+ /// the same thing as `cmd --save-context --save-runtime`. To implement that,
+ /// we have several options.
+ ///
+ /// We could create this third argument and manually check if that argument
+ /// and in our own consumer code handle the fact that both `--save-context`
+ /// and `--save-runtime` *should* have been used. But again this is error
+ /// prone and tedious. If we had code relying on checking `--save-context`
+ /// and we forgot to update that code to *also* check `--save-all` it'd mean
+ /// an error!
+ ///
+ /// Luckily we can use [`Command::replace`] so that when the user types
+ /// `--save-all`, `clap` will replace that argument with `--save-context
+ /// --save-runtime`, and parsing will continue like normal. Now all our code
+ /// that was originally checking for things like `--save-context` doesn't
+ /// need to change!
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("cmd")
+ /// .arg(Arg::new("save-context")
+ /// .long("save-context")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("save-runtime")
+ /// .long("save-runtime")
+ /// .action(ArgAction::SetTrue))
+ /// .replace("--save-all", &["--save-context", "--save-runtime"])
+ /// .get_matches_from(vec!["cmd", "--save-all"]);
+ ///
+ /// assert!(*m.get_one::<bool>("save-context").expect("defaulted by clap"));
+ /// assert!(*m.get_one::<bool>("save-runtime").expect("defaulted by clap"));
+ /// ```
+ ///
+ /// This can also be used with options, for example if our application with
+ /// `--save-*` above also had a `--format=TYPE` option. Let's say it
+ /// accepted `txt` or `json` values. However, when `--save-all` is used,
+ /// only `--format=json` is allowed, or valid. We could change the example
+ /// above to enforce this:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("cmd")
+ /// .arg(Arg::new("save-context")
+ /// .long("save-context")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("save-runtime")
+ /// .long("save-runtime")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("format")
+ /// .long("format")
+ /// .takes_value(true)
+ /// .value_parser(["txt", "json"]))
+ /// .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"])
+ /// .get_matches_from(vec!["cmd", "--save-all"]);
+ ///
+ /// assert!(*m.get_one::<bool>("save-context").expect("defaulted by clap"));
+ /// assert!(*m.get_one::<bool>("save-runtime").expect("defaulted by clap"));
+ /// assert_eq!(m.value_of("format"), Some("json"));
+ /// ```
+ ///
+ /// [`App::replace`]: Command::replace()
+ #[inline]
+ #[cfg(feature = "unstable-replace")]
+ #[must_use]
+ pub fn replace(mut self, name: &'help str, target: &'help [&'help str]) -> Self {
+ self.replacers.insert(name, target);
+ self
+ }
+
+ /// Exit gracefully if no arguments are present (e.g. `$ myprog`).
+ ///
+ /// **NOTE:** [`subcommands`] count as arguments
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command};
+ /// Command::new("myprog")
+ /// .arg_required_else_help(true);
+ /// ```
+ ///
+ /// [`subcommands`]: crate::Command::subcommand()
+ /// [`Arg::default_value`]: crate::Arg::default_value()
+ #[inline]
+ pub fn arg_required_else_help(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::ArgRequiredElseHelp)
+ } else {
+ self.unset_setting(AppSettings::ArgRequiredElseHelp)
+ }
+ }
+
+ /// Specifies that leading hyphens are allowed in all argument *values* (e.g. `-10`).
+ ///
+ /// Otherwise they will be parsed as another flag or option. See also
+ /// [`Command::allow_negative_numbers`].
+ ///
+ /// **NOTE:** Use this setting with caution as it silences certain circumstances which would
+ /// otherwise be an error (such as accidentally forgetting to specify a value for leading
+ /// option). It is preferred to set this on a per argument basis, via [`Arg::allow_hyphen_values`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Arg, Command};
+ /// // Imagine you needed to represent negative numbers as well, such as -10
+ /// let m = Command::new("nums")
+ /// .allow_hyphen_values(true)
+ /// .arg(Arg::new("neg"))
+ /// .get_matches_from(vec![
+ /// "nums", "-20"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("neg"), Some("-20"));
+ /// # ;
+ /// ```
+ /// [`Arg::allow_hyphen_values`]: crate::Arg::allow_hyphen_values()
+ #[inline]
+ pub fn allow_hyphen_values(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::AllowHyphenValues)
+ } else {
+ self.unset_setting(AppSettings::AllowHyphenValues)
+ }
+ }
+
+ /// Allows negative numbers to pass as values.
+ ///
+ /// This is similar to [`Command::allow_hyphen_values`] except that it only allows numbers,
+ /// all other undefined leading hyphens will fail to parse.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("myprog")
+ /// .allow_negative_numbers(true)
+ /// .arg(Arg::new("num"))
+ /// .try_get_matches_from(vec![
+ /// "myprog", "-20"
+ /// ]);
+ /// assert!(res.is_ok());
+ /// let m = res.unwrap();
+ /// assert_eq!(m.value_of("num").unwrap(), "-20");
+ /// ```
+ #[inline]
+ pub fn allow_negative_numbers(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::AllowNegativeNumbers)
+ } else {
+ self.unset_setting(AppSettings::AllowNegativeNumbers)
+ }
+ }
+
+ /// Specifies that the final positional argument is a "VarArg" and that `clap` should not
+ /// attempt to parse any further args.
+ ///
+ /// The values of the trailing positional argument will contain all args from itself on.
+ ///
+ /// **NOTE:** The final positional argument **must** have [`Arg::multiple_values(true)`] or the usage
+ /// string equivalent.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, arg};
+ /// let m = Command::new("myprog")
+ /// .trailing_var_arg(true)
+ /// .arg(arg!(<cmd> ... "commands to run"))
+ /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]);
+ ///
+ /// let trail: Vec<&str> = m.values_of("cmd").unwrap().collect();
+ /// assert_eq!(trail, ["arg1", "-r", "val1"]);
+ /// ```
+ /// [`Arg::multiple_values(true)`]: crate::Arg::multiple_values()
+ pub fn trailing_var_arg(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::TrailingVarArg)
+ } else {
+ self.unset_setting(AppSettings::TrailingVarArg)
+ }
+ }
+
+ /// Allows one to implement two styles of CLIs where positionals can be used out of order.
+ ///
+ /// The first example is a CLI where the second to last positional argument is optional, but
+ /// the final positional argument is required. Such as `$ prog [optional] <required>` where one
+ /// of the two following usages is allowed:
+ ///
+ /// * `$ prog [optional] <required>`
+ /// * `$ prog <required>`
+ ///
+ /// This would otherwise not be allowed. This is useful when `[optional]` has a default value.
+ ///
+ /// **Note:** when using this style of "missing positionals" the final positional *must* be
+ /// [required] if `--` will not be used to skip to the final positional argument.
+ ///
+ /// **Note:** This style also only allows a single positional argument to be "skipped" without
+ /// the use of `--`. To skip more than one, see the second example.
+ ///
+ /// The second example is when one wants to skip multiple optional positional arguments, and use
+ /// of the `--` operator is OK (but not required if all arguments will be specified anyways).
+ ///
+ /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where
+ /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments).
+ ///
+ /// With this setting the following invocations are posisble:
+ ///
+ /// * `$ prog foo bar baz1 baz2 baz3`
+ /// * `$ prog foo -- baz1 baz2 baz3`
+ /// * `$ prog -- baz1 baz2 baz3`
+ ///
+ /// # Examples
+ ///
+ /// Style number one from above:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let m = Command::new("myprog")
+ /// .allow_missing_positional(true)
+ /// .arg(Arg::new("arg1"))
+ /// .arg(Arg::new("arg2")
+ /// .required(true))
+ /// .get_matches_from(vec![
+ /// "prog", "other"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("arg1"), None);
+ /// assert_eq!(m.value_of("arg2"), Some("other"));
+ /// ```
+ ///
+ /// Now the same example, but using a default value for the first optional positional argument
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let m = Command::new("myprog")
+ /// .allow_missing_positional(true)
+ /// .arg(Arg::new("arg1")
+ /// .default_value("something"))
+ /// .arg(Arg::new("arg2")
+ /// .required(true))
+ /// .get_matches_from(vec![
+ /// "prog", "other"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("arg1"), Some("something"));
+ /// assert_eq!(m.value_of("arg2"), Some("other"));
+ /// ```
+ ///
+ /// Style number two from above:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let m = Command::new("myprog")
+ /// .allow_missing_positional(true)
+ /// .arg(Arg::new("foo"))
+ /// .arg(Arg::new("bar"))
+ /// .arg(Arg::new("baz").takes_value(true).multiple_values(true))
+ /// .get_matches_from(vec![
+ /// "prog", "foo", "bar", "baz1", "baz2", "baz3"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("foo"), Some("foo"));
+ /// assert_eq!(m.value_of("bar"), Some("bar"));
+ /// assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
+ /// ```
+ ///
+ /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let m = Command::new("myprog")
+ /// .allow_missing_positional(true)
+ /// .arg(Arg::new("foo"))
+ /// .arg(Arg::new("bar"))
+ /// .arg(Arg::new("baz").takes_value(true).multiple_values(true))
+ /// .get_matches_from(vec![
+ /// "prog", "--", "baz1", "baz2", "baz3"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_of("foo"), None);
+ /// assert_eq!(m.value_of("bar"), None);
+ /// assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
+ /// ```
+ ///
+ /// [required]: crate::Arg::required()
+ #[inline]
+ pub fn allow_missing_positional(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::AllowMissingPositional)
+ } else {
+ self.unset_setting(AppSettings::AllowMissingPositional)
+ }
+ }
+}
+
+/// # Subcommand-specific Settings
+impl<'help> App<'help> {
+ /// Sets the short version of the subcommand flag without the preceding `-`.
+ ///
+ /// Allows the subcommand to be used as if it were an [`Arg::short`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let matches = Command::new("pacman")
+ /// .subcommand(
+ /// Command::new("sync").short_flag('S').arg(
+ /// Arg::new("search")
+ /// .short('s')
+ /// .long("search")
+ /// .action(ArgAction::SetTrue)
+ /// .help("search remote repositories for matching strings"),
+ /// ),
+ /// )
+ /// .get_matches_from(vec!["pacman", "-Ss"]);
+ ///
+ /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
+ /// let sync_matches = matches.subcommand_matches("sync").unwrap();
+ /// assert!(*sync_matches.get_one::<bool>("search").expect("defaulted by clap"));
+ /// ```
+ /// [`Arg::short`]: Arg::short()
+ #[must_use]
+ pub fn short_flag(mut self, short: char) -> Self {
+ self.short_flag = Some(short);
+ self
+ }
+
+ /// Sets the long version of the subcommand flag without the preceding `--`.
+ ///
+ /// Allows the subcommand to be used as if it were an [`Arg::long`].
+ ///
+ /// **NOTE:** Any leading `-` characters will be stripped.
+ ///
+ /// # Examples
+ ///
+ /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading
+ /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however,
+ /// will *not* be stripped (i.e. `sync-file` is allowed).
+ ///
+ /// ```
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let matches = Command::new("pacman")
+ /// .subcommand(
+ /// Command::new("sync").long_flag("sync").arg(
+ /// Arg::new("search")
+ /// .short('s')
+ /// .long("search")
+ /// .action(ArgAction::SetTrue)
+ /// .help("search remote repositories for matching strings"),
+ /// ),
+ /// )
+ /// .get_matches_from(vec!["pacman", "--sync", "--search"]);
+ ///
+ /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
+ /// let sync_matches = matches.subcommand_matches("sync").unwrap();
+ /// assert!(*sync_matches.get_one::<bool>("search").expect("defaulted by clap"));
+ /// ```
+ ///
+ /// [`Arg::long`]: Arg::long()
+ #[must_use]
+ pub fn long_flag(mut self, long: &'help str) -> Self {
+ #[cfg(feature = "unstable-v4")]
+ {
+ self.long_flag = Some(long);
+ }
+ #[cfg(not(feature = "unstable-v4"))]
+ {
+ self.long_flag = Some(long.trim_start_matches(|c| c == '-'));
+ }
+ self
+ }
+
+ /// Sets a hidden alias to this subcommand.
+ ///
+ /// This allows the subcommand to be accessed via *either* the original name, or this given
+ /// alias. This is more efficient and easier than creating multiple hidden subcommands as one
+ /// only needs to check for the existence of this command, and not all aliased variants.
+ ///
+ /// **NOTE:** Aliases defined with this method are *hidden* from the help
+ /// message. If you're looking for aliases that will be displayed in the help
+ /// message, see [`Command::visible_alias`].
+ ///
+ /// **NOTE:** When using aliases and checking for the existence of a
+ /// particular subcommand within an [`ArgMatches`] struct, one only needs to
+ /// search for the original name and not all aliases.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test")
+ /// .alias("do-stuff"))
+ /// .get_matches_from(vec!["myprog", "do-stuff"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`App::visible_alias`]: Command::visible_alias()
+ #[must_use]
+ pub fn alias<S: Into<&'help str>>(mut self, name: S) -> Self {
+ self.aliases.push((name.into(), false));
+ self
+ }
+
+ /// Add an alias, which functions as "hidden" short flag subcommand
+ ///
+ /// This will automatically dispatch as if this subcommand was used. This is more efficient,
+ /// and easier than creating multiple hidden subcommands as one only needs to check for the
+ /// existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").short_flag('t')
+ /// .short_flag_alias('d'))
+ /// .get_matches_from(vec!["myprog", "-d"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ #[must_use]
+ pub fn short_flag_alias(mut self, name: char) -> Self {
+ assert!(name != '-', "short alias name cannot be `-`");
+ self.short_flag_aliases.push((name, false));
+ self
+ }
+
+ /// Add an alias, which functions as a "hidden" long flag subcommand.
+ ///
+ /// This will automatically dispatch as if this subcommand was used. This is more efficient,
+ /// and easier than creating multiple hidden subcommands as one only needs to check for the
+ /// existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").long_flag("test")
+ /// .long_flag_alias("testing"))
+ /// .get_matches_from(vec!["myprog", "--testing"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ #[must_use]
+ pub fn long_flag_alias(mut self, name: &'help str) -> Self {
+ self.long_flag_aliases.push((name, false));
+ self
+ }
+
+ /// Sets multiple hidden aliases to this subcommand.
+ ///
+ /// This allows the subcommand to be accessed via *either* the original name or any of the
+ /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands
+ /// as one only needs to check for the existence of this command and not all aliased variants.
+ ///
+ /// **NOTE:** Aliases defined with this method are *hidden* from the help
+ /// message. If looking for aliases that will be displayed in the help
+ /// message, see [`Command::visible_aliases`].
+ ///
+ /// **NOTE:** When using aliases and checking for the existence of a
+ /// particular subcommand within an [`ArgMatches`] struct, one only needs to
+ /// search for the original name and not all aliases.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test")
+ /// .aliases(&["do-stuff", "do-tests", "tests"]))
+ /// .arg(Arg::new("input")
+ /// .help("the file to add")
+ /// .required(false))
+ /// .get_matches_from(vec!["myprog", "do-tests"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`App::visible_aliases`]: Command::visible_aliases()
+ #[must_use]
+ pub fn aliases(mut self, names: &[&'help str]) -> Self {
+ self.aliases.extend(names.iter().map(|n| (*n, false)));
+ self
+ }
+
+ /// Add aliases, which function as "hidden" short flag subcommands.
+ ///
+ /// These will automatically dispatch as if this subcommand was used. This is more efficient,
+ /// and easier than creating multiple hidden subcommands as one only needs to check for the
+ /// existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").short_flag('t')
+ /// .short_flag_aliases(&['a', 'b', 'c']))
+ /// .arg(Arg::new("input")
+ /// .help("the file to add")
+ /// .required(false))
+ /// .get_matches_from(vec!["myprog", "-a"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ #[must_use]
+ pub fn short_flag_aliases(mut self, names: &[char]) -> Self {
+ for s in names {
+ assert!(s != &'-', "short alias name cannot be `-`");
+ self.short_flag_aliases.push((*s, false));
+ }
+ self
+ }
+
+ /// Add aliases, which function as "hidden" long flag subcommands.
+ ///
+ /// These will automatically dispatch as if this subcommand was used. This is more efficient,
+ /// and easier than creating multiple hidden subcommands as one only needs to check for the
+ /// existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").long_flag("test")
+ /// .long_flag_aliases(&["testing", "testall", "test_all"]))
+ /// .arg(Arg::new("input")
+ /// .help("the file to add")
+ /// .required(false))
+ /// .get_matches_from(vec!["myprog", "--testing"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ #[must_use]
+ pub fn long_flag_aliases(mut self, names: &[&'help str]) -> Self {
+ for s in names {
+ self.long_flag_aliases.push((s, false));
+ }
+ self
+ }
+
+ /// Sets a visible alias to this subcommand.
+ ///
+ /// This allows the subcommand to be accessed via *either* the
+ /// original name or the given alias. This is more efficient and easier
+ /// than creating hidden subcommands as one only needs to check for
+ /// the existence of this command and not all aliased variants.
+ ///
+ /// **NOTE:** The alias defined with this method is *visible* from the help
+ /// message and displayed as if it were just another regular subcommand. If
+ /// looking for an alias that will not be displayed in the help message, see
+ /// [`Command::alias`].
+ ///
+ /// **NOTE:** When using aliases and checking for the existence of a
+ /// particular subcommand within an [`ArgMatches`] struct, one only needs to
+ /// search for the original name and not all aliases.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test")
+ /// .visible_alias("do-stuff"))
+ /// .get_matches_from(vec!["myprog", "do-stuff"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`App::alias`]: Command::alias()
+ #[must_use]
+ pub fn visible_alias<S: Into<&'help str>>(mut self, name: S) -> Self {
+ self.aliases.push((name.into(), true));
+ self
+ }
+
+ /// Add an alias, which functions as "visible" short flag subcommand
+ ///
+ /// This will automatically dispatch as if this subcommand was used. This is more efficient,
+ /// and easier than creating multiple hidden subcommands as one only needs to check for the
+ /// existence of this command, and not all variants.
+ ///
+ /// See also [`Command::short_flag_alias`].
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").short_flag('t')
+ /// .visible_short_flag_alias('d'))
+ /// .get_matches_from(vec!["myprog", "-d"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`App::short_flag_alias`]: Command::short_flag_alias()
+ #[must_use]
+ pub fn visible_short_flag_alias(mut self, name: char) -> Self {
+ assert!(name != '-', "short alias name cannot be `-`");
+ self.short_flag_aliases.push((name, true));
+ self
+ }
+
+ /// Add an alias, which functions as a "visible" long flag subcommand.
+ ///
+ /// This will automatically dispatch as if this subcommand was used. This is more efficient,
+ /// and easier than creating multiple hidden subcommands as one only needs to check for the
+ /// existence of this command, and not all variants.
+ ///
+ /// See also [`Command::long_flag_alias`].
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").long_flag("test")
+ /// .visible_long_flag_alias("testing"))
+ /// .get_matches_from(vec!["myprog", "--testing"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`App::long_flag_alias`]: Command::long_flag_alias()
+ #[must_use]
+ pub fn visible_long_flag_alias(mut self, name: &'help str) -> Self {
+ self.long_flag_aliases.push((name, true));
+ self
+ }
+
+ /// Sets multiple visible aliases to this subcommand.
+ ///
+ /// This allows the subcommand to be accessed via *either* the
+ /// original name or any of the given aliases. This is more efficient and easier
+ /// than creating multiple hidden subcommands as one only needs to check for
+ /// the existence of this command and not all aliased variants.
+ ///
+ /// **NOTE:** The alias defined with this method is *visible* from the help
+ /// message and displayed as if it were just another regular subcommand. If
+ /// looking for an alias that will not be displayed in the help message, see
+ /// [`Command::alias`].
+ ///
+ /// **NOTE:** When using aliases, and checking for the existence of a
+ /// particular subcommand within an [`ArgMatches`] struct, one only needs to
+ /// search for the original name and not all aliases.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test")
+ /// .visible_aliases(&["do-stuff", "tests"]))
+ /// .get_matches_from(vec!["myprog", "do-stuff"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`App::alias`]: Command::alias()
+ #[must_use]
+ pub fn visible_aliases(mut self, names: &[&'help str]) -> Self {
+ self.aliases.extend(names.iter().map(|n| (*n, true)));
+ self
+ }
+
+ /// Add aliases, which function as *visible* short flag subcommands.
+ ///
+ /// See [`Command::short_flag_aliases`].
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").short_flag('b')
+ /// .visible_short_flag_aliases(&['t']))
+ /// .get_matches_from(vec!["myprog", "-t"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`App::short_flag_aliases`]: Command::short_flag_aliases()
+ #[must_use]
+ pub fn visible_short_flag_aliases(mut self, names: &[char]) -> Self {
+ for s in names {
+ assert!(s != &'-', "short alias name cannot be `-`");
+ self.short_flag_aliases.push((*s, true));
+ }
+ self
+ }
+
+ /// Add aliases, which function as *visible* long flag subcommands.
+ ///
+ /// See [`Command::long_flag_aliases`].
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").long_flag("test")
+ /// .visible_long_flag_aliases(&["testing", "testall", "test_all"]))
+ /// .get_matches_from(vec!["myprog", "--testing"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`App::long_flag_aliases`]: Command::long_flag_aliases()
+ #[must_use]
+ pub fn visible_long_flag_aliases(mut self, names: &[&'help str]) -> Self {
+ for s in names {
+ self.long_flag_aliases.push((s, true));
+ }
+ self
+ }
+
+ /// Set the placement of this subcommand within the help.
+ ///
+ /// Subcommands with a lower value will be displayed first in the help message. Subcommands
+ /// with duplicate display orders will be displayed in alphabetical order.
+ ///
+ /// This is helpful when one would like to emphasize frequently used subcommands, or prioritize
+ /// those towards the top of the list.
+ ///
+ /// **NOTE:** The default is 999 for all subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, };
+ /// let m = Command::new("cust-ord")
+ /// .subcommand(Command::new("alpha") // typically subcommands are grouped
+ /// // alphabetically by name. Subcommands
+ /// // without a display_order have a value of
+ /// // 999 and are displayed alphabetically with
+ /// // all other 999 subcommands
+ /// .about("Some help and text"))
+ /// .subcommand(Command::new("beta")
+ /// .display_order(1) // In order to force this subcommand to appear *first*
+ /// // all we have to do is give it a value lower than 999.
+ /// // Any other subcommands with a value of 1 will be displayed
+ /// // alphabetically with this one...then 2 values, then 3, etc.
+ /// .about("I should be first!"))
+ /// .get_matches_from(vec![
+ /// "cust-ord", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays the following help message
+ ///
+ /// ```text
+ /// cust-ord
+ ///
+ /// USAGE:
+ /// cust-ord [OPTIONS]
+ ///
+ /// OPTIONS:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ ///
+ /// SUBCOMMANDS:
+ /// beta I should be first!
+ /// alpha Some help and text
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn display_order(mut self, ord: usize) -> Self {
+ self.disp_ord = Some(ord);
+ self
+ }
+
+ /// Specifies that this [`subcommand`] should be hidden from help messages
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .subcommand(
+ /// Command::new("test").hide(true)
+ /// )
+ /// # ;
+ /// ```
+ ///
+ /// [`subcommand`]: crate::Command::subcommand()
+ #[inline]
+ pub fn hide(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::Hidden)
+ } else {
+ self.unset_setting(AppSettings::Hidden)
+ }
+ }
+
+ /// If no [`subcommand`] is present at runtime, error and exit gracefully.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, ErrorKind};
+ /// let err = Command::new("myprog")
+ /// .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);
+ /// # ;
+ /// ```
+ ///
+ /// [`subcommand`]: crate::Command::subcommand()
+ pub fn subcommand_required(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::SubcommandRequired)
+ } else {
+ self.unset_setting(AppSettings::SubcommandRequired)
+ }
+ }
+
+ /// Assume unexpected positional arguments are a [`subcommand`].
+ ///
+ /// Arguments will be stored in the `""` argument in the [`ArgMatches`]
+ ///
+ /// **NOTE:** Use this setting with caution,
+ /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand)
+ /// will **not** cause an error and instead be treated as a potential subcommand.
+ /// One should check for such cases manually and inform the user appropriately.
+ ///
+ /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with
+ /// `--`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let m = Command::new("myprog")
+ /// .allow_external_subcommands(true)
+ /// .get_matches_from(vec![
+ /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
+ /// ]);
+ ///
+ /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
+ /// // string argument name
+ /// match m.subcommand() {
+ /// Some((external, ext_m)) => {
+ /// let ext_args: Vec<&str> = ext_m.values_of("").unwrap().collect();
+ /// assert_eq!(external, "subcmd");
+ /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
+ /// },
+ /// _ => {},
+ /// }
+ /// ```
+ ///
+ /// [`subcommand`]: crate::Command::subcommand()
+ /// [`ArgMatches`]: crate::ArgMatches
+ /// [`ErrorKind::UnknownArgument`]: crate::ErrorKind::UnknownArgument
+ pub fn allow_external_subcommands(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::AllowExternalSubcommands)
+ } else {
+ self.unset_setting(AppSettings::AllowExternalSubcommands)
+ }
+ }
+
+ /// Specifies that external subcommands that are invalid UTF-8 should *not* be treated as an error.
+ ///
+ /// **NOTE:** Using external subcommand argument values with invalid UTF-8 requires using
+ /// [`ArgMatches::values_of_os`] or [`ArgMatches::values_of_lossy`] for those particular
+ /// arguments which may contain invalid UTF-8 values
+ ///
+ /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`]
+ ///
+ /// # Platform Specific
+ ///
+ /// Non Windows systems only
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(unix), doc = " ```ignore")]
+ #[cfg_attr(unix, doc = " ```")]
+ /// # use clap::Command;
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let m = Command::new("myprog")
+ /// .allow_invalid_utf8_for_external_subcommands(true)
+ /// .allow_external_subcommands(true)
+ /// .get_matches_from(vec![
+ /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
+ /// ]);
+ ///
+ /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
+ /// // string argument name
+ /// match m.subcommand() {
+ /// Some((external, ext_m)) => {
+ /// let ext_args: Vec<&std::ffi::OsStr> = ext_m.values_of_os("").unwrap().collect();
+ /// assert_eq!(external, "subcmd");
+ /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
+ /// },
+ /// _ => {},
+ /// }
+ /// ```
+ ///
+ /// [`ArgMatches::values_of_os`]: crate::ArgMatches::values_of_os()
+ /// [`ArgMatches::values_of_lossy`]: crate::ArgMatches::values_of_lossy()
+ /// [`subcommands`]: crate::Command::subcommand()
+ pub fn allow_invalid_utf8_for_external_subcommands(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands)
+ } else {
+ self.unset_setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands)
+ }
+ }
+
+ /// Specifies that use of an argument prevents the use of [`subcommands`].
+ ///
+ /// By default `clap` allows arguments between subcommands such
+ /// as `<cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args]`.
+ ///
+ /// This setting disables that functionality and says that arguments can
+ /// only follow the *final* subcommand. For instance using this setting
+ /// makes only the following invocations possible:
+ ///
+ /// * `<cmd> <subcmd> <subsubcmd> [subsubcmd_args]`
+ /// * `<cmd> <subcmd> [subcmd_args]`
+ /// * `<cmd> [cmd_args]`
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .args_conflicts_with_subcommands(true);
+ /// ```
+ ///
+ /// [`subcommands`]: crate::Command::subcommand()
+ pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::ArgsNegateSubcommands)
+ } else {
+ self.unset_setting(AppSettings::ArgsNegateSubcommands)
+ }
+ }
+
+ /// Prevent subcommands from being consumed as an arguments value.
+ ///
+ /// By default, if an option taking multiple values is followed by a subcommand, the
+ /// subcommand will be parsed as another value.
+ ///
+ /// ```text
+ /// cmd --foo val1 val2 subcommand
+ /// --------- ----------
+ /// values another value
+ /// ```
+ ///
+ /// This setting instructs the parser to stop when encountering a subcommand instead of
+ /// greedily consuming arguments.
+ ///
+ /// ```text
+ /// cmd --foo val1 val2 subcommand
+ /// --------- ----------
+ /// values subcommand
+ /// ```
+ ///
+ /// **Note:** Make sure you apply it as `global_setting` if you want this setting
+ /// to be propagated to subcommands and sub-subcommands!
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg(
+ /// Arg::new("arg")
+ /// .long("arg")
+ /// .multiple_values(true)
+ /// .takes_value(true),
+ /// );
+ ///
+ /// let matches = cmd
+ /// .clone()
+ /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
+ /// .unwrap();
+ /// assert_eq!(
+ /// matches.values_of("arg").unwrap().collect::<Vec<_>>(),
+ /// &["1", "2", "3", "sub"]
+ /// );
+ /// assert!(matches.subcommand_matches("sub").is_none());
+ ///
+ /// let matches = cmd
+ /// .subcommand_precedence_over_arg(true)
+ /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
+ /// .unwrap();
+ /// assert_eq!(
+ /// matches.values_of("arg").unwrap().collect::<Vec<_>>(),
+ /// &["1", "2", "3"]
+ /// );
+ /// assert!(matches.subcommand_matches("sub").is_some());
+ /// ```
+ pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::SubcommandPrecedenceOverArg)
+ } else {
+ self.unset_setting(AppSettings::SubcommandPrecedenceOverArg)
+ }
+ }
+
+ /// Allows [`subcommands`] to override all requirements of the parent command.
+ ///
+ /// For example, if you had a subcommand or top level application with a required argument
+ /// that is only required as long as there is no subcommand present,
+ /// using this setting would allow you to set those arguments to [`Arg::required(true)`]
+ /// and yet receive no error so long as the user uses a valid subcommand instead.
+ ///
+ /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements)
+ ///
+ /// # Examples
+ ///
+ /// This first example shows that it is an error to not use a required argument
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let err = Command::new("myprog")
+ /// .subcommand_negates_reqs(true)
+ /// .arg(Arg::new("opt").required(true))
+ /// .subcommand(Command::new("test"))
+ /// .try_get_matches_from(vec![
+ /// "myprog"
+ /// ]);
+ /// assert!(err.is_err());
+ /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// # ;
+ /// ```
+ ///
+ /// This next example shows that it is no longer error to not use a required argument if a
+ /// valid subcommand is used.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ErrorKind};
+ /// let noerr = Command::new("myprog")
+ /// .subcommand_negates_reqs(true)
+ /// .arg(Arg::new("opt").required(true))
+ /// .subcommand(Command::new("test"))
+ /// .try_get_matches_from(vec![
+ /// "myprog", "test"
+ /// ]);
+ /// assert!(noerr.is_ok());
+ /// # ;
+ /// ```
+ ///
+ /// [`Arg::required(true)`]: crate::Arg::required()
+ /// [`subcommands`]: crate::Command::subcommand()
+ pub fn subcommand_negates_reqs(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::SubcommandsNegateReqs)
+ } else {
+ self.unset_setting(AppSettings::SubcommandsNegateReqs)
+ }
+ }
+
+ /// Multiple-personality program dispatched on the binary name (`argv[0]`)
+ ///
+ /// A "multicall" executable is a single executable
+ /// that contains a variety of applets,
+ /// and decides which applet to run based on the name of the file.
+ /// The executable can be called from different names by creating hard links
+ /// or symbolic links to it.
+ ///
+ /// This is desirable for:
+ /// - Easy distribution, a single binary that can install hardlinks to access the different
+ /// personalities.
+ /// - Minimal binary size by sharing common code (e.g. standard library, clap)
+ /// - Custom shells or REPLs where there isn't a single top-level command
+ ///
+ /// Setting `multicall` will cause
+ /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if
+ /// [`Command::no_binary_name`][App::no_binary_name] was set.
+ /// - Help and errors to report subcommands as if they were the top-level command
+ ///
+ /// When the subcommand is not present, there are several strategies you may employ, depending
+ /// on your needs:
+ /// - Let the error percolate up normally
+ /// - Print a specialized error message using the
+ /// [`Error::context`][crate::Error::context]
+ /// - Print the [help][App::write_help] but this might be ambiguous
+ /// - Disable `multicall` and re-parse it
+ /// - Disable `multicall` and re-parse it with a specific subcommand
+ ///
+ /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand
+ /// might report the same error. Enable
+ /// [`allow_external_subcommands`][App::allow_external_subcommands] if you want to specifically
+ /// get the unrecognized binary name.
+ ///
+ /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret
+ /// the command name in incompatible ways.
+ ///
+ /// **NOTE:** The multicall command cannot have arguments.
+ ///
+ /// **NOTE:** Applets are slightly semantically different from subcommands,
+ /// so it's recommended to use [`Command::subcommand_help_heading`] and
+ /// [`Command::subcommand_value_name`] to change the descriptive text as above.
+ ///
+ /// # Examples
+ ///
+ /// `hostname` is an example of a multicall executable.
+ /// Both `hostname` and `dnsdomainname` are provided by the same executable
+ /// and which behaviour to use is based on the executable file name.
+ ///
+ /// This is desirable when the executable has a primary purpose
+ /// but there is related functionality that would be convenient to provide
+ /// and implement it to be in the same executable.
+ ///
+ /// The name of the cmd is essentially unused
+ /// and may be the same as the name of a subcommand.
+ ///
+ /// The names of the immediate subcommands of the Command
+ /// are matched against the basename of the first argument,
+ /// which is conventionally the path of the executable.
+ ///
+ /// This does not allow the subcommand to be passed as the first non-path argument.
+ ///
+ /// ```rust
+ /// # use clap::{Command, ErrorKind};
+ /// let mut cmd = Command::new("hostname")
+ /// .multicall(true)
+ /// .subcommand(Command::new("hostname"))
+ /// .subcommand(Command::new("dnsdomainname"));
+ /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]);
+ /// assert!(m.is_err());
+ /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument);
+ /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]);
+ /// assert_eq!(m.subcommand_name(), Some("dnsdomainname"));
+ /// ```
+ ///
+ /// Busybox is another common example of a multicall executable
+ /// with a subcommmand for each applet that can be run directly,
+ /// e.g. with the `cat` applet being run by running `busybox cat`,
+ /// or with `cat` as a link to the `busybox` binary.
+ ///
+ /// This is desirable when the launcher program has additional options
+ /// or it is useful to run the applet without installing a symlink
+ /// e.g. to test the applet without installing it
+ /// or there may already be a command of that name installed.
+ ///
+ /// To make an applet usable as both a multicall link and a subcommand
+ /// the subcommands must be defined both in the top-level Command
+ /// and as subcommands of the "main" applet.
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// fn applet_commands() -> [Command<'static>; 2] {
+ /// [Command::new("true"), Command::new("false")]
+ /// }
+ /// let mut cmd = Command::new("busybox")
+ /// .multicall(true)
+ /// .subcommand(
+ /// Command::new("busybox")
+ /// .subcommand_value_name("APPLET")
+ /// .subcommand_help_heading("APPLETS")
+ /// .subcommands(applet_commands()),
+ /// )
+ /// .subcommands(applet_commands());
+ /// // When called from the executable's canonical name
+ /// // its applets can be matched as subcommands.
+ /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap();
+ /// assert_eq!(m.subcommand_name(), Some("busybox"));
+ /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true"));
+ /// // When called from a link named after an applet that applet is matched.
+ /// let m = cmd.get_matches_from(&["/usr/bin/true"]);
+ /// assert_eq!(m.subcommand_name(), Some("true"));
+ /// ```
+ ///
+ /// [`no_binary_name`]: crate::Command::no_binary_name
+ /// [`App::subcommand_value_name`]: crate::Command::subcommand_value_name
+ /// [`App::subcommand_help_heading`]: crate::Command::subcommand_help_heading
+ #[inline]
+ pub fn multicall(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::Multicall)
+ } else {
+ self.unset_setting(AppSettings::Multicall)
+ }
+ }
+
+ /// Sets the value name used for subcommands when printing usage and help.
+ ///
+ /// By default, this is "SUBCOMMAND".
+ ///
+ /// See also [`Command::subcommand_help_heading`]
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .subcommand(Command::new("sub1"))
+ /// .print_help()
+ /// # ;
+ /// ```
+ ///
+ /// will produce
+ ///
+ /// ```text
+ /// myprog
+ ///
+ /// USAGE:
+ /// myprog [SUBCOMMAND]
+ ///
+ /// OPTIONS:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ ///
+ /// SUBCOMMANDS:
+ /// help Print this message or the help of the given subcommand(s)
+ /// sub1
+ /// ```
+ ///
+ /// but usage of `subcommand_value_name`
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .subcommand(Command::new("sub1"))
+ /// .subcommand_value_name("THING")
+ /// .print_help()
+ /// # ;
+ /// ```
+ ///
+ /// will produce
+ ///
+ /// ```text
+ /// myprog
+ ///
+ /// USAGE:
+ /// myprog [THING]
+ ///
+ /// OPTIONS:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ ///
+ /// SUBCOMMANDS:
+ /// help Print this message or the help of the given subcommand(s)
+ /// sub1
+ /// ```
+ #[must_use]
+ pub fn subcommand_value_name<S>(mut self, value_name: S) -> Self
+ where
+ S: Into<&'help str>,
+ {
+ self.subcommand_value_name = Some(value_name.into());
+ self
+ }
+
+ /// Sets the help heading used for subcommands when printing usage and help.
+ ///
+ /// By default, this is "SUBCOMMANDS".
+ ///
+ /// See also [`Command::subcommand_value_name`]
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .subcommand(Command::new("sub1"))
+ /// .print_help()
+ /// # ;
+ /// ```
+ ///
+ /// will produce
+ ///
+ /// ```text
+ /// myprog
+ ///
+ /// USAGE:
+ /// myprog [SUBCOMMAND]
+ ///
+ /// OPTIONS:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ ///
+ /// SUBCOMMANDS:
+ /// help Print this message or the help of the given subcommand(s)
+ /// sub1
+ /// ```
+ ///
+ /// but usage of `subcommand_help_heading`
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .subcommand(Command::new("sub1"))
+ /// .subcommand_help_heading("THINGS")
+ /// .print_help()
+ /// # ;
+ /// ```
+ ///
+ /// will produce
+ ///
+ /// ```text
+ /// myprog
+ ///
+ /// USAGE:
+ /// myprog [SUBCOMMAND]
+ ///
+ /// OPTIONS:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ ///
+ /// THINGS:
+ /// help Print this message or the help of the given subcommand(s)
+ /// sub1
+ /// ```
+ #[must_use]
+ pub fn subcommand_help_heading<T>(mut self, heading: T) -> Self
+ where
+ T: Into<&'help str>,
+ {
+ self.subcommand_heading = Some(heading.into());
+ self
+ }
+}
+
+/// # Reflection
+impl<'help> App<'help> {
+ #[inline]
+ pub(crate) fn get_usage_name(&self) -> Option<&str> {
+ self.usage_name.as_deref()
+ }
+
+ /// Get the name of the binary.
+ #[inline]
+ pub fn get_display_name(&self) -> Option<&str> {
+ self.display_name.as_deref()
+ }
+
+ /// Get the name of the binary.
+ #[inline]
+ pub fn get_bin_name(&self) -> Option<&str> {
+ self.bin_name.as_deref()
+ }
+
+ /// Set binary name. Uses `&mut self` instead of `self`.
+ pub fn set_bin_name<S: Into<String>>(&mut self, name: S) {
+ self.bin_name = Some(name.into());
+ }
+
+ /// Get the name of the cmd.
+ #[inline]
+ pub fn get_name(&self) -> &str {
+ &self.name
+ }
+
+ /// Get the version of the cmd.
+ #[inline]
+ pub fn get_version(&self) -> Option<&'help str> {
+ self.version
+ }
+
+ /// Get the long version of the cmd.
+ #[inline]
+ pub fn get_long_version(&self) -> Option<&'help str> {
+ self.long_version
+ }
+
+ /// Get the authors of the cmd.
+ #[inline]
+ pub fn get_author(&self) -> Option<&'help str> {
+ self.author
+ }
+
+ /// Get the short flag of the subcommand.
+ #[inline]
+ pub fn get_short_flag(&self) -> Option<char> {
+ self.short_flag
+ }
+
+ /// Get the long flag of the subcommand.
+ #[inline]
+ pub fn get_long_flag(&self) -> Option<&'help str> {
+ self.long_flag
+ }
+
+ /// Get the help message specified via [`Command::about`].
+ ///
+ /// [`App::about`]: Command::about()
+ #[inline]
+ pub fn get_about(&self) -> Option<&'help str> {
+ self.about
+ }
+
+ /// Get the help message specified via [`Command::long_about`].
+ ///
+ /// [`App::long_about`]: Command::long_about()
+ #[inline]
+ pub fn get_long_about(&self) -> Option<&'help str> {
+ self.long_about
+ }
+
+ /// Deprecated, replaced with [`Command::get_next_help_heading`]
+ #[inline]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.1.0", note = "Replaced with `App::get_next_help_heading`")
+ )]
+ pub fn get_help_heading(&self) -> Option<&'help str> {
+ self.get_next_help_heading()
+ }
+
+ /// Get the custom section heading specified via [`Command::help_heading`].
+ ///
+ /// [`App::help_heading`]: Command::help_heading()
+ #[inline]
+ pub fn get_next_help_heading(&self) -> Option<&'help str> {
+ self.current_help_heading
+ }
+
+ /// Iterate through the *visible* aliases for this subcommand.
+ #[inline]
+ pub fn get_visible_aliases(&self) -> impl Iterator<Item = &'help str> + '_ {
+ self.aliases.iter().filter(|(_, vis)| *vis).map(|a| a.0)
+ }
+
+ /// Iterate through the *visible* short aliases for this subcommand.
+ #[inline]
+ pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
+ self.short_flag_aliases
+ .iter()
+ .filter(|(_, vis)| *vis)
+ .map(|a| a.0)
+ }
+
+ /// Iterate through the *visible* long aliases for this subcommand.
+ #[inline]
+ pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &'help str> + '_ {
+ self.long_flag_aliases
+ .iter()
+ .filter(|(_, vis)| *vis)
+ .map(|a| a.0)
+ }
+
+ /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden.
+ #[inline]
+ pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> + '_ {
+ self.aliases.iter().map(|a| a.0)
+ }
+
+ /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden.
+ #[inline]
+ pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
+ self.short_flag_aliases.iter().map(|a| a.0)
+ }
+
+ /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden.
+ #[inline]
+ pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &'help str> + '_ {
+ self.long_flag_aliases.iter().map(|a| a.0)
+ }
+
+ /// Check if the given [`AppSettings`] variant is currently set on the `Command`.
+ ///
+ /// This checks both [local] and [global settings].
+ ///
+ /// [local]: Command::setting()
+ /// [global settings]: Command::global_setting()
+ #[inline]
+ pub fn is_set(&self, s: AppSettings) -> bool {
+ self.settings.is_set(s) || self.g_settings.is_set(s)
+ }
+
+ /// Should we color the output?
+ #[inline(never)]
+ pub fn get_color(&self) -> ColorChoice {
+ debug!("Command::color: Color setting...");
+
+ if cfg!(feature = "color") {
+ #[allow(deprecated)]
+ if self.is_set(AppSettings::ColorNever) {
+ debug!("Never");
+ ColorChoice::Never
+ } else if self.is_set(AppSettings::ColorAlways) {
+ debug!("Always");
+ ColorChoice::Always
+ } else {
+ debug!("Auto");
+ ColorChoice::Auto
+ }
+ } else {
+ ColorChoice::Never
+ }
+ }
+
+ /// Iterate through the set of subcommands, getting a reference to each.
+ #[inline]
+ pub fn get_subcommands(&self) -> impl Iterator<Item = &App<'help>> {
+ 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<Item = &mut App<'help>> {
+ self.subcommands.iter_mut()
+ }
+
+ /// Returns `true` if this `Command` has subcommands.
+ #[inline]
+ pub fn has_subcommands(&self) -> bool {
+ !self.subcommands.is_empty()
+ }
+
+ /// Returns the help heading for listing subcommands.
+ #[inline]
+ pub fn get_subcommand_help_heading(&self) -> Option<&str> {
+ self.subcommand_heading
+ }
+
+ /// Deprecated, replaced with [`App::get_subcommand_help_heading`]
+ #[inline]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `App::get_subcommand_help_heading`"
+ )
+ )]
+ pub fn get_subommand_help_heading(&self) -> Option<&str> {
+ self.get_subcommand_help_heading()
+ }
+
+ /// Returns the subcommand value name.
+ #[inline]
+ pub fn get_subcommand_value_name(&self) -> Option<&str> {
+ self.subcommand_value_name
+ }
+
+ /// Returns the help heading for listing subcommands.
+ #[inline]
+ pub fn get_before_help(&self) -> Option<&str> {
+ self.before_help
+ }
+
+ /// Returns the help heading for listing subcommands.
+ #[inline]
+ pub fn get_before_long_help(&self) -> Option<&str> {
+ self.before_long_help
+ }
+
+ /// Returns the help heading for listing subcommands.
+ #[inline]
+ pub fn get_after_help(&self) -> Option<&str> {
+ self.after_help
+ }
+
+ /// Returns the help heading for listing subcommands.
+ #[inline]
+ pub fn get_after_long_help(&self) -> Option<&str> {
+ self.after_long_help
+ }
+
+ /// Find subcommand such that its name or one of aliases equals `name`.
+ ///
+ /// This does not recurse through subcommands of subcommands.
+ #[inline]
+ pub fn find_subcommand<T>(&self, name: &T) -> Option<&App<'help>>
+ where
+ T: PartialEq<str> + ?Sized,
+ {
+ self.get_subcommands().find(|s| s.aliases_to(name))
+ }
+
+ /// Find subcommand such that its name or one of aliases equals `name`, returning
+ /// a mutable reference to the subcommand.
+ ///
+ /// This does not recurse through subcommands of subcommands.
+ #[inline]
+ pub fn find_subcommand_mut<T>(&mut self, name: &T) -> Option<&mut App<'help>>
+ where
+ T: PartialEq<str> + ?Sized,
+ {
+ self.get_subcommands_mut().find(|s| s.aliases_to(name))
+ }
+
+ /// Iterate through the set of groups.
+ #[inline]
+ pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup<'help>> {
+ self.groups.iter()
+ }
+
+ /// Iterate through the set of arguments.
+ #[inline]
+ pub fn get_arguments(&self) -> impl Iterator<Item = &Arg<'help>> {
+ self.args.args()
+ }
+
+ /// Iterate through the *positionals* arguments.
+ #[inline]
+ pub fn get_positionals(&self) -> impl Iterator<Item = &Arg<'help>> {
+ self.get_arguments().filter(|a| a.is_positional())
+ }
+
+ /// Iterate through the *options*.
+ pub fn get_opts(&self) -> impl Iterator<Item = &Arg<'help>> {
+ self.get_arguments()
+ .filter(|a| a.is_takes_value_set() && !a.is_positional())
+ }
+
+ /// Get a list of all arguments the given argument conflicts with.
+ ///
+ /// If the provided argument is declared as global, the conflicts will be determined
+ /// based on the propagation rules of global arguments.
+ ///
+ /// ### Panics
+ ///
+ /// If the given arg contains a conflict with an argument that is unknown to
+ /// this `Command`.
+ pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // FIXME: This could probably have been an iterator
+ {
+ if arg.is_global_set() {
+ self.get_global_arg_conflicts_with(arg)
+ } else {
+ 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
+ }
+ }
+
+ // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with.
+ //
+ // This behavior follows the propagation rules of global arguments.
+ // It is useful for finding conflicts for arguments declared as global.
+ //
+ // ### Panics
+ //
+ // If the given arg contains a conflict with an argument that is unknown to
+ // this `App`.
+ fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // FIXME: This could probably have been an iterator
+ {
+ arg.blacklist
+ .iter()
+ .map(|id| {
+ self.args
+ .args()
+ .chain(
+ self.get_subcommands_containing(arg)
+ .iter()
+ .flat_map(|x| x.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()
+ }
+
+ // Get a list of subcommands which contain the provided Argument
+ //
+ // This command will only include subcommands in its list for which the subcommands
+ // parent also contains the Argument.
+ //
+ // This search follows the propagation rules of global arguments.
+ // It is useful to finding subcommands, that have inherited a global argument.
+ //
+ // **NOTE:** In this case only Sucommand_1 will be included
+ // Subcommand_1 (contains Arg)
+ // Subcommand_1.1 (doesn't contain Arg)
+ // Subcommand_1.1.1 (contains Arg)
+ //
+ fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&App<'help>> {
+ let mut vec = std::vec::Vec::new();
+ for idx in 0..self.subcommands.len() {
+ if self.subcommands[idx].args.args().any(|ar| ar.id == arg.id) {
+ vec.push(&self.subcommands[idx]);
+ vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg));
+ }
+ }
+ vec
+ }
+
+ /// Report whether [`Command::no_binary_name`] is set
+ pub fn is_no_binary_name_set(&self) -> bool {
+ self.is_set(AppSettings::NoBinaryName)
+ }
+
+ /// Report whether [`Command::ignore_errors`] is set
+ pub(crate) fn is_ignore_errors_set(&self) -> bool {
+ self.is_set(AppSettings::IgnoreErrors)
+ }
+
+ /// Report whether [`Command::dont_delimit_trailing_values`] is set
+ pub fn is_dont_delimit_trailing_values_set(&self) -> bool {
+ self.is_set(AppSettings::DontDelimitTrailingValues)
+ }
+
+ /// Report whether [`Command::disable_version_flag`] is set
+ pub fn is_disable_version_flag_set(&self) -> bool {
+ self.is_set(AppSettings::DisableVersionFlag)
+ }
+
+ /// Report whether [`Command::propagate_version`] is set
+ pub fn is_propagate_version_set(&self) -> bool {
+ self.is_set(AppSettings::PropagateVersion)
+ }
+
+ /// Report whether [`Command::next_line_help`] is set
+ pub fn is_next_line_help_set(&self) -> bool {
+ self.is_set(AppSettings::NextLineHelp)
+ }
+
+ /// Report whether [`Command::disable_help_flag`] is set
+ pub fn is_disable_help_flag_set(&self) -> bool {
+ self.is_set(AppSettings::DisableHelpFlag)
+ }
+
+ /// Report whether [`Command::disable_help_subcommand`] is set
+ pub fn is_disable_help_subcommand_set(&self) -> bool {
+ self.is_set(AppSettings::DisableHelpSubcommand)
+ }
+
+ /// Report whether [`Command::disable_colored_help`] is set
+ pub fn is_disable_colored_help_set(&self) -> bool {
+ self.is_set(AppSettings::DisableColoredHelp)
+ }
+
+ /// Report whether [`Command::help_expected`] is set
+ #[cfg(debug_assertions)]
+ pub(crate) fn is_help_expected_set(&self) -> bool {
+ self.is_set(AppSettings::HelpExpected)
+ }
+
+ /// Report whether [`Command::dont_collapse_args_in_usage`] is set
+ pub fn is_dont_collapse_args_in_usage_set(&self) -> bool {
+ self.is_set(AppSettings::DontCollapseArgsInUsage)
+ }
+
+ /// Report whether [`Command::infer_long_args`] is set
+ pub(crate) fn is_infer_long_args_set(&self) -> bool {
+ self.is_set(AppSettings::InferLongArgs)
+ }
+
+ /// Report whether [`Command::infer_subcommands`] is set
+ pub(crate) fn is_infer_subcommands_set(&self) -> bool {
+ self.is_set(AppSettings::InferSubcommands)
+ }
+
+ /// Report whether [`Command::arg_required_else_help`] is set
+ pub fn is_arg_required_else_help_set(&self) -> bool {
+ self.is_set(AppSettings::ArgRequiredElseHelp)
+ }
+
+ /// Report whether [`Command::allow_hyphen_values`] is set
+ pub(crate) fn is_allow_hyphen_values_set(&self) -> bool {
+ self.is_set(AppSettings::AllowHyphenValues)
+ }
+
+ /// Report whether [`Command::allow_negative_numbers`] is set
+ pub fn is_allow_negative_numbers_set(&self) -> bool {
+ self.is_set(AppSettings::AllowNegativeNumbers)
+ }
+
+ /// Report whether [`Command::trailing_var_arg`] is set
+ pub fn is_trailing_var_arg_set(&self) -> bool {
+ self.is_set(AppSettings::TrailingVarArg)
+ }
+
+ /// Report whether [`Command::allow_missing_positional`] is set
+ pub fn is_allow_missing_positional_set(&self) -> bool {
+ self.is_set(AppSettings::AllowMissingPositional)
+ }
+
+ /// Report whether [`Command::hide`] is set
+ pub fn is_hide_set(&self) -> bool {
+ self.is_set(AppSettings::Hidden)
+ }
+
+ /// Report whether [`Command::subcommand_required`] is set
+ pub fn is_subcommand_required_set(&self) -> bool {
+ self.is_set(AppSettings::SubcommandRequired)
+ }
+
+ /// Report whether [`Command::allow_external_subcommands`] is set
+ pub fn is_allow_external_subcommands_set(&self) -> bool {
+ self.is_set(AppSettings::AllowExternalSubcommands)
+ }
+
+ /// Report whether [`Command::allow_invalid_utf8_for_external_subcommands`] is set
+ pub fn is_allow_invalid_utf8_for_external_subcommands_set(&self) -> bool {
+ self.is_set(AppSettings::AllowInvalidUtf8ForExternalSubcommands)
+ }
+
+ /// Configured parser for values passed to an external subcommand
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// let cmd = clap::Command::new("raw")
+ /// .allow_external_subcommands(true)
+ /// .allow_invalid_utf8_for_external_subcommands(true);
+ /// let value_parser = cmd.get_external_subcommand_value_parser();
+ /// println!("{:?}", value_parser);
+ /// ```
+ pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> {
+ if !self.is_allow_external_subcommands_set() {
+ None
+ } else if self.is_allow_invalid_utf8_for_external_subcommands_set() {
+ static DEFAULT: super::ValueParser = super::ValueParser::os_string();
+ Some(&DEFAULT)
+ } else {
+ static DEFAULT: super::ValueParser = super::ValueParser::string();
+ Some(&DEFAULT)
+ }
+ }
+
+ /// Report whether [`Command::args_conflicts_with_subcommands`] is set
+ pub fn is_args_conflicts_with_subcommands_set(&self) -> bool {
+ self.is_set(AppSettings::ArgsNegateSubcommands)
+ }
+
+ /// Report whether [`Command::subcommand_precedence_over_arg`] is set
+ pub fn is_subcommand_precedence_over_arg_set(&self) -> bool {
+ self.is_set(AppSettings::SubcommandPrecedenceOverArg)
+ }
+
+ /// Report whether [`Command::subcommand_negates_reqs`] is set
+ pub fn is_subcommand_negates_reqs_set(&self) -> bool {
+ self.is_set(AppSettings::SubcommandsNegateReqs)
+ }
+
+ /// Report whether [`Command::multicall`] is set
+ pub fn is_multicall_set(&self) -> bool {
+ self.is_set(AppSettings::Multicall)
+ }
+}
+
+/// Deprecated
+impl<'help> App<'help> {
+ /// 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(y: &'help Yaml) -> Self {
+ #![allow(deprecated)]
+ let yaml_file_hash = y.as_hash().expect("YAML file must be a hash");
+ // We WANT this to panic on error...so expect() is good.
+ let (mut a, yaml, err) = if let Some(name) = y["name"].as_str() {
+ (App::new(name), yaml_file_hash, "cmd".into())
+ } else {
+ let (name_yaml, value_yaml) = yaml_file_hash
+ .iter()
+ .next()
+ .expect("There must be one subcommand in the YAML file");
+ let name_str = name_yaml
+ .as_str()
+ .expect("Subcommand name must be a string");
+
+ (
+ App::new(name_str),
+ value_yaml.as_hash().expect("Subcommand must be a hash"),
+ format!("subcommand '{}'", name_str),
+ )
+ };
+
+ for (k, v) in yaml {
+ a = match k.as_str().expect("App fields must be strings") {
+ "version" => yaml_to_str!(a, v, version),
+ "long_version" => yaml_to_str!(a, v, long_version),
+ "author" => yaml_to_str!(a, v, author),
+ "bin_name" => yaml_to_str!(a, v, bin_name),
+ "about" => yaml_to_str!(a, v, about),
+ "long_about" => yaml_to_str!(a, v, long_about),
+ "before_help" => yaml_to_str!(a, v, before_help),
+ "after_help" => yaml_to_str!(a, v, after_help),
+ "template" => yaml_to_str!(a, v, help_template),
+ "usage" => yaml_to_str!(a, v, override_usage),
+ "help" => yaml_to_str!(a, v, override_help),
+ "help_message" => yaml_to_str!(a, v, help_message),
+ "version_message" => yaml_to_str!(a, v, version_message),
+ "alias" => yaml_to_str!(a, v, alias),
+ "aliases" => yaml_vec_or_str!(a, v, alias),
+ "visible_alias" => yaml_to_str!(a, v, visible_alias),
+ "visible_aliases" => yaml_vec_or_str!(a, v, visible_alias),
+ "display_order" => yaml_to_usize!(a, v, display_order),
+ "args" => {
+ if let Some(vec) = v.as_vec() {
+ for arg_yaml in vec {
+ a = a.arg(Arg::from_yaml(arg_yaml));
+ }
+ } else {
+ panic!("Failed to convert YAML value {:?} to a vec", v);
+ }
+ a
+ }
+ "subcommands" => {
+ if let Some(vec) = v.as_vec() {
+ for sc_yaml in vec {
+ a = a.subcommand(App::from_yaml(sc_yaml));
+ }
+ } else {
+ panic!("Failed to convert YAML value {:?} to a vec", v);
+ }
+ a
+ }
+ "groups" => {
+ if let Some(vec) = v.as_vec() {
+ for ag_yaml in vec {
+ a = a.group(ArgGroup::from(ag_yaml));
+ }
+ } else {
+ panic!("Failed to convert YAML value {:?} to a vec", v);
+ }
+ a
+ }
+ "setting" | "settings" => {
+ yaml_to_setting!(a, v, setting, AppSettings, "AppSetting", err)
+ }
+ "global_setting" | "global_settings" => {
+ yaml_to_setting!(a, v, global_setting, AppSettings, "AppSetting", err)
+ }
+ _ => a,
+ }
+ }
+
+ a
+ }
+
+ /// Deprecated, replaced with [`Command::override_usage`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::override_usage`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn usage<S: Into<&'help str>>(self, usage: S) -> Self {
+ self.override_usage(usage)
+ }
+
+ /// Deprecated, replaced with [`Command::override_help`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::override_help`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn help<S: Into<&'help str>>(self, help: S) -> Self {
+ self.override_help(help)
+ }
+
+ /// Deprecated, replaced with [`Command::mut_arg`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn help_short(self, c: char) -> Self {
+ self.mut_arg("help", |a| a.short(c))
+ }
+
+ /// Deprecated, replaced with [`Command::mut_arg`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn version_short(self, c: char) -> Self {
+ self.mut_arg("version", |a| a.short(c))
+ }
+
+ /// Deprecated, replaced with [`Command::mut_arg`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn help_message(self, s: impl Into<&'help str>) -> Self {
+ self.mut_arg("help", |a| a.help(s.into()))
+ }
+
+ /// Deprecated, replaced with [`Command::mut_arg`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn version_message(self, s: impl Into<&'help str>) -> Self {
+ self.mut_arg("version", |a| a.help(s.into()))
+ }
+
+ /// Deprecated, replaced with [`Command::help_template`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::help_template`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn template<S: Into<&'help str>>(self, s: S) -> Self {
+ self.help_template(s)
+ }
+
+ /// Deprecated, replaced with [`Command::setting(a| b)`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::setting(a | b)`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn settings(mut self, settings: &[AppSettings]) -> Self {
+ for s in settings {
+ self.settings.insert((*s).into());
+ }
+ self
+ }
+
+ /// Deprecated, replaced with [`Command::unset_setting(a| b)`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::unset_setting(a | b)`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn unset_settings(mut self, settings: &[AppSettings]) -> Self {
+ for s in settings {
+ self.settings.remove((*s).into());
+ }
+ self
+ }
+
+ /// Deprecated, replaced with [`Command::global_setting(a| b)`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::global_setting(a | b)`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn global_settings(mut self, settings: &[AppSettings]) -> Self {
+ for s in settings {
+ self.settings.insert((*s).into());
+ self.g_settings.insert((*s).into());
+ }
+ self
+ }
+
+ /// Deprecated, replaced with [`Command::term_width`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::term_width`")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn set_term_width(self, width: usize) -> Self {
+ self.term_width(width)
+ }
+
+ /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!].
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn arg_from_usage(self, usage: &'help str) -> Self {
+ #![allow(deprecated)]
+ self.arg(Arg::from_usage(usage))
+ }
+
+ /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!].
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!")
+ )]
+ #[doc(hidden)]
+ #[must_use]
+ pub fn args_from_usage(mut self, usage: &'help str) -> Self {
+ #![allow(deprecated)]
+ for line in usage.lines() {
+ let l = line.trim();
+ if l.is_empty() {
+ continue;
+ }
+ self = self.arg(Arg::from_usage(l));
+ }
+ self
+ }
+
+ /// Deprecated, replaced with [`Command::render_version`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::render_version`")
+ )]
+ #[doc(hidden)]
+ pub fn write_version<W: io::Write>(&self, w: &mut W) -> ClapResult<()> {
+ write!(w, "{}", self.render_version()).map_err(From::from)
+ }
+
+ /// Deprecated, replaced with [`Command::render_long_version`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::render_long_version`")
+ )]
+ #[doc(hidden)]
+ pub fn write_long_version<W: io::Write>(&self, w: &mut W) -> ClapResult<()> {
+ write!(w, "{}", self.render_long_version()).map_err(From::from)
+ }
+
+ /// Deprecated, replaced with [`Command::try_get_matches`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::try_get_matches`")
+ )]
+ #[doc(hidden)]
+ pub fn get_matches_safe(self) -> ClapResult<ArgMatches> {
+ self.try_get_matches()
+ }
+
+ /// Deprecated, replaced with [`Command::try_get_matches_from`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.0.0", note = "Replaced with `App::try_get_matches_from`")
+ )]
+ #[doc(hidden)]
+ pub fn get_matches_from_safe<I, T>(self, itr: I) -> ClapResult<ArgMatches>
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ self.try_get_matches_from(itr)
+ }
+
+ /// Deprecated, replaced with [`Command::try_get_matches_from_mut`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "Replaced with `App::try_get_matches_from_mut`"
+ )
+ )]
+ #[doc(hidden)]
+ pub fn get_matches_from_safe_borrow<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches>
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ self.try_get_matches_from_mut(itr)
+ }
+}
+
+// Internally used only
+impl<'help> App<'help> {
+ pub(crate) fn get_id(&self) -> Id {
+ self.id.clone()
+ }
+
+ pub(crate) fn get_override_usage(&self) -> Option<&str> {
+ self.usage_str
+ }
+
+ pub(crate) fn get_override_help(&self) -> Option<&str> {
+ self.help_str
+ }
+
+ pub(crate) fn get_help_template(&self) -> Option<&str> {
+ self.template
+ }
+
+ pub(crate) fn get_term_width(&self) -> Option<usize> {
+ self.term_w
+ }
+
+ pub(crate) fn get_max_term_width(&self) -> Option<usize> {
+ self.max_w
+ }
+
+ pub(crate) fn get_replacement(&self, key: &str) -> Option<&[&str]> {
+ self.replacers.get(key).copied()
+ }
+
+ pub(crate) fn get_keymap(&self) -> &MKeyMap<'help> {
+ &self.args
+ }
+
+ fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) {
+ global_arg_vec.extend(
+ self.args
+ .args()
+ .filter(|a| a.is_global_set())
+ .map(|ga| ga.id.clone()),
+ );
+ if let Some((id, matches)) = matches.subcommand() {
+ if let Some(used_sub) = self.find_subcommand(id) {
+ used_sub.get_used_global_args(matches, global_arg_vec);
+ }
+ }
+ }
+
+ fn _do_parse(
+ &mut self,
+ raw_args: &mut clap_lex::RawArgs,
+ args_cursor: clap_lex::ArgCursor,
+ ) -> ClapResult<ArgMatches> {
+ debug!("Command::_do_parse");
+
+ // If there are global arguments, or settings we need to propagate them down to subcommands
+ // before parsing in case we run into a subcommand
+ self._build_self();
+
+ let mut matcher = ArgMatcher::new(self);
+
+ // do the real parsing
+ let mut parser = Parser::new(self);
+ if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) {
+ if self.is_set(AppSettings::IgnoreErrors) {
+ debug!("Command::_do_parse: ignoring error: {}", error);
+ } else {
+ return Err(error);
+ }
+ }
+
+ let mut global_arg_vec = Default::default();
+ self.get_used_global_args(&matcher, &mut global_arg_vec);
+
+ matcher.propagate_globals(&global_arg_vec);
+
+ Ok(matcher.into_inner())
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.1.10", note = "Replaced with `Command::build`")
+ )]
+ pub fn _build_all(&mut self) {
+ self.build();
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.1.10", note = "Replaced with `Command::build`")
+ )]
+ pub fn _build(&mut self) {
+ self._build_self()
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.1.13", note = "Replaced with `Command::build`")
+ )]
+ pub fn _build_bin_names(&mut self) {
+ self._build_bin_names_internal();
+ }
+
+ /// Prepare for introspecting on all included [`Command`]s
+ ///
+ /// Call this on the top-level [`Command`] when done building and before reading state for
+ /// cases like completions, custom help output, etc.
+ pub fn build(&mut self) {
+ self._build_recursive();
+ self._build_bin_names_internal();
+ }
+
+ pub(crate) fn _build_recursive(&mut self) {
+ self._build_self();
+ for subcmd in self.get_subcommands_mut() {
+ subcmd._build_recursive();
+ }
+ }
+
+ pub(crate) fn _build_self(&mut self) {
+ debug!("Command::_build: name={:?}", self.get_name());
+ if !self.settings.is_set(AppSettings::Built) {
+ // Make sure all the globally set flags apply to us as well
+ self.settings = self.settings | self.g_settings;
+
+ if self.is_multicall_set() {
+ self.settings.insert(AppSettings::SubcommandRequired.into());
+ self.settings.insert(AppSettings::DisableHelpFlag.into());
+ self.settings.insert(AppSettings::DisableVersionFlag.into());
+ }
+
+ self._propagate();
+ self._check_help_and_version();
+ self._propagate_global_args();
+ self._derive_display_order();
+
+ let mut pos_counter = 1;
+ let self_override = self.is_set(AppSettings::AllArgsOverrideSelf);
+ let hide_pv = self.is_set(AppSettings::HidePossibleValues);
+ let auto_help =
+ !self.is_set(AppSettings::NoAutoHelp) && !self.is_disable_help_flag_set();
+ let auto_version =
+ !self.is_set(AppSettings::NoAutoVersion) && !self.is_disable_version_flag_set();
+ for a in self.args.args_mut() {
+ // Fill in the groups
+ for g in &a.groups {
+ if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) {
+ ag.args.push(a.id.clone());
+ } else {
+ let mut ag = ArgGroup::with_id(g.clone());
+ ag.args.push(a.id.clone());
+ self.groups.push(ag);
+ }
+ }
+
+ // Figure out implied settings
+ if a.is_last_set() {
+ // if an arg has `Last` set, we need to imply DontCollapseArgsInUsage so that args
+ // in the usage string don't get confused or left out.
+ self.settings.set(AppSettings::DontCollapseArgsInUsage);
+ }
+ if hide_pv && a.is_takes_value_set() {
+ a.settings.set(ArgSettings::HidePossibleValues);
+ }
+ if self_override {
+ let self_id = a.id.clone();
+ a.overrides.push(self_id);
+ }
+ a._build();
+ // HACK: Setting up action at this level while auto-help / disable help flag is
+ // required. Otherwise, most of this won't be needed because when we can break
+ // compat, actions will reign supreme (default to `Store`)
+ if a.action.is_none() {
+ if a.get_id() == "help" && auto_help && !a.is_takes_value_set() {
+ let action = super::ArgAction::Help;
+ a.action = Some(action);
+ } else if a.get_id() == "version" && auto_version && !a.is_takes_value_set() {
+ let action = super::ArgAction::Version;
+ a.action = Some(action);
+ } else if a.is_takes_value_set() {
+ let action = super::ArgAction::StoreValue;
+ a.action = Some(action);
+ } else {
+ let action = super::ArgAction::IncOccurrence;
+ a.action = Some(action);
+ }
+ }
+ if a.is_positional() && a.index.is_none() {
+ a.index = Some(pos_counter);
+ pos_counter += 1;
+ }
+ }
+
+ self.args._build();
+
+ #[cfg(debug_assertions)]
+ assert_app(self);
+ self.settings.set(AppSettings::Built);
+ } else {
+ debug!("Command::_build: already built");
+ }
+ }
+
+ pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> {
+ use std::fmt::Write;
+
+ let mut mid_string = String::from(" ");
+ 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 {
+ mid_string.push_str(s);
+ mid_string.push(' ');
+ }
+ }
+ let is_multicall_set = self.is_multicall_set();
+
+ let sc = self.subcommands.iter_mut().find(|s| s.name == name)?;
+
+ // Display subcommand name, short and long in usage
+ let mut sc_names = sc.name.clone();
+ let mut flag_subcmd = false;
+ if let Some(l) = sc.long_flag {
+ write!(sc_names, "|--{}", l).unwrap();
+ flag_subcmd = true;
+ }
+ if let Some(s) = sc.short_flag {
+ write!(sc_names, "|-{}", s).unwrap();
+ flag_subcmd = true;
+ }
+
+ if flag_subcmd {
+ sc_names = format!("{{{}}}", sc_names);
+ }
+
+ let usage_name = self
+ .bin_name
+ .as_ref()
+ .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names))
+ .unwrap_or(sc_names);
+ sc.usage_name = Some(usage_name);
+
+ // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
+ // a space
+ let bin_name = format!(
+ "{}{}{}",
+ self.bin_name.as_ref().unwrap_or(&String::new()),
+ if self.bin_name.is_some() { " " } else { "" },
+ &*sc.name
+ );
+ debug!(
+ "Command::_build_subcommand Setting bin_name of {} to {:?}",
+ sc.name, bin_name
+ );
+ sc.bin_name = Some(bin_name);
+
+ if sc.display_name.is_none() {
+ let self_display_name = if is_multicall_set {
+ self.display_name.as_deref().unwrap_or("")
+ } else {
+ self.display_name.as_deref().unwrap_or(&self.name)
+ };
+ let display_name = format!(
+ "{}{}{}",
+ self_display_name,
+ if !self_display_name.is_empty() {
+ "-"
+ } else {
+ ""
+ },
+ &*sc.name
+ );
+ debug!(
+ "Command::_build_subcommand Setting display_name of {} to {:?}",
+ sc.name, display_name
+ );
+ sc.display_name = Some(display_name);
+ }
+
+ // Ensure all args are built and ready to parse
+ sc._build_self();
+
+ Some(sc)
+ }
+
+ fn _build_bin_names_internal(&mut self) {
+ debug!("Command::_build_bin_names");
+
+ if !self.is_set(AppSettings::BinNameBuilt) {
+ let mut mid_string = String::from(" ");
+ 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 {
+ mid_string.push_str(s);
+ mid_string.push(' ');
+ }
+ }
+ let is_multicall_set = self.is_multicall_set();
+
+ let self_bin_name = if is_multicall_set {
+ self.bin_name.as_deref().unwrap_or("")
+ } else {
+ self.bin_name.as_deref().unwrap_or(&self.name)
+ }
+ .to_owned();
+
+ for mut sc in &mut self.subcommands {
+ debug!("Command::_build_bin_names:iter: bin_name set...");
+
+ if sc.usage_name.is_none() {
+ use std::fmt::Write;
+ // Display subcommand name, short and long in usage
+ let mut sc_names = sc.name.clone();
+ let mut flag_subcmd = false;
+ if let Some(l) = sc.long_flag {
+ write!(sc_names, "|--{}", l).unwrap();
+ flag_subcmd = true;
+ }
+ if let Some(s) = sc.short_flag {
+ write!(sc_names, "|-{}", s).unwrap();
+ flag_subcmd = true;
+ }
+
+ if flag_subcmd {
+ sc_names = format!("{{{}}}", sc_names);
+ }
+
+ let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names);
+ debug!(
+ "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
+ sc.name, usage_name
+ );
+ sc.usage_name = Some(usage_name);
+ } else {
+ debug!(
+ "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
+ sc.name, sc.usage_name
+ );
+ }
+
+ if sc.bin_name.is_none() {
+ let bin_name = format!(
+ "{}{}{}",
+ self_bin_name,
+ if !self_bin_name.is_empty() { " " } else { "" },
+ &*sc.name
+ );
+ debug!(
+ "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
+ sc.name, bin_name
+ );
+ sc.bin_name = Some(bin_name);
+ } else {
+ debug!(
+ "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
+ sc.name, sc.bin_name
+ );
+ }
+
+ if sc.display_name.is_none() {
+ let self_display_name = if is_multicall_set {
+ self.display_name.as_deref().unwrap_or("")
+ } else {
+ self.display_name.as_deref().unwrap_or(&self.name)
+ };
+ let display_name = format!(
+ "{}{}{}",
+ self_display_name,
+ if !self_display_name.is_empty() {
+ "-"
+ } else {
+ ""
+ },
+ &*sc.name
+ );
+ debug!(
+ "Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
+ sc.name, display_name
+ );
+ sc.display_name = Some(display_name);
+ } else {
+ debug!(
+ "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
+ sc.name, sc.display_name
+ );
+ }
+
+ sc._build_bin_names_internal();
+ }
+ self.set(AppSettings::BinNameBuilt);
+ } else {
+ debug!("Command::_build_bin_names: already built");
+ }
+ }
+
+ pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) {
+ if self.is_set(AppSettings::HelpExpected) || help_required_globally {
+ let args_missing_help: Vec<String> = self
+ .args
+ .args()
+ .filter(|arg| arg.help.is_none() && arg.long_help.is_none())
+ .map(|arg| String::from(arg.name))
+ .collect();
+
+ assert!(args_missing_help.is_empty(),
+ "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}",
+ self.name,
+ args_missing_help.join(", ")
+ );
+ }
+
+ for sub_app in &self.subcommands {
+ sub_app._panic_on_missing_help(help_required_globally);
+ }
+ }
+
+ #[cfg(debug_assertions)]
+ pub(crate) fn two_args_of<F>(&self, condition: F) -> Option<(&Arg<'help>, &Arg<'help>)>
+ where
+ F: Fn(&Arg) -> bool,
+ {
+ two_elements_of(self.args.args().filter(|a: &&Arg| condition(a)))
+ }
+
+ // just in case
+ #[allow(unused)]
+ fn two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)>
+ where
+ F: Fn(&ArgGroup) -> bool,
+ {
+ two_elements_of(self.groups.iter().filter(|a| condition(a)))
+ }
+
+ /// Propagate global args
+ pub(crate) fn _propagate_global_args(&mut self) {
+ debug!("Command::_propagate_global_args:{}", self.name);
+
+ for sc in &mut self.subcommands {
+ for a in self.args.args().filter(|a| a.is_global_set()) {
+ let mut propagate = false;
+ let is_generated = matches!(
+ a.provider,
+ ArgProvider::Generated | ArgProvider::GeneratedMutated
+ );
+
+ // Remove generated help and version args in the subcommand
+ //
+ // Don't remove if those args are further mutated
+ if is_generated {
+ let generated_pos = sc
+ .args
+ .args()
+ .position(|x| x.id == a.id && x.provider == ArgProvider::Generated);
+
+ if let Some(index) = generated_pos {
+ debug!(
+ "Command::_propagate removing {}'s {:?}",
+ sc.get_name(),
+ a.id
+ );
+ sc.args.remove(index);
+ propagate = true;
+ }
+ }
+
+ if propagate || sc.find(&a.id).is_none() {
+ debug!(
+ "Command::_propagate pushing {:?} to {}",
+ a.id,
+ sc.get_name(),
+ );
+ sc.args.push(a.clone());
+ }
+ }
+ }
+ }
+
+ /// Propagate settings
+ pub(crate) fn _propagate(&mut self) {
+ debug!("Command::_propagate:{}", self.name);
+ let mut subcommands = std::mem::take(&mut self.subcommands);
+ for sc in &mut subcommands {
+ self._propagate_subcommand(sc);
+ }
+ self.subcommands = subcommands;
+ }
+
+ fn _propagate_subcommand(&self, sc: &mut Self) {
+ // We have to create a new scope in order to tell rustc the borrow of `sc` is
+ // done and to recursively call this method
+ {
+ if self.settings.is_set(AppSettings::PropagateVersion) {
+ if sc.version.is_none() && self.version.is_some() {
+ sc.version = Some(self.version.unwrap());
+ }
+ if sc.long_version.is_none() && self.long_version.is_some() {
+ sc.long_version = Some(self.long_version.unwrap());
+ }
+ }
+
+ sc.settings = sc.settings | self.g_settings;
+ sc.g_settings = sc.g_settings | self.g_settings;
+ sc.term_w = self.term_w;
+ sc.max_w = self.max_w;
+ }
+ }
+
+ #[allow(clippy::blocks_in_if_conditions)]
+ pub(crate) fn _check_help_and_version(&mut self) {
+ debug!("Command::_check_help_and_version: {}", self.name);
+
+ if self.is_set(AppSettings::DisableHelpFlag)
+ || self.args.args().any(|x| {
+ x.provider == ArgProvider::User
+ && (x.long == Some("help") || x.id == Id::help_hash())
+ })
+ || self
+ .subcommands
+ .iter()
+ .any(|sc| sc.long_flag == Some("help"))
+ {
+ debug!("Command::_check_help_and_version: Removing generated help");
+
+ let generated_help_pos = self
+ .args
+ .args()
+ .position(|x| x.id == Id::help_hash() && x.provider == ArgProvider::Generated);
+
+ if let Some(index) = generated_help_pos {
+ self.args.remove(index);
+ }
+ } else {
+ let help = self
+ .args
+ .args()
+ .find(|x| x.id == Id::help_hash())
+ .expect(INTERNAL_ERROR_MSG);
+ assert_ne!(help.provider, ArgProvider::User);
+
+ if help.short.is_some() {
+ if help.short == Some('h') {
+ if let Some(other_arg) = self
+ .args
+ .args()
+ .find(|x| x.id != Id::help_hash() && x.short == Some('h'))
+ {
+ panic!(
+ "`help`s `-h` conflicts with `{}`.
+
+To change `help`s short, call `cmd.arg(Arg::new(\"help\")...)`.",
+ other_arg.name
+ );
+ }
+ }
+ } else if !(self.args.args().any(|x| x.short == Some('h'))
+ || self.subcommands.iter().any(|sc| sc.short_flag == Some('h')))
+ {
+ let help = self
+ .args
+ .args_mut()
+ .find(|x| x.id == Id::help_hash())
+ .expect(INTERNAL_ERROR_MSG);
+ help.short = Some('h');
+ } else {
+ debug!("Command::_check_help_and_version: Removing `-h` from help");
+ }
+ }
+
+ // Determine if we should remove the generated --version flag
+ //
+ // Note that if only mut_arg() was used, the first expression will evaluate to `true`
+ // however inside the condition block, we only check for Generated args, not
+ // GeneratedMutated args, so the `mut_arg("version", ..) will be skipped and fall through
+ // to the following condition below (Adding the short `-V`)
+ if self.settings.is_set(AppSettings::DisableVersionFlag)
+ || (self.version.is_none() && self.long_version.is_none())
+ || self.args.args().any(|x| {
+ x.provider == ArgProvider::User
+ && (x.long == Some("version") || x.id == Id::version_hash())
+ })
+ || self
+ .subcommands
+ .iter()
+ .any(|sc| sc.long_flag == Some("version"))
+ {
+ debug!("Command::_check_help_and_version: Removing generated version");
+
+ // This is the check mentioned above that only checks for Generated, not
+ // GeneratedMutated args by design.
+ let generated_version_pos = self
+ .args
+ .args()
+ .position(|x| x.id == Id::version_hash() && x.provider == ArgProvider::Generated);
+
+ if let Some(index) = generated_version_pos {
+ self.args.remove(index);
+ }
+ }
+
+ // If we still have a generated --version flag, determine if we can apply the short `-V`
+ if self.args.args().any(|x| {
+ x.id == Id::version_hash()
+ && matches!(
+ x.provider,
+ ArgProvider::Generated | ArgProvider::GeneratedMutated
+ )
+ }) {
+ let other_arg_has_short = self.args.args().any(|x| x.short == Some('V'));
+ let version = self
+ .args
+ .args_mut()
+ .find(|x| x.id == Id::version_hash())
+ .expect(INTERNAL_ERROR_MSG);
+
+ if !(version.short.is_some()
+ || other_arg_has_short
+ || self.subcommands.iter().any(|sc| sc.short_flag == Some('V')))
+ {
+ version.short = Some('V');
+ }
+ }
+
+ if !self.is_set(AppSettings::DisableHelpSubcommand)
+ && self.has_subcommands()
+ && !self.subcommands.iter().any(|s| s.id == Id::help_hash())
+ {
+ debug!("Command::_check_help_and_version: Building help subcommand");
+ let mut help_subcmd = App::new("help")
+ .about("Print this message or the help of the given subcommand(s)")
+ .arg(
+ Arg::new("subcommand")
+ .index(1)
+ .takes_value(true)
+ .multiple_occurrences(true)
+ .value_name("SUBCOMMAND")
+ .help("The subcommand whose help message to display"),
+ );
+ self._propagate_subcommand(&mut help_subcmd);
+
+ // The parser acts like this is set, so let's set it so we don't falsely
+ // advertise it to the user
+ help_subcmd.version = None;
+ help_subcmd.long_version = None;
+ help_subcmd = help_subcmd
+ .setting(AppSettings::DisableHelpFlag)
+ .unset_global_setting(AppSettings::PropagateVersion);
+
+ self.subcommands.push(help_subcmd);
+ }
+ }
+
+ pub(crate) fn _derive_display_order(&mut self) {
+ debug!("Command::_derive_display_order:{}", self.name);
+
+ if self.settings.is_set(AppSettings::DeriveDisplayOrder) {
+ for a in self
+ .args
+ .args_mut()
+ .filter(|a| !a.is_positional())
+ .filter(|a| a.provider != ArgProvider::Generated)
+ {
+ a.disp_ord.make_explicit();
+ }
+ for (i, sc) in &mut self.subcommands.iter_mut().enumerate() {
+ sc.disp_ord.get_or_insert(i);
+ }
+ }
+ for sc in &mut self.subcommands {
+ sc._derive_display_order();
+ }
+ }
+
+ pub(crate) fn _render_version(&self, use_long: bool) -> String {
+ debug!("Command::_render_version");
+
+ let ver = if use_long {
+ self.long_version.or(self.version).unwrap_or("")
+ } else {
+ self.version.or(self.long_version).unwrap_or("")
+ };
+ if let Some(bn) = self.bin_name.as_ref() {
+ if bn.contains(' ') {
+ // In case we're dealing with subcommands i.e. git mv is translated to git-mv
+ format!("{} {}\n", bn.replace(' ', "-"), ver)
+ } else {
+ format!("{} {}\n", &self.name[..], ver)
+ }
+ } else {
+ format!("{} {}\n", &self.name[..], ver)
+ }
+ }
+
+ pub(crate) fn format_group(&self, g: &Id) -> String {
+ let g_string = self
+ .unroll_args_in_group(g)
+ .iter()
+ .filter_map(|x| self.find(x))
+ .map(|x| {
+ if x.is_positional() {
+ // Print val_name for positional arguments. e.g. <file_name>
+ x.name_no_brackets().to_string()
+ } else {
+ // Print usage string for flags arguments, e.g. <--help>
+ x.to_string()
+ }
+ })
+ .collect::<Vec<_>>()
+ .join("|");
+ format!("<{}>", &*g_string)
+ }
+}
+
+/// A workaround:
+/// <https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999>
+pub(crate) trait Captures<'a> {}
+impl<'a, T> Captures<'a> for T {}
+
+// Internal Query Methods
+impl<'help> App<'help> {
+ /// Iterate through the *flags* & *options* arguments.
+ pub(crate) fn get_non_positionals(&self) -> impl Iterator<Item = &Arg<'help>> {
+ self.get_arguments().filter(|a| !a.is_positional())
+ }
+
+ /// Iterate through the *positionals* that don't have custom heading.
+ pub(crate) fn get_positionals_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>> {
+ self.get_positionals()
+ .filter(|a| a.get_help_heading().is_none())
+ }
+
+ /// Iterate through the *flags* & *options* that don't have custom heading.
+ pub(crate) fn get_non_positionals_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>> {
+ self.get_non_positionals()
+ .filter(|a| a.get_help_heading().is_none())
+ }
+
+ pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg<'help>> {
+ self.args.args().find(|a| a.id == *arg_id)
+ }
+
+ #[inline]
+ pub(crate) fn contains_short(&self, s: char) -> bool {
+ assert!(
+ self.is_set(AppSettings::Built),
+ "If App::_build hasn't been called, manually search through Arg shorts"
+ );
+
+ self.args.contains(s)
+ }
+
+ #[inline]
+ pub(crate) fn set(&mut self, s: AppSettings) {
+ self.settings.set(s)
+ }
+
+ #[inline]
+ pub(crate) fn has_args(&self) -> bool {
+ !self.args.is_empty()
+ }
+
+ pub(crate) fn has_positionals(&self) -> bool {
+ self.args.keys().any(|x| x.is_position())
+ }
+
+ pub(crate) fn has_visible_subcommands(&self) -> bool {
+ self.subcommands
+ .iter()
+ .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden))
+ }
+
+ /// Check if this subcommand can be referred to as `name`. In other words,
+ /// check if `name` is the name of this subcommand or is one of its aliases.
+ #[inline]
+ pub(crate) fn aliases_to<T>(&self, name: &T) -> bool
+ where
+ T: PartialEq<str> + ?Sized,
+ {
+ *name == *self.get_name() || self.get_all_aliases().any(|alias| *name == *alias)
+ }
+
+ /// Check if this subcommand can be referred to as `name`. In other words,
+ /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases.
+ #[inline]
+ pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool {
+ Some(flag) == self.short_flag
+ || self.get_all_short_flag_aliases().any(|alias| flag == alias)
+ }
+
+ /// Check if this subcommand can be referred to as `name`. In other words,
+ /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases.
+ #[inline]
+ pub(crate) fn long_flag_aliases_to<T>(&self, flag: &T) -> bool
+ where
+ T: PartialEq<str> + ?Sized,
+ {
+ match self.long_flag {
+ Some(long_flag) => {
+ flag == long_flag || self.get_all_long_flag_aliases().any(|alias| flag == alias)
+ }
+ None => self.get_all_long_flag_aliases().any(|alias| flag == alias),
+ }
+ }
+
+ #[cfg(debug_assertions)]
+ pub(crate) fn id_exists(&self, id: &Id) -> bool {
+ self.args.args().any(|x| x.id == *id) || self.groups.iter().any(|x| x.id == *id)
+ }
+
+ /// Iterate through the groups this arg is member of.
+ pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a {
+ debug!("Command::groups_for_arg: id={:?}", arg);
+ let arg = arg.clone();
+ self.groups
+ .iter()
+ .filter(move |grp| grp.args.iter().any(|a| a == &arg))
+ .map(|grp| grp.id.clone())
+ }
+
+ pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup<'help>> {
+ self.groups.iter().find(|g| g.id == *group_id)
+ }
+
+ /// Iterate through all the names of all subcommands (not recursively), including aliases.
+ /// Used for suggestions.
+ pub(crate) fn all_subcommand_names(&self) -> impl Iterator<Item = &str> + Captures<'help> {
+ self.get_subcommands().flat_map(|sc| {
+ let name = sc.get_name();
+ let aliases = sc.get_all_aliases();
+ std::iter::once(name).chain(aliases)
+ })
+ }
+
+ pub(crate) fn required_graph(&self) -> ChildGraph<Id> {
+ let mut reqs = ChildGraph::with_capacity(5);
+ for a in self.args.args().filter(|a| a.is_required_set()) {
+ reqs.insert(a.id.clone());
+ }
+ for group in &self.groups {
+ if group.required {
+ let idx = reqs.insert(group.id.clone());
+ for a in &group.requires {
+ reqs.insert_child(idx, a.clone());
+ }
+ }
+ }
+
+ reqs
+ }
+
+ pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec<Id> {
+ debug!("Command::unroll_args_in_group: group={:?}", group);
+ let mut g_vec = vec![group];
+ let mut args = vec![];
+
+ while let Some(g) = g_vec.pop() {
+ for n in self
+ .groups
+ .iter()
+ .find(|grp| grp.id == *g)
+ .expect(INTERNAL_ERROR_MSG)
+ .args
+ .iter()
+ {
+ debug!("Command::unroll_args_in_group:iter: entity={:?}", n);
+ if !args.contains(n) {
+ if self.find(n).is_some() {
+ debug!("Command::unroll_args_in_group:iter: this is an arg");
+ args.push(n.clone())
+ } else {
+ debug!("Command::unroll_args_in_group:iter: this is a group");
+ g_vec.push(n);
+ }
+ }
+ }
+ }
+
+ args
+ }
+
+ pub(crate) fn unroll_arg_requires<F>(&self, func: F, arg: &Id) -> Vec<Id>
+ where
+ F: Fn(&(ArgPredicate<'_>, Id)) -> Option<Id>,
+ {
+ let mut processed = vec![];
+ let mut r_vec = vec![arg];
+ let mut args = vec![];
+
+ while let Some(a) = r_vec.pop() {
+ if processed.contains(&a) {
+ continue;
+ }
+
+ processed.push(a);
+
+ if let Some(arg) = self.find(a) {
+ for r in arg.requires.iter().filter_map(&func) {
+ if let Some(req) = self.find(&r) {
+ if !req.requires.is_empty() {
+ r_vec.push(&req.id)
+ }
+ }
+ args.push(r);
+ }
+ }
+ }
+
+ args
+ }
+
+ /// Find a flag subcommand name by short flag or an alias
+ pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> {
+ self.get_subcommands()
+ .find(|sc| sc.short_flag_aliases_to(c))
+ .map(|sc| sc.get_name())
+ }
+
+ /// Find a flag subcommand name by long flag or an alias
+ pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> {
+ self.get_subcommands()
+ .find(|sc| sc.long_flag_aliases_to(long))
+ .map(|sc| sc.get_name())
+ }
+
+ pub(crate) fn get_display_order(&self) -> usize {
+ self.disp_ord.unwrap_or(999)
+ }
+
+ pub(crate) fn write_help_err(
+ &self,
+ mut use_long: bool,
+ stream: Stream,
+ ) -> ClapResult<Colorizer> {
+ debug!(
+ "Parser::write_help_err: use_long={:?}, stream={:?}",
+ use_long && self.use_long_help(),
+ stream
+ );
+
+ use_long = use_long && self.use_long_help();
+ let usage = Usage::new(self);
+
+ let mut c = Colorizer::new(stream, self.color_help());
+ Help::new(HelpWriter::Buffer(&mut c), self, &usage, use_long).write_help()?;
+ Ok(c)
+ }
+
+ pub(crate) fn use_long_help(&self) -> bool {
+ debug!("Command::use_long_help");
+ // In this case, both must be checked. This allows the retention of
+ // original formatting, but also ensures that the actual -h or --help
+ // specified by the user is sent through. If hide_short_help is not included,
+ // then items specified with hidden_short_help will also be hidden.
+ let should_long = |v: &Arg| {
+ v.long_help.is_some()
+ || v.is_hide_long_help_set()
+ || v.is_hide_short_help_set()
+ || cfg!(feature = "unstable-v4")
+ && v.get_possible_values2()
+ .iter()
+ .any(PossibleValue::should_show_help)
+ };
+
+ // Subcommands aren't checked because we prefer short help for them, deferring to
+ // `cmd subcmd --help` for more.
+ self.get_long_about().is_some()
+ || self.get_before_long_help().is_some()
+ || self.get_after_long_help().is_some()
+ || self.get_arguments().any(should_long)
+ }
+
+ // Should we color the help?
+ pub(crate) fn color_help(&self) -> ColorChoice {
+ #[cfg(feature = "color")]
+ if self.is_disable_colored_help_set() {
+ return ColorChoice::Never;
+ }
+
+ self.get_color()
+ }
+}
+
+impl<'help> Default for App<'help> {
+ fn default() -> Self {
+ Self {
+ id: Default::default(),
+ name: Default::default(),
+ long_flag: Default::default(),
+ short_flag: Default::default(),
+ display_name: Default::default(),
+ bin_name: Default::default(),
+ author: Default::default(),
+ version: Default::default(),
+ long_version: Default::default(),
+ about: Default::default(),
+ long_about: Default::default(),
+ before_help: Default::default(),
+ before_long_help: Default::default(),
+ after_help: Default::default(),
+ after_long_help: Default::default(),
+ aliases: Default::default(),
+ short_flag_aliases: Default::default(),
+ long_flag_aliases: Default::default(),
+ usage_str: Default::default(),
+ usage_name: Default::default(),
+ help_str: Default::default(),
+ disp_ord: Default::default(),
+ term_w: Default::default(),
+ max_w: Default::default(),
+ template: Default::default(),
+ settings: Default::default(),
+ g_settings: Default::default(),
+ args: Default::default(),
+ subcommands: Default::default(),
+ replacers: Default::default(),
+ groups: Default::default(),
+ current_help_heading: Default::default(),
+ current_disp_ord: Some(0),
+ subcommand_value_name: Default::default(),
+ subcommand_heading: Default::default(),
+ }
+ }
+}
+
+impl<'help> Index<&'_ Id> for App<'help> {
+ type Output = Arg<'help>;
+
+ fn index(&self, key: &Id) -> &Self::Output {
+ self.find(key).expect(INTERNAL_ERROR_MSG)
+ }
+}
+
+impl fmt::Display for App<'_> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "{}", self.name)
+ }
+}
+
+fn two_elements_of<I, T>(mut iter: I) -> Option<(T, T)>
+where
+ I: Iterator<Item = T>,
+{
+ let first = iter.next();
+ let second = iter.next();
+
+ match (first, second) {
+ (Some(first), Some(second)) => Some((first, second)),
+ _ => None,
+ }
+}
+
+#[test]
+fn check_auto_traits() {
+ static_assertions::assert_impl_all!(Command: Send, Sync, Unpin);
+}
diff --git a/3.2.23/src/builder/debug_asserts.rs b/3.2.23/src/builder/debug_asserts.rs
new file mode 100644
index 0000000..864b8b4
--- /dev/null
+++ b/3.2.23/src/builder/debug_asserts.rs
@@ -0,0 +1,851 @@
+use std::cmp::Ordering;
+
+use clap_lex::RawOsStr;
+
+use crate::builder::arg::ArgProvider;
+use crate::mkeymap::KeyType;
+use crate::ArgAction;
+use crate::{Arg, Command, ValueHint};
+
+pub(crate) fn assert_app(cmd: &Command) {
+ debug!("Command::_debug_asserts");
+
+ let mut short_flags = vec![];
+ let mut long_flags = vec![];
+
+ // Invalid version flag settings
+ if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
+ // PropagateVersion is meaningless if there is no version
+ assert!(
+ !cmd.is_propagate_version_set(),
+ "Command {}: No version information via Command::version or Command::long_version to propagate",
+ cmd.get_name(),
+ );
+
+ // Used `Command::mut_arg("version", ..) but did not provide any version information to display
+ let version_needed = cmd
+ .get_arguments()
+ .filter(|x| {
+ let action_set = matches!(x.get_action(), ArgAction::Version);
+ #[cfg(not(feature = "unstable-v4"))]
+ let provider_set = matches!(x.provider, ArgProvider::GeneratedMutated);
+ #[cfg(feature = "unstable-v4")]
+ let provider_set = matches!(
+ x.provider,
+ ArgProvider::User | ArgProvider::GeneratedMutated
+ );
+ action_set && provider_set
+ })
+ .map(|x| x.get_id())
+ .collect::<Vec<_>>();
+
+ assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
+ ,cmd.get_name()
+ );
+ }
+
+ for sc in cmd.get_subcommands() {
+ if let Some(s) = sc.get_short_flag().as_ref() {
+ short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
+ }
+
+ for short_alias in sc.get_all_short_flag_aliases() {
+ short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
+ }
+
+ if let Some(l) = sc.get_long_flag().as_ref() {
+ #[cfg(feature = "unstable-v4")]
+ {
+ assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
+ }
+ long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
+ }
+
+ for long_alias in sc.get_all_long_flag_aliases() {
+ long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
+ }
+ }
+
+ for arg in cmd.get_arguments() {
+ assert_arg(arg);
+
+ assert!(
+ !cmd.is_multicall_set(),
+ "Command {}: Arguments like {} cannot be set on a multicall command",
+ cmd.get_name(),
+ arg.name
+ );
+
+ if let Some(s) = arg.short.as_ref() {
+ short_flags.push(Flag::Arg(format!("-{}", s), &*arg.name));
+ }
+
+ for (short_alias, _) in &arg.short_aliases {
+ short_flags.push(Flag::Arg(format!("-{}", short_alias), arg.name));
+ }
+
+ if let Some(l) = arg.long.as_ref() {
+ #[cfg(feature = "unstable-v4")]
+ {
+ assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.name, l);
+ }
+ long_flags.push(Flag::Arg(format!("--{}", l), &*arg.name));
+ }
+
+ for (long_alias, _) in &arg.aliases {
+ long_flags.push(Flag::Arg(format!("--{}", long_alias), arg.name));
+ }
+
+ // Name conflicts
+ assert!(
+ cmd.two_args_of(|x| x.id == arg.id).is_none(),
+ "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group",
+ cmd.get_name(),
+ arg.name,
+ );
+
+ // Long conflicts
+ if let Some(l) = arg.long {
+ if let Some((first, second)) = cmd.two_args_of(|x| x.long == Some(l)) {
+ panic!(
+ "Command {}: Long option names must be unique for each argument, \
+ but '--{}' is in use by both '{}' and '{}'",
+ cmd.get_name(),
+ l,
+ first.name,
+ second.name
+ )
+ }
+ }
+
+ // Short conflicts
+ if let Some(s) = arg.short {
+ if let Some((first, second)) = cmd.two_args_of(|x| x.short == Some(s)) {
+ panic!(
+ "Command {}: Short option names must be unique for each argument, \
+ but '-{}' is in use by both '{}' and '{}'",
+ cmd.get_name(),
+ s,
+ first.name,
+ second.name
+ )
+ }
+ }
+
+ // Index conflicts
+ if let Some(idx) = arg.index {
+ if let Some((first, second)) =
+ cmd.two_args_of(|x| x.is_positional() && x.index == Some(idx))
+ {
+ panic!(
+ "Command {}: Argument '{}' has the same index as '{}' \
+ and they are both positional arguments\n\n\t \
+ Use Arg::multiple_values(true) to allow one \
+ positional argument to take multiple values",
+ cmd.get_name(),
+ first.name,
+ second.name
+ )
+ }
+ }
+
+ // requires, r_if, r_unless
+ for req in &arg.requires {
+ assert!(
+ cmd.id_exists(&req.1),
+ "Command {}: Argument or group '{:?}' specified in 'requires*' for '{}' does not exist",
+ cmd.get_name(),
+ req.1,
+ arg.name,
+ );
+ }
+
+ for req in &arg.r_ifs {
+ #[cfg(feature = "unstable-v4")]
+ {
+ assert!(
+ !arg.is_required_set(),
+ "Argument {}: `required` conflicts with `required_if_eq*`",
+ arg.name
+ );
+ }
+ assert!(
+ cmd.id_exists(&req.0),
+ "Command {}: Argument or group '{:?}' specified in 'required_if_eq*' for '{}' does not exist",
+ cmd.get_name(),
+ req.0,
+ arg.name
+ );
+ }
+
+ for req in &arg.r_ifs_all {
+ #[cfg(feature = "unstable-v4")]
+ {
+ assert!(
+ !arg.is_required_set(),
+ "Argument {}: `required` conflicts with `required_if_eq_all`",
+ arg.name
+ );
+ }
+ assert!(
+ cmd.id_exists(&req.0),
+ "Command {}: Argument or group '{:?}' specified in 'required_if_eq_all' for '{}' does not exist",
+ cmd.get_name(),
+ req.0,
+ arg.name
+ );
+ }
+
+ for req in &arg.r_unless {
+ #[cfg(feature = "unstable-v4")]
+ {
+ assert!(
+ !arg.is_required_set(),
+ "Argument {}: `required` conflicts with `required_unless*`",
+ arg.name
+ );
+ }
+ assert!(
+ cmd.id_exists(req),
+ "Command {}: Argument or group '{:?}' specified in 'required_unless*' for '{}' does not exist",
+ cmd.get_name(),
+ req,
+ arg.name,
+ );
+ }
+
+ for req in &arg.r_unless_all {
+ #[cfg(feature = "unstable-v4")]
+ {
+ assert!(
+ !arg.is_required_set(),
+ "Argument {}: `required` conflicts with `required_unless*`",
+ arg.name
+ );
+ }
+ assert!(
+ cmd.id_exists(req),
+ "Command {}: Argument or group '{:?}' specified in 'required_unless*' for '{}' does not exist",
+ cmd.get_name(),
+ req,
+ arg.name,
+ );
+ }
+
+ // blacklist
+ for req in &arg.blacklist {
+ assert!(
+ cmd.id_exists(req),
+ "Command {}: Argument or group '{:?}' specified in 'conflicts_with*' for '{}' does not exist",
+ cmd.get_name(),
+ req,
+ arg.name,
+ );
+ }
+
+ if arg.is_last_set() {
+ assert!(
+ arg.long.is_none(),
+ "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
+ cmd.get_name(),
+ arg.name
+ );
+ assert!(
+ arg.short.is_none(),
+ "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
+ cmd.get_name(),
+ arg.name
+ );
+ }
+
+ assert!(
+ !(arg.is_required_set() && arg.is_global_set()),
+ "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
+ cmd.get_name(),
+ arg.name
+ );
+
+ // validators
+ assert!(
+ arg.validator.is_none() || arg.validator_os.is_none(),
+ "Command {}: Argument '{}' has both `validator` and `validator_os` set which is not allowed",
+ cmd.get_name(),
+ arg.name
+ );
+
+ if arg.get_value_hint() == ValueHint::CommandWithArguments {
+ assert!(
+ arg.is_positional(),
+ "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
+ cmd.get_name(),
+ arg.name
+ );
+
+ assert!(
+ cmd.is_trailing_var_arg_set(),
+ "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have TrailingVarArg set.",
+ cmd.get_name(),
+ arg.name
+ );
+ }
+ }
+
+ for group in cmd.get_groups() {
+ // Name conflicts
+ assert!(
+ cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
+ "Command {}: Argument group name must be unique\n\n\t'{}' is already in use",
+ cmd.get_name(),
+ group.name,
+ );
+
+ // Groups should not have naming conflicts with Args
+ assert!(
+ !cmd.get_arguments().any(|x| x.id == group.id),
+ "Command {}: Argument group name '{}' must not conflict with argument name",
+ cmd.get_name(),
+ group.name,
+ );
+
+ for arg in &group.args {
+ // Args listed inside groups should exist
+ assert!(
+ cmd.get_arguments().any(|x| x.id == *arg),
+ "Command {}: Argument group '{}' contains non-existent argument '{:?}'",
+ cmd.get_name(),
+ group.name,
+ arg
+ );
+ }
+ }
+
+ // Conflicts between flags and subcommands
+
+ long_flags.sort_unstable();
+ short_flags.sort_unstable();
+
+ detect_duplicate_flags(&long_flags, "long");
+ detect_duplicate_flags(&short_flags, "short");
+
+ _verify_positionals(cmd);
+
+ if let Some(help_template) = cmd.get_help_template() {
+ assert!(
+ !help_template.contains("{flags}"),
+ "Command {}: {}",
+ cmd.get_name(),
+ "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
+ );
+ assert!(
+ !help_template.contains("{unified}"),
+ "Command {}: {}",
+ cmd.get_name(),
+ "`{unified}` template variable was removed in clap3, use `{options}` instead"
+ );
+ }
+
+ cmd._panic_on_missing_help(cmd.is_help_expected_set());
+ assert_app_flags(cmd);
+}
+
+#[derive(Eq)]
+enum Flag<'a> {
+ Command(String, &'a str),
+ Arg(String, &'a str),
+}
+
+impl PartialEq for Flag<'_> {
+ fn eq(&self, other: &Flag) -> bool {
+ self.cmp(other) == Ordering::Equal
+ }
+}
+
+impl PartialOrd for Flag<'_> {
+ fn partial_cmp(&self, other: &Flag) -> Option<Ordering> {
+ use Flag::*;
+
+ match (self, other) {
+ (Command(s1, _), Command(s2, _))
+ | (Arg(s1, _), Arg(s2, _))
+ | (Command(s1, _), Arg(s2, _))
+ | (Arg(s1, _), Command(s2, _)) => {
+ if s1 == s2 {
+ Some(Ordering::Equal)
+ } else {
+ s1.partial_cmp(s2)
+ }
+ }
+ }
+ }
+}
+
+impl Ord for Flag<'_> {
+ fn cmp(&self, other: &Self) -> Ordering {
+ self.partial_cmp(other).unwrap()
+ }
+}
+
+fn detect_duplicate_flags(flags: &[Flag], short_or_long: &str) {
+ use Flag::*;
+
+ for (one, two) in find_duplicates(flags) {
+ match (one, two) {
+ (Command(flag, one), Command(_, another)) if one != another => panic!(
+ "the '{}' {} flag is specified for both '{}' and '{}' subcommands",
+ flag, short_or_long, one, another
+ ),
+
+ (Arg(flag, one), Arg(_, another)) if one != another => panic!(
+ "{} option names must be unique, but '{}' is in use by both '{}' and '{}'",
+ short_or_long, flag, one, another
+ ),
+
+ (Arg(flag, arg), Command(_, sub)) | (Command(flag, sub), Arg(_, arg)) => panic!(
+ "the '{}' {} flag for the '{}' argument conflicts with the short flag \
+ for '{}' subcommand",
+ flag, short_or_long, arg, sub
+ ),
+
+ _ => {}
+ }
+ }
+}
+
+/// Find duplicates in a sorted array.
+///
+/// The algorithm is simple: the array is sorted, duplicates
+/// must be placed next to each other, we can check only adjacent elements.
+fn find_duplicates<T: PartialEq>(slice: &[T]) -> impl Iterator<Item = (&T, &T)> {
+ slice.windows(2).filter_map(|w| {
+ if w[0] == w[1] {
+ Some((&w[0], &w[1]))
+ } else {
+ None
+ }
+ })
+}
+
+fn assert_app_flags(cmd: &Command) {
+ macro_rules! checker {
+ ($a:ident requires $($b:ident)|+) => {
+ if cmd.$a() {
+ let mut s = String::new();
+
+ $(
+ if !cmd.$b() {
+ s.push_str(&format!(" AppSettings::{} is required when AppSettings::{} is set.\n", std::stringify!($b), std::stringify!($a)));
+ }
+ )+
+
+ if !s.is_empty() {
+ panic!("{}", s)
+ }
+ }
+ };
+ ($a:ident conflicts $($b:ident)|+) => {
+ if cmd.$a() {
+ let mut s = String::new();
+
+ $(
+ if cmd.$b() {
+ s.push_str(&format!(" AppSettings::{} conflicts with AppSettings::{}.\n", std::stringify!($b), std::stringify!($a)));
+ }
+ )+
+
+ if !s.is_empty() {
+ panic!("{}\n{}", cmd.get_name(), s)
+ }
+ }
+ };
+ }
+
+ checker!(is_allow_invalid_utf8_for_external_subcommands_set requires is_allow_external_subcommands_set);
+ checker!(is_multicall_set conflicts is_no_binary_name_set);
+}
+
+#[cfg(debug_assertions)]
+fn _verify_positionals(cmd: &Command) -> bool {
+ debug!("Command::_verify_positionals");
+ // Because you must wait until all arguments have been supplied, this is the first chance
+ // to make assertions on positional argument indexes
+ //
+ // First we verify that the index highest supplied index, is equal to the number of
+ // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3
+ // but no 2)
+
+ let highest_idx = cmd
+ .get_keymap()
+ .keys()
+ .filter_map(|x| {
+ if let KeyType::Position(n) = x {
+ Some(*n)
+ } else {
+ None
+ }
+ })
+ .max()
+ .unwrap_or(0);
+
+ let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count();
+
+ assert!(
+ highest_idx == num_p,
+ "Found positional argument whose index is {} but there \
+ are only {} positional arguments defined",
+ highest_idx,
+ num_p
+ );
+
+ // Next we verify that only the highest index has takes multiple arguments (if any)
+ let only_highest = |a: &Arg| a.is_multiple() && (a.index.unwrap_or(0) != highest_idx);
+ if cmd.get_positionals().any(only_highest) {
+ // First we make sure if there is a positional that allows multiple values
+ // the one before it (second to last) has one of these:
+ // * a value terminator
+ // * ArgSettings::Last
+ // * The last arg is Required
+
+ // We can't pass the closure (it.next()) to the macro directly because each call to
+ // find() (iterator, not macro) gets called repeatedly.
+ let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)];
+ let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)];
+
+ // Either the final positional is required
+ // Or the second to last has a terminator or .last(true) set
+ let ok = last.is_required_set()
+ || (second_to_last.terminator.is_some() || second_to_last.is_last_set())
+ || last.is_last_set();
+ assert!(
+ ok,
+ "When using a positional argument with .multiple_values(true) that is *not the \
+ last* positional argument, the last positional argument (i.e. the one \
+ with the highest index) *must* have .required(true) or .last(true) set."
+ );
+
+ // We make sure if the second to last is Multiple the last is ArgSettings::Last
+ let ok = second_to_last.is_multiple() || last.is_last_set();
+ assert!(
+ ok,
+ "Only the last positional argument, or second to last positional \
+ argument may be set to .multiple_values(true)"
+ );
+
+ // Next we check how many have both Multiple and not a specific number of values set
+ let count = cmd
+ .get_positionals()
+ .filter(|p| {
+ #[allow(deprecated)]
+ {
+ p.is_multiple_occurrences_set()
+ || (p.is_multiple_values_set() && p.num_vals.is_none())
+ }
+ })
+ .count();
+ let ok = count <= 1
+ || (last.is_last_set()
+ && last.is_multiple()
+ && second_to_last.is_multiple()
+ && count == 2);
+ assert!(
+ ok,
+ "Only one positional argument with .multiple_values(true) set is allowed per \
+ command, unless the second one also has .last(true) set"
+ );
+ }
+
+ let mut found = false;
+
+ if cmd.is_allow_missing_positional_set() {
+ // Check that if a required positional argument is found, all positions with a lower
+ // index are also required.
+ let mut foundx2 = false;
+
+ for p in cmd.get_positionals() {
+ if foundx2 && !p.is_required_set() {
+ assert!(
+ p.is_required_set(),
+ "Found non-required positional argument with a lower \
+ index than a required positional argument by two or more: {:?} \
+ index {:?}",
+ p.name,
+ p.index
+ );
+ } else if p.is_required_set() && !p.is_last_set() {
+ // Args that .last(true) don't count since they can be required and have
+ // positionals with a lower index that aren't required
+ // Imagine: prog <req1> [opt1] -- <req2>
+ // Both of these are valid invocations:
+ // $ prog r1 -- r2
+ // $ prog r1 o1 -- r2
+ if found {
+ foundx2 = true;
+ continue;
+ }
+ found = true;
+ continue;
+ } else {
+ found = false;
+ }
+ }
+ } else {
+ // Check that if a required positional argument is found, all positions with a lower
+ // index are also required
+ for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) {
+ if found {
+ assert!(
+ p.is_required_set(),
+ "Found non-required positional argument with a lower \
+ index than a required positional argument: {:?} index {:?}",
+ p.name,
+ p.index
+ );
+ } else if p.is_required_set() && !p.is_last_set() {
+ // Args that .last(true) don't count since they can be required and have
+ // positionals with a lower index that aren't required
+ // Imagine: prog <req1> [opt1] -- <req2>
+ // Both of these are valid invocations:
+ // $ prog r1 -- r2
+ // $ prog r1 o1 -- r2
+ found = true;
+ continue;
+ }
+ }
+ }
+ assert!(
+ cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2,
+ "Only one positional argument may have last(true) set. Found two."
+ );
+ if cmd
+ .get_positionals()
+ .any(|p| p.is_last_set() && p.is_required_set())
+ && cmd.has_subcommands()
+ && !cmd.is_subcommand_negates_reqs_set()
+ {
+ panic!(
+ "Having a required positional argument with .last(true) set *and* child \
+ subcommands without setting SubcommandsNegateReqs isn't compatible."
+ );
+ }
+
+ true
+}
+
+fn assert_arg(arg: &Arg) {
+ debug!("Arg::_debug_asserts:{}", arg.name);
+
+ // Self conflict
+ // TODO: this check should be recursive
+ assert!(
+ !arg.blacklist.iter().any(|x| *x == arg.id),
+ "Argument '{}' cannot conflict with itself",
+ arg.name,
+ );
+
+ assert_eq!(
+ arg.get_action().takes_values(),
+ arg.is_takes_value_set(),
+ "Argument `{}`'s selected action {:?} contradicts `takes_value`",
+ arg.name,
+ arg.get_action()
+ );
+ if let Some(action_type_id) = arg.get_action().value_type_id() {
+ assert_eq!(
+ action_type_id,
+ arg.get_value_parser().type_id(),
+ "Argument `{}`'s selected action {:?} contradicts `value_parser` ({:?})",
+ arg.name,
+ arg.get_action(),
+ arg.get_value_parser()
+ );
+ }
+
+ if arg.get_value_hint() != ValueHint::Unknown {
+ assert!(
+ arg.is_takes_value_set(),
+ "Argument '{}' has value hint but takes no value",
+ arg.name
+ );
+
+ if arg.get_value_hint() == ValueHint::CommandWithArguments {
+ assert!(
+ arg.is_multiple_values_set(),
+ "Argument '{}' uses hint CommandWithArguments and must accept multiple values",
+ arg.name
+ )
+ }
+ }
+
+ if arg.index.is_some() {
+ assert!(
+ arg.is_positional(),
+ "Argument '{}' is a positional argument and can't have short or long name versions",
+ arg.name
+ );
+ assert!(
+ arg.is_takes_value_set(),
+ "Argument '{}` is positional, it must take a value",
+ arg.name
+ );
+ }
+
+ #[cfg(feature = "unstable-v4")]
+ {
+ let num_vals = arg.get_num_vals().unwrap_or(usize::MAX);
+ let num_val_names = arg.get_value_names().unwrap_or(&[]).len();
+ if num_vals < num_val_names {
+ panic!(
+ "Argument {}: Too many value names ({}) compared to number_of_values ({})",
+ arg.name, num_val_names, num_vals
+ );
+ }
+ }
+
+ assert_arg_flags(arg);
+
+ assert_defaults(arg, "default_value", arg.default_vals.iter().copied());
+ assert_defaults(
+ arg,
+ "default_missing_value",
+ arg.default_missing_vals.iter().copied(),
+ );
+ assert_defaults(
+ arg,
+ "default_value_if",
+ arg.default_vals_ifs
+ .iter()
+ .filter_map(|(_, _, default)| *default),
+ );
+}
+
+fn assert_arg_flags(arg: &Arg) {
+ macro_rules! checker {
+ ($a:ident requires $($b:ident)|+) => {
+ if arg.$a() {
+ let mut s = String::new();
+
+ $(
+ if !arg.$b() {
+ s.push_str(&format!(" Arg::{} is required when Arg::{} is set.\n", std::stringify!($b), std::stringify!($a)));
+ }
+ )+
+
+ if !s.is_empty() {
+ panic!("Argument {:?}\n{}", arg.get_id(), s)
+ }
+ }
+ }
+ }
+
+ checker!(is_require_value_delimiter_set requires is_takes_value_set);
+ checker!(is_require_value_delimiter_set requires is_use_value_delimiter_set);
+ checker!(is_hide_possible_values_set requires is_takes_value_set);
+ checker!(is_allow_hyphen_values_set requires is_takes_value_set);
+ checker!(is_require_equals_set requires is_takes_value_set);
+ checker!(is_last_set requires is_takes_value_set);
+ checker!(is_hide_default_value_set requires is_takes_value_set);
+ checker!(is_multiple_values_set requires is_takes_value_set);
+ checker!(is_ignore_case_set requires is_takes_value_set);
+ {
+ #![allow(deprecated)]
+ checker!(is_forbid_empty_values_set requires is_takes_value_set);
+ checker!(is_allow_invalid_utf8_set requires is_takes_value_set);
+ }
+}
+
+fn assert_defaults<'d>(
+ arg: &Arg,
+ field: &'static str,
+ defaults: impl IntoIterator<Item = &'d std::ffi::OsStr>,
+) {
+ for default_os in defaults {
+ if let Some(default_s) = default_os.to_str() {
+ if !arg.possible_vals.is_empty() {
+ if let Some(delim) = arg.get_value_delimiter() {
+ for part in default_s.split(delim) {
+ assert!(
+ arg.possible_vals.iter().any(|possible_val| {
+ possible_val.matches(part, arg.is_ignore_case_set())
+ }),
+ "Argument `{}`'s {}={} doesn't match possible values",
+ arg.name,
+ field,
+ part
+ )
+ }
+ } else {
+ assert!(
+ arg.possible_vals.iter().any(|possible_val| {
+ possible_val.matches(default_s, arg.is_ignore_case_set())
+ }),
+ "Argument `{}`'s {}={} doesn't match possible values",
+ arg.name,
+ field,
+ default_s
+ );
+ }
+ }
+
+ if let Some(validator) = arg.validator.as_ref() {
+ let mut validator = validator.lock().unwrap();
+ if let Some(delim) = arg.get_value_delimiter() {
+ for part in default_s.split(delim) {
+ if let Err(err) = validator(part) {
+ panic!(
+ "Argument `{}`'s {}={} failed validation: {}",
+ arg.name, field, part, err
+ );
+ }
+ }
+ } else if let Err(err) = validator(default_s) {
+ panic!(
+ "Argument `{}`'s {}={} failed validation: {}",
+ arg.name, field, default_s, err
+ );
+ }
+ }
+ }
+
+ if let Some(validator) = arg.validator_os.as_ref() {
+ let mut validator = validator.lock().unwrap();
+ if let Some(delim) = arg.get_value_delimiter() {
+ let default_os = RawOsStr::new(default_os);
+ for part in default_os.split(delim) {
+ if let Err(err) = validator(&part.to_os_str()) {
+ panic!(
+ "Argument `{}`'s {}={:?} failed validation: {}",
+ arg.name, field, part, err
+ );
+ }
+ }
+ } else if let Err(err) = validator(default_os) {
+ panic!(
+ "Argument `{}`'s {}={:?} failed validation: {}",
+ arg.name, field, default_os, err
+ );
+ }
+ }
+
+ let value_parser = arg.get_value_parser();
+ let assert_cmd = Command::new("assert");
+ if let Some(delim) = arg.get_value_delimiter() {
+ let default_os = RawOsStr::new(default_os);
+ for part in default_os.split(delim) {
+ if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), &part.to_os_str())
+ {
+ panic!(
+ "Argument `{}`'s {}={:?} failed validation: {}",
+ arg.name,
+ field,
+ part.to_str_lossy(),
+ err
+ );
+ }
+ }
+ } else if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), default_os) {
+ panic!(
+ "Argument `{}`'s {}={:?} failed validation: {}",
+ arg.name, field, default_os, err
+ );
+ }
+ }
+}
diff --git a/src/args/macros.rs b/3.2.23/src/builder/macros.rs
index ac4b1a2..5be4d20 100644
--- a/src/args/macros.rs
+++ b/3.2.23/src/builder/macros.rs
@@ -24,7 +24,11 @@ macro_rules! yaml_tuple3 {
for ys in vec {
if let Some(tup) = ys.as_vec() {
debug_assert_eq!(3, tup.len());
- $a = $a.$c(yaml_str!(tup[0]), yaml_opt_str!(tup[1]), yaml_str!(tup[2]));
+ $a = $a.$c(
+ yaml_str!(tup[0]),
+ yaml_opt_str!(tup[1]),
+ yaml_opt_str!(tup[2]),
+ );
} else {
panic!("Failed to convert YAML value to vec");
}
@@ -38,7 +42,7 @@ macro_rules! yaml_tuple3 {
#[cfg(feature = "yaml")]
macro_rules! yaml_vec_or_str {
- ($v:ident, $a:ident, $c:ident) => {{
+ ($a:ident, $v:ident, $c:ident) => {{
let maybe_vec = $v.as_vec();
if let Some(vec) = maybe_vec {
for ys in vec {
@@ -63,9 +67,29 @@ macro_rules! yaml_vec_or_str {
}
#[cfg(feature = "yaml")]
+macro_rules! yaml_vec {
+ ($a:ident, $v:ident, $c:ident) => {{
+ let maybe_vec = $v.as_vec();
+ if let Some(vec) = maybe_vec {
+ let content = vec.into_iter().map(|ys| {
+ if let Some(s) = ys.as_str() {
+ s
+ } else {
+ panic!("Failed to convert YAML value {:?} to a string", ys);
+ }
+ });
+ $a = $a.$c(content)
+ } else {
+ panic!("Failed to convert YAML value {:?} to a vec", $v);
+ }
+ $a
+ }};
+}
+
+#[cfg(feature = "yaml")]
macro_rules! yaml_opt_str {
($v:expr) => {{
- if $v.is_null() {
+ if !$v.is_null() {
Some(
$v.as_str()
.unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)),
@@ -77,6 +101,17 @@ macro_rules! yaml_opt_str {
}
#[cfg(feature = "yaml")]
+macro_rules! yaml_char {
+ ($v:expr) => {{
+ $v.as_str()
+ .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))
+ .chars()
+ .next()
+ .unwrap_or_else(|| panic!("Expected char"))
+ }};
+}
+
+#[cfg(feature = "yaml")]
macro_rules! yaml_str {
($v:expr) => {{
$v.as_str()
@@ -85,6 +120,13 @@ macro_rules! yaml_str {
}
#[cfg(feature = "yaml")]
+macro_rules! yaml_to_char {
+ ($a:ident, $v:ident, $c:ident) => {{
+ $a.$c(yaml_char!($v))
+ }};
+}
+
+#[cfg(feature = "yaml")]
macro_rules! yaml_to_str {
($a:ident, $v:ident, $c:ident) => {{
$a.$c(yaml_str!($v))
@@ -101,21 +143,38 @@ macro_rules! yaml_to_bool {
}
#[cfg(feature = "yaml")]
-macro_rules! yaml_to_u64 {
+macro_rules! yaml_to_usize {
($a:ident, $v:ident, $c:ident) => {{
$a.$c($v
.as_i64()
.unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))
- as u64)
+ as usize)
}};
}
#[cfg(feature = "yaml")]
-macro_rules! yaml_to_usize {
- ($a:ident, $v:ident, $c:ident) => {{
- $a.$c($v
- .as_i64()
- .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))
- as usize)
+macro_rules! yaml_to_setting {
+ ($a:ident, $v:ident, $c:ident, $s:ident, $t:literal, $n:expr) => {{
+ if let Some(v) = $v.as_vec() {
+ for ys in v {
+ if let Some(s) = ys.as_str() {
+ $a = $a.$c(s.parse::<$s>().unwrap_or_else(|_| {
+ panic!("Unknown {} '{}' found in YAML file for {}", $t, s, $n)
+ }));
+ } else {
+ panic!(
+ "Failed to convert YAML {:?} value to an array of strings",
+ $v
+ );
+ }
+ }
+ } else if let Some(v) = $v.as_str() {
+ $a = $a.$c(v
+ .parse::<$s>()
+ .unwrap_or_else(|_| panic!("Unknown {} '{}' found in YAML file for {}", $t, v, $n)))
+ } else {
+ panic!("Failed to convert YAML {:?} value to a string", $v);
+ }
+ $a
}};
}
diff --git a/3.2.23/src/builder/mod.rs b/3.2.23/src/builder/mod.rs
new file mode 100644
index 0000000..4f24c74
--- /dev/null
+++ b/3.2.23/src/builder/mod.rs
@@ -0,0 +1,61 @@
+//! Define [`Command`] line [arguments][`Arg`]
+
+#[macro_use]
+mod macros;
+
+mod action;
+mod app_settings;
+mod arg;
+mod arg_group;
+mod arg_predicate;
+mod arg_settings;
+mod command;
+mod possible_value;
+mod usage_parser;
+mod value_hint;
+mod value_parser;
+
+#[cfg(feature = "regex")]
+mod regex;
+
+#[cfg(debug_assertions)]
+mod debug_asserts;
+
+#[cfg(test)]
+mod tests;
+
+pub use action::ArgAction;
+pub use app_settings::{AppFlags, AppSettings};
+pub use arg::Arg;
+pub use arg_group::ArgGroup;
+pub use arg_settings::{ArgFlags, ArgSettings};
+pub use command::Command;
+pub use possible_value::PossibleValue;
+pub use value_hint::ValueHint;
+pub use value_parser::PossibleValuesParser;
+pub use value_parser::RangedI64ValueParser;
+pub use value_parser::RangedU64ValueParser;
+pub use value_parser::StringValueParser;
+pub use value_parser::TypedValueParser;
+pub use value_parser::ValueParser;
+pub use value_parser::ValueParserFactory;
+pub use value_parser::_AnonymousValueParser;
+pub use value_parser::_AutoValueParser;
+pub use value_parser::via_prelude;
+pub use value_parser::BoolValueParser;
+pub use value_parser::BoolishValueParser;
+pub use value_parser::EnumValueParser;
+pub use value_parser::FalseyValueParser;
+pub use value_parser::NonEmptyStringValueParser;
+pub use value_parser::OsStringValueParser;
+pub use value_parser::PathBufValueParser;
+
+#[allow(deprecated)]
+pub use command::App;
+
+#[cfg(feature = "regex")]
+pub use self::regex::RegexRef;
+
+pub(crate) use action::CountType;
+pub(crate) use arg::display_arg_val;
+pub(crate) use arg_predicate::ArgPredicate;
diff --git a/3.2.23/src/builder/possible_value.rs b/3.2.23/src/builder/possible_value.rs
new file mode 100644
index 0000000..1c14217
--- /dev/null
+++ b/3.2.23/src/builder/possible_value.rs
@@ -0,0 +1,259 @@
+use std::{borrow::Cow, iter};
+
+use crate::util::eq_ignore_case;
+
+/// A possible value of an argument.
+///
+/// This is used for specifying [possible values] of [Args].
+///
+/// **NOTE:** This struct is likely not needed for most usecases as it is only required to
+/// [hide] single values from help messages and shell completions or to attach [help] to possible values.
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::{Arg, PossibleValue};
+/// let cfg = Arg::new("config")
+/// .takes_value(true)
+/// .value_name("FILE")
+/// .value_parser([
+/// PossibleValue::new("fast"),
+/// PossibleValue::new("slow").help("slower than fast"),
+/// PossibleValue::new("secret speed").hide(true)
+/// ]);
+/// ```
+/// [Args]: crate::Arg
+/// [possible values]: crate::builder::ValueParser::possible_values
+/// [hide]: PossibleValue::hide()
+/// [help]: PossibleValue::help()
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct PossibleValue<'help> {
+ name: &'help str,
+ help: Option<&'help str>,
+ aliases: Vec<&'help str>, // (name, visible)
+ hide: bool,
+}
+
+impl<'help> PossibleValue<'help> {
+ /// Create a [`PossibleValue`] with its name.
+ ///
+ /// The name will be used to decide whether this value was provided by the user to an argument.
+ ///
+ /// **NOTE:** In case it is not [hidden] it will also be shown in help messages for arguments
+ /// that use it as a [possible value] and have not hidden them through [`Arg::hide_possible_values(true)`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::PossibleValue;
+ /// PossibleValue::new("fast")
+ /// # ;
+ /// ```
+ /// [hidden]: PossibleValue::hide
+ /// [possible value]: crate::Arg::possible_values
+ /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values()
+ pub fn new(name: &'help str) -> Self {
+ PossibleValue {
+ name,
+ ..Default::default()
+ }
+ }
+
+ /// Sets the help description of the value.
+ ///
+ /// This is typically displayed in completions (where supported) and should be a short, one-line
+ /// description.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::PossibleValue;
+ /// PossibleValue::new("slow")
+ /// .help("not fast")
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn help(mut self, help: &'help str) -> Self {
+ self.help = Some(help);
+ self
+ }
+
+ /// Hides this value from help and shell completions.
+ ///
+ /// This is an alternative to hiding through [`Arg::hide_possible_values(true)`], if you only
+ /// want to hide some values.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::PossibleValue;
+ /// PossibleValue::new("secret")
+ /// .hide(true)
+ /// # ;
+ /// ```
+ /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values()
+ #[inline]
+ #[must_use]
+ pub fn hide(mut self, yes: bool) -> Self {
+ self.hide = yes;
+ self
+ }
+
+ /// Sets a *hidden* alias for this argument value.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::PossibleValue;
+ /// PossibleValue::new("slow")
+ /// .alias("not-fast")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn alias(mut self, name: &'help str) -> Self {
+ self.aliases.push(name);
+ self
+ }
+
+ /// Sets multiple *hidden* aliases for this argument value.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::PossibleValue;
+ /// PossibleValue::new("slow")
+ /// .aliases(["not-fast", "snake-like"])
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn aliases<I>(mut self, names: I) -> Self
+ where
+ I: IntoIterator<Item = &'help str>,
+ {
+ self.aliases.extend(names.into_iter());
+ self
+ }
+}
+
+/// Reflection
+impl<'help> PossibleValue<'help> {
+ /// Get the name of the argument value
+ #[inline]
+ pub fn get_name(&self) -> &'help str {
+ self.name
+ }
+
+ /// Get the help specified for this argument, if any
+ #[inline]
+ pub fn get_help(&self) -> Option<&'help str> {
+ self.help
+ }
+
+ /// Get the help specified for this argument, if any and the argument
+ /// value is not hidden
+ #[inline]
+ #[cfg(feature = "unstable-v4")]
+ pub(crate) fn get_visible_help(&self) -> Option<&'help str> {
+ if !self.hide {
+ self.help
+ } else {
+ None
+ }
+ }
+
+ /// Deprecated, replaced with [`PossibleValue::is_hide_set`]
+ #[inline]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.1.0", note = "Replaced with `PossibleValue::is_hide_set`")
+ )]
+ pub fn is_hidden(&self) -> bool {
+ self.is_hide_set()
+ }
+
+ /// Report if [`PossibleValue::hide`] is set
+ #[inline]
+ pub fn is_hide_set(&self) -> bool {
+ self.hide
+ }
+
+ /// Report if PossibleValue is not hidden and has a help message
+ pub(crate) fn should_show_help(&self) -> bool {
+ !self.hide && self.help.is_some()
+ }
+
+ /// Get the name if argument value is not hidden, `None` otherwise
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.4",
+ note = "Use `PossibleValue::is_hide_set` and `PossibleValue::get_name`"
+ )
+ )]
+ pub fn get_visible_name(&self) -> Option<&'help str> {
+ if self.hide {
+ None
+ } else {
+ Some(self.name)
+ }
+ }
+
+ /// Get the name if argument value is not hidden, `None` otherwise,
+ /// but wrapped in quotes if it contains whitespace
+ pub(crate) fn get_visible_quoted_name(&self) -> Option<Cow<'help, str>> {
+ if !self.hide {
+ Some(if self.name.contains(char::is_whitespace) {
+ format!("{:?}", self.name).into()
+ } else {
+ self.name.into()
+ })
+ } else {
+ None
+ }
+ }
+
+ /// Returns all valid values of the argument value.
+ ///
+ /// Namely the name and all aliases.
+ pub fn get_name_and_aliases(&self) -> impl Iterator<Item = &'help str> + '_ {
+ iter::once(&self.name).chain(&self.aliases).copied()
+ }
+
+ /// Tests if the value is valid for this argument value
+ ///
+ /// The value is valid if it is either the name or one of the aliases.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::PossibleValue;
+ /// let arg_value = PossibleValue::new("fast").alias("not-slow");
+ ///
+ /// assert!(arg_value.matches("fast", false));
+ /// assert!(arg_value.matches("not-slow", false));
+ ///
+ /// assert!(arg_value.matches("FAST", true));
+ /// assert!(!arg_value.matches("FAST", false));
+ /// ```
+ pub fn matches(&self, value: &str, ignore_case: bool) -> bool {
+ if ignore_case {
+ self.get_name_and_aliases()
+ .any(|name| eq_ignore_case(name, value))
+ } else {
+ self.get_name_and_aliases().any(|name| name == value)
+ }
+ }
+}
+
+impl<'help> From<&'help str> for PossibleValue<'help> {
+ fn from(s: &'help str) -> Self {
+ Self::new(s)
+ }
+}
+
+impl<'help> From<&'help &'help str> for PossibleValue<'help> {
+ fn from(s: &'help &'help str) -> Self {
+ Self::new(s)
+ }
+}
diff --git a/3.2.23/src/builder/regex.rs b/3.2.23/src/builder/regex.rs
new file mode 100644
index 0000000..bf3a78e
--- /dev/null
+++ b/3.2.23/src/builder/regex.rs
@@ -0,0 +1,88 @@
+use ::regex::{Error, Regex, RegexSet};
+
+use core::{convert::TryFrom, ops::Deref, str::FromStr};
+use std::borrow::Cow;
+
+/// Contains either a regular expression or a set of them or a reference to one.
+///
+/// See [Arg::validator_regex(][crate::Arg::validator_regex] to set this on an argument.
+#[derive(Debug, Clone)]
+pub enum RegexRef<'a> {
+ /// Used if the underlying is a regex set
+ RegexSet(Cow<'a, RegexSet>),
+ /// Used if the underlying is a regex
+ Regex(Cow<'a, Regex>),
+}
+
+impl<'a> RegexRef<'a> {
+ pub(crate) fn is_match(&self, text: &str) -> bool {
+ match self {
+ Self::Regex(r) => r.deref().is_match(text),
+ Self::RegexSet(r) => r.deref().is_match(text),
+ }
+ }
+}
+
+impl<'a> From<&'a Regex> for RegexRef<'a> {
+ fn from(r: &'a Regex) -> Self {
+ Self::Regex(Cow::Borrowed(r))
+ }
+}
+
+impl<'a> From<Regex> for RegexRef<'a> {
+ fn from(r: Regex) -> Self {
+ Self::Regex(Cow::Owned(r))
+ }
+}
+
+impl<'a> From<&'a RegexSet> for RegexRef<'a> {
+ fn from(r: &'a RegexSet) -> Self {
+ Self::RegexSet(Cow::Borrowed(r))
+ }
+}
+
+impl<'a> From<RegexSet> for RegexRef<'a> {
+ fn from(r: RegexSet) -> Self {
+ Self::RegexSet(Cow::Owned(r))
+ }
+}
+
+impl<'a> TryFrom<&'a str> for RegexRef<'a> {
+ type Error = <Self as FromStr>::Err;
+
+ fn try_from(r: &'a str) -> Result<Self, Self::Error> {
+ Self::from_str(r)
+ }
+}
+
+impl<'a> FromStr for RegexRef<'a> {
+ type Err = Error;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ Regex::from_str(s).map(|v| Self::Regex(Cow::Owned(v)))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use core::convert::TryInto;
+
+ #[test]
+ fn test_try_from_with_valid_string() {
+ let t: Result<RegexRef, _> = "^Hello, World$".try_into();
+ assert!(t.is_ok())
+ }
+
+ #[test]
+ fn test_try_from_with_invalid_string() {
+ let t: Result<RegexRef, _> = "^Hello, World)$".try_into();
+ assert!(t.is_err());
+ }
+
+ #[test]
+ fn from_str() {
+ let t: Result<RegexRef, _> = RegexRef::from_str("^Hello, World");
+ assert!(t.is_ok());
+ }
+}
diff --git a/3.2.23/src/builder/tests.rs b/3.2.23/src/builder/tests.rs
new file mode 100644
index 0000000..76c8b87
--- /dev/null
+++ b/3.2.23/src/builder/tests.rs
@@ -0,0 +1,56 @@
+use crate::Arg;
+use crate::Command;
+
+#[test]
+fn propagate_version() {
+ let mut cmd = Command::new("test")
+ .propagate_version(true)
+ .version("1.1")
+ .subcommand(Command::new("sub1"));
+ cmd._propagate();
+ assert_eq!(
+ cmd.get_subcommands().next().unwrap().get_version(),
+ Some("1.1")
+ );
+}
+
+#[test]
+fn global_setting() {
+ let mut cmd = Command::new("test")
+ .disable_version_flag(true)
+ .subcommand(Command::new("subcmd"));
+ cmd._propagate();
+ assert!(cmd
+ .get_subcommands()
+ .find(|s| s.get_name() == "subcmd")
+ .unwrap()
+ .is_disable_version_flag_set());
+}
+
+// This test will *fail to compile* if Command is not Send + Sync
+#[test]
+fn app_send_sync() {
+ fn foo<T: Send + Sync>(_: T) {}
+ foo(Command::new("test"))
+}
+
+#[test]
+fn issue_2090() {
+ let mut cmd = Command::new("cmd")
+ .disable_version_flag(true)
+ .subcommand(Command::new("sub"));
+ cmd._build_self();
+
+ assert!(cmd
+ .get_subcommands()
+ .next()
+ .unwrap()
+ .is_disable_version_flag_set());
+}
+
+// This test will *fail to compile* if Arg is not Send + Sync
+#[test]
+fn arg_send_sync() {
+ fn foo<T: Send + Sync>(_: T) {}
+ foo(Arg::new("test"))
+}
diff --git a/3.2.23/src/builder/usage_parser.rs b/3.2.23/src/builder/usage_parser.rs
new file mode 100644
index 0000000..85d0d30
--- /dev/null
+++ b/3.2.23/src/builder/usage_parser.rs
@@ -0,0 +1,1277 @@
+#![allow(deprecated)]
+
+// Internal
+use crate::builder::Arg;
+use crate::builder::ArgSettings;
+use crate::INTERNAL_ERROR_MSG;
+
+#[derive(PartialEq, Debug)]
+enum UsageToken {
+ Name,
+ ValName,
+ Short,
+ Long,
+ Help,
+ Multiple,
+ Unknown,
+ Default,
+}
+
+#[derive(Debug)]
+pub(crate) struct UsageParser<'help> {
+ usage: &'help str,
+ pos: usize,
+ start: usize,
+ prev: UsageToken,
+ explicit_name_set: bool,
+}
+
+impl<'help> UsageParser<'help> {
+ fn new(usage: &'help str) -> Self {
+ debug!("new: usage={:?}", usage);
+ UsageParser {
+ usage,
+ pos: 0,
+ start: 0,
+ prev: UsageToken::Unknown,
+ explicit_name_set: false,
+ }
+ }
+
+ pub(crate) fn from_usage(usage: &'help str) -> Self {
+ debug!("UsageParser::from_usage");
+ UsageParser::new(usage)
+ }
+
+ pub(crate) fn parse(mut self) -> Arg<'help> {
+ debug!("UsageParser::parse");
+ let mut arg = Arg::default();
+ loop {
+ debug!("UsageParser::parse:iter: pos={}", self.pos);
+ self.stop_at(token);
+ if let Some(&c) = self.usage.as_bytes().get(self.pos) {
+ match c {
+ b'-' => self.short_or_long(&mut arg),
+ b'.' => self.multiple(&mut arg),
+ b'@' => self.default(&mut arg),
+ b'\'' => self.help(&mut arg),
+ _ => self.name(&mut arg),
+ }
+ } else {
+ break;
+ }
+ }
+
+ debug!("UsageParser::parse: vals...{:?}", arg.val_names);
+ arg
+ }
+
+ fn name(&mut self, arg: &mut Arg<'help>) {
+ debug!("UsageParser::name");
+ if *self
+ .usage
+ .as_bytes()
+ .get(self.pos)
+ .expect(INTERNAL_ERROR_MSG)
+ == b'<'
+ && !self.explicit_name_set
+ {
+ arg.settings.set(ArgSettings::Required);
+ }
+ self.pos += 1;
+ self.stop_at(name_end);
+ let name = &self.usage[self.start..self.pos];
+ if self.prev == UsageToken::Unknown {
+ debug!("UsageParser::name: setting name...{}", name);
+ arg.id = name.into();
+ arg.name = name;
+ if arg.long.is_none() && arg.short.is_none() {
+ debug!("name: explicit name set...");
+ self.explicit_name_set = true;
+ self.prev = UsageToken::Name;
+ }
+ } else {
+ debug!("UsageParser::name: setting val name...{}", name);
+ if arg.val_names.is_empty() {
+ arg.settings.set(ArgSettings::TakesValue);
+ }
+ let len = arg.val_names.len();
+ arg.val_names.insert(len, name);
+ self.prev = UsageToken::ValName;
+ }
+ }
+
+ fn stop_at<F>(&mut self, f: F)
+ where
+ F: Fn(u8) -> bool,
+ {
+ debug!("UsageParser::stop_at");
+ self.start = self.pos;
+ self.pos += self.usage[self.start..]
+ .bytes()
+ .take_while(|&b| f(b))
+ .count();
+ }
+
+ fn short_or_long(&mut self, arg: &mut Arg<'help>) {
+ debug!("UsageParser::short_or_long");
+ self.pos += 1;
+ if *self
+ .usage
+ .as_bytes()
+ .get(self.pos)
+ .expect(INTERNAL_ERROR_MSG)
+ == b'-'
+ {
+ self.pos += 1;
+ self.long(arg);
+ return;
+ }
+ self.short(arg)
+ }
+
+ fn long(&mut self, arg: &mut Arg<'help>) {
+ debug!("UsageParser::long");
+ self.stop_at(long_end);
+ let name = &self.usage[self.start..self.pos];
+ if !self.explicit_name_set {
+ debug!("UsageParser::long: setting name...{}", name);
+ arg.id = name.into();
+ arg.name = name;
+ }
+ debug!("UsageParser::long: setting long...{}", name);
+ arg.long = Some(name);
+ self.prev = UsageToken::Long;
+ }
+
+ fn short(&mut self, arg: &mut Arg<'help>) {
+ debug!("UsageParser::short");
+ let start = &self.usage[self.pos..];
+ let short = start.chars().next().expect(INTERNAL_ERROR_MSG);
+ debug!("UsageParser::short: setting short...{}", short);
+ arg.short = Some(short);
+ if arg.name.is_empty() {
+ // --long takes precedence but doesn't set self.explicit_name_set
+ let name = &start[..short.len_utf8()];
+ debug!("UsageParser::short: setting name...{}", name);
+ arg.id = name.into();
+ arg.name = name;
+ }
+ self.prev = UsageToken::Short;
+ }
+
+ // "something..."
+ fn multiple(&mut self, arg: &mut Arg) {
+ debug!("UsageParser::multiple");
+ let mut dot_counter = 1;
+ let start = self.pos;
+ let mut bytes = self.usage[start..].bytes();
+ while bytes.next() == Some(b'.') {
+ dot_counter += 1;
+ self.pos += 1;
+ if dot_counter == 3 {
+ debug!("UsageParser::multiple: setting multiple");
+ arg.settings.set(ArgSettings::MultipleOccurrences);
+ if arg.is_takes_value_set() {
+ arg.settings.set(ArgSettings::MultipleValues);
+ arg.settings.set(ArgSettings::UseValueDelimiter);
+ arg.val_delim.get_or_insert(',');
+ }
+ self.prev = UsageToken::Multiple;
+ self.pos += 1;
+ break;
+ }
+ }
+ }
+
+ fn help(&mut self, arg: &mut Arg<'help>) {
+ debug!("UsageParser::help");
+ self.stop_at(help_start);
+ self.start = self.pos + 1;
+ self.pos = self.usage.len() - 1;
+ debug!(
+ "UsageParser::help: setting help...{}",
+ &self.usage[self.start..self.pos]
+ );
+ arg.help = Some(&self.usage[self.start..self.pos]);
+ self.pos += 1; // Move to next byte to keep from thinking ending ' is a start
+ self.prev = UsageToken::Help;
+ }
+
+ fn default(&mut self, arg: &mut Arg<'help>) {
+ debug!(
+ "UsageParser::default: from=\"{}\"",
+ &self.usage[self.pos..self.usage.len()]
+ );
+ self.pos += 1; // Skip @
+ self.stop_at(default_value_end); // Find first space after value
+ debug!(
+ "UsageParser::default: setting default...\"{}\"",
+ &self.usage[self.start..self.pos]
+ );
+ arg.settings.set(ArgSettings::TakesValue);
+ arg.default_vals = vec![std::ffi::OsStr::new(&self.usage[self.start..self.pos])];
+ self.prev = UsageToken::Default;
+ }
+}
+
+#[inline]
+fn name_end(b: u8) -> bool {
+ b != b']' && b != b'>'
+}
+
+#[inline]
+fn token(b: u8) -> bool {
+ b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'-' && b != b'@'
+}
+
+#[inline]
+fn long_end(b: u8) -> bool {
+ b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'=' && b != b' '
+}
+
+#[inline]
+fn help_start(b: u8) -> bool {
+ b != b'\''
+}
+
+#[inline]
+fn default_value_end(b: u8) -> bool {
+ b != b' '
+}
+
+#[cfg(test)]
+mod test {
+ #![allow(deprecated)]
+
+ use crate::builder::{Arg, ArgSettings};
+
+ #[allow(clippy::cognitive_complexity)]
+ #[test]
+ fn create_flag_usage() {
+ let a = Arg::from_usage("[flag] -f 'some help info'");
+ assert_eq!(a.name, "flag");
+ assert_eq!(a.short.unwrap(), 'f');
+ assert!(a.long.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(a.val_names.is_empty());
+
+ let a = Arg::from_usage("[flag] --flag 'some help info'");
+ assert_eq!(a.name, "flag");
+ assert_eq!(a.long.unwrap(), "flag");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(a.val_names.is_empty());
+
+ let a = Arg::from_usage("--flag 'some help info'");
+ assert_eq!(a.name, "flag");
+ assert_eq!(a.long.unwrap(), "flag");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(a.val_names.is_empty());
+
+ let a = Arg::from_usage("[flag] -f --flag 'some help info'");
+ assert_eq!(a.name, "flag");
+ assert_eq!(a.short.unwrap(), 'f');
+ assert_eq!(a.long.unwrap(), "flag");
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(a.val_names.is_empty());
+
+ let a = Arg::from_usage("[flag] -f... 'some help info'");
+ assert_eq!(a.name, "flag");
+ assert_eq!(a.short.unwrap(), 'f');
+ assert!(a.long.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.val_names.is_empty());
+
+ let a = Arg::from_usage("[flag] -f --flag... 'some help info'");
+ assert_eq!(a.name, "flag");
+ assert_eq!(a.long.unwrap(), "flag");
+ assert_eq!(a.short.unwrap(), 'f');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.val_names.is_empty());
+
+ let a = Arg::from_usage("-f --flag... 'some help info'");
+ assert_eq!(a.name, "flag");
+ assert_eq!(a.long.unwrap(), "flag");
+ assert_eq!(a.short.unwrap(), 'f');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.val_names.is_empty());
+
+ let a = Arg::from_usage("--flags");
+ assert_eq!(a.name, "flags");
+ assert_eq!(a.long.unwrap(), "flags");
+ assert!(a.val_names.is_empty());
+
+ let a = Arg::from_usage("--flags...");
+ assert_eq!(a.name, "flags");
+ assert_eq!(a.long.unwrap(), "flags");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.val_names.is_empty());
+
+ let a = Arg::from_usage("[flags] -f");
+ assert_eq!(a.name, "flags");
+ assert_eq!(a.short.unwrap(), 'f');
+ assert!(a.val_names.is_empty());
+
+ let a = Arg::from_usage("[flags] -f...");
+ assert_eq!(a.name, "flags");
+ assert_eq!(a.short.unwrap(), 'f');
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.val_names.is_empty());
+
+ let a = Arg::from_usage("-f 'some help info'");
+ assert_eq!(a.name, "f");
+ assert_eq!(a.short.unwrap(), 'f');
+ assert!(a.long.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(a.val_names.is_empty());
+
+ let a = Arg::from_usage("-f");
+ assert_eq!(a.name, "f");
+ assert_eq!(a.short.unwrap(), 'f');
+ assert!(a.val_names.is_empty());
+
+ let a = Arg::from_usage("-f...");
+ assert_eq!(a.name, "f");
+ assert_eq!(a.short.unwrap(), 'f');
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.val_names.is_empty());
+ }
+
+ #[test]
+ fn create_option_usage0() {
+ // Short only
+ let a = Arg::from_usage("[option] -o [opt] 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert!(a.long.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage1() {
+ let a = Arg::from_usage("-o [opt] 'some help info'");
+ assert_eq!(a.name, "o");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert!(a.long.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage2() {
+ let a = Arg::from_usage("<option> -o <opt> 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert!(a.long.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage3() {
+ let a = Arg::from_usage("-o <opt> 'some help info'");
+ assert_eq!(a.name, "o");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert!(a.long.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage4() {
+ let a = Arg::from_usage("[option] -o [opt]... 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert!(a.long.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage5() {
+ let a = Arg::from_usage("[option]... -o [opt] 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert!(a.long.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage6() {
+ let a = Arg::from_usage("-o [opt]... 'some help info'");
+ assert_eq!(a.name, "o");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert!(a.long.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage7() {
+ let a = Arg::from_usage("<option> -o <opt>... 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert!(a.long.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage8() {
+ let a = Arg::from_usage("<option>... -o <opt> 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert!(a.long.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage9() {
+ let a = Arg::from_usage("-o <opt>... 'some help info'");
+ assert_eq!(a.name, "o");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert!(a.long.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_long1() {
+ let a = Arg::from_usage("[option] --opt [opt] 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_long2() {
+ let a = Arg::from_usage("--opt [option] 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_long3() {
+ let a = Arg::from_usage("<option> --opt <opt> 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_long4() {
+ let a = Arg::from_usage("--opt <option> 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_long5() {
+ let a = Arg::from_usage("[option] --opt [opt]... 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_long6() {
+ let a = Arg::from_usage("[option]... --opt [opt] 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_long7() {
+ let a = Arg::from_usage("--opt [option]... 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_long8() {
+ let a = Arg::from_usage("<option> --opt <opt>... 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_long9() {
+ let a = Arg::from_usage("<option>... --opt <opt> 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_long10() {
+ let a = Arg::from_usage("--opt <option>... 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_long_equals1() {
+ let a = Arg::from_usage("[option] --opt=[opt] 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_long_equals2() {
+ let a = Arg::from_usage("--opt=[option] 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_long_equals3() {
+ let a = Arg::from_usage("<option> --opt=<opt> 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_long_equals4() {
+ let a = Arg::from_usage("--opt=<option> 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_long_equals5() {
+ let a = Arg::from_usage("[option] --opt=[opt]... 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_long_equals6() {
+ let a = Arg::from_usage("[option]... --opt=[opt] 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_long_equals7() {
+ let a = Arg::from_usage("--opt=[option]... 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_long_equals8() {
+ let a = Arg::from_usage("<option> --opt=<opt>... 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_long_equals9() {
+ let a = Arg::from_usage("<option>... --opt=<opt> 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_long_equals10() {
+ let a = Arg::from_usage("--opt=<option>... 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_both1() {
+ let a = Arg::from_usage("[option] -o --opt [option] 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_both2() {
+ let a = Arg::from_usage("-o --opt [option] 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_both3() {
+ let a = Arg::from_usage("<option> -o --opt <opt> 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_both4() {
+ let a = Arg::from_usage("-o --opt <option> 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_both5() {
+ let a = Arg::from_usage("[option]... -o --opt [option] 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_both6() {
+ let a = Arg::from_usage("-o --opt [option]... 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_both7() {
+ let a = Arg::from_usage("<option>... -o --opt <opt> 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_both8() {
+ let a = Arg::from_usage("-o --opt <option>... 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_both_equals1() {
+ let a = Arg::from_usage("[option] -o --opt=[option] 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_both_equals2() {
+ let a = Arg::from_usage("-o --opt=[option] 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_both_equals3() {
+ let a = Arg::from_usage("<option> -o --opt=<opt> 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_both_equals4() {
+ let a = Arg::from_usage("-o --opt=<option> 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_both_equals5() {
+ let a = Arg::from_usage("[option]... -o --opt=[option] 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_both_equals6() {
+ let a = Arg::from_usage("-o --opt=[option]... 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_usage_both_equals7() {
+ let a = Arg::from_usage("<option>... -o --opt=<opt> 'some help info'");
+ assert_eq!(a.name, "option");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]);
+ }
+
+ #[test]
+ fn create_option_usage_both_equals8() {
+ let a = Arg::from_usage("-o --opt=<option>... 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]);
+ }
+
+ #[test]
+ fn create_option_with_vals1() {
+ let a = Arg::from_usage("-o <file> <mode> 'some help info'");
+ assert_eq!(a.name, "o");
+ assert!(a.long.is_none());
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"file", &"mode"]);
+ }
+
+ #[test]
+ fn create_option_with_vals2() {
+ let a = Arg::from_usage("-o <file> <mode>... 'some help info'");
+ assert_eq!(a.name, "o");
+ assert!(a.long.is_none());
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"file", &"mode"]);
+ }
+
+ #[test]
+ fn create_option_with_vals3() {
+ let a = Arg::from_usage("--opt <file> <mode>... 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"file", &"mode"]);
+ }
+
+ #[test]
+ fn create_option_with_vals4() {
+ let a = Arg::from_usage("[myopt] --opt <file> <mode> 'some help info'");
+ assert_eq!(a.name, "myopt");
+ assert!(a.short.is_none());
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"file", &"mode"]);
+ }
+
+ #[test]
+ fn create_option_with_vals5() {
+ let a = Arg::from_usage("--opt <file> <mode> 'some help info'");
+ assert_eq!(a.name, "opt");
+ assert!(a.short.is_none());
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ }
+
+ #[test]
+ fn create_positional_usage() {
+ let a = Arg::from_usage("[pos] 'some help info'");
+ assert_eq!(a.name, "pos");
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(!a.is_required_set());
+ assert!(a.val_names.is_empty());
+ }
+
+ #[test]
+ fn create_positional_usage0() {
+ let a = Arg::from_usage("<pos> 'some help info'");
+ assert_eq!(a.name, "pos");
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_required_set());
+ assert!(a.val_names.is_empty());
+ }
+
+ #[test]
+ fn pos_mult_help() {
+ let a = Arg::from_usage("[pos]... 'some help info'");
+ assert_eq!(a.name, "pos");
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(!a.is_required_set());
+ assert!(a.val_names.is_empty());
+ }
+
+ #[test]
+ fn pos_help_lit_single_quote() {
+ let a = Arg::from_usage("[pos]... 'some help\' info'");
+ assert_eq!(a.name, "pos");
+ assert_eq!(a.help.unwrap(), "some help' info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(!a.is_required_set());
+ assert!(a.val_names.is_empty());
+ }
+
+ #[test]
+ fn pos_help_double_lit_single_quote() {
+ let a = Arg::from_usage("[pos]... 'some \'help\' info'");
+ assert_eq!(a.name, "pos");
+ assert_eq!(a.help.unwrap(), "some 'help' info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(!a.is_required_set());
+ assert!(a.val_names.is_empty());
+ }
+
+ #[test]
+ fn pos_help_newline() {
+ let a = Arg::from_usage(
+ "[pos]... 'some help{n}\
+ info'",
+ );
+ assert_eq!(a.name, "pos");
+ assert_eq!(a.help.unwrap(), "some help{n}info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(!a.is_required_set());
+ assert!(a.val_names.is_empty());
+ }
+
+ #[test]
+ fn pos_help_newline_lit_sq() {
+ let a = Arg::from_usage(
+ "[pos]... 'some help\' stuff{n}\
+ info'",
+ );
+ assert_eq!(a.name, "pos");
+ assert_eq!(a.help.unwrap(), "some help' stuff{n}info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(!a.is_required_set());
+ assert!(a.val_names.is_empty());
+ }
+
+ #[test]
+ fn pos_req_mult_help() {
+ let a = Arg::from_usage("<pos>... 'some help info'");
+ assert_eq!(a.name, "pos");
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_required_set());
+ assert!(a.val_names.is_empty());
+ }
+
+ #[test]
+ fn pos_req() {
+ let a = Arg::from_usage("<pos>");
+ assert_eq!(a.name, "pos");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_required_set());
+ assert!(a.val_names.is_empty());
+ }
+
+ #[test]
+ fn pos_mult() {
+ let a = Arg::from_usage("[pos]...");
+ assert_eq!(a.name, "pos");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(!a.is_required_set());
+ assert!(a.val_names.is_empty());
+ }
+
+ #[test]
+ fn pos_req_mult_def_help() {
+ let a = Arg::from_usage("<pos>... @a 'some help info'");
+ assert_eq!(a.name, "pos");
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_required_set());
+ assert!(a.val_names.is_empty());
+ assert_eq!(a.default_vals, vec![std::ffi::OsStr::new("a")]);
+ }
+
+ #[test]
+ fn create_option_with_vals1_def() {
+ let a = Arg::from_usage("-o <file> <mode> @a 'some help info'");
+ assert_eq!(a.name, "o");
+ assert!(a.long.is_none());
+ assert_eq!(a.short.unwrap(), 'o');
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"file", &"mode"]);
+ assert_eq!(a.default_vals, vec![std::ffi::OsStr::new("a")]);
+ }
+
+ #[test]
+ fn create_option_with_vals4_def() {
+ let a = Arg::from_usage("[myopt] --opt <file> <mode> @a 'some help info'");
+ assert_eq!(a.name, "myopt");
+ assert!(a.short.is_none());
+ assert_eq!(a.long.unwrap(), "opt");
+ assert_eq!(a.help.unwrap(), "some help info");
+ assert!(!a.is_multiple_occurrences_set());
+ assert!(!a.is_multiple_values_set());
+ assert!(a.is_takes_value_set());
+ assert!(!a.is_required_set());
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"file", &"mode"]);
+ assert_eq!(a.default_vals, vec![std::ffi::OsStr::new("a")]);
+ }
+
+ #[test]
+ fn nonascii() {
+ let a = Arg::from_usage("<ASCII> 'üñíčöĐ€'");
+ assert_eq!(a.name, "ASCII");
+ assert_eq!(a.help, Some("üñíčöĐ€"));
+ let a = Arg::from_usage("<üñíčöĐ€> 'ASCII'");
+ assert_eq!(a.name, "üñíčöĐ€");
+ assert_eq!(a.help, Some("ASCII"));
+ let a = Arg::from_usage("<üñíčöĐ€> 'üñíčöĐ€'");
+ assert_eq!(a.name, "üñíčöĐ€");
+ assert_eq!(a.help, Some("üñíčöĐ€"));
+ let a = Arg::from_usage("-ø 'ø'");
+ assert_eq!(a.name, "ø");
+ assert_eq!(a.short, Some('ø'));
+ assert_eq!(a.help, Some("ø"));
+ let a = Arg::from_usage("--üñíčöĐ€ 'Nōṫ ASCII'");
+ assert_eq!(a.name, "üñíčöĐ€");
+ assert_eq!(a.long, Some("üñíčöĐ€"));
+ assert_eq!(a.help, Some("Nōṫ ASCII"));
+ let a = Arg::from_usage("[ñämê] --ôpt=[üñíčöĐ€] 'hælp'");
+ assert_eq!(a.name, "ñämê");
+ assert_eq!(a.long, Some("ôpt"));
+ assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"üñíčöĐ€"]);
+ assert_eq!(a.help, Some("hælp"));
+ }
+
+ #[test]
+ fn value_names_building_num_vals_from_usage() {
+ use crate::Command;
+ let m = Command::new("test")
+ .arg(Arg::from_usage("--pos <who> <what> <why>"))
+ .try_get_matches_from(vec!["myprog", "--pos", "val1", "val2", "val3"]);
+
+ assert!(m.is_ok(), "{:?}", m.unwrap_err().kind());
+ let m = m.unwrap();
+
+ assert_eq!(
+ m.values_of("pos").unwrap().collect::<Vec<_>>(),
+ ["val1", "val2", "val3"]
+ );
+ }
+
+ #[test]
+ fn issue_665() {
+ use crate::{error::ErrorKind, Command};
+ // Verify fix for "arg_from_usage(): required values not being enforced when followed by another option"
+ let res = Command::new("tester")
+ .arg(Arg::from_usage("-v, --reroll-count=[N] 'Mark the patch series as PATCH vN'"))
+ .arg(
+ Arg::from_usage("--subject-prefix [Subject-Prefix] 'Use [Subject-Prefix] instead of the standard [PATCH] prefix'")
+ .setting(ArgSettings::ForbidEmptyValues)
+ )
+ .try_get_matches_from(vec!["test", "--subject-prefix", "-v", "2"]);
+
+ assert!(res.is_err());
+ assert_eq!(res.unwrap_err().kind(), ErrorKind::EmptyValue);
+ }
+}
diff --git a/3.2.23/src/builder/value_hint.rs b/3.2.23/src/builder/value_hint.rs
new file mode 100644
index 0000000..7c35d1e
--- /dev/null
+++ b/3.2.23/src/builder/value_hint.rs
@@ -0,0 +1,95 @@
+use std::str::FromStr;
+
+/// Provide shell with hint on how to complete an argument.
+///
+/// See [Arg::value_hint][crate::Arg::value_hint] to set this on an argument.
+///
+/// See the `clap_complete` crate for completion script generation.
+///
+/// Overview of which hints are supported by which shell:
+///
+/// | Hint | zsh | fish[^1]|
+/// | ---------------------- | --- | ------- |
+/// | `AnyPath` | Yes | Yes |
+/// | `FilePath` | Yes | Yes |
+/// | `DirPath` | Yes | Yes |
+/// | `ExecutablePath` | Yes | Partial |
+/// | `CommandName` | Yes | Yes |
+/// | `CommandString` | Yes | Partial |
+/// | `CommandWithArguments` | Yes | |
+/// | `Username` | Yes | Yes |
+/// | `Hostname` | Yes | Yes |
+/// | `Url` | Yes | |
+/// | `EmailAddress` | Yes | |
+///
+/// [^1]: fish completions currently only support named arguments (e.g. -o or --opt), not
+/// positional arguments.
+#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
+#[non_exhaustive]
+pub enum ValueHint {
+ /// Default value if hint is not specified. Follows shell default behavior, which is usually
+ /// auto-completing filenames.
+ Unknown,
+ /// None of the hints below apply. Disables shell completion for this argument.
+ Other,
+ /// Any existing path.
+ AnyPath,
+ /// Path to a file.
+ FilePath,
+ /// Path to a directory.
+ DirPath,
+ /// Path to an executable file.
+ ExecutablePath,
+ /// Name of a command, without arguments. May be relative to PATH, or full path to executable.
+ CommandName,
+ /// A single string containing a command and its arguments.
+ CommandString,
+ /// Capture the remaining arguments as a command name and arguments for that command. This is
+ /// common when writing shell wrappers that execute anther command, for example `sudo` or `env`.
+ ///
+ /// This hint is special, the argument must be a positional argument and have
+ /// [`.multiple_values(true)`] and Command must use [`Command::trailing_var_arg(true)`]. The result is that the
+ /// command line `my_app ls -la /` will be parsed as `["ls", "-la", "/"]` and clap won't try to
+ /// parse the `-la` argument itself.
+ ///
+ /// [`Command::trailing_var_arg(true)`]: crate::Command::trailing_var_arg
+ /// [`.multiple_values(true)`]: crate::Arg::multiple_values()
+ CommandWithArguments,
+ /// Name of a local operating system user.
+ Username,
+ /// Host name of a computer.
+ /// Shells usually parse `/etc/hosts` and `.ssh/known_hosts` to complete hostnames.
+ Hostname,
+ /// Complete web address.
+ Url,
+ /// Email address.
+ EmailAddress,
+}
+
+impl Default for ValueHint {
+ fn default() -> Self {
+ ValueHint::Unknown
+ }
+}
+
+impl FromStr for ValueHint {
+ type Err = String;
+ fn from_str(s: &str) -> Result<Self, <Self as FromStr>::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,
+ _ => return Err(format!("unknown ValueHint: `{}`", s)),
+ })
+ }
+}
diff --git a/3.2.23/src/builder/value_parser.rs b/3.2.23/src/builder/value_parser.rs
new file mode 100644
index 0000000..92cbbad
--- /dev/null
+++ b/3.2.23/src/builder/value_parser.rs
@@ -0,0 +1,2186 @@
+use std::convert::TryInto;
+use std::ops::RangeBounds;
+
+use crate::parser::AnyValue;
+use crate::parser::AnyValueId;
+
+/// Parse/validate argument values
+///
+/// Specified with [`Arg::value_parser`][crate::Arg::value_parser].
+///
+/// `ValueParser` defines how to convert a raw argument value into a validated and typed value for
+/// use within an application.
+///
+/// See
+/// - [`value_parser!`][crate::value_parser] for automatically selecting an implementation for a given type
+/// - [`ValueParser::new`] for additional [`TypedValueParser`] that can be used
+///
+/// # Example
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("color")
+/// .long("color")
+/// .value_parser(["always", "auto", "never"])
+/// .default_value("auto")
+/// )
+/// .arg(
+/// clap::Arg::new("hostname")
+/// .long("hostname")
+/// .value_parser(clap::builder::NonEmptyStringValueParser::new())
+/// .takes_value(true)
+/// .required(true)
+/// )
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(clap::value_parser!(u16).range(3000..))
+/// .takes_value(true)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(
+/// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"]
+/// ).unwrap();
+///
+/// let color: &String = m.get_one("color")
+/// .expect("default");
+/// assert_eq!(color, "auto");
+///
+/// let hostname: &String = m.get_one("hostname")
+/// .expect("required");
+/// assert_eq!(hostname, "rust-lang.org");
+///
+/// let port: u16 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+pub struct ValueParser(ValueParserInner);
+
+enum ValueParserInner {
+ // Common enough to optimize and for possible values
+ Bool,
+ // Common enough to optimize
+ String,
+ // Common enough to optimize
+ OsString,
+ // Common enough to optimize
+ PathBuf,
+ Other(Box<dyn AnyValueParser>),
+}
+
+impl ValueParser {
+ /// Custom parser for argument values
+ ///
+ /// To create a custom parser, see [`TypedValueParser`]
+ ///
+ /// Pre-existing implementations include:
+ /// - [`EnumValueParser`] and [`PossibleValuesParser`] for static enumerated values
+ /// - [`BoolishValueParser`] and [`FalseyValueParser`] for alternative `bool` implementations
+ /// - [`RangedI64ValueParser`] and [`RangedU64ValueParser`]
+ /// - [`NonEmptyStringValueParser`]
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// type EnvVar = (String, Option<String>);
+ /// fn parse_env_var(env: &str) -> Result<EnvVar, std::io::Error> {
+ /// if let Some((var, value)) = env.split_once('=') {
+ /// Ok((var.to_owned(), Some(value.to_owned())))
+ /// } else {
+ /// Ok((env.to_owned(), None))
+ /// }
+ /// }
+ ///
+ /// let mut cmd = clap::Command::new("raw")
+ /// .arg(
+ /// clap::Arg::new("env")
+ /// .value_parser(clap::builder::ValueParser::new(parse_env_var))
+ /// .required(true)
+ /// );
+ ///
+ /// let m = cmd.try_get_matches_from_mut(["cmd", "key=value"]).unwrap();
+ /// let port: &EnvVar = m.get_one("env")
+ /// .expect("required");
+ /// assert_eq!(*port, ("key".into(), Some("value".into())));
+ /// ```
+ pub fn new<P>(other: P) -> Self
+ where
+ P: TypedValueParser,
+ P::Value: Send + Sync + Clone,
+ {
+ Self(ValueParserInner::Other(Box::new(other)))
+ }
+
+ /// [`bool`] parser for argument values
+ ///
+ /// See also:
+ /// - [`BoolishValueParser`] for different human readable bool representations
+ /// - [`FalseyValueParser`] for assuming non-false is true
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// let mut cmd = clap::Command::new("raw")
+ /// .arg(
+ /// clap::Arg::new("download")
+ /// .value_parser(clap::value_parser!(bool))
+ /// .required(true)
+ /// );
+ ///
+ /// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap();
+ /// let port: bool = *m.get_one("download")
+ /// .expect("required");
+ /// assert_eq!(port, true);
+ ///
+ /// assert!(cmd.try_get_matches_from_mut(["cmd", "forever"]).is_err());
+ /// ```
+ pub const fn bool() -> Self {
+ Self(ValueParserInner::Bool)
+ }
+
+ /// [`String`] parser for argument values
+ ///
+ /// See also:
+ /// - [`NonEmptyStringValueParser`]
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// let mut cmd = clap::Command::new("raw")
+ /// .arg(
+ /// clap::Arg::new("port")
+ /// .value_parser(clap::value_parser!(String))
+ /// .required(true)
+ /// );
+ ///
+ /// let m = cmd.try_get_matches_from_mut(["cmd", "80"]).unwrap();
+ /// let port: &String = m.get_one("port")
+ /// .expect("required");
+ /// assert_eq!(port, "80");
+ /// ```
+ pub const fn string() -> Self {
+ Self(ValueParserInner::String)
+ }
+
+ /// [`OsString`][std::ffi::OsString] parser for argument values
+ ///
+ /// # Example
+ ///
+ #[cfg_attr(not(unix), doc = " ```ignore")]
+ #[cfg_attr(unix, doc = " ```rust")]
+ /// # use clap::{Command, Arg, builder::ValueParser};
+ /// use std::ffi::OsString;
+ /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
+ /// let r = Command::new("myprog")
+ /// .arg(
+ /// Arg::new("arg")
+ /// .required(true)
+ /// .value_parser(ValueParser::os_string())
+ /// )
+ /// .try_get_matches_from(vec![
+ /// OsString::from("myprog"),
+ /// OsString::from_vec(vec![0xe9])
+ /// ]);
+ ///
+ /// assert!(r.is_ok());
+ /// let m = r.unwrap();
+ /// let arg: &OsString = m.get_one("arg")
+ /// .expect("required");
+ /// assert_eq!(arg.as_bytes(), &[0xe9]);
+ /// ```
+ pub const fn os_string() -> Self {
+ Self(ValueParserInner::OsString)
+ }
+
+ /// [`PathBuf`][std::path::PathBuf] parser for argument values
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// # use std::path::PathBuf;
+ /// # use std::path::Path;
+ /// let mut cmd = clap::Command::new("raw")
+ /// .arg(
+ /// clap::Arg::new("output")
+ /// .value_parser(clap::value_parser!(PathBuf))
+ /// .required(true)
+ /// );
+ ///
+ /// let m = cmd.try_get_matches_from_mut(["cmd", "hello.txt"]).unwrap();
+ /// let port: &PathBuf = m.get_one("output")
+ /// .expect("required");
+ /// assert_eq!(port, Path::new("hello.txt"));
+ ///
+ /// assert!(cmd.try_get_matches_from_mut(["cmd", ""]).is_err());
+ /// ```
+ pub const fn path_buf() -> Self {
+ Self(ValueParserInner::PathBuf)
+ }
+}
+
+impl ValueParser {
+ /// Parse into a `AnyValue`
+ ///
+ /// When `arg` is `None`, an external subcommand value is being parsed.
+ pub(crate) fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<AnyValue, crate::Error> {
+ self.any_value_parser().parse_ref(cmd, arg, value)
+ }
+
+ /// Describes the content of `AnyValue`
+ pub fn type_id(&self) -> AnyValueId {
+ self.any_value_parser().type_id()
+ }
+
+ /// Reflect on enumerated value properties
+ ///
+ /// Error checking should not be done with this; it is mostly targeted at user-facing
+ /// applications like errors and completion.
+ pub fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::PossibleValue<'static>> + '_>> {
+ self.any_value_parser().possible_values()
+ }
+
+ fn any_value_parser(&self) -> &dyn AnyValueParser {
+ match &self.0 {
+ ValueParserInner::Bool => &BoolValueParser {},
+ ValueParserInner::String => &StringValueParser {},
+ ValueParserInner::OsString => &OsStringValueParser {},
+ ValueParserInner::PathBuf => &PathBufValueParser {},
+ ValueParserInner::Other(o) => o.as_ref(),
+ }
+ }
+}
+
+/// Convert a [`TypedValueParser`] to [`ValueParser`]
+///
+/// # Example
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("hostname")
+/// .long("hostname")
+/// .value_parser(clap::builder::NonEmptyStringValueParser::new())
+/// .takes_value(true)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(
+/// ["cmd", "--hostname", "rust-lang.org"]
+/// ).unwrap();
+///
+/// let hostname: &String = m.get_one("hostname")
+/// .expect("required");
+/// assert_eq!(hostname, "rust-lang.org");
+/// ```
+impl<P> From<P> for ValueParser
+where
+ P: TypedValueParser + Send + Sync + 'static,
+ P::Value: Send + Sync + Clone,
+{
+ fn from(p: P) -> Self {
+ Self::new(p)
+ }
+}
+
+impl From<_AnonymousValueParser> for ValueParser {
+ fn from(p: _AnonymousValueParser) -> Self {
+ p.0
+ }
+}
+
+/// Create an `i64` [`ValueParser`] from a `N..M` range
+///
+/// See [`RangedI64ValueParser`] for more control over the output type.
+///
+/// See also [`RangedU64ValueParser`]
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(3000..4000)
+/// .takes_value(true)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
+/// let port: i64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+impl From<std::ops::Range<i64>> for ValueParser {
+ fn from(value: std::ops::Range<i64>) -> Self {
+ let inner = RangedI64ValueParser::<i64>::new().range(value.start..value.end);
+ Self::from(inner)
+ }
+}
+
+/// Create an `i64` [`ValueParser`] from a `N..=M` range
+///
+/// See [`RangedI64ValueParser`] for more control over the output type.
+///
+/// See also [`RangedU64ValueParser`]
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(3000..=4000)
+/// .takes_value(true)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
+/// let port: i64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+impl From<std::ops::RangeInclusive<i64>> for ValueParser {
+ fn from(value: std::ops::RangeInclusive<i64>) -> Self {
+ let inner = RangedI64ValueParser::<i64>::new().range(value.start()..=value.end());
+ Self::from(inner)
+ }
+}
+
+/// Create an `i64` [`ValueParser`] from a `N..` range
+///
+/// See [`RangedI64ValueParser`] for more control over the output type.
+///
+/// See also [`RangedU64ValueParser`]
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(3000..)
+/// .takes_value(true)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
+/// let port: i64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+impl From<std::ops::RangeFrom<i64>> for ValueParser {
+ fn from(value: std::ops::RangeFrom<i64>) -> Self {
+ let inner = RangedI64ValueParser::<i64>::new().range(value.start..);
+ Self::from(inner)
+ }
+}
+
+/// Create an `i64` [`ValueParser`] from a `..M` range
+///
+/// See [`RangedI64ValueParser`] for more control over the output type.
+///
+/// See also [`RangedU64ValueParser`]
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(..3000)
+/// .takes_value(true)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "80"]).unwrap();
+/// let port: i64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 80);
+/// ```
+impl From<std::ops::RangeTo<i64>> for ValueParser {
+ fn from(value: std::ops::RangeTo<i64>) -> Self {
+ let inner = RangedI64ValueParser::<i64>::new().range(..value.end);
+ Self::from(inner)
+ }
+}
+
+/// Create an `i64` [`ValueParser`] from a `..=M` range
+///
+/// See [`RangedI64ValueParser`] for more control over the output type.
+///
+/// See also [`RangedU64ValueParser`]
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(..=3000)
+/// .takes_value(true)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "80"]).unwrap();
+/// let port: i64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 80);
+/// ```
+impl From<std::ops::RangeToInclusive<i64>> for ValueParser {
+ fn from(value: std::ops::RangeToInclusive<i64>) -> Self {
+ let inner = RangedI64ValueParser::<i64>::new().range(..=value.end);
+ Self::from(inner)
+ }
+}
+
+/// Create an `i64` [`ValueParser`] from a `..` range
+///
+/// See [`RangedI64ValueParser`] for more control over the output type.
+///
+/// See also [`RangedU64ValueParser`]
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(..)
+/// .takes_value(true)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
+/// let port: i64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+impl From<std::ops::RangeFull> for ValueParser {
+ fn from(value: std::ops::RangeFull) -> Self {
+ let inner = RangedI64ValueParser::<i64>::new().range(value);
+ Self::from(inner)
+ }
+}
+
+/// Create a [`ValueParser`] with [`PossibleValuesParser`]
+///
+/// See [`PossibleValuesParser`] for more flexibility in creating the
+/// [`PossibleValue`][crate::PossibleValue]s.
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("color")
+/// .long("color")
+/// .value_parser(["always", "auto", "never"])
+/// .default_value("auto")
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(
+/// ["cmd", "--color", "never"]
+/// ).unwrap();
+///
+/// let color: &String = m.get_one("color")
+/// .expect("default");
+/// assert_eq!(color, "never");
+/// ```
+impl<P, const C: usize> From<[P; C]> for ValueParser
+where
+ P: Into<super::PossibleValue<'static>>,
+{
+ fn from(values: [P; C]) -> Self {
+ let inner = PossibleValuesParser::from(values);
+ Self::from(inner)
+ }
+}
+
+impl std::fmt::Debug for ValueParser {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
+ match &self.0 {
+ ValueParserInner::Bool => f.debug_struct("ValueParser::bool").finish(),
+ ValueParserInner::String => f.debug_struct("ValueParser::string").finish(),
+ ValueParserInner::OsString => f.debug_struct("ValueParser::os_string").finish(),
+ ValueParserInner::PathBuf => f.debug_struct("ValueParser::path_buf").finish(),
+ ValueParserInner::Other(o) => write!(f, "ValueParser::other({:?})", o.type_id()),
+ }
+ }
+}
+
+impl Clone for ValueParser {
+ fn clone(&self) -> Self {
+ Self(match &self.0 {
+ ValueParserInner::Bool => ValueParserInner::Bool,
+ ValueParserInner::String => ValueParserInner::String,
+ ValueParserInner::OsString => ValueParserInner::OsString,
+ ValueParserInner::PathBuf => ValueParserInner::PathBuf,
+ ValueParserInner::Other(o) => ValueParserInner::Other(o.clone_any()),
+ })
+ }
+}
+
+/// A type-erased wrapper for [`TypedValueParser`].
+trait AnyValueParser: Send + Sync + 'static {
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<AnyValue, crate::Error>;
+
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<AnyValue, crate::Error>;
+
+ /// Describes the content of `AnyValue`
+ fn type_id(&self) -> AnyValueId;
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::PossibleValue<'static>> + '_>>;
+
+ fn clone_any(&self) -> Box<dyn AnyValueParser>;
+}
+
+impl<T, P> AnyValueParser for P
+where
+ T: std::any::Any + Clone + Send + Sync + 'static,
+ P: TypedValueParser<Value = T>,
+{
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<AnyValue, crate::Error> {
+ let value = TypedValueParser::parse_ref(self, cmd, arg, value)?;
+ Ok(AnyValue::new(value))
+ }
+
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<AnyValue, crate::Error> {
+ let value = TypedValueParser::parse(self, cmd, arg, value)?;
+ Ok(AnyValue::new(value))
+ }
+
+ fn type_id(&self) -> AnyValueId {
+ AnyValueId::of::<T>()
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::PossibleValue<'static>> + '_>> {
+ P::possible_values(self)
+ }
+
+ fn clone_any(&self) -> Box<dyn AnyValueParser> {
+ Box::new(self.clone())
+ }
+}
+
+/// Parse/validate argument values
+pub trait TypedValueParser: Clone + Send + Sync + 'static {
+ /// Argument's value type
+ type Value;
+
+ /// Parse the argument value
+ ///
+ /// When `arg` is `None`, an external subcommand value is being parsed.
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error>;
+
+ /// Parse the argument value
+ ///
+ /// When `arg` is `None`, an external subcommand value is being parsed.
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<Self::Value, crate::Error> {
+ self.parse_ref(cmd, arg, &value)
+ }
+
+ /// Reflect on enumerated value properties
+ ///
+ /// Error checking should not be done with this; it is mostly targeted at user-facing
+ /// applications like errors and completion.
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::PossibleValue<'static>> + '_>> {
+ None
+ }
+
+ /// Adapt a `TypedValueParser` from one value to another
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// # use clap::builder::TypedValueParser as _;
+ /// # use clap::builder::BoolishValueParser;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("flag")
+ /// .long("flag")
+ /// .action(clap::ArgAction::Set)
+ /// .value_parser(
+ /// BoolishValueParser::new()
+ /// .map(|b| -> usize {
+ /// if b { 10 } else { 5 }
+ /// })
+ /// )
+ /// );
+ ///
+ /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag=true", "--flag=true"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_one::<usize>("flag").copied(),
+ /// Some(10)
+ /// );
+ ///
+ /// let matches = cmd.try_get_matches_from(["mycmd", "--flag=false"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_one::<usize>("flag").copied(),
+ /// Some(5)
+ /// );
+ /// ```
+ fn map<T, F>(self, func: F) -> MapValueParser<Self, F>
+ where
+ T: Send + Sync + Clone,
+ F: Fn(Self::Value) -> T + Clone,
+ {
+ MapValueParser::new(self, func)
+ }
+}
+
+impl<F, T, E> TypedValueParser for F
+where
+ F: Fn(&str) -> Result<T, E> + Clone + Send + Sync + 'static,
+ E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
+{
+ type Value = T;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = value.to_str().ok_or_else(|| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ })?;
+ let value = (self)(value).map_err(|e| {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ crate::Error::value_validation(arg, value.to_owned(), e.into()).with_cmd(cmd)
+ })?;
+ Ok(value)
+ }
+}
+
+/// Implementation for [`ValueParser::string`]
+///
+/// Useful for composing new [`TypedValueParser`]s
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct StringValueParser {}
+
+impl StringValueParser {
+ /// Implementation for [`ValueParser::string`]
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl TypedValueParser for StringValueParser {
+ type Value = String;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ TypedValueParser::parse(self, cmd, arg, value.to_owned())
+ }
+
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ _arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = value.into_string().map_err(|_| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ })?;
+ Ok(value)
+ }
+}
+
+impl Default for StringValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Implementation for [`ValueParser::os_string`]
+///
+/// Useful for composing new [`TypedValueParser`]s
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct OsStringValueParser {}
+
+impl OsStringValueParser {
+ /// Implementation for [`ValueParser::os_string`]
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl TypedValueParser for OsStringValueParser {
+ type Value = std::ffi::OsString;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ TypedValueParser::parse(self, cmd, arg, value.to_owned())
+ }
+
+ fn parse(
+ &self,
+ _cmd: &crate::Command,
+ _arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<Self::Value, crate::Error> {
+ Ok(value)
+ }
+}
+
+impl Default for OsStringValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Implementation for [`ValueParser::path_buf`]
+///
+/// Useful for composing new [`TypedValueParser`]s
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct PathBufValueParser {}
+
+impl PathBufValueParser {
+ /// Implementation for [`ValueParser::path_buf`]
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl TypedValueParser for PathBufValueParser {
+ type Value = std::path::PathBuf;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ TypedValueParser::parse(self, cmd, arg, value.to_owned())
+ }
+
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<Self::Value, crate::Error> {
+ if value.is_empty() {
+ return Err(crate::Error::empty_value(
+ cmd,
+ &[],
+ arg.map(ToString::to_string)
+ .unwrap_or_else(|| "...".to_owned()),
+ ));
+ }
+ Ok(Self::Value::from(value))
+ }
+}
+
+impl Default for PathBufValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Parse an [`ValueEnum`][crate::ValueEnum] value.
+///
+/// See also:
+/// - [`PossibleValuesParser`]
+///
+/// # Example
+///
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+///
+/// #[derive(Copy, Clone, Debug, PartialEq, Eq)]
+/// enum ColorChoice {
+/// Always,
+/// Auto,
+/// Never,
+/// }
+///
+/// impl clap::ValueEnum for ColorChoice {
+/// fn value_variants<'a>() -> &'a [Self] {
+/// &[Self::Always, Self::Auto, Self::Never]
+/// }
+///
+/// fn to_possible_value<'a>(&self) -> Option<clap::PossibleValue<'a>> {
+/// match self {
+/// Self::Always => Some(clap::PossibleValue::new("always")),
+/// Self::Auto => Some(clap::PossibleValue::new("auto")),
+/// Self::Never => Some(clap::PossibleValue::new("never")),
+/// }
+/// }
+/// }
+///
+/// // Usage
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("color")
+/// .value_parser(clap::builder::EnumValueParser::<ColorChoice>::new())
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "always"]).unwrap();
+/// let port: ColorChoice = *m.get_one("color")
+/// .expect("required");
+/// assert_eq!(port, ColorChoice::Always);
+///
+/// // Semantics
+/// let value_parser = clap::builder::EnumValueParser::<ColorChoice>::new();
+/// // or
+/// let value_parser = clap::value_parser!(ColorChoice);
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("always")).unwrap(), ColorChoice::Always);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("auto")).unwrap(), ColorChoice::Auto);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("never")).unwrap(), ColorChoice::Never);
+/// ```
+#[derive(Clone, Debug)]
+pub struct EnumValueParser<E: crate::ValueEnum + Clone + Send + Sync + 'static>(
+ std::marker::PhantomData<E>,
+);
+
+impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> EnumValueParser<E> {
+ /// Parse an [`ValueEnum`][crate::ValueEnum]
+ pub fn new() -> Self {
+ let phantom: std::marker::PhantomData<E> = Default::default();
+ Self(phantom)
+ }
+}
+
+impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> TypedValueParser for EnumValueParser<E> {
+ type Value = E;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false);
+ let possible_vals = || {
+ E::value_variants()
+ .iter()
+ .filter_map(|v| v.to_possible_value())
+ .filter(|v| !v.is_hide_set())
+ .map(|v| v.get_name())
+ .collect::<Vec<_>>()
+ };
+
+ let value = value.to_str().ok_or_else(|| {
+ crate::Error::invalid_value(
+ cmd,
+ value.to_string_lossy().into_owned(),
+ &possible_vals(),
+ arg.map(ToString::to_string)
+ .unwrap_or_else(|| "...".to_owned()),
+ )
+ })?;
+ let value = E::value_variants()
+ .iter()
+ .find(|v| {
+ v.to_possible_value()
+ .expect("ValueEnum::value_variants contains only values with a corresponding ValueEnum::to_possible_value")
+ .matches(value, ignore_case)
+ })
+ .ok_or_else(|| {
+ crate::Error::invalid_value(
+ cmd,
+ value.to_owned(),
+ &possible_vals(),
+ arg.map(ToString::to_string)
+ .unwrap_or_else(|| "...".to_owned()),
+ )
+ })?
+ .clone();
+ Ok(value)
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::PossibleValue<'static>> + '_>> {
+ Some(Box::new(
+ E::value_variants()
+ .iter()
+ .filter_map(|v| v.to_possible_value()),
+ ))
+ }
+}
+
+impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> Default for EnumValueParser<E> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Verify the value is from an enumerated set of [`PossibleValue`][crate::PossibleValue].
+///
+/// See also:
+/// - [`EnumValueParser`]
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("color")
+/// .value_parser(clap::builder::PossibleValuesParser::new(["always", "auto", "never"]))
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "always"]).unwrap();
+/// let port: &String = m.get_one("color")
+/// .expect("required");
+/// assert_eq!(port, "always");
+/// ```
+///
+/// Semantics:
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+/// let value_parser = clap::builder::PossibleValuesParser::new(["always", "auto", "never"]);
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("always")).unwrap(), "always");
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("auto")).unwrap(), "auto");
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("never")).unwrap(), "never");
+/// ```
+#[derive(Clone, Debug)]
+pub struct PossibleValuesParser(Vec<super::PossibleValue<'static>>);
+
+impl PossibleValuesParser {
+ /// Verify the value is from an enumerated set pf [`PossibleValue`][crate::PossibleValue].
+ pub fn new(values: impl Into<PossibleValuesParser>) -> Self {
+ values.into()
+ }
+}
+
+impl TypedValueParser for PossibleValuesParser {
+ type Value = String;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ TypedValueParser::parse(self, cmd, arg, value.to_owned())
+ }
+
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<String, crate::Error> {
+ let value = value.into_string().map_err(|_| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ })?;
+
+ let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false);
+ if self.0.iter().any(|v| v.matches(&value, ignore_case)) {
+ Ok(value)
+ } else {
+ let possible_vals = self
+ .0
+ .iter()
+ .filter(|v| !v.is_hide_set())
+ .map(crate::builder::PossibleValue::get_name)
+ .collect::<Vec<_>>();
+
+ Err(crate::Error::invalid_value(
+ cmd,
+ value,
+ &possible_vals,
+ arg.map(ToString::to_string)
+ .unwrap_or_else(|| "...".to_owned()),
+ ))
+ }
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::PossibleValue<'static>> + '_>> {
+ Some(Box::new(self.0.iter().cloned()))
+ }
+}
+
+impl<I, T> From<I> for PossibleValuesParser
+where
+ I: IntoIterator<Item = T>,
+ T: Into<super::PossibleValue<'static>>,
+{
+ fn from(values: I) -> Self {
+ Self(values.into_iter().map(|t| t.into()).collect())
+ }
+}
+
+/// Parse number that fall within a range of values
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(clap::value_parser!(u16).range(3000..))
+/// .takes_value(true)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
+/// let port: u16 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+///
+/// Semantics:
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+/// let value_parser = clap::builder::RangedI64ValueParser::<i32>::new().range(-1..200);
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-200")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("300")).is_err());
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("-1")).unwrap(), -1);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), 0);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("50")).unwrap(), 50);
+/// ```
+#[derive(Copy, Clone, Debug)]
+pub struct RangedI64ValueParser<T: std::convert::TryFrom<i64> + Clone + Send + Sync = i64> {
+ bounds: (std::ops::Bound<i64>, std::ops::Bound<i64>),
+ target: std::marker::PhantomData<T>,
+}
+
+impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync> RangedI64ValueParser<T> {
+ /// Select full range of `i64`
+ pub fn new() -> Self {
+ Self::from(..)
+ }
+
+ /// Narrow the supported range
+ pub fn range<B: RangeBounds<i64>>(mut self, range: B) -> Self {
+ // Consideration: when the user does `value_parser!(u8).range()`
+ // - Avoid programming mistakes by accidentally expanding the range
+ // - Make it convenient to limit the range like with `..10`
+ let start = match range.start_bound() {
+ l @ std::ops::Bound::Included(i) => {
+ debug_assert!(
+ self.bounds.contains(i),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ l @ std::ops::Bound::Excluded(i) => {
+ debug_assert!(
+ self.bounds.contains(&i.saturating_add(1)),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ std::ops::Bound::Unbounded => self.bounds.start_bound().cloned(),
+ };
+ let end = match range.end_bound() {
+ l @ std::ops::Bound::Included(i) => {
+ debug_assert!(
+ self.bounds.contains(i),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ l @ std::ops::Bound::Excluded(i) => {
+ debug_assert!(
+ self.bounds.contains(&i.saturating_sub(1)),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ std::ops::Bound::Unbounded => self.bounds.end_bound().cloned(),
+ };
+ self.bounds = (start, end);
+ self
+ }
+
+ fn format_bounds(&self) -> String {
+ let mut result = match self.bounds.0 {
+ std::ops::Bound::Included(i) => i.to_string(),
+ std::ops::Bound::Excluded(i) => i.saturating_add(1).to_string(),
+ std::ops::Bound::Unbounded => i64::MIN.to_string(),
+ };
+ result.push_str("..");
+ match self.bounds.1 {
+ std::ops::Bound::Included(i) => {
+ result.push('=');
+ result.push_str(&i.to_string());
+ }
+ std::ops::Bound::Excluded(i) => {
+ result.push_str(&i.to_string());
+ }
+ std::ops::Bound::Unbounded => {
+ result.push_str(&i64::MAX.to_string());
+ }
+ }
+ result
+ }
+}
+
+impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync + 'static> TypedValueParser
+ for RangedI64ValueParser<T>
+where
+ <T as std::convert::TryFrom<i64>>::Error: Send + Sync + 'static + std::error::Error + ToString,
+{
+ type Value = T;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ raw_value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = raw_value.to_str().ok_or_else(|| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ })?;
+ let value = value.parse::<i64>().map_err(|err| {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ crate::Error::value_validation(
+ arg,
+ raw_value.to_string_lossy().into_owned(),
+ err.into(),
+ )
+ .with_cmd(cmd)
+ })?;
+ if !self.bounds.contains(&value) {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ return Err(crate::Error::value_validation(
+ arg,
+ raw_value.to_string_lossy().into_owned(),
+ format!("{} is not in {}", value, self.format_bounds()).into(),
+ )
+ .with_cmd(cmd));
+ }
+
+ let value: Result<Self::Value, _> = value.try_into();
+ let value = value.map_err(|err| {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ crate::Error::value_validation(
+ arg,
+ raw_value.to_string_lossy().into_owned(),
+ err.into(),
+ )
+ .with_cmd(cmd)
+ })?;
+
+ Ok(value)
+ }
+}
+
+impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync, B: RangeBounds<i64>> From<B>
+ for RangedI64ValueParser<T>
+{
+ fn from(range: B) -> Self {
+ Self {
+ bounds: (range.start_bound().cloned(), range.end_bound().cloned()),
+ target: Default::default(),
+ }
+ }
+}
+
+impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync> Default for RangedI64ValueParser<T> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Parse number that fall within a range of values
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(clap::value_parser!(u64).range(3000..))
+/// .takes_value(true)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
+/// let port: u64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+///
+/// Semantics:
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+/// let value_parser = clap::builder::RangedU64ValueParser::<u32>::new().range(0..200);
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-200")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("300")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-1")).is_err());
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), 0);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("50")).unwrap(), 50);
+/// ```
+#[derive(Copy, Clone, Debug)]
+pub struct RangedU64ValueParser<T: std::convert::TryFrom<u64> = u64> {
+ bounds: (std::ops::Bound<u64>, std::ops::Bound<u64>),
+ target: std::marker::PhantomData<T>,
+}
+
+impl<T: std::convert::TryFrom<u64>> RangedU64ValueParser<T> {
+ /// Select full range of `u64`
+ pub fn new() -> Self {
+ Self::from(..)
+ }
+
+ /// Narrow the supported range
+ pub fn range<B: RangeBounds<u64>>(mut self, range: B) -> Self {
+ // Consideration: when the user does `value_parser!(u8).range()`
+ // - Avoid programming mistakes by accidentally expanding the range
+ // - Make it convenient to limit the range like with `..10`
+ let start = match range.start_bound() {
+ l @ std::ops::Bound::Included(i) => {
+ debug_assert!(
+ self.bounds.contains(i),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ l @ std::ops::Bound::Excluded(i) => {
+ debug_assert!(
+ self.bounds.contains(&i.saturating_add(1)),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ std::ops::Bound::Unbounded => self.bounds.start_bound().cloned(),
+ };
+ let end = match range.end_bound() {
+ l @ std::ops::Bound::Included(i) => {
+ debug_assert!(
+ self.bounds.contains(i),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ l @ std::ops::Bound::Excluded(i) => {
+ debug_assert!(
+ self.bounds.contains(&i.saturating_sub(1)),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ std::ops::Bound::Unbounded => self.bounds.end_bound().cloned(),
+ };
+ self.bounds = (start, end);
+ self
+ }
+
+ fn format_bounds(&self) -> String {
+ let mut result = match self.bounds.0 {
+ std::ops::Bound::Included(i) => i.to_string(),
+ std::ops::Bound::Excluded(i) => i.saturating_add(1).to_string(),
+ std::ops::Bound::Unbounded => u64::MIN.to_string(),
+ };
+ result.push_str("..");
+ match self.bounds.1 {
+ std::ops::Bound::Included(i) => {
+ result.push('=');
+ result.push_str(&i.to_string());
+ }
+ std::ops::Bound::Excluded(i) => {
+ result.push_str(&i.to_string());
+ }
+ std::ops::Bound::Unbounded => {
+ result.push_str(&u64::MAX.to_string());
+ }
+ }
+ result
+ }
+}
+
+impl<T: std::convert::TryFrom<u64> + Clone + Send + Sync + 'static> TypedValueParser
+ for RangedU64ValueParser<T>
+where
+ <T as std::convert::TryFrom<u64>>::Error: Send + Sync + 'static + std::error::Error + ToString,
+{
+ type Value = T;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ raw_value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = raw_value.to_str().ok_or_else(|| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ })?;
+ let value = value.parse::<u64>().map_err(|err| {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ crate::Error::value_validation(
+ arg,
+ raw_value.to_string_lossy().into_owned(),
+ err.into(),
+ )
+ .with_cmd(cmd)
+ })?;
+ if !self.bounds.contains(&value) {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ return Err(crate::Error::value_validation(
+ arg,
+ raw_value.to_string_lossy().into_owned(),
+ format!("{} is not in {}", value, self.format_bounds()).into(),
+ )
+ .with_cmd(cmd));
+ }
+
+ let value: Result<Self::Value, _> = value.try_into();
+ let value = value.map_err(|err| {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ crate::Error::value_validation(
+ arg,
+ raw_value.to_string_lossy().into_owned(),
+ err.into(),
+ )
+ .with_cmd(cmd)
+ })?;
+
+ Ok(value)
+ }
+}
+
+impl<T: std::convert::TryFrom<u64>, B: RangeBounds<u64>> From<B> for RangedU64ValueParser<T> {
+ fn from(range: B) -> Self {
+ Self {
+ bounds: (range.start_bound().cloned(), range.end_bound().cloned()),
+ target: Default::default(),
+ }
+ }
+}
+
+impl<T: std::convert::TryFrom<u64>> Default for RangedU64ValueParser<T> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Implementation for [`ValueParser::bool`]
+///
+/// Useful for composing new [`TypedValueParser`]s
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct BoolValueParser {}
+
+impl BoolValueParser {
+ /// Implementation for [`ValueParser::bool`]
+ pub fn new() -> Self {
+ Self {}
+ }
+
+ fn possible_values() -> impl Iterator<Item = crate::PossibleValue<'static>> {
+ ["true", "false"]
+ .iter()
+ .copied()
+ .map(crate::PossibleValue::new)
+ }
+}
+
+impl TypedValueParser for BoolValueParser {
+ type Value = bool;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = if value == std::ffi::OsStr::new("true") {
+ true
+ } else if value == std::ffi::OsStr::new("false") {
+ false
+ } else {
+ // Intentionally showing hidden as we hide all of them
+ let possible_vals = Self::possible_values()
+ .map(|v| v.get_name())
+ .collect::<Vec<_>>();
+
+ return Err(crate::Error::invalid_value(
+ cmd,
+ value.to_string_lossy().into_owned(),
+ &possible_vals,
+ arg.map(ToString::to_string)
+ .unwrap_or_else(|| "...".to_owned()),
+ ));
+ };
+ Ok(value)
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::PossibleValue<'static>> + '_>> {
+ Some(Box::new(Self::possible_values()))
+ }
+}
+
+impl Default for BoolValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Parse false-like string values, everything else is `true`
+///
+/// See also:
+/// - [`ValueParser::bool`] for assuming non-false is true
+/// - [`BoolishValueParser`] for different human readable bool representations
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("append")
+/// .value_parser(clap::builder::FalseyValueParser::new())
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap();
+/// let port: bool = *m.get_one("append")
+/// .expect("required");
+/// assert_eq!(port, true);
+/// ```
+///
+/// Semantics:
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+/// let value_parser = clap::builder::FalseyValueParser::new();
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).unwrap(), true);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("100")).unwrap(), true);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("false")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("No")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oFF")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), false);
+/// ```
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct FalseyValueParser {}
+
+impl FalseyValueParser {
+ /// Parse false-like string values, everything else is `true`
+ pub fn new() -> Self {
+ Self {}
+ }
+
+ fn possible_values() -> impl Iterator<Item = crate::PossibleValue<'static>> {
+ crate::util::TRUE_LITERALS
+ .iter()
+ .chain(crate::util::FALSE_LITERALS.iter())
+ .copied()
+ .map(|l| crate::PossibleValue::new(l).hide(l != "true" && l != "false"))
+ }
+}
+
+impl TypedValueParser for FalseyValueParser {
+ type Value = bool;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ _arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = value.to_str().ok_or_else(|| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ })?;
+ let value = if value.is_empty() {
+ false
+ } else {
+ crate::util::str_to_bool(value).unwrap_or(true)
+ };
+ Ok(value)
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::PossibleValue<'static>> + '_>> {
+ Some(Box::new(Self::possible_values()))
+ }
+}
+
+impl Default for FalseyValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Parse bool-like string values, everything else is `true`
+///
+/// See also:
+/// - [`ValueParser::bool`] for different human readable bool representations
+/// - [`FalseyValueParser`] for assuming non-false is true
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("append")
+/// .value_parser(clap::builder::BoolishValueParser::new())
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap();
+/// let port: bool = *m.get_one("append")
+/// .expect("required");
+/// assert_eq!(port, true);
+/// ```
+///
+/// Semantics:
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+/// let value_parser = clap::builder::BoolishValueParser::new();
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("100")).is_err());
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("true")).unwrap(), true);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("Yes")).unwrap(), true);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oN")).unwrap(), true);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("1")).unwrap(), true);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("false")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("No")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oFF")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), false);
+/// ```
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct BoolishValueParser {}
+
+impl BoolishValueParser {
+ /// Parse bool-like string values, everything else is `true`
+ pub fn new() -> Self {
+ Self {}
+ }
+
+ fn possible_values() -> impl Iterator<Item = crate::PossibleValue<'static>> {
+ crate::util::TRUE_LITERALS
+ .iter()
+ .chain(crate::util::FALSE_LITERALS.iter())
+ .copied()
+ .map(|l| crate::PossibleValue::new(l).hide(l != "true" && l != "false"))
+ }
+}
+
+impl TypedValueParser for BoolishValueParser {
+ type Value = bool;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = value.to_str().ok_or_else(|| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ })?;
+ let value = crate::util::str_to_bool(value).ok_or_else(|| {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ crate::Error::value_validation(arg, value.to_owned(), "value was not a boolean".into())
+ .with_cmd(cmd)
+ })?;
+ Ok(value)
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::PossibleValue<'static>> + '_>> {
+ Some(Box::new(Self::possible_values()))
+ }
+}
+
+impl Default for BoolishValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Parse non-empty string values
+///
+/// See also:
+/// - [`ValueParser::string`]
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("append")
+/// .value_parser(clap::builder::NonEmptyStringValueParser::new())
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap();
+/// let port: &String = m.get_one("append")
+/// .expect("required");
+/// assert_eq!(port, "true");
+/// ```
+///
+/// Semantics:
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+/// let value_parser = clap::builder::NonEmptyStringValueParser::new();
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).unwrap(), "random");
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
+/// ```
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct NonEmptyStringValueParser {}
+
+impl NonEmptyStringValueParser {
+ /// Parse non-empty string values
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl TypedValueParser for NonEmptyStringValueParser {
+ type Value = String;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ if value.is_empty() {
+ return Err(crate::Error::empty_value(
+ cmd,
+ &[],
+ arg.map(ToString::to_string)
+ .unwrap_or_else(|| "...".to_owned()),
+ ));
+ }
+ let value = value.to_str().ok_or_else(|| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ })?;
+ Ok(value.to_owned())
+ }
+}
+
+impl Default for NonEmptyStringValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Adapt a `TypedValueParser` from one value to another
+///
+/// See [`TypedValueParser::map`]
+#[derive(Clone, Debug)]
+pub struct MapValueParser<P, F> {
+ parser: P,
+ func: F,
+}
+
+impl<P, F> MapValueParser<P, F> {
+ fn new(parser: P, func: F) -> Self {
+ Self { parser, func }
+ }
+}
+
+impl<P, F, T> TypedValueParser for MapValueParser<P, F>
+where
+ P: TypedValueParser,
+ P::Value: Send + Sync + Clone,
+ F: Fn(P::Value) -> T + Clone + Send + Sync + 'static,
+ T: Send + Sync + Clone,
+{
+ type Value = T;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = self.parser.parse_ref(cmd, arg, value)?;
+ let value = (self.func)(value);
+ Ok(value)
+ }
+
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = self.parser.parse(cmd, arg, value)?;
+ let value = (self.func)(value);
+ Ok(value)
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue<'static>> + '_>> {
+ self.parser.possible_values()
+ }
+}
+
+/// Register a type with [value_parser!][crate::value_parser!]
+///
+/// # Example
+///
+/// ```rust
+/// #[derive(Copy, Clone, Debug)]
+/// pub struct Custom(u32);
+///
+/// impl clap::builder::ValueParserFactory for Custom {
+/// type Parser = CustomValueParser;
+/// fn value_parser() -> Self::Parser {
+/// CustomValueParser
+/// }
+/// }
+///
+/// #[derive(Clone, Debug)]
+/// pub struct CustomValueParser;
+/// impl clap::builder::TypedValueParser for CustomValueParser {
+/// type Value = Custom;
+///
+/// fn parse_ref(
+/// &self,
+/// cmd: &clap::Command,
+/// arg: Option<&clap::Arg>,
+/// value: &std::ffi::OsStr,
+/// ) -> Result<Self::Value, clap::Error> {
+/// let inner = clap::value_parser!(u32);
+/// let val = inner.parse_ref(cmd, arg, value)?;
+/// Ok(Custom(val))
+/// }
+/// }
+///
+/// let parser: CustomValueParser = clap::value_parser!(Custom);
+/// ```
+pub trait ValueParserFactory {
+ /// Generated parser, usually [`ValueParser`].
+ ///
+ /// It should at least be a type that supports `Into<ValueParser>`. A non-`ValueParser` type
+ /// allows the caller to do further initialization on the parser.
+ type Parser;
+
+ /// Create the specified [`Self::Parser`]
+ fn value_parser() -> Self::Parser;
+}
+impl ValueParserFactory for String {
+ type Parser = ValueParser;
+ fn value_parser() -> Self::Parser {
+ ValueParser::string()
+ }
+}
+impl ValueParserFactory for std::ffi::OsString {
+ type Parser = ValueParser;
+ fn value_parser() -> Self::Parser {
+ ValueParser::os_string()
+ }
+}
+impl ValueParserFactory for std::path::PathBuf {
+ type Parser = ValueParser;
+ fn value_parser() -> Self::Parser {
+ ValueParser::path_buf()
+ }
+}
+impl ValueParserFactory for bool {
+ type Parser = ValueParser;
+ fn value_parser() -> Self::Parser {
+ ValueParser::bool()
+ }
+}
+impl ValueParserFactory for u8 {
+ type Parser = RangedI64ValueParser<u8>;
+ fn value_parser() -> Self::Parser {
+ let start: i64 = u8::MIN.into();
+ let end: i64 = u8::MAX.into();
+ RangedI64ValueParser::new().range(start..=end)
+ }
+}
+impl ValueParserFactory for i8 {
+ type Parser = RangedI64ValueParser<i8>;
+ fn value_parser() -> Self::Parser {
+ let start: i64 = i8::MIN.into();
+ let end: i64 = i8::MAX.into();
+ RangedI64ValueParser::new().range(start..=end)
+ }
+}
+impl ValueParserFactory for u16 {
+ type Parser = RangedI64ValueParser<u16>;
+ fn value_parser() -> Self::Parser {
+ let start: i64 = u16::MIN.into();
+ let end: i64 = u16::MAX.into();
+ RangedI64ValueParser::new().range(start..=end)
+ }
+}
+impl ValueParserFactory for i16 {
+ type Parser = RangedI64ValueParser<i16>;
+ fn value_parser() -> Self::Parser {
+ let start: i64 = i16::MIN.into();
+ let end: i64 = i16::MAX.into();
+ RangedI64ValueParser::new().range(start..=end)
+ }
+}
+impl ValueParserFactory for u32 {
+ type Parser = RangedI64ValueParser<u32>;
+ fn value_parser() -> Self::Parser {
+ let start: i64 = u32::MIN.into();
+ let end: i64 = u32::MAX.into();
+ RangedI64ValueParser::new().range(start..=end)
+ }
+}
+impl ValueParserFactory for i32 {
+ type Parser = RangedI64ValueParser<i32>;
+ fn value_parser() -> Self::Parser {
+ let start: i64 = i32::MIN.into();
+ let end: i64 = i32::MAX.into();
+ RangedI64ValueParser::new().range(start..=end)
+ }
+}
+impl ValueParserFactory for i64 {
+ type Parser = RangedI64ValueParser<i64>;
+ fn value_parser() -> Self::Parser {
+ RangedI64ValueParser::new()
+ }
+}
+impl ValueParserFactory for u64 {
+ type Parser = RangedU64ValueParser<u64>;
+ fn value_parser() -> Self::Parser {
+ RangedU64ValueParser::new()
+ }
+}
+
+#[doc(hidden)]
+#[derive(Debug)]
+pub struct _AutoValueParser<T>(std::marker::PhantomData<T>);
+
+impl<T> _AutoValueParser<T> {
+ #[doc(hidden)]
+ #[allow(clippy::new_without_default)]
+ pub fn new() -> Self {
+ Self(Default::default())
+ }
+}
+
+/// Unstable [`ValueParser`]
+///
+/// Implementation may change to more specific instance in the future
+#[doc(hidden)]
+#[derive(Debug)]
+pub struct _AnonymousValueParser(ValueParser);
+
+#[doc(hidden)]
+pub mod via_prelude {
+ use super::*;
+
+ #[doc(hidden)]
+ pub trait _ValueParserViaFactory: private::_ValueParserViaFactorySealed {
+ type Parser;
+ fn value_parser(&self) -> Self::Parser;
+ }
+ impl<P: ValueParserFactory> _ValueParserViaFactory for &&_AutoValueParser<P> {
+ type Parser = P::Parser;
+ fn value_parser(&self) -> Self::Parser {
+ P::value_parser()
+ }
+ }
+
+ #[doc(hidden)]
+ pub trait _ValueParserViaValueEnum: private::_ValueParserViaValueEnumSealed {
+ type Output;
+
+ fn value_parser(&self) -> Self::Output;
+ }
+ impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> _ValueParserViaValueEnum
+ for &_AutoValueParser<E>
+ {
+ type Output = EnumValueParser<E>;
+
+ fn value_parser(&self) -> Self::Output {
+ EnumValueParser::<E>::new()
+ }
+ }
+
+ #[doc(hidden)]
+ pub trait _ValueParserViaFromStr: private::_ValueParserViaFromStrSealed {
+ fn value_parser(&self) -> _AnonymousValueParser;
+ }
+ impl<FromStr> _ValueParserViaFromStr for _AutoValueParser<FromStr>
+ where
+ FromStr: std::str::FromStr + std::any::Any + Clone + Send + Sync + 'static,
+ <FromStr as std::str::FromStr>::Err:
+ Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
+ {
+ fn value_parser(&self) -> _AnonymousValueParser {
+ let func: fn(&str) -> Result<FromStr, <FromStr as std::str::FromStr>::Err> =
+ FromStr::from_str;
+ _AnonymousValueParser(ValueParser::new(func))
+ }
+ }
+}
+
+/// Select a [`ValueParser`] implementation from the intended type
+///
+/// To register a custom type with this macro, implement [`ValueParserFactory`].
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// # use std::path::PathBuf;
+/// # use std::path::Path;
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("output")
+/// .value_parser(clap::value_parser!(PathBuf))
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "file.txt"]).unwrap();
+/// let port: &PathBuf = m.get_one("output")
+/// .expect("required");
+/// assert_eq!(port, Path::new("file.txt"));
+/// ```
+///
+/// Supported types:
+/// ```rust
+/// // Built-in types
+/// let parser = clap::value_parser!(String);
+/// assert_eq!(format!("{:?}", parser), "ValueParser::string");
+/// let parser = clap::value_parser!(std::ffi::OsString);
+/// assert_eq!(format!("{:?}", parser), "ValueParser::os_string");
+/// let parser = clap::value_parser!(std::path::PathBuf);
+/// assert_eq!(format!("{:?}", parser), "ValueParser::path_buf");
+/// let parser = clap::value_parser!(u16).range(3000..);
+/// assert_eq!(format!("{:?}", parser), "RangedI64ValueParser { bounds: (Included(3000), Included(65535)), target: PhantomData }");
+/// let parser = clap::value_parser!(u64).range(3000..);
+/// assert_eq!(format!("{:?}", parser), "RangedU64ValueParser { bounds: (Included(3000), Unbounded), target: PhantomData }");
+///
+/// // FromStr types
+/// let parser = clap::value_parser!(usize);
+/// assert_eq!(format!("{:?}", parser), "_AnonymousValueParser(ValueParser::other(usize))");
+///
+/// // ValueEnum types
+/// #[derive(Copy, Clone, Debug, PartialEq, Eq)]
+/// enum ColorChoice {
+/// Always,
+/// Auto,
+/// Never,
+/// }
+/// impl clap::ValueEnum for ColorChoice {
+/// // ...
+/// # fn value_variants<'a>() -> &'a [Self] {
+/// # &[Self::Always, Self::Auto, Self::Never]
+/// # }
+/// # fn to_possible_value<'a>(&self) -> Option<clap::PossibleValue<'a>> {
+/// # match self {
+/// # Self::Always => Some(clap::PossibleValue::new("always")),
+/// # Self::Auto => Some(clap::PossibleValue::new("auto")),
+/// # Self::Never => Some(clap::PossibleValue::new("never")),
+/// # }
+/// # }
+/// }
+/// let parser = clap::value_parser!(ColorChoice);
+/// assert_eq!(format!("{:?}", parser), "EnumValueParser(PhantomData)");
+/// ```
+#[macro_export]
+macro_rules! value_parser {
+ ($name:ty) => {{
+ use $crate::builder::via_prelude::*;
+ let auto = $crate::builder::_AutoValueParser::<$name>::new();
+ (&&&auto).value_parser()
+ }};
+}
+
+mod private {
+ use super::*;
+
+ pub trait _ValueParserViaSelfSealed {}
+ impl<P: Into<ValueParser>> _ValueParserViaSelfSealed for &&&_AutoValueParser<P> {}
+
+ pub trait _ValueParserViaFactorySealed {}
+ impl<P: ValueParserFactory> _ValueParserViaFactorySealed for &&_AutoValueParser<P> {}
+
+ pub trait _ValueParserViaValueEnumSealed {}
+ impl<E: crate::ValueEnum> _ValueParserViaValueEnumSealed for &_AutoValueParser<E> {}
+
+ pub trait _ValueParserViaFromStrSealed {}
+ impl<FromStr> _ValueParserViaFromStrSealed for _AutoValueParser<FromStr>
+ where
+ FromStr: std::str::FromStr + std::any::Any + Send + Sync + 'static,
+ <FromStr as std::str::FromStr>::Err:
+ Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
+ {
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn ensure_typed_applies_to_parse() {
+ fn parse(_: &str) -> Result<usize, std::io::Error> {
+ Ok(10)
+ }
+ let cmd = crate::Command::new("cmd");
+ let arg = None;
+ assert_eq!(
+ TypedValueParser::parse_ref(&parse, &cmd, arg, std::ffi::OsStr::new("foo")).unwrap(),
+ 10
+ );
+ }
+}
diff --git a/3.2.23/src/derive.rs b/3.2.23/src/derive.rs
new file mode 100644
index 0000000..b6ac04d
--- /dev/null
+++ b/3.2.23/src/derive.rs
@@ -0,0 +1,577 @@
+//! This module contains traits that are usable with the `#[derive(...)].`
+//! macros in [`clap_derive`].
+
+use crate::{ArgMatches, Command, Error, PossibleValue};
+
+use std::ffi::OsString;
+
+/// Parse command-line arguments into `Self`.
+///
+/// The primary one-stop-shop trait used to create an instance of a `clap`
+/// [`Command`], conduct the parsing, and turn the resulting [`ArgMatches`] back
+/// into concrete instance of the user struct.
+///
+/// This trait is primarily a convenience on top of [`FromArgMatches`] +
+/// [`CommandFactory`] which uses those two underlying traits to build the two
+/// fundamental functions `parse` which uses the `std::env::args_os` iterator,
+/// and `parse_from` which allows the consumer to supply the iterator (along
+/// with fallible options for each).
+///
+/// See also [`Subcommand`] and [`Args`].
+///
+/// See the [derive reference](crate::_derive) for attributes and best practices.
+///
+/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features]
+///
+/// # Examples
+///
+/// The following example creates a `Context` struct that would be used
+/// throughout the application representing the normalized values coming from
+/// the CLI.
+///
+#[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+#[cfg_attr(feature = "derive", doc = " ```")]
+/// /// My super CLI
+/// #[derive(clap::Parser)]
+/// #[clap(name = "demo")]
+/// struct Context {
+/// /// More verbose output
+/// #[clap(long)]
+/// verbose: bool,
+/// /// An optional name
+/// #[clap(short, long)]
+/// name: Option<String>,
+/// }
+/// ```
+///
+/// The equivalent [`Command`] struct + `From` implementation:
+///
+/// ```rust
+/// # use clap::{Command, Arg, ArgMatches, ArgAction};
+/// Command::new("demo")
+/// .about("My super CLI")
+/// .arg(Arg::new("verbose")
+/// .long("verbose")
+/// .action(ArgAction::SetTrue)
+/// .help("More verbose output"))
+/// .arg(Arg::new("name")
+/// .long("name")
+/// .short('n')
+/// .help("An optional name")
+/// .takes_value(true));
+///
+/// struct Context {
+/// verbose: bool,
+/// name: Option<String>,
+/// }
+///
+/// impl From<ArgMatches> for Context {
+/// fn from(m: ArgMatches) -> Self {
+/// Context {
+/// verbose: *m.get_one::<bool>("verbose").expect("defaulted_by_clap"),
+/// name: m.get_one::<String>("name").cloned(),
+/// }
+/// }
+/// }
+/// ```
+///
+pub trait Parser: FromArgMatches + CommandFactory + Sized {
+ /// Parse from `std::env::args_os()`, exit on error
+ fn parse() -> Self {
+ let mut matches = <Self as CommandFactory>::command().get_matches();
+ let res = <Self as FromArgMatches>::from_arg_matches_mut(&mut matches)
+ .map_err(format_error::<Self>);
+ match res {
+ Ok(s) => s,
+ Err(e) => {
+ // Since this is more of a development-time error, we aren't doing as fancy of a quit
+ // as `get_matches`
+ e.exit()
+ }
+ }
+ }
+
+ /// Parse from `std::env::args_os()`, return Err on error.
+ fn try_parse() -> Result<Self, Error> {
+ let mut matches = <Self as CommandFactory>::command().try_get_matches()?;
+ <Self as FromArgMatches>::from_arg_matches_mut(&mut matches).map_err(format_error::<Self>)
+ }
+
+ /// Parse from iterator, exit on error
+ fn parse_from<I, T>(itr: I) -> Self
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ let mut matches = <Self as CommandFactory>::command().get_matches_from(itr);
+ let res = <Self as FromArgMatches>::from_arg_matches_mut(&mut matches)
+ .map_err(format_error::<Self>);
+ match res {
+ Ok(s) => s,
+ Err(e) => {
+ // Since this is more of a development-time error, we aren't doing as fancy of a quit
+ // as `get_matches_from`
+ e.exit()
+ }
+ }
+ }
+
+ /// Parse from iterator, return Err on error.
+ fn try_parse_from<I, T>(itr: I) -> Result<Self, Error>
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ let mut matches = <Self as CommandFactory>::command().try_get_matches_from(itr)?;
+ <Self as FromArgMatches>::from_arg_matches_mut(&mut matches).map_err(format_error::<Self>)
+ }
+
+ /// Update from iterator, exit on error
+ fn update_from<I, T>(&mut self, itr: I)
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ let mut matches = <Self as CommandFactory>::command_for_update().get_matches_from(itr);
+ let res = <Self as FromArgMatches>::update_from_arg_matches_mut(self, &mut matches)
+ .map_err(format_error::<Self>);
+ if let Err(e) = res {
+ // Since this is more of a development-time error, we aren't doing as fancy of a quit
+ // as `get_matches_from`
+ e.exit()
+ }
+ }
+
+ /// Update from iterator, return Err on error.
+ fn try_update_from<I, T>(&mut self, itr: I) -> Result<(), Error>
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ let mut matches =
+ <Self as CommandFactory>::command_for_update().try_get_matches_from(itr)?;
+ <Self as FromArgMatches>::update_from_arg_matches_mut(self, &mut matches)
+ .map_err(format_error::<Self>)
+ }
+
+ /// 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 `CommandFactory::command` (derived as part of `Parser`)"
+ )
+ )]
+ #[doc(hidden)]
+ fn clap<'help>() -> Command<'help> {
+ <Self as CommandFactory>::command()
+ }
+
+ /// Deprecated, `StructOpt::from_clap` replaced with [`FromArgMatches::from_arg_matches_mut`] (derive as part of
+ /// [`Parser`])
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "`StructOpt::from_clap` is replaced with `FromArgMatches::from_arg_matches_mut` (derived as part of `Parser`)"
+ )
+ )]
+ #[doc(hidden)]
+ fn from_clap(matches: &ArgMatches) -> Self {
+ <Self as FromArgMatches>::from_arg_matches(matches).unwrap()
+ }
+
+ /// Deprecated, `StructOpt::from_args` replaced with `Parser::parse` (note the change in derives)
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "`StructOpt::from_args` is replaced with `Parser::parse` (note the change in derives)"
+ )
+ )]
+ #[doc(hidden)]
+ fn from_args() -> Self {
+ Self::parse()
+ }
+
+ /// Deprecated, `StructOpt::from_args_safe` replaced with `Parser::try_parse` (note the change in derives)
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "`StructOpt::from_args_safe` is replaced with `Parser::try_parse` (note the change in derives)"
+ )
+ )]
+ #[doc(hidden)]
+ fn from_args_safe() -> Result<Self, Error> {
+ Self::try_parse()
+ }
+
+ /// Deprecated, `StructOpt::from_iter` replaced with `Parser::parse_from` (note the change in derives)
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "`StructOpt::from_iter` is replaced with `Parser::parse_from` (note the change in derives)"
+ )
+ )]
+ #[doc(hidden)]
+ fn from_iter<I, T>(itr: I) -> Self
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ Self::parse_from(itr)
+ }
+
+ /// Deprecated, `StructOpt::from_iter_safe` replaced with `Parser::try_parse_from` (note the
+ /// change in derives)
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.0.0",
+ note = "`StructOpt::from_iter_safe` is replaced with `Parser::try_parse_from` (note the change in derives)"
+ )
+ )]
+ #[doc(hidden)]
+ fn from_iter_safe<I, T>(itr: I) -> Result<Self, Error>
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ Self::try_parse_from(itr)
+ }
+}
+
+/// Create a [`Command`] relevant for a user-defined container.
+///
+/// Derived as part of [`Parser`].
+pub trait CommandFactory: Sized {
+ /// Build a [`Command`] that can instantiate `Self`.
+ ///
+ /// See [`FromArgMatches::from_arg_matches_mut`] for instantiating `Self`.
+ fn command<'help>() -> Command<'help> {
+ #[allow(deprecated)]
+ Self::into_app()
+ }
+ /// Deprecated, replaced with `CommandFactory::command`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.1.0", note = "Replaced with `CommandFactory::command")
+ )]
+ fn into_app<'help>() -> Command<'help>;
+ /// Build a [`Command`] that can update `self`.
+ ///
+ /// See [`FromArgMatches::update_from_arg_matches_mut`] for updating `self`.
+ fn command_for_update<'help>() -> Command<'help> {
+ #[allow(deprecated)]
+ Self::into_app_for_update()
+ }
+ /// Deprecated, replaced with `CommandFactory::command_for_update`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.1.0",
+ note = "Replaced with `CommandFactory::command_for_update"
+ )
+ )]
+ fn into_app_for_update<'help>() -> Command<'help>;
+}
+
+/// Converts an instance of [`ArgMatches`] to a user-defined container.
+///
+/// Derived as part of [`Parser`], [`Args`], and [`Subcommand`].
+pub trait FromArgMatches: Sized {
+ /// Instantiate `Self` from [`ArgMatches`], parsing the arguments as needed.
+ ///
+ /// Motivation: If our application had two CLI options, `--name
+ /// <STRING>` and the flag `--debug`, we may create a struct as follows:
+ ///
+ #[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+ #[cfg_attr(feature = "derive", doc = " ```no_run")]
+ /// struct Context {
+ /// name: String,
+ /// debug: bool
+ /// }
+ /// ```
+ ///
+ /// We then need to convert the `ArgMatches` that `clap` generated into our struct.
+ /// `from_arg_matches` serves as the equivalent of:
+ ///
+ #[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+ #[cfg_attr(feature = "derive", doc = " ```no_run")]
+ /// # use clap::ArgMatches;
+ /// # struct Context {
+ /// # name: String,
+ /// # debug: bool
+ /// # }
+ /// impl From<ArgMatches> for Context {
+ /// fn from(m: ArgMatches) -> Self {
+ /// Context {
+ /// name: m.get_one::<String>("name").unwrap().clone(),
+ /// debug: *m.get_one::<bool>("debug").expect("defaulted by clap"),
+ /// }
+ /// }
+ /// }
+ /// ```
+ fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error>;
+
+ /// Instantiate `Self` from [`ArgMatches`], parsing the arguments as needed.
+ ///
+ /// Motivation: If our application had two CLI options, `--name
+ /// <STRING>` and the flag `--debug`, we may create a struct as follows:
+ ///
+ #[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+ #[cfg_attr(feature = "derive", doc = " ```no_run")]
+ /// struct Context {
+ /// name: String,
+ /// debug: bool
+ /// }
+ /// ```
+ ///
+ /// We then need to convert the `ArgMatches` that `clap` generated into our struct.
+ /// `from_arg_matches_mut` serves as the equivalent of:
+ ///
+ #[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+ #[cfg_attr(feature = "derive", doc = " ```no_run")]
+ /// # use clap::ArgMatches;
+ /// # struct Context {
+ /// # name: String,
+ /// # debug: bool
+ /// # }
+ /// impl From<ArgMatches> for Context {
+ /// fn from(m: ArgMatches) -> Self {
+ /// Context {
+ /// name: m.get_one::<String>("name").unwrap().to_string(),
+ /// debug: *m.get_one::<bool>("debug").expect("defaulted by clap"),
+ /// }
+ /// }
+ /// }
+ /// ```
+ fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error> {
+ Self::from_arg_matches(matches)
+ }
+
+ /// Assign values from `ArgMatches` to `self`.
+ fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error>;
+
+ /// Assign values from `ArgMatches` to `self`.
+ fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> {
+ self.update_from_arg_matches(matches)
+ }
+}
+
+/// Parse a set of arguments into a user-defined container.
+///
+/// Implementing this trait lets a parent container delegate argument parsing behavior to `Self`.
+/// with:
+/// - `#[clap(flatten)] args: ChildArgs`: Attribute can only be used with struct fields that impl
+/// `Args`.
+/// - `Variant(ChildArgs)`: No attribute is used with enum variants that impl `Args`.
+///
+/// See the [derive reference](crate::_derive) for attributes and best practices.
+///
+/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features]
+///
+/// # Example
+///
+#[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+#[cfg_attr(feature = "derive", doc = " ```")]
+/// #[derive(clap::Parser)]
+/// struct Args {
+/// #[clap(flatten)]
+/// logging: LogArgs,
+/// }
+///
+/// #[derive(clap::Args)]
+/// struct LogArgs {
+/// #[clap(long, short = 'v', parse(from_occurrences))]
+/// verbose: i8,
+/// }
+/// ```
+pub trait Args: FromArgMatches + Sized {
+ /// Append to [`Command`] so it can instantiate `Self`.
+ ///
+ /// See also [`CommandFactory`].
+ fn augment_args(cmd: Command<'_>) -> Command<'_>;
+ /// Append to [`Command`] so it can update `self`.
+ ///
+ /// This is used to implement `#[clap(flatten)]`
+ ///
+ /// See also [`CommandFactory`].
+ fn augment_args_for_update(cmd: Command<'_>) -> Command<'_>;
+}
+
+/// Parse a sub-command into a user-defined enum.
+///
+/// Implementing this trait lets a parent container delegate subcommand behavior to `Self`.
+/// with:
+/// - `#[clap(subcommand)] field: SubCmd`: Attribute can be used with either struct fields or enum
+/// variants that impl `Subcommand`.
+/// - `#[clap(flatten)] Variant(SubCmd)`: Attribute can only be used with enum variants that impl
+/// `Subcommand`.
+///
+/// See the [derive reference](crate::_derive) for attributes and best practices.
+///
+/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features]
+///
+/// # Example
+///
+#[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+#[cfg_attr(feature = "derive", doc = " ```")]
+/// #[derive(clap::Parser)]
+/// struct Args {
+/// #[clap(subcommand)]
+/// action: Action,
+/// }
+///
+/// #[derive(clap::Subcommand)]
+/// enum Action {
+/// Add,
+/// Remove,
+/// }
+/// ```
+pub trait Subcommand: FromArgMatches + Sized {
+ /// Append to [`Command`] so it can instantiate `Self`.
+ ///
+ /// See also [`CommandFactory`].
+ fn augment_subcommands(cmd: Command<'_>) -> Command<'_>;
+ /// Append to [`Command`] so it can update `self`.
+ ///
+ /// This is used to implement `#[clap(flatten)]`
+ ///
+ /// See also [`CommandFactory`].
+ fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_>;
+ /// Test whether `Self` can parse a specific subcommand
+ fn has_subcommand(name: &str) -> bool;
+}
+
+/// Parse arguments into enums.
+///
+/// When deriving [`Parser`], a field whose type implements `ValueEnum` can have the attribute
+/// `#[clap(value_enum)]` which will
+/// - Call [`Arg::possible_values`][crate::Arg::possible_values]
+/// - Allowing using the `#[clap(default_value_t)]` attribute without implementing `Display`.
+///
+/// See the [derive reference](crate::_derive) for attributes and best practices.
+///
+/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features]
+///
+/// # Example
+///
+#[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+#[cfg_attr(feature = "derive", doc = " ```")]
+/// #[derive(clap::Parser)]
+/// struct Args {
+/// #[clap(value_enum)]
+/// level: Level,
+/// }
+///
+/// #[derive(clap::ValueEnum, Clone)]
+/// enum Level {
+/// Debug,
+/// Info,
+/// Warning,
+/// Error,
+/// }
+/// ```
+pub trait ValueEnum: Sized + Clone {
+ /// All possible argument values, in display order.
+ fn value_variants<'a>() -> &'a [Self];
+
+ /// Parse an argument into `Self`.
+ fn from_str(input: &str, ignore_case: bool) -> Result<Self, String> {
+ Self::value_variants()
+ .iter()
+ .find(|v| {
+ v.to_possible_value()
+ .expect("ValueEnum::value_variants contains only values with a corresponding ValueEnum::to_possible_value")
+ .matches(input, ignore_case)
+ })
+ .cloned()
+ .ok_or_else(|| format!("Invalid variant: {}", input))
+ }
+
+ /// The canonical argument value.
+ ///
+ /// The value is `None` for skipped variants.
+ fn to_possible_value<'a>(&self) -> Option<PossibleValue<'a>>;
+}
+
+impl<T: Parser> Parser for Box<T> {
+ fn parse() -> Self {
+ Box::new(<T as Parser>::parse())
+ }
+
+ fn try_parse() -> Result<Self, Error> {
+ <T as Parser>::try_parse().map(Box::new)
+ }
+
+ fn parse_from<I, It>(itr: I) -> Self
+ where
+ I: IntoIterator<Item = It>,
+ It: Into<OsString> + Clone,
+ {
+ Box::new(<T as Parser>::parse_from(itr))
+ }
+
+ fn try_parse_from<I, It>(itr: I) -> Result<Self, Error>
+ where
+ I: IntoIterator<Item = It>,
+ It: Into<OsString> + Clone,
+ {
+ <T as Parser>::try_parse_from(itr).map(Box::new)
+ }
+}
+
+#[allow(deprecated)]
+impl<T: CommandFactory> CommandFactory for Box<T> {
+ fn into_app<'help>() -> Command<'help> {
+ <T as CommandFactory>::into_app()
+ }
+ fn into_app_for_update<'help>() -> Command<'help> {
+ <T as CommandFactory>::into_app_for_update()
+ }
+}
+
+impl<T: FromArgMatches> FromArgMatches for Box<T> {
+ fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
+ <T as FromArgMatches>::from_arg_matches(matches).map(Box::new)
+ }
+ fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error> {
+ <T as FromArgMatches>::from_arg_matches_mut(matches).map(Box::new)
+ }
+ fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
+ <T as FromArgMatches>::update_from_arg_matches(self, matches)
+ }
+ fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> {
+ <T as FromArgMatches>::update_from_arg_matches_mut(self, matches)
+ }
+}
+
+impl<T: Args> Args for Box<T> {
+ fn augment_args(cmd: Command<'_>) -> Command<'_> {
+ <T as Args>::augment_args(cmd)
+ }
+ fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> {
+ <T as Args>::augment_args_for_update(cmd)
+ }
+}
+
+impl<T: Subcommand> Subcommand for Box<T> {
+ fn augment_subcommands(cmd: Command<'_>) -> Command<'_> {
+ <T as Subcommand>::augment_subcommands(cmd)
+ }
+ fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_> {
+ <T as Subcommand>::augment_subcommands_for_update(cmd)
+ }
+ fn has_subcommand(name: &str) -> bool {
+ <T as Subcommand>::has_subcommand(name)
+ }
+}
+
+fn format_error<I: CommandFactory>(err: crate::Error) -> crate::Error {
+ let mut cmd = I::command();
+ err.format(&mut cmd)
+}
diff --git a/3.2.23/src/error/context.rs b/3.2.23/src/error/context.rs
new file mode 100644
index 0000000..985cd4d
--- /dev/null
+++ b/3.2.23/src/error/context.rs
@@ -0,0 +1,55 @@
+/// Semantics for a piece of error information
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum ContextKind {
+ /// The cause of the error
+ InvalidSubcommand,
+ /// The cause of the error
+ InvalidArg,
+ /// Existing arguments
+ PriorArg,
+ /// Accepted values
+ ValidValue,
+ /// Rejected values
+ InvalidValue,
+ /// Number of values present
+ ActualNumValues,
+ /// Number of allowed values
+ ExpectedNumValues,
+ /// Minimum number of allowed values
+ MinValues,
+ /// Number of occurrences present
+ ActualNumOccurrences,
+ /// Maximum number of allowed occurrences
+ MaxOccurrences,
+ /// Potential fix for the user
+ SuggestedCommand,
+ /// Potential fix for the user
+ SuggestedSubcommand,
+ /// Potential fix for the user
+ SuggestedArg,
+ /// Potential fix for the user
+ SuggestedValue,
+ /// Trailing argument
+ TrailingArg,
+ /// A usage string
+ Usage,
+ /// An opaque message to the user
+ Custom,
+}
+
+/// A piece of error information
+#[derive(Clone, Debug, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum ContextValue {
+ /// [`ContextKind`] is self-sufficient, no additional information needed
+ None,
+ /// A single value
+ Bool(bool),
+ /// A single value
+ String(String),
+ /// Many values
+ Strings(Vec<String>),
+ /// A single value
+ Number(isize),
+}
diff --git a/3.2.23/src/error/kind.rs b/3.2.23/src/error/kind.rs
new file mode 100644
index 0000000..4c3dc48
--- /dev/null
+++ b/3.2.23/src/error/kind.rs
@@ -0,0 +1,440 @@
+/// 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 value 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/3.2.23/src/error/mod.rs b/3.2.23/src/error/mod.rs
new file mode 100644
index 0000000..fbd2b30
--- /dev/null
+++ b/3.2.23/src/error/mod.rs
@@ -0,0 +1,1153 @@
+//! 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(())
+ }
+}
+
+#[test]
+fn check_auto_traits() {
+ static_assertions::assert_impl_all!(Error: Send, Sync, Unpin);
+}
diff --git a/3.2.23/src/lib.rs b/3.2.23/src/lib.rs
new file mode 100644
index 0000000..5cefe6e
--- /dev/null
+++ b/3.2.23/src/lib.rs
@@ -0,0 +1,232 @@
+// 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.
+
+//! > **Command Line Argument Parser for Rust**
+//!
+//! Quick Links:
+//! - Derive [tutorial][_derive::_tutorial] and [reference][_derive]
+//! - Builder [tutorial][_tutorial] and [reference](index.html)
+//! - [Cookbook][_cookbook]
+//! - [FAQ][_faq]
+//! - [Discussions](https://github.com/clap-rs/clap/discussions)
+//!
+//! ## Aspirations
+//!
+//! - Out of the box, users get a polished CLI experience
+//! - Including common argument behavior, help generation, suggested fixes for users, colored output, [shell completions](https://github.com/clap-rs/clap/tree/master/clap_complete), etc
+//! - Flexible enough to port your existing CLI interface
+//! - However, we won't necessarily streamline support for each use case
+//! - Reasonable parse performance
+//! - Resilient maintainership, including
+//! - Willing to break compatibility rather than batching up breaking changes in large releases
+//! - Leverage feature flags to keep to one active branch
+//! - Being under [WG-CLI](https://github.com/rust-cli/team/) to increase the bus factor
+//! - We follow semver and will wait about 6-9 months between major breaking changes
+//! - We will support the last two minor Rust releases (MSRV, currently 1.56.1)
+//!
+//! While these aspirations can be at odds with fast build times and low binary
+//! size, we will still strive to keep these reasonable for the flexibility you
+//! get. Check out the
+//! [argparse-benchmarks](https://github.com/rust-cli/argparse-benchmarks-rs) for
+//! CLI parsers optimized for other use cases.
+//!
+//! ## Example
+//!
+//! Run
+//! ```console
+//! $ cargo add clap --features derive
+//! ```
+//! *(See also [feature flag reference][_features])*
+//!
+//! Then define your CLI in `main.rs`:
+#![cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+#![cfg_attr(feature = "derive", doc = " ```no_run")]
+#![doc = include_str!("../examples/demo.rs")]
+//! ```
+//!
+//! And try it out:
+#![doc = include_str!("../examples/demo.md")]
+//!
+//! See also the derive [tutorial][_derive::_tutorial] and [reference][_derive]
+//!
+//! ### Related Projects
+//!
+//! Augment clap:
+//! - [wild](https://crates.io/crates/wild) for supporting wildcards (`*`) on Windows like you do Linux
+//! - [argfile](https://crates.io/crates/argfile) for loading additional arguments from a file (aka response files)
+//! - [shadow-rs](https://crates.io/crates/shadow-rs) for generating `Command::long_version`
+//! - [clap_mangen](https://crates.io/crates/clap_mangen) for generating man page source (roff)
+//! - [clap_complete](https://crates.io/crates/clap_complete) for shell completion support
+//!
+//! CLI Helpers
+//! - [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag)
+//! - [clap-cargo](https://crates.io/crates/clap-cargo)
+//! - [concolor-clap](https://crates.io/crates/concolor-clap)
+//!
+//! Testing
+//! - [`trycmd`](https://crates.io/crates/trycmd): Bulk snapshot testing
+//! - [`snapbox`](https://crates.io/crates/snapbox): Specialized snapshot testing
+//! - [`assert_cmd`](https://crates.io/crates/assert_cmd) and [`assert_fs`](https://crates.io/crates/assert_fs): Customized testing
+//!
+//! Documentation:
+//! - [Command-line Apps for Rust](https://rust-cli.github.io/book/index.html) book
+//!
+
+#![cfg_attr(docsrs, feature(doc_auto_cfg))]
+#![doc(html_logo_url = "https://raw.githubusercontent.com/clap-rs/clap/master/assets/clap.png")]
+#![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(feature = "unstable-doc")]
+pub mod _cookbook;
+#[cfg(feature = "unstable-doc")]
+pub mod _derive;
+#[cfg(feature = "unstable-doc")]
+pub mod _faq;
+#[cfg(feature = "unstable-doc")]
+pub mod _features;
+#[cfg(feature = "unstable-doc")]
+pub mod _tutorial;
+
+#[doc(hidden)]
+pub mod __macro_refs {
+ #[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/3.2.23/src/macros.rs b/3.2.23/src/macros.rs
new file mode 100644
index 0000000..1f91674
--- /dev/null
+++ b/3.2.23/src/macros.rs
@@ -0,0 +1,1058 @@
+/// 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::get_one`")
+)]
+#[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::get_one`")
+)]
+#[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::get_many`")
+)]
+#[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::get_many`")
+)]
+#[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 `ValueEnum`")
+)]
+#[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 `ValueEnum`")
+)]
+#[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::__macro_refs::once_cell::sync::Lazy<String> =
+ clap::__macro_refs::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/3.2.23/src/mkeymap.rs b/3.2.23/src/mkeymap.rs
new file mode 100644
index 0000000..97ecdda
--- /dev/null
+++ b/3.2.23/src/mkeymap.rs
@@ -0,0 +1,193 @@
+use std::iter::Iterator;
+use std::ops::Index;
+use std::{ffi::OsStr, ffi::OsString};
+
+use crate::util::Id;
+use crate::Arg;
+use crate::INTERNAL_ERROR_MSG;
+
+#[derive(PartialEq, Eq, Debug, Clone)]
+pub(crate) struct Key {
+ key: KeyType,
+ index: usize,
+}
+
+#[derive(Default, PartialEq, Eq, Debug, Clone)]
+pub(crate) struct MKeyMap<'help> {
+ /// All of the arguments.
+ args: Vec<Arg<'help>>,
+
+ // Cache part:
+ /// Will be set after `_build()`.
+ keys: Vec<Key>,
+}
+
+#[derive(Debug, PartialEq, Eq, Hash, Clone)]
+pub(crate) enum KeyType {
+ Short(char),
+ Long(OsString),
+ Position(usize),
+}
+
+impl KeyType {
+ pub(crate) fn is_position(&self) -> bool {
+ matches!(self, KeyType::Position(_))
+ }
+}
+
+impl PartialEq<usize> for KeyType {
+ fn eq(&self, rhs: &usize) -> bool {
+ match self {
+ KeyType::Position(x) => x == rhs,
+ _ => false,
+ }
+ }
+}
+
+impl PartialEq<&str> for KeyType {
+ fn eq(&self, rhs: &&str) -> bool {
+ match self {
+ KeyType::Long(l) => l == rhs,
+ _ => false,
+ }
+ }
+}
+
+impl PartialEq<str> for KeyType {
+ fn eq(&self, rhs: &str) -> bool {
+ match self {
+ KeyType::Long(l) => l == rhs,
+ _ => false,
+ }
+ }
+}
+
+impl PartialEq<OsStr> for KeyType {
+ fn eq(&self, rhs: &OsStr) -> bool {
+ match self {
+ KeyType::Long(l) => l == rhs,
+ _ => false,
+ }
+ }
+}
+
+impl PartialEq<char> for KeyType {
+ fn eq(&self, rhs: &char) -> bool {
+ match self {
+ KeyType::Short(c) => c == rhs,
+ _ => false,
+ }
+ }
+}
+
+impl<'help> MKeyMap<'help> {
+ /// If any arg has corresponding key in this map, we can search the key with
+ /// u64(for positional argument), char(for short flag), &str and OsString
+ /// (for long flag)
+ pub(crate) fn contains<K>(&self, key: K) -> bool
+ where
+ KeyType: PartialEq<K>,
+ {
+ self.keys.iter().any(|x| x.key == key)
+ }
+
+ /// Reserves capacity for at least additional more elements to be inserted
+ pub(crate) fn reserve(&mut self, additional: usize) {
+ self.args.reserve(additional);
+ }
+
+ /// Push an argument in the map.
+ pub(crate) fn push(&mut self, new_arg: Arg<'help>) {
+ self.args.push(new_arg);
+ }
+
+ /// Find the arg have corresponding key in this map, we can search the key
+ /// with u64(for positional argument), char(for short flag), &str and
+ /// OsString (for long flag)
+ pub(crate) fn get<K: ?Sized>(&self, key: &K) -> Option<&Arg<'help>>
+ where
+ KeyType: PartialEq<K>,
+ {
+ self.keys
+ .iter()
+ .find(|k| &k.key == key)
+ .map(|k| &self.args[k.index])
+ }
+
+ /// Find out if the map have no arg.
+ pub(crate) fn is_empty(&self) -> bool {
+ self.args.is_empty()
+ }
+
+ /// Return iterators of all keys.
+ pub(crate) fn keys(&self) -> impl Iterator<Item = &KeyType> {
+ self.keys.iter().map(|x| &x.key)
+ }
+
+ /// Return iterators of all args.
+ pub(crate) fn args(&self) -> impl Iterator<Item = &Arg<'help>> {
+ self.args.iter()
+ }
+
+ /// Return mutable iterators of all args.
+ pub(crate) fn args_mut<'map>(&'map mut self) -> impl Iterator<Item = &'map mut Arg<'help>> {
+ self.args.iter_mut()
+ }
+
+ /// We need a lazy build here since some we may change args after creating
+ /// the map, you can checkout who uses `args_mut`.
+ pub(crate) fn _build(&mut self) {
+ for (i, arg) in self.args.iter().enumerate() {
+ append_keys(&mut self.keys, arg, i);
+ }
+ }
+
+ /// Remove an arg in the graph by Id, usually used by `mut_arg`. Return
+ /// `Some(arg)` if removed.
+ pub(crate) fn remove_by_name(&mut self, name: &Id) -> Option<Arg<'help>> {
+ self.args
+ .iter()
+ .position(|arg| &arg.id == name)
+ // since it's a cold function, using this wouldn't hurt much
+ .map(|i| self.args.remove(i))
+ }
+
+ /// Remove an arg based on index
+ pub(crate) fn remove(&mut self, index: usize) -> Arg<'help> {
+ self.args.remove(index)
+ }
+}
+
+impl<'help> Index<&'_ KeyType> for MKeyMap<'help> {
+ type Output = Arg<'help>;
+
+ fn index(&self, key: &KeyType) -> &Self::Output {
+ self.get(key).expect(INTERNAL_ERROR_MSG)
+ }
+}
+
+/// Generate key types for an specific Arg.
+fn append_keys(keys: &mut Vec<Key>, arg: &Arg, index: usize) {
+ if let Some(pos_index) = arg.index {
+ let key = KeyType::Position(pos_index);
+ keys.push(Key { key, index });
+ } else {
+ if let Some(short) = arg.short {
+ let key = KeyType::Short(short);
+ keys.push(Key { key, index });
+ }
+ if let Some(long) = arg.long {
+ let key = KeyType::Long(OsString::from(long));
+ keys.push(Key { key, index });
+ }
+
+ for (short, _) in arg.short_aliases.iter() {
+ let key = KeyType::Short(*short);
+ keys.push(Key { key, index });
+ }
+ for (long, _) in arg.aliases.iter() {
+ let key = KeyType::Long(OsString::from(long));
+ keys.push(Key { key, index });
+ }
+ }
+}
diff --git a/3.2.23/src/output/fmt.rs b/3.2.23/src/output/fmt.rs
new file mode 100644
index 0000000..dc1f46e
--- /dev/null
+++ b/3.2.23/src/output/fmt.rs
@@ -0,0 +1,158 @@
+use crate::util::color::ColorChoice;
+
+use std::{
+ fmt::{self, Display, Formatter},
+ io::{self, Write},
+};
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub(crate) enum Stream {
+ Stdout,
+ Stderr,
+}
+
+#[derive(Clone, Debug)]
+pub(crate) struct Colorizer {
+ stream: Stream,
+ #[allow(unused)]
+ color_when: ColorChoice,
+ pieces: Vec<(String, Style)>,
+}
+
+impl Colorizer {
+ #[inline(never)]
+ pub(crate) fn new(stream: Stream, color_when: ColorChoice) -> Self {
+ Colorizer {
+ stream,
+ color_when,
+ pieces: vec![],
+ }
+ }
+
+ #[inline(never)]
+ pub(crate) fn good(&mut self, msg: impl Into<String>) {
+ self.pieces.push((msg.into(), Style::Good));
+ }
+
+ #[inline(never)]
+ pub(crate) fn warning(&mut self, msg: impl Into<String>) {
+ self.pieces.push((msg.into(), Style::Warning));
+ }
+
+ #[inline(never)]
+ pub(crate) fn error(&mut self, msg: impl Into<String>) {
+ self.pieces.push((msg.into(), Style::Error));
+ }
+
+ #[inline(never)]
+ #[allow(dead_code)]
+ pub(crate) fn hint(&mut self, msg: impl Into<String>) {
+ self.pieces.push((msg.into(), Style::Hint));
+ }
+
+ #[inline(never)]
+ pub(crate) fn none(&mut self, msg: impl Into<String>) {
+ self.pieces.push((msg.into(), Style::Default));
+ }
+}
+
+/// Printing methods.
+impl Colorizer {
+ #[cfg(feature = "color")]
+ pub(crate) fn print(&self) -> io::Result<()> {
+ use termcolor::{BufferWriter, ColorChoice as DepColorChoice, ColorSpec, WriteColor};
+
+ let color_when = match self.color_when {
+ ColorChoice::Always => DepColorChoice::Always,
+ ColorChoice::Auto if is_a_tty(self.stream) => DepColorChoice::Auto,
+ _ => DepColorChoice::Never,
+ };
+
+ let writer = match self.stream {
+ Stream::Stderr => BufferWriter::stderr(color_when),
+ Stream::Stdout => BufferWriter::stdout(color_when),
+ };
+
+ let mut buffer = writer.buffer();
+
+ for piece in &self.pieces {
+ let mut color = ColorSpec::new();
+ match piece.1 {
+ Style::Good => {
+ color.set_fg(Some(termcolor::Color::Green));
+ }
+ Style::Warning => {
+ color.set_fg(Some(termcolor::Color::Yellow));
+ }
+ Style::Error => {
+ color.set_fg(Some(termcolor::Color::Red));
+ color.set_bold(true);
+ }
+ Style::Hint => {
+ color.set_dimmed(true);
+ }
+ Style::Default => {}
+ }
+
+ buffer.set_color(&color)?;
+ buffer.write_all(piece.0.as_bytes())?;
+ buffer.reset()?;
+ }
+
+ writer.print(&buffer)
+ }
+
+ #[cfg(not(feature = "color"))]
+ pub(crate) fn print(&self) -> io::Result<()> {
+ // [e]println can't be used here because it panics
+ // if something went wrong. We don't want that.
+ match self.stream {
+ Stream::Stdout => {
+ let stdout = std::io::stdout();
+ let mut stdout = stdout.lock();
+ write!(stdout, "{}", self)
+ }
+ Stream::Stderr => {
+ let stderr = std::io::stderr();
+ let mut stderr = stderr.lock();
+ write!(stderr, "{}", self)
+ }
+ }
+ }
+}
+
+/// Color-unaware printing. Never uses coloring.
+impl Display for Colorizer {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ for piece in &self.pieces {
+ Display::fmt(&piece.0, f)?;
+ }
+
+ Ok(())
+ }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum Style {
+ Good,
+ Warning,
+ Error,
+ Hint,
+ Default,
+}
+
+impl Default for Style {
+ fn default() -> Self {
+ Self::Default
+ }
+}
+
+#[cfg(feature = "color")]
+fn is_a_tty(stream: Stream) -> bool {
+ let stream = match stream {
+ Stream::Stdout => atty::Stream::Stdout,
+ Stream::Stderr => atty::Stream::Stderr,
+ };
+
+ atty::is(stream)
+}
diff --git a/3.2.23/src/output/help.rs b/3.2.23/src/output/help.rs
new file mode 100644
index 0000000..eb53bfa
--- /dev/null
+++ b/3.2.23/src/output/help.rs
@@ -0,0 +1,1176 @@
+// Std
+use std::borrow::Cow;
+use std::cmp;
+use std::fmt::Write as _;
+use std::io::{self, Write};
+use std::usize;
+
+// Internal
+use crate::builder::{display_arg_val, Arg, Command};
+use crate::output::{fmt::Colorizer, Usage};
+use crate::PossibleValue;
+
+// Third party
+use indexmap::IndexSet;
+use textwrap::core::display_width;
+
+/// `clap` Help Writer.
+///
+/// Wraps a writer stream providing different methods to generate help for `clap` objects.
+pub(crate) struct Help<'help, 'cmd, 'writer> {
+ writer: HelpWriter<'writer>,
+ cmd: &'cmd Command<'help>,
+ usage: &'cmd Usage<'help, 'cmd>,
+ next_line_help: bool,
+ term_w: usize,
+ use_long: bool,
+}
+
+// Public Functions
+impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> {
+ #[cfg(feature = "unstable-v4")]
+ const DEFAULT_TEMPLATE: &'static str = "\
+ {before-help}{name} {version}\n\
+ {author-with-newline}{about-with-newline}\n\
+ {usage-heading}\n {usage}\n\
+ \n\
+ {all-args}{after-help}\
+ ";
+ #[cfg(not(feature = "unstable-v4"))]
+ const DEFAULT_TEMPLATE: &'static str = "\
+ {before-help}{bin} {version}\n\
+ {author-with-newline}{about-with-newline}\n\
+ {usage-heading}\n {usage}\n\
+ \n\
+ {all-args}{after-help}\
+ ";
+
+ #[cfg(feature = "unstable-v4")]
+ const DEFAULT_NO_ARGS_TEMPLATE: &'static str = "\
+ {before-help}{name} {version}\n\
+ {author-with-newline}{about-with-newline}\n\
+ {usage-heading}\n {usage}{after-help}\
+ ";
+ #[cfg(not(feature = "unstable-v4"))]
+ const DEFAULT_NO_ARGS_TEMPLATE: &'static str = "\
+ {before-help}{bin} {version}\n\
+ {author-with-newline}{about-with-newline}\n\
+ {usage-heading}\n {usage}{after-help}\
+ ";
+
+ /// Create a new `Help` instance.
+ pub(crate) fn new(
+ writer: HelpWriter<'writer>,
+ cmd: &'cmd Command<'help>,
+ usage: &'cmd Usage<'help, 'cmd>,
+ use_long: bool,
+ ) -> Self {
+ debug!("Help::new cmd={}, use_long={}", cmd.get_name(), use_long);
+ let term_w = match cmd.get_term_width() {
+ Some(0) => usize::MAX,
+ Some(w) => w,
+ None => cmp::min(
+ dimensions().map_or(100, |(w, _)| w),
+ match cmd.get_max_term_width() {
+ None | Some(0) => usize::MAX,
+ Some(mw) => mw,
+ },
+ ),
+ };
+ let next_line_help = cmd.is_next_line_help_set();
+
+ Help {
+ writer,
+ cmd,
+ usage,
+ next_line_help,
+ term_w,
+ use_long,
+ }
+ }
+
+ /// Writes the parser help to the wrapped stream.
+ pub(crate) fn write_help(&mut self) -> io::Result<()> {
+ debug!("Help::write_help");
+
+ if let Some(h) = self.cmd.get_override_help() {
+ self.none(h)?;
+ } else if let Some(tmpl) = self.cmd.get_help_template() {
+ self.write_templated_help(tmpl)?;
+ } else {
+ let pos = self
+ .cmd
+ .get_positionals()
+ .any(|arg| should_show_arg(self.use_long, arg));
+ let non_pos = self
+ .cmd
+ .get_non_positionals()
+ .any(|arg| should_show_arg(self.use_long, arg));
+ let subcmds = self.cmd.has_visible_subcommands();
+
+ if non_pos || pos || subcmds {
+ self.write_templated_help(Self::DEFAULT_TEMPLATE)?;
+ } else {
+ self.write_templated_help(Self::DEFAULT_NO_ARGS_TEMPLATE)?;
+ }
+ }
+
+ self.none("\n")?;
+
+ Ok(())
+ }
+}
+
+macro_rules! write_method {
+ ($_self:ident, $msg:ident, $meth:ident) => {
+ match &mut $_self.writer {
+ HelpWriter::Buffer(c) => {
+ c.$meth(($msg).into());
+ Ok(())
+ }
+ HelpWriter::Normal(w) => w.write_all($msg.as_ref()),
+ }
+ };
+}
+
+// Methods to write Arg help.
+impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> {
+ #[inline(never)]
+ fn good<T: Into<String> + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> {
+ write_method!(self, msg, good)
+ }
+
+ #[inline(never)]
+ fn warning<T: Into<String> + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> {
+ write_method!(self, msg, warning)
+ }
+
+ #[inline(never)]
+ fn none<T: Into<String> + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> {
+ write_method!(self, msg, none)
+ }
+
+ #[inline(never)]
+ fn spaces(&mut self, n: usize) -> io::Result<()> {
+ // A string with 64 consecutive spaces.
+ const SHORT_SPACE: &str =
+ " ";
+ if let Some(short) = SHORT_SPACE.get(..n) {
+ self.none(short)
+ } else {
+ self.none(" ".repeat(n))
+ }
+ }
+
+ /// Writes help for each argument in the order they were declared to the wrapped stream.
+ fn write_args_unsorted(&mut self, args: &[&Arg<'help>]) -> io::Result<()> {
+ debug!("Help::write_args_unsorted");
+ // The shortest an arg can legally be is 2 (i.e. '-x')
+ let mut longest = 2;
+ let mut arg_v = Vec::with_capacity(10);
+
+ for &arg in args
+ .iter()
+ .filter(|arg| should_show_arg(self.use_long, *arg))
+ {
+ if arg.longest_filter() {
+ longest = longest.max(display_width(&arg.to_string()));
+ debug!(
+ "Help::write_args_unsorted: arg={:?} longest={}",
+ arg.get_id(),
+ longest
+ );
+ }
+ arg_v.push(arg)
+ }
+
+ let next_line_help = self.will_args_wrap(args, longest);
+
+ let argc = arg_v.len();
+ for (i, arg) in arg_v.iter().enumerate() {
+ self.write_arg(arg, i + 1 == argc, next_line_help, longest)?;
+ }
+ Ok(())
+ }
+
+ /// Sorts arguments by length and display order and write their help to the wrapped stream.
+ fn write_args(&mut self, args: &[&Arg<'help>], _category: &str) -> io::Result<()> {
+ debug!("Help::write_args {}", _category);
+ // The shortest an arg can legally be is 2 (i.e. '-x')
+ let mut longest = 2;
+ let mut ord_v = Vec::new();
+
+ // Determine the longest
+ for &arg in args.iter().filter(|arg| {
+ // If it's NextLineHelp we don't care to compute how long it is because it may be
+ // NextLineHelp on purpose simply *because* it's so long and would throw off all other
+ // args alignment
+ should_show_arg(self.use_long, *arg)
+ }) {
+ if arg.longest_filter() {
+ longest = longest.max(display_width(&arg.to_string()));
+ debug!(
+ "Help::write_args: arg={:?} longest={}",
+ arg.get_id(),
+ longest
+ );
+ }
+
+ // Formatting key like this to ensure that:
+ // 1. Argument has long flags are printed just after short flags.
+ // 2. For two args both have short flags like `-c` and `-C`, the
+ // `-C` arg is printed just after the `-c` arg
+ // 3. For args without short or long flag, print them at last(sorted
+ // by arg name).
+ // Example order: -a, -b, -B, -s, --select-file, --select-folder, -x
+
+ let key = if let Some(x) = arg.short {
+ let mut s = x.to_ascii_lowercase().to_string();
+ s.push(if x.is_ascii_lowercase() { '0' } else { '1' });
+ s
+ } else if let Some(x) = arg.long {
+ x.to_string()
+ } else {
+ let mut s = '{'.to_string();
+ s.push_str(arg.name);
+ s
+ };
+ ord_v.push((arg.get_display_order(), key, arg));
+ }
+ ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));
+
+ let next_line_help = self.will_args_wrap(args, longest);
+
+ for (i, (_, _, arg)) in ord_v.iter().enumerate() {
+ let last_arg = i + 1 == ord_v.len();
+ self.write_arg(arg, last_arg, next_line_help, longest)?;
+ }
+ Ok(())
+ }
+
+ /// Writes help for an argument to the wrapped stream.
+ fn write_arg(
+ &mut self,
+ arg: &Arg<'help>,
+ last_arg: bool,
+ next_line_help: bool,
+ longest: usize,
+ ) -> io::Result<()> {
+ let spec_vals = &self.spec_vals(arg);
+
+ self.short(arg)?;
+ self.long(arg)?;
+ self.val(arg)?;
+ self.align_to_about(arg, next_line_help, longest)?;
+
+ let about = if self.use_long {
+ arg.long_help.or(arg.help).unwrap_or("")
+ } else {
+ arg.help.or(arg.long_help).unwrap_or("")
+ };
+
+ self.help(Some(arg), about, spec_vals, next_line_help, longest)?;
+
+ if !last_arg {
+ self.none("\n")?;
+ if next_line_help {
+ self.none("\n")?;
+ }
+ }
+ Ok(())
+ }
+
+ /// Writes argument's short command to the wrapped stream.
+ fn short(&mut self, arg: &Arg<'help>) -> io::Result<()> {
+ debug!("Help::short");
+
+ self.none(TAB)?;
+
+ if let Some(s) = arg.short {
+ self.good(format!("-{}", s))
+ } else if !arg.is_positional() {
+ self.none(TAB)
+ } else {
+ Ok(())
+ }
+ }
+
+ /// Writes argument's long command to the wrapped stream.
+ fn long(&mut self, arg: &Arg<'help>) -> io::Result<()> {
+ debug!("Help::long");
+ if let Some(long) = arg.long {
+ if arg.short.is_some() {
+ self.none(", ")?;
+ }
+ self.good(format!("--{}", long))?;
+ }
+ Ok(())
+ }
+
+ /// Writes argument's possible values to the wrapped stream.
+ fn val(&mut self, arg: &Arg<'help>) -> io::Result<()> {
+ debug!("Help::val: arg={}", arg.name);
+ let mut need_closing_bracket = false;
+ if arg.is_takes_value_set() && !arg.is_positional() {
+ let is_optional_val = arg.min_vals == Some(0);
+ let sep = if arg.is_require_equals_set() {
+ if is_optional_val {
+ need_closing_bracket = true;
+ "[="
+ } else {
+ "="
+ }
+ } else if is_optional_val {
+ need_closing_bracket = true;
+ " ["
+ } else {
+ " "
+ };
+ self.none(sep)?;
+ }
+
+ if arg.is_takes_value_set() || arg.is_positional() {
+ display_arg_val(
+ arg,
+ |s, good| if good { self.good(s) } else { self.none(s) },
+ )?;
+ }
+
+ if need_closing_bracket {
+ self.none("]")?;
+ }
+ Ok(())
+ }
+
+ /// Write alignment padding between arg's switches/values and its about message.
+ fn align_to_about(
+ &mut self,
+ arg: &Arg<'help>,
+ next_line_help: bool,
+ longest: usize,
+ ) -> io::Result<()> {
+ debug!(
+ "Help::align_to_about: arg={}, next_line_help={}, longest={}",
+ arg.name, next_line_help, longest
+ );
+ if self.use_long || next_line_help {
+ // long help prints messages on the next line so it doesn't need to align text
+ debug!("Help::align_to_about: printing long help so skip alignment");
+ } else if !arg.is_positional() {
+ let self_len = display_width(&arg.to_string());
+ // Since we're writing spaces from the tab point we first need to know if we
+ // had a long and short, or just short
+ let padding = if arg.long.is_some() {
+ // Only account 4 after the val
+ 4
+ } else {
+ // Only account for ', --' + 4 after the val
+ 8
+ };
+ let spcs = longest + padding - self_len;
+ debug!(
+ "Help::align_to_about: positional=false arg_len={}, spaces={}",
+ self_len, spcs
+ );
+
+ self.spaces(spcs)?;
+ } else {
+ let self_len = display_width(&arg.to_string());
+ let padding = 4;
+ let spcs = longest + padding - self_len;
+ debug!(
+ "Help::align_to_about: positional=true arg_len={}, spaces={}",
+ self_len, spcs
+ );
+
+ self.spaces(spcs)?;
+ }
+ Ok(())
+ }
+
+ fn write_before_help(&mut self) -> io::Result<()> {
+ debug!("Help::write_before_help");
+ let before_help = if self.use_long {
+ self.cmd
+ .get_before_long_help()
+ .or_else(|| self.cmd.get_before_help())
+ } else {
+ self.cmd.get_before_help()
+ };
+ if let Some(output) = before_help {
+ self.none(text_wrapper(&output.replace("{n}", "\n"), self.term_w))?;
+ self.none("\n\n")?;
+ }
+ Ok(())
+ }
+
+ fn write_after_help(&mut self) -> io::Result<()> {
+ debug!("Help::write_after_help");
+ let after_help = if self.use_long {
+ self.cmd
+ .get_after_long_help()
+ .or_else(|| self.cmd.get_after_help())
+ } else {
+ self.cmd.get_after_help()
+ };
+ if let Some(output) = after_help {
+ self.none("\n\n")?;
+ self.none(text_wrapper(&output.replace("{n}", "\n"), self.term_w))?;
+ }
+ Ok(())
+ }
+
+ /// Writes argument's help to the wrapped stream.
+ fn help(
+ &mut self,
+ arg: Option<&Arg<'help>>,
+ about: &str,
+ spec_vals: &str,
+ next_line_help: bool,
+ longest: usize,
+ ) -> io::Result<()> {
+ debug!("Help::help");
+ let mut help = String::from(about) + spec_vals;
+ debug!("Help::help: Next Line...{:?}", next_line_help);
+
+ let spaces = if next_line_help {
+ 12 // "tab" * 3
+ } else {
+ longest + 12
+ };
+
+ let too_long = spaces + display_width(&help) >= self.term_w;
+
+ // Is help on next line, if so then indent
+ if next_line_help {
+ self.none(format!("\n{}{}{}", TAB, TAB, TAB))?;
+ }
+
+ debug!("Help::help: Too long...");
+ if too_long && spaces <= self.term_w || help.contains("{n}") {
+ debug!("Yes");
+ debug!("Help::help: help...{}", help);
+ debug!("Help::help: help width...{}", display_width(&help));
+ // Determine how many newlines we need to insert
+ let avail_chars = self.term_w - spaces;
+ debug!("Help::help: Usable space...{}", avail_chars);
+ help = text_wrapper(&help.replace("{n}", "\n"), avail_chars);
+ } else {
+ debug!("No");
+ }
+ if let Some(part) = help.lines().next() {
+ self.none(part)?;
+ }
+
+ // indent of help
+ let spaces = if next_line_help {
+ TAB_WIDTH * 3
+ } else if let Some(true) = arg.map(|a| a.is_positional()) {
+ longest + TAB_WIDTH * 2
+ } else {
+ longest + TAB_WIDTH * 3
+ };
+
+ for part in help.lines().skip(1) {
+ self.none("\n")?;
+ self.spaces(spaces)?;
+ self.none(part)?;
+ }
+
+ #[cfg(feature = "unstable-v4")]
+ if let Some(arg) = arg {
+ const DASH_SPACE: usize = "- ".len();
+ const COLON_SPACE: usize = ": ".len();
+ let possible_vals = arg.get_possible_values2();
+ if self.use_long
+ && !arg.is_hide_possible_values_set()
+ && possible_vals.iter().any(PossibleValue::should_show_help)
+ {
+ debug!("Help::help: Found possible vals...{:?}", possible_vals);
+ if !help.is_empty() {
+ self.none("\n\n")?;
+ self.spaces(spaces)?;
+ }
+ self.none("Possible values:")?;
+ let longest = possible_vals
+ .iter()
+ .filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name)))
+ .max()
+ .expect("Only called with possible value");
+ let help_longest = possible_vals
+ .iter()
+ .filter_map(|f| f.get_visible_help().map(display_width))
+ .max()
+ .expect("Only called with possible value with help");
+ // should new line
+ let taken = longest + spaces + DASH_SPACE;
+
+ let possible_value_new_line =
+ self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest;
+
+ let spaces = spaces + TAB_WIDTH - DASH_SPACE;
+ let spaces_help = if possible_value_new_line {
+ spaces + DASH_SPACE
+ } else {
+ spaces + longest + DASH_SPACE + COLON_SPACE
+ };
+
+ for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
+ self.none("\n")?;
+ self.spaces(spaces)?;
+ self.none("- ")?;
+ self.good(pv.get_name())?;
+ if let Some(help) = pv.get_help() {
+ debug!("Help::help: Possible Value help");
+
+ if possible_value_new_line {
+ self.none(":\n")?;
+ self.spaces(spaces_help)?;
+ } else {
+ self.none(": ")?;
+ // To align help messages
+ self.spaces(longest - display_width(pv.get_name()))?;
+ }
+
+ let avail_chars = if self.term_w > spaces_help {
+ self.term_w - spaces_help
+ } else {
+ usize::MAX
+ };
+
+ let help = text_wrapper(help, avail_chars);
+ let mut help = help.lines();
+
+ self.none(help.next().unwrap_or_default())?;
+ for part in help {
+ self.none("\n")?;
+ self.spaces(spaces_help)?;
+ self.none(part)?;
+ }
+ }
+ }
+ }
+ }
+ Ok(())
+ }
+
+ /// Will use next line help on writing args.
+ fn will_args_wrap(&self, args: &[&Arg<'help>], longest: usize) -> bool {
+ args.iter()
+ .filter(|arg| should_show_arg(self.use_long, *arg))
+ .any(|arg| {
+ let spec_vals = &self.spec_vals(arg);
+ self.arg_next_line_help(arg, spec_vals, longest)
+ })
+ }
+
+ fn arg_next_line_help(&self, arg: &Arg<'help>, spec_vals: &str, longest: usize) -> bool {
+ if self.next_line_help || arg.is_next_line_help_set() || self.use_long {
+ // setting_next_line
+ true
+ } else {
+ // force_next_line
+ let h = arg.help.unwrap_or("");
+ let h_w = display_width(h) + display_width(spec_vals);
+ let taken = longest + 12;
+ self.term_w >= taken
+ && (taken as f32 / self.term_w as f32) > 0.40
+ && h_w > (self.term_w - taken)
+ }
+ }
+
+ fn spec_vals(&self, a: &Arg) -> String {
+ debug!("Help::spec_vals: a={}", a);
+ let mut spec_vals = vec![];
+ #[cfg(feature = "env")]
+ if let Some(ref env) = a.env {
+ if !a.is_hide_env_set() {
+ debug!(
+ "Help::spec_vals: Found environment variable...[{:?}:{:?}]",
+ env.0, env.1
+ );
+ let env_val = if !a.is_hide_env_values_set() {
+ format!(
+ "={}",
+ env.1
+ .as_ref()
+ .map_or(Cow::Borrowed(""), |val| val.to_string_lossy())
+ )
+ } else {
+ String::new()
+ };
+ let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val);
+ spec_vals.push(env_info);
+ }
+ }
+ if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() {
+ debug!(
+ "Help::spec_vals: Found default value...[{:?}]",
+ a.default_vals
+ );
+
+ let pvs = a
+ .default_vals
+ .iter()
+ .map(|&pvs| pvs.to_string_lossy())
+ .map(|pvs| {
+ if pvs.contains(char::is_whitespace) {
+ Cow::from(format!("{:?}", pvs))
+ } else {
+ pvs
+ }
+ })
+ .collect::<Vec<_>>()
+ .join(" ");
+
+ spec_vals.push(format!("[default: {}]", pvs));
+ }
+ if !a.aliases.is_empty() {
+ debug!("Help::spec_vals: Found aliases...{:?}", a.aliases);
+
+ let als = a
+ .aliases
+ .iter()
+ .filter(|&als| als.1) // visible
+ .map(|&als| als.0) // name
+ .collect::<Vec<_>>()
+ .join(", ");
+
+ if !als.is_empty() {
+ spec_vals.push(format!("[aliases: {}]", als));
+ }
+ }
+
+ if !a.short_aliases.is_empty() {
+ debug!(
+ "Help::spec_vals: Found short aliases...{:?}",
+ a.short_aliases
+ );
+
+ let als = a
+ .short_aliases
+ .iter()
+ .filter(|&als| als.1) // visible
+ .map(|&als| als.0.to_string()) // name
+ .collect::<Vec<_>>()
+ .join(", ");
+
+ if !als.is_empty() {
+ spec_vals.push(format!("[short aliases: {}]", als));
+ }
+ }
+
+ let possible_vals = a.get_possible_values2();
+ if !(a.is_hide_possible_values_set()
+ || possible_vals.is_empty()
+ || cfg!(feature = "unstable-v4")
+ && self.use_long
+ && possible_vals.iter().any(PossibleValue::should_show_help))
+ {
+ debug!("Help::spec_vals: Found possible vals...{:?}", possible_vals);
+
+ let pvs = possible_vals
+ .iter()
+ .filter_map(PossibleValue::get_visible_quoted_name)
+ .collect::<Vec<_>>()
+ .join(", ");
+
+ spec_vals.push(format!("[possible values: {}]", pvs));
+ }
+ let connector = if self.use_long { "\n" } else { " " };
+ let prefix = if !spec_vals.is_empty() && !a.get_help().unwrap_or("").is_empty() {
+ if self.use_long {
+ "\n\n"
+ } else {
+ " "
+ }
+ } else {
+ ""
+ };
+ prefix.to_string() + &spec_vals.join(connector)
+ }
+
+ fn write_about(&mut self, before_new_line: bool, after_new_line: bool) -> io::Result<()> {
+ let about = if self.use_long {
+ self.cmd.get_long_about().or_else(|| self.cmd.get_about())
+ } else {
+ self.cmd.get_about()
+ };
+ if let Some(output) = about {
+ if before_new_line {
+ self.none("\n")?;
+ }
+ self.none(text_wrapper(output, self.term_w))?;
+ if after_new_line {
+ self.none("\n")?;
+ }
+ }
+ Ok(())
+ }
+
+ fn write_author(&mut self, before_new_line: bool, after_new_line: bool) -> io::Result<()> {
+ if let Some(author) = self.cmd.get_author() {
+ if before_new_line {
+ self.none("\n")?;
+ }
+ self.none(text_wrapper(author, self.term_w))?;
+ if after_new_line {
+ self.none("\n")?;
+ }
+ }
+ Ok(())
+ }
+
+ fn write_version(&mut self) -> io::Result<()> {
+ let version = self
+ .cmd
+ .get_version()
+ .or_else(|| self.cmd.get_long_version());
+ if let Some(output) = version {
+ self.none(text_wrapper(output, self.term_w))?;
+ }
+ Ok(())
+ }
+}
+
+/// Methods to write a single subcommand
+impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> {
+ fn write_subcommand(
+ &mut self,
+ sc_str: &str,
+ cmd: &Command<'help>,
+ next_line_help: bool,
+ longest: usize,
+ ) -> io::Result<()> {
+ debug!("Help::write_subcommand");
+
+ let spec_vals = &self.sc_spec_vals(cmd);
+
+ let about = cmd
+ .get_about()
+ .or_else(|| cmd.get_long_about())
+ .unwrap_or("");
+
+ self.subcmd(sc_str, next_line_help, longest)?;
+ self.help(None, about, spec_vals, next_line_help, longest)
+ }
+
+ fn sc_spec_vals(&self, a: &Command) -> String {
+ debug!("Help::sc_spec_vals: a={}", a.get_name());
+ let mut spec_vals = vec![];
+ if 0 < a.get_all_aliases().count() || 0 < a.get_all_short_flag_aliases().count() {
+ debug!(
+ "Help::spec_vals: Found aliases...{:?}",
+ a.get_all_aliases().collect::<Vec<_>>()
+ );
+ debug!(
+ "Help::spec_vals: Found short flag aliases...{:?}",
+ a.get_all_short_flag_aliases().collect::<Vec<_>>()
+ );
+
+ let mut short_als = a
+ .get_visible_short_flag_aliases()
+ .map(|a| format!("-{}", a))
+ .collect::<Vec<_>>();
+
+ let als = a.get_visible_aliases().map(|s| s.to_string());
+
+ short_als.extend(als);
+
+ let all_als = short_als.join(", ");
+
+ if !all_als.is_empty() {
+ spec_vals.push(format!(" [aliases: {}]", all_als));
+ }
+ }
+ spec_vals.join(" ")
+ }
+
+ fn subcommand_next_line_help(
+ &self,
+ cmd: &Command<'help>,
+ spec_vals: &str,
+ longest: usize,
+ ) -> bool {
+ if self.next_line_help | self.use_long {
+ // setting_next_line
+ true
+ } else {
+ // force_next_line
+ let h = cmd.get_about().unwrap_or("");
+ let h_w = display_width(h) + display_width(spec_vals);
+ let taken = longest + 12;
+ self.term_w >= taken
+ && (taken as f32 / self.term_w as f32) > 0.40
+ && h_w > (self.term_w - taken)
+ }
+ }
+
+ /// Writes subcommand to the wrapped stream.
+ fn subcmd(&mut self, sc_str: &str, next_line_help: bool, longest: usize) -> io::Result<()> {
+ self.none(TAB)?;
+ self.good(sc_str)?;
+ if !next_line_help {
+ let width = display_width(sc_str);
+ self.spaces(width.max(longest + 4) - width)?;
+ }
+ Ok(())
+ }
+}
+
+// Methods to write Parser help.
+impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> {
+ /// Writes help for all arguments (options, flags, args, subcommands)
+ /// including titles of a Parser Object to the wrapped stream.
+ pub(crate) fn write_all_args(&mut self) -> io::Result<()> {
+ debug!("Help::write_all_args");
+ let pos = self
+ .cmd
+ .get_positionals_with_no_heading()
+ .filter(|arg| should_show_arg(self.use_long, arg))
+ .collect::<Vec<_>>();
+ let non_pos = self
+ .cmd
+ .get_non_positionals_with_no_heading()
+ .filter(|arg| should_show_arg(self.use_long, arg))
+ .collect::<Vec<_>>();
+ let subcmds = self.cmd.has_visible_subcommands();
+
+ let custom_headings = self
+ .cmd
+ .get_arguments()
+ .filter_map(|arg| arg.get_help_heading())
+ .collect::<IndexSet<_>>();
+
+ let mut first = if !pos.is_empty() {
+ // Write positional args if any
+ self.warning("ARGS:\n")?;
+ self.write_args_unsorted(&pos)?;
+ false
+ } else {
+ true
+ };
+
+ if !non_pos.is_empty() {
+ if !first {
+ self.none("\n\n")?;
+ }
+ self.warning("OPTIONS:\n")?;
+ self.write_args(&non_pos, "OPTIONS")?;
+ first = false;
+ }
+ if !custom_headings.is_empty() {
+ for heading in custom_headings {
+ let args = self
+ .cmd
+ .get_arguments()
+ .filter(|a| {
+ if let Some(help_heading) = a.get_help_heading() {
+ return help_heading == heading;
+ }
+ false
+ })
+ .filter(|arg| should_show_arg(self.use_long, arg))
+ .collect::<Vec<_>>();
+
+ if !args.is_empty() {
+ if !first {
+ self.none("\n\n")?;
+ }
+ self.warning(format!("{}:\n", heading))?;
+ self.write_args(&args, heading)?;
+ first = false
+ }
+ }
+ }
+
+ if subcmds {
+ if !first {
+ self.none("\n\n")?;
+ }
+
+ self.warning(
+ self.cmd
+ .get_subcommand_help_heading()
+ .unwrap_or("SUBCOMMANDS"),
+ )?;
+ self.warning(":\n")?;
+
+ self.write_subcommands(self.cmd)?;
+ }
+
+ Ok(())
+ }
+
+ /// Will use next line help on writing subcommands.
+ fn will_subcommands_wrap<'a>(
+ &self,
+ subcommands: impl IntoIterator<Item = &'a Command<'help>>,
+ longest: usize,
+ ) -> bool
+ where
+ 'help: 'a,
+ {
+ subcommands
+ .into_iter()
+ .filter(|&subcommand| should_show_subcommand(subcommand))
+ .any(|subcommand| {
+ let spec_vals = &self.sc_spec_vals(subcommand);
+ self.subcommand_next_line_help(subcommand, spec_vals, longest)
+ })
+ }
+
+ /// Writes help for subcommands of a Parser Object to the wrapped stream.
+ fn write_subcommands(&mut self, cmd: &Command<'help>) -> io::Result<()> {
+ debug!("Help::write_subcommands");
+ // The shortest an arg can legally be is 2 (i.e. '-x')
+ let mut longest = 2;
+ let mut ord_v = Vec::new();
+ for subcommand in cmd
+ .get_subcommands()
+ .filter(|subcommand| should_show_subcommand(subcommand))
+ {
+ let mut sc_str = String::new();
+ sc_str.push_str(subcommand.get_name());
+ if let Some(short) = subcommand.get_short_flag() {
+ write!(sc_str, " -{}", short).unwrap();
+ }
+ if let Some(long) = subcommand.get_long_flag() {
+ write!(sc_str, " --{}", long).unwrap();
+ }
+ longest = longest.max(display_width(&sc_str));
+ ord_v.push((subcommand.get_display_order(), sc_str, subcommand));
+ }
+ ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));
+
+ debug!("Help::write_subcommands longest = {}", longest);
+
+ let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest);
+
+ let mut first = true;
+ for (_, sc_str, sc) in &ord_v {
+ if first {
+ first = false;
+ } else {
+ self.none("\n")?;
+ }
+ self.write_subcommand(sc_str, sc, next_line_help, longest)?;
+ }
+ Ok(())
+ }
+
+ /// Writes binary name of a Parser Object to the wrapped stream.
+ fn write_display_name(&mut self) -> io::Result<()> {
+ debug!("Help::write_display_name");
+
+ let display_name = text_wrapper(
+ &self
+ .cmd
+ .get_display_name()
+ .unwrap_or_else(|| self.cmd.get_name())
+ .replace("{n}", "\n"),
+ self.term_w,
+ );
+ self.good(&display_name)?;
+ Ok(())
+ }
+
+ /// Writes binary name of a Parser Object to the wrapped stream.
+ fn write_bin_name(&mut self) -> io::Result<()> {
+ debug!("Help::write_bin_name");
+
+ let bin_name = if let Some(bn) = self.cmd.get_bin_name() {
+ if bn.contains(' ') {
+ // In case we're dealing with subcommands i.e. git mv is translated to git-mv
+ bn.replace(' ', "-")
+ } else {
+ text_wrapper(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
+ }
+ } else {
+ text_wrapper(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
+ };
+ self.good(&bin_name)?;
+ Ok(())
+ }
+}
+
+// Methods to write Parser help using templates.
+impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> {
+ /// Write help to stream for the parser in the format defined by the template.
+ ///
+ /// For details about the template language see [`Command::help_template`].
+ ///
+ /// [`Command::help_template`]: Command::help_template()
+ fn write_templated_help(&mut self, template: &str) -> io::Result<()> {
+ debug!("Help::write_templated_help");
+
+ // The strategy is to copy the template from the reader to wrapped stream
+ // until a tag is found. Depending on its value, the appropriate content is copied
+ // to the wrapped stream.
+ // The copy from template is then resumed, repeating this sequence until reading
+ // the complete template.
+
+ macro_rules! tags {
+ (
+ match $part:ident {
+ $( $tag:expr => $action:stmt )*
+ }
+ ) => {
+ match $part {
+ $(
+ part if part.starts_with(concat!($tag, "}")) => {
+ $action
+ let rest = &part[$tag.len()+1..];
+ self.none(rest)?;
+ }
+ )*
+
+ // Unknown tag, write it back.
+ part => {
+ self.none("{")?;
+ self.none(part)?;
+ }
+ }
+ };
+ }
+
+ let mut parts = template.split('{');
+ if let Some(first) = parts.next() {
+ self.none(first)?;
+ }
+
+ for part in parts {
+ tags! {
+ match part {
+ "name" => {
+ self.write_display_name()?;
+ }
+ "bin" => {
+ self.write_bin_name()?;
+ }
+ "version" => {
+ self.write_version()?;
+ }
+ "author" => {
+ self.write_author(false, false)?;
+ }
+ "author-with-newline" => {
+ self.write_author(false, true)?;
+ }
+ "author-section" => {
+ self.write_author(true, true)?;
+ }
+ "about" => {
+ self.write_about(false, false)?;
+ }
+ "about-with-newline" => {
+ self.write_about(false, true)?;
+ }
+ "about-section" => {
+ self.write_about(true, true)?;
+ }
+ "usage-heading" => {
+ self.warning("USAGE:")?;
+ }
+ "usage" => {
+ self.none(self.usage.create_usage_no_title(&[]))?;
+ }
+ "all-args" => {
+ self.write_all_args()?;
+ }
+ "options" => {
+ // Include even those with a heading as we don't have a good way of
+ // handling help_heading in the template.
+ self.write_args(&self.cmd.get_non_positionals().collect::<Vec<_>>(), "options")?;
+ }
+ "positionals" => {
+ self.write_args(&self.cmd.get_positionals().collect::<Vec<_>>(), "positionals")?;
+ }
+ "subcommands" => {
+ self.write_subcommands(self.cmd)?;
+ }
+ "after-help" => {
+ self.write_after_help()?;
+ }
+ "before-help" => {
+ self.write_before_help()?;
+ }
+ }
+ }
+ }
+
+ Ok(())
+ }
+}
+
+pub(crate) fn dimensions() -> Option<(usize, usize)> {
+ #[cfg(not(feature = "wrap_help"))]
+ return None;
+
+ #[cfg(feature = "wrap_help")]
+ terminal_size::terminal_size().map(|(w, h)| (w.0.into(), h.0.into()))
+}
+
+const TAB: &str = " ";
+const TAB_WIDTH: usize = 4;
+
+pub(crate) enum HelpWriter<'writer> {
+ Normal(&'writer mut dyn Write),
+ Buffer(&'writer mut Colorizer),
+}
+
+fn should_show_arg(use_long: bool, arg: &Arg) -> bool {
+ debug!("should_show_arg: use_long={:?}, arg={}", use_long, arg.name);
+ if arg.is_hide_set() {
+ return false;
+ }
+ (!arg.is_hide_long_help_set() && use_long)
+ || (!arg.is_hide_short_help_set() && !use_long)
+ || arg.is_next_line_help_set()
+}
+
+fn should_show_subcommand(subcommand: &Command) -> bool {
+ !subcommand.is_hide_set()
+}
+
+fn text_wrapper(help: &str, width: usize) -> String {
+ let wrapper = textwrap::Options::new(width)
+ .break_words(false)
+ .word_splitter(textwrap::WordSplitter::NoHyphenation);
+ help.lines()
+ .map(|line| textwrap::fill(line, &wrapper))
+ .collect::<Vec<String>>()
+ .join("\n")
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn wrap_help_last_word() {
+ let help = String::from("foo bar baz");
+ assert_eq!(text_wrapper(&help, 5), "foo\nbar\nbaz");
+ }
+
+ #[test]
+ fn display_width_handles_non_ascii() {
+ // Popular Danish tongue-twister, the name of a fruit dessert.
+ let text = "rødgrød med fløde";
+ assert_eq!(display_width(text), 17);
+ // Note that the string width is smaller than the string
+ // length. This is due to the precomposed non-ASCII letters:
+ assert_eq!(text.len(), 20);
+ }
+
+ #[test]
+ fn display_width_handles_emojis() {
+ let text = "😂";
+ // There is a single `char`...
+ assert_eq!(text.chars().count(), 1);
+ // but it is double-width:
+ assert_eq!(display_width(text), 2);
+ // This is much less than the byte length:
+ assert_eq!(text.len(), 4);
+ }
+}
diff --git a/3.2.23/src/output/mod.rs b/3.2.23/src/output/mod.rs
new file mode 100644
index 0000000..e32aac2
--- /dev/null
+++ b/3.2.23/src/output/mod.rs
@@ -0,0 +1,7 @@
+mod help;
+mod usage;
+
+pub(crate) mod fmt;
+
+pub(crate) use self::help::{Help, HelpWriter};
+pub(crate) use self::usage::Usage;
diff --git a/3.2.23/src/output/usage.rs b/3.2.23/src/output/usage.rs
new file mode 100644
index 0000000..6f7a2ca
--- /dev/null
+++ b/3.2.23/src/output/usage.rs
@@ -0,0 +1,449 @@
+use indexmap::IndexSet;
+
+// Internal
+use crate::builder::AppSettings as AS;
+use crate::builder::{Arg, ArgPredicate, Command};
+use crate::parser::ArgMatcher;
+use crate::util::ChildGraph;
+use crate::util::Id;
+use crate::INTERNAL_ERROR_MSG;
+
+pub(crate) struct Usage<'help, 'cmd> {
+ cmd: &'cmd Command<'help>,
+ required: Option<&'cmd ChildGraph<Id>>,
+}
+
+impl<'help, 'cmd> Usage<'help, 'cmd> {
+ pub(crate) fn new(cmd: &'cmd Command<'help>) -> Self {
+ Usage {
+ cmd,
+ required: None,
+ }
+ }
+
+ pub(crate) fn required(mut self, required: &'cmd ChildGraph<Id>) -> Self {
+ self.required = Some(required);
+ self
+ }
+
+ // Creates a usage string for display. This happens just after all arguments were parsed, but before
+ // any subcommands have been parsed (so as to give subcommands their own usage recursively)
+ pub(crate) fn create_usage_with_title(&self, used: &[Id]) -> String {
+ debug!("Usage::create_usage_with_title");
+ let mut usage = String::with_capacity(75);
+ usage.push_str("USAGE:\n ");
+ usage.push_str(&*self.create_usage_no_title(used));
+ usage
+ }
+
+ // Creates a usage string (*without title*) if one was not provided by the user manually.
+ pub(crate) fn create_usage_no_title(&self, used: &[Id]) -> String {
+ debug!("Usage::create_usage_no_title");
+ if let Some(u) = self.cmd.get_override_usage() {
+ String::from(&*u)
+ } else if used.is_empty() {
+ self.create_help_usage(true)
+ } else {
+ self.create_smart_usage(used)
+ }
+ }
+
+ // Creates a usage string for display in help messages (i.e. not for errors)
+ fn create_help_usage(&self, incl_reqs: bool) -> String {
+ debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs);
+ let mut usage = String::with_capacity(75);
+ let name = self
+ .cmd
+ .get_usage_name()
+ .or_else(|| self.cmd.get_bin_name())
+ .unwrap_or_else(|| self.cmd.get_name());
+ usage.push_str(name);
+ let req_string = if incl_reqs {
+ self.get_required_usage_from(&[], None, false)
+ .iter()
+ .fold(String::new(), |a, s| a + " " + s)
+ } else {
+ String::new()
+ };
+
+ if self.needs_options_tag() {
+ usage.push_str(" [OPTIONS]");
+ }
+
+ let allow_missing_positional = self.cmd.is_allow_missing_positional_set();
+ if !allow_missing_positional {
+ usage.push_str(&req_string);
+ }
+
+ let has_last = self.cmd.get_positionals().any(|p| p.is_last_set());
+ // places a '--' in the usage string if there are args and options
+ // supporting multiple values
+ if self
+ .cmd
+ .get_non_positionals()
+ .any(|o| o.is_multiple_values_set())
+ && self.cmd.get_positionals().any(|p| !p.is_required_set())
+ && !(self.cmd.has_visible_subcommands() || self.cmd.is_allow_external_subcommands_set())
+ && !has_last
+ {
+ usage.push_str(" [--]");
+ }
+ let not_req_or_hidden =
+ |p: &Arg| (!p.is_required_set() || p.is_last_set()) && !p.is_hide_set();
+ if self.cmd.get_positionals().any(not_req_or_hidden) {
+ if let Some(args_tag) = self.get_args_tag(incl_reqs) {
+ usage.push_str(&*args_tag);
+ } else {
+ usage.push_str(" [ARGS]");
+ }
+ if has_last && incl_reqs {
+ let pos = self
+ .cmd
+ .get_positionals()
+ .find(|p| p.is_last_set())
+ .expect(INTERNAL_ERROR_MSG);
+ debug!("Usage::create_help_usage: '{}' has .last(true)", pos.name);
+ let req = pos.is_required_set();
+ if req && self.cmd.get_positionals().any(|p| !p.is_required_set()) {
+ usage.push_str(" -- <");
+ } else if req {
+ usage.push_str(" [--] <");
+ } else {
+ usage.push_str(" [-- <");
+ }
+ usage.push_str(&*pos.name_no_brackets());
+ usage.push('>');
+ usage.push_str(pos.multiple_str());
+ if !req {
+ usage.push(']');
+ }
+ }
+ }
+
+ if allow_missing_positional {
+ usage.push_str(&req_string);
+ }
+
+ // incl_reqs is only false when this function is called recursively
+ if self.cmd.has_visible_subcommands() && incl_reqs
+ || self.cmd.is_allow_external_subcommands_set()
+ {
+ let placeholder = self.cmd.get_subcommand_value_name().unwrap_or("SUBCOMMAND");
+ #[allow(deprecated)]
+ if self.cmd.is_subcommand_negates_reqs_set()
+ || self.cmd.is_args_conflicts_with_subcommands_set()
+ {
+ usage.push_str("\n ");
+ if !self.cmd.is_args_conflicts_with_subcommands_set() {
+ usage.push_str(&*self.create_help_usage(false));
+ } else {
+ usage.push_str(&*name);
+ }
+ usage.push_str(" <");
+ usage.push_str(placeholder);
+ usage.push('>');
+ } else if self.cmd.is_subcommand_required_set()
+ || self.cmd.is_set(AS::SubcommandRequiredElseHelp)
+ {
+ usage.push_str(" <");
+ usage.push_str(placeholder);
+ usage.push('>');
+ } else {
+ usage.push_str(" [");
+ usage.push_str(placeholder);
+ usage.push(']');
+ }
+ }
+ let usage = usage.trim().to_owned();
+ debug!("Usage::create_help_usage: usage={}", usage);
+ usage
+ }
+
+ // Creates a context aware usage string, or "smart usage" from currently used
+ // args, and requirements
+ fn create_smart_usage(&self, used: &[Id]) -> String {
+ debug!("Usage::create_smart_usage");
+ let mut usage = String::with_capacity(75);
+
+ let r_string = self
+ .get_required_usage_from(used, None, true)
+ .iter()
+ .fold(String::new(), |acc, s| acc + " " + s);
+
+ usage.push_str(
+ self.cmd
+ .get_usage_name()
+ .or_else(|| self.cmd.get_bin_name())
+ .unwrap_or_else(|| self.cmd.get_name()),
+ );
+ usage.push_str(&*r_string);
+ if self.cmd.is_subcommand_required_set() {
+ usage.push_str(" <");
+ usage.push_str(self.cmd.get_subcommand_value_name().unwrap_or("SUBCOMMAND"));
+ usage.push('>');
+ }
+ usage.shrink_to_fit();
+ usage
+ }
+
+ // Gets the `[ARGS]` tag for the usage string
+ fn get_args_tag(&self, incl_reqs: bool) -> Option<String> {
+ debug!("Usage::get_args_tag; incl_reqs = {:?}", incl_reqs);
+ let mut count = 0;
+ for pos in self
+ .cmd
+ .get_positionals()
+ .filter(|pos| !pos.is_required_set())
+ .filter(|pos| !pos.is_hide_set())
+ .filter(|pos| !pos.is_last_set())
+ {
+ debug!("Usage::get_args_tag:iter:{}", pos.name);
+ let required = self.cmd.groups_for_arg(&pos.id).any(|grp_s| {
+ debug!("Usage::get_args_tag:iter:{:?}:iter:{:?}", pos.name, grp_s);
+ // if it's part of a required group we don't want to count it
+ self.cmd.get_groups().any(|g| g.required && (g.id == grp_s))
+ });
+ if !required {
+ count += 1;
+ debug!(
+ "Usage::get_args_tag:iter: {} Args not required or hidden",
+ count
+ );
+ }
+ }
+
+ if !self.cmd.is_dont_collapse_args_in_usage_set() && count > 1 {
+ debug!("Usage::get_args_tag:iter: More than one, returning [ARGS]");
+
+ // [ARGS]
+ None
+ } else if count == 1 && incl_reqs {
+ let pos = self
+ .cmd
+ .get_positionals()
+ .find(|pos| {
+ !pos.is_required_set()
+ && !pos.is_hide_set()
+ && !pos.is_last_set()
+ && !self.cmd.groups_for_arg(&pos.id).any(|grp_s| {
+ debug!("Usage::get_args_tag:iter:{:?}:iter:{:?}", pos.name, grp_s);
+ // if it's part of a required group we don't want to count it
+ self.cmd.get_groups().any(|g| g.required && (g.id == grp_s))
+ })
+ })
+ .expect(INTERNAL_ERROR_MSG);
+
+ debug!(
+ "Usage::get_args_tag:iter: Exactly one, returning '{}'",
+ pos.name
+ );
+
+ Some(format!(
+ " [{}]{}",
+ pos.name_no_brackets(),
+ pos.multiple_str()
+ ))
+ } else if self.cmd.is_dont_collapse_args_in_usage_set()
+ && self.cmd.has_positionals()
+ && incl_reqs
+ {
+ debug!("Usage::get_args_tag:iter: Don't collapse returning all");
+ Some(
+ self.cmd
+ .get_positionals()
+ .filter(|pos| !pos.is_required_set())
+ .filter(|pos| !pos.is_hide_set())
+ .filter(|pos| !pos.is_last_set())
+ .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str()))
+ .collect::<Vec<_>>()
+ .join(""),
+ )
+ } else if !incl_reqs {
+ debug!("Usage::get_args_tag:iter: incl_reqs=false, building secondary usage string");
+ let highest_req_pos = self
+ .cmd
+ .get_positionals()
+ .filter_map(|pos| {
+ if pos.is_required_set() && !pos.is_last_set() {
+ Some(pos.index)
+ } else {
+ None
+ }
+ })
+ .max()
+ .unwrap_or_else(|| Some(self.cmd.get_positionals().count()));
+ Some(
+ self.cmd
+ .get_positionals()
+ .filter(|pos| pos.index <= highest_req_pos)
+ .filter(|pos| !pos.is_required_set())
+ .filter(|pos| !pos.is_hide_set())
+ .filter(|pos| !pos.is_last_set())
+ .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str()))
+ .collect::<Vec<_>>()
+ .join(""),
+ )
+ } else {
+ Some("".into())
+ }
+ }
+
+ // Determines if we need the `[OPTIONS]` tag in the usage string
+ fn needs_options_tag(&self) -> bool {
+ debug!("Usage::needs_options_tag");
+ 'outer: for f in self.cmd.get_non_positionals() {
+ debug!("Usage::needs_options_tag:iter: f={}", f.name);
+
+ // Don't print `[OPTIONS]` just for help or version
+ if f.long == Some("help") || f.long == Some("version") {
+ debug!("Usage::needs_options_tag:iter Option is built-in");
+ continue;
+ }
+
+ if f.is_hide_set() {
+ debug!("Usage::needs_options_tag:iter Option is hidden");
+ continue;
+ }
+ if f.is_required_set() {
+ debug!("Usage::needs_options_tag:iter Option is required");
+ continue;
+ }
+ for grp_s in self.cmd.groups_for_arg(&f.id) {
+ debug!("Usage::needs_options_tag:iter:iter: grp_s={:?}", grp_s);
+ if self.cmd.get_groups().any(|g| g.id == grp_s && g.required) {
+ debug!("Usage::needs_options_tag:iter:iter: Group is required");
+ continue 'outer;
+ }
+ }
+
+ debug!("Usage::needs_options_tag:iter: [OPTIONS] required");
+ return true;
+ }
+
+ debug!("Usage::needs_options_tag: [OPTIONS] not required");
+ false
+ }
+
+ // Returns the required args in usage string form by fully unrolling all groups
+ // `incl_last`: should we include args that are Arg::Last? (i.e. `prog [foo] -- [last]). We
+ // can't do that for required usages being built for subcommands because it would look like:
+ // `prog [foo] -- [last] <subcommand>` which is totally wrong.
+ pub(crate) fn get_required_usage_from(
+ &self,
+ incls: &[Id],
+ matcher: Option<&ArgMatcher>,
+ incl_last: bool,
+ ) -> IndexSet<String> {
+ debug!(
+ "Usage::get_required_usage_from: incls={:?}, matcher={:?}, incl_last={:?}",
+ incls,
+ matcher.is_some(),
+ incl_last
+ );
+ let mut ret_val = IndexSet::new();
+
+ let mut unrolled_reqs = IndexSet::new();
+
+ let required_owned;
+ let required = if let Some(required) = self.required {
+ required
+ } else {
+ required_owned = self.cmd.required_graph();
+ &required_owned
+ };
+
+ for a in required.iter() {
+ let is_relevant = |(val, req_arg): &(ArgPredicate<'_>, Id)| -> Option<Id> {
+ let required = match val {
+ ArgPredicate::Equals(_) => {
+ if let Some(matcher) = matcher {
+ matcher.check_explicit(a, *val)
+ } else {
+ false
+ }
+ }
+ ArgPredicate::IsPresent => true,
+ };
+ required.then(|| req_arg.clone())
+ };
+
+ for aa in self.cmd.unroll_arg_requires(is_relevant, a) {
+ // if we don't check for duplicates here this causes duplicate error messages
+ // see https://github.com/clap-rs/clap/issues/2770
+ unrolled_reqs.insert(aa);
+ }
+ // always include the required arg itself. it will not be enumerated
+ // by unroll_requirements_for_arg.
+ unrolled_reqs.insert(a.clone());
+ }
+
+ debug!(
+ "Usage::get_required_usage_from: unrolled_reqs={:?}",
+ unrolled_reqs
+ );
+
+ 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()),
+ );
+ }
+ }
+ }
+
+ 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);
+ }
+ }
+
+ debug!("Usage::get_required_usage_from: ret_val={:?}", ret_val);
+ ret_val
+ }
+}
diff --git a/3.2.23/src/parser/arg_matcher.rs b/3.2.23/src/parser/arg_matcher.rs
new file mode 100644
index 0000000..22087e7
--- /dev/null
+++ b/3.2.23/src/parser/arg_matcher.rs
@@ -0,0 +1,280 @@
+// Std
+use std::collections::HashMap;
+use std::ffi::OsString;
+use std::mem;
+use std::ops::Deref;
+
+// Internal
+use crate::builder::{Arg, ArgPredicate, Command};
+use crate::parser::AnyValue;
+use crate::parser::Identifier;
+use crate::parser::PendingArg;
+use crate::parser::{ArgMatches, MatchedArg, SubCommand, ValueSource};
+use crate::util::Id;
+use crate::INTERNAL_ERROR_MSG;
+
+#[derive(Debug, Default)]
+pub(crate) struct ArgMatcher {
+ matches: ArgMatches,
+ pending: Option<PendingArg>,
+}
+
+impl ArgMatcher {
+ pub(crate) fn new(_cmd: &Command) -> Self {
+ ArgMatcher {
+ matches: ArgMatches {
+ #[cfg(debug_assertions)]
+ valid_args: {
+ let args = _cmd.get_arguments().map(|a| a.id.clone());
+ let groups = _cmd.get_groups().map(|g| g.id.clone());
+ args.chain(groups).collect()
+ },
+ #[cfg(debug_assertions)]
+ valid_subcommands: _cmd.get_subcommands().map(|sc| sc.get_id()).collect(),
+ // HACK: Allow an external subcommand's ArgMatches be a stand-in for any ArgMatches
+ // since users can't detect it and avoid the asserts.
+ //
+ // See clap-rs/clap#3263
+ #[cfg(debug_assertions)]
+ #[cfg(not(feature = "unstable-v4"))]
+ disable_asserts: _cmd.is_allow_external_subcommands_set(),
+ #[cfg(debug_assertions)]
+ #[cfg(feature = "unstable-v4")]
+ disable_asserts: false,
+ ..Default::default()
+ },
+ pending: None,
+ }
+ }
+
+ pub(crate) fn into_inner(self) -> ArgMatches {
+ self.matches
+ }
+
+ pub(crate) fn propagate_globals(&mut self, global_arg_vec: &[Id]) {
+ debug!(
+ "ArgMatcher::get_global_values: global_arg_vec={:?}",
+ global_arg_vec
+ );
+ let mut vals_map = HashMap::new();
+ self.fill_in_global_values(global_arg_vec, &mut vals_map);
+ }
+
+ fn fill_in_global_values(
+ &mut self,
+ global_arg_vec: &[Id],
+ vals_map: &mut HashMap<Id, MatchedArg>,
+ ) {
+ for global_arg in global_arg_vec {
+ if let Some(ma) = self.get(global_arg) {
+ // We have to check if the parent's global arg wasn't used but still exists
+ // such as from a default value.
+ //
+ // For example, `myprog subcommand --global-arg=value` where `--global-arg` defines
+ // 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.source() > ma.source() {
+ parent_ma
+ } else {
+ ma
+ }
+ } else {
+ ma
+ }
+ .clone();
+ vals_map.insert(global_arg.clone(), to_update);
+ }
+ }
+ if let Some(ref mut sc) = self.matches.subcommand {
+ let mut am = ArgMatcher {
+ matches: mem::take(&mut sc.matches),
+ pending: None,
+ };
+ am.fill_in_global_values(global_arg_vec, vals_map);
+ mem::swap(&mut am.matches, &mut sc.matches);
+ }
+
+ for (name, matched_arg) in vals_map.iter_mut() {
+ self.matches.args.insert(name.clone(), matched_arg.clone());
+ }
+ }
+
+ pub(crate) fn get(&self, arg: &Id) -> Option<&MatchedArg> {
+ self.matches.args.get(arg)
+ }
+
+ pub(crate) fn get_mut(&mut self, arg: &Id) -> Option<&mut MatchedArg> {
+ self.matches.args.get_mut(arg)
+ }
+
+ pub(crate) fn remove(&mut self, arg: &Id) {
+ self.matches.args.swap_remove(arg);
+ }
+
+ pub(crate) fn contains(&self, arg: &Id) -> bool {
+ self.matches.args.contains_key(arg)
+ }
+
+ pub(crate) fn arg_ids(&self) -> indexmap::map::Keys<Id, MatchedArg> {
+ self.matches.args.keys()
+ }
+
+ pub(crate) fn entry(&mut self, arg: &Id) -> indexmap::map::Entry<Id, MatchedArg> {
+ self.matches.args.entry(arg.clone())
+ }
+
+ pub(crate) fn subcommand(&mut self, sc: SubCommand) {
+ self.matches.subcommand = Some(Box::new(sc));
+ }
+
+ pub(crate) fn subcommand_name(&self) -> Option<&str> {
+ self.matches.subcommand_name()
+ }
+
+ pub(crate) fn iter(&self) -> indexmap::map::Iter<Id, MatchedArg> {
+ self.matches.args.iter()
+ }
+
+ pub(crate) fn check_explicit<'a>(&self, arg: &Id, predicate: ArgPredicate<'a>) -> bool {
+ self.get(arg).map_or(false, |a| a.check_explicit(predicate))
+ }
+
+ pub(crate) fn start_custom_arg(&mut self, arg: &Arg, source: ValueSource) {
+ let id = &arg.id;
+ debug!(
+ "ArgMatcher::start_custom_arg: id={:?}, source={:?}",
+ id, source
+ );
+ let ma = self.entry(id).or_insert(MatchedArg::new_arg(arg));
+ debug_assert_eq!(ma.type_id(), Some(arg.get_value_parser().type_id()));
+ ma.set_source(source);
+ ma.new_val_group();
+ }
+
+ pub(crate) fn start_custom_group(&mut self, id: &Id, source: ValueSource) {
+ debug!(
+ "ArgMatcher::start_custom_arg: id={:?}, source={:?}",
+ id, source
+ );
+ let ma = self.entry(id).or_insert(MatchedArg::new_group());
+ debug_assert_eq!(ma.type_id(), None);
+ ma.set_source(source);
+ ma.new_val_group();
+ }
+
+ pub(crate) fn start_occurrence_of_arg(&mut self, arg: &Arg) {
+ let id = &arg.id;
+ debug!("ArgMatcher::start_occurrence_of_arg: id={:?}", id);
+ let ma = self.entry(id).or_insert(MatchedArg::new_arg(arg));
+ debug_assert_eq!(ma.type_id(), Some(arg.get_value_parser().type_id()));
+ ma.set_source(ValueSource::CommandLine);
+ #[allow(deprecated)]
+ ma.inc_occurrences();
+ ma.new_val_group();
+ }
+
+ pub(crate) fn start_occurrence_of_group(&mut self, id: &Id) {
+ debug!("ArgMatcher::start_occurrence_of_group: id={:?}", id);
+ let ma = self.entry(id).or_insert(MatchedArg::new_group());
+ debug_assert_eq!(ma.type_id(), None);
+ ma.set_source(ValueSource::CommandLine);
+ #[allow(deprecated)]
+ ma.inc_occurrences();
+ ma.new_val_group();
+ }
+
+ pub(crate) fn start_occurrence_of_external(&mut self, cmd: &crate::Command) {
+ let id = &Id::empty_hash();
+ debug!("ArgMatcher::start_occurrence_of_external: id={:?}", id,);
+ let ma = self.entry(id).or_insert(MatchedArg::new_external(cmd));
+ debug_assert_eq!(
+ ma.type_id(),
+ Some(
+ cmd.get_external_subcommand_value_parser()
+ .expect(INTERNAL_ERROR_MSG)
+ .type_id()
+ )
+ );
+ ma.set_source(ValueSource::CommandLine);
+ #[allow(deprecated)]
+ ma.inc_occurrences();
+ ma.new_val_group();
+ }
+
+ pub(crate) fn add_val_to(&mut self, arg: &Id, val: AnyValue, raw_val: OsString) {
+ let ma = self.get_mut(arg).expect(INTERNAL_ERROR_MSG);
+ ma.append_val(val, raw_val);
+ }
+
+ pub(crate) fn add_index_to(&mut self, arg: &Id, idx: usize) {
+ let ma = self.get_mut(arg).expect(INTERNAL_ERROR_MSG);
+ ma.push_index(idx);
+ }
+
+ pub(crate) fn needs_more_vals(&self, o: &Arg) -> bool {
+ let num_resolved = self.get(&o.id).map(|ma| ma.num_vals()).unwrap_or(0);
+ let num_pending = self
+ .pending
+ .as_ref()
+ .and_then(|p| (p.id == o.id).then(|| p.raw_vals.len()))
+ .unwrap_or(0);
+ let current_num = num_resolved + num_pending;
+ debug!(
+ "ArgMatcher::needs_more_vals: o={}, resolved={}, pending={}",
+ o.name, num_resolved, num_pending
+ );
+ if current_num == 0 {
+ true
+ } else if let Some(num) = o.num_vals {
+ debug!("ArgMatcher::needs_more_vals: num_vals...{}", num);
+ #[allow(deprecated)]
+ if o.is_multiple_occurrences_set() {
+ (current_num % num) != 0
+ } else {
+ num != current_num
+ }
+ } else if let Some(num) = o.max_vals {
+ debug!("ArgMatcher::needs_more_vals: max_vals...{}", num);
+ current_num < num
+ } else if o.min_vals.is_some() {
+ debug!("ArgMatcher::needs_more_vals: min_vals...true");
+ true
+ } else {
+ o.is_multiple_values_set()
+ }
+ }
+
+ pub(crate) fn pending_arg_id(&self) -> Option<&Id> {
+ self.pending.as_ref().map(|p| &p.id)
+ }
+
+ pub(crate) fn pending_values_mut(
+ &mut self,
+ id: &Id,
+ ident: Option<Identifier>,
+ ) -> &mut Vec<OsString> {
+ let pending = self.pending.get_or_insert_with(|| PendingArg {
+ id: id.clone(),
+ ident,
+ raw_vals: Default::default(),
+ });
+ debug_assert_eq!(pending.id, *id, "{}", INTERNAL_ERROR_MSG);
+ if ident.is_some() {
+ debug_assert_eq!(pending.ident, ident, "{}", INTERNAL_ERROR_MSG);
+ }
+ &mut pending.raw_vals
+ }
+
+ pub(crate) fn take_pending(&mut self) -> Option<PendingArg> {
+ self.pending.take()
+ }
+}
+
+impl Deref for ArgMatcher {
+ type Target = ArgMatches;
+
+ fn deref(&self) -> &Self::Target {
+ &self.matches
+ }
+}
diff --git a/3.2.23/src/parser/error.rs b/3.2.23/src/parser/error.rs
new file mode 100644
index 0000000..caeba4b
--- /dev/null
+++ b/3.2.23/src/parser/error.rs
@@ -0,0 +1,67 @@
+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")
+ }
+ }
+ }
+}
+
+#[test]
+fn check_auto_traits() {
+ static_assertions::assert_impl_all!(
+ MatchesError: Send,
+ Sync,
+ std::panic::RefUnwindSafe,
+ std::panic::UnwindSafe,
+ Unpin
+ );
+}
diff --git a/3.2.23/src/parser/features/mod.rs b/3.2.23/src/parser/features/mod.rs
new file mode 100644
index 0000000..bdeb766
--- /dev/null
+++ b/3.2.23/src/parser/features/mod.rs
@@ -0,0 +1 @@
+pub(crate) mod suggestions;
diff --git a/3.2.23/src/parser/features/suggestions.rs b/3.2.23/src/parser/features/suggestions.rs
new file mode 100644
index 0000000..9e46f3c
--- /dev/null
+++ b/3.2.23/src/parser/features/suggestions.rs
@@ -0,0 +1,105 @@
+#[cfg(feature = "suggestions")]
+use std::cmp::Ordering;
+
+// Internal
+use crate::builder::Command;
+
+/// Produces multiple strings from a given list of possible values which are similar
+/// to the passed in value `v` within a certain confidence by least confidence.
+/// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield
+/// `Some("foo")`, whereas "blark" would yield `None`.
+#[cfg(feature = "suggestions")]
+pub(crate) fn did_you_mean<T, I>(v: &str, possible_values: I) -> Vec<String>
+where
+ T: AsRef<str>,
+ I: IntoIterator<Item = T>,
+{
+ let mut candidates: Vec<(f64, String)> = possible_values
+ .into_iter()
+ .map(|pv| (strsim::jaro_winkler(v, pv.as_ref()), pv.as_ref().to_owned()))
+ .filter(|(confidence, _)| *confidence > 0.8)
+ .collect();
+ candidates.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal));
+ candidates.into_iter().map(|(_, pv)| pv).collect()
+}
+
+#[cfg(not(feature = "suggestions"))]
+pub(crate) fn did_you_mean<T, I>(_: &str, _: I) -> Vec<String>
+where
+ T: AsRef<str>,
+ I: IntoIterator<Item = T>,
+{
+ Vec::new()
+}
+
+/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase
+pub(crate) fn did_you_mean_flag<'a, 'help, I, T>(
+ arg: &str,
+ remaining_args: &[&str],
+ longs: I,
+ subcommands: impl IntoIterator<Item = &'a mut Command<'help>>,
+) -> Option<(String, Option<String>)>
+where
+ 'help: 'a,
+ T: AsRef<str>,
+ I: IntoIterator<Item = T>,
+{
+ use crate::mkeymap::KeyType;
+
+ match did_you_mean(arg, longs).pop() {
+ Some(candidate) => Some((candidate, None)),
+ None => subcommands
+ .into_iter()
+ .filter_map(|subcommand| {
+ subcommand._build_self();
+
+ let longs = subcommand.get_keymap().keys().filter_map(|a| {
+ if let KeyType::Long(v) = a {
+ Some(v.to_string_lossy().into_owned())
+ } else {
+ None
+ }
+ });
+
+ let subcommand_name = subcommand.get_name();
+
+ let candidate = did_you_mean(arg, longs).pop()?;
+ let score = remaining_args.iter().position(|x| *x == subcommand_name)?;
+ Some((score, (candidate, Some(subcommand_name.to_string()))))
+ })
+ .min_by_key(|(x, _)| *x)
+ .map(|(_, suggestion)| suggestion),
+ }
+}
+
+#[cfg(all(test, features = "suggestions"))]
+mod test {
+ use super::*;
+
+ #[test]
+ fn possible_values_match() {
+ let p_vals = ["test", "possible", "values"];
+ assert_eq!(did_you_mean("tst", p_vals.iter()), Some("test"));
+ }
+
+ #[test]
+ fn possible_values_match() {
+ let p_vals = ["test", "temp"];
+ assert_eq!(did_you_mean("te", p_vals.iter()), Some("test"));
+ }
+
+ #[test]
+ fn possible_values_nomatch() {
+ let p_vals = ["test", "possible", "values"];
+ assert!(did_you_mean("hahaahahah", p_vals.iter()).is_none());
+ }
+
+ #[test]
+ fn flag() {
+ let p_vals = ["test", "possible", "values"];
+ assert_eq!(
+ did_you_mean_flag("tst", p_vals.iter(), []),
+ Some(("test", None))
+ );
+ }
+}
diff --git a/3.2.23/src/parser/matches/any_value.rs b/3.2.23/src/parser/matches/any_value.rs
new file mode 100644
index 0000000..a9277e7
--- /dev/null
+++ b/3.2.23/src/parser/matches/any_value.rs
@@ -0,0 +1,112 @@
+#[derive(Clone)]
+pub(crate) struct AnyValue {
+ inner: std::sync::Arc<dyn std::any::Any + Send + Sync + 'static>,
+ // While we can extract `TypeId` from `inner`, the debug repr is of a number, so let's track
+ // the type_name in debug builds.
+ id: AnyValueId,
+}
+
+impl AnyValue {
+ pub(crate) fn new<V: std::any::Any + Clone + Send + Sync + 'static>(inner: V) -> Self {
+ let id = AnyValueId::of::<V>();
+ let inner = std::sync::Arc::new(inner);
+ Self { inner, id }
+ }
+
+ pub(crate) fn downcast_ref<T: std::any::Any + Clone + Send + Sync + 'static>(
+ &self,
+ ) -> Option<&T> {
+ self.inner.downcast_ref::<T>()
+ }
+
+ pub(crate) fn downcast_into<T: std::any::Any + Clone + Send + Sync>(self) -> Result<T, Self> {
+ let id = self.id;
+ let value =
+ std::sync::Arc::downcast::<T>(self.inner).map_err(|inner| Self { inner, id })?;
+ let value = std::sync::Arc::try_unwrap(value).unwrap_or_else(|arc| (*arc).clone());
+ Ok(value)
+ }
+
+ pub(crate) fn type_id(&self) -> AnyValueId {
+ self.id
+ }
+}
+
+impl std::fmt::Debug for AnyValue {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
+ f.debug_struct("AnyValue").field("inner", &self.id).finish()
+ }
+}
+
+#[derive(Copy, Clone)]
+pub struct AnyValueId {
+ type_id: std::any::TypeId,
+ #[cfg(debug_assertions)]
+ type_name: &'static str,
+}
+
+impl AnyValueId {
+ pub(crate) fn of<A: ?Sized + 'static>() -> Self {
+ Self {
+ type_id: std::any::TypeId::of::<A>(),
+ #[cfg(debug_assertions)]
+ type_name: std::any::type_name::<A>(),
+ }
+ }
+}
+
+impl PartialEq for AnyValueId {
+ fn eq(&self, other: &Self) -> bool {
+ self.type_id == other.type_id
+ }
+}
+
+impl Eq for AnyValueId {}
+
+impl PartialOrd for AnyValueId {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ self.type_id.partial_cmp(&other.type_id)
+ }
+}
+
+impl Ord for AnyValueId {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ self.type_id.cmp(&other.type_id)
+ }
+}
+
+impl std::hash::Hash for AnyValueId {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.type_id.hash(state);
+ }
+}
+
+impl std::fmt::Debug for AnyValueId {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
+ #[cfg(not(debug_assertions))]
+ {
+ self.type_id.fmt(f)
+ }
+ #[cfg(debug_assertions)]
+ {
+ f.debug_struct(self.type_name).finish()
+ }
+ }
+}
+
+impl<'a, A: ?Sized + 'static> From<&'a A> for AnyValueId {
+ fn from(_: &'a A) -> Self {
+ Self::of::<A>()
+ }
+}
+
+#[cfg(test)]
+mod test {
+ #[test]
+ #[cfg(debug_assertions)]
+ fn debug_impl() {
+ use super::*;
+
+ assert_eq!(format!("{:?}", AnyValue::new(5)), "AnyValue { inner: i32 }");
+ }
+}
diff --git a/3.2.23/src/parser/matches/arg_matches.rs b/3.2.23/src/parser/matches/arg_matches.rs
new file mode 100644
index 0000000..753443e
--- /dev/null
+++ b/3.2.23/src/parser/matches/arg_matches.rs
@@ -0,0 +1,1980 @@
+// Std
+use std::any::Any;
+use std::borrow::Cow;
+use std::ffi::{OsStr, OsString};
+use std::fmt::{Debug, Display};
+use std::iter::{Cloned, Flatten, Map};
+use std::slice::Iter;
+use std::str::FromStr;
+
+// Third Party
+use indexmap::IndexMap;
+
+// Internal
+use crate::parser::AnyValue;
+use crate::parser::AnyValueId;
+use crate::parser::MatchedArg;
+use crate::parser::MatchesError;
+use crate::parser::ValueSource;
+use crate::util::{Id, Key};
+use crate::Error;
+use crate::INTERNAL_ERROR_MSG;
+
+/// Container for parse results.
+///
+/// Used to get information about the arguments that were supplied to the program at runtime by
+/// the user. New instances of this struct are obtained by using the [`Command::get_matches`] family of
+/// methods.
+///
+/// # Examples
+///
+/// ```no_run
+/// # use clap::{Command, Arg, ValueSource};
+/// let matches = Command::new("MyApp")
+/// .arg(Arg::new("out")
+/// .long("output")
+/// .required(true)
+/// .takes_value(true)
+/// .default_value("-"))
+/// .arg(Arg::new("cfg")
+/// .short('c')
+/// .takes_value(true))
+/// .get_matches(); // builds the instance of ArgMatches
+///
+/// // to get information about the "cfg" argument we created, such as the value supplied we use
+/// // various ArgMatches methods, such as [ArgMatches::get_one]
+/// if let Some(c) = matches.get_one::<String>("cfg") {
+/// println!("Value for -c: {}", c);
+/// }
+///
+/// // The ArgMatches::get_one method returns an Option because the user may not have supplied
+/// // that argument at runtime. But if we specified that the argument was "required" as we did
+/// // with the "out" argument, we can safely unwrap because `clap` verifies that was actually
+/// // used at runtime.
+/// println!("Value for --output: {}", matches.get_one::<String>("out").unwrap());
+///
+/// // You can check the presence of an argument's values
+/// if matches.contains_id("out") {
+/// // However, if you want to know where the value came from
+/// if matches.value_source("out").expect("checked contains_id") == ValueSource::CommandLine {
+/// println!("`out` set by user");
+/// } else {
+/// println!("`out` is defaulted");
+/// }
+/// }
+/// ```
+/// [`Command::get_matches`]: crate::Command::get_matches()
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct ArgMatches {
+ #[cfg(debug_assertions)]
+ pub(crate) valid_args: Vec<Id>,
+ #[cfg(debug_assertions)]
+ pub(crate) valid_subcommands: Vec<Id>,
+ #[cfg(debug_assertions)]
+ pub(crate) disable_asserts: bool,
+ pub(crate) args: IndexMap<Id, MatchedArg>,
+ pub(crate) subcommand: Option<Box<SubCommand>>,
+}
+
+/// # Arguments
+impl ArgMatches {
+ /// Gets the value of a specific option or positional argument.
+ ///
+ /// i.e. an argument that [takes an additional value][crate::Arg::takes_value] at runtime.
+ ///
+ /// Returns an error if the wrong type was used.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set.
+ /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime.
+ ///
+ /// # Panic
+ ///
+ /// If the argument definition and access mismatch. To handle this case programmatically, see
+ /// [`ArgMatches::try_get_one`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, value_parser};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("port")
+ /// .value_parser(value_parser!(usize))
+ /// .takes_value(true)
+ /// .required(true))
+ /// .get_matches_from(vec!["myapp", "2020"]);
+ ///
+ /// let port: usize = *m
+ /// .get_one("port")
+ /// .expect("`port`is required");
+ /// assert_eq!(port, 2020);
+ /// ```
+ /// [option]: crate::Arg::takes_value()
+ /// [positional]: crate::Arg::index()
+ /// [`default_value`]: crate::Arg::default_value()
+ #[track_caller]
+ pub fn get_one<T: Any + Clone + Send + Sync + 'static>(&self, id: &str) -> Option<&T> {
+ let internal_id = Id::from(id);
+ 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.
+ ///
+ /// Returns an error if the wrong type was used.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// # Panic
+ ///
+ /// If the argument definition and access mismatch. To handle this case programmatically, see
+ /// [`ArgMatches::try_get_many`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, value_parser, ArgAction};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("ports")
+ /// .action(ArgAction::Append)
+ /// .value_parser(value_parser!(usize))
+ /// .short('p')
+ /// .takes_value(true)
+ /// .required(true))
+ /// .get_matches_from(vec![
+ /// "myprog", "-p", "22", "-p", "80", "-p", "2020"
+ /// ]);
+ /// let vals: Vec<usize> = m.get_many("ports")
+ /// .expect("`port`is required")
+ /// .copied()
+ /// .collect();
+ /// assert_eq!(vals, [22, 80, 2020]);
+ /// ```
+ #[track_caller]
+ pub fn get_many<T: Any + Clone + Send + Sync + 'static>(
+ &self,
+ id: &str,
+ ) -> Option<ValuesRef<T>> {
+ let internal_id = Id::from(id);
+ MatchesError::unwrap(&internal_id, self.try_get_many(id))
+ }
+
+ /// Iterate over the original argument values.
+ ///
+ /// An `OsStr` on Unix-like systems is any series of bytes, regardless of whether or not they
+ /// contain valid UTF-8. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid
+ /// filename on a Unix system as an argument value may contain invalid UTF-8.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// # Panic
+ ///
+ /// If the argument definition and access mismatch. To handle this case programmatically, see
+ /// [`ArgMatches::try_get_raw`].
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(unix), doc = " ```ignore")]
+ #[cfg_attr(unix, doc = " ```")]
+ /// # use clap::{Command, arg, value_parser};
+ /// # use std::ffi::{OsStr,OsString};
+ /// # use std::os::unix::ffi::{OsStrExt,OsStringExt};
+ /// use std::path::PathBuf;
+ ///
+ /// let m = Command::new("utf8")
+ /// .arg(arg!(<arg> ... "some arg").value_parser(value_parser!(PathBuf)))
+ /// .get_matches_from(vec![OsString::from("myprog"),
+ /// // "Hi"
+ /// OsString::from_vec(vec![b'H', b'i']),
+ /// // "{0xe9}!"
+ /// OsString::from_vec(vec![0xe9, b'!'])]);
+ ///
+ /// let mut itr = m.get_raw("arg")
+ /// .expect("`port`is required")
+ /// .into_iter();
+ /// assert_eq!(itr.next(), Some(OsStr::new("Hi")));
+ /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!'])));
+ /// assert_eq!(itr.next(), None);
+ /// ```
+ /// [`Iterator`]: std::iter::Iterator
+ /// [`OsSt`]: std::ffi::OsStr
+ /// [values]: OsValues
+ /// [`String`]: std::string::String
+ #[track_caller]
+ pub fn get_raw(&self, id: &str) -> Option<RawValues<'_>> {
+ let internal_id = Id::from(id);
+ MatchesError::unwrap(&internal_id, self.try_get_raw(id))
+ }
+
+ /// Returns the value of a specific option or positional argument.
+ ///
+ /// i.e. an argument that [takes an additional value][crate::Arg::takes_value] at runtime.
+ ///
+ /// Returns an error if the wrong type was used. No item will have been removed.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set.
+ /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime.
+ ///
+ /// # Panic
+ ///
+ /// If the argument definition and access mismatch. To handle this case programmatically, see
+ /// [`ArgMatches::try_remove_one`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, value_parser};
+ /// let mut m = Command::new("myprog")
+ /// .arg(Arg::new("file")
+ /// .required(true)
+ /// .takes_value(true))
+ /// .get_matches_from(vec![
+ /// "myprog", "file.txt",
+ /// ]);
+ /// let vals: String = m.remove_one("file")
+ /// .expect("`file`is required");
+ /// assert_eq!(vals, "file.txt");
+ /// ```
+ /// [option]: crate::Arg::takes_value()
+ /// [positional]: crate::Arg::index()
+ /// [`default_value`]: crate::Arg::default_value()
+ #[track_caller]
+ pub fn remove_one<T: Any + Clone + Send + Sync + 'static>(&mut self, id: &str) -> Option<T> {
+ let internal_id = Id::from(id);
+ MatchesError::unwrap(&internal_id, self.try_remove_one(id))
+ }
+
+ /// Return values of a specific option or positional argument.
+ ///
+ /// i.e. an argument that takes multiple values at runtime.
+ ///
+ /// Returns an error if the wrong type was used. No item will have been removed.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// # Panic
+ ///
+ /// If the argument definition and access mismatch. To handle this case programmatically, see
+ /// [`ArgMatches::try_remove_many`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, value_parser, ArgAction};
+ /// let mut m = Command::new("myprog")
+ /// .arg(Arg::new("file")
+ /// .action(ArgAction::Append)
+ /// .multiple_values(true)
+ /// .required(true)
+ /// .takes_value(true))
+ /// .get_matches_from(vec![
+ /// "myprog", "file1.txt", "file2.txt", "file3.txt", "file4.txt",
+ /// ]);
+ /// let vals: Vec<String> = m.remove_many("file")
+ /// .expect("`file`is required")
+ /// .collect();
+ /// assert_eq!(vals, ["file1.txt", "file2.txt", "file3.txt", "file4.txt"]);
+ /// ```
+ #[track_caller]
+ pub fn remove_many<T: Any + Clone + Send + Sync + 'static>(
+ &mut self,
+ id: &str,
+ ) -> Option<Values2<T>> {
+ let internal_id = Id::from(id);
+ MatchesError::unwrap(&internal_id, self.try_remove_many(id))
+ }
+
+ /// Check if values are present for the argument or group id
+ ///
+ /// *NOTE:* This will always return `true` if [`default_value`] has been set.
+ /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime.
+ ///
+ /// # Panics
+ ///
+ /// If `id` is is not a valid argument or group name. To handle this case programmatically, see
+ /// [`ArgMatches::try_contains_id`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("debug")
+ /// .short('d'))
+ /// .get_matches_from(vec![
+ /// "myprog", "-d"
+ /// ]);
+ ///
+ /// assert!(m.contains_id("debug"));
+ /// ```
+ ///
+ /// [`default_value`]: crate::Arg::default_value()
+ pub fn contains_id(&self, id: &str) -> bool {
+ let internal_id = Id::from(id);
+ MatchesError::unwrap(&internal_id, self.try_contains_id(id))
+ }
+
+ /// Check if any args were present on the command line
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let mut cmd = Command::new("myapp")
+ /// .arg(Arg::new("output")
+ /// .takes_value(true));
+ ///
+ /// let m = cmd
+ /// .try_get_matches_from_mut(vec!["myapp", "something"])
+ /// .unwrap();
+ /// assert!(m.args_present());
+ ///
+ /// let m = cmd
+ /// .try_get_matches_from_mut(vec!["myapp"])
+ /// .unwrap();
+ /// assert!(! m.args_present());
+ pub fn args_present(&self) -> bool {
+ !self.args.is_empty()
+ }
+
+ /// Deprecated, replaced with [`ArgMatches::get_one()`]
+ ///
+ /// Replace `m.value_of(...)` with `m.get_one::<String>(...).map(|s| s.as_str())`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `ArgMatches::get_one()`
+
+Replace `m.value_of(...)` with `m.get_one::<String>(...).map(|s| s.as_str())`
+"
+ )
+ )]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn value_of<T: Key>(&self, id: T) -> Option<&str> {
+ let id = Id::from(id);
+ let arg = self.get_arg(&id)?;
+ let v = unwrap_string_arg(&id, arg.first()?);
+ Some(v)
+ }
+
+ /// Deprecated, replaced with [`ArgMatches::get_one()`]
+ ///
+ /// Replace `m.value_of(...)` with `m.get_one::<String>(...).map(|s| s.as_str())`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `ArgMatches::get_one()`
+
+Replace `m.value_of(...)` with `m.get_one::<String>(...).map(|s| s.as_str())`
+"
+ )
+ )]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn value_of_lossy<T: Key>(&self, id: T) -> Option<Cow<'_, str>> {
+ let id = Id::from(id);
+ let arg = self.get_arg(&id)?;
+ let v = unwrap_os_string_arg(&id, arg.first()?);
+ Some(v.to_string_lossy())
+ }
+
+ /// Deprecated, replaced with [`ArgMatches::get_one()`]
+ ///
+ /// Replace `m.value_of(...)` with `m.get_one::<OsString>(...).map(|s| s.as_os_str())`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `ArgMatches::get_one()`
+
+Replace `m.value_of(...)` with `m.get_one::<OsString>(...).map(|s| s.as_os_str())`
+"
+ )
+ )]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn value_of_os<T: Key>(&self, id: T) -> Option<&OsStr> {
+ let id = Id::from(id);
+ let arg = self.get_arg(&id)?;
+ let v = unwrap_os_string_arg(&id, arg.first()?);
+ Some(v)
+ }
+
+ /// Deprecated, replaced with [`ArgMatches::get_many()`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `ArgMatches::get_many()`
+"
+ )
+ )]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn values_of<T: Key>(&self, id: T) -> Option<Values> {
+ #![allow(deprecated)]
+ let id = Id::from(id);
+ let arg = self.get_arg(&id)?;
+ let v = Values {
+ iter: arg.vals_flatten().map(unwrap_string),
+ len: arg.num_vals(),
+ };
+ Some(v)
+ }
+
+ /// Get an [`Iterator`] over groups of values of a specific option.
+ ///
+ /// specifically grouped by the occurrences of the options.
+ ///
+ /// Each group is a `Vec<&str>` containing the arguments passed to a single occurrence
+ /// of the option.
+ ///
+ /// If the option doesn't support multiple occurrences, or there was only a single occurrence,
+ /// the iterator will only contain a single item.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// # Panics
+ ///
+ /// If the value is invalid UTF-8.
+ ///
+ /// If `id` is not a valid argument or group id.
+ ///
+ /// # Examples
+ /// ```rust
+ /// # use clap::{Command,Arg, ArgAction};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("exec")
+ /// .short('x')
+ /// .min_values(1)
+ /// .action(ArgAction::Append)
+ /// .value_terminator(";"))
+ /// .get_matches_from(vec![
+ /// "myprog", "-x", "echo", "hi", ";", "-x", "echo", "bye"]);
+ /// let vals: Vec<Vec<&str>> = m.grouped_values_of("exec").unwrap().collect();
+ /// assert_eq!(vals, [["echo", "hi"], ["echo", "bye"]]);
+ /// ```
+ /// [`Iterator`]: std::iter::Iterator
+ #[cfg(feature = "unstable-grouped")]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn grouped_values_of<T: Key>(&self, id: T) -> Option<GroupedValues> {
+ let id = Id::from(id);
+ let arg = self.get_arg(&id)?;
+ let v = GroupedValues {
+ iter: arg.vals().map(|g| g.iter().map(unwrap_string).collect()),
+ len: arg.vals().len(),
+ };
+ Some(v)
+ }
+
+ /// Deprecated, replaced with [`ArgMatches::get_many()`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`")
+ )]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn values_of_lossy<T: Key>(&self, id: T) -> Option<Vec<String>> {
+ let id = Id::from(id);
+ let arg = self.get_arg(&id)?;
+ let v = arg
+ .vals_flatten()
+ .map(|v| unwrap_os_string_arg(&id, v).to_string_lossy().into_owned())
+ .collect();
+ Some(v)
+ }
+
+ /// Deprecated, replaced with [`ArgMatches::get_many()`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`")
+ )]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn values_of_os<T: Key>(&self, id: T) -> Option<OsValues> {
+ #![allow(deprecated)]
+ let id = Id::from(id);
+ let arg = self.get_arg(&id)?;
+ let v = OsValues {
+ iter: arg.vals_flatten().map(unwrap_os_string),
+ len: arg.num_vals(),
+ };
+ Some(v)
+ }
+
+ /// Deprecated, replaced with [`ArgMatches::get_one()`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_one()`")
+ )]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn value_of_t<R>(&self, name: &str) -> Result<R, Error>
+ where
+ R: FromStr,
+ <R as FromStr>::Err: Display,
+ {
+ #![allow(deprecated)]
+ let v = self
+ .value_of(name)
+ .ok_or_else(|| Error::argument_not_found_auto(name.to_string()))?;
+ v.parse::<R>().map_err(|e| {
+ let message = format!(
+ "The argument '{}' isn't a valid value for '{}': {}",
+ v, name, e
+ );
+
+ Error::value_validation(name.to_string(), v.to_string(), message.into())
+ })
+ }
+
+ /// Deprecated, replaced with [`ArgMatches::get_one()`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_one()`")
+ )]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn value_of_t_or_exit<R>(&self, name: &str) -> R
+ where
+ R: FromStr,
+ <R as FromStr>::Err: Display,
+ {
+ #![allow(deprecated)]
+ self.value_of_t(name).unwrap_or_else(|e| e.exit())
+ }
+
+ /// Deprecated, replaced with [`ArgMatches::get_many()`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`")
+ )]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn values_of_t<R>(&self, name: &str) -> Result<Vec<R>, Error>
+ where
+ R: FromStr,
+ <R as FromStr>::Err: Display,
+ {
+ #![allow(deprecated)]
+ let v = self
+ .values_of(name)
+ .ok_or_else(|| Error::argument_not_found_auto(name.to_string()))?;
+ v.map(|v| {
+ v.parse::<R>().map_err(|e| {
+ let message = format!("The argument '{}' isn't a valid value: {}", v, e);
+
+ Error::value_validation(name.to_string(), v.to_string(), message.into())
+ })
+ })
+ .collect()
+ }
+
+ /// Deprecated, replaced with [`ArgMatches::get_many()`]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`")
+ )]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn values_of_t_or_exit<R>(&self, name: &str) -> Vec<R>
+ where
+ R: FromStr,
+ <R as FromStr>::Err: Display,
+ {
+ #![allow(deprecated)]
+ self.values_of_t(name).unwrap_or_else(|e| e.exit())
+ }
+
+ /// Deprecated, replaced with [`ArgAction::SetTrue`][crate::ArgAction] or
+ /// [`ArgMatches::contains_id`].
+ ///
+ /// With `ArgAction::SetTrue` becoming the new flag default in clap v4, flags will always be present.
+ /// To make the migration easier, we've renamed this function so people can identify when they actually
+ /// care about an arg being present or if they need to update to the new way to check a flag's
+ /// presence.
+ ///
+ /// For flags, call `arg.action(ArgAction::SetTrue)` and lookup the value with `matches.get_flag(...)`
+ ///
+ /// For presence, replace `matches.is_present(...)` with `matches.contains_id(...)`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with either `ArgAction::SetTrue` or `ArgMatches::contains_id(...)` to avoid confusion over new semantics
+
+With `ArgAction::SetTrue` becoming the new flag default in clap v4, flags will always be present.
+To make the migration easier, we've renamed this function so people can identify when they actually
+care about an arg being present or if they need to update to the new way to check a flag's
+presence.
+
+For flags, call `arg.action(ArgAction::SetTrue)` and lookup the value with `matches.get_flag(...)`
+
+For presence, replace `matches.is_present(...)` with `matches.contains_id(...)`
+"
+ )
+ )]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn is_present<T: Key>(&self, id: T) -> bool {
+ let id = Id::from(id);
+
+ #[cfg(debug_assertions)]
+ self.get_arg(&id);
+
+ self.args.contains_key(&id)
+ }
+
+ /// Report where argument value came from
+ ///
+ /// # Panics
+ ///
+ /// If `id` is is not a valid argument or group id.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ValueSource};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("debug")
+ /// .short('d'))
+ /// .get_matches_from(vec![
+ /// "myprog", "-d"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_source("debug"), Some(ValueSource::CommandLine));
+ /// ```
+ ///
+ /// [`default_value`]: crate::Arg::default_value()
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn value_source<T: Key>(&self, id: T) -> Option<ValueSource> {
+ let id = Id::from(id);
+
+ let value = self.get_arg(&id);
+
+ value.and_then(MatchedArg::source)
+ }
+
+ /// Deprecated, replaced with [`ArgAction::Count`][crate::ArgAction],
+ /// [`ArgMatches::get_many`]`.len()`, or [`ArgMatches::value_source`].
+ ///
+ /// `occurrences_of`s meaning was overloaded and we are replacing it with more direct approaches.
+ ///
+ /// For counting flags, call `arg.action(ArgAction::Count)` and lookup the value with `matches.get_count(...)`
+ ///
+ /// To check if a user explicitly passed in a value, check the source with `matches.value_source(...)`
+ ///
+ /// To see how many values there are, call `matches.get_many::<T>(...).map(|v| v.len())`
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with either `ArgAction::Count`, `ArgMatches::get_many(...).len()`, or `ArgMatches::value_source`
+
+`occurrences_of`s meaning was overloaded and we are replacing it with more direct approaches.
+
+For counting flags, call `arg.action(ArgAction::Count)` and lookup the value with `matches.get_count(...)`
+
+To check if a user explicitly passed in a value, check the source with `matches.value_source(...)`
+
+To see how many values there are, call `matches.get_many::<T>(...).map(|v| v.len())`
+"
+ )
+ )]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn occurrences_of<T: Key>(&self, id: T) -> u64 {
+ #![allow(deprecated)]
+ self.get_arg(&Id::from(id))
+ .map_or(0, |a| a.get_occurrences())
+ }
+
+ /// The first index of that an argument showed up.
+ ///
+ /// Indices are similar to argv indices, but are not exactly 1:1.
+ ///
+ /// For flags (i.e. those arguments which don't have an associated value), indices refer
+ /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices
+ /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the
+ /// index for `val` would be recorded. This is by design.
+ ///
+ /// Besides the flag/option discrepancy, the primary difference between an argv index and clap
+ /// index, is that clap continues counting once all arguments have properly separated, whereas
+ /// an argv index does not.
+ ///
+ /// The examples should clear this up.
+ ///
+ /// *NOTE:* If an argument is allowed multiple times, this method will only give the *first*
+ /// index. See [`ArgMatches::indices_of`].
+ ///
+ /// # Panics
+ ///
+ /// If `id` is is not a valid argument or group id.
+ ///
+ /// # Examples
+ ///
+ /// The argv indices are listed in the comments below. See how they correspond to the clap
+ /// indices. Note that if it's not listed in a clap index, this is because it's not saved in
+ /// in an `ArgMatches` struct for querying.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("flag")
+ /// .short('f'))
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .takes_value(true))
+ /// .get_matches_from(vec!["myapp", "-f", "-o", "val"]);
+ /// // ARGV indices: ^0 ^1 ^2 ^3
+ /// // clap indices: ^1 ^3
+ ///
+ /// assert_eq!(m.index_of("flag"), Some(1));
+ /// assert_eq!(m.index_of("option"), Some(3));
+ /// ```
+ ///
+ /// Now notice, if we use one of the other styles of options:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("flag")
+ /// .short('f'))
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .takes_value(true))
+ /// .get_matches_from(vec!["myapp", "-f", "-o=val"]);
+ /// // ARGV indices: ^0 ^1 ^2
+ /// // clap indices: ^1 ^3
+ ///
+ /// assert_eq!(m.index_of("flag"), Some(1));
+ /// assert_eq!(m.index_of("option"), Some(3));
+ /// ```
+ ///
+ /// Things become much more complicated, or clear if we look at a more complex combination of
+ /// flags. Let's also throw in the final option style for good measure.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("flag")
+ /// .short('f'))
+ /// .arg(Arg::new("flag2")
+ /// .short('F'))
+ /// .arg(Arg::new("flag3")
+ /// .short('z'))
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .takes_value(true))
+ /// .get_matches_from(vec!["myapp", "-fzF", "-oval"]);
+ /// // ARGV indices: ^0 ^1 ^2
+ /// // clap indices: ^1,2,3 ^5
+ /// //
+ /// // clap sees the above as 'myapp -f -z -F -o val'
+ /// // ^0 ^1 ^2 ^3 ^4 ^5
+ /// assert_eq!(m.index_of("flag"), Some(1));
+ /// assert_eq!(m.index_of("flag2"), Some(3));
+ /// assert_eq!(m.index_of("flag3"), Some(2));
+ /// assert_eq!(m.index_of("option"), Some(5));
+ /// ```
+ ///
+ /// One final combination of flags/options to see how they combine:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("flag")
+ /// .short('f'))
+ /// .arg(Arg::new("flag2")
+ /// .short('F'))
+ /// .arg(Arg::new("flag3")
+ /// .short('z'))
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .takes_value(true))
+ /// .get_matches_from(vec!["myapp", "-fzFoval"]);
+ /// // ARGV indices: ^0 ^1
+ /// // clap indices: ^1,2,3^5
+ /// //
+ /// // clap sees the above as 'myapp -f -z -F -o val'
+ /// // ^0 ^1 ^2 ^3 ^4 ^5
+ /// assert_eq!(m.index_of("flag"), Some(1));
+ /// assert_eq!(m.index_of("flag2"), Some(3));
+ /// assert_eq!(m.index_of("flag3"), Some(2));
+ /// assert_eq!(m.index_of("option"), Some(5));
+ /// ```
+ ///
+ /// The last part to mention is when values are sent in multiple groups with a [delimiter].
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .use_value_delimiter(true)
+ /// .multiple_values(true))
+ /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
+ /// // ARGV indices: ^0 ^1
+ /// // clap indices: ^2 ^3 ^4
+ /// //
+ /// // clap sees the above as 'myapp -o val1 val2 val3'
+ /// // ^0 ^1 ^2 ^3 ^4
+ /// assert_eq!(m.index_of("option"), Some(2));
+ /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]);
+ /// ```
+ /// [delimiter]: crate::Arg::value_delimiter()
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn index_of<T: Key>(&self, id: T) -> Option<usize> {
+ let arg = self.get_arg(&Id::from(id))?;
+ let i = arg.get_index(0)?;
+ Some(i)
+ }
+
+ /// All indices an argument appeared at when parsing.
+ ///
+ /// Indices are similar to argv indices, but are not exactly 1:1.
+ ///
+ /// For flags (i.e. those arguments which don't have an associated value), indices refer
+ /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices
+ /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the
+ /// index for `val` would be recorded. This is by design.
+ ///
+ /// *NOTE:* For more information about how clap indices compared to argv indices, see
+ /// [`ArgMatches::index_of`]
+ ///
+ /// # Panics
+ ///
+ /// If `id` is is not a valid argument or group id.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .use_value_delimiter(true)
+ /// .multiple_values(true))
+ /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
+ /// // ARGV indices: ^0 ^1
+ /// // clap indices: ^2 ^3 ^4
+ /// //
+ /// // clap sees the above as 'myapp -o val1 val2 val3'
+ /// // ^0 ^1 ^2 ^3 ^4
+ /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]);
+ /// ```
+ ///
+ /// Another quick example is when flags and options are used together
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .takes_value(true)
+ /// .action(ArgAction::Append))
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::Count))
+ /// .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]);
+ /// // ARGV indices: ^0 ^1 ^2 ^3 ^4 ^5 ^6
+ /// // clap indices: ^2 ^3 ^5 ^6
+ ///
+ /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 5]);
+ /// assert_eq!(m.indices_of("flag").unwrap().collect::<Vec<_>>(), &[6]);
+ /// ```
+ ///
+ /// One final example, which is an odd case; if we *don't* use value delimiter as we did with
+ /// the first example above instead of `val1`, `val2` and `val3` all being distinc values, they
+ /// would all be a single value of `val1,val2,val3`, in which case they'd only receive a single
+ /// index.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .takes_value(true)
+ /// .multiple_values(true))
+ /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
+ /// // ARGV indices: ^0 ^1
+ /// // clap indices: ^2
+ /// //
+ /// // clap sees the above as 'myapp -o "val1,val2,val3"'
+ /// // ^0 ^1 ^2
+ /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2]);
+ /// ```
+ /// [`ArgMatches::index_of`]: ArgMatches::index_of()
+ /// [delimiter]: Arg::value_delimiter()
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn indices_of<T: Key>(&self, id: T) -> Option<Indices<'_>> {
+ let arg = self.get_arg(&Id::from(id))?;
+ let i = Indices {
+ iter: arg.indices(),
+ len: arg.num_vals(),
+ };
+ Some(i)
+ }
+
+ #[inline]
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "3.2.0",
+ note = "Replaced with `ArgMatches::try_get_one()`
+
+When helping to catch mistyped argument IDs, we overlooked the use cases for more dynamic lookups
+of arguments, so we added `is_valid_arg` as a short-term hack. Since then, we've generalized
+`value_of` as `try_get_one` to give callers all the relevant information they need.
+
+So replace
+```
+if matches.is_valid_arg(...) {
+ matches.value_of(...)
+}
+```
+with
+```
+if let Ok(value) = matches.try_get_one::<T>(...) {
+}
+```
+"
+ )
+ )]
+ pub fn is_valid_arg(&self, _id: impl Key) -> bool {
+ #[cfg(debug_assertions)]
+ {
+ let id = Id::from(_id);
+ self.disable_asserts || id == Id::empty_hash() || self.valid_args.contains(&id)
+ }
+ #[cfg(not(debug_assertions))]
+ {
+ true
+ }
+ }
+}
+
+/// # Subcommands
+impl ArgMatches {
+ /// The name and `ArgMatches` of the current [subcommand].
+ ///
+ /// Subcommand values are put in a child [`ArgMatches`]
+ ///
+ /// Returns `None` if the subcommand wasn't present at runtime,
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let app_m = Command::new("git")
+ /// .subcommand(Command::new("clone"))
+ /// .subcommand(Command::new("push"))
+ /// .subcommand(Command::new("commit"))
+ /// .get_matches();
+ ///
+ /// match app_m.subcommand() {
+ /// Some(("clone", sub_m)) => {}, // clone was used
+ /// Some(("push", sub_m)) => {}, // push was used
+ /// Some(("commit", sub_m)) => {}, // commit was used
+ /// _ => {}, // Either no subcommand or one not tested for...
+ /// }
+ /// ```
+ ///
+ /// Another useful scenario is when you want to support third party, or external, subcommands.
+ /// In these cases you can't know the subcommand name ahead of time, so use a variable instead
+ /// with pattern matching!
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let app_m = Command::new("myprog")
+ /// .allow_external_subcommands(true)
+ /// .get_matches_from(vec![
+ /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
+ /// ]);
+ ///
+ /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
+ /// // string argument name
+ /// match app_m.subcommand() {
+ /// Some((external, sub_m)) => {
+ /// let ext_args: Vec<&str> = sub_m.get_many::<String>("")
+ /// .unwrap().map(|s| s.as_str()).collect();
+ /// assert_eq!(external, "subcmd");
+ /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
+ /// },
+ /// _ => {},
+ /// }
+ /// ```
+ /// [subcommand]: crate::Command::subcommand
+ #[inline]
+ pub fn subcommand(&self) -> Option<(&str, &ArgMatches)> {
+ self.subcommand.as_ref().map(|sc| (&*sc.name, &sc.matches))
+ }
+
+ /// Return the name and `ArgMatches` of the current [subcommand].
+ ///
+ /// Subcommand values are put in a child [`ArgMatches`]
+ ///
+ /// Returns `None` if the subcommand wasn't present at runtime,
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let mut app_m = Command::new("git")
+ /// .subcommand(Command::new("clone"))
+ /// .subcommand(Command::new("push"))
+ /// .subcommand(Command::new("commit"))
+ /// .subcommand_required(true)
+ /// .get_matches();
+ ///
+ /// let (name, sub_m) = app_m.remove_subcommand().expect("required");
+ /// match (name.as_str(), sub_m) {
+ /// ("clone", sub_m) => {}, // clone was used
+ /// ("push", sub_m) => {}, // push was used
+ /// ("commit", sub_m) => {}, // commit was used
+ /// (name, _) => unimplemented!("{}", name),
+ /// }
+ /// ```
+ ///
+ /// Another useful scenario is when you want to support third party, or external, subcommands.
+ /// In these cases you can't know the subcommand name ahead of time, so use a variable instead
+ /// with pattern matching!
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let mut app_m = Command::new("myprog")
+ /// .allow_external_subcommands(true)
+ /// .get_matches_from(vec![
+ /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
+ /// ]);
+ ///
+ /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
+ /// // string argument name
+ /// match app_m.remove_subcommand() {
+ /// Some((external, mut sub_m)) => {
+ /// let ext_args: Vec<String> = sub_m.remove_many("")
+ /// .expect("`file`is required")
+ /// .collect();
+ /// assert_eq!(external, "subcmd");
+ /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
+ /// },
+ /// _ => {},
+ /// }
+ /// ```
+ /// [subcommand]: crate::Command::subcommand
+ pub fn remove_subcommand(&mut self) -> Option<(String, ArgMatches)> {
+ self.subcommand.take().map(|sc| (sc.name, sc.matches))
+ }
+
+ /// The `ArgMatches` for the current [subcommand].
+ ///
+ /// Subcommand values are put in a child [`ArgMatches`]
+ ///
+ /// Returns `None` if the subcommand wasn't present at runtime,
+ ///
+ /// # Panics
+ ///
+ /// If `id` is is not a valid subcommand.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let app_m = Command::new("myprog")
+ /// .arg(Arg::new("debug")
+ /// .short('d')
+ /// .action(ArgAction::SetTrue)
+ /// )
+ /// .subcommand(Command::new("test")
+ /// .arg(Arg::new("opt")
+ /// .long("option")
+ /// .takes_value(true)))
+ /// .get_matches_from(vec![
+ /// "myprog", "-d", "test", "--option", "val"
+ /// ]);
+ ///
+ /// // Both parent commands, and child subcommands can have arguments present at the same times
+ /// assert!(*app_m.get_one::<bool>("debug").expect("defaulted by clap"));
+ ///
+ /// // Get the subcommand's ArgMatches instance
+ /// if let Some(sub_m) = app_m.subcommand_matches("test") {
+ /// // Use the struct like normal
+ /// assert_eq!(sub_m.get_one::<String>("opt").map(|s| s.as_str()), Some("val"));
+ /// }
+ /// ```
+ ///
+ /// [subcommand]: crate::Command::subcommand
+ /// [`Command`]: crate::Command
+ pub fn subcommand_matches<T: Key>(&self, id: T) -> Option<&ArgMatches> {
+ self.get_subcommand(&id.into()).map(|sc| &sc.matches)
+ }
+
+ /// The name of the current [subcommand].
+ ///
+ /// Returns `None` if the subcommand wasn't present at runtime,
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let app_m = Command::new("git")
+ /// .subcommand(Command::new("clone"))
+ /// .subcommand(Command::new("push"))
+ /// .subcommand(Command::new("commit"))
+ /// .get_matches();
+ ///
+ /// match app_m.subcommand_name() {
+ /// Some("clone") => {}, // clone was used
+ /// Some("push") => {}, // push was used
+ /// Some("commit") => {}, // commit was used
+ /// _ => {}, // Either no subcommand or one not tested for...
+ /// }
+ /// ```
+ /// [subcommand]: crate::Command::subcommand
+ /// [`Command`]: crate::Command
+ #[inline]
+ pub fn subcommand_name(&self) -> Option<&str> {
+ self.subcommand.as_ref().map(|sc| &*sc.name)
+ }
+
+ /// Check if a subcommand can be queried
+ ///
+ /// By default, `ArgMatches` functions assert on undefined `Id`s to help catch programmer
+ /// mistakes. In some context, this doesn't work, so users can use this function to check
+ /// before they do a query on `ArgMatches`.
+ #[inline]
+ #[doc(hidden)]
+ pub fn is_valid_subcommand(&self, _id: impl Key) -> bool {
+ #[cfg(debug_assertions)]
+ {
+ let id = Id::from(_id);
+ self.disable_asserts || id == Id::empty_hash() || self.valid_subcommands.contains(&id)
+ }
+ #[cfg(not(debug_assertions))]
+ {
+ true
+ }
+ }
+}
+
+/// # Advanced
+impl ArgMatches {
+ /// Non-panicking version of [`ArgMatches::get_one`]
+ pub fn try_get_one<T: Any + Clone + Send + Sync + 'static>(
+ &self,
+ id: &str,
+ ) -> Result<Option<&T>, MatchesError> {
+ let id = Id::from(id);
+ let arg = self.try_get_arg_t::<T>(&id)?;
+ let value = match arg.and_then(|a| a.first()) {
+ Some(value) => value,
+ None => {
+ return Ok(None);
+ }
+ };
+ Ok(value
+ .downcast_ref::<T>()
+ .map(Some)
+ .expect(INTERNAL_ERROR_MSG)) // enforced by `try_get_arg_t`
+ }
+
+ /// Non-panicking version of [`ArgMatches::get_many`]
+ pub fn try_get_many<T: Any + Clone + Send + Sync + 'static>(
+ &self,
+ id: &str,
+ ) -> Result<Option<ValuesRef<T>>, MatchesError> {
+ let id = Id::from(id);
+ let arg = match self.try_get_arg_t::<T>(&id)? {
+ Some(arg) => arg,
+ None => return Ok(None),
+ };
+ let len = arg.num_vals();
+ let values = arg.vals_flatten();
+ let values = ValuesRef {
+ // enforced by `try_get_arg_t`
+ iter: values.map(|v| v.downcast_ref::<T>().expect(INTERNAL_ERROR_MSG)),
+ len,
+ };
+ Ok(Some(values))
+ }
+
+ /// Non-panicking version of [`ArgMatches::get_raw`]
+ pub fn try_get_raw(&self, id: &str) -> Result<Option<RawValues<'_>>, MatchesError> {
+ let id = Id::from(id);
+ let arg = match self.try_get_arg(&id)? {
+ Some(arg) => arg,
+ None => return Ok(None),
+ };
+ let len = arg.num_vals();
+ let values = arg.raw_vals_flatten();
+ let values = RawValues {
+ iter: values.map(OsString::as_os_str),
+ len,
+ };
+ Ok(Some(values))
+ }
+
+ /// Non-panicking version of [`ArgMatches::remove_one`]
+ pub fn try_remove_one<T: Any + Clone + Send + Sync + 'static>(
+ &mut self,
+ id: &str,
+ ) -> Result<Option<T>, MatchesError> {
+ let id = Id::from(id);
+ match self.try_remove_arg_t::<T>(&id)? {
+ Some(values) => Ok(values
+ .into_vals_flatten()
+ // enforced by `try_get_arg_t`
+ .map(|v| v.downcast_into::<T>().expect(INTERNAL_ERROR_MSG))
+ .next()),
+ None => Ok(None),
+ }
+ }
+
+ /// Non-panicking version of [`ArgMatches::remove_many`]
+ pub fn try_remove_many<T: Any + Clone + Send + Sync + 'static>(
+ &mut self,
+ id: &str,
+ ) -> Result<Option<Values2<T>>, MatchesError> {
+ let id = Id::from(id);
+ let arg = match self.try_remove_arg_t::<T>(&id)? {
+ Some(arg) => arg,
+ None => return Ok(None),
+ };
+ let len = arg.num_vals();
+ let values = arg.into_vals_flatten();
+ let values = Values2 {
+ // enforced by `try_get_arg_t`
+ iter: values.map(|v| v.downcast_into::<T>().expect(INTERNAL_ERROR_MSG)),
+ len,
+ };
+ Ok(Some(values))
+ }
+
+ /// Non-panicking version of [`ArgMatches::contains_id`]
+ pub fn try_contains_id(&self, id: &str) -> Result<bool, MatchesError> {
+ let id = Id::from(id);
+
+ self.verify_arg(&id)?;
+
+ let presence = self.args.contains_key(&id);
+ Ok(presence)
+ }
+}
+
+// Private methods
+impl ArgMatches {
+ #[inline]
+ fn try_get_arg(&self, arg: &Id) -> Result<Option<&MatchedArg>, MatchesError> {
+ self.verify_arg(arg)?;
+ Ok(self.args.get(arg))
+ }
+
+ #[inline]
+ fn try_get_arg_t<T: Any + Send + Sync + 'static>(
+ &self,
+ arg: &Id,
+ ) -> Result<Option<&MatchedArg>, MatchesError> {
+ let arg = match self.try_get_arg(arg)? {
+ Some(arg) => arg,
+ None => {
+ return Ok(None);
+ }
+ };
+ self.verify_arg_t::<T>(arg)?;
+ Ok(Some(arg))
+ }
+
+ #[inline]
+ fn try_remove_arg_t<T: Any + Send + Sync + 'static>(
+ &mut self,
+ arg: &Id,
+ ) -> Result<Option<MatchedArg>, MatchesError> {
+ self.verify_arg(arg)?;
+ let matched = match self.args.remove(arg) {
+ Some(matched) => matched,
+ None => {
+ return Ok(None);
+ }
+ };
+
+ let expected = AnyValueId::of::<T>();
+ let actual = matched.infer_type_id(expected);
+ if actual == expected {
+ Ok(Some(matched))
+ } else {
+ self.args.insert(arg.clone(), matched);
+ Err(MatchesError::Downcast { actual, expected })
+ }
+ }
+
+ fn verify_arg_t<T: Any + Send + Sync + 'static>(
+ &self,
+ arg: &MatchedArg,
+ ) -> Result<(), MatchesError> {
+ let expected = AnyValueId::of::<T>();
+ let actual = arg.infer_type_id(expected);
+ if expected == actual {
+ Ok(())
+ } else {
+ Err(MatchesError::Downcast { actual, expected })
+ }
+ }
+
+ #[inline]
+ fn verify_arg(&self, _arg: &Id) -> Result<(), MatchesError> {
+ #[cfg(debug_assertions)]
+ {
+ if self.disable_asserts || *_arg == Id::empty_hash() || self.valid_args.contains(_arg) {
+ } else if self.valid_subcommands.contains(_arg) {
+ debug!(
+ "Subcommand `{:?}` used where an argument or group name was expected.",
+ _arg
+ );
+ return Err(MatchesError::UnknownArgument {});
+ } else {
+ debug!(
+ "`{:?}` is not an id of an argument or a group.\n\
+ Make sure you're using the name of the argument itself \
+ and not the name of short or long flags.",
+ _arg
+ );
+ return Err(MatchesError::UnknownArgument {});
+ }
+ }
+ Ok(())
+ }
+
+ #[inline]
+ #[cfg_attr(debug_assertions, track_caller)]
+ fn get_arg(&self, arg: &Id) -> Option<&MatchedArg> {
+ #[cfg(debug_assertions)]
+ {
+ if self.disable_asserts || *arg == Id::empty_hash() || self.valid_args.contains(arg) {
+ } else if self.valid_subcommands.contains(arg) {
+ panic!(
+ "Subcommand `{:?}` used where an argument or group name was expected.",
+ arg
+ );
+ } else {
+ panic!(
+ "`{:?}` is not an id of an argument or a group.\n\
+ Make sure you're using the name of the argument itself \
+ and not the name of short or long flags.",
+ arg
+ );
+ }
+ }
+
+ self.args.get(arg)
+ }
+
+ #[inline]
+ #[cfg_attr(debug_assertions, track_caller)]
+ fn get_subcommand(&self, id: &Id) -> Option<&SubCommand> {
+ #[cfg(debug_assertions)]
+ {
+ if self.disable_asserts
+ || *id == Id::empty_hash()
+ || self.valid_subcommands.contains(id)
+ {
+ } else if self.valid_args.contains(id) {
+ panic!(
+ "Argument or group `{:?}` used where a subcommand name was expected.",
+ id
+ );
+ } else {
+ panic!("`{:?}` is not a name of a subcommand.", id);
+ }
+ }
+
+ if let Some(ref sc) = self.subcommand {
+ if sc.id == *id {
+ return Some(sc);
+ }
+ }
+
+ None
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct SubCommand {
+ pub(crate) id: Id,
+ pub(crate) name: String,
+ pub(crate) matches: ArgMatches,
+}
+
+/// Iterate over multiple values for an argument via [`ArgMatches::remove_many`].
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::{Command, Arg, ArgAction};
+/// let mut m = Command::new("myapp")
+/// .arg(Arg::new("output")
+/// .short('o')
+/// .action(ArgAction::Append)
+/// .takes_value(true))
+/// .get_matches_from(vec!["myapp", "-o", "val1", "-o", "val2"]);
+///
+/// let mut values = m.remove_many::<String>("output")
+/// .unwrap();
+///
+/// assert_eq!(values.next(), Some(String::from("val1")));
+/// assert_eq!(values.next(), Some(String::from("val2")));
+/// assert_eq!(values.next(), None);
+/// ```
+#[derive(Clone, Debug)]
+pub struct Values2<T> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Flatten<std::vec::IntoIter<Vec<AnyValue>>>, fn(AnyValue) -> T>,
+ len: usize,
+}
+
+impl<T> Iterator for Values2<T> {
+ type Item = T;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
+ }
+}
+
+impl<T> DoubleEndedIterator for Values2<T> {
+ fn next_back(&mut self) -> Option<Self::Item> {
+ self.iter.next_back()
+ }
+}
+
+impl<T> ExactSizeIterator for Values2<T> {}
+
+/// Creates an empty iterator.
+impl<T> Default for Values2<T> {
+ fn default() -> Self {
+ let empty: Vec<Vec<AnyValue>> = Default::default();
+ Values2 {
+ iter: empty.into_iter().flatten().map(|_| unreachable!()),
+ len: 0,
+ }
+ }
+}
+
+/// Iterate over multiple values for an argument via [`ArgMatches::get_many`].
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::{Command, Arg, ArgAction};
+/// let m = Command::new("myapp")
+/// .arg(Arg::new("output")
+/// .short('o')
+/// .action(ArgAction::Append)
+/// .takes_value(true))
+/// .get_matches_from(vec!["myapp", "-o", "val1", "-o", "val2"]);
+///
+/// let mut values = m.get_many::<String>("output")
+/// .unwrap()
+/// .map(|s| s.as_str());
+///
+/// assert_eq!(values.next(), Some("val1"));
+/// assert_eq!(values.next(), Some("val2"));
+/// assert_eq!(values.next(), None);
+/// ```
+#[derive(Clone, Debug)]
+pub struct ValuesRef<'a, T> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Flatten<Iter<'a, Vec<AnyValue>>>, fn(&AnyValue) -> &T>,
+ len: usize,
+}
+
+impl<'a, T: 'a> Iterator for ValuesRef<'a, T> {
+ type Item = &'a T;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
+ }
+}
+
+impl<'a, T: 'a> DoubleEndedIterator for ValuesRef<'a, T> {
+ fn next_back(&mut self) -> Option<Self::Item> {
+ self.iter.next_back()
+ }
+}
+
+impl<'a, T: 'a> ExactSizeIterator for ValuesRef<'a, T> {}
+
+/// Creates an empty iterator.
+impl<'a, T: 'a> Default for ValuesRef<'a, T> {
+ fn default() -> Self {
+ static EMPTY: [Vec<AnyValue>; 0] = [];
+ ValuesRef {
+ iter: EMPTY[..].iter().flatten().map(|_| unreachable!()),
+ len: 0,
+ }
+ }
+}
+
+/// Iterate over raw argument values via [`ArgMatches::get_raw`].
+///
+/// # Examples
+///
+#[cfg_attr(not(unix), doc = " ```ignore")]
+#[cfg_attr(unix, doc = " ```")]
+/// # use clap::{Command, arg, value_parser};
+/// use std::ffi::OsString;
+/// use std::os::unix::ffi::{OsStrExt,OsStringExt};
+///
+/// let m = Command::new("utf8")
+/// .arg(arg!(<arg> "some arg")
+/// .value_parser(value_parser!(OsString)))
+/// .get_matches_from(vec![OsString::from("myprog"),
+/// // "Hi {0xe9}!"
+/// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
+/// assert_eq!(
+/// &*m.get_raw("arg")
+/// .unwrap()
+/// .next().unwrap()
+/// .as_bytes(),
+/// [b'H', b'i', b' ', 0xe9, b'!']
+/// );
+/// ```
+#[derive(Clone, Debug)]
+pub struct RawValues<'a> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Flatten<Iter<'a, Vec<OsString>>>, fn(&OsString) -> &OsStr>,
+ len: usize,
+}
+
+impl<'a> Iterator for RawValues<'a> {
+ type Item = &'a OsStr;
+
+ fn next(&mut self) -> Option<&'a OsStr> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
+ }
+}
+
+impl<'a> DoubleEndedIterator for RawValues<'a> {
+ fn next_back(&mut self) -> Option<&'a OsStr> {
+ self.iter.next_back()
+ }
+}
+
+impl<'a> ExactSizeIterator for RawValues<'a> {}
+
+/// Creates an empty iterator.
+impl Default for RawValues<'_> {
+ fn default() -> Self {
+ static EMPTY: [Vec<OsString>; 0] = [];
+ RawValues {
+ iter: EMPTY[..].iter().flatten().map(|_| unreachable!()),
+ len: 0,
+ }
+ }
+}
+
+// The following were taken and adapted from vec_map source
+// repo: https://github.com/contain-rs/vec-map
+// commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33
+// license: MIT - Copyright (c) 2015 The Rust Project Developers
+
+/// Deprecated, replaced with [`ArgMatches::get_many()`]
+#[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`")
+)]
+#[derive(Clone, Debug)]
+pub struct Values<'a> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Flatten<Iter<'a, Vec<AnyValue>>>, for<'r> fn(&'r AnyValue) -> &'r str>,
+ len: usize,
+}
+
+#[allow(deprecated)]
+impl<'a> Iterator for Values<'a> {
+ type Item = &'a str;
+
+ fn next(&mut self) -> Option<&'a str> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
+ }
+}
+
+#[allow(deprecated)]
+impl<'a> DoubleEndedIterator for Values<'a> {
+ fn next_back(&mut self) -> Option<&'a str> {
+ self.iter.next_back()
+ }
+}
+
+#[allow(deprecated)]
+impl<'a> ExactSizeIterator for Values<'a> {}
+
+/// Creates an empty iterator.
+#[allow(deprecated)]
+impl<'a> Default for Values<'a> {
+ fn default() -> Self {
+ static EMPTY: [Vec<AnyValue>; 0] = [];
+ Values {
+ iter: EMPTY[..].iter().flatten().map(|_| unreachable!()),
+ len: 0,
+ }
+ }
+}
+
+#[derive(Clone)]
+#[allow(missing_debug_implementations)]
+pub struct GroupedValues<'a> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Iter<'a, Vec<AnyValue>>, fn(&Vec<AnyValue>) -> Vec<&str>>,
+ len: usize,
+}
+
+impl<'a> Iterator for GroupedValues<'a> {
+ type Item = Vec<&'a str>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
+ }
+}
+
+impl<'a> DoubleEndedIterator for GroupedValues<'a> {
+ fn next_back(&mut self) -> Option<Self::Item> {
+ self.iter.next_back()
+ }
+}
+
+impl<'a> ExactSizeIterator for GroupedValues<'a> {}
+
+/// Creates an empty iterator. Used for `unwrap_or_default()`.
+impl<'a> Default for GroupedValues<'a> {
+ fn default() -> Self {
+ #![allow(deprecated)]
+ static EMPTY: [Vec<AnyValue>; 0] = [];
+ GroupedValues {
+ iter: EMPTY[..].iter().map(|_| unreachable!()),
+ len: 0,
+ }
+ }
+}
+
+/// Deprecated, replaced with [`ArgMatches::get_many()`]
+#[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "3.2.0", note = "Replaced with `ArgMatches::get_many()`")
+)]
+#[derive(Clone, Debug)]
+pub struct OsValues<'a> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Flatten<Iter<'a, Vec<AnyValue>>>, fn(&AnyValue) -> &OsStr>,
+ len: usize,
+}
+
+#[allow(deprecated)]
+impl<'a> Iterator for OsValues<'a> {
+ type Item = &'a OsStr;
+
+ fn next(&mut self) -> Option<&'a OsStr> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
+ }
+}
+
+#[allow(deprecated)]
+impl<'a> DoubleEndedIterator for OsValues<'a> {
+ fn next_back(&mut self) -> Option<&'a OsStr> {
+ self.iter.next_back()
+ }
+}
+
+#[allow(deprecated)]
+impl<'a> ExactSizeIterator for OsValues<'a> {}
+
+/// Creates an empty iterator.
+#[allow(deprecated)]
+impl Default for OsValues<'_> {
+ fn default() -> Self {
+ static EMPTY: [Vec<AnyValue>; 0] = [];
+ OsValues {
+ iter: EMPTY[..].iter().flatten().map(|_| unreachable!()),
+ len: 0,
+ }
+ }
+}
+
+/// Iterate over indices for where an argument appeared when parsing, via [`ArgMatches::indices_of`]
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::{Command, Arg};
+/// let m = Command::new("myapp")
+/// .arg(Arg::new("output")
+/// .short('o')
+/// .multiple_values(true)
+/// .takes_value(true))
+/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]);
+///
+/// let mut indices = m.indices_of("output").unwrap();
+///
+/// assert_eq!(indices.next(), Some(2));
+/// assert_eq!(indices.next(), Some(3));
+/// assert_eq!(indices.next(), None);
+/// ```
+/// [`ArgMatches::indices_of`]: ArgMatches::indices_of()
+#[derive(Clone, Debug)]
+pub struct Indices<'a> {
+ iter: Cloned<Iter<'a, usize>>,
+ len: usize,
+}
+
+impl<'a> Iterator for Indices<'a> {
+ type Item = usize;
+
+ fn next(&mut self) -> Option<usize> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
+ }
+}
+
+impl<'a> DoubleEndedIterator for Indices<'a> {
+ fn next_back(&mut self) -> Option<usize> {
+ self.iter.next_back()
+ }
+}
+
+impl<'a> ExactSizeIterator for Indices<'a> {}
+
+/// Creates an empty iterator.
+impl<'a> Default for Indices<'a> {
+ fn default() -> Self {
+ static EMPTY: [usize; 0] = [];
+ // This is never called because the iterator is empty:
+ Indices {
+ iter: EMPTY[..].iter().cloned(),
+ len: 0,
+ }
+ }
+}
+
+#[cfg_attr(debug_assertions, track_caller)]
+#[inline]
+fn unwrap_string(value: &AnyValue) -> &str {
+ match value.downcast_ref::<String>() {
+ Some(value) => value,
+ None => {
+ panic!("Must use `_os` lookups with `Arg::allow_invalid_utf8`",)
+ }
+ }
+}
+
+#[cfg_attr(debug_assertions, track_caller)]
+#[inline]
+fn unwrap_string_arg<'v>(id: &Id, value: &'v AnyValue) -> &'v str {
+ match value.downcast_ref::<String>() {
+ Some(value) => value,
+ None => {
+ panic!(
+ "Must use `_os` lookups with `Arg::allow_invalid_utf8` at `{:?}`",
+ id
+ )
+ }
+ }
+}
+
+#[cfg_attr(debug_assertions, track_caller)]
+#[inline]
+fn unwrap_os_string(value: &AnyValue) -> &OsStr {
+ match value.downcast_ref::<OsString>() {
+ Some(value) => value,
+ None => {
+ panic!("Must use `Arg::allow_invalid_utf8` with `_os` lookups",)
+ }
+ }
+}
+
+#[cfg_attr(debug_assertions, track_caller)]
+#[inline]
+fn unwrap_os_string_arg<'v>(id: &Id, value: &'v AnyValue) -> &'v OsStr {
+ match value.downcast_ref::<OsString>() {
+ Some(value) => value,
+ None => {
+ panic!(
+ "Must use `Arg::allow_invalid_utf8` with `_os` lookups at `{:?}`",
+ id
+ )
+ }
+ }
+}
+
+#[cfg(test)]
+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();
+ assert_eq!(values.next(), None);
+ }
+
+ #[test]
+ fn test_default_osvalues() {
+ #![allow(deprecated)]
+ let mut values: OsValues = OsValues::default();
+ assert_eq!(values.next(), None);
+ }
+
+ #[test]
+ fn test_default_raw_values() {
+ let mut values: RawValues = Default::default();
+ assert_eq!(values.next(), None);
+ }
+
+ #[test]
+ fn test_default_indices() {
+ let mut indices: Indices = Indices::default();
+ assert_eq!(indices.next(), None);
+ }
+
+ #[test]
+ fn test_default_indices_with_shorter_lifetime() {
+ let matches = ArgMatches::default();
+ let mut indices = matches.indices_of("").unwrap_or_default();
+ assert_eq!(indices.next(), None);
+ }
+
+ #[test]
+ fn values_exact_size() {
+ let l = crate::Command::new("test")
+ .arg(
+ crate::Arg::new("POTATO")
+ .takes_value(true)
+ .multiple_values(true)
+ .required(true),
+ )
+ .try_get_matches_from(["test", "one"])
+ .unwrap()
+ .get_many::<String>("POTATO")
+ .expect("present")
+ .count();
+ assert_eq!(l, 1);
+ }
+
+ #[test]
+ fn os_values_exact_size() {
+ let l = crate::Command::new("test")
+ .arg(
+ crate::Arg::new("POTATO")
+ .takes_value(true)
+ .multiple_values(true)
+ .value_parser(crate::builder::ValueParser::os_string())
+ .required(true),
+ )
+ .try_get_matches_from(["test", "one"])
+ .unwrap()
+ .get_many::<std::ffi::OsString>("POTATO")
+ .expect("present")
+ .count();
+ assert_eq!(l, 1);
+ }
+
+ #[test]
+ fn indices_exact_size() {
+ let l = crate::Command::new("test")
+ .arg(
+ crate::Arg::new("POTATO")
+ .takes_value(true)
+ .multiple_values(true)
+ .required(true),
+ )
+ .try_get_matches_from(["test", "one"])
+ .unwrap()
+ .indices_of("POTATO")
+ .expect("present")
+ .len();
+ assert_eq!(l, 1);
+ }
+}
diff --git a/3.2.23/src/parser/matches/matched_arg.rs b/3.2.23/src/parser/matches/matched_arg.rs
new file mode 100644
index 0000000..fde6d37
--- /dev/null
+++ b/3.2.23/src/parser/matches/matched_arg.rs
@@ -0,0 +1,240 @@
+// Std
+use std::{
+ ffi::{OsStr, OsString},
+ iter::{Cloned, Flatten},
+ slice::Iter,
+};
+
+use crate::builder::ArgPredicate;
+use crate::parser::AnyValue;
+use crate::parser::AnyValueId;
+use crate::parser::ValueSource;
+use crate::util::eq_ignore_case;
+use crate::INTERNAL_ERROR_MSG;
+
+#[derive(Debug, Clone)]
+pub(crate) struct MatchedArg {
+ occurs: u64,
+ source: Option<ValueSource>,
+ indices: Vec<usize>,
+ type_id: Option<AnyValueId>,
+ vals: Vec<Vec<AnyValue>>,
+ raw_vals: Vec<Vec<OsString>>,
+ ignore_case: bool,
+}
+
+impl MatchedArg {
+ pub(crate) fn new_arg(arg: &crate::Arg) -> Self {
+ let ignore_case = arg.is_ignore_case_set();
+ Self {
+ occurs: 0,
+ source: None,
+ indices: Vec::new(),
+ type_id: Some(arg.get_value_parser().type_id()),
+ vals: Vec::new(),
+ raw_vals: Vec::new(),
+ ignore_case,
+ }
+ }
+
+ pub(crate) fn new_group() -> Self {
+ let ignore_case = false;
+ Self {
+ occurs: 0,
+ source: None,
+ indices: Vec::new(),
+ type_id: None,
+ vals: Vec::new(),
+ raw_vals: Vec::new(),
+ ignore_case,
+ }
+ }
+
+ pub(crate) fn new_external(cmd: &crate::Command) -> Self {
+ let ignore_case = false;
+ Self {
+ occurs: 0,
+ source: None,
+ indices: Vec::new(),
+ type_id: Some(
+ cmd.get_external_subcommand_value_parser()
+ .expect(INTERNAL_ERROR_MSG)
+ .type_id(),
+ ),
+ vals: Vec::new(),
+ raw_vals: Vec::new(),
+ ignore_case,
+ }
+ }
+
+ #[cfg_attr(feature = "deprecated", deprecated(since = "3.2.0"))]
+ pub(crate) fn inc_occurrences(&mut self) {
+ self.occurs += 1;
+ }
+
+ #[cfg_attr(feature = "deprecated", deprecated(since = "3.2.0"))]
+ pub(crate) fn set_occurrences(&mut self, occurs: u64) {
+ self.occurs = occurs
+ }
+
+ #[cfg_attr(feature = "deprecated", deprecated(since = "3.2.0"))]
+ pub(crate) fn get_occurrences(&self) -> u64 {
+ self.occurs
+ }
+
+ pub(crate) fn indices(&self) -> Cloned<Iter<'_, usize>> {
+ self.indices.iter().cloned()
+ }
+
+ pub(crate) fn get_index(&self, index: usize) -> Option<usize> {
+ self.indices.get(index).cloned()
+ }
+
+ pub(crate) fn push_index(&mut self, index: usize) {
+ self.indices.push(index)
+ }
+
+ #[cfg(feature = "unstable-grouped")]
+ pub(crate) fn vals(&self) -> Iter<Vec<AnyValue>> {
+ self.vals.iter()
+ }
+
+ pub(crate) fn vals_flatten(&self) -> Flatten<Iter<Vec<AnyValue>>> {
+ self.vals.iter().flatten()
+ }
+
+ pub(crate) fn into_vals_flatten(self) -> Flatten<std::vec::IntoIter<Vec<AnyValue>>> {
+ self.vals.into_iter().flatten()
+ }
+
+ pub(crate) fn raw_vals_flatten(&self) -> Flatten<Iter<Vec<OsString>>> {
+ self.raw_vals.iter().flatten()
+ }
+
+ pub(crate) fn first(&self) -> Option<&AnyValue> {
+ self.vals_flatten().next()
+ }
+
+ #[cfg(test)]
+ pub(crate) fn first_raw(&self) -> Option<&OsString> {
+ self.raw_vals_flatten().next()
+ }
+
+ pub(crate) fn new_val_group(&mut self) {
+ self.vals.push(vec![]);
+ self.raw_vals.push(vec![]);
+ }
+
+ pub(crate) fn append_val(&mut self, val: AnyValue, raw_val: OsString) {
+ // We assume there is always a group created before.
+ self.vals.last_mut().expect(INTERNAL_ERROR_MSG).push(val);
+ self.raw_vals
+ .last_mut()
+ .expect(INTERNAL_ERROR_MSG)
+ .push(raw_val);
+ }
+
+ pub(crate) fn num_vals(&self) -> usize {
+ self.vals.iter().map(|v| v.len()).sum()
+ }
+
+ // Will be used later
+ #[allow(dead_code)]
+ pub(crate) fn num_vals_last_group(&self) -> usize {
+ self.vals.last().map(|x| x.len()).unwrap_or(0)
+ }
+
+ pub(crate) fn all_val_groups_empty(&self) -> bool {
+ self.vals.iter().flatten().count() == 0
+ }
+
+ pub(crate) fn check_explicit(&self, predicate: ArgPredicate) -> bool {
+ if self.source == Some(ValueSource::DefaultValue) {
+ return false;
+ }
+
+ match predicate {
+ ArgPredicate::Equals(val) => self.raw_vals_flatten().any(|v| {
+ if self.ignore_case {
+ // If `v` isn't utf8, it can't match `val`, so `OsStr::to_str` should be fine
+ eq_ignore_case(&v.to_string_lossy(), &val.to_string_lossy())
+ } else {
+ OsString::as_os_str(v) == OsStr::new(val)
+ }
+ }),
+ ArgPredicate::IsPresent => true,
+ }
+ }
+
+ pub(crate) fn source(&self) -> Option<ValueSource> {
+ self.source
+ }
+
+ pub(crate) fn set_source(&mut self, source: ValueSource) {
+ if let Some(existing) = self.source {
+ self.source = Some(existing.max(source));
+ } else {
+ self.source = Some(source)
+ }
+ }
+
+ pub(crate) fn type_id(&self) -> Option<AnyValueId> {
+ self.type_id
+ }
+
+ pub(crate) fn infer_type_id(&self, expected: AnyValueId) -> AnyValueId {
+ self.type_id()
+ .or_else(|| {
+ self.vals_flatten()
+ .map(|v| v.type_id())
+ .find(|actual| *actual != expected)
+ })
+ .unwrap_or(expected)
+ }
+}
+
+impl PartialEq for MatchedArg {
+ fn eq(&self, other: &MatchedArg) -> bool {
+ let MatchedArg {
+ occurs: self_occurs,
+ source: self_source,
+ indices: self_indices,
+ type_id: self_type_id,
+ vals: _,
+ raw_vals: self_raw_vals,
+ ignore_case: self_ignore_case,
+ } = self;
+ let MatchedArg {
+ occurs: other_occurs,
+ source: other_source,
+ indices: other_indices,
+ type_id: other_type_id,
+ vals: _,
+ raw_vals: other_raw_vals,
+ ignore_case: other_ignore_case,
+ } = other;
+ self_occurs == other_occurs
+ && self_source == other_source
+ && self_indices == other_indices
+ && self_type_id == other_type_id
+ && self_raw_vals == other_raw_vals
+ && self_ignore_case == other_ignore_case
+ }
+}
+
+impl Eq for MatchedArg {}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_grouped_vals_first() {
+ let mut m = MatchedArg::new_group();
+ m.new_val_group();
+ m.new_val_group();
+ m.append_val(AnyValue::new(String::from("bbb")), "bbb".into());
+ m.append_val(AnyValue::new(String::from("ccc")), "ccc".into());
+ assert_eq!(m.first_raw(), Some(&OsString::from("bbb")));
+ }
+}
diff --git a/3.2.23/src/parser/matches/mod.rs b/3.2.23/src/parser/matches/mod.rs
new file mode 100644
index 0000000..7b88eec
--- /dev/null
+++ b/3.2.23/src/parser/matches/mod.rs
@@ -0,0 +1,17 @@
+mod any_value;
+mod arg_matches;
+mod matched_arg;
+mod value_source;
+
+pub use any_value::AnyValueId;
+pub use arg_matches::RawValues;
+pub use arg_matches::ValuesRef;
+pub use arg_matches::{ArgMatches, Indices};
+pub use value_source::ValueSource;
+
+pub(crate) use any_value::AnyValue;
+pub(crate) use arg_matches::SubCommand;
+pub(crate) use matched_arg::MatchedArg;
+
+#[allow(deprecated)]
+pub use arg_matches::{OsValues, Values};
diff --git a/3.2.23/src/parser/matches/value_source.rs b/3.2.23/src/parser/matches/value_source.rs
new file mode 100644
index 0000000..fb762d2
--- /dev/null
+++ b/3.2.23/src/parser/matches/value_source.rs
@@ -0,0 +1,11 @@
+/// Origin of the argument's value
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+#[non_exhaustive]
+pub enum ValueSource {
+ /// Value came [`Arg::default_value`][crate::Arg::default_value]
+ DefaultValue,
+ /// Value came [`Arg::env`][crate::Arg::env]
+ EnvVariable,
+ /// Value was passed in on the command-line
+ CommandLine,
+}
diff --git a/3.2.23/src/parser/mod.rs b/3.2.23/src/parser/mod.rs
new file mode 100644
index 0000000..da81648
--- /dev/null
+++ b/3.2.23/src/parser/mod.rs
@@ -0,0 +1,27 @@
+//! [`Command`][crate::Command] line argument parser
+
+mod arg_matcher;
+mod error;
+mod matches;
+#[allow(clippy::module_inception)]
+mod parser;
+mod validator;
+
+pub(crate) mod features;
+
+pub(crate) use self::arg_matcher::ArgMatcher;
+pub(crate) use self::matches::AnyValue;
+pub(crate) use self::matches::AnyValueId;
+pub(crate) use self::matches::{MatchedArg, SubCommand};
+pub(crate) use self::parser::Identifier;
+pub(crate) use self::parser::PendingArg;
+pub(crate) use self::parser::{ParseState, Parser};
+pub(crate) use self::validator::Validator;
+
+pub use self::matches::RawValues;
+pub use self::matches::ValuesRef;
+pub use self::matches::{ArgMatches, Indices, ValueSource};
+pub use error::MatchesError;
+
+#[allow(deprecated)]
+pub use self::matches::{OsValues, Values};
diff --git a/3.2.23/src/parser/parser.rs b/3.2.23/src/parser/parser.rs
new file mode 100644
index 0000000..ad2bc6e
--- /dev/null
+++ b/3.2.23/src/parser/parser.rs
@@ -0,0 +1,1729 @@
+// Std
+use std::{
+ cell::Cell,
+ ffi::{OsStr, OsString},
+};
+
+// Third Party
+use clap_lex::RawOsStr;
+
+// Internal
+use crate::builder::AppSettings as AS;
+use crate::builder::{Arg, Command};
+use crate::error::Error as ClapError;
+use crate::error::Result as ClapResult;
+use crate::mkeymap::KeyType;
+use crate::output::fmt::Stream;
+use crate::output::{fmt::Colorizer, Usage};
+use crate::parser::features::suggestions;
+use crate::parser::{ArgMatcher, SubCommand};
+use crate::parser::{Validator, ValueSource};
+use crate::util::Id;
+use crate::ArgAction;
+use crate::{INTERNAL_ERROR_MSG, INVALID_UTF8};
+
+pub(crate) struct Parser<'help, 'cmd> {
+ cmd: &'cmd mut Command<'help>,
+ cur_idx: Cell<usize>,
+ /// Index of the previous flag subcommand in a group of flags.
+ flag_subcmd_at: Option<usize>,
+ /// Counter indicating the number of items to skip
+ /// when revisiting the group of flags which includes the flag subcommand.
+ flag_subcmd_skip: usize,
+}
+
+// Initializing Methods
+impl<'help, 'cmd> Parser<'help, 'cmd> {
+ pub(crate) fn new(cmd: &'cmd mut Command<'help>) -> Self {
+ Parser {
+ cmd,
+ cur_idx: Cell::new(0),
+ flag_subcmd_at: None,
+ flag_subcmd_skip: 0,
+ }
+ }
+}
+
+// Parsing Methods
+impl<'help, 'cmd> Parser<'help, 'cmd> {
+ // The actual parsing function
+ #[allow(clippy::cognitive_complexity)]
+ pub(crate) fn get_matches_with(
+ &mut self,
+ matcher: &mut ArgMatcher,
+ raw_args: &mut clap_lex::RawArgs,
+ mut args_cursor: clap_lex::ArgCursor,
+ ) -> ClapResult<()> {
+ debug!("Parser::get_matches_with");
+ // Verify all positional assertions pass
+
+ let mut subcmd_name: Option<String> = None;
+ let mut keep_state = false;
+ let mut parse_state = ParseState::ValuesDone;
+ let mut pos_counter = 1;
+
+ // Already met any valid arg(then we shouldn't expect subcommands after it).
+ let mut valid_arg_found = false;
+ // If the user already passed '--'. Meaning only positional args follow.
+ let mut trailing_values = false;
+
+ // Count of positional args
+ let positional_count = self
+ .cmd
+ .get_keymap()
+ .keys()
+ .filter(|x| x.is_position())
+ .count();
+ // If any arg sets .last(true)
+ let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set());
+
+ while let Some(arg_os) = raw_args.next(&mut args_cursor) {
+ // Recover the replaced items if any.
+ if let Some(replaced_items) = arg_os
+ .to_value()
+ .ok()
+ .and_then(|a| self.cmd.get_replacement(a))
+ {
+ debug!(
+ "Parser::get_matches_with: found replacer: {:?}, target: {:?}",
+ arg_os, replaced_items
+ );
+ raw_args.insert(&args_cursor, replaced_items);
+ continue;
+ }
+
+ debug!(
+ "Parser::get_matches_with: Begin parsing '{:?}' ({:?})",
+ arg_os.to_value_os(),
+ arg_os.to_value_os().as_raw_bytes()
+ );
+
+ // Has the user already passed '--'? Meaning only positional args follow
+ if !trailing_values {
+ if self.cmd.is_subcommand_precedence_over_arg_set()
+ || !matches!(parse_state, ParseState::Opt(_) | ParseState::Pos(_))
+ {
+ // Does the arg match a subcommand name, or any of its aliases (if defined)
+ let sc_name = self.possible_subcommand(arg_os.to_value(), valid_arg_found);
+ debug!("Parser::get_matches_with: sc={:?}", sc_name);
+ if let Some(sc_name) = sc_name {
+ #[allow(deprecated)]
+ if sc_name == "help"
+ && !self.is_set(AS::NoAutoHelp)
+ && !self.cmd.is_disable_help_subcommand_set()
+ {
+ self.parse_help_subcommand(raw_args.remaining(&mut args_cursor))?;
+ unreachable!("`parse_help_subcommand` always errors");
+ } else {
+ subcmd_name = Some(sc_name.to_owned());
+ }
+ break;
+ }
+ }
+
+ if arg_os.is_escape() {
+ if matches!(&parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
+ self.cmd[opt].is_allow_hyphen_values_set())
+ {
+ // ParseResult::MaybeHyphenValue, do nothing
+ } else {
+ debug!("Parser::get_matches_with: setting TrailingVals=true");
+ trailing_values = true;
+ continue;
+ }
+ } else if let Some((long_arg, long_value)) = arg_os.to_long() {
+ let parse_result = self.parse_long_arg(
+ matcher,
+ long_arg,
+ long_value,
+ &parse_state,
+ &mut valid_arg_found,
+ trailing_values,
+ )?;
+ debug!(
+ "Parser::get_matches_with: After parse_long_arg {:?}",
+ parse_result
+ );
+ match parse_result {
+ ParseResult::NoArg => {
+ unreachable!("`to_long` always has the flag specified")
+ }
+ ParseResult::ValuesDone => {
+ parse_state = ParseState::ValuesDone;
+ continue;
+ }
+ ParseResult::Opt(id) => {
+ parse_state = ParseState::Opt(id);
+ continue;
+ }
+ ParseResult::FlagSubCommand(name) => {
+ debug!(
+ "Parser::get_matches_with: FlagSubCommand found in long arg {:?}",
+ &name
+ );
+ subcmd_name = Some(name);
+ break;
+ }
+ ParseResult::EqualsNotProvided { arg } => {
+ let _ = self.resolve_pending(matcher);
+ return Err(ClapError::no_equals(
+ self.cmd,
+ arg,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+ ParseResult::NoMatchingArg { arg } => {
+ let _ = self.resolve_pending(matcher);
+ let remaining_args: Vec<_> = raw_args
+ .remaining(&mut args_cursor)
+ .map(|x| x.to_str().expect(INVALID_UTF8))
+ .collect();
+ return Err(self.did_you_mean_error(&arg, matcher, &remaining_args));
+ }
+ ParseResult::UnneededAttachedValue { rest, used, arg } => {
+ let _ = self.resolve_pending(matcher);
+ return Err(ClapError::too_many_values(
+ self.cmd,
+ rest,
+ arg,
+ Usage::new(self.cmd).create_usage_no_title(&used),
+ ));
+ }
+ ParseResult::MaybeHyphenValue => {
+ // Maybe a hyphen value, do nothing.
+ }
+ ParseResult::AttachedValueNotConsumed => {
+ unreachable!()
+ }
+ }
+ } else if let Some(short_arg) = arg_os.to_short() {
+ // Arg looks like a short flag, and not a possible number
+
+ // Try to parse short args like normal, if allow_hyphen_values or
+ // AllowNegativeNumbers is set, parse_short_arg will *not* throw
+ // an error, and instead return Ok(None)
+ let parse_result = self.parse_short_arg(
+ matcher,
+ short_arg,
+ &parse_state,
+ pos_counter,
+ &mut valid_arg_found,
+ trailing_values,
+ )?;
+ // If it's None, we then check if one of those two AppSettings was set
+ debug!(
+ "Parser::get_matches_with: After parse_short_arg {:?}",
+ parse_result
+ );
+ match parse_result {
+ ParseResult::NoArg => {
+ // Is a single dash `-`, try positional.
+ }
+ ParseResult::ValuesDone => {
+ parse_state = ParseState::ValuesDone;
+ continue;
+ }
+ ParseResult::Opt(id) => {
+ parse_state = ParseState::Opt(id);
+ continue;
+ }
+ ParseResult::FlagSubCommand(name) => {
+ // If there are more short flags to be processed, we should keep the state, and later
+ // revisit the current group of short flags skipping the subcommand.
+ keep_state = self
+ .flag_subcmd_at
+ .map(|at| {
+ raw_args
+ .seek(&mut args_cursor, clap_lex::SeekFrom::Current(-1));
+ // Since we are now saving the current state, the number of flags to skip during state recovery should
+ // be the current index (`cur_idx`) minus ONE UNIT TO THE LEFT of the starting position.
+ self.flag_subcmd_skip = self.cur_idx.get() - at + 1;
+ })
+ .is_some();
+
+ debug!(
+ "Parser::get_matches_with:FlagSubCommandShort: subcmd_name={}, keep_state={}, flag_subcmd_skip={}",
+ name,
+ keep_state,
+ self.flag_subcmd_skip
+ );
+
+ subcmd_name = Some(name);
+ break;
+ }
+ ParseResult::EqualsNotProvided { arg } => {
+ let _ = self.resolve_pending(matcher);
+ return Err(ClapError::no_equals(
+ self.cmd,
+ arg,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+ ParseResult::NoMatchingArg { arg } => {
+ let _ = self.resolve_pending(matcher);
+ return Err(ClapError::unknown_argument(
+ self.cmd,
+ arg,
+ None,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+ ParseResult::MaybeHyphenValue => {
+ // Maybe a hyphen value, do nothing.
+ }
+ ParseResult::UnneededAttachedValue { .. }
+ | ParseResult::AttachedValueNotConsumed => unreachable!(),
+ }
+ }
+
+ if let ParseState::Opt(id) = &parse_state {
+ // Assume this is a value of a previous arg.
+
+ // get the option so we can check the settings
+ let arg_values = matcher.pending_values_mut(id, None);
+ let arg = &self.cmd[id];
+ let parse_result = self.split_arg_values(
+ arg,
+ arg_os.to_value_os(),
+ trailing_values,
+ arg_values,
+ );
+ let parse_result = parse_result.unwrap_or_else(|| {
+ if matcher.needs_more_vals(arg) {
+ ParseResult::Opt(arg.id.clone())
+ } else {
+ ParseResult::ValuesDone
+ }
+ });
+ parse_state = match parse_result {
+ ParseResult::Opt(id) => ParseState::Opt(id),
+ ParseResult::ValuesDone => ParseState::ValuesDone,
+ _ => unreachable!(),
+ };
+ // get the next value from the iterator
+ continue;
+ }
+ }
+
+ // 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);
+ return Err(ClapError::unknown_argument(
+ self.cmd,
+ arg_os.display().to_string(),
+ None,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+
+ if self.cmd.is_trailing_var_arg_set() && pos_counter == positional_count {
+ trailing_values = true;
+ }
+
+ if matcher.pending_arg_id() != Some(&arg.id) || !arg.is_multiple_values_set() {
+ self.resolve_pending(matcher)?;
+ }
+ let arg_values = matcher.pending_values_mut(&arg.id, Some(Identifier::Index));
+ let _parse_result =
+ self.split_arg_values(arg, arg_os.to_value_os(), trailing_values, arg_values);
+ if let Some(_parse_result) = _parse_result {
+ if _parse_result != ParseResult::ValuesDone {
+ debug!(
+ "Parser::get_matches_with: Ignoring state {:?}; positionals do their own thing",
+ _parse_result
+ );
+ }
+ }
+
+ // Only increment the positional counter if it doesn't allow multiples
+ if !arg.is_multiple() {
+ pos_counter += 1;
+ parse_state = ParseState::ValuesDone;
+ } else {
+ parse_state = ParseState::Pos(arg.id.clone());
+ }
+ valid_arg_found = true;
+ } else if let Some(external_parser) =
+ self.cmd.get_external_subcommand_value_parser().cloned()
+ {
+ // Get external subcommand name
+ let sc_name = match arg_os.to_value() {
+ Ok(s) => s.to_string(),
+ Err(_) => {
+ let _ = self.resolve_pending(matcher);
+ return Err(ClapError::invalid_utf8(
+ self.cmd,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+ };
+
+ // Collect the external subcommand args
+ let mut sc_m = ArgMatcher::new(self.cmd);
+ if cfg!(feature = "unstable-v4") || !raw_args.is_end(&args_cursor) {
+ sc_m.start_occurrence_of_external(self.cmd);
+ }
+
+ for raw_val in raw_args.remaining(&mut args_cursor) {
+ let val = external_parser.parse_ref(self.cmd, None, raw_val)?;
+ let external_id = &Id::empty_hash();
+ sc_m.add_val_to(external_id, val, raw_val.to_os_string());
+ }
+
+ matcher.subcommand(SubCommand {
+ id: Id::from(&*sc_name),
+ name: sc_name,
+ matches: sc_m.into_inner(),
+ });
+
+ self.resolve_pending(matcher)?;
+ #[cfg(feature = "env")]
+ self.add_env(matcher)?;
+ self.add_defaults(matcher)?;
+ return Validator::new(self.cmd).validate(parse_state, matcher);
+ } else {
+ // Start error processing
+ let _ = self.resolve_pending(matcher);
+ return Err(self.match_arg_error(&arg_os, valid_arg_found, trailing_values));
+ }
+ }
+
+ if let Some(ref pos_sc_name) = subcmd_name {
+ let sc_name = self
+ .cmd
+ .find_subcommand(pos_sc_name)
+ .expect(INTERNAL_ERROR_MSG)
+ .get_name()
+ .to_owned();
+ self.parse_subcommand(&sc_name, matcher, raw_args, args_cursor, keep_state)?;
+ }
+
+ self.resolve_pending(matcher)?;
+ #[cfg(feature = "env")]
+ self.add_env(matcher)?;
+ self.add_defaults(matcher)?;
+ Validator::new(self.cmd).validate(parse_state, matcher)
+ }
+
+ fn match_arg_error(
+ &self,
+ arg_os: &clap_lex::ParsedArg<'_>,
+ valid_arg_found: bool,
+ trailing_values: bool,
+ ) -> ClapError {
+ // If argument follows a `--`
+ if trailing_values {
+ // If the arg matches a subcommand name, or any of its aliases (if defined)
+ if self
+ .possible_subcommand(arg_os.to_value(), valid_arg_found)
+ .is_some()
+ {
+ return ClapError::unnecessary_double_dash(
+ self.cmd,
+ arg_os.display().to_string(),
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ );
+ }
+ }
+ let candidates = suggestions::did_you_mean(
+ &arg_os.display().to_string(),
+ self.cmd.all_subcommand_names(),
+ );
+ // If the argument looks like a subcommand.
+ if !candidates.is_empty() {
+ let candidates: Vec<_> = candidates
+ .iter()
+ .map(|candidate| format!("'{}'", candidate))
+ .collect();
+ return ClapError::invalid_subcommand(
+ self.cmd,
+ arg_os.display().to_string(),
+ candidates.join(" or "),
+ self.cmd
+ .get_bin_name()
+ .unwrap_or_else(|| self.cmd.get_name())
+ .to_owned(),
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ );
+ }
+ // If the argument must be a subcommand.
+ if !self.cmd.has_args() || self.cmd.is_infer_subcommands_set() && self.cmd.has_subcommands()
+ {
+ return ClapError::unrecognized_subcommand(
+ self.cmd,
+ arg_os.display().to_string(),
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ );
+ }
+ ClapError::unknown_argument(
+ self.cmd,
+ arg_os.display().to_string(),
+ None,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ )
+ }
+
+ // Checks if the arg matches a subcommand name, or any of its aliases (if defined)
+ fn possible_subcommand(
+ &self,
+ arg: Result<&str, &RawOsStr>,
+ valid_arg_found: bool,
+ ) -> Option<&str> {
+ debug!("Parser::possible_subcommand: arg={:?}", arg);
+ let arg = arg.ok()?;
+
+ if !(self.cmd.is_args_conflicts_with_subcommands_set() && valid_arg_found) {
+ if self.cmd.is_infer_subcommands_set() {
+ // For subcommand `test`, we accepts it's prefix: `t`, `te`,
+ // `tes` and `test`.
+ let v = self
+ .cmd
+ .all_subcommand_names()
+ .filter(|s| s.starts_with(arg))
+ .collect::<Vec<_>>();
+
+ if v.len() == 1 {
+ return Some(v[0]);
+ }
+
+ // If there is any ambiguity, fallback to non-infer subcommand
+ // search.
+ }
+ if let Some(sc) = self.cmd.find_subcommand(arg) {
+ return Some(sc.get_name());
+ }
+ }
+ None
+ }
+
+ // Checks if the arg matches a long flag subcommand name, or any of its aliases (if defined)
+ fn possible_long_flag_subcommand(&self, arg: &str) -> Option<&str> {
+ debug!("Parser::possible_long_flag_subcommand: arg={:?}", arg);
+ if self.cmd.is_infer_subcommands_set() {
+ let options = self
+ .cmd
+ .get_subcommands()
+ .fold(Vec::new(), |mut options, sc| {
+ if let Some(long) = sc.get_long_flag() {
+ if long.starts_with(arg) {
+ options.push(long);
+ }
+ options.extend(sc.get_all_aliases().filter(|alias| alias.starts_with(arg)))
+ }
+ options
+ });
+ if options.len() == 1 {
+ return Some(options[0]);
+ }
+
+ for sc in options {
+ if sc == arg {
+ return Some(sc);
+ }
+ }
+ } else if let Some(sc_name) = self.cmd.find_long_subcmd(arg) {
+ return Some(sc_name);
+ }
+ None
+ }
+
+ fn parse_help_subcommand(
+ &self,
+ cmds: impl Iterator<Item = &'cmd OsStr>,
+ ) -> ClapResult<std::convert::Infallible> {
+ debug!("Parser::parse_help_subcommand");
+
+ let mut cmd = self.cmd.clone();
+ let sc = {
+ let mut sc = &mut cmd;
+
+ for cmd in cmds {
+ sc = if let Some(sc_name) =
+ sc.find_subcommand(cmd).map(|sc| sc.get_name().to_owned())
+ {
+ sc._build_subcommand(&sc_name).unwrap()
+ } else {
+ return Err(ClapError::unrecognized_subcommand(
+ sc,
+ cmd.to_string_lossy().into_owned(),
+ Usage::new(sc).create_usage_with_title(&[]),
+ ));
+ };
+ }
+
+ sc
+ };
+ let parser = Parser::new(sc);
+
+ Err(parser.help_err(true, Stream::Stdout))
+ }
+
+ fn is_new_arg(&self, next: &clap_lex::ParsedArg<'_>, current_positional: &Arg) -> bool {
+ #![allow(clippy::needless_bool)] // Prefer consistent if/else-if ladder
+
+ debug!(
+ "Parser::is_new_arg: {:?}:{:?}",
+ next.to_value_os(),
+ current_positional.name
+ );
+
+ if self.cmd.is_allow_hyphen_values_set()
+ || self.cmd[&current_positional.id].is_allow_hyphen_values_set()
+ || (self.cmd.is_allow_negative_numbers_set() && next.is_number())
+ {
+ // If allow hyphen, this isn't a new arg.
+ debug!("Parser::is_new_arg: Allow hyphen");
+ false
+ } else if next.is_long() {
+ // If this is a long flag, this is a new arg.
+ debug!("Parser::is_new_arg: --<something> found");
+ true
+ } else if next.is_short() {
+ // If this is a short flag, this is a new arg. But a singe '-' by
+ // itself is a value and typically means "stdin" on unix systems.
+ debug!("Parser::is_new_arg: -<something> found");
+ true
+ } else {
+ // Nothing special, this is a value.
+ debug!("Parser::is_new_arg: value");
+ false
+ }
+ }
+
+ fn parse_subcommand(
+ &mut self,
+ sc_name: &str,
+ matcher: &mut ArgMatcher,
+ raw_args: &mut clap_lex::RawArgs,
+ args_cursor: clap_lex::ArgCursor,
+ keep_state: bool,
+ ) -> ClapResult<()> {
+ debug!("Parser::parse_subcommand");
+
+ let partial_parsing_enabled = self.cmd.is_ignore_errors_set();
+
+ if let Some(sc) = self.cmd._build_subcommand(sc_name) {
+ let mut sc_matcher = ArgMatcher::new(sc);
+
+ debug!(
+ "Parser::parse_subcommand: About to parse sc={}",
+ sc.get_name()
+ );
+
+ {
+ let mut p = Parser::new(sc);
+ // HACK: maintain indexes between parsers
+ // FlagSubCommand short arg needs to revisit the current short args, but skip the subcommand itself
+ if keep_state {
+ p.cur_idx.set(self.cur_idx.get());
+ p.flag_subcmd_at = self.flag_subcmd_at;
+ p.flag_subcmd_skip = self.flag_subcmd_skip;
+ }
+ if let Err(error) = p.get_matches_with(&mut sc_matcher, raw_args, args_cursor) {
+ if partial_parsing_enabled {
+ debug!(
+ "Parser::parse_subcommand: ignored error in subcommand {}: {:?}",
+ sc_name, error
+ );
+ } else {
+ return Err(error);
+ }
+ }
+ }
+ matcher.subcommand(SubCommand {
+ id: sc.get_id(),
+ name: sc.get_name().to_owned(),
+ matches: sc_matcher.into_inner(),
+ });
+ }
+ Ok(())
+ }
+
+ fn parse_long_arg(
+ &mut self,
+ matcher: &mut ArgMatcher,
+ long_arg: Result<&str, &RawOsStr>,
+ long_value: Option<&RawOsStr>,
+ parse_state: &ParseState,
+ valid_arg_found: &mut bool,
+ trailing_values: bool,
+ ) -> ClapResult<ParseResult> {
+ // maybe here lifetime should be 'a
+ debug!("Parser::parse_long_arg");
+
+ if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
+ self.cmd[opt].is_allow_hyphen_values_set())
+ {
+ return Ok(ParseResult::MaybeHyphenValue);
+ }
+
+ debug!("Parser::parse_long_arg: Does it contain '='...");
+ let long_arg = match long_arg {
+ Ok(long_arg) => long_arg,
+ Err(long_arg) => {
+ return Ok(ParseResult::NoMatchingArg {
+ arg: long_arg.to_str_lossy().into_owned(),
+ });
+ }
+ };
+ if long_arg.is_empty() {
+ 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) {
+ debug!(
+ "Parser::parse_long_arg: Found valid arg or flag '{}'",
+ arg.to_string()
+ );
+ Some((long_arg, arg))
+ } else if self.cmd.is_infer_long_args_set() {
+ self.cmd.get_arguments().find_map(|a| {
+ if let Some(long) = a.long {
+ if long.starts_with(long_arg) {
+ return Some((long, a));
+ }
+ }
+ a.aliases
+ .iter()
+ .find_map(|(alias, _)| alias.starts_with(long_arg).then(|| (*alias, a)))
+ })
+ } else {
+ None
+ };
+
+ if let Some((_long_arg, arg)) = arg {
+ let ident = Identifier::Long;
+ *valid_arg_found = true;
+ if arg.is_takes_value_set() {
+ debug!(
+ "Parser::parse_long_arg({:?}): Found an arg with value '{:?}'",
+ long_arg, &long_value
+ );
+ let has_eq = long_value.is_some();
+ self.parse_opt_value(ident, long_value, arg, matcher, trailing_values, has_eq)
+ } else if let Some(rest) = long_value {
+ let required = self.cmd.required_graph();
+ debug!(
+ "Parser::parse_long_arg({:?}): Got invalid literal `{:?}`",
+ long_arg, rest
+ );
+ let used: Vec<Id> = matcher
+ .arg_ids()
+ .filter(|arg_id| {
+ matcher.check_explicit(arg_id, crate::builder::ArgPredicate::IsPresent)
+ })
+ .filter(|&n| {
+ self.cmd
+ .find(n)
+ .map_or(true, |a| !(a.is_hide_set() || required.contains(&a.id)))
+ })
+ .cloned()
+ .collect();
+
+ Ok(ParseResult::UnneededAttachedValue {
+ rest: rest.to_str_lossy().into_owned(),
+ used,
+ arg: arg.to_string(),
+ })
+ } else {
+ debug!("Parser::parse_long_arg({:?}): Presence validated", long_arg);
+ self.react(Some(ident), ValueSource::CommandLine, arg, vec![], matcher)
+ }
+ } else if let Some(sc_name) = self.possible_long_flag_subcommand(long_arg) {
+ Ok(ParseResult::FlagSubCommand(sc_name.to_string()))
+ } else if self.cmd.is_allow_hyphen_values_set() {
+ Ok(ParseResult::MaybeHyphenValue)
+ } else {
+ Ok(ParseResult::NoMatchingArg {
+ arg: long_arg.to_owned(),
+ })
+ }
+ }
+
+ fn parse_short_arg(
+ &mut self,
+ matcher: &mut ArgMatcher,
+ mut short_arg: clap_lex::ShortFlags<'_>,
+ parse_state: &ParseState,
+ // change this to possible pos_arg when removing the usage of &mut Parser.
+ pos_counter: usize,
+ valid_arg_found: &mut bool,
+ trailing_values: bool,
+ ) -> ClapResult<ParseResult> {
+ debug!("Parser::parse_short_arg: short_arg={:?}", short_arg);
+
+ #[allow(clippy::blocks_in_if_conditions)]
+ if self.cmd.is_allow_negative_numbers_set() && short_arg.is_number() {
+ debug!("Parser::parse_short_arg: negative number");
+ return Ok(ParseResult::MaybeHyphenValue);
+ } else if self.cmd.is_allow_hyphen_values_set()
+ && short_arg
+ .clone()
+ .any(|c| !c.map(|c| self.cmd.contains_short(c)).unwrap_or_default())
+ {
+ debug!("Parser::parse_short_args: contains non-short flag");
+ return Ok(ParseResult::MaybeHyphenValue);
+ } else if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt)
+ if self.cmd[opt].is_allow_hyphen_values_set())
+ {
+ debug!("Parser::parse_short_args: prior arg accepts hyphenated values",);
+ return Ok(ParseResult::MaybeHyphenValue);
+ } else if self
+ .cmd
+ .get_keymap()
+ .get(&pos_counter)
+ .map_or(false, |arg| {
+ arg.is_allow_hyphen_values_set() && !arg.is_last_set()
+ })
+ {
+ debug!(
+ "Parser::parse_short_args: positional at {} allows hyphens",
+ pos_counter
+ );
+ return Ok(ParseResult::MaybeHyphenValue);
+ }
+
+ let mut ret = ParseResult::NoArg;
+
+ let skip = self.flag_subcmd_skip;
+ self.flag_subcmd_skip = 0;
+ let res = short_arg.advance_by(skip);
+ debug_assert_eq!(
+ res,
+ Ok(()),
+ "tracking of `flag_subcmd_skip` is off for `{:?}`",
+ short_arg
+ );
+ while let Some(c) = short_arg.next_flag() {
+ let c = match c {
+ Ok(c) => c,
+ Err(rest) => {
+ return Ok(ParseResult::NoMatchingArg {
+ arg: format!("-{}", rest.to_str_lossy()),
+ });
+ }
+ };
+ debug!("Parser::parse_short_arg:iter:{}", c);
+
+ // Check for matching short options, and return the name if there is no trailing
+ // concatenated value: -oval
+ // Option: -o
+ // Value: val
+ if let Some(arg) = self.cmd.get_keymap().get(&c) {
+ let ident = Identifier::Short;
+ debug!(
+ "Parser::parse_short_arg:iter:{}: Found valid opt or flag",
+ c
+ );
+ *valid_arg_found = true;
+ if !arg.is_takes_value_set() {
+ ret =
+ self.react(Some(ident), ValueSource::CommandLine, arg, vec![], matcher)?;
+ continue;
+ }
+
+ // Check for trailing concatenated value
+ //
+ // Cloning the iterator, so we rollback if it isn't there.
+ let val = short_arg.clone().next_value_os().unwrap_or_default();
+ debug!(
+ "Parser::parse_short_arg:iter:{}: val={:?} (bytes), val={:?} (ascii), short_arg={:?}",
+ c, val, val.as_raw_bytes(), short_arg
+ );
+ let val = Some(val).filter(|v| !v.is_empty());
+
+ // Default to "we're expecting a value later".
+ //
+ // If attached value is not consumed, we may have more short
+ // flags to parse, continue.
+ //
+ // e.g. `-xvf`, when require_equals && x.min_vals == 0, we don't
+ // consume the `vf`, even if it's provided as value.
+ let (val, has_eq) = if let Some(val) = val.and_then(|v| v.strip_prefix('=')) {
+ (Some(val), true)
+ } else {
+ (val, false)
+ };
+ match self.parse_opt_value(ident, val, arg, matcher, trailing_values, has_eq)? {
+ ParseResult::AttachedValueNotConsumed => continue,
+ x => return Ok(x),
+ }
+ }
+
+ return if let Some(sc_name) = self.cmd.find_short_subcmd(c) {
+ debug!("Parser::parse_short_arg:iter:{}: subcommand={}", c, sc_name);
+ // Make sure indices get updated before reading `self.cur_idx`
+ self.resolve_pending(matcher)?;
+ self.cur_idx.set(self.cur_idx.get() + 1);
+ debug!("Parser::parse_short_arg: cur_idx:={}", self.cur_idx.get());
+
+ let name = sc_name.to_string();
+ // Get the index of the previously saved flag subcommand in the group of flags (if exists).
+ // If it is a new flag subcommand, then the formentioned index should be the current one
+ // (ie. `cur_idx`), and should be registered.
+ let cur_idx = self.cur_idx.get();
+ self.flag_subcmd_at.get_or_insert(cur_idx);
+ let done_short_args = short_arg.is_empty();
+ if done_short_args {
+ self.flag_subcmd_at = None;
+ }
+ Ok(ParseResult::FlagSubCommand(name))
+ } else {
+ Ok(ParseResult::NoMatchingArg {
+ arg: format!("-{}", c),
+ })
+ };
+ }
+ Ok(ret)
+ }
+
+ fn parse_opt_value(
+ &self,
+ ident: Identifier,
+ attached_value: Option<&RawOsStr>,
+ arg: &Arg<'help>,
+ matcher: &mut ArgMatcher,
+ trailing_values: bool,
+ has_eq: bool,
+ ) -> ClapResult<ParseResult> {
+ debug!(
+ "Parser::parse_opt_value; arg={}, val={:?}, has_eq={:?}",
+ arg.name, attached_value, has_eq
+ );
+ debug!("Parser::parse_opt_value; arg.settings={:?}", arg.settings);
+
+ debug!("Parser::parse_opt_value; Checking for val...");
+ // require_equals is set, but no '=' is provided, try throwing error.
+ if arg.is_require_equals_set() && !has_eq {
+ if arg.min_vals == Some(0) {
+ debug!("Requires equals, but min_vals == 0");
+ let mut arg_values = Vec::new();
+ // We assume this case is valid: require equals, but min_vals == 0.
+ if !arg.default_missing_vals.is_empty() {
+ debug!("Parser::parse_opt_value: has default_missing_vals");
+ for v in arg.default_missing_vals.iter() {
+ let trailing_values = false; // CLI should not be affecting default_missing_values
+ let _parse_result = self.split_arg_values(
+ arg,
+ &RawOsStr::new(v),
+ trailing_values,
+ &mut arg_values,
+ );
+ if let Some(_parse_result) = _parse_result {
+ if _parse_result != ParseResult::ValuesDone {
+ debug!("Parser::parse_opt_value: Ignoring state {:?}; no values accepted after default_missing_values", _parse_result);
+ }
+ }
+ }
+ };
+ let react_result = self.react(
+ Some(ident),
+ ValueSource::CommandLine,
+ arg,
+ arg_values,
+ matcher,
+ )?;
+ debug_assert_eq!(react_result, ParseResult::ValuesDone);
+ if attached_value.is_some() {
+ Ok(ParseResult::AttachedValueNotConsumed)
+ } else {
+ Ok(ParseResult::ValuesDone)
+ }
+ } else {
+ debug!("Requires equals but not provided. Error.");
+ Ok(ParseResult::EqualsNotProvided {
+ arg: arg.to_string(),
+ })
+ }
+ } else if let Some(v) = attached_value {
+ let mut arg_values = Vec::new();
+ let parse_result = self.split_arg_values(arg, v, trailing_values, &mut arg_values);
+ let react_result = self.react(
+ Some(ident),
+ ValueSource::CommandLine,
+ arg,
+ arg_values,
+ matcher,
+ )?;
+ debug_assert_eq!(react_result, ParseResult::ValuesDone);
+ let mut parse_result = parse_result.unwrap_or_else(|| {
+ if matcher.needs_more_vals(arg) {
+ ParseResult::Opt(arg.id.clone())
+ } else {
+ ParseResult::ValuesDone
+ }
+ });
+ if parse_result != ParseResult::ValuesDone {
+ debug!("Parser::parse_opt_value: Overriding state {:?}; no values accepted after attached", parse_result);
+ parse_result = ParseResult::ValuesDone;
+ }
+ Ok(parse_result)
+ } else {
+ debug!("Parser::parse_opt_value: More arg vals required...");
+ self.resolve_pending(matcher)?;
+ matcher.pending_values_mut(&arg.id, Some(ident));
+ Ok(ParseResult::Opt(arg.id.clone()))
+ }
+ }
+
+ fn split_arg_values(
+ &self,
+ arg: &Arg<'help>,
+ val: &RawOsStr,
+ trailing_values: bool,
+ output: &mut Vec<OsString>,
+ ) -> Option<ParseResult> {
+ debug!("Parser::split_arg_values; arg={}, val={:?}", arg.name, val);
+ debug!(
+ "Parser::split_arg_values; trailing_values={:?}, DontDelimTrailingVals={:?}",
+ trailing_values,
+ self.cmd.is_dont_delimit_trailing_values_set()
+ );
+
+ let mut delim = arg.val_delim;
+ if trailing_values && self.cmd.is_dont_delimit_trailing_values_set() {
+ delim = None;
+ }
+ match delim {
+ Some(delim) if val.contains(delim) => {
+ let vals = val.split(delim).map(|x| x.to_os_str().into_owned());
+ for raw_val in vals {
+ if Some(raw_val.as_os_str()) == arg.terminator.map(OsStr::new) {
+ return Some(ParseResult::ValuesDone);
+ }
+ output.push(raw_val);
+ }
+ // Delimited values are always considered the final value
+ Some(ParseResult::ValuesDone)
+ }
+ _ if Some(val) == arg.terminator.map(RawOsStr::from_str) => {
+ Some(ParseResult::ValuesDone)
+ }
+ _ => {
+ output.push(val.to_os_str().into_owned());
+ if arg.is_require_value_delimiter_set() {
+ Some(ParseResult::ValuesDone)
+ } else {
+ None
+ }
+ }
+ }
+ }
+
+ fn push_arg_values(
+ &self,
+ arg: &Arg<'help>,
+ raw_vals: Vec<OsString>,
+ matcher: &mut ArgMatcher,
+ ) -> ClapResult<()> {
+ debug!("Parser::push_arg_values: {:?}", raw_vals);
+
+ for raw_val in raw_vals {
+ // update the current index because each value is a distinct index to clap
+ self.cur_idx.set(self.cur_idx.get() + 1);
+ debug!(
+ "Parser::add_single_val_to_arg: cur_idx:={}",
+ self.cur_idx.get()
+ );
+ let value_parser = arg.get_value_parser();
+ let val = value_parser.parse_ref(self.cmd, Some(arg), &raw_val)?;
+
+ // Increment or create the group "args"
+ for group in self.cmd.groups_for_arg(&arg.id) {
+ matcher.add_val_to(&group, val.clone(), raw_val.clone());
+ }
+
+ matcher.add_val_to(&arg.id, val, raw_val);
+ matcher.add_index_to(&arg.id, self.cur_idx.get());
+ }
+
+ Ok(())
+ }
+
+ fn resolve_pending(&self, matcher: &mut ArgMatcher) -> ClapResult<()> {
+ let pending = match matcher.take_pending() {
+ Some(pending) => pending,
+ None => {
+ return Ok(());
+ }
+ };
+
+ debug!("Parser::resolve_pending: id={:?}", pending.id);
+ let arg = self.cmd.find(&pending.id).expect(INTERNAL_ERROR_MSG);
+ let _ = self.react(
+ pending.ident,
+ ValueSource::CommandLine,
+ arg,
+ pending.raw_vals,
+ matcher,
+ )?;
+
+ Ok(())
+ }
+
+ fn react(
+ &self,
+ ident: Option<Identifier>,
+ source: ValueSource,
+ arg: &Arg<'help>,
+ raw_vals: Vec<OsString>,
+ matcher: &mut ArgMatcher,
+ ) -> ClapResult<ParseResult> {
+ self.resolve_pending(matcher)?;
+
+ debug!(
+ "Parser::react action={:?}, identifier={:?}, source={:?}",
+ arg.get_action(),
+ ident,
+ source
+ );
+ match arg.get_action() {
+ ArgAction::Set => {
+ if source == ValueSource::CommandLine
+ && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long))
+ {
+ // Record flag's index
+ self.cur_idx.set(self.cur_idx.get() + 1);
+ debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
+ }
+ matcher.remove(&arg.id);
+ self.start_custom_arg(matcher, arg, source);
+ self.push_arg_values(arg, raw_vals, matcher)?;
+ if cfg!(debug_assertions) && matcher.needs_more_vals(arg) {
+ debug!(
+ "Parser::react not enough values passed in, leaving it to the validator to complain",
+ );
+ }
+ Ok(ParseResult::ValuesDone)
+ }
+ ArgAction::Append => {
+ if source == ValueSource::CommandLine
+ && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long))
+ {
+ // Record flag's index
+ self.cur_idx.set(self.cur_idx.get() + 1);
+ debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
+ }
+ self.start_custom_arg(matcher, arg, source);
+ self.push_arg_values(arg, raw_vals, matcher)?;
+ if cfg!(debug_assertions) && matcher.needs_more_vals(arg) {
+ debug!(
+ "Parser::react not enough values passed in, leaving it to the validator to complain",
+ );
+ }
+ Ok(ParseResult::ValuesDone)
+ }
+ #[allow(deprecated)]
+ ArgAction::StoreValue => {
+ if ident == Some(Identifier::Index)
+ && arg.is_multiple_values_set()
+ && matcher.contains(&arg.id)
+ {
+ // HACK: Reuse existing occurrence
+ } else if source == ValueSource::CommandLine {
+ if matches!(ident, Some(Identifier::Short) | Some(Identifier::Long)) {
+ // Record flag's index
+ self.cur_idx.set(self.cur_idx.get() + 1);
+ debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
+ }
+ self.start_occurrence_of_arg(matcher, arg);
+ } else {
+ self.start_custom_arg(matcher, arg, source);
+ }
+ self.push_arg_values(arg, raw_vals, matcher)?;
+ if ident == Some(Identifier::Index) && arg.is_multiple_values_set() {
+ // HACK: Maintain existing occurrence behavior
+ let matched = matcher.get_mut(&arg.id).unwrap();
+ #[allow(deprecated)]
+ matched.set_occurrences(matched.num_vals() as u64);
+ }
+ if cfg!(debug_assertions) && matcher.needs_more_vals(arg) {
+ debug!(
+ "Parser::react not enough values passed in, leaving it to the validator to complain",
+ );
+ }
+ Ok(ParseResult::ValuesDone)
+ }
+ #[allow(deprecated)]
+ ArgAction::IncOccurrence => {
+ debug_assert_eq!(raw_vals, Vec::<OsString>::new());
+ if source == ValueSource::CommandLine {
+ if matches!(ident, Some(Identifier::Short) | Some(Identifier::Long)) {
+ // Record flag's index
+ self.cur_idx.set(self.cur_idx.get() + 1);
+ debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
+ }
+ self.start_occurrence_of_arg(matcher, arg);
+ } else {
+ self.start_custom_arg(matcher, arg, source);
+ }
+ matcher.add_index_to(&arg.id, self.cur_idx.get());
+ Ok(ParseResult::ValuesDone)
+ }
+ ArgAction::SetTrue => {
+ let raw_vals = match raw_vals.len() {
+ 0 => {
+ vec![OsString::from("true")]
+ }
+ 1 => raw_vals,
+ _ => {
+ debug!("Parser::react ignoring trailing values: {:?}", raw_vals);
+ let mut raw_vals = raw_vals;
+ raw_vals.resize(1, Default::default());
+ raw_vals
+ }
+ };
+
+ matcher.remove(&arg.id);
+ self.start_custom_arg(matcher, arg, source);
+ self.push_arg_values(arg, raw_vals, matcher)?;
+ Ok(ParseResult::ValuesDone)
+ }
+ ArgAction::SetFalse => {
+ let raw_vals = match raw_vals.len() {
+ 0 => {
+ vec![OsString::from("false")]
+ }
+ 1 => raw_vals,
+ _ => {
+ debug!("Parser::react ignoring trailing values: {:?}", raw_vals);
+ let mut raw_vals = raw_vals;
+ raw_vals.resize(1, Default::default());
+ raw_vals
+ }
+ };
+
+ matcher.remove(&arg.id);
+ self.start_custom_arg(matcher, arg, source);
+ self.push_arg_values(arg, raw_vals, matcher)?;
+ Ok(ParseResult::ValuesDone)
+ }
+ ArgAction::Count => {
+ let raw_vals = match raw_vals.len() {
+ 0 => {
+ let existing_value = *matcher
+ .get_one::<crate::builder::CountType>(arg.get_id())
+ .unwrap_or(&0);
+ let next_value = existing_value.saturating_add(1);
+ vec![OsString::from(next_value.to_string())]
+ }
+ 1 => raw_vals,
+ _ => {
+ debug!("Parser::react ignoring trailing values: {:?}", raw_vals);
+ let mut raw_vals = raw_vals;
+ raw_vals.resize(1, Default::default());
+ raw_vals
+ }
+ };
+
+ matcher.remove(&arg.id);
+ self.start_custom_arg(matcher, arg, source);
+ self.push_arg_values(arg, raw_vals, matcher)?;
+ Ok(ParseResult::ValuesDone)
+ }
+ ArgAction::Help => {
+ debug_assert_eq!(raw_vals, Vec::<OsString>::new());
+ let use_long = match ident {
+ Some(Identifier::Long) => true,
+ Some(Identifier::Short) => false,
+ Some(Identifier::Index) => true,
+ None => true,
+ };
+ debug!("Help: use_long={}", use_long);
+ Err(self.help_err(use_long, Stream::Stdout))
+ }
+ ArgAction::Version => {
+ debug_assert_eq!(raw_vals, Vec::<OsString>::new());
+ let use_long = match ident {
+ Some(Identifier::Long) => true,
+ Some(Identifier::Short) => false,
+ Some(Identifier::Index) => true,
+ None => true,
+ };
+ debug!("Version: use_long={}", use_long);
+ Err(self.version_err(use_long))
+ }
+ }
+ }
+
+ fn remove_overrides(&self, arg: &Arg<'help>, matcher: &mut ArgMatcher) {
+ debug!("Parser::remove_overrides: id={:?}", arg.id);
+ for override_id in &arg.overrides {
+ debug!("Parser::remove_overrides:iter:{:?}: removing", override_id);
+ matcher.remove(override_id);
+ }
+
+ // Override anything that can override us
+ let mut transitive = Vec::new();
+ for arg_id in matcher.arg_ids() {
+ if let Some(overrider) = self.cmd.find(arg_id) {
+ if overrider.overrides.contains(&arg.id) {
+ transitive.push(&overrider.id);
+ }
+ }
+ }
+ for overrider_id in transitive {
+ debug!("Parser::remove_overrides:iter:{:?}: removing", overrider_id);
+ matcher.remove(overrider_id);
+ }
+ }
+
+ #[cfg(feature = "env")]
+ fn add_env(&mut self, matcher: &mut ArgMatcher) -> ClapResult<()> {
+ debug!("Parser::add_env");
+ use crate::util::str_to_bool;
+
+ let trailing_values = false; // defaults are independent of the commandline
+ for arg in self.cmd.get_arguments() {
+ // Use env only if the arg was absent among command line args,
+ // early return if this is not the case.
+ if matcher.contains(&arg.id) {
+ debug!("Parser::add_env: Skipping existing arg `{}`", arg);
+ continue;
+ }
+
+ debug!("Parser::add_env: Checking arg `{}`", arg);
+ if let Some((_, Some(ref val))) = arg.env {
+ let val = RawOsStr::new(val);
+
+ if arg.is_takes_value_set() {
+ debug!(
+ "Parser::add_env: Found an opt with value={:?}, trailing={:?}",
+ val, trailing_values
+ );
+ let mut arg_values = Vec::new();
+ let _parse_result =
+ self.split_arg_values(arg, &val, trailing_values, &mut arg_values);
+ let _ = self.react(None, ValueSource::EnvVariable, arg, arg_values, matcher)?;
+ if let Some(_parse_result) = _parse_result {
+ if _parse_result != ParseResult::ValuesDone {
+ debug!("Parser::add_env: Ignoring state {:?}; env variables are outside of the parse loop", _parse_result);
+ }
+ }
+ } else {
+ match arg.get_action() {
+ #[allow(deprecated)]
+ ArgAction::StoreValue => unreachable!("{:?} is not a flag", arg.get_id()),
+ #[allow(deprecated)]
+ ArgAction::IncOccurrence => {
+ debug!("Parser::add_env: Found a flag with value `{:?}`", val);
+ let predicate = str_to_bool(val.to_str_lossy());
+ debug!("Parser::add_env: Found boolean literal `{:?}`", predicate);
+ if predicate.unwrap_or(true) {
+ let _ = self.react(
+ None,
+ ValueSource::EnvVariable,
+ arg,
+ vec![],
+ matcher,
+ )?;
+ }
+ }
+ ArgAction::Set
+ | ArgAction::Append
+ | ArgAction::SetTrue
+ | ArgAction::SetFalse
+ | ArgAction::Count => {
+ let mut arg_values = Vec::new();
+ let _parse_result =
+ self.split_arg_values(arg, &val, trailing_values, &mut arg_values);
+ let _ = self.react(
+ None,
+ ValueSource::EnvVariable,
+ arg,
+ arg_values,
+ matcher,
+ )?;
+ if let Some(_parse_result) = _parse_result {
+ if _parse_result != ParseResult::ValuesDone {
+ debug!("Parser::add_env: Ignoring state {:?}; env variables are outside of the parse loop", _parse_result);
+ }
+ }
+ }
+ // Early return on `Help` or `Version`.
+ ArgAction::Help | ArgAction::Version => {
+ let _ =
+ self.react(None, ValueSource::EnvVariable, arg, vec![], matcher)?;
+ }
+ }
+ }
+ }
+ }
+
+ Ok(())
+ }
+
+ fn add_defaults(&self, matcher: &mut ArgMatcher) -> ClapResult<()> {
+ debug!("Parser::add_defaults");
+
+ for arg in self.cmd.get_arguments() {
+ debug!("Parser::add_defaults:iter:{}:", arg.name);
+ self.add_default_value(arg, matcher)?;
+ }
+
+ Ok(())
+ }
+
+ fn add_default_value(&self, arg: &Arg<'help>, matcher: &mut ArgMatcher) -> ClapResult<()> {
+ let trailing_values = false; // defaults are independent of the commandline
+
+ if !arg.default_missing_vals.is_empty() {
+ debug!(
+ "Parser::add_default_value:iter:{}: has default missing vals",
+ arg.name
+ );
+ match matcher.get(&arg.id) {
+ Some(ma) if ma.all_val_groups_empty() => {
+ debug!(
+ "Parser::add_default_value:iter:{}: has no user defined vals",
+ arg.name
+ );
+ // The flag occurred, we just want to add the val groups
+ let mut arg_values = Vec::new();
+ for v in arg.default_missing_vals.iter() {
+ let _parse_result = self.split_arg_values(
+ arg,
+ &RawOsStr::new(v),
+ trailing_values,
+ &mut arg_values,
+ );
+ if let Some(_parse_result) = _parse_result {
+ if _parse_result != ParseResult::ValuesDone {
+ debug!("Parser::add_default_value: Ignoring state {:?}; defaults are outside of the parse loop", _parse_result);
+ }
+ }
+ }
+ self.start_custom_arg(matcher, arg, ValueSource::CommandLine);
+ self.push_arg_values(arg, arg_values, matcher)?;
+ }
+ None => {
+ debug!("Parser::add_default_value:iter:{}: wasn't used", arg.name);
+ // do nothing
+ }
+ _ => {
+ debug!(
+ "Parser::add_default_value:iter:{}: has user defined vals",
+ arg.name
+ );
+ // do nothing
+ }
+ }
+ } else {
+ debug!(
+ "Parser::add_default_value:iter:{}: doesn't have default missing vals",
+ arg.name
+ );
+ // do nothing
+ }
+
+ if !arg.default_vals_ifs.is_empty() {
+ debug!("Parser::add_default_value: has conditional defaults");
+ if !matcher.contains(&arg.id) {
+ for (id, val, default) in arg.default_vals_ifs.iter() {
+ let add = if let Some(a) = matcher.get(id) {
+ match val {
+ crate::builder::ArgPredicate::Equals(v) => {
+ a.raw_vals_flatten().any(|value| v == value)
+ }
+ crate::builder::ArgPredicate::IsPresent => true,
+ }
+ } else {
+ false
+ };
+
+ if add {
+ if let Some(default) = default {
+ let mut arg_values = Vec::new();
+ let _parse_result = self.split_arg_values(
+ arg,
+ &RawOsStr::new(default),
+ trailing_values,
+ &mut arg_values,
+ );
+ let _ = self.react(
+ None,
+ ValueSource::DefaultValue,
+ arg,
+ arg_values,
+ matcher,
+ )?;
+ if let Some(_parse_result) = _parse_result {
+ if _parse_result != ParseResult::ValuesDone {
+ debug!("Parser::add_default_value: Ignoring state {:?}; defaults are outside of the parse loop", _parse_result);
+ }
+ }
+ }
+ return Ok(());
+ }
+ }
+ }
+ } else {
+ debug!("Parser::add_default_value: doesn't have conditional defaults");
+ }
+
+ if !arg.default_vals.is_empty() {
+ debug!(
+ "Parser::add_default_value:iter:{}: has default vals",
+ arg.name
+ );
+ if matcher.contains(&arg.id) {
+ debug!("Parser::add_default_value:iter:{}: was used", arg.name);
+ // do nothing
+ } else {
+ debug!("Parser::add_default_value:iter:{}: wasn't used", arg.name);
+ let mut arg_values = Vec::new();
+ for v in arg.default_vals.iter() {
+ let _parse_result = self.split_arg_values(
+ arg,
+ &RawOsStr::new(v),
+ trailing_values,
+ &mut arg_values,
+ );
+ if let Some(_parse_result) = _parse_result {
+ if _parse_result != ParseResult::ValuesDone {
+ debug!("Parser::add_default_value: Ignoring state {:?}; defaults are outside of the parse loop", _parse_result);
+ }
+ }
+ }
+ let _ = self.react(None, ValueSource::DefaultValue, arg, arg_values, matcher)?;
+ }
+ } else {
+ debug!(
+ "Parser::add_default_value:iter:{}: doesn't have default vals",
+ arg.name
+ );
+
+ // do nothing
+ }
+
+ Ok(())
+ }
+
+ fn start_custom_arg(&self, matcher: &mut ArgMatcher, arg: &Arg<'help>, source: ValueSource) {
+ if source == ValueSource::CommandLine {
+ // With each new occurrence, remove overrides from prior occurrences
+ self.remove_overrides(arg, matcher);
+ }
+ matcher.start_custom_arg(arg, source);
+ for group in self.cmd.groups_for_arg(&arg.id) {
+ matcher.start_custom_group(&group, source);
+ }
+ }
+
+ /// Increase occurrence of specific argument and the grouped arg it's in.
+ fn start_occurrence_of_arg(&self, matcher: &mut ArgMatcher, arg: &Arg<'help>) {
+ // With each new occurrence, remove overrides from prior occurrences
+ self.remove_overrides(arg, matcher);
+
+ matcher.start_occurrence_of_arg(arg);
+ // Increment or create the group "args"
+ for group in self.cmd.groups_for_arg(&arg.id) {
+ matcher.start_occurrence_of_group(&group);
+ }
+ }
+}
+
+// Error, Help, and Version Methods
+impl<'help, 'cmd> Parser<'help, 'cmd> {
+ /// Is only used for the long flag(which is the only one needs fuzzy searching)
+ fn did_you_mean_error(
+ &mut self,
+ arg: &str,
+ matcher: &mut ArgMatcher,
+ remaining_args: &[&str],
+ ) -> ClapError {
+ debug!("Parser::did_you_mean_error: arg={}", arg);
+ // Didn't match a flag or option
+ let longs = self
+ .cmd
+ .get_keymap()
+ .keys()
+ .filter_map(|x| match x {
+ KeyType::Long(l) => Some(l.to_string_lossy().into_owned()),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+ debug!("Parser::did_you_mean_error: longs={:?}", longs);
+
+ let did_you_mean = suggestions::did_you_mean_flag(
+ arg,
+ remaining_args,
+ longs.iter().map(|x| &x[..]),
+ self.cmd.get_subcommands_mut(),
+ );
+
+ // Add the arg to the matches to build a proper usage string
+ if let Some((name, _)) = did_you_mean.as_ref() {
+ if let Some(arg) = self.cmd.get_keymap().get(&name.as_ref()) {
+ self.start_occurrence_of_arg(matcher, arg);
+ }
+ }
+
+ let required = self.cmd.required_graph();
+ let used: Vec<Id> = matcher
+ .arg_ids()
+ .filter(|arg_id| {
+ matcher.check_explicit(arg_id, crate::builder::ArgPredicate::IsPresent)
+ })
+ .filter(|n| self.cmd.find(n).map_or(true, |a| !a.is_hide_set()))
+ .cloned()
+ .collect();
+
+ ClapError::unknown_argument(
+ self.cmd,
+ format!("--{}", arg),
+ did_you_mean,
+ Usage::new(self.cmd)
+ .required(&required)
+ .create_usage_with_title(&*used),
+ )
+ }
+
+ fn help_err(&self, use_long: bool, stream: Stream) -> ClapError {
+ match self.cmd.write_help_err(use_long, stream) {
+ Ok(c) => ClapError::display_help(self.cmd, c),
+ Err(e) => e,
+ }
+ }
+
+ fn version_err(&self, use_long: bool) -> ClapError {
+ debug!("Parser::version_err");
+
+ let msg = self.cmd._render_version(use_long);
+ let mut c = Colorizer::new(Stream::Stdout, self.cmd.color_help());
+ c.none(msg);
+ ClapError::display_version(self.cmd, c)
+ }
+}
+
+// Query Methods
+impl<'help, 'cmd> Parser<'help, 'cmd> {
+ pub(crate) fn is_set(&self, s: AS) -> bool {
+ self.cmd.is_set(s)
+ }
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) enum ParseState {
+ ValuesDone,
+ Opt(Id),
+ Pos(Id),
+}
+
+/// Recoverable Parsing results.
+#[derive(Debug, PartialEq, Clone)]
+#[must_use]
+enum ParseResult {
+ FlagSubCommand(String),
+ Opt(Id),
+ ValuesDone,
+ /// Value attached to the short flag is not consumed(e.g. 'u' for `-cu` is
+ /// not consumed).
+ AttachedValueNotConsumed,
+ /// This long flag doesn't need a value but is provided one.
+ UnneededAttachedValue {
+ rest: String,
+ used: Vec<Id>,
+ arg: String,
+ },
+ /// This flag might be an hyphen Value.
+ MaybeHyphenValue,
+ /// Equals required but not provided.
+ EqualsNotProvided {
+ arg: String,
+ },
+ /// Failed to match a Arg.
+ NoMatchingArg {
+ arg: String,
+ },
+ /// No argument found e.g. parser is given `-` when parsing a flag.
+ NoArg,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct PendingArg {
+ pub(crate) id: Id,
+ pub(crate) ident: Option<Identifier>,
+ pub(crate) raw_vals: Vec<OsString>,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub(crate) enum Identifier {
+ Short,
+ Long,
+ Index,
+}
diff --git a/3.2.23/src/parser/validator.rs b/3.2.23/src/parser/validator.rs
new file mode 100644
index 0000000..ebf2b23
--- /dev/null
+++ b/3.2.23/src/parser/validator.rs
@@ -0,0 +1,692 @@
+// Internal
+use crate::builder::{AppSettings, Arg, ArgPredicate, Command, PossibleValue};
+use crate::error::{Error, Result as ClapResult};
+use crate::output::fmt::Stream;
+use crate::output::Usage;
+use crate::parser::{ArgMatcher, MatchedArg, ParseState};
+use crate::util::ChildGraph;
+use crate::util::Id;
+use crate::{INTERNAL_ERROR_MSG, INVALID_UTF8};
+
+pub(crate) struct Validator<'help, 'cmd> {
+ cmd: &'cmd Command<'help>,
+ required: ChildGraph<Id>,
+}
+
+impl<'help, 'cmd> Validator<'help, 'cmd> {
+ pub(crate) fn new(cmd: &'cmd Command<'help>) -> Self {
+ let required = cmd.required_graph();
+ Validator { cmd, required }
+ }
+
+ pub(crate) fn validate(
+ &mut self,
+ parse_state: ParseState,
+ matcher: &mut ArgMatcher,
+ ) -> ClapResult<()> {
+ debug!("Validator::validate");
+ let mut conflicts = Conflicts::new();
+ let has_subcmd = matcher.subcommand_name().is_some();
+
+ if let ParseState::Opt(a) = parse_state {
+ debug!("Validator::validate: needs_val_of={:?}", a);
+
+ let o = &self.cmd[&a];
+ let should_err = if let Some(v) = matcher.args.get(&o.id) {
+ v.all_val_groups_empty() && !(o.min_vals.is_some() && o.min_vals.unwrap() == 0)
+ } else {
+ true
+ };
+ if should_err {
+ return Err(Error::empty_value(
+ self.cmd,
+ &get_possible_values(o)
+ .iter()
+ .filter(|pv| !pv.is_hide_set())
+ .map(PossibleValue::get_name)
+ .collect::<Vec<_>>(),
+ o.to_string(),
+ ));
+ }
+ }
+
+ if !has_subcmd && self.cmd.is_arg_required_else_help_set() {
+ let num_user_values = matcher
+ .arg_ids()
+ .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent))
+ .count();
+ if num_user_values == 0 {
+ let message = self.cmd.write_help_err(false, Stream::Stderr)?;
+ return Err(Error::display_help_error(self.cmd, message));
+ }
+ }
+ #[allow(deprecated)]
+ if !has_subcmd && self.cmd.is_subcommand_required_set() {
+ let bn = self
+ .cmd
+ .get_bin_name()
+ .unwrap_or_else(|| self.cmd.get_name());
+ return Err(Error::missing_subcommand(
+ self.cmd,
+ bn.to_string(),
+ Usage::new(self.cmd)
+ .required(&self.required)
+ .create_usage_with_title(&[]),
+ ));
+ } else if !has_subcmd && self.cmd.is_set(AppSettings::SubcommandRequiredElseHelp) {
+ debug!("Validator::new::get_matches_with: SubcommandRequiredElseHelp=true");
+ let message = self.cmd.write_help_err(false, Stream::Stderr)?;
+ return Err(Error::display_help_error(self.cmd, message));
+ }
+
+ self.validate_conflicts(matcher, &mut conflicts)?;
+ if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) {
+ self.validate_required(matcher, &mut conflicts)?;
+ }
+ self.validate_matched_args(matcher)?;
+
+ Ok(())
+ }
+
+ fn validate_arg_values(&self, arg: &Arg, ma: &MatchedArg) -> ClapResult<()> {
+ debug!("Validator::validate_arg_values: arg={:?}", arg.name);
+ for val in ma.raw_vals_flatten() {
+ if !arg.possible_vals.is_empty() {
+ debug!(
+ "Validator::validate_arg_values: possible_vals={:?}",
+ arg.possible_vals
+ );
+ let val_str = val.to_string_lossy();
+ let ok = arg
+ .possible_vals
+ .iter()
+ .any(|pv| pv.matches(&val_str, arg.is_ignore_case_set()));
+ if !ok {
+ return Err(Error::invalid_value(
+ self.cmd,
+ val_str.into_owned(),
+ &arg.possible_vals
+ .iter()
+ .filter(|pv| !pv.is_hide_set())
+ .map(PossibleValue::get_name)
+ .collect::<Vec<_>>(),
+ arg.to_string(),
+ ));
+ }
+ }
+ {
+ #![allow(deprecated)]
+ if arg.is_forbid_empty_values_set() && val.is_empty() {
+ debug!("Validator::validate_arg_values: illegal empty val found");
+ return Err(Error::empty_value(
+ self.cmd,
+ &get_possible_values(arg)
+ .iter()
+ .filter(|pv| !pv.is_hide_set())
+ .map(PossibleValue::get_name)
+ .collect::<Vec<_>>(),
+ arg.to_string(),
+ ));
+ }
+ }
+
+ if let Some(ref vtor) = arg.validator {
+ debug!("Validator::validate_arg_values: checking validator...");
+ let mut vtor = vtor.lock().unwrap();
+ if let Err(e) = vtor(&*val.to_string_lossy()) {
+ debug!("error");
+ return Err(Error::value_validation(
+ arg.to_string(),
+ val.to_string_lossy().into_owned(),
+ e,
+ )
+ .with_cmd(self.cmd));
+ } else {
+ debug!("good");
+ }
+ }
+ if let Some(ref vtor) = arg.validator_os {
+ debug!("Validator::validate_arg_values: checking validator_os...");
+ let mut vtor = vtor.lock().unwrap();
+ if let Err(e) = vtor(val) {
+ debug!("error");
+ return Err(Error::value_validation(
+ arg.to_string(),
+ val.to_string_lossy().into(),
+ e,
+ )
+ .with_cmd(self.cmd));
+ } else {
+ debug!("good");
+ }
+ }
+ }
+ Ok(())
+ }
+
+ fn validate_conflicts(
+ &mut self,
+ matcher: &ArgMatcher,
+ conflicts: &mut Conflicts,
+ ) -> ClapResult<()> {
+ debug!("Validator::validate_conflicts");
+
+ self.validate_exclusive(matcher)?;
+
+ for arg_id in matcher
+ .arg_ids()
+ .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent))
+ .filter(|arg_id| self.cmd.find(arg_id).is_some())
+ {
+ debug!("Validator::validate_conflicts::iter: id={:?}", arg_id);
+ let conflicts = conflicts.gather_conflicts(self.cmd, matcher, arg_id);
+ self.build_conflict_err(arg_id, &conflicts, matcher)?;
+ }
+
+ Ok(())
+ }
+
+ fn validate_exclusive(&self, matcher: &ArgMatcher) -> ClapResult<()> {
+ debug!("Validator::validate_exclusive");
+ let args_count = matcher
+ .arg_ids()
+ .filter(|arg_id| {
+ matcher.check_explicit(arg_id, crate::builder::ArgPredicate::IsPresent)
+ })
+ .count();
+ if args_count <= 1 {
+ // Nothing present to conflict with
+ return Ok(());
+ }
+
+ matcher
+ .arg_ids()
+ .filter(|arg_id| {
+ matcher.check_explicit(arg_id, crate::builder::ArgPredicate::IsPresent)
+ })
+ .filter_map(|name| {
+ debug!("Validator::validate_exclusive:iter:{:?}", name);
+ self.cmd
+ .find(name)
+ // Find `arg`s which are exclusive but also appear with other args.
+ .filter(|&arg| arg.is_exclusive_set() && args_count > 1)
+ })
+ // Throw an error for the first conflict found.
+ .try_for_each(|arg| {
+ Err(Error::argument_conflict(
+ self.cmd,
+ arg.to_string(),
+ Vec::new(),
+ Usage::new(self.cmd)
+ .required(&self.required)
+ .create_usage_with_title(&[]),
+ ))
+ })
+ }
+
+ fn build_conflict_err(
+ &self,
+ name: &Id,
+ conflict_ids: &[Id],
+ matcher: &ArgMatcher,
+ ) -> ClapResult<()> {
+ if conflict_ids.is_empty() {
+ return Ok(());
+ }
+
+ debug!("Validator::build_conflict_err: name={:?}", name);
+ let mut seen = std::collections::HashSet::new();
+ let conflicts = conflict_ids
+ .iter()
+ .flat_map(|c_id| {
+ if self.cmd.find_group(c_id).is_some() {
+ self.cmd.unroll_args_in_group(c_id)
+ } else {
+ vec![c_id.clone()]
+ }
+ })
+ .filter_map(|c_id| {
+ seen.insert(c_id.clone()).then(|| {
+ let c_arg = self.cmd.find(&c_id).expect(INTERNAL_ERROR_MSG);
+ c_arg.to_string()
+ })
+ })
+ .collect();
+
+ let former_arg = self.cmd.find(name).expect(INTERNAL_ERROR_MSG);
+ let usg = self.build_conflict_err_usage(matcher, conflict_ids);
+ Err(Error::argument_conflict(
+ self.cmd,
+ former_arg.to_string(),
+ conflicts,
+ usg,
+ ))
+ }
+
+ fn build_conflict_err_usage(&self, matcher: &ArgMatcher, conflicting_keys: &[Id]) -> String {
+ let used_filtered: Vec<Id> = matcher
+ .arg_ids()
+ .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent))
+ .filter(|n| {
+ // Filter out the args we don't want to specify.
+ self.cmd.find(n).map_or(true, |a| !a.is_hide_set())
+ })
+ .filter(|key| !conflicting_keys.contains(key))
+ .cloned()
+ .collect();
+ let required: Vec<Id> = used_filtered
+ .iter()
+ .filter_map(|key| self.cmd.find(key))
+ .flat_map(|arg| arg.requires.iter().map(|item| &item.1))
+ .filter(|key| !used_filtered.contains(key) && !conflicting_keys.contains(key))
+ .chain(used_filtered.iter())
+ .cloned()
+ .collect();
+ Usage::new(self.cmd)
+ .required(&self.required)
+ .create_usage_with_title(&required)
+ }
+
+ fn gather_requires(&mut self, matcher: &ArgMatcher) {
+ debug!("Validator::gather_requires");
+ for name in matcher
+ .arg_ids()
+ .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent))
+ {
+ debug!("Validator::gather_requires:iter:{:?}", name);
+ if let Some(arg) = self.cmd.find(name) {
+ let is_relevant = |(val, req_arg): &(ArgPredicate<'_>, Id)| -> Option<Id> {
+ let required = matcher.check_explicit(&arg.id, *val);
+ required.then(|| req_arg.clone())
+ };
+
+ for req in self.cmd.unroll_arg_requires(is_relevant, &arg.id) {
+ self.required.insert(req);
+ }
+ } else if let Some(g) = self.cmd.find_group(name) {
+ debug!("Validator::gather_requires:iter:{:?}:group", name);
+ for r in &g.requires {
+ self.required.insert(r.clone());
+ }
+ }
+ }
+ }
+
+ fn validate_matched_args(&self, matcher: &ArgMatcher) -> ClapResult<()> {
+ debug!("Validator::validate_matched_args");
+ matcher.iter().try_for_each(|(name, ma)| {
+ debug!(
+ "Validator::validate_matched_args:iter:{:?}: vals={:#?}",
+ name,
+ ma.vals_flatten()
+ );
+ if let Some(arg) = self.cmd.find(name) {
+ self.validate_arg_num_vals(arg, ma)?;
+ self.validate_arg_values(arg, ma)?;
+ self.validate_arg_num_occurs(arg, ma)?;
+ }
+ Ok(())
+ })
+ }
+
+ fn validate_arg_num_occurs(&self, a: &Arg, ma: &MatchedArg) -> ClapResult<()> {
+ #![allow(deprecated)]
+ debug!(
+ "Validator::validate_arg_num_occurs: {:?}={}",
+ a.name,
+ ma.get_occurrences()
+ );
+ // Occurrence of positional argument equals to number of values rather
+ // than number of grouped values.
+ if ma.get_occurrences() > 1 && !a.is_multiple_occurrences_set() && !a.is_positional() {
+ // Not the first time, and we don't allow multiples
+ return Err(Error::unexpected_multiple_usage(
+ self.cmd,
+ a.to_string(),
+ Usage::new(self.cmd)
+ .required(&self.required)
+ .create_usage_with_title(&[]),
+ ));
+ }
+ if let Some(max_occurs) = a.max_occurs {
+ debug!(
+ "Validator::validate_arg_num_occurs: max_occurs set...{}",
+ max_occurs
+ );
+ let occurs = ma.get_occurrences() as usize;
+ if occurs > max_occurs {
+ return Err(Error::too_many_occurrences(
+ self.cmd,
+ a.to_string(),
+ max_occurs,
+ occurs,
+ Usage::new(self.cmd)
+ .required(&self.required)
+ .create_usage_with_title(&[]),
+ ));
+ }
+ }
+
+ Ok(())
+ }
+
+ fn validate_arg_num_vals(&self, a: &Arg, ma: &MatchedArg) -> ClapResult<()> {
+ debug!("Validator::validate_arg_num_vals");
+ if let Some(num) = a.num_vals {
+ let total_num = ma.num_vals();
+ debug!("Validator::validate_arg_num_vals: num_vals set...{}", num);
+ #[allow(deprecated)]
+ let should_err = if a.is_multiple_occurrences_set() {
+ total_num % num != 0
+ } else {
+ num != total_num
+ };
+ if should_err {
+ debug!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues");
+ return Err(Error::wrong_number_of_values(
+ self.cmd,
+ a.to_string(),
+ num,
+ #[allow(deprecated)]
+ if a.is_multiple_occurrences_set() {
+ total_num % num
+ } else {
+ total_num
+ },
+ Usage::new(self.cmd)
+ .required(&self.required)
+ .create_usage_with_title(&[]),
+ ));
+ }
+ }
+ if let Some(num) = a.max_vals {
+ debug!("Validator::validate_arg_num_vals: max_vals set...{}", num);
+ if ma.num_vals() > num {
+ debug!("Validator::validate_arg_num_vals: Sending error TooManyValues");
+ return Err(Error::too_many_values(
+ self.cmd,
+ ma.raw_vals_flatten()
+ .last()
+ .expect(INTERNAL_ERROR_MSG)
+ .to_str()
+ .expect(INVALID_UTF8)
+ .to_string(),
+ a.to_string(),
+ Usage::new(self.cmd)
+ .required(&self.required)
+ .create_usage_with_title(&[]),
+ ));
+ }
+ }
+ let min_vals_zero = if let Some(num) = a.min_vals {
+ debug!("Validator::validate_arg_num_vals: min_vals set: {}", num);
+ if ma.num_vals() < num && num != 0 {
+ debug!("Validator::validate_arg_num_vals: Sending error TooFewValues");
+ return Err(Error::too_few_values(
+ self.cmd,
+ a.to_string(),
+ num,
+ ma.num_vals(),
+ Usage::new(self.cmd)
+ .required(&self.required)
+ .create_usage_with_title(&[]),
+ ));
+ }
+ num == 0
+ } else {
+ false
+ };
+ // Issue 665 (https://github.com/clap-rs/clap/issues/665)
+ // Issue 1105 (https://github.com/clap-rs/clap/issues/1105)
+ if a.is_takes_value_set() && !min_vals_zero && ma.all_val_groups_empty() {
+ return Err(Error::empty_value(
+ self.cmd,
+ &get_possible_values(a)
+ .iter()
+ .filter(|pv| !pv.is_hide_set())
+ .map(PossibleValue::get_name)
+ .collect::<Vec<_>>(),
+ a.to_string(),
+ ));
+ }
+ Ok(())
+ }
+
+ fn validate_required(
+ &mut self,
+ matcher: &ArgMatcher,
+ conflicts: &mut Conflicts,
+ ) -> ClapResult<()> {
+ debug!("Validator::validate_required: required={:?}", self.required);
+ self.gather_requires(matcher);
+
+ let is_exclusive_present = matcher
+ .arg_ids()
+ .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent))
+ .any(|id| {
+ self.cmd
+ .find(id)
+ .map(|arg| arg.is_exclusive_set())
+ .unwrap_or_default()
+ });
+ debug!(
+ "Validator::validate_required: is_exclusive_present={}",
+ is_exclusive_present
+ );
+
+ for arg_or_group in self
+ .required
+ .iter()
+ .filter(|r| !matcher.check_explicit(r, ArgPredicate::IsPresent))
+ {
+ debug!("Validator::validate_required:iter:aog={:?}", arg_or_group);
+ if let Some(arg) = self.cmd.find(arg_or_group) {
+ debug!("Validator::validate_required:iter: This is an arg");
+ if !is_exclusive_present && !self.is_missing_required_ok(arg, matcher, conflicts) {
+ return self.missing_required_error(matcher, vec![]);
+ }
+ } else if let Some(group) = self.cmd.find_group(arg_or_group) {
+ debug!("Validator::validate_required:iter: This is a group");
+ if !self
+ .cmd
+ .unroll_args_in_group(&group.id)
+ .iter()
+ .any(|a| matcher.check_explicit(a, ArgPredicate::IsPresent))
+ {
+ return self.missing_required_error(matcher, vec![]);
+ }
+ }
+ }
+
+ // Validate the conditionally required args
+ for a in self.cmd.get_arguments() {
+ for (other, val) in &a.r_ifs {
+ if matcher.check_explicit(other, ArgPredicate::Equals(std::ffi::OsStr::new(*val)))
+ && !matcher.check_explicit(&a.id, ArgPredicate::IsPresent)
+ {
+ return self.missing_required_error(matcher, vec![a.id.clone()]);
+ }
+ }
+
+ let match_all = a.r_ifs_all.iter().all(|(other, val)| {
+ matcher.check_explicit(other, ArgPredicate::Equals(std::ffi::OsStr::new(*val)))
+ });
+ if match_all
+ && !a.r_ifs_all.is_empty()
+ && !matcher.check_explicit(&a.id, ArgPredicate::IsPresent)
+ {
+ return self.missing_required_error(matcher, vec![a.id.clone()]);
+ }
+ }
+
+ self.validate_required_unless(matcher)?;
+
+ Ok(())
+ }
+
+ fn is_missing_required_ok(
+ &self,
+ a: &Arg<'help>,
+ matcher: &ArgMatcher,
+ conflicts: &mut Conflicts,
+ ) -> bool {
+ debug!("Validator::is_missing_required_ok: {}", a.name);
+ let conflicts = conflicts.gather_conflicts(self.cmd, matcher, &a.id);
+ !conflicts.is_empty()
+ }
+
+ fn validate_required_unless(&self, matcher: &ArgMatcher) -> ClapResult<()> {
+ debug!("Validator::validate_required_unless");
+ let failed_args: Vec<_> = self
+ .cmd
+ .get_arguments()
+ .filter(|&a| {
+ (!a.r_unless.is_empty() || !a.r_unless_all.is_empty())
+ && !matcher.check_explicit(&a.id, ArgPredicate::IsPresent)
+ && self.fails_arg_required_unless(a, matcher)
+ })
+ .map(|a| a.id.clone())
+ .collect();
+ if failed_args.is_empty() {
+ Ok(())
+ } else {
+ self.missing_required_error(matcher, failed_args)
+ }
+ }
+
+ // Failing a required unless means, the arg's "unless" wasn't present, and neither were they
+ fn fails_arg_required_unless(&self, a: &Arg<'help>, matcher: &ArgMatcher) -> bool {
+ debug!("Validator::fails_arg_required_unless: a={:?}", a.name);
+ let exists = |id| matcher.check_explicit(id, ArgPredicate::IsPresent);
+
+ (a.r_unless_all.is_empty() || !a.r_unless_all.iter().all(exists))
+ && !a.r_unless.iter().any(exists)
+ }
+
+ // `incl`: an arg to include in the error even if not used
+ fn missing_required_error(&self, matcher: &ArgMatcher, incl: Vec<Id>) -> ClapResult<()> {
+ debug!("Validator::missing_required_error; incl={:?}", incl);
+ debug!(
+ "Validator::missing_required_error: reqs={:?}",
+ self.required
+ );
+
+ let usg = Usage::new(self.cmd).required(&self.required);
+
+ let req_args = usg
+ .get_required_usage_from(&incl, Some(matcher), true)
+ .into_iter()
+ .collect::<Vec<_>>();
+
+ debug!(
+ "Validator::missing_required_error: req_args={:#?}",
+ req_args
+ );
+
+ let used: Vec<Id> = matcher
+ .arg_ids()
+ .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent))
+ .filter(|n| {
+ // Filter out the args we don't want to specify.
+ self.cmd.find(n).map_or(true, |a| !a.is_hide_set())
+ })
+ .cloned()
+ .chain(incl)
+ .collect();
+
+ Err(Error::missing_required_argument(
+ self.cmd,
+ req_args,
+ usg.create_usage_with_title(&used),
+ ))
+ }
+}
+
+#[derive(Default, Clone, Debug)]
+struct Conflicts {
+ potential: std::collections::HashMap<Id, Vec<Id>>,
+}
+
+impl Conflicts {
+ fn new() -> Self {
+ Self::default()
+ }
+
+ fn gather_conflicts(&mut self, cmd: &Command, matcher: &ArgMatcher, arg_id: &Id) -> Vec<Id> {
+ debug!("Conflicts::gather_conflicts: arg={:?}", arg_id);
+ let mut conflicts = Vec::new();
+ for other_arg_id in matcher
+ .arg_ids()
+ .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent))
+ {
+ if arg_id == other_arg_id {
+ continue;
+ }
+
+ if self
+ .gather_direct_conflicts(cmd, arg_id)
+ .contains(other_arg_id)
+ {
+ conflicts.push(other_arg_id.clone());
+ }
+ if self
+ .gather_direct_conflicts(cmd, other_arg_id)
+ .contains(arg_id)
+ {
+ conflicts.push(other_arg_id.clone());
+ }
+ }
+ debug!("Conflicts::gather_conflicts: conflicts={:?}", conflicts);
+ conflicts
+ }
+
+ fn gather_direct_conflicts(&mut self, cmd: &Command, arg_id: &Id) -> &[Id] {
+ self.potential.entry(arg_id.clone()).or_insert_with(|| {
+ let conf = if let Some(arg) = cmd.find(arg_id) {
+ let mut conf = arg.blacklist.clone();
+ for group_id in cmd.groups_for_arg(arg_id) {
+ let group = cmd.find_group(&group_id).expect(INTERNAL_ERROR_MSG);
+ conf.extend(group.conflicts.iter().cloned());
+ if !group.multiple {
+ for member_id in &group.args {
+ if member_id != arg_id {
+ conf.push(member_id.clone());
+ }
+ }
+ }
+ }
+
+ // Overrides are implicitly conflicts
+ conf.extend(arg.overrides.iter().cloned());
+
+ conf
+ } else if let Some(group) = cmd.find_group(arg_id) {
+ group.conflicts.clone()
+ } else {
+ debug_assert!(false, "id={:?} is unknown", arg_id);
+ Vec::new()
+ };
+ debug!(
+ "Conflicts::gather_direct_conflicts id={:?}, conflicts={:?}",
+ arg_id, conf
+ );
+ conf
+ })
+ }
+}
+
+fn get_possible_values<'help>(a: &Arg<'help>) -> Vec<PossibleValue<'help>> {
+ #![allow(deprecated)]
+ if !a.is_takes_value_set() {
+ vec![]
+ } else if let Some(pvs) = a.get_possible_values() {
+ // Check old first in case the user explicitly set possible values and the derive inferred
+ // a `ValueParser` with some.
+ pvs.to_vec()
+ } else {
+ a.get_value_parser()
+ .possible_values()
+ .map(|pvs| pvs.collect())
+ .unwrap_or_default()
+ }
+}
diff --git a/3.2.23/src/util/color.rs b/3.2.23/src/util/color.rs
new file mode 100644
index 0000000..15c9901
--- /dev/null
+++ b/3.2.23/src/util/color.rs
@@ -0,0 +1,62 @@
+/// Represents the color preferences for program output
+#[derive(Debug, Copy, Clone, Eq, PartialEq)]
+pub enum ColorChoice {
+ /// Enables colored output only when the output is going to a terminal or TTY.
+ ///
+ /// **NOTE:** This is the default behavior of `clap`.
+ ///
+ /// # Platform Specific
+ ///
+ /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms).
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(feature = "color"), doc = " ```ignore")]
+ #[cfg_attr(feature = "color", doc = " ```no_run")]
+ /// # use clap::{Command, ColorChoice};
+ /// Command::new("myprog")
+ /// .color(ColorChoice::Auto)
+ /// .get_matches();
+ /// ```
+ Auto,
+
+ /// Enables colored output regardless of whether or not the output is going to a terminal/TTY.
+ ///
+ /// # Platform Specific
+ ///
+ /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms).
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(feature = "color"), doc = " ```ignore")]
+ #[cfg_attr(feature = "color", doc = " ```no_run")]
+ /// # use clap::{Command, ColorChoice};
+ /// Command::new("myprog")
+ /// .color(ColorChoice::Always)
+ /// .get_matches();
+ /// ```
+ Always,
+
+ /// Disables colored output no matter if the output is going to a terminal/TTY, or not.
+ ///
+ /// # Platform Specific
+ ///
+ /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms)
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(feature = "color"), doc = " ```ignore")]
+ #[cfg_attr(feature = "color", doc = " ```no_run")]
+ /// # use clap::{Command, ColorChoice};
+ /// Command::new("myprog")
+ /// .color(ColorChoice::Never)
+ /// .get_matches();
+ /// ```
+ Never,
+}
+
+impl Default for ColorChoice {
+ fn default() -> Self {
+ Self::Auto
+ }
+}
diff --git a/3.2.23/src/util/fnv.rs b/3.2.23/src/util/fnv.rs
new file mode 100644
index 0000000..4602300
--- /dev/null
+++ b/3.2.23/src/util/fnv.rs
@@ -0,0 +1,46 @@
+use std::{
+ fmt::Display,
+ hash::{Hash, Hasher},
+};
+
+const MAGIC_INIT: u64 = 0x811C_9DC5;
+
+// TODO: Docs
+pub trait Key: Hash + Display {
+ fn key(&self) -> u64;
+}
+
+impl<T> Key for T
+where
+ T: Hash + Display,
+{
+ fn key(&self) -> u64 {
+ let mut hasher = FnvHasher::new();
+ self.hash(&mut hasher);
+ hasher.finish()
+ }
+}
+
+pub(crate) struct FnvHasher(u64);
+
+impl FnvHasher {
+ pub(crate) fn new() -> Self {
+ FnvHasher(MAGIC_INIT)
+ }
+}
+
+impl Hasher for FnvHasher {
+ fn finish(&self) -> u64 {
+ self.0
+ }
+ fn write(&mut self, bytes: &[u8]) {
+ let FnvHasher(mut hash) = *self;
+
+ for byte in bytes.iter() {
+ hash ^= u64::from(*byte);
+ hash = hash.wrapping_mul(0x0100_0000_01b3);
+ }
+
+ *self = FnvHasher(hash);
+ }
+}
diff --git a/3.2.23/src/util/graph.rs b/3.2.23/src/util/graph.rs
new file mode 100644
index 0000000..d646400
--- /dev/null
+++ b/3.2.23/src/util/graph.rs
@@ -0,0 +1,49 @@
+#[derive(Debug)]
+struct Child<T> {
+ id: T,
+ children: Vec<usize>,
+}
+
+impl<T> Child<T> {
+ fn new(id: T) -> Self {
+ Child {
+ id,
+ children: vec![],
+ }
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct ChildGraph<T>(Vec<Child<T>>);
+
+impl<T> ChildGraph<T>
+where
+ T: Sized + PartialEq + Clone,
+{
+ pub(crate) fn with_capacity(s: usize) -> Self {
+ ChildGraph(Vec::with_capacity(s))
+ }
+
+ pub(crate) fn insert(&mut self, req: T) -> usize {
+ self.0.iter().position(|e| e.id == req).unwrap_or_else(|| {
+ let idx = self.0.len();
+ self.0.push(Child::new(req));
+ idx
+ })
+ }
+
+ pub(crate) fn insert_child(&mut self, parent: usize, child: T) -> usize {
+ let c_idx = self.0.len();
+ self.0.push(Child::new(child));
+ self.0[parent].children.push(c_idx);
+ c_idx
+ }
+
+ pub(crate) fn iter(&self) -> impl Iterator<Item = &T> {
+ self.0.iter().map(|r| &r.id)
+ }
+
+ pub(crate) fn contains(&self, req: &T) -> bool {
+ self.0.iter().any(|r| r.id == *req)
+ }
+}
diff --git a/3.2.23/src/util/id.rs b/3.2.23/src/util/id.rs
new file mode 100644
index 0000000..63a7e00
--- /dev/null
+++ b/3.2.23/src/util/id.rs
@@ -0,0 +1,92 @@
+use crate::util::fnv::Key;
+
+use std::{
+ fmt::{Debug, Formatter, Result},
+ hash::{Hash, Hasher},
+ ops::Deref,
+};
+
+#[derive(Clone, Eq, Default)]
+#[cfg_attr(not(debug_assertions), repr(transparent))]
+pub(crate) struct Id {
+ #[cfg(debug_assertions)]
+ name: String,
+ id: u64,
+}
+
+macro_rules! precomputed_hashes {
+ ($($fn_name:ident, $const:expr, $name:expr;)*) => {
+ impl Id {
+ $(
+ pub(crate) fn $fn_name() -> Self {
+ Id {
+ #[cfg(debug_assertions)]
+ name: $name.into(),
+ id: $const,
+ }
+ }
+ )*
+ }
+ };
+}
+
+// precompute some common values
+precomputed_hashes! {
+ empty_hash, 0x1C9D_3ADB_639F_298E, "";
+ help_hash, 0x5963_6393_CFFB_FE5F, "help";
+ version_hash, 0x30FF_0B7C_4D07_9478, "version";
+}
+
+impl Id {
+ pub(crate) fn from_ref<T: Key>(val: T) -> Self {
+ Id {
+ #[cfg(debug_assertions)]
+ name: val.to_string(),
+ id: val.key(),
+ }
+ }
+}
+
+impl Debug for Id {
+ fn fmt(&self, f: &mut Formatter) -> Result {
+ #[cfg(debug_assertions)]
+ write!(f, "{}", self.name)?;
+ #[cfg(not(debug_assertions))]
+ write!(f, "[hash: {:X}]", self.id)?;
+
+ Ok(())
+ }
+}
+
+impl Deref for Id {
+ type Target = u64;
+
+ fn deref(&self) -> &Self::Target {
+ &self.id
+ }
+}
+
+impl<T: Key> From<T> for Id {
+ fn from(val: T) -> Self {
+ Id {
+ #[cfg(debug_assertions)]
+ name: val.to_string(),
+ id: val.key(),
+ }
+ }
+}
+
+impl Hash for Id {
+ fn hash<H>(&self, state: &mut H)
+ where
+ H: Hasher,
+ {
+ self.id.hash(state)
+ }
+}
+
+impl PartialEq for Id {
+ fn eq(&self, other: &Id) -> bool {
+ self.id == other.id
+ }
+}
diff --git a/3.2.23/src/util/mod.rs b/3.2.23/src/util/mod.rs
new file mode 100644
index 0000000..8adc8db
--- /dev/null
+++ b/3.2.23/src/util/mod.rs
@@ -0,0 +1,40 @@
+#![allow(clippy::single_component_path_imports)]
+
+mod fnv;
+mod graph;
+mod id;
+mod str_to_bool;
+
+pub use self::fnv::Key;
+
+pub(crate) use self::str_to_bool::str_to_bool;
+pub(crate) use self::str_to_bool::FALSE_LITERALS;
+pub(crate) use self::str_to_bool::TRUE_LITERALS;
+pub(crate) use self::{graph::ChildGraph, id::Id};
+
+pub(crate) mod color;
+
+pub(crate) const SUCCESS_CODE: i32 = 0;
+// While sysexists.h defines EX_USAGE as 64, this doesn't seem to be used much in practice but
+// instead 2 seems to be frequently used.
+// Examples
+// - GNU `ls` returns 2
+// - Python's `argparse` returns 2
+pub(crate) const USAGE_CODE: i32 = 2;
+
+pub(crate) fn safe_exit(code: i32) -> ! {
+ use std::io::Write;
+
+ let _ = std::io::stdout().lock().flush();
+ let _ = std::io::stderr().lock().flush();
+
+ std::process::exit(code)
+}
+
+#[cfg(not(feature = "unicode"))]
+pub(crate) fn eq_ignore_case(left: &str, right: &str) -> bool {
+ left.eq_ignore_ascii_case(right)
+}
+
+#[cfg(feature = "unicode")]
+pub(crate) use unicase::eq as eq_ignore_case;
diff --git a/3.2.23/src/util/str_to_bool.rs b/3.2.23/src/util/str_to_bool.rs
new file mode 100644
index 0000000..1fbdc75
--- /dev/null
+++ b/3.2.23/src/util/str_to_bool.rs
@@ -0,0 +1,21 @@
+/// True values are `y`, `yes`, `t`, `true`, `on`, and `1`.
+pub(crate) const TRUE_LITERALS: [&str; 6] = ["y", "yes", "t", "true", "on", "1"];
+
+/// False values are `n`, `no`, `f`, `false`, `off`, and `0`.
+pub(crate) const FALSE_LITERALS: [&str; 6] = ["n", "no", "f", "false", "off", "0"];
+
+/// Converts a string literal representation of truth to true or false.
+///
+/// `false` values are `n`, `no`, `f`, `false`, `off`, and `0` (case insensitive).
+///
+/// Any other value will be considered as `true`.
+pub(crate) fn str_to_bool(val: impl AsRef<str>) -> Option<bool> {
+ let pat: &str = &val.as_ref().to_lowercase();
+ if TRUE_LITERALS.contains(&pat) {
+ Some(true)
+ } else if FALSE_LITERALS.contains(&pat) {
+ Some(false)
+ } else {
+ None
+ }
+}
diff --git a/Android.bp b/Android.bp
index 488af76..1595d5e 100644
--- a/Android.bp
+++ b/Android.bp
@@ -18,6 +18,11 @@ package {
// For unused files, consider creating a 'fileGroup' with "//visibility:private"
// to attach the license to, and including a comment whether the files may be
// used in the current project.
+//
+// large-scale-change included anything that looked like it might be a license
+// text as a license_text. e.g. LICENSE, NOTICE, COPYING etc.
+//
+// Please consider removing redundant or irrelevant files from 'license_text:'.
// See: http://go/android-license-faq
license {
name: "external_rust_crates_clap_license",
@@ -27,26 +32,62 @@ license {
"SPDX-license-identifier-MIT",
],
license_text: [
+ "LICENSE-APACHE",
"LICENSE-MIT",
],
}
rust_library {
name: "libclap",
- // has rustc warnings
host_supported: true,
crate_name: "clap",
cargo_env_compat: true,
- cargo_pkg_version: "2.33.3",
+ cargo_pkg_version: "4.1.8",
srcs: ["src/lib.rs"],
- edition: "2015",
+ edition: "2021",
+ features: [
+ "derive",
+ "error-context",
+ "help",
+ "std",
+ "usage",
+ ],
rustlibs: [
- "libbitflags",
- "libtextwrap",
+ "libbitflags-1.3.2",
+ "libclap_lex",
+ "libonce_cell",
],
+ proc_macros: ["libclap_derive"],
apex_available: [
"//apex_available:platform",
- "com.android.compos",
- "com.android.virt",
+ "//apex_available:anyapex",
+ ],
+ product_available: true,
+ vendor_available: true,
+}
+
+rust_binary {
+ name: "stdio_fixture",
+ host_supported: true,
+ crate_name: "stdio_fixture",
+ cargo_env_compat: true,
+ cargo_pkg_version: "4.1.8",
+ srcs: ["src/bin/stdio-fixture.rs"],
+ edition: "2021",
+ features: [
+ "derive",
+ "error-context",
+ "help",
+ "std",
+ "usage",
+ ],
+ rustlibs: [
+ "libbitflags-1.3.2",
+ "libclap",
+ "libclap_lex",
+ "libonce_cell",
],
+ proc_macros: ["libclap_derive"],
+ product_available: true,
+ vendor_available: true,
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
deleted file mode 100644
index a2400b5..0000000
--- a/CHANGELOG.md
+++ /dev/null
@@ -1,2890 +0,0 @@
-<a name="v2.33.3"></a>
-### v2.33.3 (2020-08-13)
-
-#### Improvements
-
-* Suppress deprecation warnings when using `crate_*` macros.
-
-<a name="v2.33.2"></a>
-### v2.33.2 (2020-08-5)
-
-#### Documentation
-
-* Fixed links to `2.x` examples. Now they point to the right place.
-
-<a name="v2.33.1"></a>
-### v2.33.1 (2020-05-11)
-
-#### Bug Fixes
-
-* Windows: Prevent some panics when parsing invalid Unicode on Windows ([922c645](https://github.com/clap-rs/clap/commit/922c64508389170c9c77f1c8a4e597d14d3ed2f0), closes [#1905](https://github.com/clap-rs/clap/issues/1905))
-
-#### Documentation
-
-* fixes versions referenced in the README ([d307466a](https://github.com/kbknapp/clap-rs/commit/d307466af1013f172b8ec0252f01a473e2192d6b))
-* **README.md:**
- * cuts down the number of examples to reduce confusion ([6e508ee0](https://github.com/kbknapp/clap-rs/commit/6e508ee09e7153de4adf4e88b0aa6418a537dadd))
-
-#### Improvements
-
-* **Deps:** doesnt compile ansi_term on Windows since its not used ([b57ee946](https://github.com/kbknapp/clap-rs/commit/b57ee94609da3ddc897286cfba968f26ff961491), closes [#1155](https://github.com/kbknapp/clap-rs/issues/1155))
-
-#### Minimum Required Rust
-
-* As of this release, `clap` requires `rustc 1.36.0` or greater.
-
-<a name="v2.33.0"></a>
-## v2.33.0 (2019-04-06)
-
-#### New Sponsor
-
-* Stephen Oats is now a sponsor \o/ ([823457c0](https://github.com/kbknapp/clap-rs/commit/823457c0ef5e994ed7080cf62addbfe1aa3b1833))
-* **SPONSORS.md:** fixes Josh Triplett's info in the sponsor document ([24cb5740](https://github.com/kbknapp/clap-rs/commit/24cb574090a11159b48bba105d5ec2dfb0a20e4e))
-
-#### Features
-
-* **Completions:** adds completion support for Elvish. ([e9d0562a](https://github.com/kbknapp/clap-rs/commit/e9d0562a1dc5dfe731ed7c767e6cee0af08f0cf9))
-* There is a new setting to disable automatic building of `--help` and `-h` flags (`AppSettings::DisableAutoHelp`)
-
-#### Improvements
-
-* **arg_matches.rs:** add Debug implementations ([47192b7a](https://github.com/kbknapp/clap-rs/commit/47192b7a2d84ec716b81ae4af621e008a8762dc9))
-* **macros:** Support shorthand syntax for ArgGroups ([df9095e7](https://github.com/kbknapp/clap-rs/commit/df9095e75bb1e7896415251d0d4ffd8a0ebcd559))
-
-#### Documentation
-
-* Refer to macOS rather than OSX. ([ab0d767f](https://github.com/kbknapp/clap-rs/commit/ab0d767f3a5a57e2bbb97d0183c2ef63c8c77a6c))
-* **README.md:** use https for all links ([96a7639a](https://github.com/kbknapp/clap-rs/commit/96a7639a36bcb184c3f45348986883115ef1ab3a))
-
-#### Bug Fixes
-
-* add debug assertion for missing args in subcommand ArgGroup ([2699d9e5](https://github.com/kbknapp/clap-rs/commit/2699d9e51e7eadc258ba64c4e347c5d1fef61343))
-* Restore compat with Rust 1.21 ([6b263de1](https://github.com/kbknapp/clap-rs/commit/6b263de1d42ede692ec5ee55019ad2fc6386f92e))
-* Dont mention unused subcommands ([ef92e2b6](https://github.com/kbknapp/clap-rs/commit/ef92e2b639ed305bdade4741f60fa85cb0101c5a))
-* **OsValues:** Add `ExactSizeIterator` implementation ([356c69e5](https://github.com/kbknapp/clap-rs/commit/356c69e508fd25a9f0ea2d27bf80ae1d9a8d88f4))
-* **arg_enum!:**
- * Fix comma position for valid values. ([1f1f9ff3](https://github.com/kbknapp/clap-rs/commit/1f1f9ff3fa38a43231ef8be9cfea89a32e53f518))
- * Invalid expansions of some trailing-comma patterns ([7023184f](https://github.com/kbknapp/clap-rs/commit/7023184fca04e852c270341548d6a16207d13862))
-* **completions:** improve correctness of completions when whitespace is involved ([5a08ff29](https://github.com/kbknapp/clap-rs/commit/5a08ff295b2aa6ce29420df6252a0e3ff4441bdc))
-* **help message:** Unconditionally uses long description for subcommands ([6acc8b6a](https://github.com/kbknapp/clap-rs/commit/6acc8b6a621a765cbf513450188000d943676a30), closes [#897](https://github.com/kbknapp/clap-rs/issues/897))
-* **macros:** fixes broken pattern which prevented calling multi-argument Arg methods ([9e7a352e](https://github.com/kbknapp/clap-rs/commit/9e7a352e13aaf8025d80f2bac5c47fb32528672b))
-* **parser:** Better interaction between AllowExternalSubcommands and SubcommandRequired ([9601c95a](https://github.com/kbknapp/clap-rs/commit/9601c95a03d2b82bf265c328b4769238f1b79002))
-
-#### Minimum Required Rust
-
-* As of this release, `clap` requires `rustc 1.31.0` or greater.
-
-<a name="v2.32.0"></a>
-## v2.32.0 (2018-06-26)
-
-#### Minimum Required Rust
-
-* As of this release, `clap` requires `rustc 1.21.0` or greater.
-
-
-#### Features
-
-* **Completions:** adds completion support for Elvish. ([e9d0562a](https://github.com/kbknapp/clap-rs/commit/e9d0562a1dc5dfe731ed7c767e6cee0af08f0cf9))
-
-#### Improvements
-
-* **macros:** Support shorthand syntax for ArgGroups ([df9095e7](https://github.com/kbknapp/clap-rs/commit/df9095e75bb1e7896415251d0d4ffd8a0ebcd559))
-
-#### Bug Fixes
-
-* **OsValues:** Add `ExactSizeIterator` implementation ([356c69e5](https://github.com/kbknapp/clap-rs/commit/356c69e508fd25a9f0ea2d27bf80ae1d9a8d88f4))
-* **arg_enum!:** Invalid expansions of some trailing-comma patterns ([7023184f](https://github.com/kbknapp/clap-rs/commit/7023184fca04e852c270341548d6a16207d13862))
-* **help message:** Unconditionally uses long description for subcommands ([6acc8b6a](https://github.com/kbknapp/clap-rs/commit/6acc8b6a621a765cbf513450188000d943676a30), closes [#897](https://github.com/kbknapp/clap-rs/issues/897))
-
-#### Documentation
-
-* Refer to macOS rather than OSX. ([ab0d767f](https://github.com/kbknapp/clap-rs/commit/ab0d767f3a5a57e2bbb97d0183c2ef63c8c77a6c))
-
-
-
-<a name="v2.31.2"></a>
-### v2.31.2 (2018-03-19)
-
-#### Bug Fixes
-
-* **Fish Completions:** fixes a bug that only allowed a single completion in in Fish Shell ([e8774a8](https://github.com/kbknapp/clap-rs/pull/1214/commits/e8774a84ee4a319c888036e7c595ab46451d8e48), closes [#1212](https://github.com/kbknapp/clap-rs/issues/1212))
-* **AllowExternalSubcommands**: fixes a bug where external subcommands would be blocked by a similarly named subcommand (suggestions were getting in the way). ([a410e85](https://github.com/kbknapp/clap-rs/pull/1215/commits/a410e855bcd82b05f9efa73fa8b9774dc8842c6b))
-
-#### Documentation
-
-* Fixes some typos in the `README.md` ([c8e685d7](https://github.com/kbknapp/clap-rs/commit/c8e685d76adee2a3cc06cac6952ffcf6f9548089))
-
-<a name="v2.31.1"></a>
-### v2.31.1 (2018-03-06)
-
-
-#### Improvements
-
-* **AllowMissingPositional:** improves the ability of AllowMissingPositional to allow 'skipping' to the last positional arg with '--' ([df20e6e2](https://github.com/kbknapp/clap-rs/commit/df20e6e24b4e782be0b423b484b9798e3e2efe2f))
-
-
-<a name="v2.31.0"></a>
-## v2.31.0 (2018-03-04)
-
-
-#### Features
-
-* **Arg Indices:** adds the ability to query argument value indices ([f58d0576](https://github.com/kbknapp/clap-rs/commit/f58d05767ec8133c8eb2de117cb642b9ae29ccbc))
-* **Indices:** implements an Indices<Item=&usize> iterator ([1e67be44](https://github.com/kbknapp/clap-rs/commit/1e67be44f0ccf161cc84c4e6082382072e89c302))
-* **Raw Args** adds a convenience function to `Arg` that allows implying all of `Arg::last` `Arg::allow_hyphen_values` and `Arg::multiple(true)` ([66a78f29](https://github.com/kbknapp/clap-rs/commit/66a78f2972786f5fe7c07937a1ac23da2542afd2))
-
-#### Documentation
-
-* Fix some typos and markdown issues. ([935ba0dd](https://github.com/kbknapp/clap-rs/commit/935ba0dd547a69c3f636c5486795012019408794))
-* **Arg Indices:** adds the documentation for the arg index querying methods ([50bc0047](https://github.com/kbknapp/clap-rs/commit/50bc00477afa64dc6cdc5de161d3de3ba1d105a7))
-* **CONTRIBUTING.md:** fix url to clippy upstream repo to point to https://github.com/rust-lang-nursery/rust-clippy instead of https://github.com/Manishearth/rust-clippy ([42407d7f](https://github.com/kbknapp/clap-rs/commit/42407d7f21d794103cda61f49d2615aae0a4bcd9))
-* **Values:** improves the docs example of the Values iterator ([74075d65](https://github.com/kbknapp/clap-rs/commit/74075d65e8db1ddb5e2a4558009a5729d749d1b6))
-* Updates readme to hint that the `wrap_help` feature is a thing ([fc7ab227](https://github.com/kbknapp/clap-rs/commit/66a78f2972786f5fe7c07937a1ac23da2542afd2))
-
-### Improvements
-
-* Cargo.toml: use codegen-units = 1 in release and bench profiles ([19f425ea](https://github.com/kbknapp/clap-rs/commit/66a78f2972786f5fe7c07937a1ac23da2542afd2))
-* Adds WASM support (clap now compiles on WASM!) ([689949e5](https://github.com/kbknapp/clap-rs/commit/689949e57d390bb61bc69f3ed91f60a2105738d0))
-* Uses the short help tool-tip for PowerShell completion scripts ([ecda22ce](https://github.com/kbknapp/clap-rs/commit/ecda22ce7210ce56d7b2d1a5445dd1b8a2959656))
-
-
-<a name="v2.30.0"></a>
-## v2.30.0 (2018-02-13)
-
-#### Bug Fixes
-
-* **YAML:** Adds a missing conversion from `Arg::last` when instantiating from a YAML file ([aab77c81a5](https://github.com/kbknapp/clap-rs/pull/1175/commits/aab77c81a519b045f95946ae0dd3e850f9b93070), closes [#1160](https://github.com/kbknapp/clap-rs/issues/1173))
-
-#### Improvements
-
-* **Bash Completions:** instead of completing a generic option name, all bash completions fall back to file completions UNLESS `Arg::possible_values` was used ([872f02ae](https://github.com/kbknapp/clap-rs/commit/872f02aea900ffa376850a279eb164645e1234fa))
-* **Deps:** No longer needlessly compiles `ansi_term` on Windows since its not used ([b57ee946](https://github.com/kbknapp/clap-rs/commit/b57ee94609da3ddc897286cfba968f26ff961491), closes [#1155](https://github.com/kbknapp/clap-rs/issues/1155))
-* **Help Message:** changes the `[values: foo bar baz]` array to `[possible values: foo bar baz]` for consistency with the API ([414707e4e97](https://github.com/kbknapp/clap-rs/pull/1176/commits/414707e4e979d07bfe555247e5d130c546673708), closes [#1160](https://github.com/kbknapp/clap-rs/issues/1160))
-
-
-<a name="v2.29.4"></a>
-### v2.29.4 (2018-02-06)
-
-
-#### Bug Fixes
-
-* **Overrides Self:** fixes a bug where options with multiple values couldnt ever have multiple values ([d95907cf](https://github.com/kbknapp/clap-rs/commit/d95907cff6d011a901fe35fa00b0f4e18547a1fb))
-
-
-
-<a name="v2.29.3"></a>
-### v2.29.3 (2018-02-05)
-
-
-#### Improvements
-
-* **Overrides:** clap now supports arguments which override with themselves ([6c7a0010](https://github.com/kbknapp/clap-rs/commit/6c7a001023ca1eac1cc6ffe6c936b4c4a2aa3c45), closes [#976](https://github.com/kbknapp/clap-rs/issues/976))
-
-#### Bug Fixes
-
-* **Requirements:** fixes an issue where conflicting args would still show up as required ([e06cefac](https://github.com/kbknapp/clap-rs/commit/e06cefac97083838c0a4e1444dcad02a5c3f911e), closes [#1158](https://github.com/kbknapp/clap-rs/issues/1158))
-* Fixes a bug which disallows proper nesting of `--` ([73993fe](https://github.com/kbknapp/clap-rs/commit/73993fe30d135f682e763ec93dcb0814ed518011), closes [#1161](https://github.com/kbknapp/clap-rs/issues/1161))
-
-#### New Settings
-
-* **AllArgsOverrideSelf:** adds a new convenience setting to allow all args to override themselves ([4670325d](https://github.com/kbknapp/clap-rs/commit/4670325d1bf0369addec2ae2bcb56f1be054c924))
-
-
-
-<a name="v2.29.2"></a>
-### v2.29.2 (2018-01-16)
-
-
-#### Features
-
-* **completions/zsh.rs:**
- * Escape possible values for options ([25561dec](https://github.com/kbknapp/clap-rs/commit/25561decf147d329b64634a14d9695673c2fc78f))
- * Implement postional argument possible values completion ([f3b0afd2](https://github.com/kbknapp/clap-rs/commit/f3b0afd2bef8b7be97162f8a7802ddf7603dff36))
- * Complete positional arguments properly ([e39aeab8](https://github.com/kbknapp/clap-rs/commit/e39aeab8487596046fbdbc6a226e5c8820585245))
-
-#### Bug Fixes
-
-* **completions/zsh.rs:**
- * Add missing autoload for is-at-least ([a6522607](https://github.com/kbknapp/clap-rs/commit/a652260795d1519f6ec2a7a09ccc1258499cad7b))
- * Don't pass -S to _arguments if Zsh is too old ([16b4f143](https://github.com/kbknapp/clap-rs/commit/16b4f143ff466b7ef18a267bc44ade0f9639109b))
- * Maybe fix completions with mixed positionals and subcommands ([1146f0da](https://github.com/kbknapp/clap-rs/commit/1146f0da154d6796fbfcb09db8efa3593cb0d898))
-* **completions/zsh.zsh:** Remove redundant code from output ([0e185b92](https://github.com/kbknapp/clap-rs/commit/0e185b922ed1e0fd653de00b4cd8d567d72ff68e), closes [#1142](https://github.com/kbknapp/clap-rs/issues/1142))
-
-
-
-<a name="2.29.1"></a>
-### 2.29.1 (2018-01-09)
-
-
-#### Documentation
-
-* fixes broken links. ([56e734b8](https://github.com/kbknapp/clap-rs/commit/56e734b839303d733d2e5baf7dac39bd7b97b8e4))
-* updates contributors list ([e1313a5a](https://github.com/kbknapp/clap-rs/commit/e1313a5a0f69d8f4016f73b860a63af8318a6676))
-
-#### Performance
-
-* further debloating by removing generics from error cases ([eb8d919e](https://github.com/kbknapp/clap-rs/commit/eb8d919e6f3443db279ba0c902f15d76676c02dc))
-* debloats clap by deduplicating logic and refactors ([03e413d7](https://github.com/kbknapp/clap-rs/commit/03e413d7175d35827cd7d8908d47dbae15a849a3))
-
-#### Bug Fixes
-
-* fixes the ripgrep benchmark by adding a value to a flag that expects it ([d26ab2b9](https://github.com/kbknapp/clap-rs/commit/d26ab2b97cf9c0ea675b440b7b0eaf6ac3ad01f4))
-* **bash completion:** Change the bash completion script code generation to support hyphens. ([ba7f1d18](https://github.com/kbknapp/clap-rs/commit/ba7f1d18eba7a07ce7f57e0981986f66c994b639))
-* **completions/zsh.rs:** Fix completion of long option values ([46365cf8](https://github.com/kbknapp/clap-rs/commit/46365cf8be5331ba04c895eb183e2f230b5aad51))
-
-
-<a name="2.29.0"></a>
-## 2.29.0 (2017-12-02)
-
-
-#### API Additions
-
-* **Arg:** adds Arg::hide_env_values(bool) which allows one to hide any current env values and display only the key in help messages ([fb41d062](https://github.com/kbknapp/clap-rs/commit/fb41d062eedf37cb4f805c90adca29909bd197d7))
-
-
-
-<a name="2.28.0"></a>
-## 2.28.0 (2017-11-28)
-
-The minimum required Rust is now 1.20. This was done to start using bitflags 1.0 and having >1.0 deps is a *very good* thing!
-
-#### Documentation
-
-* changes the demo version to 2.28 to stay in sync ([ce6ca492](https://github.com/kbknapp/clap-rs/commit/ce6ca492c7510ab6474075806360b96081b021a9))
-* Fix URL path to github hosted files ([ce72aada](https://github.com/kbknapp/clap-rs/commit/ce72aada56a9581d4a6cb4bf9bdb861c3906f8df), closes [#1106](https://github.com/kbknapp/clap-rs/issues/1106))
-* fix typo ([002b07fc](https://github.com/kbknapp/clap-rs/commit/002b07fc98a1c85acb66296b1eec0b2aba906125))
-* **README.md:** updates the readme and pulls out some redundant sections ([db6caf86](https://github.com/kbknapp/clap-rs/commit/db6caf8663747e679d2f4ed3bd127f33476754aa))
-
-#### Improvements
-
-* adds '[SUBCOMMAND]' to usage strings with only AppSettings::AllowExternalSubcommands is used with no other subcommands ([e78bb757](https://github.com/kbknapp/clap-rs/commit/e78bb757a3df16e82d539e450c06767a6bfcf859), closes [#1093](https://github.com/kbknapp/clap-rs/issues/1093))
-
-#### API Additions
-
-* Adds Arg::case_insensitive(bool) which allows matching Arg::possible_values without worrying about ASCII case ([1fec268e](https://github.com/kbknapp/clap-rs/commit/1fec268e51736602e38e67c76266f439e2e0ef12), closes [#1118](https://github.com/kbknapp/clap-rs/issues/1118))
-* Adds the traits to be used with the clap-derive crate to be able to use Custom Derive ([6f4c3412](https://github.com/kbknapp/clap-rs/commit/6f4c3412415e882f5ca2cc3fbd6d4dce79440828))
-
-#### Bug Fixes
-
-* Fixes a regression where --help couldn't be overridden ([a283d69f](https://github.com/kbknapp/clap-rs/commit/a283d69fc08aa016ae1bf9ba010012abecc7ba69), closes [#1112](https://github.com/kbknapp/clap-rs/issues/1112))
-* fixes a bug that allowed options to pass parsing when no value was provided ([2fb75821](https://github.com/kbknapp/clap-rs/commit/2fb758219c7a60d639da67692e100b855a8165ac), closes [#1105](https://github.com/kbknapp/clap-rs/issues/1105))
-* ignore PropagateGlobalValuesDown deprecation warning ([f61ce3f5](https://github.com/kbknapp/clap-rs/commit/f61ce3f55fe65e16b3db0bd4facdc4575de22767), closes [#1086](https://github.com/kbknapp/clap-rs/issues/1086))
-
-#### Deps
-
-* Updates `bitflags` to 1.0
-
-
-
-<a name="v2.27.1"></a>
-## v2.27.1 (2017-10-24)
-
-
-#### Bug Fixes
-
-* Adds `term_size` as an optional dependency (with feature `wrap_help`) to fix compile bug
-
-<a name="v2.27.0"></a>
-## v2.27.0 (2017-10-24)
-
-** This release raises the minimum required version of Rust to 1.18 **
-
-** This release also contains a very minor breaking change to fix a bug **
-
-The only CLIs affected will be those using unrestrained multiple values and subcommands where the
-subcommand name can coincide with one of the multiple values.
-
-See the commit [0c223f54](https://github.com/kbknapp/clap-rs/commit/0c223f54ed46da406bc8b43a5806e0b227863b31) for full details.
-
-
-#### Bug Fixes
-
-* Values from global args are now propagated UP and DOWN!
-* fixes a bug where using AppSettings::AllowHyphenValues would allow invalid arguments even when there is no way for them to be valid ([77ed4684](https://github.com/kbknapp/clap-rs/commit/77ed46841fc0263d7aa32fcc5cc49ef703b37c04), closes [#1066](https://github.com/kbknapp/clap-rs/issues/1066))
-* when an argument requires a value and that value happens to match a subcommand name, its parsed as a value ([0c223f54](https://github.com/kbknapp/clap-rs/commit/0c223f54ed46da406bc8b43a5806e0b227863b31), closes [#1031](https://github.com/kbknapp/clap-rs/issues/1031), breaks [#](https://github.com/kbknapp/clap-rs/issues/), [#](https://github.com/kbknapp/clap-rs/issues/))
-* fixes a bug that prevented number_of_values and default_values to be used together ([5eb342a9](https://github.com/kbknapp/clap-rs/commit/5eb342a99dde07b0f011048efde3e283bc1110fc), closes [#1050](https://github.com/kbknapp/clap-rs/issues/1050), [#1056](https://github.com/kbknapp/clap-rs/issues/1056))
-* fixes a bug that didn't allow args with default values to have conflicts ([58b5b4be](https://github.com/kbknapp/clap-rs/commit/58b5b4be315280888d50d9b15119b91a9028f050), closes [#1071](https://github.com/kbknapp/clap-rs/issues/1071))
-* fixes a panic when using global args and calling App::get_matches_from_safe_borrow multiple times ([d86ec797](https://github.com/kbknapp/clap-rs/commit/d86ec79742c77eb3f663fb30e225954515cf25bb), closes [#1076](https://github.com/kbknapp/clap-rs/issues/1076))
-* fixes issues and potential regressions with global args values not being propagated properly or at all ([a43f9dd4](https://github.com/kbknapp/clap-rs/commit/a43f9dd4aaf1864dd14a3c28dec89ccdd70c61e5), closes [#1010](https://github.com/kbknapp/clap-rs/issues/1010), [#1061](https://github.com/kbknapp/clap-rs/issues/1061), [#978](https://github.com/kbknapp/clap-rs/issues/978))
-* fixes a bug where default values are not applied if the option supports zero values ([9c248cbf](https://github.com/kbknapp/clap-rs/commit/9c248cbf7d8a825119bc387c23e9a1d1989682b0), closes [#1047](https://github.com/kbknapp/clap-rs/issues/1047))
-
-#### Documentation
-
-* adds addtional blurbs about using multiples with subcommands ([03455b77](https://github.com/kbknapp/clap-rs/commit/03455b7751a757e7b2f6ffaf2d16168539c99661))
-* updates the docs to reflect changes to global args and that global args values can now be propagated back up the stack ([ead076f0](https://github.com/kbknapp/clap-rs/commit/ead076f03ada4c322bf3e34203925561ec496d87))
-* add html_root_url attribute ([e67a061b](https://github.com/kbknapp/clap-rs/commit/e67a061bcf567c6518d6c2f58852e01f02764b22))
-* sync README version numbers with crate version ([5536361b](https://github.com/kbknapp/clap-rs/commit/5536361bcda29887ed86bb68e43d0b603cbc423f))
-
-#### Improvements
-
-* args that have require_delimiter(true) is now reflected in help and usage strings ([dce61699](https://github.com/kbknapp/clap-rs/commit/dce616998ed9bd95e8ed3bec1f09a4883da47b85), closes [#1052](https://github.com/kbknapp/clap-rs/issues/1052))
-* if all subcommands are hidden, the subcommands section of the help message is no longer displayed ([4ae7b046](https://github.com/kbknapp/clap-rs/commit/4ae7b0464750bc07ec80ece38e43f003fdd1b8ae), closes [#1046](https://github.com/kbknapp/clap-rs/issues/1046))
-
-#### Breaking Changes
-
-* when an argument requires a value and that value happens to match a subcommand name, its parsed as a value ([0c223f54](https://github.com/kbknapp/clap-rs/commit/0c223f54ed46da406bc8b43a5806e0b227863b31), closes [#1031](https://github.com/kbknapp/clap-rs/issues/1031), breaks [#](https://github.com/kbknapp/clap-rs/issues/), [#](https://github.com/kbknapp/clap-rs/issues/))
-
-#### Deprecations
-
-* **AppSettings::PropagateGlobalValuesDown:** this setting is no longer required to propagate values down or up ([2bb5ddce](https://github.com/kbknapp/clap-rs/commit/2bb5ddcee61c791ca1aaca494fbeb4bd5e277488))
-
-
-
-<a name="v2.26.2"></a>
-### v2.26.2 (2017-09-14)
-
-
-#### Improvements
-
-* if all subcommands are hidden, the subcommands section of the help message is no longer displayed ([4ae7b046](https://github.com/kbknapp/clap-rs/commit/4ae7b0464750bc07ec80ece38e43f003fdd1b8ae), closes [#1046](https://github.com/kbknapp/clap-rs/issues/1046))
-
-#### Bug Fixes
-
-* fixes a bug where default values are not applied if the option supports zero values ([9c248cbf](https://github.com/kbknapp/clap-rs/commit/9c248cbf7d8a825119bc387c23e9a1d1989682b0), closes [#1047](https://github.com/kbknapp/clap-rs/issues/1047))
-
-
-
-<a name="v2.26.1"></a>
-### v2.26.1 (2017-09-14)
-
-
-#### Bug Fixes
-
-* fixes using require_equals(true) and min_values(0) together ([10ae208f](https://github.com/kbknapp/clap-rs/commit/10ae208f68518eff6e98166724065745f4083174), closes [#1044](https://github.com/kbknapp/clap-rs/issues/1044))
-* escape special characters in zsh and fish completions ([87e019fc](https://github.com/kbknapp/clap-rs/commit/87e019fc84ba6193a8c4ddc26c61eb99efffcd25))
-* avoid panic generating default help msg if term width set to 0 due to bug in textwrap 0.7.0 ([b3eadb0d](https://github.com/kbknapp/clap-rs/commit/b3eadb0de516106db4e08f078ad32e8f6d6e7a57))
-* Change `who's` -> `whose` ([53c1ffe8](https://github.com/kbknapp/clap-rs/commit/53c1ffe87f38b05d8804a0f7832412a952845349))
-* adds a debug assertion to ensure all args added to groups actually exist ([7ad123e2](https://github.com/kbknapp/clap-rs/commit/7ad123e2c02577e3ca30f7e205181e896b157d11), closes [#917](https://github.com/kbknapp/clap-rs/issues/917))
-* fixes a bug where args that allow values to start with a hyphen couldnt contain a double hyphen -- as a value ([ab2f4c9e](https://github.com/kbknapp/clap-rs/commit/ab2f4c9e563e36ec739a4b55d5a5b76fdb9e9fa4), closes [#960](https://github.com/kbknapp/clap-rs/issues/960))
-* fixes a bug where positional argument help text is misaligned ([54c16836](https://github.com/kbknapp/clap-rs/commit/54c16836dea4651806a2cfad53146a83fa3abf21))
-* **Help Message:** fixes long_about not being usable ([a8257ea0](https://github.com/kbknapp/clap-rs/commit/a8257ea0ffb812e552aca256c4a3d2aebfd8065b), closes [#1043](https://github.com/kbknapp/clap-rs/issues/1043))
-* **Suggestions:** output for flag after subcommand ([434ea5ba](https://github.com/kbknapp/clap-rs/commit/434ea5ba71395d8c1afcf88e69f0b0d8339b01a1))
-
-
-
-<a name="v2.26.0"></a>
-## v2.26.0 (2017-07-29)
-
-Minimum version of Rust is now v1.13.0 (Stable)
-
-
-#### Improvements
-
-* bumps unicode-segmentation to v1.2 ([cd7b40a2](https://github.com/kbknapp/clap-rs/commit/cd7b40a21c77bae17ba453c5512cb82b7d1ce474))
-
-
-#### Performance
-
-* update textwrap to version 0.7.0 ([c2d4e637](https://github.com/kbknapp/clap-rs/commit/c2d4e63756a6f070e38c16dff846e9b0a53d6f93))
-
-
-
-
-<a name="v2.25.1"></a>
-### v2.25.1 (2017-07-21)
-
-#### Improvements
-
-* impl Default for Values + OsValues for any lifetime. ([fb7d6231f1](https://github.com/kbknapp/clap-rs/commit/fb7d6231f13a2f79f411e62dca210b7dc9994c18))
-
-#### Documentation
-
-* Various documentation typos and grammar fixes
-
-<a name="v2.25.0"></a>
-### v2.25.0 (2017-06-20)
-
-
-#### Features
-
-* use textwrap crate for wrapping help texts ([b93870c1](https://github.com/kbknapp/clap-rs/commit/b93870c10ae3bd90d233c586a33e086803117285))
-
-#### Improvements
-
-* **Suggestions:** suggests to use flag after subcommand when applicable ([2671ca72](https://github.com/kbknapp/clap-rs/commit/2671ca7260119d4311d21c4075466aafdd9da734))
-* Bumps bitflags crate to v0.9
-
-#### Documentation
-
-* Change `who's` -> `whose` ([53c1ffe8](https://github.com/kbknapp/clap-rs/commit/53c1ffe87f38b05d8804a0f7832412a952845349))
-
-#### Documentation
-
-* **App::template:** adds details about the necessity to use AppSettings::UnifiedHelpMessage when using {unified} tags in the help template ([cbea3d5a](https://github.com/kbknapp/clap-rs/commit/cbea3d5acf3271a7a734498c4d99c709941c331e), closes [#949](https://github.com/kbknapp/clap-rs/issues/949))
-* **Arg::allow_hyphen_values:** updates the docs to include warnings for allow_hyphen_values and multiple(true) used together ([f9b0d657](https://github.com/kbknapp/clap-rs/commit/f9b0d657835d3f517f313d70962177dc30acf4a7))
-* **README.md:**
- * added a warning about using ~ deps ([821929b5](https://github.com/kbknapp/clap-rs/commit/821929b51bd60213955705900a436c9a64fcb79f), closes [#964](https://github.com/kbknapp/clap-rs/issues/964))
-* **clap_app!:** adds using the @group specifier to the macro docs ([826048cb](https://github.com/kbknapp/clap-rs/commit/826048cb3cbc0280169303f1498ff0a2b7395883), closes [#932](https://github.com/kbknapp/clap-rs/issues/932))
-
-
-
-<a name="v2.24.2"></a>
-### v2.24.2 (2017-05-15)
-
-
-#### Bug Fixes
-
-* adds a debug assertion to ensure all args added to groups actually exist ([14f6b8f3](https://github.com/kbknapp/clap-rs/commit/14f6b8f3a2f6df73aeeec9c54a54909b1acfc158), closes [#917](https://github.com/kbknapp/clap-rs/issues/917))
-* fixes a bug where args that allow values to start with a hyphen couldnt contain a double hyphen -- as a value ([ebf73a09](https://github.com/kbknapp/clap-rs/commit/ebf73a09db6f3c03c19cdd76b1ba6113930e1643), closes [#960](https://github.com/kbknapp/clap-rs/issues/960))
-* fixes a bug where positional argument help text is misaligned ([54c16836](https://github.com/kbknapp/clap-rs/commit/54c16836dea4651806a2cfad53146a83fa3abf21))
-
-#### Documentation
-
-* **App::template:** adds details about the necessity to use AppSettings::UnifiedHelpMessage when using {unified} tags in the help template ([cf569438](https://github.com/kbknapp/clap-rs/commit/cf569438f309c199800bb8e46c9f140187de69d7), closes [#949](https://github.com/kbknapp/clap-rs/issues/949))
-* **Arg::allow_hyphen_values:** updates the docs to include warnings for allow_hyphen_values and multiple(true) used together ([ded5a2f1](https://github.com/kbknapp/clap-rs/commit/ded5a2f15474d4a5bd46a67b130ccb8b6781bd01))
-* **clap_app!:** adds using the @group specifier to the macro docs ([fe85fcb1](https://github.com/kbknapp/clap-rs/commit/fe85fcb1772b61f13b20b7ea5290e2437a76190c), closes [#932](https://github.com/kbknapp/clap-rs/issues/932))
-
-
-
-<a name="v2.24.0"></a>
-### v2.24.0 (2017-05-07)
-
-
-#### Bug Fixes
-
-* fixes a bug where args with last(true) and required(true) set were not being printed in the usage string ([3ac533fe](https://github.com/kbknapp/clap-rs/commit/3ac533fedabf713943eedf006f830a5a486bbe80), closes [#944](https://github.com/kbknapp/clap-rs/issues/944))
-* fixes a bug that was printing the arg name, instead of value name when Arg::last(true) was used ([e1fe8ac3](https://github.com/kbknapp/clap-rs/commit/e1fe8ac3bc1f9cf4e36df0d881f8419755f1787b), closes [#940](https://github.com/kbknapp/clap-rs/issues/940))
-* fixes a bug where flags were parsed as flags AND positional values when specific combinations of settings were used ([20f83292](https://github.com/kbknapp/clap-rs/commit/20f83292d070038b8cee2a6b47e91f6b0a2f7871), closes [#946](https://github.com/kbknapp/clap-rs/issues/946))
-
-
-
-<a name="v2.24.0"></a>
-## v2.24.0 (2017-05-05)
-
-
-#### Documentation
-
-* **README.md:** fix some typos ([fa34deac](https://github.com/kbknapp/clap-rs/commit/fa34deac079f334c3af97bb7fb151880ba8887f8))
-
-#### API Additions
-
-* **Arg:** add `default_value_os` ([d5ef8955](https://github.com/kbknapp/clap-rs/commit/d5ef8955414b1587060f7218385256105b639c88))
-* **arg_matches.rs:** Added a Default implementation for Values and OsValues iterators. ([0a4384e3](https://github.com/kbknapp/clap-rs/commit/0a4384e350eed74c2a4dc8964c203f21ac64897f))
-
-
-<a name="v2.23.2"></a>
-### v2.23.2 (2017-04-19)
-
-
-#### Bug Fixes
-
-* **PowerShell Completions:** fixes a bug where powershells completions cant be used if no subcommands are defined ([a8bce558](https://github.com/kbknapp/clap-rs/commit/a8bce55837dc4e0fb187dc93180884a40ae09c6f), closes [#931](https://github.com/kbknapp/clap-rs/issues/931))
-
-#### Improvements
-
-* bumps term_size to take advantage of better terminal dimension handling ([e05100b7](https://github.com/kbknapp/clap-rs/commit/e05100b73d74066a90876bf38f952adf5e8ee422))
-* **PowerShell Completions:** massively dedups subcommand names in the generate script to make smaller scripts that are still functionally equiv ([85b0e1cc](https://github.com/kbknapp/clap-rs/commit/85b0e1cc4b9755dda75a93d898d79bc38631552b))
-
-#### Documentation
-
-* Fix a typo the minimum rust version required ([71dabba3](https://github.com/kbknapp/clap-rs/commit/71dabba3ea0a17c88b0e2199c9d99f0acbf3bc17))
-
-<a name="v2.23.1"></a>
-### v2.23.1 (2017-04-05)
-
-
-#### Bug Fixes
-
-* fixes a missing newline character in the autogenerated help and version messages in some instances ([5ae9007d](https://github.com/kbknapp/clap-rs/commit/5ae9007d984ae94ae2752df51bcbaeb0ec89bc15))
-
-
-<a name="v2.23.0"></a>
-## v2.23.0 (2017-04-05)
-
-
-#### API Additions
-
-* `App::long_about`
-* `App::long_version`
-* `App::print_long_help`
-* `App::write_long_help`
-* `App::print_long_version`
-* `App::write_long_version`
-* `Arg::long_help`
-
-#### Features
-
-* allows distinguishing between short and long version messages (-V/short or --version/long) ([59272b06](https://github.com/kbknapp/clap-rs/commit/59272b06cc213289dc604dbc694cb95d383a5d68))
-* allows distinguishing between short and long help with subcommands in the same manner as args ([6b371891](https://github.com/kbknapp/clap-rs/commit/6b371891a1702173a849d1e95f9fecb168bf6fc4))
-* allows specifying a short help vs a long help (i.e. varying levels of detail depending on if -h or --help was used) ([ef1b24c3](https://github.com/kbknapp/clap-rs/commit/ef1b24c3a0dff2f58c5e2e90880fbc2b69df20ee))
-* **clap_app!:** adds support for arg names with hyphens similar to longs with hyphens ([f7a88779](https://github.com/kbknapp/clap-rs/commit/f7a8877978c8f90e6543d4f0d9600c086cf92cd7), closes [#869](https://github.com/kbknapp/clap-rs/issues/869))
-
-#### Bug Fixes
-
-* fixes a bug that wasn't allowing help and version to be properly overridden ([8b2ceb83](https://github.com/kbknapp/clap-rs/commit/8b2ceb8368bcb70689fadf1c7f4b9549184926c1), closes [#922](https://github.com/kbknapp/clap-rs/issues/922))
-
-#### Documentation
-
-* **clap_app!:** documents the `--("some-arg")` method for using args with hyphens inside them ([bc08ef3e](https://github.com/kbknapp/clap-rs/commit/bc08ef3e185393073d969d301989b6319c616c1f), closes [#919](https://github.com/kbknapp/clap-rs/issues/919))
-
-
-
-<a name="v2.22.2"></a>
-### v2.22.2 (2017-03-30)
-
-
-#### Bug Fixes
-
-* **Custom Usage Strings:** fixes the usage string regression when using help templates ([0e4fd96d](https://github.com/kbknapp/clap-rs/commit/0e4fd96d74280d306d09e60ac44f938a82321769))
-
-
-
-<a name="v2.22.1"></a>
-### v2.22.1 (2017-03-24)
-
-
-#### Bug Fixes
-
-* **usage:** fixes a big regression with custom usage strings ([2c41caba](https://github.com/kbknapp/clap-rs/commit/2c41caba3c7d723a2894e315d04da796b0e97759))
-
-<a name="v2.22.0"></a>
-## v2.22.0 (2017-03-23)
-
-#### API Additions
-
-* **App::name:** adds the ability to change the name of the App instance after creation ([d49e8292](https://github.com/kbknapp/clap-rs/commit/d49e8292b026b06e2b70447cd9f08299f4fcba76), closes [#908](https://github.com/kbknapp/clap-rs/issues/908))
-* **Arg::hide_default_value:** adds ability to hide the default value of an argument from the help string ([89e6ea86](https://github.com/kbknapp/clap-rs/commit/89e6ea861e16a1ad56757ca12f6b32d02253e44a), closes [#902](https://github.com/kbknapp/clap-rs/issues/902))
-
-
-<a name="v2.21.3"></a>
-### v2.21.3 (2017-03-23)
-
-#### Bug Fixes
-
-* **yaml:** adds support for loading author info from yaml ([e04c390c](https://github.com/kbknapp/clap-rs/commit/e04c390c597a55fa27e724050342f16c42f1c5c9))
-
-
-<a name="v2.21.2"></a>
-### v2.21.2 (2017-03-17)
-
-
-#### Improvements
-
-* add fish subcommand help support ([f8f68cf8](https://github.com/kbknapp/clap-rs/commit/f8f68cf8251669aef4539a25a7c1166f0ac81ea6))
-* options that use `require_equals(true)` now display the equals sign in help messages, usage strings, and errors" ([c8eb0384](https://github.com/kbknapp/clap-rs/commit/c8eb0384d394d2900ccdc1593099c97808a3fa05), closes [#903](https://github.com/kbknapp/clap-rs/issues/903))
-
-
-#### Bug Fixes
-
-* setting the max term width now correctly propagates down through child subcommands
-
-
-
-<a name="v2.21.1"></a>
-### v2.21.1 (2017-03-12)
-
-
-#### Bug Fixes
-
-* **ArgRequiredElseHelp:** fixes the precedence of this error to prioritize over other error messages ([74b751ff](https://github.com/kbknapp/clap-rs/commit/74b751ff2e3631e337b7946347c1119829a41c53), closes [#895](https://github.com/kbknapp/clap-rs/issues/895))
-* **Positionals:** fixes some regression bugs resulting from old asserts in debug mode. ([9a3bc98e](https://github.com/kbknapp/clap-rs/commit/9a3bc98e9b55e7514b74b73374c5ac8b6e5e0508), closes [#896](https://github.com/kbknapp/clap-rs/issues/896))
-
-
-
-<a name="v2.21.0"></a>
-## v2.21.0 (2017-03-09)
-
-#### Performance
-
-* doesn't run `arg_post_processing` on multiple values anymore ([ec516182](https://github.com/kbknapp/clap-rs/commit/ec5161828729f6a53f0fccec8648f71697f01f78))
-* changes internal use of `VecMap` to `Vec` for matched values of `Arg`s ([22bf137a](https://github.com/kbknapp/clap-rs/commit/22bf137ac581684c6ed460d2c3c640c503d62621))
-* vastly reduces the amount of cloning when adding non-global args minus when they're added from `App::args` which is forced to clone ([8da0303b](https://github.com/kbknapp/clap-rs/commit/8da0303bc02db5fe047cfc0631a9da41d9dc60f7))
-* refactor to remove unneeded vectors and allocations and checks for significant performance increases ([0efa4119](https://github.com/kbknapp/clap-rs/commit/0efa4119632f134fc5b8b9695b007dd94b76735d))
-
-#### Documentation
-
-* Fix examples link in CONTRIBUTING.md ([60cf875d](https://github.com/kbknapp/clap-rs/commit/60cf875d67a252e19bb85054be57696fac2c57a1))
-
-#### Improvements
-
-* when `AppSettings::SubcommandsNegateReqs` and `ArgsNegateSubcommands` are used, a new more accurate double line usage string is shown ([50f02300](https://github.com/kbknapp/clap-rs/commit/50f02300d81788817acefef0697e157e01b6ca32), closes [#871](https://github.com/kbknapp/clap-rs/issues/871))
-
-#### API Additions
-
-* **Arg::last:** adds the ability to mark a positional argument as 'last' which means it should be used with `--` syntax and can be accessed early ([6a7aea90](https://github.com/kbknapp/clap-rs/commit/6a7aea9043b83badd9ab038b4ecc4c787716147e), closes [#888](https://github.com/kbknapp/clap-rs/issues/888))
-* provides `default_value_os` and `default_value_if[s]_os` ([0f2a3782](https://github.com/kbknapp/clap-rs/commit/0f2a378219a6930748d178ba350fe5925be5dad5), closes [#849](https://github.com/kbknapp/clap-rs/issues/849))
-* provides `App::help_message` and `App::version_message` which allows one to override the auto-generated help/version flag associated help ([389c413](https://github.com/kbknapp/clap-rs/commit/389c413b7023dccab8c76aa00577ea1d048e7a99), closes [#889](https://github.com/kbknapp/clap-rs/issues/889))
-
-#### New Settings
-
-* **InferSubcommands:** adds a setting to allow one to infer shortened subcommands or aliases (i.e. for subcommmand "test", "t", "te", or "tes" would be allowed assuming no other ambiguities) ([11602032](https://github.com/kbknapp/clap-rs/commit/11602032f6ff05881e3adf130356e37d5e66e8f9), closes [#863](https://github.com/kbknapp/clap-rs/issues/863))
-
-#### Bug Fixes
-
-* doesn't print the argument sections in the help message if all args in that section are hidden ([ce5ee5f5](https://github.com/kbknapp/clap-rs/commit/ce5ee5f5a76f838104aeddd01c8ec956dd347f50))
-* doesn't include the various [ARGS] [FLAGS] or [OPTIONS] if the only ones available are hidden ([7b4000af](https://github.com/kbknapp/clap-rs/commit/7b4000af97637703645c5fb2ac8bb65bd546b95b), closes [#882](https://github.com/kbknapp/clap-rs/issues/882))
-* now correctly shows subcommand as required in the usage string when AppSettings::SubcommandRequiredElseHelp is used ([8f0884c1](https://github.com/kbknapp/clap-rs/commit/8f0884c1764983a49b45de52a1eddf8d721564d8))
-* fixes some memory leaks when an error is detected and clap exits ([8c2dd287](https://github.com/kbknapp/clap-rs/commit/8c2dd28718262ace4ae0db98563809548e02a86b))
-* fixes a trait that's marked private accidentlly, but should be crate internal public ([1ae21108](https://github.com/kbknapp/clap-rs/commit/1ae21108015cea87e5360402e1747025116c7878))
-* **Completions:** fixes a bug that tried to propogate global args multiple times when generating multiple completion scripts ([5e9b9cf4](https://github.com/kbknapp/clap-rs/commit/5e9b9cf4dd80fa66a624374fd04e6545635c1f94), closes [#846](https://github.com/kbknapp/clap-rs/issues/846))
-
-#### Features
-
-* **Options:** adds the ability to require the equals syntax with options --opt=val ([f002693d](https://github.com/kbknapp/clap-rs/commit/f002693dec6a6959c4e9590cb7b7bfffd6d6e5bc), closes [#833](https://github.com/kbknapp/clap-rs/issues/833))
-
-
-
-<a name="v2.20.5"></a>
-### v2.20.5 (2017-02-18)
-
-
-#### Bug Fixes
-
-* **clap_app!:** fixes a critical bug of a missing fragment specifier when using `!property` style tags. ([5635c1f94](https://github.com/kbknapp/clap-rs/commit/5e9b9cf4dd80fa66a624374fd04e6545635c1f94))
-
-
-<a name="v2.20.4"></a>
-### v2.20.4 (2017-02-15)
-
-
-#### Bug Fixes
-
-* **Completions:** fixes a bug that tried to propogate global args multiple times when generating multiple completion scripts ([5e9b9cf4](https://github.com/kbknapp/clap-rs/commit/5e9b9cf4dd80fa66a624374fd04e6545635c1f94), closes [#846](https://github.com/kbknapp/clap-rs/issues/846))
-
-#### Documentation
-
-* Fix examples link in CONTRIBUTING.md ([60cf875d](https://github.com/kbknapp/clap-rs/commit/60cf875d67a252e19bb85054be57696fac2c57a1))
-
-
-<a name="v2.20.3"></a>
-### v2.20.3 (2017-02-03)
-
-
-#### Documentation
-
-* **Macros:** adds a warning about changing values in Cargo.toml not triggering a rebuild automatically ([112aea3e](https://github.com/kbknapp/clap-rs/commit/112aea3e42ae9e0c0a2d33ebad89496dbdd95e5d), closes [#838](https://github.com/kbknapp/clap-rs/issues/838))
-
-#### Bug Fixes
-
-* fixes a println->debugln typo ([279aa62e](https://github.com/kbknapp/clap-rs/commit/279aa62eaf08f56ce090ba16b937bc763cbb45be))
-* fixes bash completions for commands that have an underscore in the name ([7f5cfa72](https://github.com/kbknapp/clap-rs/commit/7f5cfa724f0ac4e098f5fe466c903febddb2d994), closes [#581](https://github.com/kbknapp/clap-rs/issues/581))
-* fixes a bug where ZSH completions would panic if the binary name had an underscore in it ([891a2a00](https://github.com/kbknapp/clap-rs/commit/891a2a006f775e92c556dda48bb32fac9807c4fb), closes [#581](https://github.com/kbknapp/clap-rs/issues/581))
-* allow final word to be wrapped in wrap_help ([564c5f0f](https://github.com/kbknapp/clap-rs/commit/564c5f0f1730f4a2c1cdd128664f1a981c31dcd4), closes [#828](https://github.com/kbknapp/clap-rs/issues/828))
-* fixes a bug where global args weren't included in the generated completion scripts ([9a1e006e](https://github.com/kbknapp/clap-rs/commit/9a1e006eb75ad5a6057ebd119aa90f7e06c0ace8), closes [#841](https://github.com/kbknapp/clap-rs/issues/841))
-
-
-
-<a name="v2.20.2"></a>
-### v2.20.2 (2017-02-03)
-
-#### Bug Fixes
-
-* fixes a critical bug where subcommand settings were being propogated too far ([74648c94](https://github.com/kbknapp/clap-rs/commit/74648c94b893df542bfa5bb595e68c7bb8167e36), closes [#832](https://github.com/kbknapp/clap-rs/issues/832))
-
-
-#### Improvements
-
-* adds ArgGroup::multiple to the supported YAML fields for building ArgGroups from YAML ([d8590037](https://github.com/kbknapp/clap-rs/commit/d8590037ce07dafd8cd5b26928aa4a9fd3018288), closes [#840](https://github.com/kbknapp/clap-rs/issues/840))
-
-<a name="v2.20.1"></a>
-### v2.20.1 (2017-01-31)
-
-#### Bug Fixes
-
-* allow final word to be wrapped in wrap_help ([564c5f0f](https://github.com/kbknapp/clap-rs/commit/564c5f0f1730f4a2c1cdd128664f1a981c31dcd4), closes [#828](https://github.com/kbknapp/clap-rs/issues/828))
-* actually show character in debug output ([84d8c547](https://github.com/kbknapp/clap-rs/commit/84d8c5476de95b7f37d61888bc4f13688b712434))
-* include final character in line lenght ([aff4ba18](https://github.com/kbknapp/clap-rs/commit/aff4ba18da8147e1259b04b0bfbc1fcb5c78a3c0))
-
-#### Improvements
-
-* updates libc and term_size deps for the libc version conflict ([6802ac4a](https://github.com/kbknapp/clap-rs/commit/6802ac4a59c142cda9ec55ca0c45ae5cb9a6ab55))
-
-#### Documentation
-
-* fix link from app_from_crate! to crate_authors! (#822) ([5b29be9b](https://github.com/kbknapp/clap-rs/commit/5b29be9b073330ab1f7227cdd19fe4aab39d5dcb))
-* fix spelling of "guaranteed" ([4f30a65b](https://github.com/kbknapp/clap-rs/commit/4f30a65b9c03eb09607eb91a929a6396637dc105))
-
-<a name="v2.20.0"></a>
-
-#### New Settings
-
-* **ArgsNegateSubcommands:** disables args being allowed between subcommands ([5e2af8c9](https://github.com/kbknapp/clap-rs/commit/5e2af8c96adb5ab75fa2d1536237ebcb41869494), closes [#793](https://github.com/kbknapp/clap-rs/issues/793))
-* **DontCollapseArgsInUsage:** disables the collapsing of positional args into `[ARGS]` in the usage string ([c2978afc](https://github.com/kbknapp/clap-rs/commit/c2978afc61fb46d5263ab3b2d87ecde1c9ce1553), closes [#769](https://github.com/kbknapp/clap-rs/issues/769))
-* **DisableHelpSubcommand:** disables building the `help` subcommand ([a10fc859](https://github.com/kbknapp/clap-rs/commit/a10fc859ee20159fbd9ff4337be59b76467a64f2))
-* **AllowMissingPositional:** allows one to implement `$ prog [optional] <required>` style CLIs where the second postional argument is required, but the first is optional ([1110fdc7](https://github.com/kbknapp/clap-rs/commit/1110fdc7a345c108820dc45783a9bf893fa4c214), closes [#636](https://github.com/kbknapp/clap-rs/issues/636))
-* **PropagateGlobalValuesDown:** automatically propagats global arg's values down through *used* subcommands ([985536c8](https://github.com/kbknapp/clap-rs/commit/985536c8ebcc09af98aac835f42a8072ad58c262), closes [#694](https://github.com/kbknapp/clap-rs/issues/694))
-
-#### API Additions
-
-##### Arg
-
-* **Arg::value_terminator:** adds the ability to terminate multiple values with a given string or char ([be64ce0c](https://github.com/kbknapp/clap-rs/commit/be64ce0c373efc106384baca3f487ea99fe7b8cf), closes [#782](https://github.com/kbknapp/clap-rs/issues/782))
-* **Arg::default_value_if[s]:** adds new methods for *conditional* default values (such as a particular value from another argument was used) ([eb4010e7](https://github.com/kbknapp/clap-rs/commit/eb4010e7b21724447ef837db11ac441915728f22))
-* **Arg::requires_if[s]:** adds the ability to *conditionally* require additional args (such as if a particular value was used) ([198449d6](https://github.com/kbknapp/clap-rs/commit/198449d64393c265f0bc327aaeac23ec4bb97226))
-* **Arg::required_if[s]:** adds the ability for an arg to be *conditionally* required (i.e. "arg X is only required if arg Y was used with value Z") ([ee9cfddf](https://github.com/kbknapp/clap-rs/commit/ee9cfddf345a6b5ae2af42ba72aa5c89e2ca7f59))
-* **Arg::validator_os:** adds ability to validate values which may contain invalid UTF-8 ([47232498](https://github.com/kbknapp/clap-rs/commit/47232498a813db4f3366ccd3e9faf0bff56433a4))
-
-##### Macros
-
-* **crate_description!:** Uses the `Cargo.toml` description field to fill in the `App::about` method at compile time ([4d9a82db](https://github.com/kbknapp/clap-rs/commit/4d9a82db8e875e9b64a9c2a5c6e22c25afc1279d), closes [#778](https://github.com/kbknapp/clap-rs/issues/778))
-* **crate_name!:** Uses the `Cargo.toml` name field to fill in the `App::new` method at compile time ([4d9a82db](https://github.com/kbknapp/clap-rs/commit/4d9a82db8e875e9b64a9c2a5c6e22c25afc1279d), closes [#778](https://github.com/kbknapp/clap-rs/issues/778))
-* **app_from_crate!:** Combines `crate_version!`, `crate_name!`, `crate_description!`, and `crate_authors!` into a single macro call to build a default `App` instance from the `Cargo.toml` fields ([4d9a82db](https://github.com/kbknapp/clap-rs/commit/4d9a82db8e875e9b64a9c2a5c6e22c25afc1279d), closes [#778](https://github.com/kbknapp/clap-rs/issues/778))
-
-
-#### Features
-
-* **no_cargo:** adds a `no_cargo` feature to disable Cargo-env-var-dependent macros for those *not* using `cargo` to build their crates (#786) ([6fdd2f9d](https://github.com/kbknapp/clap-rs/commit/6fdd2f9d693aaf1118fc61bd362273950703f43d))
-
-#### Bug Fixes
-
-* **Options:** fixes a critical bug where options weren't forced to have a value ([5a5f2b1e](https://github.com/kbknapp/clap-rs/commit/5a5f2b1e9f598a0d0280ef3e98abbbba2bc41132), closes [#665](https://github.com/kbknapp/clap-rs/issues/665))
-* fixes a bug where calling the help of a subcommand wasn't ignoring required args of parent commands ([d3d34a2b](https://github.com/kbknapp/clap-rs/commit/d3d34a2b51ef31004055b0ab574f766d801c3adf), closes [#789](https://github.com/kbknapp/clap-rs/issues/789))
-* **Help Subcommand:** fixes a bug where the help subcommand couldn't be overriden ([d34ec3e0](https://github.com/kbknapp/clap-rs/commit/d34ec3e032d03e402d8e87af9b2942fe2819b2da), closes [#787](https://github.com/kbknapp/clap-rs/issues/787))
-* **Low Index Multiples:** fixes a bug which caused combinations of LowIndexMultiples and `Arg::allow_hyphen_values` to fail parsing ([26c670ca](https://github.com/kbknapp/clap-rs/commit/26c670ca16d2c80dc26d5c1ce83380ace6357318))
-
-#### Improvements
-
-* **Default Values:** improves the error message when default values are involved ([1f33de54](https://github.com/kbknapp/clap-rs/commit/1f33de545036e7fd2f80faba251fca009bd519b8), closes [#774](https://github.com/kbknapp/clap-rs/issues/774))
-* **YAML:** adds conditional requirements and conditional default values to YAML ([9a4df327](https://github.com/kbknapp/clap-rs/commit/9a4df327893486adb5558ffefba790c634ccdc6e), closes [#764](https://github.com/kbknapp/clap-rs/issues/764))
-* Support `--("some-arg-name")` syntax for defining long arg names when using `clap_app!` macro ([f41ec962](https://github.com/kbknapp/clap-rs/commit/f41ec962c243a5ffff8b1be1ae2ad63970d3d1d4))
-* Support `("some app name")` syntax for defining app names when using `clap_app!` macro ([9895b671](https://github.com/kbknapp/clap-rs/commit/9895b671cff784f35cf56abcd8270f7c2ba09699), closes [#759](https://github.com/kbknapp/clap-rs/issues/759))
-* **Help Wrapping:** long app names (with spaces), authors, and descriptions are now wrapped appropriately ([ad4691b7](https://github.com/kbknapp/clap-rs/commit/ad4691b71a63e951ace346318238d8834e04ad8a), closes [#777](https://github.com/kbknapp/clap-rs/issues/777))
-
-
-#### Documentation
-
-* **Conditional Default Values:** fixes the failing doc tests of Arg::default_value_ifs ([4ef09101](https://github.com/kbknapp/clap-rs/commit/4ef091019c083b4db1a0c13f1c1e95ac363259f2))
-* **Conditional Requirements:** adds docs for Arg::requires_ifs ([7f296e29](https://github.com/kbknapp/clap-rs/commit/7f296e29db7d9036e76e5dbcc9c8b20dfe7b25bd))
-* **README.md:** fix some typos ([f22c21b4](https://github.com/kbknapp/clap-rs/commit/f22c21b422d5b287d1a1ac183a379ee02eebf54f))
-* **src/app/mod.rs:** fix some typos ([5c9b0d47](https://github.com/kbknapp/clap-rs/commit/5c9b0d47ca78dea285c5b9dec79063d24c3e451a))
-
-<a name="v2.19.3"></a>
-### v2.19.3 (2016-12-28)
-
-
-#### Bug Fixes
-
-* fixes a bug where calling the help of a subcommand wasn't ignoring required args of parent commands ([a0ee4993](https://github.com/kbknapp/clap-rs/commit/a0ee4993015ea97b06b5bc9f378d8bcb18f1c51c), closes [#789](https://github.com/kbknapp/clap-rs/issues/789))
-
-
-
-<a name="v2.19.2"></a>
-### v2.19.2 (2016-12-08)
-
-#### Bug Fixes
-
-* **ZSH Completions:** escapes square brackets in ZSH completions ([7e17d5a3](https://github.com/kbknapp/clap-rs/commit/7e17d5a36b2cc2cc77e7b15796b14d639ed3cbf7), closes [#771](https://github.com/kbknapp/clap-rs/issues/771))
-
-#### Documentation
-
-* **Examples:** adds subcommand examples ([0e0f3354](https://github.com/kbknapp/clap-rs/commit/0e0f33547a6901425afc1d9fbe19f7ae3832d9a4), closes [#766](https://github.com/kbknapp/clap-rs/issues/766))
-* **README.md:** adds guidance on when to use ~ in version pinning, and clarifies breaking change policy ([591eaefc](https://github.com/kbknapp/clap-rs/commit/591eaefc7319142ba921130e502bb0729feed907), closes [#765](https://github.com/kbknapp/clap-rs/issues/765))
-
-
-
-<a name="v2.19.1"></a>
-### v2.19.1 (2016-12-01)
-
-
-#### Bug Fixes
-
-* **Help Messages:** fixes help message alignment when specific settings are used on options ([cd94b318](https://github.com/kbknapp/clap-rs/commit/cd94b3188d63b63295a319e90e826bca46befcd2), closes [#760](https://github.com/kbknapp/clap-rs/issues/760))
-
-#### Improvements
-
-* **Bash Completion:** allows bash completion to fall back to traidtional bash completion upon no matching completing function ([b1b16d56](https://github.com/kbknapp/clap-rs/commit/b1b16d56d8fddf819bdbe24b3724bb6a9f3fa613)))
-
-
-<a name="v2.19.0"></a>
-## v2.19.0 (2016-11-21)
-
-#### Features
-
-* allows specifying AllowLeadingHyphen style values, but only for specific args vice command wide ([c0d70feb](https://github.com/kbknapp/clap-rs/commit/c0d70febad9996a77a54107054daf1914c50d4ef), closes [#742](https://github.com/kbknapp/clap-rs/issues/742))
-
-#### Bug Fixes
-
-* **Required Unless:** fixes a bug where having required_unless set doesn't work when conflicts are also set ([d20331b6](https://github.com/kbknapp/clap-rs/commit/d20331b6f7940ac3a4e919999f8bb4780875125d), closes [#753](https://github.com/kbknapp/clap-rs/issues/753))
-* **ZSH Completions:** fixes an issue where zsh completions caused panics if there were no subcommands ([49e7cdab](https://github.com/kbknapp/clap-rs/commit/49e7cdab76dd1ccc07221e360f07808ec62648aa), closes [#754](https://github.com/kbknapp/clap-rs/issues/754))
-
-#### Improvements
-
-* **Validators:** improves the error messages for validators ([65eb3385](https://github.com/kbknapp/clap-rs/commit/65eb33859d3ff53e7d3277f02a9d3fd9038a9dfb), closes [#744](https://github.com/kbknapp/clap-rs/issues/744))
-
-#### Documentation
-
-* updates the docs landing page ([01e1e33f](https://github.com/kbknapp/clap-rs/commit/01e1e33f377934099a4a725fab5cd6c5ff50eaa2))
-* adds the macro version back to the readme ([45eb9bf1](https://github.com/kbknapp/clap-rs/commit/45eb9bf130329c3f3853aba0342c2fe3c64ff80f))
-* fix broken docs links ([808e7cee](https://github.com/kbknapp/clap-rs/commit/808e7ceeb86d4a319bdc270f51c23a64621dbfb3))
-* **Compatibility Policy:** adds an official compatibility policy to ([760d66dc](https://github.com/kbknapp/clap-rs/commit/760d66dc17310b357f257776624151da933cd25d), closes [#740](https://github.com/kbknapp/clap-rs/issues/740))
-* **Contributing:** updates the readme to improve the readability and contributing sections ([eb51316c](https://github.com/kbknapp/clap-rs/commit/eb51316cdfdc7258d287ba13b67ef2f42bd2b8f6))
-
-<a name="v2.18.0"></a>
-## v2.18.0 (2016-11-05)
-
-
-#### Features
-
-* **Completions:** adds completion support for PowerShell. ([cff82c88](https://github.com/kbknapp/clap-rs/commit/cff82c880e21064fca63351507b80350df6caadf), closes [#729](https://github.com/kbknapp/clap-rs/issues/729))
-
-
-
-<a name="v2.17.1"></a>
-### v2.17.1 (2016-11-02)
-
-
-#### Bug Fixes
-
-* **Low Index Multiples:** fixes a bug where using low index multiples was propagated to subcommands ([33924e88](https://github.com/kbknapp/clap-rs/commit/33924e884461983c4e6b5ea1330fecc769a4ade7), closes [#725](https://github.com/kbknapp/clap-rs/issues/725))
-
-
-
-<a name="v2.17.0"></a>
-## v2.17.0 (2016-11-01)
-
-
-#### Features
-
-* **Positional Args:** allows specifying the second to last positional argument as multiple(true) ([1ced2a74](https://github.com/kbknapp/clap-rs/commit/1ced2a7433ea8937a1b260ea65d708f32ca7c95e), closes [#725](https://github.com/kbknapp/clap-rs/issues/725))
-
-
-
-<a name="v2.16.4"></a>
-### v2.16.4 (2016-10-31)
-
-
-#### Improvements
-
-* **Error Output:** conflicting errors are now symetrical, meaning more consistent and less confusing ([3d37001d](https://github.com/kbknapp/clap-rs/commit/3d37001d1dc647d73cc597ff172f1072d4beb80d), closes [#718](https://github.com/kbknapp/clap-rs/issues/718))
-
-#### Documentation
-
-* Fix typo in example `13a_enum_values_automatic` ([c22fbc07](https://github.com/kbknapp/clap-rs/commit/c22fbc07356e556ffb5d1a79ec04597d149b915e))
-* **README.md:** fixes failing yaml example (#715) ([21fba9e6](https://github.com/kbknapp/clap-rs/commit/21fba9e6cd8c163012999cd0ce271ec8780c5695))
-
-#### Bug Fixes
-
-* **ZSH Completions:** fixes bug that caused panic on subcommands with aliases ([5c70e1a0](https://github.com/kbknapp/clap-rs/commit/5c70e1a01bc977e44c10015d18bb8e215c32dfc8), closes [#714](https://github.com/kbknapp/clap-rs/issues/714))
-* **debug:** fixes the debug feature (#716) ([6c11ccf4](https://github.com/kbknapp/clap-rs/commit/6c11ccf443d46258d51f7cda33fbcc81e7fe8e90))
-
-
-
-<a name="v2.16.3"></a>
-### v2.16.3 (2016-10-28)
-
-
-#### Bug Fixes
-
-* Derive display order after propagation ([9cb6facf](https://github.com/kbknapp/clap-rs/commit/9cb6facf507aff7cddd124b8c29714d2b0e7bd13), closes [#706](https://github.com/kbknapp/clap-rs/issues/706))
-* **yaml-example:** inconsistent args ([847f7199](https://github.com/kbknapp/clap-rs/commit/847f7199219ead5065561d91d64780d99ae4b587))
-
-
-
-<a name="v2.15.1"></a>
-### v2.16.2 (2016-10-25)
-
-
-#### Bug Fixes
-
-* **Fish Completions:** fixes a bug where single quotes are not escaped ([780b4a18](https://github.com/kbknapp/clap-rs/commit/780b4a18281b6f7f7071e1b9db2290fae653c406), closes [#704](https://github.com/kbknapp/clap-rs/issues/704))
-
-
-<a name="v2.16.1"></a>
-### v2.16.1 (2016-10-24)
-
-
-#### Bug Fixes
-
-* **Help Message:** fixes a regression bug where args with multiple(true) threw off alignment ([ebddac79](https://github.com/kbknapp/clap-rs/commit/ebddac791f3ceac193d5ad833b4b734b9643a7af), closes [#702](https://github.com/kbknapp/clap-rs/issues/702))
-
-
-
-<a name="v2.16.0"></a>
-## v2.16.0 (2016-10-23)
-
-
-#### Features
-
-* **Completions:** adds ZSH completion support ([3e36b0ba](https://github.com/kbknapp/clap-rs/commit/3e36b0bac491d3f6194aee14604caf7be26b3d56), closes [#699](https://github.com/kbknapp/clap-rs/issues/699))
-
-
-
-<a name="v2.15.0"></a>
-## v2.15.0 (2016-10-21)
-
-
-#### Features
-
-* **AppSettings:** adds new setting `AppSettings::AllowNegativeNumbers` ([ab064546](https://github.com/kbknapp/clap-rs/commit/ab06454677fb6aa9b9f804644fcca2168b1eaee3), closes [#696](https://github.com/kbknapp/clap-rs/issues/696))
-
-#### Documentation
-
-* **app/settings.rs:** moves variants to roughly alphabetical order ([9ed4d4d7](https://github.com/kbknapp/clap-rs/commit/9ed4d4d7957a23357aef60081e45639ab9e3905f))
-
-
-<a name="v2.14.1"></a>
-### v2.14.1 (2016-10-20)
-
-
-#### Documentation
-
-* Improve documentation around features ([4ee85b95](https://github.com/kbknapp/clap-rs/commit/4ee85b95d2d16708a016a3ba4e6e2c93b89b7fad))
-* reword docs for ErrorKind and app::Settings ([3ccde7a4](https://github.com/kbknapp/clap-rs/commit/3ccde7a4b8f7a2ea8b916a5415c04a8ff4b5cb7a))
-* fix tests that fail when the "suggestions" feature is disabled ([996fc381](https://github.com/kbknapp/clap-rs/commit/996fc381763a48d125c7ea8a58fed057fd0b4ac6))
-* fix the OsString-using doc-tests ([af9e1a39](https://github.com/kbknapp/clap-rs/commit/af9e1a393ce6cdda46a03c8a4f48df222b015a24))
-* tag non-rust code blocks as such instead of ignoring them ([0ba9f4b1](https://github.com/kbknapp/clap-rs/commit/0ba9f4b123f281952581b6dec948f7e51dd22890))
-* **ErrorKind:** improve some errors about subcommands ([9f6217a4](https://github.com/kbknapp/clap-rs/commit/9f6217a424da823343d7b801b9c350dee3cd1906))
-* **yaml:** make sure the doc-tests don't fail before "missing file" ([8c0f5551](https://github.com/kbknapp/clap-rs/commit/8c0f55516f4910c78c9f8a2bdbd822729574f95b))
-
-#### Improvements
-
-* Stabilize clap_app! ([cd516006](https://github.com/kbknapp/clap-rs/commit/cd516006e35c37b005f329338560a0a53d1f3e00))
-* **with_defaults:** Deprecate App::with_defaults() ([26085409](https://github.com/kbknapp/clap-rs/commit/2608540940c8bb66e517b65706bc7dea55510682), closes [#638](https://github.com/kbknapp/clap-rs/issues/638))
-
-#### Bug Fixes
-
-* fixes a bug that made determining when to auto-wrap long help messages inconsistent ([468baadb](https://github.com/kbknapp/clap-rs/commit/468baadb8398fc1d37897b0c49374aef4cf97dca), closes [#688](https://github.com/kbknapp/clap-rs/issues/688))
-* **Completions:** fish completions for nested subcommands ([a61eaf8a](https://github.com/kbknapp/clap-rs/commit/a61eaf8aade76cfe90ccc0f7125751ebf60e3254))
-* **features:** Make lints not enable other nightly-requiring features ([835f75e3](https://github.com/kbknapp/clap-rs/commit/835f75e3ba20999117363ed9f916464d777f36ef))
-
-
-
-<a name="v2.14.0"></a>
-## v2.14.0 (2016-10-05)
-
-
-#### Features
-
-* **arg_aliases:** Ability to alias arguments ([33b5f6ef](https://github.com/kbknapp/clap-rs/commit/33b5f6ef2c9612ecabb31f96b824793e46bfd3dd), closes [#669](https://github.com/kbknapp/clap-rs/issues/669))
-* **flag_aliases:** Ability to alias flags ([40d6dac9](https://github.com/kbknapp/clap-rs/commit/40d6dac973927dded6ab423481634ef47ee7bfd7))
-
-#### Bug Fixes
-
-* **UsageParser:** Handle non-ascii names / options. ([1d6a7c6e](https://github.com/kbknapp/clap-rs/commit/1d6a7c6e7e6aadc527346aa822f19d8587f714f3), closes [#664](https://github.com/kbknapp/clap-rs/issues/664))
-
-#### Documentation
-
-* typo ([bac417fa](https://github.com/kbknapp/clap-rs/commit/bac417fa1cea3d32308334c7cccfcf54546cd9d8))
-
-
-<a name="v2.13.0"></a>
-## v2.13.0 (2016-09-18)
-
-
-#### Documentation
-
-* updates README.md with new website information and updated video tutorials info ([0c19c580](https://github.com/kbknapp/clap-rs/commit/0c19c580cf50f1b82ff32f70b36708ae2bcac132))
-* updates the docs about removing implicit value_delimiter(true) ([c81bc722](https://github.com/kbknapp/clap-rs/commit/c81bc722ebb8a86d22be89b5aec98df9fe222a08))
-* **Default Values:** adds better examples on using default values ([57a8d9ab](https://github.com/kbknapp/clap-rs/commit/57a8d9abb2f973c235a8a14f8fc031673d7a7460), closes [#418](https://github.com/kbknapp/clap-rs/issues/418))
-
-#### Bug Fixes
-
-* **Value Delimiters:** fixes the confusion around implicitly setting value delimiters. (default is now `false`) ([09d4d0a9](https://github.com/kbknapp/clap-rs/commit/09d4d0a9038d7ce2df55c2aec95e16f36189fcee), closes [#666](https://github.com/kbknapp/clap-rs/issues/666))
-
-
-
-<a name="v2.12.1"></a>
-### v2.12.1 (2016-09-13)
-
-
-#### Bug Fixes
-
-* **Help Wrapping:** fixes a regression-bug where the old {n} newline char stopped working ([92ac353b](https://github.com/kbknapp/clap-rs/commit/92ac353b48b7caa2511ad2a046d94da93c236cf6), closes [#661](https://github.com/kbknapp/clap-rs/issues/661))
-
-
-
-<a name="v2.12.0"></a>
-## v2.12.0 (2016-09-13)
-
-
-#### Features
-
-* **Help:** adds ability to hide the possible values on a per argument basis ([9151ef73](https://github.com/kbknapp/clap-rs/commit/9151ef739871f2e74910c342299c0de196b95dec), closes [#640](https://github.com/kbknapp/clap-rs/issues/640))
-* **help:** allow for limiting detected terminal width ([a43e28af](https://github.com/kbknapp/clap-rs/commit/a43e28af85c9a9deaedd5ef735f4f13008daab29), closes [#653](https://github.com/kbknapp/clap-rs/issues/653))
-
-#### Documentation
-
-* **Help Wrapping:** removes the verbiage about using `'{n}'` to insert newlines in help text ([c5a2b352](https://github.com/kbknapp/clap-rs/commit/c5a2b352ca600f5b802290ad945731066cd53611))
-* **Value Delimiters:** updates the docs for the Arg::multiple method WRT value delimiters and default settings ([f9d17a06](https://github.com/kbknapp/clap-rs/commit/f9d17a060aa53f10d0a6e1a7eed5d989d1a59533))
-* **appsettings:** Document AppSetting::DisableVersion ([94501965](https://github.com/kbknapp/clap-rs/commit/945019654d2ca67eb2b1d6014fdf80b84d528d30), closes [#589](https://github.com/kbknapp/clap-rs/issues/589))
-
-#### Bug Fixes
-
-* **AllowLeadingHyphen:** fixes a bug where valid args aren't recognized with this setting ([a9699e4d](https://github.com/kbknapp/clap-rs/commit/a9699e4d7cdc9a06e73b845933ff1fe6d76f016a), closes [#588](https://github.com/kbknapp/clap-rs/issues/588))
-
-#### Improvements
-
-* **Help Wrapping:**
- * clap now ignores hard newlines in help messages and properly re-aligns text, but still wraps if the term width is too small ([c7678523](https://github.com/kbknapp/clap-rs/commit/c76785239fd42adc8ca04f9202b6fec615aa9f14), closes [#617](https://github.com/kbknapp/clap-rs/issues/617))
- * makes some minor changes to when next line help is automatically used ([01cae799](https://github.com/kbknapp/clap-rs/commit/01cae7990a33167ac35103fb36c811b4fe6eb98f))
-* **Value Delimiters:** changes the default value delimiter rules ([f9e69254](https://github.com/kbknapp/clap-rs/commit/f9e692548e8c94de15f909432de301407d6bb834), closes [#655](https://github.com/kbknapp/clap-rs/issues/655))
-* **YAML:** supports setting Arg::require_delimiter from YAML ([b9b55a39](https://github.com/kbknapp/clap-rs/commit/b9b55a39dfebcdbdc05dca2692927e503db50816))
-
-#### Performance
-
-* **help:** fix redundant contains() checks ([a8afed74](https://github.com/kbknapp/clap-rs/commit/a8afed7428bf0733f8e93bb11ad6c00d9e970fcc))
-
-
-
-<a name="v2.11.3"></a>
-### v2.11.3 (2016-09-07)
-
-
-#### Documentation
-
-* **Help Wrapping:** removes the verbiage about using `'{n}'` to insert newlines in help text ([c5a2b352](https://github.com/kbknapp/clap-rs/commit/c5a2b352ca600f5b802290ad945731066cd53611))
-
-#### Improvements
-
-* **Help Wrapping:**
- * clap now ignores hard newlines in help messages and properly re-aligns text, but still wraps if the term width is too small ([c7678523](https://github.com/kbknapp/clap-rs/commit/c76785239fd42adc8ca04f9202b6fec615aa9f14), closes [#617](https://github.com/kbknapp/clap-rs/issues/617))
- * makes some minor changes to when next line help is automatically used ([01cae799](https://github.com/kbknapp/clap-rs/commit/01cae7990a33167ac35103fb36c811b4fe6eb98f))
-* **YAML:** supports setting Arg::require_delimiter from YAML ([b9b55a39](https://github.com/kbknapp/clap-rs/commit/b9b55a39dfebcdbdc05dca2692927e503db50816))
-
-
-
-
-<a name="v2.11.2"></a>
-### v2.11.2 (2016-09-06)
-
-#### Improvements
-
-* **Help Wrapping:** makes some minor changes to when next line help is automatically used ([5658b117](https://github.com/kbknapp/clap-rs/commit/5658b117aec3e03adff9c8c52a4c4bc1fcb4e1ff))
-
-
-<a name="v2.11.1"></a>
-### v2.11.1 (2016-09-05)
-
-
-#### Bug Fixes
-
-* **Settings:** fixes an issue where settings weren't propogated down through grand-child subcommands ([b3efc107](https://github.com/kbknapp/clap-rs/commit/b3efc107515d78517b20798ff3890b8a2b04498e), closes [#638](https://github.com/kbknapp/clap-rs/issues/638))
-
-#### Features
-
-* **Errors:** Errors with custom description ([58512f2f](https://github.com/kbknapp/clap-rs/commit/58512f2fcb430745f1ee6ee8f1c67f62dc216c73))
-
-#### Improvements
-
-* **help:** use term_size instead of home-grown solution ([fc7327e9](https://github.com/kbknapp/clap-rs/commit/fc7327e9dcf4258ef2baebf0a8714d9c0622855b))
-
-
-
-<a name="v2.11.0"></a>
-### v2.11.0 (2016-08-28)
-
-
-#### Bug Fixes
-
-* **Groups:** fixes some usage strings that contain both args in groups and ones that conflict with each other ([3d782def](https://github.com/kbknapp/clap-rs/commit/3d782def57725e2de26ca5a5bc5cc2e40ddebefb), closes [#616](https://github.com/kbknapp/clap-rs/issues/616))
-
-#### Documentation
-
-* moves docs to docs.rs ([03209d5e](https://github.com/kbknapp/clap-rs/commit/03209d5e1300906f00bafec1869c2047a92e5071), closes [#634](https://github.com/kbknapp/clap-rs/issues/634))
-
-#### Improvements
-
-* **Completions:** uses standard conventions for bash completion files, namely '{bin}.bash-completion' ([27f5bbfb](https://github.com/kbknapp/clap-rs/commit/27f5bbfbcc9474c2f57c2b92b1feb898ae46ee70), closes [#567](https://github.com/kbknapp/clap-rs/issues/567))
-* **Help:** automatically moves help text to the next line and wraps when term width is determined to be too small, or help text is too long ([150964c4](https://github.com/kbknapp/clap-rs/commit/150964c4e7124d54476c9d9b4b3f2406f0fd00e5), closes [#597](https://github.com/kbknapp/clap-rs/issues/597))
-* **YAML Errors:** vastly improves error messages when using YAML ([f43b7c65](https://github.com/kbknapp/clap-rs/commit/f43b7c65941c53adc0616b8646a21dc255862eb2), closes [#574](https://github.com/kbknapp/clap-rs/issues/574))
-
-#### Features
-
-* adds App::with_defaults to automatically use crate_authors! and crate_version! macros ([5520bb01](https://github.com/kbknapp/clap-rs/commit/5520bb012c127dfd299fd55699443c744d8dcd5b), closes [#600](https://github.com/kbknapp/clap-rs/issues/600))
-
-
-
-<a name="v2.10.4"></a>
-### v2.10.4 (2016-08-25)
-
-
-#### Bug Fixes
-
-* **Help Wrapping:** fixes a bug where help is wrapped incorrectly and causing a panic with some non-English characters ([d0b442c7](https://github.com/kbknapp/clap-rs/commit/d0b442c7beeecac9764406bc3bd171ced0b8825e), closes [#626](https://github.com/kbknapp/clap-rs/issues/626))
-
-
-
-<a name="v2.10.3"></a>
-### v2.10.3 (2016-08-25)
-
-#### Features
-
-* **Help:** adds new short hand way to use source formatting and ignore term width in help messages ([7dfdaf20](https://github.com/kbknapp/clap-rs/commit/7dfdaf200ebb5c431351a045b48f5e0f0d3f31db), closes [#625](https://github.com/kbknapp/clap-rs/issues/625))
-
-#### Documentation
-
-* **Term Width:** adds details about set_term_width(0) ([00b8205d](https://github.com/kbknapp/clap-rs/commit/00b8205d22639d1b54b9c453c55c785aace52cb2))
-
-#### Bug Fixes
-
-* **Unicode:** fixes two bugs where non-English characters were stripped or caused a panic with help wrapping ([763a5c92](https://github.com/kbknapp/clap-rs/commit/763a5c920e23efc74d190af0cb8b5dd714b2d67a), closes [#626](https://github.com/kbknapp/clap-rs/issues/626))
-
-
-
-<a name="v2.10.2"></a>
-### v2.10.2 (2016-08-22)
-
-
-#### Bug Fixes
-
-* fixes a bug where the help is printed twice ([a643fb28](https://github.com/kbknapp/clap-rs/commit/a643fb283acd9905dc727c4579c5c9fa2ceaa7e7), closes [#623](https://github.com/kbknapp/clap-rs/issues/623))
-
-
-
-<a name="v2.10.1"></a>
-### v2.10.1 (2016-08-21)
-
-
-#### Bug Fixes
-
-* **Help Subcommand:** fixes misleading usage string when using multi-level subcommmands ([e203515e](https://github.com/kbknapp/clap-rs/commit/e203515e3ac495b405dbba4f78fb6af148fd282e), closes [#618](https://github.com/kbknapp/clap-rs/issues/618))
-
-#### Features
-
-* **YAML:** allows using lists or single values with arg declarations ([9ade2cd4](https://github.com/kbknapp/clap-rs/commit/9ade2cd4b268d6d7fe828319ce6a523c641b9c38), closes [#614](https://github.com/kbknapp/clap-rs/issues/614), [#613](https://github.com/kbknapp/clap-rs/issues/613))
-
-
-
-<a name="v2.10.0"></a>
-## v2.10.0 (2016-07-29)
-
-
-#### Features
-
-* **Completions:** one can generate a basic fish completions script at compile time ([1979d2f2](https://github.com/kbknapp/clap-rs/commit/1979d2f2f3216e57d02a97e624a8a8f6cf867ed9))
-
-#### Bug Fixes
-
-* **parser:** preserve external subcommand name ([875df243](https://github.com/kbknapp/clap-rs/commit/875df24316c266920a073c13bbefbf546bc1f635))
-
-#### Breaking Changes
-
-* **parser:** preserve external subcommand name ([875df243](https://github.com/kbknapp/clap-rs/commit/875df24316c266920a073c13bbefbf546bc1f635))
-
-#### Documentation
-
-* **YAML:** fixes example 17's incorrect reference to arg_groups instead of groups ([b6c99e13](https://github.com/kbknapp/clap-rs/commit/b6c99e1377f918e78c16c8faced70a71607da931), closes [#601](https://github.com/kbknapp/clap-rs/issues/601))
-
-
-
-<a name="2.9.3"></a>
-### 2.9.3 (2016-07-24)
-
-
-#### Bug Fixes
-
-* fixes bug where only first arg in list of required_unless_one is recognized ([1fc3b55b](https://github.com/kbknapp/clap-rs/commit/1fc3b55bd6c8653b02e7c4253749c6b77737d2ac), closes [#575](https://github.com/kbknapp/clap-rs/issues/575))
-* **Settings:** fixes typo subcommandsrequired->subcommandrequired ([fc72cdf5](https://github.com/kbknapp/clap-rs/commit/fc72cdf591d30f5d9375d0b5cc2a2ff3e812f9f6), closes [#593](https://github.com/kbknapp/clap-rs/issues/593))
-
-#### Features
-
-* **Completions:** adds the ability to generate completions to io::Write object ([9f62cf73](https://github.com/kbknapp/clap-rs/commit/9f62cf7378ba5acb5ce8c5bac89b4aa60c30755f))
-* **Settings:** Add unset_setting and unset_settings fns to App (#598) ([0ceba231](https://github.com/kbknapp/clap-rs/commit/0ceba231c6767cd6d88fdb1feeeea41deadf77ff), closes [#590](https://github.com/kbknapp/clap-rs/issues/590))
-
-
-<a name="2.9.2"></a>
-### 2.9.2 (2016-07-03)
-
-
-#### Documentation
-
-* **Completions:** fixes the formatting of the Cargo.toml excerpt in the completions example ([722f2607](https://github.com/kbknapp/clap-rs/commit/722f2607beaef56b6a0e433db5fd09492d9f028c))
-
-#### Bug Fixes
-
-* **Completions:** fixes bug where --help and --version short weren't added to the completion list ([e9f2438e](https://github.com/kbknapp/clap-rs/commit/e9f2438e2ce99af0ae570a2eaf541fc7f55b771b), closes [#536](https://github.com/kbknapp/clap-rs/issues/536))
-
-
-
-<a name="2.9.1"></a>
-### 2.9.1 (2016-07-02)
-
-
-#### Improvements
-
-* **Completions:** allows multiple completions to be built by namespacing with bin name ([57484b2d](https://github.com/kbknapp/clap-rs/commit/57484b2daeaac01c1026e8c84efc8bf099e0eb31))
-
-
-<a name="v2.9.0"></a>
-## v2.9.0 (2016-07-01)
-
-
-#### Documentation
-
-* **Completions:**
- * fixes some errors in the completion docs ([9b359bf0](https://github.com/kbknapp/clap-rs/commit/9b359bf06255d3dad8f489308044b60a9d1e6a87))
- * adds documentation for completion scripts ([c6c519e4](https://github.com/kbknapp/clap-rs/commit/c6c519e40efd6c4533a9ef5efe8e74fd150391b7))
-
-#### Features
-
-* **Completions:**
- * one can now generate a bash completions script at compile time! ([e75b6c7b](https://github.com/kbknapp/clap-rs/commit/e75b6c7b75f729afb9eb1d2a2faf61dca7674634), closes [#376](https://github.com/kbknapp/clap-rs/issues/376))
- * completions now include aliases to subcommands, including all subcommand options ([0ab9f840](https://github.com/kbknapp/clap-rs/commit/0ab9f84052a8cf65b5551657f46c0c270841e634), closes [#556](https://github.com/kbknapp/clap-rs/issues/556))
- * completions now continue completing even after first completion ([18fc2e5b](https://github.com/kbknapp/clap-rs/commit/18fc2e5b5af63bf54a94b72cec5e1223d49f4806))
- * allows matching on possible values in options ([89cc2026](https://github.com/kbknapp/clap-rs/commit/89cc2026ba9ac69cf44c5254360bbf99236d4f89), closes [#557](https://github.com/kbknapp/clap-rs/issues/557))
-
-#### Bug Fixes
-
-* **AllowLeadingHyphen:** fixes an issue where isn't ignored like it should be with this setting ([96c24c9a](https://github.com/kbknapp/clap-rs/commit/96c24c9a8fa1f85e06138d3cdd133e51659e19d2), closes [#558](https://github.com/kbknapp/clap-rs/issues/558))
-
-<a name="v2.8.0"></a>
-## v2.8.0 (2016-06-30)
-
-
-#### Features
-
-* **Arg:** adds new setting `Arg::require_delimiter` which requires val delimiter to parse multiple values ([920b5595](https://github.com/kbknapp/clap-rs/commit/920b5595ed72abfb501ce054ab536067d8df2a66))
-
-#### Bug Fixes
-
-* Declare term::Winsize as repr(C) ([5d663d90](https://github.com/kbknapp/clap-rs/commit/5d663d905c9829ce6e7a164f1f0896cdd70236dd))
-
-#### Documentation
-
-* **Arg:** adds docs for ([49af4e38](https://github.com/kbknapp/clap-rs/commit/49af4e38a5dae2ab0a7fc3b4147e2c053d532484))
-
-
-
-<a name="v2.7.1"></a>
-### v2.7.1 (2016-06-29)
-
-
-#### Bug Fixes
-
-* **Options:**
- * options with multiple values and using delimiters no longer parse additional values after a trailing space ([cdc500bd](https://github.com/kbknapp/clap-rs/commit/cdc500bdde6abe238c36ade406ddafc2bafff583))
- * using options with multiple values and with an = no longer parse args after the trailing space as values ([290f61d0](https://github.com/kbknapp/clap-rs/commit/290f61d07177413cf082ada55526d83405f6d011))
-
-
-
-<a name="v2.7.0"></a>
-## v2.7.0 (2016-06-28)
-
-
-#### Documentation
-
-* fix typos ([43b3d40b](https://github.com/kbknapp/clap-rs/commit/43b3d40b8c38b1571da75af86b5088be96cccec2))
-* **ArgGroup:** vastly improves ArgGroup docs by adding better examples ([9e5f4f5d](https://github.com/kbknapp/clap-rs/commit/9e5f4f5d734d630bca5535c3a0aa4fd4f9db3e39), closes [#534](https://github.com/kbknapp/clap-rs/issues/534))
-
-#### Features
-
-* **ArgGroup:** one can now specify groups which require AT LEAST one of the args ([33689acc](https://github.com/kbknapp/clap-rs/commit/33689acc689b217a8c0ee439f1b1225590c38355), closes [#533](https://github.com/kbknapp/clap-rs/issues/533))
-
-#### Bug Fixes
-
-* **App:** using `App::print_help` now prints the same as would have been printed by `--help` or the like ([e84cc018](https://github.com/kbknapp/clap-rs/commit/e84cc01836bbe0527e97de6db9889bd9e0fd6ba1), closes [#536](https://github.com/kbknapp/clap-rs/issues/536))
-* **Help:**
- * prevents invoking <cmd> help help and displaying incorrect help message ([e3d2893f](https://github.com/kbknapp/clap-rs/commit/e3d2893f377942a2d4cf3c6ff04524d0346e6fdb), closes [#538](https://github.com/kbknapp/clap-rs/issues/538))
- * subcommand help messages requested via <cmd> help <sub> now correctly match <cmd> <sub> --help ([08ad1cff](https://github.com/kbknapp/clap-rs/commit/08ad1cff4fec57224ea957a2891a057b323c01bc), closes [#539](https://github.com/kbknapp/clap-rs/issues/539))
-
-#### Improvements
-
-* **ArgGroup:** Add multiple ArgGroups per Arg ([902e182f](https://github.com/kbknapp/clap-rs/commit/902e182f7a58aff11ff01e0a452abcdbdb2262aa), closes [#426](https://github.com/kbknapp/clap-rs/issues/426))
-* **Usage Strings:** `[FLAGS]` and `[ARGS]` are no longer blindly added to usage strings ([9b2e45b1](https://github.com/kbknapp/clap-rs/commit/9b2e45b170aff567b038d8b3368880b6046c10c6), closes [#537](https://github.com/kbknapp/clap-rs/issues/537))
-* **arg_enum!:** allows using meta items like repr(C) with arg_enum!s ([edf9b233](https://github.com/kbknapp/clap-rs/commit/edf9b2331c17a2cbcc13f961add4c55c2778e773), closes [#543](https://github.com/kbknapp/clap-rs/issues/543))
-
-
-
-<a name="v2.6.0"></a>
-## v2.6.0 (2016-06-14)
-
-
-#### Improvements
-
-* removes extra newline from help output ([86e61d19](https://github.com/kbknapp/clap-rs/commit/86e61d19a748fb9870fcf1175308984e51ca1115))
-* allows printing version to any io::Write object ([921f5f79](https://github.com/kbknapp/clap-rs/commit/921f5f7916597f1d028cd4a65bfe76a01c801724))
-* removes extra newline when printing version ([7e2e2cbb](https://github.com/kbknapp/clap-rs/commit/7e2e2cbb4a8a0f050bb8072a376f742fc54b8589))
-* **Aliases:** improves readability of asliases in help messages ([ca511de7](https://github.com/kbknapp/clap-rs/commit/ca511de71f5b8c2ac419f1b188658e8c63b67846), closes [#526](https://github.com/kbknapp/clap-rs/issues/526), [#529](https://github.com/kbknapp/clap-rs/issues/529))
-* **Usage Strings:** improves the default usage string when only a single positional arg is present ([ec86f2da](https://github.com/kbknapp/clap-rs/commit/ec86f2dada1545a63fc72355e22fcdc4c466c215), closes [#518](https://github.com/kbknapp/clap-rs/issues/518))
-
-#### Features
-
-* **Help:** allows wrapping at specified term width (Even on Windows!) ([1761dc0d](https://github.com/kbknapp/clap-rs/commit/1761dc0d27d0d621229d792be40c36fbf65c3014), closes [#451](https://github.com/kbknapp/clap-rs/issues/451))
-* **Settings:**
- * adds new setting to stop delimiting values with -- or TrailingVarArg ([fc3e0f5a](https://github.com/kbknapp/clap-rs/commit/fc3e0f5afda6d24cdb3c4676614beebe13e1e870), closes [#511](https://github.com/kbknapp/clap-rs/issues/511))
- * one can now set an AppSetting which is propogated down through child subcommands ([e2341835](https://github.com/kbknapp/clap-rs/commit/e23418351a3b98bf08dfd7744bc14377c70d59ee), closes [#519](https://github.com/kbknapp/clap-rs/issues/519))
-* **Subcommands:** adds support for visible aliases ([7b10e7f8](https://github.com/kbknapp/clap-rs/commit/7b10e7f8937a07fdb8d16a6d8df79ce78d080cd3), closes [#522](https://github.com/kbknapp/clap-rs/issues/522))
-
-#### Bug Fixes
-
-* fixes bug where args are printed out of order with templates ([05abb534](https://github.com/kbknapp/clap-rs/commit/05abb534864764102031a0d402e64ac65867aa87))
-* fixes bug where one can't override version or help flags ([90d7d6a2](https://github.com/kbknapp/clap-rs/commit/90d7d6a2ea8240122dd9bf8d82d3c4f5ebb5c703), closes [#514](https://github.com/kbknapp/clap-rs/issues/514))
-* fixes issue where before_help wasn't printed ([b3faff60](https://github.com/kbknapp/clap-rs/commit/b3faff6030f76a23f26afcfa6a90169002ed7106))
-* **Help:** `App::before_help` and `App::after_help` now correctly wrap ([1f4da767](https://github.com/kbknapp/clap-rs/commit/1f4da7676e6e71aa8dda799f3eeefad105a47819), closes [#516](https://github.com/kbknapp/clap-rs/issues/516))
-* **Settings:** fixes bug where new color settings couldn't be converted from strs ([706a7c11](https://github.com/kbknapp/clap-rs/commit/706a7c11b0900be594de6d5a3121938eff197602))
-* **Subcommands:** subcommands with aliases now display help of the aliased subcommand ([5354d14b](https://github.com/kbknapp/clap-rs/commit/5354d14b51f189885ba110e01e6b76cca3752992), closes [#521](https://github.com/kbknapp/clap-rs/issues/521))
-* **Windows:** fixes a failing windows build ([01e7dfd6](https://github.com/kbknapp/clap-rs/commit/01e7dfd6c07228c0be6695b3c7bf9370d82860d4))
-* **YAML:** adds missing YAML methods for App and Arg ([e468faf3](https://github.com/kbknapp/clap-rs/commit/e468faf3f05950fd9f72d84b69aa2061e91c6c64), closes [#528](https://github.com/kbknapp/clap-rs/issues/528))
-
-
-
-<a name="v2.5.2"></a>
-### v2.5.2 (2016-05-31)
-
-
-#### Improvements
-
-* removes extra newline from help output ([86e61d19](https://github.com/kbknapp/clap-rs/commit/86e61d19a748fb9870fcf1175308984e51ca1115))
-* allows printing version to any io::Write object ([921f5f79](https://github.com/kbknapp/clap-rs/commit/921f5f7916597f1d028cd4a65bfe76a01c801724))
-* removes extra newline when printing version ([7e2e2cbb](https://github.com/kbknapp/clap-rs/commit/7e2e2cbb4a8a0f050bb8072a376f742fc54b8589))
-
-#### Bug Fixes
-
-* fixes bug where args are printed out of order with templates ([3935431d](https://github.com/kbknapp/clap-rs/commit/3935431d5633f577c0826ae2142794b301f4b8ca))
-* fixes bug where one can't override version or help flags ([90d7d6a2](https://github.com/kbknapp/clap-rs/commit/90d7d6a2ea8240122dd9bf8d82d3c4f5ebb5c703), closes [#514](https://github.com/kbknapp/clap-rs/issues/514))
-* fixes issue where before_help wasn't printed ([b3faff60](https://github.com/kbknapp/clap-rs/commit/b3faff6030f76a23f26afcfa6a90169002ed7106))
-
-#### Documentation
-
-* inter-links all types and pages ([3312893d](https://github.com/kbknapp/clap-rs/commit/3312893ddaef3f44d68d8d26ed3d08010be50d97), closes [#505](https://github.com/kbknapp/clap-rs/issues/505))
-* makes all publicly available types viewable in docs ([52ca6505](https://github.com/kbknapp/clap-rs/commit/52ca6505b4fec7b5c2d53d160c072d395eb21da6))
-
-<a name="v2.5.1"></a>
-### v2.5.1 (2016-05-11)
-
-
-#### Bug Fixes
-
-* **Subcommand Aliases**: fixes lifetime issue when setting multiple aliases at once ([ac42f6cf0](https://github.com/kbknapp/clap-rs/commit/ac42f6cf0de6c4920f703807d63061803930b18d))
-
-<a name="v2.5.0"></a>
-## v2.5.0 (2016-05-10)
-
-
-#### Improvements
-
-* **SubCommand Aliases:** adds feature to yaml configs too ([69592195](https://github.com/kbknapp/clap-rs/commit/695921954dde46dfd483399dcdef482c9dd7f34a))
-
-#### Features
-
-* **SubCommands:** adds support for subcommand aliases ([66b4dea6](https://github.com/kbknapp/clap-rs/commit/66b4dea65c44d8f77ff522238a9237aed1bcab6d), closes [#469](https://github.com/kbknapp/clap-rs/issues/469))
-
-
-<a name="v2.4.3"></a>
-### v2.4.3 (2016-05-10)
-
-
-#### Bug Fixes
-
-* **Usage Strings:**
- * now properly dedups args that are also in groups ([3ca0947c](https://github.com/kbknapp/clap-rs/commit/3ca0947c166b4f8525752255e3a4fa6565eb9689), closes [#498](https://github.com/kbknapp/clap-rs/issues/498))
- * removes duplicate groups from usage strings ([f574fb8a](https://github.com/kbknapp/clap-rs/commit/f574fb8a7cde4d4a2fa4c4481d59be2d0f135427))
-
-#### Improvements
-
-* **Groups:** formats positional args in groups in a better way ([fef11154](https://github.com/kbknapp/clap-rs/commit/fef11154fb7430d1cbf04a672aabb366e456a368))
-* **Help:**
- * moves positionals to standard <> formatting ([03dfe5ce](https://github.com/kbknapp/clap-rs/commit/03dfe5ceff1d63f172788ff688567ddad9fe119b))
- * default help subcommand string has been shortened ([5b7fe8e4](https://github.com/kbknapp/clap-rs/commit/5b7fe8e4161e43ab19e2e5fcf55fbe46791134e9), closes [#494](https://github.com/kbknapp/clap-rs/issues/494))
-
-<a name="v2.4.2"></a>
-### v2.4.3 (2016-05-10)
-
-* Ghost Release
-
-<a name="v2.4.1"></a>
-### v2.4.3 (2016-05-10)
-
-* Ghost Release
-
-<a name="v2.4.0"></a>
-## v2.4.0 (2016-05-02)
-
-
-#### Features
-
-* **Help:** adds support for displaying info before help message ([29fbfa3b](https://github.com/kbknapp/clap-rs/commit/29fbfa3b963f2f3ca7704bf5d3e1201531baa373))
-* **Required:** adds allowing args that are required unless certain args are present ([af1f7916](https://github.com/kbknapp/clap-rs/commit/af1f79168390ea7da4074d0d9777de458ea64971))
-
-#### Documentation
-
-* hides formatting from docs ([cb708093](https://github.com/kbknapp/clap-rs/commit/cb708093a7cd057f08c98b7bd1ed54c2db86ae7e))
-* **required_unless:** adds docs and examples for required_unless ([ca727b52](https://github.com/kbknapp/clap-rs/commit/ca727b52423b9883acd88b2f227b2711bc144573))
-
-#### Bug Fixes
-
-* **Required Args:** fixes issue where missing required args are sometimes duplicatd in error messages ([3beebd81](https://github.com/kbknapp/clap-rs/commit/3beebd81e7bc2faa4115ac109cf570e512c5477f), closes [#492](https://github.com/kbknapp/clap-rs/issues/492))
-
-
-<a name="v2.3.0"></a>
-## v2.3.0 (2016-04-18)
-
-
-#### Improvements
-
-* **macros.rs:** Added write_nspaces macro (a new version of write_spaces) ([9d757e86](https://github.com/kbknapp/clap-rs/commit/9d757e8678e334e5a740ac750c76a9ed4e785cba))
-* **parser.rs:**
- * Provide a way to create a usage string without the USAGE: title ([a91d378b](https://github.com/kbknapp/clap-rs/commit/a91d378ba0c91b5796457f8c6e881b13226ab735))
- * Make Parser's create_usage public allowing to have function outside the parser to generate the help ([d51945f8](https://github.com/kbknapp/clap-rs/commit/d51945f8b82ebb0963f4f40b384a9e8335783091))
- * Expose Parser's flags, opts and positionals argument as iterators ([9b23e7ee](https://github.com/kbknapp/clap-rs/commit/9b23e7ee40e51f7a823644c4496be955dc6c9d3a))
-* **src/args:** Exposes argument display order by introducing a new Trait ([1321630e](https://github.com/kbknapp/clap-rs/commit/1321630ef56955f152c73376d4d85cceb0bb4a12))
-* **srs/args:** Added longest_filter to AnyArg trait ([65b3f667](https://github.com/kbknapp/clap-rs/commit/65b3f667532685f854c699ddd264d326599cf7e5))
-
-#### Features
-
-* **Authors Macro:** adds a crate_authors macro ([38fb59ab](https://github.com/kbknapp/clap-rs/commit/38fb59abf480eb2b6feca269097412f8b00b5b54), closes [#447](https://github.com/kbknapp/clap-rs/issues/447))
-* **HELP:**
- * implements optional colored help messages ([abc8f669](https://github.com/kbknapp/clap-rs/commit/abc8f669c3c8193ffc3a3b0ac6c3ac2198794d4f), closes [#483](https://github.com/kbknapp/clap-rs/issues/483))
- * Add a Templated Help system. ([81e121ed](https://github.com/kbknapp/clap-rs/commit/81e121edd616f7285593f11120c63bcccae0d23e))
-
-#### Bug Fixes
-
-* **HELP:** Adjust Help to semantic changes introduced in 6933b84 ([8d23806b](https://github.com/kbknapp/clap-rs/commit/8d23806bd67530ad412c34a1dcdcb1435555573d))
-
-<a name="v2.2.6"></a>
-### v2.2.6 (2016-04-11)
-
-#### Bug Fixes
-
-* **Arg Groups**: fixes bug where arg name isn't printed properly ([3019a685](https://github.com/kbknapp/clap-rs/commit/3019a685eee747ccbe6be09ad5dddce0b1d1d4db), closes [#476](https://github.com/kbknapp/clap-rs/issues/476))
-
-
-<a name="v2.2.5"></a>
-### v2.2.5 (2016-04-03)
-
-
-#### Bug Fixes
-
-* **Empty Values:** fixes bug where empty values weren't stored ([885d166f](https://github.com/kbknapp/clap-rs/commit/885d166f04eb3fb581898ae5818c6c8032e5a686), closes [#470](https://github.com/kbknapp/clap-rs/issues/470))
-* **Help Message:** fixes bug where arg name is printed twice ([71acf1d5](https://github.com/kbknapp/clap-rs/commit/71acf1d576946658b8bbdb5ae79e6716c43a030f), closes [#472](https://github.com/kbknapp/clap-rs/issues/472))
-
-
-<a name="v2.2.4"></a>
-### v2.2.4 (2016-03-30)
-
-
-#### Bug Fixes
-
-* fixes compiling with debug cargo feature ([d4b55450](https://github.com/kbknapp/clap-rs/commit/d4b554509928031ac0808076178075bb21f8c1da))
-* **Empty Values:** fixes bug where empty values weren't stored ([885d166f](https://github.com/kbknapp/clap-rs/commit/885d166f04eb3fb581898ae5818c6c8032e5a686), closes [#470](https://github.com/kbknapp/clap-rs/issues/470))
-
-
-
-<a name="v2.2.3"></a>
-### v2.2.3 (2016-03-28)
-
-
-#### Bug Fixes
-
-* **Help Subcommand:** fixes issue where help and version flags weren't properly displayed ([205b07bf](https://github.com/kbknapp/clap-rs/commit/205b07bf2e6547851f1290f8cd6b169145e144f1), closes [#466](https://github.com/kbknapp/clap-rs/issues/466))
-
-<a name="v2.2.2"></a>
-### v2.2.2 (2016-03-27)
-
-
-#### Bug Fixes
-
-* **Help Message:** fixes bug with wrapping in the middle of a unicode sequence ([05365ddc](https://github.com/kbknapp/clap-rs/commit/05365ddcc252e4b49e7a75e199d6001a430bd84d), closes [#456](https://github.com/kbknapp/clap-rs/issues/456))
-* **Usage Strings:** fixes small bug where -- would appear needlessly in usage strings ([6933b849](https://github.com/kbknapp/clap-rs/commit/6933b8491c2a7e28cdb61b47dcf10caf33c2f78a), closes [#461](https://github.com/kbknapp/clap-rs/issues/461))
-
-
-<a name="2.2.1"></a>
-### 2.2.1 (2016-03-16)
-
-
-#### Features
-
-* **Help Message:** wraps and aligns the help message of subcommands ([813d75d0](https://github.com/kbknapp/clap-rs/commit/813d75d06fbf077c65762608c0fa5e941cfc393c), closes [#452](https://github.com/kbknapp/clap-rs/issues/452))
-
-#### Bug Fixes
-
-* **Help Message:** fixes a bug where small terminal sizes causing a loop ([1d73b035](https://github.com/kbknapp/clap-rs/commit/1d73b0355236923aeaf6799abc759762ded7e1d0), closes [#453](https://github.com/kbknapp/clap-rs/issues/453))
-
-
-<a name="v2.2.0"></a>
-## v2.2.0 (2016-03-15)
-
-
-#### Features
-
-* **Help Message:** can auto wrap and aligning help text to term width ([e36af026](https://github.com/kbknapp/clap-rs/commit/e36af0266635f23e85e951b9088d561e9a5d1bf6), closes [#428](https://github.com/kbknapp/clap-rs/issues/428))
-* **Help Subcommand:** adds support passing additional subcommands to help subcommand ([2c12757b](https://github.com/kbknapp/clap-rs/commit/2c12757bbdf34ce481f3446c074e24c09c2e60fd), closes [#416](https://github.com/kbknapp/clap-rs/issues/416))
-* **Opts and Flags:** adds support for custom ordering in help messages ([9803b51e](https://github.com/kbknapp/clap-rs/commit/9803b51e799904c0befaac457418ee766ccc1ab9))
-* **Settings:** adds support for automatically deriving custom display order of args ([ad86e433](https://github.com/kbknapp/clap-rs/commit/ad86e43334c4f70e86909689a088fb87e26ff95a), closes [#444](https://github.com/kbknapp/clap-rs/issues/444))
-* **Subcommands:** adds support for custom ordering in help messages ([7d2a2ed4](https://github.com/kbknapp/clap-rs/commit/7d2a2ed413f5517d45988eef0765cdcd663b6372), closes [#442](https://github.com/kbknapp/clap-rs/issues/442))
-
-#### Bug Fixes
-
-* **From Usage:** fixes a bug where adding empty lines werent ignored ([c5c58c86](https://github.com/kbknapp/clap-rs/commit/c5c58c86b9c503d8de19da356a5a5cffb59fbe84))
-
-#### Documentation
-
-* **Groups:** explains required ArgGroups better ([4ff0205b](https://github.com/kbknapp/clap-rs/commit/4ff0205b85a45151b59bbaf090a89df13438380f), closes [#439](https://github.com/kbknapp/clap-rs/issues/439))
-
-<a name="v2.1.2"></a>
-### v2.1.2 (2016-02-24)
-
-#### Bug Fixes
-
-* **Nightly:** fixes failing nightly build ([d752c170](https://github.com/kbknapp/clap-rs/commit/d752c17029598b19037710f204b7943f0830ae75), closes [#434](https://github.com/kbknapp/clap-rs/issues/434))
-
-
-<a name="v2.1.1"></a>
-### v2.1.1 (2016-02-19)
-
-
-#### Documentation
-
-* **AppSettings:** clarifies that AppSettings do not propagate ([3c8db0e9](https://github.com/kbknapp/clap-rs/commit/3c8db0e9be1d24edaad364359513cbb02abb4186), closes [#429](https://github.com/kbknapp/clap-rs/issues/429))
-* **Arg Examples:** adds better examples ([1e79cccc](https://github.com/kbknapp/clap-rs/commit/1e79cccc12937bc0e7cd2aad8e404410798e9fff))
-
-#### Improvements
-
-* **Help:** adds setting for next line help by arg ([066df748](https://github.com/kbknapp/clap-rs/commit/066df7486e684cf50a8479a356a12ba972c34ce1), closes [#427](https://github.com/kbknapp/clap-rs/issues/427))
-
-
-<a name="v2.1.0"></a>
-## v2.1.0 (2016-02-10)
-
-
-#### Features
-
-* **Defult Values:** adds support for default values in args ([73211952](https://github.com/kbknapp/clap-rs/commit/73211952964a79d97b434dd567e6d7d34be7feb5), closes [#418](https://github.com/kbknapp/clap-rs/issues/418))
-
-#### Documentation
-
-* **Default Values:** adds better examples and notes for default values ([9facd74f](https://github.com/kbknapp/clap-rs/commit/9facd74f843ef3807c5d35259558a344e6c25905))
-
-
-<a name="v2.0.6"></a>
-### v2.0.6 (2016-02-09)
-
-
-#### Improvements
-
-* **Positional Arguments:** now displays value name if appropriate ([f0a99916](https://github.com/kbknapp/clap-rs/commit/f0a99916c59ce675515c6dcdfe9a40b130510908), closes [#420](https://github.com/kbknapp/clap-rs/issues/420))
-
-
-<a name="v2.0.5"></a>
-### v2.0.5 (2016-02-05)
-
-
-#### Bug Fixes
-
-* **Multiple Values:** fixes bug where number_of_values wasnt respected ([72c387da](https://github.com/kbknapp/clap-rs/commit/72c387da0bb8a6f526f863770f08bb8ca0d3de03))
-
-
-<a name="v2.0.4"></a>
-### v2.0.4 (2016-02-04)
-
-
-#### Bug Fixes
-
-* adds support for building ArgGroups from standalone YAML ([fcbc7e12](https://github.com/kbknapp/clap-rs/commit/fcbc7e12f5d7b023b8f30cba8cad28a01cf6cd26))
-* Stop lonely hyphens from causing panic ([85b11468](https://github.com/kbknapp/clap-rs/commit/85b11468b0189d5cc15f1cfac5db40d17a0077dc), closes [#410](https://github.com/kbknapp/clap-rs/issues/410))
-* **AppSettings:** fixes bug where subcmds didn't receive parent ver ([a62e4527](https://github.com/kbknapp/clap-rs/commit/a62e452754b3b0e3ac9a15aa8b5330636229ead1))
-
-<a name="v2.0.3"></a>
-### v2.0.3 (2016-02-02)
-
-
-#### Improvements
-
-* **values:** adds support for up to u64::max values per arg ([c7abf7d7](https://github.com/kbknapp/clap-rs/commit/c7abf7d7611e317b0d31d97632e3d2e13570947c))
-* **occurrences:** Allow for more than 256 occurrences of an argument. ([3731ddb3](https://github.com/kbknapp/clap-rs/commit/3731ddb361163f3d6b86844362871e48c80fa530))
-
-#### Features
-
-* **AppSettings:** adds HidePossibleValuesInHelp to skip writing those values ([cdee7a0e](https://github.com/kbknapp/clap-rs/commit/cdee7a0eb2beeec723cb98acfacf03bf629c1da3))
-
-#### Bug Fixes
-
-* **value_t_or_exit:** fixes typo which causes value_t_or_exit to return a Result ([ee96baff](https://github.com/kbknapp/clap-rs/commit/ee96baffd306cb8d20ddc5575cf739bb1a6354e8))
-
-
-<a name="v2.0.2"></a>
-### v2.0.2 (2016-01-31)
-
-
-#### Improvements
-
-* **arg_enum:** enum declared with arg_enum returns [&'static str; #] instead of Vec ([9c4b8a1a](https://github.com/kbknapp/clap-rs/commit/9c4b8a1a6b12949222f17d1074578ad7676b9c0d))
-
-#### Bug Fixes
-
-* clap_app! should be gated by unstable, not nightly feature ([0c8b84af](https://github.com/kbknapp/clap-rs/commit/0c8b84af6161d5baf683688eafc00874846f83fa))
-* **SubCommands:** fixed where subcmds weren't recognized after mult args ([c19c17a8](https://github.com/kbknapp/clap-rs/commit/c19c17a8850602990e24347aeb4427cf43316223), closes [#405](https://github.com/kbknapp/clap-rs/issues/405))
-* **Usage Parser:** fixes a bug where literal single quotes weren't allowed in help strings ([0bcc7120](https://github.com/kbknapp/clap-rs/commit/0bcc71206478074769e311479b34a9f74fe80f5c), closes [#406](https://github.com/kbknapp/clap-rs/issues/406))
-
-
-<a name="v2.0.1"></a>
-### v2.0.1 (2016-01-30)
-
-
-#### Bug Fixes
-
-* fixes cargo features to NOT require nightly with unstable features ([dcbcc60c](https://github.com/kbknapp/clap-rs/commit/dcbcc60c9ba17894be636472ea4b07a82d86a9db), closes [#402](https://github.com/kbknapp/clap-rs/issues/402))
-
-
-<a name="v2.0.0"></a>
-## v2.0.0 (2016-01-28)
-
-
-#### Improvements
-
-* **From Usage:** vastly improves the usage parser ([fa3a2f86](https://github.com/kbknapp/clap-rs/commit/fa3a2f86bd674c5eb07128c95098fab7d1437247), closes [#350](https://github.com/kbknapp/clap-rs/issues/350))
-
-#### Features
-
-* adds support for external subcommands ([177fe5cc](https://github.com/kbknapp/clap-rs/commit/177fe5cce745c2164a8e38c23be4c4460d2d7211), closes [#372](https://github.com/kbknapp/clap-rs/issues/372))
-* adds support values with a leading hyphen ([e4d429b9](https://github.com/kbknapp/clap-rs/commit/e4d429b9d52e95197bd0b572d59efacecf305a59), closes [#385](https://github.com/kbknapp/clap-rs/issues/385))
-* adds support for turning off the value delimiter ([508db850](https://github.com/kbknapp/clap-rs/commit/508db850a87c2e251cf6b6ddead9ad56b29f9e57), closes [#352](https://github.com/kbknapp/clap-rs/issues/352))
-* adds support changing the value delimiter ([dafeae8a](https://github.com/kbknapp/clap-rs/commit/dafeae8a526162640f6a68da434370c64d190889), closes [#353](https://github.com/kbknapp/clap-rs/issues/353))
-* adds support for comma separated values ([e69da6af](https://github.com/kbknapp/clap-rs/commit/e69da6afcd2fe48a3c458ca031db40997f860eda), closes [#348](https://github.com/kbknapp/clap-rs/issues/348))
-* adds support with options with optional values ([4555736c](https://github.com/kbknapp/clap-rs/commit/4555736cad01441dcde4ea84a285227e0844c16e), closes [#367](https://github.com/kbknapp/clap-rs/issues/367))
-* **UTF-8:** adds support for invalid utf8 in values ([c5c59dec](https://github.com/kbknapp/clap-rs/commit/c5c59dec0bc33b86b2e99d30741336f17ec84282), closes [#269](https://github.com/kbknapp/clap-rs/issues/269))
-* **v2:** implementing the base of 2.x ([a3536054](https://github.com/kbknapp/clap-rs/commit/a3536054512ba833533dc56615ce3663d884381c))
-
-#### Bug Fixes
-
-* fixes nightly build with new lints ([17599195](https://github.com/kbknapp/clap-rs/commit/175991956c37dc83ba9c49396e927a1cb65c5b11))
-* fixes Windows build for 2x release ([674c9b48](https://github.com/kbknapp/clap-rs/commit/674c9b48c7c92079cb180cc650a9e39f34781c32), closes [#392](https://github.com/kbknapp/clap-rs/issues/392))
-* fixes yaml build for 2x base ([adceae64](https://github.com/kbknapp/clap-rs/commit/adceae64c8556d00ab715677377b216f9f468ad7))
-
-#### Documentation
-
-* updates examples for 2x release ([1303b360](https://github.com/kbknapp/clap-rs/commit/1303b3607468f362ab1b452d5614c1a064dc69b4), closes [#394](https://github.com/kbknapp/clap-rs/issues/394))
-* updates examples for 2x release ([0a011f31](https://github.com/kbknapp/clap-rs/commit/0a011f3142aec338d388a6c8bfe22fa7036021bb), closes [#394](https://github.com/kbknapp/clap-rs/issues/394))
-* updates documentation for v2 release ([8d51724e](https://github.com/kbknapp/clap-rs/commit/8d51724ef73dfde5bb94fb9466bc5463a1cc1502))
-* updating docs for 2x release ([576d0e0e](https://github.com/kbknapp/clap-rs/commit/576d0e0e2c7b8f386589179bbf7419b93abacf1c))
-* **README.md:**
- * updates readme for v2 release ([acaba01a](https://github.com/kbknapp/clap-rs/commit/acaba01a353c12144b9cd9a3ce447400691849b0), closes [#393](https://github.com/kbknapp/clap-rs/issues/393))
- * fix typo and make documentation conspicuous ([07b9f614](https://github.com/kbknapp/clap-rs/commit/07b9f61495d927f69f7abe6c0d85253f0f4e6107))
-
-#### BREAKING CHANGES
-
-* **Fewer liftimes! Yay!**
- * `App<'a, 'b, 'c, 'd, 'e, 'f>` => `App<'a, 'b>`
- * `Arg<'a, 'b, 'c, 'd, 'e, 'f>` => `Arg<'a, 'b>`
- * `ArgMatches<'a, 'b>` => `ArgMatches<'a>`
-* **Simply Renamed**
- * `App::arg_group` => `App::group`
- * `App::arg_groups` => `App::groups`
- * `ArgGroup::add` => `ArgGroup::arg`
- * `ArgGroup::add_all` => `ArgGroup::args`
- * `ClapError` => `Error`
- * struct field `ClapError::error_type` => `Error::kind`
- * `ClapResult` => `Result`
- * `ClapErrorType` => `ErrorKind`
-* **Removed Deprecated Functions and Methods**
- * `App::subcommands_negate_reqs`
- * `App::subcommand_required`
- * `App::arg_required_else_help`
- * `App::global_version(bool)`
- * `App::versionless_subcommands`
- * `App::unified_help_messages`
- * `App::wait_on_error`
- * `App::subcommand_required_else_help`
- * `SubCommand::new`
- * `App::error_on_no_subcommand`
- * `Arg::new`
- * `Arg::mutually_excludes`
- * `Arg::mutually_excludes_all`
- * `Arg::mutually_overrides_with`
- * `simple_enum!`
-* **Renamed Error Variants**
- * `InvalidUnicode` => `InvalidUtf8`
- * `InvalidArgument` => `UnknownArgument`
-* **Usage Parser**
- * Value names can now be specified inline, i.e. `-o, --option <FILE> <FILE2> 'some option which takes two files'`
- * **There is now a priority of order to determine the name** - This is perhaps the biggest breaking change. See the documentation for full details. Prior to this change, the value name took precedence. **Ensure your args are using the proper names (i.e. typically the long or short and NOT the value name) throughout the code**
-* `ArgMatches::values_of` returns an `Values` now which implements `Iterator` (should not break any code)
-* `crate_version!` returns `&'static str` instead of `String`
-* Using the `clap_app!` macro requires compiling with the `unstable` feature because the syntax could change slightly in the future
-
-
-<a name="v1.5.5"></a>
-### v1.5.5 (2016-01-04)
-
-
-#### Bug Fixes
-
-* fixes an issue where invalid short args didn't cause an error ([c9bf7e44](https://github.com/kbknapp/clap-rs/commit/c9bf7e4440bd2f9b524ea955311d433c40a7d1e0))
-* prints the name in version and help instead of binary name ([8f3817f6](https://github.com/kbknapp/clap-rs/commit/8f3817f665c0cab6726bc16c56a53b6a61e44448), closes [#368](https://github.com/kbknapp/clap-rs/issues/368))
-* fixes an intentional panic issue discovered via clippy ([ea83a3d4](https://github.com/kbknapp/clap-rs/commit/ea83a3d421ea8856d4cac763942834d108b71406))
-
-
-<a name="v1.5.4"></a>
-### v1.5.4 (2015-12-18)
-
-
-#### Examples
-
-* **17_yaml:** conditinonally compile 17_yaml example ([575de089](https://github.com/kbknapp/clap-rs/commit/575de089a3e240c398cb10e6cf5a5c6b68662c01))
-
-#### Improvements
-
-* clippy improvements ([99cdebc2](https://github.com/kbknapp/clap-rs/commit/99cdebc23da3a45a165f14b27bebeb2ed828a2ce))
-
-#### Bug Fixes
-
-
-* **errors:** return correct error type in WrongNumValues error builder ([5ba8ba9d](https://github.com/kbknapp/clap-rs/commit/5ba8ba9dcccdfa74dd1c44260e64b359bbb36be6))
-* ArgRequiredElseHelp setting now takes precedence over missing required args ([faad83fb](https://github.com/kbknapp/clap-rs/commit/faad83fbef6752f3093b6e98fca09a9449b830f4), closes [#362](https://github.com/kbknapp/clap-rs/issues/362))
-
-
-<a name="v1.5.3"></a>
-### v1.5.3 (2015-11-20)
-
-
-#### Bug Fixes
-
-* **Errors:** fixes some instances when errors are missing a final newline ([c4d2b171](https://github.com/kbknapp/clap-rs/commit/c4d2b1711994479ad64ee52b6b49d2ceccbf2118))
-
-
-
-
-<a name="v1.5.2"></a>
-### v1.5.2 (2015-11-14)
-
-
-#### Bug Fixes
-
-* **Errors:** fixes a compiling bug when built on Windows or without the color feature ([a35f7634](https://github.com/kbknapp/clap-rs/commit/a35f76346fe6ecc88dda6a1eb13627186e7ce185))
-
-
-
-<a name="v1.5.1"></a>
-### v1.5.1 (2015-11-13)
-
-
-#### Bug Fixes
-
-* **Required Args:** fixes a bug where required args are not correctly accounted for ([f03b88a9](https://github.com/kbknapp/clap-rs/commit/f03b88a9766b331a63879bcd747687f2e5a2661b), closes [#343](https://github.com/kbknapp/clap-rs/issues/343))
-
-
-
-<a name="v1.5.0"></a>
-## v1.5.0 (2015-11-13)
-
-
-#### Bug Fixes
-
-* fixes a bug with required positional args in usage strings ([c6858f78](https://github.com/kbknapp/clap-rs/commit/c6858f78755f8e860204323c828c8355a066dc83))
-
-#### Documentation
-
-* **FAQ:** updates readme with slight changes to FAQ ([a4ef0fab](https://github.com/kbknapp/clap-rs/commit/a4ef0fab73c8dc68f1b138965d1340459c113398))
-
-#### Improvements
-
-* massive errors overhaul ([cdc29175](https://github.com/kbknapp/clap-rs/commit/cdc29175bc9c53e5b4aec86cbc04c1743154dae6))
-* **ArgMatcher:** huge refactor and deduplication of code ([8988853f](https://github.com/kbknapp/clap-rs/commit/8988853fb8825e8f841fde349834cc12cdbad081))
-* **Errors:** errors have been vastly improved ([e59bc0c1](https://github.com/kbknapp/clap-rs/commit/e59bc0c16046db156a88ba71a037db05028e995c))
-* **Traits:** refactoring some configuration into traits ([5800cdec](https://github.com/kbknapp/clap-rs/commit/5800cdec6dce3def4242b9f7bd136308afb19685))
-
-#### Performance
-
-* **App:**
- * more BTreeMap->Vec, Opts and SubCmds ([bc4495b3](https://github.com/kbknapp/clap-rs/commit/bc4495b32ec752b6c4b29719e831c043ef2a26ce))
- * changes flags BTreeMap->Vec ([d357640f](https://github.com/kbknapp/clap-rs/commit/d357640fab55e5964fe83efc3c771e53aa3222fd))
- * removed unneeded BTreeMap ([78971fd6](https://github.com/kbknapp/clap-rs/commit/78971fd68d7dc5c8e6811b4520cdc54e4188f733))
- * changes BTreeMap to VecMap in some instances ([64b921d0](https://github.com/kbknapp/clap-rs/commit/64b921d087fdd03775c95ba0bcf65d3f5d36f812))
- * removed excess clones ([ec0089d4](https://github.com/kbknapp/clap-rs/commit/ec0089d42ed715d293fb668d3a90b0db0aa3ec39))
-
-
-
-<a name="v1.4.7"></a>
-### v1.4.7 (2015-11-03)
-
-
-#### Documentation
-
-* Clarify behavior of Arg::multiple with options. ([434f497a](https://github.com/kbknapp/clap-rs/commit/434f497ab6d831f8145cf09278c97ca6ee6c6fe7))
-* Fix typos and improve grammar. ([c1f66b5d](https://github.com/kbknapp/clap-rs/commit/c1f66b5de7b5269fbf8760a005ef8c645edd3229))
-
-#### Bug Fixes
-
-* **Error Status:** fixes bug where --help and --version return non-zero exit code ([89b51fdf](https://github.com/kbknapp/clap-rs/commit/89b51fdf8b1ab67607567344e2317ff1a757cb12))
-
-
-
-<a name="v1.4.6"></a>
-### v1.4.6 (2015-10-29)
-
-
-#### Features
-
-* allows parsing without a binary name for daemons and interactive CLIs ([aff89d57](https://github.com/kbknapp/clap-rs/commit/aff89d579b5b85c3dc81b64f16d5865299ec39a2), closes [#318](https://github.com/kbknapp/clap-rs/issues/318))
-
-#### Bug Fixes
-
-* **Errors:** tones down quoting in some error messages ([34ce59ed](https://github.com/kbknapp/clap-rs/commit/34ce59ede53bfa2eef722c74881cdba7419fd9c7), closes [#309](https://github.com/kbknapp/clap-rs/issues/309))
-* **Help and Version:** only builds help and version once ([e3be87cf](https://github.com/kbknapp/clap-rs/commit/e3be87cfc095fc41c9811adcdc6d2b079f237d5e))
-* **Option Args:** fixes bug with args and multiple values ([c9a9548a](https://github.com/kbknapp/clap-rs/commit/c9a9548a8f96cef8a3dd9a980948325fbbc1b91b), closes [#323](https://github.com/kbknapp/clap-rs/issues/323))
-* **POSIX Overrides:** fixes bug where required args are overridden ([40ed2b50](https://github.com/kbknapp/clap-rs/commit/40ed2b50c3a9fe88bfdbaa43cef9fd6493ecaa8e))
-* **Safe Matches:** using 'safe' forms of the get_matches family no longer exit the process ([c47025dc](https://github.com/kbknapp/clap-rs/commit/c47025dca2b3305dea0a0acfdd741b09af0c0d05), closes [#256](https://github.com/kbknapp/clap-rs/issues/256))
-* **Versionless SubCommands:** fixes a bug where the -V flag was needlessly built ([27df8b9d](https://github.com/kbknapp/clap-rs/commit/27df8b9d98d13709dad3929a009f40ebff089a1a), closes [#329](https://github.com/kbknapp/clap-rs/issues/329))
-
-#### Documentation
-
-* adds comparison in readme ([1a8bf31e](https://github.com/kbknapp/clap-rs/commit/1a8bf31e7a6b87ce48a66af2cde1645b2dd5bc95), closes [#325](https://github.com/kbknapp/clap-rs/issues/325))
-
-
-
-<a name="v1.4.5"></a>
-### v1.4.5 (2015-10-06)
-
-
-#### Bug Fixes
-
-* fixes crash on invalid arg error ([c78ce128](https://github.com/kbknapp/clap-rs/commit/c78ce128ebbe7b8f730815f8176c29d76f4ade8c))
-
-
-
-<a name="v1.4.4"></a>
-### v1.4.4 (2015-10-06)
-
-
-#### Documentation
-
-* clean up some formatting ([b7df92d7](https://github.com/kbknapp/clap-rs/commit/b7df92d7ea25835701dd22ddff984b9749f48a00))
-* move the crate-level docs to top of the lib.rs file ([d7233bf1](https://github.com/kbknapp/clap-rs/commit/d7233bf122dbf80ba8fc79e5641be2df8af10e7a))
-* changes doc comments to rustdoc comments ([34b601be](https://github.com/kbknapp/clap-rs/commit/34b601be5fdde76c1a0859385b359b96d66b8732))
-* fixes panic in 14_groups example ([945b00a0](https://github.com/kbknapp/clap-rs/commit/945b00a0c27714b63bdca48d003fe205fcfdc578), closes [#295](https://github.com/kbknapp/clap-rs/issues/295))
-* avoid suggesting star dependencies. ([d33228f4](https://github.com/kbknapp/clap-rs/commit/d33228f40b5fefb84cf3dd51546bfb340dcd9f5a))
-* **Rustdoc:** adds portions of the readme to main rustdoc page ([6f9ee181](https://github.com/kbknapp/clap-rs/commit/6f9ee181e69d90bd4206290e59d6f3f1e8f0cbb2), closes [#293](https://github.com/kbknapp/clap-rs/issues/293))
-
-#### Bug Fixes
-
-* grammar error in some conflicting option errors ([e73b07e1](https://github.com/kbknapp/clap-rs/commit/e73b07e19474323ad2260da66abbf6a6d4ecbd4f))
-* **Unified Help:** sorts both flags and options as a unified category ([2a223dad](https://github.com/kbknapp/clap-rs/commit/2a223dad82901fa2e74baad3bfc4c7b94509300f))
-* **Usage:** fixes a bug where required args aren't filtered properly ([72b453dc](https://github.com/kbknapp/clap-rs/commit/72b453dc170af3050bb123d35364f6da77fc06d7), closes [#277](https://github.com/kbknapp/clap-rs/issues/277))
-* **Usage Strings:** fixes a bug ordering of elements in usage strings ([aaf0d6fe](https://github.com/kbknapp/clap-rs/commit/aaf0d6fe7aa2403e76096c16204d254a9ee61ee2), closes [#298](https://github.com/kbknapp/clap-rs/issues/298))
-
-#### Features
-
-* supports -aValue style options ([0e3733e4](https://github.com/kbknapp/clap-rs/commit/0e3733e4fec2015c2d566a51432dcd92cb69cad3))
-* **Trailing VarArg:** adds opt-in setting for final arg being vararg ([27018b18](https://github.com/kbknapp/clap-rs/commit/27018b1821a4bcd5235cfe92abe71b3c99efc24d), closes [#278](https://github.com/kbknapp/clap-rs/issues/278))
-
-
-
-<a name="v1.4.3"></a>
-### v1.4.3 (2015-09-30)
-
-
-#### Features
-
-* allows accessing arg values by group name ([c92a4b9e](https://github.com/kbknapp/clap-rs/commit/c92a4b9eff2d679957f61c0c41ff404b40d38a91))
-
-#### Documentation
-
-* use links to examples instead of plain text ([bb4fe237](https://github.com/kbknapp/clap-rs/commit/bb4fe237858535627271465147add537e4556b43))
-
-#### Bug Fixes
-
-* **Help Message:** required args no longer double list in usage ([1412e639](https://github.com/kbknapp/clap-rs/commit/1412e639e0a79df84936d1101a837f90077d1c83), closes [#277](https://github.com/kbknapp/clap-rs/issues/277))
-* **Possible Values:** possible value validation is restored ([f121ae74](https://github.com/kbknapp/clap-rs/commit/f121ae749f8f4bfe754ef2e8a6dfc286504b5b75), closes [#287](https://github.com/kbknapp/clap-rs/issues/287))
-
-
-
-<a name="v1.4.2"></a>
-### v1.4.2 (2015-09-23)
-
-
-#### Bug Fixes
-
-* **Conflicts:** fixes bug with conflicts not removing required args ([e17fcec5](https://github.com/kbknapp/clap-rs/commit/e17fcec53b3216ad047a13dddc6f740473fad1a1), closes [#271](https://github.com/kbknapp/clap-rs/issues/271))
-
-
-
-<a name="v1.4.1"></a>
-### v1.4.1 (2015-09-22)
-
-
-#### Examples
-
-* add clap_app quick example ([4ba6249c](https://github.com/kbknapp/clap-rs/commit/4ba6249c3cf4d2e083370d1fe4dcc7025282c28a))
-
-#### Features
-
-* **Unicode:** allows non-panicing on invalid unicode characters ([c5bf7ddc](https://github.com/kbknapp/clap-rs/commit/c5bf7ddc8cfb876ec928a5aaf5591232bbb32e5d))
-
-#### Documentation
-
-* properly names Examples section for rustdoc ([87ba5445](https://github.com/kbknapp/clap-rs/commit/87ba54451d7ec7b1c9b9ef134f90bbe39e6fac69))
-* fixes various typos and spelling ([f85640f9](https://github.com/kbknapp/clap-rs/commit/f85640f9f6d8fd3821a40e9b8b7a34fabb789d02))
-* **Arg:** unhides fields of the Arg struct ([931aea88](https://github.com/kbknapp/clap-rs/commit/931aea88427edf43a3da90d5a500c1ff2b2c3614))
-
-#### Bug Fixes
-
-* flush the buffer in App::print_version() ([cbc42a37](https://github.com/kbknapp/clap-rs/commit/cbc42a37d212d84d22b1777d08e584ff191934e7))
-* Macro benchmarks ([13712da1](https://github.com/kbknapp/clap-rs/commit/13712da1d36dc7614eec3a10ad488257ba615751))
-
-
-
-<a name="v1.4.0"></a>
-## v1.4.0 (2015-09-09)
-
-
-#### Features
-
-* allows printing help message by library consumers ([56b95f32](https://github.com/kbknapp/clap-rs/commit/56b95f320875c62dda82cb91b29059671e120ed1))
-* allows defining hidden args and subcmds ([2cab4d03](https://github.com/kbknapp/clap-rs/commit/2cab4d0334ea3c2439a1d4bfca5bf9905c7ea9ac), closes [#231](https://github.com/kbknapp/clap-rs/issues/231))
-* Builder macro to assist with App/Arg/Group/SubCommand building ([443841b0](https://github.com/kbknapp/clap-rs/commit/443841b012a8d795cd5c2bd69ae6e23ef9b16477))
-* **Errors:** allows consumers to write to stderr and exit on error ([1e6403b6](https://github.com/kbknapp/clap-rs/commit/1e6403b6a863574fa3cb6946b1fb58f034e8664c))
-
-
-
-<a name="v1.3.2"></a>
-### v1.3.2 (2015-09-08)
-
-
-#### Documentation
-
-* fixed ErrorKind docs ([dd057843](https://github.com/kbknapp/clap-rs/commit/dd05784327fa070eb6ce5ce89a8507e011d8db94))
-* **ErrorKind:** changed examples content ([b9ca2616](https://github.com/kbknapp/clap-rs/commit/b9ca261634b89613bbf3d98fd74d55cefbb31a8c))
-
-#### Bug Fixes
-
-* fixes a bug where the help subcommand wasn't overridable ([94003db4](https://github.com/kbknapp/clap-rs/commit/94003db4b5eebe552ca337521c1c001295822745))
-
-#### Features
-
-* adds abiltiy not consume self when parsing matches and/or exit on help ([94003db4](https://github.com/kbknapp/clap-rs/commit/94003db4b5eebe552ca337521c1c001295822745))
-* **App:** Added ability for users to handle errors themselves ([934e6fbb](https://github.com/kbknapp/clap-rs/commit/934e6fbb643b2385efc23444fe6fce31494dc288))
-
-
-
-<a name="v1.3.1"></a>
-### v1.3.1 (2015-09-04)
-
-
-#### Examples
-
-* **17_yaml:** fixed example ([9b848622](https://github.com/kbknapp/clap-rs/commit/9b848622296c8c5c7b9a39b93ddd41f51df790b5))
-
-#### Performance
-
-* changes ArgGroup HashSets to Vec ([3cb4a48e](https://github.com/kbknapp/clap-rs/commit/3cb4a48ebd15c20692f4f3a2a924284dc7fd5e10))
-* changes BTreeSet for Vec in some instances ([baab2e3f](https://github.com/kbknapp/clap-rs/commit/baab2e3f4060e811abee14b1654cbcd5cf3b5fea))
-
-
-
-<a name="v1.3.0"></a>
-## v1.3.0 (2015-09-01)
-
-
-#### Features
-
-* **YAML:** allows building a CLI from YAML files ([86cf4c45](https://github.com/kbknapp/clap-rs/commit/86cf4c45626a36b8115446952f9069f73c1debc3))
-* **ArgGroups:** adds support for building ArgGroups from yaml ([ecf88665](https://github.com/kbknapp/clap-rs/commit/ecf88665cbff367018b29161a1b75d44a212707d))
-* **Subcommands:** adds support for subcommands from yaml ([e415cf78](https://github.com/kbknapp/clap-rs/commit/e415cf78ba916052d118a8648deba2b9c16b1530))
-
-#### Documentation
-
-* **YAML:** adds examples for using YAML to build a CLI ([ab41d7f3](https://github.com/kbknapp/clap-rs/commit/ab41d7f38219544750e6e1426076dc498073191b))
-* **Args from YAML:** fixes doc examples ([19b348a1](https://github.com/kbknapp/clap-rs/commit/19b348a10050404cd93888dbbbe4f396681b67d0))
-* **Examples:** adds better usage examples instead of having unused variables ([8cbacd88](https://github.com/kbknapp/clap-rs/commit/8cbacd8883004fe71a8ea036ec4391c7dd8efe94))
-
-#### Examples
-
-* Add AppSettings example ([12705079](https://github.com/kbknapp/clap-rs/commit/12705079ca96a709b4dd94f7ddd20a833b26838c))
-
-#### Bug Fixes
-
-* **Unified Help Messages:** fixes a crash from this setting and no opts ([169ffec1](https://github.com/kbknapp/clap-rs/commit/169ffec1003d58d105d7ef2585b3425e57980000), closes [#210](https://github.com/kbknapp/clap-rs/issues/210))
-
-
-
-<a name="v1.2.5"></a>
-### v1.2.5 (2015-08-27)
-
-
-#### Examples
-
-* add custom validator example ([b9997d1f](https://github.com/kbknapp/clap-rs/commit/b9997d1fca74d4d8f93971f2a01bdf9798f913d5))
-* fix indentation ([d4f1b740](https://github.com/kbknapp/clap-rs/commit/d4f1b740ede410fd2528b9ecd89592c2fd8b1e20))
-
-#### Features
-
-* **Args:** allows opts and args to define a name for help and usage msgs ([ad962ec4](https://github.com/kbknapp/clap-rs/commit/ad962ec478da999c7dba0afdb84c266f4d09b1bd))
-
-
-
-<a name="v1.2.4"></a>
-### v1.2.4 (2015-08-26)
-
-
-#### Bug Fixes
-
-* **Possible Values:** fixes a bug where suggestions arent made when using --long=value format ([3d5e9a6c](https://github.com/kbknapp/clap-rs/commit/3d5e9a6cedb26668839b481c9978e2fbbab8be6f), closes [#192](https://github.com/kbknapp/clap-rs/issues/192))
-
-
-
-<a name="v1.2.3"></a>
-### v1.2.3 (2015-08-24)
-
-
-#### Bug Fixes
-
-* **App, Args:** fixed subcommand reqs negation ([b41afa8c](https://github.com/kbknapp/clap-rs/commit/b41afa8c3ded3d1be12f7a2f8ea06cc44afc9458), closes [#188](https://github.com/kbknapp/clap-rs/issues/188))
-
-
-
-<a name="v1.2.2"></a>
-### v1.2.2 (2015-08-23)
-
-
-#### Bug Fixes
-
-* fixed confusing error message, also added test for it ([fc7a31a7](https://github.com/kbknapp/clap-rs/commit/fc7a31a745efbf1768ee2c62cd3bb72bfe30c708))
-* **App:** fixed requirmets overriding ([9c135eb7](https://github.com/kbknapp/clap-rs/commit/9c135eb790fa16183e5bdb2009ddc3cf9e25f99f))
-
-
-
-<a name="v1.2.1"></a>
-### v1.2.1 (2015-08-20)
-
-
-#### Documentation
-
-* **README.md:** updates for new features ([16cf9245](https://github.com/kbknapp/clap-rs/commit/16cf9245fb5fc4cf6face898e358368bf9961cbb))
-
-#### Features
-
-* implements posix compatible conflicts for long args ([8c2d48ac](https://github.com/kbknapp/clap-rs/commit/8c2d48acf5473feebd721a9049a9c9b7051e70f9))
-* added overrides to support conflicts in POSIX compatible manner ([0b916a00](https://github.com/kbknapp/clap-rs/commit/0b916a00de26f6941538f6bc5f3365fa302083c1))
-* **Args:** allows defining POSIX compatible argument conflicts ([d715646e](https://github.com/kbknapp/clap-rs/commit/d715646e69759ccd95e01f49b04f489827ecf502))
-
-#### Bug Fixes
-
-* fixed links in cargo and license buttons ([6d9837ad](https://github.com/kbknapp/clap-rs/commit/6d9837ad9a9e006117cd7372fdc60f9a3889c7e2))
-
-#### Performance
-
-* **Args and Apps:** changes HashSet->Vec in some instances for increased performance ([d0c3b379](https://github.com/kbknapp/clap-rs/commit/d0c3b379700757e0a9b0c40af709f8af1f5b4949))
-
-
-
-<a name="v1.2.0"></a>
-### v1.2.0 (2015-08-15)
-
-
-#### Bug Fixes
-
-* fixed misspell and enum name ([7df170d7](https://github.com/kbknapp/clap-rs/commit/7df170d7f4ecff06608317655d1e0c4298f62076))
-* fixed use for clap crate ([dc3ada73](https://github.com/kbknapp/clap-rs/commit/dc3ada738667d4b689678f79d14251ee82004ece))
-
-#### Documentation
-
-* updates docs for new features ([03496547](https://github.com/kbknapp/clap-rs/commit/034965471782d872ca495045b58d34b31807c5b1))
-* fixed docs for previous changes ([ade36778](https://github.com/kbknapp/clap-rs/commit/ade367780c366425de462506d256e0f554ed3b9c))
-
-#### Improvements
-
-* **AppSettings:** adds ability to add multiple settings at once ([4a00e251](https://github.com/kbknapp/clap-rs/commit/4a00e2510d0ca8d095d5257d51691ba3b61c1374))
-
-#### Features
-
-* Replace application level settings with enum variants ([618dc4e2](https://github.com/kbknapp/clap-rs/commit/618dc4e2c205bf26bc43146164e65eb1f6b920ed))
-* **Args:** allows for custom argument value validations to be defined ([84ae2ddb](https://github.com/kbknapp/clap-rs/commit/84ae2ddbceda34b5cbda98a6959edaa52fde2e1a), closes [#170](https://github.com/kbknapp/clap-rs/issues/170))
-
-
-
-<a name="v1.1.6"></a>
-### v1.1.6 (2015-08-01)
-
-
-#### Bug Fixes
-
-* fixes two bugs in App when printing newlines in help and subcommands required error ([d63c0136](https://github.com/kbknapp/clap-rs/commit/d63c0136310db9dd2b1c7b4745938311601d8938))
-
-
-
-<a name="v1.1.5"></a>
-### v1.1.5 (2015-07-29)
-
-#### Performance
-
-* removes some unneeded allocations ([93e915df](https://github.com/kbknapp/clap-rs/commit/93e915dfe300f7b7d6209ca93323c6a46f89a8c1))
-
-<a name="v1.1.4"></a>
-### v1.1.4 (2015-07-20)
-
-
-#### Improvements
-
-* **Usage Strings** displays a [--] when it may be helpful ([86c3be85](https://github.com/kbknapp/clap-rs/commit/86c3be85fb6f77f83b5a6d2df40ae60937486984))
-
-#### Bug Fixes
-
-* **Macros** fixes a typo in a macro generated error message ([c9195c5f](https://github.com/kbknapp/clap-rs/commit/c9195c5f92abb8cd6a37b4f4fbb2f1fee2a8e368))
-* **Type Errors** fixes formatting of error output when failed type parsing ([fe5d95c6](https://github.com/kbknapp/clap-rs/commit/fe5d95c64f3296e6eddcbec0cb8b86659800145f))
-
-
-
-<a name="v1.1.3"></a>
-### v1.1.3 (2015-07-18)
-
-
-#### Documentation
-
-* updates README.md to include lack of color support on Windows ([52f81e17](https://github.com/kbknapp/clap-rs/commit/52f81e17377b18d2bd0f34693b642b7f358998ee))
-
-#### Bug Fixes
-
-* fixes formatting bug which prevented compiling on windows ([9cb5dceb](https://github.com/kbknapp/clap-rs/commit/9cb5dceb3e5fe5e0e7b24619ff77e5040672b723), closes [#163](https://github.com/kbknapp/clap-rs/issues/163))
-
-
-
-<a name="v1.1.2"></a>
-### v1.1.2 (2015-07-17)
-
-
-#### Bug Fixes
-
-* fixes a bug when parsing multiple {n} newlines inside help strings ([6d214b54](https://github.com/kbknapp/clap-rs/commit/6d214b549a9b7e189a94e5fa2b7c92cc333ca637))
-
-
-
-<a name="v1.1.1"></a>
-## v1.1.1 (2015-07-17)
-
-
-#### Bug Fixes
-
-* fixes a logic bug and allows setting Arg::number_of_values() < 2 ([42b6d1fc](https://github.com/kbknapp/clap-rs/commit/42b6d1fc3c519c92dfb3af15276e7d3b635e6cfe), closes [#161](https://github.com/kbknapp/clap-rs/issues/161))
-
-
-
-<a name="v1.1.0"></a>
-## v1.1.0 (2015-07-16)
-
-
-#### Features
-
-* allows creating unified help messages, a la docopt or getopts ([52bcd892](https://github.com/kbknapp/clap-rs/commit/52bcd892ea51564ce463bc5865acd64f8fe91cb1), closes [#158](https://github.com/kbknapp/clap-rs/issues/158))
-* allows stating all subcommands should *not* have --version flags ([336c476f](https://github.com/kbknapp/clap-rs/commit/336c476f631d512b54ac56fdca6f29ebdc2c00c5), closes [#156](https://github.com/kbknapp/clap-rs/issues/156))
-* allows setting version number to auto-propagate through subcommands ([bc66d3c6](https://github.com/kbknapp/clap-rs/commit/bc66d3c6deedeca62463fff95369ab1cfcdd366b), closes [#157](https://github.com/kbknapp/clap-rs/issues/157))
-
-#### Improvements
-
-* **Help Strings** properly aligns and handles newlines in long help strings ([f9800a29](https://github.com/kbknapp/clap-rs/commit/f9800a29696dd2cc0b0284bf693b3011831e556f), closes [#145](https://github.com/kbknapp/clap-rs/issues/145))
-
-
-#### Performance
-
-* **Help Messages** big performance improvements when printing help messages ([52bcd892](https://github.com/kbknapp/clap-rs/commit/52bcd892ea51564ce463bc5865acd64f8fe91cb1))
-
-#### Documentation
-
-* updates readme with new features ([8232f7bb](https://github.com/kbknapp/clap-rs/commit/8232f7bb52e88862bc13c3d4f99ee4f56cfe4bc0))
-* fix incorrect code example for `App::subcommand_required` ([8889689d](https://github.com/kbknapp/clap-rs/commit/8889689dc6336ccc45b2c9f2cf8e2e483a639e93))
-
-
-<a name="v1.0.3"></a>
-### v1.0.3 (2015-07-11)
-
-
-#### Improvements
-
-* **Errors** writes errors to stderr ([cc76ab8c](https://github.com/kbknapp/clap-rs/commit/cc76ab8c2b77c67b42f4717ded530df7806142cf), closes [#154](https://github.com/kbknapp/clap-rs/issues/154))
-
-#### Documentation
-
-* **README.md** updates example help message to new format ([0aca29bd](https://github.com/kbknapp/clap-rs/commit/0aca29bd5d6d1a4e9971bdc88d946ffa58606efa))
-
-
-
-<a name="v1.0.2"></a>
-### v1.0.2 (2015-07-09)
-
-
-#### Improvements
-
-* **Usage** re-orders optional arguments and required to natural standard ([dc7e1fce](https://github.com/kbknapp/clap-rs/commit/dc7e1fcea5c85d317018fb201d2a9262249131b4), closes [#147](https://github.com/kbknapp/clap-rs/issues/147))
-
-
-
-<a name="v1.0.1"></a>
-### v1.0.1 (2015-07-08)
-
-
-#### Bug Fixes
-
-* allows empty values when using --long='' syntax ([083f82d3](https://github.com/kbknapp/clap-rs/commit/083f82d333b69720a6ef30074875310921d964d1), closes [#151](https://github.com/kbknapp/clap-rs/issues/151))
-
-
-
-<a name="v1.0.0"></a>
-## v1.0.0 (2015-07-08)
-
-
-#### Documentation
-
-* **README.md** adds new features to what's new list ([938f7f01](https://github.com/kbknapp/clap-rs/commit/938f7f01340f521969376cf4e2e3d9436bca21f7))
-* **README.md** use with_name for subcommands ([28b7e316](https://github.com/kbknapp/clap-rs/commit/28b7e3161fb772e5309042648fe8c3a420645bac))
-
-#### Features
-
-* args can now be parsed from arbitrary locations, not just std::env::args() ([75312528](https://github.com/kbknapp/clap-rs/commit/753125282b1b9bfff875f1557ce27610edcc59e1))
-
-
-
-<a name="v1.0.0"></a>
-## v1.0.0-beta (2015-06-30)
-
-
-#### Features
-
-* allows waiting for user input on error ([d0da3bdd](https://github.com/kbknapp/clap-rs/commit/d0da3bdd9d1871541907ea9c645322a74d260e07), closes [#140](https://github.com/kbknapp/clap-rs/issues/140))
-* **Help** allows one to fully override the auto-generated help message ([26d5ae3e](https://github.com/kbknapp/clap-rs/commit/26d5ae3e330d1e150811d5b60b2b01a8f8df854e), closes [#141](https://github.com/kbknapp/clap-rs/issues/141))
-
-#### Documentation
-
-* adds "whats new" section to readme ([ff149a29](https://github.com/kbknapp/clap-rs/commit/ff149a29dd9e179865e6d577cd7dc87c54f8f95c))
-
-#### Improvements
-
-* removes deprecated functions in prep for 1.0 ([274484df](https://github.com/kbknapp/clap-rs/commit/274484dfd08fff4859cefd7e9bef3b73d3a9cb5f))
-
-
-
-<a name="v0.11.0"></a>
-## v0.11.0 (2015-06-17) - BREAKING CHANGE
-
-
-#### Documentation
-
-* updates docs to new version flag defaults ([ebf442eb](https://github.com/kbknapp/clap-rs/commit/ebf442ebebbcd2ec6bfe2c06566c9d362bccb112))
-
-#### Features
-
-* **Help and Version** default short for version is now `-V` but can be overridden (only breaks manual documentation) (**BREAKING CHANGE** [eb1d9320](https://github.com/kbknapp/clap-rs/commit/eb1d9320c509c1e4e57d7c7959da82bcfe06ada0))
-
-
-
-<a name="v0.10.5"></a>
-### v0.10.5 (2015-06-06)
-
-
-#### Bug Fixes
-
-* **Global Args** global arguments propogate fully now ([1f377960](https://github.com/kbknapp/clap-rs/commit/1f377960a48c82f54ca5f39eb56bcb393140b046), closes [#137](https://github.com/kbknapp/clap-rs/issues/137))
-
-
-
-<a name="v0.10.4"></a>
-### v0.10.4 (2015-06-06)
-
-
-#### Bug Fixes
-
-* **Global Args** global arguments propogate fully now ([8f2c0160](https://github.com/kbknapp/clap-rs/commit/8f2c0160c8d844daef375a33dbaec7d89de00a00), closes [#137](https://github.com/kbknapp/clap-rs/issues/137))
-
-
-
-<a name="v0.10.3"></a>
-### v0.10.3 (2015-05-31)
-
-
-#### Bug Fixes
-
-* **Global Args** fixes a bug where globals only transfer to one subcommand ([a37842ee](https://github.com/kbknapp/clap-rs/commit/a37842eec1ee3162b86fdbda23420b221cdb1e3b), closes [#135](https://github.com/kbknapp/clap-rs/issues/135))
-
-
-
-<a name="v0.10.2"></a>
-### v0.10.2 (2015-05-30)
-
-
-#### Improvements
-
-* **Binary Names** allows users to override the system determined bin name ([2191fe94](https://github.com/kbknapp/clap-rs/commit/2191fe94bda35771383b52872fb7f5421b178be1), closes [#134](https://github.com/kbknapp/clap-rs/issues/134))
-
-#### Documentation
-
-* adds contributing guidelines ([6f76bd0a](https://github.com/kbknapp/clap-rs/commit/6f76bd0a07e8b7419b391243ab2d6687cd8a9c5f))
-
-
-
-<a name="v0.10.1"></a>
-### v0.10.1 (2015-05-26)
-
-
-#### Features
-
-* can now specify that an app or subcommand should display help on no args or subcommands ([29ca7b2f](https://github.com/kbknapp/clap-rs/commit/29ca7b2f74376ca0cdb9d8ee3bfa99f7640cc404), closes [#133](https://github.com/kbknapp/clap-rs/issues/133))
-
-
-
-<a name="v0.10.0"></a>
-## v0.10.0 (2015-05-23)
-
-
-#### Features
-
-* **Global Args** allows args that propagate down to child commands ([2bcc6137](https://github.com/kbknapp/clap-rs/commit/2bcc6137a83cb07757771a0afea953e68e692f0b), closes [#131](https://github.com/kbknapp/clap-rs/issues/131))
-
-#### Improvements
-
-* **Colors** implements more structured colored output ([d6c3ed54](https://github.com/kbknapp/clap-rs/commit/d6c3ed54d21cf7b40d9f130d4280ff5448522fc5), closes [#129](https://github.com/kbknapp/clap-rs/issues/129))
-
-#### Deprecations
-
-* **SubCommand/App** several methods and functions for stable release ([28b73855](https://github.com/kbknapp/clap-rs/commit/28b73855523ad170544afdb20665db98702fbe70))
-
-#### Documentation
-
-* updates for deprecations and new features ([743eefe8](https://github.com/kbknapp/clap-rs/commit/743eefe8dd40c1260065ce086d572e9e9358bc4c))
-
-
-
-<a name="v0.9.2"></a>
-## v0.9.2 (2015-05-20)
-
-
-#### Bug Fixes
-
-* **help** allows parent requirements to be ignored with help and version ([52218cc1](https://github.com/kbknapp/clap-rs/commit/52218cc1fdb06a42456c964d98cc2c7ac3432412), closes [#124](https://github.com/kbknapp/clap-rs/issues/124))
-
-
-
-<a name="v0.9.1"></a>
-## v0.9.1 (2015-05-18)
-
-
-#### Bug Fixes
-
-* **help** fixes a bug where requirements are included as program name in help and version ([08ba3f25](https://github.com/kbknapp/clap-rs/commit/08ba3f25cf38b149229ba8b9cb37a5804fe6b789))
-
-
-
-<a name="v0.9.0"></a>
-## v0.9.0 (2015-05-17)
-
-
-#### Improvements
-
-* **usage** usage strings now include parent command requirements ([dd8f21c7](https://github.com/kbknapp/clap-rs/commit/dd8f21c7c15cde348fdcf44fa7c205f0e98d2e4a), closes [#125](https://github.com/kbknapp/clap-rs/issues/125))
-* **args** allows consumer of clap to decide if empty values are allowed or not ([ab4ec609](https://github.com/kbknapp/clap-rs/commit/ab4ec609ccf692b9b72cccef5c9f74f5577e360d), closes [#122](https://github.com/kbknapp/clap-rs/issues/122))
-
-#### Features
-
-* **subcommands**
- * allows optionally specifying that no subcommand is an error ([7554f238](https://github.com/kbknapp/clap-rs/commit/7554f238fd3afdd60b7e4dcf00ff4a9eccf842c1), closes [#126](https://github.com/kbknapp/clap-rs/issues/126))
- * subcommands can optionally negate parent requirements ([4a4229f5](https://github.com/kbknapp/clap-rs/commit/4a4229f500e21c350e1ef78dd09ef27559653288), closes [#123](https://github.com/kbknapp/clap-rs/issues/123))
-
-
-
-<a name="v0.8.6"></a>
-## v0.8.6 (2015-05-17)
-
-
-#### Bug Fixes
-
-* **args** `-` can now be parsed as a value for an argument ([bc12e78e](https://github.com/kbknapp/clap-rs/commit/bc12e78eadd7eaf9d008a8469fdd2dfd7990cb5d), closes [#121](https://github.com/kbknapp/clap-rs/issues/121))
-
-
-
-<a name="v0.8.5"></a>
-## v0.8.5 (2015-05-15)
-
-
-#### Bug Fixes
-
-* **macros** makes macro errors consistent with others ([0c264a8c](https://github.com/kbknapp/clap-rs/commit/0c264a8ca57ec1cfdcb74dae79145d766cdc9b97), closes [#118](https://github.com/kbknapp/clap-rs/issues/118))
-
-#### Features
-
-* **macros**
- * arg_enum! and simple_enum! provide a Vec<&str> of variant names ([30fa87ba](https://github.com/kbknapp/clap-rs/commit/30fa87ba4e0f3189351d8f4f78b72e616a30d0bd), closes [#119](https://github.com/kbknapp/clap-rs/issues/119))
- * arg_enum! and simple_enum! auto-implement Display ([d1219f0d](https://github.com/kbknapp/clap-rs/commit/d1219f0d1371d872061bd0718057eca4ef47b739), closes [#120](https://github.com/kbknapp/clap-rs/issues/120))
-
-
-
-<a name="v0.8.4"></a>
-## v0.8.4 (2015-05-12)
-
-
-#### Bug Fixes
-
-* **suggestions** --help and --version now get suggestions ([d2b3b1fa](https://github.com/kbknapp/clap-rs/commit/d2b3b1faa0bdc1c5d2350cc4635aba81e02e9d96), closes [#116](https://github.com/kbknapp/clap-rs/issues/116))
-
-
-
-<a name="v0.8.3"></a>
-## v0.8.3 (2015-05-10)
-
-
-#### Bug Fixes
-
-* **usage** groups unfold their members in usage strings ([55d15582](https://github.com/kbknapp/clap-rs/commit/55d155827ea4a6b077a83669701e797ce1ad68f4), closes [#114](https://github.com/kbknapp/clap-rs/issues/114))
-
-#### Performance
-
-* **usage** removes unneeded allocations ([fd53cd18](https://github.com/kbknapp/clap-rs/commit/fd53cd188555f5c3dc8bc341c5d7eb04b761a70f))
-
-
-
-<a name="v0.8.2"></a>
-## v0.8.2 (2015-05-08)
-
-
-#### Bug Fixes
-
-* **usage strings** positional arguments are presented in index order ([eb0e374e](https://github.com/kbknapp/clap-rs/commit/eb0e374ecf952f1eefbc73113f21e0705936e40b), closes [#112](https://github.com/kbknapp/clap-rs/issues/112))
-
-
-
-<a name="v0.8.1"></a>
-## v0.8.1 (2015-05-06)
-
-
-#### Bug Fixes
-
-* **subcommands** stops parsing multiple values when subcommands are found ([fc79017e](https://github.com/kbknapp/clap-rs/commit/fc79017eced04fd41cc1801331e5054df41fac17), closes [#109](https://github.com/kbknapp/clap-rs/issues/109))
-
-#### Improvements
-
-* **color** reduces color in error messages ([aab44cca](https://github.com/kbknapp/clap-rs/commit/aab44cca6352f47e280c296e50c535f5d752dd46), closes [#110](https://github.com/kbknapp/clap-rs/issues/110))
-* **suggestions** adds suggested arguments to usage strings ([99447414](https://github.com/kbknapp/clap-rs/commit/994474146e9fb8b701af773a52da71553d74d4b7))
-
-
-
-<a name="v0.8.0"></a>
-## v0.8.0 (2015-05-06)
-
-
-#### Bug Fixes
-
-* **did-you-mean** for review ([0535cfb0](https://github.com/kbknapp/clap-rs/commit/0535cfb0c711331568b4de8080eeef80bd254b68))
-* **Positional** positionals were ignored if they matched a subcmd, even after '--' ([90e7b081](https://github.com/kbknapp/clap-rs/commit/90e7b0818741668b47cbe3becd029bab588e3553))
-* **help** fixes bug where space between arg and help is too long ([632fb115](https://github.com/kbknapp/clap-rs/commit/632fb11514c504999ea86bdce47cdd34f8ebf646))
-
-#### Features
-
-* **from_usage** adds ability to add value names or num of vals in usage string ([3d581976](https://github.com/kbknapp/clap-rs/commit/3d58197674ed7886ca315efb76e411608a327501), closes [#98](https://github.com/kbknapp/clap-rs/issues/98))
-* **did-you-mean**
- * gate it behind 'suggestions' ([c0e38351](https://github.com/kbknapp/clap-rs/commit/c0e383515d01bdd5ca459af9c2f7e2cf49e2488b))
- * for possible values ([1cc2deb2](https://github.com/kbknapp/clap-rs/commit/1cc2deb29158e0e4e8b434e4ce26b3d819301a7d))
- * for long flags (i.e. --long) ([52a0b850](https://github.com/kbknapp/clap-rs/commit/52a0b8505c99354bdf5fd1cd256cf41197ac2d81))
- * for subcommands ([06e869b5](https://github.com/kbknapp/clap-rs/commit/06e869b5180258047ed3c60ba099de818dd25fff))
-* **Flags** adds sugestions functionality ([8745071c](https://github.com/kbknapp/clap-rs/commit/8745071c3257dd327c497013516f12a823df9530))
-* **errors** colorizes output red on error ([f8b26b13](https://github.com/kbknapp/clap-rs/commit/f8b26b13da82ba3ba9a932d3d1ab4ea45d1ab036))
-
-#### Improvements
-
-* **arg_enum** allows ascii case insensitivity for enum variants ([b249f965](https://github.com/kbknapp/clap-rs/commit/b249f9657c6921c004764bd80d13ebca81585eec), closes [#104](https://github.com/kbknapp/clap-rs/issues/104))
-* **clap-test** simplified `make test` invocation ([d17dcb29](https://github.com/kbknapp/clap-rs/commit/d17dcb2920637a1f58c61c596b7bd362fd53047c))
-
-#### Documentation
-
-* **README** adds details about optional and new features ([960389de](https://github.com/kbknapp/clap-rs/commit/960389de02c9872aaee9adabe86987f71f986e39))
-* **clap** fix typos caught by codespell ([8891d929](https://github.com/kbknapp/clap-rs/commit/8891d92917aa1a069cca67272be41b99e548356e))
-* **from_usage** explains new usage strings with multiple values ([05476fc6](https://github.com/kbknapp/clap-rs/commit/05476fc61cd1e5f4a4e750d258c878732a3a9c64))
-
-
-
-<a name="v0.7.6"></a>
-## v0.7.6 (2015-05-05)
-
-
-#### Improvements
-
-* **Options** adds number of values to options in help/usage ([c1c993c4](https://github.com/kbknapp/clap-rs/commit/c1c993c419d18e35c443785053d8de9a2ef88073))
-
-#### Features
-
-* **from_usage** adds ability to add value names or num of vals in usage string ([ad55748c](https://github.com/kbknapp/clap-rs/commit/ad55748c265cf27935c7b210307d2040b6a09125), closes [#98](https://github.com/kbknapp/clap-rs/issues/98))
-
-#### Bug Fixes
-
-* **MultipleValues** properly distinguishes between multiple values and multiple occurrences ([dd2a7564](https://github.com/kbknapp/clap-rs/commit/dd2a75640ca68a91b973faad15f04df891356cef), closes [#99](https://github.com/kbknapp/clap-rs/issues/99))
-* **help** fixes tab alignment with multiple values ([847001ff](https://github.com/kbknapp/clap-rs/commit/847001ff6d8f4d9518e810fefb8edf746dd0f31e))
-
-#### Documentation
-
-* **from_usage** explains new usage strings with multiple values ([5a3a42df](https://github.com/kbknapp/clap-rs/commit/5a3a42dfa3a783537f88dedc0fd5f0edcb8ea372))
-
-
-
-<a name="v0.7.5"></a>
-## v0.7.5 (2015-05-04)
-
-
-#### Bug Fixes
-
-* **Options** fixes bug where options with no value don't error out ([a1fb94be](https://github.com/kbknapp/clap-rs/commit/a1fb94be53141572ffd97aad037295d4ffec82d0))
-
-
-
-<a name="v0.7.4"></a>
-## v0.7.4 (2015-05-03)
-
-
-#### Bug Fixes
-
-* **Options** fixes a bug where option arguments in succession get their values skipped ([f66334d0](https://github.com/kbknapp/clap-rs/commit/f66334d0ce984e2b56e5c19abb1dd536fae9342a))
-
-
-
-<a name="v0.7.3"></a>
-## v0.7.3 (2015-05-03)
-
-
-#### Bug Fixes
-
-* **RequiredValues** fixes a bug where missing values are parsed as missing arguments ([93c4a723](https://github.com/kbknapp/clap-rs/commit/93c4a7231ba1a08152648598f7aa4503ea82e4de))
-
-#### Improvements
-
-* **ErrorMessages** improves error messages and corrections ([a29c3983](https://github.com/kbknapp/clap-rs/commit/a29c3983c4229906655a29146ec15a0e46dd942d))
-* **ArgGroups** improves requirement and confliction support for groups ([c236dc5f](https://github.com/kbknapp/clap-rs/commit/c236dc5ff475110d2a1b80e62903f80296163ad3))
-
-
-
-<a name="v0.7.2"></a>
-## v0.7.2 (2015-05-03)
-
-
-#### Bug Fixes
-
-* **RequiredArgs** fixes bug where required-by-default arguments are not listed in usage ([12aea961](https://github.com/kbknapp/clap-rs/commit/12aea9612d290845ba86515c240aeeb0a21198db), closes [#96](https://github.com/kbknapp/clap-rs/issues/96))
-
-
-
-<a name="v0.7.1"></a>
-## v0.7.1 (2015-05-01)
-
-
-#### Bug Fixes
-
-* **MultipleValues** stops evaluating values if the max or exact number of values was reached ([86d92c9f](https://github.com/kbknapp/clap-rs/commit/86d92c9fdbf9f422442e9562977bbaf268dbbae1))
-
-
-
-<a name="v0.7.0"></a>
-## v0.7.0 (2015-04-30) - BREAKING CHANGE
-
-
-#### Bug Fixes
-
-* **from_usage** removes bug where usage strings have no help text ([ad4e5451](https://github.com/kbknapp/clap-rs/commit/ad4e54510739aeabf75f0da3278fb0952db531b3), closes [#83](https://github.com/kbknapp/clap-rs/issues/83))
-
-#### Features
-
-* **MultipleValues**
- * add support for minimum and maximum number of values ([53f6b8c9](https://github.com/kbknapp/clap-rs/commit/53f6b8c9d8dc408b4fa9f833fc3a63683873c42f))
- * adds support limited number and named values ([ae09f05e](https://github.com/kbknapp/clap-rs/commit/ae09f05e92251c1b39a83d372736fcc7b504e432))
- * implement shorthand for options with multiple values ([6669f0a9](https://github.com/kbknapp/clap-rs/commit/6669f0a9687d4f668523145d7bd5c007d1eb59a8))
-* **arg** allow other types besides Vec for multiple value settings (**BREAKING CHANGE** [0cc2f698](https://github.com/kbknapp/clap-rs/commit/0cc2f69839b9b1db5d06330771b494783049a88e), closes [#87](https://github.com/kbknapp/clap-rs/issues/87))
-* **usage** implement smart usage strings on errors ([d77048ef](https://github.com/kbknapp/clap-rs/commit/d77048efb1e595ffe831f1a2bea2f2700db53b9f), closes [#88](https://github.com/kbknapp/clap-rs/issues/88))
-
-
-
-<a name="v0.6.9"></a>
-## v0.6.9 (2015-04-29)
-
-
-#### Bug Fixes
-
-* **from_usage** removes bug where usage strings have no help text ([ad4e5451](https://github.com/kbknapp/clap-rs/commit/ad4e54510739aeabf75f0da3278fb0952db531b3), closes [#83](https://github.com/kbknapp/clap-rs/issues/83))
-
-
-
-<a name="0.6.8"></a>
-## 0.6.8 (2015-04-27)
-
-
-#### Bug Fixes
-
-* **help** change long help --long=long -> --long <long> ([1e25abfc](https://github.com/kbknapp/clap-rs/commit/1e25abfc36679ab89eae71bf98ced4de81992d00))
-* **RequiredArgs** required by default args should no longer be required when their exclusions are present ([4bb4c3cc](https://github.com/kbknapp/clap-rs/commit/4bb4c3cc076b49e86720e882bf8c489877199f2d))
-
-#### Features
-
-* **ArgGroups** add ability to create arg groups ([09eb4d98](https://github.com/kbknapp/clap-rs/commit/09eb4d9893af40c347e50e2b717e1adef552357d))
-
-
-
-<a name="v0.6.7"></a>
-## v0.6.7 (2015-04-22)
-
-
-#### Bug Fixes
-
-* **from_usage** fix bug causing args to not be required ([b76129e9](https://github.com/kbknapp/clap-rs/commit/b76129e9b71a63365d5c77a7f57b58dbd1e94d49))
-
-#### Features
-
-* **apps** add ability to display additional help info after auto-gen'ed help msg ([65cc259e](https://github.com/kbknapp/clap-rs/commit/65cc259e4559cbe3653c865ec0c4b1e42a389b07))
-
-
-
-<a name="v0.6.6"></a>
-## v0.6.6 (2015-04-19)
-
-
-#### Bug Fixes
-
-* **from_usage** tabs and spaces should be treated equally ([4fd44181](https://github.com/kbknapp/clap-rs/commit/4fd44181d55d8eb88caab1e625231cfa3129e347))
-
-#### Features
-
-* **macros.rs** add macro to get version from Cargo.toml ([c630969a](https://github.com/kbknapp/clap-rs/commit/c630969aa3bbd386379219cae27ba1305b117f3e))
-
-
-
-<a name="v0.6.5"></a>
-## v0.6.5 (2015-04-19)
-
-
-#### Bug Fixes
-
-* **macros.rs** fix use statements for trait impls ([86e4075e](https://github.com/kbknapp/clap-rs/commit/86e4075eb111937c8a7bdb344e866e350429f042))
-
-
-
-<a name="v0.6.4"></a>
-## v0.6.4 (2015-04-17)
-
-
-#### Features
-
-* **macros** add ability to create enums pub or priv with derives ([2c499f80](https://github.com/kbknapp/clap-rs/commit/2c499f8015a199827cdf1fa3ec4f6f171722f8c7))
-
-
-
-<a name="v0.6.3"></a>
-## v0.6.3 (2015-04-16)
-
-
-#### Features
-
-* **macros** add macro to create custom enums to use as types ([fb672aff](https://github.com/kbknapp/clap-rs/commit/fb672aff561c29db2e343d6c607138f141aca8b6))
-
-
-
-<a name="v0.6.2"></a>
-## v0.6.2 (2015-04-14)
-
-
-#### Features
-
-* **macros**
- * add ability to get multiple typed values or exit ([0b87251f](https://github.com/kbknapp/clap-rs/commit/0b87251fc088234bee51c323c2b652d7254f7a59))
- * add ability to get a typed multiple values ([e243fe38](https://github.com/kbknapp/clap-rs/commit/e243fe38ddbbf845a46c0b9baebaac3778c80927))
- * add convenience macro to get a typed value or exit ([4b7cd3ea](https://github.com/kbknapp/clap-rs/commit/4b7cd3ea4947780d9daa39f3e1ddab53ad4c7fef))
- * add convenience macro to get a typed value ([8752700f](https://github.com/kbknapp/clap-rs/commit/8752700fbb30e89ee68adbce24489ae9a24d33a9))
-
-
-
-<a name="v0.6.1"></a>
-## v0.6.1 (2015-04-13)
-
-
-#### Bug Fixes
-
-* **from_usage** trim all whitespace before parsing ([91d29045](https://github.com/kbknapp/clap-rs/commit/91d2904599bd602deef2e515dfc65dc2863bdea0))
-
-
-
-<a name="v0.6.0"></a>
-## v0.6.0 (2015-04-13)
-
-
-#### Bug Fixes
-
-* **tests** fix failing doc tests ([3710cd69](https://github.com/kbknapp/clap-rs/commit/3710cd69162f87221a62464f63437c1ce843ad3c))
-
-#### Features
-
-* **app** add support for building args from usage strings ([d5d48bcf](https://github.com/kbknapp/clap-rs/commit/d5d48bcf463a4e494ef758836bd69a4c220bbbb5))
-* **args** add ability to create basic arguments from a usage string ([ab409a8f](https://github.com/kbknapp/clap-rs/commit/ab409a8f1db9e37cc70200f6f4a84a162692e618))
-
-
-
-<a name="v0.5.14"></a>
-## v0.5.14 (2015-04-10)
-
-
-#### Bug Fixes
-
-* **usage**
- * remove unneeded space ([51372789](https://github.com/kbknapp/clap-rs/commit/5137278942121bc2593ce6e5dc224ec2682549e6))
- * remove warning about unused variables ([ba817b9d](https://github.com/kbknapp/clap-rs/commit/ba817b9d815e37320650973f1bea0e7af3030fd7))
-
-#### Features
-
-* **usage** add ability to get usage string for subcommands too ([3636afc4](https://github.com/kbknapp/clap-rs/commit/3636afc401c2caa966efb5b1869ef4f1ed3384aa))
-
-
-
-<a name="v0.5.13"></a>
-## v0.5.13 (2015-04-09)
-
-
-#### Features
-
-* **SubCommands** add method to get name and subcommand matches together ([64e53928](https://github.com/kbknapp/clap-rs/commit/64e539280e23e567cf5de393b346eb0ca20e7eb5))
-* **ArgMatches** add method to get default usage string ([02462150](https://github.com/kbknapp/clap-rs/commit/02462150ca750bdc7012627d7e8d96379d494d7f))
-
-
-
-<a name="v0.5.12"></a>
-## v0.5.12 (2015-04-08)
-
-
-#### Features
-
-* **help** sort arguments by name so as to not display a random order ([f4b2bf57](https://github.com/kbknapp/clap-rs/commit/f4b2bf5767386013069fb74862e6e938dacf44d2))
-
-
-
-<a name="v0.5.11"></a>
-## v0.5.11 (2015-04-08)
-
-
-#### Bug Fixes
-
-* **flags** fix bug not allowing users to specify -v or -h ([90e72cff](https://github.com/kbknapp/clap-rs/commit/90e72cffdee321b79eea7a2207119533540062b4))
-
-
-
-<a name="v0.5.10"></a>
-## v0.5.10 (2015-04-08)
-
-
-#### Bug Fixes
-
-* **help** fix spacing when option argument has not long version ([ca17fa49](https://github.com/kbknapp/clap-rs/commit/ca17fa494b68e92da83ee364bf64b0687006824b))
-
-
-
-<a name="v0.5.9"></a>
-## v0.5.9 (2015-04-08)
-
-
-#### Bug Fixes
-
-* **positional args** all previous positional args become required when a latter one is required ([c14c3f31](https://github.com/kbknapp/clap-rs/commit/c14c3f31fd557c165570b60911d8ee483d89d6eb), closes [#50](https://github.com/kbknapp/clap-rs/issues/50))
-* **clap** remove unstable features for Rust 1.0 ([9abdb438](https://github.com/kbknapp/clap-rs/commit/9abdb438e36e364d41550e7f5d44ebcaa8ee6b10))
-* **args** improve error messages for arguments with mutual exclusions ([18dbcf37](https://github.com/kbknapp/clap-rs/commit/18dbcf37024daf2b76ca099a6f118b53827aa339), closes [#51](https://github.com/kbknapp/clap-rs/issues/51))
-
-
-
-<a name="v0.5.8"></a>
-## v0.5.8 (2015-04-08)
-
-
-#### Bug Fixes
-
-* **option args** fix bug in getting the wrong number of occurrences for options ([82ad6ad7](https://github.com/kbknapp/clap-rs/commit/82ad6ad77539cf9f9a03b78db466f575ebd972cc))
-* **help** fix formatting for option arguments with no long ([e8691004](https://github.com/kbknapp/clap-rs/commit/e869100423d93fa3acff03c4620cbcc0d0e790a1))
-* **flags** add assertion to catch flags with specific value sets ([a0a2a40f](https://github.com/kbknapp/clap-rs/commit/a0a2a40fed57f7c5ad9d68970d090e9856306c7d), closes [#52](https://github.com/kbknapp/clap-rs/issues/52))
-* **args** improve error messages for arguments with mutual exclusions ([bff945fc](https://github.com/kbknapp/clap-rs/commit/bff945fc5d03bba4266533340adcffb002508d1b), closes [#51](https://github.com/kbknapp/clap-rs/issues/51))
-* **tests** add missing .takes_value(true) to option2 ([bdb0e88f](https://github.com/kbknapp/clap-rs/commit/bdb0e88f696c8595c3def3bfb0e52d538c7be085))
-* **positional args** all previous positional args become required when a latter one is required ([343d47dc](https://github.com/kbknapp/clap-rs/commit/343d47dcbf83786a45c0d0f01b27fd9dd76725de), closes [#50](https://github.com/kbknapp/clap-rs/issues/50))
-
-
-
-<a name="v0.5.7"></a>
-## v0.5.7 (2015-04-08)
-
-
-#### Bug Fixes
-
-* **args** fix bug in arguments who are required and mutually exclusive ([6ceb88a5](https://github.com/kbknapp/clap-rs/commit/6ceb88a594caae825605abc1cdad95204996bf29))
-
-
-
-<a name="v0.5.6"></a>
-## v0.5.6 (2015-04-08)
-
-
-#### Bug Fixes
-
-* **help** fix formatting of help and usage ([28691b52](https://github.com/kbknapp/clap-rs/commit/28691b52f67e65c599e10e4ea2a0f6f9765a06b8))
-
-
-
-<a name="v0.5.5"></a>
-## v0.5.5 (2015-04-08)
-
-
-#### Bug Fixes
-
-* **help** fix formatting of help for flags and options ([6ec10115](https://github.com/kbknapp/clap-rs/commit/6ec1011563a746f0578a93b76d45e63878e0f9a8))
-
-
-
-<a name="v0.5.4"></a>
-## v0.5.4 (2015-04-08)
-
-
-#### Features
-
-* **help** add '...' to indicate multiple values supported ([297ddba7](https://github.com/kbknapp/clap-rs/commit/297ddba77000e2228762ab0eca50b480f7467386))
-
-
-
-<a name="v0.5.3"></a>
-## v0.5.3 (2015-04-08)
-
-
-#### Features
-
-* **positionals**
- * add assertions for positional args with multiple vals ([b7fa72d4](https://github.com/kbknapp/clap-rs/commit/b7fa72d40f18806ec2042dd67a518401c2cf5681))
- * add support for multiple values ([80784009](https://github.com/kbknapp/clap-rs/commit/807840094109fbf90b348039ae22669ef27889ba))
-
-
-
-<a name="v0.5.2"></a>
-## v0.5.2 (2015-04-08)
-
-
-#### Bug Fixes
-
-* **apps** allow use of hyphens in application and subcommand names ([da549dcb](https://github.com/kbknapp/clap-rs/commit/da549dcb6c7e0d773044ab17829744483a8b0f7f))
-
-
-
-<a name="v0.5.1"></a>
-## v0.5.1 (2015-04-08)
-
-
-#### Bug Fixes
-
-* **args** determine if the only arguments allowed are also required ([0a09eb36](https://github.com/kbknapp/clap-rs/commit/0a09eb365ced9a03faf8ed24f083ef730acc90e8))
-
-
-
-<a name="v0.5.0"></a>
-## v0.5.0 (2015-04-08)
-
-
-#### Features
-
-* **args** add support for a specific set of allowed values on options or positional arguments ([270eb889](https://github.com/kbknapp/clap-rs/commit/270eb88925b6dc2881bff1f31ee344f085d31809))
-
-
-
-<a name="v0.4.18"></a>
-## v0.4.18 (2015-04-08)
-
-
-#### Bug Fixes
-
-* **usage** display required args in usage, even if only required by others ([1b7316d4](https://github.com/kbknapp/clap-rs/commit/1b7316d4a8df70b0aa584ccbfd33f68966ad2a54))
-
-#### Features
-
-* **subcommands** properly list subcommands in help and usage ([4ee02344](https://github.com/kbknapp/clap-rs/commit/4ee023442abc3dba54b68138006a52b714adf331))
-
-
-
-<a name="v0.4.17"></a>
-## v0.4.17 (2015-04-08)
-
-
-#### Bug Fixes
-
-* **tests** remove cargo test from claptests makefile ([1cf73817](https://github.com/kbknapp/clap-rs/commit/1cf73817d6fb1dccb5b6a23b46c2efa8b567ad62))
-
-
-
-<a name="v0.4.16"></a>
-## v0.4.16 (2015-04-08)
-
-
-#### Bug Fixes
-
-* **option** fix bug with option occurrence values ([9af52e93](https://github.com/kbknapp/clap-rs/commit/9af52e93cef9e17ac9974963f132013d0b97b946))
-* **tests** fix testing script bug and formatting ([d8f03a55](https://github.com/kbknapp/clap-rs/commit/d8f03a55c4f74d126710ee06aad5a667246a8001))
-
-#### Features
-
-* **arg** allow lifetimes other than 'static in arguments ([9e8c1fb9](https://github.com/kbknapp/clap-rs/commit/9e8c1fb9406f8448873ca58bab07fe905f1551e5))
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
deleted file mode 100644
index f0fd777..0000000
--- a/CONTRIBUTORS.md
+++ /dev/null
@@ -1,91 +0,0 @@
-the following is a list of contributors:
-
-
-[<img alt="kbknapp" src="https://avatars1.githubusercontent.com/u/6942134?v=4&s=117" width="117">](https://github.com/kbknapp) |[<img alt="homu" src="https://avatars1.githubusercontent.com/u/10212162?v=4&s=117" width="117">](https://github.com/homu) |[<img alt="Vinatorul" src="https://avatars1.githubusercontent.com/u/6770624?v=4&s=117" width="117">](https://github.com/Vinatorul) |[<img alt="tormol" src="https://avatars3.githubusercontent.com/u/10460821?v=4&s=117" width="117">](https://github.com/tormol) |[<img alt="willmurphyscode" src="https://avatars3.githubusercontent.com/u/12529630?v=4&s=117" width="117">](https://github.com/willmurphyscode) |[<img alt="little-dude" src="https://avatars2.githubusercontent.com/u/6646324?v=4&s=117" width="117">](https://github.com/little-dude) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[kbknapp](https://github.com/kbknapp) |[homu](https://github.com/homu) |[Vinatorul](https://github.com/Vinatorul) |[tormol](https://github.com/tormol) |[willmurphyscode](https://github.com/willmurphyscode) |[little-dude](https://github.com/little-dude) |
-
-[<img alt="sru" src="https://avatars3.githubusercontent.com/u/2485892?v=4&s=117" width="117">](https://github.com/sru) |[<img alt="mgeisler" src="https://avatars0.githubusercontent.com/u/89623?v=4&s=117" width="117">](https://github.com/mgeisler) |[<img alt="nabijaczleweli" src="https://avatars3.githubusercontent.com/u/6709544?v=4&s=117" width="117">](https://github.com/nabijaczleweli) |[<img alt="Byron" src="https://avatars2.githubusercontent.com/u/63622?v=4&s=117" width="117">](https://github.com/Byron) |[<img alt="hgrecco" src="https://avatars0.githubusercontent.com/u/278566?v=4&s=117" width="117">](https://github.com/hgrecco) |[<img alt="bluejekyll" src="https://avatars3.githubusercontent.com/u/986845?v=4&s=117" width="117">](https://github.com/bluejekyll) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[sru](https://github.com/sru) |[mgeisler](https://github.com/mgeisler) |[nabijaczleweli](https://github.com/nabijaczleweli) |[Byron](https://github.com/Byron) |[hgrecco](https://github.com/hgrecco) |[bluejekyll](https://github.com/bluejekyll) |
-
-[<img alt="segevfiner" src="https://avatars0.githubusercontent.com/u/24731903?v=4&s=117" width="117">](https://github.com/segevfiner) |[<img alt="ignatenkobrain" src="https://avatars1.githubusercontent.com/u/2866862?v=4&s=117" width="117">](https://github.com/ignatenkobrain) |[<img alt="james-darkfox" src="https://avatars3.githubusercontent.com/u/637155?v=4&s=117" width="117">](https://github.com/james-darkfox) |[<img alt="H2CO3" src="https://avatars2.githubusercontent.com/u/742370?v=4&s=117" width="117">](https://github.com/H2CO3) |[<img alt="nateozem" src="https://avatars2.githubusercontent.com/u/22719441?v=4&s=117" width="117">](https://github.com/nateozem) |[<img alt="glowing-chemist" src="https://avatars0.githubusercontent.com/u/17074682?v=4&s=117" width="117">](https://github.com/glowing-chemist) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[segevfiner](https://github.com/segevfiner) |[ignatenkobrain](https://github.com/ignatenkobrain) |[james-darkfox](https://github.com/james-darkfox) |[H2CO3](https://github.com/H2CO3) |[nateozem](https://github.com/nateozem) |[glowing-chemist](https://github.com/glowing-chemist) |
-
-[<img alt="discosultan" src="https://avatars1.githubusercontent.com/u/2970736?v=4&s=117" width="117">](https://github.com/discosultan) |[<img alt="rtaycher" src="https://avatars0.githubusercontent.com/u/324733?v=4&s=117" width="117">](https://github.com/rtaycher) |[<img alt="Arnavion" src="https://avatars2.githubusercontent.com/u/1096010?v=4&s=117" width="117">](https://github.com/Arnavion) |[<img alt="japaric" src="https://avatars3.githubusercontent.com/u/5018213?v=4&s=117" width="117">](https://github.com/japaric) |[<img alt="untitaker" src="https://avatars0.githubusercontent.com/u/837573?v=4&s=117" width="117">](https://github.com/untitaker) |[<img alt="afiune" src="https://avatars0.githubusercontent.com/u/5712253?v=4&s=117" width="117">](https://github.com/afiune) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[discosultan](https://github.com/discosultan) |[rtaycher](https://github.com/rtaycher) |[Arnavion](https://github.com/Arnavion) |[japaric](https://github.com/japaric) |[untitaker](https://github.com/untitaker) |[afiune](https://github.com/afiune) |
-
-[<img alt="crazymerlyn" src="https://avatars1.githubusercontent.com/u/6919679?v=4&s=117" width="117">](https://github.com/crazymerlyn) |[<img alt="SuperFluffy" src="https://avatars0.githubusercontent.com/u/701177?v=4&s=117" width="117">](https://github.com/SuperFluffy) |[<img alt="matthiasbeyer" src="https://avatars0.githubusercontent.com/u/427866?v=4&s=117" width="117">](https://github.com/matthiasbeyer) |[<img alt="malbarbo" src="https://avatars3.githubusercontent.com/u/1678126?v=4&s=117" width="117">](https://github.com/malbarbo) |[<img alt="tshepang" src="https://avatars0.githubusercontent.com/u/588486?v=4&s=117" width="117">](https://github.com/tshepang) |[<img alt="golem131" src="https://avatars3.githubusercontent.com/u/2429587?v=4&s=117" width="117">](https://github.com/golem131) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[crazymerlyn](https://github.com/crazymerlyn) |[SuperFluffy](https://github.com/SuperFluffy) |[matthiasbeyer](https://github.com/matthiasbeyer) |[malbarbo](https://github.com/malbarbo) |[tshepang](https://github.com/tshepang) |[golem131](https://github.com/golem131) |
-
-[<img alt="jimmycuadra" src="https://avatars2.githubusercontent.com/u/122457?v=4&s=117" width="117">](https://github.com/jimmycuadra) |[<img alt="Nemo157" src="https://avatars1.githubusercontent.com/u/81079?v=4&s=117" width="117">](https://github.com/Nemo157) |[<img alt="severen" src="https://avatars1.githubusercontent.com/u/4061736?v=4&s=117" width="117">](https://github.com/severen) |[<img alt="Eijebong" src="https://avatars2.githubusercontent.com/u/3650385?v=4&s=117" width="117">](https://github.com/Eijebong) |[<img alt="cstorey" src="https://avatars3.githubusercontent.com/u/743059?v=4&s=117" width="117">](https://github.com/cstorey) |[<img alt="wdv4758h" src="https://avatars1.githubusercontent.com/u/2716047?v=4&s=117" width="117">](https://github.com/wdv4758h) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[jimmycuadra](https://github.com/jimmycuadra) |[Nemo157](https://github.com/Nemo157) |[severen](https://github.com/severen) |[Eijebong](https://github.com/Eijebong) |[cstorey](https://github.com/cstorey) |[wdv4758h](https://github.com/wdv4758h) |
-
-[<img alt="frewsxcv" src="https://avatars2.githubusercontent.com/u/416575?v=4&s=117" width="117">](https://github.com/frewsxcv) |[<img alt="hoodie" src="https://avatars1.githubusercontent.com/u/260370?v=4&s=117" width="117">](https://github.com/hoodie) |[<img alt="huonw" src="https://avatars1.githubusercontent.com/u/1203825?v=4&s=117" width="117">](https://github.com/huonw) |[<img alt="GrappigPanda" src="https://avatars0.githubusercontent.com/u/2055372?v=4&s=117" width="117">](https://github.com/GrappigPanda) |[<img alt="shepmaster" src="https://avatars0.githubusercontent.com/u/174509?v=4&s=117" width="117">](https://github.com/shepmaster) |[<img alt="starkat99" src="https://avatars1.githubusercontent.com/u/8295111?v=4&s=117" width="117">](https://github.com/starkat99) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[frewsxcv](https://github.com/frewsxcv) |[hoodie](https://github.com/hoodie) |[huonw](https://github.com/huonw) |[GrappigPanda](https://github.com/GrappigPanda) |[shepmaster](https://github.com/shepmaster) |[starkat99](https://github.com/starkat99) |
-
-[<img alt="porglezomp" src="https://avatars1.githubusercontent.com/u/1690225?v=4&s=117" width="117">](https://github.com/porglezomp) |[<img alt="kraai" src="https://avatars1.githubusercontent.com/u/552646?v=4&s=117" width="117">](https://github.com/kraai) |[<img alt="musoke" src="https://avatars0.githubusercontent.com/u/16665084?v=4&s=117" width="117">](https://github.com/musoke) |[<img alt="nelsonjchen" src="https://avatars1.githubusercontent.com/u/5363?v=4&s=117" width="117">](https://github.com/nelsonjchen) |[<img alt="pkgw" src="https://avatars0.githubusercontent.com/u/59598?v=4&s=117" width="117">](https://github.com/pkgw) |[<img alt="Deedasmi" src="https://avatars0.githubusercontent.com/u/5093293?v=4&s=117" width="117">](https://github.com/Deedasmi) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[porglezomp](https://github.com/porglezomp) |[kraai](https://github.com/kraai) |[musoke](https://github.com/musoke) |[nelsonjchen](https://github.com/nelsonjchen) |[pkgw](https://github.com/pkgw) |[Deedasmi](https://github.com/Deedasmi) |
-
-[<img alt="vmchale" src="https://avatars1.githubusercontent.com/u/13259982?v=4&s=117" width="117">](https://github.com/vmchale) |[<img alt="etopiei" src="https://avatars3.githubusercontent.com/u/17671663?v=4&s=117" width="117">](https://github.com/etopiei) |[<img alt="messense" src="https://avatars0.githubusercontent.com/u/1556054?v=4&s=117" width="117">](https://github.com/messense) |[<img alt="Keats" src="https://avatars2.githubusercontent.com/u/680355?v=4&s=117" width="117">](https://github.com/Keats) |[<img alt="kieraneglin" src="https://avatars0.githubusercontent.com/u/569917?v=4&s=117" width="117">](https://github.com/kieraneglin) |[<img alt="durka" src="https://avatars3.githubusercontent.com/u/47007?v=4&s=117" width="117">](https://github.com/durka) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[vmchale](https://github.com/vmchale) |[etopiei](https://github.com/etopiei) |[messense](https://github.com/messense) |[Keats](https://github.com/Keats) |[kieraneglin](https://github.com/kieraneglin) |[durka](https://github.com/durka) |
-
-[<img alt="alex-gulyas" src="https://avatars0.githubusercontent.com/u/8698329?v=4&s=117" width="117">](https://github.com/alex-gulyas) |[<img alt="cite-reader" src="https://avatars1.githubusercontent.com/u/4196987?v=4&s=117" width="117">](https://github.com/cite-reader) |[<img alt="alexbool" src="https://avatars3.githubusercontent.com/u/1283792?v=4&s=117" width="117">](https://github.com/alexbool) |[<img alt="AluisioASG" src="https://avatars2.githubusercontent.com/u/1904165?v=4&s=117" width="117">](https://github.com/AluisioASG) |[<img alt="BurntSushi" src="https://avatars3.githubusercontent.com/u/456674?v=4&s=117" width="117">](https://github.com/BurntSushi) |[<img alt="AndrewGaspar" src="https://avatars1.githubusercontent.com/u/2292643?v=4&s=117" width="117">](https://github.com/AndrewGaspar) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[alex-gulyas](https://github.com/alex-gulyas) |[cite-reader](https://github.com/cite-reader) |[alexbool](https://github.com/alexbool) |[AluisioASG](https://github.com/AluisioASG) |[BurntSushi](https://github.com/BurntSushi) |[AndrewGaspar](https://github.com/AndrewGaspar) |
-
-[<img alt="nox" src="https://avatars0.githubusercontent.com/u/123095?v=4&s=117" width="117">](https://github.com/nox) |[<img alt="mitsuhiko" src="https://avatars1.githubusercontent.com/u/7396?v=4&s=117" width="117">](https://github.com/mitsuhiko) |[<img alt="pixelistik" src="https://avatars1.githubusercontent.com/u/170929?v=4&s=117" width="117">](https://github.com/pixelistik) |[<img alt="ogham" src="https://avatars3.githubusercontent.com/u/503760?v=4&s=117" width="117">](https://github.com/ogham) |[<img alt="Bilalh" src="https://avatars0.githubusercontent.com/u/171602?v=4&s=117" width="117">](https://github.com/Bilalh) |[<img alt="dotdash" src="https://avatars1.githubusercontent.com/u/230962?v=4&s=117" width="117">](https://github.com/dotdash) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[nox](https://github.com/nox) |[mitsuhiko](https://github.com/mitsuhiko) |[pixelistik](https://github.com/pixelistik) |[ogham](https://github.com/ogham) |[Bilalh](https://github.com/Bilalh) |[dotdash](https://github.com/dotdash) |
-
-[<img alt="bradurani" src="https://avatars0.githubusercontent.com/u/4195952?v=4&s=117" width="117">](https://github.com/bradurani) |[<img alt="Seeker14491" src="https://avatars2.githubusercontent.com/u/6490497?v=4&s=117" width="117">](https://github.com/Seeker14491) |[<img alt="brianp" src="https://avatars1.githubusercontent.com/u/179134?v=4&s=117" width="117">](https://github.com/brianp) |[<img alt="cldershem" src="https://avatars3.githubusercontent.com/u/201608?v=4&s=117" width="117">](https://github.com/cldershem) |[<img alt="casey" src="https://avatars2.githubusercontent.com/u/1945?v=4&s=117" width="117">](https://github.com/casey) |[<img alt="volks73" src="https://avatars1.githubusercontent.com/u/1915469?v=4&s=117" width="117">](https://github.com/volks73) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[bradurani](https://github.com/bradurani) |[Seeker14491](https://github.com/Seeker14491) |[brianp](https://github.com/brianp) |[cldershem](https://github.com/cldershem) |[casey](https://github.com/casey) |[volks73](https://github.com/volks73) |
-
-[<img alt="daboross" src="https://avatars1.githubusercontent.com/u/1152146?v=4&s=117" width="117">](https://github.com/daboross) |[<img alt="da-x" src="https://avatars1.githubusercontent.com/u/321273?v=4&s=117" width="117">](https://github.com/da-x) |[<img alt="mernen" src="https://avatars0.githubusercontent.com/u/6412?v=4&s=117" width="117">](https://github.com/mernen) |[<img alt="dguo" src="https://avatars0.githubusercontent.com/u/2763135?v=4&s=117" width="117">](https://github.com/dguo) |[<img alt="davidszotten" src="https://avatars3.githubusercontent.com/u/412005?v=4&s=117" width="117">](https://github.com/davidszotten) |[<img alt="drusellers" src="https://avatars1.githubusercontent.com/u/63355?v=4&s=117" width="117">](https://github.com/drusellers) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[daboross](https://github.com/daboross) |[da-x](https://github.com/da-x) |[mernen](https://github.com/mernen) |[dguo](https://github.com/dguo) |[davidszotten](https://github.com/davidszotten) |[drusellers](https://github.com/drusellers) |
-
-[<img alt="eddyb" src="https://avatars2.githubusercontent.com/u/77424?v=4&s=117" width="117">](https://github.com/eddyb) |[<img alt="Enet4" src="https://avatars0.githubusercontent.com/u/4738426?v=4&s=117" width="117">](https://github.com/Enet4) |[<img alt="Fraser999" src="https://avatars3.githubusercontent.com/u/190532?v=4&s=117" width="117">](https://github.com/Fraser999) |[<img alt="birkenfeld" src="https://avatars0.githubusercontent.com/u/144359?v=4&s=117" width="117">](https://github.com/birkenfeld) |[<img alt="guanqun" src="https://avatars0.githubusercontent.com/u/53862?v=4&s=117" width="117">](https://github.com/guanqun) |[<img alt="tanakh" src="https://avatars2.githubusercontent.com/u/109069?v=4&s=117" width="117">](https://github.com/tanakh) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[eddyb](https://github.com/eddyb) |[Enet4](https://github.com/Enet4) |[Fraser999](https://github.com/Fraser999) |[birkenfeld](https://github.com/birkenfeld) |[guanqun](https://github.com/guanqun) |[tanakh](https://github.com/tanakh) |
-
-[<img alt="SirVer" src="https://avatars0.githubusercontent.com/u/140115?v=4&s=117" width="117">](https://github.com/SirVer) |[<img alt="idmit" src="https://avatars1.githubusercontent.com/u/2546728?v=4&s=117" width="117">](https://github.com/idmit) |[<img alt="archer884" src="https://avatars1.githubusercontent.com/u/679494?v=4&s=117" width="117">](https://github.com/archer884) |[<img alt="jacobmischka" src="https://avatars1.githubusercontent.com/u/3939997?v=4&s=117" width="117">](https://github.com/jacobmischka) |[<img alt="jespino" src="https://avatars0.githubusercontent.com/u/290303?v=4&s=117" width="117">](https://github.com/jespino) |[<img alt="jfrankenau" src="https://avatars3.githubusercontent.com/u/2736480?v=4&s=117" width="117">](https://github.com/jfrankenau) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[SirVer](https://github.com/SirVer) |[idmit](https://github.com/idmit) |[archer884](https://github.com/archer884) |[jacobmischka](https://github.com/jacobmischka) |[jespino](https://github.com/jespino) |[jfrankenau](https://github.com/jfrankenau) |
-
-[<img alt="jtdowney" src="https://avatars1.githubusercontent.com/u/44654?v=4&s=117" width="117">](https://github.com/jtdowney) |[<img alt="andete" src="https://avatars2.githubusercontent.com/u/689017?v=4&s=117" width="117">](https://github.com/andete) |[<img alt="joshtriplett" src="https://avatars2.githubusercontent.com/u/162737?v=4&s=117" width="117">](https://github.com/joshtriplett) |[<img alt="Kalwyn" src="https://avatars3.githubusercontent.com/u/22778640?v=4&s=117" width="117">](https://github.com/Kalwyn) |[<img alt="manuel-rhdt" src="https://avatars1.githubusercontent.com/u/3199013?v=4&s=117" width="117">](https://github.com/manuel-rhdt) |[<img alt="Marwes" src="https://avatars3.githubusercontent.com/u/957312?v=4&s=117" width="117">](https://github.com/Marwes) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[jtdowney](https://github.com/jtdowney) |[andete](https://github.com/andete) |[joshtriplett](https://github.com/joshtriplett) |[Kalwyn](https://github.com/Kalwyn) |[manuel-rhdt](https://github.com/manuel-rhdt) |[Marwes](https://github.com/Marwes) |
-
-[<img alt="mdaffin" src="https://avatars1.githubusercontent.com/u/171232?v=4&s=117" width="117">](https://github.com/mdaffin) |[<img alt="iliekturtles" src="https://avatars3.githubusercontent.com/u/5081378?v=4&s=117" width="117">](https://github.com/iliekturtles) |[<img alt="nicompte" src="https://avatars2.githubusercontent.com/u/439369?v=4&s=117" width="117">](https://github.com/nicompte) |[<img alt="NickeZ" src="https://avatars2.githubusercontent.com/u/492753?v=4&s=117" width="117">](https://github.com/NickeZ) |[<img alt="nvzqz" src="https://avatars0.githubusercontent.com/u/10367662?v=4&s=117" width="117">](https://github.com/nvzqz) |[<img alt="nuew" src="https://avatars2.githubusercontent.com/u/26099511?v=4&s=117" width="117">](https://github.com/nuew) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[mdaffin](https://github.com/mdaffin) |[iliekturtles](https://github.com/iliekturtles) |[nicompte](https://github.com/nicompte) |[NickeZ](https://github.com/NickeZ) |[nvzqz](https://github.com/nvzqz) |[nuew](https://github.com/nuew) |
-
-[<img alt="Geogi" src="https://avatars1.githubusercontent.com/u/1818316?v=4&s=117" width="117">](https://github.com/Geogi) |[<img alt="focusaurus" src="https://avatars1.githubusercontent.com/u/482377?v=4&s=117" width="117">](https://github.com/focusaurus) |[<img alt="flying-sheep" src="https://avatars0.githubusercontent.com/u/291575?v=4&s=117" width="117">](https://github.com/flying-sheep) |[<img alt="Phlosioneer" src="https://avatars2.githubusercontent.com/u/4657718?v=4&s=117" width="117">](https://github.com/Phlosioneer) |[<img alt="peppsac" src="https://avatars3.githubusercontent.com/u/2198295?v=4&s=117" width="117">](https://github.com/peppsac) |[<img alt="golddranks" src="https://avatars1.githubusercontent.com/u/2675542?v=4&s=117" width="117">](https://github.com/golddranks) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[Geogi](https://github.com/Geogi) |[focusaurus](https://github.com/focusaurus) |[flying-sheep](https://github.com/flying-sheep) |[Phlosioneer](https://github.com/Phlosioneer) |[peppsac](https://github.com/peppsac) |[golddranks](https://github.com/golddranks) |
-
-[<img alt="hexjelly" src="https://avatars0.githubusercontent.com/u/435283?v=4&s=117" width="117">](https://github.com/hexjelly) |[<img alt="rom1v" src="https://avatars1.githubusercontent.com/u/543275?v=4&s=117" width="117">](https://github.com/rom1v) |[<img alt="rnelson" src="https://avatars3.githubusercontent.com/u/118361?v=4&s=117" width="117">](https://github.com/rnelson) |[<img alt="swatteau" src="https://avatars3.githubusercontent.com/u/5521255?v=4&s=117" width="117">](https://github.com/swatteau) |[<img alt="tchajed" src="https://avatars3.githubusercontent.com/u/1255037?v=4&s=117" width="117">](https://github.com/tchajed) |[<img alt="tspiteri" src="https://avatars0.githubusercontent.com/u/18604588?v=4&s=117" width="117">](https://github.com/tspiteri) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[hexjelly](https://github.com/hexjelly) |[rom1v](https://github.com/rom1v) |[rnelson](https://github.com/rnelson) |[swatteau](https://github.com/swatteau) |[tchajed](https://github.com/tchajed) |[tspiteri](https://github.com/tspiteri) |
-
-[<img alt="siiptuo" src="https://avatars0.githubusercontent.com/u/10729330?v=4&s=117" width="117">](https://github.com/siiptuo) |[<img alt="vks" src="https://avatars2.githubusercontent.com/u/33460?v=4&s=117" width="117">](https://github.com/vks) |[<img alt="vsupalov" src="https://avatars2.githubusercontent.com/u/2801030?v=4&s=117" width="117">](https://github.com/vsupalov) |[<img alt="mineo" src="https://avatars1.githubusercontent.com/u/78236?v=4&s=117" width="117">](https://github.com/mineo) |[<img alt="wabain" src="https://avatars3.githubusercontent.com/u/7651435?v=4&s=117" width="117">](https://github.com/wabain) |[<img alt="grossws" src="https://avatars2.githubusercontent.com/u/171284?v=4&s=117" width="117">](https://github.com/grossws) |
-:---: |:---: |:---: |:---: |:---: |:---: |
-[siiptuo](https://github.com/siiptuo) |[vks](https://github.com/vks) |[vsupalov](https://github.com/vsupalov) |[mineo](https://github.com/mineo) |[wabain](https://github.com/wabain) |[grossws](https://github.com/grossws) |
-
-[<img alt="kennytm" src="https://avatars1.githubusercontent.com/u/103023?v=4&s=117" width="117">](https://github.com/kennytm) |[<img alt="king6cong" src="https://avatars3.githubusercontent.com/u/302560?v=4&s=117" width="117">](https://github.com/king6cong) |[<img alt="mvaude" src="https://avatars1.githubusercontent.com/u/9532611?v=4&s=117" width="117">](https://github.com/mvaude) |[<img alt="panicbit" src="https://avatars2.githubusercontent.com/u/628445?v=4&s=117" width="117">](https://github.com/panicbit) |[<img alt="brennie" src="https://avatars3.githubusercontent.com/u/156585?v=4&s=117" width="117">](https://github.com/brennie) |
-:---: |:---: |:---: |:---: |:---: |
-[kennytm](https://github.com/kennytm) |[king6cong](https://github.com/king6cong) |[mvaude](https://github.com/mvaude) |[panicbit](https://github.com/panicbit) |[brennie](https://github.com/brennie) |
-
-
-
-
-This list was generated by [mgechev/github-contributors-list](https://github.com/mgechev/github-contributors-list)
diff --git a/Cargo.toml b/Cargo.toml
index c0a1669..fc59af3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,134 +3,483 @@
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
-# to registry (e.g., crates.io) dependencies
+# to registry (e.g., crates.io) dependencies.
#
-# If you believe there's an error in this file please file an
-# issue against the rust-lang/cargo repository. If you're
-# editing this file be aware that the upstream Cargo.toml
-# will likely look very different (and much more reasonable)
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
[package]
+edition = "2021"
+rust-version = "1.64.0"
name = "clap"
-version = "2.33.3"
-authors = ["Kevin K. <kbknapp@gmail.com>"]
-exclude = ["examples/*", "clap-test/*", "tests/*", "benches/*", "*.png", "clap-perf/*", "*.dot"]
-description = "A simple to use, efficient, and full-featured Command Line Argument Parser\n"
-homepage = "https://clap.rs/"
-documentation = "https://docs.rs/clap/"
+version = "4.1.8"
+include = [
+ "build.rs",
+ "src/**/*",
+ "Cargo.toml",
+ "LICENSE*",
+ "README.md",
+ "benches/**/*",
+ "examples/**/*",
+]
+description = "A simple to use, efficient, and full-featured Command Line Argument Parser"
readme = "README.md"
-keywords = ["argument", "cli", "arg", "parser", "parse"]
+keywords = [
+ "argument",
+ "cli",
+ "arg",
+ "parser",
+ "parse",
+]
categories = ["command-line-interface"]
-license = "MIT"
+license = "MIT OR Apache-2.0"
repository = "https://github.com/clap-rs/clap"
+
[package.metadata.docs.rs]
-features = ["doc"]
+features = ["unstable-doc"]
+rustdoc-args = [
+ "--cfg",
+ "docsrs",
+]
+cargo-args = [
+ "-Zunstable-options",
+ "-Zrustdoc-scrape-examples",
+]
+
+[package.metadata.playground]
+features = ["unstable-doc"]
+
+[package.metadata.release]
+shared-version = true
+tag-name = "v{{version}}"
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = "Unreleased"
+replace = "{{version}}"
+min = 1
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = '\.\.\.HEAD'
+replace = "...{{tag_name}}"
+exactly = 1
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = "ReleaseDate"
+replace = "{{date}}"
+min = 1
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = "<!-- next-header -->"
+replace = """
+<!-- next-header -->
+## [Unreleased] - ReleaseDate
+"""
+exactly = 1
+
+[[package.metadata.release.pre-release-replacements]]
+file = "CHANGELOG.md"
+search = "<!-- next-url -->"
+replace = """
+<!-- next-url -->
+[Unreleased]: https://github.com/clap-rs/clap/compare/{{tag_name}}...HEAD"""
+exactly = 1
+
[profile.bench]
-opt-level = 3
-lto = true
-codegen-units = 1
-debug = false
-debug-assertions = false
-rpath = false
-
-[profile.dev]
-opt-level = 0
-lto = false
-codegen-units = 4
-debug = true
-debug-assertions = true
-rpath = false
-
-[profile.release]
-opt-level = 3
lto = true
codegen-units = 1
-debug = false
-debug-assertions = false
-rpath = false
[profile.test]
opt-level = 1
-lto = false
-codegen-units = 4
-debug = true
-debug-assertions = true
-rpath = false
-[dependencies.atty]
-version = "0.2.2"
+
+[lib]
+bench = false
+
+[[example]]
+name = "demo"
+required-features = ["derive"]
+
+[[example]]
+name = "cargo-example"
+required-features = ["cargo"]
+
+[[example]]
+name = "cargo-example-derive"
+required-features = ["derive"]
+
+[[example]]
+name = "escaped-positional"
+required-features = ["cargo"]
+
+[[example]]
+name = "escaped-positional-derive"
+required-features = ["derive"]
+
+[[example]]
+name = "find"
+required-features = ["cargo"]
+
+[[example]]
+name = "git-derive"
+required-features = ["derive"]
+
+[[example]]
+name = "typed-derive"
+required-features = ["derive"]
+
+[[example]]
+name = "busybox"
+path = "examples/multicall-busybox.rs"
+
+[[example]]
+name = "hostname"
+path = "examples/multicall-hostname.rs"
+
+[[example]]
+name = "repl"
+path = "examples/repl.rs"
+required-features = ["help"]
+
+[[example]]
+name = "01_quick"
+path = "examples/tutorial_builder/01_quick.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "02_apps"
+path = "examples/tutorial_builder/02_apps.rs"
+
+[[example]]
+name = "02_crate"
+path = "examples/tutorial_builder/02_crate.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "02_app_settings"
+path = "examples/tutorial_builder/02_app_settings.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_01_flag_bool"
+path = "examples/tutorial_builder/03_01_flag_bool.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_01_flag_count"
+path = "examples/tutorial_builder/03_01_flag_count.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_02_option"
+path = "examples/tutorial_builder/03_02_option.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_02_option_mult"
+path = "examples/tutorial_builder/03_02_option_mult.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_03_positional"
+path = "examples/tutorial_builder/03_03_positional.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_03_positional_mult"
+path = "examples/tutorial_builder/03_03_positional_mult.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_04_subcommands"
+path = "examples/tutorial_builder/03_04_subcommands.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_05_default_values"
+path = "examples/tutorial_builder/03_05_default_values.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_01_possible"
+path = "examples/tutorial_builder/04_01_possible.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_01_enum"
+path = "examples/tutorial_builder/04_01_enum.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_02_parse"
+path = "examples/tutorial_builder/04_02_parse.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_02_validate"
+path = "examples/tutorial_builder/04_02_validate.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_03_relations"
+path = "examples/tutorial_builder/04_03_relations.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_04_custom"
+path = "examples/tutorial_builder/04_04_custom.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "05_01_assert"
+path = "examples/tutorial_builder/05_01_assert.rs"
+test = true
+required-features = ["cargo"]
+
+[[example]]
+name = "01_quick_derive"
+path = "examples/tutorial_derive/01_quick.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "02_apps_derive"
+path = "examples/tutorial_derive/02_apps.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "02_crate_derive"
+path = "examples/tutorial_derive/02_crate.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "02_app_settings_derive"
+path = "examples/tutorial_derive/02_app_settings.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_01_flag_bool_derive"
+path = "examples/tutorial_derive/03_01_flag_bool.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_01_flag_count_derive"
+path = "examples/tutorial_derive/03_01_flag_count.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_02_option_derive"
+path = "examples/tutorial_derive/03_02_option.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_02_option_mult_derive"
+path = "examples/tutorial_derive/03_02_option_mult.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_03_positional_derive"
+path = "examples/tutorial_derive/03_03_positional.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_03_positional_mult_derive"
+path = "examples/tutorial_derive/03_03_positional_mult.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_04_subcommands_derive"
+path = "examples/tutorial_derive/03_04_subcommands.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_04_subcommands_alt_derive"
+path = "examples/tutorial_derive/03_04_subcommands_alt.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_05_default_values_derive"
+path = "examples/tutorial_derive/03_05_default_values.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_01_enum_derive"
+path = "examples/tutorial_derive/04_01_enum.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_02_parse_derive"
+path = "examples/tutorial_derive/04_02_parse.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_02_validate_derive"
+path = "examples/tutorial_derive/04_02_validate.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_03_relations_derive"
+path = "examples/tutorial_derive/04_03_relations.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_04_custom_derive"
+path = "examples/tutorial_derive/04_04_custom.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "05_01_assert_derive"
+path = "examples/tutorial_derive/05_01_assert.rs"
+test = true
+required-features = ["derive"]
+
+[[example]]
+name = "interop_augment_args"
+path = "examples/derive_ref/augment_args.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "interop_augment_subcommands"
+path = "examples/derive_ref/augment_subcommands.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "interop_hand_subcommand"
+path = "examples/derive_ref/hand_subcommand.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "interop_flatten_hand_args"
+path = "examples/derive_ref/flatten_hand_args.rs"
+required-features = ["derive"]
+
+[dependencies.backtrace]
+version = "0.3"
optional = true
[dependencies.bitflags]
-version = "1.0"
+version = "1.2"
-[dependencies.clippy]
-version = "~0.0.166"
+[dependencies.clap_derive]
+version = "=4.1.8"
optional = true
-[dependencies.strsim]
-version = "0.8"
+[dependencies.clap_lex]
+version = "0.3.0"
+
+[dependencies.is-terminal]
+version = "0.4.1"
optional = true
-[dependencies.terminal_size]
-version = "0.1.12"
+[dependencies.once_cell]
+version = "1.12.0"
optional = true
-[dependencies.textwrap]
-version = "0.13"
-default-features = false
-features = []
+[dependencies.strsim]
+version = "0.10"
+optional = true
-[dependencies.unicode-width]
-version = "0.1"
+[dependencies.termcolor]
+version = "1.1.1"
optional = true
-[dependencies.vec_map]
-version = "0.8"
+[dependencies.terminal_size]
+version = "0.2.1"
optional = true
-[dependencies.yaml-rust]
-version = "0.3.5"
+[dependencies.unicase]
+version = "2.6"
+optional = true
+
+[dependencies.unicode-width]
+version = "0.1.9"
optional = true
-[dev-dependencies.lazy_static]
-version = "1.3"
-[dev-dependencies.regex]
+[dev-dependencies.humantime]
+version = "2"
+
+[dev-dependencies.rustversion]
version = "1"
-[dev-dependencies.version-sync]
-version = "0.8"
+[dev-dependencies.shlex]
+version = "1.1.0"
-[features]
-color = ["ansi_term", "atty"]
-debug = []
-default = ["suggestions", "color", "vec_map"]
-doc = ["yaml"]
-lints = ["clippy"]
-nightly = []
-no_cargo = []
-suggestions = ["strsim"]
-unstable = []
-wrap_help = ["terminal_size", "textwrap/terminal_size"]
-unicode_help= ["unicode-width", "textwrap/unicode-width"] # Enable if any unicode in help message
-yaml = ["yaml-rust"]
-[target."cfg(not(windows))".dependencies.ansi_term]
-version = "0.11"
-optional = true
-[badges.appveyor]
-repository = "clap-rs/clap"
+[dev-dependencies.snapbox]
+version = "0.4"
-[badges.coveralls]
-branch = "master"
-repository = "clap-rs/clap"
+[dev-dependencies.static_assertions]
+version = "1.1.0"
-[badges.is-it-maintained-issue-resolution]
-repository = "clap-rs/clap"
+[dev-dependencies.trybuild]
+version = "1.0.73"
-[badges.is-it-maintained-open-issues]
-repository = "clap-rs/clap"
+[dev-dependencies.trycmd]
+version = "0.14.9"
+features = [
+ "color-auto",
+ "diff",
+ "examples",
+]
+default-features = false
-[badges.maintenance]
-status = "actively-developed"
+[dev-dependencies.unic-emoji-char]
+version = "0.9.0"
-[badges.travis-ci]
-repository = "clap-rs/clap"
+[features]
+cargo = ["dep:once_cell"]
+color = [
+ "dep:is-terminal",
+ "dep:termcolor",
+]
+debug = [
+ "clap_derive?/debug",
+ "dep:backtrace",
+]
+default = [
+ "std",
+ "color",
+ "help",
+ "usage",
+ "error-context",
+ "suggestions",
+]
+deprecated = ["clap_derive?/deprecated"]
+derive = [
+ "dep:clap_derive",
+ "dep:once_cell",
+]
+env = []
+error-context = []
+help = []
+std = []
+string = []
+suggestions = [
+ "dep:strsim",
+ "error-context",
+]
+unicode = [
+ "dep:unicode-width",
+ "dep:unicase",
+]
+unstable-doc = [
+ "derive",
+ "cargo",
+ "wrap_help",
+ "env",
+ "unicode",
+ "string",
+ "unstable-replace",
+]
+unstable-grouped = []
+unstable-replace = []
+unstable-v5 = [
+ "clap_derive?/unstable-v5",
+ "deprecated",
+]
+usage = []
+wrap_help = [
+ "help",
+ "dep:terminal_size",
+]
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
new file mode 100644
index 0000000..fac36f6
--- /dev/null
+++ b/Cargo.toml.orig
@@ -0,0 +1,384 @@
+[workspace]
+members = [
+ "clap_bench",
+ "clap_derive",
+ "clap_lex",
+ "clap_complete",
+ "clap_complete_fig",
+ "clap_mangen",
+]
+
+[workspace.package]
+license = "MIT OR Apache-2.0"
+edition = "2021"
+rust-version = "1.64.0" # MSRV
+include = [
+ "build.rs",
+ "src/**/*",
+ "Cargo.toml",
+ "LICENSE*",
+ "README.md",
+ "benches/**/*",
+ "examples/**/*"
+]
+
+[package]
+name = "clap"
+version = "4.1.8"
+description = "A simple to use, efficient, and full-featured Command Line Argument Parser"
+repository = "https://github.com/clap-rs/clap"
+categories = ["command-line-interface"]
+keywords = [
+ "argument",
+ "cli",
+ "arg",
+ "parser",
+ "parse"
+]
+license.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+include.workspace = true
+
+[package.metadata.docs.rs]
+features = ["unstable-doc"]
+rustdoc-args = ["--cfg", "docsrs"]
+cargo-args = ["-Zunstable-options", "-Zrustdoc-scrape-examples"]
+
+[package.metadata.playground]
+features = ["unstable-doc"]
+
+[package.metadata.release]
+shared-version = true
+tag-name = "v{{version}}"
+pre-release-replacements = [
+ {file="CHANGELOG.md", search="Unreleased", replace="{{version}}", min=1},
+ {file="CHANGELOG.md", search="\\.\\.\\.HEAD", replace="...{{tag_name}}", exactly=1},
+ {file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}", min=1},
+ {file="CHANGELOG.md", search="<!-- next-header -->", replace="<!-- next-header -->\n## [Unreleased] - ReleaseDate\n", exactly=1},
+ {file="CHANGELOG.md", search="<!-- next-url -->", replace="<!-- next-url -->\n[Unreleased]: https://github.com/clap-rs/clap/compare/{{tag_name}}...HEAD", exactly=1},
+]
+
+[features]
+default = [
+ "std",
+ "color",
+ "help",
+ "usage",
+ "error-context",
+ "suggestions",
+]
+debug = ["clap_derive?/debug", "dep:backtrace"] # Enables debug messages
+unstable-doc = ["derive", "cargo", "wrap_help", "env", "unicode", "string", "unstable-replace"] # for docs.rs
+
+# Used in default
+std = [] # support for no_std in a backwards-compatible way
+color = ["dep:is-terminal", "dep:termcolor"]
+help = []
+usage = []
+error-context = []
+suggestions = ["dep:strsim", "error-context"]
+
+# Optional
+deprecated = ["clap_derive?/deprecated"] # Guided experience to prepare for next breaking release (at different stages of development, this may become default)
+derive = ["dep:clap_derive", "dep:once_cell"]
+cargo = ["dep:once_cell"] # Disable if you're not using Cargo, enables Cargo-env-var-dependent macros
+wrap_help = ["help", "dep:terminal_size"]
+env = [] # Use environment variables during arg parsing
+unicode = ["dep:unicode-width", "dep:unicase"] # Support for unicode characters in arguments and help messages
+string = [] # Allow runtime generated strings
+
+# In-work features
+unstable-replace = []
+unstable-grouped = []
+unstable-v5 = ["clap_derive?/unstable-v5", "deprecated"]
+
+[lib]
+bench = false
+
+[dependencies]
+clap_derive = { path = "./clap_derive", version = "=4.1.8", optional = true }
+clap_lex = { path = "./clap_lex", version = "0.3.0" }
+bitflags = "1.2"
+unicase = { version = "2.6", optional = true }
+strsim = { version = "0.10", optional = true }
+is-terminal = { version = "0.4.1", optional = true }
+termcolor = { version = "1.1.1", optional = true }
+terminal_size = { version = "0.2.1", optional = true }
+backtrace = { version = "0.3", optional = true }
+unicode-width = { version = "0.1.9", optional = true }
+once_cell = { version = "1.12.0", optional = true }
+
+[dev-dependencies]
+trybuild = "1.0.73"
+rustversion = "1"
+# Cutting out `filesystem` feature
+trycmd = { version = "0.14.9", default-features = false, features = ["color-auto", "diff", "examples"] }
+humantime = "2"
+snapbox = "0.4"
+shlex = "1.1.0"
+static_assertions = "1.1.0"
+unic-emoji-char = "0.9.0"
+
+[[example]]
+name = "demo"
+required-features = ["derive"]
+
+[[example]]
+name = "cargo-example"
+required-features = ["cargo"]
+
+[[example]]
+name = "cargo-example-derive"
+required-features = ["derive"]
+
+[[example]]
+name = "escaped-positional"
+required-features = ["cargo"]
+
+[[example]]
+name = "escaped-positional-derive"
+required-features = ["derive"]
+
+[[example]]
+name = "find"
+required-features = ["cargo"]
+
+[[example]]
+name = "git-derive"
+required-features = ["derive"]
+
+[[example]]
+name = "typed-derive"
+required-features = ["derive"]
+
+[[example]]
+name = "busybox"
+path = "examples/multicall-busybox.rs"
+
+[[example]]
+name = "hostname"
+path = "examples/multicall-hostname.rs"
+
+[[example]]
+name = "repl"
+path = "examples/repl.rs"
+required-features = ["help"]
+
+[[example]]
+name = "01_quick"
+path = "examples/tutorial_builder/01_quick.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "02_apps"
+path = "examples/tutorial_builder/02_apps.rs"
+
+[[example]]
+name = "02_crate"
+path = "examples/tutorial_builder/02_crate.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "02_app_settings"
+path = "examples/tutorial_builder/02_app_settings.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_01_flag_bool"
+path = "examples/tutorial_builder/03_01_flag_bool.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_01_flag_count"
+path = "examples/tutorial_builder/03_01_flag_count.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_02_option"
+path = "examples/tutorial_builder/03_02_option.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_02_option_mult"
+path = "examples/tutorial_builder/03_02_option_mult.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_03_positional"
+path = "examples/tutorial_builder/03_03_positional.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_03_positional_mult"
+path = "examples/tutorial_builder/03_03_positional_mult.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_04_subcommands"
+path = "examples/tutorial_builder/03_04_subcommands.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "03_05_default_values"
+path = "examples/tutorial_builder/03_05_default_values.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_01_possible"
+path = "examples/tutorial_builder/04_01_possible.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_01_enum"
+path = "examples/tutorial_builder/04_01_enum.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_02_parse"
+path = "examples/tutorial_builder/04_02_parse.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_02_validate"
+path = "examples/tutorial_builder/04_02_validate.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_03_relations"
+path = "examples/tutorial_builder/04_03_relations.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "04_04_custom"
+path = "examples/tutorial_builder/04_04_custom.rs"
+required-features = ["cargo"]
+
+[[example]]
+name = "05_01_assert"
+path = "examples/tutorial_builder/05_01_assert.rs"
+required-features = ["cargo"]
+test = true
+
+[[example]]
+name = "01_quick_derive"
+path = "examples/tutorial_derive/01_quick.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "02_apps_derive"
+path = "examples/tutorial_derive/02_apps.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "02_crate_derive"
+path = "examples/tutorial_derive/02_crate.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "02_app_settings_derive"
+path = "examples/tutorial_derive/02_app_settings.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_01_flag_bool_derive"
+path = "examples/tutorial_derive/03_01_flag_bool.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_01_flag_count_derive"
+path = "examples/tutorial_derive/03_01_flag_count.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_02_option_derive"
+path = "examples/tutorial_derive/03_02_option.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_02_option_mult_derive"
+path = "examples/tutorial_derive/03_02_option_mult.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_03_positional_derive"
+path = "examples/tutorial_derive/03_03_positional.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_03_positional_mult_derive"
+path = "examples/tutorial_derive/03_03_positional_mult.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_04_subcommands_derive"
+path = "examples/tutorial_derive/03_04_subcommands.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_04_subcommands_alt_derive"
+path = "examples/tutorial_derive/03_04_subcommands_alt.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "03_05_default_values_derive"
+path = "examples/tutorial_derive/03_05_default_values.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_01_enum_derive"
+path = "examples/tutorial_derive/04_01_enum.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_02_parse_derive"
+path = "examples/tutorial_derive/04_02_parse.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_02_validate_derive"
+path = "examples/tutorial_derive/04_02_validate.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_03_relations_derive"
+path = "examples/tutorial_derive/04_03_relations.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "04_04_custom_derive"
+path = "examples/tutorial_derive/04_04_custom.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "05_01_assert_derive"
+path = "examples/tutorial_derive/05_01_assert.rs"
+required-features = ["derive"]
+test = true
+
+[[example]]
+name = "interop_augment_args"
+path = "examples/derive_ref/augment_args.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "interop_augment_subcommands"
+path = "examples/derive_ref/augment_subcommands.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "interop_hand_subcommand"
+path = "examples/derive_ref/hand_subcommand.rs"
+required-features = ["derive"]
+
+[[example]]
+name = "interop_flatten_hand_args"
+path = "examples/derive_ref/flatten_hand_args.rs"
+required-features = ["derive"]
+
+[profile.test]
+opt-level = 1
+
+[profile.bench]
+lto = true
+codegen-units = 1
diff --git a/LICENSE b/LICENSE
index 7f9a88e..6b579aa 120000
--- a/LICENSE
+++ b/LICENSE
@@ -1 +1 @@
-LICENSE-MIT \ No newline at end of file
+LICENSE-APACHE \ No newline at end of file
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/LICENSE-MIT b/LICENSE-MIT
index 5acedf0..7b05b84 100644
--- a/LICENSE-MIT
+++ b/LICENSE-MIT
@@ -1,6 +1,6 @@
The MIT License (MIT)
-Copyright (c) 2015-2016 Kevin B. Knapp
+Copyright (c) 2015-2022 Kevin B. Knapp and Clap Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/METADATA b/METADATA
index ba73a38..ac42e03 100644
--- a/METADATA
+++ b/METADATA
@@ -1,3 +1,7 @@
+# This project was upgraded with external_updater.
+# Usage: tools/external_updater/updater.sh update rust/crates/clap
+# For more info, check https://cs.android.com/android/platform/superproject/+/master:tools/external_updater/README.md
+
name: "clap"
description: "A simple to use, efficient, and full-featured Command Line Argument Parser"
third_party {
@@ -7,13 +11,13 @@ third_party {
}
url {
type: ARCHIVE
- value: "https://static.crates.io/crates/clap/clap-2.33.3.crate"
+ value: "https://static.crates.io/crates/clap/clap-4.1.8.crate"
}
- version: "2.33.3"
+ version: "4.1.8"
license_type: NOTICE
last_upgrade_date {
- year: 2020
- month: 11
- day: 3
+ year: 2023
+ month: 3
+ day: 2
}
}
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/MODULE_LICENSE_APACHE2
diff --git a/NOTICE b/NOTICE
deleted file mode 120000
index 7a694c9..0000000
--- a/NOTICE
+++ /dev/null
@@ -1 +0,0 @@
-LICENSE \ No newline at end of file
diff --git a/OWNERS b/OWNERS
index 46fc303..45dc4dd 100644
--- a/OWNERS
+++ b/OWNERS
@@ -1 +1 @@
-include platform/prebuilts/rust:/OWNERS
+include platform/prebuilts/rust:master:/OWNERS
diff --git a/README.md b/README.md
index e3a9142..b1298f8 100644
--- a/README.md
+++ b/README.md
@@ -1,542 +1,43 @@
-clap
-====
+# clap
-[![Crates.io](https://img.shields.io/crates/v/clap.svg)](https://crates.io/crates/clap) [![Crates.io](https://img.shields.io/crates/d/clap.svg)](https://crates.io/crates/clap) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/clap-rs/clap/blob/master/LICENSE-MIT) [![Coverage Status](https://coveralls.io/repos/kbknapp/clap-rs/badge.svg?branch=master&service=github)](https://coveralls.io/github/kbknapp/clap-rs?branch=master) [![Join the chat at https://gitter.im/kbknapp/clap-rs](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/kbknapp/clap-rs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+> **Command Line Argument Parser for Rust**
-Linux: [![Build Status](https://travis-ci.org/clap-rs/clap.svg?branch=master)](https://travis-ci.org/clap-rs/clap)
-Windows: [![Build status](https://ci.appveyor.com/api/projects/status/ejg8c33dn31nhv36/branch/master?svg=true)](https://ci.appveyor.com/project/kbknapp/clap-rs/branch/master)
+[![Crates.io](https://img.shields.io/crates/v/clap?style=flat-square)](https://crates.io/crates/clap)
+[![Crates.io](https://img.shields.io/crates/d/clap?style=flat-square)](https://crates.io/crates/clap)
+[![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](LICENSE-APACHE)
+[![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](LICENSE-MIT)
+[![Build Status](https://img.shields.io/github/actions/workflow/status/clap-rs/clap/ci.yml?branch=master&style=flat-square)](https://github.com/clap-rs/clap/actions/workflows/ci.yml?query=branch%3Amaster)
+[![Coverage Status](https://img.shields.io/coveralls/github/clap-rs/clap/master?style=flat-square)](https://coveralls.io/github/clap-rs/clap?branch=master)
+[![Contributors](https://img.shields.io/github/contributors/clap-rs/clap?style=flat-square)](https://github.com/clap-rs/clap/graphs/contributors)
-Command Line Argument Parser for Rust
-
-It is a simple-to-use, efficient, and full-featured library for parsing command line arguments and subcommands when writing console/terminal applications.
-
-* [documentation](https://docs.rs/clap/)
-* [website](https://clap.rs/)
-* [video tutorials](https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U)
-
-Table of Contents
-=================
-
-* [About](#about)
-* [FAQ](#faq)
-* [Features](#features)
-* [Quick Example](#quick-example)
-* [Try it!](#try-it)
- * [Pre-Built Test](#pre-built-test)
- * [BYOB (Build Your Own Binary)](#byob-build-your-own-binary)
-* [Usage](#usage)
- * [Optional Dependencies / Features](#optional-dependencies--features)
- * [Dependencies Tree](#dependencies-tree)
- * [More Information](#more-information)
- * [Video Tutorials](#video-tutorials)
-* [How to Contribute](#how-to-contribute)
- * [Compatibility Policy](#compatibility-policy)
- * [Minimum Version of Rust](#minimum-version-of-rust)
-* [Related Crates](#related-crates)
-* [License](#license)
-* [Recent Breaking Changes](#recent-breaking-changes)
- * [Deprecations](#deprecations)
-
-Created by [gh-md-toc](https://github.com/ekalinin/github-markdown-toc)
+Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT).
## About
-`clap` is used to parse *and validate* the string of command line arguments provided by a user at runtime. You provide the list of valid possibilities, and `clap` handles the rest. This means you focus on your *applications* functionality, and less on the parsing and validating of arguments.
-
-`clap` provides many things 'for free' (with no configuration) including the traditional version and help switches (or flags) along with associated messages. If you are using subcommands, `clap` will also auto-generate a `help` subcommand and separate associated help messages.
-
-Once `clap` parses the user provided string of arguments, it returns the matches along with any applicable values. If the user made an error or typo, `clap` informs them with a friendly message and exits gracefully (or returns a `Result` type and allows you to perform any clean up prior to exit). Because of this, you can make reasonable assumptions in your code about the validity of the arguments prior to your applications main execution.
-
-## FAQ
-
-For a full FAQ and more in depth details, see [the wiki page](https://github.com/clap-rs/clap/wiki/FAQ)
-
-### Comparisons
-
-First, let me say that these comparisons are highly subjective, and not meant in a critical or harsh manner. All the argument parsing libraries out there (to include `clap`) have their own strengths and weaknesses. Sometimes it just comes down to personal taste when all other factors are equal. When in doubt, try them all and pick one that you enjoy :) There's plenty of room in the Rust community for multiple implementations!
-
-#### How does `clap` compare to [getopts](https://github.com/rust-lang-nursery/getopts)?
-
-`getopts` is a very basic, fairly minimalist argument parsing library. This isn't a bad thing, sometimes you don't need tons of features, you just want to parse some simple arguments, and have some help text generated for you based on valid arguments you specify. The downside to this approach is that you must manually implement most of the common features (such as checking to display help messages, usage strings, etc.). If you want a highly custom argument parser, and don't mind writing the majority of the functionality yourself, `getopts` is an excellent base.
-
-`getopts` also doesn't allocate much, or at all. This gives it a very small performance boost. Although, as you start implementing additional features, that boost quickly disappears.
-
-Personally, I find many, many uses of `getopts` are manually implementing features that `clap` provides by default. Using `clap` simplifies your codebase allowing you to focus on your application, and not argument parsing.
-
-#### How does `clap` compare to [docopt.rs](https://github.com/docopt/docopt.rs)?
-
-I first want to say I'm a big a fan of BurntSushi's work, the creator of `Docopt.rs`. I aspire to produce the quality of libraries that this man does! When it comes to comparing these two libraries they are very different. `docopt` tasks you with writing a help message, and then it parsers that message for you to determine all valid arguments and their use. Some people LOVE this approach, others do not. If you're willing to write a detailed help message, it's nice that you can stick that in your program and have `docopt` do the rest. On the downside, it's far less flexible.
-
-`docopt` is also excellent at translating arguments into Rust types automatically. There is even a syntax extension which will do all this for you, if you're willing to use a nightly compiler (use of a stable compiler requires you to somewhat manually translate from arguments to Rust types). To use BurntSushi's words, `docopt` is also a sort of black box. You get what you get, and it's hard to tweak implementation or customize the experience for your use case.
-
-Because `docopt` is doing a ton of work to parse your help messages and determine what you were trying to communicate as valid arguments, it's also one of the more heavy weight parsers performance-wise. For most applications this isn't a concern and this isn't to say `docopt` is slow, in fact far from it. This is just something to keep in mind while comparing.
-
-#### All else being equal, what are some reasons to use `clap`? (The Pitch)
-
-`clap` is as fast, and as lightweight as possible while still giving all the features you'd expect from a modern argument parser. In fact, for the amount and type of features `clap` offers it remains about as fast as `getopts`. If you use `clap` when just need some simple arguments parsed, you'll find it's a walk in the park. `clap` also makes it possible to represent extremely complex, and advanced requirements, without too much thought. `clap` aims to be intuitive, easy to use, and fully capable for wide variety use cases and needs.
-
-#### All else being equal, what are some reasons *not* to use `clap`? (The Anti Pitch)
-
-Depending on the style in which you choose to define the valid arguments, `clap` can be very verbose. `clap` also offers so many fine-tuning knobs and dials, that learning everything can seem overwhelming. I strive to keep the simple cases simple, but when turning all those custom dials it can get complex. `clap` is also opinionated about parsing. Even though so much can be tweaked and tuned with `clap` (and I'm adding more all the time), there are still certain features which `clap` implements in specific ways which may be contrary to some users use-cases. Finally, `clap` is "stringly typed" when referring to arguments which can cause typos in code. This particular paper-cut is being actively worked on, and should be gone in v3.x.
-
-## Features
-
-Below are a few of the features which `clap` supports, full descriptions and usage can be found in the [documentation](https://docs.rs/clap/) and [examples/](examples) directory
-
-* **Auto-generated Help, Version, and Usage information**
- - Can optionally be fully, or partially overridden if you want a custom help, version, or usage statements
-* **Auto-generated completion scripts at compile time (Bash, Zsh, Fish, and PowerShell)**
- - Even works through many multiple levels of subcommands
- - Works with options which only accept certain values
- - Works with subcommand aliases
-* **Flags / Switches** (i.e. bool fields)
- - Both short and long versions supported (i.e. `-f` and `--flag` respectively)
- - Supports combining short versions (i.e. `-fBgoZ` is the same as `-f -B -g -o -Z`)
- - Supports multiple occurrences (i.e. `-vvv` or `-v -v -v`)
-* **Positional Arguments** (i.e. those which are based off an index from the program name)
- - Supports multiple values (i.e. `myprog <file>...` such as `myprog file1.txt file2.txt` being two values for the same "file" argument)
- - Supports Specific Value Sets (See below)
- - Can set value parameters (such as the minimum number of values, the maximum number of values, or the exact number of values)
- - Can set custom validations on values to extend the argument parsing capability to truly custom domains
-* **Option Arguments** (i.e. those that take values)
- - Both short and long versions supported (i.e. `-o value`, `-ovalue`, `-o=value` and `--option value` or `--option=value` respectively)
- - Supports multiple values (i.e. `-o <val1> -o <val2>` or `-o <val1> <val2>`)
- - Supports delimited values (i.e. `-o=val1,val2,val3`, can also change the delimiter)
- - Supports Specific Value Sets (See below)
- - Supports named values so that the usage/help info appears as `-o <FILE> <INTERFACE>` etc. for when you require specific multiple values
- - Can set value parameters (such as the minimum number of values, the maximum number of values, or the exact number of values)
- - Can set custom validations on values to extend the argument parsing capability to truly custom domains
-* **Sub-Commands** (i.e. `git add <file>` where `add` is a sub-command of `git`)
- - Support their own sub-arguments, and sub-sub-commands independent of the parent
- - Get their own auto-generated Help, Version, and Usage independent of parent
-* **Support for building CLIs from YAML** - This keeps your Rust source nice and tidy and makes supporting localized translation very simple!
-* **Requirement Rules**: Arguments can define the following types of requirement rules
- - Can be required by default
- - Can be required only if certain arguments are present
- - Can require other arguments to be present
- - Can be required only if certain values of other arguments are used
-* **Confliction Rules**: Arguments can optionally define the following types of exclusion rules
- - Can be disallowed when certain arguments are present
- - Can disallow use of other arguments when present
-* **Groups**: Arguments can be made part of a group
- - Fully compatible with other relational rules (requirements, conflicts, and overrides) which allows things like requiring the use of any arg in a group, or denying the use of an entire group conditionally
-* **Specific Value Sets**: Positional or Option Arguments can define a specific set of allowed values (i.e. imagine a `--mode` option which may *only* have one of two values `fast` or `slow` such as `--mode fast` or `--mode slow`)
-* **Default Values**
- - Also supports conditional default values (i.e. a default which only applies if specific arguments are used, or specific values of those arguments)
-* **Automatic Version from Cargo.toml**: `clap` is fully compatible with Rust's `env!()` macro for automatically setting the version of your application to the version in your Cargo.toml. See [09_auto_version example](examples/09_auto_version.rs) for how to do this (Thanks to [jhelwig](https://github.com/jhelwig) for pointing this out)
-* **Typed Values**: You can use several convenience macros provided by `clap` to get typed values (i.e. `i32`, `u8`, etc.) from positional or option arguments so long as the type you request implements `std::str::FromStr` See the [12_typed_values example](examples/12_typed_values.rs). You can also use `clap`s `arg_enum!` macro to create an enum with variants that automatically implement `std::str::FromStr`. See [13a_enum_values_automatic example](examples/13a_enum_values_automatic.rs) for details
-* **Suggestions**: Suggests corrections when the user enters a typo. For example, if you defined a `--myoption` argument, and the user mistakenly typed `--moyption` (notice `y` and `o` transposed), they would receive a `Did you mean '--myoption'?` error and exit gracefully. This also works for subcommands and flags. (Thanks to [Byron](https://github.com/Byron) for the implementation) (This feature can optionally be disabled, see 'Optional Dependencies / Features')
-* **Colorized Errors (Non Windows OS only)**: Error message are printed in in colored text (this feature can optionally be disabled, see 'Optional Dependencies / Features').
-* **Global Arguments**: Arguments can optionally be defined once, and be available to all child subcommands. There values will also be propagated up/down throughout all subcommands.
-* **Custom Validations**: You can define a function to use as a validator of argument values. Imagine defining a function to validate IP addresses, or fail parsing upon error. This means your application logic can be solely focused on *using* values.
-* **POSIX Compatible Conflicts/Overrides** - In POSIX args can be conflicting, but not fail parsing because whichever arg comes *last* "wins" so to speak. This allows things such as aliases (i.e. `alias ls='ls -l'` but then using `ls -C` in your terminal which ends up passing `ls -l -C` as the final arguments. Since `-l` and `-C` aren't compatible, this effectively runs `ls -C` in `clap` if you choose...`clap` also supports hard conflicts that fail parsing). (Thanks to [Vinatorul](https://github.com/Vinatorul)!)
-* Supports the Unix `--` meaning, only positional arguments follow
-
-## Quick Example
-
-The following examples show a quick example of some of the very basic functionality of `clap`. For more advanced usage, such as requirements, conflicts, groups, multiple values and occurrences see the [documentation](https://docs.rs/clap/), [examples/](examples) directory of this repository or the [video tutorials](https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U).
-
- **NOTE:** All of these examples are functionally the same, but show different styles in which to use `clap`. These different styles are purely a matter of personal preference.
-
-The first example shows a method using the 'Builder Pattern' which allows more advanced configuration options (not shown in this small example), or even dynamically generating arguments when desired.
-
-```rust
-// (Full example with detailed comments in examples/01b_quick_example.rs)
-//
-// This example demonstrates clap's full 'builder pattern' style of creating arguments which is
-// more verbose, but allows easier editing, and at times more advanced options, or the possibility
-// to generate arguments dynamically.
-extern crate clap;
-use clap::{Arg, App, SubCommand};
-
-fn main() {
- let matches = App::new("My Super Program")
- .version("1.0")
- .author("Kevin K. <kbknapp@gmail.com>")
- .about("Does awesome things")
- .arg(Arg::with_name("config")
- .short("c")
- .long("config")
- .value_name("FILE")
- .help("Sets a custom config file")
- .takes_value(true))
- .arg(Arg::with_name("INPUT")
- .help("Sets the input file to use")
- .required(true)
- .index(1))
- .arg(Arg::with_name("v")
- .short("v")
- .multiple(true)
- .help("Sets the level of verbosity"))
- .subcommand(SubCommand::with_name("test")
- .about("controls testing features")
- .version("1.3")
- .author("Someone E. <someone_else@other.com>")
- .arg(Arg::with_name("debug")
- .short("d")
- .help("print debug information verbosely")))
- .get_matches();
-
- // Gets a value for config if supplied by user, or defaults to "default.conf"
- let config = matches.value_of("config").unwrap_or("default.conf");
- println!("Value for config: {}", config);
-
- // Calling .unwrap() is safe here because "INPUT" is required (if "INPUT" wasn't
- // required we could have used an 'if let' to conditionally get the value)
- println!("Using input file: {}", matches.value_of("INPUT").unwrap());
-
- // Vary the output based on how many times the user used the "verbose" flag
- // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v'
- match matches.occurrences_of("v") {
- 0 => println!("No verbose info"),
- 1 => println!("Some verbose info"),
- 2 => println!("Tons of verbose info"),
- 3 | _ => println!("Don't be crazy"),
- }
-
- // You can handle information about subcommands by requesting their matches by name
- // (as below), requesting just the name used, or both at the same time
- if let Some(matches) = matches.subcommand_matches("test") {
- if matches.is_present("debug") {
- println!("Printing debug info...");
- } else {
- println!("Printing normally...");
- }
- }
-
- // more program logic goes here...
-}
-```
-
-One could also optionally declare their CLI in YAML format and keep your Rust source tidy
-or support multiple localized translations by having different YAML files for each localization.
-
-First, create the `cli.yml` file to hold your CLI options, but it could be called anything we like:
-
-```yaml
-name: myapp
-version: "1.0"
-author: Kevin K. <kbknapp@gmail.com>
-about: Does awesome things
-args:
- - config:
- short: c
- long: config
- value_name: FILE
- help: Sets a custom config file
- takes_value: true
- - INPUT:
- help: Sets the input file to use
- required: true
- index: 1
- - verbose:
- short: v
- multiple: true
- help: Sets the level of verbosity
-subcommands:
- - test:
- about: controls testing features
- version: "1.3"
- author: Someone E. <someone_else@other.com>
- args:
- - debug:
- short: d
- help: print debug information
-```
-
-Since this feature requires additional dependencies that not everyone may want, it is *not* compiled in by default and we need to enable a feature flag in Cargo.toml:
-
-Simply change your `clap = "2.33"` to `clap = {version = "2.33", features = ["yaml"]}`.
-
-Finally we create our `main.rs` file just like we would have with the previous two examples:
-
-```rust
-// (Full example with detailed comments in examples/17_yaml.rs)
-//
-// This example demonstrates clap's building from YAML style of creating arguments which is far
-// more clean, but takes a very small performance hit compared to the other two methods.
-#[macro_use]
-extern crate clap;
-use clap::App;
-
-fn main() {
- // The YAML file is found relative to the current file, similar to how modules are found
- let yaml = load_yaml!("cli.yml");
- let matches = App::from_yaml(yaml).get_matches();
-
- // Same as previous examples...
-}
-```
-
-If you were to compile any of the above programs and run them with the flag `--help` or `-h` (or `help` subcommand, since we defined `test` as a subcommand) the following would be output
-
-```sh
-$ myprog --help
-My Super Program 1.0
-Kevin K. <kbknapp@gmail.com>
-Does awesome things
-
-USAGE:
- MyApp [FLAGS] [OPTIONS] <INPUT> [SUBCOMMAND]
-
-FLAGS:
- -h, --help Prints help information
- -v Sets the level of verbosity
- -V, --version Prints version information
-
-OPTIONS:
- -c, --config <FILE> Sets a custom config file
-
-ARGS:
- INPUT The input file to use
-
-SUBCOMMANDS:
- help Prints this message or the help of the given subcommand(s)
- test Controls testing features
-```
-
-**NOTE:** You could also run `myapp test --help` or `myapp help test` to see the help message for the `test` subcommand.
-
-There are also two other methods to create CLIs. Which style you choose is largely a matter of personal preference. The two other methods are:
-
-* Using [usage strings (examples/01a_quick_example.rs)](examples/01a_quick_example.rs) similar to (but not exact) docopt style usage statements. This is far less verbose than the above methods, but incurs a slight runtime penalty.
-* Using [a macro (examples/01c_quick_example.rs)](examples/01c_quick_example.rs) which is like a hybrid of the builder and usage string style. It's less verbose, but doesn't incur the runtime penalty of the usage string style. The downside is that it's harder to debug, and more opaque.
-
-Examples of each method can be found in the [examples/](examples) directory of this repository.
-
-## Try it!
-
-### Pre-Built Test
-
-To try out the pre-built examples, use the following steps:
-
-* Clone the repository `$ git clone https://github.com/clap-rs/clap && cd clap-rs/`
-* Compile the example `$ cargo build --example <EXAMPLE>`
-* Run the help info `$ ./target/debug/examples/<EXAMPLE> --help`
-* Play with the arguments!
-* You can also do a onetime run via `$ cargo run --example <EXAMPLE> -- [args to example]`
-
-### BYOB (Build Your Own Binary)
-
-To test out `clap`'s default auto-generated help/version follow these steps:
-* Create a new cargo project `$ cargo new fake --bin && cd fake`
-* Add `clap` to your `Cargo.toml`
-
-```toml
-[dependencies]
-clap = "2"
-```
-
-* Add the following to your `src/main.rs`
-
-```rust
-extern crate clap;
-use clap::App;
-
-fn main() {
- App::new("fake").version("v1.0-beta").get_matches();
-}
-```
-
-* Build your program `$ cargo build --release`
-* Run with help or version `$ ./target/release/fake --help` or `$ ./target/release/fake --version`
-
-## Usage
-
-For full usage, add `clap` as a dependency in your `Cargo.toml` () to use from crates.io:
-
-```toml
-[dependencies]
-clap = "~2.33"
-```
-
-(**note**: If you are concerned with supporting a minimum version of Rust that is *older* than the current stable Rust minus 2 stable releases, it's recommended to use the `~major.minor.patch` style versions in your `Cargo.toml` which will only update the patch version automatically. For more information see the [Compatibility Policy](#compatibility-policy))
-
-Then add `extern crate clap;` to your crate root.
-
-Define a list of valid arguments for your program (see the [documentation](https://docs.rs/clap/) or [examples/](examples) directory of this repo)
-
-Then run `cargo build` or `cargo update && cargo build` for your project.
-
-### Optional Dependencies / Features
-
-#### Features enabled by default
-
-* **"suggestions"**: Turns on the `Did you mean '--myoption'?` feature for when users make typos. (builds dependency `strsim`)
-* **"color"**: Turns on colored error messages. This feature only works on non-Windows OSs. (builds dependency `ansi-term` only on non-Windows targets)
-* **"vec_map"**: Use [`VecMap`](https://crates.io/crates/vec_map) internally instead of a [`BTreeMap`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html). This feature provides a _slight_ performance improvement. (builds dependency `vec_map`)
-
-To disable these, add this to your `Cargo.toml`:
-
-```toml
-[dependencies.clap]
-version = "2.33"
-default-features = false
-```
-
-You can also selectively enable only the features you'd like to include, by adding:
-
-```toml
-[dependencies.clap]
-version = "2.33"
-default-features = false
-
-# Cherry-pick the features you'd like to use
-features = [ "suggestions", "color" ]
-```
-
-#### Opt-in features
-
-* **"yaml"**: Enables building CLIs from YAML documents. (builds dependency `yaml-rust`)
-* **"unstable"**: Enables unstable `clap` features that may change from release to release
-* **"wrap_help"**: Turns on the help text wrapping feature, based on the terminal size. (builds dependency `term-size`)
-
-### Dependencies Tree
-
-The following graphic depicts `clap`s dependency graph (generated using [cargo-graph](https://github.com/kbknapp/cargo-graph)).
-
- * **Dashed** Line: Optional dependency
- * **Red** Color: **NOT** included by default (must use cargo `features` to enable)
- * **Blue** Color: Dev dependency, only used while developing.
-
-![clap dependencies](clap_dep_graph.png)
-
-### More Information
-
-You can find complete documentation on the [docs.rs](https://docs.rs/clap/) for this project.
-
-You can also find usage examples in the [examples/](examples) directory of this repo.
-
-#### Video Tutorials
-
-There's also the video tutorial series [Argument Parsing with Rust v2](https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U).
-
-These videos slowly trickle out as I finish them and currently a work in progress.
-
-## How to Contribute
-
-Details on how to contribute can be found in the [CONTRIBUTING.md](.github/CONTRIBUTING.md) file.
-
-### Compatibility Policy
-
-Because `clap` takes SemVer and compatibility seriously, this is the official policy regarding breaking changes and minimum required versions of Rust.
-
-`clap` will pin the minimum required version of Rust to the CI builds. Bumping the minimum version of Rust is considered a minor breaking change, meaning *at a minimum* the minor version of `clap` will be bumped.
-
-In order to keep from being surprised of breaking changes, it is **highly** recommended to use the `~major.minor.patch` style in your `Cargo.toml` only if you wish to target a version of Rust that is *older* than current stable minus two releases:
-
-```toml
-[dependencies]
-clap = "~2.33"
-```
-
-This will cause *only* the patch version to be updated upon a `cargo update` call, and therefore cannot break due to new features, or bumped minimum versions of Rust.
-
-#### Warning about '~' Dependencies
-
-Using `~` can cause issues in certain circumstances.
-
-From @alexcrichton:
-
-Right now Cargo's version resolution is pretty naive, it's just a brute-force search of the solution space, returning the first resolvable graph. This also means that it currently won't terminate until it proves there is not possible resolvable graph. This leads to situations where workspaces with multiple binaries, for example, have two different dependencies such as:
-
-```toml,no_sync
-
-# In one Cargo.toml
-[dependencies]
-clap = "~2.33.0"
-
-# In another Cargo.toml
-[dependencies]
-clap = "2.33.0"
-```
-
-This is inherently an unresolvable crate graph in Cargo right now. Cargo requires there's only one major version of a crate, and being in the same workspace these two crates must share a version. This is impossible in this location, though, as these version constraints cannot be met.
-
-#### Minimum Version of Rust
-
-`clap` will officially support current stable Rust, minus two releases, but may work with prior releases as well. For example, current stable Rust at the time of this writing is 1.41.0, meaning `clap` is guaranteed to compile with 1.39.0 and beyond.
-
-At the 1.42.0 stable release, `clap` will be guaranteed to compile with 1.40.0 and beyond, etc.
-
-Upon bumping the minimum version of Rust (assuming it's within the stable-2 range), it *must* be clearly annotated in the `CHANGELOG.md`
-
-#### Breaking Changes
-
-`clap` takes a similar policy to Rust and will bump the major version number upon breaking changes with only the following exceptions:
-
- * The breaking change is to fix a security concern
- * The breaking change is to be fixing a bug (i.e. relying on a bug as a feature)
- * The breaking change is a feature isn't used in the wild, or all users of said feature have given approval *prior* to the change
-
-#### Compatibility with Wasm
-
-A best effort is made to ensure that `clap` will work on projects targeting `wasm32-unknown-unknown`. However there is no dedicated CI build
-covering this specific target.
-
-## License
-
-`clap` is licensed under the MIT license. Please read the [LICENSE-MIT](LICENSE-MIT) file in this repository for more information.
-
-## Related Crates
-
-There are several excellent crates which can be used with `clap`, I recommend checking them all out! If you've got a crate that would be a good fit to be used with `clap` open an issue and let me know, I'd love to add it!
-
-* [`structopt`](https://github.com/TeXitoi/structopt) - This crate allows you to define a struct, and build a CLI from it! No more "stringly typed" and it uses `clap` behind the scenes! (*Note*: There is work underway to pull this crate into mainline `clap`).
-* [`assert_cli`](https://github.com/assert-rs/assert_cli) - This crate allows you test your CLIs in a very intuitive and functional way!
+Create your command-line parser, with all of the bells and whistles, declaratively or procedurally.
-## Recent Breaking Changes
+For more details, see:
+- [docs.rs](https://docs.rs/clap/latest/clap/)
+- [examples](examples/)
-`clap` follows semantic versioning, so breaking changes should only happen upon major version bumps. The only exception to this rule is breaking changes that happen due to implementation that was deemed to be a bug, security concerns, or it can be reasonably proved to affect no code. For the full details, see [CHANGELOG.md](./CHANGELOG.md).
+## Sponsors
-As of 2.27.0:
+<!-- omit in TOC -->
+### Gold
-* Argument values now take precedence over subcommand names. This only arises by using unrestrained multiple values and subcommands together where the subcommand name can coincide with one of the multiple values. Such as `$ prog <files>... <subcommand>`. The fix is to place restraints on number of values, or disallow the use of `$ prog <prog-args> <subcommand>` structure.
+[![](https://opencollective.com/clap/tiers/gold.svg?avatarHeight=36&width=600)](https://opencollective.com/clap)
-As of 2.0.0 (From 1.x)
+<!-- omit in TOC -->
+### Silver
-* **Fewer lifetimes! Yay!**
- * `App<'a, 'b, 'c, 'd, 'e, 'f>` => `App<'a, 'b>`
- * `Arg<'a, 'b, 'c, 'd, 'e, 'f>` => `Arg<'a, 'b>`
- * `ArgMatches<'a, 'b>` => `ArgMatches<'a>`
-* **Simply Renamed**
- * `App::arg_group` => `App::group`
- * `App::arg_groups` => `App::groups`
- * `ArgGroup::add` => `ArgGroup::arg`
- * `ArgGroup::add_all` => `ArgGroup::args`
- * `ClapError` => `Error`
- * struct field `ClapError::error_type` => `Error::kind`
- * `ClapResult` => `Result`
- * `ClapErrorType` => `ErrorKind`
-* **Removed Deprecated Functions and Methods**
- * `App::subcommands_negate_reqs`
- * `App::subcommand_required`
- * `App::arg_required_else_help`
- * `App::global_version(bool)`
- * `App::versionless_subcommands`
- * `App::unified_help_messages`
- * `App::wait_on_error`
- * `App::subcommand_required_else_help`
- * `SubCommand::new`
- * `App::error_on_no_subcommand`
- * `Arg::new`
- * `Arg::mutually_excludes`
- * `Arg::mutually_excludes_all`
- * `Arg::mutually_overrides_with`
- * `simple_enum!`
-* **Renamed Error Variants**
- * `InvalidUnicode` => `InvalidUtf8`
- * `InvalidArgument` => `UnknownArgument`
-* **Usage Parser**
- * Value names can now be specified inline, i.e. `-o, --option <FILE> <FILE2> 'some option which takes two files'`
- * **There is now a priority of order to determine the name** - This is perhaps the biggest breaking change. See the documentation for full details. Prior to this change, the value name took precedence. **Ensure your args are using the proper names (i.e. typically the long or short and NOT the value name) throughout the code**
-* `ArgMatches::values_of` returns an `Values` now which implements `Iterator` (should not break any code)
-* `crate_version!` returns `&'static str` instead of `String`
+[![](https://opencollective.com/clap/tiers/silver.svg?avatarHeight=36&width=600)](https://opencollective.com/clap)
-### Deprecations
+<!-- omit in TOC -->
+### Bronze
-Old method names will be left around for several minor version bumps, or one major version bump.
+[![](https://opencollective.com/clap/tiers/bronze.svg?avatarHeight=36&width=600)](https://opencollective.com/clap)
-As of 2.27.0:
+<!-- omit in TOC -->
+### Backer
-* **AppSettings::PropagateGlobalValuesDown:** this setting deprecated and is no longer required to propagate values down or up
+[![](https://opencollective.com/clap/tiers/backer.svg?avatarHeight=36&width=600)](https://opencollective.com/clap)
diff --git a/SPONSORS.md b/SPONSORS.md
deleted file mode 100644
index 67f5544..0000000
--- a/SPONSORS.md
+++ /dev/null
@@ -1,17 +0,0 @@
-Below is a list of sponsors for the clap-rs project
-
-If you are interested in becoming a sponsor for this project please our [sponsorship page](https://clap.rs/sponsorship/).
-
-## Recurring Sponsors:
-
-| [<img alt="Noelia Seva-Gonzalez" src="https://clap.rs/wp-content/uploads/2017/10/noelia_sm-1.png" width="117">](https://noeliasg.com/about/) | [<img alt="messense" src="https://clap.rs/wp-content/uploads/2018/01/messense-400x400.png" width="117">](https://github.com/messense) | [<img alt="Josh" src="https://clap.rs/wp-content/uploads/2018/11/josh_t.jpg" width="117">](https://joshtriplett.org) | <img alt="Stephen Oats" src="https://clap.rs/wp-content/uploads/2019/03/stephenoats.png" width="117"> |
-|:-:|:-:|:-:|:-:|
-|Noelia Seva-Gonzalez | Messense | Josh Triplett | Stephen Oats |
-
-
-## Single-Donation and Former Sponsors:
-
-| [<img alt="Rob Tsuk" src="https://clap.rs/wp-content/uploads/2017/10/robtsuk_sm.png" width="117">](https://github.com/rtsuk)| | |
-|:-:|:-:|:-:|
-|Rob Tsuk| | |
-
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 07d379e..999bbcf 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -2,65 +2,37 @@
{
"imports": [
{
- "path": "external/rust/crates/base64"
- },
- {
"path": "external/rust/crates/libsqlite3-sys"
},
{
- "path": "external/rust/crates/tinytemplate"
- },
- {
- "path": "external/rust/crates/tinyvec"
- },
- {
- "path": "external/rust/crates/unicode-xid"
- }
- ],
- "presubmit": [
- {
- "name": "ZipFuseTest"
- },
- {
- "name": "apkdmverity.test"
- },
- {
- "name": "authfs_device_test_src_lib"
+ "path": "packages/modules/Virtualization/apkdmverity"
},
{
- "name": "diced_test"
+ "path": "packages/modules/Virtualization/authfs"
},
{
- "name": "keystore2_test"
+ "path": "packages/modules/Virtualization/avmd"
},
{
- "name": "keystore2_vintf_test"
- },
- {
- "name": "legacykeystore_test"
- }
- ],
- "presubmit-rust": [
- {
- "name": "ZipFuseTest"
+ "path": "packages/modules/Virtualization/encryptedstore"
},
{
- "name": "apkdmverity.test"
+ "path": "packages/modules/Virtualization/virtualizationmanager"
},
{
- "name": "authfs_device_test_src_lib"
+ "path": "packages/modules/Virtualization/vm"
},
{
- "name": "diced_test"
+ "path": "packages/modules/Virtualization/zipfuse"
},
{
- "name": "keystore2_test"
+ "path": "system/security/diced"
},
{
- "name": "keystore2_vintf_test"
+ "path": "system/security/keystore2"
},
{
- "name": "legacykeystore_test"
+ "path": "system/security/keystore2/legacykeystore"
}
]
}
diff --git a/cargo2android.json b/cargo2android.json
index a78ac00..e49ebf5 100644
--- a/cargo2android.json
+++ b/cargo2android.json
@@ -1,11 +1,6 @@
{
- "apex-available": [
- "//apex_available:platform",
- "com.android.compos",
- "com.android.virt"
- ],
"dependencies": true,
"device": true,
- "features": "",
+ "features": "derive,error-context,help,std,usage",
"run": true
-} \ No newline at end of file
+}
diff --git a/clap-test.rs b/clap-test.rs
deleted file mode 100644
index 7d57ac4..0000000
--- a/clap-test.rs
+++ /dev/null
@@ -1,86 +0,0 @@
-#[allow(unused_imports, dead_code)]
-mod test {
- use std::str;
- use std::io::{Cursor, Write};
-
- use regex::Regex;
-
- use clap::{App, Arg, SubCommand, ArgGroup};
-
- fn compare<S, S2>(l: S, r: S2) -> bool
- where S: AsRef<str>,
- S2: AsRef<str>
- {
- let re = Regex::new("\x1b[^m]*m").unwrap();
- // Strip out any mismatching \r character on windows that might sneak in on either side
- let ls = l.as_ref().trim().replace("\r", "");
- let rs = r.as_ref().trim().replace("\r", "");
- let left = re.replace_all(&*ls, "");
- let right = re.replace_all(&*rs, "");
- let b = left == right;
- if !b {
- println!();
- println!("--> left");
- println!("{}", left);
- println!("--> right");
- println!("{}", right);
- println!("--")
- }
- b
- }
-
- pub fn compare_output(l: App, args: &str, right: &str, stderr: bool) -> bool {
- let mut buf = Cursor::new(Vec::with_capacity(50));
- let res = l.get_matches_from_safe(args.split(' ').collect::<Vec<_>>());
- let err = res.unwrap_err();
- err.write_to(&mut buf).unwrap();
- let content = buf.into_inner();
- let left = String::from_utf8(content).unwrap();
- assert_eq!(stderr, err.use_stderr());
- compare(left, right)
- }
- pub fn compare_output2(l: App, args: &str, right1: &str, right2: &str, stderr: bool) -> bool {
- let mut buf = Cursor::new(Vec::with_capacity(50));
- let res = l.get_matches_from_safe(args.split(' ').collect::<Vec<_>>());
- let err = res.unwrap_err();
- err.write_to(&mut buf).unwrap();
- let content = buf.into_inner();
- let left = String::from_utf8(content).unwrap();
- assert_eq!(stderr, err.use_stderr());
- compare(&*left, right1) || compare(&*left, right2)
- }
-
- // Legacy tests from the Python script days
-
- pub fn complex_app() -> App<'static, 'static> {
- let args = "-o --option=[opt]... 'tests options'
- [positional] 'tests positionals'";
- let opt3_vals = ["fast", "slow"];
- let pos3_vals = ["vi", "emacs"];
- App::new("clap-test")
- .version("v1.4.8")
- .about("tests clap library")
- .author("Kevin K. <kbknapp@gmail.com>")
- .args_from_usage(args)
- .arg(Arg::from_usage("-f --flag... 'tests flags'")
- .global(true))
- .args(&[
- Arg::from_usage("[flag2] -F 'tests flags with exclusions'").conflicts_with("flag").requires("long-option-2"),
- Arg::from_usage("--long-option-2 [option2] 'tests long options with exclusions'").conflicts_with("option").requires("positional2"),
- Arg::from_usage("[positional2] 'tests positionals with exclusions'"),
- Arg::from_usage("-O --Option [option3] 'specific vals'").possible_values(&opt3_vals),
- Arg::from_usage("[positional3]... 'tests specific values'").possible_values(&pos3_vals),
- Arg::from_usage("--multvals [one] [two] 'Tests multiple values, not mult occs'"),
- Arg::from_usage("--multvalsmo... [one] [two] 'Tests multiple values, and mult occs'"),
- Arg::from_usage("--minvals2 [minvals]... 'Tests 2 min vals'").min_values(2),
- Arg::from_usage("--maxvals3 [maxvals]... 'Tests 3 max vals'").max_values(3)
- ])
- .subcommand(SubCommand::with_name("subcmd")
- .about("tests subcommands")
- .version("0.1")
- .author("Kevin K. <kbknapp@gmail.com>")
- .arg_from_usage("-o --option [scoption]... 'tests options'")
- .arg_from_usage("-s --subcmdarg [subcmdarg] 'tests other args'")
- .arg_from_usage("[scpositional] 'tests positionals'"))
- }
-}
diff --git a/examples/README.md b/examples/README.md
new file mode 100644
index 0000000..f98c370
--- /dev/null
+++ b/examples/README.md
@@ -0,0 +1,16 @@
+# Examples
+
+We try to focus our documentation on the [four types of
+documentation](https://documentation.divio.com/). Examples fit into this by
+providing:
+- [Cookbook / How-To Guides](https://docs.rs/clap/latest/clap/_cookbook/index.html)
+- Tutorials ([derive](https://docs.rs/clap/latest/clap/_derive/_tutorial/index.html), [builder](https://docs.rs/clap/latest/clap/_tutorial/index.html))
+
+This directory contains the source for the above.
+
+## Contributing
+
+New examples should fit within the above structure and support their narrative
+- Add the example to [Cargo.toml](../Cargo.toml) for any `required-features`
+- Document how the example works with a `.md` file which will be verified using [trycmd](https://docs.rs/trycmd)
+- Pull the `.rs` and `.md` file into the appropriate module doc comment to be accessible on docs.rs
diff --git a/examples/cargo-example-derive.md b/examples/cargo-example-derive.md
new file mode 100644
index 0000000..a3dcef3
--- /dev/null
+++ b/examples/cargo-example-derive.md
@@ -0,0 +1,38 @@
+For more on creating a custom subcommand, see [the cargo
+book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands).
+The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in
+mimicking cargo's interface.
+
+The help looks like:
+```console
+$ cargo-example-derive --help
+Usage: cargo <COMMAND>
+
+Commands:
+ example-derive A simple to use, efficient, and full-featured Command Line Argument Parser
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -h, --help Print help
+
+$ cargo-example-derive example-derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: cargo example-derive [OPTIONS]
+
+Options:
+ --manifest-path <MANIFEST_PATH>
+ -h, --help Print help
+ -V, --version Print version
+
+```
+
+Then to directly invoke the command, run:
+```console
+$ cargo-example-derive example-derive
+None
+
+$ cargo-example-derive example-derive --manifest-path Cargo.toml
+Some("Cargo.toml")
+
+```
diff --git a/examples/cargo-example-derive.rs b/examples/cargo-example-derive.rs
new file mode 100644
index 0000000..dfdd799
--- /dev/null
+++ b/examples/cargo-example-derive.rs
@@ -0,0 +1,20 @@
+use clap::Parser;
+
+#[derive(Parser)] // requires `derive` feature
+#[command(name = "cargo")]
+#[command(bin_name = "cargo")]
+enum CargoCli {
+ ExampleDerive(ExampleDeriveArgs),
+}
+
+#[derive(clap::Args)]
+#[command(author, version, about, long_about = None)]
+struct ExampleDeriveArgs {
+ #[arg(long)]
+ manifest_path: Option<std::path::PathBuf>,
+}
+
+fn main() {
+ let CargoCli::ExampleDerive(args) = CargoCli::parse();
+ println!("{:?}", args.manifest_path);
+}
diff --git a/examples/cargo-example.md b/examples/cargo-example.md
new file mode 100644
index 0000000..edf8ee1
--- /dev/null
+++ b/examples/cargo-example.md
@@ -0,0 +1,38 @@
+For more on creating a custom subcommand, see [the cargo
+book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands).
+The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in
+mimicking cargo's interface.
+
+The help looks like:
+```console
+$ cargo-example --help
+Usage: cargo <COMMAND>
+
+Commands:
+ example A simple to use, efficient, and full-featured Command Line Argument Parser
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -h, --help Print help
+
+$ cargo-example example --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: cargo example [OPTIONS]
+
+Options:
+ --manifest-path <PATH>
+ -h, --help Print help
+ -V, --version Print version
+
+```
+
+Then to directly invoke the command, run:
+```console
+$ cargo-example example
+None
+
+$ cargo-example example --manifest-path Cargo.toml
+Some("Cargo.toml")
+
+```
diff --git a/examples/cargo-example.rs b/examples/cargo-example.rs
new file mode 100644
index 0000000..b0861a6
--- /dev/null
+++ b/examples/cargo-example.rs
@@ -0,0 +1,18 @@
+fn main() {
+ let cmd = clap::Command::new("cargo")
+ .bin_name("cargo")
+ .subcommand_required(true)
+ .subcommand(
+ clap::command!("example").arg(
+ clap::arg!(--"manifest-path" <PATH>)
+ .value_parser(clap::value_parser!(std::path::PathBuf)),
+ ),
+ );
+ let matches = cmd.get_matches();
+ let matches = match matches.subcommand() {
+ Some(("example", matches)) => matches,
+ _ => unreachable!("clap should ensure we don't get here"),
+ };
+ let manifest_path = matches.get_one::<std::path::PathBuf>("manifest-path");
+ println!("{:?}", manifest_path);
+}
diff --git a/examples/demo.md b/examples/demo.md
new file mode 100644
index 0000000..772d98d
--- /dev/null
+++ b/examples/demo.md
@@ -0,0 +1,17 @@
+```console
+$ demo --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: demo[EXE] [OPTIONS] --name <NAME>
+
+Options:
+ -n, --name <NAME> Name of the person to greet
+ -c, --count <COUNT> Number of times to greet [default: 1]
+ -h, --help Print help
+ -V, --version Print version
+
+$ demo --name Me
+Hello Me!
+
+```
+*(version number and `.exe` extension on windows replaced by placeholders)*
diff --git a/examples/demo.rs b/examples/demo.rs
new file mode 100644
index 0000000..8e4304a
--- /dev/null
+++ b/examples/demo.rs
@@ -0,0 +1,22 @@
+use clap::Parser;
+
+/// Simple program to greet a person
+#[derive(Parser, Debug)]
+#[command(author, version, about, long_about = None)]
+struct Args {
+ /// Name of the person to greet
+ #[arg(short, long)]
+ name: String,
+
+ /// Number of times to greet
+ #[arg(short, long, default_value_t = 1)]
+ count: u8,
+}
+
+fn main() {
+ let args = Args::parse();
+
+ for _ in 0..args.count {
+ println!("Hello {}!", args.name)
+ }
+}
diff --git a/examples/derive_ref/augment_args.rs b/examples/derive_ref/augment_args.rs
new file mode 100644
index 0000000..39d837c
--- /dev/null
+++ b/examples/derive_ref/augment_args.rs
@@ -0,0 +1,27 @@
+use clap::{arg, Args, Command, FromArgMatches as _};
+
+#[derive(Args, Debug)]
+struct DerivedArgs {
+ #[arg(short, long)]
+ derived: bool,
+}
+
+fn main() {
+ let cli = Command::new("CLI").arg(arg!(-b - -built).action(clap::ArgAction::SetTrue));
+ // Augment built args with derived args
+ let cli = DerivedArgs::augment_args(cli);
+
+ let matches = cli.get_matches();
+ println!("Value of built: {:?}", matches.get_flag("built"));
+ println!(
+ "Value of derived via ArgMatches: {:?}",
+ matches.get_flag("derived")
+ );
+
+ // Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches.
+ // This is the main benefit of using derived arguments.
+ let derived_matches = DerivedArgs::from_arg_matches(&matches)
+ .map_err(|err| err.exit())
+ .unwrap();
+ println!("Value of derived: {derived_matches:#?}");
+}
diff --git a/examples/derive_ref/augment_subcommands.rs b/examples/derive_ref/augment_subcommands.rs
new file mode 100644
index 0000000..51cbe75
--- /dev/null
+++ b/examples/derive_ref/augment_subcommands.rs
@@ -0,0 +1,21 @@
+use clap::{Command, FromArgMatches as _, Parser, Subcommand as _};
+
+#[derive(Parser, Debug)]
+enum Subcommands {
+ Derived {
+ #[arg(short, long)]
+ derived_flag: bool,
+ },
+}
+
+fn main() {
+ let cli = Command::new("Built CLI");
+ // Augment with derived subcommands
+ let cli = Subcommands::augment_subcommands(cli);
+
+ let matches = cli.get_matches();
+ let derived_subcommands = Subcommands::from_arg_matches(&matches)
+ .map_err(|err| err.exit())
+ .unwrap();
+ println!("Derived subcommands: {derived_subcommands:#?}");
+}
diff --git a/examples/derive_ref/flatten_hand_args.rs b/examples/derive_ref/flatten_hand_args.rs
new file mode 100644
index 0000000..36aac09
--- /dev/null
+++ b/examples/derive_ref/flatten_hand_args.rs
@@ -0,0 +1,91 @@
+use clap::error::Error;
+use clap::{Arg, ArgAction, ArgMatches, Args, Command, FromArgMatches, Parser};
+
+#[derive(Debug)]
+struct CliArgs {
+ foo: bool,
+ bar: bool,
+ quuz: Option<String>,
+}
+
+impl FromArgMatches for CliArgs {
+ fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
+ let mut matches = matches.clone();
+ Self::from_arg_matches_mut(&mut matches)
+ }
+ fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error> {
+ Ok(Self {
+ foo: matches.get_flag("foo"),
+ bar: matches.get_flag("bar"),
+ quuz: matches.remove_one::<String>("quuz"),
+ })
+ }
+ fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
+ let mut matches = matches.clone();
+ self.update_from_arg_matches_mut(&mut matches)
+ }
+ fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> {
+ self.foo |= matches.get_flag("foo");
+ self.bar |= matches.get_flag("bar");
+ if let Some(quuz) = matches.remove_one::<String>("quuz") {
+ self.quuz = Some(quuz);
+ }
+ Ok(())
+ }
+}
+
+impl Args for CliArgs {
+ fn augment_args(cmd: Command) -> Command {
+ cmd.arg(
+ Arg::new("foo")
+ .short('f')
+ .long("foo")
+ .action(ArgAction::SetTrue),
+ )
+ .arg(
+ Arg::new("bar")
+ .short('b')
+ .long("bar")
+ .action(ArgAction::SetTrue),
+ )
+ .arg(
+ Arg::new("quuz")
+ .short('q')
+ .long("quuz")
+ .action(ArgAction::Set),
+ )
+ }
+ fn augment_args_for_update(cmd: Command) -> Command {
+ cmd.arg(
+ Arg::new("foo")
+ .short('f')
+ .long("foo")
+ .action(ArgAction::SetTrue),
+ )
+ .arg(
+ Arg::new("bar")
+ .short('b')
+ .long("bar")
+ .action(ArgAction::SetTrue),
+ )
+ .arg(
+ Arg::new("quuz")
+ .short('q')
+ .long("quuz")
+ .action(ArgAction::Set),
+ )
+ }
+}
+
+#[derive(Parser, Debug)]
+struct Cli {
+ #[arg(short, long)]
+ top_level: bool,
+ #[command(flatten)]
+ more_args: CliArgs,
+}
+
+fn main() {
+ let args = Cli::parse();
+ println!("{args:#?}");
+}
diff --git a/examples/derive_ref/hand_subcommand.rs b/examples/derive_ref/hand_subcommand.rs
new file mode 100644
index 0000000..ebaa60d
--- /dev/null
+++ b/examples/derive_ref/hand_subcommand.rs
@@ -0,0 +1,79 @@
+use clap::error::{Error, ErrorKind};
+use clap::{ArgMatches, Args as _, Command, FromArgMatches, Parser, Subcommand};
+
+#[derive(Parser, Debug)]
+struct AddArgs {
+ name: Vec<String>,
+}
+#[derive(Parser, Debug)]
+struct RemoveArgs {
+ #[arg(short, long)]
+ force: bool,
+ name: Vec<String>,
+}
+
+#[derive(Debug)]
+enum CliSub {
+ Add(AddArgs),
+ Remove(RemoveArgs),
+}
+
+impl FromArgMatches for CliSub {
+ fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
+ match matches.subcommand() {
+ Some(("add", args)) => Ok(Self::Add(AddArgs::from_arg_matches(args)?)),
+ Some(("remove", args)) => Ok(Self::Remove(RemoveArgs::from_arg_matches(args)?)),
+ Some((_, _)) => Err(Error::raw(
+ ErrorKind::InvalidSubcommand,
+ "Valid subcommands are `add` and `remove`",
+ )),
+ None => Err(Error::raw(
+ ErrorKind::MissingSubcommand,
+ "Valid subcommands are `add` and `remove`",
+ )),
+ }
+ }
+ fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
+ match matches.subcommand() {
+ Some(("add", args)) => *self = Self::Add(AddArgs::from_arg_matches(args)?),
+ Some(("remove", args)) => *self = Self::Remove(RemoveArgs::from_arg_matches(args)?),
+ Some((_, _)) => {
+ return Err(Error::raw(
+ ErrorKind::InvalidSubcommand,
+ "Valid subcommands are `add` and `remove`",
+ ))
+ }
+ None => (),
+ };
+ Ok(())
+ }
+}
+
+impl Subcommand for CliSub {
+ fn augment_subcommands(cmd: Command) -> Command {
+ cmd.subcommand(AddArgs::augment_args(Command::new("add")))
+ .subcommand(RemoveArgs::augment_args(Command::new("remove")))
+ .subcommand_required(true)
+ }
+ fn augment_subcommands_for_update(cmd: Command) -> Command {
+ cmd.subcommand(AddArgs::augment_args(Command::new("add")))
+ .subcommand(RemoveArgs::augment_args(Command::new("remove")))
+ .subcommand_required(true)
+ }
+ fn has_subcommand(name: &str) -> bool {
+ matches!(name, "add" | "remove")
+ }
+}
+
+#[derive(Parser, Debug)]
+struct Cli {
+ #[arg(short, long)]
+ top_level: bool,
+ #[command(subcommand)]
+ subcommand: CliSub,
+}
+
+fn main() {
+ let args = Cli::parse();
+ println!("{args:#?}");
+}
diff --git a/examples/derive_ref/interop_tests.md b/examples/derive_ref/interop_tests.md
new file mode 100644
index 0000000..a7bcc7e
--- /dev/null
+++ b/examples/derive_ref/interop_tests.md
@@ -0,0 +1,248 @@
+Following are tests for the interop examples in this directory.
+
+## Augment Args
+
+```console
+$ interop_augment_args
+Value of built: false
+Value of derived via ArgMatches: false
+Value of derived: DerivedArgs {
+ derived: false,
+}
+
+```
+
+```console
+$ interop_augment_args -b --derived
+Value of built: true
+Value of derived via ArgMatches: true
+Value of derived: DerivedArgs {
+ derived: true,
+}
+
+```
+
+```console
+$ interop_augment_args -d --built
+Value of built: true
+Value of derived via ArgMatches: true
+Value of derived: DerivedArgs {
+ derived: true,
+}
+
+```
+
+```console
+$ interop_augment_args --unknown
+? failed
+error: unexpected argument '--unknown' found
+
+Usage: interop_augment_args[EXE] [OPTIONS]
+
+For more information, try '--help'.
+
+```
+
+## Augment Subcommands
+
+```console
+$ interop_augment_subcommands
+? failed
+error: A subcommand is required but one was not provided.
+```
+
+```console
+$ interop_augment_subcommands derived
+Derived subcommands: Derived {
+ derived_flag: false,
+}
+
+```
+
+```console
+$ interop_augment_subcommands derived --derived-flag
+Derived subcommands: Derived {
+ derived_flag: true,
+}
+
+```
+
+```console
+$ interop_augment_subcommands derived --unknown
+? failed
+error: unexpected argument '--unknown' found
+
+Usage: interop_augment_subcommands[EXE] derived [OPTIONS]
+
+For more information, try '--help'.
+
+```
+
+```console
+$ interop_augment_subcommands unknown
+? failed
+error: unrecognized subcommand 'unknown'
+
+Usage: interop_augment_subcommands[EXE] [COMMAND]
+
+For more information, try '--help'.
+
+```
+
+## Hand-Implemented Subcommand
+
+```console
+$ interop_hand_subcommand
+? failed
+Usage: interop_hand_subcommand[EXE] [OPTIONS] <COMMAND>
+
+Commands:
+ add
+ remove
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -t, --top-level
+ -h, --help Print help
+
+```
+
+```console
+$ interop_hand_subcommand add
+Cli {
+ top_level: false,
+ subcommand: Add(
+ AddArgs {
+ name: [],
+ },
+ ),
+}
+
+```
+
+```console
+$ interop_hand_subcommand add a b c
+Cli {
+ top_level: false,
+ subcommand: Add(
+ AddArgs {
+ name: [
+ "a",
+ "b",
+ "c",
+ ],
+ },
+ ),
+}
+
+```
+
+```console
+$ interop_hand_subcommand add --unknown
+? failed
+error: unexpected argument '--unknown' found
+
+ note: to pass '--unknown' as a value, use '-- --unknown'
+
+Usage: interop_hand_subcommand[EXE] add [NAME]...
+
+For more information, try '--help'.
+
+```
+
+```console
+$ interop_hand_subcommand remove
+Cli {
+ top_level: false,
+ subcommand: Remove(
+ RemoveArgs {
+ force: false,
+ name: [],
+ },
+ ),
+}
+
+```
+
+```console
+$ interop_hand_subcommand remove --force a b c
+Cli {
+ top_level: false,
+ subcommand: Remove(
+ RemoveArgs {
+ force: true,
+ name: [
+ "a",
+ "b",
+ "c",
+ ],
+ },
+ ),
+}
+
+```
+
+```console
+$ interop_hand_subcommand unknown
+? failed
+error: unrecognized subcommand 'unknown'
+
+Usage: interop_hand_subcommand[EXE] [OPTIONS] <COMMAND>
+
+For more information, try '--help'.
+
+```
+
+## Flatten Hand-Implemented Args
+
+```console
+$ interop_flatten_hand_args
+Cli {
+ top_level: false,
+ more_args: CliArgs {
+ foo: false,
+ bar: false,
+ quuz: None,
+ },
+}
+
+```
+
+```console
+$ interop_flatten_hand_args -f --bar
+Cli {
+ top_level: false,
+ more_args: CliArgs {
+ foo: true,
+ bar: true,
+ quuz: None,
+ },
+}
+
+```
+
+```console
+$ interop_flatten_hand_args --quuz abc
+Cli {
+ top_level: false,
+ more_args: CliArgs {
+ foo: false,
+ bar: false,
+ quuz: Some(
+ "abc",
+ ),
+ },
+}
+
+```
+
+```console
+$ interop_flatten_hand_args --unknown
+? failed
+error: unexpected argument '--unknown' found
+
+Usage: interop_flatten_hand_args[EXE] [OPTIONS]
+
+For more information, try '--help'.
+
+```
diff --git a/examples/escaped-positional-derive.md b/examples/escaped-positional-derive.md
new file mode 100644
index 0000000..82990b5
--- /dev/null
+++ b/examples/escaped-positional-derive.md
@@ -0,0 +1,60 @@
+**This requires enabling the [`derive` feature flag][crate::_features].**
+
+You can use `--` to escape further arguments.
+
+Let's see what this looks like in the help:
+```console
+$ escaped-positional-derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: escaped-positional-derive[EXE] [OPTIONS] [-- <SLOP>...]
+
+Arguments:
+ [SLOP]...
+
+Options:
+ -f
+ -p <PEAR>
+ -h, --help Print help
+ -V, --version Print version
+
+```
+
+Here is a baseline without any arguments:
+```console
+$ escaped-positional-derive
+-f used: false
+-p's value: None
+'slops' values: []
+
+```
+
+Notice that we can't pass positional arguments before `--`:
+```console
+$ escaped-positional-derive foo bar
+? failed
+error: unexpected argument 'foo' found
+
+Usage: escaped-positional-derive[EXE] [OPTIONS] [-- <SLOP>...]
+
+For more information, try '--help'.
+
+```
+
+But you can after:
+```console
+$ escaped-positional-derive -f -p=bob -- sloppy slop slop
+-f used: true
+-p's value: Some("bob")
+'slops' values: ["sloppy", "slop", "slop"]
+
+```
+
+As mentioned, the parser will directly pass everything through:
+```console
+$ escaped-positional-derive -- -f -p=bob sloppy slop slop
+-f used: false
+-p's value: None
+'slops' values: ["-f", "-p=bob", "sloppy", "slop", "slop"]
+
+```
diff --git a/examples/escaped-positional-derive.rs b/examples/escaped-positional-derive.rs
new file mode 100644
index 0000000..719b3d6
--- /dev/null
+++ b/examples/escaped-positional-derive.rs
@@ -0,0 +1,25 @@
+use clap::Parser;
+
+#[derive(Parser)] // requires `derive` feature
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ #[arg(short = 'f')]
+ eff: bool,
+
+ #[arg(short = 'p', value_name = "PEAR")]
+ pea: Option<String>,
+
+ #[arg(last = true)]
+ slop: Vec<String>,
+}
+
+fn main() {
+ let args = Cli::parse();
+
+ // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`...
+ println!("-f used: {:?}", args.eff); // -f used: true
+ println!("-p's value: {:?}", args.pea); // -p's value: Some("bob")
+ println!("'slops' values: {:?}", args.slop); // 'slops' values: Some(["sloppy", "slop", "slop"])
+
+ // Continued program logic goes here...
+}
diff --git a/examples/escaped-positional.md b/examples/escaped-positional.md
new file mode 100644
index 0000000..d94e399
--- /dev/null
+++ b/examples/escaped-positional.md
@@ -0,0 +1,60 @@
+**This requires enabling the [`cargo` feature flag][crate::_features].**
+
+You can use `--` to escape further arguments.
+
+Let's see what this looks like in the help:
+```console
+$ escaped-positional --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: escaped-positional[EXE] [OPTIONS] [-- <SLOP>...]
+
+Arguments:
+ [SLOP]...
+
+Options:
+ -f
+ -p <PEAR>
+ -h, --help Print help
+ -V, --version Print version
+
+```
+
+Here is a baseline without any arguments:
+```console
+$ escaped-positional
+-f used: false
+-p's value: None
+'slops' values: []
+
+```
+
+Notice that we can't pass positional arguments before `--`:
+```console
+$ escaped-positional foo bar
+? failed
+error: unexpected argument 'foo' found
+
+Usage: escaped-positional[EXE] [OPTIONS] [-- <SLOP>...]
+
+For more information, try '--help'.
+
+```
+
+But you can after:
+```console
+$ escaped-positional -f -p=bob -- sloppy slop slop
+-f used: true
+-p's value: Some("bob")
+'slops' values: ["sloppy", "slop", "slop"]
+
+```
+
+As mentioned, the parser will directly pass everything through:
+```console
+$ escaped-positional -- -f -p=bob sloppy slop slop
+-f used: false
+-p's value: None
+'slops' values: ["-f", "-p=bob", "sloppy", "slop", "slop"]
+
+```
diff --git a/examples/escaped-positional.rs b/examples/escaped-positional.rs
new file mode 100644
index 0000000..d107e47
--- /dev/null
+++ b/examples/escaped-positional.rs
@@ -0,0 +1,32 @@
+use clap::{arg, command, value_parser, ArgAction};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(arg!(eff: -f).action(ArgAction::SetTrue))
+ .arg(arg!(pea: -p <PEAR>).value_parser(value_parser!(String)))
+ .arg(
+ // Indicates that `slop` is only accessible after `--`.
+ arg!(slop: [SLOP])
+ .num_args(1..)
+ .last(true)
+ .value_parser(value_parser!(String)),
+ )
+ .get_matches();
+
+ // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`...
+
+ // -f used: true
+ println!("-f used: {:?}", matches.get_flag("eff"));
+ // -p's value: Some("bob")
+ println!("-p's value: {:?}", matches.get_one::<String>("pea"));
+ // 'slops' values: Some(["sloppy", "slop", "slop"])
+ println!(
+ "'slops' values: {:?}",
+ matches
+ .get_many::<String>("slop")
+ .map(|vals| vals.collect::<Vec<_>>())
+ .unwrap_or_default()
+ );
+
+ // Continued program logic goes here...
+}
diff --git a/examples/find.md b/examples/find.md
new file mode 100644
index 0000000..e9b1a86
--- /dev/null
+++ b/examples/find.md
@@ -0,0 +1,45 @@
+`find` is an example of position-sensitive flags
+
+```console
+$ find --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: find[EXE] [OPTIONS]
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+TESTS:
+ --empty File is empty and is either a regular file or a directory
+ --name <NAME> Base of file name (the path with the leading directories removed) matches shell
+ pattern pattern
+
+OPERATORS:
+ -o, --or expr2 is not evaluate if exp1 is true
+ -a, --and Same as `expr1 expr1`
+
+$ find --empty -o --name .keep
+[
+ (
+ "empty",
+ Bool(
+ true,
+ ),
+ ),
+ (
+ "or",
+ Bool(
+ true,
+ ),
+ ),
+ (
+ "name",
+ String(
+ ".keep",
+ ),
+ ),
+]
+
+```
+
diff --git a/examples/find.rs b/examples/find.rs
new file mode 100644
index 0000000..e073e70
--- /dev/null
+++ b/examples/find.rs
@@ -0,0 +1,99 @@
+use std::collections::BTreeMap;
+
+use clap::{arg, command, ArgGroup, ArgMatches, Command};
+
+fn main() {
+ let matches = cli().get_matches();
+ let values = Value::from_matches(&matches);
+ println!("{:#?}", values);
+}
+
+fn cli() -> Command {
+ command!()
+ .group(ArgGroup::new("tests").multiple(true))
+ .next_help_heading("TESTS")
+ .args([
+ arg!(--empty "File is empty and is either a regular file or a directory").group("tests"),
+ arg!(--name <NAME> "Base of file name (the path with the leading directories removed) matches shell pattern pattern").group("tests"),
+ ])
+ .group(ArgGroup::new("operators").multiple(true))
+ .next_help_heading("OPERATORS")
+ .args([
+ arg!(-o - -or "expr2 is not evaluate if exp1 is true").group("operators"),
+ arg!(-a - -and "Same as `expr1 expr1`").group("operators"),
+ ])
+}
+
+#[derive(Clone, PartialEq, Eq, Hash, Debug)]
+pub enum Value {
+ Bool(bool),
+ String(String),
+}
+
+impl Value {
+ pub fn from_matches(matches: &ArgMatches) -> Vec<(clap::Id, Self)> {
+ let mut values = BTreeMap::new();
+ for id in matches.ids() {
+ if matches.try_get_many::<clap::Id>(id.as_str()).is_ok() {
+ // ignore groups
+ continue;
+ }
+ let value_source = matches
+ .value_source(id.as_str())
+ .expect("id came from matches");
+ if value_source != clap::parser::ValueSource::CommandLine {
+ // Any other source just gets tacked on at the end (like default values)
+ continue;
+ }
+ if Self::extract::<String>(matches, id, &mut values) {
+ continue;
+ }
+ if Self::extract::<bool>(matches, id, &mut values) {
+ continue;
+ }
+ unimplemented!("unknown type for {}: {:?}", id, matches);
+ }
+ values.into_values().collect::<Vec<_>>()
+ }
+
+ fn extract<T: Clone + Into<Value> + Send + Sync + 'static>(
+ matches: &ArgMatches,
+ id: &clap::Id,
+ output: &mut BTreeMap<usize, (clap::Id, Self)>,
+ ) -> bool {
+ match matches.try_get_many::<T>(id.as_str()) {
+ Ok(Some(values)) => {
+ for (value, index) in values.zip(
+ matches
+ .indices_of(id.as_str())
+ .expect("id came from matches"),
+ ) {
+ output.insert(index, (id.clone(), value.clone().into()));
+ }
+ true
+ }
+ Ok(None) => {
+ unreachable!("`ids` only reports what is present")
+ }
+ Err(clap::parser::MatchesError::UnknownArgument { .. }) => {
+ unreachable!("id came from matches")
+ }
+ Err(clap::parser::MatchesError::Downcast { .. }) => false,
+ Err(_) => {
+ unreachable!("id came from matches")
+ }
+ }
+ }
+}
+
+impl From<String> for Value {
+ fn from(other: String) -> Self {
+ Self::String(other)
+ }
+}
+
+impl From<bool> for Value {
+ fn from(other: bool) -> Self {
+ Self::Bool(other)
+ }
+}
diff --git a/examples/git-derive.md b/examples/git-derive.md
new file mode 100644
index 0000000..57edb61
--- /dev/null
+++ b/examples/git-derive.md
@@ -0,0 +1,159 @@
+**This requires enabling the [`derive` feature flag][crate::_features].**
+
+Git is an example of several common subcommand patterns.
+
+Help:
+```console
+$ git-derive
+? failed
+A fictional versioning CLI
+
+Usage: git-derive[EXE] <COMMAND>
+
+Commands:
+ clone Clones repos
+ diff Compare two commits
+ push pushes things
+ add adds things
+ stash
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -h, --help Print help
+
+$ git-derive help
+A fictional versioning CLI
+
+Usage: git-derive[EXE] <COMMAND>
+
+Commands:
+ clone Clones repos
+ diff Compare two commits
+ push pushes things
+ add adds things
+ stash
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -h, --help Print help
+
+$ git-derive help add
+adds things
+
+Usage: git-derive[EXE] add <PATH>...
+
+Arguments:
+ <PATH>... Stuff to add
+
+Options:
+ -h, --help Print help
+
+```
+
+A basic argument:
+```console
+$ git-derive add
+? failed
+adds things
+
+Usage: git-derive[EXE] add <PATH>...
+
+Arguments:
+ <PATH>... Stuff to add
+
+Options:
+ -h, --help Print help
+
+$ git-derive add Cargo.toml Cargo.lock
+Adding ["Cargo.toml", "Cargo.lock"]
+
+```
+
+Default subcommand:
+```console
+$ git-derive stash -h
+Usage: git-derive[EXE] stash [OPTIONS]
+ git-derive[EXE] stash <COMMAND>
+
+Commands:
+ push
+ pop
+ apply
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -m, --message <MESSAGE>
+ -h, --help Print help
+
+$ git-derive stash push -h
+Usage: git-derive[EXE] stash push [OPTIONS]
+
+Options:
+ -m, --message <MESSAGE>
+ -h, --help Print help
+
+$ git-derive stash pop -h
+Usage: git-derive[EXE] stash pop [STASH]
+
+Arguments:
+ [STASH]
+
+Options:
+ -h, --help Print help
+
+$ git-derive stash -m "Prototype"
+Pushing StashPushArgs { message: Some("Prototype") }
+
+$ git-derive stash pop
+Popping None
+
+$ git-derive stash push -m "Prototype"
+Pushing StashPushArgs { message: Some("Prototype") }
+
+$ git-derive stash pop
+Popping None
+
+```
+
+External subcommands:
+```console
+$ git-derive custom-tool arg1 --foo bar
+Calling out to "custom-tool" with ["arg1", "--foo", "bar"]
+
+```
+
+Last argument:
+```console
+$ git-derive diff --help
+Compare two commits
+
+Usage: git-derive[EXE] diff [OPTIONS] [COMMIT] [COMMIT] [-- <PATH>]
+
+Arguments:
+ [COMMIT]
+ [COMMIT]
+ [PATH]
+
+Options:
+ --color[=<WHEN>] [default: auto] [possible values: always, auto, never]
+ -h, --help Print help
+
+$ git-derive diff
+Diffing stage..worktree (color=auto)
+
+$ git-derive diff ./src
+Diffing stage..worktree ./src (color=auto)
+
+$ git-derive diff HEAD ./src
+Diffing HEAD..worktree ./src (color=auto)
+
+$ git-derive diff HEAD~~ -- HEAD
+Diffing HEAD~~..worktree HEAD (color=auto)
+
+$ git-derive diff --color
+Diffing stage..worktree (color=always)
+
+$ git-derive diff --color=never
+Diffing stage..worktree (color=never)
+
+```
diff --git a/examples/git-derive.rs b/examples/git-derive.rs
new file mode 100644
index 0000000..ad82e0c
--- /dev/null
+++ b/examples/git-derive.rs
@@ -0,0 +1,164 @@
+use std::ffi::OsStr;
+use std::ffi::OsString;
+use std::path::PathBuf;
+
+use clap::{Args, Parser, Subcommand, ValueEnum};
+
+/// A fictional versioning CLI
+#[derive(Debug, Parser)] // requires `derive` feature
+#[command(name = "git")]
+#[command(about = "A fictional versioning CLI", long_about = None)]
+struct Cli {
+ #[command(subcommand)]
+ command: Commands,
+}
+
+#[derive(Debug, Subcommand)]
+enum Commands {
+ /// Clones repos
+ #[command(arg_required_else_help = true)]
+ Clone {
+ /// The remote to clone
+ remote: String,
+ },
+ /// Compare two commits
+ Diff {
+ #[arg(value_name = "COMMIT")]
+ base: Option<OsString>,
+ #[arg(value_name = "COMMIT")]
+ head: Option<OsString>,
+ #[arg(last = true)]
+ path: Option<OsString>,
+ #[arg(
+ long,
+ require_equals = true,
+ value_name = "WHEN",
+ num_args = 0..=1,
+ default_value_t = ColorWhen::Auto,
+ default_missing_value = "always",
+ value_enum
+ )]
+ color: ColorWhen,
+ },
+ /// pushes things
+ #[command(arg_required_else_help = true)]
+ Push {
+ /// The remote to target
+ remote: String,
+ },
+ /// adds things
+ #[command(arg_required_else_help = true)]
+ Add {
+ /// Stuff to add
+ #[arg(required = true)]
+ path: Vec<PathBuf>,
+ },
+ Stash(StashArgs),
+ #[command(external_subcommand)]
+ External(Vec<OsString>),
+}
+
+#[derive(ValueEnum, Copy, Clone, Debug, PartialEq, Eq)]
+enum ColorWhen {
+ Always,
+ Auto,
+ Never,
+}
+
+impl std::fmt::Display for ColorWhen {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ self.to_possible_value()
+ .expect("no values are skipped")
+ .get_name()
+ .fmt(f)
+ }
+}
+
+#[derive(Debug, Args)]
+#[command(args_conflicts_with_subcommands = true)]
+struct StashArgs {
+ #[command(subcommand)]
+ command: Option<StashCommands>,
+
+ #[command(flatten)]
+ push: StashPushArgs,
+}
+
+#[derive(Debug, Subcommand)]
+enum StashCommands {
+ Push(StashPushArgs),
+ Pop { stash: Option<String> },
+ Apply { stash: Option<String> },
+}
+
+#[derive(Debug, Args)]
+struct StashPushArgs {
+ #[arg(short, long)]
+ message: Option<String>,
+}
+
+fn main() {
+ let args = Cli::parse();
+
+ match args.command {
+ Commands::Clone { remote } => {
+ println!("Cloning {remote}");
+ }
+ Commands::Diff {
+ mut base,
+ mut head,
+ mut path,
+ color,
+ } => {
+ if path.is_none() {
+ path = head;
+ head = None;
+ if path.is_none() {
+ path = base;
+ base = None;
+ }
+ }
+ let base = base
+ .as_deref()
+ .map(|s| s.to_str().unwrap())
+ .unwrap_or("stage");
+ let head = head
+ .as_deref()
+ .map(|s| s.to_str().unwrap())
+ .unwrap_or("worktree");
+ let path = path.as_deref().unwrap_or_else(|| OsStr::new(""));
+ println!(
+ "Diffing {}..{} {} (color={})",
+ base,
+ head,
+ path.to_string_lossy(),
+ color
+ );
+ }
+ Commands::Push { remote } => {
+ println!("Pushing to {remote}");
+ }
+ Commands::Add { path } => {
+ println!("Adding {path:?}");
+ }
+ Commands::Stash(stash) => {
+ let stash_cmd = stash.command.unwrap_or(StashCommands::Push(stash.push));
+ match stash_cmd {
+ StashCommands::Push(push) => {
+ println!("Pushing {push:?}");
+ }
+ StashCommands::Pop { stash } => {
+ println!("Popping {stash:?}");
+ }
+ StashCommands::Apply { stash } => {
+ println!("Applying {stash:?}");
+ }
+ }
+ }
+ Commands::External(args) => {
+ println!("Calling out to {:?} with {:?}", &args[0], &args[1..]);
+ }
+ }
+
+ // Continued program logic goes here...
+}
diff --git a/examples/git.md b/examples/git.md
new file mode 100644
index 0000000..d90b2e8
--- /dev/null
+++ b/examples/git.md
@@ -0,0 +1,157 @@
+Git is an example of several common subcommand patterns.
+
+Help:
+```console
+$ git
+? failed
+A fictional versioning CLI
+
+Usage: git[EXE] <COMMAND>
+
+Commands:
+ clone Clones repos
+ diff Compare two commits
+ push pushes things
+ add adds things
+ stash
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -h, --help Print help
+
+$ git help
+A fictional versioning CLI
+
+Usage: git[EXE] <COMMAND>
+
+Commands:
+ clone Clones repos
+ diff Compare two commits
+ push pushes things
+ add adds things
+ stash
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -h, --help Print help
+
+$ git help add
+adds things
+
+Usage: git[EXE] add <PATH>...
+
+Arguments:
+ <PATH>... Stuff to add
+
+Options:
+ -h, --help Print help
+
+```
+
+A basic argument:
+```console
+$ git add
+? failed
+adds things
+
+Usage: git[EXE] add <PATH>...
+
+Arguments:
+ <PATH>... Stuff to add
+
+Options:
+ -h, --help Print help
+
+$ git add Cargo.toml Cargo.lock
+Adding ["Cargo.toml", "Cargo.lock"]
+
+```
+
+Default subcommand:
+```console
+$ git stash -h
+Usage: git[EXE] stash [OPTIONS]
+ git[EXE] stash <COMMAND>
+
+Commands:
+ push
+ pop
+ apply
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -m, --message <MESSAGE>
+ -h, --help Print help
+
+$ git stash push -h
+Usage: git[EXE] stash push [OPTIONS]
+
+Options:
+ -m, --message <MESSAGE>
+ -h, --help Print help
+
+$ git stash pop -h
+Usage: git[EXE] stash pop [STASH]
+
+Arguments:
+ [STASH]
+
+Options:
+ -h, --help Print help
+
+$ git stash -m "Prototype"
+Pushing Some("Prototype")
+
+$ git stash pop
+Popping None
+
+$ git stash push -m "Prototype"
+Pushing Some("Prototype")
+
+$ git stash pop
+Popping None
+
+```
+
+External subcommands:
+```console
+$ git custom-tool arg1 --foo bar
+Calling out to "custom-tool" with ["arg1", "--foo", "bar"]
+
+```
+
+Last argument:
+```console
+$ git diff --help
+Compare two commits
+
+Usage: git[EXE] diff [OPTIONS] [COMMIT] [COMMIT] [-- <PATH>]
+
+Arguments:
+ [COMMIT]
+ [COMMIT]
+ [PATH]
+
+Options:
+ --color[=<WHEN>] [default: auto] [possible values: always, auto, never]
+ -h, --help Print help
+
+$ git diff
+Diffing stage..worktree (color=auto)
+
+$ git diff ./src
+Diffing stage..worktree ./src (color=auto)
+
+$ git diff HEAD ./src
+Diffing HEAD..worktree ./src (color=auto)
+
+$ git diff HEAD~~ -- HEAD
+Diffing HEAD~~..worktree HEAD (color=auto)
+
+$ git diff --color
+Diffing stage..worktree (color=always)
+
+$ git diff --color=never
+Diffing stage..worktree (color=never)
+
+```
diff --git a/examples/git.rs b/examples/git.rs
new file mode 100644
index 0000000..bd05e53
--- /dev/null
+++ b/examples/git.rs
@@ -0,0 +1,137 @@
+use std::ffi::OsString;
+use std::path::PathBuf;
+
+use clap::{arg, Command};
+
+fn cli() -> Command {
+ Command::new("git")
+ .about("A fictional versioning CLI")
+ .subcommand_required(true)
+ .arg_required_else_help(true)
+ .allow_external_subcommands(true)
+ .subcommand(
+ Command::new("clone")
+ .about("Clones repos")
+ .arg(arg!(<REMOTE> "The remote to clone"))
+ .arg_required_else_help(true),
+ )
+ .subcommand(
+ Command::new("diff")
+ .about("Compare two commits")
+ .arg(arg!(base: [COMMIT]))
+ .arg(arg!(head: [COMMIT]))
+ .arg(arg!(path: [PATH]).last(true))
+ .arg(
+ arg!(--color <WHEN>)
+ .value_parser(["always", "auto", "never"])
+ .num_args(0..=1)
+ .require_equals(true)
+ .default_value("auto")
+ .default_missing_value("always"),
+ ),
+ )
+ .subcommand(
+ Command::new("push")
+ .about("pushes things")
+ .arg(arg!(<REMOTE> "The remote to target"))
+ .arg_required_else_help(true),
+ )
+ .subcommand(
+ Command::new("add")
+ .about("adds things")
+ .arg_required_else_help(true)
+ .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
+ )
+ .subcommand(
+ Command::new("stash")
+ .args_conflicts_with_subcommands(true)
+ .args(push_args())
+ .subcommand(Command::new("push").args(push_args()))
+ .subcommand(Command::new("pop").arg(arg!([STASH])))
+ .subcommand(Command::new("apply").arg(arg!([STASH]))),
+ )
+}
+
+fn push_args() -> Vec<clap::Arg> {
+ vec![arg!(-m --message <MESSAGE>)]
+}
+
+fn main() {
+ let matches = cli().get_matches();
+
+ match matches.subcommand() {
+ Some(("clone", sub_matches)) => {
+ println!(
+ "Cloning {}",
+ sub_matches.get_one::<String>("REMOTE").expect("required")
+ );
+ }
+ Some(("diff", sub_matches)) => {
+ let color = sub_matches
+ .get_one::<String>("color")
+ .map(|s| s.as_str())
+ .expect("defaulted in clap");
+
+ let mut base = sub_matches.get_one::<String>("base").map(|s| s.as_str());
+ let mut head = sub_matches.get_one::<String>("head").map(|s| s.as_str());
+ let mut path = sub_matches.get_one::<String>("path").map(|s| s.as_str());
+ if path.is_none() {
+ path = head;
+ head = None;
+ if path.is_none() {
+ path = base;
+ base = None;
+ }
+ }
+ let base = base.unwrap_or("stage");
+ let head = head.unwrap_or("worktree");
+ let path = path.unwrap_or("");
+ println!("Diffing {base}..{head} {path} (color={color})");
+ }
+ Some(("push", sub_matches)) => {
+ println!(
+ "Pushing to {}",
+ sub_matches.get_one::<String>("REMOTE").expect("required")
+ );
+ }
+ Some(("add", sub_matches)) => {
+ let paths = sub_matches
+ .get_many::<PathBuf>("PATH")
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>();
+ println!("Adding {paths:?}");
+ }
+ Some(("stash", sub_matches)) => {
+ let stash_command = sub_matches.subcommand().unwrap_or(("push", sub_matches));
+ match stash_command {
+ ("apply", sub_matches) => {
+ let stash = sub_matches.get_one::<String>("STASH");
+ println!("Applying {stash:?}");
+ }
+ ("pop", sub_matches) => {
+ let stash = sub_matches.get_one::<String>("STASH");
+ println!("Popping {stash:?}");
+ }
+ ("push", sub_matches) => {
+ let message = sub_matches.get_one::<String>("message");
+ println!("Pushing {message:?}");
+ }
+ (name, _) => {
+ unreachable!("Unsupported subcommand `{}`", name)
+ }
+ }
+ }
+ Some((ext, sub_matches)) => {
+ let args = sub_matches
+ .get_many::<OsString>("")
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>();
+ println!("Calling out to {ext:?} with {args:?}");
+ }
+ _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable!()
+ }
+
+ // Continued program logic goes here...
+}
diff --git a/examples/multicall-busybox.md b/examples/multicall-busybox.md
new file mode 100644
index 0000000..e84b263
--- /dev/null
+++ b/examples/multicall-busybox.md
@@ -0,0 +1,39 @@
+See the documentation for [`Command::multicall`][crate::Command::multicall] for rationale.
+
+This example omits every command except true and false,
+which are the most trivial to implement,
+```console
+$ busybox true
+? 0
+
+$ busybox false
+? 1
+
+```
+*Note: without the links setup, we can't demonstrate the multicall behavior*
+
+But includes the `--install` option as an example of why it can be useful
+for the main program to take arguments that aren't applet subcommands.
+```console
+$ busybox --install
+? failed
+...
+
+```
+
+Though users must pass something:
+```console
+$ busybox
+? failed
+Usage: busybox [OPTIONS] [APPLET]
+
+APPLETS:
+ true does nothing successfully
+ false does nothing unsuccessfully
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ --install <install> Install hardlinks for all subcommands in path
+ -h, --help Print help
+
+```
diff --git a/examples/multicall-busybox.rs b/examples/multicall-busybox.rs
new file mode 100644
index 0000000..9260e1d
--- /dev/null
+++ b/examples/multicall-busybox.rs
@@ -0,0 +1,47 @@
+use std::path::PathBuf;
+use std::process::exit;
+
+use clap::{value_parser, Arg, ArgAction, Command};
+
+fn applet_commands() -> [Command; 2] {
+ [
+ Command::new("true").about("does nothing successfully"),
+ Command::new("false").about("does nothing unsuccessfully"),
+ ]
+}
+
+fn main() {
+ let cmd = Command::new(env!("CARGO_CRATE_NAME"))
+ .multicall(true)
+ .subcommand(
+ Command::new("busybox")
+ .arg_required_else_help(true)
+ .subcommand_value_name("APPLET")
+ .subcommand_help_heading("APPLETS")
+ .arg(
+ Arg::new("install")
+ .long("install")
+ .help("Install hardlinks for all subcommands in path")
+ .exclusive(true)
+ .action(ArgAction::Set)
+ .default_missing_value("/usr/local/bin")
+ .value_parser(value_parser!(PathBuf)),
+ )
+ .subcommands(applet_commands()),
+ )
+ .subcommands(applet_commands());
+
+ let matches = cmd.get_matches();
+ let mut subcommand = matches.subcommand();
+ if let Some(("busybox", cmd)) = subcommand {
+ if cmd.contains_id("install") {
+ unimplemented!("Make hardlinks to the executable here");
+ }
+ subcommand = cmd.subcommand();
+ }
+ match subcommand {
+ Some(("false", _)) => exit(1),
+ Some(("true", _)) => exit(0),
+ _ => unreachable!("parser should ensure only valid subcommand names are used"),
+ }
+}
diff --git a/examples/multicall-hostname.md b/examples/multicall-hostname.md
new file mode 100644
index 0000000..0df1274
--- /dev/null
+++ b/examples/multicall-hostname.md
@@ -0,0 +1,10 @@
+See the documentation for [`Command::multicall`][crate::Command::multicall] for rationale.
+
+This example omits the implementation of displaying address config
+
+```console
+$ hostname
+www
+
+```
+*Note: without the links setup, we can't demonstrate the multicall behavior*
diff --git a/examples/multicall-hostname.rs b/examples/multicall-hostname.rs
new file mode 100644
index 0000000..b57680a
--- /dev/null
+++ b/examples/multicall-hostname.rs
@@ -0,0 +1,17 @@
+use clap::Command;
+
+fn main() {
+ let cmd = Command::new(env!("CARGO_CRATE_NAME"))
+ .multicall(true)
+ .arg_required_else_help(true)
+ .subcommand_value_name("APPLET")
+ .subcommand_help_heading("APPLETS")
+ .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
+ .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
+
+ match cmd.get_matches().subcommand_name() {
+ Some("hostname") => println!("www"),
+ Some("dnsdomainname") => println!("example.com"),
+ _ => unreachable!("parser should ensure only valid subcommand names are used"),
+ }
+}
diff --git a/examples/pacman.md b/examples/pacman.md
new file mode 100644
index 0000000..b02cf8f
--- /dev/null
+++ b/examples/pacman.md
@@ -0,0 +1,79 @@
+[`pacman`](https://wiki.archlinux.org/index.php/pacman) defines subcommands via flags.
+
+Here, `-S` is a short flag subcommand:
+```console
+$ pacman -S package
+Installing package...
+
+```
+
+Here `--sync` is a long flag subcommand:
+```console
+$ pacman --sync package
+Installing package...
+
+```
+
+Now the short flag subcommand (`-S`) with a long flag:
+```console
+$ pacman -S --search name
+Searching for name...
+
+```
+
+And the various forms of short flags that work:
+```console
+$ pacman -S -s name
+Searching for name...
+
+$ pacman -Ss name
+Searching for name...
+
+```
+*(users can "stack" short subcommands with short flags or with other short flag subcommands)*
+
+In the help, this looks like:
+```console
+$ pacman -h
+package manager utility
+
+Usage: pacman[EXE] <COMMAND>
+
+Commands:
+ query, -Q, --query Query the package database.
+ sync, -S, --sync Synchronize packages.
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ pacman -S -h
+Synchronize packages.
+
+Usage: pacman[EXE] {sync|--sync|-S} [OPTIONS] [package]...
+
+Arguments:
+ [package]... packages
+
+Options:
+ -s, --search <search>... search remote repositories for matching strings
+ -i, --info view package information
+ -h, --help Print help
+
+```
+
+And errors:
+```console
+$ pacman -S -s foo -i bar
+? failed
+error: the argument '--search <search>...' cannot be used with '--info'
+
+Usage: pacman[EXE] {sync|--sync|-S} --search <search>... <package>...
+
+For more information, try '--help'.
+
+```
+
+**NOTE:** Keep in mind that subcommands, flags, and long flags are *case sensitive*: `-Q` and `-q` are different flags/subcommands. For example, you can have both `-Q` subcommand and `-q` flag, and they will be properly disambiguated.
+Let's make a quick program to illustrate.
diff --git a/examples/pacman.rs b/examples/pacman.rs
new file mode 100644
index 0000000..7ab30db
--- /dev/null
+++ b/examples/pacman.rs
@@ -0,0 +1,111 @@
+use clap::{Arg, ArgAction, Command};
+
+fn main() {
+ let matches = Command::new("pacman")
+ .about("package manager utility")
+ .version("5.2.1")
+ .subcommand_required(true)
+ .arg_required_else_help(true)
+ .author("Pacman Development Team")
+ // Query subcommand
+ //
+ // Only a few of its arguments are implemented below.
+ .subcommand(
+ Command::new("query")
+ .short_flag('Q')
+ .long_flag("query")
+ .about("Query the package database.")
+ .arg(
+ Arg::new("search")
+ .short('s')
+ .long("search")
+ .help("search locally installed packages for matching strings")
+ .conflicts_with("info")
+ .action(ArgAction::Set)
+ .num_args(1..),
+ )
+ .arg(
+ Arg::new("info")
+ .long("info")
+ .short('i')
+ .conflicts_with("search")
+ .help("view package information")
+ .action(ArgAction::Set)
+ .num_args(1..),
+ ),
+ )
+ // Sync subcommand
+ //
+ // Only a few of its arguments are implemented below.
+ .subcommand(
+ Command::new("sync")
+ .short_flag('S')
+ .long_flag("sync")
+ .about("Synchronize packages.")
+ .arg(
+ Arg::new("search")
+ .short('s')
+ .long("search")
+ .conflicts_with("info")
+ .action(ArgAction::Set)
+ .num_args(1..)
+ .help("search remote repositories for matching strings"),
+ )
+ .arg(
+ Arg::new("info")
+ .long("info")
+ .conflicts_with("search")
+ .short('i')
+ .action(ArgAction::SetTrue)
+ .help("view package information"),
+ )
+ .arg(
+ Arg::new("package")
+ .help("packages")
+ .required_unless_present("search")
+ .action(ArgAction::Set)
+ .num_args(1..),
+ ),
+ )
+ .get_matches();
+
+ match matches.subcommand() {
+ Some(("sync", sync_matches)) => {
+ if sync_matches.contains_id("search") {
+ let packages: Vec<_> = sync_matches
+ .get_many::<String>("search")
+ .expect("contains_id")
+ .map(|s| s.as_str())
+ .collect();
+ let values = packages.join(", ");
+ println!("Searching for {values}...");
+ return;
+ }
+
+ let packages: Vec<_> = sync_matches
+ .get_many::<String>("package")
+ .expect("is present")
+ .map(|s| s.as_str())
+ .collect();
+ let values = packages.join(", ");
+
+ if sync_matches.get_flag("info") {
+ println!("Retrieving info for {values}...");
+ } else {
+ println!("Installing {values}...");
+ }
+ }
+ Some(("query", query_matches)) => {
+ if let Some(packages) = query_matches.get_many::<String>("info") {
+ let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
+ println!("Retrieving info for {comma_sep}...");
+ } else if let Some(queries) = query_matches.get_many::<String>("search") {
+ let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
+ println!("Searching Locally for {comma_sep}...");
+ } else {
+ println!("Displaying all locally installed packages...");
+ }
+ }
+ _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
+ }
+}
diff --git a/examples/repl.rs b/examples/repl.rs
new file mode 100644
index 0000000..2806ac8
--- /dev/null
+++ b/examples/repl.rs
@@ -0,0 +1,92 @@
+use std::io::Write;
+
+use clap::Command;
+
+fn main() -> Result<(), String> {
+ loop {
+ let line = readline()?;
+ let line = line.trim();
+ if line.is_empty() {
+ continue;
+ }
+
+ match respond(line) {
+ Ok(quit) => {
+ if quit {
+ break;
+ }
+ }
+ Err(err) => {
+ write!(std::io::stdout(), "{err}").map_err(|e| e.to_string())?;
+ std::io::stdout().flush().map_err(|e| e.to_string())?;
+ }
+ }
+ }
+
+ Ok(())
+}
+
+fn respond(line: &str) -> Result<bool, String> {
+ let args = shlex::split(line).ok_or("error: Invalid quoting")?;
+ let matches = cli()
+ .try_get_matches_from(args)
+ .map_err(|e| e.to_string())?;
+ match matches.subcommand() {
+ Some(("ping", _matches)) => {
+ write!(std::io::stdout(), "Pong").map_err(|e| e.to_string())?;
+ std::io::stdout().flush().map_err(|e| e.to_string())?;
+ }
+ Some(("quit", _matches)) => {
+ write!(std::io::stdout(), "Exiting ...").map_err(|e| e.to_string())?;
+ std::io::stdout().flush().map_err(|e| e.to_string())?;
+ return Ok(true);
+ }
+ Some((name, _matches)) => unimplemented!("{}", name),
+ None => unreachable!("subcommand required"),
+ }
+
+ Ok(false)
+}
+
+fn cli() -> Command {
+ // strip out usage
+ const PARSER_TEMPLATE: &str = "\
+ {all-args}
+ ";
+ // strip out name/version
+ const APPLET_TEMPLATE: &str = "\
+ {about-with-newline}\n\
+ {usage-heading}\n {usage}\n\
+ \n\
+ {all-args}{after-help}\
+ ";
+
+ Command::new("repl")
+ .multicall(true)
+ .arg_required_else_help(true)
+ .subcommand_required(true)
+ .subcommand_value_name("APPLET")
+ .subcommand_help_heading("APPLETS")
+ .help_template(PARSER_TEMPLATE)
+ .subcommand(
+ Command::new("ping")
+ .about("Get a response")
+ .help_template(APPLET_TEMPLATE),
+ )
+ .subcommand(
+ Command::new("quit")
+ .alias("exit")
+ .about("Quit the REPL")
+ .help_template(APPLET_TEMPLATE),
+ )
+}
+
+fn readline() -> Result<String, String> {
+ write!(std::io::stdout(), "$ ").map_err(|e| e.to_string())?;
+ std::io::stdout().flush().map_err(|e| e.to_string())?;
+ let mut buffer = String::new();
+ std::io::stdin()
+ .read_line(&mut buffer)
+ .map_err(|e| e.to_string())?;
+ Ok(buffer)
+}
diff --git a/examples/tutorial_builder/01_quick.md b/examples/tutorial_builder/01_quick.md
new file mode 100644
index 0000000..bdba15c
--- /dev/null
+++ b/examples/tutorial_builder/01_quick.md
@@ -0,0 +1,35 @@
+```console
+$ 01_quick --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 01_quick[EXE] [OPTIONS] [name] [COMMAND]
+
+Commands:
+ test does testing things
+ help Print this message or the help of the given subcommand(s)
+
+Arguments:
+ [name] Optional name to operate on
+
+Options:
+ -c, --config <FILE> Sets a custom config file
+ -d, --debug... Turn debugging information on
+ -h, --help Print help
+ -V, --version Print version
+
+```
+
+By default, the program does nothing:
+```console
+$ 01_quick
+Debug mode is off
+
+```
+
+But you can mix and match the various features
+```console
+$ 01_quick -dd test
+Debug mode is on
+Not printing testing lists...
+
+```
diff --git a/examples/tutorial_builder/01_quick.rs b/examples/tutorial_builder/01_quick.rs
new file mode 100644
index 0000000..8126e33
--- /dev/null
+++ b/examples/tutorial_builder/01_quick.rs
@@ -0,0 +1,60 @@
+use std::path::PathBuf;
+
+use clap::{arg, command, value_parser, ArgAction, Command};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(arg!([name] "Optional name to operate on"))
+ .arg(
+ arg!(
+ -c --config <FILE> "Sets a custom config file"
+ )
+ // We don't have syntax yet for optional options, so manually calling `required`
+ .required(false)
+ .value_parser(value_parser!(PathBuf)),
+ )
+ .arg(arg!(
+ -d --debug ... "Turn debugging information on"
+ ))
+ .subcommand(
+ Command::new("test")
+ .about("does testing things")
+ .arg(arg!(-l --list "lists test values").action(ArgAction::SetTrue)),
+ )
+ .get_matches();
+
+ // You can check the value provided by positional arguments, or option arguments
+ if let Some(name) = matches.get_one::<String>("name") {
+ println!("Value for name: {}", name);
+ }
+
+ if let Some(config_path) = matches.get_one::<PathBuf>("config") {
+ println!("Value for config: {}", config_path.display());
+ }
+
+ // You can see how many times a particular flag or argument occurred
+ // Note, only flags can have multiple occurrences
+ match matches
+ .get_one::<u8>("debug")
+ .expect("Count's are defaulted")
+ {
+ 0 => println!("Debug mode is off"),
+ 1 => println!("Debug mode is kind of on"),
+ 2 => println!("Debug mode is on"),
+ _ => println!("Don't be crazy"),
+ }
+
+ // You can check for the existence of subcommands, and if found use their
+ // matches just as you would the top level cmd
+ if let Some(matches) = matches.subcommand_matches("test") {
+ // "$ myapp test" was run
+ if matches.get_flag("list") {
+ // "$ myapp test -l" was run
+ println!("Printing testing lists...");
+ } else {
+ println!("Not printing testing lists...");
+ }
+ }
+
+ // Continued program logic goes here...
+}
diff --git a/examples/tutorial_builder/02_app_settings.md b/examples/tutorial_builder/02_app_settings.md
new file mode 100644
index 0000000..3ac9a95
--- /dev/null
+++ b/examples/tutorial_builder/02_app_settings.md
@@ -0,0 +1,17 @@
+```console
+$ 02_app_settings --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 02_app_settings[EXE] --two <VALUE> --one <VALUE>
+
+Options:
+ --two <VALUE>
+
+ --one <VALUE>
+
+ -h, --help
+ Print help
+ -V, --version
+ Print version
+
+```
diff --git a/examples/tutorial_builder/02_app_settings.rs b/examples/tutorial_builder/02_app_settings.rs
new file mode 100644
index 0000000..4e30ec9
--- /dev/null
+++ b/examples/tutorial_builder/02_app_settings.rs
@@ -0,0 +1,18 @@
+use clap::{arg, command, ArgAction};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .next_line_help(true)
+ .arg(arg!(--two <VALUE>).required(true).action(ArgAction::Set))
+ .arg(arg!(--one <VALUE>).required(true).action(ArgAction::Set))
+ .get_matches();
+
+ println!(
+ "two: {:?}",
+ matches.get_one::<String>("two").expect("required")
+ );
+ println!(
+ "one: {:?}",
+ matches.get_one::<String>("one").expect("required")
+ );
+}
diff --git a/examples/tutorial_builder/02_apps.md b/examples/tutorial_builder/02_apps.md
new file mode 100644
index 0000000..1f8b071
--- /dev/null
+++ b/examples/tutorial_builder/02_apps.md
@@ -0,0 +1,16 @@
+```console
+$ 02_apps --help
+Does awesome things
+
+Usage: 02_apps[EXE] --two <VALUE> --one <VALUE>
+
+Options:
+ --two <VALUE>
+ --one <VALUE>
+ -h, --help Print help
+ -V, --version Print version
+
+$ 02_apps --version
+MyApp 1.0
+
+```
diff --git a/examples/tutorial_builder/02_apps.rs b/examples/tutorial_builder/02_apps.rs
new file mode 100644
index 0000000..7d98e6c
--- /dev/null
+++ b/examples/tutorial_builder/02_apps.rs
@@ -0,0 +1,20 @@
+use clap::{arg, Command};
+
+fn main() {
+ let matches = Command::new("MyApp")
+ .version("1.0")
+ .author("Kevin K. <kbknapp@gmail.com>")
+ .about("Does awesome things")
+ .arg(arg!(--two <VALUE>).required(true))
+ .arg(arg!(--one <VALUE>).required(true))
+ .get_matches();
+
+ println!(
+ "two: {:?}",
+ matches.get_one::<String>("two").expect("required")
+ );
+ println!(
+ "one: {:?}",
+ matches.get_one::<String>("one").expect("required")
+ );
+}
diff --git a/examples/tutorial_builder/02_crate.md b/examples/tutorial_builder/02_crate.md
new file mode 100644
index 0000000..a0d21b3
--- /dev/null
+++ b/examples/tutorial_builder/02_crate.md
@@ -0,0 +1,16 @@
+```console
+$ 02_crate --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 02_crate[EXE] --two <VALUE> --one <VALUE>
+
+Options:
+ --two <VALUE>
+ --one <VALUE>
+ -h, --help Print help
+ -V, --version Print version
+
+$ 02_crate --version
+clap [..]
+
+```
diff --git a/examples/tutorial_builder/02_crate.rs b/examples/tutorial_builder/02_crate.rs
new file mode 100644
index 0000000..ad6bb47
--- /dev/null
+++ b/examples/tutorial_builder/02_crate.rs
@@ -0,0 +1,18 @@
+use clap::{arg, command};
+
+fn main() {
+ // requires `cargo` feature, reading name, version, author, and description from `Cargo.toml`
+ let matches = command!()
+ .arg(arg!(--two <VALUE>).required(true))
+ .arg(arg!(--one <VALUE>).required(true))
+ .get_matches();
+
+ println!(
+ "two: {:?}",
+ matches.get_one::<String>("two").expect("required")
+ );
+ println!(
+ "one: {:?}",
+ matches.get_one::<String>("one").expect("required")
+ );
+}
diff --git a/examples/tutorial_builder/03_01_flag_bool.md b/examples/tutorial_builder/03_01_flag_bool.md
new file mode 100644
index 0000000..feec8e0
--- /dev/null
+++ b/examples/tutorial_builder/03_01_flag_bool.md
@@ -0,0 +1,26 @@
+```console
+$ 03_01_flag_bool --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_01_flag_bool[EXE] [OPTIONS]
+
+Options:
+ -v, --verbose
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_01_flag_bool
+verbose: false
+
+$ 03_01_flag_bool --verbose
+verbose: true
+
+$ 03_01_flag_bool --verbose --verbose
+? failed
+error: the argument '--verbose' cannot be used multiple times
+
+Usage: 03_01_flag_bool[EXE] [OPTIONS]
+
+For more information, try '--help'.
+
+```
diff --git a/examples/tutorial_builder/03_01_flag_bool.rs b/examples/tutorial_builder/03_01_flag_bool.rs
new file mode 100644
index 0000000..03f2f17
--- /dev/null
+++ b/examples/tutorial_builder/03_01_flag_bool.rs
@@ -0,0 +1,14 @@
+use clap::{command, Arg, ArgAction};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(
+ Arg::new("verbose")
+ .short('v')
+ .long("verbose")
+ .action(ArgAction::SetTrue),
+ )
+ .get_matches();
+
+ println!("verbose: {:?}", matches.get_flag("verbose"));
+}
diff --git a/examples/tutorial_builder/03_01_flag_count.md b/examples/tutorial_builder/03_01_flag_count.md
new file mode 100644
index 0000000..5e964b6
--- /dev/null
+++ b/examples/tutorial_builder/03_01_flag_count.md
@@ -0,0 +1,21 @@
+```console
+$ 03_01_flag_count --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_01_flag_count[EXE] [OPTIONS]
+
+Options:
+ -v, --verbose...
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_01_flag_count
+verbose: 0
+
+$ 03_01_flag_count --verbose
+verbose: 1
+
+$ 03_01_flag_count --verbose --verbose
+verbose: 2
+
+```
diff --git a/examples/tutorial_builder/03_01_flag_count.rs b/examples/tutorial_builder/03_01_flag_count.rs
new file mode 100644
index 0000000..492f7d4
--- /dev/null
+++ b/examples/tutorial_builder/03_01_flag_count.rs
@@ -0,0 +1,14 @@
+use clap::{command, Arg, ArgAction};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(
+ Arg::new("verbose")
+ .short('v')
+ .long("verbose")
+ .action(ArgAction::Count),
+ )
+ .get_matches();
+
+ println!("verbose: {:?}", matches.get_count("verbose"));
+}
diff --git a/examples/tutorial_builder/03_02_option.md b/examples/tutorial_builder/03_02_option.md
new file mode 100644
index 0000000..42b81fd
--- /dev/null
+++ b/examples/tutorial_builder/03_02_option.md
@@ -0,0 +1,30 @@
+```console
+$ 03_02_option --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_02_option[EXE] [OPTIONS]
+
+Options:
+ -n, --name <name>
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_02_option
+name: None
+
+$ 03_02_option --name bob
+name: Some("bob")
+
+$ 03_02_option --name=bob
+name: Some("bob")
+
+$ 03_02_option -n bob
+name: Some("bob")
+
+$ 03_02_option -n=bob
+name: Some("bob")
+
+$ 03_02_option -nbob
+name: Some("bob")
+
+```
diff --git a/examples/tutorial_builder/03_02_option.rs b/examples/tutorial_builder/03_02_option.rs
new file mode 100644
index 0000000..e9ba3e4
--- /dev/null
+++ b/examples/tutorial_builder/03_02_option.rs
@@ -0,0 +1,9 @@
+use clap::{command, Arg};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(Arg::new("name").short('n').long("name"))
+ .get_matches();
+
+ println!("name: {:?}", matches.get_one::<String>("name"));
+}
diff --git a/examples/tutorial_builder/03_02_option_mult.md b/examples/tutorial_builder/03_02_option_mult.md
new file mode 100644
index 0000000..659748e
--- /dev/null
+++ b/examples/tutorial_builder/03_02_option_mult.md
@@ -0,0 +1,30 @@
+```console
+$ 03_02_option_mult --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_02_option_mult[EXE] [OPTIONS]
+
+Options:
+ -n, --name <name>
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_02_option_mult
+name: None
+
+$ 03_02_option_mult --name bob
+name: Some("bob")
+
+$ 03_02_option_mult --name=bob
+name: Some("bob")
+
+$ 03_02_option_mult -n bob
+name: Some("bob")
+
+$ 03_02_option_mult -n=bob
+name: Some("bob")
+
+$ 03_02_option_mult -nbob
+name: Some("bob")
+
+```
diff --git a/examples/tutorial_builder/03_02_option_mult.rs b/examples/tutorial_builder/03_02_option_mult.rs
new file mode 100644
index 0000000..1370477
--- /dev/null
+++ b/examples/tutorial_builder/03_02_option_mult.rs
@@ -0,0 +1,14 @@
+use clap::{command, Arg, ArgAction};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(
+ Arg::new("name")
+ .short('n')
+ .long("name")
+ .action(ArgAction::Append),
+ )
+ .get_matches();
+
+ println!("name: {:?}", matches.get_one::<String>("name"));
+}
diff --git a/examples/tutorial_builder/03_03_positional.md b/examples/tutorial_builder/03_03_positional.md
new file mode 100644
index 0000000..d8d49f3
--- /dev/null
+++ b/examples/tutorial_builder/03_03_positional.md
@@ -0,0 +1,20 @@
+```console
+$ 03_03_positional --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_03_positional[EXE] [name]
+
+Arguments:
+ [name]
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_03_positional
+name: None
+
+$ 03_03_positional bob
+name: Some("bob")
+
+```
diff --git a/examples/tutorial_builder/03_03_positional.rs b/examples/tutorial_builder/03_03_positional.rs
new file mode 100644
index 0000000..f652d27
--- /dev/null
+++ b/examples/tutorial_builder/03_03_positional.rs
@@ -0,0 +1,9 @@
+use clap::{command, Arg};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(Arg::new("name"))
+ .get_matches();
+
+ println!("name: {:?}", matches.get_one::<String>("name"));
+}
diff --git a/examples/tutorial_builder/03_03_positional_mult.md b/examples/tutorial_builder/03_03_positional_mult.md
new file mode 100644
index 0000000..174ddd9
--- /dev/null
+++ b/examples/tutorial_builder/03_03_positional_mult.md
@@ -0,0 +1,23 @@
+```console
+$ 03_03_positional_mult --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_03_positional_mult[EXE] [name]...
+
+Arguments:
+ [name]...
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_03_positional_mult
+names: []
+
+$ 03_03_positional_mult bob
+names: ["bob"]
+
+$ 03_03_positional_mult bob john
+names: ["bob", "john"]
+
+```
diff --git a/examples/tutorial_builder/03_03_positional_mult.rs b/examples/tutorial_builder/03_03_positional_mult.rs
new file mode 100644
index 0000000..bcd288d
--- /dev/null
+++ b/examples/tutorial_builder/03_03_positional_mult.rs
@@ -0,0 +1,15 @@
+use clap::{command, Arg, ArgAction};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(Arg::new("name").action(ArgAction::Append))
+ .get_matches();
+
+ let args = matches
+ .get_many::<String>("name")
+ .unwrap_or_default()
+ .map(|v| v.as_str())
+ .collect::<Vec<_>>();
+
+ println!("names: {:?}", &args);
+}
diff --git a/examples/tutorial_builder/03_04_subcommands.md b/examples/tutorial_builder/03_04_subcommands.md
new file mode 100644
index 0000000..7c73add
--- /dev/null
+++ b/examples/tutorial_builder/03_04_subcommands.md
@@ -0,0 +1,58 @@
+```console
+$ 03_04_subcommands help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_04_subcommands[EXE] <COMMAND>
+
+Commands:
+ add Adds files to myapp
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_04_subcommands help add
+Adds files to myapp
+
+Usage: 03_04_subcommands[EXE] add [NAME]
+
+Arguments:
+ [NAME]
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_04_subcommands add bob
+'myapp add' was used, name is: Some("bob")
+
+```
+
+Because we set [`Command::arg_required_else_help`][crate::Command::arg_required_else_help]:
+```console
+$ 03_04_subcommands
+? failed
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_04_subcommands[EXE] <COMMAND>
+
+Commands:
+ add Adds files to myapp
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+```
+
+Because we set [`Command::propagate_version`][crate::Command::propagate_version]:
+```console
+$ 03_04_subcommands --version
+clap [..]
+
+$ 03_04_subcommands add --version
+clap-add [..]
+
+```
diff --git a/examples/tutorial_builder/03_04_subcommands.rs b/examples/tutorial_builder/03_04_subcommands.rs
new file mode 100644
index 0000000..fbe2380
--- /dev/null
+++ b/examples/tutorial_builder/03_04_subcommands.rs
@@ -0,0 +1,22 @@
+use clap::{arg, command, Command};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .propagate_version(true)
+ .subcommand_required(true)
+ .arg_required_else_help(true)
+ .subcommand(
+ Command::new("add")
+ .about("Adds files to myapp")
+ .arg(arg!([NAME])),
+ )
+ .get_matches();
+
+ match matches.subcommand() {
+ Some(("add", sub_matches)) => println!(
+ "'myapp add' was used, name is: {:?}",
+ sub_matches.get_one::<String>("NAME")
+ ),
+ _ => unreachable!("Exhausted list of subcommands and subcommand_required prevents `None`"),
+ }
+}
diff --git a/examples/tutorial_builder/03_05_default_values.md b/examples/tutorial_builder/03_05_default_values.md
new file mode 100644
index 0000000..b62a415
--- /dev/null
+++ b/examples/tutorial_builder/03_05_default_values.md
@@ -0,0 +1,20 @@
+```console
+$ 03_05_default_values --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_05_default_values[EXE] [PORT]
+
+Arguments:
+ [PORT] [default: 2020]
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_05_default_values
+port: 2020
+
+$ 03_05_default_values 22
+port: 22
+
+```
diff --git a/examples/tutorial_builder/03_05_default_values.rs b/examples/tutorial_builder/03_05_default_values.rs
new file mode 100644
index 0000000..d259ee0
--- /dev/null
+++ b/examples/tutorial_builder/03_05_default_values.rs
@@ -0,0 +1,18 @@
+use clap::{arg, command, value_parser};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(
+ arg!([PORT])
+ .value_parser(value_parser!(u16))
+ .default_value("2020"),
+ )
+ .get_matches();
+
+ println!(
+ "port: {:?}",
+ matches
+ .get_one::<u16>("PORT")
+ .expect("default ensures there is always a value")
+ );
+}
diff --git a/examples/tutorial_builder/04_01_enum.md b/examples/tutorial_builder/04_01_enum.md
new file mode 100644
index 0000000..ec4c0ae
--- /dev/null
+++ b/examples/tutorial_builder/04_01_enum.md
@@ -0,0 +1,47 @@
+```console
+$ 04_01_enum --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 04_01_enum[EXE] <MODE>
+
+Arguments:
+ <MODE>
+ What mode to run the program in
+
+ Possible values:
+ - fast: Run swiftly
+ - slow: Crawl slowly but steadily
+
+Options:
+ -h, --help
+ Print help (see a summary with '-h')
+
+ -V, --version
+ Print version
+
+$ 04_01_enum -h
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 04_01_enum[EXE] <MODE>
+
+Arguments:
+ <MODE> What mode to run the program in [possible values: fast, slow]
+
+Options:
+ -h, --help Print help (see more with '--help')
+ -V, --version Print version
+
+$ 04_01_enum fast
+Hare
+
+$ 04_01_enum slow
+Tortoise
+
+$ 04_01_enum medium
+? failed
+error: invalid value 'medium' for '<MODE>'
+ [possible values: fast, slow]
+
+For more information, try '--help'.
+
+```
diff --git a/examples/tutorial_builder/04_01_enum.rs b/examples/tutorial_builder/04_01_enum.rs
new file mode 100644
index 0000000..1afa018
--- /dev/null
+++ b/examples/tutorial_builder/04_01_enum.rs
@@ -0,0 +1,66 @@
+use clap::{arg, builder::PossibleValue, command, value_parser, ValueEnum};
+
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
+enum Mode {
+ Fast,
+ Slow,
+}
+
+// Can also be derived with feature flag `derive`
+impl ValueEnum for Mode {
+ fn value_variants<'a>() -> &'a [Self] {
+ &[Mode::Fast, Mode::Slow]
+ }
+
+ fn to_possible_value<'a>(&self) -> Option<PossibleValue> {
+ Some(match self {
+ Mode::Fast => PossibleValue::new("fast").help("Run swiftly"),
+ Mode::Slow => PossibleValue::new("slow").help("Crawl slowly but steadily"),
+ })
+ }
+}
+
+impl std::fmt::Display for Mode {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ self.to_possible_value()
+ .expect("no values are skipped")
+ .get_name()
+ .fmt(f)
+ }
+}
+
+impl std::str::FromStr for Mode {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ for variant in Self::value_variants() {
+ if variant.to_possible_value().unwrap().matches(s, false) {
+ return Ok(*variant);
+ }
+ }
+ Err(format!("invalid variant: {}", s))
+ }
+}
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(
+ arg!(<MODE>)
+ .help("What mode to run the program in")
+ .value_parser(value_parser!(Mode)),
+ )
+ .get_matches();
+
+ // Note, it's safe to call unwrap() because the arg is required
+ match matches
+ .get_one::<Mode>("MODE")
+ .expect("'MODE' is required and parsing will fail if its missing")
+ {
+ Mode::Fast => {
+ println!("Hare");
+ }
+ Mode::Slow => {
+ println!("Tortoise");
+ }
+ }
+}
diff --git a/examples/tutorial_builder/04_01_possible.md b/examples/tutorial_builder/04_01_possible.md
new file mode 100644
index 0000000..fa2c835
--- /dev/null
+++ b/examples/tutorial_builder/04_01_possible.md
@@ -0,0 +1,27 @@
+```console
+$ 04_01_possible --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 04_01_possible[EXE] <MODE>
+
+Arguments:
+ <MODE> What mode to run the program in [possible values: fast, slow]
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 04_01_possible fast
+Hare
+
+$ 04_01_possible slow
+Tortoise
+
+$ 04_01_possible medium
+? failed
+error: invalid value 'medium' for '<MODE>'
+ [possible values: fast, slow]
+
+For more information, try '--help'.
+
+```
diff --git a/examples/tutorial_builder/04_01_possible.rs b/examples/tutorial_builder/04_01_possible.rs
new file mode 100644
index 0000000..3da7aca
--- /dev/null
+++ b/examples/tutorial_builder/04_01_possible.rs
@@ -0,0 +1,26 @@
+use clap::{arg, command};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(
+ arg!(<MODE>)
+ .help("What mode to run the program in")
+ .value_parser(["fast", "slow"]),
+ )
+ .get_matches();
+
+ // Note, it's safe to call unwrap() because the arg is required
+ match matches
+ .get_one::<String>("MODE")
+ .expect("'MODE' is required and parsing will fail if its missing")
+ .as_str()
+ {
+ "fast" => {
+ println!("Hare");
+ }
+ "slow" => {
+ println!("Tortoise");
+ }
+ _ => unreachable!(),
+ }
+}
diff --git a/examples/tutorial_builder/04_02_parse.md b/examples/tutorial_builder/04_02_parse.md
new file mode 100644
index 0000000..af03e95
--- /dev/null
+++ b/examples/tutorial_builder/04_02_parse.md
@@ -0,0 +1,29 @@
+```console
+$ 04_02_parse --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 04_02_parse[EXE] <PORT>
+
+Arguments:
+ <PORT> Network port to use
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 04_02_parse 22
+PORT = 22
+
+$ 04_02_parse foobar
+? failed
+error: invalid value 'foobar' for '<PORT>': invalid digit found in string
+
+For more information, try '--help'.
+
+$ 04_02_parse_derive 0
+? failed
+error: invalid value '0' for '<PORT>': 0 is not in 1..=65535
+
+For more information, try '--help'.
+
+```
diff --git a/examples/tutorial_builder/04_02_parse.rs b/examples/tutorial_builder/04_02_parse.rs
new file mode 100644
index 0000000..13f41a1
--- /dev/null
+++ b/examples/tutorial_builder/04_02_parse.rs
@@ -0,0 +1,17 @@
+use clap::{arg, command, value_parser};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(
+ arg!(<PORT>)
+ .help("Network port to use")
+ .value_parser(value_parser!(u16).range(1..)),
+ )
+ .get_matches();
+
+ // Note, it's safe to call unwrap() because the arg is required
+ let port: u16 = *matches
+ .get_one::<u16>("PORT")
+ .expect("'PORT' is required and parsing will fail if its missing");
+ println!("PORT = {}", port);
+}
diff --git a/examples/tutorial_builder/04_02_validate.md b/examples/tutorial_builder/04_02_validate.md
new file mode 100644
index 0000000..949072b
--- /dev/null
+++ b/examples/tutorial_builder/04_02_validate.md
@@ -0,0 +1,29 @@
+```console
+$ 04_02_validate --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 04_02_validate[EXE] <PORT>
+
+Arguments:
+ <PORT> Network port to use
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 04_02_validate 22
+PORT = 22
+
+$ 04_02_validate foobar
+? failed
+error: invalid value 'foobar' for '<PORT>': `foobar` isn't a port number
+
+For more information, try '--help'.
+
+$ 04_02_validate 0
+? failed
+error: invalid value '0' for '<PORT>': port not in range 1-65535
+
+For more information, try '--help'.
+
+```
diff --git a/examples/tutorial_builder/04_02_validate.rs b/examples/tutorial_builder/04_02_validate.rs
new file mode 100644
index 0000000..4690e8e
--- /dev/null
+++ b/examples/tutorial_builder/04_02_validate.rs
@@ -0,0 +1,36 @@
+use std::ops::RangeInclusive;
+
+use clap::{arg, command};
+
+fn main() {
+ let matches = command!() // requires `cargo` feature
+ .arg(
+ arg!(<PORT>)
+ .help("Network port to use")
+ .value_parser(port_in_range),
+ )
+ .get_matches();
+
+ // Note, it's safe to call unwrap() because the arg is required
+ let port: u16 = *matches
+ .get_one::<u16>("PORT")
+ .expect("'PORT' is required and parsing will fail if its missing");
+ println!("PORT = {}", port);
+}
+
+const PORT_RANGE: RangeInclusive<usize> = 1..=65535;
+
+fn port_in_range(s: &str) -> Result<u16, String> {
+ let port: usize = s
+ .parse()
+ .map_err(|_| format!("`{}` isn't a port number", s))?;
+ if PORT_RANGE.contains(&port) {
+ Ok(port as u16)
+ } else {
+ Err(format!(
+ "port not in range {}-{}",
+ PORT_RANGE.start(),
+ PORT_RANGE.end()
+ ))
+ }
+}
diff --git a/examples/tutorial_builder/04_03_relations.md b/examples/tutorial_builder/04_03_relations.md
new file mode 100644
index 0000000..dd0c35a
--- /dev/null
+++ b/examples/tutorial_builder/04_03_relations.md
@@ -0,0 +1,53 @@
+```console
+$ 04_03_relations --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 04_03_relations[EXE] [OPTIONS] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]
+
+Arguments:
+ [INPUT_FILE] some regular input
+
+Options:
+ --set-ver <VER> set version manually
+ --major auto inc major
+ --minor auto inc minor
+ --patch auto inc patch
+ --spec-in <SPEC_IN> some special input argument
+ -c <CONFIG>
+ -h, --help Print help
+ -V, --version Print version
+
+$ 04_03_relations
+? failed
+error: the following required arguments were not provided:
+ <--set-ver <VER>|--major|--minor|--patch>
+
+Usage: 04_03_relations[EXE] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]
+
+For more information, try '--help'.
+
+$ 04_03_relations --major
+Version: 2.2.3
+
+$ 04_03_relations --major --minor
+? failed
+error: the argument '--major' cannot be used with '--minor'
+
+Usage: 04_03_relations[EXE] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]
+
+For more information, try '--help'.
+
+$ 04_03_relations --major -c config.toml
+? failed
+error: the following required arguments were not provided:
+ <INPUT_FILE|--spec-in <SPEC_IN>>
+
+Usage: 04_03_relations[EXE] -c <CONFIG> <--set-ver <VER>|--major|--minor|--patch> <INPUT_FILE|--spec-in <SPEC_IN>>
+
+For more information, try '--help'.
+
+$ 04_03_relations --major -c config.toml --spec-in input.txt
+Version: 2.2.3
+Doing work using input input.txt and config config.toml
+
+```
diff --git a/examples/tutorial_builder/04_03_relations.rs b/examples/tutorial_builder/04_03_relations.rs
new file mode 100644
index 0000000..9d2d3d8
--- /dev/null
+++ b/examples/tutorial_builder/04_03_relations.rs
@@ -0,0 +1,78 @@
+use std::path::PathBuf;
+
+use clap::{arg, command, value_parser, ArgAction, ArgGroup};
+
+fn main() {
+ // Create application like normal
+ let matches = command!() // requires `cargo` feature
+ // Add the version arguments
+ .arg(arg!(--"set-ver" <VER> "set version manually"))
+ .arg(arg!(--major "auto inc major").action(ArgAction::SetTrue))
+ .arg(arg!(--minor "auto inc minor").action(ArgAction::SetTrue))
+ .arg(arg!(--patch "auto inc patch").action(ArgAction::SetTrue))
+ // Create a group, make it required, and add the above arguments
+ .group(
+ ArgGroup::new("vers")
+ .required(true)
+ .args(["set-ver", "major", "minor", "patch"]),
+ )
+ // Arguments can also be added to a group individually, these two arguments
+ // are part of the "input" group which is not required
+ .arg(
+ arg!([INPUT_FILE] "some regular input")
+ .value_parser(value_parser!(PathBuf))
+ .group("input"),
+ )
+ .arg(
+ arg!(--"spec-in" <SPEC_IN> "some special input argument")
+ .value_parser(value_parser!(PathBuf))
+ .group("input"),
+ )
+ // Now let's assume we have a -c [config] argument which requires one of
+ // (but **not** both) the "input" arguments
+ .arg(
+ arg!(config: -c <CONFIG>)
+ .value_parser(value_parser!(PathBuf))
+ .requires("input"),
+ )
+ .get_matches();
+
+ // Let's assume the old version 1.2.3
+ let mut major = 1;
+ let mut minor = 2;
+ let mut patch = 3;
+
+ // See if --set-ver was used to set the version manually
+ let version = if let Some(ver) = matches.get_one::<String>("set-ver") {
+ ver.to_owned()
+ } else {
+ // Increment the one requested (in a real program, we'd reset the lower numbers)
+ let (maj, min, pat) = (
+ matches.get_flag("major"),
+ matches.get_flag("minor"),
+ matches.get_flag("patch"),
+ );
+ match (maj, min, pat) {
+ (true, _, _) => major += 1,
+ (_, true, _) => minor += 1,
+ (_, _, true) => patch += 1,
+ _ => unreachable!(),
+ };
+ format!("{}.{}.{}", major, minor, patch)
+ };
+
+ println!("Version: {}", version);
+
+ // Check for usage of -c
+ if matches.contains_id("config") {
+ let input = matches
+ .get_one::<PathBuf>("INPUT_FILE")
+ .unwrap_or_else(|| matches.get_one::<PathBuf>("spec-in").unwrap())
+ .display();
+ println!(
+ "Doing work using input {} and config {}",
+ input,
+ matches.get_one::<PathBuf>("config").unwrap().display()
+ );
+ }
+}
diff --git a/examples/tutorial_builder/04_04_custom.md b/examples/tutorial_builder/04_04_custom.md
new file mode 100644
index 0000000..0a83eb9
--- /dev/null
+++ b/examples/tutorial_builder/04_04_custom.md
@@ -0,0 +1,52 @@
+```console
+$ 04_04_custom --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]
+
+Arguments:
+ [INPUT_FILE] some regular input
+
+Options:
+ --set-ver <VER> set version manually
+ --major auto inc major
+ --minor auto inc minor
+ --patch auto inc patch
+ --spec-in <SPEC_IN> some special input argument
+ -c <CONFIG>
+ -h, --help Print help
+ -V, --version Print version
+
+$ 04_04_custom
+? failed
+error: Can only modify one version field
+
+Usage: 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]
+
+For more information, try '--help'.
+
+$ 04_04_custom --major
+Version: 2.2.3
+
+$ 04_04_custom --major --minor
+? failed
+error: Can only modify one version field
+
+Usage: 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]
+
+For more information, try '--help'.
+
+$ 04_04_custom --major -c config.toml
+? failed
+Version: 2.2.3
+error: INPUT_FILE or --spec-in is required when using --config
+
+Usage: 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]
+
+For more information, try '--help'.
+
+$ 04_04_custom --major -c config.toml --spec-in input.txt
+Version: 2.2.3
+Doing work using input input.txt and config config.toml
+
+```
diff --git a/examples/tutorial_builder/04_04_custom.rs b/examples/tutorial_builder/04_04_custom.rs
new file mode 100644
index 0000000..ebbae67
--- /dev/null
+++ b/examples/tutorial_builder/04_04_custom.rs
@@ -0,0 +1,84 @@
+use std::path::PathBuf;
+
+use clap::error::ErrorKind;
+use clap::{arg, command, value_parser, ArgAction};
+
+fn main() {
+ // Create application like normal
+ let mut cmd = command!() // requires `cargo` feature
+ // Add the version arguments
+ .arg(arg!(--"set-ver" <VER> "set version manually"))
+ .arg(arg!(--major "auto inc major").action(ArgAction::SetTrue))
+ .arg(arg!(--minor "auto inc minor").action(ArgAction::SetTrue))
+ .arg(arg!(--patch "auto inc patch").action(ArgAction::SetTrue))
+ // Arguments can also be added to a group individually, these two arguments
+ // are part of the "input" group which is not required
+ .arg(arg!([INPUT_FILE] "some regular input").value_parser(value_parser!(PathBuf)))
+ .arg(
+ arg!(--"spec-in" <SPEC_IN> "some special input argument")
+ .value_parser(value_parser!(PathBuf)),
+ )
+ // Now let's assume we have a -c [config] argument which requires one of
+ // (but **not** both) the "input" arguments
+ .arg(arg!(config: -c <CONFIG>).value_parser(value_parser!(PathBuf)));
+ let matches = cmd.get_matches_mut();
+
+ // Let's assume the old version 1.2.3
+ let mut major = 1;
+ let mut minor = 2;
+ let mut patch = 3;
+
+ // See if --set-ver was used to set the version manually
+ let version = if let Some(ver) = matches.get_one::<String>("set-ver") {
+ if matches.get_flag("major") || matches.get_flag("minor") || matches.get_flag("patch") {
+ cmd.error(
+ ErrorKind::ArgumentConflict,
+ "Can't do relative and absolute version change",
+ )
+ .exit();
+ }
+ ver.to_string()
+ } else {
+ // Increment the one requested (in a real program, we'd reset the lower numbers)
+ let (maj, min, pat) = (
+ matches.get_flag("major"),
+ matches.get_flag("minor"),
+ matches.get_flag("patch"),
+ );
+ match (maj, min, pat) {
+ (true, false, false) => major += 1,
+ (false, true, false) => minor += 1,
+ (false, false, true) => patch += 1,
+ _ => {
+ cmd.error(
+ ErrorKind::ArgumentConflict,
+ "Can only modify one version field",
+ )
+ .exit();
+ }
+ };
+ format!("{}.{}.{}", major, minor, patch)
+ };
+
+ println!("Version: {}", version);
+
+ // Check for usage of -c
+ if matches.contains_id("config") {
+ let input = matches
+ .get_one::<PathBuf>("INPUT_FILE")
+ .or_else(|| matches.get_one::<PathBuf>("spec-in"))
+ .unwrap_or_else(|| {
+ cmd.error(
+ ErrorKind::MissingRequiredArgument,
+ "INPUT_FILE or --spec-in is required when using --config",
+ )
+ .exit()
+ })
+ .display();
+ println!(
+ "Doing work using input {} and config {}",
+ input,
+ matches.get_one::<PathBuf>("config").unwrap().display()
+ );
+ }
+}
diff --git a/examples/tutorial_builder/05_01_assert.rs b/examples/tutorial_builder/05_01_assert.rs
new file mode 100644
index 0000000..90c0a63
--- /dev/null
+++ b/examples/tutorial_builder/05_01_assert.rs
@@ -0,0 +1,25 @@
+use clap::{arg, command, value_parser};
+
+fn main() {
+ let matches = cmd().get_matches();
+
+ // Note, it's safe to call unwrap() because the arg is required
+ let port: usize = *matches
+ .get_one::<usize>("PORT")
+ .expect("'PORT' is required and parsing will fail if its missing");
+ println!("PORT = {}", port);
+}
+
+fn cmd() -> clap::Command {
+ command!() // requires `cargo` feature
+ .arg(
+ arg!(<PORT>)
+ .help("Network port to use")
+ .value_parser(value_parser!(usize)),
+ )
+}
+
+#[test]
+fn verify_cmd() {
+ cmd().debug_assert();
+}
diff --git a/examples/tutorial_derive/01_quick.md b/examples/tutorial_derive/01_quick.md
new file mode 100644
index 0000000..21bbfe1
--- /dev/null
+++ b/examples/tutorial_derive/01_quick.md
@@ -0,0 +1,35 @@
+```console
+$ 01_quick_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 01_quick_derive[EXE] [OPTIONS] [NAME] [COMMAND]
+
+Commands:
+ test does testing things
+ help Print this message or the help of the given subcommand(s)
+
+Arguments:
+ [NAME] Optional name to operate on
+
+Options:
+ -c, --config <FILE> Sets a custom config file
+ -d, --debug... Turn debugging information on
+ -h, --help Print help
+ -V, --version Print version
+
+```
+
+By default, the program does nothing:
+```console
+$ 01_quick_derive
+Debug mode is off
+
+```
+
+But you can mix and match the various features
+```console
+$ 01_quick_derive -dd test
+Debug mode is on
+Not printing testing lists...
+
+```
diff --git a/examples/tutorial_derive/01_quick.rs b/examples/tutorial_derive/01_quick.rs
new file mode 100644
index 0000000..0edcd25
--- /dev/null
+++ b/examples/tutorial_derive/01_quick.rs
@@ -0,0 +1,68 @@
+use std::path::PathBuf;
+
+use clap::{Parser, Subcommand};
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ /// Optional name to operate on
+ name: Option<String>,
+
+ /// Sets a custom config file
+ #[arg(short, long, value_name = "FILE")]
+ config: Option<PathBuf>,
+
+ /// Turn debugging information on
+ #[arg(short, long, action = clap::ArgAction::Count)]
+ debug: u8,
+
+ #[command(subcommand)]
+ command: Option<Commands>,
+}
+
+#[derive(Subcommand)]
+enum Commands {
+ /// does testing things
+ Test {
+ /// lists test values
+ #[arg(short, long)]
+ list: bool,
+ },
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ // You can check the value provided by positional arguments, or option arguments
+ if let Some(name) = cli.name.as_deref() {
+ println!("Value for name: {name}");
+ }
+
+ if let Some(config_path) = cli.config.as_deref() {
+ println!("Value for config: {}", config_path.display());
+ }
+
+ // You can see how many times a particular flag or argument occurred
+ // Note, only flags can have multiple occurrences
+ match cli.debug {
+ 0 => println!("Debug mode is off"),
+ 1 => println!("Debug mode is kind of on"),
+ 2 => println!("Debug mode is on"),
+ _ => println!("Don't be crazy"),
+ }
+
+ // You can check for the existence of subcommands, and if found use their
+ // matches just as you would the top level cmd
+ match &cli.command {
+ Some(Commands::Test { list }) => {
+ if *list {
+ println!("Printing testing lists...");
+ } else {
+ println!("Not printing testing lists...");
+ }
+ }
+ None => {}
+ }
+
+ // Continued program logic goes here...
+}
diff --git a/examples/tutorial_derive/02_app_settings.md b/examples/tutorial_derive/02_app_settings.md
new file mode 100644
index 0000000..90da3ae
--- /dev/null
+++ b/examples/tutorial_derive/02_app_settings.md
@@ -0,0 +1,17 @@
+```console
+$ 02_app_settings_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 02_app_settings_derive[EXE] --two <TWO> --one <ONE>
+
+Options:
+ --two <TWO>
+
+ --one <ONE>
+
+ -h, --help
+ Print help
+ -V, --version
+ Print version
+
+```
diff --git a/examples/tutorial_derive/02_app_settings.rs b/examples/tutorial_derive/02_app_settings.rs
new file mode 100644
index 0000000..abea13d
--- /dev/null
+++ b/examples/tutorial_derive/02_app_settings.rs
@@ -0,0 +1,18 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+#[command(next_line_help = true)]
+struct Cli {
+ #[arg(long)]
+ two: String,
+ #[arg(long)]
+ one: String,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("two: {:?}", cli.two);
+ println!("one: {:?}", cli.one);
+}
diff --git a/examples/tutorial_derive/02_apps.md b/examples/tutorial_derive/02_apps.md
new file mode 100644
index 0000000..b5ae114
--- /dev/null
+++ b/examples/tutorial_derive/02_apps.md
@@ -0,0 +1,16 @@
+```console
+$ 02_apps_derive --help
+Does awesome things
+
+Usage: 02_apps_derive[EXE] --two <TWO> --one <ONE>
+
+Options:
+ --two <TWO>
+ --one <ONE>
+ -h, --help Print help
+ -V, --version Print version
+
+$ 02_apps_derive --version
+MyApp 1.0
+
+```
diff --git a/examples/tutorial_derive/02_apps.rs b/examples/tutorial_derive/02_apps.rs
new file mode 100644
index 0000000..75455ef
--- /dev/null
+++ b/examples/tutorial_derive/02_apps.rs
@@ -0,0 +1,20 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[command(name = "MyApp")]
+#[command(author = "Kevin K. <kbknapp@gmail.com>")]
+#[command(version = "1.0")]
+#[command(about = "Does awesome things", long_about = None)]
+struct Cli {
+ #[arg(long)]
+ two: String,
+ #[arg(long)]
+ one: String,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("two: {:?}", cli.two);
+ println!("one: {:?}", cli.one);
+}
diff --git a/examples/tutorial_derive/02_crate.md b/examples/tutorial_derive/02_crate.md
new file mode 100644
index 0000000..3f64460
--- /dev/null
+++ b/examples/tutorial_derive/02_crate.md
@@ -0,0 +1,16 @@
+```console
+$ 02_crate_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 02_crate_derive[EXE] --two <TWO> --one <ONE>
+
+Options:
+ --two <TWO>
+ --one <ONE>
+ -h, --help Print help
+ -V, --version Print version
+
+$ 02_crate_derive --version
+clap [..]
+
+```
diff --git a/examples/tutorial_derive/02_crate.rs b/examples/tutorial_derive/02_crate.rs
new file mode 100644
index 0000000..33a7a4e
--- /dev/null
+++ b/examples/tutorial_derive/02_crate.rs
@@ -0,0 +1,17 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)] // Read from `Cargo.toml`
+struct Cli {
+ #[arg(long)]
+ two: String,
+ #[arg(long)]
+ one: String,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("two: {:?}", cli.two);
+ println!("one: {:?}", cli.one);
+}
diff --git a/examples/tutorial_derive/03_01_flag_bool.md b/examples/tutorial_derive/03_01_flag_bool.md
new file mode 100644
index 0000000..9762260
--- /dev/null
+++ b/examples/tutorial_derive/03_01_flag_bool.md
@@ -0,0 +1,26 @@
+```console
+$ 03_01_flag_bool_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_01_flag_bool_derive[EXE] [OPTIONS]
+
+Options:
+ -v, --verbose
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_01_flag_bool_derive
+verbose: false
+
+$ 03_01_flag_bool_derive --verbose
+verbose: true
+
+$ 03_01_flag_bool_derive --verbose --verbose
+? failed
+error: the argument '--verbose' cannot be used multiple times
+
+Usage: 03_01_flag_bool_derive[EXE] [OPTIONS]
+
+For more information, try '--help'.
+
+```
diff --git a/examples/tutorial_derive/03_01_flag_bool.rs b/examples/tutorial_derive/03_01_flag_bool.rs
new file mode 100644
index 0000000..4f68fc8
--- /dev/null
+++ b/examples/tutorial_derive/03_01_flag_bool.rs
@@ -0,0 +1,14 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ #[arg(short, long)]
+ verbose: bool,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("verbose: {:?}", cli.verbose);
+}
diff --git a/examples/tutorial_derive/03_01_flag_count.md b/examples/tutorial_derive/03_01_flag_count.md
new file mode 100644
index 0000000..56ef9ca
--- /dev/null
+++ b/examples/tutorial_derive/03_01_flag_count.md
@@ -0,0 +1,21 @@
+```console
+$ 03_01_flag_count_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_01_flag_count_derive[EXE] [OPTIONS]
+
+Options:
+ -v, --verbose...
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_01_flag_count_derive
+verbose: 0
+
+$ 03_01_flag_count_derive --verbose
+verbose: 1
+
+$ 03_01_flag_count_derive --verbose --verbose
+verbose: 2
+
+```
diff --git a/examples/tutorial_derive/03_01_flag_count.rs b/examples/tutorial_derive/03_01_flag_count.rs
new file mode 100644
index 0000000..2b8a453
--- /dev/null
+++ b/examples/tutorial_derive/03_01_flag_count.rs
@@ -0,0 +1,14 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ #[arg(short, long, action = clap::ArgAction::Count)]
+ verbose: u8,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("verbose: {:?}", cli.verbose);
+}
diff --git a/examples/tutorial_derive/03_02_option.md b/examples/tutorial_derive/03_02_option.md
new file mode 100644
index 0000000..24e272a
--- /dev/null
+++ b/examples/tutorial_derive/03_02_option.md
@@ -0,0 +1,30 @@
+```console
+$ 03_02_option_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_02_option_derive[EXE] [OPTIONS]
+
+Options:
+ -n, --name <NAME>
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_02_option_derive
+name: None
+
+$ 03_02_option_derive --name bob
+name: Some("bob")
+
+$ 03_02_option_derive --name=bob
+name: Some("bob")
+
+$ 03_02_option_derive -n bob
+name: Some("bob")
+
+$ 03_02_option_derive -n=bob
+name: Some("bob")
+
+$ 03_02_option_derive -nbob
+name: Some("bob")
+
+```
diff --git a/examples/tutorial_derive/03_02_option.rs b/examples/tutorial_derive/03_02_option.rs
new file mode 100644
index 0000000..aad8ef1
--- /dev/null
+++ b/examples/tutorial_derive/03_02_option.rs
@@ -0,0 +1,14 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ #[arg(short, long)]
+ name: Option<String>,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("name: {:?}", cli.name.as_deref());
+}
diff --git a/examples/tutorial_derive/03_02_option_mult.md b/examples/tutorial_derive/03_02_option_mult.md
new file mode 100644
index 0000000..cd2fe13
--- /dev/null
+++ b/examples/tutorial_derive/03_02_option_mult.md
@@ -0,0 +1,30 @@
+```console
+$ 03_02_option_mult_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_02_option_mult_derive[EXE] [OPTIONS]
+
+Options:
+ -n, --name <NAME>
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_02_option_mult_derive
+name: []
+
+$ 03_02_option_mult_derive --name bob
+name: ["bob"]
+
+$ 03_02_option_mult_derive --name=bob
+name: ["bob"]
+
+$ 03_02_option_mult_derive -n bob
+name: ["bob"]
+
+$ 03_02_option_mult_derive -n=bob
+name: ["bob"]
+
+$ 03_02_option_mult_derive -nbob
+name: ["bob"]
+
+```
diff --git a/examples/tutorial_derive/03_02_option_mult.rs b/examples/tutorial_derive/03_02_option_mult.rs
new file mode 100644
index 0000000..1caa440
--- /dev/null
+++ b/examples/tutorial_derive/03_02_option_mult.rs
@@ -0,0 +1,14 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ #[arg(short, long)]
+ name: Vec<String>,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("name: {:?}", cli.name);
+}
diff --git a/examples/tutorial_derive/03_03_positional.md b/examples/tutorial_derive/03_03_positional.md
new file mode 100644
index 0000000..9437c24
--- /dev/null
+++ b/examples/tutorial_derive/03_03_positional.md
@@ -0,0 +1,20 @@
+```console
+$ 03_03_positional_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_03_positional_derive[EXE] [NAME]
+
+Arguments:
+ [NAME]
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_03_positional_derive
+name: None
+
+$ 03_03_positional_derive bob
+name: Some("bob")
+
+```
diff --git a/examples/tutorial_derive/03_03_positional.rs b/examples/tutorial_derive/03_03_positional.rs
new file mode 100644
index 0000000..cf5f405
--- /dev/null
+++ b/examples/tutorial_derive/03_03_positional.rs
@@ -0,0 +1,13 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ name: Option<String>,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("name: {:?}", cli.name.as_deref());
+}
diff --git a/examples/tutorial_derive/03_03_positional_mult.md b/examples/tutorial_derive/03_03_positional_mult.md
new file mode 100644
index 0000000..8f295e0
--- /dev/null
+++ b/examples/tutorial_derive/03_03_positional_mult.md
@@ -0,0 +1,23 @@
+```console
+$ 03_03_positional_mult_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_03_positional_mult_derive[EXE] [NAME]...
+
+Arguments:
+ [NAME]...
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_03_positional_mult_derive
+name: []
+
+$ 03_03_positional_mult_derive bob
+name: ["bob"]
+
+$ 03_03_positional_mult_derive bob john
+name: ["bob", "john"]
+
+```
diff --git a/examples/tutorial_derive/03_03_positional_mult.rs b/examples/tutorial_derive/03_03_positional_mult.rs
new file mode 100644
index 0000000..bd57a55
--- /dev/null
+++ b/examples/tutorial_derive/03_03_positional_mult.rs
@@ -0,0 +1,13 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ name: Vec<String>,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("name: {:?}", cli.name);
+}
diff --git a/examples/tutorial_derive/03_04_subcommands.md b/examples/tutorial_derive/03_04_subcommands.md
new file mode 100644
index 0000000..1fbac8f
--- /dev/null
+++ b/examples/tutorial_derive/03_04_subcommands.md
@@ -0,0 +1,58 @@
+```console
+$ 03_04_subcommands_derive help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_04_subcommands_derive[EXE] <COMMAND>
+
+Commands:
+ add Adds files to myapp
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_04_subcommands_derive help add
+Adds files to myapp
+
+Usage: 03_04_subcommands_derive[EXE] add [NAME]
+
+Arguments:
+ [NAME]
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_04_subcommands_derive add bob
+'myapp add' was used, name is: Some("bob")
+
+```
+
+Because we used `command: Commands` instead of `command: Option<Commands>`:
+```console
+$ 03_04_subcommands_derive
+? failed
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_04_subcommands_derive[EXE] <COMMAND>
+
+Commands:
+ add Adds files to myapp
+ help Print this message or the help of the given subcommand(s)
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+```
+
+Because we added `#[command(propagate_version = true)]`:
+```console
+$ 03_04_subcommands_derive --version
+clap [..]
+
+$ 03_04_subcommands_derive add --version
+clap-add [..]
+
+```
diff --git a/examples/tutorial_derive/03_04_subcommands.rs b/examples/tutorial_derive/03_04_subcommands.rs
new file mode 100644
index 0000000..da7c644
--- /dev/null
+++ b/examples/tutorial_derive/03_04_subcommands.rs
@@ -0,0 +1,27 @@
+use clap::{Parser, Subcommand};
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+#[command(propagate_version = true)]
+struct Cli {
+ #[command(subcommand)]
+ command: Commands,
+}
+
+#[derive(Subcommand)]
+enum Commands {
+ /// Adds files to myapp
+ Add { name: Option<String> },
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ // You can check for the existence of subcommands, and if found use their
+ // matches just as you would the top level cmd
+ match &cli.command {
+ Commands::Add { name } => {
+ println!("'myapp add' was used, name is: {name:?}")
+ }
+ }
+}
diff --git a/examples/tutorial_derive/03_04_subcommands_alt.rs b/examples/tutorial_derive/03_04_subcommands_alt.rs
new file mode 100644
index 0000000..80b0ec6
--- /dev/null
+++ b/examples/tutorial_derive/03_04_subcommands_alt.rs
@@ -0,0 +1,32 @@
+use clap::{Args, Parser, Subcommand};
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+#[command(propagate_version = true)]
+struct Cli {
+ #[command(subcommand)]
+ command: Commands,
+}
+
+#[derive(Subcommand)]
+enum Commands {
+ /// Adds files to myapp
+ Add(AddArgs),
+}
+
+#[derive(Args)]
+struct AddArgs {
+ name: Option<String>,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ // You can check for the existence of subcommands, and if found use their
+ // matches just as you would the top level cmd
+ match &cli.command {
+ Commands::Add(name) => {
+ println!("'myapp add' was used, name is: {:?}", name.name)
+ }
+ }
+}
diff --git a/examples/tutorial_derive/03_05_default_values.md b/examples/tutorial_derive/03_05_default_values.md
new file mode 100644
index 0000000..994cb33
--- /dev/null
+++ b/examples/tutorial_derive/03_05_default_values.md
@@ -0,0 +1,20 @@
+```console
+$ 03_05_default_values_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 03_05_default_values_derive[EXE] [PORT]
+
+Arguments:
+ [PORT] [default: 2020]
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 03_05_default_values_derive
+port: 2020
+
+$ 03_05_default_values_derive 22
+port: 22
+
+```
diff --git a/examples/tutorial_derive/03_05_default_values.rs b/examples/tutorial_derive/03_05_default_values.rs
new file mode 100644
index 0000000..bc33a93
--- /dev/null
+++ b/examples/tutorial_derive/03_05_default_values.rs
@@ -0,0 +1,14 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ #[arg(default_value_t = 2020)]
+ port: u16,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("port: {:?}", cli.port);
+}
diff --git a/examples/tutorial_derive/04_01_enum.md b/examples/tutorial_derive/04_01_enum.md
new file mode 100644
index 0000000..89db08c
--- /dev/null
+++ b/examples/tutorial_derive/04_01_enum.md
@@ -0,0 +1,47 @@
+```console
+$ 04_01_enum_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 04_01_enum_derive[EXE] <MODE>
+
+Arguments:
+ <MODE>
+ What mode to run the program in
+
+ Possible values:
+ - fast: Run swiftly
+ - slow: Crawl slowly but steadily
+
+Options:
+ -h, --help
+ Print help (see a summary with '-h')
+
+ -V, --version
+ Print version
+
+$ 04_01_enum_derive -h
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 04_01_enum_derive[EXE] <MODE>
+
+Arguments:
+ <MODE> What mode to run the program in [possible values: fast, slow]
+
+Options:
+ -h, --help Print help (see more with '--help')
+ -V, --version Print version
+
+$ 04_01_enum_derive fast
+Hare
+
+$ 04_01_enum_derive slow
+Tortoise
+
+$ 04_01_enum_derive medium
+? failed
+error: invalid value 'medium' for '<MODE>'
+ [possible values: fast, slow]
+
+For more information, try '--help'.
+
+```
diff --git a/examples/tutorial_derive/04_01_enum.rs b/examples/tutorial_derive/04_01_enum.rs
new file mode 100644
index 0000000..41410a3
--- /dev/null
+++ b/examples/tutorial_derive/04_01_enum.rs
@@ -0,0 +1,32 @@
+use clap::{Parser, ValueEnum};
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ /// What mode to run the program in
+ #[arg(value_enum)]
+ mode: Mode,
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
+enum Mode {
+ /// Run swiftly
+ Fast,
+ /// Crawl slowly but steadily
+ ///
+ /// This paragraph is ignored because there is no long help text for possible values.
+ Slow,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ match cli.mode {
+ Mode::Fast => {
+ println!("Hare");
+ }
+ Mode::Slow => {
+ println!("Tortoise");
+ }
+ }
+}
diff --git a/examples/tutorial_derive/04_02_parse.md b/examples/tutorial_derive/04_02_parse.md
new file mode 100644
index 0000000..573b43c
--- /dev/null
+++ b/examples/tutorial_derive/04_02_parse.md
@@ -0,0 +1,29 @@
+```console
+$ 04_02_parse_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 04_02_parse_derive[EXE] <PORT>
+
+Arguments:
+ <PORT> Network port to use
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 04_02_parse_derive 22
+PORT = 22
+
+$ 04_02_parse_derive foobar
+? failed
+error: invalid value 'foobar' for '<PORT>': invalid digit found in string
+
+For more information, try '--help'.
+
+$ 04_02_parse_derive 0
+? failed
+error: invalid value '0' for '<PORT>': 0 is not in 1..=65535
+
+For more information, try '--help'.
+
+```
diff --git a/examples/tutorial_derive/04_02_parse.rs b/examples/tutorial_derive/04_02_parse.rs
new file mode 100644
index 0000000..a40c682
--- /dev/null
+++ b/examples/tutorial_derive/04_02_parse.rs
@@ -0,0 +1,15 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ /// Network port to use
+ #[arg(value_parser = clap::value_parser!(u16).range(1..))]
+ port: u16,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("PORT = {}", cli.port);
+}
diff --git a/examples/tutorial_derive/04_02_validate.md b/examples/tutorial_derive/04_02_validate.md
new file mode 100644
index 0000000..f8835fd
--- /dev/null
+++ b/examples/tutorial_derive/04_02_validate.md
@@ -0,0 +1,29 @@
+```console
+$ 04_02_validate_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 04_02_validate_derive[EXE] <PORT>
+
+Arguments:
+ <PORT> Network port to use
+
+Options:
+ -h, --help Print help
+ -V, --version Print version
+
+$ 04_02_validate_derive 22
+PORT = 22
+
+$ 04_02_validate_derive foobar
+? failed
+error: invalid value 'foobar' for '<PORT>': `foobar` isn't a port number
+
+For more information, try '--help'.
+
+$ 04_02_validate_derive 0
+? failed
+error: invalid value '0' for '<PORT>': port not in range 1-65535
+
+For more information, try '--help'.
+
+```
diff --git a/examples/tutorial_derive/04_02_validate.rs b/examples/tutorial_derive/04_02_validate.rs
new file mode 100644
index 0000000..3391d5b
--- /dev/null
+++ b/examples/tutorial_derive/04_02_validate.rs
@@ -0,0 +1,34 @@
+use std::ops::RangeInclusive;
+
+use clap::Parser;
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ /// Network port to use
+ #[arg(value_parser = port_in_range)]
+ port: u16,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("PORT = {}", cli.port);
+}
+
+const PORT_RANGE: RangeInclusive<usize> = 1..=65535;
+
+fn port_in_range(s: &str) -> Result<u16, String> {
+ let port: usize = s
+ .parse()
+ .map_err(|_| format!("`{s}` isn't a port number"))?;
+ if PORT_RANGE.contains(&port) {
+ Ok(port as u16)
+ } else {
+ Err(format!(
+ "port not in range {}-{}",
+ PORT_RANGE.start(),
+ PORT_RANGE.end()
+ ))
+ }
+}
diff --git a/examples/tutorial_derive/04_03_relations.md b/examples/tutorial_derive/04_03_relations.md
new file mode 100644
index 0000000..6eafb9f
--- /dev/null
+++ b/examples/tutorial_derive/04_03_relations.md
@@ -0,0 +1,53 @@
+```console
+$ 04_03_relations_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 04_03_relations_derive[EXE] [OPTIONS] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]
+
+Arguments:
+ [INPUT_FILE] some regular input
+
+Options:
+ --set-ver <VER> set version manually
+ --major auto inc major
+ --minor auto inc minor
+ --patch auto inc patch
+ --spec-in <SPEC_IN> some special input argument
+ -c <CONFIG>
+ -h, --help Print help
+ -V, --version Print version
+
+$ 04_03_relations_derive
+? failed
+error: the following required arguments were not provided:
+ <--set-ver <VER>|--major|--minor|--patch>
+
+Usage: 04_03_relations_derive[EXE] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]
+
+For more information, try '--help'.
+
+$ 04_03_relations_derive --major
+Version: 2.2.3
+
+$ 04_03_relations_derive --major --minor
+? failed
+error: the argument '--major' cannot be used with '--minor'
+
+Usage: 04_03_relations_derive[EXE] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]
+
+For more information, try '--help'.
+
+$ 04_03_relations_derive --major -c config.toml
+? failed
+error: the following required arguments were not provided:
+ <INPUT_FILE|--spec-in <SPEC_IN>>
+
+Usage: 04_03_relations_derive[EXE] -c <CONFIG> <--set-ver <VER>|--major|--minor|--patch> <INPUT_FILE|--spec-in <SPEC_IN>>
+
+For more information, try '--help'.
+
+$ 04_03_relations_derive --major -c config.toml --spec-in input.txt
+Version: 2.2.3
+Doing work using input input.txt and config config.toml
+
+```
diff --git a/examples/tutorial_derive/04_03_relations.rs b/examples/tutorial_derive/04_03_relations.rs
new file mode 100644
index 0000000..cbe491d
--- /dev/null
+++ b/examples/tutorial_derive/04_03_relations.rs
@@ -0,0 +1,72 @@
+use clap::{ArgGroup, Parser};
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+#[command(group(
+ ArgGroup::new("vers")
+ .required(true)
+ .args(["set_ver", "major", "minor", "patch"]),
+ ))]
+struct Cli {
+ /// set version manually
+ #[arg(long, value_name = "VER")]
+ set_ver: Option<String>,
+
+ /// auto inc major
+ #[arg(long)]
+ major: bool,
+
+ /// auto inc minor
+ #[arg(long)]
+ minor: bool,
+
+ /// auto inc patch
+ #[arg(long)]
+ patch: bool,
+
+ /// some regular input
+ #[arg(group = "input")]
+ input_file: Option<String>,
+
+ /// some special input argument
+ #[arg(long, group = "input")]
+ spec_in: Option<String>,
+
+ #[arg(short, requires = "input")]
+ config: Option<String>,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ // Let's assume the old version 1.2.3
+ let mut major = 1;
+ let mut minor = 2;
+ let mut patch = 3;
+
+ // See if --set_ver was used to set the version manually
+ let version = if let Some(ver) = cli.set_ver.as_deref() {
+ ver.to_string()
+ } else {
+ // Increment the one requested (in a real program, we'd reset the lower numbers)
+ let (maj, min, pat) = (cli.major, cli.minor, cli.patch);
+ match (maj, min, pat) {
+ (true, _, _) => major += 1,
+ (_, true, _) => minor += 1,
+ (_, _, true) => patch += 1,
+ _ => unreachable!(),
+ };
+ format!("{major}.{minor}.{patch}")
+ };
+
+ println!("Version: {version}");
+
+ // Check for usage of -c
+ if let Some(config) = cli.config.as_deref() {
+ let input = cli
+ .input_file
+ .as_deref()
+ .unwrap_or_else(|| cli.spec_in.as_deref().unwrap());
+ println!("Doing work using input {input} and config {config}");
+ }
+}
diff --git a/examples/tutorial_derive/04_04_custom.md b/examples/tutorial_derive/04_04_custom.md
new file mode 100644
index 0000000..c601e9f
--- /dev/null
+++ b/examples/tutorial_derive/04_04_custom.md
@@ -0,0 +1,52 @@
+```console
+$ 04_04_custom_derive --help
+A simple to use, efficient, and full-featured Command Line Argument Parser
+
+Usage: 04_04_custom_derive[EXE] [OPTIONS] [INPUT_FILE]
+
+Arguments:
+ [INPUT_FILE] some regular input
+
+Options:
+ --set-ver <VER> set version manually
+ --major auto inc major
+ --minor auto inc minor
+ --patch auto inc patch
+ --spec-in <SPEC_IN> some special input argument
+ -c <CONFIG>
+ -h, --help Print help
+ -V, --version Print version
+
+$ 04_04_custom_derive
+? failed
+error: Can only modify one version field
+
+Usage: clap [OPTIONS] [INPUT_FILE]
+
+For more information, try '--help'.
+
+$ 04_04_custom_derive --major
+Version: 2.2.3
+
+$ 04_04_custom_derive --major --minor
+? failed
+error: Can only modify one version field
+
+Usage: clap [OPTIONS] [INPUT_FILE]
+
+For more information, try '--help'.
+
+$ 04_04_custom_derive --major -c config.toml
+? failed
+Version: 2.2.3
+error: INPUT_FILE or --spec-in is required when using --config
+
+Usage: clap [OPTIONS] [INPUT_FILE]
+
+For more information, try '--help'.
+
+$ 04_04_custom_derive --major -c config.toml --spec-in input.txt
+Version: 2.2.3
+Doing work using input input.txt and config config.toml
+
+```
diff --git a/examples/tutorial_derive/04_04_custom.rs b/examples/tutorial_derive/04_04_custom.rs
new file mode 100644
index 0000000..a84b5ed
--- /dev/null
+++ b/examples/tutorial_derive/04_04_custom.rs
@@ -0,0 +1,91 @@
+use clap::error::ErrorKind;
+use clap::{CommandFactory, Parser};
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ /// set version manually
+ #[arg(long, value_name = "VER")]
+ set_ver: Option<String>,
+
+ /// auto inc major
+ #[arg(long)]
+ major: bool,
+
+ /// auto inc minor
+ #[arg(long)]
+ minor: bool,
+
+ /// auto inc patch
+ #[arg(long)]
+ patch: bool,
+
+ /// some regular input
+ input_file: Option<String>,
+
+ /// some special input argument
+ #[arg(long)]
+ spec_in: Option<String>,
+
+ #[arg(short)]
+ config: Option<String>,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ // Let's assume the old version 1.2.3
+ let mut major = 1;
+ let mut minor = 2;
+ let mut patch = 3;
+
+ // See if --set-ver was used to set the version manually
+ let version = if let Some(ver) = cli.set_ver.as_deref() {
+ if cli.major || cli.minor || cli.patch {
+ let mut cmd = Cli::command();
+ cmd.error(
+ ErrorKind::ArgumentConflict,
+ "Can't do relative and absolute version change",
+ )
+ .exit();
+ }
+ ver.to_string()
+ } else {
+ // Increment the one requested (in a real program, we'd reset the lower numbers)
+ let (maj, min, pat) = (cli.major, cli.minor, cli.patch);
+ match (maj, min, pat) {
+ (true, false, false) => major += 1,
+ (false, true, false) => minor += 1,
+ (false, false, true) => patch += 1,
+ _ => {
+ let mut cmd = Cli::command();
+ cmd.error(
+ ErrorKind::ArgumentConflict,
+ "Can only modify one version field",
+ )
+ .exit();
+ }
+ };
+ format!("{major}.{minor}.{patch}")
+ };
+
+ println!("Version: {version}");
+
+ // Check for usage of -c
+ if let Some(config) = cli.config.as_deref() {
+ let input = cli
+ .input_file
+ .as_deref()
+ // 'or' is preferred to 'or_else' here since `Option::as_deref` is 'const'
+ .or(cli.spec_in.as_deref())
+ .unwrap_or_else(|| {
+ let mut cmd = Cli::command();
+ cmd.error(
+ ErrorKind::MissingRequiredArgument,
+ "INPUT_FILE or --spec-in is required when using --config",
+ )
+ .exit()
+ });
+ println!("Doing work using input {input} and config {config}");
+ }
+}
diff --git a/examples/tutorial_derive/05_01_assert.rs b/examples/tutorial_derive/05_01_assert.rs
new file mode 100644
index 0000000..42ebda9
--- /dev/null
+++ b/examples/tutorial_derive/05_01_assert.rs
@@ -0,0 +1,20 @@
+use clap::Parser;
+
+#[derive(Parser)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ /// Network port to use
+ port: u16,
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ println!("PORT = {}", cli.port);
+}
+
+#[test]
+fn verify_cli() {
+ use clap::CommandFactory;
+ Cli::command().debug_assert()
+}
diff --git a/examples/typed-derive.md b/examples/typed-derive.md
new file mode 100644
index 0000000..bf7a56a
--- /dev/null
+++ b/examples/typed-derive.md
@@ -0,0 +1,131 @@
+**This requires enabling the [`derive` feature flag][crate::_features].**
+
+Help:
+```console
+$ typed-derive --help
+Usage: typed-derive[EXE] [OPTIONS]
+
+Options:
+ -O <OPTIMIZATION> Implicitly using `std::str::FromStr`
+ -I <DIR> Allow invalid UTF-8 paths
+ --bind <BIND> Handle IP addresses
+ --sleep <SLEEP> Allow human-readable durations
+ -D <DEFINES> Hand-written parser for tuples
+ --port <PORT> Support for discrete numbers [default: 22] [possible values: 22, 80]
+ --log-level <LOG_LEVEL> Support enums from a foreign crate that don't implement `ValueEnum` [default: info] [possible values: info, debug, info, warn, error]
+ -h, --help Print help
+
+```
+
+Optimization-level (number)
+```console
+$ typed-derive -O 1
+Args { optimization: Some(1), include: None, bind: None, sleep: None, defines: [], port: 22, log_level: Info }
+
+$ typed-derive -O plaid
+? failed
+error: invalid value 'plaid' for '-O <OPTIMIZATION>': invalid digit found in string
+
+For more information, try '--help'.
+
+```
+
+Include (path)
+```console
+$ typed-derive -I../hello
+Args { optimization: None, include: Some("../hello"), bind: None, sleep: None, defines: [], port: 22, log_level: Info }
+
+```
+
+IP Address
+```console
+$ typed-derive --bind 192.0.0.1
+Args { optimization: None, include: None, bind: Some(192.0.0.1), sleep: None, defines: [], port: 22, log_level: Info }
+
+$ typed-derive --bind localhost
+? failed
+error: invalid value 'localhost' for '--bind <BIND>': invalid IP address syntax
+
+For more information, try '--help'.
+
+```
+
+Time
+```console
+$ typed-derive --sleep 10s
+Args { optimization: None, include: None, bind: None, sleep: Some(Duration(10s)), defines: [], port: 22, log_level: Info }
+
+$ typed-derive --sleep forever
+? failed
+error: invalid value 'forever' for '--sleep <SLEEP>': expected number at 0
+
+For more information, try '--help'.
+
+```
+
+Defines (key-value pairs)
+```console
+$ typed-derive -D Foo=10 -D Alice=30
+Args { optimization: None, include: None, bind: None, sleep: None, defines: [("Foo", 10), ("Alice", 30)], port: 22, log_level: Info }
+
+$ typed-derive -D Foo
+? failed
+error: invalid value 'Foo' for '-D <DEFINES>': invalid KEY=value: no `=` found in `Foo`
+
+For more information, try '--help'.
+
+$ typed-derive -D Foo=Bar
+? failed
+error: invalid value 'Foo=Bar' for '-D <DEFINES>': invalid digit found in string
+
+For more information, try '--help'.
+
+```
+
+Discrete numbers
+```console
+$ typed-derive --port 22
+Args { optimization: None, include: None, bind: None, sleep: None, defines: [], port: 22, log_level: Info }
+
+$ typed-derive --port 80
+Args { optimization: None, include: None, bind: None, sleep: None, defines: [], port: 80, log_level: Info }
+
+$ typed-derive --port
+? failed
+error: a value is required for '--port <PORT>' but none was supplied
+ [possible values: 22, 80]
+
+For more information, try '--help'.
+
+$ typed-derive --port 3000
+? failed
+error: invalid value '3000' for '--port <PORT>'
+ [possible values: 22, 80]
+
+For more information, try '--help'.
+
+```
+
+Enums from crates that can't implement `ValueEnum`
+```console
+$ typed-derive --log-level debug
+Args { optimization: None, include: None, bind: None, sleep: None, defines: [], port: 22, log_level: Debug }
+
+$ typed-derive --log-level error
+Args { optimization: None, include: None, bind: None, sleep: None, defines: [], port: 22, log_level: Error }
+
+$ typed-derive --log-level
+? failed
+error: a value is required for '--log-level <LOG_LEVEL>' but none was supplied
+ [possible values: info, debug, info, warn, error]
+
+For more information, try '--help'.
+
+$ typed-derive --log-level critical
+? failed
+error: invalid value 'critical' for '--log-level <LOG_LEVEL>'
+ [possible values: info, debug, info, warn, error]
+
+For more information, try '--help'.
+
+```
diff --git a/examples/typed-derive.rs b/examples/typed-derive.rs
new file mode 100644
index 0000000..8d7a84e
--- /dev/null
+++ b/examples/typed-derive.rs
@@ -0,0 +1,102 @@
+use clap::builder::TypedValueParser as _;
+use clap::Parser;
+use std::error::Error;
+
+#[derive(Parser, Debug)] // requires `derive` feature
+#[command(term_width = 0)] // Just to make testing across clap features easier
+struct Args {
+ /// Implicitly using `std::str::FromStr`
+ #[arg(short = 'O')]
+ optimization: Option<usize>,
+
+ /// Allow invalid UTF-8 paths
+ #[arg(short = 'I', value_name = "DIR", value_hint = clap::ValueHint::DirPath)]
+ include: Option<std::path::PathBuf>,
+
+ /// Handle IP addresses
+ #[arg(long)]
+ bind: Option<std::net::IpAddr>,
+
+ /// Allow human-readable durations
+ #[arg(long)]
+ sleep: Option<humantime::Duration>,
+
+ /// Hand-written parser for tuples
+ #[arg(short = 'D', value_parser = parse_key_val::<String, i32>)]
+ defines: Vec<(String, i32)>,
+
+ /// Support for discrete numbers
+ #[arg(
+ long,
+ default_value_t = 22,
+ value_parser = clap::builder::PossibleValuesParser::new(["22", "80"])
+ .map(|s| s.parse::<usize>().unwrap()),
+ )]
+ port: usize,
+
+ /// Support enums from a foreign crate that don't implement `ValueEnum`
+ #[arg(
+ long,
+ default_value_t = foreign_crate::LogLevel::Info,
+ value_parser = clap::builder::PossibleValuesParser::new(["info", "debug", "info", "warn", "error"])
+ .map(|s| s.parse::<foreign_crate::LogLevel>().unwrap()),
+ )]
+ log_level: foreign_crate::LogLevel,
+}
+
+/// Parse a single key-value pair
+fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>>
+where
+ T: std::str::FromStr,
+ T::Err: Error + Send + Sync + 'static,
+ U: std::str::FromStr,
+ U::Err: Error + Send + Sync + 'static,
+{
+ let pos = s
+ .find('=')
+ .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{s}`"))?;
+ Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
+}
+
+mod foreign_crate {
+ #[derive(Copy, Clone, PartialEq, Eq, Debug)]
+ pub enum LogLevel {
+ Trace,
+ Debug,
+ Info,
+ Warn,
+ Error,
+ }
+
+ impl std::fmt::Display for LogLevel {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let s = match self {
+ Self::Trace => "trace",
+ Self::Debug => "debug",
+ Self::Info => "info",
+ Self::Warn => "warn",
+ Self::Error => "error",
+ };
+ s.fmt(f)
+ }
+ }
+ impl std::str::FromStr for LogLevel {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ 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}")),
+ }
+ }
+ }
+}
+
+fn main() {
+ let args = Args::parse();
+ println!("{args:?}");
+}
diff --git a/justfile b/justfile
deleted file mode 100644
index 0768764..0000000
--- a/justfile
+++ /dev/null
@@ -1,39 +0,0 @@
-@update-contributors:
- echo 'Removing old CONTRIBUTORS.md'
- mv CONTRIBUTORS.md CONTRIBUTORS.md.bak
- echo 'Downloading a list of new contributors'
- echo "the following is a list of contributors:" > CONTRIBUTORS.md
- echo "" >> CONTRIBUTORS.md
- echo "" >> CONTRIBUTORS.md
- githubcontrib --owner clap-rs --repo clap --sha master --cols 6 --format md --showlogin true --sortBy contributions --sortOrder desc >> CONTRIBUTORS.md
- echo "" >> CONTRIBUTORS.md
- echo "" >> CONTRIBUTORS.md
- echo "This list was generated by [mgechev/github-contributors-list](https://github.com/mgechev/github-contributors-list)" >> CONTRIBUTORS.md
- rm CONTRIBUTORS.md.bak
-
-run-test TEST:
- cargo test --test {{TEST}}
-
-debug TEST:
- cargo test --test {{TEST}} --features debug
-
-run-tests:
- cargo test --features "yaml unstable"
-
-@bench: nightly
- cargo bench && just remove-nightly
-
-nightly:
- rustup override add nightly
-
-remove-nightly:
- rustup override remove
-
-@lint: nightly
- cargo build --features lints && just remove-nightly
-
-clean:
- cargo clean
- find . -type f -name "*.orig" -exec rm {} \;
- find . -type f -name "*.bk" -exec rm {} \;
- find . -type f -name ".*~" -exec rm {} \;
diff --git a/patches/Android.bp.diff b/patches/Android.bp.diff
new file mode 100644
index 0000000..a4dc389
--- /dev/null
+++ b/patches/Android.bp.diff
@@ -0,0 +1,22 @@
+diff --git a/Android.bp b/Android.bp
+index 235586c..1595d5e 100644
+--- a/Android.bp
++++ b/Android.bp
+@@ -53,7 +53,7 @@ rust_library {
+ "usage",
+ ],
+ rustlibs: [
+- "libbitflags",
++ "libbitflags-1.3.2",
+ "libclap_lex",
+ "libonce_cell",
+ ],
+@@ -82,7 +82,7 @@ rust_binary {
+ "usage",
+ ],
+ rustlibs: [
+- "libbitflags",
++ "libbitflags-1.3.2",
+ "libclap",
+ "libclap_lex",
+ "libonce_cell",
diff --git a/src/_cookbook/cargo_example.rs b/src/_cookbook/cargo_example.rs
new file mode 100644
index 0000000..ec5d582
--- /dev/null
+++ b/src/_cookbook/cargo_example.rs
@@ -0,0 +1,7 @@
+//! # Example: cargo subcommand (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/cargo-example.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/cargo-example.md")]
diff --git a/src/_cookbook/cargo_example_derive.rs b/src/_cookbook/cargo_example_derive.rs
new file mode 100644
index 0000000..d49f956
--- /dev/null
+++ b/src/_cookbook/cargo_example_derive.rs
@@ -0,0 +1,7 @@
+//! # Example: cargo subcommand (Derive API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/cargo-example-derive.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/cargo-example-derive.md")]
diff --git a/src/_cookbook/escaped_positional.rs b/src/_cookbook/escaped_positional.rs
new file mode 100644
index 0000000..99a3f83
--- /dev/null
+++ b/src/_cookbook/escaped_positional.rs
@@ -0,0 +1,7 @@
+//! # Example (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/escaped-positional.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/escaped-positional.md")]
diff --git a/src/_cookbook/escaped_positional_derive.rs b/src/_cookbook/escaped_positional_derive.rs
new file mode 100644
index 0000000..e6f99ad
--- /dev/null
+++ b/src/_cookbook/escaped_positional_derive.rs
@@ -0,0 +1,7 @@
+//! # Example (Derive API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/escaped-positional-derive.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/escaped-positional-derive.md")]
diff --git a/src/_cookbook/find.rs b/src/_cookbook/find.rs
new file mode 100644
index 0000000..2ca11c6
--- /dev/null
+++ b/src/_cookbook/find.rs
@@ -0,0 +1,7 @@
+//! # Example: find-like CLI (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/find.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/find.md")]
diff --git a/src/_cookbook/git.rs b/src/_cookbook/git.rs
new file mode 100644
index 0000000..03a926c
--- /dev/null
+++ b/src/_cookbook/git.rs
@@ -0,0 +1,7 @@
+//! # Example: git-like CLI (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/git.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/git.md")]
diff --git a/src/_cookbook/git_derive.rs b/src/_cookbook/git_derive.rs
new file mode 100644
index 0000000..d311973
--- /dev/null
+++ b/src/_cookbook/git_derive.rs
@@ -0,0 +1,7 @@
+//! # Example: git-like CLI (Derive API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/git-derive.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/git-derive.md")]
diff --git a/src/_cookbook/mod.rs b/src/_cookbook/mod.rs
new file mode 100644
index 0000000..dacb121
--- /dev/null
+++ b/src/_cookbook/mod.rs
@@ -0,0 +1,61 @@
+// Contributing
+//
+// New examples:
+// - Building: They must be added to `Cargo.toml` with the appropriate `required-features`.
+// - Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax
+// - Link the `.md` file from here
+
+//! # Documentation: Cookbook
+//!
+//! Typed arguments: [derive][typed_derive]
+//! - Topics:
+//! - Custom `parse()`
+//!
+//! Custom cargo command: [builder][cargo_example], [derive][cargo_example_derive]
+//! - Topics:
+//! - Subcommands
+//! - Cargo plugins
+//!
+//! find-like interface: [builder][find]
+//! - Topics:
+//! - Position-sensitive flags
+//!
+//! git-like interface: [builder][git], [derive][git_derive]
+//! - Topics:
+//! - Subcommands
+//! - External subcommands
+//! - Optional subcommands
+//! - Default subcommands
+//! - [`last`][crate::Arg::last]
+//!
+//! pacman-like interface: [builder][pacman]
+//! - Topics:
+//! - Flag subcommands
+//! - Conflicting arguments
+//!
+//! Escaped positionals with `--`: [builder][escaped_positional], [derive][escaped_positional_derive]
+//!
+//! Multi-call
+//! - busybox: [builder][multicall_busybox]
+//! - Topics:
+//! - Subcommands
+//! - hostname: [builder][multicall_hostname]
+//! - Topics:
+//! - Subcommands
+//!
+//! repl: [builder][repl]
+//! - Topics:
+//! - Read-Eval-Print Loops / Custom command lines
+
+pub mod cargo_example;
+pub mod cargo_example_derive;
+pub mod escaped_positional;
+pub mod escaped_positional_derive;
+pub mod find;
+pub mod git;
+pub mod git_derive;
+pub mod multicall_busybox;
+pub mod multicall_hostname;
+pub mod pacman;
+pub mod repl;
+pub mod typed_derive;
diff --git a/src/_cookbook/multicall_busybox.rs b/src/_cookbook/multicall_busybox.rs
new file mode 100644
index 0000000..e3384d6
--- /dev/null
+++ b/src/_cookbook/multicall_busybox.rs
@@ -0,0 +1,7 @@
+//! # Example: busybox-like CLI (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/multicall-busybox.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/multicall-busybox.md")]
diff --git a/src/_cookbook/multicall_hostname.rs b/src/_cookbook/multicall_hostname.rs
new file mode 100644
index 0000000..9777654
--- /dev/null
+++ b/src/_cookbook/multicall_hostname.rs
@@ -0,0 +1,7 @@
+//! # Example: hostname-like CLI (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/multicall-hostname.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/multicall-hostname.md")]
diff --git a/src/_cookbook/pacman.rs b/src/_cookbook/pacman.rs
new file mode 100644
index 0000000..880c581
--- /dev/null
+++ b/src/_cookbook/pacman.rs
@@ -0,0 +1,7 @@
+//! # Example: pacman-like CLI (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/pacman.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/pacman.md")]
diff --git a/src/_cookbook/repl.rs b/src/_cookbook/repl.rs
new file mode 100644
index 0000000..549ec82
--- /dev/null
+++ b/src/_cookbook/repl.rs
@@ -0,0 +1,5 @@
+//! # Example: Command REPL (Builder API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/repl.rs")]
+//! ```
diff --git a/src/_cookbook/typed_derive.rs b/src/_cookbook/typed_derive.rs
new file mode 100644
index 0000000..a5fd15f
--- /dev/null
+++ b/src/_cookbook/typed_derive.rs
@@ -0,0 +1,7 @@
+//! # Example: Custom Types (Derive API)
+//!
+//! ```rust
+#![doc = include_str!("../../examples/typed-derive.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/typed-derive.md")]
diff --git a/src/_derive/_tutorial.rs b/src/_derive/_tutorial.rs
new file mode 100644
index 0000000..f3f55c3
--- /dev/null
+++ b/src/_derive/_tutorial.rs
@@ -0,0 +1,226 @@
+// Contributing
+//
+// New example code:
+// - Please update the corresponding section in the derive tutorial
+// - Building: They must be added to `Cargo.toml` with the appropriate `required-features`.
+// - Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax
+//
+// See also the general CONTRIBUTING
+
+//! # Documentation: Derive Tutorial
+//!
+//! 1. [Quick Start](#quick-start)
+//! 2. [Configuring the Parser](#configuring-the-parser)
+//! 3. [Adding Arguments](#adding-arguments)
+//! 1. [Positionals](#positionals)
+//! 2. [Options](#options)
+//! 3. [Flags](#flags)
+//! 4. [Subcommands](#subcommands)
+//! 5. [Defaults](#defaults)
+//! 4. Validation
+//! 1. [Enumerated values](#enumerated-values)
+//! 2. [Validated values](#validated-values)
+//! 3. [Argument Relations](#argument-relations)
+//! 4. [Custom Validation](#custom-validation)
+//! 5. [Testing](#testing)
+//!
+//! See also
+//! - [FAQ: When should I use the builder vs derive APIs?][crate::_faq#when-should-i-use-the-builder-vs-derive-apis]
+//! - The [cookbook][crate::_cookbook] for more application-focused examples
+//!
+//! ## Quick Start
+//!
+//! You can create an application declaratively with a `struct` and some
+//! attributes. **This requires enabling the [`derive` feature flag][crate::_features].**
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/01_quick.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/tutorial_derive/01_quick.md")]
+//!
+//! ## Configuring the Parser
+//!
+//! You use derive [`Parser`][crate::Parser] to start building a parser.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/02_apps.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/tutorial_derive/02_apps.md")]
+//!
+//! You can use `#[command(author, version, about)]` attribute defaults to fill these fields in from your `Cargo.toml` file.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/02_crate.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/02_crate.md")]
+//!
+//! You can use attributes to change the application level behavior of clap. Any [`Command`][crate::Command] builder function can be used as an attribute.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/02_app_settings.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/02_app_settings.md")]
+//!
+//! ## Adding Arguments
+//!
+//! ### Positionals
+//!
+//! You can have users specify values by their position on the command-line:
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_03_positional.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/03_03_positional.md")]
+//!
+//! Note that the default [`ArgAction`][crate::ArgAction] is [`Set`][crate::ArgAction::Set]. To
+//! accept multiple values, use [`Append`][crate::ArgAction::Append] via `Vec`:
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_03_positional_mult.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/03_03_positional_mult.md")]
+//!
+//! ### Options
+//!
+//! You can name your arguments with a flag:
+//! - Order doesn't matter
+//! - They can be optional
+//! - Intent is clearer
+//!
+//! The `#[arg(short = 'n')]` and `#[arg(long = "name")]` attributes that define
+//! the flags are [`Arg`][crate::Args] methods that are derived from the field name when no value
+//! is specified (`#[arg(short)]` and `#[arg(long)]`).
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_02_option.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/03_02_option.md")]
+//!
+//! Note that the default [`ArgAction`][crate::ArgAction] is [`Set`][crate::ArgAction::Set]. To
+//! accept multiple occurrences, use [`Append`][crate::ArgAction::Append] via `Vec`:
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_02_option_mult.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/03_02_option_mult.md")]
+//!
+//! ### Flags
+//!
+//! Flags can also be switches that can be on/off. This is enabled via the
+//! `#[arg(action = ArgAction::SetTrue)]` attribute though this is implied when the field is a
+//! `bool`.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_bool.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_bool.md")]
+//!
+//! Note that the default [`ArgAction`][crate::ArgAction] for a `bool` field is
+//! [`SetTrue`][crate::ArgAction::SetTrue]. To accept multiple flags, use
+//! [`Count`][crate::ArgAction::Count]:
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_count.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_count.md")]
+//!
+//! ### Subcommands
+//!
+//! Subcommands are derived with `#[derive(Subcommand)]` and be added via `#[command(subcommand)]` attribute. Each
+//! instance of a [Subcommand][crate::Subcommand] can have its own version, author(s), Args, and even its own
+//! subcommands.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_04_subcommands.rs")]
+//! ```
+//! We used a struct-variant to define the `add` subcommand.
+//! Alternatively, you can use a struct for your subcommand's arguments:
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_04_subcommands_alt.rs")]
+//! ```
+//!
+#![doc = include_str!("../../examples/tutorial_derive/03_04_subcommands.md")]
+//!
+//! ### Defaults
+//!
+//! We've previously showed that arguments can be [`required`][crate::Arg::required] or optional.
+//! When optional, you work with a `Option` and can `unwrap_or`. Alternatively, you can
+//! set `#[arg(default_value_t)]`.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/03_05_default_values.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/03_05_default_values.md")]
+//!
+//! ## Validation
+//!
+//! An appropriate default parser/validator will be selected for the field's type. See
+//! [`value_parser!`][crate::value_parser!] for more details.
+//!
+//! ### Enumerated values
+//!
+//! For example, if you have arguments of specific values you want to test for, you can derive
+//! [`ValueEnum`][crate::ValueEnum].
+//!
+//! This allows you specify the valid values for that argument. If the user does not use one of
+//! those specific values, they will receive a graceful exit with error message informing them
+//! of the mistake, and what the possible valid values are
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/04_01_enum.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/04_01_enum.md")]
+//!
+//! ### Validated values
+//!
+//! More generally, you can validate and parse into any data type.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/04_02_parse.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/04_02_parse.md")]
+//!
+//! A custom parser can be used to improve the error messages or provide additional validation:
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/04_02_validate.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/04_02_validate.md")]
+//!
+//! See [`Arg::value_parser`][crate::Arg::value_parser] for more details.
+//!
+//! ### Argument Relations
+//!
+//! You can declare dependencies or conflicts between [`Arg`][crate::Arg]s or even
+//! [`ArgGroup`][crate::ArgGroup]s.
+//!
+//! [`ArgGroup`][crate::ArgGroup]s make it easier to declare relations instead of having to list
+//! each individually, or when you want a rule to apply "any but not all" arguments.
+//!
+//! Perhaps the most common use of [`ArgGroup`][crate::ArgGroup]s is to require one and *only* one
+//! argument to be present out of a given set. Imagine that you had multiple arguments, and you
+//! want one of them to be required, but making all of them required isn't feasible because perhaps
+//! they conflict with each other.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/04_03_relations.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/04_03_relations.md")]
+//!
+//! ### Custom Validation
+//!
+//! As a last resort, you can create custom errors with the basics of clap's formatting.
+//!
+//! ```rust
+#![doc = include_str!("../../examples/tutorial_derive/04_04_custom.rs")]
+//! ```
+#![doc = include_str!("../../examples/tutorial_derive/04_04_custom.md")]
+//!
+//! ## Testing
+//!
+//! clap reports most development errors as `debug_assert!`s. Rather than checking every
+//! subcommand, you should have a test that calls
+//! [`Command::debug_assert`][crate::Command::debug_assert]:
+//! ```rust,no_run
+#![doc = include_str!("../../examples/tutorial_derive/05_01_assert.rs")]
+//! ```
diff --git a/src/_derive/mod.rs b/src/_derive/mod.rs
new file mode 100644
index 0000000..a92b7c8
--- /dev/null
+++ b/src/_derive/mod.rs
@@ -0,0 +1,480 @@
+//! # Documentation: Derive Reference
+//!
+//! 1. [Overview](#overview)
+//! 2. [Attributes](#attributes)
+//! 1. [Terminology](#terminology)
+//! 2. [Command Attributes](#command-attributes)
+//! 2. [ArgGroup Attributes](#arggroup-attributes)
+//! 3. [Arg Attributes](#arg-attributes)
+//! 4. [ValueEnum Attributes](#valueenum-attributes)
+//! 5. [Possible Value Attributes](#possible-value-attributes)
+//! 3. [Arg Types](#arg-types)
+//! 4. [Doc Comments](#doc-comments)
+//! 5. [Mixing Builder and Derive APIs](#mixing-builder-and-derive-apis)
+//! 6. [Tips](#tips)
+//!
+//! ## Overview
+//!
+//! To derive `clap` types, you need to enable the [`derive` feature flag][crate::_features].
+//!
+//! Example:
+//! ```rust
+#![doc = include_str!("../../examples/demo.rs")]
+//! ```
+//!
+//! Let's start by breaking down the anatomy of the derive attributes:
+//! ```rust
+//! use clap::{Parser, Args, Subcommand, ValueEnum};
+//!
+//! /// Doc comment
+//! #[derive(Parser)]
+//! #[command(CMD ATTRIBUTE)]
+//! #[group(GROUP ATTRIBUTE)]
+//! struct Cli {
+//! /// Doc comment
+//! #[arg(ARG ATTRIBUTE)]
+//! field: UserType,
+//!
+//! #[arg(value_enum, ARG ATTRIBUTE...)]
+//! field: EnumValues,
+//!
+//! #[command(flatten)]
+//! delegate: Struct,
+//!
+//! #[command(subcommand)]
+//! command: Command,
+//! }
+//!
+//! /// Doc comment
+//! #[derive(Args)]
+//! #[command(PARENT CMD ATTRIBUTE)]
+//! #[group(GROUP ATTRIBUTE)]
+//! struct Struct {
+//! /// Doc comment
+//! #[command(ARG ATTRIBUTE)]
+//! field: UserType,
+//! }
+//!
+//! /// Doc comment
+//! #[derive(Subcommand)]
+//! #[command(PARENT CMD ATTRIBUTE)]
+//! enum Command {
+//! /// Doc comment
+//! #[command(CMD ATTRIBUTE)]
+//! Variant1(Struct),
+//!
+//! /// Doc comment
+//! #[command(CMD ATTRIBUTE)]
+//! Variant2 {
+//! /// Doc comment
+//! #[arg(ARG ATTRIBUTE)]
+//! field: UserType,
+//! }
+//! }
+//!
+//! /// Doc comment
+//! #[derive(ValueEnum)]
+//! #[value(VALUE ENUM ATTRIBUTE)]
+//! enum EnumValues {
+//! /// Doc comment
+//! #[value(POSSIBLE VALUE ATTRIBUTE)]
+//! Variant1,
+//! }
+//!
+//! fn main() {
+//! let cli = Cli::parse();
+//! }
+//! ```
+//!
+//! Traits:
+//! - [`Parser`][crate::Parser] parses arguments into a `struct` (arguments) or `enum` (subcommands).
+//! - [`Args`][crate::Args] allows defining a set of re-usable arguments that get merged into their parent container.
+//! - [`Subcommand`][crate::Subcommand] defines available subcommands.
+//! - Subcommand arguments can be defined in a struct-variant or automatically flattened with a tuple-variant.
+//! - [`ValueEnum`][crate::ValueEnum] allows parsing a value directly into an `enum`, erroring on unsupported values.
+//! - The derive doesn't work on enums that contain non-unit variants, unless they are skipped
+//!
+//! *See also the [derive tutorial][crate::_derive::_tutorial] and [cookbook][crate::_cookbook]*
+//!
+//! ## Attributes
+//!
+//! ### Terminology
+//!
+//! **Raw attributes** are forwarded directly to the underlying [`clap` builder][crate::builder]. Any
+//! [`Command`][crate::Command], [`Arg`][crate::Arg], or [`PossibleValue`][crate::builder::PossibleValue] method can be used as an attribute.
+//!
+//! Raw attributes come in two different syntaxes:
+//! ```rust,ignore
+//! #[arg(
+//! global = true, // name = arg form, neat for one-arg methods
+//! required_if_eq("out", "file") // name(arg1, arg2, ...) form.
+//! )]
+//! ```
+//!
+//! - `method = arg` can only be used for methods which take only one argument.
+//! - `method(arg1, arg2)` can be used with any method.
+//!
+//! As long as `method_name` is not one of the magical methods it will be
+//! translated into a mere method call.
+//!
+//! **Magic attributes** have post-processing done to them, whether that is
+//! - Providing of defaults
+//! - Special behavior is triggered off of it
+//!
+//! Magic attributes are more constrained in the syntax they support, usually just
+//! `<attr> = <value>` though some use `<attr>(<value>)` instead. See the specific
+//! magic attributes documentation for details. This allows users to access the
+//! raw behavior of an attribute via `<attr>(<value>)` syntax.
+//!
+//! **NOTE:** Some attributes are inferred from [Arg Types](#arg-types) and [Doc
+//! Comments](#doc-comments). Explicit attributes take precedence over inferred
+//! attributes.
+//!
+//! ### Command Attributes
+//!
+//! These correspond to a [`Command`][crate::Command] which is used for both top-level parsers and
+//! when defining subcommands.
+//!
+//! **Raw attributes:** Any [`Command` method][crate::Command] can also be used as an attribute,
+//! see [Terminology](#terminology) for syntax.
+//! - e.g. `#[command(arg_required_else_help(true))]` would translate to `cmd.arg_required_else_help(true)`
+//!
+//! **Magic attributes:**
+//! - `name = <expr>`: [`Command::name`][crate::Command::name]
+//! - When not present: [crate `name`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-name-field) (if on [`Parser`][crate::Parser] container), variant name (if on [`Subcommand`][crate::Subcommand] variant)
+//! - `version [= <expr>]`: [`Command::version`][crate::Command::version]
+//! - When not present: no version set
+//! - Without `<expr>`: defaults to [crate `version`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field)
+//! - `author [= <expr>]`: [`Command::author`][crate::Command::author]
+//! - When not present: no author set
+//! - Without `<expr>`: defaults to [crate `authors`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field)
+//! - `about [= <expr>]`: [`Command::about`][crate::Command::about]
+//! - When not present: [Doc comment summary](#doc-comments)
+//! - Without `<expr>`: [crate `description`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-description-field) ([`Parser`][crate::Parser] container)
+//! - **TIP:** When a doc comment is also present, you most likely want to add
+//! `#[arg(long_about = None)]` to clear the doc comment so only [`about`][crate::Command::about]
+//! gets shown with both `-h` and `--help`.
+//! - `long_about[ = <expr>]`: [`Command::long_about`][crate::Command::long_about]
+//! - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing
+//! - When present without a value: [Doc comment](#doc-comments)
+//! - `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to [`about`][crate::Command::about] / [`long_about`][crate::Command::long_about]
+//! - `next_display_order`: [`Command::next_display_order`][crate::Command::next_display_order]
+//! - `next_help_heading`: [`Command::next_help_heading`][crate::Command::next_help_heading]
+//! - When `flatten`ing [`Args`][crate::Args], this is scoped to just the args in this struct and any struct `flatten`ed into it
+//! - `rename_all = <string_literal>`: Override default field / variant name case conversion for [`Command::name`][crate::Command::name] / [`Arg::id`][crate::Arg::id]
+//! - When not present: `"kebab-case"`
+//! - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"`
+//! - `rename_all_env = <string_literal>`: Override default field name case conversion for env variables for [`Arg::env`][crate::Arg::env]
+//! - When not present: `"SCREAMING_SNAKE_CASE"`
+//! - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"`
+//!
+//! And for [`Subcommand`][crate::Subcommand] variants:
+//! - `skip`: Ignore this variant
+//! - `flatten`: Delegates to the variant for more subcommands (must implement
+//! [`Subcommand`][crate::Subcommand])
+//! - `subcommand`: Nest subcommands under the current set of subcommands (must implement
+//! [`Subcommand`][crate::Subcommand])
+//! - `external_subcommand`: [`Command::allow_external_subcommand(true)`][crate::Command::allow_external_subcommands]
+//! - Variant must be either `Variant(Vec<String>)` or `Variant(Vec<OsString>)`
+//!
+//! And for [`Args`][crate::Args] fields:
+//! - `flatten`: Delegates to the field for more arguments (must implement [`Args`][crate::Args])
+//! - Only [`next_help_heading`][crate::Command::next_help_heading] can be used with `flatten`. See
+//! [clap-rs/clap#3269](https://github.com/clap-rs/clap/issues/3269) for why
+//! arg attributes are not generally supported.
+//! - **Tip:** Though we do apply a flattened [`Args`][crate::Args]'s Parent Command Attributes, this
+//! makes reuse harder. Generally prefer putting the cmd attributes on the
+//! [`Parser`][crate::Parser] or on the flattened field.
+//! - `subcommand`: Delegates definition of subcommands to the field (must implement
+//! [`Subcommand`][crate::Subcommand])
+//! - When `Option<T>`, the subcommand becomes optional
+//!
+//! ### ArgGroup Attributes
+//!
+//! These correspond to the [`ArgGroup`][crate::ArgGroup] which is implicitly created for each
+//! `Args` derive.
+//!
+//! At the moment, only `#[group(skip)]` is supported
+//!
+//! ### Arg Attributes
+//!
+//! These correspond to a [`Arg`][crate::Arg].
+//!
+//! **Raw attributes:** Any [`Arg` method][crate::Arg] can also be used as an attribute, see [Terminology](#terminology) for syntax.
+//! - e.g. `#[arg(max_values(3))]` would translate to `arg.max_values(3)`
+//!
+//! **Magic attributes**:
+//! - `id = <expr>`: [`Arg::id`][crate::Arg::id]
+//! - When not present: case-converted field name is used
+//! - `value_parser [= <expr>]`: [`Arg::value_parser`][crate::Arg::value_parser]
+//! - When not present: will auto-select an implementation based on the field type using
+//! [`value_parser!`][crate::value_parser!]
+//! - `action [= <expr>]`: [`Arg::action`][crate::Arg::action]
+//! - When not present: will auto-select an action based on the field type
+//! - `help = <expr>`: [`Arg::help`][crate::Arg::help]
+//! - When not present: [Doc comment summary](#doc-comments)
+//! - `long_help[ = <expr>]`: [`Arg::long_help`][crate::Arg::long_help]
+//! - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing
+//! - When present without a value: [Doc comment](#doc-comments)
+//! - `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to [`help`][crate::Arg::help] / [`long_help`][crate::Arg::long_help]
+//! - `short [= <char>]`: [`Arg::short`][crate::Arg::short]
+//! - When not present: no short set
+//! - Without `<char>`: defaults to first character in the case-converted field name
+//! - `long [= <str>]`: [`Arg::long`][crate::Arg::long]
+//! - When not present: no long set
+//! - Without `<str>`: defaults to the case-converted field name
+//! - `env [= <str>]`: [`Arg::env`][crate::Arg::env] (needs [`env` feature][crate::_features] enabled)
+//! - When not present: no env set
+//! - Without `<str>`: defaults to the case-converted field name
+//! - `from_global`: Read a [`Arg::global`][crate::Arg::global] argument (raw attribute), regardless of what subcommand you are in
+//! - `value_enum`: Parse the value using the [`ValueEnum`][crate::ValueEnum]
+//! - `skip [= <expr>]`: Ignore this field, filling in with `<expr>`
+//! - Without `<expr>`: fills the field with `Default::default()`
+//! - `default_value = <str>`: [`Arg::default_value`][crate::Arg::default_value] and [`Arg::required(false)`][crate::Arg::required]
+//! - `default_value_t [= <expr>]`: [`Arg::default_value`][crate::Arg::default_value] and [`Arg::required(false)`][crate::Arg::required]
+//! - Requires `std::fmt::Display` that roundtrips correctly with the
+//! [`Arg::value_parser`][crate::Arg::value_parser] or `#[arg(value_enum)]`
+//! - Without `<expr>`, relies on `Default::default()`
+//! - `default_values_t = <expr>`: [`Arg::default_values`][crate::Arg::default_values] and [`Arg::required(false)`][crate::Arg::required]
+//! - Requires field arg to be of type `Vec<T>` and `T` to implement `std::fmt::Display` or `#[arg(value_enum)]`
+//! - `<expr>` must implement `IntoIterator<T>`
+//! - `default_value_os_t [= <expr>]`: [`Arg::default_value_os`][crate::Arg::default_value_os] and [`Arg::required(false)`][crate::Arg::required]
+//! - Requires `std::convert::Into<OsString>` or `#[arg(value_enum)]`
+//! - Without `<expr>`, relies on `Default::default()`
+//! - `default_values_os_t = <expr>`: [`Arg::default_values_os`][crate::Arg::default_values_os] and [`Arg::required(false)`][crate::Arg::required]
+//! - Requires field arg to be of type `Vec<T>` and `T` to implement `std::convert::Into<OsString>` or `#[arg(value_enum)]`
+//! - `<expr>` must implement `IntoIterator<T>`
+//!
+//! ### ValueEnum Attributes
+//!
+//! - `rename_all = <string_literal>`: Override default field / variant name case conversion for [`PossibleValue::new`][crate::builder::PossibleValue]
+//! - When not present: `"kebab-case"`
+//! - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"`
+//!
+//! ### Possible Value Attributes
+//!
+//! These correspond to a [`PossibleValue`][crate::builder::PossibleValue].
+//!
+//! **Raw attributes:** Any [`PossibleValue` method][crate::builder::PossibleValue] can also be used as an attribute, see [Terminology](#terminology) for syntax.
+//! - e.g. `#[value(alias("foo"))]` would translate to `pv.alias("foo")`
+//!
+//! **Magic attributes**:
+//! - `name = <expr>`: [`PossibleValue::new`][crate::builder::PossibleValue::new]
+//! - When not present: case-converted field name is used
+//! - `help = <expr>`: [`PossibleValue::help`][crate::builder::PossibleValue::help]
+//! - When not present: [Doc comment summary](#doc-comments)
+//! - `skip`: Ignore this variant
+//!
+//! ## Arg Types
+//!
+//! `clap` assumes some intent based on the type used:
+//!
+//! | Type | Effect | Implies |
+//! |---------------------|--------------------------------------|-------------------------------------------------------------|
+//! | `()` | user-defined | `.action(ArgAction::Set).required(false)` |
+//! | `bool` | flag | `.action(ArgAction::SetTrue)` |
+//! | `Option<T>` | optional argument | `.action(ArgAction::Set).required(false)` |
+//! | `Option<Option<T>>` | optional value for optional argument | `.action(ArgAction::Set).required(false).num_args(0..=1)` |
+//! | `T` | required argument | `.action(ArgAction::Set).required(!has_default)` |
+//! | `Vec<T>` | `0..` occurrences of argument | `.action(ArgAction::Append).required(false)` |
+//! | `Option<Vec<T>>` | `0..` occurrences of argument | `.action(ArgAction::Append).required(false)` |
+//!
+//! In addition, [`.value_parser(value_parser!(T))`][crate::value_parser!] is called for each
+//! field.
+//!
+//! Notes:
+//! - For custom type behavior, you can override the implied attributes/settings and/or set additional ones
+//! - `Option<Vec<T>>` will be `None` instead of `vec![]` if no arguments are provided.
+//! - This gives the user some flexibility in designing their argument, like with `num_args(0..)`
+//!
+//! ## Doc Comments
+//!
+//! In clap, help messages for the whole binary can be specified
+//! via [`Command::about`][crate::Command::about] and [`Command::long_about`][crate::Command::long_about] while help messages
+//! for individual arguments can be specified via [`Arg::help`][crate::Arg::help] and [`Arg::long_help`][crate::Arg::long_help].
+//!
+//! `long_*` variants are used when user calls the program with
+//! `--help` and "short" variants are used with `-h` flag.
+//!
+//! ```rust
+//! # use clap::Parser;
+//!
+//! #[derive(Parser)]
+//! #[command(about = "I am a program and I work, just pass `-h`", long_about = None)]
+//! struct Foo {
+//! #[arg(short, help = "Pass `-h` and you'll see me!")]
+//! bar: String,
+//! }
+//! ```
+//!
+//! For convenience, doc comments can be used instead of raw methods
+//! (this example works exactly like the one above):
+//!
+//! ```rust
+//! # use clap::Parser;
+//!
+//! #[derive(Parser)]
+//! /// I am a program and I work, just pass `-h`
+//! struct Foo {
+//! /// Pass `-h` and you'll see me!
+//! bar: String,
+//! }
+//! ```
+//!
+//! **NOTE:** Attributes have priority over doc comments!
+//!
+//! **Top level doc comments always generate `Command::about/long_about` calls!**
+//! If you really want to use the `Command::about/long_about` methods (you likely don't),
+//! use the `about` / `long_about` attributes to override the calls generated from
+//! the doc comment. To clear `long_about`, you can use
+//! `#[command(long_about = None)]`.
+//!
+//! ### Pre-processing
+//!
+//! ```rust
+//! # use clap::Parser;
+//! #[derive(Parser)]
+//! /// Hi there, I'm Robo!
+//! ///
+//! /// I like beeping, stumbling, eating your electricity,
+//! /// and making records of you singing in a shower.
+//! /// Pay up, or I'll upload it to youtube!
+//! struct Robo {
+//! /// Call my brother SkyNet.
+//! ///
+//! /// I am artificial superintelligence. I won't rest
+//! /// until I'll have destroyed humanity. Enjoy your
+//! /// pathetic existence, you mere mortals.
+//! #[arg(long, action)]
+//! kill_all_humans: bool,
+//! }
+//! ```
+//!
+//! A doc comment consists of three parts:
+//! - Short summary
+//! - A blank line (whitespace only)
+//! - Detailed description, all the rest
+//!
+//! The summary corresponds with `Command::about` / `Arg::help`. When a blank line is
+//! present, the whole doc comment will be passed to `Command::long_about` /
+//! `Arg::long_help`. Or in other words, a doc may result in just a `Command::about` /
+//! `Arg::help` or `Command::about` / `Arg::help` and `Command::long_about` /
+//! `Arg::long_help`
+//!
+//! In addition, when `verbatim_doc_comment` is not present, `clap` applies some preprocessing, including:
+//!
+//! - Strip leading and trailing whitespace from every line, if present.
+//!
+//! - Strip leading and trailing blank lines, if present.
+//!
+//! - Interpret each group of non-empty lines as a word-wrapped paragraph.
+//!
+//! We replace newlines within paragraphs with spaces to allow the output
+//! to be re-wrapped to the terminal width.
+//!
+//! - Strip any excess blank lines so that there is exactly one per paragraph break.
+//!
+//! - If the first paragraph ends in exactly one period,
+//! remove the trailing period (i.e. strip trailing periods but not trailing ellipses).
+//!
+//! Sometimes you don't want this preprocessing to apply, for example the comment contains
+//! some ASCII art or markdown tables, you would need to preserve LFs along with
+//! blank lines and the leading/trailing whitespace. When you pass use the
+//! `verbatim_doc_comment` magic attribute, you preserve
+//! them.
+//!
+//! **Note:** Keep in mind that `verbatim_doc_comment` will *still*
+//! - Remove one leading space from each line, even if this attribute is present,
+//! to allow for a space between `///` and the content.
+//! - Remove leading and trailing blank lines
+//!
+//! ## Mixing Builder and Derive APIs
+//!
+//! The builder and derive APIs do not live in isolation. They can work together, which is
+//! especially helpful if some arguments can be specified at compile-time while others must be
+//! specified at runtime.
+//!
+//! ### Using derived arguments in a builder application
+//!
+//! When using the derive API, you can `#[command(flatten)]` a struct deriving `Args` into a struct
+//! deriving `Args` or `Parser`. This example shows how you can augment a `Command` instance
+//! created using the builder API with `Args` created using the derive API.
+//!
+//! It uses the [`Args::augment_args`][crate::Args::augment_args] method to add the arguments to
+//! the `Command` instance.
+//!
+//! Crates such as [clap-verbosity-flag](https://github.com/rust-cli/clap-verbosity-flag) provide
+//! structs that implement `Args`. Without the technique shown in this example, it would not be
+//! possible to use such crates with the builder API.
+//!
+//! For example:
+//! ```rust
+#![doc = include_str!("../../examples/derive_ref/augment_args.rs")]
+//! ```
+//!
+//! ### Using derived subcommands in a builder application
+//!
+//! When using the derive API, you can use `#[command(subcommand)]` inside the struct to add
+//! subcommands. The type of the field is usually an enum that derived `Parser`. However, you can
+//! also add the subcommands in that enum to a `Command` instance created with the builder API.
+//!
+//! It uses the [`Subcommand::augment_subcommands`][crate::Subcommand::augment_subcommands] method
+//! to add the subcommands to the `Command` instance.
+//!
+//! For example:
+//! ```rust
+#![doc = include_str!("../../examples/derive_ref/augment_subcommands.rs")]
+//! ```
+//!
+//! ### Adding hand-implemented subcommands to a derived application
+//!
+//! When using the derive API, you can use `#[command(subcommand)]` inside the struct to add
+//! subcommands. The type of the field is usually an enum that derived `Parser`. However, you can
+//! also implement the `Subcommand` trait manually on this enum (or any other type) and it can
+//! still be used inside the struct created with the derive API. The implementation of the
+//! `Subcommand` trait will use the builder API to add the subcommands to the `Command` instance
+//! created behind the scenes for you by the derive API.
+//!
+//! Notice how in the previous example we used
+//! [`augment_subcommands`][crate::Subcommand::augment_subcommands] on an enum that derived
+//! `Parser`, whereas now we implement
+//! [`augment_subcommands`][crate::Subcommand::augment_subcommands] ourselves, but the derive API
+//! calls it automatically since we used the `#[command(subcommand)]` attribute.
+//!
+//! For example:
+//! ```rust
+#![doc = include_str!("../../examples/derive_ref/hand_subcommand.rs")]
+//! ```
+//!
+//! ### Flattening hand-implemented args into a derived application
+//!
+//! When using the derive API, you can use `#[command(flatten)]` inside the struct to add arguments as
+//! if they were added directly to the containing struct. The type of the field is usually an
+//! struct that derived `Args`. However, you can also implement the `Args` trait manually on this
+//! struct (or any other type) and it can still be used inside the struct created with the derive
+//! API. The implementation of the `Args` trait will use the builder API to add the arguments to
+//! the `Command` instance created behind the scenes for you by the derive API.
+//!
+//! Notice how in the previous example we used [`augment_args`][crate::Args::augment_args] on the
+//! struct that derived `Parser`, whereas now we implement
+//! [`augment_args`][crate::Args::augment_args] ourselves, but the derive API calls it
+//! automatically since we used the `#[command(flatten)]` attribute.
+//!
+//! For example:
+//! ```rust
+#![doc = include_str!("../../examples/derive_ref/flatten_hand_args.rs")]
+//! ```
+//!
+//! ## Tips
+//!
+//! - To get access to a [`Command`][crate::Command] call
+//! [`CommandFactory::command`][crate::CommandFactory::command] (implemented when deriving
+//! [`Parser`][crate::Parser])
+//! - Proactively check for bad [`Command`][crate::Command] configurations by calling
+//! [`Command::debug_assert`][crate::Command::debug_assert] in a test
+//! ([example](../tutorial_derive/05_01_assert.rs))
+//! - Always remember to [document](#doc-comments) args and commands with `#![deny(missing_docs)]`
+
+pub mod _tutorial;
+#[doc(inline)]
+pub use crate::_cookbook;
diff --git a/src/_faq.rs b/src/_faq.rs
new file mode 100644
index 0000000..70e7ca5
--- /dev/null
+++ b/src/_faq.rs
@@ -0,0 +1,95 @@
+//! # Documentation: FAQ
+//!
+//! 1. [Comparisons](#comparisons)
+//! 1. [How does `clap` compare to structopt?](#how-does-clap-compare-to-structopt)
+//! 2. [What are some reasons to use `clap`? (The Pitch)](#what-are-some-reasons-to-use-clap-the-pitch)
+//! 3. [What are some reasons *not* to use `clap`? (The Anti Pitch)](#what-are-some-reasons-not-to-use-clap-the-anti-pitch)
+//! 4. [Reasons to use `clap`](#reasons-to-use-clap)
+//! 2. [How many approaches are there to create a parser?](#how-many-approaches-are-there-to-create-a-parser)
+//! 3. [When should I use the builder vs derive APIs?](#when-should-i-use-the-builder-vs-derive-apis)
+//! 4. [Why is there a default subcommand of help?](#why-is-there-a-default-subcommand-of-help)
+//!
+//! ### Comparisons
+//!
+//! First, let me say that these comparisons are highly subjective, and not meant
+//! in a critical or harsh manner. All the argument parsing libraries out there (to
+//! include `clap`) have their own strengths and weaknesses. Sometimes it just
+//! comes down to personal taste when all other factors are equal. When in doubt,
+//! try them all and pick one that you enjoy :). There's plenty of room in the Rust
+//! community for multiple implementations!
+//!
+//! For less detailed but more broad comparisons, see
+//! [argparse-benchmarks](https://github.com/rust-cli/argparse-benchmarks-rs).
+//!
+//! #### How does `clap` compare to [structopt](https://github.com/TeXitoi/structopt)?
+//!
+//! Simple! `clap` *is* `structopt`. `structopt` started as a derive API built on
+//! top of clap v2. With clap v3, we've forked structopt and integrated it
+//! directly into clap. structopt is in
+//! [maintenance mode](https://github.com/TeXitoi/structopt/issues/516#issuecomment-989566094)
+//! with the release of `clap_derive`.
+//!
+//! The benefits of integrating `structopt` and `clap` are:
+//! - Easier cross-linking in documentation
+//! - [Documentation parity](../examples)
+//! - Tighter design feedback loop, ensuring all new features are designed with
+//! derives in mind and easier to change `clap` in response to `structopt` bugs.
+//! - Clearer endorsement of `structopt`
+//!
+//! See also
+//! - [`clap` v3 CHANGELOG](../CHANGELOG.md#300---2021-12-31)
+//! - [`structopt` migration guide](../CHANGELOG.md#migrate-structopt)
+//!
+//! #### What are some reasons to use `clap`? (The Pitch)
+//!
+//! `clap` is as fast, and as lightweight as possible while still giving all the features you'd expect from a modern argument parser. In fact, for the amount and type of features `clap` offers it remains about as fast as `getopts`. If you use `clap`, when you just need some simple arguments parsed, you'll find it's a walk in the park. `clap` also makes it possible to represent extremely complex and advanced requirements without too much thought. `clap` aims to be intuitive, easy to use, and fully capable for wide variety use cases and needs.
+//!
+//! #### What are some reasons *not* to use `clap`? (The Anti Pitch)
+//!
+//! Depending on the style in which you choose to define the valid arguments, `clap` can be very verbose. `clap` also offers so many finetuning knobs and dials, that learning everything can seem overwhelming. I strive to keep the simple cases simple, but when turning all those custom dials it can get complex. `clap` is also opinionated about parsing. Even though so much can be tweaked and tuned with `clap` (and I'm adding more all the time), there are still certain features which `clap` implements in specific ways that may be contrary to some users' use-cases.
+//!
+//! #### Reasons to use `clap`
+//!
+//! * You want all the nice CLI features your users may expect, yet you don't want to implement them all yourself. You'd like to focus on your application, not argument parsing.
+//! * In addition to the point above, you don't want to sacrifice performance to get all those nice features.
+//! * You have complex requirements/conflicts between your various valid args.
+//! * You want to use subcommands (although other libraries also support subcommands, they are not nearly as feature rich as those provided by `clap`).
+//! * You want some sort of custom validation built into the argument parsing process, instead of as part of your application (which allows for earlier failures, better error messages, more cohesive experience, etc.).
+//!
+//! ### How many approaches are there to create a parser?
+//!
+//! The following APIs are supported:
+//! - [Derive][crate::_derive::_tutorial]
+//! - [Builder][crate::_tutorial]
+//!
+//! Previously, we supported:
+//! - [YAML](https://github.com/clap-rs/clap/issues/3087)
+//! - [docopt](http://docopt.org/)-inspired [usage parser](https://github.com/clap-rs/clap/issues/3086)
+//! - [`clap_app!`](https://github.com/clap-rs/clap/issues/2835)
+//!
+//! There are also experiments with other APIs:
+//! - [fncmd](https://github.com/yuhr/fncmd): function attribute
+//! - [clap-serde](https://github.com/aobatact/clap-serde): create an `Command` from a deserializer
+//!
+//! ### When should I use the builder vs derive APIs?
+//!
+//! Our default answer is to use the [Derive API][crate::_derive::_tutorial]:
+//! - Easier to read, write, and modify
+//! - Easier to keep the argument declaration and reading of argument in sync
+//! - Easier to reuse, e.g. [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag)
+//!
+//! The [Builder API][crate::_tutorial] is a lower-level API that someone might want to use for
+//! - Faster compile times if you aren't already using other procedural macros
+//! - More flexibility, e.g. you can look up an [arguments values][crate::ArgMatches::get_many],
+//! their [ordering with other arguments][crate::ArgMatches::indices_of], and [what set
+//! them][crate::ArgMatches::value_source]. The Derive API can only report values and not
+//! indices of or other data.
+//!
+//! You can [interop between Derive and Builder APIs][crate::_derive#mixing-builder-and-derive-apis].
+//!
+//! ### Why is there a default subcommand of help?
+//!
+//! There is only a default subcommand of `help` when other subcommands have been defined manually. So it's opt-in(ish), being that you only get a `help` subcommand if you're actually using subcommands.
+//!
+//! Also, if the user defined a `help` subcommand themselves, the auto-generated one wouldn't be added (meaning it's only generated if the user hasn't defined one themselves).
+//!
diff --git a/src/_features.rs b/src/_features.rs
new file mode 100644
index 0000000..2f551e7
--- /dev/null
+++ b/src/_features.rs
@@ -0,0 +1,29 @@
+//! ## Documentation: Feature Flags
+//!
+//! Available [compile-time feature flags](https://doc.rust-lang.org/cargo/reference/features.html#dependency-features)
+//!
+//! #### Default Features
+//!
+//! * **std**: _Not Currently Used._ Placeholder for supporting `no_std` environments in a backwards compatible manner.
+//! * **color**: Turns on colored error messages.
+//! * **help**: Auto-generate help output
+//! * **usage**: Auto-generate usage
+//! * **error-context**: Include contextual information for errors (which arg failed, etc)
+//! * **suggestions**: Turns on the `Did you mean '--myoption'?` feature for when users make typos.
+//!
+//! #### Optional features
+//!
+//! * **deprecated**: Guided experience to prepare for next breaking release (at different stages of development, this may become default)
+//! * **derive**: Enables the custom derive (i.e. `#[derive(Parser)]`). Without this you must use one of the other methods of creating a `clap` CLI listed above.
+//! * **cargo**: Turns on macros that read values from [`CARGO_*` environment variables](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates).
+//! * **env**: Turns on the usage of environment variables during parsing.
+//! * **unicode**: Turns on support for unicode characters (including emoji) in arguments and help messages.
+//! * **wrap_help**: Turns on the help text wrapping feature, based on the terminal size.
+//! * **string**: Allow runtime generated strings (e.g. with [`Str`][crate::builder::Str]).
+//!
+//! #### Experimental features
+//!
+//! **Warning:** These may contain breaking changes between minor releases.
+//!
+//! * **unstable-replace**: Enable [`Command::replace`](https://github.com/clap-rs/clap/issues/2836)
+//! * **unstable-v5**: Preview features which will be stable on the v5.0 release
diff --git a/src/_tutorial.rs b/src/_tutorial.rs
new file mode 100644
index 0000000..4605ec9
--- /dev/null
+++ b/src/_tutorial.rs
@@ -0,0 +1,222 @@
+// Contributing
+//
+// New example code:
+// - Please update the corresponding section in the derive tutorial
+// - Building: They must be added to `Cargo.toml` with the appropriate `required-features`.
+// - Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax
+//
+// See also the general CONTRIBUTING
+
+//! # Documentation: Builder Tutorial
+//!
+//! 1. [Quick Start](#quick-start)
+//! 2. [Configuring the Parser](#configuring-the-parser)
+//! 3. [Adding Arguments](#adding-arguments)
+//! 1. [Positionals](#positionals)
+//! 2. [Options](#options)
+//! 3. [Flags](#flags)
+//! 4. [Subcommands](#subcommands)
+//! 5. [Defaults](#defaults)
+//! 4. Validation
+//! 1. [Enumerated values](#enumerated-values)
+//! 2. [Validated values](#validated-values)
+//! 3. [Argument Relations](#argument-relations)
+//! 4. [Custom Validation](#custom-validation)
+//! 5. [Testing](#testing)
+//!
+//! See also
+//! - [FAQ: When should I use the builder vs derive APIs?][crate::_faq#when-should-i-use-the-builder-vs-derive-apis]
+//! - The [cookbook][crate::_cookbook] for more application-focused examples
+//!
+//! ## Quick Start
+//!
+//! You can create an application with several arguments using usage strings.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/01_quick.rs")]
+//! ```
+//!
+#![doc = include_str!("../examples/tutorial_builder/01_quick.md")]
+//!
+//! ## Configuring the Parser
+//!
+//! You use [`Command`][crate::Command] to start building a parser.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/02_apps.rs")]
+//! ```
+//!
+#![doc = include_str!("../examples/tutorial_builder/02_apps.md")]
+//!
+//! You can use [`command!()`][crate::command!] to fill these fields in from your `Cargo.toml`
+//! file. **This requires the [`cargo` feature flag][crate::_features].**
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/02_crate.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/02_crate.md")]
+//!
+//! You can use [`Command`][crate::Command] methods to change the application level behavior of
+//! clap.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/02_app_settings.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/02_app_settings.md")]
+//!
+//! ## Adding Arguments
+//!
+//! ### Positionals
+//!
+//! You can have users specify values by their position on the command-line:
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_03_positional.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_03_positional.md")]
+//!
+//! Note that the default [`ArgAction`][crate::ArgAction] is [`Set`][crate::ArgAction::Set]. To
+//! accept multiple values, use [`Append`][crate::ArgAction::Append]:
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_03_positional_mult.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_03_positional_mult.md")]
+//!
+//! ### Options
+//!
+//! You can name your arguments with a flag:
+//! - Order doesn't matter
+//! - They can be optional
+//! - Intent is clearer
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_02_option.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_02_option.md")]
+//!
+//! Note that the default [`ArgAction`][crate::ArgAction] is [`Set`][crate::ArgAction::Set]. To
+//! accept multiple occurrences, use [`Append`][crate::ArgAction::Append]:
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_02_option_mult.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_02_option_mult.md")]
+//!
+//! ### Flags
+//!
+//! Flags can also be switches that can be on/off:
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_01_flag_bool.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_01_flag_bool.md")]
+//!
+//! To accept multiple flags, use [`Count`][crate::ArgAction::Count]:
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_01_flag_count.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_01_flag_count.md")]
+//!
+//! ### Subcommands
+//!
+//! Subcommands are defined as [`Command`][crate::Command]s that get added via
+//! [`Command::subcommand`][crate::Command::subcommand]. Each instance of a Subcommand can have its
+//! own version, author(s), Args, and even its own subcommands.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_04_subcommands.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_04_subcommands.md")]
+//!
+//! ### Defaults
+//!
+//! We've previously showed that arguments can be [`required`][crate::Arg::required] or optional.
+//! When optional, you work with a `Option` and can `unwrap_or`. Alternatively, you can set
+//! [`Arg::default_value`][crate::Arg::default_value].
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/03_05_default_values.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/03_05_default_values.md")]
+//!
+//! ## Validation
+//!
+//! By default, arguments are assumed to be `String`s and only UTF-8 validation is performed.
+//!
+//! ### Enumerated values
+//!
+//! If you have arguments of specific values you want to test for, you can use the
+//! [`PossibleValuesParser`][crate::builder::PossibleValuesParser] or [`Arg::value_parser(["val1",
+//! ...])`][crate::Arg::value_parser] for short.
+//!
+//! This allows you specify the valid values for that argument. If the user does not use one of
+//! those specific values, they will receive a graceful exit with error message informing them
+//! of the mistake, and what the possible valid values are
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/04_01_possible.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/04_01_possible.md")]
+//!
+//! When enabling the [`derive` feature][crate::_features], you can use
+//! [`ValueEnum`][crate::ValueEnum] to take care of the boiler plate for you, giving the same
+//! results.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/04_01_enum.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/04_01_enum.md")]
+//!
+//! ### Validated values
+//!
+//! More generally, you can validate and parse into any data type.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/04_02_parse.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/04_02_parse.md")]
+//!
+//! A custom parser can be used to improve the error messages or provide additional validation:
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/04_02_validate.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/04_02_validate.md")]
+//!
+//! See [`Arg::value_parser`][crate::Arg::value_parser] for more details.
+//!
+//! ### Argument Relations
+//!
+//! You can declare dependencies or conflicts between [`Arg`][crate::Arg]s or even
+//! [`ArgGroup`][crate::ArgGroup]s.
+//!
+//! [`ArgGroup`][crate::ArgGroup]s make it easier to declare relations instead of having to list
+//! each individually, or when you want a rule to apply "any but not all" arguments.
+//!
+//! Perhaps the most common use of [`ArgGroup`][crate::ArgGroup]s is to require one and *only* one
+//! argument to be present out of a given set. Imagine that you had multiple arguments, and you
+//! want one of them to be required, but making all of them required isn't feasible because perhaps
+//! they conflict with each other.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/04_03_relations.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/04_03_relations.md")]
+//!
+//! ### Custom Validation
+//!
+//! As a last resort, you can create custom errors with the basics of clap's formatting.
+//!
+//! ```rust
+#![doc = include_str!("../examples/tutorial_builder/04_04_custom.rs")]
+//! ```
+#![doc = include_str!("../examples/tutorial_builder/04_04_custom.md")]
+//!
+//! ## Testing
+//!
+//! clap reports most development errors as `debug_assert!`s. Rather than checking every
+//! subcommand, you should have a test that calls
+//! [`Command::debug_assert`][crate::Command::debug_assert]:
+//! ```rust,no_run
+#![doc = include_str!("../examples/tutorial_builder/05_01_assert.rs")]
+//! ```
diff --git a/src/app/help.rs b/src/app/help.rs
deleted file mode 100644
index ef57dbb..0000000
--- a/src/app/help.rs
+++ /dev/null
@@ -1,1034 +0,0 @@
-// Std
-use std::borrow::Cow;
-use std::cmp;
-use std::collections::BTreeMap;
-use std::fmt::Display;
-use std::io::{self, Cursor, Read, Write};
-use std::usize;
-
-// Internal
-use app::parser::Parser;
-use app::usage;
-use app::{App, AppSettings};
-use args::{AnyArg, ArgSettings, DispOrder};
-use errors::{Error, Result as ClapResult};
-use fmt::{Colorizer, ColorizerOption, Format};
-use map::VecMap;
-use INTERNAL_ERROR_MSG;
-
-// Third Party
-#[cfg(feature = "wrap_help")]
-use term_size;
-use textwrap;
-
-#[cfg(not(feature = "wrap_help"))]
-mod term_size {
- pub fn dimensions() -> Option<(usize, usize)> {
- None
- }
-}
-
-fn str_width(s: &str) -> usize {
- #[cfg(not(feature = "unicode_help"))]
- return s.len();
-
- #[cfg(feature = "unicode_help")]
- UnicodeWidthStr::width(s)
-}
-
-const TAB: &'static str = " ";
-
-// These are just convenient traits to make the code easier to read.
-trait ArgWithDisplay<'b, 'c>: AnyArg<'b, 'c> + Display {}
-impl<'b, 'c, T> ArgWithDisplay<'b, 'c> for T where T: AnyArg<'b, 'c> + Display {}
-
-trait ArgWithOrder<'b, 'c>: ArgWithDisplay<'b, 'c> + DispOrder {
- fn as_base(&self) -> &ArgWithDisplay<'b, 'c>;
-}
-impl<'b, 'c, T> ArgWithOrder<'b, 'c> for T
-where
- T: ArgWithDisplay<'b, 'c> + DispOrder,
-{
- fn as_base(&self) -> &ArgWithDisplay<'b, 'c> {
- self
- }
-}
-
-fn as_arg_trait<'a, 'b, T: ArgWithOrder<'a, 'b>>(x: &T) -> &ArgWithOrder<'a, 'b> {
- x
-}
-
-impl<'b, 'c> DispOrder for App<'b, 'c> {
- fn disp_ord(&self) -> usize {
- 999
- }
-}
-
-macro_rules! color {
- ($_self:ident, $s:expr, $c:ident) => {
- if $_self.color {
- write!($_self.writer, "{}", $_self.cizer.$c($s))
- } else {
- write!($_self.writer, "{}", $s)
- }
- };
- ($_self:ident, $fmt_s:expr, $v:expr, $c:ident) => {
- if $_self.color {
- write!($_self.writer, "{}", $_self.cizer.$c(format!($fmt_s, $v)))
- } else {
- write!($_self.writer, $fmt_s, $v)
- }
- };
-}
-
-/// `clap` Help Writer.
-///
-/// Wraps a writer stream providing different methods to generate help for `clap` objects.
-pub struct Help<'a> {
- writer: &'a mut Write,
- next_line_help: bool,
- hide_pv: bool,
- term_w: usize,
- color: bool,
- cizer: Colorizer,
- longest: usize,
- force_next_line: bool,
- use_long: bool,
-}
-
-// Public Functions
-impl<'a> Help<'a> {
- /// Create a new `Help` instance.
- #[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
- pub fn new(
- w: &'a mut Write,
- next_line_help: bool,
- hide_pv: bool,
- color: bool,
- cizer: Colorizer,
- term_w: Option<usize>,
- max_w: Option<usize>,
- use_long: bool,
- ) -> Self {
- debugln!("Help::new;");
- Help {
- writer: w,
- next_line_help: next_line_help,
- hide_pv: hide_pv,
- term_w: match term_w {
- Some(width) => {
- if width == 0 {
- usize::MAX
- } else {
- width
- }
- }
- None => cmp::min(
- term_size::dimensions().map_or(120, |(w, _)| w),
- match max_w {
- None | Some(0) => usize::MAX,
- Some(mw) => mw,
- },
- ),
- },
- color: color,
- cizer: cizer,
- longest: 0,
- force_next_line: false,
- use_long: use_long,
- }
- }
-
- /// Reads help settings from an App
- /// and write its help to the wrapped stream.
- pub fn write_app_help(w: &'a mut Write, app: &App, use_long: bool) -> ClapResult<()> {
- debugln!("Help::write_app_help;");
- Self::write_parser_help(w, &app.p, use_long)
- }
-
- /// Reads help settings from a Parser
- /// and write its help to the wrapped stream.
- pub fn write_parser_help(w: &'a mut Write, parser: &Parser, use_long: bool) -> ClapResult<()> {
- debugln!("Help::write_parser_help;");
- Self::_write_parser_help(w, parser, false, use_long)
- }
-
- /// Reads help settings from a Parser
- /// and write its help to the wrapped stream which will be stderr. This method prevents
- /// formatting when required.
- pub fn write_parser_help_to_stderr(w: &'a mut Write, parser: &Parser) -> ClapResult<()> {
- debugln!("Help::write_parser_help;");
- Self::_write_parser_help(w, parser, true, false)
- }
-
- #[doc(hidden)]
- pub fn _write_parser_help(
- w: &'a mut Write,
- parser: &Parser,
- stderr: bool,
- use_long: bool,
- ) -> ClapResult<()> {
- debugln!("Help::write_parser_help;");
- let nlh = parser.is_set(AppSettings::NextLineHelp);
- let hide_v = parser.is_set(AppSettings::HidePossibleValuesInHelp);
- let color = parser.is_set(AppSettings::ColoredHelp);
- let cizer = Colorizer::new(ColorizerOption {
- use_stderr: stderr,
- when: parser.color(),
- });
- Self::new(
- w,
- nlh,
- hide_v,
- color,
- cizer,
- parser.meta.term_w,
- parser.meta.max_w,
- use_long,
- )
- .write_help(parser)
- }
-
- /// Writes the parser help to the wrapped stream.
- pub fn write_help(&mut self, parser: &Parser) -> ClapResult<()> {
- debugln!("Help::write_help;");
- if let Some(h) = parser.meta.help_str {
- write!(self.writer, "{}", h).map_err(Error::from)?;
- } else if let Some(tmpl) = parser.meta.template {
- self.write_templated_help(parser, tmpl)?;
- } else {
- self.write_default_help(parser)?;
- }
- Ok(())
- }
-}
-
-// Methods to write AnyArg help.
-impl<'a> Help<'a> {
- /// Writes help for each argument in the order they were declared to the wrapped stream.
- fn write_args_unsorted<'b: 'd, 'c: 'd, 'd, I: 'd>(&mut self, args: I) -> io::Result<()>
- where
- I: Iterator<Item = &'d ArgWithOrder<'b, 'c>>,
- {
- debugln!("Help::write_args_unsorted;");
- // The shortest an arg can legally be is 2 (i.e. '-x')
- self.longest = 2;
- let mut arg_v = Vec::with_capacity(10);
- let use_long = self.use_long;
- for arg in args.filter(|arg| should_show_arg(use_long, *arg)) {
- if arg.longest_filter() {
- self.longest = cmp::max(self.longest, str_width(arg.to_string().as_str()));
- }
- arg_v.push(arg)
- }
- let mut first = true;
- for arg in arg_v {
- if first {
- first = false;
- } else {
- self.writer.write_all(b"\n")?;
- }
- self.write_arg(arg.as_base())?;
- }
- Ok(())
- }
-
- /// Sorts arguments by length and display order and write their help to the wrapped stream.
- fn write_args<'b: 'd, 'c: 'd, 'd, I: 'd>(&mut self, args: I) -> io::Result<()>
- where
- I: Iterator<Item = &'d ArgWithOrder<'b, 'c>>,
- {
- debugln!("Help::write_args;");
- // The shortest an arg can legally be is 2 (i.e. '-x')
- self.longest = 2;
- let mut ord_m = VecMap::new();
- let use_long = self.use_long;
- // Determine the longest
- for arg in args.filter(|arg| {
- // If it's NextLineHelp, but we don't care to compute how long because it may be
- // NextLineHelp on purpose *because* it's so long and would throw off all other
- // args alignment
- should_show_arg(use_long, *arg)
- }) {
- if arg.longest_filter() {
- debugln!("Help::write_args: Current Longest...{}", self.longest);
- self.longest = cmp::max(self.longest, str_width(arg.to_string().as_str()));
- debugln!("Help::write_args: New Longest...{}", self.longest);
- }
- let btm = ord_m.entry(arg.disp_ord()).or_insert(BTreeMap::new());
- btm.insert(arg.name(), arg);
- }
- let mut first = true;
- for btm in ord_m.values() {
- for arg in btm.values() {
- if first {
- first = false;
- } else {
- self.writer.write_all(b"\n")?;
- }
- self.write_arg(arg.as_base())?;
- }
- }
- Ok(())
- }
-
- /// Writes help for an argument to the wrapped stream.
- fn write_arg<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> {
- debugln!("Help::write_arg;");
- self.short(arg)?;
- self.long(arg)?;
- let spec_vals = self.val(arg)?;
- self.help(arg, &*spec_vals)?;
- Ok(())
- }
-
- /// Writes argument's short command to the wrapped stream.
- fn short<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> {
- debugln!("Help::short;");
- write!(self.writer, "{}", TAB)?;
- if let Some(s) = arg.short() {
- color!(self, "-{}", s, good)
- } else if arg.has_switch() {
- write!(self.writer, "{}", TAB)
- } else {
- Ok(())
- }
- }
-
- /// Writes argument's long command to the wrapped stream.
- fn long<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> {
- debugln!("Help::long;");
- if !arg.has_switch() {
- return Ok(());
- }
- if arg.takes_value() {
- if let Some(l) = arg.long() {
- if arg.short().is_some() {
- write!(self.writer, ", ")?;
- }
- color!(self, "--{}", l, good)?
- }
-
- let sep = if arg.is_set(ArgSettings::RequireEquals) {
- "="
- } else {
- " "
- };
- write!(self.writer, "{}", sep)?;
- } else if let Some(l) = arg.long() {
- if arg.short().is_some() {
- write!(self.writer, ", ")?;
- }
- color!(self, "--{}", l, good)?;
- }
- Ok(())
- }
-
- /// Writes argument's possible values to the wrapped stream.
- fn val<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> Result<String, io::Error> {
- debugln!("Help::val: arg={}", arg);
- if arg.takes_value() {
- let delim = if arg.is_set(ArgSettings::RequireDelimiter) {
- arg.val_delim().expect(INTERNAL_ERROR_MSG)
- } else {
- ' '
- };
- if let Some(vec) = arg.val_names() {
- let mut it = vec.iter().peekable();
- while let Some((_, val)) = it.next() {
- color!(self, "<{}>", val, good)?;
- if it.peek().is_some() {
- write!(self.writer, "{}", delim)?;
- }
- }
- let num = vec.len();
- if arg.is_set(ArgSettings::Multiple) && num == 1 {
- color!(self, "...", good)?;
- }
- } else if let Some(num) = arg.num_vals() {
- let mut it = (0..num).peekable();
- while let Some(_) = it.next() {
- color!(self, "<{}>", arg.name(), good)?;
- if it.peek().is_some() {
- write!(self.writer, "{}", delim)?;
- }
- }
- if arg.is_set(ArgSettings::Multiple) && num == 1 {
- color!(self, "...", good)?;
- }
- } else if arg.has_switch() {
- color!(self, "<{}>", arg.name(), good)?;
- if arg.is_set(ArgSettings::Multiple) {
- color!(self, "...", good)?;
- }
- } else {
- color!(self, "{}", arg, good)?;
- }
- }
-
- let spec_vals = self.spec_vals(arg);
- let h = arg.help().unwrap_or("");
- let h_w = str_width(h) + str_width(&*spec_vals);
- let nlh = self.next_line_help || arg.is_set(ArgSettings::NextLineHelp);
- let taken = self.longest + 12;
- self.force_next_line = !nlh
- && self.term_w >= taken
- && (taken as f32 / self.term_w as f32) > 0.40
- && h_w > (self.term_w - taken);
-
- debug!("Help::val: Has switch...");
- if arg.has_switch() {
- sdebugln!("Yes");
- debugln!("Help::val: force_next_line...{:?}", self.force_next_line);
- debugln!("Help::val: nlh...{:?}", nlh);
- debugln!("Help::val: taken...{}", taken);
- debugln!(
- "Help::val: help_width > (width - taken)...{} > ({} - {})",
- h_w,
- self.term_w,
- taken
- );
- debugln!("Help::val: longest...{}", self.longest);
- debug!("Help::val: next_line...");
- if !(nlh || self.force_next_line) {
- sdebugln!("No");
- let self_len = str_width(arg.to_string().as_str());
- // subtract ourself
- let mut spcs = self.longest - self_len;
- // Since we're writing spaces from the tab point we first need to know if we
- // had a long and short, or just short
- if arg.long().is_some() {
- // Only account 4 after the val
- spcs += 4;
- } else {
- // Only account for ', --' + 4 after the val
- spcs += 8;
- }
-
- write_nspaces!(self.writer, spcs);
- } else {
- sdebugln!("Yes");
- }
- } else if !(nlh || self.force_next_line) {
- sdebugln!("No, and not next_line");
- write_nspaces!(
- self.writer,
- self.longest + 4 - (str_width(arg.to_string().as_str()))
- );
- } else {
- sdebugln!("No");
- }
- Ok(spec_vals)
- }
-
- fn write_before_after_help(&mut self, h: &str) -> io::Result<()> {
- debugln!("Help::write_before_after_help;");
- let mut help = String::from(h);
- // determine if our help fits or needs to wrap
- debugln!(
- "Help::write_before_after_help: Term width...{}",
- self.term_w
- );
- let too_long = str_width(h) >= self.term_w;
-
- debug!("Help::write_before_after_help: Too long...");
- if too_long || h.contains("{n}") {
- sdebugln!("Yes");
- debugln!("Help::write_before_after_help: help: {}", help);
- debugln!(
- "Help::write_before_after_help: help width: {}",
- str_width(&*help)
- );
- // Determine how many newlines we need to insert
- debugln!(
- "Help::write_before_after_help: Usable space: {}",
- self.term_w
- );
- help = wrap_help(&help.replace("{n}", "\n"), self.term_w);
- } else {
- sdebugln!("No");
- }
- write!(self.writer, "{}", help)?;
- Ok(())
- }
-
- /// Writes argument's help to the wrapped stream.
- fn help<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>, spec_vals: &str) -> io::Result<()> {
- debugln!("Help::help;");
- let h = if self.use_long && arg.name() != "" {
- arg.long_help().unwrap_or_else(|| arg.help().unwrap_or(""))
- } else {
- arg.help().unwrap_or_else(|| arg.long_help().unwrap_or(""))
- };
- let mut help = String::from(h) + spec_vals;
- let nlh = self.next_line_help
- || arg.is_set(ArgSettings::NextLineHelp)
- || (self.use_long && arg.name() != "");
- debugln!("Help::help: Next Line...{:?}", nlh);
-
- let spcs = if nlh || self.force_next_line {
- 12 // "tab" * 3
- } else {
- self.longest + 12
- };
-
- let too_long = spcs + str_width(h) + str_width(&*spec_vals) >= self.term_w;
-
- // Is help on next line, if so then indent
- if nlh || self.force_next_line {
- write!(self.writer, "\n{}{}{}", TAB, TAB, TAB)?;
- }
-
- debug!("Help::help: Too long...");
- if too_long && spcs <= self.term_w || h.contains("{n}") {
- sdebugln!("Yes");
- debugln!("Help::help: help...{}", help);
- debugln!("Help::help: help width...{}", str_width(&*help));
- // Determine how many newlines we need to insert
- let avail_chars = self.term_w - spcs;
- debugln!("Help::help: Usable space...{}", avail_chars);
- help = wrap_help(&help.replace("{n}", "\n"), avail_chars);
- } else {
- sdebugln!("No");
- }
- if let Some(part) = help.lines().next() {
- write!(self.writer, "{}", part)?;
- }
- for part in help.lines().skip(1) {
- write!(self.writer, "\n")?;
- if nlh || self.force_next_line {
- write!(self.writer, "{}{}{}", TAB, TAB, TAB)?;
- } else if arg.has_switch() {
- write_nspaces!(self.writer, self.longest + 12);
- } else {
- write_nspaces!(self.writer, self.longest + 8);
- }
- write!(self.writer, "{}", part)?;
- }
- if !help.contains('\n') && (nlh || self.force_next_line) {
- write!(self.writer, "\n")?;
- }
- Ok(())
- }
-
- fn spec_vals(&self, a: &ArgWithDisplay) -> String {
- debugln!("Help::spec_vals: a={}", a);
- let mut spec_vals = vec![];
- if let Some(ref env) = a.env() {
- debugln!(
- "Help::spec_vals: Found environment variable...[{:?}:{:?}]",
- env.0,
- env.1
- );
- let env_val = if !a.is_set(ArgSettings::HideEnvValues) {
- format!(
- "={}",
- env.1.map_or(Cow::Borrowed(""), |val| val.to_string_lossy())
- )
- } else {
- String::new()
- };
- let env_info = format!(" [env: {}{}]", env.0.to_string_lossy(), env_val);
- spec_vals.push(env_info);
- }
- if !a.is_set(ArgSettings::HideDefaultValue) {
- if let Some(pv) = a.default_val() {
- debugln!("Help::spec_vals: Found default value...[{:?}]", pv);
- spec_vals.push(format!(
- " [default: {}]",
- if self.color {
- self.cizer.good(pv.to_string_lossy())
- } else {
- Format::None(pv.to_string_lossy())
- }
- ));
- }
- }
- if let Some(ref aliases) = a.aliases() {
- debugln!("Help::spec_vals: Found aliases...{:?}", aliases);
- spec_vals.push(format!(
- " [aliases: {}]",
- if self.color {
- aliases
- .iter()
- .map(|v| format!("{}", self.cizer.good(v)))
- .collect::<Vec<_>>()
- .join(", ")
- } else {
- aliases.join(", ")
- }
- ));
- }
- if !self.hide_pv && !a.is_set(ArgSettings::HidePossibleValues) {
- if let Some(pv) = a.possible_vals() {
- debugln!("Help::spec_vals: Found possible vals...{:?}", pv);
- spec_vals.push(if self.color {
- format!(
- " [possible values: {}]",
- pv.iter()
- .map(|v| format!("{}", self.cizer.good(v)))
- .collect::<Vec<_>>()
- .join(", ")
- )
- } else {
- format!(" [possible values: {}]", pv.join(", "))
- });
- }
- }
- spec_vals.join(" ")
- }
-}
-
-fn should_show_arg(use_long: bool, arg: &ArgWithOrder) -> bool {
- if arg.is_set(ArgSettings::Hidden) {
- return false;
- }
-
- (!arg.is_set(ArgSettings::HiddenLongHelp) && use_long)
- || (!arg.is_set(ArgSettings::HiddenShortHelp) && !use_long)
- || arg.is_set(ArgSettings::NextLineHelp)
-}
-
-// Methods to write Parser help.
-impl<'a> Help<'a> {
- /// Writes help for all arguments (options, flags, args, subcommands)
- /// including titles of a Parser Object to the wrapped stream.
- #[cfg_attr(feature = "lints", allow(useless_let_if_seq))]
- #[cfg_attr(feature = "cargo-clippy", allow(useless_let_if_seq))]
- pub fn write_all_args(&mut self, parser: &Parser) -> ClapResult<()> {
- debugln!("Help::write_all_args;");
- let flags = parser.has_flags();
- let pos = parser
- .positionals()
- .filter(|arg| !arg.is_set(ArgSettings::Hidden))
- .count()
- > 0;
- let opts = parser.has_opts();
- let subcmds = parser.has_visible_subcommands();
-
- let unified_help = parser.is_set(AppSettings::UnifiedHelpMessage);
-
- let mut first = true;
-
- if unified_help && (flags || opts) {
- let opts_flags = parser
- .flags()
- .map(as_arg_trait)
- .chain(parser.opts().map(as_arg_trait));
- color!(self, "OPTIONS:\n", warning)?;
- self.write_args(opts_flags)?;
- first = false;
- } else {
- if flags {
- color!(self, "FLAGS:\n", warning)?;
- self.write_args(parser.flags().map(as_arg_trait))?;
- first = false;
- }
- if opts {
- if !first {
- self.writer.write_all(b"\n\n")?;
- }
- color!(self, "OPTIONS:\n", warning)?;
- self.write_args(parser.opts().map(as_arg_trait))?;
- first = false;
- }
- }
-
- if pos {
- if !first {
- self.writer.write_all(b"\n\n")?;
- }
- color!(self, "ARGS:\n", warning)?;
- self.write_args_unsorted(parser.positionals().map(as_arg_trait))?;
- first = false;
- }
-
- if subcmds {
- if !first {
- self.writer.write_all(b"\n\n")?;
- }
- color!(self, "SUBCOMMANDS:\n", warning)?;
- self.write_subcommands(parser)?;
- }
-
- Ok(())
- }
-
- /// Writes help for subcommands of a Parser Object to the wrapped stream.
- fn write_subcommands(&mut self, parser: &Parser) -> io::Result<()> {
- debugln!("Help::write_subcommands;");
- // The shortest an arg can legally be is 2 (i.e. '-x')
- self.longest = 2;
- let mut ord_m = VecMap::new();
- for sc in parser
- .subcommands
- .iter()
- .filter(|s| !s.p.is_set(AppSettings::Hidden))
- {
- let btm = ord_m.entry(sc.p.meta.disp_ord).or_insert(BTreeMap::new());
- self.longest = cmp::max(self.longest, str_width(sc.p.meta.name.as_str()));
- //self.longest = cmp::max(self.longest, sc.p.meta.name.len());
- btm.insert(sc.p.meta.name.clone(), sc.clone());
- }
-
- let mut first = true;
- for btm in ord_m.values() {
- for sc in btm.values() {
- if first {
- first = false;
- } else {
- self.writer.write_all(b"\n")?;
- }
- self.write_arg(sc)?;
- }
- }
- Ok(())
- }
-
- /// Writes version of a Parser Object to the wrapped stream.
- fn write_version(&mut self, parser: &Parser) -> io::Result<()> {
- debugln!("Help::write_version;");
- write!(self.writer, "{}", parser.meta.version.unwrap_or(""))?;
- Ok(())
- }
-
- /// Writes binary name of a Parser Object to the wrapped stream.
- fn write_bin_name(&mut self, parser: &Parser) -> io::Result<()> {
- debugln!("Help::write_bin_name;");
- macro_rules! write_name {
- () => {{
- let mut name = parser.meta.name.clone();
- name = name.replace("{n}", "\n");
- color!(self, wrap_help(&name, self.term_w), good)?;
- }};
- }
- if let Some(bn) = parser.meta.bin_name.as_ref() {
- if bn.contains(' ') {
- // Incase we're dealing with subcommands i.e. git mv is translated to git-mv
- color!(self, bn.replace(" ", "-"), good)?
- } else {
- write_name!();
- }
- } else {
- write_name!();
- }
- Ok(())
- }
-
- /// Writes default help for a Parser Object to the wrapped stream.
- pub fn write_default_help(&mut self, parser: &Parser) -> ClapResult<()> {
- debugln!("Help::write_default_help;");
- if let Some(h) = parser.meta.pre_help {
- self.write_before_after_help(h)?;
- self.writer.write_all(b"\n\n")?;
- }
-
- macro_rules! write_thing {
- ($thing:expr) => {{
- let mut owned_thing = $thing.to_owned();
- owned_thing = owned_thing.replace("{n}", "\n");
- write!(self.writer, "{}\n", wrap_help(&owned_thing, self.term_w))?
- }};
- }
- // Print the version
- self.write_bin_name(parser)?;
- self.writer.write_all(b" ")?;
- self.write_version(parser)?;
- self.writer.write_all(b"\n")?;
- if let Some(author) = parser.meta.author {
- write_thing!(author)
- }
- // if self.use_long {
- // if let Some(about) = parser.meta.long_about {
- // debugln!("Help::write_default_help: writing long about");
- // write_thing!(about)
- // } else if let Some(about) = parser.meta.about {
- // debugln!("Help::write_default_help: writing about");
- // write_thing!(about)
- // }
- // } else
- if let Some(about) = parser.meta.long_about {
- debugln!("Help::write_default_help: writing long about");
- write_thing!(about)
- } else if let Some(about) = parser.meta.about {
- debugln!("Help::write_default_help: writing about");
- write_thing!(about)
- }
-
- color!(self, "\nUSAGE:", warning)?;
- write!(
- self.writer,
- "\n{}{}\n\n",
- TAB,
- usage::create_usage_no_title(parser, &[])
- )?;
-
- let flags = parser.has_flags();
- let pos = parser.has_positionals();
- let opts = parser.has_opts();
- let subcmds = parser.has_subcommands();
-
- if flags || opts || pos || subcmds {
- self.write_all_args(parser)?;
- }
-
- if let Some(h) = parser.meta.more_help {
- if flags || opts || pos || subcmds {
- self.writer.write_all(b"\n\n")?;
- }
- self.write_before_after_help(h)?;
- }
-
- self.writer.flush().map_err(Error::from)
- }
-}
-
-/// Possible results for a copying function that stops when a given
-/// byte was found.
-enum CopyUntilResult {
- DelimiterFound(usize),
- DelimiterNotFound(usize),
- ReaderEmpty,
- ReadError(io::Error),
- WriteError(io::Error),
-}
-
-/// Copies the contents of a reader into a writer until a delimiter byte is found.
-/// On success, the total number of bytes that were
-/// copied from reader to writer is returned.
-fn copy_until<R: Read, W: Write>(r: &mut R, w: &mut W, delimiter_byte: u8) -> CopyUntilResult {
- debugln!("copy_until;");
-
- let mut count = 0;
- for wb in r.bytes() {
- match wb {
- Ok(b) => {
- if b == delimiter_byte {
- return CopyUntilResult::DelimiterFound(count);
- }
- match w.write(&[b]) {
- Ok(c) => count += c,
- Err(e) => return CopyUntilResult::WriteError(e),
- }
- }
- Err(e) => return CopyUntilResult::ReadError(e),
- }
- }
- if count > 0 {
- CopyUntilResult::DelimiterNotFound(count)
- } else {
- CopyUntilResult::ReaderEmpty
- }
-}
-
-/// Copies the contents of a reader into a writer until a {tag} is found,
-/// copying the tag content to a buffer and returning its size.
-/// In addition to errors, there are three possible outputs:
-/// - `None`: The reader was consumed.
-/// - `Some(Ok(0))`: No tag was captured but the reader still contains data.
-/// - `Some(Ok(length>0))`: a tag with `length` was captured to the `tag_buffer`.
-fn copy_and_capture<R: Read, W: Write>(
- r: &mut R,
- w: &mut W,
- tag_buffer: &mut Cursor<Vec<u8>>,
-) -> Option<io::Result<usize>> {
- use self::CopyUntilResult::*;
- debugln!("copy_and_capture;");
-
- // Find the opening byte.
- match copy_until(r, w, b'{') {
- // The end of the reader was reached without finding the opening tag.
- // (either with or without having copied data to the writer)
- // Return None indicating that we are done.
- ReaderEmpty | DelimiterNotFound(_) => None,
-
- // Something went wrong.
- ReadError(e) | WriteError(e) => Some(Err(e)),
-
- // The opening byte was found.
- // (either with or without having copied data to the writer)
- DelimiterFound(_) => {
- // Lets reset the buffer first and find out how long it is.
- tag_buffer.set_position(0);
- let buffer_size = tag_buffer.get_ref().len();
-
- // Find the closing byte,limiting the reader to the length of the buffer.
- let mut rb = r.take(buffer_size as u64);
- match copy_until(&mut rb, tag_buffer, b'}') {
- // We were already at the end of the reader.
- // Return None indicating that we are done.
- ReaderEmpty => None,
-
- // The closing tag was found.
- // Return the tag_length.
- DelimiterFound(tag_length) => Some(Ok(tag_length)),
-
- // The end of the reader was found without finding the closing tag.
- // Write the opening byte and captured text to the writer.
- // Return 0 indicating that nothing was captured but the reader still contains data.
- DelimiterNotFound(not_tag_length) => match w.write(b"{") {
- Err(e) => Some(Err(e)),
- _ => match w.write(&tag_buffer.get_ref()[0..not_tag_length]) {
- Err(e) => Some(Err(e)),
- _ => Some(Ok(0)),
- },
- },
-
- ReadError(e) | WriteError(e) => Some(Err(e)),
- }
- }
- }
-}
-
-// Methods to write Parser help using templates.
-impl<'a> Help<'a> {
- /// Write help to stream for the parser in the format defined by the template.
- ///
- /// Tags arg given inside curly brackets:
- /// Valid tags are:
- /// * `{bin}` - Binary name.
- /// * `{version}` - Version number.
- /// * `{author}` - Author information.
- /// * `{usage}` - Automatically generated or given usage string.
- /// * `{all-args}` - Help for all arguments (options, flags, positionals arguments,
- /// and subcommands) including titles.
- /// * `{unified}` - Unified help for options and flags.
- /// * `{flags}` - Help for flags.
- /// * `{options}` - Help for options.
- /// * `{positionals}` - Help for positionals arguments.
- /// * `{subcommands}` - Help for subcommands.
- /// * `{after-help}` - Info to be displayed after the help message.
- /// * `{before-help}` - Info to be displayed before the help message.
- ///
- /// The template system is, on purpose, very simple. Therefore the tags have to written
- /// in the lowercase and without spacing.
- fn write_templated_help(&mut self, parser: &Parser, template: &str) -> ClapResult<()> {
- debugln!("Help::write_templated_help;");
- let mut tmplr = Cursor::new(&template);
- let mut tag_buf = Cursor::new(vec![0u8; 15]);
-
- // The strategy is to copy the template from the reader to wrapped stream
- // until a tag is found. Depending on its value, the appropriate content is copied
- // to the wrapped stream.
- // The copy from template is then resumed, repeating this sequence until reading
- // the complete template.
-
- loop {
- let tag_length = match copy_and_capture(&mut tmplr, &mut self.writer, &mut tag_buf) {
- None => return Ok(()),
- Some(Err(e)) => return Err(Error::from(e)),
- Some(Ok(val)) if val > 0 => val,
- _ => continue,
- };
-
- debugln!("Help::write_template_help:iter: tag_buf={};", unsafe {
- String::from_utf8_unchecked(
- tag_buf.get_ref()[0..tag_length]
- .iter()
- .map(|&i| i)
- .collect::<Vec<_>>(),
- )
- });
- match &tag_buf.get_ref()[0..tag_length] {
- b"?" => {
- self.writer.write_all(b"Could not decode tag name")?;
- }
- b"bin" => {
- self.write_bin_name(parser)?;
- }
- b"version" => {
- write!(
- self.writer,
- "{}",
- parser.meta.version.unwrap_or("unknown version")
- )?;
- }
- b"author" => {
- write!(
- self.writer,
- "{}",
- parser.meta.author.unwrap_or("unknown author")
- )?;
- }
- b"about" => {
- write!(
- self.writer,
- "{}",
- parser.meta.about.unwrap_or("unknown about")
- )?;
- }
- b"long-about" => {
- write!(
- self.writer,
- "{}",
- parser.meta.long_about.unwrap_or("unknown about")
- )?;
- }
- b"usage" => {
- write!(self.writer, "{}", usage::create_usage_no_title(parser, &[]))?;
- }
- b"all-args" => {
- self.write_all_args(parser)?;
- }
- b"unified" => {
- let opts_flags = parser
- .flags()
- .map(as_arg_trait)
- .chain(parser.opts().map(as_arg_trait));
- self.write_args(opts_flags)?;
- }
- b"flags" => {
- self.write_args(parser.flags().map(as_arg_trait))?;
- }
- b"options" => {
- self.write_args(parser.opts().map(as_arg_trait))?;
- }
- b"positionals" => {
- self.write_args(parser.positionals().map(as_arg_trait))?;
- }
- b"subcommands" => {
- self.write_subcommands(parser)?;
- }
- b"after-help" => {
- write!(
- self.writer,
- "{}",
- parser.meta.more_help.unwrap_or("unknown after-help")
- )?;
- }
- b"before-help" => {
- write!(
- self.writer,
- "{}",
- parser.meta.pre_help.unwrap_or("unknown before-help")
- )?;
- }
- // Unknown tag, write it back.
- r => {
- self.writer.write_all(b"{")?;
- self.writer.write_all(r)?;
- self.writer.write_all(b"}")?;
- }
- }
- }
- }
-}
-
-fn wrap_help(help: &str, avail_chars: usize) -> String {
- let wrapper = textwrap::Options::new(avail_chars).break_words(false);
- help.lines()
- .map(|line| textwrap::fill(line, &wrapper))
- .collect::<Vec<String>>()
- .join("\n")
-}
-
-#[cfg(test)]
-mod test {
- use super::wrap_help;
-
- #[test]
- fn wrap_help_last_word() {
- let help = String::from("foo bar baz");
- assert_eq!(wrap_help(&help, 5), "foo\nbar\nbaz");
- }
-}
diff --git a/src/app/meta.rs b/src/app/meta.rs
deleted file mode 100644
index 8916101..0000000
--- a/src/app/meta.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-#[doc(hidden)]
-#[allow(missing_debug_implementations)]
-#[derive(Default, Clone)]
-pub struct AppMeta<'b> {
- pub name: String,
- pub bin_name: Option<String>,
- pub author: Option<&'b str>,
- pub version: Option<&'b str>,
- pub long_version: Option<&'b str>,
- pub about: Option<&'b str>,
- pub long_about: Option<&'b str>,
- pub more_help: Option<&'b str>,
- pub pre_help: Option<&'b str>,
- pub aliases: Option<Vec<(&'b str, bool)>>, // (name, visible)
- pub usage_str: Option<&'b str>,
- pub usage: Option<String>,
- pub help_str: Option<&'b str>,
- pub disp_ord: usize,
- pub term_w: Option<usize>,
- pub max_w: Option<usize>,
- pub template: Option<&'b str>,
-}
-
-impl<'b> AppMeta<'b> {
- pub fn new() -> Self {
- Default::default()
- }
- pub fn with_name(s: String) -> Self {
- AppMeta {
- name: s,
- disp_ord: 999,
- ..Default::default()
- }
- }
-}
diff --git a/src/app/mod.rs b/src/app/mod.rs
deleted file mode 100644
index 3fff846..0000000
--- a/src/app/mod.rs
+++ /dev/null
@@ -1,1904 +0,0 @@
-mod help;
-mod meta;
-pub mod parser;
-mod settings;
-mod usage;
-mod validator;
-
-// Std
-use std::env;
-use std::ffi::{OsStr, OsString};
-use std::fmt;
-use std::io::{self, BufRead, BufWriter, Write};
-use std::path::Path;
-use std::process;
-use std::rc::Rc;
-use std::result::Result as StdResult;
-
-// Third Party
-#[cfg(feature = "yaml")]
-use yaml_rust::Yaml;
-
-// Internal
-pub use self::settings::AppSettings;
-use app::help::Help;
-use app::parser::Parser;
-use args::{AnyArg, Arg, ArgGroup, ArgMatcher, ArgMatches, ArgSettings};
-use completions::Shell;
-use errors::Result as ClapResult;
-use map::{self, VecMap};
-
-/// Used to create a representation of a command line program and all possible command line
-/// arguments. Application settings are set using the "builder pattern" with the
-/// [`App::get_matches`] family of methods being the terminal methods that starts the
-/// runtime-parsing process. These methods then return information about the user supplied
-/// arguments (or lack there of).
-///
-/// **NOTE:** There aren't any mandatory "options" that one must set. The "options" may
-/// also appear in any order (so long as one of the [`App::get_matches`] methods is the last method
-/// called).
-///
-/// # Examples
-///
-/// ```no_run
-/// # use clap::{App, Arg};
-/// let m = App::new("My Program")
-/// .author("Me, me@mail.com")
-/// .version("1.0.2")
-/// .about("Explains in brief what the program does")
-/// .arg(
-/// Arg::with_name("in_file").index(1)
-/// )
-/// .after_help("Longer explanation to appear after the options when \
-/// displaying the help information from --help or -h")
-/// .get_matches();
-///
-/// // Your program logic starts here...
-/// ```
-/// [`App::get_matches`]: ./struct.App.html#method.get_matches
-#[allow(missing_debug_implementations)]
-pub struct App<'a, 'b>
-where
- 'a: 'b,
-{
- #[doc(hidden)]
- pub p: Parser<'a, 'b>,
-}
-
-impl<'a, 'b> App<'a, 'b> {
- /// Creates a new instance of an application requiring a name. The name may be, but doesn't
- /// have to be same as the binary. The name will be displayed to the user when they request to
- /// print version or help and usage information.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// let prog = App::new("My Program")
- /// # ;
- /// ```
- pub fn new<S: Into<String>>(n: S) -> Self {
- App {
- p: Parser::with_name(n.into()),
- }
- }
-
- /// Get the name of the app
- pub fn get_name(&self) -> &str {
- &self.p.meta.name
- }
-
- /// Get the name of the binary
- pub fn get_bin_name(&self) -> Option<&str> {
- self.p.meta.bin_name.as_ref().map(|s| s.as_str())
- }
-
- /// Creates a new instance of an application requiring a name, but uses the [`crate_authors!`]
- /// and [`crate_version!`] macros to fill in the [`App::author`] and [`App::version`] fields.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// let prog = App::with_defaults("My Program")
- /// # ;
- /// ```
- /// [`crate_authors!`]: ./macro.crate_authors!.html
- /// [`crate_version!`]: ./macro.crate_version!.html
- /// [`App::author`]: ./struct.App.html#method.author
- /// [`App::version`]: ./struct.App.html#method.author
- #[deprecated(
- since = "2.14.1",
- note = "Can never work; use explicit App::author() and App::version() calls instead"
- )]
- pub fn with_defaults<S: Into<String>>(n: S) -> Self {
- let mut a = App {
- p: Parser::with_name(n.into()),
- };
- a.p.meta.author = Some("Kevin K. <kbknapp@gmail.com>");
- a.p.meta.version = Some("2.19.2");
- a
- }
-
- /// Creates a new instance of [`App`] from a .yml (YAML) file. A full example of supported YAML
- /// objects can be found in [`examples/17_yaml.rs`] and [`examples/17_yaml.yml`]. One great use
- /// for using YAML is when supporting multiple languages and dialects, as each language could
- /// be a distinct YAML file and determined at compiletime via `cargo` "features" in your
- /// `Cargo.toml`
- ///
- /// In order to use this function you must compile `clap` with the `features = ["yaml"]` in
- /// your settings for the `[dependencies.clap]` table of your `Cargo.toml`
- ///
- /// **NOTE:** Due to how the YAML objects are built there is a convenience macro for loading
- /// the YAML file at compile time (relative to the current file, like modules work). That YAML
- /// object can then be passed to this function.
- ///
- /// # Panics
- ///
- /// The YAML file must be properly formatted or this function will [`panic!`]. A good way to
- /// ensure this doesn't happen is to run your program with the `--help` switch. If this passes
- /// without error, you needn't worry because the YAML is properly formatted.
- ///
- /// # Examples
- ///
- /// The following example shows how to load a properly formatted YAML file to build an instance
- /// of an [`App`] struct.
- ///
- /// ```ignore
- /// # #[macro_use]
- /// # extern crate clap;
- /// # use clap::App;
- /// # fn main() {
- /// let yml = load_yaml!("app.yml");
- /// let app = App::from_yaml(yml);
- ///
- /// // continued logic goes here, such as `app.get_matches()` etc.
- /// # }
- /// ```
- /// [`App`]: ./struct.App.html
- /// [`examples/17_yaml.rs`]: https://github.com/clap-rs/clap/blob/v2.33.1/examples/17_yaml.rs
- /// [`examples/17_yaml.yml`]: https://github.com/clap-rs/clap/blob/v2.33.1/examples/17_yaml.yml
- /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
- #[cfg(feature = "yaml")]
- pub fn from_yaml(yaml: &'a Yaml) -> App<'a, 'a> {
- App::from(yaml)
- }
-
- /// Sets a string of author(s) that will be displayed to the user when they
- /// request the help information with `--help` or `-h`.
- ///
- /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to automatically set your
- /// application's author(s) to the same thing as your crate at compile time. See the [`examples/`]
- /// directory for more information
- ///
- /// See the [`examples/`]
- /// directory for more information
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .author("Me, me@mymain.com")
- /// # ;
- /// ```
- /// [`crate_authors!`]: ./macro.crate_authors!.html
- /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples
- pub fn author<S: Into<&'b str>>(mut self, author: S) -> Self {
- self.p.meta.author = Some(author.into());
- self
- }
-
- /// Overrides the system-determined binary name. This should only be used when absolutely
- /// necessary, such as when the binary name for your application is misleading, or perhaps
- /// *not* how the user should invoke your program.
- ///
- /// **Pro-tip:** When building things such as third party `cargo` subcommands, this setting
- /// **should** be used!
- ///
- /// **NOTE:** This command **should not** be used for [`SubCommand`]s.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("My Program")
- /// .bin_name("my_binary")
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- pub fn bin_name<S: Into<String>>(mut self, name: S) -> Self {
- self.p.meta.bin_name = Some(name.into());
- self
- }
-
- /// Sets a string describing what the program does. This will be displayed when displaying help
- /// information with `-h`.
- ///
- /// **NOTE:** If only `about` is provided, and not [`App::long_about`] but the user requests
- /// `--help` clap will still display the contents of `about` appropriately
- ///
- /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be
- /// concise
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .about("Does really amazing things to great people")
- /// # ;
- /// ```
- /// [`App::long_about`]: ./struct.App.html#method.long_about
- pub fn about<S: Into<&'b str>>(mut self, about: S) -> Self {
- self.p.meta.about = Some(about.into());
- self
- }
-
- /// Sets a string describing what the program does. This will be displayed when displaying help
- /// information.
- ///
- /// **NOTE:** If only `long_about` is provided, and not [`App::about`] but the user requests
- /// `-h` clap will still display the contents of `long_about` appropriately
- ///
- /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be
- /// concise
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .long_about(
- /// "Does really amazing things to great people. Now let's talk a little
- /// more in depth about how this subcommand really works. It may take about
- /// a few lines of text, but that's ok!")
- /// # ;
- /// ```
- /// [`App::about`]: ./struct.App.html#method.about
- pub fn long_about<S: Into<&'b str>>(mut self, about: S) -> Self {
- self.p.meta.long_about = Some(about.into());
- self
- }
-
- /// Sets the program's name. This will be displayed when displaying help information.
- ///
- /// **Pro-top:** This function is particularly useful when configuring a program via
- /// [`App::from_yaml`] in conjunction with the [`crate_name!`] macro to derive the program's
- /// name from its `Cargo.toml`.
- ///
- /// # Examples
- /// ```ignore
- /// # #[macro_use]
- /// # extern crate clap;
- /// # use clap::App;
- /// # fn main() {
- /// let yml = load_yaml!("app.yml");
- /// let app = App::from_yaml(yml)
- /// .name(crate_name!());
- ///
- /// // continued logic goes here, such as `app.get_matches()` etc.
- /// # }
- /// ```
- ///
- /// [`App::from_yaml`]: ./struct.App.html#method.from_yaml
- /// [`crate_name!`]: ./macro.crate_name.html
- pub fn name<S: Into<String>>(mut self, name: S) -> Self {
- self.p.meta.name = name.into();
- self
- }
-
- /// Adds additional help information to be displayed in addition to auto-generated help. This
- /// information is displayed **after** the auto-generated help information. This is often used
- /// to describe how to use the arguments, or caveats to be noted.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::App;
- /// App::new("myprog")
- /// .after_help("Does really amazing things to great people...but be careful with -R")
- /// # ;
- /// ```
- pub fn after_help<S: Into<&'b str>>(mut self, help: S) -> Self {
- self.p.meta.more_help = Some(help.into());
- self
- }
-
- /// Adds additional help information to be displayed in addition to auto-generated help. This
- /// information is displayed **before** the auto-generated help information. This is often used
- /// for header information.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::App;
- /// App::new("myprog")
- /// .before_help("Some info I'd like to appear before the help info")
- /// # ;
- /// ```
- pub fn before_help<S: Into<&'b str>>(mut self, help: S) -> Self {
- self.p.meta.pre_help = Some(help.into());
- self
- }
-
- /// Sets a string of the version number to be displayed when displaying version or help
- /// information with `-V`.
- ///
- /// **NOTE:** If only `version` is provided, and not [`App::long_version`] but the user
- /// requests `--version` clap will still display the contents of `version` appropriately
- ///
- /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to automatically set your
- /// application's version to the same thing as your crate at compile time. See the [`examples/`]
- /// directory for more information
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .version("v0.1.24")
- /// # ;
- /// ```
- /// [`crate_version!`]: ./macro.crate_version!.html
- /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples
- /// [`App::long_version`]: ./struct.App.html#method.long_version
- pub fn version<S: Into<&'b str>>(mut self, ver: S) -> Self {
- self.p.meta.version = Some(ver.into());
- self
- }
-
- /// Sets a string of the version number to be displayed when displaying version or help
- /// information with `--version`.
- ///
- /// **NOTE:** If only `long_version` is provided, and not [`App::version`] but the user
- /// requests `-V` clap will still display the contents of `long_version` appropriately
- ///
- /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to automatically set your
- /// application's version to the same thing as your crate at compile time. See the [`examples/`]
- /// directory for more information
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .long_version(
- /// "v0.1.24
- /// commit: abcdef89726d
- /// revision: 123
- /// release: 2
- /// binary: myprog")
- /// # ;
- /// ```
- /// [`crate_version!`]: ./macro.crate_version!.html
- /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples
- /// [`App::version`]: ./struct.App.html#method.version
- pub fn long_version<S: Into<&'b str>>(mut self, ver: S) -> Self {
- self.p.meta.long_version = Some(ver.into());
- self
- }
-
- /// Sets a custom usage string to override the auto-generated usage string.
- ///
- /// This will be displayed to the user when errors are found in argument parsing, or when you
- /// call [`ArgMatches::usage`]
- ///
- /// **CAUTION:** Using this setting disables `clap`s "context-aware" usage strings. After this
- /// setting is set, this will be the only usage string displayed to the user!
- ///
- /// **NOTE:** You do not need to specify the "USAGE: \n\t" portion, as that will
- /// still be applied by `clap`, you only need to specify the portion starting
- /// with the binary name.
- ///
- /// **NOTE:** This will not replace the entire help message, *only* the portion
- /// showing the usage.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .usage("myapp [-clDas] <some_file>")
- /// # ;
- /// ```
- /// [`ArgMatches::usage`]: ./struct.ArgMatches.html#method.usage
- pub fn usage<S: Into<&'b str>>(mut self, usage: S) -> Self {
- self.p.meta.usage_str = Some(usage.into());
- self
- }
-
- /// Sets a custom help message and overrides the auto-generated one. This should only be used
- /// when the auto-generated message does not suffice.
- ///
- /// This will be displayed to the user when they use `--help` or `-h`
- ///
- /// **NOTE:** This replaces the **entire** help message, so nothing will be auto-generated.
- ///
- /// **NOTE:** This **only** replaces the help message for the current command, meaning if you
- /// are using subcommands, those help messages will still be auto-generated unless you
- /// specify a [`Arg::help`] for them as well.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myapp")
- /// .help("myapp v1.0\n\
- /// Does awesome things\n\
- /// (C) me@mail.com\n\n\
- ///
- /// USAGE: myapp <opts> <command>\n\n\
- ///
- /// Options:\n\
- /// -h, --help Display this message\n\
- /// -V, --version Display version info\n\
- /// -s <stuff> Do something with stuff\n\
- /// -v Be verbose\n\n\
- ///
- /// Commmands:\n\
- /// help Prints this message\n\
- /// work Do some work")
- /// # ;
- /// ```
- /// [`Arg::help`]: ./struct.Arg.html#method.help
- pub fn help<S: Into<&'b str>>(mut self, help: S) -> Self {
- self.p.meta.help_str = Some(help.into());
- self
- }
-
- /// Sets the [`short`] for the auto-generated `help` argument.
- ///
- /// By default `clap` automatically assigns `h`, but this can be overridden if you have a
- /// different argument which you'd prefer to use the `-h` short with. This can be done by
- /// defining your own argument with a lowercase `h` as the [`short`].
- ///
- /// `clap` lazily generates these `help` arguments **after** you've defined any arguments of
- /// your own.
- ///
- /// **NOTE:** Any leading `-` characters will be stripped, and only the first
- /// non `-` character will be used as the [`short`] version
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .help_short("H") // Using an uppercase `H` instead of the default lowercase `h`
- /// # ;
- /// ```
- /// [`short`]: ./struct.Arg.html#method.short
- pub fn help_short<S: AsRef<str> + 'b>(mut self, s: S) -> Self {
- self.p.help_short(s.as_ref());
- self
- }
-
- /// Sets the [`short`] for the auto-generated `version` argument.
- ///
- /// By default `clap` automatically assigns `V`, but this can be overridden if you have a
- /// different argument which you'd prefer to use the `-V` short with. This can be done by
- /// defining your own argument with an uppercase `V` as the [`short`].
- ///
- /// `clap` lazily generates these `version` arguments **after** you've defined any arguments of
- /// your own.
- ///
- /// **NOTE:** Any leading `-` characters will be stripped, and only the first
- /// non `-` character will be used as the `short` version
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .version_short("v") // Using a lowercase `v` instead of the default capital `V`
- /// # ;
- /// ```
- /// [`short`]: ./struct.Arg.html#method.short
- pub fn version_short<S: AsRef<str>>(mut self, s: S) -> Self {
- self.p.version_short(s.as_ref());
- self
- }
-
- /// Sets the help text for the auto-generated `help` argument.
- ///
- /// By default `clap` sets this to `"Prints help information"`, but if you're using a
- /// different convention for your help messages and would prefer a different phrasing you can
- /// override it.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .help_message("Print help information") // Perhaps you want imperative help messages
- ///
- /// # ;
- /// ```
- pub fn help_message<S: Into<&'a str>>(mut self, s: S) -> Self {
- self.p.help_message = Some(s.into());
- self
- }
-
- /// Sets the help text for the auto-generated `version` argument.
- ///
- /// By default `clap` sets this to `"Prints version information"`, but if you're using a
- /// different convention for your help messages and would prefer a different phrasing then you
- /// can change it.
- ///
- /// # Examples
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .version_message("Print version information") // Perhaps you want imperative help messages
- /// # ;
- /// ```
- pub fn version_message<S: Into<&'a str>>(mut self, s: S) -> Self {
- self.p.version_message = Some(s.into());
- self
- }
-
- /// Sets the help template to be used, overriding the default format.
- ///
- /// Tags arg given inside curly brackets.
- ///
- /// Valid tags are:
- ///
- /// * `{bin}` - Binary name.
- /// * `{version}` - Version number.
- /// * `{author}` - Author information.
- /// * `{about}` - General description (from [`App::about`])
- /// * `{usage}` - Automatically generated or given usage string.
- /// * `{all-args}` - Help for all arguments (options, flags, positionals arguments,
- /// and subcommands) including titles.
- /// * `{unified}` - Unified help for options and flags. Note, you must *also* set
- /// [`AppSettings::UnifiedHelpMessage`] to fully merge both options and
- /// flags, otherwise the ordering is "best effort"
- /// * `{flags}` - Help for flags.
- /// * `{options}` - Help for options.
- /// * `{positionals}` - Help for positionals arguments.
- /// * `{subcommands}` - Help for subcommands.
- /// * `{after-help}` - Help from [`App::after_help`]
- /// * `{before-help}` - Help from [`App::before_help`]
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .version("1.0")
- /// .template("{bin} ({version}) - {usage}")
- /// # ;
- /// ```
- /// **NOTE:** The template system is, on purpose, very simple. Therefore the tags have to be
- /// written in lowercase and without spacing.
- ///
- /// [`App::about`]: ./struct.App.html#method.about
- /// [`App::after_help`]: ./struct.App.html#method.after_help
- /// [`App::before_help`]: ./struct.App.html#method.before_help
- /// [`AppSettings::UnifiedHelpMessage`]: ./enum.AppSettings.html#variant.UnifiedHelpMessage
- pub fn template<S: Into<&'b str>>(mut self, s: S) -> Self {
- self.p.meta.template = Some(s.into());
- self
- }
-
- /// Enables a single command, or [`SubCommand`], level settings.
- ///
- /// See [`AppSettings`] for a full list of possibilities and examples.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::SubcommandRequired)
- /// .setting(AppSettings::WaitOnError)
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`AppSettings`]: ./enum.AppSettings.html
- pub fn setting(mut self, setting: AppSettings) -> Self {
- self.p.set(setting);
- self
- }
-
- /// Enables multiple command, or [`SubCommand`], level settings
- ///
- /// See [`AppSettings`] for a full list of possibilities and examples.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, AppSettings};
- /// App::new("myprog")
- /// .settings(&[AppSettings::SubcommandRequired,
- /// AppSettings::WaitOnError])
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`AppSettings`]: ./enum.AppSettings.html
- pub fn settings(mut self, settings: &[AppSettings]) -> Self {
- for s in settings {
- self.p.set(*s);
- }
- self
- }
-
- /// Enables a single setting that is propagated down through all child [`SubCommand`]s.
- ///
- /// See [`AppSettings`] for a full list of possibilities and examples.
- ///
- /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, AppSettings};
- /// App::new("myprog")
- /// .global_setting(AppSettings::SubcommandRequired)
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`AppSettings`]: ./enum.AppSettings.html
- pub fn global_setting(mut self, setting: AppSettings) -> Self {
- self.p.set(setting);
- self.p.g_settings.set(setting);
- self
- }
-
- /// Enables multiple settings which are propagated *down* through all child [`SubCommand`]s.
- ///
- /// See [`AppSettings`] for a full list of possibilities and examples.
- ///
- /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, AppSettings};
- /// App::new("myprog")
- /// .global_settings(&[AppSettings::SubcommandRequired,
- /// AppSettings::ColoredHelp])
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`AppSettings`]: ./enum.AppSettings.html
- pub fn global_settings(mut self, settings: &[AppSettings]) -> Self {
- for s in settings {
- self.p.set(*s);
- self.p.g_settings.set(*s)
- }
- self
- }
-
- /// Disables a single command, or [`SubCommand`], level setting.
- ///
- /// See [`AppSettings`] for a full list of possibilities and examples.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, AppSettings};
- /// App::new("myprog")
- /// .unset_setting(AppSettings::ColorAuto)
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`AppSettings`]: ./enum.AppSettings.html
- pub fn unset_setting(mut self, setting: AppSettings) -> Self {
- self.p.unset(setting);
- self
- }
-
- /// Disables multiple command, or [`SubCommand`], level settings.
- ///
- /// See [`AppSettings`] for a full list of possibilities and examples.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, AppSettings};
- /// App::new("myprog")
- /// .unset_settings(&[AppSettings::ColorAuto,
- /// AppSettings::AllowInvalidUtf8])
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`AppSettings`]: ./enum.AppSettings.html
- pub fn unset_settings(mut self, settings: &[AppSettings]) -> Self {
- for s in settings {
- self.p.unset(*s);
- }
- self
- }
-
- /// Sets the terminal width at which to wrap help messages. Defaults to `120`. Using `0` will
- /// ignore terminal widths and use source formatting.
- ///
- /// `clap` automatically tries to determine the terminal width on Unix, Linux, macOS and Windows
- /// if the `wrap_help` cargo "feature" has been used while compiling. If the terminal width
- /// cannot be determined, `clap` defaults to `120`.
- ///
- /// **NOTE:** This setting applies globally and *not* on a per-command basis.
- ///
- /// **NOTE:** This setting must be set **before** any subcommands are added!
- ///
- /// # Platform Specific
- ///
- /// Only Unix, Linux, macOS and Windows support automatic determination of terminal width.
- /// Even on those platforms, this setting is useful if for any reason the terminal width
- /// cannot be determined.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::App;
- /// App::new("myprog")
- /// .set_term_width(80)
- /// # ;
- /// ```
- pub fn set_term_width(mut self, width: usize) -> Self {
- self.p.meta.term_w = Some(width);
- self
- }
-
- /// Sets the max terminal width at which to wrap help messages. Using `0` will ignore terminal
- /// widths and use source formatting.
- ///
- /// `clap` automatically tries to determine the terminal width on Unix, Linux, macOS and Windows
- /// if the `wrap_help` cargo "feature" has been used while compiling, but one might want to
- /// limit the size (e.g. when the terminal is running fullscreen).
- ///
- /// **NOTE:** This setting applies globally and *not* on a per-command basis.
- ///
- /// **NOTE:** This setting must be set **before** any subcommands are added!
- ///
- /// # Platform Specific
- ///
- /// Only Unix, Linux, macOS and Windows support automatic determination of terminal width.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::App;
- /// App::new("myprog")
- /// .max_term_width(100)
- /// # ;
- /// ```
- pub fn max_term_width(mut self, w: usize) -> Self {
- self.p.meta.max_w = Some(w);
- self
- }
-
- /// Adds an [argument] to the list of valid possibilities.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// // Adding a single "flag" argument with a short and help text, using Arg::with_name()
- /// .arg(
- /// Arg::with_name("debug")
- /// .short("d")
- /// .help("turns on debugging mode")
- /// )
- /// // Adding a single "option" argument with a short, a long, and help text using the less
- /// // verbose Arg::from_usage()
- /// .arg(
- /// Arg::from_usage("-c --config=[CONFIG] 'Optionally sets a config file to use'")
- /// )
- /// # ;
- /// ```
- /// [argument]: ./struct.Arg.html
- pub fn arg<A: Into<Arg<'a, 'b>>>(mut self, a: A) -> Self {
- self.p.add_arg(a.into());
- self
- }
-
- /// Adds multiple [arguments] to the list of valid possibilities
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .args(
- /// &[Arg::from_usage("[debug] -d 'turns on debugging info'"),
- /// Arg::with_name("input").index(1).help("the input file to use")]
- /// )
- /// # ;
- /// ```
- /// [arguments]: ./struct.Arg.html
- pub fn args(mut self, args: &[Arg<'a, 'b>]) -> Self {
- for arg in args {
- self.p.add_arg_ref(arg);
- }
- self
- }
-
- /// A convenience method for adding a single [argument] from a usage type string. The string
- /// used follows the same rules and syntax as [`Arg::from_usage`]
- ///
- /// **NOTE:** The downside to using this method is that you can not set any additional
- /// properties of the [`Arg`] other than what [`Arg::from_usage`] supports.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .arg_from_usage("-c --config=<FILE> 'Sets a configuration file to use'")
- /// # ;
- /// ```
- /// [argument]: ./struct.Arg.html
- /// [`Arg`]: ./struct.Arg.html
- /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage
- pub fn arg_from_usage(mut self, usage: &'a str) -> Self {
- self.p.add_arg(Arg::from_usage(usage));
- self
- }
-
- /// Adds multiple [arguments] at once from a usage string, one per line. See
- /// [`Arg::from_usage`] for details on the syntax and rules supported.
- ///
- /// **NOTE:** Like [`App::arg_from_usage`] the downside is you only set properties for the
- /// [`Arg`]s which [`Arg::from_usage`] supports.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// App::new("myprog")
- /// .args_from_usage(
- /// "-c --config=[FILE] 'Sets a configuration file to use'
- /// [debug]... -d 'Sets the debugging level'
- /// <FILE> 'The input file to use'"
- /// )
- /// # ;
- /// ```
- /// [arguments]: ./struct.Arg.html
- /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage
- /// [`App::arg_from_usage`]: ./struct.App.html#method.arg_from_usage
- /// [`Arg`]: ./struct.Arg.html
- pub fn args_from_usage(mut self, usage: &'a str) -> Self {
- for line in usage.lines() {
- let l = line.trim();
- if l.is_empty() {
- continue;
- }
- self.p.add_arg(Arg::from_usage(l));
- }
- self
- }
-
- /// Allows adding a [`SubCommand`] alias, which function as "hidden" subcommands that
- /// automatically dispatch as if this subcommand was used. This is more efficient, and easier
- /// than creating multiple hidden subcommands as one only needs to check for the existence of
- /// this command, and not all variants.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand};
- /// let m = App::new("myprog")
- /// .subcommand(SubCommand::with_name("test")
- /// .alias("do-stuff"))
- /// .get_matches_from(vec!["myprog", "do-stuff"]);
- /// assert_eq!(m.subcommand_name(), Some("test"));
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- pub fn alias<S: Into<&'b str>>(mut self, name: S) -> Self {
- if let Some(ref mut als) = self.p.meta.aliases {
- als.push((name.into(), false));
- } else {
- self.p.meta.aliases = Some(vec![(name.into(), false)]);
- }
- self
- }
-
- /// Allows adding [`SubCommand`] aliases, which function as "hidden" subcommands that
- /// automatically dispatch as if this subcommand was used. This is more efficient, and easier
- /// than creating multiple hidden subcommands as one only needs to check for the existence of
- /// this command, and not all variants.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, SubCommand};
- /// let m = App::new("myprog")
- /// .subcommand(SubCommand::with_name("test")
- /// .aliases(&["do-stuff", "do-tests", "tests"]))
- /// .arg(Arg::with_name("input")
- /// .help("the file to add")
- /// .index(1)
- /// .required(false))
- /// .get_matches_from(vec!["myprog", "do-tests"]);
- /// assert_eq!(m.subcommand_name(), Some("test"));
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- pub fn aliases(mut self, names: &[&'b str]) -> Self {
- if let Some(ref mut als) = self.p.meta.aliases {
- for n in names {
- als.push((n, false));
- }
- } else {
- self.p.meta.aliases = Some(names.iter().map(|n| (*n, false)).collect::<Vec<_>>());
- }
- self
- }
-
- /// Allows adding a [`SubCommand`] alias that functions exactly like those defined with
- /// [`App::alias`], except that they are visible inside the help message.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand};
- /// let m = App::new("myprog")
- /// .subcommand(SubCommand::with_name("test")
- /// .visible_alias("do-stuff"))
- /// .get_matches_from(vec!["myprog", "do-stuff"]);
- /// assert_eq!(m.subcommand_name(), Some("test"));
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`App::alias`]: ./struct.App.html#method.alias
- pub fn visible_alias<S: Into<&'b str>>(mut self, name: S) -> Self {
- if let Some(ref mut als) = self.p.meta.aliases {
- als.push((name.into(), true));
- } else {
- self.p.meta.aliases = Some(vec![(name.into(), true)]);
- }
- self
- }
-
- /// Allows adding multiple [`SubCommand`] aliases that functions exactly like those defined
- /// with [`App::aliases`], except that they are visible inside the help message.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand};
- /// let m = App::new("myprog")
- /// .subcommand(SubCommand::with_name("test")
- /// .visible_aliases(&["do-stuff", "tests"]))
- /// .get_matches_from(vec!["myprog", "do-stuff"]);
- /// assert_eq!(m.subcommand_name(), Some("test"));
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`App::aliases`]: ./struct.App.html#method.aliases
- pub fn visible_aliases(mut self, names: &[&'b str]) -> Self {
- if let Some(ref mut als) = self.p.meta.aliases {
- for n in names {
- als.push((n, true));
- }
- } else {
- self.p.meta.aliases = Some(names.iter().map(|n| (*n, true)).collect::<Vec<_>>());
- }
- self
- }
-
- /// Adds an [`ArgGroup`] to the application. [`ArgGroup`]s are a family of related arguments.
- /// By placing them in a logical group, you can build easier requirement and exclusion rules.
- /// For instance, you can make an entire [`ArgGroup`] required, meaning that one (and *only*
- /// one) argument from that group must be present at runtime.
- ///
- /// You can also do things such as name an [`ArgGroup`] as a conflict to another argument.
- /// Meaning any of the arguments that belong to that group will cause a failure if present with
- /// the conflicting argument.
- ///
- /// Another added benefit of [`ArgGroup`]s is that you can extract a value from a group instead
- /// of determining exactly which argument was used.
- ///
- /// Finally, using [`ArgGroup`]s to ensure exclusion between arguments is another very common
- /// use
- ///
- /// # Examples
- ///
- /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one,
- /// of the arguments from the specified group is present at runtime.
- ///
- /// ```no_run
- /// # use clap::{App, ArgGroup};
- /// App::new("app")
- /// .args_from_usage(
- /// "--set-ver [ver] 'set the version manually'
- /// --major 'auto increase major'
- /// --minor 'auto increase minor'
- /// --patch 'auto increase patch'")
- /// .group(ArgGroup::with_name("vers")
- /// .args(&["set-ver", "major", "minor","patch"])
- /// .required(true))
- /// # ;
- /// ```
- /// [`ArgGroup`]: ./struct.ArgGroup.html
- pub fn group(mut self, group: ArgGroup<'a>) -> Self {
- self.p.add_group(group);
- self
- }
-
- /// Adds multiple [`ArgGroup`]s to the [`App`] at once.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, ArgGroup};
- /// App::new("app")
- /// .args_from_usage(
- /// "--set-ver [ver] 'set the version manually'
- /// --major 'auto increase major'
- /// --minor 'auto increase minor'
- /// --patch 'auto increase patch'
- /// -c [FILE] 'a config file'
- /// -i [IFACE] 'an interface'")
- /// .groups(&[
- /// ArgGroup::with_name("vers")
- /// .args(&["set-ver", "major", "minor","patch"])
- /// .required(true),
- /// ArgGroup::with_name("input")
- /// .args(&["c", "i"])
- /// ])
- /// # ;
- /// ```
- /// [`ArgGroup`]: ./struct.ArgGroup.html
- /// [`App`]: ./struct.App.html
- pub fn groups(mut self, groups: &[ArgGroup<'a>]) -> Self {
- for g in groups {
- self = self.group(g.into());
- }
- self
- }
-
- /// Adds a [`SubCommand`] to the list of valid possibilities. Subcommands are effectively
- /// sub-[`App`]s, because they can contain their own arguments, subcommands, version, usage,
- /// etc. They also function just like [`App`]s, in that they get their own auto generated help,
- /// version, and usage.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand};
- /// App::new("myprog")
- /// .subcommand(SubCommand::with_name("config")
- /// .about("Controls configuration features")
- /// .arg_from_usage("<config> 'Required configuration file to use'"))
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`App`]: ./struct.App.html
- pub fn subcommand(mut self, subcmd: App<'a, 'b>) -> Self {
- self.p.add_subcommand(subcmd);
- self
- }
-
- /// Adds multiple subcommands to the list of valid possibilities by iterating over an
- /// [`IntoIterator`] of [`SubCommand`]s
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, SubCommand};
- /// # App::new("myprog")
- /// .subcommands( vec![
- /// SubCommand::with_name("config").about("Controls configuration functionality")
- /// .arg(Arg::with_name("config_file").index(1)),
- /// SubCommand::with_name("debug").about("Controls debug functionality")])
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`IntoIterator`]: https://doc.rust-lang.org/std/iter/trait.IntoIterator.html
- pub fn subcommands<I>(mut self, subcmds: I) -> Self
- where
- I: IntoIterator<Item = App<'a, 'b>>,
- {
- for subcmd in subcmds {
- self.p.add_subcommand(subcmd);
- }
- self
- }
-
- /// Allows custom ordering of [`SubCommand`]s within the help message. Subcommands with a lower
- /// value will be displayed first in the help message. This is helpful when one would like to
- /// emphasise frequently used subcommands, or prioritize those towards the top of the list.
- /// Duplicate values **are** allowed. Subcommands with duplicate display orders will be
- /// displayed in alphabetical order.
- ///
- /// **NOTE:** The default is 999 for all subcommands.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, SubCommand};
- /// let m = App::new("cust-ord")
- /// .subcommand(SubCommand::with_name("alpha") // typically subcommands are grouped
- /// // alphabetically by name. Subcommands
- /// // without a display_order have a value of
- /// // 999 and are displayed alphabetically with
- /// // all other 999 subcommands
- /// .about("Some help and text"))
- /// .subcommand(SubCommand::with_name("beta")
- /// .display_order(1) // In order to force this subcommand to appear *first*
- /// // all we have to do is give it a value lower than 999.
- /// // Any other subcommands with a value of 1 will be displayed
- /// // alphabetically with this one...then 2 values, then 3, etc.
- /// .about("I should be first!"))
- /// .get_matches_from(vec![
- /// "cust-ord", "--help"
- /// ]);
- /// ```
- ///
- /// The above example displays the following help message
- ///
- /// ```text
- /// cust-ord
- ///
- /// USAGE:
- /// cust-ord [FLAGS] [OPTIONS]
- ///
- /// FLAGS:
- /// -h, --help Prints help information
- /// -V, --version Prints version information
- ///
- /// SUBCOMMANDS:
- /// beta I should be first!
- /// alpha Some help and text
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- pub fn display_order(mut self, ord: usize) -> Self {
- self.p.meta.disp_ord = ord;
- self
- }
-
- /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same
- /// method as if someone ran `-h` to request the help message
- ///
- /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
- /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::App;
- /// let mut app = App::new("myprog");
- /// app.print_help();
- /// ```
- /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html
- /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
- /// [`-h` (short)]: ./struct.Arg.html#method.help
- /// [`--help` (long)]: ./struct.Arg.html#method.long_help
- pub fn print_help(&mut self) -> ClapResult<()> {
- // If there are global arguments, or settings we need to propagate them down to subcommands
- // before parsing incase we run into a subcommand
- self.p.propagate_globals();
- self.p.propagate_settings();
- self.p.derive_display_order();
-
- self.p.create_help_and_version();
- let out = io::stdout();
- let mut buf_w = BufWriter::new(out.lock());
- self.write_help(&mut buf_w)
- }
-
- /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same
- /// method as if someone ran `--help` to request the help message
- ///
- /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
- /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::App;
- /// let mut app = App::new("myprog");
- /// app.print_long_help();
- /// ```
- /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html
- /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
- /// [`-h` (short)]: ./struct.Arg.html#method.help
- /// [`--help` (long)]: ./struct.Arg.html#method.long_help
- pub fn print_long_help(&mut self) -> ClapResult<()> {
- let out = io::stdout();
- let mut buf_w = BufWriter::new(out.lock());
- self.write_long_help(&mut buf_w)
- }
-
- /// Writes the full help message to the user to a [`io::Write`] object in the same method as if
- /// the user ran `-h`
- ///
- /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
- /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
- ///
- /// **NOTE:** There is a known bug where this method does not write propagated global arguments
- /// or autogenerated arguments (i.e. the default help/version args). Prefer
- /// [`App::write_long_help`] instead if possible!
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::App;
- /// use std::io;
- /// let mut app = App::new("myprog");
- /// let mut out = io::stdout();
- /// app.write_help(&mut out).expect("failed to write to stdout");
- /// ```
- /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
- /// [`-h` (short)]: ./struct.Arg.html#method.help
- /// [`--help` (long)]: ./struct.Arg.html#method.long_help
- pub fn write_help<W: Write>(&self, w: &mut W) -> ClapResult<()> {
- // PENDING ISSUE: 808
- // https://github.com/clap-rs/clap/issues/808
- // If there are global arguments, or settings we need to propagate them down to subcommands
- // before parsing incase we run into a subcommand
- // self.p.propagate_globals();
- // self.p.propagate_settings();
- // self.p.derive_display_order();
- // self.p.create_help_and_version();
-
- Help::write_app_help(w, self, false)
- }
-
- /// Writes the full help message to the user to a [`io::Write`] object in the same method as if
- /// the user ran `--help`
- ///
- /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
- /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::App;
- /// use std::io;
- /// let mut app = App::new("myprog");
- /// let mut out = io::stdout();
- /// app.write_long_help(&mut out).expect("failed to write to stdout");
- /// ```
- /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
- /// [`-h` (short)]: ./struct.Arg.html#method.help
- /// [`--help` (long)]: ./struct.Arg.html#method.long_help
- pub fn write_long_help<W: Write>(&mut self, w: &mut W) -> ClapResult<()> {
- // If there are global arguments, or settings we need to propagate them down to subcommands
- // before parsing incase we run into a subcommand
- self.p.propagate_globals();
- self.p.propagate_settings();
- self.p.derive_display_order();
- self.p.create_help_and_version();
-
- Help::write_app_help(w, self, true)
- }
-
- /// Writes the version message to the user to a [`io::Write`] object as if the user ran `-V`.
- ///
- /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages
- /// depending on if the user ran [`-V` (short)] or [`--version` (long)]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::App;
- /// use std::io;
- /// let mut app = App::new("myprog");
- /// let mut out = io::stdout();
- /// app.write_version(&mut out).expect("failed to write to stdout");
- /// ```
- /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
- /// [`-V` (short)]: ./struct.App.html#method.version
- /// [`--version` (long)]: ./struct.App.html#method.long_version
- pub fn write_version<W: Write>(&self, w: &mut W) -> ClapResult<()> {
- self.p.write_version(w, false).map_err(From::from)
- }
-
- /// Writes the version message to the user to a [`io::Write`] object
- ///
- /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages
- /// depending on if the user ran [`-V` (short)] or [`--version` (long)]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::App;
- /// use std::io;
- /// let mut app = App::new("myprog");
- /// let mut out = io::stdout();
- /// app.write_long_version(&mut out).expect("failed to write to stdout");
- /// ```
- /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
- /// [`-V` (short)]: ./struct.App.html#method.version
- /// [`--version` (long)]: ./struct.App.html#method.long_version
- pub fn write_long_version<W: Write>(&self, w: &mut W) -> ClapResult<()> {
- self.p.write_version(w, true).map_err(From::from)
- }
-
- /// Generate a completions file for a specified shell at compile time.
- ///
- /// **NOTE:** to generate the file at compile time you must use a `build.rs` "Build Script"
- ///
- /// # Examples
- ///
- /// The following example generates a bash completion script via a `build.rs` script. In this
- /// simple example, we'll demo a very small application with only a single subcommand and two
- /// args. Real applications could be many multiple levels deep in subcommands, and have tens or
- /// potentially hundreds of arguments.
- ///
- /// First, it helps if we separate out our `App` definition into a separate file. Whether you
- /// do this as a function, or bare App definition is a matter of personal preference.
- ///
- /// ```
- /// // src/cli.rs
- ///
- /// use clap::{App, Arg, SubCommand};
- ///
- /// pub fn build_cli() -> App<'static, 'static> {
- /// App::new("compl")
- /// .about("Tests completions")
- /// .arg(Arg::with_name("file")
- /// .help("some input file"))
- /// .subcommand(SubCommand::with_name("test")
- /// .about("tests things")
- /// .arg(Arg::with_name("case")
- /// .long("case")
- /// .takes_value(true)
- /// .help("the case to test")))
- /// }
- /// ```
- ///
- /// In our regular code, we can simply call this `build_cli()` function, then call
- /// `get_matches()`, or any of the other normal methods directly after. For example:
- ///
- /// ```ignore
- /// // src/main.rs
- ///
- /// mod cli;
- ///
- /// fn main() {
- /// let m = cli::build_cli().get_matches();
- ///
- /// // normal logic continues...
- /// }
- /// ```
- ///
- /// Next, we set up our `Cargo.toml` to use a `build.rs` build script.
- ///
- /// ```toml
- /// # Cargo.toml
- /// build = "build.rs"
- ///
- /// [build-dependencies]
- /// clap = "2.23"
- /// ```
- ///
- /// Next, we place a `build.rs` in our project root.
- ///
- /// ```ignore
- /// extern crate clap;
- ///
- /// use clap::Shell;
- ///
- /// include!("src/cli.rs");
- ///
- /// fn main() {
- /// let outdir = match env::var_os("OUT_DIR") {
- /// None => return,
- /// Some(outdir) => outdir,
- /// };
- /// let mut app = build_cli();
- /// app.gen_completions("myapp", // We need to specify the bin name manually
- /// Shell::Bash, // Then say which shell to build completions for
- /// outdir); // Then say where write the completions to
- /// }
- /// ```
- /// Now, once we compile there will be a `{bin_name}.bash` file in the directory.
- /// Assuming we compiled with debug mode, it would be somewhere similar to
- /// `<project>/target/debug/build/myapp-<hash>/out/myapp.bash`.
- ///
- /// Fish shell completions will use the file format `{bin_name}.fish`
- pub fn gen_completions<T: Into<OsString>, S: Into<String>>(
- &mut self,
- bin_name: S,
- for_shell: Shell,
- out_dir: T,
- ) {
- self.p.meta.bin_name = Some(bin_name.into());
- self.p.gen_completions(for_shell, out_dir.into());
- }
-
- /// Generate a completions file for a specified shell at runtime. Until `cargo install` can
- /// install extra files like a completion script, this may be used e.g. in a command that
- /// outputs the contents of the completion script, to be redirected into a file by the user.
- ///
- /// # Examples
- ///
- /// Assuming a separate `cli.rs` like the [example above](./struct.App.html#method.gen_completions),
- /// we can let users generate a completion script using a command:
- ///
- /// ```ignore
- /// // src/main.rs
- ///
- /// mod cli;
- /// use std::io;
- ///
- /// fn main() {
- /// let matches = cli::build_cli().get_matches();
- ///
- /// if matches.is_present("generate-bash-completions") {
- /// cli::build_cli().gen_completions_to("myapp", Shell::Bash, &mut io::stdout());
- /// }
- ///
- /// // normal logic continues...
- /// }
- ///
- /// ```
- ///
- /// Usage:
- ///
- /// ```shell
- /// $ myapp generate-bash-completions > /usr/share/bash-completion/completions/myapp.bash
- /// ```
- pub fn gen_completions_to<W: Write, S: Into<String>>(
- &mut self,
- bin_name: S,
- for_shell: Shell,
- buf: &mut W,
- ) {
- self.p.meta.bin_name = Some(bin_name.into());
- self.p.gen_completions_to(for_shell, buf);
- }
-
- /// Starts the parsing process, upon a failed parse an error will be displayed to the user and
- /// the process will exit with the appropriate error code. By default this method gets all user
- /// provided arguments from [`env::args_os`] in order to allow for invalid UTF-8 code points,
- /// which are legal on many platforms.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// let matches = App::new("myprog")
- /// // Args and options go here...
- /// .get_matches();
- /// ```
- /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html
- pub fn get_matches(self) -> ArgMatches<'a> {
- self.get_matches_from(&mut env::args_os())
- }
-
- /// Starts the parsing process. This method will return a [`clap::Result`] type instead of exiting
- /// the process on failed parse. By default this method gets matches from [`env::args_os`]
- ///
- /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
- /// used. It will return a [`clap::Error`], where the [`kind`] is a
- /// [`ErrorKind::HelpDisplayed`] or [`ErrorKind::VersionDisplayed`] respectively. You must call
- /// [`Error::exit`] or perform a [`std::process::exit`].
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// let matches = App::new("myprog")
- /// // Args and options go here...
- /// .get_matches_safe()
- /// .unwrap_or_else( |e| e.exit() );
- /// ```
- /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html
- /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed
- /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed
- /// [`Error::exit`]: ./struct.Error.html#method.exit
- /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html
- /// [`clap::Result`]: ./type.Result.html
- /// [`clap::Error`]: ./struct.Error.html
- /// [`kind`]: ./struct.Error.html
- pub fn get_matches_safe(self) -> ClapResult<ArgMatches<'a>> {
- // Start the parsing
- self.get_matches_from_safe(&mut env::args_os())
- }
-
- /// Starts the parsing process. Like [`App::get_matches`] this method does not return a [`clap::Result`]
- /// and will automatically exit with an error message. This method, however, lets you specify
- /// what iterator to use when performing matches, such as a [`Vec`] of your making.
- ///
- /// **NOTE:** The first argument will be parsed as the binary name unless
- /// [`AppSettings::NoBinaryName`] is used
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
- ///
- /// let matches = App::new("myprog")
- /// // Args and options go here...
- /// .get_matches_from(arg_vec);
- /// ```
- /// [`App::get_matches`]: ./struct.App.html#method.get_matches
- /// [`clap::Result`]: ./type.Result.html
- /// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
- /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
- pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches<'a>
- where
- I: IntoIterator<Item = T>,
- T: Into<OsString> + Clone,
- {
- self.get_matches_from_safe_borrow(itr).unwrap_or_else(|e| {
- // Otherwise, write to stderr and exit
- if e.use_stderr() {
- wlnerr!("{}", e.message);
- if self.p.is_set(AppSettings::WaitOnError) {
- wlnerr!("\nPress [ENTER] / [RETURN] to continue...");
- let mut s = String::new();
- let i = io::stdin();
- i.lock().read_line(&mut s).unwrap();
- }
- drop(self);
- drop(e);
- process::exit(1);
- }
-
- drop(self);
- e.exit()
- })
- }
-
- /// Starts the parsing process. A combination of [`App::get_matches_from`], and
- /// [`App::get_matches_safe`]
- ///
- /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
- /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::HelpDisplayed`]
- /// or [`ErrorKind::VersionDisplayed`] respectively. You must call [`Error::exit`] or
- /// perform a [`std::process::exit`] yourself.
- ///
- /// **NOTE:** The first argument will be parsed as the binary name unless
- /// [`AppSettings::NoBinaryName`] is used
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
- ///
- /// let matches = App::new("myprog")
- /// // Args and options go here...
- /// .get_matches_from_safe(arg_vec)
- /// .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
- /// ```
- /// [`App::get_matches_from`]: ./struct.App.html#method.get_matches_from
- /// [`App::get_matches_safe`]: ./struct.App.html#method.get_matches_safe
- /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed
- /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed
- /// [`Error::exit`]: ./struct.Error.html#method.exit
- /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html
- /// [`clap::Error`]: ./struct.Error.html
- /// [`Error::exit`]: ./struct.Error.html#method.exit
- /// [`kind`]: ./struct.Error.html
- /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
- pub fn get_matches_from_safe<I, T>(mut self, itr: I) -> ClapResult<ArgMatches<'a>>
- where
- I: IntoIterator<Item = T>,
- T: Into<OsString> + Clone,
- {
- self.get_matches_from_safe_borrow(itr)
- }
-
- /// Starts the parsing process without consuming the [`App`] struct `self`. This is normally not
- /// the desired functionality, instead prefer [`App::get_matches_from_safe`] which *does*
- /// consume `self`.
- ///
- /// **NOTE:** The first argument will be parsed as the binary name unless
- /// [`AppSettings::NoBinaryName`] is used
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg};
- /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
- ///
- /// let mut app = App::new("myprog");
- /// // Args and options go here...
- /// let matches = app.get_matches_from_safe_borrow(arg_vec)
- /// .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
- /// ```
- /// [`App`]: ./struct.App.html
- /// [`App::get_matches_from_safe`]: ./struct.App.html#method.get_matches_from_safe
- /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
- pub fn get_matches_from_safe_borrow<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches<'a>>
- where
- I: IntoIterator<Item = T>,
- T: Into<OsString> + Clone,
- {
- // If there are global arguments, or settings we need to propagate them down to subcommands
- // before parsing incase we run into a subcommand
- if !self.p.is_set(AppSettings::Propagated) {
- self.p.propagate_globals();
- self.p.propagate_settings();
- self.p.derive_display_order();
- self.p.set(AppSettings::Propagated);
- }
-
- let mut matcher = ArgMatcher::new();
-
- let mut it = itr.into_iter();
- // Get the name of the program (argument 1 of env::args()) and determine the
- // actual file
- // that was used to execute the program. This is because a program called
- // ./target/release/my_prog -a
- // will have two arguments, './target/release/my_prog', '-a' but we don't want
- // to display
- // the full path when displaying help messages and such
- if !self.p.is_set(AppSettings::NoBinaryName) {
- if let Some(name) = it.next() {
- let bn_os = name.into();
- let p = Path::new(&*bn_os);
- if let Some(f) = p.file_name() {
- if let Some(s) = f.to_os_string().to_str() {
- if self.p.meta.bin_name.is_none() {
- self.p.meta.bin_name = Some(s.to_owned());
- }
- }
- }
- }
- }
-
- // do the real parsing
- if let Err(e) = self.p.get_matches_with(&mut matcher, &mut it.peekable()) {
- return Err(e);
- }
-
- let global_arg_vec: Vec<&str> = (&self).p.global_args.iter().map(|ga| ga.b.name).collect();
- matcher.propagate_globals(&global_arg_vec);
-
- Ok(matcher.into())
- }
-}
-
-#[cfg(feature = "yaml")]
-impl<'a> From<&'a Yaml> for App<'a, 'a> {
- fn from(mut yaml: &'a Yaml) -> Self {
- use args::SubCommand;
- // We WANT this to panic on error...so expect() is good.
- let mut is_sc = None;
- let mut a = if let Some(name) = yaml["name"].as_str() {
- App::new(name)
- } else {
- let yaml_hash = yaml.as_hash().unwrap();
- let sc_key = yaml_hash.keys().nth(0).unwrap();
- is_sc = Some(yaml_hash.get(sc_key).unwrap());
- App::new(sc_key.as_str().unwrap())
- };
- yaml = if let Some(sc) = is_sc { sc } else { yaml };
-
- macro_rules! yaml_str {
- ($a:ident, $y:ident, $i:ident) => {
- if let Some(v) = $y[stringify!($i)].as_str() {
- $a = $a.$i(v);
- } else if $y[stringify!($i)] != Yaml::BadValue {
- panic!(
- "Failed to convert YAML value {:?} to a string",
- $y[stringify!($i)]
- );
- }
- };
- }
-
- yaml_str!(a, yaml, version);
- yaml_str!(a, yaml, long_version);
- yaml_str!(a, yaml, author);
- yaml_str!(a, yaml, bin_name);
- yaml_str!(a, yaml, about);
- yaml_str!(a, yaml, long_about);
- yaml_str!(a, yaml, before_help);
- yaml_str!(a, yaml, after_help);
- yaml_str!(a, yaml, template);
- yaml_str!(a, yaml, usage);
- yaml_str!(a, yaml, help);
- yaml_str!(a, yaml, help_short);
- yaml_str!(a, yaml, version_short);
- yaml_str!(a, yaml, help_message);
- yaml_str!(a, yaml, version_message);
- yaml_str!(a, yaml, alias);
- yaml_str!(a, yaml, visible_alias);
-
- if let Some(v) = yaml["display_order"].as_i64() {
- a = a.display_order(v as usize);
- } else if yaml["display_order"] != Yaml::BadValue {
- panic!(
- "Failed to convert YAML value {:?} to a u64",
- yaml["display_order"]
- );
- }
- if let Some(v) = yaml["setting"].as_str() {
- a = a.setting(v.parse().expect("unknown AppSetting found in YAML file"));
- } else if yaml["setting"] != Yaml::BadValue {
- panic!(
- "Failed to convert YAML value {:?} to an AppSetting",
- yaml["setting"]
- );
- }
- if let Some(v) = yaml["settings"].as_vec() {
- for ys in v {
- if let Some(s) = ys.as_str() {
- a = a.setting(s.parse().expect("unknown AppSetting found in YAML file"));
- }
- }
- } else if let Some(v) = yaml["settings"].as_str() {
- a = a.setting(v.parse().expect("unknown AppSetting found in YAML file"));
- } else if yaml["settings"] != Yaml::BadValue {
- panic!(
- "Failed to convert YAML value {:?} to a string",
- yaml["settings"]
- );
- }
- if let Some(v) = yaml["global_setting"].as_str() {
- a = a.setting(v.parse().expect("unknown AppSetting found in YAML file"));
- } else if yaml["global_setting"] != Yaml::BadValue {
- panic!(
- "Failed to convert YAML value {:?} to an AppSetting",
- yaml["setting"]
- );
- }
- if let Some(v) = yaml["global_settings"].as_vec() {
- for ys in v {
- if let Some(s) = ys.as_str() {
- a = a.global_setting(s.parse().expect("unknown AppSetting found in YAML file"));
- }
- }
- } else if let Some(v) = yaml["global_settings"].as_str() {
- a = a.global_setting(v.parse().expect("unknown AppSetting found in YAML file"));
- } else if yaml["global_settings"] != Yaml::BadValue {
- panic!(
- "Failed to convert YAML value {:?} to a string",
- yaml["global_settings"]
- );
- }
-
- macro_rules! vec_or_str {
- ($a:ident, $y:ident, $as_vec:ident, $as_single:ident) => {{
- let maybe_vec = $y[stringify!($as_vec)].as_vec();
- if let Some(vec) = maybe_vec {
- for ys in vec {
- if let Some(s) = ys.as_str() {
- $a = $a.$as_single(s);
- } else {
- panic!("Failed to convert YAML value {:?} to a string", ys);
- }
- }
- } else {
- if let Some(s) = $y[stringify!($as_vec)].as_str() {
- $a = $a.$as_single(s);
- } else if $y[stringify!($as_vec)] != Yaml::BadValue {
- panic!(
- "Failed to convert YAML value {:?} to either a vec or string",
- $y[stringify!($as_vec)]
- );
- }
- }
- $a
- }};
- }
-
- a = vec_or_str!(a, yaml, aliases, alias);
- a = vec_or_str!(a, yaml, visible_aliases, visible_alias);
-
- if let Some(v) = yaml["args"].as_vec() {
- for arg_yaml in v {
- a = a.arg(Arg::from_yaml(arg_yaml.as_hash().unwrap()));
- }
- }
- if let Some(v) = yaml["subcommands"].as_vec() {
- for sc_yaml in v {
- a = a.subcommand(SubCommand::from_yaml(sc_yaml));
- }
- }
- if let Some(v) = yaml["groups"].as_vec() {
- for ag_yaml in v {
- a = a.group(ArgGroup::from(ag_yaml.as_hash().unwrap()));
- }
- }
-
- a
- }
-}
-
-impl<'a, 'b> Clone for App<'a, 'b> {
- fn clone(&self) -> Self {
- App { p: self.p.clone() }
- }
-}
-
-impl<'n, 'e> AnyArg<'n, 'e> for App<'n, 'e> {
- fn name(&self) -> &'n str {
- ""
- }
- fn overrides(&self) -> Option<&[&'e str]> {
- None
- }
- fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> {
- None
- }
- fn blacklist(&self) -> Option<&[&'e str]> {
- None
- }
- fn required_unless(&self) -> Option<&[&'e str]> {
- None
- }
- fn val_names(&self) -> Option<&VecMap<&'e str>> {
- None
- }
- fn is_set(&self, _: ArgSettings) -> bool {
- false
- }
- fn val_terminator(&self) -> Option<&'e str> {
- None
- }
- fn set(&mut self, _: ArgSettings) {
- unreachable!("App struct does not support AnyArg::set, this is a bug!")
- }
- fn has_switch(&self) -> bool {
- false
- }
- fn max_vals(&self) -> Option<u64> {
- None
- }
- fn num_vals(&self) -> Option<u64> {
- None
- }
- fn possible_vals(&self) -> Option<&[&'e str]> {
- None
- }
- fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> {
- None
- }
- fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> {
- None
- }
- fn min_vals(&self) -> Option<u64> {
- None
- }
- fn short(&self) -> Option<char> {
- None
- }
- fn long(&self) -> Option<&'e str> {
- None
- }
- fn val_delim(&self) -> Option<char> {
- None
- }
- fn takes_value(&self) -> bool {
- true
- }
- fn help(&self) -> Option<&'e str> {
- self.p.meta.about
- }
- fn long_help(&self) -> Option<&'e str> {
- self.p.meta.long_about
- }
- fn default_val(&self) -> Option<&'e OsStr> {
- None
- }
- fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> {
- None
- }
- fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> {
- None
- }
- fn longest_filter(&self) -> bool {
- true
- }
- fn aliases(&self) -> Option<Vec<&'e str>> {
- if let Some(ref aliases) = self.p.meta.aliases {
- let vis_aliases: Vec<_> = aliases
- .iter()
- .filter_map(|&(n, v)| if v { Some(n) } else { None })
- .collect();
- if vis_aliases.is_empty() {
- None
- } else {
- Some(vis_aliases)
- }
- } else {
- None
- }
- }
-}
-
-impl<'n, 'e> fmt::Display for App<'n, 'e> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "{}", self.p.meta.name)
- }
-}
diff --git a/src/app/parser.rs b/src/app/parser.rs
deleted file mode 100644
index c05602e..0000000
--- a/src/app/parser.rs
+++ /dev/null
@@ -1,2241 +0,0 @@
-// Std
-#[cfg(all(feature = "debug", any(target_os = "windows", target_arch = "wasm32")))]
-use osstringext::OsStrExt3;
-use std::cell::Cell;
-use std::ffi::{OsStr, OsString};
-use std::fmt::Display;
-use std::fs::File;
-use std::io::{self, BufWriter, Write};
-use std::iter::Peekable;
-#[cfg(all(
- feature = "debug",
- not(any(target_os = "windows", target_arch = "wasm32"))
-))]
-use std::os::unix::ffi::OsStrExt;
-use std::path::PathBuf;
-use std::slice::Iter;
-
-// Internal
-use app::help::Help;
-use app::meta::AppMeta;
-use app::settings::AppFlags;
-use app::settings::AppSettings as AS;
-use app::usage;
-use app::validator::Validator;
-use app::App;
-use args::settings::ArgSettings;
-use args::{
- AnyArg, Arg, ArgGroup, ArgMatcher, Base, FlagBuilder, OptBuilder, PosBuilder, Switched,
-};
-use completions::ComplGen;
-use completions::Shell;
-use errors::Result as ClapResult;
-use errors::{Error, ErrorKind};
-use fmt::ColorWhen;
-use map::{self, VecMap};
-use osstringext::OsStrExt2;
-use suggestions;
-use SubCommand;
-use INTERNAL_ERROR_MSG;
-use INVALID_UTF8;
-
-#[derive(Debug, PartialEq, Copy, Clone)]
-#[doc(hidden)]
-pub enum ParseResult<'a> {
- Flag,
- Opt(&'a str),
- Pos(&'a str),
- MaybeHyphenValue,
- MaybeNegNum,
- NotFound,
- ValuesDone,
-}
-
-#[allow(missing_debug_implementations)]
-#[doc(hidden)]
-#[derive(Clone, Default)]
-pub struct Parser<'a, 'b>
-where
- 'a: 'b,
-{
- pub meta: AppMeta<'b>,
- settings: AppFlags,
- pub g_settings: AppFlags,
- pub flags: Vec<FlagBuilder<'a, 'b>>,
- pub opts: Vec<OptBuilder<'a, 'b>>,
- pub positionals: VecMap<PosBuilder<'a, 'b>>,
- pub subcommands: Vec<App<'a, 'b>>,
- pub groups: Vec<ArgGroup<'a>>,
- pub global_args: Vec<Arg<'a, 'b>>,
- pub required: Vec<&'a str>,
- pub r_ifs: Vec<(&'a str, &'b str, &'a str)>,
- pub overrides: Vec<(&'b str, &'a str)>,
- help_short: Option<char>,
- version_short: Option<char>,
- cache: Option<&'a str>,
- pub help_message: Option<&'a str>,
- pub version_message: Option<&'a str>,
- cur_idx: Cell<usize>,
-}
-
-impl<'a, 'b> Parser<'a, 'b>
-where
- 'a: 'b,
-{
- pub fn with_name(n: String) -> Self {
- Parser {
- meta: AppMeta::with_name(n),
- g_settings: AppFlags::zeroed(),
- cur_idx: Cell::new(0),
- ..Default::default()
- }
- }
-
- pub fn help_short(&mut self, s: &str) {
- let c = s
- .trim_left_matches(|c| c == '-')
- .chars()
- .nth(0)
- .unwrap_or('h');
- self.help_short = Some(c);
- }
-
- pub fn version_short(&mut self, s: &str) {
- let c = s
- .trim_left_matches(|c| c == '-')
- .chars()
- .nth(0)
- .unwrap_or('V');
- self.version_short = Some(c);
- }
-
- pub fn gen_completions_to<W: Write>(&mut self, for_shell: Shell, buf: &mut W) {
- if !self.is_set(AS::Propagated) {
- self.propagate_help_version();
- self.build_bin_names();
- self.propagate_globals();
- self.propagate_settings();
- self.set(AS::Propagated);
- }
-
- ComplGen::new(self).generate(for_shell, buf)
- }
-
- pub fn gen_completions(&mut self, for_shell: Shell, od: OsString) {
- use std::error::Error;
-
- let out_dir = PathBuf::from(od);
- let name = &*self.meta.bin_name.as_ref().unwrap().clone();
- let file_name = match for_shell {
- Shell::Bash => format!("{}.bash", name),
- Shell::Fish => format!("{}.fish", name),
- Shell::Zsh => format!("_{}", name),
- Shell::PowerShell => format!("_{}.ps1", name),
- Shell::Elvish => format!("{}.elv", name),
- };
-
- let mut file = match File::create(out_dir.join(file_name)) {
- Err(why) => panic!("couldn't create completion file: {}", why.description()),
- Ok(file) => file,
- };
- self.gen_completions_to(for_shell, &mut file)
- }
-
- #[inline]
- fn app_debug_asserts(&self) -> bool {
- assert!(self.verify_positionals());
- let should_err = self.groups.iter().all(|g| {
- g.args.iter().all(|arg| {
- (self.flags.iter().any(|f| &f.b.name == arg)
- || self.opts.iter().any(|o| &o.b.name == arg)
- || self.positionals.values().any(|p| &p.b.name == arg)
- || self.groups.iter().any(|g| &g.name == arg))
- })
- });
- let g = self.groups.iter().find(|g| {
- g.args.iter().any(|arg| {
- !(self.flags.iter().any(|f| &f.b.name == arg)
- || self.opts.iter().any(|o| &o.b.name == arg)
- || self.positionals.values().any(|p| &p.b.name == arg)
- || self.groups.iter().any(|g| &g.name == arg))
- })
- });
- assert!(
- should_err,
- "The group '{}' contains the arg '{}' that doesn't actually exist.",
- g.unwrap().name,
- g.unwrap()
- .args
- .iter()
- .find(|arg| !(self.flags.iter().any(|f| &&f.b.name == arg)
- || self.opts.iter().any(|o| &&o.b.name == arg)
- || self.positionals.values().any(|p| &&p.b.name == arg)
- || self.groups.iter().any(|g| &&g.name == arg)))
- .unwrap()
- );
- true
- }
-
- #[inline]
- fn debug_asserts(&self, a: &Arg) -> bool {
- assert!(
- !arg_names!(self).any(|name| name == a.b.name),
- format!("Non-unique argument name: {} is already in use", a.b.name)
- );
- if let Some(l) = a.s.long {
- assert!(
- !self.contains_long(l),
- "Argument long must be unique\n\n\t--{} is already in use",
- l
- );
- }
- if let Some(s) = a.s.short {
- assert!(
- !self.contains_short(s),
- "Argument short must be unique\n\n\t-{} is already in use",
- s
- );
- }
- let i = if a.index.is_none() {
- (self.positionals.len() + 1)
- } else {
- a.index.unwrap() as usize
- };
- assert!(
- !self.positionals.contains_key(i),
- "Argument \"{}\" has the same index as another positional \
- argument\n\n\tPerhaps try .multiple(true) to allow one positional argument \
- to take multiple values",
- a.b.name
- );
- assert!(
- !(a.is_set(ArgSettings::Required) && a.is_set(ArgSettings::Global)),
- "Global arguments cannot be required.\n\n\t'{}' is marked as \
- global and required",
- a.b.name
- );
- if a.b.is_set(ArgSettings::Last) {
- assert!(
- !self
- .positionals
- .values()
- .any(|p| p.b.is_set(ArgSettings::Last)),
- "Only one positional argument may have last(true) set. Found two."
- );
- assert!(a.s.long.is_none(),
- "Flags or Options may not have last(true) set. {} has both a long and last(true) set.",
- a.b.name);
- assert!(a.s.short.is_none(),
- "Flags or Options may not have last(true) set. {} has both a short and last(true) set.",
- a.b.name);
- }
- true
- }
-
- #[inline]
- fn add_conditional_reqs(&mut self, a: &Arg<'a, 'b>) {
- if let Some(ref r_ifs) = a.r_ifs {
- for &(arg, val) in r_ifs {
- self.r_ifs.push((arg, val, a.b.name));
- }
- }
- }
-
- #[inline]
- fn add_arg_groups(&mut self, a: &Arg<'a, 'b>) {
- if let Some(ref grps) = a.b.groups {
- for g in grps {
- let mut found = false;
- if let Some(ref mut ag) = self.groups.iter_mut().find(|grp| &grp.name == g) {
- ag.args.push(a.b.name);
- found = true;
- }
- if !found {
- let mut ag = ArgGroup::with_name(g);
- ag.args.push(a.b.name);
- self.groups.push(ag);
- }
- }
- }
- }
-
- #[inline]
- fn add_reqs(&mut self, a: &Arg<'a, 'b>) {
- if a.is_set(ArgSettings::Required) {
- // If the arg is required, add all it's requirements to master required list
- self.required.push(a.b.name);
- if let Some(ref areqs) = a.b.requires {
- for name in areqs
- .iter()
- .filter(|&&(val, _)| val.is_none())
- .map(|&(_, name)| name)
- {
- self.required.push(name);
- }
- }
- }
- }
-
- #[inline]
- fn implied_settings(&mut self, a: &Arg<'a, 'b>) {
- if a.is_set(ArgSettings::Last) {
- // if an arg has `Last` set, we need to imply DontCollapseArgsInUsage so that args
- // in the usage string don't get confused or left out.
- self.set(AS::DontCollapseArgsInUsage);
- self.set(AS::ContainsLast);
- }
- if let Some(l) = a.s.long {
- if l == "version" {
- self.unset(AS::NeedsLongVersion);
- } else if l == "help" {
- self.unset(AS::NeedsLongHelp);
- }
- }
- }
-
- // actually adds the arguments
- pub fn add_arg(&mut self, a: Arg<'a, 'b>) {
- // if it's global we have to clone anyways
- if a.is_set(ArgSettings::Global) {
- return self.add_arg_ref(&a);
- }
- debug_assert!(self.debug_asserts(&a));
- self.add_conditional_reqs(&a);
- self.add_arg_groups(&a);
- self.add_reqs(&a);
- self.implied_settings(&a);
- if a.index.is_some() || (a.s.short.is_none() && a.s.long.is_none()) {
- let i = if a.index.is_none() {
- (self.positionals.len() + 1)
- } else {
- a.index.unwrap() as usize
- };
- self.positionals
- .insert(i, PosBuilder::from_arg(a, i as u64));
- } else if a.is_set(ArgSettings::TakesValue) {
- let mut ob = OptBuilder::from(a);
- ob.s.unified_ord = self.flags.len() + self.opts.len();
- self.opts.push(ob);
- } else {
- let mut fb = FlagBuilder::from(a);
- fb.s.unified_ord = self.flags.len() + self.opts.len();
- self.flags.push(fb);
- }
- }
- // actually adds the arguments but from a borrow (which means we have to do some cloning)
- pub fn add_arg_ref(&mut self, a: &Arg<'a, 'b>) {
- debug_assert!(self.debug_asserts(a));
- self.add_conditional_reqs(a);
- self.add_arg_groups(a);
- self.add_reqs(a);
- self.implied_settings(a);
- if a.index.is_some() || (a.s.short.is_none() && a.s.long.is_none()) {
- let i = if a.index.is_none() {
- (self.positionals.len() + 1)
- } else {
- a.index.unwrap() as usize
- };
- let pb = PosBuilder::from_arg_ref(a, i as u64);
- self.positionals.insert(i, pb);
- } else if a.is_set(ArgSettings::TakesValue) {
- let mut ob = OptBuilder::from(a);
- ob.s.unified_ord = self.flags.len() + self.opts.len();
- self.opts.push(ob);
- } else {
- let mut fb = FlagBuilder::from(a);
- fb.s.unified_ord = self.flags.len() + self.opts.len();
- self.flags.push(fb);
- }
- if a.is_set(ArgSettings::Global) {
- self.global_args.push(a.into());
- }
- }
-
- pub fn add_group(&mut self, group: ArgGroup<'a>) {
- if group.required {
- self.required.push(group.name);
- if let Some(ref reqs) = group.requires {
- self.required.extend_from_slice(reqs);
- }
- // if let Some(ref bl) = group.conflicts {
- // self.blacklist.extend_from_slice(bl);
- // }
- }
- if self.groups.iter().any(|g| g.name == group.name) {
- let grp = self
- .groups
- .iter_mut()
- .find(|g| g.name == group.name)
- .expect(INTERNAL_ERROR_MSG);
- grp.args.extend_from_slice(&group.args);
- grp.requires = group.requires.clone();
- grp.conflicts = group.conflicts.clone();
- grp.required = group.required;
- } else {
- self.groups.push(group);
- }
- }
-
- pub fn add_subcommand(&mut self, mut subcmd: App<'a, 'b>) {
- debugln!(
- "Parser::add_subcommand: term_w={:?}, name={}",
- self.meta.term_w,
- subcmd.p.meta.name
- );
- subcmd.p.meta.term_w = self.meta.term_w;
- if subcmd.p.meta.name == "help" {
- self.unset(AS::NeedsSubcommandHelp);
- }
-
- self.subcommands.push(subcmd);
- }
-
- pub fn propagate_settings(&mut self) {
- debugln!(
- "Parser::propagate_settings: self={}, g_settings={:#?}",
- self.meta.name,
- self.g_settings
- );
- for sc in &mut self.subcommands {
- debugln!(
- "Parser::propagate_settings: sc={}, settings={:#?}, g_settings={:#?}",
- sc.p.meta.name,
- sc.p.settings,
- sc.p.g_settings
- );
- // We have to create a new scope in order to tell rustc the borrow of `sc` is
- // done and to recursively call this method
- {
- let vsc = self.settings.is_set(AS::VersionlessSubcommands);
- let gv = self.settings.is_set(AS::GlobalVersion);
-
- if vsc {
- sc.p.set(AS::DisableVersion);
- }
- if gv && sc.p.meta.version.is_none() && self.meta.version.is_some() {
- sc.p.set(AS::GlobalVersion);
- sc.p.meta.version = Some(self.meta.version.unwrap());
- }
- sc.p.settings = sc.p.settings | self.g_settings;
- sc.p.g_settings = sc.p.g_settings | self.g_settings;
- sc.p.meta.term_w = self.meta.term_w;
- sc.p.meta.max_w = self.meta.max_w;
- }
- sc.p.propagate_settings();
- }
- }
-
- #[cfg_attr(feature = "lints", allow(needless_borrow))]
- pub fn derive_display_order(&mut self) {
- if self.is_set(AS::DeriveDisplayOrder) {
- let unified = self.is_set(AS::UnifiedHelpMessage);
- for (i, o) in self
- .opts
- .iter_mut()
- .enumerate()
- .filter(|&(_, ref o)| o.s.disp_ord == 999)
- {
- o.s.disp_ord = if unified { o.s.unified_ord } else { i };
- }
- for (i, f) in self
- .flags
- .iter_mut()
- .enumerate()
- .filter(|&(_, ref f)| f.s.disp_ord == 999)
- {
- f.s.disp_ord = if unified { f.s.unified_ord } else { i };
- }
- for (i, sc) in &mut self
- .subcommands
- .iter_mut()
- .enumerate()
- .filter(|&(_, ref sc)| sc.p.meta.disp_ord == 999)
- {
- sc.p.meta.disp_ord = i;
- }
- }
- for sc in &mut self.subcommands {
- sc.p.derive_display_order();
- }
- }
-
- pub fn required(&self) -> Iter<&str> {
- self.required.iter()
- }
-
- #[cfg_attr(feature = "lints", allow(needless_borrow))]
- #[inline]
- pub fn has_args(&self) -> bool {
- !(self.flags.is_empty() && self.opts.is_empty() && self.positionals.is_empty())
- }
-
- #[inline]
- pub fn has_opts(&self) -> bool {
- !self.opts.is_empty()
- }
-
- #[inline]
- pub fn has_flags(&self) -> bool {
- !self.flags.is_empty()
- }
-
- #[inline]
- pub fn has_positionals(&self) -> bool {
- !self.positionals.is_empty()
- }
-
- #[inline]
- pub fn has_subcommands(&self) -> bool {
- !self.subcommands.is_empty()
- }
-
- #[inline]
- pub fn has_visible_opts(&self) -> bool {
- if self.opts.is_empty() {
- return false;
- }
- self.opts.iter().any(|o| !o.is_set(ArgSettings::Hidden))
- }
-
- #[inline]
- pub fn has_visible_flags(&self) -> bool {
- if self.flags.is_empty() {
- return false;
- }
- self.flags.iter().any(|f| !f.is_set(ArgSettings::Hidden))
- }
-
- #[inline]
- pub fn has_visible_positionals(&self) -> bool {
- if self.positionals.is_empty() {
- return false;
- }
- self.positionals
- .values()
- .any(|p| !p.is_set(ArgSettings::Hidden))
- }
-
- #[inline]
- pub fn has_visible_subcommands(&self) -> bool {
- self.has_subcommands()
- && self
- .subcommands
- .iter()
- .filter(|sc| sc.p.meta.name != "help")
- .any(|sc| !sc.p.is_set(AS::Hidden))
- }
-
- #[inline]
- pub fn is_set(&self, s: AS) -> bool {
- self.settings.is_set(s)
- }
-
- #[inline]
- pub fn set(&mut self, s: AS) {
- self.settings.set(s)
- }
-
- #[inline]
- pub fn unset(&mut self, s: AS) {
- self.settings.unset(s)
- }
-
- #[cfg_attr(feature = "lints", allow(block_in_if_condition_stmt))]
- pub fn verify_positionals(&self) -> bool {
- // Because you must wait until all arguments have been supplied, this is the first chance
- // to make assertions on positional argument indexes
- //
- // First we verify that the index highest supplied index, is equal to the number of
- // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3
- // but no 2)
- if let Some((idx, p)) = self.positionals.iter().rev().next() {
- assert!(
- !(idx != self.positionals.len()),
- "Found positional argument \"{}\" whose index is {} but there \
- are only {} positional arguments defined",
- p.b.name,
- idx,
- self.positionals.len()
- );
- }
-
- // Next we verify that only the highest index has a .multiple(true) (if any)
- if self.positionals.values().any(|a| {
- a.b.is_set(ArgSettings::Multiple) && (a.index as usize != self.positionals.len())
- }) {
- let mut it = self.positionals.values().rev();
- let last = it.next().unwrap();
- let second_to_last = it.next().unwrap();
- // Either the final positional is required
- // Or the second to last has a terminator or .last(true) set
- let ok = last.is_set(ArgSettings::Required)
- || (second_to_last.v.terminator.is_some()
- || second_to_last.b.is_set(ArgSettings::Last))
- || last.is_set(ArgSettings::Last);
- assert!(
- ok,
- "When using a positional argument with .multiple(true) that is *not the \
- last* positional argument, the last positional argument (i.e the one \
- with the highest index) *must* have .required(true) or .last(true) set."
- );
- let ok = second_to_last.is_set(ArgSettings::Multiple) || last.is_set(ArgSettings::Last);
- assert!(
- ok,
- "Only the last positional argument, or second to last positional \
- argument may be set to .multiple(true)"
- );
-
- let count = self
- .positionals
- .values()
- .filter(|p| p.b.settings.is_set(ArgSettings::Multiple) && p.v.num_vals.is_none())
- .count();
- let ok = count <= 1
- || (last.is_set(ArgSettings::Last)
- && last.is_set(ArgSettings::Multiple)
- && second_to_last.is_set(ArgSettings::Multiple)
- && count == 2);
- assert!(
- ok,
- "Only one positional argument with .multiple(true) set is allowed per \
- command, unless the second one also has .last(true) set"
- );
- }
-
- if self.is_set(AS::AllowMissingPositional) {
- // Check that if a required positional argument is found, all positions with a lower
- // index are also required.
- let mut found = false;
- let mut foundx2 = false;
- for p in self.positionals.values().rev() {
- if foundx2 && !p.b.settings.is_set(ArgSettings::Required) {
- assert!(
- p.b.is_set(ArgSettings::Required),
- "Found positional argument which is not required with a lower \
- index than a required positional argument by two or more: {:?} \
- index {}",
- p.b.name,
- p.index
- );
- } else if p.b.is_set(ArgSettings::Required) && !p.b.is_set(ArgSettings::Last) {
- // Args that .last(true) don't count since they can be required and have
- // positionals with a lower index that aren't required
- // Imagine: prog <req1> [opt1] -- <req2>
- // Both of these are valid invocations:
- // $ prog r1 -- r2
- // $ prog r1 o1 -- r2
- if found {
- foundx2 = true;
- continue;
- }
- found = true;
- continue;
- } else {
- found = false;
- }
- }
- } else {
- // Check that if a required positional argument is found, all positions with a lower
- // index are also required
- let mut found = false;
- for p in self.positionals.values().rev() {
- if found {
- assert!(
- p.b.is_set(ArgSettings::Required),
- "Found positional argument which is not required with a lower \
- index than a required positional argument: {:?} index {}",
- p.b.name,
- p.index
- );
- } else if p.b.is_set(ArgSettings::Required) && !p.b.is_set(ArgSettings::Last) {
- // Args that .last(true) don't count since they can be required and have
- // positionals with a lower index that aren't required
- // Imagine: prog <req1> [opt1] -- <req2>
- // Both of these are valid invocations:
- // $ prog r1 -- r2
- // $ prog r1 o1 -- r2
- found = true;
- continue;
- }
- }
- }
- if self
- .positionals
- .values()
- .any(|p| p.b.is_set(ArgSettings::Last) && p.b.is_set(ArgSettings::Required))
- && self.has_subcommands()
- && !self.is_set(AS::SubcommandsNegateReqs)
- {
- panic!(
- "Having a required positional argument with .last(true) set *and* child \
- subcommands without setting SubcommandsNegateReqs isn't compatible."
- );
- }
-
- true
- }
-
- pub fn propagate_globals(&mut self) {
- for sc in &mut self.subcommands {
- // We have to create a new scope in order to tell rustc the borrow of `sc` is
- // done and to recursively call this method
- {
- for a in &self.global_args {
- sc.p.add_arg_ref(a);
- }
- }
- sc.p.propagate_globals();
- }
- }
-
- // Checks if the arg matches a subcommand name, or any of it's aliases (if defined)
- fn possible_subcommand(&self, arg_os: &OsStr) -> (bool, Option<&str>) {
- #[cfg(any(target_os = "windows", target_arch = "wasm32"))]
- use osstringext::OsStrExt3;
- #[cfg(not(any(target_os = "windows", target_arch = "wasm32")))]
- use std::os::unix::ffi::OsStrExt;
- debugln!("Parser::possible_subcommand: arg={:?}", arg_os);
- fn starts(h: &str, n: &OsStr) -> bool {
- let n_bytes = n.as_bytes();
- let h_bytes = OsStr::new(h).as_bytes();
-
- h_bytes.starts_with(n_bytes)
- }
-
- if self.is_set(AS::ArgsNegateSubcommands) && self.is_set(AS::ValidArgFound) {
- return (false, None);
- }
- if !self.is_set(AS::InferSubcommands) {
- if let Some(sc) = find_subcmd!(self, arg_os) {
- return (true, Some(&sc.p.meta.name));
- }
- } else {
- let v = self
- .subcommands
- .iter()
- .filter(|s| {
- starts(&s.p.meta.name[..], &*arg_os)
- || (s.p.meta.aliases.is_some()
- && s.p
- .meta
- .aliases
- .as_ref()
- .unwrap()
- .iter()
- .filter(|&&(a, _)| starts(a, &*arg_os))
- .count()
- == 1)
- })
- .map(|sc| &sc.p.meta.name)
- .collect::<Vec<_>>();
-
- for sc in &v {
- if OsStr::new(sc) == arg_os {
- return (true, Some(sc));
- }
- }
-
- if v.len() == 1 {
- return (true, Some(v[0]));
- }
- }
- (false, None)
- }
-
- fn parse_help_subcommand<I, T>(&self, it: &mut I) -> ClapResult<ParseResult<'a>>
- where
- I: Iterator<Item = T>,
- T: Into<OsString>,
- {
- debugln!("Parser::parse_help_subcommand;");
- let cmds: Vec<OsString> = it.map(|c| c.into()).collect();
- let mut help_help = false;
- let mut bin_name = self
- .meta
- .bin_name
- .as_ref()
- .unwrap_or(&self.meta.name)
- .clone();
- let mut sc = {
- let mut sc: &Parser = self;
- for (i, cmd) in cmds.iter().enumerate() {
- if &*cmd.to_string_lossy() == "help" {
- // cmd help help
- help_help = true;
- }
- if let Some(c) = sc
- .subcommands
- .iter()
- .find(|s| &*s.p.meta.name == cmd)
- .map(|sc| &sc.p)
- {
- sc = c;
- if i == cmds.len() - 1 {
- break;
- }
- } else if let Some(c) = sc
- .subcommands
- .iter()
- .find(|s| {
- if let Some(ref als) = s.p.meta.aliases {
- als.iter().any(|&(a, _)| a == &*cmd.to_string_lossy())
- } else {
- false
- }
- })
- .map(|sc| &sc.p)
- {
- sc = c;
- if i == cmds.len() - 1 {
- break;
- }
- } else {
- return Err(Error::unrecognized_subcommand(
- cmd.to_string_lossy().into_owned(),
- self.meta.bin_name.as_ref().unwrap_or(&self.meta.name),
- self.color(),
- ));
- }
- bin_name = format!("{} {}", bin_name, &*sc.meta.name);
- }
- sc.clone()
- };
- if help_help {
- let mut pb = PosBuilder::new("subcommand", 1);
- pb.b.help = Some("The subcommand whose help message to display");
- pb.set(ArgSettings::Multiple);
- sc.positionals.insert(1, pb);
- sc.settings = sc.settings | self.g_settings;
- } else {
- sc.create_help_and_version();
- }
- if sc.meta.bin_name != self.meta.bin_name {
- sc.meta.bin_name = Some(format!("{} {}", bin_name, sc.meta.name));
- }
- Err(sc._help(false))
- }
-
- // allow wrong self convention due to self.valid_neg_num = true and it's a private method
- #[cfg_attr(feature = "lints", allow(wrong_self_convention))]
- fn is_new_arg(&mut self, arg_os: &OsStr, needs_val_of: ParseResult) -> bool {
- debugln!("Parser::is_new_arg:{:?}:{:?}", arg_os, needs_val_of);
- let app_wide_settings = if self.is_set(AS::AllowLeadingHyphen) {
- true
- } else if self.is_set(AS::AllowNegativeNumbers) {
- let a = arg_os.to_string_lossy();
- if a.parse::<i64>().is_ok() || a.parse::<f64>().is_ok() {
- self.set(AS::ValidNegNumFound);
- true
- } else {
- false
- }
- } else {
- false
- };
- let arg_allows_tac = match needs_val_of {
- ParseResult::Opt(name) => {
- let o = self
- .opts
- .iter()
- .find(|o| o.b.name == name)
- .expect(INTERNAL_ERROR_MSG);
- (o.is_set(ArgSettings::AllowLeadingHyphen) || app_wide_settings)
- }
- ParseResult::Pos(name) => {
- let p = self
- .positionals
- .values()
- .find(|p| p.b.name == name)
- .expect(INTERNAL_ERROR_MSG);
- (p.is_set(ArgSettings::AllowLeadingHyphen) || app_wide_settings)
- }
- ParseResult::ValuesDone => return true,
- _ => false,
- };
- debugln!("Parser::is_new_arg: arg_allows_tac={:?}", arg_allows_tac);
-
- // Is this a new argument, or values from a previous option?
- let mut ret = if arg_os.starts_with(b"--") {
- debugln!("Parser::is_new_arg: -- found");
- if arg_os.len() == 2 && !arg_allows_tac {
- return true; // We have to return true so override everything else
- } else if arg_allows_tac {
- return false;
- }
- true
- } else if arg_os.starts_with(b"-") {
- debugln!("Parser::is_new_arg: - found");
- // a singe '-' by itself is a value and typically means "stdin" on unix systems
- !(arg_os.len() == 1)
- } else {
- debugln!("Parser::is_new_arg: probably value");
- false
- };
-
- ret = ret && !arg_allows_tac;
-
- debugln!("Parser::is_new_arg: starts_new_arg={:?}", ret);
- ret
- }
-
- // The actual parsing function
- #[cfg_attr(feature = "lints", allow(while_let_on_iterator, collapsible_if))]
- pub fn get_matches_with<I, T>(
- &mut self,
- matcher: &mut ArgMatcher<'a>,
- it: &mut Peekable<I>,
- ) -> ClapResult<()>
- where
- I: Iterator<Item = T>,
- T: Into<OsString> + Clone,
- {
- debugln!("Parser::get_matches_with;");
- // Verify all positional assertions pass
- debug_assert!(self.app_debug_asserts());
- if self.positionals.values().any(|a| {
- a.b.is_set(ArgSettings::Multiple) && (a.index as usize != self.positionals.len())
- }) && self
- .positionals
- .values()
- .last()
- .map_or(false, |p| !p.is_set(ArgSettings::Last))
- {
- self.settings.set(AS::LowIndexMultiplePositional);
- }
- let has_args = self.has_args();
-
- // Next we create the `--help` and `--version` arguments and add them if
- // necessary
- self.create_help_and_version();
-
- let mut subcmd_name: Option<String> = None;
- let mut needs_val_of: ParseResult<'a> = ParseResult::NotFound;
- let mut pos_counter = 1;
- let mut sc_is_external = false;
- while let Some(arg) = it.next() {
- let arg_os = arg.into();
- debugln!(
- "Parser::get_matches_with: Begin parsing '{:?}' ({:?})",
- arg_os,
- &*arg_os.as_bytes()
- );
-
- self.unset(AS::ValidNegNumFound);
- // Is this a new argument, or values from a previous option?
- let starts_new_arg = self.is_new_arg(&arg_os, needs_val_of);
- if !self.is_set(AS::TrailingValues)
- && arg_os.starts_with(b"--")
- && arg_os.len() == 2
- && starts_new_arg
- {
- debugln!("Parser::get_matches_with: setting TrailingVals=true");
- self.set(AS::TrailingValues);
- continue;
- }
-
- // Has the user already passed '--'? Meaning only positional args follow
- if !self.is_set(AS::TrailingValues) {
- // Does the arg match a subcommand name, or any of it's aliases (if defined)
- {
- match needs_val_of {
- ParseResult::Opt(_) | ParseResult::Pos(_) => (),
- _ => {
- let (is_match, sc_name) = self.possible_subcommand(&arg_os);
- debugln!(
- "Parser::get_matches_with: possible_sc={:?}, sc={:?}",
- is_match,
- sc_name
- );
- if is_match {
- let sc_name = sc_name.expect(INTERNAL_ERROR_MSG);
- if sc_name == "help" && self.is_set(AS::NeedsSubcommandHelp) {
- self.parse_help_subcommand(it)?;
- }
- subcmd_name = Some(sc_name.to_owned());
- break;
- }
- }
- }
- }
-
- if starts_new_arg {
- let check_all = self.is_set(AS::AllArgsOverrideSelf);
- {
- let any_arg = find_any_by_name!(self, self.cache.unwrap_or(""));
- matcher.process_arg_overrides(
- any_arg,
- &mut self.overrides,
- &mut self.required,
- check_all,
- );
- }
-
- if arg_os.starts_with(b"--") {
- needs_val_of = self.parse_long_arg(matcher, &arg_os, it)?;
- debugln!(
- "Parser:get_matches_with: After parse_long_arg {:?}",
- needs_val_of
- );
- match needs_val_of {
- ParseResult::Flag | ParseResult::Opt(..) | ParseResult::ValuesDone => {
- continue
- }
- _ => (),
- }
- } else if arg_os.starts_with(b"-") && arg_os.len() != 1 {
- // Try to parse short args like normal, if AllowLeadingHyphen or
- // AllowNegativeNumbers is set, parse_short_arg will *not* throw
- // an error, and instead return Ok(None)
- needs_val_of = self.parse_short_arg(matcher, &arg_os)?;
- // If it's None, we then check if one of those two AppSettings was set
- debugln!(
- "Parser:get_matches_with: After parse_short_arg {:?}",
- needs_val_of
- );
- match needs_val_of {
- ParseResult::MaybeNegNum => {
- if !(arg_os.to_string_lossy().parse::<i64>().is_ok()
- || arg_os.to_string_lossy().parse::<f64>().is_ok())
- {
- return Err(Error::unknown_argument(
- &*arg_os.to_string_lossy(),
- "",
- &*usage::create_error_usage(self, matcher, None),
- self.color(),
- ));
- }
- }
- ParseResult::Opt(..) | ParseResult::Flag | ParseResult::ValuesDone => {
- continue
- }
- _ => (),
- }
- }
- } else {
- if let ParseResult::Opt(name) = needs_val_of {
- // Check to see if parsing a value from a previous arg
- let arg = self
- .opts
- .iter()
- .find(|o| o.b.name == name)
- .expect(INTERNAL_ERROR_MSG);
- // get the OptBuilder so we can check the settings
- needs_val_of = self.add_val_to_arg(arg, &arg_os, matcher)?;
- // get the next value from the iterator
- continue;
- }
- }
- }
-
- if !(self.is_set(AS::ArgsNegateSubcommands) && self.is_set(AS::ValidArgFound))
- && !self.is_set(AS::InferSubcommands)
- && !self.is_set(AS::AllowExternalSubcommands)
- {
- if let Some(cdate) =
- suggestions::did_you_mean(&*arg_os.to_string_lossy(), sc_names!(self))
- {
- return Err(Error::invalid_subcommand(
- arg_os.to_string_lossy().into_owned(),
- cdate,
- self.meta.bin_name.as_ref().unwrap_or(&self.meta.name),
- &*usage::create_error_usage(self, matcher, None),
- self.color(),
- ));
- }
- }
-
- let low_index_mults = self.is_set(AS::LowIndexMultiplePositional)
- && pos_counter == (self.positionals.len() - 1);
- let missing_pos = self.is_set(AS::AllowMissingPositional)
- && (pos_counter == (self.positionals.len() - 1)
- && !self.is_set(AS::TrailingValues));
- debugln!(
- "Parser::get_matches_with: Positional counter...{}",
- pos_counter
- );
- debugln!(
- "Parser::get_matches_with: Low index multiples...{:?}",
- low_index_mults
- );
- if low_index_mults || missing_pos {
- if let Some(na) = it.peek() {
- let n = (*na).clone().into();
- needs_val_of = if needs_val_of != ParseResult::ValuesDone {
- if let Some(p) = self.positionals.get(pos_counter) {
- ParseResult::Pos(p.b.name)
- } else {
- ParseResult::ValuesDone
- }
- } else {
- ParseResult::ValuesDone
- };
- let sc_match = { self.possible_subcommand(&n).0 };
- if self.is_new_arg(&n, needs_val_of)
- || sc_match
- || suggestions::did_you_mean(&n.to_string_lossy(), sc_names!(self))
- .is_some()
- {
- debugln!("Parser::get_matches_with: Bumping the positional counter...");
- pos_counter += 1;
- }
- } else {
- debugln!("Parser::get_matches_with: Bumping the positional counter...");
- pos_counter += 1;
- }
- } else if (self.is_set(AS::AllowMissingPositional) && self.is_set(AS::TrailingValues))
- || (self.is_set(AS::ContainsLast) && self.is_set(AS::TrailingValues))
- {
- // Came to -- and one postional has .last(true) set, so we go immediately
- // to the last (highest index) positional
- debugln!("Parser::get_matches_with: .last(true) and --, setting last pos");
- pos_counter = self.positionals.len();
- }
- if let Some(p) = self.positionals.get(pos_counter) {
- if p.is_set(ArgSettings::Last) && !self.is_set(AS::TrailingValues) {
- return Err(Error::unknown_argument(
- &*arg_os.to_string_lossy(),
- "",
- &*usage::create_error_usage(self, matcher, None),
- self.color(),
- ));
- }
- if !self.is_set(AS::TrailingValues)
- && (self.is_set(AS::TrailingVarArg) && pos_counter == self.positionals.len())
- {
- self.settings.set(AS::TrailingValues);
- }
- if self.cache.map_or(true, |name| name != p.b.name) {
- let check_all = self.is_set(AS::AllArgsOverrideSelf);
- {
- let any_arg = find_any_by_name!(self, self.cache.unwrap_or(""));
- matcher.process_arg_overrides(
- any_arg,
- &mut self.overrides,
- &mut self.required,
- check_all,
- );
- }
- self.cache = Some(p.b.name);
- }
- let _ = self.add_val_to_arg(p, &arg_os, matcher)?;
-
- matcher.inc_occurrence_of(p.b.name);
- let _ = self
- .groups_for_arg(p.b.name)
- .and_then(|vec| Some(matcher.inc_occurrences_of(&*vec)));
-
- self.settings.set(AS::ValidArgFound);
- // Only increment the positional counter if it doesn't allow multiples
- if !p.b.settings.is_set(ArgSettings::Multiple) {
- pos_counter += 1;
- }
- self.settings.set(AS::ValidArgFound);
- } else if self.is_set(AS::AllowExternalSubcommands) {
- // Get external subcommand name
- let sc_name = match arg_os.to_str() {
- Some(s) => s.to_string(),
- None => {
- if !self.is_set(AS::StrictUtf8) {
- return Err(Error::invalid_utf8(
- &*usage::create_error_usage(self, matcher, None),
- self.color(),
- ));
- }
- arg_os.to_string_lossy().into_owned()
- }
- };
-
- // Collect the external subcommand args
- let mut sc_m = ArgMatcher::new();
- while let Some(v) = it.next() {
- let a = v.into();
- if a.to_str().is_none() && !self.is_set(AS::StrictUtf8) {
- return Err(Error::invalid_utf8(
- &*usage::create_error_usage(self, matcher, None),
- self.color(),
- ));
- }
- sc_m.add_val_to("", &a);
- }
-
- matcher.subcommand(SubCommand {
- name: sc_name,
- matches: sc_m.into(),
- });
- sc_is_external = true;
- } else if !((self.is_set(AS::AllowLeadingHyphen)
- || self.is_set(AS::AllowNegativeNumbers))
- && arg_os.starts_with(b"-"))
- && !self.is_set(AS::InferSubcommands)
- {
- return Err(Error::unknown_argument(
- &*arg_os.to_string_lossy(),
- "",
- &*usage::create_error_usage(self, matcher, None),
- self.color(),
- ));
- } else if !has_args || self.is_set(AS::InferSubcommands) && self.has_subcommands() {
- if let Some(cdate) =
- suggestions::did_you_mean(&*arg_os.to_string_lossy(), sc_names!(self))
- {
- return Err(Error::invalid_subcommand(
- arg_os.to_string_lossy().into_owned(),
- cdate,
- self.meta.bin_name.as_ref().unwrap_or(&self.meta.name),
- &*usage::create_error_usage(self, matcher, None),
- self.color(),
- ));
- } else {
- return Err(Error::unrecognized_subcommand(
- arg_os.to_string_lossy().into_owned(),
- self.meta.bin_name.as_ref().unwrap_or(&self.meta.name),
- self.color(),
- ));
- }
- } else {
- return Err(Error::unknown_argument(
- &*arg_os.to_string_lossy(),
- "",
- &*usage::create_error_usage(self, matcher, None),
- self.color(),
- ));
- }
- }
-
- if !sc_is_external {
- if let Some(ref pos_sc_name) = subcmd_name {
- let sc_name = {
- find_subcmd!(self, pos_sc_name)
- .expect(INTERNAL_ERROR_MSG)
- .p
- .meta
- .name
- .clone()
- };
- self.parse_subcommand(&*sc_name, matcher, it)?;
- } else if self.is_set(AS::SubcommandRequired) {
- let bn = self.meta.bin_name.as_ref().unwrap_or(&self.meta.name);
- return Err(Error::missing_subcommand(
- bn,
- &usage::create_error_usage(self, matcher, None),
- self.color(),
- ));
- } else if self.is_set(AS::SubcommandRequiredElseHelp) {
- debugln!("Parser::get_matches_with: SubcommandRequiredElseHelp=true");
- let mut out = vec![];
- self.write_help_err(&mut out)?;
- return Err(Error {
- message: String::from_utf8_lossy(&*out).into_owned(),
- kind: ErrorKind::MissingArgumentOrSubcommand,
- info: None,
- });
- }
- }
-
- // In case the last arg was new, we need to process it's overrides
- let check_all = self.is_set(AS::AllArgsOverrideSelf);
- {
- let any_arg = find_any_by_name!(self, self.cache.unwrap_or(""));
- matcher.process_arg_overrides(
- any_arg,
- &mut self.overrides,
- &mut self.required,
- check_all,
- );
- }
-
- self.remove_overrides(matcher);
-
- Validator::new(self).validate(needs_val_of, subcmd_name, matcher)
- }
-
- fn remove_overrides(&mut self, matcher: &mut ArgMatcher) {
- debugln!("Parser::remove_overrides:{:?};", self.overrides);
- for &(overr, name) in &self.overrides {
- debugln!("Parser::remove_overrides:iter:({},{});", overr, name);
- if matcher.is_present(overr) {
- debugln!(
- "Parser::remove_overrides:iter:({},{}): removing {};",
- overr,
- name,
- name
- );
- matcher.remove(name);
- for i in (0..self.required.len()).rev() {
- debugln!(
- "Parser::remove_overrides:iter:({},{}): removing required {};",
- overr,
- name,
- name
- );
- if self.required[i] == name {
- self.required.swap_remove(i);
- break;
- }
- }
- }
- }
- }
-
- fn propagate_help_version(&mut self) {
- debugln!("Parser::propagate_help_version;");
- self.create_help_and_version();
- for sc in &mut self.subcommands {
- sc.p.propagate_help_version();
- }
- }
-
- fn build_bin_names(&mut self) {
- debugln!("Parser::build_bin_names;");
- for sc in &mut self.subcommands {
- debug!("Parser::build_bin_names:iter: bin_name set...");
- if sc.p.meta.bin_name.is_none() {
- sdebugln!("No");
- let bin_name = format!(
- "{}{}{}",
- self.meta
- .bin_name
- .as_ref()
- .unwrap_or(&self.meta.name.clone()),
- if self.meta.bin_name.is_some() {
- " "
- } else {
- ""
- },
- &*sc.p.meta.name
- );
- debugln!(
- "Parser::build_bin_names:iter: Setting bin_name of {} to {}",
- self.meta.name,
- bin_name
- );
- sc.p.meta.bin_name = Some(bin_name);
- } else {
- sdebugln!("yes ({:?})", sc.p.meta.bin_name);
- }
- debugln!(
- "Parser::build_bin_names:iter: Calling build_bin_names from...{}",
- sc.p.meta.name
- );
- sc.p.build_bin_names();
- }
- }
-
- fn parse_subcommand<I, T>(
- &mut self,
- sc_name: &str,
- matcher: &mut ArgMatcher<'a>,
- it: &mut Peekable<I>,
- ) -> ClapResult<()>
- where
- I: Iterator<Item = T>,
- T: Into<OsString> + Clone,
- {
- use std::fmt::Write;
- debugln!("Parser::parse_subcommand;");
- let mut mid_string = String::new();
- if !self.is_set(AS::SubcommandsNegateReqs) {
- let mut hs: Vec<&str> = self.required.iter().map(|n| &**n).collect();
- for k in matcher.arg_names() {
- hs.push(k);
- }
- let reqs = usage::get_required_usage_from(self, &hs, Some(matcher), None, false);
-
- for s in &reqs {
- write!(&mut mid_string, " {}", s).expect(INTERNAL_ERROR_MSG);
- }
- }
- mid_string.push_str(" ");
- if let Some(ref mut sc) = self
- .subcommands
- .iter_mut()
- .find(|s| s.p.meta.name == sc_name)
- {
- let mut sc_matcher = ArgMatcher::new();
- // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
- // a space
- sc.p.meta.usage = Some(format!(
- "{}{}{}",
- self.meta.bin_name.as_ref().unwrap_or(&String::new()),
- if self.meta.bin_name.is_some() {
- &*mid_string
- } else {
- ""
- },
- &*sc.p.meta.name
- ));
- sc.p.meta.bin_name = Some(format!(
- "{}{}{}",
- self.meta.bin_name.as_ref().unwrap_or(&String::new()),
- if self.meta.bin_name.is_some() {
- " "
- } else {
- ""
- },
- &*sc.p.meta.name
- ));
- debugln!(
- "Parser::parse_subcommand: About to parse sc={}",
- sc.p.meta.name
- );
- debugln!("Parser::parse_subcommand: sc settings={:#?}", sc.p.settings);
- sc.p.get_matches_with(&mut sc_matcher, it)?;
- matcher.subcommand(SubCommand {
- name: sc.p.meta.name.clone(),
- matches: sc_matcher.into(),
- });
- }
- Ok(())
- }
-
- pub fn groups_for_arg(&self, name: &str) -> Option<Vec<&'a str>> {
- debugln!("Parser::groups_for_arg: name={}", name);
-
- if self.groups.is_empty() {
- debugln!("Parser::groups_for_arg: No groups defined");
- return None;
- }
- let mut res = vec![];
- debugln!("Parser::groups_for_arg: Searching through groups...");
- for grp in &self.groups {
- for a in &grp.args {
- if a == &name {
- sdebugln!("\tFound '{}'", grp.name);
- res.push(&*grp.name);
- }
- }
- }
- if res.is_empty() {
- return None;
- }
-
- Some(res)
- }
-
- pub fn args_in_group(&self, group: &str) -> Vec<String> {
- debug_assert!(self.app_debug_asserts());
-
- let mut g_vec = vec![];
- let mut args = vec![];
-
- for n in &self
- .groups
- .iter()
- .find(|g| g.name == group)
- .expect(INTERNAL_ERROR_MSG)
- .args
- {
- if let Some(f) = self.flags.iter().find(|f| &f.b.name == n) {
- args.push(f.to_string());
- } else if let Some(f) = self.opts.iter().find(|o| &o.b.name == n) {
- args.push(f.to_string());
- } else if let Some(p) = self.positionals.values().find(|p| &p.b.name == n) {
- args.push(p.b.name.to_owned());
- } else {
- g_vec.push(*n);
- }
- }
-
- for av in g_vec.iter().map(|g| self.args_in_group(g)) {
- args.extend(av);
- }
- args.dedup();
- args.iter().map(ToOwned::to_owned).collect()
- }
-
- pub fn arg_names_in_group(&self, group: &str) -> Vec<&'a str> {
- let mut g_vec = vec![];
- let mut args = vec![];
-
- for n in &self
- .groups
- .iter()
- .find(|g| g.name == group)
- .expect(INTERNAL_ERROR_MSG)
- .args
- {
- if self.groups.iter().any(|g| g.name == *n) {
- args.extend(self.arg_names_in_group(n));
- g_vec.push(*n);
- } else if !args.contains(n) {
- args.push(*n);
- }
- }
-
- args.iter().map(|s| *s).collect()
- }
-
- pub fn create_help_and_version(&mut self) {
- debugln!("Parser::create_help_and_version;");
- // name is "hclap_help" because flags are sorted by name
- if !self.is_set(AS::DisableHelpFlags) && !self.contains_long("help") {
- debugln!("Parser::create_help_and_version: Building --help");
- if self.help_short.is_none() && !self.contains_short('h') {
- self.help_short = Some('h');
- }
- let arg = FlagBuilder {
- b: Base {
- name: "hclap_help",
- help: self.help_message.or(Some("Prints help information")),
- ..Default::default()
- },
- s: Switched {
- short: self.help_short,
- long: Some("help"),
- ..Default::default()
- },
- };
- self.flags.push(arg);
- }
- if !self.is_set(AS::DisableVersion) && !self.contains_long("version") {
- debugln!("Parser::create_help_and_version: Building --version");
- if self.version_short.is_none() && !self.contains_short('V') {
- self.version_short = Some('V');
- }
- // name is "vclap_version" because flags are sorted by name
- let arg = FlagBuilder {
- b: Base {
- name: "vclap_version",
- help: self.version_message.or(Some("Prints version information")),
- ..Default::default()
- },
- s: Switched {
- short: self.version_short,
- long: Some("version"),
- ..Default::default()
- },
- };
- self.flags.push(arg);
- }
- if !self.subcommands.is_empty()
- && !self.is_set(AS::DisableHelpSubcommand)
- && self.is_set(AS::NeedsSubcommandHelp)
- {
- debugln!("Parser::create_help_and_version: Building help");
- self.subcommands.push(
- App::new("help")
- .about("Prints this message or the help of the given subcommand(s)"),
- );
- }
- }
-
- // Retrieves the names of all args the user has supplied thus far, except required ones
- // because those will be listed in self.required
- fn check_for_help_and_version_str(&self, arg: &OsStr) -> ClapResult<()> {
- debugln!("Parser::check_for_help_and_version_str;");
- debug!(
- "Parser::check_for_help_and_version_str: Checking if --{} is help or version...",
- arg.to_str().unwrap()
- );
- if arg == "help" && self.is_set(AS::NeedsLongHelp) {
- sdebugln!("Help");
- return Err(self._help(true));
- }
- if arg == "version" && self.is_set(AS::NeedsLongVersion) {
- sdebugln!("Version");
- return Err(self._version(true));
- }
- sdebugln!("Neither");
-
- Ok(())
- }
-
- fn check_for_help_and_version_char(&self, arg: char) -> ClapResult<()> {
- debugln!("Parser::check_for_help_and_version_char;");
- debug!(
- "Parser::check_for_help_and_version_char: Checking if -{} is help or version...",
- arg
- );
- if let Some(h) = self.help_short {
- if arg == h && self.is_set(AS::NeedsLongHelp) {
- sdebugln!("Help");
- return Err(self._help(false));
- }
- }
- if let Some(v) = self.version_short {
- if arg == v && self.is_set(AS::NeedsLongVersion) {
- sdebugln!("Version");
- return Err(self._version(false));
- }
- }
- sdebugln!("Neither");
- Ok(())
- }
-
- fn use_long_help(&self) -> bool {
- // In this case, both must be checked. This allows the retention of
- // original formatting, but also ensures that the actual -h or --help
- // specified by the user is sent through. If HiddenShortHelp is not included,
- // then items specified with hidden_short_help will also be hidden.
- let should_long = |v: &Base| {
- v.long_help.is_some()
- || v.is_set(ArgSettings::HiddenLongHelp)
- || v.is_set(ArgSettings::HiddenShortHelp)
- };
-
- self.meta.long_about.is_some()
- || self.flags.iter().any(|f| should_long(&f.b))
- || self.opts.iter().any(|o| should_long(&o.b))
- || self.positionals.values().any(|p| should_long(&p.b))
- || self
- .subcommands
- .iter()
- .any(|s| s.p.meta.long_about.is_some())
- }
-
- fn _help(&self, mut use_long: bool) -> Error {
- debugln!("Parser::_help: use_long={:?}", use_long);
- use_long = use_long && self.use_long_help();
- let mut buf = vec![];
- match Help::write_parser_help(&mut buf, self, use_long) {
- Err(e) => e,
- _ => Error {
- message: String::from_utf8(buf).unwrap_or_default(),
- kind: ErrorKind::HelpDisplayed,
- info: None,
- },
- }
- }
-
- fn _version(&self, use_long: bool) -> Error {
- debugln!("Parser::_version: ");
- let out = io::stdout();
- let mut buf_w = BufWriter::new(out.lock());
- match self.print_version(&mut buf_w, use_long) {
- Err(e) => e,
- _ => Error {
- message: String::new(),
- kind: ErrorKind::VersionDisplayed,
- info: None,
- },
- }
- }
-
- fn parse_long_arg<I, T>(
- &mut self,
- matcher: &mut ArgMatcher<'a>,
- full_arg: &OsStr,
- it: &mut Peekable<I>,
- ) -> ClapResult<ParseResult<'a>>
- where
- I: Iterator<Item = T>,
- T: Into<OsString> + Clone,
- {
- // maybe here lifetime should be 'a
- debugln!("Parser::parse_long_arg;");
-
- // Update the current index
- self.cur_idx.set(self.cur_idx.get() + 1);
-
- let mut val = None;
- debug!("Parser::parse_long_arg: Does it contain '='...");
- let arg = if full_arg.contains_byte(b'=') {
- let (p0, p1) = full_arg.trim_left_matches(b'-').split_at_byte(b'=');
- sdebugln!("Yes '{:?}'", p1);
- val = Some(p1);
- p0
- } else {
- sdebugln!("No");
- full_arg.trim_left_matches(b'-')
- };
-
- if let Some(opt) = find_opt_by_long!(@os self, arg) {
- debugln!(
- "Parser::parse_long_arg: Found valid opt '{}'",
- opt.to_string()
- );
- self.settings.set(AS::ValidArgFound);
- let ret = self.parse_opt(val, opt, val.is_some(), matcher)?;
- if self.cache.map_or(true, |name| name != opt.b.name) {
- self.cache = Some(opt.b.name);
- }
-
- return Ok(ret);
- } else if let Some(flag) = find_flag_by_long!(@os self, arg) {
- debugln!(
- "Parser::parse_long_arg: Found valid flag '{}'",
- flag.to_string()
- );
- self.settings.set(AS::ValidArgFound);
- // Only flags could be help or version, and we need to check the raw long
- // so this is the first point to check
- self.check_for_help_and_version_str(arg)?;
-
- self.parse_flag(flag, matcher)?;
-
- // Handle conflicts, requirements, etc.
- if self.cache.map_or(true, |name| name != flag.b.name) {
- self.cache = Some(flag.b.name);
- }
-
- return Ok(ParseResult::Flag);
- } else if self.is_set(AS::AllowLeadingHyphen) {
- return Ok(ParseResult::MaybeHyphenValue);
- } else if self.is_set(AS::ValidNegNumFound) {
- return Ok(ParseResult::MaybeNegNum);
- }
-
- debugln!("Parser::parse_long_arg: Didn't match anything");
-
- let args_rest: Vec<_> = it.map(|x| x.clone().into()).collect();
- let args_rest2: Vec<_> = args_rest
- .iter()
- .map(|x| x.to_str().expect(INVALID_UTF8))
- .collect();
- self.did_you_mean_error(arg.to_str().expect(INVALID_UTF8), matcher, &args_rest2[..])
- .map(|_| ParseResult::NotFound)
- }
-
- #[cfg_attr(feature = "lints", allow(len_zero))]
- fn parse_short_arg(
- &mut self,
- matcher: &mut ArgMatcher<'a>,
- full_arg: &OsStr,
- ) -> ClapResult<ParseResult<'a>> {
- debugln!("Parser::parse_short_arg: full_arg={:?}", full_arg);
- let arg_os = full_arg.trim_left_matches(b'-');
- let arg = arg_os.to_string_lossy();
-
- // If AllowLeadingHyphen is set, we want to ensure `-val` gets parsed as `-val` and not
- // `-v` `-a` `-l` assuming `v` `a` and `l` are all, or mostly, valid shorts.
- if self.is_set(AS::AllowLeadingHyphen) {
- if arg.chars().any(|c| !self.contains_short(c)) {
- debugln!(
- "Parser::parse_short_arg: LeadingHyphenAllowed yet -{} isn't valid",
- arg
- );
- return Ok(ParseResult::MaybeHyphenValue);
- }
- } else if self.is_set(AS::ValidNegNumFound) {
- // TODO: Add docs about having AllowNegativeNumbers and `-2` as a valid short
- // May be better to move this to *after* not finding a valid flag/opt?
- debugln!("Parser::parse_short_arg: Valid negative num...");
- return Ok(ParseResult::MaybeNegNum);
- }
-
- let mut ret = ParseResult::NotFound;
- for c in arg.chars() {
- debugln!("Parser::parse_short_arg:iter:{}", c);
-
- // update each index because `-abcd` is four indices to clap
- self.cur_idx.set(self.cur_idx.get() + 1);
-
- // Check for matching short options, and return the name if there is no trailing
- // concatenated value: -oval
- // Option: -o
- // Value: val
- if let Some(opt) = find_opt_by_short!(self, c) {
- debugln!("Parser::parse_short_arg:iter:{}: Found valid opt", c);
- self.settings.set(AS::ValidArgFound);
- // Check for trailing concatenated value
- let p: Vec<_> = arg.splitn(2, c).collect();
- debugln!(
- "Parser::parse_short_arg:iter:{}: p[0]={:?}, p[1]={:?}",
- c,
- p[0].as_bytes(),
- p[1].as_bytes()
- );
- let i = p[0].as_bytes().len() + 1;
- let val = if p[1].as_bytes().len() > 0 {
- debugln!(
- "Parser::parse_short_arg:iter:{}: val={:?} (bytes), val={:?} (ascii)",
- c,
- arg_os.split_at(i).1.as_bytes(),
- arg_os.split_at(i).1
- );
- Some(arg_os.split_at(i).1)
- } else {
- None
- };
-
- // Default to "we're expecting a value later"
- let ret = self.parse_opt(val, opt, false, matcher)?;
-
- if self.cache.map_or(true, |name| name != opt.b.name) {
- self.cache = Some(opt.b.name);
- }
-
- return Ok(ret);
- } else if let Some(flag) = find_flag_by_short!(self, c) {
- debugln!("Parser::parse_short_arg:iter:{}: Found valid flag", c);
- self.settings.set(AS::ValidArgFound);
- // Only flags can be help or version
- self.check_for_help_and_version_char(c)?;
- ret = self.parse_flag(flag, matcher)?;
-
- // Handle conflicts, requirements, overrides, etc.
- // Must be called here due to mutabililty
- if self.cache.map_or(true, |name| name != flag.b.name) {
- self.cache = Some(flag.b.name);
- }
- } else {
- let arg = format!("-{}", c);
- return Err(Error::unknown_argument(
- &*arg,
- "",
- &*usage::create_error_usage(self, matcher, None),
- self.color(),
- ));
- }
- }
- Ok(ret)
- }
-
- fn parse_opt(
- &self,
- val: Option<&OsStr>,
- opt: &OptBuilder<'a, 'b>,
- had_eq: bool,
- matcher: &mut ArgMatcher<'a>,
- ) -> ClapResult<ParseResult<'a>> {
- debugln!("Parser::parse_opt; opt={}, val={:?}", opt.b.name, val);
- debugln!("Parser::parse_opt; opt.settings={:?}", opt.b.settings);
- let mut has_eq = false;
- let no_val = val.is_none();
- let empty_vals = opt.is_set(ArgSettings::EmptyValues);
- let min_vals_zero = opt.v.min_vals.unwrap_or(1) == 0;
- let needs_eq = opt.is_set(ArgSettings::RequireEquals);
-
- debug!("Parser::parse_opt; Checking for val...");
- if let Some(fv) = val {
- has_eq = fv.starts_with(&[b'=']) || had_eq;
- let v = fv.trim_left_matches(b'=');
- if !empty_vals && (v.len() == 0 || (needs_eq && !has_eq)) {
- sdebugln!("Found Empty - Error");
- return Err(Error::empty_value(
- opt,
- &*usage::create_error_usage(self, matcher, None),
- self.color(),
- ));
- }
- sdebugln!("Found - {:?}, len: {}", v, v.len());
- debugln!(
- "Parser::parse_opt: {:?} contains '='...{:?}",
- fv,
- fv.starts_with(&[b'='])
- );
- self.add_val_to_arg(opt, v, matcher)?;
- } else if needs_eq && !(empty_vals || min_vals_zero) {
- sdebugln!("None, but requires equals...Error");
- return Err(Error::empty_value(
- opt,
- &*usage::create_error_usage(self, matcher, None),
- self.color(),
- ));
- } else {
- sdebugln!("None");
- }
-
- matcher.inc_occurrence_of(opt.b.name);
- // Increment or create the group "args"
- self.groups_for_arg(opt.b.name)
- .and_then(|vec| Some(matcher.inc_occurrences_of(&*vec)));
-
- let needs_delim = opt.is_set(ArgSettings::RequireDelimiter);
- let mult = opt.is_set(ArgSettings::Multiple);
- if no_val && min_vals_zero && !has_eq && needs_eq {
- debugln!("Parser::parse_opt: More arg vals not required...");
- return Ok(ParseResult::ValuesDone);
- } else if no_val || (mult && !needs_delim) && !has_eq && matcher.needs_more_vals(opt) {
- debugln!("Parser::parse_opt: More arg vals required...");
- return Ok(ParseResult::Opt(opt.b.name));
- }
- debugln!("Parser::parse_opt: More arg vals not required...");
- Ok(ParseResult::ValuesDone)
- }
-
- fn add_val_to_arg<A>(
- &self,
- arg: &A,
- val: &OsStr,
- matcher: &mut ArgMatcher<'a>,
- ) -> ClapResult<ParseResult<'a>>
- where
- A: AnyArg<'a, 'b> + Display,
- {
- debugln!("Parser::add_val_to_arg; arg={}, val={:?}", arg.name(), val);
- debugln!(
- "Parser::add_val_to_arg; trailing_vals={:?}, DontDelimTrailingVals={:?}",
- self.is_set(AS::TrailingValues),
- self.is_set(AS::DontDelimitTrailingValues)
- );
- if !(self.is_set(AS::TrailingValues) && self.is_set(AS::DontDelimitTrailingValues)) {
- if let Some(delim) = arg.val_delim() {
- if val.is_empty() {
- Ok(self.add_single_val_to_arg(arg, val, matcher)?)
- } else {
- let mut iret = ParseResult::ValuesDone;
- for v in val.split(delim as u32 as u8) {
- iret = self.add_single_val_to_arg(arg, v, matcher)?;
- }
- // If there was a delimiter used, we're not looking for more values
- if val.contains_byte(delim as u32 as u8)
- || arg.is_set(ArgSettings::RequireDelimiter)
- {
- iret = ParseResult::ValuesDone;
- }
- Ok(iret)
- }
- } else {
- self.add_single_val_to_arg(arg, val, matcher)
- }
- } else {
- self.add_single_val_to_arg(arg, val, matcher)
- }
- }
-
- fn add_single_val_to_arg<A>(
- &self,
- arg: &A,
- v: &OsStr,
- matcher: &mut ArgMatcher<'a>,
- ) -> ClapResult<ParseResult<'a>>
- where
- A: AnyArg<'a, 'b> + Display,
- {
- debugln!("Parser::add_single_val_to_arg;");
- debugln!("Parser::add_single_val_to_arg: adding val...{:?}", v);
-
- // update the current index because each value is a distinct index to clap
- self.cur_idx.set(self.cur_idx.get() + 1);
-
- // @TODO @docs @p4: docs for indices should probably note that a terminator isn't a value
- // and therefore not reported in indices
- if let Some(t) = arg.val_terminator() {
- if t == v {
- return Ok(ParseResult::ValuesDone);
- }
- }
-
- matcher.add_val_to(arg.name(), v);
- matcher.add_index_to(arg.name(), self.cur_idx.get());
-
- // Increment or create the group "args"
- if let Some(grps) = self.groups_for_arg(arg.name()) {
- for grp in grps {
- matcher.add_val_to(&*grp, v);
- }
- }
-
- if matcher.needs_more_vals(arg) {
- return Ok(ParseResult::Opt(arg.name()));
- }
- Ok(ParseResult::ValuesDone)
- }
-
- fn parse_flag(
- &self,
- flag: &FlagBuilder<'a, 'b>,
- matcher: &mut ArgMatcher<'a>,
- ) -> ClapResult<ParseResult<'a>> {
- debugln!("Parser::parse_flag;");
-
- matcher.inc_occurrence_of(flag.b.name);
- matcher.add_index_to(flag.b.name, self.cur_idx.get());
-
- // Increment or create the group "args"
- self.groups_for_arg(flag.b.name)
- .and_then(|vec| Some(matcher.inc_occurrences_of(&*vec)));
-
- Ok(ParseResult::Flag)
- }
-
- fn did_you_mean_error(
- &self,
- arg: &str,
- matcher: &mut ArgMatcher<'a>,
- args_rest: &[&str],
- ) -> ClapResult<()> {
- // Didn't match a flag or option
- let suffix =
- suggestions::did_you_mean_flag_suffix(arg, &args_rest, longs!(self), &self.subcommands);
-
- // Add the arg to the matches to build a proper usage string
- if let Some(name) = suffix.1 {
- if let Some(opt) = find_opt_by_long!(self, name) {
- self.groups_for_arg(&*opt.b.name)
- .and_then(|grps| Some(matcher.inc_occurrences_of(&*grps)));
- matcher.insert(&*opt.b.name);
- } else if let Some(flg) = find_flag_by_long!(self, name) {
- self.groups_for_arg(&*flg.b.name)
- .and_then(|grps| Some(matcher.inc_occurrences_of(&*grps)));
- matcher.insert(&*flg.b.name);
- }
- }
-
- let used_arg = format!("--{}", arg);
- Err(Error::unknown_argument(
- &*used_arg,
- &*suffix.0,
- &*usage::create_error_usage(self, matcher, None),
- self.color(),
- ))
- }
-
- // Prints the version to the user and exits if quit=true
- fn print_version<W: Write>(&self, w: &mut W, use_long: bool) -> ClapResult<()> {
- self.write_version(w, use_long)?;
- w.flush().map_err(Error::from)
- }
-
- pub fn write_version<W: Write>(&self, w: &mut W, use_long: bool) -> io::Result<()> {
- let ver = if use_long {
- self.meta
- .long_version
- .unwrap_or_else(|| self.meta.version.unwrap_or(""))
- } else {
- self.meta
- .version
- .unwrap_or_else(|| self.meta.long_version.unwrap_or(""))
- };
- if let Some(bn) = self.meta.bin_name.as_ref() {
- if bn.contains(' ') {
- // Incase we're dealing with subcommands i.e. git mv is translated to git-mv
- write!(w, "{} {}", bn.replace(" ", "-"), ver)
- } else {
- write!(w, "{} {}", &self.meta.name[..], ver)
- }
- } else {
- write!(w, "{} {}", &self.meta.name[..], ver)
- }
- }
-
- pub fn print_help(&self) -> ClapResult<()> {
- let out = io::stdout();
- let mut buf_w = BufWriter::new(out.lock());
- self.write_help(&mut buf_w)
- }
-
- pub fn write_help<W: Write>(&self, w: &mut W) -> ClapResult<()> {
- Help::write_parser_help(w, self, false)
- }
-
- pub fn write_long_help<W: Write>(&self, w: &mut W) -> ClapResult<()> {
- Help::write_parser_help(w, self, true)
- }
-
- pub fn write_help_err<W: Write>(&self, w: &mut W) -> ClapResult<()> {
- Help::write_parser_help_to_stderr(w, self)
- }
-
- pub fn add_defaults(&mut self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> {
- debugln!("Parser::add_defaults;");
- macro_rules! add_val {
- (@default $_self:ident, $a:ident, $m:ident) => {
- if let Some(ref val) = $a.v.default_val {
- debugln!("Parser::add_defaults:iter:{}: has default vals", $a.b.name);
- if $m.get($a.b.name).map(|ma| ma.vals.len()).map(|len| len == 0).unwrap_or(false) {
- debugln!("Parser::add_defaults:iter:{}: has no user defined vals", $a.b.name);
- $_self.add_val_to_arg($a, OsStr::new(val), $m)?;
-
- if $_self.cache.map_or(true, |name| name != $a.name()) {
- $_self.cache = Some($a.name());
- }
- } else if $m.get($a.b.name).is_some() {
- debugln!("Parser::add_defaults:iter:{}: has user defined vals", $a.b.name);
- } else {
- debugln!("Parser::add_defaults:iter:{}: wasn't used", $a.b.name);
-
- $_self.add_val_to_arg($a, OsStr::new(val), $m)?;
-
- if $_self.cache.map_or(true, |name| name != $a.name()) {
- $_self.cache = Some($a.name());
- }
- }
- } else {
- debugln!("Parser::add_defaults:iter:{}: doesn't have default vals", $a.b.name);
- }
- };
- ($_self:ident, $a:ident, $m:ident) => {
- if let Some(ref vm) = $a.v.default_vals_ifs {
- sdebugln!(" has conditional defaults");
- let mut done = false;
- if $m.get($a.b.name).is_none() {
- for &(arg, val, default) in vm.values() {
- let add = if let Some(a) = $m.get(arg) {
- if let Some(v) = val {
- a.vals.iter().any(|value| v == value)
- } else {
- true
- }
- } else {
- false
- };
- if add {
- $_self.add_val_to_arg($a, OsStr::new(default), $m)?;
- if $_self.cache.map_or(true, |name| name != $a.name()) {
- $_self.cache = Some($a.name());
- }
- done = true;
- break;
- }
- }
- }
-
- if done {
- continue; // outer loop (outside macro)
- }
- } else {
- sdebugln!(" doesn't have conditional defaults");
- }
- add_val!(@default $_self, $a, $m)
- };
- }
-
- for o in &self.opts {
- debug!("Parser::add_defaults:iter:{}:", o.b.name);
- add_val!(self, o, matcher);
- }
- for p in self.positionals.values() {
- debug!("Parser::add_defaults:iter:{}:", p.b.name);
- add_val!(self, p, matcher);
- }
- Ok(())
- }
-
- pub fn add_env(&mut self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> {
- macro_rules! add_val {
- ($_self:ident, $a:ident, $m:ident) => {
- if let Some(ref val) = $a.v.env {
- if $m
- .get($a.b.name)
- .map(|ma| ma.vals.len())
- .map(|len| len == 0)
- .unwrap_or(false)
- {
- if let Some(ref val) = val.1 {
- $_self.add_val_to_arg($a, OsStr::new(val), $m)?;
-
- if $_self.cache.map_or(true, |name| name != $a.name()) {
- $_self.cache = Some($a.name());
- }
- }
- } else {
- if let Some(ref val) = val.1 {
- $_self.add_val_to_arg($a, OsStr::new(val), $m)?;
-
- if $_self.cache.map_or(true, |name| name != $a.name()) {
- $_self.cache = Some($a.name());
- }
- }
- }
- }
- };
- }
-
- for o in &self.opts {
- add_val!(self, o, matcher);
- }
- for p in self.positionals.values() {
- add_val!(self, p, matcher);
- }
- Ok(())
- }
-
- pub fn flags(&self) -> Iter<FlagBuilder<'a, 'b>> {
- self.flags.iter()
- }
-
- pub fn opts(&self) -> Iter<OptBuilder<'a, 'b>> {
- self.opts.iter()
- }
-
- pub fn positionals(&self) -> map::Values<PosBuilder<'a, 'b>> {
- self.positionals.values()
- }
-
- pub fn subcommands(&self) -> Iter<App> {
- self.subcommands.iter()
- }
-
- // Should we color the output? None=determined by output location, true=yes, false=no
- #[doc(hidden)]
- pub fn color(&self) -> ColorWhen {
- debugln!("Parser::color;");
- debug!("Parser::color: Color setting...");
- if self.is_set(AS::ColorNever) {
- sdebugln!("Never");
- ColorWhen::Never
- } else if self.is_set(AS::ColorAlways) {
- sdebugln!("Always");
- ColorWhen::Always
- } else {
- sdebugln!("Auto");
- ColorWhen::Auto
- }
- }
-
- pub fn find_any_arg(&self, name: &str) -> Option<&AnyArg<'a, 'b>> {
- if let Some(f) = find_by_name!(self, name, flags, iter) {
- return Some(f);
- }
- if let Some(o) = find_by_name!(self, name, opts, iter) {
- return Some(o);
- }
- if let Some(p) = find_by_name!(self, name, positionals, values) {
- return Some(p);
- }
- None
- }
-
- /// Check is a given string matches the binary name for this parser
- fn is_bin_name(&self, value: &str) -> bool {
- self.meta
- .bin_name
- .as_ref()
- .and_then(|name| Some(value == name))
- .unwrap_or(false)
- }
-
- /// Check is a given string is an alias for this parser
- fn is_alias(&self, value: &str) -> bool {
- self.meta
- .aliases
- .as_ref()
- .and_then(|aliases| {
- for alias in aliases {
- if alias.0 == value {
- return Some(true);
- }
- }
- Some(false)
- })
- .unwrap_or(false)
- }
-
- // Only used for completion scripts due to bin_name messiness
- #[cfg_attr(feature = "lints", allow(block_in_if_condition_stmt))]
- pub fn find_subcommand(&'b self, sc: &str) -> Option<&'b App<'a, 'b>> {
- debugln!("Parser::find_subcommand: sc={}", sc);
- debugln!(
- "Parser::find_subcommand: Currently in Parser...{}",
- self.meta.bin_name.as_ref().unwrap()
- );
- for s in &self.subcommands {
- if s.p.is_bin_name(sc) {
- return Some(s);
- }
- // XXX: why do we split here?
- // isn't `sc` supposed to be single word already?
- let last = sc.split(' ').rev().next().expect(INTERNAL_ERROR_MSG);
- if s.p.is_alias(last) {
- return Some(s);
- }
-
- if let Some(app) = s.p.find_subcommand(sc) {
- return Some(app);
- }
- }
- None
- }
-
- #[inline]
- fn contains_long(&self, l: &str) -> bool {
- longs!(self).any(|al| al == &l)
- }
-
- #[inline]
- fn contains_short(&self, s: char) -> bool {
- shorts!(self).any(|arg_s| arg_s == &s)
- }
-}
diff --git a/src/app/settings.rs b/src/app/settings.rs
deleted file mode 100644
index e387d9e..0000000
--- a/src/app/settings.rs
+++ /dev/null
@@ -1,1192 +0,0 @@
-// Std
-#[allow(deprecated, unused_imports)]
-use std::ascii::AsciiExt;
-use std::ops::BitOr;
-use std::str::FromStr;
-
-bitflags! {
- struct Flags: u64 {
- const SC_NEGATE_REQS = 1;
- const SC_REQUIRED = 1 << 1;
- const A_REQUIRED_ELSE_HELP = 1 << 2;
- const GLOBAL_VERSION = 1 << 3;
- const VERSIONLESS_SC = 1 << 4;
- const UNIFIED_HELP = 1 << 5;
- const WAIT_ON_ERROR = 1 << 6;
- const SC_REQUIRED_ELSE_HELP= 1 << 7;
- const NEEDS_LONG_HELP = 1 << 8;
- const NEEDS_LONG_VERSION = 1 << 9;
- const NEEDS_SC_HELP = 1 << 10;
- const DISABLE_VERSION = 1 << 11;
- const HIDDEN = 1 << 12;
- const TRAILING_VARARG = 1 << 13;
- const NO_BIN_NAME = 1 << 14;
- const ALLOW_UNK_SC = 1 << 15;
- const UTF8_STRICT = 1 << 16;
- const UTF8_NONE = 1 << 17;
- const LEADING_HYPHEN = 1 << 18;
- const NO_POS_VALUES = 1 << 19;
- const NEXT_LINE_HELP = 1 << 20;
- const DERIVE_DISP_ORDER = 1 << 21;
- const COLORED_HELP = 1 << 22;
- const COLOR_ALWAYS = 1 << 23;
- const COLOR_AUTO = 1 << 24;
- const COLOR_NEVER = 1 << 25;
- const DONT_DELIM_TRAIL = 1 << 26;
- const ALLOW_NEG_NUMS = 1 << 27;
- const LOW_INDEX_MUL_POS = 1 << 28;
- const DISABLE_HELP_SC = 1 << 29;
- const DONT_COLLAPSE_ARGS = 1 << 30;
- const ARGS_NEGATE_SCS = 1 << 31;
- const PROPAGATE_VALS_DOWN = 1 << 32;
- const ALLOW_MISSING_POS = 1 << 33;
- const TRAILING_VALUES = 1 << 34;
- const VALID_NEG_NUM_FOUND = 1 << 35;
- const PROPAGATED = 1 << 36;
- const VALID_ARG_FOUND = 1 << 37;
- const INFER_SUBCOMMANDS = 1 << 38;
- const CONTAINS_LAST = 1 << 39;
- const ARGS_OVERRIDE_SELF = 1 << 40;
- const DISABLE_HELP_FLAGS = 1 << 41;
- }
-}
-
-#[doc(hidden)]
-#[derive(Debug, Copy, Clone, PartialEq)]
-pub struct AppFlags(Flags);
-
-impl BitOr for AppFlags {
- type Output = Self;
- fn bitor(self, rhs: Self) -> Self {
- AppFlags(self.0 | rhs.0)
- }
-}
-
-impl Default for AppFlags {
- fn default() -> Self {
- AppFlags(
- Flags::NEEDS_LONG_VERSION
- | Flags::NEEDS_LONG_HELP
- | Flags::NEEDS_SC_HELP
- | Flags::UTF8_NONE
- | Flags::COLOR_AUTO,
- )
- }
-}
-
-#[allow(deprecated)]
-impl AppFlags {
- pub fn new() -> Self {
- AppFlags::default()
- }
- pub fn zeroed() -> Self {
- AppFlags(Flags::empty())
- }
-
- impl_settings! { AppSettings,
- ArgRequiredElseHelp => Flags::A_REQUIRED_ELSE_HELP,
- ArgsNegateSubcommands => Flags::ARGS_NEGATE_SCS,
- AllArgsOverrideSelf => Flags::ARGS_OVERRIDE_SELF,
- AllowExternalSubcommands => Flags::ALLOW_UNK_SC,
- AllowInvalidUtf8 => Flags::UTF8_NONE,
- AllowLeadingHyphen => Flags::LEADING_HYPHEN,
- AllowNegativeNumbers => Flags::ALLOW_NEG_NUMS,
- AllowMissingPositional => Flags::ALLOW_MISSING_POS,
- ColoredHelp => Flags::COLORED_HELP,
- ColorAlways => Flags::COLOR_ALWAYS,
- ColorAuto => Flags::COLOR_AUTO,
- ColorNever => Flags::COLOR_NEVER,
- DontDelimitTrailingValues => Flags::DONT_DELIM_TRAIL,
- DontCollapseArgsInUsage => Flags::DONT_COLLAPSE_ARGS,
- DeriveDisplayOrder => Flags::DERIVE_DISP_ORDER,
- DisableHelpFlags => Flags::DISABLE_HELP_FLAGS,
- DisableHelpSubcommand => Flags::DISABLE_HELP_SC,
- DisableVersion => Flags::DISABLE_VERSION,
- GlobalVersion => Flags::GLOBAL_VERSION,
- HidePossibleValuesInHelp => Flags::NO_POS_VALUES,
- Hidden => Flags::HIDDEN,
- LowIndexMultiplePositional => Flags::LOW_INDEX_MUL_POS,
- NeedsLongHelp => Flags::NEEDS_LONG_HELP,
- NeedsLongVersion => Flags::NEEDS_LONG_VERSION,
- NeedsSubcommandHelp => Flags::NEEDS_SC_HELP,
- NoBinaryName => Flags::NO_BIN_NAME,
- PropagateGlobalValuesDown=> Flags::PROPAGATE_VALS_DOWN,
- StrictUtf8 => Flags::UTF8_STRICT,
- SubcommandsNegateReqs => Flags::SC_NEGATE_REQS,
- SubcommandRequired => Flags::SC_REQUIRED,
- SubcommandRequiredElseHelp => Flags::SC_REQUIRED_ELSE_HELP,
- TrailingVarArg => Flags::TRAILING_VARARG,
- UnifiedHelpMessage => Flags::UNIFIED_HELP,
- NextLineHelp => Flags::NEXT_LINE_HELP,
- VersionlessSubcommands => Flags::VERSIONLESS_SC,
- WaitOnError => Flags::WAIT_ON_ERROR,
- TrailingValues => Flags::TRAILING_VALUES,
- ValidNegNumFound => Flags::VALID_NEG_NUM_FOUND,
- Propagated => Flags::PROPAGATED,
- ValidArgFound => Flags::VALID_ARG_FOUND,
- InferSubcommands => Flags::INFER_SUBCOMMANDS,
- ContainsLast => Flags::CONTAINS_LAST
- }
-}
-
-/// Application level settings, which affect how [`App`] operates
-///
-/// **NOTE:** When these settings are used, they apply only to current command, and are *not*
-/// propagated down or up through child or parent subcommands
-///
-/// [`App`]: ./struct.App.html
-#[derive(Debug, PartialEq, Copy, Clone)]
-pub enum AppSettings {
- /// Specifies that any invalid UTF-8 code points should *not* be treated as an error.
- /// This is the default behavior of `clap`.
- ///
- /// **NOTE:** Using argument values with invalid UTF-8 code points requires using
- /// [`ArgMatches::os_value_of`], [`ArgMatches::os_values_of`], [`ArgMatches::lossy_value_of`],
- /// or [`ArgMatches::lossy_values_of`] for those particular arguments which may contain invalid
- /// UTF-8 values
- ///
- /// **NOTE:** This rule only applies to argument values, as flags, options, and
- /// [`SubCommand`]s themselves only allow valid UTF-8 code points.
- ///
- /// # Platform Specific
- ///
- /// Non Windows systems only
- ///
- /// # Examples
- ///
- #[cfg_attr(not(unix), doc = " ```ignore")]
- #[cfg_attr(unix, doc = " ```")]
- /// # use clap::{App, AppSettings};
- /// use std::ffi::OsString;
- /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
- ///
- /// let r = App::new("myprog")
- /// //.setting(AppSettings::AllowInvalidUtf8)
- /// .arg_from_usage("<arg> 'some positional arg'")
- /// .get_matches_from_safe(
- /// vec![
- /// OsString::from("myprog"),
- /// OsString::from_vec(vec![0xe9])]);
- ///
- /// assert!(r.is_ok());
- /// let m = r.unwrap();
- /// assert_eq!(m.value_of_os("arg").unwrap().as_bytes(), &[0xe9]);
- /// ```
- /// [`ArgMatches::os_value_of`]: ./struct.ArgMatches.html#method.os_value_of
- /// [`ArgMatches::os_values_of`]: ./struct.ArgMatches.html#method.os_values_of
- /// [`ArgMatches::lossy_value_of`]: ./struct.ArgMatches.html#method.lossy_value_of
- /// [`ArgMatches::lossy_values_of`]: ./struct.ArgMatches.html#method.lossy_values_of
- /// [`SubCommand`]: ./struct.SubCommand.html
- AllowInvalidUtf8,
-
- /// Essentially sets [`Arg::overrides_with("itself")`] for all arguments.
- ///
- /// **WARNING:** Positional arguments cannot override themselves (or we would never be able
- /// to advance to the next positional). This setting ignores positional arguments.
- /// [`Arg::overrides_with("itself")`]: ./struct.Arg.html#method.overrides_with
- AllArgsOverrideSelf,
-
- /// Specifies that leading hyphens are allowed in argument *values*, such as negative numbers
- /// like `-10`. (which would otherwise be parsed as another flag or option)
- ///
- /// **NOTE:** Use this setting with caution as it silences certain circumstances which would
- /// otherwise be an error (such as accidentally forgetting to specify a value for leading
- /// option). It is preferred to set this on a per argument basis, via [`Arg::allow_hyphen_values`]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{Arg, App, AppSettings};
- /// // Imagine you needed to represent negative numbers as well, such as -10
- /// let m = App::new("nums")
- /// .setting(AppSettings::AllowLeadingHyphen)
- /// .arg(Arg::with_name("neg").index(1))
- /// .get_matches_from(vec![
- /// "nums", "-20"
- /// ]);
- ///
- /// assert_eq!(m.value_of("neg"), Some("-20"));
- /// # ;
- /// ```
- /// [`Arg::allow_hyphen_values`]: ./struct.Arg.html#method.allow_hyphen_values
- AllowLeadingHyphen,
-
- /// Allows negative numbers to pass as values. This is similar to
- /// `AllowLeadingHyphen` except that it only allows numbers, all
- /// other undefined leading hyphens will fail to parse.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings};
- /// let res = App::new("myprog")
- /// .version("v1.1")
- /// .setting(AppSettings::AllowNegativeNumbers)
- /// .arg(Arg::with_name("num"))
- /// .get_matches_from_safe(vec![
- /// "myprog", "-20"
- /// ]);
- /// assert!(res.is_ok());
- /// let m = res.unwrap();
- /// assert_eq!(m.value_of("num").unwrap(), "-20");
- /// ```
- /// [`AllowLeadingHyphen`]: ./enum.AppSettings.html#variant.AllowLeadingHyphen
- AllowNegativeNumbers,
-
- /// Allows one to implement two styles of CLIs where positionals can be used out of order.
- ///
- /// The first example is a CLI where the second to last positional argument is optional, but
- /// the final positional argument is required. Such as `$ prog [optional] <required>` where one
- /// of the two following usages is allowed:
- ///
- /// * `$ prog [optional] <required>`
- /// * `$ prog <required>`
- ///
- /// This would otherwise not be allowed. This is useful when `[optional]` has a default value.
- ///
- /// **Note:** when using this style of "missing positionals" the final positional *must* be
- /// [required] if `--` will not be used to skip to the final positional argument.
- ///
- /// **Note:** This style also only allows a single positional argument to be "skipped" without
- /// the use of `--`. To skip more than one, see the second example.
- ///
- /// The second example is when one wants to skip multiple optional positional arguments, and use
- /// of the `--` operator is OK (but not required if all arguments will be specified anyways).
- ///
- /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where
- /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments).
- ///
- /// With this setting the following invocations are possible:
- ///
- /// * `$ prog foo bar baz1 baz2 baz3`
- /// * `$ prog foo -- baz1 baz2 baz3`
- /// * `$ prog -- baz1 baz2 baz3`
- ///
- /// # Examples
- ///
- /// Style number one from above:
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings};
- /// // Assume there is an external subcommand named "subcmd"
- /// let m = App::new("myprog")
- /// .setting(AppSettings::AllowMissingPositional)
- /// .arg(Arg::with_name("arg1"))
- /// .arg(Arg::with_name("arg2")
- /// .required(true))
- /// .get_matches_from(vec![
- /// "prog", "other"
- /// ]);
- ///
- /// assert_eq!(m.value_of("arg1"), None);
- /// assert_eq!(m.value_of("arg2"), Some("other"));
- /// ```
- ///
- /// Now the same example, but using a default value for the first optional positional argument
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings};
- /// // Assume there is an external subcommand named "subcmd"
- /// let m = App::new("myprog")
- /// .setting(AppSettings::AllowMissingPositional)
- /// .arg(Arg::with_name("arg1")
- /// .default_value("something"))
- /// .arg(Arg::with_name("arg2")
- /// .required(true))
- /// .get_matches_from(vec![
- /// "prog", "other"
- /// ]);
- ///
- /// assert_eq!(m.value_of("arg1"), Some("something"));
- /// assert_eq!(m.value_of("arg2"), Some("other"));
- /// ```
- /// Style number two from above:
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings};
- /// // Assume there is an external subcommand named "subcmd"
- /// let m = App::new("myprog")
- /// .setting(AppSettings::AllowMissingPositional)
- /// .arg(Arg::with_name("foo"))
- /// .arg(Arg::with_name("bar"))
- /// .arg(Arg::with_name("baz").multiple(true))
- /// .get_matches_from(vec![
- /// "prog", "foo", "bar", "baz1", "baz2", "baz3"
- /// ]);
- ///
- /// assert_eq!(m.value_of("foo"), Some("foo"));
- /// assert_eq!(m.value_of("bar"), Some("bar"));
- /// assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
- /// ```
- ///
- /// Now notice if we don't specify `foo` or `baz` but use the `--` operator.
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings};
- /// // Assume there is an external subcommand named "subcmd"
- /// let m = App::new("myprog")
- /// .setting(AppSettings::AllowMissingPositional)
- /// .arg(Arg::with_name("foo"))
- /// .arg(Arg::with_name("bar"))
- /// .arg(Arg::with_name("baz").multiple(true))
- /// .get_matches_from(vec![
- /// "prog", "--", "baz1", "baz2", "baz3"
- /// ]);
- ///
- /// assert_eq!(m.value_of("foo"), None);
- /// assert_eq!(m.value_of("bar"), None);
- /// assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
- /// ```
- /// [required]: ./struct.Arg.html#method.required
- AllowMissingPositional,
-
- /// Specifies that an unexpected positional argument,
- /// which would otherwise cause a [`ErrorKind::UnknownArgument`] error,
- /// should instead be treated as a [`SubCommand`] within the [`ArgMatches`] struct.
- ///
- /// **NOTE:** Use this setting with caution,
- /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand)
- /// will **not** cause an error and instead be treated as a potential subcommand.
- /// One should check for such cases manually and inform the user appropriately.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, AppSettings};
- /// // Assume there is an external subcommand named "subcmd"
- /// let m = App::new("myprog")
- /// .setting(AppSettings::AllowExternalSubcommands)
- /// .get_matches_from(vec![
- /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
- /// ]);
- ///
- /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
- /// // string argument name
- /// match m.subcommand() {
- /// (external, Some(ext_m)) => {
- /// let ext_args: Vec<&str> = ext_m.values_of("").unwrap().collect();
- /// assert_eq!(external, "subcmd");
- /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
- /// },
- /// _ => {},
- /// }
- /// ```
- /// [`ErrorKind::UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`ArgMatches`]: ./struct.ArgMatches.html
- AllowExternalSubcommands,
-
- /// Specifies that use of a valid [argument] negates [subcommands] being used after. By default
- /// `clap` allows arguments between subcommands such as
- /// `<cmd> [cmd_args] <cmd2> [cmd2_args] <cmd3> [cmd3_args]`. This setting disables that
- /// functionality and says that arguments can only follow the *final* subcommand. For instance
- /// using this setting makes only the following invocations possible:
- ///
- /// * `<cmd> <cmd2> <cmd3> [cmd3_args]`
- /// * `<cmd> <cmd2> [cmd2_args]`
- /// * `<cmd> [cmd_args]`
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::ArgsNegateSubcommands)
- /// # ;
- /// ```
- /// [subcommands]: ./struct.SubCommand.html
- /// [argument]: ./struct.Arg.html
- ArgsNegateSubcommands,
-
- /// Specifies that the help text should be displayed (and then exit gracefully),
- /// if no arguments are present at runtime (i.e. an empty run such as, `$ myprog`.
- ///
- /// **NOTE:** [`SubCommand`]s count as arguments
- ///
- /// **NOTE:** Setting [`Arg::default_value`] effectively disables this option as it will
- /// ensure that some argument is always present.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::ArgRequiredElseHelp)
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value
- ArgRequiredElseHelp,
-
- /// Uses colorized help messages.
- ///
- /// **NOTE:** Must be compiled with the `color` cargo feature
- ///
- /// # Platform Specific
- ///
- /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms)
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::ColoredHelp)
- /// .get_matches();
- /// ```
- ColoredHelp,
-
- /// Enables colored output only when the output is going to a terminal or TTY.
- ///
- /// **NOTE:** This is the default behavior of `clap`.
- ///
- /// **NOTE:** Must be compiled with the `color` cargo feature.
- ///
- /// # Platform Specific
- ///
- /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms).
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::ColorAuto)
- /// .get_matches();
- /// ```
- ColorAuto,
-
- /// Enables colored output regardless of whether or not the output is going to a terminal/TTY.
- ///
- /// **NOTE:** Must be compiled with the `color` cargo feature.
- ///
- /// # Platform Specific
- ///
- /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms).
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::ColorAlways)
- /// .get_matches();
- /// ```
- ColorAlways,
-
- /// Disables colored output no matter if the output is going to a terminal/TTY, or not.
- ///
- /// **NOTE:** Must be compiled with the `color` cargo feature
- ///
- /// # Platform Specific
- ///
- /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms)
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::ColorNever)
- /// .get_matches();
- /// ```
- ColorNever,
-
- /// Disables the automatic collapsing of positional args into `[ARGS]` inside the usage string
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::DontCollapseArgsInUsage)
- /// .get_matches();
- /// ```
- DontCollapseArgsInUsage,
-
- /// Disables the automatic delimiting of values when `--` or [`AppSettings::TrailingVarArg`]
- /// was used.
- ///
- /// **NOTE:** The same thing can be done manually by setting the final positional argument to
- /// [`Arg::use_delimiter(false)`]. Using this setting is safer, because it's easier to locate
- /// when making changes.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::DontDelimitTrailingValues)
- /// .get_matches();
- /// ```
- /// [`AppSettings::TrailingVarArg`]: ./enum.AppSettings.html#variant.TrailingVarArg
- /// [`Arg::use_delimiter(false)`]: ./struct.Arg.html#method.use_delimiter
- DontDelimitTrailingValues,
-
- /// Disables `-h` and `--help` [`App`] without affecting any of the [`SubCommand`]s
- /// (Defaults to `false`; application *does* have help flags)
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, AppSettings, ErrorKind};
- /// let res = App::new("myprog")
- /// .setting(AppSettings::DisableHelpFlags)
- /// .get_matches_from_safe(vec![
- /// "myprog", "-h"
- /// ]);
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
- /// ```
- ///
- /// ```rust
- /// # use clap::{App, SubCommand, AppSettings, ErrorKind};
- /// let res = App::new("myprog")
- /// .setting(AppSettings::DisableHelpFlags)
- /// .subcommand(SubCommand::with_name("test"))
- /// .get_matches_from_safe(vec![
- /// "myprog", "test", "-h"
- /// ]);
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::HelpDisplayed);
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`App`]: ./struct.App.html
- DisableHelpFlags,
-
- /// Disables the `help` subcommand
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, AppSettings, ErrorKind, SubCommand};
- /// let res = App::new("myprog")
- /// .version("v1.1")
- /// .setting(AppSettings::DisableHelpSubcommand)
- /// // Normally, creating a subcommand causes a `help` subcommand to automatically
- /// // be generated as well
- /// .subcommand(SubCommand::with_name("test"))
- /// .get_matches_from_safe(vec![
- /// "myprog", "help"
- /// ]);
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- DisableHelpSubcommand,
-
- /// Disables `-V` and `--version` [`App`] without affecting any of the [`SubCommand`]s
- /// (Defaults to `false`; application *does* have a version flag)
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, AppSettings, ErrorKind};
- /// let res = App::new("myprog")
- /// .version("v1.1")
- /// .setting(AppSettings::DisableVersion)
- /// .get_matches_from_safe(vec![
- /// "myprog", "-V"
- /// ]);
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
- /// ```
- ///
- /// ```rust
- /// # use clap::{App, SubCommand, AppSettings, ErrorKind};
- /// let res = App::new("myprog")
- /// .version("v1.1")
- /// .setting(AppSettings::DisableVersion)
- /// .subcommand(SubCommand::with_name("test"))
- /// .get_matches_from_safe(vec![
- /// "myprog", "test", "-V"
- /// ]);
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::VersionDisplayed);
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`App`]: ./struct.App.html
- DisableVersion,
-
- /// Displays the arguments and [`SubCommand`]s in the help message in the order that they were
- /// declared in, and not alphabetically which is the default.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::DeriveDisplayOrder)
- /// .get_matches();
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- DeriveDisplayOrder,
-
- /// Specifies to use the version of the current command for all child [`SubCommand`]s.
- /// (Defaults to `false`; subcommands have independent version strings from their parents.)
- ///
- /// **NOTE:** The version for the current command **and** this setting must be set **prior** to
- /// adding any child subcommands
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand, AppSettings};
- /// App::new("myprog")
- /// .version("v1.1")
- /// .setting(AppSettings::GlobalVersion)
- /// .subcommand(SubCommand::with_name("test"))
- /// .get_matches();
- /// // running `$ myprog test --version` will display
- /// // "myprog-test v1.1"
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- GlobalVersion,
-
- /// Specifies that this [`SubCommand`] should be hidden from help messages
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings, SubCommand};
- /// App::new("myprog")
- /// .subcommand(SubCommand::with_name("test")
- /// .setting(AppSettings::Hidden))
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- Hidden,
-
- /// Tells `clap` *not* to print possible values when displaying help information.
- /// This can be useful if there are many values, or they are explained elsewhere.
- HidePossibleValuesInHelp,
-
- /// Tries to match unknown args to partial [`subcommands`] or their [aliases]. For example to
- /// match a subcommand named `test`, one could use `t`, `te`, `tes`, and `test`.
- ///
- /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te`
- /// to `test` there could not also be a subcommand or alias `temp` because both start with `te`
- ///
- /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when
- /// designing CLIs which allow inferred subcommands and have potential positional/free
- /// arguments whose values could start with the same characters as subcommands. If this is the
- /// case, it's recommended to use settings such as [`AppSeettings::ArgsNegateSubcommands`] in
- /// conjunction with this setting.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand, AppSettings};
- /// let m = App::new("prog")
- /// .setting(AppSettings::InferSubcommands)
- /// .subcommand(SubCommand::with_name("test"))
- /// .get_matches_from(vec![
- /// "prog", "te"
- /// ]);
- /// assert_eq!(m.subcommand_name(), Some("test"));
- /// ```
- /// [`subcommands`]: ./struct.SubCommand.html
- /// [positional/free arguments]: ./struct.Arg.html#method.index
- /// [aliases]: ./struct.App.html#method.alias
- /// [`AppSeettings::ArgsNegateSubcommands`]: ./enum.AppSettings.html#variant.ArgsNegateSubcommands
- InferSubcommands,
-
- /// Specifies that the parser should not assume the first argument passed is the binary name.
- /// This is normally the case when using a "daemon" style mode, or an interactive CLI where one
- /// one would not normally type the binary or program name for each command.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings};
- /// let m = App::new("myprog")
- /// .setting(AppSettings::NoBinaryName)
- /// .arg(Arg::from_usage("<cmd>... 'commands to run'"))
- /// .get_matches_from(vec!["command", "set"]);
- ///
- /// let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect();
- /// assert_eq!(cmds, ["command", "set"]);
- /// ```
- NoBinaryName,
-
- /// Places the help string for all arguments on the line after the argument.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::NextLineHelp)
- /// .get_matches();
- /// ```
- NextLineHelp,
-
- /// **DEPRECATED**: This setting is no longer required in order to propagate values up or down
- ///
- /// Specifies that the parser should propagate global arg's values down or up through any *used*
- /// child subcommands. Meaning, if a subcommand wasn't used, the values won't be propagated to
- /// said subcommand.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings, SubCommand};
- /// let m = App::new("myprog")
- /// .arg(Arg::from_usage("[cmd] 'command to run'")
- /// .global(true))
- /// .subcommand(SubCommand::with_name("foo"))
- /// .get_matches_from(vec!["myprog", "set", "foo"]);
- ///
- /// assert_eq!(m.value_of("cmd"), Some("set"));
- ///
- /// let sub_m = m.subcommand_matches("foo").unwrap();
- /// assert_eq!(sub_m.value_of("cmd"), Some("set"));
- /// ```
- /// Now doing the same thing, but *not* using any subcommands will result in the value not being
- /// propagated down.
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings, SubCommand};
- /// let m = App::new("myprog")
- /// .arg(Arg::from_usage("[cmd] 'command to run'")
- /// .global(true))
- /// .subcommand(SubCommand::with_name("foo"))
- /// .get_matches_from(vec!["myprog", "set"]);
- ///
- /// assert_eq!(m.value_of("cmd"), Some("set"));
- ///
- /// assert!(m.subcommand_matches("foo").is_none());
- /// ```
- #[deprecated(since = "2.27.0", note = "No longer required to propagate values")]
- PropagateGlobalValuesDown,
-
- /// Allows [`SubCommand`]s to override all requirements of the parent command.
- /// For example if you had a subcommand or top level application with a required argument
- /// that is only required as long as there is no subcommand present,
- /// using this setting would allow you to set those arguments to [`Arg::required(true)`]
- /// and yet receive no error so long as the user uses a valid subcommand instead.
- ///
- /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements)
- ///
- /// # Examples
- ///
- /// This first example shows that it is an error to not use a required argument
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings, SubCommand, ErrorKind};
- /// let err = App::new("myprog")
- /// .setting(AppSettings::SubcommandsNegateReqs)
- /// .arg(Arg::with_name("opt").required(true))
- /// .subcommand(SubCommand::with_name("test"))
- /// .get_matches_from_safe(vec![
- /// "myprog"
- /// ]);
- /// assert!(err.is_err());
- /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
- /// # ;
- /// ```
- ///
- /// This next example shows that it is no longer error to not use a required argument if a
- /// valid subcommand is used.
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings, SubCommand, ErrorKind};
- /// let noerr = App::new("myprog")
- /// .setting(AppSettings::SubcommandsNegateReqs)
- /// .arg(Arg::with_name("opt").required(true))
- /// .subcommand(SubCommand::with_name("test"))
- /// .get_matches_from_safe(vec![
- /// "myprog", "test"
- /// ]);
- /// assert!(noerr.is_ok());
- /// # ;
- /// ```
- /// [`Arg::required(true)`]: ./struct.Arg.html#method.required
- /// [`SubCommand`]: ./struct.SubCommand.html
- SubcommandsNegateReqs,
-
- /// Specifies that the help text should be displayed (before exiting gracefully) if no
- /// [`SubCommand`]s are present at runtime (i.e. an empty run such as `$ myprog`).
- ///
- /// **NOTE:** This should *not* be used with [`AppSettings::SubcommandRequired`] as they do
- /// nearly same thing; this prints the help text, and the other prints an error.
- ///
- /// **NOTE:** If the user specifies arguments at runtime, but no subcommand the help text will
- /// still be displayed and exit. If this is *not* the desired result, consider using
- /// [`AppSettings::ArgRequiredElseHelp`] instead.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::SubcommandRequiredElseHelp)
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`AppSettings::SubcommandRequired`]: ./enum.AppSettings.html#variant.SubcommandRequired
- /// [`AppSettings::ArgRequiredElseHelp`]: ./enum.AppSettings.html#variant.ArgRequiredElseHelp
- SubcommandRequiredElseHelp,
-
- /// Specifies that any invalid UTF-8 code points should be treated as an error and fail
- /// with a [`ErrorKind::InvalidUtf8`] error.
- ///
- /// **NOTE:** This rule only applies to argument values; Things such as flags, options, and
- /// [`SubCommand`]s themselves only allow valid UTF-8 code points.
- ///
- /// # Platform Specific
- ///
- /// Non Windows systems only
- ///
- /// # Examples
- ///
- #[cfg_attr(not(unix), doc = " ```ignore")]
- #[cfg_attr(unix, doc = " ```")]
- /// # use clap::{App, AppSettings, ErrorKind};
- /// use std::ffi::OsString;
- /// use std::os::unix::ffi::OsStringExt;
- ///
- /// let m = App::new("myprog")
- /// .setting(AppSettings::StrictUtf8)
- /// .arg_from_usage("<arg> 'some positional arg'")
- /// .get_matches_from_safe(
- /// vec![
- /// OsString::from("myprog"),
- /// OsString::from_vec(vec![0xe9])]);
- ///
- /// assert!(m.is_err());
- /// assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidUtf8);
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`ErrorKind::InvalidUtf8`]: ./enum.ErrorKind.html#variant.InvalidUtf8
- StrictUtf8,
-
- /// Allows specifying that if no [`SubCommand`] is present at runtime,
- /// error and exit gracefully.
- ///
- /// **NOTE:** This defaults to `false` (subcommands do *not* need to be present)
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, AppSettings, SubCommand, ErrorKind};
- /// let err = App::new("myprog")
- /// .setting(AppSettings::SubcommandRequired)
- /// .subcommand(SubCommand::with_name("test"))
- /// .get_matches_from_safe(vec![
- /// "myprog",
- /// ]);
- /// assert!(err.is_err());
- /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand);
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- SubcommandRequired,
-
- /// Specifies that the final positional argument is a "VarArg" and that `clap` should not
- /// attempt to parse any further args.
- ///
- /// The values of the trailing positional argument will contain all args from itself on.
- ///
- /// **NOTE:** The final positional argument **must** have [`Arg::multiple(true)`] or the usage
- /// string equivalent.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings};
- /// let m = App::new("myprog")
- /// .setting(AppSettings::TrailingVarArg)
- /// .arg(Arg::from_usage("<cmd>... 'commands to run'"))
- /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]);
- ///
- /// let trail: Vec<&str> = m.values_of("cmd").unwrap().collect();
- /// assert_eq!(trail, ["arg1", "-r", "val1"]);
- /// ```
- /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
- TrailingVarArg,
-
- /// Groups flags and options together, presenting a more unified help message
- /// (a la `getopts` or `docopt` style).
- ///
- /// The default is that the auto-generated help message will group flags, and options
- /// separately.
- ///
- /// **NOTE:** This setting is cosmetic only and does not affect any functionality.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::UnifiedHelpMessage)
- /// .get_matches();
- /// // running `myprog --help` will display a unified "docopt" or "getopts" style help message
- /// ```
- UnifiedHelpMessage,
-
- /// Disables `-V` and `--version` for all [`SubCommand`]s
- /// (Defaults to `false`; subcommands *do* have version flags.)
- ///
- /// **NOTE:** This setting must be set **prior** to adding any subcommands.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, SubCommand, AppSettings, ErrorKind};
- /// let res = App::new("myprog")
- /// .version("v1.1")
- /// .setting(AppSettings::VersionlessSubcommands)
- /// .subcommand(SubCommand::with_name("test"))
- /// .get_matches_from_safe(vec![
- /// "myprog", "test", "-V"
- /// ]);
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- VersionlessSubcommands,
-
- /// Will display a message "Press \[ENTER\]/\[RETURN\] to continue..." and wait for user before
- /// exiting
- ///
- /// This is most useful when writing an application which is run from a GUI shortcut, or on
- /// Windows where a user tries to open the binary by double-clicking instead of using the
- /// command line.
- ///
- /// **NOTE:** This setting is **not** recursive with [`SubCommand`]s, meaning if you wish this
- /// behavior for all subcommands, you must set this on each command (needing this is extremely
- /// rare)
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings};
- /// App::new("myprog")
- /// .setting(AppSettings::WaitOnError)
- /// # ;
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- WaitOnError,
-
- #[doc(hidden)]
- NeedsLongVersion,
-
- #[doc(hidden)]
- NeedsLongHelp,
-
- #[doc(hidden)]
- NeedsSubcommandHelp,
-
- #[doc(hidden)]
- LowIndexMultiplePositional,
-
- #[doc(hidden)]
- TrailingValues,
-
- #[doc(hidden)]
- ValidNegNumFound,
-
- #[doc(hidden)]
- Propagated,
-
- #[doc(hidden)]
- ValidArgFound,
-
- #[doc(hidden)]
- ContainsLast,
-}
-
-impl FromStr for AppSettings {
- type Err = String;
- fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
- match &*s.to_ascii_lowercase() {
- "disablehelpflags" => Ok(AppSettings::DisableHelpFlags),
- "argrequiredelsehelp" => Ok(AppSettings::ArgRequiredElseHelp),
- "argsnegatesubcommands" => Ok(AppSettings::ArgsNegateSubcommands),
- "allowinvalidutf8" => Ok(AppSettings::AllowInvalidUtf8),
- "allowleadinghyphen" => Ok(AppSettings::AllowLeadingHyphen),
- "allowexternalsubcommands" => Ok(AppSettings::AllowExternalSubcommands),
- "allownegativenumbers" => Ok(AppSettings::AllowNegativeNumbers),
- "colorauto" => Ok(AppSettings::ColorAuto),
- "coloralways" => Ok(AppSettings::ColorAlways),
- "colornever" => Ok(AppSettings::ColorNever),
- "coloredhelp" => Ok(AppSettings::ColoredHelp),
- "derivedisplayorder" => Ok(AppSettings::DeriveDisplayOrder),
- "dontcollapseargsinusage" => Ok(AppSettings::DontCollapseArgsInUsage),
- "dontdelimittrailingvalues" => Ok(AppSettings::DontDelimitTrailingValues),
- "disablehelpsubcommand" => Ok(AppSettings::DisableHelpSubcommand),
- "disableversion" => Ok(AppSettings::DisableVersion),
- "globalversion" => Ok(AppSettings::GlobalVersion),
- "hidden" => Ok(AppSettings::Hidden),
- "hidepossiblevaluesinhelp" => Ok(AppSettings::HidePossibleValuesInHelp),
- "infersubcommands" => Ok(AppSettings::InferSubcommands),
- "lowindexmultiplepositional" => Ok(AppSettings::LowIndexMultiplePositional),
- "nobinaryname" => Ok(AppSettings::NoBinaryName),
- "nextlinehelp" => Ok(AppSettings::NextLineHelp),
- "strictutf8" => Ok(AppSettings::StrictUtf8),
- "subcommandsnegatereqs" => Ok(AppSettings::SubcommandsNegateReqs),
- "subcommandrequired" => Ok(AppSettings::SubcommandRequired),
- "subcommandrequiredelsehelp" => Ok(AppSettings::SubcommandRequiredElseHelp),
- "trailingvararg" => Ok(AppSettings::TrailingVarArg),
- "unifiedhelpmessage" => Ok(AppSettings::UnifiedHelpMessage),
- "versionlesssubcommands" => Ok(AppSettings::VersionlessSubcommands),
- "waitonerror" => Ok(AppSettings::WaitOnError),
- "validnegnumfound" => Ok(AppSettings::ValidNegNumFound),
- "validargfound" => Ok(AppSettings::ValidArgFound),
- "propagated" => Ok(AppSettings::Propagated),
- "trailingvalues" => Ok(AppSettings::TrailingValues),
- _ => Err("unknown AppSetting, cannot convert from str".to_owned()),
- }
- }
-}
-
-#[cfg(test)]
-mod test {
- use super::AppSettings;
-
- #[test]
- fn app_settings_fromstr() {
- assert_eq!(
- "disablehelpflags".parse::<AppSettings>().unwrap(),
- AppSettings::DisableHelpFlags
- );
- assert_eq!(
- "argsnegatesubcommands".parse::<AppSettings>().unwrap(),
- AppSettings::ArgsNegateSubcommands
- );
- assert_eq!(
- "argrequiredelsehelp".parse::<AppSettings>().unwrap(),
- AppSettings::ArgRequiredElseHelp
- );
- assert_eq!(
- "allowexternalsubcommands".parse::<AppSettings>().unwrap(),
- AppSettings::AllowExternalSubcommands
- );
- assert_eq!(
- "allowinvalidutf8".parse::<AppSettings>().unwrap(),
- AppSettings::AllowInvalidUtf8
- );
- assert_eq!(
- "allowleadinghyphen".parse::<AppSettings>().unwrap(),
- AppSettings::AllowLeadingHyphen
- );
- assert_eq!(
- "allownegativenumbers".parse::<AppSettings>().unwrap(),
- AppSettings::AllowNegativeNumbers
- );
- assert_eq!(
- "coloredhelp".parse::<AppSettings>().unwrap(),
- AppSettings::ColoredHelp
- );
- assert_eq!(
- "colorauto".parse::<AppSettings>().unwrap(),
- AppSettings::ColorAuto
- );
- assert_eq!(
- "coloralways".parse::<AppSettings>().unwrap(),
- AppSettings::ColorAlways
- );
- assert_eq!(
- "colornever".parse::<AppSettings>().unwrap(),
- AppSettings::ColorNever
- );
- assert_eq!(
- "disablehelpsubcommand".parse::<AppSettings>().unwrap(),
- AppSettings::DisableHelpSubcommand
- );
- assert_eq!(
- "disableversion".parse::<AppSettings>().unwrap(),
- AppSettings::DisableVersion
- );
- assert_eq!(
- "dontcollapseargsinusage".parse::<AppSettings>().unwrap(),
- AppSettings::DontCollapseArgsInUsage
- );
- assert_eq!(
- "dontdelimittrailingvalues".parse::<AppSettings>().unwrap(),
- AppSettings::DontDelimitTrailingValues
- );
- assert_eq!(
- "derivedisplayorder".parse::<AppSettings>().unwrap(),
- AppSettings::DeriveDisplayOrder
- );
- assert_eq!(
- "globalversion".parse::<AppSettings>().unwrap(),
- AppSettings::GlobalVersion
- );
- assert_eq!(
- "hidden".parse::<AppSettings>().unwrap(),
- AppSettings::Hidden
- );
- assert_eq!(
- "hidepossiblevaluesinhelp".parse::<AppSettings>().unwrap(),
- AppSettings::HidePossibleValuesInHelp
- );
- assert_eq!(
- "lowindexmultiplePositional".parse::<AppSettings>().unwrap(),
- AppSettings::LowIndexMultiplePositional
- );
- assert_eq!(
- "nobinaryname".parse::<AppSettings>().unwrap(),
- AppSettings::NoBinaryName
- );
- assert_eq!(
- "nextlinehelp".parse::<AppSettings>().unwrap(),
- AppSettings::NextLineHelp
- );
- assert_eq!(
- "subcommandsnegatereqs".parse::<AppSettings>().unwrap(),
- AppSettings::SubcommandsNegateReqs
- );
- assert_eq!(
- "subcommandrequired".parse::<AppSettings>().unwrap(),
- AppSettings::SubcommandRequired
- );
- assert_eq!(
- "subcommandrequiredelsehelp".parse::<AppSettings>().unwrap(),
- AppSettings::SubcommandRequiredElseHelp
- );
- assert_eq!(
- "strictutf8".parse::<AppSettings>().unwrap(),
- AppSettings::StrictUtf8
- );
- assert_eq!(
- "trailingvararg".parse::<AppSettings>().unwrap(),
- AppSettings::TrailingVarArg
- );
- assert_eq!(
- "unifiedhelpmessage".parse::<AppSettings>().unwrap(),
- AppSettings::UnifiedHelpMessage
- );
- assert_eq!(
- "versionlesssubcommands".parse::<AppSettings>().unwrap(),
- AppSettings::VersionlessSubcommands
- );
- assert_eq!(
- "waitonerror".parse::<AppSettings>().unwrap(),
- AppSettings::WaitOnError
- );
- assert_eq!(
- "validnegnumfound".parse::<AppSettings>().unwrap(),
- AppSettings::ValidNegNumFound
- );
- assert_eq!(
- "validargfound".parse::<AppSettings>().unwrap(),
- AppSettings::ValidArgFound
- );
- assert_eq!(
- "propagated".parse::<AppSettings>().unwrap(),
- AppSettings::Propagated
- );
- assert_eq!(
- "trailingvalues".parse::<AppSettings>().unwrap(),
- AppSettings::TrailingValues
- );
- assert_eq!(
- "infersubcommands".parse::<AppSettings>().unwrap(),
- AppSettings::InferSubcommands
- );
- assert!("hahahaha".parse::<AppSettings>().is_err());
- }
-}
diff --git a/src/app/usage.rs b/src/app/usage.rs
deleted file mode 100644
index e8105c6..0000000
--- a/src/app/usage.rs
+++ /dev/null
@@ -1,495 +0,0 @@
-// std
-use std::collections::{BTreeMap, VecDeque};
-
-// Internal
-use app::parser::Parser;
-use app::settings::AppSettings as AS;
-use args::settings::ArgSettings;
-use args::{AnyArg, ArgMatcher, PosBuilder};
-use INTERNAL_ERROR_MSG;
-
-// Creates a usage string for display. This happens just after all arguments were parsed, but before
-// any subcommands have been parsed (so as to give subcommands their own usage recursively)
-pub fn create_usage_with_title(p: &Parser, used: &[&str]) -> String {
- debugln!("usage::create_usage_with_title;");
- let mut usage = String::with_capacity(75);
- usage.push_str("USAGE:\n ");
- usage.push_str(&*create_usage_no_title(p, used));
- usage
-}
-
-// Creates a usage string to be used in error message (i.e. one with currently used args)
-pub fn create_error_usage<'a, 'b>(
- p: &Parser<'a, 'b>,
- matcher: &'b ArgMatcher<'a>,
- extra: Option<&str>,
-) -> String {
- let mut args: Vec<_> = matcher
- .arg_names()
- .iter()
- .filter(|n| {
- if let Some(o) = find_by_name!(p, **n, opts, iter) {
- !o.b.is_set(ArgSettings::Required) && !o.b.is_set(ArgSettings::Hidden)
- } else if let Some(p) = find_by_name!(p, **n, positionals, values) {
- !p.b.is_set(ArgSettings::Required) && p.b.is_set(ArgSettings::Hidden)
- } else {
- true // flags can't be required, so they're always true
- }
- })
- .map(|&n| n)
- .collect();
- if let Some(r) = extra {
- args.push(r);
- }
- create_usage_with_title(p, &*args)
-}
-
-// Creates a usage string (*without title*) if one was not provided by the user manually.
-pub fn create_usage_no_title(p: &Parser, used: &[&str]) -> String {
- debugln!("usage::create_usage_no_title;");
- if let Some(u) = p.meta.usage_str {
- String::from(&*u)
- } else if used.is_empty() {
- create_help_usage(p, true)
- } else {
- create_smart_usage(p, used)
- }
-}
-
-// Creates a usage string for display in help messages (i.e. not for errors)
-pub fn create_help_usage(p: &Parser, incl_reqs: bool) -> String {
- let mut usage = String::with_capacity(75);
- let name = p
- .meta
- .usage
- .as_ref()
- .unwrap_or_else(|| p.meta.bin_name.as_ref().unwrap_or(&p.meta.name));
- usage.push_str(&*name);
- let req_string = if incl_reqs {
- let mut reqs: Vec<&str> = p.required().map(|r| &**r).collect();
- reqs.sort();
- reqs.dedup();
- get_required_usage_from(p, &reqs, None, None, false)
- .iter()
- .fold(String::new(), |a, s| a + &format!(" {}", s)[..])
- } else {
- String::new()
- };
-
- let flags = needs_flags_tag(p);
- if flags && !p.is_set(AS::UnifiedHelpMessage) {
- usage.push_str(" [FLAGS]");
- } else if flags {
- usage.push_str(" [OPTIONS]");
- }
- if !p.is_set(AS::UnifiedHelpMessage)
- && p.opts
- .iter()
- .any(|o| !o.is_set(ArgSettings::Required) && !o.is_set(ArgSettings::Hidden))
- {
- usage.push_str(" [OPTIONS]");
- }
-
- usage.push_str(&req_string[..]);
-
- let has_last = p.positionals.values().any(|p| p.is_set(ArgSettings::Last));
- // places a '--' in the usage string if there are args and options
- // supporting multiple values
- if p.opts.iter().any(|o| o.is_set(ArgSettings::Multiple))
- && p.positionals
- .values()
- .any(|p| !p.is_set(ArgSettings::Required))
- && !(p.has_visible_subcommands() || p.is_set(AS::AllowExternalSubcommands))
- && !has_last
- {
- usage.push_str(" [--]");
- }
- let not_req_or_hidden = |p: &PosBuilder| {
- (!p.is_set(ArgSettings::Required) || p.is_set(ArgSettings::Last))
- && !p.is_set(ArgSettings::Hidden)
- };
- if p.has_positionals() && p.positionals.values().any(not_req_or_hidden) {
- if let Some(args_tag) = get_args_tag(p, incl_reqs) {
- usage.push_str(&*args_tag);
- } else {
- usage.push_str(" [ARGS]");
- }
- if has_last && incl_reqs {
- let pos = p
- .positionals
- .values()
- .find(|p| p.b.is_set(ArgSettings::Last))
- .expect(INTERNAL_ERROR_MSG);
- debugln!("usage::create_help_usage: '{}' has .last(true)", pos.name());
- let req = pos.is_set(ArgSettings::Required);
- if req
- && p.positionals
- .values()
- .any(|p| !p.is_set(ArgSettings::Required))
- {
- usage.push_str(" -- <");
- } else if req {
- usage.push_str(" [--] <");
- } else {
- usage.push_str(" [-- <");
- }
- usage.push_str(&*pos.name_no_brackets());
- usage.push_str(">");
- usage.push_str(pos.multiple_str());
- if !req {
- usage.push_str("]");
- }
- }
- }
-
- // incl_reqs is only false when this function is called recursively
- if p.has_visible_subcommands() && incl_reqs || p.is_set(AS::AllowExternalSubcommands) {
- if p.is_set(AS::SubcommandsNegateReqs) || p.is_set(AS::ArgsNegateSubcommands) {
- if !p.is_set(AS::ArgsNegateSubcommands) {
- usage.push_str("\n ");
- usage.push_str(&*create_help_usage(p, false));
- usage.push_str(" <SUBCOMMAND>");
- } else {
- usage.push_str("\n ");
- usage.push_str(&*name);
- usage.push_str(" <SUBCOMMAND>");
- }
- } else if p.is_set(AS::SubcommandRequired) || p.is_set(AS::SubcommandRequiredElseHelp) {
- usage.push_str(" <SUBCOMMAND>");
- } else {
- usage.push_str(" [SUBCOMMAND]");
- }
- }
- usage.shrink_to_fit();
- debugln!("usage::create_help_usage: usage={}", usage);
- usage
-}
-
-// Creates a context aware usage string, or "smart usage" from currently used
-// args, and requirements
-fn create_smart_usage(p: &Parser, used: &[&str]) -> String {
- debugln!("usage::smart_usage;");
- let mut usage = String::with_capacity(75);
- let mut hs: Vec<&str> = p.required().map(|s| &**s).collect();
- hs.extend_from_slice(used);
-
- let r_string = get_required_usage_from(p, &hs, None, None, false)
- .iter()
- .fold(String::new(), |acc, s| acc + &format!(" {}", s)[..]);
-
- usage.push_str(
- &p.meta
- .usage
- .as_ref()
- .unwrap_or_else(|| p.meta.bin_name.as_ref().unwrap_or(&p.meta.name))[..],
- );
- usage.push_str(&*r_string);
- if p.is_set(AS::SubcommandRequired) {
- usage.push_str(" <SUBCOMMAND>");
- }
- usage.shrink_to_fit();
- usage
-}
-
-// Gets the `[ARGS]` tag for the usage string
-fn get_args_tag(p: &Parser, incl_reqs: bool) -> Option<String> {
- debugln!("usage::get_args_tag;");
- let mut count = 0;
- 'outer: for pos in p
- .positionals
- .values()
- .filter(|pos| !pos.is_set(ArgSettings::Required))
- .filter(|pos| !pos.is_set(ArgSettings::Hidden))
- .filter(|pos| !pos.is_set(ArgSettings::Last))
- {
- debugln!("usage::get_args_tag:iter:{}:", pos.b.name);
- if let Some(g_vec) = p.groups_for_arg(pos.b.name) {
- for grp_s in &g_vec {
- debugln!("usage::get_args_tag:iter:{}:iter:{};", pos.b.name, grp_s);
- // if it's part of a required group we don't want to count it
- if p.groups.iter().any(|g| g.required && (&g.name == grp_s)) {
- continue 'outer;
- }
- }
- }
- count += 1;
- debugln!(
- "usage::get_args_tag:iter: {} Args not required or hidden",
- count
- );
- }
- if !p.is_set(AS::DontCollapseArgsInUsage) && count > 1 {
- debugln!("usage::get_args_tag:iter: More than one, returning [ARGS]");
- return None; // [ARGS]
- } else if count == 1 && incl_reqs {
- let pos = p
- .positionals
- .values()
- .find(|pos| {
- !pos.is_set(ArgSettings::Required)
- && !pos.is_set(ArgSettings::Hidden)
- && !pos.is_set(ArgSettings::Last)
- })
- .expect(INTERNAL_ERROR_MSG);
- debugln!(
- "usage::get_args_tag:iter: Exactly one, returning '{}'",
- pos.name()
- );
- return Some(format!(
- " [{}]{}",
- pos.name_no_brackets(),
- pos.multiple_str()
- ));
- } else if p.is_set(AS::DontCollapseArgsInUsage) && !p.positionals.is_empty() && incl_reqs {
- debugln!("usage::get_args_tag:iter: Don't collapse returning all");
- return Some(
- p.positionals
- .values()
- .filter(|pos| !pos.is_set(ArgSettings::Required))
- .filter(|pos| !pos.is_set(ArgSettings::Hidden))
- .filter(|pos| !pos.is_set(ArgSettings::Last))
- .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str()))
- .collect::<Vec<_>>()
- .join(""),
- );
- } else if !incl_reqs {
- debugln!("usage::get_args_tag:iter: incl_reqs=false, building secondary usage string");
- let highest_req_pos = p
- .positionals
- .iter()
- .filter_map(|(idx, pos)| {
- if pos.b.is_set(ArgSettings::Required) && !pos.b.is_set(ArgSettings::Last) {
- Some(idx)
- } else {
- None
- }
- })
- .max()
- .unwrap_or_else(|| p.positionals.len());
- return Some(
- p.positionals
- .iter()
- .filter_map(|(idx, pos)| {
- if idx <= highest_req_pos {
- Some(pos)
- } else {
- None
- }
- })
- .filter(|pos| !pos.is_set(ArgSettings::Required))
- .filter(|pos| !pos.is_set(ArgSettings::Hidden))
- .filter(|pos| !pos.is_set(ArgSettings::Last))
- .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str()))
- .collect::<Vec<_>>()
- .join(""),
- );
- }
- Some("".into())
-}
-
-// Determines if we need the `[FLAGS]` tag in the usage string
-fn needs_flags_tag(p: &Parser) -> bool {
- debugln!("usage::needs_flags_tag;");
- 'outer: for f in &p.flags {
- debugln!("usage::needs_flags_tag:iter: f={};", f.b.name);
- if let Some(l) = f.s.long {
- if l == "help" || l == "version" {
- // Don't print `[FLAGS]` just for help or version
- continue;
- }
- }
- if let Some(g_vec) = p.groups_for_arg(f.b.name) {
- for grp_s in &g_vec {
- debugln!("usage::needs_flags_tag:iter:iter: grp_s={};", grp_s);
- if p.groups.iter().any(|g| &g.name == grp_s && g.required) {
- debugln!("usage::needs_flags_tag:iter:iter: Group is required");
- continue 'outer;
- }
- }
- }
- if f.is_set(ArgSettings::Hidden) {
- continue;
- }
- debugln!("usage::needs_flags_tag:iter: [FLAGS] required");
- return true;
- }
-
- debugln!("usage::needs_flags_tag: [FLAGS] not required");
- false
-}
-
-// Returns the required args in usage string form by fully unrolling all groups
-pub fn get_required_usage_from<'a, 'b>(
- p: &Parser<'a, 'b>,
- reqs: &[&'a str],
- matcher: Option<&ArgMatcher<'a>>,
- extra: Option<&str>,
- incl_last: bool,
-) -> VecDeque<String> {
- debugln!(
- "usage::get_required_usage_from: reqs={:?}, extra={:?}",
- reqs,
- extra
- );
- let mut desc_reqs: Vec<&str> = vec![];
- desc_reqs.extend(extra);
- let mut new_reqs: Vec<&str> = vec![];
- macro_rules! get_requires {
- (@group $a: ident, $v:ident, $p:ident) => {{
- if let Some(rl) = p
- .groups
- .iter()
- .filter(|g| g.requires.is_some())
- .find(|g| &g.name == $a)
- .map(|g| g.requires.as_ref().unwrap())
- {
- for r in rl {
- if !$p.contains(&r) {
- debugln!(
- "usage::get_required_usage_from:iter:{}: adding group req={:?}",
- $a,
- r
- );
- $v.push(r);
- }
- }
- }
- }};
- ($a:ident, $what:ident, $how:ident, $v:ident, $p:ident) => {{
- if let Some(rl) = p
- .$what
- .$how()
- .filter(|a| a.b.requires.is_some())
- .find(|arg| &arg.b.name == $a)
- .map(|a| a.b.requires.as_ref().unwrap())
- {
- for &(_, r) in rl.iter() {
- if !$p.contains(&r) {
- debugln!(
- "usage::get_required_usage_from:iter:{}: adding arg req={:?}",
- $a,
- r
- );
- $v.push(r);
- }
- }
- }
- }};
- }
- // initialize new_reqs
- for a in reqs {
- get_requires!(a, flags, iter, new_reqs, reqs);
- get_requires!(a, opts, iter, new_reqs, reqs);
- get_requires!(a, positionals, values, new_reqs, reqs);
- get_requires!(@group a, new_reqs, reqs);
- }
- desc_reqs.extend_from_slice(&*new_reqs);
- debugln!(
- "usage::get_required_usage_from: after init desc_reqs={:?}",
- desc_reqs
- );
- loop {
- let mut tmp = vec![];
- for a in &new_reqs {
- get_requires!(a, flags, iter, tmp, desc_reqs);
- get_requires!(a, opts, iter, tmp, desc_reqs);
- get_requires!(a, positionals, values, tmp, desc_reqs);
- get_requires!(@group a, tmp, desc_reqs);
- }
- if tmp.is_empty() {
- debugln!("usage::get_required_usage_from: no more children");
- break;
- } else {
- debugln!("usage::get_required_usage_from: after iter tmp={:?}", tmp);
- debugln!(
- "usage::get_required_usage_from: after iter new_reqs={:?}",
- new_reqs
- );
- desc_reqs.extend_from_slice(&*new_reqs);
- new_reqs.clear();
- new_reqs.extend_from_slice(&*tmp);
- debugln!(
- "usage::get_required_usage_from: after iter desc_reqs={:?}",
- desc_reqs
- );
- }
- }
- desc_reqs.extend_from_slice(reqs);
- desc_reqs.sort();
- desc_reqs.dedup();
- debugln!(
- "usage::get_required_usage_from: final desc_reqs={:?}",
- desc_reqs
- );
- let mut ret_val = VecDeque::new();
- let args_in_groups = p
- .groups
- .iter()
- .filter(|gn| desc_reqs.contains(&gn.name))
- .flat_map(|g| p.arg_names_in_group(g.name))
- .collect::<Vec<_>>();
-
- let pmap = if let Some(m) = matcher {
- desc_reqs
- .iter()
- .filter(|a| p.positionals.values().any(|p| &&p.b.name == a))
- .filter(|&pos| !m.contains(pos))
- .filter_map(|pos| p.positionals.values().find(|x| &x.b.name == pos))
- .filter(|&pos| incl_last || !pos.is_set(ArgSettings::Last))
- .filter(|pos| !args_in_groups.contains(&pos.b.name))
- .map(|pos| (pos.index, pos))
- .collect::<BTreeMap<u64, &PosBuilder>>() // sort by index
- } else {
- desc_reqs
- .iter()
- .filter(|a| p.positionals.values().any(|pos| &&pos.b.name == a))
- .filter_map(|pos| p.positionals.values().find(|x| &x.b.name == pos))
- .filter(|&pos| incl_last || !pos.is_set(ArgSettings::Last))
- .filter(|pos| !args_in_groups.contains(&pos.b.name))
- .map(|pos| (pos.index, pos))
- .collect::<BTreeMap<u64, &PosBuilder>>() // sort by index
- };
- debugln!(
- "usage::get_required_usage_from: args_in_groups={:?}",
- args_in_groups
- );
- for &p in pmap.values() {
- let s = p.to_string();
- if args_in_groups.is_empty() || !args_in_groups.contains(&&*s) {
- ret_val.push_back(s);
- }
- }
- for a in desc_reqs
- .iter()
- .filter(|name| !p.positionals.values().any(|p| &&p.b.name == name))
- .filter(|name| !p.groups.iter().any(|g| &&g.name == name))
- .filter(|name| !args_in_groups.contains(name))
- .filter(|name| !(matcher.is_some() && matcher.as_ref().unwrap().contains(name)))
- {
- debugln!("usage::get_required_usage_from:iter:{}:", a);
- let arg = find_by_name!(p, *a, flags, iter)
- .map(|f| f.to_string())
- .unwrap_or_else(|| {
- find_by_name!(p, *a, opts, iter)
- .map(|o| o.to_string())
- .expect(INTERNAL_ERROR_MSG)
- });
- ret_val.push_back(arg);
- }
- let mut g_vec: Vec<String> = vec![];
- for g in desc_reqs
- .iter()
- .filter(|n| p.groups.iter().any(|g| &&g.name == n))
- {
- let g_string = p.args_in_group(g).join("|");
- let elem = format!("<{}>", &g_string[..g_string.len()]);
- if !g_vec.contains(&elem) {
- g_vec.push(elem);
- }
- }
- for g in g_vec {
- ret_val.push_back(g);
- }
-
- ret_val
-}
diff --git a/src/app/validator.rs b/src/app/validator.rs
deleted file mode 100644
index 862f0bb..0000000
--- a/src/app/validator.rs
+++ /dev/null
@@ -1,583 +0,0 @@
-// std
-#[allow(deprecated, unused_imports)]
-use std::ascii::AsciiExt;
-use std::fmt::Display;
-
-// Internal
-use app::parser::{ParseResult, Parser};
-use app::settings::AppSettings as AS;
-use app::usage;
-use args::settings::ArgSettings;
-use args::{AnyArg, ArgMatcher, MatchedArg};
-use errors::Result as ClapResult;
-use errors::{Error, ErrorKind};
-use fmt::{Colorizer, ColorizerOption};
-use INTERNAL_ERROR_MSG;
-use INVALID_UTF8;
-
-pub struct Validator<'a, 'b, 'z>(&'z mut Parser<'a, 'b>)
-where
- 'a: 'b,
- 'b: 'z;
-
-impl<'a, 'b, 'z> Validator<'a, 'b, 'z> {
- pub fn new(p: &'z mut Parser<'a, 'b>) -> Self {
- Validator(p)
- }
-
- pub fn validate(
- &mut self,
- needs_val_of: ParseResult<'a>,
- subcmd_name: Option<String>,
- matcher: &mut ArgMatcher<'a>,
- ) -> ClapResult<()> {
- debugln!("Validator::validate;");
- let mut reqs_validated = false;
- self.0.add_env(matcher)?;
- self.0.add_defaults(matcher)?;
- if let ParseResult::Opt(a) = needs_val_of {
- debugln!("Validator::validate: needs_val_of={:?}", a);
- let o = {
- self.0
- .opts
- .iter()
- .find(|o| o.b.name == a)
- .expect(INTERNAL_ERROR_MSG)
- .clone()
- };
- self.validate_required(matcher)?;
- reqs_validated = true;
- let should_err = if let Some(v) = matcher.0.args.get(&*o.b.name) {
- v.vals.is_empty() && !(o.v.min_vals.is_some() && o.v.min_vals.unwrap() == 0)
- } else {
- true
- };
- if should_err {
- return Err(Error::empty_value(
- &o,
- &*usage::create_error_usage(self.0, matcher, None),
- self.0.color(),
- ));
- }
- }
-
- if matcher.is_empty()
- && matcher.subcommand_name().is_none()
- && self.0.is_set(AS::ArgRequiredElseHelp)
- {
- let mut out = vec![];
- self.0.write_help_err(&mut out)?;
- return Err(Error {
- message: String::from_utf8_lossy(&*out).into_owned(),
- kind: ErrorKind::MissingArgumentOrSubcommand,
- info: None,
- });
- }
- self.validate_blacklist(matcher)?;
- if !(self.0.is_set(AS::SubcommandsNegateReqs) && subcmd_name.is_some()) && !reqs_validated {
- self.validate_required(matcher)?;
- }
- self.validate_matched_args(matcher)?;
- matcher.usage(usage::create_usage_with_title(self.0, &[]));
-
- Ok(())
- }
-
- fn validate_arg_values<A>(
- &self,
- arg: &A,
- ma: &MatchedArg,
- matcher: &ArgMatcher<'a>,
- ) -> ClapResult<()>
- where
- A: AnyArg<'a, 'b> + Display,
- {
- debugln!("Validator::validate_arg_values: arg={:?}", arg.name());
- for val in &ma.vals {
- if self.0.is_set(AS::StrictUtf8) && val.to_str().is_none() {
- debugln!(
- "Validator::validate_arg_values: invalid UTF-8 found in val {:?}",
- val
- );
- return Err(Error::invalid_utf8(
- &*usage::create_error_usage(self.0, matcher, None),
- self.0.color(),
- ));
- }
- if let Some(p_vals) = arg.possible_vals() {
- debugln!("Validator::validate_arg_values: possible_vals={:?}", p_vals);
- let val_str = val.to_string_lossy();
- let ok = if arg.is_set(ArgSettings::CaseInsensitive) {
- p_vals.iter().any(|pv| pv.eq_ignore_ascii_case(&*val_str))
- } else {
- p_vals.contains(&&*val_str)
- };
- if !ok {
- return Err(Error::invalid_value(
- val_str,
- p_vals,
- arg,
- &*usage::create_error_usage(self.0, matcher, None),
- self.0.color(),
- ));
- }
- }
- if !arg.is_set(ArgSettings::EmptyValues)
- && val.is_empty()
- && matcher.contains(&*arg.name())
- {
- debugln!("Validator::validate_arg_values: illegal empty val found");
- return Err(Error::empty_value(
- arg,
- &*usage::create_error_usage(self.0, matcher, None),
- self.0.color(),
- ));
- }
- if let Some(vtor) = arg.validator() {
- debug!("Validator::validate_arg_values: checking validator...");
- if let Err(e) = vtor(val.to_string_lossy().into_owned()) {
- sdebugln!("error");
- return Err(Error::value_validation(Some(arg), e, self.0.color()));
- } else {
- sdebugln!("good");
- }
- }
- if let Some(vtor) = arg.validator_os() {
- debug!("Validator::validate_arg_values: checking validator_os...");
- if let Err(e) = vtor(val) {
- sdebugln!("error");
- return Err(Error::value_validation(
- Some(arg),
- (*e).to_string_lossy().to_string(),
- self.0.color(),
- ));
- } else {
- sdebugln!("good");
- }
- }
- }
- Ok(())
- }
-
- fn build_err(&self, name: &str, matcher: &ArgMatcher) -> ClapResult<()> {
- debugln!("build_err!: name={}", name);
- let mut c_with = find_from!(self.0, &name, blacklist, matcher);
- c_with = c_with.or(self
- .0
- .find_any_arg(name)
- .map_or(None, |aa| aa.blacklist())
- .map_or(None, |bl| bl.iter().find(|arg| matcher.contains(arg)))
- .map_or(None, |an| self.0.find_any_arg(an))
- .map_or(None, |aa| Some(format!("{}", aa))));
- debugln!("build_err!: '{:?}' conflicts with '{}'", c_with, &name);
- // matcher.remove(&name);
- let usg = usage::create_error_usage(self.0, matcher, None);
- if let Some(f) = find_by_name!(self.0, name, flags, iter) {
- debugln!("build_err!: It was a flag...");
- Err(Error::argument_conflict(f, c_with, &*usg, self.0.color()))
- } else if let Some(o) = find_by_name!(self.0, name, opts, iter) {
- debugln!("build_err!: It was an option...");
- Err(Error::argument_conflict(o, c_with, &*usg, self.0.color()))
- } else {
- match find_by_name!(self.0, name, positionals, values) {
- Some(p) => {
- debugln!("build_err!: It was a positional...");
- Err(Error::argument_conflict(p, c_with, &*usg, self.0.color()))
- }
- None => panic!(INTERNAL_ERROR_MSG),
- }
- }
- }
-
- fn validate_blacklist(&self, matcher: &mut ArgMatcher) -> ClapResult<()> {
- debugln!("Validator::validate_blacklist;");
- let mut conflicts: Vec<&str> = vec![];
- for (&name, _) in matcher.iter() {
- debugln!("Validator::validate_blacklist:iter:{};", name);
- if let Some(grps) = self.0.groups_for_arg(name) {
- for grp in &grps {
- if let Some(g) = self.0.groups.iter().find(|g| &g.name == grp) {
- if !g.multiple {
- for arg in &g.args {
- if arg == &name {
- continue;
- }
- conflicts.push(arg);
- }
- }
- if let Some(ref gc) = g.conflicts {
- conflicts.extend(&*gc);
- }
- }
- }
- }
- if let Some(arg) = find_any_by_name!(self.0, name) {
- if let Some(bl) = arg.blacklist() {
- for conf in bl {
- if matcher.get(conf).is_some() {
- conflicts.push(conf);
- }
- }
- }
- } else {
- debugln!("Validator::validate_blacklist:iter:{}:group;", name);
- let args = self.0.arg_names_in_group(name);
- for arg in &args {
- debugln!(
- "Validator::validate_blacklist:iter:{}:group:iter:{};",
- name,
- arg
- );
- if let Some(bl) = find_any_by_name!(self.0, *arg).unwrap().blacklist() {
- for conf in bl {
- if matcher.get(conf).is_some() {
- conflicts.push(conf);
- }
- }
- }
- }
- }
- }
-
- for name in &conflicts {
- debugln!(
- "Validator::validate_blacklist:iter:{}: Checking blacklisted arg",
- name
- );
- let mut should_err = false;
- if self.0.groups.iter().any(|g| &g.name == name) {
- debugln!(
- "Validator::validate_blacklist:iter:{}: groups contains it...",
- name
- );
- for n in self.0.arg_names_in_group(name) {
- debugln!(
- "Validator::validate_blacklist:iter:{}:iter:{}: looking in group...",
- name,
- n
- );
- if matcher.contains(n) {
- debugln!(
- "Validator::validate_blacklist:iter:{}:iter:{}: matcher contains it...",
- name,
- n
- );
- return self.build_err(n, matcher);
- }
- }
- } else if let Some(ma) = matcher.get(name) {
- debugln!(
- "Validator::validate_blacklist:iter:{}: matcher contains it...",
- name
- );
- should_err = ma.occurs > 0;
- }
- if should_err {
- return self.build_err(*name, matcher);
- }
- }
- Ok(())
- }
-
- fn validate_matched_args(&self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> {
- debugln!("Validator::validate_matched_args;");
- for (name, ma) in matcher.iter() {
- debugln!(
- "Validator::validate_matched_args:iter:{}: vals={:#?}",
- name,
- ma.vals
- );
- if let Some(opt) = find_by_name!(self.0, *name, opts, iter) {
- self.validate_arg_num_vals(opt, ma, matcher)?;
- self.validate_arg_values(opt, ma, matcher)?;
- self.validate_arg_requires(opt, ma, matcher)?;
- self.validate_arg_num_occurs(opt, ma, matcher)?;
- } else if let Some(flag) = find_by_name!(self.0, *name, flags, iter) {
- self.validate_arg_requires(flag, ma, matcher)?;
- self.validate_arg_num_occurs(flag, ma, matcher)?;
- } else if let Some(pos) = find_by_name!(self.0, *name, positionals, values) {
- self.validate_arg_num_vals(pos, ma, matcher)?;
- self.validate_arg_num_occurs(pos, ma, matcher)?;
- self.validate_arg_values(pos, ma, matcher)?;
- self.validate_arg_requires(pos, ma, matcher)?;
- } else {
- let grp = self
- .0
- .groups
- .iter()
- .find(|g| &g.name == name)
- .expect(INTERNAL_ERROR_MSG);
- if let Some(ref g_reqs) = grp.requires {
- if g_reqs.iter().any(|&n| !matcher.contains(n)) {
- return self.missing_required_error(matcher, None);
- }
- }
- }
- }
- Ok(())
- }
-
- fn validate_arg_num_occurs<A>(
- &self,
- a: &A,
- ma: &MatchedArg,
- matcher: &ArgMatcher,
- ) -> ClapResult<()>
- where
- A: AnyArg<'a, 'b> + Display,
- {
- debugln!("Validator::validate_arg_num_occurs: a={};", a.name());
- if ma.occurs > 1 && !a.is_set(ArgSettings::Multiple) {
- // Not the first time, and we don't allow multiples
- return Err(Error::unexpected_multiple_usage(
- a,
- &*usage::create_error_usage(self.0, matcher, None),
- self.0.color(),
- ));
- }
- Ok(())
- }
-
- fn validate_arg_num_vals<A>(
- &self,
- a: &A,
- ma: &MatchedArg,
- matcher: &ArgMatcher,
- ) -> ClapResult<()>
- where
- A: AnyArg<'a, 'b> + Display,
- {
- debugln!("Validator::validate_arg_num_vals:{}", a.name());
- if let Some(num) = a.num_vals() {
- debugln!("Validator::validate_arg_num_vals: num_vals set...{}", num);
- let should_err = if a.is_set(ArgSettings::Multiple) {
- ((ma.vals.len() as u64) % num) != 0
- } else {
- num != (ma.vals.len() as u64)
- };
- if should_err {
- debugln!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues");
- return Err(Error::wrong_number_of_values(
- a,
- num,
- if a.is_set(ArgSettings::Multiple) {
- (ma.vals.len() % num as usize)
- } else {
- ma.vals.len()
- },
- if ma.vals.len() == 1
- || (a.is_set(ArgSettings::Multiple) && (ma.vals.len() % num as usize) == 1)
- {
- "as"
- } else {
- "ere"
- },
- &*usage::create_error_usage(self.0, matcher, None),
- self.0.color(),
- ));
- }
- }
- if let Some(num) = a.max_vals() {
- debugln!("Validator::validate_arg_num_vals: max_vals set...{}", num);
- if (ma.vals.len() as u64) > num {
- debugln!("Validator::validate_arg_num_vals: Sending error TooManyValues");
- return Err(Error::too_many_values(
- ma.vals
- .iter()
- .last()
- .expect(INTERNAL_ERROR_MSG)
- .to_str()
- .expect(INVALID_UTF8),
- a,
- &*usage::create_error_usage(self.0, matcher, None),
- self.0.color(),
- ));
- }
- }
- let min_vals_zero = if let Some(num) = a.min_vals() {
- debugln!("Validator::validate_arg_num_vals: min_vals set: {}", num);
- if (ma.vals.len() as u64) < num && num != 0 {
- debugln!("Validator::validate_arg_num_vals: Sending error TooFewValues");
- return Err(Error::too_few_values(
- a,
- num,
- ma.vals.len(),
- &*usage::create_error_usage(self.0, matcher, None),
- self.0.color(),
- ));
- }
- num == 0
- } else {
- false
- };
- // Issue 665 (https://github.com/clap-rs/clap/issues/665)
- // Issue 1105 (https://github.com/clap-rs/clap/issues/1105)
- if a.takes_value() && !min_vals_zero && ma.vals.is_empty() {
- return Err(Error::empty_value(
- a,
- &*usage::create_error_usage(self.0, matcher, None),
- self.0.color(),
- ));
- }
- Ok(())
- }
-
- fn validate_arg_requires<A>(
- &self,
- a: &A,
- ma: &MatchedArg,
- matcher: &ArgMatcher,
- ) -> ClapResult<()>
- where
- A: AnyArg<'a, 'b> + Display,
- {
- debugln!("Validator::validate_arg_requires:{};", a.name());
- if let Some(a_reqs) = a.requires() {
- for &(val, name) in a_reqs.iter().filter(|&&(val, _)| val.is_some()) {
- let missing_req =
- |v| v == val.expect(INTERNAL_ERROR_MSG) && !matcher.contains(name);
- if ma.vals.iter().any(missing_req) {
- return self.missing_required_error(matcher, None);
- }
- }
- for &(_, name) in a_reqs.iter().filter(|&&(val, _)| val.is_none()) {
- if !matcher.contains(name) {
- return self.missing_required_error(matcher, Some(name));
- }
- }
- }
- Ok(())
- }
-
- fn validate_required(&mut self, matcher: &ArgMatcher) -> ClapResult<()> {
- debugln!(
- "Validator::validate_required: required={:?};",
- self.0.required
- );
-
- let mut should_err = false;
- let mut to_rem = Vec::new();
- for name in &self.0.required {
- debugln!("Validator::validate_required:iter:{}:", name);
- if matcher.contains(name) {
- continue;
- }
- if to_rem.contains(name) {
- continue;
- } else if let Some(a) = find_any_by_name!(self.0, *name) {
- if self.is_missing_required_ok(a, matcher) {
- to_rem.push(a.name());
- if let Some(reqs) = a.requires() {
- for r in reqs
- .iter()
- .filter(|&&(val, _)| val.is_none())
- .map(|&(_, name)| name)
- {
- to_rem.push(r);
- }
- }
- continue;
- }
- }
- should_err = true;
- break;
- }
- if should_err {
- for r in &to_rem {
- 'inner: for i in (0..self.0.required.len()).rev() {
- if &self.0.required[i] == r {
- self.0.required.swap_remove(i);
- break 'inner;
- }
- }
- }
- return self.missing_required_error(matcher, None);
- }
-
- // Validate the conditionally required args
- for &(a, v, r) in &self.0.r_ifs {
- if let Some(ma) = matcher.get(a) {
- if matcher.get(r).is_none() && ma.vals.iter().any(|val| val == v) {
- return self.missing_required_error(matcher, Some(r));
- }
- }
- }
- Ok(())
- }
-
- fn validate_arg_conflicts(&self, a: &AnyArg, matcher: &ArgMatcher) -> Option<bool> {
- debugln!("Validator::validate_arg_conflicts: a={:?};", a.name());
- a.blacklist().map(|bl| {
- bl.iter().any(|conf| {
- matcher.contains(conf)
- || self
- .0
- .groups
- .iter()
- .find(|g| &g.name == conf)
- .map_or(false, |g| g.args.iter().any(|arg| matcher.contains(arg)))
- })
- })
- }
-
- fn validate_required_unless(&self, a: &AnyArg, matcher: &ArgMatcher) -> Option<bool> {
- debugln!("Validator::validate_required_unless: a={:?};", a.name());
- macro_rules! check {
- ($how:ident, $_self:expr, $a:ident, $m:ident) => {{
- $a.required_unless().map(|ru| {
- ru.iter().$how(|n| {
- $m.contains(n) || {
- if let Some(grp) = $_self.groups.iter().find(|g| &g.name == n) {
- grp.args.iter().any(|arg| $m.contains(arg))
- } else {
- false
- }
- }
- })
- })
- }};
- }
- if a.is_set(ArgSettings::RequiredUnlessAll) {
- check!(all, self.0, a, matcher)
- } else {
- check!(any, self.0, a, matcher)
- }
- }
-
- fn missing_required_error(&self, matcher: &ArgMatcher, extra: Option<&str>) -> ClapResult<()> {
- debugln!("Validator::missing_required_error: extra={:?}", extra);
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: self.0.color(),
- });
- let mut reqs = self.0.required.iter().map(|&r| &*r).collect::<Vec<_>>();
- if let Some(r) = extra {
- reqs.push(r);
- }
- reqs.retain(|n| !matcher.contains(n));
- reqs.dedup();
- debugln!("Validator::missing_required_error: reqs={:#?}", reqs);
- let req_args =
- usage::get_required_usage_from(self.0, &reqs[..], Some(matcher), extra, true)
- .iter()
- .fold(String::new(), |acc, s| {
- acc + &format!("\n {}", c.error(s))[..]
- });
- debugln!(
- "Validator::missing_required_error: req_args={:#?}",
- req_args
- );
- Err(Error::missing_required_argument(
- &*req_args,
- &*usage::create_error_usage(self.0, matcher, extra),
- self.0.color(),
- ))
- }
-
- #[inline]
- fn is_missing_required_ok(&self, a: &AnyArg, matcher: &ArgMatcher) -> bool {
- debugln!("Validator::is_missing_required_ok: a={}", a.name());
- self.validate_arg_conflicts(a, matcher).unwrap_or(false)
- || self.validate_required_unless(a, matcher).unwrap_or(false)
- }
-}
diff --git a/src/args/any_arg.rs b/src/args/any_arg.rs
deleted file mode 100644
index 46aa763..0000000
--- a/src/args/any_arg.rs
+++ /dev/null
@@ -1,131 +0,0 @@
-// Std
-use std::ffi::{OsStr, OsString};
-use std::fmt as std_fmt;
-use std::rc::Rc;
-
-// Internal
-use args::settings::ArgSettings;
-use map::{self, VecMap};
-use INTERNAL_ERROR_MSG;
-
-#[doc(hidden)]
-pub trait AnyArg<'n, 'e>: std_fmt::Display {
- fn name(&self) -> &'n str;
- fn overrides(&self) -> Option<&[&'e str]>;
- fn aliases(&self) -> Option<Vec<&'e str>>;
- fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]>;
- fn blacklist(&self) -> Option<&[&'e str]>;
- fn required_unless(&self) -> Option<&[&'e str]>;
- fn is_set(&self, ArgSettings) -> bool;
- fn set(&mut self, ArgSettings);
- fn has_switch(&self) -> bool;
- fn max_vals(&self) -> Option<u64>;
- fn min_vals(&self) -> Option<u64>;
- fn num_vals(&self) -> Option<u64>;
- fn possible_vals(&self) -> Option<&[&'e str]>;
- fn validator(&self) -> Option<&Rc<Fn(String) -> Result<(), String>>>;
- fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> Result<(), OsString>>>;
- fn short(&self) -> Option<char>;
- fn long(&self) -> Option<&'e str>;
- fn val_delim(&self) -> Option<char>;
- fn takes_value(&self) -> bool;
- fn val_names(&self) -> Option<&VecMap<&'e str>>;
- fn help(&self) -> Option<&'e str>;
- fn long_help(&self) -> Option<&'e str>;
- fn default_val(&self) -> Option<&'e OsStr>;
- fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>>;
- fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)>;
- fn longest_filter(&self) -> bool;
- fn val_terminator(&self) -> Option<&'e str>;
-}
-
-pub trait DispOrder {
- fn disp_ord(&self) -> usize;
-}
-
-impl<'n, 'e, 'z, T: ?Sized> AnyArg<'n, 'e> for &'z T
-where
- T: AnyArg<'n, 'e> + 'z,
-{
- fn name(&self) -> &'n str {
- (*self).name()
- }
- fn overrides(&self) -> Option<&[&'e str]> {
- (*self).overrides()
- }
- fn aliases(&self) -> Option<Vec<&'e str>> {
- (*self).aliases()
- }
- fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> {
- (*self).requires()
- }
- fn blacklist(&self) -> Option<&[&'e str]> {
- (*self).blacklist()
- }
- fn required_unless(&self) -> Option<&[&'e str]> {
- (*self).required_unless()
- }
- fn is_set(&self, a: ArgSettings) -> bool {
- (*self).is_set(a)
- }
- fn set(&mut self, _: ArgSettings) {
- panic!(INTERNAL_ERROR_MSG)
- }
- fn has_switch(&self) -> bool {
- (*self).has_switch()
- }
- fn max_vals(&self) -> Option<u64> {
- (*self).max_vals()
- }
- fn min_vals(&self) -> Option<u64> {
- (*self).min_vals()
- }
- fn num_vals(&self) -> Option<u64> {
- (*self).num_vals()
- }
- fn possible_vals(&self) -> Option<&[&'e str]> {
- (*self).possible_vals()
- }
- fn validator(&self) -> Option<&Rc<Fn(String) -> Result<(), String>>> {
- (*self).validator()
- }
- fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> Result<(), OsString>>> {
- (*self).validator_os()
- }
- fn short(&self) -> Option<char> {
- (*self).short()
- }
- fn long(&self) -> Option<&'e str> {
- (*self).long()
- }
- fn val_delim(&self) -> Option<char> {
- (*self).val_delim()
- }
- fn takes_value(&self) -> bool {
- (*self).takes_value()
- }
- fn val_names(&self) -> Option<&VecMap<&'e str>> {
- (*self).val_names()
- }
- fn help(&self) -> Option<&'e str> {
- (*self).help()
- }
- fn long_help(&self) -> Option<&'e str> {
- (*self).long_help()
- }
- fn default_val(&self) -> Option<&'e OsStr> {
- (*self).default_val()
- }
- fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> {
- (*self).default_vals_ifs()
- }
- fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> {
- (*self).env()
- }
- fn longest_filter(&self) -> bool {
- (*self).longest_filter()
- }
- fn val_terminator(&self) -> Option<&'e str> {
- (*self).val_terminator()
- }
-}
diff --git a/src/args/arg.rs b/src/args/arg.rs
deleted file mode 100644
index ce578e0..0000000
--- a/src/args/arg.rs
+++ /dev/null
@@ -1,3959 +0,0 @@
-#[cfg(any(target_os = "windows", target_arch = "wasm32"))]
-use osstringext::OsStrExt3;
-#[cfg(feature = "yaml")]
-use std::collections::BTreeMap;
-use std::env;
-use std::ffi::{OsStr, OsString};
-#[cfg(not(any(target_os = "windows", target_arch = "wasm32")))]
-use std::os::unix::ffi::OsStrExt;
-use std::rc::Rc;
-
-use map::VecMap;
-#[cfg(feature = "yaml")]
-use yaml_rust::Yaml;
-
-use args::arg_builder::{Base, Switched, Valued};
-use args::settings::ArgSettings;
-use usage_parser::UsageParser;
-
-/// The abstract representation of a command line argument. Used to set all the options and
-/// relationships that define a valid argument for the program.
-///
-/// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options
-/// manually, or using a usage string which is far less verbose but has fewer options. You can also
-/// use a combination of the two methods to achieve the best of both worlds.
-///
-/// # Examples
-///
-/// ```rust
-/// # use clap::Arg;
-/// // Using the traditional builder pattern and setting each option manually
-/// let cfg = Arg::with_name("config")
-/// .short("c")
-/// .long("config")
-/// .takes_value(true)
-/// .value_name("FILE")
-/// .help("Provides a config file to myprog");
-/// // Using a usage string (setting a similar argument to the one above)
-/// let input = Arg::from_usage("-i, --input=[FILE] 'Provides an input file to the program'");
-/// ```
-/// [`Arg`]: ./struct.Arg.html
-#[allow(missing_debug_implementations)]
-#[derive(Default, Clone)]
-pub struct Arg<'a, 'b>
-where
- 'a: 'b,
-{
- #[doc(hidden)]
- pub b: Base<'a, 'b>,
- #[doc(hidden)]
- pub s: Switched<'b>,
- #[doc(hidden)]
- pub v: Valued<'a, 'b>,
- #[doc(hidden)]
- pub index: Option<u64>,
- #[doc(hidden)]
- pub r_ifs: Option<Vec<(&'a str, &'b str)>>,
-}
-
-impl<'a, 'b> Arg<'a, 'b> {
- /// Creates a new instance of [`Arg`] using a unique string name. The name will be used to get
- /// information about whether or not the argument was used at runtime, get values, set
- /// relationships with other args, etc..
- ///
- /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::takes_value(true)`])
- /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also
- /// be displayed when the user prints the usage/help information of the program.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("config")
- /// # ;
- /// ```
- /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
- /// [`Arg`]: ./struct.Arg.html
- pub fn with_name(n: &'a str) -> Self {
- Arg {
- b: Base::new(n),
- ..Default::default()
- }
- }
-
- /// Creates a new instance of [`Arg`] from a .yml (YAML) file.
- ///
- /// # Examples
- ///
- /// ```ignore
- /// # #[macro_use]
- /// # extern crate clap;
- /// # use clap::Arg;
- /// # fn main() {
- /// let yml = load_yaml!("arg.yml");
- /// let arg = Arg::from_yaml(yml);
- /// # }
- /// ```
- /// [`Arg`]: ./struct.Arg.html
- #[cfg(feature = "yaml")]
- pub fn from_yaml(y: &BTreeMap<Yaml, Yaml>) -> Arg {
- // We WANT this to panic on error...so expect() is good.
- let name_yml = y.keys().nth(0).unwrap();
- let name_str = name_yml.as_str().unwrap();
- let mut a = Arg::with_name(name_str);
- let arg_settings = y.get(name_yml).unwrap().as_hash().unwrap();
-
- for (k, v) in arg_settings.iter() {
- a = match k.as_str().unwrap() {
- "short" => yaml_to_str!(a, v, short),
- "long" => yaml_to_str!(a, v, long),
- "aliases" => yaml_vec_or_str!(v, a, alias),
- "help" => yaml_to_str!(a, v, help),
- "long_help" => yaml_to_str!(a, v, long_help),
- "required" => yaml_to_bool!(a, v, required),
- "required_if" => yaml_tuple2!(a, v, required_if),
- "required_ifs" => yaml_tuple2!(a, v, required_if),
- "takes_value" => yaml_to_bool!(a, v, takes_value),
- "index" => yaml_to_u64!(a, v, index),
- "global" => yaml_to_bool!(a, v, global),
- "multiple" => yaml_to_bool!(a, v, multiple),
- "hidden" => yaml_to_bool!(a, v, hidden),
- "next_line_help" => yaml_to_bool!(a, v, next_line_help),
- "empty_values" => yaml_to_bool!(a, v, empty_values),
- "group" => yaml_to_str!(a, v, group),
- "number_of_values" => yaml_to_u64!(a, v, number_of_values),
- "max_values" => yaml_to_u64!(a, v, max_values),
- "min_values" => yaml_to_u64!(a, v, min_values),
- "value_name" => yaml_to_str!(a, v, value_name),
- "use_delimiter" => yaml_to_bool!(a, v, use_delimiter),
- "allow_hyphen_values" => yaml_to_bool!(a, v, allow_hyphen_values),
- "last" => yaml_to_bool!(a, v, last),
- "require_delimiter" => yaml_to_bool!(a, v, require_delimiter),
- "value_delimiter" => yaml_to_str!(a, v, value_delimiter),
- "required_unless" => yaml_to_str!(a, v, required_unless),
- "display_order" => yaml_to_usize!(a, v, display_order),
- "default_value" => yaml_to_str!(a, v, default_value),
- "default_value_if" => yaml_tuple3!(a, v, default_value_if),
- "default_value_ifs" => yaml_tuple3!(a, v, default_value_if),
- "env" => yaml_to_str!(a, v, env),
- "value_names" => yaml_vec_or_str!(v, a, value_name),
- "groups" => yaml_vec_or_str!(v, a, group),
- "requires" => yaml_vec_or_str!(v, a, requires),
- "requires_if" => yaml_tuple2!(a, v, requires_if),
- "requires_ifs" => yaml_tuple2!(a, v, requires_if),
- "conflicts_with" => yaml_vec_or_str!(v, a, conflicts_with),
- "overrides_with" => yaml_vec_or_str!(v, a, overrides_with),
- "possible_values" => yaml_vec_or_str!(v, a, possible_value),
- "case_insensitive" => yaml_to_bool!(a, v, case_insensitive),
- "required_unless_one" => yaml_vec_or_str!(v, a, required_unless),
- "required_unless_all" => {
- a = yaml_vec_or_str!(v, a, required_unless);
- a.setb(ArgSettings::RequiredUnlessAll);
- a
- }
- s => panic!(
- "Unknown Arg setting '{}' in YAML file for arg '{}'",
- s, name_str
- ),
- }
- }
-
- a
- }
-
- /// Creates a new instance of [`Arg`] from a usage string. Allows creation of basic settings
- /// for the [`Arg`]. The syntax is flexible, but there are some rules to follow.
- ///
- /// **NOTE**: Not all settings may be set using the usage string method. Some properties are
- /// only available via the builder pattern.
- ///
- /// **NOTE**: Only ASCII values are officially supported in [`Arg::from_usage`] strings. Some
- /// UTF-8 codepoints may work just fine, but this is not guaranteed.
- ///
- /// # Syntax
- ///
- /// Usage strings typically following the form:
- ///
- /// ```notrust
- /// [explicit name] [short] [long] [value names] [help string]
- /// ```
- ///
- /// This is not a hard rule as the attributes can appear in other orders. There are also
- /// several additional sigils which denote additional settings. Below are the details of each
- /// portion of the string.
- ///
- /// ### Explicit Name
- ///
- /// 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:
- ///
- /// * Explicit Name (This always takes precedence when present)
- /// * Long
- /// * Short
- /// * Value Name
- ///
- /// `clap` determines explicit names as the first string of characters between either `[]` or
- /// `<>` where `[]` has the dual notation of meaning the argument is optional, and `<>` meaning
- /// the argument is required.
- ///
- /// Explicit names may be followed by:
- /// * The multiple denotation `...`
- ///
- /// Example explicit names as follows (`ename` for an optional argument, and `rname` for a
- /// required argument):
- ///
- /// ```notrust
- /// [ename] -s, --long 'some flag'
- /// <rname> -r, --longer 'some other flag'
- /// ```
- ///
- /// ### Short
- ///
- /// This is set by placing a single character after a leading `-`.
- ///
- /// Shorts may be followed by
- /// * The multiple denotation `...`
- /// * An optional comma `,` which is cosmetic only
- /// * Value notation
- ///
- /// Example shorts are as follows (`-s`, and `-r`):
- ///
- /// ```notrust
- /// -s, --long 'some flag'
- /// <rname> -r [val], --longer 'some option'
- /// ```
- ///
- /// ### Long
- ///
- /// This is set by placing a word (no spaces) after a leading `--`.
- ///
- /// Shorts may be followed by
- /// * The multiple denotation `...`
- /// * Value notation
- ///
- /// Example longs are as follows (`--some`, and `--rapid`):
- ///
- /// ```notrust
- /// -s, --some 'some flag'
- /// --rapid=[FILE] 'some option'
- /// ```
- ///
- /// ### Values (Value Notation)
- ///
- /// This is set by placing a word(s) between `[]` or `<>` optionally after `=` (although this
- /// is cosmetic only and does not affect functionality). If an explicit name has **not** been
- /// set, using `<>` will denote a required argument, and `[]` will denote an optional argument
- ///
- /// Values may be followed by
- /// * The multiple denotation `...`
- /// * More Value notation
- ///
- /// More than one value will also implicitly set the arguments number of values, i.e. having
- /// two values, `--option [val1] [val2]` specifies that in order for option to be satisified it
- /// must receive exactly two values
- ///
- /// Example values are as follows (`FILE`, and `SPEED`):
- ///
- /// ```notrust
- /// -s, --some [FILE] 'some option'
- /// --rapid=<SPEED>... 'some required multiple option'
- /// ```
- ///
- /// ### Help String
- ///
- /// The help string is denoted between a pair of single quotes `''` and may contain any
- /// characters.
- ///
- /// Example help strings are as follows:
- ///
- /// ```notrust
- /// -s, --some [FILE] 'some option'
- /// --rapid=<SPEED>... 'some required multiple option'
- /// ```
- ///
- /// ### Additional Sigils
- ///
- /// Multiple notation `...` (three consecutive dots/periods) specifies that this argument may
- /// be used multiple times. Do not confuse multiple occurrences (`...`) with multiple values.
- /// `--option val1 val2` is a single occurrence with multiple values. `--flag --flag` is
- /// multiple occurrences (and then you can obviously have instances of both as well)
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// App::new("prog")
- /// .args(&[
- /// Arg::from_usage("--config <FILE> 'a required file for the configuration and no short'"),
- /// Arg::from_usage("-d, --debug... 'turns on debugging information and allows multiples'"),
- /// Arg::from_usage("[input] 'an optional input file to use'")
- /// ])
- /// # ;
- /// ```
- /// [`Arg`]: ./struct.Arg.html
- /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage
- pub fn from_usage(u: &'a str) -> Self {
- let parser = UsageParser::from_usage(u);
- parser.parse()
- }
-
- /// Sets the short version of the argument without the preceding `-`.
- ///
- /// By default `clap` automatically assigns `V` and `h` to the auto-generated `version` and
- /// `help` arguments respectively. You may use the uppercase `V` or lowercase `h` for your own
- /// arguments, in which case `clap` simply will not assign those to the auto-generated
- /// `version` or `help` arguments.
- ///
- /// **NOTE:** Any leading `-` characters will be stripped, and only the first
- /// non `-` character will be used as the [`short`] version
- ///
- /// # Examples
- ///
- /// To set [`short`] use a single valid UTF-8 code point. If you supply a leading `-` such as
- /// `-c`, the `-` will be stripped.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("config")
- /// .short("c")
- /// # ;
- /// ```
- ///
- /// Setting [`short`] allows using the argument via a single hyphen (`-`) such as `-c`
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("config")
- /// .short("c"))
- /// .get_matches_from(vec![
- /// "prog", "-c"
- /// ]);
- ///
- /// assert!(m.is_present("config"));
- /// ```
- /// [`short`]: ./struct.Arg.html#method.short
- pub fn short<S: AsRef<str>>(mut self, s: S) -> Self {
- self.s.short = s.as_ref().trim_left_matches(|c| c == '-').chars().nth(0);
- self
- }
-
- /// Sets the long version of the argument without the preceding `--`.
- ///
- /// By default `clap` automatically assigns `version` and `help` to the auto-generated
- /// `version` and `help` arguments respectively. You may use the word `version` or `help` for
- /// the long form of your own arguments, in which case `clap` simply will not assign those to
- /// the auto-generated `version` or `help` arguments.
- ///
- /// **NOTE:** Any leading `-` characters will be stripped
- ///
- /// # Examples
- ///
- /// To set `long` use a word containing valid UTF-8 codepoints. If you supply a double leading
- /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however,
- /// will *not* be stripped (i.e. `config-file` is allowed)
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("cfg")
- /// .long("config")
- /// # ;
- /// ```
- ///
- /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config`
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .long("config"))
- /// .get_matches_from(vec![
- /// "prog", "--config"
- /// ]);
- ///
- /// assert!(m.is_present("cfg"));
- /// ```
- pub fn long(mut self, l: &'b str) -> Self {
- self.s.long = Some(l.trim_left_matches(|c| c == '-'));
- self
- }
-
- /// Allows adding a [`Arg`] alias, which function as "hidden" arguments that
- /// automatically dispatch as if this argument was used. This is more efficient, and easier
- /// than creating multiple hidden arguments as one only needs to check for the existence of
- /// this command, and not all variants.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("test")
- /// .long("test")
- /// .alias("alias")
- /// .takes_value(true))
- /// .get_matches_from(vec![
- /// "prog", "--alias", "cool"
- /// ]);
- /// assert!(m.is_present("test"));
- /// assert_eq!(m.value_of("test"), Some("cool"));
- /// ```
- /// [`Arg`]: ./struct.Arg.html
- pub fn alias<S: Into<&'b str>>(mut self, name: S) -> Self {
- if let Some(ref mut als) = self.s.aliases {
- als.push((name.into(), false));
- } else {
- self.s.aliases = Some(vec![(name.into(), false)]);
- }
- self
- }
-
- /// Allows adding [`Arg`] aliases, which function as "hidden" arguments that
- /// automatically dispatch as if this argument was used. This is more efficient, and easier
- /// than creating multiple hidden subcommands as one only needs to check for the existence of
- /// this command, and not all variants.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("test")
- /// .long("test")
- /// .aliases(&["do-stuff", "do-tests", "tests"])
- /// .help("the file to add")
- /// .required(false))
- /// .get_matches_from(vec![
- /// "prog", "--do-tests"
- /// ]);
- /// assert!(m.is_present("test"));
- /// ```
- /// [`Arg`]: ./struct.Arg.html
- pub fn aliases(mut self, names: &[&'b str]) -> Self {
- if let Some(ref mut als) = self.s.aliases {
- for n in names {
- als.push((n, false));
- }
- } else {
- self.s.aliases = Some(names.iter().map(|n| (*n, false)).collect::<Vec<_>>());
- }
- self
- }
-
- /// Allows adding a [`Arg`] alias that functions exactly like those defined with
- /// [`Arg::alias`], except that they are visible inside the help message.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("test")
- /// .visible_alias("something-awesome")
- /// .long("test")
- /// .takes_value(true))
- /// .get_matches_from(vec![
- /// "prog", "--something-awesome", "coffee"
- /// ]);
- /// assert!(m.is_present("test"));
- /// assert_eq!(m.value_of("test"), Some("coffee"));
- /// ```
- /// [`Arg`]: ./struct.Arg.html
- /// [`App::alias`]: ./struct.Arg.html#method.alias
- pub fn visible_alias<S: Into<&'b str>>(mut self, name: S) -> Self {
- if let Some(ref mut als) = self.s.aliases {
- als.push((name.into(), true));
- } else {
- self.s.aliases = Some(vec![(name.into(), true)]);
- }
- self
- }
-
- /// Allows adding multiple [`Arg`] aliases that functions exactly like those defined
- /// with [`Arg::aliases`], except that they are visible inside the help message.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("test")
- /// .long("test")
- /// .visible_aliases(&["something", "awesome", "cool"]))
- /// .get_matches_from(vec![
- /// "prog", "--awesome"
- /// ]);
- /// assert!(m.is_present("test"));
- /// ```
- /// [`Arg`]: ./struct.Arg.html
- /// [`App::aliases`]: ./struct.Arg.html#method.aliases
- pub fn visible_aliases(mut self, names: &[&'b str]) -> Self {
- if let Some(ref mut als) = self.s.aliases {
- for n in names {
- als.push((n, true));
- }
- } else {
- self.s.aliases = Some(names.iter().map(|n| (*n, true)).collect::<Vec<_>>());
- }
- self
- }
-
- /// Sets the short help text of the argument that will be displayed to the user when they print
- /// the help information with `-h`. Typically, this is a short (one line) description of the
- /// arg.
- ///
- /// **NOTE:** If only `Arg::help` is provided, and not [`Arg::long_help`] but the user requests
- /// `--help` clap will still display the contents of `help` appropriately
- ///
- /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise
- ///
- /// # Examples
- ///
- /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
- /// include a newline in the help text and have the following text be properly aligned with all
- /// the other help text.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("config")
- /// .help("The config file used by the myprog")
- /// # ;
- /// ```
- ///
- /// Setting `help` displays a short message to the side of the argument when the user passes
- /// `-h` or `--help` (by default).
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .long("config")
- /// .help("Some help text describing the --config arg"))
- /// .get_matches_from(vec![
- /// "prog", "--help"
- /// ]);
- /// ```
- ///
- /// The above example displays
- ///
- /// ```notrust
- /// helptest
- ///
- /// USAGE:
- /// helptest [FLAGS]
- ///
- /// FLAGS:
- /// --config Some help text describing the --config arg
- /// -h, --help Prints help information
- /// -V, --version Prints version information
- /// ```
- /// [`Arg::long_help`]: ./struct.Arg.html#method.long_help
- pub fn help(mut self, h: &'b str) -> Self {
- self.b.help = Some(h);
- self
- }
-
- /// Sets the long help text of the argument that will be displayed to the user when they print
- /// the help information with `--help`. Typically this a more detailed (multi-line) message
- /// that describes the arg.
- ///
- /// **NOTE:** If only `long_help` is provided, and not [`Arg::help`] but the user requests `-h`
- /// clap will still display the contents of `long_help` appropriately
- ///
- /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise
- ///
- /// # Examples
- ///
- /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
- /// include a newline in the help text and have the following text be properly aligned with all
- /// the other help text.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("config")
- /// .long_help(
- /// "The config file used by the myprog must be in JSON format
- /// with only valid keys and may not contain other nonsense
- /// that cannot be read by this program. Obviously I'm going on
- /// and on, so I'll stop now.")
- /// # ;
- /// ```
- ///
- /// Setting `help` displays a short message to the side of the argument when the user passes
- /// `-h` or `--help` (by default).
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .long("config")
- /// .long_help(
- /// "The config file used by the myprog must be in JSON format
- /// with only valid keys and may not contain other nonsense
- /// that cannot be read by this program. Obviously I'm going on
- /// and on, so I'll stop now."))
- /// .get_matches_from(vec![
- /// "prog", "--help"
- /// ]);
- /// ```
- ///
- /// The above example displays
- ///
- /// ```notrust
- /// helptest
- ///
- /// USAGE:
- /// helptest [FLAGS]
- ///
- /// FLAGS:
- /// --config
- /// The config file used by the myprog must be in JSON format
- /// with only valid keys and may not contain other nonsense
- /// that cannot be read by this program. Obviously I'm going on
- /// and on, so I'll stop now.
- ///
- /// -h, --help
- /// Prints help information
- ///
- /// -V, --version
- /// Prints version information
- /// ```
- /// [`Arg::help`]: ./struct.Arg.html#method.help
- pub fn long_help(mut self, h: &'b str) -> Self {
- self.b.long_help = Some(h);
- self
- }
-
- /// Specifies that this arg is the last, or final, positional argument (i.e. has the highest
- /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args --
- /// last_arg`). Even, if no other arguments are left to parse, if the user omits the `--` syntax
- /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also
- /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with
- /// the `--` syntax is otherwise not possible.
- ///
- /// **NOTE:** This will change the usage string to look like `$ prog [FLAGS] [-- <ARG>]` if
- /// `ARG` is marked as `.last(true)`.
- ///
- /// **NOTE:** This setting will imply [`AppSettings::DontCollapseArgsInUsage`] because failing
- /// to set this can make the usage string very confusing.
- ///
- /// **NOTE**: This setting only applies to positional arguments, and has no affect on FLAGS /
- /// OPTIONS
- ///
- /// **CAUTION:** Setting an argument to `.last(true)` *and* having child subcommands is not
- /// recommended with the exception of *also* using [`AppSettings::ArgsNegateSubcommands`]
- /// (or [`AppSettings::SubcommandsNegateReqs`] if the argument marked `.last(true)` is also
- /// marked [`.required(true)`])
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("args")
- /// .last(true)
- /// # ;
- /// ```
- ///
- /// Setting [`Arg::last(true)`] ensures the arg has the highest [index] of all positional args
- /// and requires that the `--` syntax be used to access it early.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("first"))
- /// .arg(Arg::with_name("second"))
- /// .arg(Arg::with_name("third").last(true))
- /// .get_matches_from_safe(vec![
- /// "prog", "one", "--", "three"
- /// ]);
- ///
- /// assert!(res.is_ok());
- /// let m = res.unwrap();
- /// assert_eq!(m.value_of("third"), Some("three"));
- /// assert!(m.value_of("second").is_none());
- /// ```
- ///
- /// Even if the positional argument marked `.last(true)` is the only argument left to parse,
- /// failing to use the `--` syntax results in an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("first"))
- /// .arg(Arg::with_name("second"))
- /// .arg(Arg::with_name("third").last(true))
- /// .get_matches_from_safe(vec![
- /// "prog", "one", "two", "three"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
- /// ```
- /// [`Arg::last(true)`]: ./struct.Arg.html#method.last
- /// [index]: ./struct.Arg.html#method.index
- /// [`AppSettings::DontCollapseArgsInUsage`]: ./enum.AppSettings.html#variant.DontCollapseArgsInUsage
- /// [`AppSettings::ArgsNegateSubcommands`]: ./enum.AppSettings.html#variant.ArgsNegateSubcommands
- /// [`AppSettings::SubcommandsNegateReqs`]: ./enum.AppSettings.html#variant.SubcommandsNegateReqs
- /// [`.required(true)`]: ./struct.Arg.html#method.required
- /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument
- pub fn last(self, l: bool) -> Self {
- if l {
- self.set(ArgSettings::Last)
- } else {
- self.unset(ArgSettings::Last)
- }
- }
-
- /// Sets whether or not the argument is required by default. Required by default means it is
- /// required, when no other conflicting rules have been evaluated. Conflicting rules take
- /// precedence over being required. **Default:** `false`
- ///
- /// **NOTE:** Flags (i.e. not positional, or arguments that take values) cannot be required by
- /// default. This is simply because if a flag should be required, it should simply be implied
- /// as no additional information is required from user. Flags by their very nature are simply
- /// yes/no, or true/false.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("config")
- /// .required(true)
- /// # ;
- /// ```
- ///
- /// Setting [`Arg::required(true)`] requires that the argument be used at runtime.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .required(true)
- /// .takes_value(true)
- /// .long("config"))
- /// .get_matches_from_safe(vec![
- /// "prog", "--config", "file.conf"
- /// ]);
- ///
- /// assert!(res.is_ok());
- /// ```
- ///
- /// Setting [`Arg::required(true)`] and *not* supplying that argument is an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .required(true)
- /// .takes_value(true)
- /// .long("config"))
- /// .get_matches_from_safe(vec![
- /// "prog"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
- /// ```
- /// [`Arg::required(true)`]: ./struct.Arg.html#method.required
- pub fn required(self, r: bool) -> Self {
- if r {
- self.set(ArgSettings::Required)
- } else {
- self.unset(ArgSettings::Required)
- }
- }
-
- /// Requires that options use the `--option=val` syntax (i.e. an equals between the option and
- /// associated value) **Default:** `false`
- ///
- /// **NOTE:** This setting also removes the default of allowing empty values and implies
- /// [`Arg::empty_values(false)`].
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("config")
- /// .long("config")
- /// .takes_value(true)
- /// .require_equals(true)
- /// # ;
- /// ```
- ///
- /// Setting [`Arg::require_equals(true)`] requires that the option have an equals sign between
- /// it and the associated value.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .require_equals(true)
- /// .takes_value(true)
- /// .long("config"))
- /// .get_matches_from_safe(vec![
- /// "prog", "--config=file.conf"
- /// ]);
- ///
- /// assert!(res.is_ok());
- /// ```
- ///
- /// Setting [`Arg::require_equals(true)`] and *not* supplying the equals will cause an error
- /// unless [`Arg::empty_values(true)`] is set.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .require_equals(true)
- /// .takes_value(true)
- /// .long("config"))
- /// .get_matches_from_safe(vec![
- /// "prog", "--config", "file.conf"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue);
- /// ```
- /// [`Arg::require_equals(true)`]: ./struct.Arg.html#method.require_equals
- /// [`Arg::empty_values(true)`]: ./struct.Arg.html#method.empty_values
- /// [`Arg::empty_values(false)`]: ./struct.Arg.html#method.empty_values
- pub fn require_equals(mut self, r: bool) -> Self {
- if r {
- self.unsetb(ArgSettings::EmptyValues);
- self.set(ArgSettings::RequireEquals)
- } else {
- self.unset(ArgSettings::RequireEquals)
- }
- }
-
- /// Allows values which start with a leading hyphen (`-`)
- ///
- /// **WARNING**: Take caution when using this setting combined with [`Arg::multiple(true)`], as
- /// this becomes ambiguous `$ prog --arg -- -- val`. All three `--, --, val` will be values
- /// when the user may have thought the second `--` would constitute the normal, "Only
- /// positional args follow" idiom. To fix this, consider using [`Arg::number_of_values(1)`]
- ///
- /// **WARNING**: When building your CLIs, consider the effects of allowing leading hyphens and
- /// the user passing in a value that matches a valid short. For example `prog -opt -F` where
- /// `-F` is supposed to be a value, yet `-F` is *also* a valid short for another arg. Care should
- /// should be taken when designing these args. This is compounded by the ability to "stack"
- /// short args. I.e. if `-val` is supposed to be a value, but `-v`, `-a`, and `-l` are all valid
- /// shorts.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("pattern")
- /// .allow_hyphen_values(true)
- /// # ;
- /// ```
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("pat")
- /// .allow_hyphen_values(true)
- /// .takes_value(true)
- /// .long("pattern"))
- /// .get_matches_from(vec![
- /// "prog", "--pattern", "-file"
- /// ]);
- ///
- /// assert_eq!(m.value_of("pat"), Some("-file"));
- /// ```
- ///
- /// Not setting [`Arg::allow_hyphen_values(true)`] and supplying a value which starts with a
- /// hyphen is an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("pat")
- /// .takes_value(true)
- /// .long("pattern"))
- /// .get_matches_from_safe(vec![
- /// "prog", "--pattern", "-file"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
- /// ```
- /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values
- /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
- /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values
- pub fn allow_hyphen_values(self, a: bool) -> Self {
- if a {
- self.set(ArgSettings::AllowLeadingHyphen)
- } else {
- self.unset(ArgSettings::AllowLeadingHyphen)
- }
- }
- /// Sets an arg that override this arg's required setting. (i.e. this arg will be required
- /// unless this other argument is present).
- ///
- /// **Pro Tip:** Using [`Arg::required_unless`] implies [`Arg::required`] and is therefore not
- /// mandatory to also set.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("config")
- /// .required_unless("debug")
- /// # ;
- /// ```
- ///
- /// Setting [`Arg::required_unless(name)`] requires that the argument be used at runtime
- /// *unless* `name` is present. In the following example, the required argument is *not*
- /// provided, but it's not an error because the `unless` arg has been supplied.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .required_unless("dbg")
- /// .takes_value(true)
- /// .long("config"))
- /// .arg(Arg::with_name("dbg")
- /// .long("debug"))
- /// .get_matches_from_safe(vec![
- /// "prog", "--debug"
- /// ]);
- ///
- /// assert!(res.is_ok());
- /// ```
- ///
- /// Setting [`Arg::required_unless(name)`] and *not* supplying `name` or this arg is an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .required_unless("dbg")
- /// .takes_value(true)
- /// .long("config"))
- /// .arg(Arg::with_name("dbg")
- /// .long("debug"))
- /// .get_matches_from_safe(vec![
- /// "prog"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
- /// ```
- /// [`Arg::required_unless`]: ./struct.Arg.html#method.required_unless
- /// [`Arg::required`]: ./struct.Arg.html#method.required
- /// [`Arg::required_unless(name)`]: ./struct.Arg.html#method.required_unless
- pub fn required_unless(mut self, name: &'a str) -> Self {
- if let Some(ref mut vec) = self.b.r_unless {
- vec.push(name);
- } else {
- self.b.r_unless = Some(vec![name]);
- }
- self.required(true)
- }
-
- /// Sets args that override this arg's required setting. (i.e. this arg will be required unless
- /// all these other arguments are present).
- ///
- /// **NOTE:** If you wish for this argument to only be required if *one of* these args are
- /// present see [`Arg::required_unless_one`]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("config")
- /// .required_unless_all(&["cfg", "dbg"])
- /// # ;
- /// ```
- ///
- /// Setting [`Arg::required_unless_all(names)`] requires that the argument be used at runtime
- /// *unless* *all* the args in `names` are present. In the following example, the required
- /// argument is *not* provided, but it's not an error because all the `unless` args have been
- /// supplied.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .required_unless_all(&["dbg", "infile"])
- /// .takes_value(true)
- /// .long("config"))
- /// .arg(Arg::with_name("dbg")
- /// .long("debug"))
- /// .arg(Arg::with_name("infile")
- /// .short("i")
- /// .takes_value(true))
- /// .get_matches_from_safe(vec![
- /// "prog", "--debug", "-i", "file"
- /// ]);
- ///
- /// assert!(res.is_ok());
- /// ```
- ///
- /// Setting [`Arg::required_unless_all(names)`] and *not* supplying *all* of `names` or this
- /// arg is an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .required_unless_all(&["dbg", "infile"])
- /// .takes_value(true)
- /// .long("config"))
- /// .arg(Arg::with_name("dbg")
- /// .long("debug"))
- /// .arg(Arg::with_name("infile")
- /// .short("i")
- /// .takes_value(true))
- /// .get_matches_from_safe(vec![
- /// "prog"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
- /// ```
- /// [`Arg::required_unless_one`]: ./struct.Arg.html#method.required_unless_one
- /// [`Arg::required_unless_all(names)`]: ./struct.Arg.html#method.required_unless_all
- pub fn required_unless_all(mut self, names: &[&'a str]) -> Self {
- if let Some(ref mut vec) = self.b.r_unless {
- for s in names {
- vec.push(s);
- }
- } else {
- self.b.r_unless = Some(names.iter().map(|s| *s).collect::<Vec<_>>());
- }
- self.setb(ArgSettings::RequiredUnlessAll);
- self.required(true)
- }
-
- /// Sets args that override this arg's [required] setting. (i.e. this arg will be required
- /// unless *at least one of* these other arguments are present).
- ///
- /// **NOTE:** If you wish for this argument to only be required if *all of* these args are
- /// present see [`Arg::required_unless_all`]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("config")
- /// .required_unless_all(&["cfg", "dbg"])
- /// # ;
- /// ```
- ///
- /// Setting [`Arg::required_unless_one(names)`] requires that the argument be used at runtime
- /// *unless* *at least one of* the args in `names` are present. In the following example, the
- /// required argument is *not* provided, but it's not an error because one the `unless` args
- /// have been supplied.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .required_unless_one(&["dbg", "infile"])
- /// .takes_value(true)
- /// .long("config"))
- /// .arg(Arg::with_name("dbg")
- /// .long("debug"))
- /// .arg(Arg::with_name("infile")
- /// .short("i")
- /// .takes_value(true))
- /// .get_matches_from_safe(vec![
- /// "prog", "--debug"
- /// ]);
- ///
- /// assert!(res.is_ok());
- /// ```
- ///
- /// Setting [`Arg::required_unless_one(names)`] and *not* supplying *at least one of* `names`
- /// or this arg is an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .required_unless_one(&["dbg", "infile"])
- /// .takes_value(true)
- /// .long("config"))
- /// .arg(Arg::with_name("dbg")
- /// .long("debug"))
- /// .arg(Arg::with_name("infile")
- /// .short("i")
- /// .takes_value(true))
- /// .get_matches_from_safe(vec![
- /// "prog"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
- /// ```
- /// [required]: ./struct.Arg.html#method.required
- /// [`Arg::required_unless_one(names)`]: ./struct.Arg.html#method.required_unless_one
- /// [`Arg::required_unless_all`]: ./struct.Arg.html#method.required_unless_all
- pub fn required_unless_one(mut self, names: &[&'a str]) -> Self {
- if let Some(ref mut vec) = self.b.r_unless {
- for s in names {
- vec.push(s);
- }
- } else {
- self.b.r_unless = Some(names.iter().map(|s| *s).collect::<Vec<_>>());
- }
- self.required(true)
- }
-
- /// Sets a conflicting argument by name. I.e. when using this argument,
- /// the following argument can't be present and vice versa.
- ///
- /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
- /// only need to be set for one of the two arguments, they do not need to be set for each.
- ///
- /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
- /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need
- /// need to also do B.conflicts_with(A))
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("config")
- /// .conflicts_with("debug")
- /// # ;
- /// ```
- ///
- /// Setting conflicting argument, and having both arguments present at runtime is an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .takes_value(true)
- /// .conflicts_with("debug")
- /// .long("config"))
- /// .arg(Arg::with_name("debug")
- /// .long("debug"))
- /// .get_matches_from_safe(vec![
- /// "prog", "--debug", "--config", "file.conf"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict);
- /// ```
- pub fn conflicts_with(mut self, name: &'a str) -> Self {
- if let Some(ref mut vec) = self.b.blacklist {
- vec.push(name);
- } else {
- self.b.blacklist = Some(vec![name]);
- }
- self
- }
-
- /// The same as [`Arg::conflicts_with`] but allows specifying multiple two-way conlicts per
- /// argument.
- ///
- /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
- /// only need to be set for one of the two arguments, they do not need to be set for each.
- ///
- /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
- /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need
- /// need to also do B.conflicts_with(A))
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("config")
- /// .conflicts_with_all(&["debug", "input"])
- /// # ;
- /// ```
- ///
- /// Setting conflicting argument, and having any of the arguments present at runtime with a
- /// conflicting argument is an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .takes_value(true)
- /// .conflicts_with_all(&["debug", "input"])
- /// .long("config"))
- /// .arg(Arg::with_name("debug")
- /// .long("debug"))
- /// .arg(Arg::with_name("input")
- /// .index(1))
- /// .get_matches_from_safe(vec![
- /// "prog", "--config", "file.conf", "file.txt"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict);
- /// ```
- /// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with
- pub fn conflicts_with_all(mut self, names: &[&'a str]) -> Self {
- if let Some(ref mut vec) = self.b.blacklist {
- for s in names {
- vec.push(s);
- }
- } else {
- self.b.blacklist = Some(names.iter().map(|s| *s).collect::<Vec<_>>());
- }
- self
- }
-
- /// Sets a overridable argument by name. I.e. this argument and the following argument
- /// will override each other in POSIX style (whichever argument was specified at runtime
- /// **last** "wins")
- ///
- /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
- /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
- ///
- /// **WARNING:** Positional arguments cannot override themselves (or we would never be able
- /// to advance to the next positional). If a positional agument lists itself as an override,
- /// it is simply ignored.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::from_usage("-f, --flag 'some flag'")
- /// .conflicts_with("debug"))
- /// .arg(Arg::from_usage("-d, --debug 'other flag'"))
- /// .arg(Arg::from_usage("-c, --color 'third flag'")
- /// .overrides_with("flag"))
- /// .get_matches_from(vec![
- /// "prog", "-f", "-d", "-c"]);
- /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color
- ///
- /// assert!(m.is_present("color"));
- /// assert!(m.is_present("debug")); // even though flag conflicts with debug, it's as if flag
- /// // was never used because it was overridden with color
- /// assert!(!m.is_present("flag"));
- /// ```
- /// Care must be taken when using this setting, and having an arg override with itself. This
- /// is common practice when supporting things like shell aliases, config files, etc.
- /// However, when combined with multiple values, it can get dicy.
- /// Here is how clap handles such situations:
- ///
- /// When a flag overrides itself, it's as if the flag was only ever used once (essentially
- /// preventing a "Unexpected multiple usage" error):
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("posix")
- /// .arg(Arg::from_usage("--flag 'some flag'").overrides_with("flag"))
- /// .get_matches_from(vec!["posix", "--flag", "--flag"]);
- /// assert!(m.is_present("flag"));
- /// assert_eq!(m.occurrences_of("flag"), 1);
- /// ```
- /// Making a arg `multiple(true)` and override itself is essentially meaningless. Therefore
- /// clap ignores an override of self if it's a flag and it already accepts multiple occurrences.
- ///
- /// ```
- /// # use clap::{App, Arg};
- /// let m = App::new("posix")
- /// .arg(Arg::from_usage("--flag... 'some flag'").overrides_with("flag"))
- /// .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]);
- /// assert!(m.is_present("flag"));
- /// assert_eq!(m.occurrences_of("flag"), 4);
- /// ```
- /// Now notice with options (which *do not* set `multiple(true)`), it's as if only the last
- /// occurrence happened.
- ///
- /// ```
- /// # use clap::{App, Arg};
- /// let m = App::new("posix")
- /// .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("opt"))
- /// .get_matches_from(vec!["", "--opt=some", "--opt=other"]);
- /// assert!(m.is_present("opt"));
- /// assert_eq!(m.occurrences_of("opt"), 1);
- /// assert_eq!(m.value_of("opt"), Some("other"));
- /// ```
- ///
- /// Just like flags, options with `multiple(true)` set, will ignore the "override self" setting.
- ///
- /// ```
- /// # use clap::{App, Arg};
- /// let m = App::new("posix")
- /// .arg(Arg::from_usage("--opt [val]... 'some option'")
- /// .overrides_with("opt"))
- /// .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]);
- /// assert!(m.is_present("opt"));
- /// assert_eq!(m.occurrences_of("opt"), 2);
- /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["first", "over", "other", "val"]);
- /// ```
- ///
- /// A safe thing to do if you'd like to support an option which supports multiple values, but
- /// also is "overridable" by itself, is to use `use_delimiter(false)` and *not* use
- /// `multiple(true)` while telling users to seperate values with a comma (i.e. `val1,val2`)
- ///
- /// ```
- /// # use clap::{App, Arg};
- /// let m = App::new("posix")
- /// .arg(Arg::from_usage("--opt [val] 'some option'")
- /// .overrides_with("opt")
- /// .use_delimiter(false))
- /// .get_matches_from(vec!["", "--opt=some,other", "--opt=one,two"]);
- /// assert!(m.is_present("opt"));
- /// assert_eq!(m.occurrences_of("opt"), 1);
- /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["one,two"]);
- /// ```
- pub fn overrides_with(mut self, name: &'a str) -> Self {
- if let Some(ref mut vec) = self.b.overrides {
- vec.push(name);
- } else {
- self.b.overrides = Some(vec![name]);
- }
- self
- }
-
- /// Sets multiple mutually overridable arguments by name. I.e. this argument and the following
- /// argument will override each other in POSIX style (whichever argument was specified at
- /// runtime **last** "wins")
- ///
- /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
- /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::from_usage("-f, --flag 'some flag'")
- /// .conflicts_with("color"))
- /// .arg(Arg::from_usage("-d, --debug 'other flag'"))
- /// .arg(Arg::from_usage("-c, --color 'third flag'")
- /// .overrides_with_all(&["flag", "debug"]))
- /// .get_matches_from(vec![
- /// "prog", "-f", "-d", "-c"]);
- /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color
- ///
- /// assert!(m.is_present("color")); // even though flag conflicts with color, it's as if flag
- /// // and debug were never used because they were overridden
- /// // with color
- /// assert!(!m.is_present("debug"));
- /// assert!(!m.is_present("flag"));
- /// ```
- pub fn overrides_with_all(mut self, names: &[&'a str]) -> Self {
- if let Some(ref mut vec) = self.b.overrides {
- for s in names {
- vec.push(s);
- }
- } else {
- self.b.overrides = Some(names.iter().map(|s| *s).collect::<Vec<_>>());
- }
- self
- }
-
- /// Sets an argument by name that is required when this one is present I.e. when
- /// using this argument, the following argument *must* be present.
- ///
- /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("config")
- /// .requires("input")
- /// # ;
- /// ```
- ///
- /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the
- /// defining argument is used. If the defining argument isn't used, the other argument isn't
- /// required
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .takes_value(true)
- /// .requires("input")
- /// .long("config"))
- /// .arg(Arg::with_name("input")
- /// .index(1))
- /// .get_matches_from_safe(vec![
- /// "prog"
- /// ]);
- ///
- /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required
- /// ```
- ///
- /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .takes_value(true)
- /// .requires("input")
- /// .long("config"))
- /// .arg(Arg::with_name("input")
- /// .index(1))
- /// .get_matches_from_safe(vec![
- /// "prog", "--config", "file.conf"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
- /// ```
- /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
- /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
- /// [override]: ./struct.Arg.html#method.overrides_with
- pub fn requires(mut self, name: &'a str) -> Self {
- if let Some(ref mut vec) = self.b.requires {
- vec.push((None, name));
- } else {
- let mut vec = vec![];
- vec.push((None, name));
- self.b.requires = Some(vec);
- }
- self
- }
-
- /// Allows a conditional requirement. The requirement will only become valid if this arg's value
- /// equals `val`.
- ///
- /// **NOTE:** If using YAML the values should be laid out as follows
- ///
- /// ```yaml
- /// requires_if:
- /// - [val, arg]
- /// ```
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("config")
- /// .requires_if("val", "arg")
- /// # ;
- /// ```
- ///
- /// Setting [`Arg::requires_if(val, arg)`] requires that the `arg` be used at runtime if the
- /// defining argument's value is equal to `val`. If the defining argument is anything other than
- /// `val`, the other argument isn't required.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .takes_value(true)
- /// .requires_if("my.cfg", "other")
- /// .long("config"))
- /// .arg(Arg::with_name("other"))
- /// .get_matches_from_safe(vec![
- /// "prog", "--config", "some.cfg"
- /// ]);
- ///
- /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required
- /// ```
- ///
- /// Setting [`Arg::requires_if(val, arg)`] and setting the value to `val` but *not* supplying
- /// `arg` is an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .takes_value(true)
- /// .requires_if("my.cfg", "input")
- /// .long("config"))
- /// .arg(Arg::with_name("input"))
- /// .get_matches_from_safe(vec![
- /// "prog", "--config", "my.cfg"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
- /// ```
- /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
- /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
- /// [override]: ./struct.Arg.html#method.overrides_with
- pub fn requires_if(mut self, val: &'b str, arg: &'a str) -> Self {
- if let Some(ref mut vec) = self.b.requires {
- vec.push((Some(val), arg));
- } else {
- self.b.requires = Some(vec![(Some(val), arg)]);
- }
- self
- }
-
- /// Allows multiple conditional requirements. The requirement will only become valid if this arg's value
- /// equals `val`.
- ///
- /// **NOTE:** If using YAML the values should be laid out as follows
- ///
- /// ```yaml
- /// requires_if:
- /// - [val, arg]
- /// - [val2, arg2]
- /// ```
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("config")
- /// .requires_ifs(&[
- /// ("val", "arg"),
- /// ("other_val", "arg2"),
- /// ])
- /// # ;
- /// ```
- ///
- /// Setting [`Arg::requires_ifs(&["val", "arg"])`] requires that the `arg` be used at runtime if the
- /// defining argument's value is equal to `val`. If the defining argument's value is anything other
- /// than `val`, `arg` isn't required.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .takes_value(true)
- /// .requires_ifs(&[
- /// ("special.conf", "opt"),
- /// ("other.conf", "other"),
- /// ])
- /// .long("config"))
- /// .arg(Arg::with_name("opt")
- /// .long("option")
- /// .takes_value(true))
- /// .arg(Arg::with_name("other"))
- /// .get_matches_from_safe(vec![
- /// "prog", "--config", "special.conf"
- /// ]);
- ///
- /// assert!(res.is_err()); // We used --config=special.conf so --option <val> is required
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
- /// ```
- /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
- /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
- /// [override]: ./struct.Arg.html#method.overrides_with
- pub fn requires_ifs(mut self, ifs: &[(&'b str, &'a str)]) -> Self {
- if let Some(ref mut vec) = self.b.requires {
- for &(val, arg) in ifs {
- vec.push((Some(val), arg));
- }
- } else {
- let mut vec = vec![];
- for &(val, arg) in ifs {
- vec.push((Some(val), arg));
- }
- self.b.requires = Some(vec);
- }
- self
- }
-
- /// Allows specifying that an argument is [required] conditionally. The requirement will only
- /// become valid if the specified `arg`'s value equals `val`.
- ///
- /// **NOTE:** If using YAML the values should be laid out as follows
- ///
- /// ```yaml
- /// required_if:
- /// - [arg, val]
- /// ```
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("config")
- /// .required_if("other_arg", "value")
- /// # ;
- /// ```
- ///
- /// Setting [`Arg::required_if(arg, val)`] makes this arg required if the `arg` is used at
- /// runtime and it's value is equal to `val`. If the `arg`'s value is anything other than `val`,
- /// this argument isn't required.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .takes_value(true)
- /// .required_if("other", "special")
- /// .long("config"))
- /// .arg(Arg::with_name("other")
- /// .long("other")
- /// .takes_value(true))
- /// .get_matches_from_safe(vec![
- /// "prog", "--other", "not-special"
- /// ]);
- ///
- /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required
- /// ```
- ///
- /// Setting [`Arg::required_if(arg, val)`] and having `arg` used with a value of `val` but *not*
- /// using this arg is an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .takes_value(true)
- /// .required_if("other", "special")
- /// .long("config"))
- /// .arg(Arg::with_name("other")
- /// .long("other")
- /// .takes_value(true))
- /// .get_matches_from_safe(vec![
- /// "prog", "--other", "special"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
- /// ```
- /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
- /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
- /// [required]: ./struct.Arg.html#method.required
- pub fn required_if(mut self, arg: &'a str, val: &'b str) -> Self {
- if let Some(ref mut vec) = self.r_ifs {
- vec.push((arg, val));
- } else {
- self.r_ifs = Some(vec![(arg, val)]);
- }
- self
- }
-
- /// Allows specifying that an argument is [required] based on multiple conditions. The
- /// conditions are set up in a `(arg, val)` style tuple. The requirement will only become valid
- /// if one of the specified `arg`'s value equals it's corresponding `val`.
- ///
- /// **NOTE:** If using YAML the values should be laid out as follows
- ///
- /// ```yaml
- /// required_if:
- /// - [arg, val]
- /// - [arg2, val2]
- /// ```
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("config")
- /// .required_ifs(&[
- /// ("extra", "val"),
- /// ("option", "spec")
- /// ])
- /// # ;
- /// ```
- ///
- /// Setting [`Arg::required_ifs(&[(arg, val)])`] makes this arg required if any of the `arg`s
- /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is
- /// anything other than `val`, this argument isn't required.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .required_ifs(&[
- /// ("extra", "val"),
- /// ("option", "spec")
- /// ])
- /// .takes_value(true)
- /// .long("config"))
- /// .arg(Arg::with_name("extra")
- /// .takes_value(true)
- /// .long("extra"))
- /// .arg(Arg::with_name("option")
- /// .takes_value(true)
- /// .long("option"))
- /// .get_matches_from_safe(vec![
- /// "prog", "--option", "other"
- /// ]);
- ///
- /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required
- /// ```
- ///
- /// Setting [`Arg::required_ifs(&[(arg, val)])`] and having any of the `arg`s used with it's
- /// value of `val` but *not* using this arg is an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .required_ifs(&[
- /// ("extra", "val"),
- /// ("option", "spec")
- /// ])
- /// .takes_value(true)
- /// .long("config"))
- /// .arg(Arg::with_name("extra")
- /// .takes_value(true)
- /// .long("extra"))
- /// .arg(Arg::with_name("option")
- /// .takes_value(true)
- /// .long("option"))
- /// .get_matches_from_safe(vec![
- /// "prog", "--option", "spec"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
- /// ```
- /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
- /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
- /// [required]: ./struct.Arg.html#method.required
- pub fn required_ifs(mut self, ifs: &[(&'a str, &'b str)]) -> Self {
- if let Some(ref mut vec) = self.r_ifs {
- for r_if in ifs {
- vec.push((r_if.0, r_if.1));
- }
- } else {
- let mut vec = vec![];
- for r_if in ifs {
- vec.push((r_if.0, r_if.1));
- }
- self.r_ifs = Some(vec);
- }
- self
- }
-
- /// Sets multiple arguments by names that are required when this one is present I.e. when
- /// using this argument, the following arguments *must* be present.
- ///
- /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required
- /// by default.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::Arg;
- /// Arg::with_name("config")
- /// .requires_all(&["input", "output"])
- /// # ;
- /// ```
- ///
- /// Setting [`Arg::requires_all(&[arg, arg2])`] requires that all the arguments be used at
- /// runtime if the defining argument is used. If the defining argument isn't used, the other
- /// argument isn't required
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .takes_value(true)
- /// .requires("input")
- /// .long("config"))
- /// .arg(Arg::with_name("input")
- /// .index(1))
- /// .arg(Arg::with_name("output")
- /// .index(2))
- /// .get_matches_from_safe(vec![
- /// "prog"
- /// ]);
- ///
- /// assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required
- /// ```
- ///
- /// Setting [`Arg::requires_all(&[arg, arg2])`] and *not* supplying all the arguments is an
- /// error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .takes_value(true)
- /// .requires_all(&["input", "output"])
- /// .long("config"))
- /// .arg(Arg::with_name("input")
- /// .index(1))
- /// .arg(Arg::with_name("output")
- /// .index(2))
- /// .get_matches_from_safe(vec![
- /// "prog", "--config", "file.conf", "in.txt"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// // We didn't use output
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
- /// ```
- /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
- /// [override]: ./struct.Arg.html#method.overrides_with
- /// [`Arg::requires_all(&[arg, arg2])`]: ./struct.Arg.html#method.requires_all
- pub fn requires_all(mut self, names: &[&'a str]) -> Self {
- if let Some(ref mut vec) = self.b.requires {
- for s in names {
- vec.push((None, s));
- }
- } else {
- let mut vec = vec![];
- for s in names {
- vec.push((None, *s));
- }
- self.b.requires = Some(vec);
- }
- self
- }
-
- /// Specifies that the argument takes a value at run time.
- ///
- /// **NOTE:** values for arguments may be specified in any of the following methods
- ///
- /// * Using a space such as `-o value` or `--option value`
- /// * Using an equals and no space such as `-o=value` or `--option=value`
- /// * Use a short and no space such as `-ovalue`
- ///
- /// **NOTE:** By default, args which allow [multiple values] are delimited by commas, meaning
- /// `--option=val1,val2,val3` is three values for the `--option` argument. If you wish to
- /// change the delimiter to another character you can use [`Arg::value_delimiter(char)`],
- /// alternatively you can turn delimiting values **OFF** by using [`Arg::use_delimiter(false)`]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("config")
- /// .takes_value(true)
- /// # ;
- /// ```
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("mode")
- /// .long("mode")
- /// .takes_value(true))
- /// .get_matches_from(vec![
- /// "prog", "--mode", "fast"
- /// ]);
- ///
- /// assert!(m.is_present("mode"));
- /// assert_eq!(m.value_of("mode"), Some("fast"));
- /// ```
- /// [`Arg::value_delimiter(char)`]: ./struct.Arg.html#method.value_delimiter
- /// [`Arg::use_delimiter(false)`]: ./struct.Arg.html#method.use_delimiter
- /// [multiple values]: ./struct.Arg.html#method.multiple
- pub fn takes_value(self, tv: bool) -> Self {
- if tv {
- self.set(ArgSettings::TakesValue)
- } else {
- self.unset(ArgSettings::TakesValue)
- }
- }
-
- /// Specifies if the possible values of an argument should be displayed in the help text or
- /// not. Defaults to `false` (i.e. show possible values)
- ///
- /// This is useful for args with many values, or ones which are explained elsewhere in the
- /// help text.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("config")
- /// .hide_possible_values(true)
- /// # ;
- /// ```
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("mode")
- /// .long("mode")
- /// .possible_values(&["fast", "slow"])
- /// .takes_value(true)
- /// .hide_possible_values(true));
- ///
- /// ```
- ///
- /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of
- /// the help text would be omitted.
- pub fn hide_possible_values(self, hide: bool) -> Self {
- if hide {
- self.set(ArgSettings::HidePossibleValues)
- } else {
- self.unset(ArgSettings::HidePossibleValues)
- }
- }
-
- /// Specifies if the default value of an argument should be displayed in the help text or
- /// not. Defaults to `false` (i.e. show default value)
- ///
- /// This is useful when default behavior of an arg is explained elsewhere in the help text.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("config")
- /// .hide_default_value(true)
- /// # ;
- /// ```
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("connect")
- /// .arg(Arg::with_name("host")
- /// .long("host")
- /// .default_value("localhost")
- /// .hide_default_value(true));
- ///
- /// ```
- ///
- /// If we were to run the above program with `--help` the `[default: localhost]` portion of
- /// the help text would be omitted.
- pub fn hide_default_value(self, hide: bool) -> Self {
- if hide {
- self.set(ArgSettings::HideDefaultValue)
- } else {
- self.unset(ArgSettings::HideDefaultValue)
- }
- }
-
- /// Specifies the index of a positional argument **starting at** 1.
- ///
- /// **NOTE:** The index refers to position according to **other positional argument**. It does
- /// not define position in the argument list as a whole.
- ///
- /// **NOTE:** If no [`Arg::short`], or [`Arg::long`] have been defined, you can optionally
- /// leave off the `index` method, and the index will be assigned in order of evaluation.
- /// Utilizing the `index` method allows for setting indexes out of order
- ///
- /// **NOTE:** When utilized with [`Arg::multiple(true)`], only the **last** positional argument
- /// may be defined as multiple (i.e. with the highest index)
- ///
- /// # Panics
- ///
- /// Although not in this method directly, [`App`] will [`panic!`] if indexes are skipped (such
- /// as defining `index(1)` and `index(3)` but not `index(2)`, or a positional argument is
- /// defined as multiple and is not the highest index
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("config")
- /// .index(1)
- /// # ;
- /// ```
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("mode")
- /// .index(1))
- /// .arg(Arg::with_name("debug")
- /// .long("debug"))
- /// .get_matches_from(vec![
- /// "prog", "--debug", "fast"
- /// ]);
- ///
- /// assert!(m.is_present("mode"));
- /// assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional"
- /// // *not* first argument
- /// ```
- /// [`Arg::short`]: ./struct.Arg.html#method.short
- /// [`Arg::long`]: ./struct.Arg.html#method.long
- /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
- /// [`App`]: ./struct.App.html
- /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
- pub fn index(mut self, idx: u64) -> Self {
- self.index = Some(idx);
- self
- }
-
- /// Specifies that the argument may appear more than once. For flags, this results
- /// in the number of occurrences of the flag being recorded. For example `-ddd` or `-d -d -d`
- /// would count as three occurrences. For options there is a distinct difference in multiple
- /// occurrences vs multiple values.
- ///
- /// For example, `--opt val1 val2` is one occurrence, but two values. Whereas
- /// `--opt val1 --opt val2` is two occurrences.
- ///
- /// **WARNING:**
- ///
- /// Setting `multiple(true)` for an [option] with no other details, allows multiple values
- /// **and** multiple occurrences because it isn't possible to have more occurrences than values
- /// for options. Because multiple values are allowed, `--option val1 val2 val3` is perfectly
- /// valid, be careful when designing a CLI where positional arguments are expected after a
- /// option which accepts multiple values, as `clap` will continue parsing *values* until it
- /// reaches the max or specific number of values defined, or another flag or option.
- ///
- /// **Pro Tip**:
- ///
- /// It's possible to define an option which allows multiple occurrences, but only one value per
- /// occurrence. To do this use [`Arg::number_of_values(1)`] in coordination with
- /// [`Arg::multiple(true)`].
- ///
- /// **WARNING:**
- ///
- /// When using args with `multiple(true)` on [options] or [positionals] (i.e. those args that
- /// accept values) and [subcommands], one needs to consider the possibility of an argument value
- /// being the same as a valid subcommand. By default `clap` will parse the argument in question
- /// as a value *only if* a value is possible at that moment. Otherwise it will be parsed as a
- /// subcommand. In effect, this means using `multiple(true)` with no additional parameters and
- /// a possible value that coincides with a subcommand name, the subcommand cannot be called
- /// unless another argument is passed first.
- ///
- /// As an example, consider a CLI with an option `--ui-paths=<paths>...` and subcommand `signer`
- ///
- /// The following would be parsed as values to `--ui-paths`.
- ///
- /// ```notrust
- /// $ program --ui-paths path1 path2 signer
- /// ```
- ///
- /// This is because `--ui-paths` accepts multiple values. `clap` will continue parsing values
- /// until another argument is reached and it knows `--ui-paths` is done.
- ///
- /// By adding additional parameters to `--ui-paths` we can solve this issue. Consider adding
- /// [`Arg::number_of_values(1)`] as discussed above. The following are all valid, and `signer`
- /// is parsed as both a subcommand and a value in the second case.
- ///
- /// ```notrust
- /// $ program --ui-paths path1 signer
- /// $ program --ui-paths path1 --ui-paths signer signer
- /// ```
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("debug")
- /// .short("d")
- /// .multiple(true)
- /// # ;
- /// ```
- /// An example with flags
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("verbose")
- /// .multiple(true)
- /// .short("v"))
- /// .get_matches_from(vec![
- /// "prog", "-v", "-v", "-v" // note, -vvv would have same result
- /// ]);
- ///
- /// assert!(m.is_present("verbose"));
- /// assert_eq!(m.occurrences_of("verbose"), 3);
- /// ```
- ///
- /// An example with options
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("file")
- /// .multiple(true)
- /// .takes_value(true)
- /// .short("F"))
- /// .get_matches_from(vec![
- /// "prog", "-F", "file1", "file2", "file3"
- /// ]);
- ///
- /// assert!(m.is_present("file"));
- /// assert_eq!(m.occurrences_of("file"), 1); // notice only one occurrence
- /// let files: Vec<_> = m.values_of("file").unwrap().collect();
- /// assert_eq!(files, ["file1", "file2", "file3"]);
- /// ```
- /// This is functionally equivalent to the example above
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("file")
- /// .multiple(true)
- /// .takes_value(true)
- /// .short("F"))
- /// .get_matches_from(vec![
- /// "prog", "-F", "file1", "-F", "file2", "-F", "file3"
- /// ]);
- /// let files: Vec<_> = m.values_of("file").unwrap().collect();
- /// assert_eq!(files, ["file1", "file2", "file3"]);
- ///
- /// assert!(m.is_present("file"));
- /// assert_eq!(m.occurrences_of("file"), 3); // Notice 3 occurrences
- /// let files: Vec<_> = m.values_of("file").unwrap().collect();
- /// assert_eq!(files, ["file1", "file2", "file3"]);
- /// ```
- ///
- /// A common mistake is to define an option which allows multiples, and a positional argument
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("file")
- /// .multiple(true)
- /// .takes_value(true)
- /// .short("F"))
- /// .arg(Arg::with_name("word")
- /// .index(1))
- /// .get_matches_from(vec![
- /// "prog", "-F", "file1", "file2", "file3", "word"
- /// ]);
- ///
- /// assert!(m.is_present("file"));
- /// let files: Vec<_> = m.values_of("file").unwrap().collect();
- /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?!
- /// assert!(!m.is_present("word")); // but we clearly used word!
- /// ```
- /// The problem is clap doesn't know when to stop parsing values for "files". This is further
- /// compounded by if we'd said `word -F file1 file2` it would have worked fine, so it would
- /// appear to only fail sometimes...not good!
- ///
- /// A solution for the example above is to specify that `-F` only accepts one value, but is
- /// allowed to appear multiple times
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("file")
- /// .multiple(true)
- /// .takes_value(true)
- /// .number_of_values(1)
- /// .short("F"))
- /// .arg(Arg::with_name("word")
- /// .index(1))
- /// .get_matches_from(vec![
- /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word"
- /// ]);
- ///
- /// assert!(m.is_present("file"));
- /// let files: Vec<_> = m.values_of("file").unwrap().collect();
- /// assert_eq!(files, ["file1", "file2", "file3"]);
- /// assert!(m.is_present("word"));
- /// assert_eq!(m.value_of("word"), Some("word"));
- /// ```
- /// As a final example, notice if we define [`Arg::number_of_values(1)`] and try to run the
- /// problem example above, it would have been a runtime error with a pretty message to the
- /// user :)
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("file")
- /// .multiple(true)
- /// .takes_value(true)
- /// .number_of_values(1)
- /// .short("F"))
- /// .arg(Arg::with_name("word")
- /// .index(1))
- /// .get_matches_from_safe(vec![
- /// "prog", "-F", "file1", "file2", "file3", "word"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
- /// ```
- /// [option]: ./struct.Arg.html#method.takes_value
- /// [options]: ./struct.Arg.html#method.takes_value
- /// [subcommands]: ./struct.SubCommand.html
- /// [positionals]: ./struct.Arg.html#method.index
- /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values
- /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
- pub fn multiple(self, multi: bool) -> Self {
- if multi {
- self.set(ArgSettings::Multiple)
- } else {
- self.unset(ArgSettings::Multiple)
- }
- }
-
- /// Specifies a value that *stops* parsing multiple values of a give argument. By default when
- /// one sets [`multiple(true)`] on an argument, clap will continue parsing values for that
- /// argument until it reaches another valid argument, or one of the other more specific settings
- /// for multiple values is used (such as [`min_values`], [`max_values`] or
- /// [`number_of_values`]).
- ///
- /// **NOTE:** This setting only applies to [options] and [positional arguments]
- ///
- /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one
- /// of the values
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("vals")
- /// .takes_value(true)
- /// .multiple(true)
- /// .value_terminator(";")
- /// # ;
- /// ```
- /// The following example uses two arguments, a sequence of commands, and the location in which
- /// to perform them
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("cmds")
- /// .multiple(true)
- /// .allow_hyphen_values(true)
- /// .value_terminator(";"))
- /// .arg(Arg::with_name("location"))
- /// .get_matches_from(vec![
- /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap"
- /// ]);
- /// let cmds: Vec<_> = m.values_of("cmds").unwrap().collect();
- /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]);
- /// assert_eq!(m.value_of("location"), Some("/home/clap"));
- /// ```
- /// [options]: ./struct.Arg.html#method.takes_value
- /// [positional arguments]: ./struct.Arg.html#method.index
- /// [`multiple(true)`]: ./struct.Arg.html#method.multiple
- /// [`min_values`]: ./struct.Arg.html#method.min_values
- /// [`number_of_values`]: ./struct.Arg.html#method.number_of_values
- /// [`max_values`]: ./struct.Arg.html#method.max_values
- pub fn value_terminator(mut self, term: &'b str) -> Self {
- self.setb(ArgSettings::TakesValue);
- self.v.terminator = Some(term);
- self
- }
-
- /// Specifies that an argument can be matched to all child [`SubCommand`]s.
- ///
- /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however
- /// their values once a user uses them will be propagated back up to parents. In effect, this
- /// means one should *define* all global arguments at the top level, however it doesn't matter
- /// where the user *uses* the global argument.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("debug")
- /// .short("d")
- /// .global(true)
- /// # ;
- /// ```
- ///
- /// For example, assume an application with two subcommands, and you'd like to define a
- /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't
- /// want to clutter the source with three duplicate [`Arg`] definitions.
- ///
- /// ```rust
- /// # use clap::{App, Arg, SubCommand};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("verb")
- /// .long("verbose")
- /// .short("v")
- /// .global(true))
- /// .subcommand(SubCommand::with_name("test"))
- /// .subcommand(SubCommand::with_name("do-stuff"))
- /// .get_matches_from(vec![
- /// "prog", "do-stuff", "--verbose"
- /// ]);
- ///
- /// assert_eq!(m.subcommand_name(), Some("do-stuff"));
- /// let sub_m = m.subcommand_matches("do-stuff").unwrap();
- /// assert!(sub_m.is_present("verb"));
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [required]: ./struct.Arg.html#method.required
- /// [`ArgMatches`]: ./struct.ArgMatches.html
- /// [`ArgMatches::is_present("flag")`]: ./struct.ArgMatches.html#method.is_present
- /// [`Arg`]: ./struct.Arg.html
- pub fn global(self, g: bool) -> Self {
- if g {
- self.set(ArgSettings::Global)
- } else {
- self.unset(ArgSettings::Global)
- }
- }
-
- /// Allows an argument to accept explicitly empty values. An empty value must be specified at
- /// the command line with an explicit `""`, or `''`
- ///
- /// **NOTE:** Defaults to `true` (Explicitly empty values are allowed)
- ///
- /// **NOTE:** Implicitly sets [`Arg::takes_value(true)`] when set to `false`
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("file")
- /// .long("file")
- /// .empty_values(false)
- /// # ;
- /// ```
- /// The default is to allow empty values, such as `--option ""` would be an empty value. But
- /// we can change to make empty values become an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .long("config")
- /// .short("v")
- /// .empty_values(false))
- /// .get_matches_from_safe(vec![
- /// "prog", "--config="
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue);
- /// ```
- /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
- pub fn empty_values(mut self, ev: bool) -> Self {
- if ev {
- self.set(ArgSettings::EmptyValues)
- } else {
- self = self.set(ArgSettings::TakesValue);
- self.unset(ArgSettings::EmptyValues)
- }
- }
-
- /// Hides an argument from help message output.
- ///
- /// **NOTE:** Implicitly sets [`Arg::hidden_short_help(true)`] and [`Arg::hidden_long_help(true)`]
- /// when set to true
- ///
- /// **NOTE:** This does **not** hide the argument from usage strings on error
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("debug")
- /// .hidden(true)
- /// # ;
- /// ```
- /// Setting `hidden(true)` will hide the argument when displaying help text
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .long("config")
- /// .hidden(true)
- /// .help("Some help text describing the --config arg"))
- /// .get_matches_from(vec![
- /// "prog", "--help"
- /// ]);
- /// ```
- ///
- /// The above example displays
- ///
- /// ```notrust
- /// helptest
- ///
- /// USAGE:
- /// helptest [FLAGS]
- ///
- /// FLAGS:
- /// -h, --help Prints help information
- /// -V, --version Prints version information
- /// ```
- /// [`Arg::hidden_short_help(true)`]: ./struct.Arg.html#method.hidden_short_help
- /// [`Arg::hidden_long_help(true)`]: ./struct.Arg.html#method.hidden_long_help
- pub fn hidden(self, h: bool) -> Self {
- if h {
- self.set(ArgSettings::Hidden)
- } else {
- self.unset(ArgSettings::Hidden)
- }
- }
-
- /// Specifies a list of possible values for this argument. At runtime, `clap` verifies that
- /// only one of the specified values was used, or fails with an error message.
- ///
- /// **NOTE:** This setting only applies to [options] and [positional arguments]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("mode")
- /// .takes_value(true)
- /// .possible_values(&["fast", "slow", "medium"])
- /// # ;
- /// ```
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("mode")
- /// .long("mode")
- /// .takes_value(true)
- /// .possible_values(&["fast", "slow", "medium"]))
- /// .get_matches_from(vec![
- /// "prog", "--mode", "fast"
- /// ]);
- /// assert!(m.is_present("mode"));
- /// assert_eq!(m.value_of("mode"), Some("fast"));
- /// ```
- ///
- /// The next example shows a failed parse from using a value which wasn't defined as one of the
- /// possible values.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("mode")
- /// .long("mode")
- /// .takes_value(true)
- /// .possible_values(&["fast", "slow", "medium"]))
- /// .get_matches_from_safe(vec![
- /// "prog", "--mode", "wrong"
- /// ]);
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue);
- /// ```
- /// [options]: ./struct.Arg.html#method.takes_value
- /// [positional arguments]: ./struct.Arg.html#method.index
- pub fn possible_values(mut self, names: &[&'b str]) -> Self {
- if let Some(ref mut vec) = self.v.possible_vals {
- for s in names {
- vec.push(s);
- }
- } else {
- self.v.possible_vals = Some(names.iter().map(|s| *s).collect::<Vec<_>>());
- }
- self
- }
-
- /// Specifies a possible value for this argument, one at a time. At runtime, `clap` verifies
- /// that only one of the specified values was used, or fails with error message.
- ///
- /// **NOTE:** This setting only applies to [options] and [positional arguments]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("mode")
- /// .takes_value(true)
- /// .possible_value("fast")
- /// .possible_value("slow")
- /// .possible_value("medium")
- /// # ;
- /// ```
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("mode")
- /// .long("mode")
- /// .takes_value(true)
- /// .possible_value("fast")
- /// .possible_value("slow")
- /// .possible_value("medium"))
- /// .get_matches_from(vec![
- /// "prog", "--mode", "fast"
- /// ]);
- /// assert!(m.is_present("mode"));
- /// assert_eq!(m.value_of("mode"), Some("fast"));
- /// ```
- ///
- /// The next example shows a failed parse from using a value which wasn't defined as one of the
- /// possible values.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("mode")
- /// .long("mode")
- /// .takes_value(true)
- /// .possible_value("fast")
- /// .possible_value("slow")
- /// .possible_value("medium"))
- /// .get_matches_from_safe(vec![
- /// "prog", "--mode", "wrong"
- /// ]);
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue);
- /// ```
- /// [options]: ./struct.Arg.html#method.takes_value
- /// [positional arguments]: ./struct.Arg.html#method.index
- pub fn possible_value(mut self, name: &'b str) -> Self {
- if let Some(ref mut vec) = self.v.possible_vals {
- vec.push(name);
- } else {
- self.v.possible_vals = Some(vec![name]);
- }
- self
- }
-
- /// When used with [`Arg::possible_values`] it allows the argument value to pass validation even if
- /// the case differs from that of the specified `possible_value`.
- ///
- /// **Pro Tip:** Use this setting with [`arg_enum!`]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// # use std::ascii::AsciiExt;
- /// let m = App::new("pv")
- /// .arg(Arg::with_name("option")
- /// .long("--option")
- /// .takes_value(true)
- /// .possible_value("test123")
- /// .case_insensitive(true))
- /// .get_matches_from(vec![
- /// "pv", "--option", "TeSt123",
- /// ]);
- ///
- /// assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123"));
- /// ```
- ///
- /// This setting also works when multiple values can be defined:
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("pv")
- /// .arg(Arg::with_name("option")
- /// .short("-o")
- /// .long("--option")
- /// .takes_value(true)
- /// .possible_value("test123")
- /// .possible_value("test321")
- /// .multiple(true)
- /// .case_insensitive(true))
- /// .get_matches_from(vec![
- /// "pv", "--option", "TeSt123", "teST123", "tESt321"
- /// ]);
- ///
- /// let matched_vals = m.values_of("option").unwrap().collect::<Vec<_>>();
- /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]);
- /// ```
- /// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.possible_values
- /// [`arg_enum!`]: ./macro.arg_enum.html
- pub fn case_insensitive(self, ci: bool) -> Self {
- if ci {
- self.set(ArgSettings::CaseInsensitive)
- } else {
- self.unset(ArgSettings::CaseInsensitive)
- }
- }
-
- /// Specifies the name of the [`ArgGroup`] the argument belongs to.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("debug")
- /// .long("debug")
- /// .group("mode")
- /// # ;
- /// ```
- ///
- /// Multiple arguments can be a member of a single group and then the group checked as if it
- /// was one of said arguments.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("debug")
- /// .long("debug")
- /// .group("mode"))
- /// .arg(Arg::with_name("verbose")
- /// .long("verbose")
- /// .group("mode"))
- /// .get_matches_from(vec![
- /// "prog", "--debug"
- /// ]);
- /// assert!(m.is_present("mode"));
- /// ```
- /// [`ArgGroup`]: ./struct.ArgGroup.html
- pub fn group(mut self, name: &'a str) -> Self {
- if let Some(ref mut vec) = self.b.groups {
- vec.push(name);
- } else {
- self.b.groups = Some(vec![name]);
- }
- self
- }
-
- /// Specifies the names of multiple [`ArgGroup`]'s the argument belongs to.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("debug")
- /// .long("debug")
- /// .groups(&["mode", "verbosity"])
- /// # ;
- /// ```
- ///
- /// Arguments can be members of multiple groups and then the group checked as if it
- /// was one of said arguments.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("debug")
- /// .long("debug")
- /// .groups(&["mode", "verbosity"]))
- /// .arg(Arg::with_name("verbose")
- /// .long("verbose")
- /// .groups(&["mode", "verbosity"]))
- /// .get_matches_from(vec![
- /// "prog", "--debug"
- /// ]);
- /// assert!(m.is_present("mode"));
- /// assert!(m.is_present("verbosity"));
- /// ```
- /// [`ArgGroup`]: ./struct.ArgGroup.html
- pub fn groups(mut self, names: &[&'a str]) -> Self {
- if let Some(ref mut vec) = self.b.groups {
- for s in names {
- vec.push(s);
- }
- } else {
- self.b.groups = Some(names.into_iter().map(|s| *s).collect::<Vec<_>>());
- }
- self
- }
-
- /// Specifies how many values are required to satisfy this argument. For example, if you had a
- /// `-f <file>` argument where you wanted exactly 3 'files' you would set
- /// `.number_of_values(3)`, and this argument wouldn't be satisfied unless the user provided
- /// 3 and only 3 values.
- ///
- /// **NOTE:** Does *not* require [`Arg::multiple(true)`] to be set. Setting
- /// [`Arg::multiple(true)`] would allow `-f <file> <file> <file> -f <file> <file> <file>` where
- /// as *not* setting [`Arg::multiple(true)`] would only allow one occurrence of this argument.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("file")
- /// .short("f")
- /// .number_of_values(3)
- /// # ;
- /// ```
- ///
- /// Not supplying the correct number of values is an error
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("file")
- /// .takes_value(true)
- /// .number_of_values(2)
- /// .short("F"))
- /// .get_matches_from_safe(vec![
- /// "prog", "-F", "file1"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::WrongNumberOfValues);
- /// ```
- /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
- pub fn number_of_values(mut self, qty: u64) -> Self {
- self.setb(ArgSettings::TakesValue);
- self.v.num_vals = Some(qty);
- self
- }
-
- /// Allows one to perform a custom validation on the argument value. You provide a closure
- /// which accepts a [`String`] value, and return a [`Result`] where the [`Err(String)`] is a
- /// message displayed to the user.
- ///
- /// **NOTE:** The error message does *not* need to contain the `error:` portion, only the
- /// message as all errors will appear as
- /// `error: Invalid value for '<arg>': <YOUR MESSAGE>` where `<arg>` is replaced by the actual
- /// arg, and `<YOUR MESSAGE>` is the `String` you return as the error.
- ///
- /// **NOTE:** There is a small performance hit for using validators, as they are implemented
- /// with [`Rc`] pointers. And the value to be checked will be allocated an extra time in order
- /// to to be passed to the closure. This performance hit is extremely minimal in the grand
- /// scheme of things.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// fn has_at(v: String) -> Result<(), String> {
- /// if v.contains("@") { return Ok(()); }
- /// Err(String::from("The value did not contain the required @ sigil"))
- /// }
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("file")
- /// .index(1)
- /// .validator(has_at))
- /// .get_matches_from_safe(vec![
- /// "prog", "some@file"
- /// ]);
- /// assert!(res.is_ok());
- /// assert_eq!(res.unwrap().value_of("file"), Some("some@file"));
- /// ```
- /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
- /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
- /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
- /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html
- pub fn validator<F>(mut self, f: F) -> Self
- where
- F: Fn(String) -> Result<(), String> + 'static,
- {
- self.v.validator = Some(Rc::new(f));
- self
- }
-
- /// Works identically to Validator but is intended to be used with values that could
- /// contain non UTF-8 formatted strings.
- ///
- /// # Examples
- ///
- #[cfg_attr(not(unix), doc = " ```ignore")]
- #[cfg_attr(unix, doc = " ```rust")]
- /// # use clap::{App, Arg};
- /// # use std::ffi::{OsStr, OsString};
- /// # use std::os::unix::ffi::OsStrExt;
- /// fn has_ampersand(v: &OsStr) -> Result<(), OsString> {
- /// if v.as_bytes().iter().any(|b| *b == b'&') { return Ok(()); }
- /// Err(OsString::from("The value did not contain the required & sigil"))
- /// }
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("file")
- /// .index(1)
- /// .validator_os(has_ampersand))
- /// .get_matches_from_safe(vec![
- /// "prog", "Fish & chips"
- /// ]);
- /// assert!(res.is_ok());
- /// assert_eq!(res.unwrap().value_of("file"), Some("Fish & chips"));
- /// ```
- /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
- /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
- /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html
- /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
- /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
- /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html
- pub fn validator_os<F>(mut self, f: F) -> Self
- where
- F: Fn(&OsStr) -> Result<(), OsString> + 'static,
- {
- self.v.validator_os = Some(Rc::new(f));
- self
- }
-
- /// Specifies the *maximum* number of values are for this argument. For example, if you had a
- /// `-f <file>` argument where you wanted up to 3 'files' you would set `.max_values(3)`, and
- /// this argument would be satisfied if the user provided, 1, 2, or 3 values.
- ///
- /// **NOTE:** This does *not* implicitly set [`Arg::multiple(true)`]. This is because
- /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single
- /// occurrence with multiple values. For positional arguments this **does** set
- /// [`Arg::multiple(true)`] because there is no way to determine the difference between multiple
- /// occurrences and multiple values.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("file")
- /// .short("f")
- /// .max_values(3)
- /// # ;
- /// ```
- ///
- /// Supplying less than the maximum number of values is allowed
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("file")
- /// .takes_value(true)
- /// .max_values(3)
- /// .short("F"))
- /// .get_matches_from_safe(vec![
- /// "prog", "-F", "file1", "file2"
- /// ]);
- ///
- /// assert!(res.is_ok());
- /// let m = res.unwrap();
- /// let files: Vec<_> = m.values_of("file").unwrap().collect();
- /// assert_eq!(files, ["file1", "file2"]);
- /// ```
- ///
- /// Supplying more than the maximum number of values is an error
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("file")
- /// .takes_value(true)
- /// .max_values(2)
- /// .short("F"))
- /// .get_matches_from_safe(vec![
- /// "prog", "-F", "file1", "file2", "file3"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooManyValues);
- /// ```
- /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
- pub fn max_values(mut self, qty: u64) -> Self {
- self.setb(ArgSettings::TakesValue);
- self.v.max_vals = Some(qty);
- self
- }
-
- /// Specifies the *minimum* number of values for this argument. For example, if you had a
- /// `-f <file>` argument where you wanted at least 2 'files' you would set
- /// `.min_values(2)`, and this argument would be satisfied if the user provided, 2 or more
- /// values.
- ///
- /// **NOTE:** This does not implicitly set [`Arg::multiple(true)`]. This is because
- /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single
- /// occurrence with multiple values. For positional arguments this **does** set
- /// [`Arg::multiple(true)`] because there is no way to determine the difference between multiple
- /// occurrences and multiple values.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("file")
- /// .short("f")
- /// .min_values(3)
- /// # ;
- /// ```
- ///
- /// Supplying more than the minimum number of values is allowed
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("file")
- /// .takes_value(true)
- /// .min_values(2)
- /// .short("F"))
- /// .get_matches_from_safe(vec![
- /// "prog", "-F", "file1", "file2", "file3"
- /// ]);
- ///
- /// assert!(res.is_ok());
- /// let m = res.unwrap();
- /// let files: Vec<_> = m.values_of("file").unwrap().collect();
- /// assert_eq!(files, ["file1", "file2", "file3"]);
- /// ```
- ///
- /// Supplying less than the minimum number of values is an error
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("file")
- /// .takes_value(true)
- /// .min_values(2)
- /// .short("F"))
- /// .get_matches_from_safe(vec![
- /// "prog", "-F", "file1"
- /// ]);
- ///
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooFewValues);
- /// ```
- /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
- pub fn min_values(mut self, qty: u64) -> Self {
- self.v.min_vals = Some(qty);
- self.set(ArgSettings::TakesValue)
- }
-
- /// Specifies whether or not an argument should allow grouping of multiple values via a
- /// delimiter. I.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`,
- /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the
- /// value delimiter for all arguments that accept values (options and positional arguments)
- ///
- /// **NOTE:** The default is `false`. When set to `true` the default [`Arg::value_delimiter`]
- /// is the comma `,`.
- ///
- /// # Examples
- ///
- /// The following example shows the default behavior.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let delims = App::new("prog")
- /// .arg(Arg::with_name("option")
- /// .long("option")
- /// .use_delimiter(true)
- /// .takes_value(true))
- /// .get_matches_from(vec![
- /// "prog", "--option=val1,val2,val3",
- /// ]);
- ///
- /// assert!(delims.is_present("option"));
- /// assert_eq!(delims.occurrences_of("option"), 1);
- /// assert_eq!(delims.values_of("option").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
- /// ```
- /// The next example shows the difference when turning delimiters off. This is the default
- /// behavior
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let nodelims = App::new("prog")
- /// .arg(Arg::with_name("option")
- /// .long("option")
- /// .use_delimiter(false)
- /// .takes_value(true))
- /// .get_matches_from(vec![
- /// "prog", "--option=val1,val2,val3",
- /// ]);
- ///
- /// assert!(nodelims.is_present("option"));
- /// assert_eq!(nodelims.occurrences_of("option"), 1);
- /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3");
- /// ```
- /// [`Arg::value_delimiter`]: ./struct.Arg.html#method.value_delimiter
- pub fn use_delimiter(mut self, d: bool) -> Self {
- if d {
- if self.v.val_delim.is_none() {
- self.v.val_delim = Some(',');
- }
- self.setb(ArgSettings::TakesValue);
- self.setb(ArgSettings::UseValueDelimiter);
- self.unset(ArgSettings::ValueDelimiterNotSet)
- } else {
- self.v.val_delim = None;
- self.unsetb(ArgSettings::UseValueDelimiter);
- self.unset(ArgSettings::ValueDelimiterNotSet)
- }
- }
-
- /// Specifies that *multiple values* may only be set using the delimiter. This means if an
- /// if an option is encountered, and no delimiter is found, it automatically assumed that no
- /// additional values for that option follow. This is unlike the default, where it is generally
- /// assumed that more values will follow regardless of whether or not a delimiter is used.
- ///
- /// **NOTE:** The default is `false`.
- ///
- /// **NOTE:** Setting this to true implies [`Arg::use_delimiter(true)`]
- ///
- /// **NOTE:** It's a good idea to inform the user that use of a delimiter is required, either
- /// through help text or other means.
- ///
- /// # Examples
- ///
- /// These examples demonstrate what happens when `require_delimiter(true)` is used. Notice
- /// everything works in this first example, as we use a delimiter, as expected.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let delims = App::new("prog")
- /// .arg(Arg::with_name("opt")
- /// .short("o")
- /// .takes_value(true)
- /// .multiple(true)
- /// .require_delimiter(true))
- /// .get_matches_from(vec![
- /// "prog", "-o", "val1,val2,val3",
- /// ]);
- ///
- /// assert!(delims.is_present("opt"));
- /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
- /// ```
- /// In this next example, we will *not* use a delimiter. Notice it's now an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("opt")
- /// .short("o")
- /// .takes_value(true)
- /// .multiple(true)
- /// .require_delimiter(true))
- /// .get_matches_from_safe(vec![
- /// "prog", "-o", "val1", "val2", "val3",
- /// ]);
- ///
- /// assert!(res.is_err());
- /// let err = res.unwrap_err();
- /// assert_eq!(err.kind, ErrorKind::UnknownArgument);
- /// ```
- /// What's happening is `-o` is getting `val1`, and because delimiters are required yet none
- /// were present, it stops parsing `-o`. At this point it reaches `val2` and because no
- /// positional arguments have been defined, it's an error of an unexpected argument.
- ///
- /// In this final example, we contrast the above with `clap`'s default behavior where the above
- /// is *not* an error.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let delims = App::new("prog")
- /// .arg(Arg::with_name("opt")
- /// .short("o")
- /// .takes_value(true)
- /// .multiple(true))
- /// .get_matches_from(vec![
- /// "prog", "-o", "val1", "val2", "val3",
- /// ]);
- ///
- /// assert!(delims.is_present("opt"));
- /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
- /// ```
- /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter
- pub fn require_delimiter(mut self, d: bool) -> Self {
- if d {
- self = self.use_delimiter(true);
- self.unsetb(ArgSettings::ValueDelimiterNotSet);
- self.setb(ArgSettings::UseValueDelimiter);
- self.set(ArgSettings::RequireDelimiter)
- } else {
- self = self.use_delimiter(false);
- self.unsetb(ArgSettings::UseValueDelimiter);
- self.unset(ArgSettings::RequireDelimiter)
- }
- }
-
- /// Specifies the separator to use when values are clumped together, defaults to `,` (comma).
- ///
- /// **NOTE:** implicitly sets [`Arg::use_delimiter(true)`]
- ///
- /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("config")
- /// .short("c")
- /// .long("config")
- /// .value_delimiter(";"))
- /// .get_matches_from(vec![
- /// "prog", "--config=val1;val2;val3"
- /// ]);
- ///
- /// assert_eq!(m.values_of("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"])
- /// ```
- /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter
- /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
- pub fn value_delimiter(mut self, d: &str) -> Self {
- self.unsetb(ArgSettings::ValueDelimiterNotSet);
- self.setb(ArgSettings::TakesValue);
- self.setb(ArgSettings::UseValueDelimiter);
- self.v.val_delim = Some(
- d.chars()
- .nth(0)
- .expect("Failed to get value_delimiter from arg"),
- );
- self
- }
-
- /// Specify multiple names for values of option arguments. These names are cosmetic only, used
- /// for help and usage strings only. The names are **not** used to access arguments. The values
- /// of the arguments are accessed in numeric order (i.e. if you specify two names `one` and
- /// `two` `one` will be the first matched value, `two` will be the second).
- ///
- /// This setting can be very helpful when describing the type of input the user should be
- /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to
- /// use all capital letters for the value name.
- ///
- /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or
- /// multiple value names in order to not throw off the help text alignment of all options.
- ///
- /// **NOTE:** This implicitly sets [`Arg::number_of_values`] if the number of value names is
- /// greater than one. I.e. be aware that the number of "names" you set for the values, will be
- /// the *exact* number of values required to satisfy this argument
- ///
- /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
- ///
- /// **NOTE:** Does *not* require or imply [`Arg::multiple(true)`].
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("speed")
- /// .short("s")
- /// .value_names(&["fast", "slow"])
- /// # ;
- /// ```
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("io")
- /// .long("io-files")
- /// .value_names(&["INFILE", "OUTFILE"]))
- /// .get_matches_from(vec![
- /// "prog", "--help"
- /// ]);
- /// ```
- /// Running the above program produces the following output
- ///
- /// ```notrust
- /// valnames
- ///
- /// USAGE:
- /// valnames [FLAGS] [OPTIONS]
- ///
- /// FLAGS:
- /// -h, --help Prints help information
- /// -V, --version Prints version information
- ///
- /// OPTIONS:
- /// --io-files <INFILE> <OUTFILE> Some help text
- /// ```
- /// [`Arg::next_line_help(true)`]: ./struct.Arg.html#method.next_line_help
- /// [`Arg::number_of_values`]: ./struct.Arg.html#method.number_of_values
- /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
- /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
- pub fn value_names(mut self, names: &[&'b str]) -> Self {
- self.setb(ArgSettings::TakesValue);
- if self.is_set(ArgSettings::ValueDelimiterNotSet) {
- self.unsetb(ArgSettings::ValueDelimiterNotSet);
- self.setb(ArgSettings::UseValueDelimiter);
- }
- if let Some(ref mut vals) = self.v.val_names {
- let mut l = vals.len();
- for s in names {
- vals.insert(l, s);
- l += 1;
- }
- } else {
- let mut vm = VecMap::new();
- for (i, n) in names.iter().enumerate() {
- vm.insert(i, *n);
- }
- self.v.val_names = Some(vm);
- }
- self
- }
-
- /// Specifies the name for value of [option] or [positional] arguments inside of help
- /// documentation. This name is cosmetic only, the name is **not** used to access arguments.
- /// This setting can be very helpful when describing the type of input the user should be
- /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to
- /// use all capital letters for the value name.
- ///
- /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("cfg")
- /// .long("config")
- /// .value_name("FILE")
- /// # ;
- /// ```
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("config")
- /// .long("config")
- /// .value_name("FILE"))
- /// .get_matches_from(vec![
- /// "prog", "--help"
- /// ]);
- /// ```
- /// Running the above program produces the following output
- ///
- /// ```notrust
- /// valnames
- ///
- /// USAGE:
- /// valnames [FLAGS] [OPTIONS]
- ///
- /// FLAGS:
- /// -h, --help Prints help information
- /// -V, --version Prints version information
- ///
- /// OPTIONS:
- /// --config <FILE> Some help text
- /// ```
- /// [option]: ./struct.Arg.html#method.takes_value
- /// [positional]: ./struct.Arg.html#method.index
- /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
- pub fn value_name(mut self, name: &'b str) -> Self {
- self.setb(ArgSettings::TakesValue);
- if let Some(ref mut vals) = self.v.val_names {
- let l = vals.len();
- vals.insert(l, name);
- } else {
- let mut vm = VecMap::new();
- vm.insert(0, name);
- self.v.val_names = Some(vm);
- }
- self
- }
-
- /// Specifies the value of the argument when *not* specified at runtime.
- ///
- /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`]
- /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified.
- ///
- /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::is_present`] will
- /// still return `true`. If you wish to determine whether the argument was used at runtime or
- /// not, consider [`ArgMatches::occurrences_of`] which will return `0` if the argument was *not*
- /// used at runtime.
- ///
- /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly
- /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg
- /// at runtime. `Arg::default_value_if` however only takes affect when the user has not provided
- /// a value at runtime **and** these other conditions are met as well. If you have set
- /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide a this
- /// arg at runtime, nor did were the conditions met for `Arg::default_value_if`, the
- /// `Arg::default_value` will be applied.
- ///
- /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
- ///
- /// **NOTE:** This setting effectively disables `AppSettings::ArgRequiredElseHelp` if used in
- /// conjunction as it ensures that some argument will always be present.
- ///
- /// # Examples
- ///
- /// First we use the default value without providing any value at runtime.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("opt")
- /// .long("myopt")
- /// .default_value("myval"))
- /// .get_matches_from(vec![
- /// "prog"
- /// ]);
- ///
- /// assert_eq!(m.value_of("opt"), Some("myval"));
- /// assert!(m.is_present("opt"));
- /// assert_eq!(m.occurrences_of("opt"), 0);
- /// ```
- ///
- /// Next we provide a value at runtime to override the default.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("opt")
- /// .long("myopt")
- /// .default_value("myval"))
- /// .get_matches_from(vec![
- /// "prog", "--myopt=non_default"
- /// ]);
- ///
- /// assert_eq!(m.value_of("opt"), Some("non_default"));
- /// assert!(m.is_present("opt"));
- /// assert_eq!(m.occurrences_of("opt"), 1);
- /// ```
- /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of
- /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of
- /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
- /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present
- /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if
- pub fn default_value(self, val: &'a str) -> Self {
- self.default_value_os(OsStr::from_bytes(val.as_bytes()))
- }
-
- /// Provides a default value in the exact same manner as [`Arg::default_value`]
- /// only using [`OsStr`]s instead.
- /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value
- /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
- pub fn default_value_os(mut self, val: &'a OsStr) -> Self {
- self.setb(ArgSettings::TakesValue);
- self.v.default_val = Some(val);
- self
- }
-
- /// Specifies the value of the argument if `arg` has been used at runtime. If `val` is set to
- /// `None`, `arg` only needs to be present. If `val` is set to `"some-val"` then `arg` must be
- /// present at runtime **and** have the value `val`.
- ///
- /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly
- /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg
- /// at runtime. This setting however only takes affect when the user has not provided a value at
- /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value`
- /// and `Arg::default_value_if`, and the user **did not** provide a this arg at runtime, nor did
- /// were the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be
- /// applied.
- ///
- /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
- ///
- /// **NOTE:** If using YAML the values should be laid out as follows (`None` can be represented
- /// as `null` in YAML)
- ///
- /// ```yaml
- /// default_value_if:
- /// - [arg, val, default]
- /// ```
- ///
- /// # Examples
- ///
- /// First we use the default value only if another arg is present at runtime.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("flag")
- /// .long("flag"))
- /// .arg(Arg::with_name("other")
- /// .long("other")
- /// .default_value_if("flag", None, "default"))
- /// .get_matches_from(vec![
- /// "prog", "--flag"
- /// ]);
- ///
- /// assert_eq!(m.value_of("other"), Some("default"));
- /// ```
- ///
- /// Next we run the same test, but without providing `--flag`.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("flag")
- /// .long("flag"))
- /// .arg(Arg::with_name("other")
- /// .long("other")
- /// .default_value_if("flag", None, "default"))
- /// .get_matches_from(vec![
- /// "prog"
- /// ]);
- ///
- /// assert_eq!(m.value_of("other"), None);
- /// ```
- ///
- /// Now lets only use the default value if `--opt` contains the value `special`.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("opt")
- /// .takes_value(true)
- /// .long("opt"))
- /// .arg(Arg::with_name("other")
- /// .long("other")
- /// .default_value_if("opt", Some("special"), "default"))
- /// .get_matches_from(vec![
- /// "prog", "--opt", "special"
- /// ]);
- ///
- /// assert_eq!(m.value_of("other"), Some("default"));
- /// ```
- ///
- /// We can run the same test and provide any value *other than* `special` and we won't get a
- /// default value.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("opt")
- /// .takes_value(true)
- /// .long("opt"))
- /// .arg(Arg::with_name("other")
- /// .long("other")
- /// .default_value_if("opt", Some("special"), "default"))
- /// .get_matches_from(vec![
- /// "prog", "--opt", "hahaha"
- /// ]);
- ///
- /// assert_eq!(m.value_of("other"), None);
- /// ```
- /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
- /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value
- pub fn default_value_if(self, arg: &'a str, val: Option<&'b str>, default: &'b str) -> Self {
- self.default_value_if_os(
- arg,
- val.map(str::as_bytes).map(OsStr::from_bytes),
- OsStr::from_bytes(default.as_bytes()),
- )
- }
-
- /// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`]
- /// only using [`OsStr`]s instead.
- /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if
- /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
- pub fn default_value_if_os(
- mut self,
- arg: &'a str,
- val: Option<&'b OsStr>,
- default: &'b OsStr,
- ) -> Self {
- self.setb(ArgSettings::TakesValue);
- if let Some(ref mut vm) = self.v.default_vals_ifs {
- let l = vm.len();
- vm.insert(l, (arg, val, default));
- } else {
- let mut vm = VecMap::new();
- vm.insert(0, (arg, val, default));
- self.v.default_vals_ifs = Some(vm);
- }
- self
- }
-
- /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`].
- /// The method takes a slice of tuples in the `(arg, Option<val>, default)` format.
- ///
- /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first
- /// if multiple conditions are true, the first one found will be applied and the ultimate value.
- ///
- /// **NOTE:** If using YAML the values should be laid out as follows
- ///
- /// ```yaml
- /// default_value_if:
- /// - [arg, val, default]
- /// - [arg2, null, default2]
- /// ```
- ///
- /// # Examples
- ///
- /// First we use the default value only if another arg is present at runtime.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("flag")
- /// .long("flag"))
- /// .arg(Arg::with_name("opt")
- /// .long("opt")
- /// .takes_value(true))
- /// .arg(Arg::with_name("other")
- /// .long("other")
- /// .default_value_ifs(&[
- /// ("flag", None, "default"),
- /// ("opt", Some("channal"), "chan"),
- /// ]))
- /// .get_matches_from(vec![
- /// "prog", "--opt", "channal"
- /// ]);
- ///
- /// assert_eq!(m.value_of("other"), Some("chan"));
- /// ```
- ///
- /// Next we run the same test, but without providing `--flag`.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("flag")
- /// .long("flag"))
- /// .arg(Arg::with_name("other")
- /// .long("other")
- /// .default_value_ifs(&[
- /// ("flag", None, "default"),
- /// ("opt", Some("channal"), "chan"),
- /// ]))
- /// .get_matches_from(vec![
- /// "prog"
- /// ]);
- ///
- /// assert_eq!(m.value_of("other"), None);
- /// ```
- ///
- /// We can also see that these values are applied in order, and if more than one condition is
- /// true, only the first evaluated "wins"
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("flag")
- /// .long("flag"))
- /// .arg(Arg::with_name("opt")
- /// .long("opt")
- /// .takes_value(true))
- /// .arg(Arg::with_name("other")
- /// .long("other")
- /// .default_value_ifs(&[
- /// ("flag", None, "default"),
- /// ("opt", Some("channal"), "chan"),
- /// ]))
- /// .get_matches_from(vec![
- /// "prog", "--opt", "channal", "--flag"
- /// ]);
- ///
- /// assert_eq!(m.value_of("other"), Some("default"));
- /// ```
- /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
- /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value
- pub fn default_value_ifs(mut self, ifs: &[(&'a str, Option<&'b str>, &'b str)]) -> Self {
- for &(arg, val, default) in ifs {
- self = self.default_value_if_os(
- arg,
- val.map(str::as_bytes).map(OsStr::from_bytes),
- OsStr::from_bytes(default.as_bytes()),
- );
- }
- self
- }
-
- /// Provides multiple conditional default values in the exact same manner as
- /// [`Arg::default_value_ifs`] only using [`OsStr`]s instead.
- /// [`Arg::default_value_ifs`]: ./struct.Arg.html#method.default_value_ifs
- /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
- #[cfg_attr(feature = "lints", allow(explicit_counter_loop))]
- pub fn default_value_ifs_os(mut self, ifs: &[(&'a str, Option<&'b OsStr>, &'b OsStr)]) -> Self {
- for &(arg, val, default) in ifs {
- self = self.default_value_if_os(arg, val, default);
- }
- self
- }
-
- /// Specifies that if the value is not passed in as an argument, that it should be retrieved
- /// from the environment, if available. If it is not present in the environment, then default
- /// rules will apply.
- ///
- /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`]
- /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified.
- ///
- /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::is_present`] will
- /// return `true` if the variable is present in the environment . If you wish to determine whether
- /// the argument was used at runtime or not, consider [`ArgMatches::occurrences_of`] which will
- /// return `0` if the argument was *not* used at runtime.
- ///
- /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
- ///
- /// **NOTE:** If [`Arg::multiple(true)`] is set then [`Arg::use_delimiter(true)`] should also be
- /// set. Otherwise, only a single argument will be returned from the environment variable. The
- /// default delimiter is `,` and follows all the other delimiter rules.
- ///
- /// # Examples
- ///
- /// In this example, we show the variable coming from the environment:
- ///
- /// ```rust
- /// # use std::env;
- /// # use clap::{App, Arg};
- ///
- /// env::set_var("MY_FLAG", "env");
- ///
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("flag")
- /// .long("flag")
- /// .env("MY_FLAG"))
- /// .get_matches_from(vec![
- /// "prog"
- /// ]);
- ///
- /// assert_eq!(m.value_of("flag"), Some("env"));
- /// ```
- ///
- /// In this example, we show the variable coming from an option on the CLI:
- ///
- /// ```rust
- /// # use std::env;
- /// # use clap::{App, Arg};
- ///
- /// env::set_var("MY_FLAG", "env");
- ///
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("flag")
- /// .long("flag")
- /// .env("MY_FLAG"))
- /// .get_matches_from(vec![
- /// "prog", "--flag", "opt"
- /// ]);
- ///
- /// assert_eq!(m.value_of("flag"), Some("opt"));
- /// ```
- ///
- /// In this example, we show the variable coming from the environment even with the
- /// presence of a default:
- ///
- /// ```rust
- /// # use std::env;
- /// # use clap::{App, Arg};
- ///
- /// env::set_var("MY_FLAG", "env");
- ///
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("flag")
- /// .long("flag")
- /// .env("MY_FLAG")
- /// .default_value("default"))
- /// .get_matches_from(vec![
- /// "prog"
- /// ]);
- ///
- /// assert_eq!(m.value_of("flag"), Some("env"));
- /// ```
- ///
- /// In this example, we show the use of multiple values in a single environment variable:
- ///
- /// ```rust
- /// # use std::env;
- /// # use clap::{App, Arg};
- ///
- /// env::set_var("MY_FLAG_MULTI", "env1,env2");
- ///
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("flag")
- /// .long("flag")
- /// .env("MY_FLAG_MULTI")
- /// .multiple(true)
- /// .use_delimiter(true))
- /// .get_matches_from(vec![
- /// "prog"
- /// ]);
- ///
- /// assert_eq!(m.values_of("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]);
- /// ```
- /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of
- /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of
- /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present
- /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
- /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
- /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter
- pub fn env(self, name: &'a str) -> Self {
- self.env_os(OsStr::new(name))
- }
-
- /// Specifies that if the value is not passed in as an argument, that it should be retrieved
- /// from the environment if available in the exact same manner as [`Arg::env`] only using
- /// [`OsStr`]s instead.
- pub fn env_os(mut self, name: &'a OsStr) -> Self {
- self.setb(ArgSettings::TakesValue);
-
- self.v.env = Some((name, env::var_os(name)));
- self
- }
-
- /// @TODO @p2 @docs @release: write docs
- pub fn hide_env_values(self, hide: bool) -> Self {
- if hide {
- self.set(ArgSettings::HideEnvValues)
- } else {
- self.unset(ArgSettings::HideEnvValues)
- }
- }
-
- /// When set to `true` the help string will be displayed on the line after the argument and
- /// indented once. This can be helpful for arguments with very long or complex help messages.
- /// This can also be helpful for arguments with very long flag names, or many/long value names.
- ///
- /// **NOTE:** To apply this setting to all arguments consider using
- /// [`AppSettings::NextLineHelp`]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("opt")
- /// .long("long-option-flag")
- /// .short("o")
- /// .takes_value(true)
- /// .value_names(&["value1", "value2"])
- /// .help("Some really long help and complex\n\
- /// help that makes more sense to be\n\
- /// on a line after the option")
- /// .next_line_help(true))
- /// .get_matches_from(vec![
- /// "prog", "--help"
- /// ]);
- /// ```
- ///
- /// The above example displays the following help message
- ///
- /// ```notrust
- /// nlh
- ///
- /// USAGE:
- /// nlh [FLAGS] [OPTIONS]
- ///
- /// FLAGS:
- /// -h, --help Prints help information
- /// -V, --version Prints version information
- ///
- /// OPTIONS:
- /// -o, --long-option-flag <value1> <value2>
- /// Some really long help and complex
- /// help that makes more sense to be
- /// on a line after the option
- /// ```
- /// [`AppSettings::NextLineHelp`]: ./enum.AppSettings.html#variant.NextLineHelp
- pub fn next_line_help(mut self, nlh: bool) -> Self {
- if nlh {
- self.setb(ArgSettings::NextLineHelp);
- } else {
- self.unsetb(ArgSettings::NextLineHelp);
- }
- self
- }
-
- /// Allows custom ordering of args within the help message. Args with a lower value will be
- /// displayed first in the help message. This is helpful when one would like to emphasise
- /// frequently used args, or prioritize those towards the top of the list. Duplicate values
- /// **are** allowed. Args with duplicate display orders will be displayed in alphabetical
- /// order.
- ///
- /// **NOTE:** The default is 999 for all arguments.
- ///
- /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in
- /// [index] order.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("a") // Typically args are grouped alphabetically by name.
- /// // Args without a display_order have a value of 999 and are
- /// // displayed alphabetically with all other 999 valued args.
- /// .long("long-option")
- /// .short("o")
- /// .takes_value(true)
- /// .help("Some help and text"))
- /// .arg(Arg::with_name("b")
- /// .long("other-option")
- /// .short("O")
- /// .takes_value(true)
- /// .display_order(1) // In order to force this arg to appear *first*
- /// // all we have to do is give it a value lower than 999.
- /// // Any other args with a value of 1 will be displayed
- /// // alphabetically with this one...then 2 values, then 3, etc.
- /// .help("I should be first!"))
- /// .get_matches_from(vec![
- /// "prog", "--help"
- /// ]);
- /// ```
- ///
- /// The above example displays the following help message
- ///
- /// ```notrust
- /// cust-ord
- ///
- /// USAGE:
- /// cust-ord [FLAGS] [OPTIONS]
- ///
- /// FLAGS:
- /// -h, --help Prints help information
- /// -V, --version Prints version information
- ///
- /// OPTIONS:
- /// -O, --other-option <b> I should be first!
- /// -o, --long-option <a> Some help and text
- /// ```
- /// [positional arguments]: ./struct.Arg.html#method.index
- /// [index]: ./struct.Arg.html#method.index
- pub fn display_order(mut self, ord: usize) -> Self {
- self.s.disp_ord = ord;
- self
- }
-
- /// Indicates that all parameters passed after this should not be parsed
- /// individually, but rather passed in their entirety. It is worth noting
- /// that setting this requires all values to come after a `--` to indicate they
- /// should all be captured. For example:
- ///
- /// ```notrust
- /// --foo something -- -v -v -v -b -b -b --baz -q -u -x
- /// ```
- /// Will result in everything after `--` to be considered one raw argument. This behavior
- /// may not be exactly what you are expecting and using [`AppSettings::TrailingVarArg`]
- /// may be more appropriate.
- ///
- /// **NOTE:** Implicitly sets [`Arg::multiple(true)`], [`Arg::allow_hyphen_values(true)`], and
- /// [`Arg::last(true)`] when set to `true`
- ///
- /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
- /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values
- /// [`Arg::last(true)`]: ./struct.Arg.html#method.last
- /// [`AppSettings::TrailingVarArg`]: ./enum.AppSettings.html#variant.TrailingVarArg
- pub fn raw(self, raw: bool) -> Self {
- self.multiple(raw).allow_hyphen_values(raw).last(raw)
- }
-
- /// Hides an argument from short help message output.
- ///
- /// **NOTE:** This does **not** hide the argument from usage strings on error
- ///
- /// **NOTE:** Setting this option will cause next-line-help output style to be used
- /// when long help (`--help`) is called.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("debug")
- /// .hidden_short_help(true)
- /// # ;
- /// ```
- /// Setting `hidden_short_help(true)` will hide the argument when displaying short help text
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .long("config")
- /// .hidden_short_help(true)
- /// .help("Some help text describing the --config arg"))
- /// .get_matches_from(vec![
- /// "prog", "-h"
- /// ]);
- /// ```
- ///
- /// The above example displays
- ///
- /// ```notrust
- /// helptest
- ///
- /// USAGE:
- /// helptest [FLAGS]
- ///
- /// FLAGS:
- /// -h, --help Prints help information
- /// -V, --version Prints version information
- /// ```
- ///
- /// However, when --help is called
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .long("config")
- /// .hidden_short_help(true)
- /// .help("Some help text describing the --config arg"))
- /// .get_matches_from(vec![
- /// "prog", "--help"
- /// ]);
- /// ```
- ///
- /// Then the following would be displayed
- ///
- /// ```notrust
- /// helptest
- ///
- /// USAGE:
- /// helptest [FLAGS]
- ///
- /// FLAGS:
- /// --config Some help text describing the --config arg
- /// -h, --help Prints help information
- /// -V, --version Prints version information
- /// ```
- pub fn hidden_short_help(self, hide: bool) -> Self {
- if hide {
- self.set(ArgSettings::HiddenShortHelp)
- } else {
- self.unset(ArgSettings::HiddenShortHelp)
- }
- }
-
- /// Hides an argument from long help message output.
- ///
- /// **NOTE:** This does **not** hide the argument from usage strings on error
- ///
- /// **NOTE:** Setting this option will cause next-line-help output style to be used
- /// when long help (`--help`) is called.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// Arg::with_name("debug")
- /// .hidden_long_help(true)
- /// # ;
- /// ```
- /// Setting `hidden_long_help(true)` will hide the argument when displaying long help text
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .long("config")
- /// .hidden_long_help(true)
- /// .help("Some help text describing the --config arg"))
- /// .get_matches_from(vec![
- /// "prog", "--help"
- /// ]);
- /// ```
- ///
- /// The above example displays
- ///
- /// ```notrust
- /// helptest
- ///
- /// USAGE:
- /// helptest [FLAGS]
- ///
- /// FLAGS:
- /// -h, --help Prints help information
- /// -V, --version Prints version information
- /// ```
- ///
- /// However, when -h is called
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("prog")
- /// .arg(Arg::with_name("cfg")
- /// .long("config")
- /// .hidden_long_help(true)
- /// .help("Some help text describing the --config arg"))
- /// .get_matches_from(vec![
- /// "prog", "-h"
- /// ]);
- /// ```
- ///
- /// Then the following would be displayed
- ///
- /// ```notrust
- /// helptest
- ///
- /// USAGE:
- /// helptest [FLAGS]
- ///
- /// FLAGS:
- /// --config Some help text describing the --config arg
- /// -h, --help Prints help information
- /// -V, --version Prints version information
- /// ```
- pub fn hidden_long_help(self, hide: bool) -> Self {
- if hide {
- self.set(ArgSettings::HiddenLongHelp)
- } else {
- self.unset(ArgSettings::HiddenLongHelp)
- }
- }
-
- /// Checks if one of the [`ArgSettings`] settings is set for the argument.
- ///
- /// [`ArgSettings`]: ./enum.ArgSettings.html
- pub fn is_set(&self, s: ArgSettings) -> bool {
- self.b.is_set(s)
- }
-
- /// Sets one of the [`ArgSettings`] settings for the argument.
- ///
- /// [`ArgSettings`]: ./enum.ArgSettings.html
- pub fn set(mut self, s: ArgSettings) -> Self {
- self.setb(s);
- self
- }
-
- /// Unsets one of the [`ArgSettings`] settings for the argument.
- ///
- /// [`ArgSettings`]: ./enum.ArgSettings.html
- pub fn unset(mut self, s: ArgSettings) -> Self {
- self.unsetb(s);
- self
- }
-
- #[doc(hidden)]
- pub fn setb(&mut self, s: ArgSettings) {
- self.b.set(s);
- }
-
- #[doc(hidden)]
- pub fn unsetb(&mut self, s: ArgSettings) {
- self.b.unset(s);
- }
-}
-
-impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for Arg<'a, 'b> {
- fn from(a: &'z Arg<'a, 'b>) -> Self {
- Arg {
- b: a.b.clone(),
- v: a.v.clone(),
- s: a.s.clone(),
- index: a.index,
- r_ifs: a.r_ifs.clone(),
- }
- }
-}
-
-impl<'n, 'e> PartialEq for Arg<'n, 'e> {
- fn eq(&self, other: &Arg<'n, 'e>) -> bool {
- self.b == other.b
- }
-}
diff --git a/src/args/arg_builder/base.rs b/src/args/arg_builder/base.rs
deleted file mode 100644
index cc8de72..0000000
--- a/src/args/arg_builder/base.rs
+++ /dev/null
@@ -1,48 +0,0 @@
-use args::{Arg, ArgFlags, ArgSettings};
-
-#[derive(Debug, Clone, Default)]
-pub struct Base<'a, 'b>
-where
- 'a: 'b,
-{
- pub name: &'a str,
- pub help: Option<&'b str>,
- pub long_help: Option<&'b str>,
- pub blacklist: Option<Vec<&'a str>>,
- pub settings: ArgFlags,
- pub r_unless: Option<Vec<&'a str>>,
- pub overrides: Option<Vec<&'a str>>,
- pub groups: Option<Vec<&'a str>>,
- pub requires: Option<Vec<(Option<&'b str>, &'a str)>>,
-}
-
-impl<'n, 'e> Base<'n, 'e> {
- pub fn new(name: &'n str) -> Self {
- Base {
- name: name,
- ..Default::default()
- }
- }
-
- pub fn set(&mut self, s: ArgSettings) {
- self.settings.set(s);
- }
- pub fn unset(&mut self, s: ArgSettings) {
- self.settings.unset(s);
- }
- pub fn is_set(&self, s: ArgSettings) -> bool {
- self.settings.is_set(s)
- }
-}
-
-impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Base<'n, 'e> {
- fn from(a: &'z Arg<'n, 'e>) -> Self {
- a.b.clone()
- }
-}
-
-impl<'n, 'e> PartialEq for Base<'n, 'e> {
- fn eq(&self, other: &Base<'n, 'e>) -> bool {
- self.name == other.name
- }
-}
diff --git a/src/args/arg_builder/flag.rs b/src/args/arg_builder/flag.rs
deleted file mode 100644
index 4b92231..0000000
--- a/src/args/arg_builder/flag.rs
+++ /dev/null
@@ -1,211 +0,0 @@
-// Std
-use std::convert::From;
-use std::ffi::{OsStr, OsString};
-use std::fmt::{Display, Formatter, Result};
-use std::mem;
-use std::rc::Rc;
-use std::result::Result as StdResult;
-
-// Internal
-use args::{AnyArg, ArgSettings, Base, DispOrder, Switched};
-use map::{self, VecMap};
-use Arg;
-
-#[derive(Default, Clone, Debug)]
-#[doc(hidden)]
-pub struct FlagBuilder<'n, 'e>
-where
- 'n: 'e,
-{
- pub b: Base<'n, 'e>,
- pub s: Switched<'e>,
-}
-
-impl<'n, 'e> FlagBuilder<'n, 'e> {
- pub fn new(name: &'n str) -> Self {
- FlagBuilder {
- b: Base::new(name),
- ..Default::default()
- }
- }
-}
-
-impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for FlagBuilder<'a, 'b> {
- fn from(a: &'z Arg<'a, 'b>) -> Self {
- FlagBuilder {
- b: Base::from(a),
- s: Switched::from(a),
- }
- }
-}
-
-impl<'a, 'b> From<Arg<'a, 'b>> for FlagBuilder<'a, 'b> {
- fn from(mut a: Arg<'a, 'b>) -> Self {
- FlagBuilder {
- b: mem::replace(&mut a.b, Base::default()),
- s: mem::replace(&mut a.s, Switched::default()),
- }
- }
-}
-
-impl<'n, 'e> Display for FlagBuilder<'n, 'e> {
- fn fmt(&self, f: &mut Formatter) -> Result {
- if let Some(l) = self.s.long {
- write!(f, "--{}", l)?;
- } else {
- write!(f, "-{}", self.s.short.unwrap())?;
- }
-
- Ok(())
- }
-}
-
-impl<'n, 'e> AnyArg<'n, 'e> for FlagBuilder<'n, 'e> {
- fn name(&self) -> &'n str {
- self.b.name
- }
- fn overrides(&self) -> Option<&[&'e str]> {
- self.b.overrides.as_ref().map(|o| &o[..])
- }
- fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> {
- self.b.requires.as_ref().map(|o| &o[..])
- }
- fn blacklist(&self) -> Option<&[&'e str]> {
- self.b.blacklist.as_ref().map(|o| &o[..])
- }
- fn required_unless(&self) -> Option<&[&'e str]> {
- self.b.r_unless.as_ref().map(|o| &o[..])
- }
- fn is_set(&self, s: ArgSettings) -> bool {
- self.b.settings.is_set(s)
- }
- fn has_switch(&self) -> bool {
- true
- }
- fn takes_value(&self) -> bool {
- false
- }
- fn set(&mut self, s: ArgSettings) {
- self.b.settings.set(s)
- }
- fn max_vals(&self) -> Option<u64> {
- None
- }
- fn val_names(&self) -> Option<&VecMap<&'e str>> {
- None
- }
- fn num_vals(&self) -> Option<u64> {
- None
- }
- fn possible_vals(&self) -> Option<&[&'e str]> {
- None
- }
- fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> {
- None
- }
- fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> {
- None
- }
- fn min_vals(&self) -> Option<u64> {
- None
- }
- fn short(&self) -> Option<char> {
- self.s.short
- }
- fn long(&self) -> Option<&'e str> {
- self.s.long
- }
- fn val_delim(&self) -> Option<char> {
- None
- }
- fn help(&self) -> Option<&'e str> {
- self.b.help
- }
- fn long_help(&self) -> Option<&'e str> {
- self.b.long_help
- }
- fn val_terminator(&self) -> Option<&'e str> {
- None
- }
- fn default_val(&self) -> Option<&'e OsStr> {
- None
- }
- fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> {
- None
- }
- fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> {
- None
- }
- fn longest_filter(&self) -> bool {
- self.s.long.is_some()
- }
- fn aliases(&self) -> Option<Vec<&'e str>> {
- if let Some(ref aliases) = self.s.aliases {
- let vis_aliases: Vec<_> = aliases
- .iter()
- .filter_map(|&(n, v)| if v { Some(n) } else { None })
- .collect();
- if vis_aliases.is_empty() {
- None
- } else {
- Some(vis_aliases)
- }
- } else {
- None
- }
- }
-}
-
-impl<'n, 'e> DispOrder for FlagBuilder<'n, 'e> {
- fn disp_ord(&self) -> usize {
- self.s.disp_ord
- }
-}
-
-impl<'n, 'e> PartialEq for FlagBuilder<'n, 'e> {
- fn eq(&self, other: &FlagBuilder<'n, 'e>) -> bool {
- self.b == other.b
- }
-}
-
-#[cfg(test)]
-mod test {
- use super::FlagBuilder;
- use args::settings::ArgSettings;
-
- #[test]
- fn flagbuilder_display() {
- let mut f = FlagBuilder::new("flg");
- f.b.settings.set(ArgSettings::Multiple);
- f.s.long = Some("flag");
-
- assert_eq!(&*format!("{}", f), "--flag");
-
- let mut f2 = FlagBuilder::new("flg");
- f2.s.short = Some('f');
-
- assert_eq!(&*format!("{}", f2), "-f");
- }
-
- #[test]
- fn flagbuilder_display_single_alias() {
- let mut f = FlagBuilder::new("flg");
- f.s.long = Some("flag");
- f.s.aliases = Some(vec![("als", true)]);
-
- assert_eq!(&*format!("{}", f), "--flag");
- }
-
- #[test]
- fn flagbuilder_display_multiple_aliases() {
- let mut f = FlagBuilder::new("flg");
- f.s.short = Some('f');
- f.s.aliases = Some(vec![
- ("alias_not_visible", false),
- ("f2", true),
- ("f3", true),
- ("f4", true),
- ]);
- assert_eq!(&*format!("{}", f), "-f");
- }
-}
diff --git a/src/args/arg_builder/mod.rs b/src/args/arg_builder/mod.rs
deleted file mode 100644
index 2d79208..0000000
--- a/src/args/arg_builder/mod.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-pub use self::base::Base;
-pub use self::flag::FlagBuilder;
-pub use self::option::OptBuilder;
-pub use self::positional::PosBuilder;
-pub use self::switched::Switched;
-pub use self::valued::Valued;
-
-mod base;
-mod flag;
-mod option;
-mod positional;
-mod switched;
-mod valued;
diff --git a/src/args/arg_builder/option.rs b/src/args/arg_builder/option.rs
deleted file mode 100644
index 45d41fa..0000000
--- a/src/args/arg_builder/option.rs
+++ /dev/null
@@ -1,290 +0,0 @@
-// Std
-use std::ffi::{OsStr, OsString};
-use std::fmt::{Display, Formatter, Result};
-use std::mem;
-use std::rc::Rc;
-use std::result::Result as StdResult;
-
-// Internal
-use args::{AnyArg, Arg, ArgSettings, Base, DispOrder, Switched, Valued};
-use map::{self, VecMap};
-use INTERNAL_ERROR_MSG;
-
-#[allow(missing_debug_implementations)]
-#[doc(hidden)]
-#[derive(Default, Clone)]
-pub struct OptBuilder<'n, 'e>
-where
- 'n: 'e,
-{
- pub b: Base<'n, 'e>,
- pub s: Switched<'e>,
- pub v: Valued<'n, 'e>,
-}
-
-impl<'n, 'e> OptBuilder<'n, 'e> {
- pub fn new(name: &'n str) -> Self {
- OptBuilder {
- b: Base::new(name),
- ..Default::default()
- }
- }
-}
-
-impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for OptBuilder<'n, 'e> {
- fn from(a: &'z Arg<'n, 'e>) -> Self {
- OptBuilder {
- b: Base::from(a),
- s: Switched::from(a),
- v: Valued::from(a),
- }
- }
-}
-
-impl<'n, 'e> From<Arg<'n, 'e>> for OptBuilder<'n, 'e> {
- fn from(mut a: Arg<'n, 'e>) -> Self {
- a.v.fill_in();
- OptBuilder {
- b: mem::replace(&mut a.b, Base::default()),
- s: mem::replace(&mut a.s, Switched::default()),
- v: mem::replace(&mut a.v, Valued::default()),
- }
- }
-}
-
-impl<'n, 'e> Display for OptBuilder<'n, 'e> {
- fn fmt(&self, f: &mut Formatter) -> Result {
- debugln!("OptBuilder::fmt:{}", self.b.name);
- let sep = if self.b.is_set(ArgSettings::RequireEquals) {
- "="
- } else {
- " "
- };
- // Write the name such --long or -l
- if let Some(l) = self.s.long {
- write!(f, "--{}{}", l, sep)?;
- } else {
- write!(f, "-{}{}", self.s.short.unwrap(), sep)?;
- }
- let delim = if self.is_set(ArgSettings::RequireDelimiter) {
- self.v.val_delim.expect(INTERNAL_ERROR_MSG)
- } else {
- ' '
- };
-
- // Write the values such as <name1> <name2>
- if let Some(ref vec) = self.v.val_names {
- let mut it = vec.iter().peekable();
- while let Some((_, val)) = it.next() {
- write!(f, "<{}>", val)?;
- if it.peek().is_some() {
- write!(f, "{}", delim)?;
- }
- }
- let num = vec.len();
- if self.is_set(ArgSettings::Multiple) && num == 1 {
- write!(f, "...")?;
- }
- } else if let Some(num) = self.v.num_vals {
- let mut it = (0..num).peekable();
- while let Some(_) = it.next() {
- write!(f, "<{}>", self.b.name)?;
- if it.peek().is_some() {
- write!(f, "{}", delim)?;
- }
- }
- if self.is_set(ArgSettings::Multiple) && num == 1 {
- write!(f, "...")?;
- }
- } else {
- write!(
- f,
- "<{}>{}",
- self.b.name,
- if self.is_set(ArgSettings::Multiple) {
- "..."
- } else {
- ""
- }
- )?;
- }
-
- Ok(())
- }
-}
-
-impl<'n, 'e> AnyArg<'n, 'e> for OptBuilder<'n, 'e> {
- fn name(&self) -> &'n str {
- self.b.name
- }
- fn overrides(&self) -> Option<&[&'e str]> {
- self.b.overrides.as_ref().map(|o| &o[..])
- }
- fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> {
- self.b.requires.as_ref().map(|o| &o[..])
- }
- fn blacklist(&self) -> Option<&[&'e str]> {
- self.b.blacklist.as_ref().map(|o| &o[..])
- }
- fn required_unless(&self) -> Option<&[&'e str]> {
- self.b.r_unless.as_ref().map(|o| &o[..])
- }
- fn val_names(&self) -> Option<&VecMap<&'e str>> {
- self.v.val_names.as_ref()
- }
- fn is_set(&self, s: ArgSettings) -> bool {
- self.b.settings.is_set(s)
- }
- fn has_switch(&self) -> bool {
- true
- }
- fn set(&mut self, s: ArgSettings) {
- self.b.settings.set(s)
- }
- fn max_vals(&self) -> Option<u64> {
- self.v.max_vals
- }
- fn val_terminator(&self) -> Option<&'e str> {
- self.v.terminator
- }
- fn num_vals(&self) -> Option<u64> {
- self.v.num_vals
- }
- fn possible_vals(&self) -> Option<&[&'e str]> {
- self.v.possible_vals.as_ref().map(|o| &o[..])
- }
- fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> {
- self.v.validator.as_ref()
- }
- fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> {
- self.v.validator_os.as_ref()
- }
- fn min_vals(&self) -> Option<u64> {
- self.v.min_vals
- }
- fn short(&self) -> Option<char> {
- self.s.short
- }
- fn long(&self) -> Option<&'e str> {
- self.s.long
- }
- fn val_delim(&self) -> Option<char> {
- self.v.val_delim
- }
- fn takes_value(&self) -> bool {
- true
- }
- fn help(&self) -> Option<&'e str> {
- self.b.help
- }
- fn long_help(&self) -> Option<&'e str> {
- self.b.long_help
- }
- fn default_val(&self) -> Option<&'e OsStr> {
- self.v.default_val
- }
- fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> {
- self.v.default_vals_ifs.as_ref().map(|vm| vm.values())
- }
- fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> {
- self.v
- .env
- .as_ref()
- .map(|&(key, ref value)| (key, value.as_ref()))
- }
- fn longest_filter(&self) -> bool {
- true
- }
- fn aliases(&self) -> Option<Vec<&'e str>> {
- if let Some(ref aliases) = self.s.aliases {
- let vis_aliases: Vec<_> = aliases
- .iter()
- .filter_map(|&(n, v)| if v { Some(n) } else { None })
- .collect();
- if vis_aliases.is_empty() {
- None
- } else {
- Some(vis_aliases)
- }
- } else {
- None
- }
- }
-}
-
-impl<'n, 'e> DispOrder for OptBuilder<'n, 'e> {
- fn disp_ord(&self) -> usize {
- self.s.disp_ord
- }
-}
-
-impl<'n, 'e> PartialEq for OptBuilder<'n, 'e> {
- fn eq(&self, other: &OptBuilder<'n, 'e>) -> bool {
- self.b == other.b
- }
-}
-
-#[cfg(test)]
-mod test {
- use super::OptBuilder;
- use args::settings::ArgSettings;
- use map::VecMap;
-
- #[test]
- fn optbuilder_display1() {
- let mut o = OptBuilder::new("opt");
- o.s.long = Some("option");
- o.b.settings.set(ArgSettings::Multiple);
-
- assert_eq!(&*format!("{}", o), "--option <opt>...");
- }
-
- #[test]
- fn optbuilder_display2() {
- let mut v_names = VecMap::new();
- v_names.insert(0, "file");
- v_names.insert(1, "name");
-
- let mut o2 = OptBuilder::new("opt");
- o2.s.short = Some('o');
- o2.v.val_names = Some(v_names);
-
- assert_eq!(&*format!("{}", o2), "-o <file> <name>");
- }
-
- #[test]
- fn optbuilder_display3() {
- let mut v_names = VecMap::new();
- v_names.insert(0, "file");
- v_names.insert(1, "name");
-
- let mut o2 = OptBuilder::new("opt");
- o2.s.short = Some('o');
- o2.v.val_names = Some(v_names);
- o2.b.settings.set(ArgSettings::Multiple);
-
- assert_eq!(&*format!("{}", o2), "-o <file> <name>");
- }
-
- #[test]
- fn optbuilder_display_single_alias() {
- let mut o = OptBuilder::new("opt");
- o.s.long = Some("option");
- o.s.aliases = Some(vec![("als", true)]);
-
- assert_eq!(&*format!("{}", o), "--option <opt>");
- }
-
- #[test]
- fn optbuilder_display_multiple_aliases() {
- let mut o = OptBuilder::new("opt");
- o.s.long = Some("option");
- o.s.aliases = Some(vec![
- ("als_not_visible", false),
- ("als2", true),
- ("als3", true),
- ("als4", true),
- ]);
- assert_eq!(&*format!("{}", o), "--option <opt>");
- }
-}
diff --git a/src/args/arg_builder/positional.rs b/src/args/arg_builder/positional.rs
deleted file mode 100644
index 6d8c1fe..0000000
--- a/src/args/arg_builder/positional.rs
+++ /dev/null
@@ -1,280 +0,0 @@
-// Std
-use std::borrow::Cow;
-use std::ffi::{OsStr, OsString};
-use std::fmt::{Display, Formatter, Result};
-use std::mem;
-use std::rc::Rc;
-use std::result::Result as StdResult;
-
-// Internal
-use args::{AnyArg, ArgSettings, Base, DispOrder, Valued};
-use map::{self, VecMap};
-use Arg;
-use INTERNAL_ERROR_MSG;
-
-#[allow(missing_debug_implementations)]
-#[doc(hidden)]
-#[derive(Clone, Default)]
-pub struct PosBuilder<'n, 'e>
-where
- 'n: 'e,
-{
- pub b: Base<'n, 'e>,
- pub v: Valued<'n, 'e>,
- pub index: u64,
-}
-
-impl<'n, 'e> PosBuilder<'n, 'e> {
- pub fn new(name: &'n str, idx: u64) -> Self {
- PosBuilder {
- b: Base::new(name),
- index: idx,
- ..Default::default()
- }
- }
-
- pub fn from_arg_ref(a: &Arg<'n, 'e>, idx: u64) -> Self {
- let mut pb = PosBuilder {
- b: Base::from(a),
- v: Valued::from(a),
- index: idx,
- };
- if a.v.max_vals.is_some()
- || a.v.min_vals.is_some()
- || (a.v.num_vals.is_some() && a.v.num_vals.unwrap() > 1)
- {
- pb.b.settings.set(ArgSettings::Multiple);
- }
- pb
- }
-
- pub fn from_arg(mut a: Arg<'n, 'e>, idx: u64) -> Self {
- if a.v.max_vals.is_some()
- || a.v.min_vals.is_some()
- || (a.v.num_vals.is_some() && a.v.num_vals.unwrap() > 1)
- {
- a.b.settings.set(ArgSettings::Multiple);
- }
- PosBuilder {
- b: mem::replace(&mut a.b, Base::default()),
- v: mem::replace(&mut a.v, Valued::default()),
- index: idx,
- }
- }
-
- pub fn multiple_str(&self) -> &str {
- let mult_vals = self
- .v
- .val_names
- .as_ref()
- .map_or(true, |names| names.len() < 2);
- if self.is_set(ArgSettings::Multiple) && mult_vals {
- "..."
- } else {
- ""
- }
- }
-
- pub fn name_no_brackets(&self) -> Cow<str> {
- debugln!("PosBuilder::name_no_brackets;");
- let mut delim = String::new();
- delim.push(if self.is_set(ArgSettings::RequireDelimiter) {
- self.v.val_delim.expect(INTERNAL_ERROR_MSG)
- } else {
- ' '
- });
- if let Some(ref names) = self.v.val_names {
- debugln!("PosBuilder:name_no_brackets: val_names={:#?}", names);
- if names.len() > 1 {
- Cow::Owned(
- names
- .values()
- .map(|n| format!("<{}>", n))
- .collect::<Vec<_>>()
- .join(&*delim),
- )
- } else {
- Cow::Borrowed(names.values().next().expect(INTERNAL_ERROR_MSG))
- }
- } else {
- debugln!("PosBuilder:name_no_brackets: just name");
- Cow::Borrowed(self.b.name)
- }
- }
-}
-
-impl<'n, 'e> Display for PosBuilder<'n, 'e> {
- fn fmt(&self, f: &mut Formatter) -> Result {
- let mut delim = String::new();
- delim.push(if self.is_set(ArgSettings::RequireDelimiter) {
- self.v.val_delim.expect(INTERNAL_ERROR_MSG)
- } else {
- ' '
- });
- if let Some(ref names) = self.v.val_names {
- write!(
- f,
- "{}",
- names
- .values()
- .map(|n| format!("<{}>", n))
- .collect::<Vec<_>>()
- .join(&*delim)
- )?;
- } else {
- write!(f, "<{}>", self.b.name)?;
- }
- if self.b.settings.is_set(ArgSettings::Multiple)
- && (self.v.val_names.is_none() || self.v.val_names.as_ref().unwrap().len() == 1)
- {
- write!(f, "...")?;
- }
-
- Ok(())
- }
-}
-
-impl<'n, 'e> AnyArg<'n, 'e> for PosBuilder<'n, 'e> {
- fn name(&self) -> &'n str {
- self.b.name
- }
- fn overrides(&self) -> Option<&[&'e str]> {
- self.b.overrides.as_ref().map(|o| &o[..])
- }
- fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> {
- self.b.requires.as_ref().map(|o| &o[..])
- }
- fn blacklist(&self) -> Option<&[&'e str]> {
- self.b.blacklist.as_ref().map(|o| &o[..])
- }
- fn required_unless(&self) -> Option<&[&'e str]> {
- self.b.r_unless.as_ref().map(|o| &o[..])
- }
- fn val_names(&self) -> Option<&VecMap<&'e str>> {
- self.v.val_names.as_ref()
- }
- fn is_set(&self, s: ArgSettings) -> bool {
- self.b.settings.is_set(s)
- }
- fn set(&mut self, s: ArgSettings) {
- self.b.settings.set(s)
- }
- fn has_switch(&self) -> bool {
- false
- }
- fn max_vals(&self) -> Option<u64> {
- self.v.max_vals
- }
- fn val_terminator(&self) -> Option<&'e str> {
- self.v.terminator
- }
- fn num_vals(&self) -> Option<u64> {
- self.v.num_vals
- }
- fn possible_vals(&self) -> Option<&[&'e str]> {
- self.v.possible_vals.as_ref().map(|o| &o[..])
- }
- fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> {
- self.v.validator.as_ref()
- }
- fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> {
- self.v.validator_os.as_ref()
- }
- fn min_vals(&self) -> Option<u64> {
- self.v.min_vals
- }
- fn short(&self) -> Option<char> {
- None
- }
- fn long(&self) -> Option<&'e str> {
- None
- }
- fn val_delim(&self) -> Option<char> {
- self.v.val_delim
- }
- fn takes_value(&self) -> bool {
- true
- }
- fn help(&self) -> Option<&'e str> {
- self.b.help
- }
- fn long_help(&self) -> Option<&'e str> {
- self.b.long_help
- }
- fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> {
- self.v.default_vals_ifs.as_ref().map(|vm| vm.values())
- }
- fn default_val(&self) -> Option<&'e OsStr> {
- self.v.default_val
- }
- fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> {
- self.v
- .env
- .as_ref()
- .map(|&(key, ref value)| (key, value.as_ref()))
- }
- fn longest_filter(&self) -> bool {
- true
- }
- fn aliases(&self) -> Option<Vec<&'e str>> {
- None
- }
-}
-
-impl<'n, 'e> DispOrder for PosBuilder<'n, 'e> {
- fn disp_ord(&self) -> usize {
- self.index as usize
- }
-}
-
-impl<'n, 'e> PartialEq for PosBuilder<'n, 'e> {
- fn eq(&self, other: &PosBuilder<'n, 'e>) -> bool {
- self.b == other.b
- }
-}
-
-#[cfg(test)]
-mod test {
- use super::PosBuilder;
- use args::settings::ArgSettings;
- use map::VecMap;
-
- #[test]
- fn display_mult() {
- let mut p = PosBuilder::new("pos", 1);
- p.b.settings.set(ArgSettings::Multiple);
-
- assert_eq!(&*format!("{}", p), "<pos>...");
- }
-
- #[test]
- fn display_required() {
- let mut p2 = PosBuilder::new("pos", 1);
- p2.b.settings.set(ArgSettings::Required);
-
- assert_eq!(&*format!("{}", p2), "<pos>");
- }
-
- #[test]
- fn display_val_names() {
- let mut p2 = PosBuilder::new("pos", 1);
- let mut vm = VecMap::new();
- vm.insert(0, "file1");
- vm.insert(1, "file2");
- p2.v.val_names = Some(vm);
-
- assert_eq!(&*format!("{}", p2), "<file1> <file2>");
- }
-
- #[test]
- fn display_val_names_req() {
- let mut p2 = PosBuilder::new("pos", 1);
- p2.b.settings.set(ArgSettings::Required);
- let mut vm = VecMap::new();
- vm.insert(0, "file1");
- vm.insert(1, "file2");
- p2.v.val_names = Some(vm);
-
- assert_eq!(&*format!("{}", p2), "<file1> <file2>");
- }
-}
diff --git a/src/args/arg_builder/switched.rs b/src/args/arg_builder/switched.rs
deleted file mode 100644
index 777ff1d..0000000
--- a/src/args/arg_builder/switched.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-use Arg;
-
-#[derive(Debug)]
-pub struct Switched<'b> {
- pub short: Option<char>,
- pub long: Option<&'b str>,
- pub aliases: Option<Vec<(&'b str, bool)>>, // (name, visible)
- pub disp_ord: usize,
- pub unified_ord: usize,
-}
-
-impl<'e> Default for Switched<'e> {
- fn default() -> Self {
- Switched {
- short: None,
- long: None,
- aliases: None,
- disp_ord: 999,
- unified_ord: 999,
- }
- }
-}
-
-impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Switched<'e> {
- fn from(a: &'z Arg<'n, 'e>) -> Self {
- a.s.clone()
- }
-}
-
-impl<'e> Clone for Switched<'e> {
- fn clone(&self) -> Self {
- Switched {
- short: self.short,
- long: self.long,
- aliases: self.aliases.clone(),
- disp_ord: self.disp_ord,
- unified_ord: self.unified_ord,
- }
- }
-}
diff --git a/src/args/arg_builder/valued.rs b/src/args/arg_builder/valued.rs
deleted file mode 100644
index 82e1487..0000000
--- a/src/args/arg_builder/valued.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-use std::ffi::{OsStr, OsString};
-use std::rc::Rc;
-
-use map::VecMap;
-
-use Arg;
-
-#[allow(missing_debug_implementations)]
-#[derive(Clone)]
-pub struct Valued<'a, 'b>
-where
- 'a: 'b,
-{
- pub possible_vals: Option<Vec<&'b str>>,
- pub val_names: Option<VecMap<&'b str>>,
- pub num_vals: Option<u64>,
- pub max_vals: Option<u64>,
- pub min_vals: Option<u64>,
- pub validator: Option<Rc<Fn(String) -> Result<(), String>>>,
- pub validator_os: Option<Rc<Fn(&OsStr) -> Result<(), OsString>>>,
- pub val_delim: Option<char>,
- pub default_val: Option<&'b OsStr>,
- pub default_vals_ifs: Option<VecMap<(&'a str, Option<&'b OsStr>, &'b OsStr)>>,
- pub env: Option<(&'a OsStr, Option<OsString>)>,
- pub terminator: Option<&'b str>,
-}
-
-impl<'n, 'e> Default for Valued<'n, 'e> {
- fn default() -> Self {
- Valued {
- possible_vals: None,
- num_vals: None,
- min_vals: None,
- max_vals: None,
- val_names: None,
- validator: None,
- validator_os: None,
- val_delim: None,
- default_val: None,
- default_vals_ifs: None,
- env: None,
- terminator: None,
- }
- }
-}
-
-impl<'n, 'e> Valued<'n, 'e> {
- pub fn fill_in(&mut self) {
- if let Some(ref vec) = self.val_names {
- if vec.len() > 1 {
- self.num_vals = Some(vec.len() as u64);
- }
- }
- }
-}
-
-impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Valued<'n, 'e> {
- fn from(a: &'z Arg<'n, 'e>) -> Self {
- let mut v = a.v.clone();
- if let Some(ref vec) = a.v.val_names {
- if vec.len() > 1 {
- v.num_vals = Some(vec.len() as u64);
- }
- }
- v
- }
-}
diff --git a/src/args/arg_matcher.rs b/src/args/arg_matcher.rs
deleted file mode 100644
index 1a0a149..0000000
--- a/src/args/arg_matcher.rs
+++ /dev/null
@@ -1,269 +0,0 @@
-// Std
-use std::collections::hash_map::{Entry, Iter};
-use std::collections::HashMap;
-use std::ffi::OsStr;
-use std::mem;
-use std::ops::Deref;
-
-// Internal
-use args::settings::ArgSettings;
-use args::AnyArg;
-use args::{ArgMatches, MatchedArg, SubCommand};
-
-#[doc(hidden)]
-#[allow(missing_debug_implementations)]
-pub struct ArgMatcher<'a>(pub ArgMatches<'a>);
-
-impl<'a> Default for ArgMatcher<'a> {
- fn default() -> Self {
- ArgMatcher(ArgMatches::default())
- }
-}
-
-impl<'a> ArgMatcher<'a> {
- pub fn new() -> Self {
- ArgMatcher::default()
- }
-
- pub fn process_arg_overrides<'b>(
- &mut self,
- a: Option<&AnyArg<'a, 'b>>,
- overrides: &mut Vec<(&'b str, &'a str)>,
- required: &mut Vec<&'a str>,
- check_all: bool,
- ) {
- debugln!(
- "ArgMatcher::process_arg_overrides:{:?};",
- a.map_or(None, |a| Some(a.name()))
- );
- if let Some(aa) = a {
- let mut self_done = false;
- if let Some(a_overrides) = aa.overrides() {
- for overr in a_overrides {
- debugln!("ArgMatcher::process_arg_overrides:iter:{};", overr);
- if overr == &aa.name() {
- self_done = true;
- self.handle_self_overrides(a);
- } else if self.is_present(overr) {
- debugln!(
- "ArgMatcher::process_arg_overrides:iter:{}: removing from matches;",
- overr
- );
- self.remove(overr);
- for i in (0..required.len()).rev() {
- if &required[i] == overr {
- debugln!(
- "ArgMatcher::process_arg_overrides:iter:{}: removing required;",
- overr
- );
- required.swap_remove(i);
- break;
- }
- }
- overrides.push((overr, aa.name()));
- } else {
- overrides.push((overr, aa.name()));
- }
- }
- }
- if check_all && !self_done {
- self.handle_self_overrides(a);
- }
- }
- }
-
- pub fn handle_self_overrides<'b>(&mut self, a: Option<&AnyArg<'a, 'b>>) {
- debugln!(
- "ArgMatcher::handle_self_overrides:{:?};",
- a.map_or(None, |a| Some(a.name()))
- );
- if let Some(aa) = a {
- if !aa.has_switch() || aa.is_set(ArgSettings::Multiple) {
- // positional args can't override self or else we would never advance to the next
-
- // Also flags with --multiple set are ignored otherwise we could never have more
- // than one
- return;
- }
- if let Some(ma) = self.get_mut(aa.name()) {
- if ma.vals.len() > 1 {
- // swap_remove(0) would be O(1) but does not preserve order, which
- // we need
- ma.vals.remove(0);
- ma.occurs = 1;
- } else if !aa.takes_value() && ma.occurs > 1 {
- ma.occurs = 1;
- }
- }
- }
- }
-
- pub fn is_present(&self, name: &str) -> bool {
- self.0.is_present(name)
- }
-
- pub fn propagate_globals(&mut self, global_arg_vec: &[&'a str]) {
- debugln!(
- "ArgMatcher::get_global_values: global_arg_vec={:?}",
- global_arg_vec
- );
- let mut vals_map = HashMap::new();
- self.fill_in_global_values(global_arg_vec, &mut vals_map);
- }
-
- fn fill_in_global_values(
- &mut self,
- global_arg_vec: &[&'a str],
- vals_map: &mut HashMap<&'a str, MatchedArg>,
- ) {
- for global_arg in global_arg_vec {
- if let Some(ma) = self.get(global_arg) {
- // We have to check if the parent's global arg wasn't used but still exists
- // such as from a default value.
- //
- // For example, `myprog subcommand --global-arg=value` where --global-arg defines
- // a default value of `other` myprog would have an existing MatchedArg for
- // --global-arg where the value is `other`, however the occurs will be 0.
- let to_update = if let Some(parent_ma) = vals_map.get(global_arg) {
- if parent_ma.occurs > 0 && ma.occurs == 0 {
- parent_ma.clone()
- } else {
- ma.clone()
- }
- } else {
- ma.clone()
- };
- vals_map.insert(global_arg, to_update);
- }
- }
- if let Some(ref mut sc) = self.0.subcommand {
- let mut am = ArgMatcher(mem::replace(&mut sc.matches, ArgMatches::new()));
- am.fill_in_global_values(global_arg_vec, vals_map);
- mem::swap(&mut am.0, &mut sc.matches);
- }
-
- for (name, matched_arg) in vals_map.into_iter() {
- self.0.args.insert(name, matched_arg.clone());
- }
- }
-
- pub fn get_mut(&mut self, arg: &str) -> Option<&mut MatchedArg> {
- self.0.args.get_mut(arg)
- }
-
- pub fn get(&self, arg: &str) -> Option<&MatchedArg> {
- self.0.args.get(arg)
- }
-
- pub fn remove(&mut self, arg: &str) {
- self.0.args.remove(arg);
- }
-
- pub fn remove_all(&mut self, args: &[&str]) {
- for &arg in args {
- self.0.args.remove(arg);
- }
- }
-
- pub fn insert(&mut self, name: &'a str) {
- self.0.args.insert(name, MatchedArg::new());
- }
-
- pub fn contains(&self, arg: &str) -> bool {
- self.0.args.contains_key(arg)
- }
-
- pub fn is_empty(&self) -> bool {
- self.0.args.is_empty()
- }
-
- pub fn usage(&mut self, usage: String) {
- self.0.usage = Some(usage);
- }
-
- pub fn arg_names(&'a self) -> Vec<&'a str> {
- self.0.args.keys().map(Deref::deref).collect()
- }
-
- pub fn entry(&mut self, arg: &'a str) -> Entry<&'a str, MatchedArg> {
- self.0.args.entry(arg)
- }
-
- pub fn subcommand(&mut self, sc: SubCommand<'a>) {
- self.0.subcommand = Some(Box::new(sc));
- }
-
- pub fn subcommand_name(&self) -> Option<&str> {
- self.0.subcommand_name()
- }
-
- pub fn iter(&self) -> Iter<&str, MatchedArg> {
- self.0.args.iter()
- }
-
- pub fn inc_occurrence_of(&mut self, arg: &'a str) {
- debugln!("ArgMatcher::inc_occurrence_of: arg={}", arg);
- if let Some(a) = self.get_mut(arg) {
- a.occurs += 1;
- return;
- }
- debugln!("ArgMatcher::inc_occurrence_of: first instance");
- self.insert(arg);
- }
-
- pub fn inc_occurrences_of(&mut self, args: &[&'a str]) {
- debugln!("ArgMatcher::inc_occurrences_of: args={:?}", args);
- for arg in args {
- self.inc_occurrence_of(arg);
- }
- }
-
- pub fn add_val_to(&mut self, arg: &'a str, val: &OsStr) {
- let ma = self.entry(arg).or_insert(MatchedArg {
- occurs: 0,
- indices: Vec::with_capacity(1),
- vals: Vec::with_capacity(1),
- });
- ma.vals.push(val.to_owned());
- }
-
- pub fn add_index_to(&mut self, arg: &'a str, idx: usize) {
- let ma = self.entry(arg).or_insert(MatchedArg {
- occurs: 0,
- indices: Vec::with_capacity(1),
- vals: Vec::new(),
- });
- ma.indices.push(idx);
- }
-
- pub fn needs_more_vals<'b, A>(&self, o: &A) -> bool
- where
- A: AnyArg<'a, 'b>,
- {
- debugln!("ArgMatcher::needs_more_vals: o={}", o.name());
- if let Some(ma) = self.get(o.name()) {
- if let Some(num) = o.num_vals() {
- debugln!("ArgMatcher::needs_more_vals: num_vals...{}", num);
- return if o.is_set(ArgSettings::Multiple) {
- ((ma.vals.len() as u64) % num) != 0
- } else {
- num != (ma.vals.len() as u64)
- };
- } else if let Some(num) = o.max_vals() {
- debugln!("ArgMatcher::needs_more_vals: max_vals...{}", num);
- return !((ma.vals.len() as u64) > num);
- } else if o.min_vals().is_some() {
- debugln!("ArgMatcher::needs_more_vals: min_vals...true");
- return true;
- }
- return o.is_set(ArgSettings::Multiple);
- }
- true
- }
-}
-
-impl<'a> Into<ArgMatches<'a>> for ArgMatcher<'a> {
- fn into(self) -> ArgMatches<'a> {
- self.0
- }
-}
diff --git a/src/args/arg_matches.rs b/src/args/arg_matches.rs
deleted file mode 100644
index f017c4e..0000000
--- a/src/args/arg_matches.rs
+++ /dev/null
@@ -1,998 +0,0 @@
-// Std
-use std::borrow::Cow;
-use std::collections::HashMap;
-use std::ffi::{OsStr, OsString};
-use std::iter::Map;
-use std::slice::Iter;
-
-// Internal
-use args::MatchedArg;
-use args::SubCommand;
-use INVALID_UTF8;
-
-/// Used to get information about the arguments that were supplied to the program at runtime by
-/// the user. New instances of this struct are obtained by using the [`App::get_matches`] family of
-/// methods.
-///
-/// # Examples
-///
-/// ```no_run
-/// # use clap::{App, Arg};
-/// let matches = App::new("MyApp")
-/// .arg(Arg::with_name("out")
-/// .long("output")
-/// .required(true)
-/// .takes_value(true))
-/// .arg(Arg::with_name("debug")
-/// .short("d")
-/// .multiple(true))
-/// .arg(Arg::with_name("cfg")
-/// .short("c")
-/// .takes_value(true))
-/// .get_matches(); // builds the instance of ArgMatches
-///
-/// // to get information about the "cfg" argument we created, such as the value supplied we use
-/// // various ArgMatches methods, such as ArgMatches::value_of
-/// if let Some(c) = matches.value_of("cfg") {
-/// println!("Value for -c: {}", c);
-/// }
-///
-/// // The ArgMatches::value_of method returns an Option because the user may not have supplied
-/// // that argument at runtime. But if we specified that the argument was "required" as we did
-/// // with the "out" argument, we can safely unwrap because `clap` verifies that was actually
-/// // used at runtime.
-/// println!("Value for --output: {}", matches.value_of("out").unwrap());
-///
-/// // You can check the presence of an argument
-/// if matches.is_present("out") {
-/// // Another way to check if an argument was present, or if it occurred multiple times is to
-/// // use occurrences_of() which returns 0 if an argument isn't found at runtime, or the
-/// // number of times that it occurred, if it was. To allow an argument to appear more than
-/// // once, you must use the .multiple(true) method, otherwise it will only return 1 or 0.
-/// if matches.occurrences_of("debug") > 2 {
-/// println!("Debug mode is REALLY on, don't be crazy");
-/// } else {
-/// println!("Debug mode kind of on");
-/// }
-/// }
-/// ```
-/// [`App::get_matches`]: ./struct.App.html#method.get_matches
-#[derive(Debug, Clone)]
-pub struct ArgMatches<'a> {
- #[doc(hidden)]
- pub args: HashMap<&'a str, MatchedArg>,
- #[doc(hidden)]
- pub subcommand: Option<Box<SubCommand<'a>>>,
- #[doc(hidden)]
- pub usage: Option<String>,
-}
-
-impl<'a> Default for ArgMatches<'a> {
- fn default() -> Self {
- ArgMatches {
- args: HashMap::new(),
- subcommand: None,
- usage: None,
- }
- }
-}
-
-impl<'a> ArgMatches<'a> {
- #[doc(hidden)]
- pub fn new() -> Self {
- ArgMatches {
- ..Default::default()
- }
- }
-
- /// Gets the value of a specific [option] or [positional] argument (i.e. an argument that takes
- /// an additional value at runtime). If the option wasn't present at runtime
- /// it returns `None`.
- ///
- /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
- /// prefer [`ArgMatches::values_of`] as `ArgMatches::value_of` will only return the *first*
- /// value.
- ///
- /// # Panics
- ///
- /// This method will [`panic!`] if the value contains invalid UTF-8 code points.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("myapp")
- /// .arg(Arg::with_name("output")
- /// .takes_value(true))
- /// .get_matches_from(vec!["myapp", "something"]);
- ///
- /// assert_eq!(m.value_of("output"), Some("something"));
- /// ```
- /// [option]: ./struct.Arg.html#method.takes_value
- /// [positional]: ./struct.Arg.html#method.index
- /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
- /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
- pub fn value_of<S: AsRef<str>>(&self, name: S) -> Option<&str> {
- if let Some(arg) = self.args.get(name.as_ref()) {
- if let Some(v) = arg.vals.get(0) {
- return Some(v.to_str().expect(INVALID_UTF8));
- }
- }
- None
- }
-
- /// Gets the lossy value of a specific argument. If the argument wasn't present at runtime
- /// it returns `None`. A lossy value is one which contains invalid UTF-8 code points, those
- /// invalid points will be replaced with `\u{FFFD}`
- ///
- /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
- /// prefer [`Arg::values_of_lossy`] as `value_of_lossy()` will only return the *first* value.
- ///
- /// # Examples
- ///
- #[cfg_attr(not(unix), doc = " ```ignore")]
- #[cfg_attr(unix, doc = " ```")]
- /// # use clap::{App, Arg};
- /// use std::ffi::OsString;
- /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
- ///
- /// let m = App::new("utf8")
- /// .arg(Arg::from_usage("<arg> 'some arg'"))
- /// .get_matches_from(vec![OsString::from("myprog"),
- /// // "Hi {0xe9}!"
- /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
- /// assert_eq!(&*m.value_of_lossy("arg").unwrap(), "Hi \u{FFFD}!");
- /// ```
- /// [`Arg::values_of_lossy`]: ./struct.ArgMatches.html#method.values_of_lossy
- pub fn value_of_lossy<S: AsRef<str>>(&'a self, name: S) -> Option<Cow<'a, str>> {
- if let Some(arg) = self.args.get(name.as_ref()) {
- if let Some(v) = arg.vals.get(0) {
- return Some(v.to_string_lossy());
- }
- }
- None
- }
-
- /// Gets the OS version of a string value of a specific argument. If the option wasn't present
- /// at runtime it returns `None`. An OS value on Unix-like systems is any series of bytes,
- /// regardless of whether or not they contain valid UTF-8 code points. Since [`String`]s in
- /// Rust are guaranteed to be valid UTF-8, a valid filename on a Unix system as an argument
- /// value may contain invalid UTF-8 code points.
- ///
- /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
- /// prefer [`ArgMatches::values_of_os`] as `Arg::value_of_os` will only return the *first*
- /// value.
- ///
- /// # Examples
- ///
- #[cfg_attr(not(unix), doc = " ```ignore")]
- #[cfg_attr(unix, doc = " ```")]
- /// # use clap::{App, Arg};
- /// use std::ffi::OsString;
- /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
- ///
- /// let m = App::new("utf8")
- /// .arg(Arg::from_usage("<arg> 'some arg'"))
- /// .get_matches_from(vec![OsString::from("myprog"),
- /// // "Hi {0xe9}!"
- /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
- /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
- /// ```
- /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
- /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
- pub fn value_of_os<S: AsRef<str>>(&self, name: S) -> Option<&OsStr> {
- self.args
- .get(name.as_ref())
- .and_then(|arg| arg.vals.get(0).map(|v| v.as_os_str()))
- }
-
- /// Gets a [`Values`] struct which implements [`Iterator`] for values of a specific argument
- /// (i.e. an argument that takes multiple values at runtime). If the option wasn't present at
- /// runtime it returns `None`
- ///
- /// # Panics
- ///
- /// This method will panic if any of the values contain invalid UTF-8 code points.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("myprog")
- /// .arg(Arg::with_name("output")
- /// .multiple(true)
- /// .short("o")
- /// .takes_value(true))
- /// .get_matches_from(vec![
- /// "myprog", "-o", "val1", "val2", "val3"
- /// ]);
- /// let vals: Vec<&str> = m.values_of("output").unwrap().collect();
- /// assert_eq!(vals, ["val1", "val2", "val3"]);
- /// ```
- /// [`Values`]: ./struct.Values.html
- /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
- pub fn values_of<S: AsRef<str>>(&'a self, name: S) -> Option<Values<'a>> {
- if let Some(arg) = self.args.get(name.as_ref()) {
- fn to_str_slice(o: &OsString) -> &str {
- o.to_str().expect(INVALID_UTF8)
- }
- let to_str_slice: fn(&OsString) -> &str = to_str_slice; // coerce to fn pointer
- return Some(Values {
- iter: arg.vals.iter().map(to_str_slice),
- });
- }
- None
- }
-
- /// Gets the lossy values of a specific argument. If the option wasn't present at runtime
- /// it returns `None`. A lossy value is one where if it contains invalid UTF-8 code points,
- /// those invalid points will be replaced with `\u{FFFD}`
- ///
- /// # Examples
- ///
- #[cfg_attr(not(unix), doc = " ```ignore")]
- #[cfg_attr(unix, doc = " ```")]
- /// # use clap::{App, Arg};
- /// use std::ffi::OsString;
- /// use std::os::unix::ffi::OsStringExt;
- ///
- /// let m = App::new("utf8")
- /// .arg(Arg::from_usage("<arg>... 'some arg'"))
- /// .get_matches_from(vec![OsString::from("myprog"),
- /// // "Hi"
- /// OsString::from_vec(vec![b'H', b'i']),
- /// // "{0xe9}!"
- /// OsString::from_vec(vec![0xe9, b'!'])]);
- /// let mut itr = m.values_of_lossy("arg").unwrap().into_iter();
- /// assert_eq!(&itr.next().unwrap()[..], "Hi");
- /// assert_eq!(&itr.next().unwrap()[..], "\u{FFFD}!");
- /// assert_eq!(itr.next(), None);
- /// ```
- pub fn values_of_lossy<S: AsRef<str>>(&'a self, name: S) -> Option<Vec<String>> {
- if let Some(arg) = self.args.get(name.as_ref()) {
- return Some(
- arg.vals
- .iter()
- .map(|v| v.to_string_lossy().into_owned())
- .collect(),
- );
- }
- None
- }
-
- /// Gets a [`OsValues`] struct which is implements [`Iterator`] for [`OsString`] values of a
- /// specific argument. If the option wasn't present at runtime it returns `None`. An OS value
- /// on Unix-like systems is any series of bytes, regardless of whether or not they contain
- /// valid UTF-8 code points. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid
- /// filename as an argument value on Linux (for example) may contain invalid UTF-8 code points.
- ///
- /// # Examples
- ///
- #[cfg_attr(not(unix), doc = " ```ignore")]
- #[cfg_attr(unix, doc = " ```")]
- /// # use clap::{App, Arg};
- /// use std::ffi::{OsStr,OsString};
- /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
- ///
- /// let m = App::new("utf8")
- /// .arg(Arg::from_usage("<arg>... 'some arg'"))
- /// .get_matches_from(vec![OsString::from("myprog"),
- /// // "Hi"
- /// OsString::from_vec(vec![b'H', b'i']),
- /// // "{0xe9}!"
- /// OsString::from_vec(vec![0xe9, b'!'])]);
- ///
- /// let mut itr = m.values_of_os("arg").unwrap().into_iter();
- /// assert_eq!(itr.next(), Some(OsStr::new("Hi")));
- /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!'])));
- /// assert_eq!(itr.next(), None);
- /// ```
- /// [`OsValues`]: ./struct.OsValues.html
- /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
- /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html
- /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
- pub fn values_of_os<S: AsRef<str>>(&'a self, name: S) -> Option<OsValues<'a>> {
- fn to_str_slice(o: &OsString) -> &OsStr {
- &*o
- }
- let to_str_slice: fn(&'a OsString) -> &'a OsStr = to_str_slice; // coerce to fn pointer
- if let Some(arg) = self.args.get(name.as_ref()) {
- return Some(OsValues {
- iter: arg.vals.iter().map(to_str_slice),
- });
- }
- None
- }
-
- /// Returns `true` if an argument was present at runtime, otherwise `false`.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("myprog")
- /// .arg(Arg::with_name("debug")
- /// .short("d"))
- /// .get_matches_from(vec![
- /// "myprog", "-d"
- /// ]);
- ///
- /// assert!(m.is_present("debug"));
- /// ```
- pub fn is_present<S: AsRef<str>>(&self, name: S) -> bool {
- if let Some(ref sc) = self.subcommand {
- if sc.name == name.as_ref() {
- return true;
- }
- }
- self.args.contains_key(name.as_ref())
- }
-
- /// Returns the number of times an argument was used at runtime. If an argument isn't present
- /// it will return `0`.
- ///
- /// **NOTE:** This returns the number of times the argument was used, *not* the number of
- /// values. For example, `-o val1 val2 val3 -o val4` would return `2` (2 occurrences, but 4
- /// values).
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("myprog")
- /// .arg(Arg::with_name("debug")
- /// .short("d")
- /// .multiple(true))
- /// .get_matches_from(vec![
- /// "myprog", "-d", "-d", "-d"
- /// ]);
- ///
- /// assert_eq!(m.occurrences_of("debug"), 3);
- /// ```
- ///
- /// This next example shows that counts actual uses of the argument, not just `-`'s
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("myprog")
- /// .arg(Arg::with_name("debug")
- /// .short("d")
- /// .multiple(true))
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .get_matches_from(vec![
- /// "myprog", "-ddfd"
- /// ]);
- ///
- /// assert_eq!(m.occurrences_of("debug"), 3);
- /// assert_eq!(m.occurrences_of("flag"), 1);
- /// ```
- pub fn occurrences_of<S: AsRef<str>>(&self, name: S) -> u64 {
- self.args.get(name.as_ref()).map_or(0, |a| a.occurs)
- }
-
- /// Gets the starting index of the argument in respect to all other arguments. Indices are
- /// similar to argv indices, but are not exactly 1:1.
- ///
- /// For flags (i.e. those arguments which don't have an associated value), indices refer
- /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices
- /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the
- /// index for `val` would be recorded. This is by design.
- ///
- /// Besides the flag/option descrepancy, the primary difference between an argv index and clap
- /// index, is that clap continues counting once all arguments have properly seperated, whereas
- /// an argv index does not.
- ///
- /// The examples should clear this up.
- ///
- /// *NOTE:* If an argument is allowed multiple times, this method will only give the *first*
- /// index.
- ///
- /// # Examples
- ///
- /// The argv indices are listed in the comments below. See how they correspond to the clap
- /// indices. Note that if it's not listed in a clap index, this is becuase it's not saved in
- /// in an `ArgMatches` struct for querying.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("myapp")
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .arg(Arg::with_name("option")
- /// .short("o")
- /// .takes_value(true))
- /// .get_matches_from(vec!["myapp", "-f", "-o", "val"]);
- /// // ARGV idices: ^0 ^1 ^2 ^3
- /// // clap idices: ^1 ^3
- ///
- /// assert_eq!(m.index_of("flag"), Some(1));
- /// assert_eq!(m.index_of("option"), Some(3));
- /// ```
- ///
- /// Now notice, if we use one of the other styles of options:
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("myapp")
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .arg(Arg::with_name("option")
- /// .short("o")
- /// .takes_value(true))
- /// .get_matches_from(vec!["myapp", "-f", "-o=val"]);
- /// // ARGV idices: ^0 ^1 ^2
- /// // clap idices: ^1 ^3
- ///
- /// assert_eq!(m.index_of("flag"), Some(1));
- /// assert_eq!(m.index_of("option"), Some(3));
- /// ```
- ///
- /// Things become much more complicated, or clear if we look at a more complex combination of
- /// flags. Let's also throw in the final option style for good measure.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("myapp")
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .arg(Arg::with_name("flag2")
- /// .short("F"))
- /// .arg(Arg::with_name("flag3")
- /// .short("z"))
- /// .arg(Arg::with_name("option")
- /// .short("o")
- /// .takes_value(true))
- /// .get_matches_from(vec!["myapp", "-fzF", "-oval"]);
- /// // ARGV idices: ^0 ^1 ^2
- /// // clap idices: ^1,2,3 ^5
- /// //
- /// // clap sees the above as 'myapp -f -z -F -o val'
- /// // ^0 ^1 ^2 ^3 ^4 ^5
- /// assert_eq!(m.index_of("flag"), Some(1));
- /// assert_eq!(m.index_of("flag2"), Some(3));
- /// assert_eq!(m.index_of("flag3"), Some(2));
- /// assert_eq!(m.index_of("option"), Some(5));
- /// ```
- ///
- /// One final combination of flags/options to see how they combine:
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("myapp")
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .arg(Arg::with_name("flag2")
- /// .short("F"))
- /// .arg(Arg::with_name("flag3")
- /// .short("z"))
- /// .arg(Arg::with_name("option")
- /// .short("o")
- /// .takes_value(true)
- /// .multiple(true))
- /// .get_matches_from(vec!["myapp", "-fzFoval"]);
- /// // ARGV idices: ^0 ^1
- /// // clap idices: ^1,2,3^5
- /// //
- /// // clap sees the above as 'myapp -f -z -F -o val'
- /// // ^0 ^1 ^2 ^3 ^4 ^5
- /// assert_eq!(m.index_of("flag"), Some(1));
- /// assert_eq!(m.index_of("flag2"), Some(3));
- /// assert_eq!(m.index_of("flag3"), Some(2));
- /// assert_eq!(m.index_of("option"), Some(5));
- /// ```
- ///
- /// The last part to mention is when values are sent in multiple groups with a [delimiter].
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("myapp")
- /// .arg(Arg::with_name("option")
- /// .short("o")
- /// .takes_value(true)
- /// .multiple(true))
- /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
- /// // ARGV idices: ^0 ^1
- /// // clap idices: ^2 ^3 ^4
- /// //
- /// // clap sees the above as 'myapp -o val1 val2 val3'
- /// // ^0 ^1 ^2 ^3 ^4
- /// assert_eq!(m.index_of("option"), Some(2));
- /// ```
- /// [`ArgMatches`]: ./struct.ArgMatches.html
- /// [delimiter]: ./struct.Arg.html#method.value_delimiter
- pub fn index_of<S: AsRef<str>>(&self, name: S) -> Option<usize> {
- if let Some(arg) = self.args.get(name.as_ref()) {
- if let Some(i) = arg.indices.get(0) {
- return Some(*i);
- }
- }
- None
- }
-
- /// Gets all indices of the argument in respect to all other arguments. Indices are
- /// similar to argv indices, but are not exactly 1:1.
- ///
- /// For flags (i.e. those arguments which don't have an associated value), indices refer
- /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices
- /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the
- /// index for `val` would be recorded. This is by design.
- ///
- /// *NOTE:* For more information about how clap indices compare to argv indices, see
- /// [`ArgMatches::index_of`]
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("myapp")
- /// .arg(Arg::with_name("option")
- /// .short("o")
- /// .takes_value(true)
- /// .use_delimiter(true)
- /// .multiple(true))
- /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
- /// // ARGV idices: ^0 ^1
- /// // clap idices: ^2 ^3 ^4
- /// //
- /// // clap sees the above as 'myapp -o val1 val2 val3'
- /// // ^0 ^1 ^2 ^3 ^4
- /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]);
- /// ```
- ///
- /// Another quick example is when flags and options are used together
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("myapp")
- /// .arg(Arg::with_name("option")
- /// .short("o")
- /// .takes_value(true)
- /// .multiple(true))
- /// .arg(Arg::with_name("flag")
- /// .short("f")
- /// .multiple(true))
- /// .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]);
- /// // ARGV idices: ^0 ^1 ^2 ^3 ^4 ^5 ^6
- /// // clap idices: ^2 ^3 ^5 ^6
- ///
- /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 5]);
- /// assert_eq!(m.indices_of("flag").unwrap().collect::<Vec<_>>(), &[3, 6]);
- /// ```
- ///
- /// One final example, which is an odd case; if we *don't* use value delimiter as we did with
- /// the first example above instead of `val1`, `val2` and `val3` all being distinc values, they
- /// would all be a single value of `val1,val2,val3`, in which case case they'd only receive a
- /// single index.
- ///
- /// ```rust
- /// # use clap::{App, Arg};
- /// let m = App::new("myapp")
- /// .arg(Arg::with_name("option")
- /// .short("o")
- /// .takes_value(true)
- /// .multiple(true))
- /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
- /// // ARGV idices: ^0 ^1
- /// // clap idices: ^2
- /// //
- /// // clap sees the above as 'myapp -o "val1,val2,val3"'
- /// // ^0 ^1 ^2
- /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2]);
- /// ```
- /// [`ArgMatches`]: ./struct.ArgMatches.html
- /// [`ArgMatches::index_of`]: ./struct.ArgMatches.html#method.index_of
- /// [delimiter]: ./struct.Arg.html#method.value_delimiter
- pub fn indices_of<S: AsRef<str>>(&'a self, name: S) -> Option<Indices<'a>> {
- if let Some(arg) = self.args.get(name.as_ref()) {
- fn to_usize(i: &usize) -> usize {
- *i
- }
- let to_usize: fn(&usize) -> usize = to_usize; // coerce to fn pointer
- return Some(Indices {
- iter: arg.indices.iter().map(to_usize),
- });
- }
- None
- }
-
- /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
- /// as well. This method returns the [`ArgMatches`] for a particular subcommand or `None` if
- /// the subcommand wasn't present at runtime.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, SubCommand};
- /// let app_m = App::new("myprog")
- /// .arg(Arg::with_name("debug")
- /// .short("d"))
- /// .subcommand(SubCommand::with_name("test")
- /// .arg(Arg::with_name("opt")
- /// .long("option")
- /// .takes_value(true)))
- /// .get_matches_from(vec![
- /// "myprog", "-d", "test", "--option", "val"
- /// ]);
- ///
- /// // Both parent commands, and child subcommands can have arguments present at the same times
- /// assert!(app_m.is_present("debug"));
- ///
- /// // Get the subcommand's ArgMatches instance
- /// if let Some(sub_m) = app_m.subcommand_matches("test") {
- /// // Use the struct like normal
- /// assert_eq!(sub_m.value_of("opt"), Some("val"));
- /// }
- /// ```
- /// [`Subcommand`]: ./struct.SubCommand.html
- /// [`App`]: ./struct.App.html
- /// [`ArgMatches`]: ./struct.ArgMatches.html
- pub fn subcommand_matches<S: AsRef<str>>(&self, name: S) -> Option<&ArgMatches<'a>> {
- if let Some(ref s) = self.subcommand {
- if s.name == name.as_ref() {
- return Some(&s.matches);
- }
- }
- None
- }
-
- /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
- /// as well.But simply getting the sub-[`ArgMatches`] doesn't help much if we don't also know
- /// which subcommand was actually used. This method returns the name of the subcommand that was
- /// used at runtime, or `None` if one wasn't.
- ///
- /// *NOTE*: Subcommands form a hierarchy, where multiple subcommands can be used at runtime,
- /// but only a single subcommand from any group of sibling commands may used at once.
- ///
- /// An ASCII art depiction may help explain this better...Using a fictional version of `git` as
- /// the demo subject. Imagine the following are all subcommands of `git` (note, the author is
- /// aware these aren't actually all subcommands in the real `git` interface, but it makes
- /// explanation easier)
- ///
- /// ```notrust
- /// Top Level App (git) TOP
- /// |
- /// -----------------------------------------
- /// / | \ \
- /// clone push add commit LEVEL 1
- /// | / \ / \ |
- /// url origin remote ref name message LEVEL 2
- /// / /\
- /// path remote local LEVEL 3
- /// ```
- ///
- /// Given the above fictional subcommand hierarchy, valid runtime uses would be (not an all
- /// inclusive list, and not including argument options per command for brevity and clarity):
- ///
- /// ```sh
- /// $ git clone url
- /// $ git push origin path
- /// $ git add ref local
- /// $ git commit message
- /// ```
- ///
- /// Notice only one command per "level" may be used. You could not, for example, do `$ git
- /// clone url push origin path`
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand};
- /// let app_m = App::new("git")
- /// .subcommand(SubCommand::with_name("clone"))
- /// .subcommand(SubCommand::with_name("push"))
- /// .subcommand(SubCommand::with_name("commit"))
- /// .get_matches();
- ///
- /// match app_m.subcommand_name() {
- /// Some("clone") => {}, // clone was used
- /// Some("push") => {}, // push was used
- /// Some("commit") => {}, // commit was used
- /// _ => {}, // Either no subcommand or one not tested for...
- /// }
- /// ```
- /// [`Subcommand`]: ./struct.SubCommand.html
- /// [`App`]: ./struct.App.html
- /// [`ArgMatches`]: ./struct.ArgMatches.html
- pub fn subcommand_name(&self) -> Option<&str> {
- self.subcommand.as_ref().map(|sc| &sc.name[..])
- }
-
- /// This brings together [`ArgMatches::subcommand_matches`] and [`ArgMatches::subcommand_name`]
- /// by returning a tuple with both pieces of information.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand};
- /// let app_m = App::new("git")
- /// .subcommand(SubCommand::with_name("clone"))
- /// .subcommand(SubCommand::with_name("push"))
- /// .subcommand(SubCommand::with_name("commit"))
- /// .get_matches();
- ///
- /// match app_m.subcommand() {
- /// ("clone", Some(sub_m)) => {}, // clone was used
- /// ("push", Some(sub_m)) => {}, // push was used
- /// ("commit", Some(sub_m)) => {}, // commit was used
- /// _ => {}, // Either no subcommand or one not tested for...
- /// }
- /// ```
- ///
- /// Another useful scenario is when you want to support third party, or external, subcommands.
- /// In these cases you can't know the subcommand name ahead of time, so use a variable instead
- /// with pattern matching!
- ///
- /// ```rust
- /// # use clap::{App, AppSettings};
- /// // Assume there is an external subcommand named "subcmd"
- /// let app_m = App::new("myprog")
- /// .setting(AppSettings::AllowExternalSubcommands)
- /// .get_matches_from(vec![
- /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
- /// ]);
- ///
- /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
- /// // string argument name
- /// match app_m.subcommand() {
- /// (external, Some(sub_m)) => {
- /// let ext_args: Vec<&str> = sub_m.values_of("").unwrap().collect();
- /// assert_eq!(external, "subcmd");
- /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
- /// },
- /// _ => {},
- /// }
- /// ```
- /// [`ArgMatches::subcommand_matches`]: ./struct.ArgMatches.html#method.subcommand_matches
- /// [`ArgMatches::subcommand_name`]: ./struct.ArgMatches.html#method.subcommand_name
- pub fn subcommand(&self) -> (&str, Option<&ArgMatches<'a>>) {
- self.subcommand
- .as_ref()
- .map_or(("", None), |sc| (&sc.name[..], Some(&sc.matches)))
- }
-
- /// Returns a string slice of the usage statement for the [`App`] or [`SubCommand`]
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use clap::{App, Arg, SubCommand};
- /// let app_m = App::new("myprog")
- /// .subcommand(SubCommand::with_name("test"))
- /// .get_matches();
- ///
- /// println!("{}", app_m.usage());
- /// ```
- /// [`Subcommand`]: ./struct.SubCommand.html
- /// [`App`]: ./struct.App.html
- pub fn usage(&self) -> &str {
- self.usage.as_ref().map_or("", |u| &u[..])
- }
-}
-
-// The following were taken and adapated from vec_map source
-// repo: https://github.com/contain-rs/vec-map
-// commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33
-// license: MIT - Copyright (c) 2015 The Rust Project Developers
-
-/// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of`]
-/// method.
-///
-/// # Examples
-///
-/// ```rust
-/// # use clap::{App, Arg};
-/// let m = App::new("myapp")
-/// .arg(Arg::with_name("output")
-/// .short("o")
-/// .multiple(true)
-/// .takes_value(true))
-/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]);
-///
-/// let mut values = m.values_of("output").unwrap();
-///
-/// assert_eq!(values.next(), Some("val1"));
-/// assert_eq!(values.next(), Some("val2"));
-/// assert_eq!(values.next(), None);
-/// ```
-/// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
-#[derive(Debug, Clone)]
-pub struct Values<'a> {
- iter: Map<Iter<'a, OsString>, fn(&'a OsString) -> &'a str>,
-}
-
-impl<'a> Iterator for Values<'a> {
- type Item = &'a str;
-
- fn next(&mut self) -> Option<&'a str> {
- self.iter.next()
- }
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
- }
-}
-
-impl<'a> DoubleEndedIterator for Values<'a> {
- fn next_back(&mut self) -> Option<&'a str> {
- self.iter.next_back()
- }
-}
-
-impl<'a> ExactSizeIterator for Values<'a> {}
-
-/// Creates an empty iterator.
-impl<'a> Default for Values<'a> {
- fn default() -> Self {
- static EMPTY: [OsString; 0] = [];
- // This is never called because the iterator is empty:
- fn to_str_slice(_: &OsString) -> &str {
- unreachable!()
- };
- Values {
- iter: EMPTY[..].iter().map(to_str_slice),
- }
- }
-}
-
-/// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of_os`]
-/// method. Usage of this iterator allows values which contain invalid UTF-8 code points unlike
-/// [`Values`].
-///
-/// # Examples
-///
-#[cfg_attr(not(unix), doc = " ```ignore")]
-#[cfg_attr(unix, doc = " ```")]
-/// # use clap::{App, Arg};
-/// use std::ffi::OsString;
-/// use std::os::unix::ffi::{OsStrExt,OsStringExt};
-///
-/// let m = App::new("utf8")
-/// .arg(Arg::from_usage("<arg> 'some arg'"))
-/// .get_matches_from(vec![OsString::from("myprog"),
-/// // "Hi {0xe9}!"
-/// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
-/// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
-/// ```
-/// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
-/// [`Values`]: ./struct.Values.html
-#[derive(Debug, Clone)]
-pub struct OsValues<'a> {
- iter: Map<Iter<'a, OsString>, fn(&'a OsString) -> &'a OsStr>,
-}
-
-impl<'a> Iterator for OsValues<'a> {
- type Item = &'a OsStr;
-
- fn next(&mut self) -> Option<&'a OsStr> {
- self.iter.next()
- }
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
- }
-}
-
-impl<'a> DoubleEndedIterator for OsValues<'a> {
- fn next_back(&mut self) -> Option<&'a OsStr> {
- self.iter.next_back()
- }
-}
-
-impl<'a> ExactSizeIterator for OsValues<'a> {}
-
-/// Creates an empty iterator.
-impl<'a> Default for OsValues<'a> {
- fn default() -> Self {
- static EMPTY: [OsString; 0] = [];
- // This is never called because the iterator is empty:
- fn to_str_slice(_: &OsString) -> &OsStr {
- unreachable!()
- };
- OsValues {
- iter: EMPTY[..].iter().map(to_str_slice),
- }
- }
-}
-
-/// An iterator for getting multiple indices out of an argument via the [`ArgMatches::indices_of`]
-/// method.
-///
-/// # Examples
-///
-/// ```rust
-/// # use clap::{App, Arg};
-/// let m = App::new("myapp")
-/// .arg(Arg::with_name("output")
-/// .short("o")
-/// .multiple(true)
-/// .takes_value(true))
-/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]);
-///
-/// let mut indices = m.indices_of("output").unwrap();
-///
-/// assert_eq!(indices.next(), Some(2));
-/// assert_eq!(indices.next(), Some(3));
-/// assert_eq!(indices.next(), None);
-/// ```
-/// [`ArgMatches::indices_of`]: ./struct.ArgMatches.html#method.indices_of
-#[derive(Debug, Clone)]
-pub struct Indices<'a> {
- // would rather use '_, but: https://github.com/rust-lang/rust/issues/48469
- iter: Map<Iter<'a, usize>, fn(&'a usize) -> usize>,
-}
-
-impl<'a> Iterator for Indices<'a> {
- type Item = usize;
-
- fn next(&mut self) -> Option<usize> {
- self.iter.next()
- }
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
- }
-}
-
-impl<'a> DoubleEndedIterator for Indices<'a> {
- fn next_back(&mut self) -> Option<usize> {
- self.iter.next_back()
- }
-}
-
-impl<'a> ExactSizeIterator for Indices<'a> {}
-
-/// Creates an empty iterator.
-impl<'a> Default for Indices<'a> {
- fn default() -> Self {
- static EMPTY: [usize; 0] = [];
- // This is never called because the iterator is empty:
- fn to_usize(_: &usize) -> usize {
- unreachable!()
- };
- Indices {
- iter: EMPTY[..].iter().map(to_usize),
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_default_values() {
- let mut values: Values = Values::default();
- assert_eq!(values.next(), None);
- }
-
- #[test]
- fn test_default_values_with_shorter_lifetime() {
- let matches = ArgMatches::new();
- let mut values = matches.values_of("").unwrap_or_default();
- assert_eq!(values.next(), None);
- }
-
- #[test]
- fn test_default_osvalues() {
- let mut values: OsValues = OsValues::default();
- assert_eq!(values.next(), None);
- }
-
- #[test]
- fn test_default_osvalues_with_shorter_lifetime() {
- let matches = ArgMatches::new();
- let mut values = matches.values_of_os("").unwrap_or_default();
- assert_eq!(values.next(), None);
- }
-
- #[test]
- fn test_default_indices() {
- let mut indices: Indices = Indices::default();
- assert_eq!(indices.next(), None);
- }
-
- #[test]
- fn test_default_indices_with_shorter_lifetime() {
- let matches = ArgMatches::new();
- let mut indices = matches.indices_of("").unwrap_or_default();
- assert_eq!(indices.next(), None);
- }
-}
diff --git a/src/args/group.rs b/src/args/group.rs
deleted file mode 100644
index 8103a9c..0000000
--- a/src/args/group.rs
+++ /dev/null
@@ -1,638 +0,0 @@
-#[cfg(feature = "yaml")]
-use std::collections::BTreeMap;
-use std::fmt::{Debug, Formatter, Result};
-
-#[cfg(feature = "yaml")]
-use yaml_rust::Yaml;
-
-/// `ArgGroup`s are a family of related [arguments] and way for you to express, "Any of these
-/// arguments". By placing arguments in a logical group, you can create easier requirement and
-/// exclusion rules instead of having to list each argument individually, or when you want a rule
-/// to apply "any but not all" arguments.
-///
-/// For instance, you can make an entire `ArgGroup` required. If [`ArgGroup::multiple(true)`] is
-/// set, this means that at least one argument from that group must be present. If
-/// [`ArgGroup::multiple(false)`] is set (the default), one and *only* one must be present.
-///
-/// You can also do things such as name an entire `ArgGroup` as a [conflict] or [requirement] for
-/// another argument, meaning any of the arguments that belong to that group will cause a failure
-/// if present, or must present respectively.
-///
-/// Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be
-/// present out of a given set. Imagine that you had multiple arguments, and you want one of them
-/// to be required, but making all of them required isn't feasible because perhaps they conflict
-/// with each other. For example, lets say that you were building an application where one could
-/// set a given version number by supplying a string with an option argument, i.e.
-/// `--set-ver v1.2.3`, you also wanted to support automatically using a previous version number
-/// and simply incrementing one of the three numbers. So you create three flags `--major`,
-/// `--minor`, and `--patch`. All of these arguments shouldn't be used at one time but you want to
-/// specify that *at least one* of them is used. For this, you can create a group.
-///
-/// Finally, you may use `ArgGroup`s to pull a value from a group of arguments when you don't care
-/// exactly which argument was actually used at runtime.
-///
-/// # Examples
-///
-/// The following example demonstrates using an `ArgGroup` to ensure that one, and only one, of
-/// the arguments from the specified group is present at runtime.
-///
-/// ```rust
-/// # use clap::{App, ArgGroup, ErrorKind};
-/// let result = App::new("app")
-/// .args_from_usage(
-/// "--set-ver [ver] 'set the version manually'
-/// --major 'auto increase major'
-/// --minor 'auto increase minor'
-/// --patch 'auto increase patch'")
-/// .group(ArgGroup::with_name("vers")
-/// .args(&["set-ver", "major", "minor", "patch"])
-/// .required(true))
-/// .get_matches_from_safe(vec!["app", "--major", "--patch"]);
-/// // Because we used two args in the group it's an error
-/// assert!(result.is_err());
-/// let err = result.unwrap_err();
-/// assert_eq!(err.kind, ErrorKind::ArgumentConflict);
-/// ```
-/// This next example shows a passing parse of the same scenario
-///
-/// ```rust
-/// # use clap::{App, ArgGroup};
-/// let result = App::new("app")
-/// .args_from_usage(
-/// "--set-ver [ver] 'set the version manually'
-/// --major 'auto increase major'
-/// --minor 'auto increase minor'
-/// --patch 'auto increase patch'")
-/// .group(ArgGroup::with_name("vers")
-/// .args(&["set-ver", "major", "minor","patch"])
-/// .required(true))
-/// .get_matches_from_safe(vec!["app", "--major"]);
-/// assert!(result.is_ok());
-/// let matches = result.unwrap();
-/// // We may not know which of the args was used, so we can test for the group...
-/// assert!(matches.is_present("vers"));
-/// // we could also alternatively check each arg individually (not shown here)
-/// ```
-/// [`ArgGroup::multiple(true)`]: ./struct.ArgGroup.html#method.multiple
-/// [arguments]: ./struct.Arg.html
-/// [conflict]: ./struct.Arg.html#method.conflicts_with
-/// [requirement]: ./struct.Arg.html#method.requires
-#[derive(Default)]
-pub struct ArgGroup<'a> {
- #[doc(hidden)]
- pub name: &'a str,
- #[doc(hidden)]
- pub args: Vec<&'a str>,
- #[doc(hidden)]
- pub required: bool,
- #[doc(hidden)]
- pub requires: Option<Vec<&'a str>>,
- #[doc(hidden)]
- pub conflicts: Option<Vec<&'a str>>,
- #[doc(hidden)]
- pub multiple: bool,
-}
-
-impl<'a> ArgGroup<'a> {
- /// Creates a new instance of `ArgGroup` using a unique string name. The name will be used to
- /// get values from the group or refer to the group inside of conflict and requirement rules.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, ArgGroup};
- /// ArgGroup::with_name("config")
- /// # ;
- /// ```
- pub fn with_name(n: &'a str) -> Self {
- ArgGroup {
- name: n,
- required: false,
- args: vec![],
- requires: None,
- conflicts: None,
- multiple: false,
- }
- }
-
- /// Creates a new instance of `ArgGroup` from a .yml (YAML) file.
- ///
- /// # Examples
- ///
- /// ```ignore
- /// # #[macro_use]
- /// # extern crate clap;
- /// # use clap::ArgGroup;
- /// # fn main() {
- /// let yml = load_yaml!("group.yml");
- /// let ag = ArgGroup::from_yaml(yml);
- /// # }
- /// ```
- #[cfg(feature = "yaml")]
- pub fn from_yaml(y: &'a Yaml) -> ArgGroup<'a> {
- ArgGroup::from(y.as_hash().unwrap())
- }
-
- /// Adds an [argument] to this group by name
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, ArgGroup};
- /// let m = App::new("myprog")
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .arg(Arg::with_name("color")
- /// .short("c"))
- /// .group(ArgGroup::with_name("req_flags")
- /// .arg("flag")
- /// .arg("color"))
- /// .get_matches_from(vec!["myprog", "-f"]);
- /// // maybe we don't know which of the two flags was used...
- /// assert!(m.is_present("req_flags"));
- /// // but we can also check individually if needed
- /// assert!(m.is_present("flag"));
- /// ```
- /// [argument]: ./struct.Arg.html
- #[cfg_attr(feature = "lints", allow(should_assert_eq))]
- pub fn arg(mut self, n: &'a str) -> Self {
- assert!(
- self.name != n,
- "ArgGroup '{}' can not have same name as arg inside it",
- &*self.name
- );
- self.args.push(n);
- self
- }
-
- /// Adds multiple [arguments] to this group by name
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, ArgGroup};
- /// let m = App::new("myprog")
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .arg(Arg::with_name("color")
- /// .short("c"))
- /// .group(ArgGroup::with_name("req_flags")
- /// .args(&["flag", "color"]))
- /// .get_matches_from(vec!["myprog", "-f"]);
- /// // maybe we don't know which of the two flags was used...
- /// assert!(m.is_present("req_flags"));
- /// // but we can also check individually if needed
- /// assert!(m.is_present("flag"));
- /// ```
- /// [arguments]: ./struct.Arg.html
- pub fn args(mut self, ns: &[&'a str]) -> Self {
- for n in ns {
- self = self.arg(n);
- }
- self
- }
-
- /// Allows more than one of the ['Arg']s in this group to be used. (Default: `false`)
- ///
- /// # Examples
- ///
- /// Notice in this example we use *both* the `-f` and `-c` flags which are both part of the
- /// group
- ///
- /// ```rust
- /// # use clap::{App, Arg, ArgGroup};
- /// let m = App::new("myprog")
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .arg(Arg::with_name("color")
- /// .short("c"))
- /// .group(ArgGroup::with_name("req_flags")
- /// .args(&["flag", "color"])
- /// .multiple(true))
- /// .get_matches_from(vec!["myprog", "-f", "-c"]);
- /// // maybe we don't know which of the two flags was used...
- /// assert!(m.is_present("req_flags"));
- /// ```
- /// In this next example, we show the default behavior (i.e. `multiple(false)) which will throw
- /// an error if more than one of the args in the group was used.
- ///
- /// ```rust
- /// # use clap::{App, Arg, ArgGroup, ErrorKind};
- /// let result = App::new("myprog")
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .arg(Arg::with_name("color")
- /// .short("c"))
- /// .group(ArgGroup::with_name("req_flags")
- /// .args(&["flag", "color"]))
- /// .get_matches_from_safe(vec!["myprog", "-f", "-c"]);
- /// // Because we used both args in the group it's an error
- /// assert!(result.is_err());
- /// let err = result.unwrap_err();
- /// assert_eq!(err.kind, ErrorKind::ArgumentConflict);
- /// ```
- /// ['Arg']: ./struct.Arg.html
- pub fn multiple(mut self, m: bool) -> Self {
- self.multiple = m;
- self
- }
-
- /// Sets the group as required or not. A required group will be displayed in the usage string
- /// of the application in the format `<arg|arg2|arg3>`. A required `ArgGroup` simply states
- /// that one argument from this group *must* be present at runtime (unless
- /// conflicting with another argument).
- ///
- /// **NOTE:** This setting only applies to the current [`App`] / [`SubCommand`], and not
- /// globally.
- ///
- /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with
- /// `ArgGroup::required(true)` states, "One and *only one* arg must be used from this group.
- /// Use of more than one arg is an error." Vice setting `ArgGroup::multiple(true)` which
- /// states, '*At least* one arg from this group must be used. Using multiple is OK."
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, ArgGroup, ErrorKind};
- /// let result = App::new("myprog")
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .arg(Arg::with_name("color")
- /// .short("c"))
- /// .group(ArgGroup::with_name("req_flags")
- /// .args(&["flag", "color"])
- /// .required(true))
- /// .get_matches_from_safe(vec!["myprog"]);
- /// // Because we didn't use any of the args in the group, it's an error
- /// assert!(result.is_err());
- /// let err = result.unwrap_err();
- /// assert_eq!(err.kind, ErrorKind::MissingRequiredArgument);
- /// ```
- /// [`App`]: ./struct.App.html
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`ArgGroup::multiple`]: ./struct.ArgGroup.html#method.multiple
- pub fn required(mut self, r: bool) -> Self {
- self.required = r;
- self
- }
-
- /// Sets the requirement rules of this group. This is not to be confused with a
- /// [required group]. Requirement rules function just like [argument requirement rules], you
- /// can name other arguments or groups that must be present when any one of the arguments from
- /// this group is used.
- ///
- /// **NOTE:** The name provided may be an argument, or group name
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, ArgGroup, ErrorKind};
- /// let result = App::new("myprog")
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .arg(Arg::with_name("color")
- /// .short("c"))
- /// .arg(Arg::with_name("debug")
- /// .short("d"))
- /// .group(ArgGroup::with_name("req_flags")
- /// .args(&["flag", "color"])
- /// .requires("debug"))
- /// .get_matches_from_safe(vec!["myprog", "-c"]);
- /// // because we used an arg from the group, and the group requires "-d" to be used, it's an
- /// // error
- /// assert!(result.is_err());
- /// let err = result.unwrap_err();
- /// assert_eq!(err.kind, ErrorKind::MissingRequiredArgument);
- /// ```
- /// [required group]: ./struct.ArgGroup.html#method.required
- /// [argument requirement rules]: ./struct.Arg.html#method.requires
- pub fn requires(mut self, n: &'a str) -> Self {
- if let Some(ref mut reqs) = self.requires {
- reqs.push(n);
- } else {
- self.requires = Some(vec![n]);
- }
- self
- }
-
- /// Sets the requirement rules of this group. This is not to be confused with a
- /// [required group]. Requirement rules function just like [argument requirement rules], you
- /// can name other arguments or groups that must be present when one of the arguments from this
- /// group is used.
- ///
- /// **NOTE:** The names provided may be an argument, or group name
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, ArgGroup, ErrorKind};
- /// let result = App::new("myprog")
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .arg(Arg::with_name("color")
- /// .short("c"))
- /// .arg(Arg::with_name("debug")
- /// .short("d"))
- /// .arg(Arg::with_name("verb")
- /// .short("v"))
- /// .group(ArgGroup::with_name("req_flags")
- /// .args(&["flag", "color"])
- /// .requires_all(&["debug", "verb"]))
- /// .get_matches_from_safe(vec!["myprog", "-c", "-d"]);
- /// // because we used an arg from the group, and the group requires "-d" and "-v" to be used,
- /// // yet we only used "-d" it's an error
- /// assert!(result.is_err());
- /// let err = result.unwrap_err();
- /// assert_eq!(err.kind, ErrorKind::MissingRequiredArgument);
- /// ```
- /// [required group]: ./struct.ArgGroup.html#method.required
- /// [argument requirement rules]: ./struct.Arg.html#method.requires_all
- pub fn requires_all(mut self, ns: &[&'a str]) -> Self {
- for n in ns {
- self = self.requires(n);
- }
- self
- }
-
- /// Sets the exclusion rules of this group. Exclusion (aka conflict) rules function just like
- /// [argument exclusion rules], you can name other arguments or groups that must *not* be
- /// present when one of the arguments from this group are used.
- ///
- /// **NOTE:** The name provided may be an argument, or group name
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, ArgGroup, ErrorKind};
- /// let result = App::new("myprog")
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .arg(Arg::with_name("color")
- /// .short("c"))
- /// .arg(Arg::with_name("debug")
- /// .short("d"))
- /// .group(ArgGroup::with_name("req_flags")
- /// .args(&["flag", "color"])
- /// .conflicts_with("debug"))
- /// .get_matches_from_safe(vec!["myprog", "-c", "-d"]);
- /// // because we used an arg from the group, and the group conflicts with "-d", it's an error
- /// assert!(result.is_err());
- /// let err = result.unwrap_err();
- /// assert_eq!(err.kind, ErrorKind::ArgumentConflict);
- /// ```
- /// [argument exclusion rules]: ./struct.Arg.html#method.conflicts_with
- pub fn conflicts_with(mut self, n: &'a str) -> Self {
- if let Some(ref mut confs) = self.conflicts {
- confs.push(n);
- } else {
- self.conflicts = Some(vec![n]);
- }
- self
- }
-
- /// Sets the exclusion rules of this group. Exclusion rules function just like
- /// [argument exclusion rules], you can name other arguments or groups that must *not* be
- /// present when one of the arguments from this group are used.
- ///
- /// **NOTE:** The names provided may be an argument, or group name
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, ArgGroup, ErrorKind};
- /// let result = App::new("myprog")
- /// .arg(Arg::with_name("flag")
- /// .short("f"))
- /// .arg(Arg::with_name("color")
- /// .short("c"))
- /// .arg(Arg::with_name("debug")
- /// .short("d"))
- /// .arg(Arg::with_name("verb")
- /// .short("v"))
- /// .group(ArgGroup::with_name("req_flags")
- /// .args(&["flag", "color"])
- /// .conflicts_with_all(&["debug", "verb"]))
- /// .get_matches_from_safe(vec!["myprog", "-c", "-v"]);
- /// // because we used an arg from the group, and the group conflicts with either "-v" or "-d"
- /// // it's an error
- /// assert!(result.is_err());
- /// let err = result.unwrap_err();
- /// assert_eq!(err.kind, ErrorKind::ArgumentConflict);
- /// ```
- /// [argument exclusion rules]: ./struct.Arg.html#method.conflicts_with_all
- pub fn conflicts_with_all(mut self, ns: &[&'a str]) -> Self {
- for n in ns {
- self = self.conflicts_with(n);
- }
- self
- }
-}
-
-impl<'a> Debug for ArgGroup<'a> {
- fn fmt(&self, f: &mut Formatter) -> Result {
- write!(
- f,
- "{{\n\
- \tname: {:?},\n\
- \targs: {:?},\n\
- \trequired: {:?},\n\
- \trequires: {:?},\n\
- \tconflicts: {:?},\n\
- }}",
- self.name, self.args, self.required, self.requires, self.conflicts
- )
- }
-}
-
-impl<'a, 'z> From<&'z ArgGroup<'a>> for ArgGroup<'a> {
- fn from(g: &'z ArgGroup<'a>) -> Self {
- ArgGroup {
- name: g.name,
- required: g.required,
- args: g.args.clone(),
- requires: g.requires.clone(),
- conflicts: g.conflicts.clone(),
- multiple: g.multiple,
- }
- }
-}
-
-#[cfg(feature = "yaml")]
-impl<'a> From<&'a BTreeMap<Yaml, Yaml>> for ArgGroup<'a> {
- fn from(b: &'a BTreeMap<Yaml, Yaml>) -> Self {
- // We WANT this to panic on error...so expect() is good.
- let mut a = ArgGroup::default();
- let group_settings = if b.len() == 1 {
- let name_yml = b.keys().nth(0).expect("failed to get name");
- let name_str = name_yml
- .as_str()
- .expect("failed to convert arg YAML name to str");
- a.name = name_str;
- b.get(name_yml)
- .expect("failed to get name_str")
- .as_hash()
- .expect("failed to convert to a hash")
- } else {
- b
- };
-
- for (k, v) in group_settings {
- a = match k.as_str().unwrap() {
- "required" => a.required(v.as_bool().unwrap()),
- "multiple" => a.multiple(v.as_bool().unwrap()),
- "args" => yaml_vec_or_str!(v, a, arg),
- "arg" => {
- if let Some(ys) = v.as_str() {
- a = a.arg(ys);
- }
- a
- }
- "requires" => yaml_vec_or_str!(v, a, requires),
- "conflicts_with" => yaml_vec_or_str!(v, a, conflicts_with),
- "name" => {
- if let Some(ys) = v.as_str() {
- a.name = ys;
- }
- a
- }
- s => panic!(
- "Unknown ArgGroup setting '{}' in YAML file for \
- ArgGroup '{}'",
- s, a.name
- ),
- }
- }
-
- a
- }
-}
-
-#[cfg(test)]
-mod test {
- use super::ArgGroup;
- #[cfg(feature = "yaml")]
- use yaml_rust::YamlLoader;
-
- #[test]
- fn groups() {
- let g = ArgGroup::with_name("test")
- .arg("a1")
- .arg("a4")
- .args(&["a2", "a3"])
- .required(true)
- .conflicts_with("c1")
- .conflicts_with_all(&["c2", "c3"])
- .conflicts_with("c4")
- .requires("r1")
- .requires_all(&["r2", "r3"])
- .requires("r4");
-
- let args = vec!["a1", "a4", "a2", "a3"];
- let reqs = vec!["r1", "r2", "r3", "r4"];
- let confs = vec!["c1", "c2", "c3", "c4"];
-
- assert_eq!(g.args, args);
- assert_eq!(g.requires, Some(reqs));
- assert_eq!(g.conflicts, Some(confs));
- }
-
- #[test]
- fn test_debug() {
- let g = ArgGroup::with_name("test")
- .arg("a1")
- .arg("a4")
- .args(&["a2", "a3"])
- .required(true)
- .conflicts_with("c1")
- .conflicts_with_all(&["c2", "c3"])
- .conflicts_with("c4")
- .requires("r1")
- .requires_all(&["r2", "r3"])
- .requires("r4");
-
- let args = vec!["a1", "a4", "a2", "a3"];
- let reqs = vec!["r1", "r2", "r3", "r4"];
- let confs = vec!["c1", "c2", "c3", "c4"];
-
- let debug_str = format!(
- "{{\n\
- \tname: \"test\",\n\
- \targs: {:?},\n\
- \trequired: {:?},\n\
- \trequires: {:?},\n\
- \tconflicts: {:?},\n\
- }}",
- args,
- true,
- Some(reqs),
- Some(confs)
- );
- assert_eq!(&*format!("{:?}", g), &*debug_str);
- }
-
- #[test]
- fn test_from() {
- let g = ArgGroup::with_name("test")
- .arg("a1")
- .arg("a4")
- .args(&["a2", "a3"])
- .required(true)
- .conflicts_with("c1")
- .conflicts_with_all(&["c2", "c3"])
- .conflicts_with("c4")
- .requires("r1")
- .requires_all(&["r2", "r3"])
- .requires("r4");
-
- let args = vec!["a1", "a4", "a2", "a3"];
- let reqs = vec!["r1", "r2", "r3", "r4"];
- let confs = vec!["c1", "c2", "c3", "c4"];
-
- let g2 = ArgGroup::from(&g);
- assert_eq!(g2.args, args);
- assert_eq!(g2.requires, Some(reqs));
- assert_eq!(g2.conflicts, Some(confs));
- }
-
- #[cfg(feature = "yaml")]
- #[cfg_attr(feature = "yaml", test)]
- fn test_yaml() {
- let g_yaml = "name: test
-args:
-- a1
-- a4
-- a2
-- a3
-conflicts_with:
-- c1
-- c2
-- c3
-- c4
-requires:
-- r1
-- r2
-- r3
-- r4";
- let yml = &YamlLoader::load_from_str(g_yaml).expect("failed to load YAML file")[0];
- let g = ArgGroup::from_yaml(yml);
- let args = vec!["a1", "a4", "a2", "a3"];
- let reqs = vec!["r1", "r2", "r3", "r4"];
- let confs = vec!["c1", "c2", "c3", "c4"];
- assert_eq!(g.args, args);
- assert_eq!(g.requires, Some(reqs));
- assert_eq!(g.conflicts, Some(confs));
- }
-}
-
-impl<'a> Clone for ArgGroup<'a> {
- fn clone(&self) -> Self {
- ArgGroup {
- name: self.name,
- required: self.required,
- args: self.args.clone(),
- requires: self.requires.clone(),
- conflicts: self.conflicts.clone(),
- multiple: self.multiple,
- }
- }
-}
diff --git a/src/args/matched_arg.rs b/src/args/matched_arg.rs
deleted file mode 100644
index 681e5d2..0000000
--- a/src/args/matched_arg.rs
+++ /dev/null
@@ -1,29 +0,0 @@
-// Std
-use std::ffi::OsString;
-
-#[doc(hidden)]
-#[derive(Debug, Clone)]
-pub struct MatchedArg {
- #[doc(hidden)]
- pub occurs: u64,
- #[doc(hidden)]
- pub indices: Vec<usize>,
- #[doc(hidden)]
- pub vals: Vec<OsString>,
-}
-
-impl Default for MatchedArg {
- fn default() -> Self {
- MatchedArg {
- occurs: 1,
- indices: Vec::new(),
- vals: Vec::new(),
- }
- }
-}
-
-impl MatchedArg {
- pub fn new() -> Self {
- MatchedArg::default()
- }
-}
diff --git a/src/args/mod.rs b/src/args/mod.rs
deleted file mode 100644
index 8f076ea..0000000
--- a/src/args/mod.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-pub use self::any_arg::{AnyArg, DispOrder};
-pub use self::arg::Arg;
-pub use self::arg_builder::{Base, FlagBuilder, OptBuilder, PosBuilder, Switched, Valued};
-pub use self::arg_matcher::ArgMatcher;
-pub use self::arg_matches::{ArgMatches, OsValues, Values};
-pub use self::group::ArgGroup;
-pub use self::matched_arg::MatchedArg;
-pub use self::settings::{ArgFlags, ArgSettings};
-pub use self::subcommand::SubCommand;
-
-#[macro_use]
-mod macros;
-pub mod any_arg;
-mod arg;
-mod arg_builder;
-mod arg_matcher;
-mod arg_matches;
-mod group;
-mod matched_arg;
-pub mod settings;
-mod subcommand;
diff --git a/src/args/settings.rs b/src/args/settings.rs
deleted file mode 100644
index 833a1ea..0000000
--- a/src/args/settings.rs
+++ /dev/null
@@ -1,237 +0,0 @@
-// Std
-#[allow(deprecated, unused_imports)]
-use std::ascii::AsciiExt;
-use std::str::FromStr;
-
-bitflags! {
- struct Flags: u32 {
- const REQUIRED = 1;
- const MULTIPLE = 1 << 1;
- const EMPTY_VALS = 1 << 2;
- const GLOBAL = 1 << 3;
- const HIDDEN = 1 << 4;
- const TAKES_VAL = 1 << 5;
- const USE_DELIM = 1 << 6;
- const NEXT_LINE_HELP = 1 << 7;
- const R_UNLESS_ALL = 1 << 8;
- const REQ_DELIM = 1 << 9;
- const DELIM_NOT_SET = 1 << 10;
- const HIDE_POS_VALS = 1 << 11;
- const ALLOW_TAC_VALS = 1 << 12;
- const REQUIRE_EQUALS = 1 << 13;
- const LAST = 1 << 14;
- const HIDE_DEFAULT_VAL = 1 << 15;
- const CASE_INSENSITIVE = 1 << 16;
- const HIDE_ENV_VALS = 1 << 17;
- const HIDDEN_SHORT_H = 1 << 18;
- const HIDDEN_LONG_H = 1 << 19;
- }
-}
-
-#[doc(hidden)]
-#[derive(Debug, Clone, Copy)]
-pub struct ArgFlags(Flags);
-
-impl ArgFlags {
- pub fn new() -> Self {
- ArgFlags::default()
- }
-
- impl_settings! {ArgSettings,
- Required => Flags::REQUIRED,
- Multiple => Flags::MULTIPLE,
- EmptyValues => Flags::EMPTY_VALS,
- Global => Flags::GLOBAL,
- Hidden => Flags::HIDDEN,
- TakesValue => Flags::TAKES_VAL,
- UseValueDelimiter => Flags::USE_DELIM,
- NextLineHelp => Flags::NEXT_LINE_HELP,
- RequiredUnlessAll => Flags::R_UNLESS_ALL,
- RequireDelimiter => Flags::REQ_DELIM,
- ValueDelimiterNotSet => Flags::DELIM_NOT_SET,
- HidePossibleValues => Flags::HIDE_POS_VALS,
- AllowLeadingHyphen => Flags::ALLOW_TAC_VALS,
- RequireEquals => Flags::REQUIRE_EQUALS,
- Last => Flags::LAST,
- CaseInsensitive => Flags::CASE_INSENSITIVE,
- HideEnvValues => Flags::HIDE_ENV_VALS,
- HideDefaultValue => Flags::HIDE_DEFAULT_VAL,
- HiddenShortHelp => Flags::HIDDEN_SHORT_H,
- HiddenLongHelp => Flags::HIDDEN_LONG_H
- }
-}
-
-impl Default for ArgFlags {
- fn default() -> Self {
- ArgFlags(Flags::EMPTY_VALS | Flags::DELIM_NOT_SET)
- }
-}
-
-/// Various settings that apply to arguments and may be set, unset, and checked via getter/setter
-/// methods [`Arg::set`], [`Arg::unset`], and [`Arg::is_set`]
-///
-/// [`Arg::set`]: ./struct.Arg.html#method.set
-/// [`Arg::unset`]: ./struct.Arg.html#method.unset
-/// [`Arg::is_set`]: ./struct.Arg.html#method.is_set
-#[derive(Debug, PartialEq, Copy, Clone)]
-pub enum ArgSettings {
- /// The argument must be used
- Required,
- /// The argument may be used multiple times such as `--flag --flag`
- Multiple,
- /// The argument allows empty values such as `--option ""`
- EmptyValues,
- /// The argument should be propagated down through all child [`SubCommand`]s
- ///
- /// [`SubCommand`]: ./struct.SubCommand.html
- Global,
- /// The argument should **not** be shown in help text
- Hidden,
- /// The argument accepts a value, such as `--option <value>`
- TakesValue,
- /// Determines if the argument allows values to be grouped via a delimiter
- UseValueDelimiter,
- /// Prints the help text on the line after the argument
- NextLineHelp,
- /// Requires the use of a value delimiter for all multiple values
- RequireDelimiter,
- /// Hides the possible values from the help string
- HidePossibleValues,
- /// Allows vals that start with a '-'
- AllowLeadingHyphen,
- /// Require options use `--option=val` syntax
- RequireEquals,
- /// Specifies that the arg is the last positional argument and may be accessed early via `--`
- /// syntax
- Last,
- /// Hides the default value from the help string
- HideDefaultValue,
- /// Makes `Arg::possible_values` case insensitive
- CaseInsensitive,
- /// Hides ENV values in the help message
- HideEnvValues,
- /// The argument should **not** be shown in short help text
- HiddenShortHelp,
- /// The argument should **not** be shown in long help text
- HiddenLongHelp,
- #[doc(hidden)]
- RequiredUnlessAll,
- #[doc(hidden)]
- ValueDelimiterNotSet,
-}
-
-impl FromStr for ArgSettings {
- type Err = String;
- fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
- match &*s.to_ascii_lowercase() {
- "required" => Ok(ArgSettings::Required),
- "multiple" => Ok(ArgSettings::Multiple),
- "global" => Ok(ArgSettings::Global),
- "emptyvalues" => Ok(ArgSettings::EmptyValues),
- "hidden" => Ok(ArgSettings::Hidden),
- "takesvalue" => Ok(ArgSettings::TakesValue),
- "usevaluedelimiter" => Ok(ArgSettings::UseValueDelimiter),
- "nextlinehelp" => Ok(ArgSettings::NextLineHelp),
- "requiredunlessall" => Ok(ArgSettings::RequiredUnlessAll),
- "requiredelimiter" => Ok(ArgSettings::RequireDelimiter),
- "valuedelimiternotset" => Ok(ArgSettings::ValueDelimiterNotSet),
- "hidepossiblevalues" => Ok(ArgSettings::HidePossibleValues),
- "allowleadinghyphen" => Ok(ArgSettings::AllowLeadingHyphen),
- "requireequals" => Ok(ArgSettings::RequireEquals),
- "last" => Ok(ArgSettings::Last),
- "hidedefaultvalue" => Ok(ArgSettings::HideDefaultValue),
- "caseinsensitive" => Ok(ArgSettings::CaseInsensitive),
- "hideenvvalues" => Ok(ArgSettings::HideEnvValues),
- "hiddenshorthelp" => Ok(ArgSettings::HiddenShortHelp),
- "hiddenlonghelp" => Ok(ArgSettings::HiddenLongHelp),
- _ => Err("unknown ArgSetting, cannot convert from str".to_owned()),
- }
- }
-}
-
-#[cfg(test)]
-mod test {
- use super::ArgSettings;
-
- #[test]
- fn arg_settings_fromstr() {
- assert_eq!(
- "allowleadinghyphen".parse::<ArgSettings>().unwrap(),
- ArgSettings::AllowLeadingHyphen
- );
- assert_eq!(
- "emptyvalues".parse::<ArgSettings>().unwrap(),
- ArgSettings::EmptyValues
- );
- assert_eq!(
- "global".parse::<ArgSettings>().unwrap(),
- ArgSettings::Global
- );
- assert_eq!(
- "hidepossiblevalues".parse::<ArgSettings>().unwrap(),
- ArgSettings::HidePossibleValues
- );
- assert_eq!(
- "hidden".parse::<ArgSettings>().unwrap(),
- ArgSettings::Hidden
- );
- assert_eq!(
- "multiple".parse::<ArgSettings>().unwrap(),
- ArgSettings::Multiple
- );
- assert_eq!(
- "nextlinehelp".parse::<ArgSettings>().unwrap(),
- ArgSettings::NextLineHelp
- );
- assert_eq!(
- "requiredunlessall".parse::<ArgSettings>().unwrap(),
- ArgSettings::RequiredUnlessAll
- );
- assert_eq!(
- "requiredelimiter".parse::<ArgSettings>().unwrap(),
- ArgSettings::RequireDelimiter
- );
- assert_eq!(
- "required".parse::<ArgSettings>().unwrap(),
- ArgSettings::Required
- );
- assert_eq!(
- "takesvalue".parse::<ArgSettings>().unwrap(),
- ArgSettings::TakesValue
- );
- assert_eq!(
- "usevaluedelimiter".parse::<ArgSettings>().unwrap(),
- ArgSettings::UseValueDelimiter
- );
- assert_eq!(
- "valuedelimiternotset".parse::<ArgSettings>().unwrap(),
- ArgSettings::ValueDelimiterNotSet
- );
- assert_eq!(
- "requireequals".parse::<ArgSettings>().unwrap(),
- ArgSettings::RequireEquals
- );
- assert_eq!("last".parse::<ArgSettings>().unwrap(), ArgSettings::Last);
- assert_eq!(
- "hidedefaultvalue".parse::<ArgSettings>().unwrap(),
- ArgSettings::HideDefaultValue
- );
- assert_eq!(
- "caseinsensitive".parse::<ArgSettings>().unwrap(),
- ArgSettings::CaseInsensitive
- );
- assert_eq!(
- "hideenvvalues".parse::<ArgSettings>().unwrap(),
- ArgSettings::HideEnvValues
- );
- assert_eq!(
- "hiddenshorthelp".parse::<ArgSettings>().unwrap(),
- ArgSettings::HiddenShortHelp
- );
- assert_eq!(
- "hiddenlonghelp".parse::<ArgSettings>().unwrap(),
- ArgSettings::HiddenLongHelp
- );
- assert!("hahahaha".parse::<ArgSettings>().is_err());
- }
-}
diff --git a/src/args/subcommand.rs b/src/args/subcommand.rs
deleted file mode 100644
index 8b8049e..0000000
--- a/src/args/subcommand.rs
+++ /dev/null
@@ -1,72 +0,0 @@
-// Third Party
-#[cfg(feature = "yaml")]
-use yaml_rust::Yaml;
-
-// Internal
-use App;
-use ArgMatches;
-
-/// The abstract representation of a command line subcommand.
-///
-/// This struct describes all the valid options of the subcommand for the program. Subcommands are
-/// essentially "sub-[`App`]s" and contain all the same possibilities (such as their own
-/// [arguments], subcommands, and settings).
-///
-/// # Examples
-///
-/// ```rust
-/// # use clap::{App, Arg, SubCommand};
-/// App::new("myprog")
-/// .subcommand(
-/// SubCommand::with_name("config")
-/// .about("Used for configuration")
-/// .arg(Arg::with_name("config_file")
-/// .help("The configuration file to use")
-/// .index(1)))
-/// # ;
-/// ```
-/// [`App`]: ./struct.App.html
-/// [arguments]: ./struct.Arg.html
-#[derive(Debug, Clone)]
-pub struct SubCommand<'a> {
- #[doc(hidden)]
- pub name: String,
- #[doc(hidden)]
- pub matches: ArgMatches<'a>,
-}
-
-impl<'a> SubCommand<'a> {
- /// Creates a new instance of a subcommand requiring a name. The name will be displayed
- /// to the user when they print version or help and usage information.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, SubCommand};
- /// App::new("myprog")
- /// .subcommand(
- /// SubCommand::with_name("config"))
- /// # ;
- /// ```
- pub fn with_name<'b>(name: &str) -> App<'a, 'b> {
- App::new(name)
- }
-
- /// Creates a new instance of a subcommand from a YAML (.yml) document
- ///
- /// # Examples
- ///
- /// ```ignore
- /// # #[macro_use]
- /// # extern crate clap;
- /// # use clap::Subcommand;
- /// # fn main() {
- /// let sc_yaml = load_yaml!("test_subcommand.yml");
- /// let sc = SubCommand::from_yaml(sc_yaml);
- /// # }
- /// ```
- #[cfg(feature = "yaml")]
- pub fn from_yaml(yaml: &Yaml) -> App {
- App::from_yaml(yaml)
- }
-}
diff --git a/src/bin/stdio-fixture.rs b/src/bin/stdio-fixture.rs
new file mode 100644
index 0000000..3a60d13
--- /dev/null
+++ b/src/bin/stdio-fixture.rs
@@ -0,0 +1,15 @@
+fn main() {
+ let cmd = clap::Command::new("stdio-fixture")
+ .version("1.0")
+ .long_version("1.0 - a2132c")
+ .arg_required_else_help(true)
+ .subcommand(clap::Command::new("more"))
+ .arg(
+ clap::Arg::new("verbose")
+ .long("verbose")
+ .help("log")
+ .action(clap::ArgAction::SetTrue)
+ .long_help("more log"),
+ );
+ cmd.get_matches();
+}
diff --git a/src/builder/action.rs b/src/builder/action.rs
new file mode 100644
index 0000000..9739f88
--- /dev/null
+++ b/src/builder/action.rs
@@ -0,0 +1,344 @@
+/// Behavior of arguments when they are encountered while parsing
+///
+/// # Examples
+///
+#[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+#[cfg_attr(feature = "help", doc = " ```")]
+/// # use clap::Command;
+/// # use clap::Arg;
+/// let cmd = Command::new("mycmd")
+/// .arg(
+/// Arg::new("special-help")
+/// .short('?')
+/// .action(clap::ArgAction::Help)
+/// );
+///
+/// // Existing help still exists
+/// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err();
+/// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
+///
+/// // New help available
+/// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err();
+/// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
+/// ```
+#[derive(Clone, Debug)]
+#[non_exhaustive]
+#[allow(missing_copy_implementations)] // In the future, we may accept `Box<dyn ...>`
+pub enum ArgAction {
+ /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches]
+ ///
+ /// **NOTE:** If the argument has previously been seen, it will result in a
+ /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless
+ /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("flag")
+ /// .long("flag")
+ /// .action(clap::ArgAction::Set)
+ /// );
+ ///
+ /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(),
+ /// vec!["value"]
+ /// );
+ /// ```
+ Set,
+ /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("flag")
+ /// .long("flag")
+ /// .action(clap::ArgAction::Append)
+ /// );
+ ///
+ /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value1", "--flag", "value2"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(),
+ /// vec!["value1", "value2"]
+ /// );
+ /// ```
+ Append,
+ /// When encountered, act as if `"true"` was encountered on the command-line
+ ///
+ /// If no [`default_value`][super::Arg::default_value] is set, it will be `false`.
+ ///
+ /// No value is allowed. To optionally accept a value, see
+ /// [`Arg::default_missing_value`][super::Arg::default_missing_value]
+ ///
+ /// **NOTE:** If the argument has previously been seen, it will result in a
+ /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless
+ /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set.
+ ///
+ /// # 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"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_flag("flag"),
+ /// true
+ /// );
+ ///
+ /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_flag("flag"),
+ /// false
+ /// );
+ /// ```
+ ///
+ /// You can use [`TypedValueParser::map`][crate::builder::TypedValueParser::map] to have the
+ /// flag control an application-specific type:
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// # use clap::builder::TypedValueParser as _;
+ /// # use clap::builder::BoolishValueParser;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("flag")
+ /// .long("flag")
+ /// .action(clap::ArgAction::SetTrue)
+ /// .value_parser(
+ /// BoolishValueParser::new()
+ /// .map(|b| -> usize {
+ /// if b { 10 } else { 5 }
+ /// })
+ /// )
+ /// );
+ ///
+ /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_one::<usize>("flag").copied(),
+ /// Some(10)
+ /// );
+ ///
+ /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_one::<usize>("flag").copied(),
+ /// Some(5)
+ /// );
+ /// ```
+ SetTrue,
+ /// When encountered, act as if `"false"` was encountered on the command-line
+ ///
+ /// If no [`default_value`][super::Arg::default_value] is set, it will be `true`.
+ ///
+ /// No value is allowed. To optionally accept a value, see
+ /// [`Arg::default_missing_value`][super::Arg::default_missing_value]
+ ///
+ /// **NOTE:** If the argument has previously been seen, it will result in a
+ /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless
+ /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("flag")
+ /// .long("flag")
+ /// .action(clap::ArgAction::SetFalse)
+ /// );
+ ///
+ /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_flag("flag"),
+ /// false
+ /// );
+ ///
+ /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_flag("flag"),
+ /// true
+ /// );
+ /// ```
+ SetFalse,
+ /// When encountered, increment a `u8` counter
+ ///
+ /// If no [`default_value`][super::Arg::default_value] is set, it will be `0`.
+ ///
+ /// No value is allowed. To optionally accept a value, see
+ /// [`Arg::default_missing_value`][super::Arg::default_missing_value]
+ ///
+ /// # 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!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_count("flag"),
+ /// 2
+ /// );
+ ///
+ /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_count("flag"),
+ /// 0
+ /// );
+ /// ```
+ Count,
+ /// When encountered, display [`Command::print_help`][super::Command::print_help]
+ ///
+ /// Depending on the flag, [`Command::print_long_help`][super::Command::print_long_help] may be shown
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("special-help")
+ /// .short('?')
+ /// .action(clap::ArgAction::Help)
+ /// );
+ ///
+ /// // Existing help still exists
+ /// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err();
+ /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
+ ///
+ /// // New help available
+ /// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err();
+ /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
+ /// ```
+ Help,
+ /// When encountered, display [`Command::version`][super::Command::version]
+ ///
+ /// Depending on the flag, [`Command::long_version`][super::Command::long_version] may be shown
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// let cmd = Command::new("mycmd")
+ /// .version("1.0.0")
+ /// .arg(
+ /// Arg::new("special-version")
+ /// .long("special-version")
+ /// .action(clap::ArgAction::Version)
+ /// );
+ ///
+ /// // Existing help still exists
+ /// let err = cmd.clone().try_get_matches_from(["mycmd", "--version"]).unwrap_err();
+ /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion);
+ ///
+ /// // New help available
+ /// let err = cmd.try_get_matches_from(["mycmd", "--special-version"]).unwrap_err();
+ /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion);
+ /// ```
+ Version,
+}
+
+impl ArgAction {
+ /// Returns whether this action accepts values on the command-line
+ ///
+ /// [`default_values`][super::Arg::default_values] and [`env`][super::Arg::env] may still be
+ /// 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::Version => false,
+ }
+ }
+
+ pub(crate) fn default_value(&self) -> Option<&'static std::ffi::OsStr> {
+ match self {
+ Self::Set => None,
+ Self::Append => None,
+ 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::Version => None,
+ }
+ }
+
+ pub(crate) fn default_missing_value(&self) -> Option<&'static std::ffi::OsStr> {
+ match self {
+ Self::Set => None,
+ 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::Version => None,
+ }
+ }
+
+ pub(crate) fn default_value_parser(&self) -> Option<super::ValueParser> {
+ match self {
+ Self::Set => None,
+ Self::Append => None,
+ Self::SetTrue => Some(super::ValueParser::bool()),
+ Self::SetFalse => Some(super::ValueParser::bool()),
+ Self::Count => Some(crate::value_parser!(u8).into()),
+ Self::Help => None,
+ Self::Version => None,
+ }
+ }
+
+ #[cfg(debug_assertions)]
+ pub(crate) fn value_type_id(&self) -> Option<crate::parser::AnyValueId> {
+ use crate::parser::AnyValueId;
+
+ match self {
+ Self::Set => None,
+ Self::Append => None,
+ Self::SetTrue => None,
+ Self::SetFalse => None,
+ Self::Count => Some(AnyValueId::of::<CountType>()),
+ Self::Help => None,
+ Self::Version => None,
+ }
+ }
+}
+
+pub(crate) type CountType = u8;
diff --git a/src/builder/app_settings.rs b/src/builder/app_settings.rs
new file mode 100644
index 0000000..7a9ff8c
--- /dev/null
+++ b/src/builder/app_settings.rs
@@ -0,0 +1,172 @@
+// Std
+use std::ops::BitOr;
+
+#[allow(unused)]
+use crate::Arg;
+#[allow(unused)]
+use crate::Command;
+
+// Third party
+use bitflags::bitflags;
+
+#[doc(hidden)]
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+pub(crate) struct AppFlags(Flags);
+
+impl Default for AppFlags {
+ fn default() -> Self {
+ AppFlags(Flags::COLOR_AUTO)
+ }
+}
+
+/// Application level settings, which affect how [`Command`] operates
+///
+/// **NOTE:** When these settings are used, they apply only to current command, and are *not*
+/// propagated down or up through child or parent subcommands
+///
+/// [`Command`]: crate::Command
+#[derive(Debug, PartialEq, Copy, Clone)]
+#[non_exhaustive]
+pub(crate) enum AppSettings {
+ IgnoreErrors,
+ AllowHyphenValues,
+ AllowNegativeNumbers,
+ AllArgsOverrideSelf,
+ AllowMissingPositional,
+ TrailingVarArg,
+ DontDelimitTrailingValues,
+ InferLongArgs,
+ InferSubcommands,
+ SubcommandRequired,
+ AllowExternalSubcommands,
+ Multicall,
+ SubcommandsNegateReqs,
+ ArgsNegateSubcommands,
+ SubcommandPrecedenceOverArg,
+ ArgRequiredElseHelp,
+ NextLineHelp,
+ DisableColoredHelp,
+ DisableHelpFlag,
+ DisableHelpSubcommand,
+ DisableVersionFlag,
+ PropagateVersion,
+ Hidden,
+ HidePossibleValues,
+ HelpExpected,
+ NoBinaryName,
+ #[allow(dead_code)]
+ ColorAuto,
+ ColorAlways,
+ ColorNever,
+ Built,
+ BinNameBuilt,
+}
+
+bitflags! {
+ struct Flags: u64 {
+ const SC_NEGATE_REQS = 1;
+ const SC_REQUIRED = 1 << 1;
+ const ARG_REQUIRED_ELSE_HELP = 1 << 2;
+ const PROPAGATE_VERSION = 1 << 3;
+ const DISABLE_VERSION_FOR_SC = 1 << 4;
+ const WAIT_ON_ERROR = 1 << 6;
+ const DISABLE_VERSION_FLAG = 1 << 10;
+ const HIDDEN = 1 << 11;
+ const TRAILING_VARARG = 1 << 12;
+ const NO_BIN_NAME = 1 << 13;
+ const ALLOW_UNK_SC = 1 << 14;
+ const LEADING_HYPHEN = 1 << 16;
+ const NO_POS_VALUES = 1 << 17;
+ const NEXT_LINE_HELP = 1 << 18;
+ const DISABLE_COLORED_HELP = 1 << 20;
+ const COLOR_ALWAYS = 1 << 21;
+ const COLOR_AUTO = 1 << 22;
+ const COLOR_NEVER = 1 << 23;
+ const DONT_DELIM_TRAIL = 1 << 24;
+ const ALLOW_NEG_NUMS = 1 << 25;
+ const DISABLE_HELP_SC = 1 << 27;
+ const ARGS_NEGATE_SCS = 1 << 29;
+ const PROPAGATE_VALS_DOWN = 1 << 30;
+ const ALLOW_MISSING_POS = 1 << 31;
+ const TRAILING_VALUES = 1 << 32;
+ const BUILT = 1 << 33;
+ const BIN_NAME_BUILT = 1 << 34;
+ const VALID_ARG_FOUND = 1 << 35;
+ const INFER_SUBCOMMANDS = 1 << 36;
+ const CONTAINS_LAST = 1 << 37;
+ const ARGS_OVERRIDE_SELF = 1 << 38;
+ const HELP_REQUIRED = 1 << 39;
+ const SUBCOMMAND_PRECEDENCE_OVER_ARG = 1 << 40;
+ const DISABLE_HELP_FLAG = 1 << 41;
+ const INFER_LONG_ARGS = 1 << 43;
+ const IGNORE_ERRORS = 1 << 44;
+ const MULTICALL = 1 << 45;
+ const EXPAND_HELP_SUBCOMMAND_TREES = 1 << 46;
+ const NO_OP = 0;
+ }
+}
+
+impl_settings! { AppSettings, AppFlags,
+ ArgRequiredElseHelp
+ => Flags::ARG_REQUIRED_ELSE_HELP,
+ SubcommandPrecedenceOverArg
+ => Flags::SUBCOMMAND_PRECEDENCE_OVER_ARG,
+ ArgsNegateSubcommands
+ => Flags::ARGS_NEGATE_SCS,
+ AllowExternalSubcommands
+ => Flags::ALLOW_UNK_SC,
+ AllowHyphenValues
+ => Flags::LEADING_HYPHEN,
+ AllowNegativeNumbers
+ => Flags::ALLOW_NEG_NUMS,
+ AllowMissingPositional
+ => Flags::ALLOW_MISSING_POS,
+ ColorAlways
+ => Flags::COLOR_ALWAYS,
+ ColorAuto
+ => Flags::COLOR_AUTO,
+ ColorNever
+ => Flags::COLOR_NEVER,
+ DontDelimitTrailingValues
+ => Flags::DONT_DELIM_TRAIL,
+ DisableColoredHelp
+ => Flags::DISABLE_COLORED_HELP,
+ DisableHelpSubcommand
+ => Flags::DISABLE_HELP_SC,
+ DisableHelpFlag
+ => Flags::DISABLE_HELP_FLAG,
+ DisableVersionFlag
+ => Flags::DISABLE_VERSION_FLAG,
+ PropagateVersion
+ => Flags::PROPAGATE_VERSION,
+ HidePossibleValues
+ => Flags::NO_POS_VALUES,
+ HelpExpected
+ => Flags::HELP_REQUIRED,
+ Hidden
+ => Flags::HIDDEN,
+ Multicall
+ => Flags::MULTICALL,
+ NoBinaryName
+ => Flags::NO_BIN_NAME,
+ SubcommandsNegateReqs
+ => Flags::SC_NEGATE_REQS,
+ SubcommandRequired
+ => Flags::SC_REQUIRED,
+ TrailingVarArg
+ => Flags::TRAILING_VARARG,
+ NextLineHelp
+ => Flags::NEXT_LINE_HELP,
+ IgnoreErrors
+ => Flags::IGNORE_ERRORS,
+ Built
+ => Flags::BUILT,
+ BinNameBuilt
+ => Flags::BIN_NAME_BUILT,
+ InferSubcommands
+ => Flags::INFER_SUBCOMMANDS,
+ AllArgsOverrideSelf
+ => Flags::ARGS_OVERRIDE_SELF,
+ InferLongArgs
+ => Flags::INFER_LONG_ARGS
+}
diff --git a/src/builder/arg.rs b/src/builder/arg.rs
new file mode 100644
index 0000000..bf898cb
--- /dev/null
+++ b/src/builder/arg.rs
@@ -0,0 +1,4648 @@
+// Std
+#[cfg(feature = "env")]
+use std::env;
+#[cfg(feature = "env")]
+use std::ffi::OsString;
+use std::{
+ cmp::{Ord, Ordering},
+ fmt::{self, Display, Formatter},
+ str,
+};
+
+// Internal
+use super::{ArgFlags, ArgSettings};
+use crate::builder::ArgPredicate;
+use crate::builder::IntoResettable;
+use crate::builder::OsStr;
+use crate::builder::PossibleValue;
+use crate::builder::Str;
+use crate::builder::StyledStr;
+use crate::builder::ValueRange;
+use crate::ArgAction;
+use crate::Id;
+use crate::ValueHint;
+use crate::INTERNAL_ERROR_MSG;
+
+/// The abstract representation of a command line argument. Used to set all the options and
+/// relationships that define a valid argument for the program.
+///
+/// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options
+/// manually, or using a usage string which is far less verbose but has fewer options. You can also
+/// use a combination of the two methods to achieve the best of both worlds.
+///
+/// - [Basic API][crate::Arg#basic-api]
+/// - [Value Handling][crate::Arg#value-handling]
+/// - [Help][crate::Arg#help-1]
+/// - [Advanced Argument Relations][crate::Arg#advanced-argument-relations]
+/// - [Reflection][crate::Arg#reflection]
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::{Arg, arg, ArgAction};
+/// // Using the traditional builder pattern and setting each option manually
+/// let cfg = Arg::new("config")
+/// .short('c')
+/// .long("config")
+/// .action(ArgAction::Set)
+/// .value_name("FILE")
+/// .help("Provides a config file to myprog");
+/// // Using a usage string (setting a similar argument to the one above)
+/// let input = arg!(-i --input <FILE> "Provides an input file to the program");
+/// ```
+#[derive(Default, Clone)]
+pub struct Arg {
+ pub(crate) id: Id,
+ pub(crate) help: Option<StyledStr>,
+ pub(crate) long_help: Option<StyledStr>,
+ pub(crate) action: Option<ArgAction>,
+ pub(crate) value_parser: Option<super::ValueParser>,
+ pub(crate) blacklist: Vec<Id>,
+ pub(crate) settings: ArgFlags,
+ pub(crate) overrides: Vec<Id>,
+ pub(crate) groups: Vec<Id>,
+ pub(crate) requires: Vec<(ArgPredicate, Id)>,
+ pub(crate) r_ifs: Vec<(Id, OsStr)>,
+ pub(crate) r_ifs_all: Vec<(Id, OsStr)>,
+ pub(crate) r_unless: Vec<Id>,
+ pub(crate) r_unless_all: Vec<Id>,
+ pub(crate) short: Option<char>,
+ pub(crate) long: Option<Str>,
+ pub(crate) aliases: Vec<(Str, bool)>, // (name, visible)
+ pub(crate) short_aliases: Vec<(char, bool)>, // (name, visible)
+ pub(crate) disp_ord: Option<usize>,
+ pub(crate) val_names: Vec<Str>,
+ pub(crate) num_vals: Option<ValueRange>,
+ pub(crate) val_delim: Option<char>,
+ pub(crate) default_vals: Vec<OsStr>,
+ pub(crate) default_vals_ifs: Vec<(Id, ArgPredicate, Option<OsStr>)>,
+ pub(crate) default_missing_vals: Vec<OsStr>,
+ #[cfg(feature = "env")]
+ pub(crate) env: Option<(OsStr, Option<OsString>)>,
+ pub(crate) terminator: Option<Str>,
+ pub(crate) index: Option<usize>,
+ pub(crate) help_heading: Option<Option<Str>>,
+ pub(crate) value_hint: Option<ValueHint>,
+}
+
+/// # Basic API
+impl Arg {
+ /// Create a new [`Arg`] with a unique name.
+ ///
+ /// The name is used to check whether or not the argument was used at
+ /// runtime, get values, set relationships with other args, etc..
+ ///
+ /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::action(ArgAction::Set)`])
+ /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also
+ /// be displayed when the user prints the usage/help information of the program.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("config")
+ /// # ;
+ /// ```
+ /// [`Arg::action(ArgAction::Set)`]: Arg::action()
+ pub fn new(id: impl Into<Id>) -> Self {
+ Arg::default().id(id)
+ }
+
+ /// Set the identifier used for referencing this argument in the clap API.
+ ///
+ /// See [`Arg::new`] for more details.
+ #[must_use]
+ pub fn id(mut self, id: impl Into<Id>) -> Self {
+ self.id = id.into();
+ self
+ }
+
+ /// Sets the short version of the argument without the preceding `-`.
+ ///
+ /// By default `V` and `h` are used by the auto-generated `version` and `help` arguments,
+ /// respectively. You will need to disable the auto-generated flags
+ /// ([`disable_help_flag`][crate::Command::disable_help_flag],
+ /// [`disable_version_flag`][crate::Command::disable_version_flag]) and define your own.
+ ///
+ /// # Examples
+ ///
+ /// When calling `short`, use a single valid UTF-8 character which will allow using the
+ /// argument via a single hyphen (`-`) such as `-c`:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("config")
+ /// .short('c')
+ /// .action(ArgAction::Set))
+ /// .get_matches_from(vec![
+ /// "prog", "-c", "file.toml"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("config").map(String::as_str), Some("file.toml"));
+ /// ```
+ ///
+ /// To use `-h` for your own flag and still have help:
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .disable_help_flag(true)
+ /// .arg(Arg::new("host")
+ /// .short('h')
+ /// .long("host"))
+ /// .arg(Arg::new("help")
+ /// .long("help")
+ /// .global(true)
+ /// .action(ArgAction::Help))
+ /// .get_matches_from(vec![
+ /// "prog", "-h", "wikipedia.org"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("host").map(String::as_str), Some("wikipedia.org"));
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn short(mut self, s: impl IntoResettable<char>) -> Self {
+ if let Some(s) = s.into_resettable().into_option() {
+ debug_assert!(s != '-', "short option name cannot be `-`");
+ self.short = Some(s);
+ } else {
+ self.short = None;
+ }
+ self
+ }
+
+ /// Sets the long version of the argument without the preceding `--`.
+ ///
+ /// By default `version` and `help` are used by the auto-generated `version` and `help`
+ /// arguments, respectively. You may use the word `version` or `help` for the long form of your
+ /// own arguments, in which case `clap` simply will not assign those to the auto-generated
+ /// `version` or `help` arguments.
+ ///
+ /// **NOTE:** Any leading `-` characters will be stripped
+ ///
+ /// # Examples
+ ///
+ /// To set `long` use a word containing valid UTF-8. If you supply a double leading
+ /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however,
+ /// will *not* be stripped (i.e. `config-file` is allowed).
+ ///
+ /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config`
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .action(ArgAction::Set))
+ /// .get_matches_from(vec![
+ /// "prog", "--config", "file.toml"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("cfg").map(String::as_str), Some("file.toml"));
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn long(mut self, l: impl IntoResettable<Str>) -> Self {
+ self.long = l.into_resettable().into_option();
+ self
+ }
+
+ /// Add an alias, which functions as a hidden long flag.
+ ///
+ /// This is more efficient, and easier than creating multiple hidden arguments as one only
+ /// needs to check for the existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .long("test")
+ /// .alias("alias")
+ /// .action(ArgAction::Set))
+ /// .get_matches_from(vec![
+ /// "prog", "--alias", "cool"
+ /// ]);
+ /// assert_eq!(m.get_one::<String>("test").unwrap(), "cool");
+ /// ```
+ #[must_use]
+ pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self {
+ if let Some(name) = name.into_resettable().into_option() {
+ self.aliases.push((name, false));
+ } else {
+ self.aliases.clear();
+ }
+ self
+ }
+
+ /// Add an alias, which functions as a hidden short flag.
+ ///
+ /// This is more efficient, and easier than creating multiple hidden arguments as one only
+ /// needs to check for the existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .short('t')
+ /// .short_alias('e')
+ /// .action(ArgAction::Set))
+ /// .get_matches_from(vec![
+ /// "prog", "-e", "cool"
+ /// ]);
+ /// assert_eq!(m.get_one::<String>("test").unwrap(), "cool");
+ /// ```
+ #[must_use]
+ pub fn short_alias(mut self, name: impl IntoResettable<char>) -> Self {
+ if let Some(name) = name.into_resettable().into_option() {
+ debug_assert!(name != '-', "short alias name cannot be `-`");
+ self.short_aliases.push((name, false));
+ } else {
+ self.short_aliases.clear();
+ }
+ self
+ }
+
+ /// Add aliases, which function as hidden long flags.
+ ///
+ /// This is more efficient, and easier than creating multiple hidden subcommands as one only
+ /// needs to check for the existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .long("test")
+ /// .aliases(["do-stuff", "do-tests", "tests"])
+ /// .action(ArgAction::SetTrue)
+ /// .help("the file to add")
+ /// .required(false))
+ /// .get_matches_from(vec![
+ /// "prog", "--do-tests"
+ /// ]);
+ /// assert_eq!(m.get_flag("test"), true);
+ /// ```
+ #[must_use]
+ pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
+ self.aliases
+ .extend(names.into_iter().map(|x| (x.into(), false)));
+ self
+ }
+
+ /// Add aliases, which functions as a hidden short flag.
+ ///
+ /// This is more efficient, and easier than creating multiple hidden subcommands as one only
+ /// needs to check for the existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .short('t')
+ /// .short_aliases(['e', 's'])
+ /// .action(ArgAction::SetTrue)
+ /// .help("the file to add")
+ /// .required(false))
+ /// .get_matches_from(vec![
+ /// "prog", "-s"
+ /// ]);
+ /// assert_eq!(m.get_flag("test"), true);
+ /// ```
+ #[must_use]
+ pub fn short_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self {
+ for s in names {
+ debug_assert!(s != '-', "short alias name cannot be `-`");
+ self.short_aliases.push((s, false));
+ }
+ self
+ }
+
+ /// Add an alias, which functions as a visible long flag.
+ ///
+ /// Like [`Arg::alias`], except that they are visible inside the help message.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .visible_alias("something-awesome")
+ /// .long("test")
+ /// .action(ArgAction::Set))
+ /// .get_matches_from(vec![
+ /// "prog", "--something-awesome", "coffee"
+ /// ]);
+ /// assert_eq!(m.get_one::<String>("test").unwrap(), "coffee");
+ /// ```
+ /// [`Command::alias`]: Arg::alias()
+ #[must_use]
+ pub fn visible_alias(mut self, name: impl IntoResettable<Str>) -> Self {
+ if let Some(name) = name.into_resettable().into_option() {
+ self.aliases.push((name, true));
+ } else {
+ self.aliases.clear();
+ }
+ self
+ }
+
+ /// Add an alias, which functions as a visible short flag.
+ ///
+ /// Like [`Arg::short_alias`], except that they are visible inside the help message.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .long("test")
+ /// .visible_short_alias('t')
+ /// .action(ArgAction::Set))
+ /// .get_matches_from(vec![
+ /// "prog", "-t", "coffee"
+ /// ]);
+ /// assert_eq!(m.get_one::<String>("test").unwrap(), "coffee");
+ /// ```
+ #[must_use]
+ pub fn visible_short_alias(mut self, name: impl IntoResettable<char>) -> Self {
+ if let Some(name) = name.into_resettable().into_option() {
+ debug_assert!(name != '-', "short alias name cannot be `-`");
+ self.short_aliases.push((name, true));
+ } else {
+ self.short_aliases.clear();
+ }
+ self
+ }
+
+ /// Add aliases, which function as visible long flags.
+ ///
+ /// Like [`Arg::aliases`], except that they are visible inside the help message.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .long("test")
+ /// .action(ArgAction::SetTrue)
+ /// .visible_aliases(["something", "awesome", "cool"]))
+ /// .get_matches_from(vec![
+ /// "prog", "--awesome"
+ /// ]);
+ /// assert_eq!(m.get_flag("test"), true);
+ /// ```
+ /// [`Command::aliases`]: Arg::aliases()
+ #[must_use]
+ pub fn visible_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
+ self.aliases
+ .extend(names.into_iter().map(|n| (n.into(), true)));
+ self
+ }
+
+ /// Add aliases, which function as visible short flags.
+ ///
+ /// Like [`Arg::short_aliases`], except that they are visible inside the help message.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("test")
+ /// .long("test")
+ /// .action(ArgAction::SetTrue)
+ /// .visible_short_aliases(['t', 'e']))
+ /// .get_matches_from(vec![
+ /// "prog", "-t"
+ /// ]);
+ /// assert_eq!(m.get_flag("test"), true);
+ /// ```
+ #[must_use]
+ pub fn visible_short_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self {
+ for n in names {
+ debug_assert!(n != '-', "short alias name cannot be `-`");
+ self.short_aliases.push((n, true));
+ }
+ self
+ }
+
+ /// Specifies the index of a positional argument **starting at** 1.
+ ///
+ /// **NOTE:** The index refers to position according to **other positional argument**. It does
+ /// not define position in the argument list as a whole.
+ ///
+ /// **NOTE:** You can optionally leave off the `index` method, and the index will be
+ /// assigned in order of evaluation. Utilizing the `index` method allows for setting
+ /// indexes out of order
+ ///
+ /// **NOTE:** This is only meant to be used for positional arguments and shouldn't to be used
+ /// with [`Arg::short`] or [`Arg::long`].
+ ///
+ /// **NOTE:** When utilized with [`Arg::num_args(1..)`], only the **last** positional argument
+ /// may be defined as having a variable number of arguments (i.e. with the highest index)
+ ///
+ /// # Panics
+ ///
+ /// [`Command`] will [`panic!`] if indexes are skipped (such as defining `index(1)` and `index(3)`
+ /// but not `index(2)`, or a positional argument is defined as multiple and is not the highest
+ /// index
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("config")
+ /// .index(1)
+ /// # ;
+ /// ```
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("mode")
+ /// .index(1))
+ /// .arg(Arg::new("debug")
+ /// .long("debug")
+ /// .action(ArgAction::SetTrue))
+ /// .get_matches_from(vec![
+ /// "prog", "--debug", "fast"
+ /// ]);
+ ///
+ /// assert!(m.contains_id("mode"));
+ /// assert_eq!(m.get_one::<String>("mode").unwrap(), "fast"); // notice index(1) means "first positional"
+ /// // *not* first argument
+ /// ```
+ /// [`Arg::short`]: Arg::short()
+ /// [`Arg::long`]: Arg::long()
+ /// [`Arg::num_args(true)`]: Arg::num_args()
+ /// [`Command`]: crate::Command
+ #[inline]
+ #[must_use]
+ pub fn index(mut self, idx: impl IntoResettable<usize>) -> Self {
+ self.index = idx.into_resettable().into_option();
+ self
+ }
+
+ /// This is a "VarArg" and everything that follows should be captured by it, as if the user had
+ /// used a `--`.
+ ///
+ /// **NOTE:** To start the trailing "VarArg" on unknown flags (and not just a positional
+ /// value), set [`allow_hyphen_values`][Arg::allow_hyphen_values]. Either way, users still
+ /// have the option to explicitly escape ambiguous arguments with `--`.
+ ///
+ /// **NOTE:** [`Arg::value_delimiter`] still applies if set.
+ ///
+ /// **NOTE:** Setting this requires [`Arg::num_args(..)`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, arg};
+ /// let m = Command::new("myprog")
+ /// .arg(arg!(<cmd> ... "commands to run").trailing_var_arg(true))
+ /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]);
+ ///
+ /// let trail: Vec<_> = m.get_many::<String>("cmd").unwrap().collect();
+ /// assert_eq!(trail, ["arg1", "-r", "val1"]);
+ /// ```
+ /// [`Arg::num_args(..)`]: crate::Arg::num_args()
+ pub fn trailing_var_arg(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::TrailingVarArg)
+ } else {
+ self.unset_setting(ArgSettings::TrailingVarArg)
+ }
+ }
+
+ /// This arg is the last, or final, positional argument (i.e. has the highest
+ /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args --
+ /// last_arg`).
+ ///
+ /// Even, if no other arguments are left to parse, if the user omits the `--` syntax
+ /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also
+ /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with
+ /// the `--` syntax is otherwise not possible.
+ ///
+ /// **NOTE:** This will change the usage string to look like `$ prog [OPTIONS] [-- <ARG>]` if
+ /// `ARG` is marked as `.last(true)`.
+ ///
+ /// **NOTE:** This setting will imply [`crate::Command::dont_collapse_args_in_usage`] because failing
+ /// to set this can make the usage string very confusing.
+ ///
+ /// **NOTE**: This setting only applies to positional arguments, and has no effect on OPTIONS
+ ///
+ /// **NOTE:** Setting this requires [taking values][Arg::num_args]
+ ///
+ /// **CAUTION:** Using this setting *and* having child subcommands is not
+ /// recommended with the exception of *also* using
+ /// [`crate::Command::args_conflicts_with_subcommands`]
+ /// (or [`crate::Command::subcommand_negates_reqs`] if the argument marked `Last` is also
+ /// marked [`Arg::required`])
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Arg, ArgAction};
+ /// Arg::new("args")
+ /// .action(ArgAction::Set)
+ /// .last(true)
+ /// # ;
+ /// ```
+ ///
+ /// Setting `last` ensures the arg has the highest [index] of all positional args
+ /// and requires that the `--` syntax be used to access it early.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("first"))
+ /// .arg(Arg::new("second"))
+ /// .arg(Arg::new("third")
+ /// .action(ArgAction::Set)
+ /// .last(true))
+ /// .try_get_matches_from(vec![
+ /// "prog", "one", "--", "three"
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// let m = res.unwrap();
+ /// assert_eq!(m.get_one::<String>("third").unwrap(), "three");
+ /// assert_eq!(m.get_one::<String>("second"), None);
+ /// ```
+ ///
+ /// Even if the positional argument marked `Last` is the only argument left to parse,
+ /// failing to use the `--` syntax results in an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("first"))
+ /// .arg(Arg::new("second"))
+ /// .arg(Arg::new("third")
+ /// .action(ArgAction::Set)
+ /// .last(true))
+ /// .try_get_matches_from(vec![
+ /// "prog", "one", "two", "three"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
+ /// ```
+ /// [index]: Arg::index()
+ /// [`UnknownArgument`]: crate::error::ErrorKind::UnknownArgument
+ #[inline]
+ #[must_use]
+ pub fn last(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::Last)
+ } else {
+ self.unset_setting(ArgSettings::Last)
+ }
+ }
+
+ /// Specifies that the argument must be present.
+ ///
+ /// Required by default means it is required, when no other conflicting rules or overrides have
+ /// been evaluated. Conflicting rules take precedence over being required.
+ ///
+ /// **Pro tip:** Flags (i.e. not positional, or arguments that take values) shouldn't be
+ /// required by default. This is because if a flag were to be required, it should simply be
+ /// implied. No additional information is required from user. Flags by their very nature are
+ /// simply boolean on/off switches. The only time a user *should* be required to use a flag
+ /// is if the operation is destructive in nature, and the user is essentially proving to you,
+ /// "Yes, I know what I'm doing."
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required(true)
+ /// # ;
+ /// ```
+ ///
+ /// Setting required requires that the argument be used at runtime.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required(true)
+ /// .action(ArgAction::Set)
+ /// .long("config"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "file.conf",
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// ```
+ ///
+ /// Setting required and then *not* supplying that argument at runtime is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required(true)
+ /// .action(ArgAction::Set)
+ /// .long("config"))
+ /// .try_get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn required(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::Required)
+ } else {
+ self.unset_setting(ArgSettings::Required)
+ }
+ }
+
+ /// Sets an argument that is required when this one is present
+ ///
+ /// i.e. when using this argument, the following argument *must* be present.
+ ///
+ /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .requires("input")
+ /// # ;
+ /// ```
+ ///
+ /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the
+ /// defining argument is used. If the defining argument isn't used, the other argument isn't
+ /// required
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .requires("input")
+ /// .long("config"))
+ /// .arg(Arg::new("input"))
+ /// .try_get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required
+ /// ```
+ ///
+ /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .requires("input")
+ /// .long("config"))
+ /// .arg(Arg::new("input"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "file.conf"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [`Arg::requires(name)`]: Arg::requires()
+ /// [Conflicting]: Arg::conflicts_with()
+ /// [override]: Arg::overrides_with()
+ #[must_use]
+ pub fn requires(mut self, arg_id: impl IntoResettable<Id>) -> Self {
+ if let Some(arg_id) = arg_id.into_resettable().into_option() {
+ self.requires.push((ArgPredicate::IsPresent, arg_id));
+ } else {
+ self.requires.clear();
+ }
+ self
+ }
+
+ /// This argument must be passed alone; it conflicts with all other arguments.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .exclusive(true)
+ /// # ;
+ /// ```
+ ///
+ /// Setting an exclusive argument and having any other arguments present at runtime
+ /// is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("exclusive")
+ /// .action(ArgAction::Set)
+ /// .exclusive(true)
+ /// .long("exclusive"))
+ /// .arg(Arg::new("debug")
+ /// .long("debug"))
+ /// .arg(Arg::new("input"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--exclusive", "file.conf", "file.txt"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn exclusive(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::Exclusive)
+ } else {
+ self.unset_setting(ArgSettings::Exclusive)
+ }
+ }
+
+ /// Specifies that an argument can be matched to all child [`Subcommand`]s.
+ ///
+ /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however
+ /// their values once a user uses them will be propagated back up to parents. In effect, this
+ /// means one should *define* all global arguments at the top level, however it doesn't matter
+ /// where the user *uses* the global argument.
+ ///
+ /// # Examples
+ ///
+ /// Assume an application with two subcommands, and you'd like to define a
+ /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't
+ /// want to clutter the source with three duplicate [`Arg`] definitions.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("verb")
+ /// .long("verbose")
+ /// .short('v')
+ /// .action(ArgAction::SetTrue)
+ /// .global(true))
+ /// .subcommand(Command::new("test"))
+ /// .subcommand(Command::new("do-stuff"))
+ /// .get_matches_from(vec![
+ /// "prog", "do-stuff", "--verbose"
+ /// ]);
+ ///
+ /// assert_eq!(m.subcommand_name(), Some("do-stuff"));
+ /// let sub_m = m.subcommand_matches("do-stuff").unwrap();
+ /// assert_eq!(sub_m.get_flag("verb"), true);
+ /// ```
+ ///
+ /// [`Subcommand`]: crate::Subcommand
+ #[inline]
+ #[must_use]
+ pub fn global(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::Global)
+ } else {
+ self.unset_setting(ArgSettings::Global)
+ }
+ }
+
+ #[inline]
+ pub(crate) fn is_set(&self, s: ArgSettings) -> bool {
+ self.settings.is_set(s)
+ }
+
+ #[inline]
+ #[must_use]
+ pub(crate) fn setting<F>(mut self, setting: F) -> Self
+ where
+ F: Into<ArgFlags>,
+ {
+ self.settings.insert(setting.into());
+ self
+ }
+
+ #[inline]
+ #[must_use]
+ pub(crate) fn unset_setting<F>(mut self, setting: F) -> Self
+ where
+ F: Into<ArgFlags>,
+ {
+ self.settings.remove(setting.into());
+ self
+ }
+}
+
+/// # Value Handling
+impl Arg {
+ /// Specify how to react to an argument when parsing it.
+ ///
+ /// [ArgAction][crate::ArgAction] controls things like
+ /// - Overwriting previous values with new ones
+ /// - Appending new values to all previous ones
+ /// - Counting how many times a flag occurs
+ ///
+ /// The default action is `ArgAction::Set`
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("flag")
+ /// .long("flag")
+ /// .action(clap::ArgAction::Append)
+ /// );
+ ///
+ /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(),
+ /// vec!["value"]
+ /// );
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn action(mut self, action: impl IntoResettable<ArgAction>) -> Self {
+ self.action = action.into_resettable().into_option();
+ self
+ }
+
+ /// Specify the typed behavior of the argument.
+ ///
+ /// This allows parsing and validating a value before storing it into
+ /// [`ArgMatches`][crate::ArgMatches] as the given type.
+ ///
+ /// Possible value parsers include:
+ /// - [`value_parser!(T)`][crate::value_parser!] for auto-selecting a value parser for a given type
+ /// - Or [range expressions like `0..=1`][std::ops::RangeBounds] as a shorthand for [`RangedI64ValueParser`][crate::builder::RangedI64ValueParser]
+ /// - `Fn(&str) -> Result<T, E>`
+ /// - `[&str]` and [`PossibleValuesParser`][crate::builder::PossibleValuesParser] for static enumerated values
+ /// - [`BoolishValueParser`][crate::builder::BoolishValueParser], and [`FalseyValueParser`][crate::builder::FalseyValueParser] for alternative `bool` implementations
+ /// - [`NonEmptyStringValueParser`][crate::builder::NonEmptyStringValueParser] for basic validation for strings
+ /// - or any other [`TypedValueParser`][crate::builder::TypedValueParser] implementation
+ ///
+ /// The default value is [`ValueParser::string`][crate::builder::ValueParser::string].
+ ///
+ /// ```rust
+ /// # use clap::ArgAction;
+ /// let mut cmd = clap::Command::new("raw")
+ /// .arg(
+ /// clap::Arg::new("color")
+ /// .long("color")
+ /// .value_parser(["always", "auto", "never"])
+ /// .default_value("auto")
+ /// )
+ /// .arg(
+ /// clap::Arg::new("hostname")
+ /// .long("hostname")
+ /// .value_parser(clap::builder::NonEmptyStringValueParser::new())
+ /// .action(ArgAction::Set)
+ /// .required(true)
+ /// )
+ /// .arg(
+ /// clap::Arg::new("port")
+ /// .long("port")
+ /// .value_parser(clap::value_parser!(u16).range(3000..))
+ /// .action(ArgAction::Set)
+ /// .required(true)
+ /// );
+ ///
+ /// let m = cmd.try_get_matches_from_mut(
+ /// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"]
+ /// ).unwrap();
+ ///
+ /// let color: &String = m.get_one("color")
+ /// .expect("default");
+ /// assert_eq!(color, "auto");
+ ///
+ /// let hostname: &String = m.get_one("hostname")
+ /// .expect("required");
+ /// assert_eq!(hostname, "rust-lang.org");
+ ///
+ /// let port: u16 = *m.get_one("port")
+ /// .expect("required");
+ /// assert_eq!(port, 3001);
+ /// ```
+ pub fn value_parser(mut self, parser: impl IntoResettable<super::ValueParser>) -> Self {
+ self.value_parser = parser.into_resettable().into_option();
+ self
+ }
+
+ /// Specifies the number of arguments parsed per occurrence
+ ///
+ /// For example, if you had a `-f <file>` argument where you wanted exactly 3 'files' you would
+ /// set `.num_args(3)`, and this argument wouldn't be satisfied unless the user
+ /// provided 3 and only 3 values.
+ ///
+ /// Users may specify values for arguments in any of the following methods
+ ///
+ /// - Using a space such as `-o value` or `--option value`
+ /// - Using an equals and no space such as `-o=value` or `--option=value`
+ /// - Use a short and no space such as `-ovalue`
+ ///
+ /// **WARNING:**
+ ///
+ /// Setting a variable number of values (e.g. `1..=10`) for an argument without
+ /// other details can be dangerous in some circumstances. Because multiple values are
+ /// allowed, `--option val1 val2 val3` is perfectly valid. Be careful when designing a CLI
+ /// where **positional arguments** or **subcommands** are *also* expected as `clap` will continue
+ /// parsing *values* until one of the following happens:
+ ///
+ /// - It reaches the maximum number of values
+ /// - It reaches a specific number of values
+ /// - It finds another flag or option (i.e. something that starts with a `-`)
+ /// - It reaches the [`Arg::value_terminator`] if set
+ ///
+ /// Alternatively,
+ /// - Use a delimiter between values with [Arg::value_delimiter]
+ /// - Require a flag occurrence per value with [`ArgAction::Append`]
+ /// - Require positional arguments to appear after `--` with [`Arg::last`]
+ ///
+ /// # Examples
+ ///
+ /// Option:
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("mode")
+ /// .long("mode")
+ /// .num_args(1))
+ /// .get_matches_from(vec![
+ /// "prog", "--mode", "fast"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("mode").unwrap(), "fast");
+ /// ```
+ ///
+ /// Flag/option hybrid (see also [default_missing_value][Arg::default_missing_value])
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let cmd = Command::new("prog")
+ /// .arg(Arg::new("mode")
+ /// .long("mode")
+ /// .default_missing_value("slow")
+ /// .default_value("plaid")
+ /// .num_args(0..=1));
+ ///
+ /// let m = cmd.clone()
+ /// .get_matches_from(vec![
+ /// "prog", "--mode", "fast"
+ /// ]);
+ /// assert_eq!(m.get_one::<String>("mode").unwrap(), "fast");
+ ///
+ /// let m = cmd.clone()
+ /// .get_matches_from(vec![
+ /// "prog", "--mode",
+ /// ]);
+ /// assert_eq!(m.get_one::<String>("mode").unwrap(), "slow");
+ ///
+ /// let m = cmd.clone()
+ /// .get_matches_from(vec![
+ /// "prog",
+ /// ]);
+ /// assert_eq!(m.get_one::<String>("mode").unwrap(), "plaid");
+ /// ```
+ ///
+ /// Tuples
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let cmd = Command::new("prog")
+ /// .arg(Arg::new("file")
+ /// .action(ArgAction::Set)
+ /// .num_args(2)
+ /// .short('F'));
+ ///
+ /// let m = cmd.clone()
+ /// .get_matches_from(vec![
+ /// "prog", "-F", "in-file", "out-file"
+ /// ]);
+ /// assert_eq!(
+ /// m.get_many::<String>("file").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(),
+ /// vec!["in-file", "out-file"]
+ /// );
+ ///
+ /// let res = cmd.clone()
+ /// .try_get_matches_from(vec![
+ /// "prog", "-F", "file1"
+ /// ]);
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::WrongNumberOfValues);
+ /// ```
+ ///
+ /// A common mistake is to define an option which allows multiple values and a positional
+ /// argument.
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let cmd = Command::new("prog")
+ /// .arg(Arg::new("file")
+ /// .action(ArgAction::Set)
+ /// .num_args(0..)
+ /// .short('F'))
+ /// .arg(Arg::new("word"));
+ ///
+ /// let m = cmd.clone().get_matches_from(vec![
+ /// "prog", "-F", "file1", "file2", "file3", "word"
+ /// ]);
+ /// let files: Vec<_> = m.get_many::<String>("file").unwrap().collect();
+ /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?!
+ /// assert!(!m.contains_id("word")); // but we clearly used word!
+ ///
+ /// // but this works
+ /// let m = cmd.clone().get_matches_from(vec![
+ /// "prog", "word", "-F", "file1", "file2", "file3",
+ /// ]);
+ /// let files: Vec<_> = m.get_many::<String>("file").unwrap().collect();
+ /// assert_eq!(files, ["file1", "file2", "file3"]);
+ /// assert_eq!(m.get_one::<String>("word").unwrap(), "word");
+ /// ```
+ /// The problem is `clap` doesn't know when to stop parsing values for "file".
+ ///
+ /// A solution for the example above is to limit how many values with a maximum, or specific
+ /// number, or to say [`ArgAction::Append`] is ok, but multiple values are not.
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("file")
+ /// .action(ArgAction::Append)
+ /// .short('F'))
+ /// .arg(Arg::new("word"))
+ /// .get_matches_from(vec![
+ /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word"
+ /// ]);
+ ///
+ /// let files: Vec<_> = m.get_many::<String>("file").unwrap().collect();
+ /// assert_eq!(files, ["file1", "file2", "file3"]);
+ /// assert_eq!(m.get_one::<String>("word").unwrap(), "word");
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn num_args(mut self, qty: impl IntoResettable<ValueRange>) -> Self {
+ self.num_vals = qty.into_resettable().into_option();
+ self
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Arg::num_args`")
+ )]
+ pub fn number_of_values(self, qty: usize) -> Self {
+ self.num_args(qty)
+ }
+
+ /// Placeholder for the argument's value in the help message / usage.
+ ///
+ /// This name is cosmetic only; the name is **not** used to access arguments.
+ /// This setting can be very helpful when describing the type of input the user should be
+ /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to
+ /// use all capital letters for the value name.
+ ///
+ /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("cfg")
+ /// .long("config")
+ /// .value_name("FILE")
+ /// # ;
+ /// ```
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("config")
+ /// .long("config")
+ /// .value_name("FILE")
+ /// .help("Some help text"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ /// Running the above program produces the following output
+ ///
+ /// ```text
+ /// valnames
+ ///
+ /// Usage: valnames [OPTIONS]
+ ///
+ /// Options:
+ /// --config <FILE> Some help text
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ /// [positional]: Arg::index()
+ /// [`Arg::action(ArgAction::Set)`]: Arg::action()
+ #[inline]
+ #[must_use]
+ pub fn value_name(mut self, name: impl IntoResettable<Str>) -> Self {
+ if let Some(name) = name.into_resettable().into_option() {
+ self.value_names([name])
+ } else {
+ self.val_names.clear();
+ self
+ }
+ }
+
+ /// Placeholders for the argument's values in the help message / usage.
+ ///
+ /// These names are cosmetic only, used for help and usage strings only. The names are **not**
+ /// used to access arguments. The values of the arguments are accessed in numeric order (i.e.
+ /// if you specify two names `one` and `two` `one` will be the first matched value, `two` will
+ /// be the second).
+ ///
+ /// This setting can be very helpful when describing the type of input the user should be
+ /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to
+ /// use all capital letters for the value name.
+ ///
+ /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or
+ /// multiple value names in order to not throw off the help text alignment of all options.
+ ///
+ /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`] and [`Arg::num_args(1..)`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("speed")
+ /// .short('s')
+ /// .value_names(["fast", "slow"]);
+ /// ```
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("io")
+ /// .long("io-files")
+ /// .value_names(["INFILE", "OUTFILE"]))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// Running the above program produces the following output
+ ///
+ /// ```text
+ /// valnames
+ ///
+ /// Usage: valnames [OPTIONS]
+ ///
+ /// Options:
+ /// -h, --help Print help information
+ /// --io-files <INFILE> <OUTFILE> Some help text
+ /// -V, --version Print version information
+ /// ```
+ /// [`Arg::next_line_help(true)`]: Arg::next_line_help()
+ /// [`Arg::num_args`]: Arg::num_args()
+ /// [`Arg::action(ArgAction::Set)`]: Arg::action()
+ /// [`Arg::num_args(1..)`]: Arg::num_args()
+ #[must_use]
+ pub fn value_names(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
+ self.val_names = names.into_iter().map(|s| s.into()).collect();
+ self
+ }
+
+ /// Provide the shell a hint about how to complete this argument.
+ ///
+ /// See [`ValueHint`][crate::ValueHint] for more information.
+ ///
+ /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`].
+ ///
+ /// For example, to take a username as argument:
+ ///
+ /// ```
+ /// # use clap::{Arg, ValueHint};
+ /// Arg::new("user")
+ /// .short('u')
+ /// .long("user")
+ /// .value_hint(ValueHint::Username);
+ /// ```
+ ///
+ /// To take a full command line and its arguments (for example, when writing a command wrapper):
+ ///
+ /// ```
+ /// # use clap::{Command, Arg, ValueHint, ArgAction};
+ /// Command::new("prog")
+ /// .trailing_var_arg(true)
+ /// .arg(
+ /// Arg::new("command")
+ /// .action(ArgAction::Set)
+ /// .num_args(1..)
+ /// .value_hint(ValueHint::CommandWithArguments)
+ /// );
+ /// ```
+ #[must_use]
+ pub fn value_hint(mut self, value_hint: impl IntoResettable<ValueHint>) -> Self {
+ self.value_hint = value_hint.into_resettable().into_option();
+ self
+ }
+
+ /// Match values against [`PossibleValuesParser`][crate::builder::PossibleValuesParser] without matching case.
+ ///
+ /// When other arguments are conditionally required based on the
+ /// value of a case-insensitive argument, the equality check done
+ /// by [`Arg::required_if_eq`], [`Arg::required_if_eq_any`], or
+ /// [`Arg::required_if_eq_all`] is case-insensitive.
+ ///
+ ///
+ /// **NOTE:** Setting this requires [taking values][Arg::num_args]
+ ///
+ /// **NOTE:** To do unicode case folding, enable the `unicode` feature flag.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("pv")
+ /// .arg(Arg::new("option")
+ /// .long("option")
+ /// .action(ArgAction::Set)
+ /// .ignore_case(true)
+ /// .value_parser(["test123"]))
+ /// .get_matches_from(vec![
+ /// "pv", "--option", "TeSt123",
+ /// ]);
+ ///
+ /// assert!(m.get_one::<String>("option").unwrap().eq_ignore_ascii_case("test123"));
+ /// ```
+ ///
+ /// This setting also works when multiple values can be defined:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("pv")
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .long("option")
+ /// .action(ArgAction::Set)
+ /// .ignore_case(true)
+ /// .num_args(1..)
+ /// .value_parser(["test123", "test321"]))
+ /// .get_matches_from(vec![
+ /// "pv", "--option", "TeSt123", "teST123", "tESt321"
+ /// ]);
+ ///
+ /// let matched_vals = m.get_many::<String>("option").unwrap().collect::<Vec<_>>();
+ /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]);
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn ignore_case(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::IgnoreCase)
+ } else {
+ self.unset_setting(ArgSettings::IgnoreCase)
+ }
+ }
+
+ /// Allows values which start with a leading hyphen (`-`)
+ ///
+ /// To limit values to just numbers, see
+ /// [`allow_negative_numbers`][Arg::allow_negative_numbers].
+ ///
+ /// See also [`trailing_var_arg`][Arg::trailing_var_arg].
+ ///
+ /// **NOTE:** Setting this requires [taking values][Arg::num_args]
+ ///
+ /// **WARNING:** Prior arguments with `allow_hyphen_values(true)` get precedence over known
+ /// flags but known flags get precedence over the next possible positional argument with
+ /// `allow_hyphen_values(true)`. When combined with [`Arg::num_args(..)`],
+ /// [`Arg::value_terminator`] is one way to ensure processing stops.
+ ///
+ /// **WARNING**: Take caution when using this setting combined with another argument using
+ /// [`Arg::num_args`], as this becomes ambiguous `$ prog --arg -- -- val`. All
+ /// three `--, --, val` will be values when the user may have thought the second `--` would
+ /// constitute the normal, "Only positional args follow" idiom.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("pat")
+ /// .action(ArgAction::Set)
+ /// .allow_hyphen_values(true)
+ /// .long("pattern"))
+ /// .get_matches_from(vec![
+ /// "prog", "--pattern", "-file"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("pat").unwrap(), "-file");
+ /// ```
+ ///
+ /// Not setting `Arg::allow_hyphen_values(true)` and supplying a value which starts with a
+ /// hyphen is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("pat")
+ /// .action(ArgAction::Set)
+ /// .long("pattern"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--pattern", "-file"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
+ /// ```
+ /// [`Arg::num_args(1)`]: Arg::num_args()
+ #[inline]
+ #[must_use]
+ pub fn allow_hyphen_values(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::AllowHyphenValues)
+ } else {
+ self.unset_setting(ArgSettings::AllowHyphenValues)
+ }
+ }
+
+ /// Allows negative numbers to pass as values.
+ ///
+ /// This is similar to [`Arg::allow_hyphen_values`] except that it only allows numbers,
+ /// all other undefined leading hyphens will fail to parse.
+ ///
+ /// **NOTE:** Setting this requires [taking values][Arg::num_args]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let res = Command::new("myprog")
+ /// .arg(Arg::new("num").allow_negative_numbers(true))
+ /// .try_get_matches_from(vec![
+ /// "myprog", "-20"
+ /// ]);
+ /// assert!(res.is_ok());
+ /// let m = res.unwrap();
+ /// assert_eq!(m.get_one::<String>("num").unwrap(), "-20");
+ /// ```
+ #[inline]
+ pub fn allow_negative_numbers(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::AllowNegativeNumbers)
+ } else {
+ self.unset_setting(ArgSettings::AllowNegativeNumbers)
+ }
+ }
+
+ /// Requires that options use the `--option=val` syntax
+ ///
+ /// i.e. an equals between the option and associated value.
+ ///
+ /// **NOTE:** Setting this requires [taking values][Arg::num_args]
+ ///
+ /// # Examples
+ ///
+ /// Setting `require_equals` requires that the option have an equals sign between
+ /// it and the associated value.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .require_equals(true)
+ /// .long("config"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config=file.conf"
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// ```
+ ///
+ /// Setting `require_equals` and *not* supplying the equals will cause an
+ /// error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .require_equals(true)
+ /// .long("config"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "file.conf"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals);
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn require_equals(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::RequireEquals)
+ } else {
+ self.unset_setting(ArgSettings::RequireEquals)
+ }
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Arg::value_delimiter`")
+ )]
+ pub fn use_value_delimiter(mut self, yes: bool) -> Self {
+ if yes {
+ self.val_delim.get_or_insert(',');
+ } else {
+ self.val_delim = None;
+ }
+ self
+ }
+
+ /// Allow grouping of multiple values via a delimiter.
+ ///
+ /// i.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`,
+ /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the
+ /// value delimiter for all arguments that accept values (options and positional arguments)
+ ///
+ /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("config")
+ /// .short('c')
+ /// .long("config")
+ /// .value_delimiter(','))
+ /// .get_matches_from(vec![
+ /// "prog", "--config=val1,val2,val3"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_many::<String>("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"])
+ /// ```
+ /// [`Arg::value_delimiter(',')`]: Arg::value_delimiter()
+ /// [`Arg::action(ArgAction::Set)`]: Arg::action()
+ #[inline]
+ #[must_use]
+ pub fn value_delimiter(mut self, d: impl IntoResettable<char>) -> Self {
+ self.val_delim = d.into_resettable().into_option();
+ self
+ }
+
+ /// Sentinel to **stop** parsing multiple values of a given argument.
+ ///
+ /// By default when
+ /// one sets [`num_args(1..)`] on an argument, clap will continue parsing values for that
+ /// argument until it reaches another valid argument, or one of the other more specific settings
+ /// for multiple values is used (such as [`num_args`]).
+ ///
+ /// **NOTE:** This setting only applies to [options] and [positional arguments]
+ ///
+ /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one
+ /// of the values
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// Arg::new("vals")
+ /// .action(ArgAction::Set)
+ /// .num_args(1..)
+ /// .value_terminator(";")
+ /// # ;
+ /// ```
+ ///
+ /// The following example uses two arguments, a sequence of commands, and the location in which
+ /// to perform them
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cmds")
+ /// .action(ArgAction::Set)
+ /// .num_args(1..)
+ /// .allow_hyphen_values(true)
+ /// .value_terminator(";"))
+ /// .arg(Arg::new("location"))
+ /// .get_matches_from(vec![
+ /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap"
+ /// ]);
+ /// let cmds: Vec<_> = m.get_many::<String>("cmds").unwrap().collect();
+ /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]);
+ /// assert_eq!(m.get_one::<String>("location").unwrap(), "/home/clap");
+ /// ```
+ /// [options]: Arg::action
+ /// [positional arguments]: Arg::index()
+ /// [`num_args(1..)`]: Arg::num_args()
+ /// [`num_args`]: Arg::num_args()
+ #[inline]
+ #[must_use]
+ pub fn value_terminator(mut self, term: impl IntoResettable<Str>) -> Self {
+ self.terminator = term.into_resettable().into_option();
+ self
+ }
+
+ /// Consume all following arguments.
+ ///
+ /// Do not be parse them individually, but rather pass them in entirety.
+ ///
+ /// It is worth noting that setting this requires all values to come after a `--` to indicate
+ /// they should all be captured. For example:
+ ///
+ /// ```text
+ /// --foo something -- -v -v -v -b -b -b --baz -q -u -x
+ /// ```
+ ///
+ /// Will result in everything after `--` to be considered one raw argument. This behavior
+ /// may not be exactly what you are expecting and using [`crate::Command::trailing_var_arg`]
+ /// may be more appropriate.
+ ///
+ /// **NOTE:** Implicitly sets [`Arg::action(ArgAction::Set)`] [`Arg::num_args(1..)`],
+ /// [`Arg::allow_hyphen_values(true)`], and [`Arg::last(true)`] when set to `true`.
+ ///
+ /// [`Arg::action(ArgAction::Set)`]: Arg::action()
+ /// [`Arg::num_args(1..)`]: Arg::num_args()
+ /// [`Arg::allow_hyphen_values(true)`]: Arg::allow_hyphen_values()
+ /// [`Arg::last(true)`]: Arg::last()
+ #[inline]
+ #[must_use]
+ pub fn raw(mut self, yes: bool) -> Self {
+ if yes {
+ self.num_vals.get_or_insert_with(|| (1..).into());
+ }
+ self.allow_hyphen_values(yes).last(yes)
+ }
+
+ /// Value for the argument when not present.
+ ///
+ /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::contains_id`] will
+ /// still return `true`. If you wish to determine whether the argument was used at runtime or
+ /// not, consider [`ArgMatches::value_source`][crate::ArgMatches::value_source].
+ ///
+ /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly
+ /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg
+ /// at runtime. `Arg::default_value_if` however only takes effect when the user has not provided
+ /// a value at runtime **and** these other conditions are met as well. If you have set
+ /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide this arg
+ /// at runtime, nor were the conditions met for `Arg::default_value_if`, the `Arg::default_value`
+ /// will be applied.
+ ///
+ /// **NOTE:** This implicitly sets [`Arg::action(ArgAction::Set)`].
+ ///
+ /// # Examples
+ ///
+ /// First we use the default value without providing any value at runtime.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, parser::ValueSource};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("opt")
+ /// .long("myopt")
+ /// .default_value("myval"))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("opt").unwrap(), "myval");
+ /// assert!(m.contains_id("opt"));
+ /// assert_eq!(m.value_source("opt"), Some(ValueSource::DefaultValue));
+ /// ```
+ ///
+ /// Next we provide a value at runtime to override the default.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, parser::ValueSource};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("opt")
+ /// .long("myopt")
+ /// .default_value("myval"))
+ /// .get_matches_from(vec![
+ /// "prog", "--myopt=non_default"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("opt").unwrap(), "non_default");
+ /// assert!(m.contains_id("opt"));
+ /// assert_eq!(m.value_source("opt"), Some(ValueSource::CommandLine));
+ /// ```
+ /// [`Arg::action(ArgAction::Set)`]: Arg::action()
+ /// [`ArgMatches::contains_id`]: crate::ArgMatches::contains_id()
+ /// [`Arg::default_value_if`]: Arg::default_value_if()
+ #[inline]
+ #[must_use]
+ pub fn default_value(mut self, val: impl IntoResettable<OsStr>) -> Self {
+ if let Some(val) = val.into_resettable().into_option() {
+ self.default_values([val])
+ } else {
+ self.default_vals.clear();
+ self
+ }
+ }
+
+ #[inline]
+ #[must_use]
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value`")
+ )]
+ pub fn default_value_os(self, val: impl Into<OsStr>) -> Self {
+ self.default_values([val])
+ }
+
+ /// Value for the argument when not present.
+ ///
+ /// See [`Arg::default_value`].
+ ///
+ /// [`Arg::default_value`]: Arg::default_value()
+ #[inline]
+ #[must_use]
+ pub fn default_values(mut self, vals: impl IntoIterator<Item = impl Into<OsStr>>) -> Self {
+ self.default_vals = vals.into_iter().map(|s| s.into()).collect();
+ self
+ }
+
+ #[inline]
+ #[must_use]
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Arg::default_values`")
+ )]
+ pub fn default_values_os(self, vals: impl IntoIterator<Item = impl Into<OsStr>>) -> Self {
+ self.default_values(vals)
+ }
+
+ /// Value for the argument when the flag is present but no value is specified.
+ ///
+ /// This configuration option is often used to give the user a shortcut and allow them to
+ /// efficiently specify an option argument without requiring an explicitly value. The `--color`
+ /// argument is a common example. By, supplying an default, such as `default_missing_value("always")`,
+ /// the user can quickly just add `--color` to the command line to produce the desired color output.
+ ///
+ /// **NOTE:** using this configuration option requires the use of the
+ /// [`.num_args(0..N)`][Arg::num_args] and the
+ /// [`.require_equals(true)`][Arg::require_equals] configuration option. These are required in
+ /// order to unambiguously determine what, if any, value was supplied for the argument.
+ ///
+ /// # Examples
+ ///
+ /// For POSIX style `--color`:
+ /// ```rust
+ /// # use clap::{Command, Arg, parser::ValueSource};
+ /// fn cli() -> Command {
+ /// Command::new("prog")
+ /// .arg(Arg::new("color").long("color")
+ /// .value_name("WHEN")
+ /// .value_parser(["always", "auto", "never"])
+ /// .default_value("auto")
+ /// .num_args(0..=1)
+ /// .require_equals(true)
+ /// .default_missing_value("always")
+ /// .help("Specify WHEN to colorize output.")
+ /// )
+ /// }
+ ///
+ /// // first, we'll provide no arguments
+ /// let m = cli().get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ /// assert_eq!(m.get_one::<String>("color").unwrap(), "auto");
+ /// assert_eq!(m.value_source("color"), Some(ValueSource::DefaultValue));
+ ///
+ /// // next, we'll provide a runtime value to override the default (as usually done).
+ /// let m = cli().get_matches_from(vec![
+ /// "prog", "--color=never"
+ /// ]);
+ /// assert_eq!(m.get_one::<String>("color").unwrap(), "never");
+ /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));
+ ///
+ /// // finally, we will use the shortcut and only provide the argument without a value.
+ /// let m = cli().get_matches_from(vec![
+ /// "prog", "--color"
+ /// ]);
+ /// assert_eq!(m.get_one::<String>("color").unwrap(), "always");
+ /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));
+ /// ```
+ ///
+ /// For bool literals:
+ /// ```rust
+ /// # use clap::{Command, Arg, parser::ValueSource, value_parser};
+ /// fn cli() -> Command {
+ /// Command::new("prog")
+ /// .arg(Arg::new("create").long("create")
+ /// .value_name("BOOL")
+ /// .value_parser(value_parser!(bool))
+ /// .num_args(0..=1)
+ /// .require_equals(true)
+ /// .default_missing_value("true")
+ /// )
+ /// }
+ ///
+ /// // first, we'll provide no arguments
+ /// let m = cli().get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ /// assert_eq!(m.get_one::<bool>("create").copied(), None);
+ ///
+ /// // next, we'll provide a runtime value to override the default (as usually done).
+ /// let m = cli().get_matches_from(vec![
+ /// "prog", "--create=false"
+ /// ]);
+ /// assert_eq!(m.get_one::<bool>("create").copied(), Some(false));
+ /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));
+ ///
+ /// // finally, we will use the shortcut and only provide the argument without a value.
+ /// let m = cli().get_matches_from(vec![
+ /// "prog", "--create"
+ /// ]);
+ /// assert_eq!(m.get_one::<bool>("create").copied(), Some(true));
+ /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));
+ /// ```
+ ///
+ /// [`Arg::action(ArgAction::Set)`]: Arg::action()
+ /// [`Arg::default_value`]: Arg::default_value()
+ #[inline]
+ #[must_use]
+ pub fn default_missing_value(mut self, val: impl IntoResettable<OsStr>) -> Self {
+ if let Some(val) = val.into_resettable().into_option() {
+ self.default_missing_values_os([val])
+ } else {
+ self.default_missing_vals.clear();
+ self
+ }
+ }
+
+ /// Value for the argument when the flag is present but no value is specified.
+ ///
+ /// See [`Arg::default_missing_value`].
+ ///
+ /// [`Arg::default_missing_value`]: Arg::default_missing_value()
+ /// [`OsStr`]: std::ffi::OsStr
+ #[inline]
+ #[must_use]
+ pub fn default_missing_value_os(self, val: impl Into<OsStr>) -> Self {
+ self.default_missing_values_os([val])
+ }
+
+ /// Value for the argument when the flag is present but no value is specified.
+ ///
+ /// See [`Arg::default_missing_value`].
+ ///
+ /// [`Arg::default_missing_value`]: Arg::default_missing_value()
+ #[inline]
+ #[must_use]
+ pub fn default_missing_values(self, vals: impl IntoIterator<Item = impl Into<OsStr>>) -> Self {
+ self.default_missing_values_os(vals)
+ }
+
+ /// Value for the argument when the flag is present but no value is specified.
+ ///
+ /// See [`Arg::default_missing_values`].
+ ///
+ /// [`Arg::default_missing_values`]: Arg::default_missing_values()
+ /// [`OsStr`]: std::ffi::OsStr
+ #[inline]
+ #[must_use]
+ pub fn default_missing_values_os(
+ mut self,
+ vals: impl IntoIterator<Item = impl Into<OsStr>>,
+ ) -> Self {
+ self.default_missing_vals = vals.into_iter().map(|s| s.into()).collect();
+ self
+ }
+
+ /// Read from `name` environment variable when argument is not present.
+ ///
+ /// If it is not present in the environment, then default
+ /// rules will apply.
+ ///
+ /// If user sets the argument in the environment:
+ /// - When [`Arg::action(ArgAction::Set)`] is not set, the flag is considered raised.
+ /// - When [`Arg::action(ArgAction::Set)`] is set,
+ /// [`ArgMatches::get_one`][crate::ArgMatches::get_one] will
+ /// return value of the environment variable.
+ ///
+ /// If user doesn't set the argument in the environment:
+ /// - When [`Arg::action(ArgAction::Set)`] is not set, the flag is considered off.
+ /// - When [`Arg::action(ArgAction::Set)`] is set,
+ /// [`ArgMatches::get_one`][crate::ArgMatches::get_one] will
+ /// return the default specified.
+ ///
+ /// # Examples
+ ///
+ /// In this example, we show the variable coming from the environment:
+ ///
+ /// ```rust
+ /// # use std::env;
+ /// # use clap::{Command, Arg, ArgAction};
+ ///
+ /// env::set_var("MY_FLAG", "env");
+ ///
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .env("MY_FLAG")
+ /// .action(ArgAction::Set))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("flag").unwrap(), "env");
+ /// ```
+ ///
+ /// In this example, because `prog` is a flag that accepts an optional, case-insensitive
+ /// boolean literal.
+ ///
+ /// Note that the value parser controls how flags are parsed. In this case we've selected
+ /// [`FalseyValueParser`][crate::builder::FalseyValueParser]. A `false` literal is `n`, `no`,
+ /// `f`, `false`, `off` or `0`. An absent environment variable will also be considered as
+ /// `false`. Anything else will considered as `true`.
+ ///
+ /// ```rust
+ /// # use std::env;
+ /// # use clap::{Command, Arg, ArgAction};
+ /// # use clap::builder::FalseyValueParser;
+ ///
+ /// env::set_var("TRUE_FLAG", "true");
+ /// env::set_var("FALSE_FLAG", "0");
+ ///
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("true_flag")
+ /// .long("true_flag")
+ /// .action(ArgAction::SetTrue)
+ /// .value_parser(FalseyValueParser::new())
+ /// .env("TRUE_FLAG"))
+ /// .arg(Arg::new("false_flag")
+ /// .long("false_flag")
+ /// .action(ArgAction::SetTrue)
+ /// .value_parser(FalseyValueParser::new())
+ /// .env("FALSE_FLAG"))
+ /// .arg(Arg::new("absent_flag")
+ /// .long("absent_flag")
+ /// .action(ArgAction::SetTrue)
+ /// .value_parser(FalseyValueParser::new())
+ /// .env("ABSENT_FLAG"))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert!(m.get_flag("true_flag"));
+ /// assert!(!m.get_flag("false_flag"));
+ /// assert!(!m.get_flag("absent_flag"));
+ /// ```
+ ///
+ /// In this example, we show the variable coming from an option on the CLI:
+ ///
+ /// ```rust
+ /// # use std::env;
+ /// # use clap::{Command, Arg, ArgAction};
+ ///
+ /// env::set_var("MY_FLAG", "env");
+ ///
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .env("MY_FLAG")
+ /// .action(ArgAction::Set))
+ /// .get_matches_from(vec![
+ /// "prog", "--flag", "opt"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("flag").unwrap(), "opt");
+ /// ```
+ ///
+ /// In this example, we show the variable coming from the environment even with the
+ /// presence of a default:
+ ///
+ /// ```rust
+ /// # use std::env;
+ /// # use clap::{Command, Arg, ArgAction};
+ ///
+ /// env::set_var("MY_FLAG", "env");
+ ///
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .env("MY_FLAG")
+ /// .action(ArgAction::Set)
+ /// .default_value("default"))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("flag").unwrap(), "env");
+ /// ```
+ ///
+ /// In this example, we show the use of multiple values in a single environment variable:
+ ///
+ /// ```rust
+ /// # use std::env;
+ /// # use clap::{Command, Arg, ArgAction};
+ ///
+ /// env::set_var("MY_FLAG_MULTI", "env1,env2");
+ ///
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .env("MY_FLAG_MULTI")
+ /// .action(ArgAction::Set)
+ /// .num_args(1..)
+ /// .value_delimiter(','))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_many::<String>("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]);
+ /// ```
+ /// [`Arg::action(ArgAction::Set)`]: Arg::action()
+ /// [`Arg::value_delimiter(',')`]: Arg::value_delimiter()
+ #[cfg(feature = "env")]
+ #[inline]
+ #[must_use]
+ pub fn env(mut self, name: impl IntoResettable<OsStr>) -> Self {
+ if let Some(name) = name.into_resettable().into_option() {
+ let value = env::var_os(&name);
+ self.env = Some((name, value));
+ } else {
+ self.env = None;
+ }
+ self
+ }
+
+ #[cfg(feature = "env")]
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Arg::env`")
+ )]
+ pub fn env_os(self, name: impl Into<OsStr>) -> Self {
+ self.env(name)
+ }
+}
+
+/// # Help
+impl Arg {
+ /// Sets the description of the argument for short help (`-h`).
+ ///
+ /// Typically, this is a short (one line) description of the arg.
+ ///
+ /// If [`Arg::long_help`] is not specified, this message will be displayed for `--help`.
+ ///
+ /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise
+ ///
+ /// # Examples
+ ///
+ /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
+ /// include a newline in the help text and have the following text be properly aligned with all
+ /// the other help text.
+ ///
+ /// Setting `help` displays a short message to the side of the argument when the user passes
+ /// `-h` or `--help` (by default).
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .help("Some help text describing the --config arg"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays
+ ///
+ /// ```notrust
+ /// helptest
+ ///
+ /// Usage: helptest [OPTIONS]
+ ///
+ /// Options:
+ /// --config Some help text describing the --config arg
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ /// [`Arg::long_help`]: Arg::long_help()
+ #[inline]
+ #[must_use]
+ pub fn help(mut self, h: impl IntoResettable<StyledStr>) -> Self {
+ self.help = h.into_resettable().into_option();
+ self
+ }
+
+ /// Sets the description of the argument for long help (`--help`).
+ ///
+ /// Typically this a more detailed (multi-line) message
+ /// that describes the arg.
+ ///
+ /// If [`Arg::help`] is not specified, this message will be displayed for `-h`.
+ ///
+ /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise
+ ///
+ /// # Examples
+ ///
+ /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
+ /// include a newline in the help text and have the following text be properly aligned with all
+ /// the other help text.
+ ///
+ /// Setting `help` displays a short message to the side of the argument when the user passes
+ /// `-h` or `--help` (by default).
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .long_help(
+ /// "The config file used by the myprog must be in JSON format
+ /// with only valid keys and may not contain other nonsense
+ /// that cannot be read by this program. Obviously I'm going on
+ /// and on, so I'll stop now."))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays
+ ///
+ /// ```text
+ /// prog
+ ///
+ /// Usage: prog [OPTIONS]
+ ///
+ /// Options:
+ /// --config
+ /// The config file used by the myprog must be in JSON format
+ /// with only valid keys and may not contain other nonsense
+ /// that cannot be read by this program. Obviously I'm going on
+ /// and on, so I'll stop now.
+ ///
+ /// -h, --help
+ /// Print help information
+ ///
+ /// -V, --version
+ /// Print version information
+ /// ```
+ /// [`Arg::help`]: Arg::help()
+ #[inline]
+ #[must_use]
+ pub fn long_help(mut self, h: impl IntoResettable<StyledStr>) -> Self {
+ self.long_help = h.into_resettable().into_option();
+ self
+ }
+
+ /// Allows custom ordering of args within the help message.
+ ///
+ /// Args with a lower value will be displayed first in the help message. This is helpful when
+ /// one would like to emphasise frequently used args, or prioritize those towards the top of
+ /// the list. Args with duplicate display orders will be displayed in the order they are
+ /// defined.
+ ///
+ /// **NOTE:** The default is 999 for all arguments.
+ ///
+ /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in
+ /// [index] order.
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("a") // Typically args are grouped alphabetically by name.
+ /// // Args without a display_order have a value of 999 and are
+ /// // displayed alphabetically with all other 999 valued args.
+ /// .long("long-option")
+ /// .short('o')
+ /// .action(ArgAction::Set)
+ /// .help("Some help and text"))
+ /// .arg(Arg::new("b")
+ /// .long("other-option")
+ /// .short('O')
+ /// .action(ArgAction::Set)
+ /// .display_order(1) // In order to force this arg to appear *first*
+ /// // all we have to do is give it a value lower than 999.
+ /// // Any other args with a value of 1 will be displayed
+ /// // alphabetically with this one...then 2 values, then 3, etc.
+ /// .help("I should be first!"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays the following help message
+ ///
+ /// ```text
+ /// cust-ord
+ ///
+ /// Usage: cust-ord [OPTIONS]
+ ///
+ /// Options:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// -O, --other-option <b> I should be first!
+ /// -o, --long-option <a> Some help and text
+ /// ```
+ /// [positional arguments]: Arg::index()
+ /// [index]: Arg::index()
+ #[inline]
+ #[must_use]
+ pub fn display_order(mut self, ord: impl IntoResettable<usize>) -> Self {
+ self.disp_ord = ord.into_resettable().into_option();
+ self
+ }
+
+ /// Override the [current] help section.
+ ///
+ /// [current]: crate::Command::next_help_heading
+ #[inline]
+ #[must_use]
+ pub fn help_heading(mut self, heading: impl IntoResettable<Str>) -> Self {
+ self.help_heading = Some(heading.into_resettable().into_option());
+ self
+ }
+
+ /// Render the [help][Arg::help] on the line after the argument.
+ ///
+ /// This can be helpful for arguments with very long or complex help messages.
+ /// This can also be helpful for arguments with very long flag names, or many/long value names.
+ ///
+ /// **NOTE:** To apply this setting to all arguments and subcommands, consider using
+ /// [`crate::Command::next_line_help`]
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("opt")
+ /// .long("long-option-flag")
+ /// .short('o')
+ /// .action(ArgAction::Set)
+ /// .next_line_help(true)
+ /// .value_names(["value1", "value2"])
+ /// .help("Some really long help and complex\n\
+ /// help that makes more sense to be\n\
+ /// on a line after the option"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays the following help message
+ ///
+ /// ```text
+ /// nlh
+ ///
+ /// Usage: nlh [OPTIONS]
+ ///
+ /// Options:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// -o, --long-option-flag <value1> <value2>
+ /// Some really long help and complex
+ /// help that makes more sense to be
+ /// on a line after the option
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn next_line_help(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::NextLineHelp)
+ } else {
+ self.unset_setting(ArgSettings::NextLineHelp)
+ }
+ }
+
+ /// Do not display the argument in help message.
+ ///
+ /// **NOTE:** This does **not** hide the argument from usage strings on error
+ ///
+ /// # Examples
+ ///
+ /// Setting `Hidden` will hide the argument when displaying help text
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .hide(true)
+ /// .help("Some help text describing the --config arg"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays
+ ///
+ /// ```text
+ /// helptest
+ ///
+ /// Usage: helptest [OPTIONS]
+ ///
+ /// Options:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn hide(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::Hidden)
+ } else {
+ self.unset_setting(ArgSettings::Hidden)
+ }
+ }
+
+ /// Do not display the [possible values][crate::builder::ValueParser::possible_values] in the help message.
+ ///
+ /// This is useful for args with many values, or ones which are explained elsewhere in the
+ /// help text.
+ ///
+ /// **NOTE:** Setting this requires [taking values][Arg::num_args]
+ ///
+ /// To set this for all arguments, see
+ /// [`Command::hide_possible_values`][crate::Command::hide_possible_values].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("mode")
+ /// .long("mode")
+ /// .value_parser(["fast", "slow"])
+ /// .action(ArgAction::Set)
+ /// .hide_possible_values(true));
+ /// ```
+ /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of
+ /// the help text would be omitted.
+ #[inline]
+ #[must_use]
+ pub fn hide_possible_values(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::HidePossibleValues)
+ } else {
+ self.unset_setting(ArgSettings::HidePossibleValues)
+ }
+ }
+
+ /// Do not display the default value of the argument in the help message.
+ ///
+ /// This is useful when default behavior of an arg is explained elsewhere in the help text.
+ ///
+ /// **NOTE:** Setting this requires [taking values][Arg::num_args]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("connect")
+ /// .arg(Arg::new("host")
+ /// .long("host")
+ /// .default_value("localhost")
+ /// .action(ArgAction::Set)
+ /// .hide_default_value(true));
+ ///
+ /// ```
+ ///
+ /// If we were to run the above program with `--help` the `[default: localhost]` portion of
+ /// the help text would be omitted.
+ #[inline]
+ #[must_use]
+ pub fn hide_default_value(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::HideDefaultValue)
+ } else {
+ self.unset_setting(ArgSettings::HideDefaultValue)
+ }
+ }
+
+ /// Do not display in help the environment variable name.
+ ///
+ /// This is useful when the variable option is explained elsewhere in the help text.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("mode")
+ /// .long("mode")
+ /// .env("MODE")
+ /// .action(ArgAction::Set)
+ /// .hide_env(true));
+ /// ```
+ ///
+ /// If we were to run the above program with `--help` the `[env: MODE]` portion of the help
+ /// text would be omitted.
+ #[cfg(feature = "env")]
+ #[inline]
+ #[must_use]
+ pub fn hide_env(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::HideEnv)
+ } else {
+ self.unset_setting(ArgSettings::HideEnv)
+ }
+ }
+
+ /// Do not display in help any values inside the associated ENV variables for the argument.
+ ///
+ /// This is useful when ENV vars contain sensitive values.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("connect")
+ /// .arg(Arg::new("host")
+ /// .long("host")
+ /// .env("CONNECT")
+ /// .action(ArgAction::Set)
+ /// .hide_env_values(true));
+ ///
+ /// ```
+ ///
+ /// If we were to run the above program with `$ CONNECT=super_secret connect --help` the
+ /// `[default: CONNECT=super_secret]` portion of the help text would be omitted.
+ #[cfg(feature = "env")]
+ #[inline]
+ #[must_use]
+ pub fn hide_env_values(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::HideEnvValues)
+ } else {
+ self.unset_setting(ArgSettings::HideEnvValues)
+ }
+ }
+
+ /// Hides an argument from short help (`-h`).
+ ///
+ /// **NOTE:** This does **not** hide the argument from usage strings on error
+ ///
+ /// **NOTE:** Setting this option will cause next-line-help output style to be used
+ /// when long help (`--help`) is called.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Arg::new("debug")
+ /// .hide_short_help(true);
+ /// ```
+ ///
+ /// Setting `hide_short_help(true)` will hide the argument when displaying short help text
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .hide_short_help(true)
+ /// .help("Some help text describing the --config arg"))
+ /// .get_matches_from(vec![
+ /// "prog", "-h"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays
+ ///
+ /// ```text
+ /// helptest
+ ///
+ /// Usage: helptest [OPTIONS]
+ ///
+ /// Options:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ ///
+ /// However, when --help is called
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .hide_short_help(true)
+ /// .help("Some help text describing the --config arg"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// Then the following would be displayed
+ ///
+ /// ```text
+ /// helptest
+ ///
+ /// Usage: helptest [OPTIONS]
+ ///
+ /// Options:
+ /// --config Some help text describing the --config arg
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn hide_short_help(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::HiddenShortHelp)
+ } else {
+ self.unset_setting(ArgSettings::HiddenShortHelp)
+ }
+ }
+
+ /// Hides an argument from long help (`--help`).
+ ///
+ /// **NOTE:** This does **not** hide the argument from usage strings on error
+ ///
+ /// **NOTE:** Setting this option will cause next-line-help output style to be used
+ /// when long help (`--help`) is called.
+ ///
+ /// # Examples
+ ///
+ /// Setting `hide_long_help(true)` will hide the argument when displaying long help text
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .hide_long_help(true)
+ /// .help("Some help text describing the --config arg"))
+ /// .get_matches_from(vec![
+ /// "prog", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays
+ ///
+ /// ```text
+ /// helptest
+ ///
+ /// Usage: helptest [OPTIONS]
+ ///
+ /// Options:
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ ///
+ /// However, when -h is called
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .long("config")
+ /// .hide_long_help(true)
+ /// .help("Some help text describing the --config arg"))
+ /// .get_matches_from(vec![
+ /// "prog", "-h"
+ /// ]);
+ /// ```
+ ///
+ /// Then the following would be displayed
+ ///
+ /// ```text
+ /// helptest
+ ///
+ /// Usage: helptest [OPTIONS]
+ ///
+ /// OPTIONS:
+ /// --config Some help text describing the --config arg
+ /// -h, --help Print help information
+ /// -V, --version Print version information
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn hide_long_help(self, yes: bool) -> Self {
+ if yes {
+ self.setting(ArgSettings::HiddenLongHelp)
+ } else {
+ self.unset_setting(ArgSettings::HiddenLongHelp)
+ }
+ }
+}
+
+/// # Advanced Argument Relations
+impl Arg {
+ /// The name of the [`ArgGroup`] the argument belongs to.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// Arg::new("debug")
+ /// .long("debug")
+ /// .action(ArgAction::SetTrue)
+ /// .group("mode")
+ /// # ;
+ /// ```
+ ///
+ /// Multiple arguments can be a member of a single group and then the group checked as if it
+ /// was one of said arguments.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("debug")
+ /// .long("debug")
+ /// .action(ArgAction::SetTrue)
+ /// .group("mode"))
+ /// .arg(Arg::new("verbose")
+ /// .long("verbose")
+ /// .action(ArgAction::SetTrue)
+ /// .group("mode"))
+ /// .get_matches_from(vec![
+ /// "prog", "--debug"
+ /// ]);
+ /// assert!(m.contains_id("mode"));
+ /// ```
+ ///
+ /// [`ArgGroup`]: crate::ArgGroup
+ #[must_use]
+ pub fn group(mut self, group_id: impl IntoResettable<Id>) -> Self {
+ if let Some(group_id) = group_id.into_resettable().into_option() {
+ self.groups.push(group_id);
+ } else {
+ self.groups.clear();
+ }
+ self
+ }
+
+ /// The names of [`ArgGroup`]'s the argument belongs to.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// Arg::new("debug")
+ /// .long("debug")
+ /// .action(ArgAction::SetTrue)
+ /// .groups(["mode", "verbosity"])
+ /// # ;
+ /// ```
+ ///
+ /// Arguments can be members of multiple groups and then the group checked as if it
+ /// was one of said arguments.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("debug")
+ /// .long("debug")
+ /// .action(ArgAction::SetTrue)
+ /// .groups(["mode", "verbosity"]))
+ /// .arg(Arg::new("verbose")
+ /// .long("verbose")
+ /// .action(ArgAction::SetTrue)
+ /// .groups(["mode", "verbosity"]))
+ /// .get_matches_from(vec![
+ /// "prog", "--debug"
+ /// ]);
+ /// assert!(m.contains_id("mode"));
+ /// assert!(m.contains_id("verbosity"));
+ /// ```
+ ///
+ /// [`ArgGroup`]: crate::ArgGroup
+ #[must_use]
+ pub fn groups(mut self, group_ids: impl IntoIterator<Item = impl Into<Id>>) -> Self {
+ self.groups.extend(group_ids.into_iter().map(Into::into));
+ self
+ }
+
+ /// Specifies the value of the argument if `arg` has been used at runtime.
+ ///
+ /// If `default` is set to `None`, `default_value` will be removed.
+ ///
+ /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly
+ /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg
+ /// at runtime. This setting however only takes effect when the user has not provided a value at
+ /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value`
+ /// and `Arg::default_value_if`, and the user **did not** provide this arg at runtime, nor were
+ /// the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be applied.
+ ///
+ /// **NOTE:** This implicitly sets [`Arg::action(ArgAction::Set)`].
+ ///
+ /// # Examples
+ ///
+ /// First we use the default value only if another arg is present at runtime.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// # use clap::builder::{ArgPredicate};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_if("flag", ArgPredicate::IsPresent, Some("default")))
+ /// .get_matches_from(vec![
+ /// "prog", "--flag"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("other").unwrap(), "default");
+ /// ```
+ ///
+ /// Next we run the same test, but without providing `--flag`.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_if("flag", "true", Some("default")))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("other"), None);
+ /// ```
+ ///
+ /// Now lets only use the default value if `--opt` contains the value `special`.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("opt")
+ /// .action(ArgAction::Set)
+ /// .long("opt"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_if("opt", "special", Some("default")))
+ /// .get_matches_from(vec![
+ /// "prog", "--opt", "special"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("other").unwrap(), "default");
+ /// ```
+ ///
+ /// We can run the same test and provide any value *other than* `special` and we won't get a
+ /// default value.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("opt")
+ /// .action(ArgAction::Set)
+ /// .long("opt"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_if("opt", "special", Some("default")))
+ /// .get_matches_from(vec![
+ /// "prog", "--opt", "hahaha"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("other"), None);
+ /// ```
+ ///
+ /// If we want to unset the default value for an Arg based on the presence or
+ /// value of some other Arg.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value("default")
+ /// .default_value_if("flag", "true", None))
+ /// .get_matches_from(vec![
+ /// "prog", "--flag"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("other"), None);
+ /// ```
+ /// [`Arg::action(ArgAction::Set)`]: Arg::action()
+ /// [`Arg::default_value`]: Arg::default_value()
+ #[must_use]
+ pub fn default_value_if(
+ mut self,
+ arg_id: impl Into<Id>,
+ predicate: impl Into<ArgPredicate>,
+ default: impl IntoResettable<OsStr>,
+ ) -> Self {
+ self.default_vals_ifs.push((
+ arg_id.into(),
+ predicate.into(),
+ default.into_resettable().into_option(),
+ ));
+ self
+ }
+
+ #[must_use]
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_if`")
+ )]
+ pub fn default_value_if_os(
+ self,
+ arg_id: impl Into<Id>,
+ predicate: impl Into<ArgPredicate>,
+ default: impl IntoResettable<OsStr>,
+ ) -> Self {
+ self.default_value_if(arg_id, predicate, default)
+ }
+
+ /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`].
+ ///
+ /// The method takes a slice of tuples in the `(arg, predicate, default)` format.
+ ///
+ /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first
+ /// if multiple conditions are true, the first one found will be applied and the ultimate value.
+ ///
+ /// # Examples
+ ///
+ /// First we use the default value only if another arg is present at runtime.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("opt")
+ /// .long("opt")
+ /// .action(ArgAction::Set))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_ifs([
+ /// ("flag", "true", Some("default")),
+ /// ("opt", "channal", Some("chan")),
+ /// ]))
+ /// .get_matches_from(vec![
+ /// "prog", "--opt", "channal"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("other").unwrap(), "chan");
+ /// ```
+ ///
+ /// Next we run the same test, but without providing `--flag`.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_ifs([
+ /// ("flag", "true", Some("default")),
+ /// ("opt", "channal", Some("chan")),
+ /// ]))
+ /// .get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("other"), None);
+ /// ```
+ ///
+ /// We can also see that these values are applied in order, and if more than one condition is
+ /// true, only the first evaluated "wins"
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// # use clap::builder::ArgPredicate;
+ /// let m = Command::new("prog")
+ /// .arg(Arg::new("flag")
+ /// .long("flag")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("opt")
+ /// .long("opt")
+ /// .action(ArgAction::Set))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .default_value_ifs([
+ /// ("flag", ArgPredicate::IsPresent, Some("default")),
+ /// ("opt", ArgPredicate::Equals("channal".into()), Some("chan")),
+ /// ]))
+ /// .get_matches_from(vec![
+ /// "prog", "--opt", "channal", "--flag"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("other").unwrap(), "default");
+ /// ```
+ /// [`Arg::action(ArgAction::Set)`]: Arg::action()
+ /// [`Arg::default_value_if`]: Arg::default_value_if()
+ #[must_use]
+ pub fn default_value_ifs(
+ mut self,
+ ifs: impl IntoIterator<
+ Item = (
+ impl Into<Id>,
+ impl Into<ArgPredicate>,
+ impl IntoResettable<OsStr>,
+ ),
+ >,
+ ) -> Self {
+ for (arg, predicate, default) in ifs {
+ self = self.default_value_if(arg, predicate, default);
+ }
+ self
+ }
+
+ #[must_use]
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_ifs`")
+ )]
+ pub fn default_value_ifs_os(
+ self,
+ ifs: impl IntoIterator<
+ Item = (
+ impl Into<Id>,
+ impl Into<ArgPredicate>,
+ impl IntoResettable<OsStr>,
+ ),
+ >,
+ ) -> Self {
+ self.default_value_ifs(ifs)
+ }
+
+ /// Set this arg as [required] as long as the specified argument is not present at runtime.
+ ///
+ /// **Pro Tip:** Using `Arg::required_unless_present` implies [`Arg::required`] and is therefore not
+ /// mandatory to also set.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required_unless_present("debug")
+ /// # ;
+ /// ```
+ ///
+ /// In the following example, the required argument is *not* provided,
+ /// but it's not an error because the `unless` arg has been supplied.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_unless_present("dbg")
+ /// .action(ArgAction::Set)
+ /// .long("config"))
+ /// .arg(Arg::new("dbg")
+ /// .long("debug")
+ /// .action(ArgAction::SetTrue))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--debug"
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// ```
+ ///
+ /// Setting `Arg::required_unless_present(name)` and *not* supplying `name` or this arg is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_unless_present("dbg")
+ /// .action(ArgAction::Set)
+ /// .long("config"))
+ /// .arg(Arg::new("dbg")
+ /// .long("debug"))
+ /// .try_get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [required]: Arg::required()
+ #[must_use]
+ pub fn required_unless_present(mut self, arg_id: impl IntoResettable<Id>) -> Self {
+ if let Some(arg_id) = arg_id.into_resettable().into_option() {
+ self.r_unless.push(arg_id);
+ } else {
+ self.r_unless.clear();
+ }
+ self
+ }
+
+ /// Sets this arg as [required] unless *all* of the specified arguments are present at runtime.
+ ///
+ /// In other words, parsing will succeed only if user either
+ /// * supplies the `self` arg.
+ /// * supplies *all* of the `names` arguments.
+ ///
+ /// **NOTE:** If you wish for this argument to only be required unless *any of* these args are
+ /// present see [`Arg::required_unless_present_any`]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required_unless_present_all(["cfg", "dbg"])
+ /// # ;
+ /// ```
+ ///
+ /// In the following example, the required argument is *not* provided, but it's not an error
+ /// because *all* of the `names` args have been supplied.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_unless_present_all(["dbg", "infile"])
+ /// .action(ArgAction::Set)
+ /// .long("config"))
+ /// .arg(Arg::new("dbg")
+ /// .long("debug")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("infile")
+ /// .short('i')
+ /// .action(ArgAction::Set))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--debug", "-i", "file"
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// ```
+ ///
+ /// Setting [`Arg::required_unless_present_all(names)`] and *not* supplying
+ /// either *all* of `unless` args or the `self` arg is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_unless_present_all(["dbg", "infile"])
+ /// .action(ArgAction::Set)
+ /// .long("config"))
+ /// .arg(Arg::new("dbg")
+ /// .long("debug")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("infile")
+ /// .short('i')
+ /// .action(ArgAction::Set))
+ /// .try_get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [required]: Arg::required()
+ /// [`Arg::required_unless_present_any`]: Arg::required_unless_present_any()
+ /// [`Arg::required_unless_present_all(names)`]: Arg::required_unless_present_all()
+ #[must_use]
+ pub fn required_unless_present_all(
+ mut self,
+ names: impl IntoIterator<Item = impl Into<Id>>,
+ ) -> Self {
+ self.r_unless_all.extend(names.into_iter().map(Into::into));
+ self
+ }
+
+ /// Sets this arg as [required] unless *any* of the specified arguments are present at runtime.
+ ///
+ /// In other words, parsing will succeed only if user either
+ /// * supplies the `self` arg.
+ /// * supplies *one or more* of the `unless` arguments.
+ ///
+ /// **NOTE:** If you wish for this argument to be required unless *all of* these args are
+ /// present see [`Arg::required_unless_present_all`]
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required_unless_present_any(["cfg", "dbg"])
+ /// # ;
+ /// ```
+ ///
+ /// Setting [`Arg::required_unless_present_any(names)`] requires that the argument be used at runtime
+ /// *unless* *at least one of* the args in `names` are present. In the following example, the
+ /// required argument is *not* provided, but it's not an error because one the `unless` args
+ /// have been supplied.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_unless_present_any(["dbg", "infile"])
+ /// .action(ArgAction::Set)
+ /// .long("config"))
+ /// .arg(Arg::new("dbg")
+ /// .long("debug")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("infile")
+ /// .short('i')
+ /// .action(ArgAction::Set))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--debug"
+ /// ]);
+ ///
+ /// assert!(res.is_ok());
+ /// ```
+ ///
+ /// Setting [`Arg::required_unless_present_any(names)`] and *not* supplying *at least one of* `names`
+ /// or this arg is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_unless_present_any(["dbg", "infile"])
+ /// .action(ArgAction::Set)
+ /// .long("config"))
+ /// .arg(Arg::new("dbg")
+ /// .long("debug")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("infile")
+ /// .short('i')
+ /// .action(ArgAction::Set))
+ /// .try_get_matches_from(vec![
+ /// "prog"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [required]: Arg::required()
+ /// [`Arg::required_unless_present_any(names)`]: Arg::required_unless_present_any()
+ /// [`Arg::required_unless_present_all`]: Arg::required_unless_present_all()
+ #[must_use]
+ pub fn required_unless_present_any(
+ mut self,
+ names: impl IntoIterator<Item = impl Into<Id>>,
+ ) -> Self {
+ self.r_unless.extend(names.into_iter().map(Into::into));
+ self
+ }
+
+ /// This argument is [required] only if the specified `arg` is present at runtime and its value
+ /// equals `val`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required_if_eq("other_arg", "value")
+ /// # ;
+ /// ```
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .required_if_eq("other", "special")
+ /// .long("config"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .action(ArgAction::Set))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--other", "not-special"
+ /// ]);
+ ///
+ /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required
+ ///
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .required_if_eq("other", "special")
+ /// .long("config"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .action(ArgAction::Set))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--other", "special"
+ /// ]);
+ ///
+ /// // We did use --other=special so "cfg" had become required but was missing.
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ ///
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .required_if_eq("other", "special")
+ /// .long("config"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .action(ArgAction::Set))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--other", "SPECIAL"
+ /// ]);
+ ///
+ /// // By default, the comparison is case-sensitive, so "cfg" wasn't required
+ /// assert!(res.is_ok());
+ ///
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .required_if_eq("other", "special")
+ /// .long("config"))
+ /// .arg(Arg::new("other")
+ /// .long("other")
+ /// .ignore_case(true)
+ /// .action(ArgAction::Set))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--other", "SPECIAL"
+ /// ]);
+ ///
+ /// // However, case-insensitive comparisons can be enabled. This typically occurs when using Arg::possible_values().
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [`Arg::requires(name)`]: Arg::requires()
+ /// [Conflicting]: Arg::conflicts_with()
+ /// [required]: Arg::required()
+ #[must_use]
+ pub fn required_if_eq(mut self, arg_id: impl Into<Id>, val: impl Into<OsStr>) -> Self {
+ self.r_ifs.push((arg_id.into(), val.into()));
+ self
+ }
+
+ /// Specify this argument is [required] based on multiple conditions.
+ ///
+ /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become
+ /// valid if one of the specified `arg`'s value equals its corresponding `val`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required_if_eq_any([
+ /// ("extra", "val"),
+ /// ("option", "spec")
+ /// ])
+ /// # ;
+ /// ```
+ ///
+ /// Setting `Arg::required_if_eq_any([(arg, val)])` makes this arg required if any of the `arg`s
+ /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is
+ /// anything other than `val`, this argument isn't required.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_if_eq_any([
+ /// ("extra", "val"),
+ /// ("option", "spec")
+ /// ])
+ /// .action(ArgAction::Set)
+ /// .long("config"))
+ /// .arg(Arg::new("extra")
+ /// .action(ArgAction::Set)
+ /// .long("extra"))
+ /// .arg(Arg::new("option")
+ /// .action(ArgAction::Set)
+ /// .long("option"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--option", "other"
+ /// ]);
+ ///
+ /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required
+ /// ```
+ ///
+ /// Setting `Arg::required_if_eq_any([(arg, val)])` and having any of the `arg`s used with its
+ /// value of `val` but *not* using this arg is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_if_eq_any([
+ /// ("extra", "val"),
+ /// ("option", "spec")
+ /// ])
+ /// .action(ArgAction::Set)
+ /// .long("config"))
+ /// .arg(Arg::new("extra")
+ /// .action(ArgAction::Set)
+ /// .long("extra"))
+ /// .arg(Arg::new("option")
+ /// .action(ArgAction::Set)
+ /// .long("option"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--option", "spec"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [`Arg::requires(name)`]: Arg::requires()
+ /// [Conflicting]: Arg::conflicts_with()
+ /// [required]: Arg::required()
+ #[must_use]
+ pub fn required_if_eq_any(
+ mut self,
+ ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>,
+ ) -> Self {
+ self.r_ifs
+ .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into())));
+ self
+ }
+
+ /// Specify this argument is [required] based on multiple conditions.
+ ///
+ /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become
+ /// valid if every one of the specified `arg`'s value equals its corresponding `val`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .required_if_eq_all([
+ /// ("extra", "val"),
+ /// ("option", "spec")
+ /// ])
+ /// # ;
+ /// ```
+ ///
+ /// Setting `Arg::required_if_eq_all([(arg, val)])` makes this arg required if all of the `arg`s
+ /// are used at runtime and every value is equal to its corresponding `val`. If the `arg`'s value is
+ /// anything other than `val`, this argument isn't required.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_if_eq_all([
+ /// ("extra", "val"),
+ /// ("option", "spec")
+ /// ])
+ /// .action(ArgAction::Set)
+ /// .long("config"))
+ /// .arg(Arg::new("extra")
+ /// .action(ArgAction::Set)
+ /// .long("extra"))
+ /// .arg(Arg::new("option")
+ /// .action(ArgAction::Set)
+ /// .long("option"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--option", "spec"
+ /// ]);
+ ///
+ /// assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required
+ /// ```
+ ///
+ /// Setting `Arg::required_if_eq_all([(arg, val)])` and having all of the `arg`s used with its
+ /// value of `val` but *not* using this arg is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .required_if_eq_all([
+ /// ("extra", "val"),
+ /// ("option", "spec")
+ /// ])
+ /// .action(ArgAction::Set)
+ /// .long("config"))
+ /// .arg(Arg::new("extra")
+ /// .action(ArgAction::Set)
+ /// .long("extra"))
+ /// .arg(Arg::new("option")
+ /// .action(ArgAction::Set)
+ /// .long("option"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--extra", "val", "--option", "spec"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [required]: Arg::required()
+ #[must_use]
+ pub fn required_if_eq_all(
+ mut self,
+ ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>,
+ ) -> Self {
+ self.r_ifs_all
+ .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into())));
+ self
+ }
+
+ /// Require another argument if this arg matches the [`ArgPredicate`]
+ ///
+ /// This method takes `value, another_arg` pair. At runtime, clap will check
+ /// if this arg (`self`) matches the [`ArgPredicate`].
+ /// If it does, `another_arg` will be marked as required.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .requires_if("val", "arg")
+ /// # ;
+ /// ```
+ ///
+ /// Setting `Arg::requires_if(val, arg)` requires that the `arg` be used at runtime if the
+ /// defining argument's value is equal to `val`. If the defining argument is anything other than
+ /// `val`, the other argument isn't required.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .requires_if("my.cfg", "other")
+ /// .long("config"))
+ /// .arg(Arg::new("other"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "some.cfg"
+ /// ]);
+ ///
+ /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required
+ /// ```
+ ///
+ /// Setting `Arg::requires_if(val, arg)` and setting the value to `val` but *not* supplying
+ /// `arg` is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .requires_if("my.cfg", "input")
+ /// .long("config"))
+ /// .arg(Arg::new("input"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "my.cfg"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [`Arg::requires(name)`]: Arg::requires()
+ /// [Conflicting]: Arg::conflicts_with()
+ /// [override]: Arg::overrides_with()
+ #[must_use]
+ pub fn requires_if(mut self, val: impl Into<ArgPredicate>, arg_id: impl Into<Id>) -> Self {
+ self.requires.push((val.into(), arg_id.into()));
+ self
+ }
+
+ /// Allows multiple conditional requirements.
+ ///
+ /// The requirement will only become valid if this arg's value matches the
+ /// [`ArgPredicate`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .requires_ifs([
+ /// ("val", "arg"),
+ /// ("other_val", "arg2"),
+ /// ])
+ /// # ;
+ /// ```
+ ///
+ /// Setting `Arg::requires_ifs(["val", "arg"])` requires that the `arg` be used at runtime if the
+ /// defining argument's value is equal to `val`. If the defining argument's value is anything other
+ /// than `val`, `arg` isn't required.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .requires_ifs([
+ /// ("special.conf", "opt"),
+ /// ("other.conf", "other"),
+ /// ])
+ /// .long("config"))
+ /// .arg(Arg::new("opt")
+ /// .long("option")
+ /// .action(ArgAction::Set))
+ /// .arg(Arg::new("other"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "special.conf"
+ /// ]);
+ ///
+ /// assert!(res.is_err()); // We used --config=special.conf so --option <val> is required
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ ///
+ /// Setting `Arg::requires_ifs` with [`ArgPredicate::IsPresent`] and *not* supplying all the
+ /// arguments is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction, builder::ArgPredicate};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .requires_ifs([
+ /// (ArgPredicate::IsPresent, "input"),
+ /// (ArgPredicate::IsPresent, "output"),
+ /// ])
+ /// .long("config"))
+ /// .arg(Arg::new("input"))
+ /// .arg(Arg::new("output"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "file.conf", "in.txt"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// // We didn't use output
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ ///
+ /// [`Arg::requires(name)`]: Arg::requires()
+ /// [Conflicting]: Arg::conflicts_with()
+ /// [override]: Arg::overrides_with()
+ #[must_use]
+ pub fn requires_ifs(
+ mut self,
+ ifs: impl IntoIterator<Item = (impl Into<ArgPredicate>, impl Into<Id>)>,
+ ) -> Self {
+ self.requires
+ .extend(ifs.into_iter().map(|(val, arg)| (val.into(), arg.into())));
+ self
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Arg::requires_ifs`")
+ )]
+ pub fn requires_all(self, ids: impl IntoIterator<Item = impl Into<Id>>) -> Self {
+ self.requires_ifs(ids.into_iter().map(|id| (ArgPredicate::IsPresent, id)))
+ }
+
+ /// This argument is mutually exclusive with the specified argument.
+ ///
+ /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
+ /// only need to be set for one of the two arguments, they do not need to be set for each.
+ ///
+ /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
+ /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not
+ /// need to also do B.conflicts_with(A))
+ ///
+ /// **NOTE:** [`Arg::conflicts_with_all(names)`] allows specifying an argument which conflicts with more than one argument.
+ ///
+ /// **NOTE** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument.
+ ///
+ /// **NOTE:** All arguments implicitly conflict with themselves.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .conflicts_with("debug")
+ /// # ;
+ /// ```
+ ///
+ /// Setting conflicting argument, and having both arguments present at runtime is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .conflicts_with("debug")
+ /// .long("config"))
+ /// .arg(Arg::new("debug")
+ /// .long("debug")
+ /// .action(ArgAction::SetTrue))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--debug", "--config", "file.conf"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
+ /// ```
+ ///
+ /// [`Arg::conflicts_with_all(names)`]: Arg::conflicts_with_all()
+ /// [`Arg::exclusive(true)`]: Arg::exclusive()
+ #[must_use]
+ pub fn conflicts_with(mut self, arg_id: impl IntoResettable<Id>) -> Self {
+ if let Some(arg_id) = arg_id.into_resettable().into_option() {
+ self.blacklist.push(arg_id);
+ } else {
+ self.blacklist.clear();
+ }
+ self
+ }
+
+ /// This argument is mutually exclusive with the specified arguments.
+ ///
+ /// See [`Arg::conflicts_with`].
+ ///
+ /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
+ /// only need to be set for one of the two arguments, they do not need to be set for each.
+ ///
+ /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
+ /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need
+ /// need to also do B.conflicts_with(A))
+ ///
+ /// **NOTE:** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// Arg::new("config")
+ /// .conflicts_with_all(["debug", "input"])
+ /// # ;
+ /// ```
+ ///
+ /// Setting conflicting argument, and having any of the arguments present at runtime with a
+ /// conflicting argument is an error.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("cfg")
+ /// .action(ArgAction::Set)
+ /// .conflicts_with_all(["debug", "input"])
+ /// .long("config"))
+ /// .arg(Arg::new("debug")
+ /// .long("debug"))
+ /// .arg(Arg::new("input"))
+ /// .try_get_matches_from(vec![
+ /// "prog", "--config", "file.conf", "file.txt"
+ /// ]);
+ ///
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
+ /// ```
+ /// [`Arg::conflicts_with`]: Arg::conflicts_with()
+ /// [`Arg::exclusive(true)`]: Arg::exclusive()
+ #[must_use]
+ pub fn conflicts_with_all(mut self, names: impl IntoIterator<Item = impl Into<Id>>) -> Self {
+ self.blacklist.extend(names.into_iter().map(Into::into));
+ self
+ }
+
+ /// Sets an overridable argument.
+ ///
+ /// i.e. this argument and the following argument
+ /// will override each other in POSIX style (whichever argument was specified at runtime
+ /// **last** "wins")
+ ///
+ /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
+ /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
+ ///
+ /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, arg};
+ /// let m = Command::new("prog")
+ /// .arg(arg!(-f --flag "some flag")
+ /// .conflicts_with("debug"))
+ /// .arg(arg!(-d --debug "other flag"))
+ /// .arg(arg!(-c --color "third flag")
+ /// .overrides_with("flag"))
+ /// .get_matches_from(vec![
+ /// "prog", "-f", "-d", "-c"]);
+ /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color
+ ///
+ /// assert!(m.get_flag("color"));
+ /// assert!(m.get_flag("debug")); // even though flag conflicts with debug, it's as if flag
+ /// // was never used because it was overridden with color
+ /// assert!(!m.get_flag("flag"));
+ /// ```
+ #[must_use]
+ pub fn overrides_with(mut self, arg_id: impl IntoResettable<Id>) -> Self {
+ if let Some(arg_id) = arg_id.into_resettable().into_option() {
+ self.overrides.push(arg_id);
+ } else {
+ self.overrides.clear();
+ }
+ self
+ }
+
+ /// Sets multiple mutually overridable arguments by name.
+ ///
+ /// i.e. this argument and the following argument will override each other in POSIX style
+ /// (whichever argument was specified at runtime **last** "wins")
+ ///
+ /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
+ /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
+ ///
+ /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with_all`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, arg};
+ /// let m = Command::new("prog")
+ /// .arg(arg!(-f --flag "some flag")
+ /// .conflicts_with("color"))
+ /// .arg(arg!(-d --debug "other flag"))
+ /// .arg(arg!(-c --color "third flag")
+ /// .overrides_with_all(["flag", "debug"]))
+ /// .get_matches_from(vec![
+ /// "prog", "-f", "-d", "-c"]);
+ /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color
+ ///
+ /// assert!(m.get_flag("color")); // even though flag conflicts with color, it's as if flag
+ /// // and debug were never used because they were overridden
+ /// // with color
+ /// assert!(!m.get_flag("debug"));
+ /// assert!(!m.get_flag("flag"));
+ /// ```
+ #[must_use]
+ pub fn overrides_with_all(mut self, names: impl IntoIterator<Item = impl Into<Id>>) -> Self {
+ self.overrides.extend(names.into_iter().map(Into::into));
+ self
+ }
+}
+
+/// # Reflection
+impl Arg {
+ /// Get the name of the argument
+ #[inline]
+ pub fn get_id(&self) -> &Id {
+ &self.id
+ }
+
+ /// Get the help specified for this argument, if any
+ #[inline]
+ pub fn get_help(&self) -> Option<&StyledStr> {
+ self.help.as_ref()
+ }
+
+ /// Get the long help specified for this argument, if any
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// let arg = Arg::new("foo").long_help("long help");
+ /// assert_eq!(Some("long help".to_owned()), arg.get_long_help().map(|s| s.to_string()));
+ /// ```
+ ///
+ #[inline]
+ pub fn get_long_help(&self) -> Option<&StyledStr> {
+ self.long_help.as_ref()
+ }
+
+ /// Get the help heading specified for this argument, if any
+ #[inline]
+ pub fn get_help_heading(&self) -> Option<&str> {
+ self.help_heading
+ .as_ref()
+ .map(|s| s.as_deref())
+ .unwrap_or_default()
+ }
+
+ /// Get the short option name for this argument, if any
+ #[inline]
+ pub fn get_short(&self) -> Option<char> {
+ self.short
+ }
+
+ /// Get visible short aliases for this argument, if any
+ #[inline]
+ pub fn get_visible_short_aliases(&self) -> Option<Vec<char>> {
+ if self.short_aliases.is_empty() {
+ None
+ } else {
+ Some(
+ self.short_aliases
+ .iter()
+ .filter_map(|(c, v)| if *v { Some(c) } else { None })
+ .copied()
+ .collect(),
+ )
+ }
+ }
+
+ /// 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>> {
+ let mut shorts = match self.short {
+ Some(short) => vec![short],
+ None => return None,
+ };
+ if let Some(aliases) = self.get_visible_short_aliases() {
+ shorts.extend(aliases);
+ }
+ Some(shorts)
+ }
+
+ /// Get the long option name for this argument, if any
+ #[inline]
+ pub fn get_long(&self) -> Option<&str> {
+ self.long.as_deref()
+ }
+
+ /// Get visible aliases for this argument, if any
+ #[inline]
+ pub fn get_visible_aliases(&self) -> Option<Vec<&str>> {
+ if self.aliases.is_empty() {
+ None
+ } else {
+ Some(
+ self.aliases
+ .iter()
+ .filter_map(|(s, v)| if *v { Some(s.as_str()) } else { None })
+ .collect(),
+ )
+ }
+ }
+
+ /// Get *all* aliases for this argument, if any, both visible and hidden.
+ #[inline]
+ pub fn get_all_aliases(&self) -> Option<Vec<&str>> {
+ if self.aliases.is_empty() {
+ None
+ } else {
+ Some(self.aliases.iter().map(|(s, _)| s.as_str()).collect())
+ }
+ }
+
+ /// Get the long option name and its visible aliases, if any
+ #[inline]
+ pub fn get_long_and_visible_aliases(&self) -> Option<Vec<&str>> {
+ let mut longs = match self.get_long() {
+ Some(long) => vec![long],
+ None => return None,
+ };
+ if let Some(aliases) = self.get_visible_aliases() {
+ longs.extend(aliases);
+ }
+ Some(longs)
+ }
+
+ /// Get the names of possible values for this argument. Only useful for user
+ /// facing applications, such as building help messages or man files
+ pub fn get_possible_values(&self) -> Vec<PossibleValue> {
+ if !self.is_takes_value_set() {
+ vec![]
+ } else {
+ self.get_value_parser()
+ .possible_values()
+ .map(|pvs| pvs.collect())
+ .unwrap_or_default()
+ }
+ }
+
+ /// Get the names of values for this argument.
+ #[inline]
+ pub fn get_value_names(&self) -> Option<&[Str]> {
+ if self.val_names.is_empty() {
+ None
+ } else {
+ Some(&self.val_names)
+ }
+ }
+
+ /// Get the number of values for this argument.
+ #[inline]
+ pub fn get_num_args(&self) -> Option<ValueRange> {
+ self.num_vals
+ }
+
+ #[inline]
+ pub(crate) fn get_min_vals(&self) -> usize {
+ self.get_num_args().expect(INTERNAL_ERROR_MSG).min_values()
+ }
+
+ /// Get the delimiter between multiple values
+ #[inline]
+ pub fn get_value_delimiter(&self) -> Option<char> {
+ self.val_delim
+ }
+
+ /// Get the value terminator for this argument. The value_terminator is a value
+ /// that terminates parsing of multi-valued arguments.
+ #[inline]
+ pub fn get_value_terminator(&self) -> Option<&Str> {
+ self.terminator.as_ref()
+ }
+
+ /// Get the index of this argument, if any
+ #[inline]
+ pub fn get_index(&self) -> Option<usize> {
+ self.index
+ }
+
+ /// Get the value hint of this argument
+ pub fn get_value_hint(&self) -> ValueHint {
+ self.value_hint.unwrap_or_else(|| {
+ if self.is_takes_value_set() {
+ let type_id = self.get_value_parser().type_id();
+ if type_id == crate::parser::AnyValueId::of::<std::path::PathBuf>() {
+ ValueHint::AnyPath
+ } else {
+ ValueHint::default()
+ }
+ } else {
+ ValueHint::default()
+ }
+ })
+ }
+
+ /// Get the environment variable name specified for this argument, if any
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use std::ffi::OsStr;
+ /// # use clap::Arg;
+ /// let arg = Arg::new("foo").env("ENVIRONMENT");
+ /// assert_eq!(arg.get_env(), Some(OsStr::new("ENVIRONMENT")));
+ /// ```
+ #[cfg(feature = "env")]
+ pub fn get_env(&self) -> Option<&std::ffi::OsStr> {
+ self.env.as_ref().map(|x| x.0.as_os_str())
+ }
+
+ /// Get the default values specified for this argument, if any
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Arg;
+ /// let arg = Arg::new("foo").default_value("default value");
+ /// assert_eq!(arg.get_default_values(), &["default value"]);
+ /// ```
+ pub fn get_default_values(&self) -> &[OsStr] {
+ &self.default_vals
+ }
+
+ /// Checks whether this argument is a positional or not.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use clap::Arg;
+ /// let arg = Arg::new("foo");
+ /// assert_eq!(arg.is_positional(), true);
+ ///
+ /// let arg = Arg::new("foo").long("foo");
+ /// assert_eq!(arg.is_positional(), false);
+ /// ```
+ pub fn is_positional(&self) -> bool {
+ self.get_long().is_none() && self.get_short().is_none()
+ }
+
+ /// Reports whether [`Arg::required`] is set
+ pub fn is_required_set(&self) -> bool {
+ self.is_set(ArgSettings::Required)
+ }
+
+ pub(crate) fn is_multiple_values_set(&self) -> bool {
+ self.get_num_args().unwrap_or_default().is_multiple()
+ }
+
+ pub(crate) fn is_takes_value_set(&self) -> bool {
+ self.get_action().takes_values()
+ }
+
+ /// Report whether [`Arg::allow_hyphen_values`] is set
+ pub fn is_allow_hyphen_values_set(&self) -> bool {
+ self.is_set(ArgSettings::AllowHyphenValues)
+ }
+
+ /// Report whether [`Arg::allow_negative_numbers`] is set
+ pub fn is_allow_negative_numbers_set(&self) -> bool {
+ self.is_set(ArgSettings::AllowNegativeNumbers)
+ }
+
+ /// Behavior when parsing the argument
+ pub fn get_action(&self) -> &super::ArgAction {
+ const DEFAULT: super::ArgAction = super::ArgAction::Set;
+ self.action.as_ref().unwrap_or(&DEFAULT)
+ }
+
+ /// Configured parser for argument values
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// let cmd = clap::Command::new("raw")
+ /// .arg(
+ /// clap::Arg::new("port")
+ /// .value_parser(clap::value_parser!(usize))
+ /// );
+ /// let value_parser = cmd.get_arguments()
+ /// .find(|a| a.get_id() == "port").unwrap()
+ /// .get_value_parser();
+ /// println!("{:?}", value_parser);
+ /// ```
+ pub fn get_value_parser(&self) -> &super::ValueParser {
+ if let Some(value_parser) = self.value_parser.as_ref() {
+ value_parser
+ } else {
+ static DEFAULT: super::ValueParser = super::ValueParser::string();
+ &DEFAULT
+ }
+ }
+
+ /// Report whether [`Arg::global`] is set
+ pub fn is_global_set(&self) -> bool {
+ self.is_set(ArgSettings::Global)
+ }
+
+ /// Report whether [`Arg::next_line_help`] is set
+ pub fn is_next_line_help_set(&self) -> bool {
+ self.is_set(ArgSettings::NextLineHelp)
+ }
+
+ /// Report whether [`Arg::hide`] is set
+ pub fn is_hide_set(&self) -> bool {
+ self.is_set(ArgSettings::Hidden)
+ }
+
+ /// Report whether [`Arg::hide_default_value`] is set
+ pub fn is_hide_default_value_set(&self) -> bool {
+ self.is_set(ArgSettings::HideDefaultValue)
+ }
+
+ /// Report whether [`Arg::hide_possible_values`] is set
+ pub fn is_hide_possible_values_set(&self) -> bool {
+ self.is_set(ArgSettings::HidePossibleValues)
+ }
+
+ /// Report whether [`Arg::hide_env`] is set
+ #[cfg(feature = "env")]
+ pub fn is_hide_env_set(&self) -> bool {
+ self.is_set(ArgSettings::HideEnv)
+ }
+
+ /// Report whether [`Arg::hide_env_values`] is set
+ #[cfg(feature = "env")]
+ pub fn is_hide_env_values_set(&self) -> bool {
+ self.is_set(ArgSettings::HideEnvValues)
+ }
+
+ /// Report whether [`Arg::hide_short_help`] is set
+ pub fn is_hide_short_help_set(&self) -> bool {
+ self.is_set(ArgSettings::HiddenShortHelp)
+ }
+
+ /// Report whether [`Arg::hide_long_help`] is set
+ pub fn is_hide_long_help_set(&self) -> bool {
+ self.is_set(ArgSettings::HiddenLongHelp)
+ }
+
+ /// Report whether [`Arg::require_equals`] is set
+ pub fn is_require_equals_set(&self) -> bool {
+ self.is_set(ArgSettings::RequireEquals)
+ }
+
+ /// Reports whether [`Arg::exclusive`] is set
+ pub fn is_exclusive_set(&self) -> bool {
+ self.is_set(ArgSettings::Exclusive)
+ }
+
+ /// Report whether [`Arg::trailing_var_arg`] is set
+ pub fn is_trailing_var_arg_set(&self) -> bool {
+ self.is_set(ArgSettings::TrailingVarArg)
+ }
+
+ /// Reports whether [`Arg::last`] is set
+ pub fn is_last_set(&self) -> bool {
+ self.is_set(ArgSettings::Last)
+ }
+
+ /// Reports whether [`Arg::ignore_case`] is set
+ pub fn is_ignore_case_set(&self) -> bool {
+ self.is_set(ArgSettings::IgnoreCase)
+ }
+}
+
+/// # Internally used only
+impl Arg {
+ pub(crate) fn _build(&mut self) {
+ if self.action.is_none() {
+ if self.num_vals == Some(ValueRange::EMPTY) {
+ let action = super::ArgAction::SetTrue;
+ self.action = Some(action);
+ } else {
+ let action =
+ if self.is_positional() && self.num_vals.unwrap_or_default().is_unbounded() {
+ // Allow collecting arguments interleaved with flags
+ //
+ // Bounded values are probably a group and the user should explicitly opt-in to
+ // Append
+ super::ArgAction::Append
+ } else {
+ super::ArgAction::Set
+ };
+ self.action = Some(action);
+ }
+ }
+ if let Some(action) = self.action.as_ref() {
+ if let Some(default_value) = action.default_value() {
+ if self.default_vals.is_empty() {
+ self.default_vals = vec![default_value.into()];
+ }
+ }
+ if let Some(default_value) = action.default_missing_value() {
+ if self.default_missing_vals.is_empty() {
+ self.default_missing_vals = vec![default_value.into()];
+ }
+ }
+ }
+
+ if self.value_parser.is_none() {
+ if let Some(default) = self.action.as_ref().and_then(|a| a.default_value_parser()) {
+ self.value_parser = Some(default);
+ } else {
+ self.value_parser = Some(super::ValueParser::string());
+ }
+ }
+
+ let val_names_len = self.val_names.len();
+ if val_names_len > 1 {
+ self.num_vals.get_or_insert(val_names_len.into());
+ } else {
+ let nargs = if self.get_action().takes_values() {
+ ValueRange::SINGLE
+ } else {
+ ValueRange::EMPTY
+ };
+ self.num_vals.get_or_insert(nargs);
+ }
+ }
+
+ // Used for positionals when printing
+ pub(crate) fn name_no_brackets(&self) -> String {
+ debug!("Arg::name_no_brackets:{}", self.get_id());
+ let delim = " ";
+ if !self.val_names.is_empty() {
+ debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names);
+
+ if self.val_names.len() > 1 {
+ self.val_names
+ .iter()
+ .map(|n| format!("<{n}>"))
+ .collect::<Vec<_>>()
+ .join(delim)
+ } else {
+ self.val_names
+ .first()
+ .expect(INTERNAL_ERROR_MSG)
+ .as_str()
+ .to_owned()
+ }
+ } else {
+ debug!("Arg::name_no_brackets: just name");
+ self.get_id().as_str().to_owned()
+ }
+ }
+
+ pub(crate) fn stylized(&self, required: Option<bool>) -> StyledStr {
+ let mut styled = StyledStr::new();
+ // Write the name such --long or -l
+ if let Some(l) = self.get_long() {
+ styled.literal("--");
+ styled.literal(l);
+ } else if let Some(s) = self.get_short() {
+ styled.literal("-");
+ styled.literal(s);
+ }
+ styled.extend(self.stylize_arg_suffix(required).into_iter());
+ styled
+ }
+
+ pub(crate) fn stylize_arg_suffix(&self, required: Option<bool>) -> StyledStr {
+ let mut styled = StyledStr::new();
+
+ let mut need_closing_bracket = false;
+ if self.is_takes_value_set() && !self.is_positional() {
+ let is_optional_val = self.get_min_vals() == 0;
+ if self.is_require_equals_set() {
+ if is_optional_val {
+ need_closing_bracket = true;
+ styled.placeholder("[=");
+ } else {
+ styled.literal("=");
+ }
+ } else if is_optional_val {
+ need_closing_bracket = true;
+ styled.placeholder(" [");
+ } else {
+ styled.placeholder(" ");
+ }
+ }
+ if self.is_takes_value_set() || self.is_positional() {
+ let required = required.unwrap_or_else(|| self.is_required_set());
+ let arg_val = self.render_arg_val(required);
+ styled.placeholder(arg_val);
+ } else if matches!(*self.get_action(), ArgAction::Count) {
+ styled.placeholder("...");
+ }
+ if need_closing_bracket {
+ styled.placeholder("]");
+ }
+
+ styled
+ }
+
+ /// Write the values such as `<name1> <name2>`
+ fn render_arg_val(&self, required: bool) -> String {
+ let mut rendered = String::new();
+
+ let num_vals = self.get_num_args().unwrap_or_else(|| 1.into());
+
+ let mut val_names = if self.val_names.is_empty() {
+ vec![self.id.as_internal_str().to_owned()]
+ } else {
+ self.val_names.clone()
+ };
+ if val_names.len() == 1 {
+ let min = num_vals.min_values().max(1);
+ let val_name = val_names.pop().unwrap();
+ val_names = vec![val_name; min];
+ }
+
+ debug_assert!(self.is_takes_value_set());
+ for (n, val_name) in val_names.iter().enumerate() {
+ let arg_name = if self.is_positional() && (num_vals.min_values() == 0 || !required) {
+ format!("[{val_name}]")
+ } else {
+ format!("<{val_name}>")
+ };
+
+ if n != 0 {
+ rendered.push(' ');
+ }
+ rendered.push_str(&arg_name);
+ }
+
+ let mut extra_values = false;
+ extra_values |= val_names.len() < num_vals.max_values();
+ if self.is_positional() && matches!(*self.get_action(), ArgAction::Append) {
+ extra_values = true;
+ }
+ if extra_values {
+ rendered.push_str("...");
+ }
+
+ rendered
+ }
+
+ /// Either multiple values or occurrences
+ pub(crate) fn is_multiple(&self) -> bool {
+ self.is_multiple_values_set() || matches!(*self.get_action(), ArgAction::Append)
+ }
+
+ #[cfg(feature = "help")]
+ pub(crate) fn get_display_order(&self) -> usize {
+ self.disp_ord.unwrap_or(999)
+ }
+}
+
+impl From<&'_ Arg> for Arg {
+ fn from(a: &Arg) -> Self {
+ a.clone()
+ }
+}
+
+impl PartialEq for Arg {
+ fn eq(&self, other: &Arg) -> bool {
+ self.get_id() == other.get_id()
+ }
+}
+
+impl PartialOrd for Arg {
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+impl Ord for Arg {
+ fn cmp(&self, other: &Arg) -> Ordering {
+ self.get_id().cmp(other.get_id())
+ }
+}
+
+impl Eq for Arg {}
+
+impl Display for Arg {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ self.stylized(None).fmt(f)
+ }
+}
+
+impl fmt::Debug for Arg {
+ fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
+ let mut ds = f.debug_struct("Arg");
+
+ #[allow(unused_mut)]
+ let mut ds = ds
+ .field("id", &self.id)
+ .field("help", &self.help)
+ .field("long_help", &self.long_help)
+ .field("action", &self.action)
+ .field("value_parser", &self.value_parser)
+ .field("blacklist", &self.blacklist)
+ .field("settings", &self.settings)
+ .field("overrides", &self.overrides)
+ .field("groups", &self.groups)
+ .field("requires", &self.requires)
+ .field("r_ifs", &self.r_ifs)
+ .field("r_unless", &self.r_unless)
+ .field("short", &self.short)
+ .field("long", &self.long)
+ .field("aliases", &self.aliases)
+ .field("short_aliases", &self.short_aliases)
+ .field("disp_ord", &self.disp_ord)
+ .field("val_names", &self.val_names)
+ .field("num_vals", &self.num_vals)
+ .field("val_delim", &self.val_delim)
+ .field("default_vals", &self.default_vals)
+ .field("default_vals_ifs", &self.default_vals_ifs)
+ .field("terminator", &self.terminator)
+ .field("index", &self.index)
+ .field("help_heading", &self.help_heading)
+ .field("value_hint", &self.value_hint)
+ .field("default_missing_vals", &self.default_missing_vals);
+
+ #[cfg(feature = "env")]
+ {
+ ds = ds.field("env", &self.env);
+ }
+
+ ds.finish()
+ }
+}
+
+// Flags
+#[cfg(test)]
+mod test {
+ use super::Arg;
+ use super::ArgAction;
+
+ #[test]
+ fn flag_display_long() {
+ let mut f = Arg::new("flg").long("flag").action(ArgAction::SetTrue);
+ f._build();
+
+ assert_eq!(f.to_string(), "--flag");
+ }
+
+ #[test]
+ fn flag_display_short() {
+ let mut f2 = Arg::new("flg").short('f').action(ArgAction::SetTrue);
+ f2._build();
+
+ assert_eq!(f2.to_string(), "-f");
+ }
+
+ #[test]
+ fn flag_display_count() {
+ let mut f2 = Arg::new("flg").long("flag").action(ArgAction::Count);
+ f2._build();
+
+ assert_eq!(f2.to_string(), "--flag...");
+ }
+
+ #[test]
+ fn flag_display_single_alias() {
+ let mut f = Arg::new("flg")
+ .long("flag")
+ .visible_alias("als")
+ .action(ArgAction::SetTrue);
+ f._build();
+
+ assert_eq!(f.to_string(), "--flag")
+ }
+
+ #[test]
+ fn flag_display_multiple_aliases() {
+ let mut f = Arg::new("flg").short('f').action(ArgAction::SetTrue);
+ f.aliases = vec![
+ ("alias_not_visible".into(), false),
+ ("f2".into(), true),
+ ("f3".into(), true),
+ ("f4".into(), true),
+ ];
+ f._build();
+
+ assert_eq!(f.to_string(), "-f");
+ }
+
+ #[test]
+ fn flag_display_single_short_alias() {
+ let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue);
+ f.short_aliases = vec![('b', true)];
+ f._build();
+
+ assert_eq!(f.to_string(), "-a")
+ }
+
+ #[test]
+ fn flag_display_multiple_short_aliases() {
+ let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue);
+ f.short_aliases = vec![('b', false), ('c', true), ('d', true), ('e', true)];
+ f._build();
+
+ assert_eq!(f.to_string(), "-a");
+ }
+
+ // Options
+
+ #[test]
+ fn option_display_multiple_occurrences() {
+ let mut o = Arg::new("opt").long("option").action(ArgAction::Append);
+ o._build();
+
+ assert_eq!(o.to_string(), "--option <opt>");
+ }
+
+ #[test]
+ fn option_display_multiple_values() {
+ let mut o = Arg::new("opt")
+ .long("option")
+ .action(ArgAction::Set)
+ .num_args(1..);
+ o._build();
+
+ assert_eq!(o.to_string(), "--option <opt>...");
+ }
+
+ #[test]
+ fn option_display_zero_or_more_values() {
+ let mut o = Arg::new("opt")
+ .long("option")
+ .action(ArgAction::Set)
+ .num_args(0..);
+ o._build();
+
+ assert_eq!(o.to_string(), "--option [<opt>...]");
+ }
+
+ #[test]
+ fn option_display_one_or_more_values() {
+ let mut o = Arg::new("opt")
+ .long("option")
+ .action(ArgAction::Set)
+ .num_args(1..);
+ o._build();
+
+ assert_eq!(o.to_string(), "--option <opt>...");
+ }
+
+ #[test]
+ fn option_display_zero_or_more_values_with_value_name() {
+ let mut o = Arg::new("opt")
+ .short('o')
+ .action(ArgAction::Set)
+ .num_args(0..)
+ .value_names(["file"]);
+ o._build();
+
+ assert_eq!(o.to_string(), "-o [<file>...]");
+ }
+
+ #[test]
+ fn option_display_one_or_more_values_with_value_name() {
+ let mut o = Arg::new("opt")
+ .short('o')
+ .action(ArgAction::Set)
+ .num_args(1..)
+ .value_names(["file"]);
+ o._build();
+
+ assert_eq!(o.to_string(), "-o <file>...");
+ }
+
+ #[test]
+ fn option_display_optional_value() {
+ let mut o = Arg::new("opt")
+ .long("option")
+ .action(ArgAction::Set)
+ .num_args(0..=1);
+ o._build();
+
+ assert_eq!(o.to_string(), "--option [<opt>]");
+ }
+
+ #[test]
+ fn option_display_value_names() {
+ let mut o = Arg::new("opt")
+ .short('o')
+ .action(ArgAction::Set)
+ .value_names(["file", "name"]);
+ o._build();
+
+ assert_eq!(o.to_string(), "-o <file> <name>");
+ }
+
+ #[test]
+ fn option_display3() {
+ let mut o = Arg::new("opt")
+ .short('o')
+ .num_args(1..)
+ .action(ArgAction::Set)
+ .value_names(["file", "name"]);
+ o._build();
+
+ assert_eq!(o.to_string(), "-o <file> <name>...");
+ }
+
+ #[test]
+ fn option_display_single_alias() {
+ let mut o = Arg::new("opt")
+ .long("option")
+ .action(ArgAction::Set)
+ .visible_alias("als");
+ o._build();
+
+ assert_eq!(o.to_string(), "--option <opt>");
+ }
+
+ #[test]
+ fn option_display_multiple_aliases() {
+ let mut o = Arg::new("opt")
+ .long("option")
+ .action(ArgAction::Set)
+ .visible_aliases(["als2", "als3", "als4"])
+ .alias("als_not_visible");
+ o._build();
+
+ assert_eq!(o.to_string(), "--option <opt>");
+ }
+
+ #[test]
+ fn option_display_single_short_alias() {
+ let mut o = Arg::new("opt")
+ .short('a')
+ .action(ArgAction::Set)
+ .visible_short_alias('b');
+ o._build();
+
+ assert_eq!(o.to_string(), "-a <opt>");
+ }
+
+ #[test]
+ fn option_display_multiple_short_aliases() {
+ let mut o = Arg::new("opt")
+ .short('a')
+ .action(ArgAction::Set)
+ .visible_short_aliases(['b', 'c', 'd'])
+ .short_alias('e');
+ o._build();
+
+ assert_eq!(o.to_string(), "-a <opt>");
+ }
+
+ // Positionals
+
+ #[test]
+ fn positional_display_multiple_values() {
+ let mut p = Arg::new("pos").index(1).num_args(1..);
+ p._build();
+
+ assert_eq!(p.to_string(), "[pos]...");
+ }
+
+ #[test]
+ fn positional_display_multiple_values_required() {
+ let mut p = Arg::new("pos").index(1).num_args(1..).required(true);
+ p._build();
+
+ assert_eq!(p.to_string(), "<pos>...");
+ }
+
+ #[test]
+ fn positional_display_zero_or_more_values() {
+ let mut p = Arg::new("pos").index(1).num_args(0..);
+ p._build();
+
+ assert_eq!(p.to_string(), "[pos]...");
+ }
+
+ #[test]
+ fn positional_display_one_or_more_values() {
+ let mut p = Arg::new("pos").index(1).num_args(1..);
+ p._build();
+
+ assert_eq!(p.to_string(), "[pos]...");
+ }
+
+ #[test]
+ fn positional_display_one_or_more_values_required() {
+ let mut p = Arg::new("pos").index(1).num_args(1..).required(true);
+ p._build();
+
+ assert_eq!(p.to_string(), "<pos>...");
+ }
+
+ #[test]
+ fn positional_display_optional_value() {
+ let mut p = Arg::new("pos")
+ .index(1)
+ .num_args(0..=1)
+ .action(ArgAction::Set);
+ p._build();
+
+ assert_eq!(p.to_string(), "[pos]");
+ }
+
+ #[test]
+ fn positional_display_multiple_occurrences() {
+ let mut p = Arg::new("pos").index(1).action(ArgAction::Append);
+ p._build();
+
+ assert_eq!(p.to_string(), "[pos]...");
+ }
+
+ #[test]
+ fn positional_display_multiple_occurrences_required() {
+ let mut p = Arg::new("pos")
+ .index(1)
+ .action(ArgAction::Append)
+ .required(true);
+ p._build();
+
+ assert_eq!(p.to_string(), "<pos>...");
+ }
+
+ #[test]
+ fn positional_display_required() {
+ let mut p = Arg::new("pos").index(1).required(true);
+ p._build();
+
+ assert_eq!(p.to_string(), "<pos>");
+ }
+
+ #[test]
+ fn positional_display_val_names() {
+ let mut p = Arg::new("pos").index(1).value_names(["file1", "file2"]);
+ p._build();
+
+ assert_eq!(p.to_string(), "[file1] [file2]");
+ }
+
+ #[test]
+ fn positional_display_val_names_required() {
+ let mut p = Arg::new("pos")
+ .index(1)
+ .value_names(["file1", "file2"])
+ .required(true);
+ p._build();
+
+ assert_eq!(p.to_string(), "<file1> <file2>");
+ }
+
+ #[test]
+ fn positional_display_val_names_req() {
+ let mut p = Arg::new("pos")
+ .index(1)
+ .required(true)
+ .value_names(["file1", "file2"]);
+ p._build();
+
+ assert_eq!(p.to_string(), "<file1> <file2>");
+ }
+}
diff --git a/src/builder/arg_group.rs b/src/builder/arg_group.rs
new file mode 100644
index 0000000..a6386a1
--- /dev/null
+++ b/src/builder/arg_group.rs
@@ -0,0 +1,596 @@
+// Internal
+use crate::builder::IntoResettable;
+use crate::util::Id;
+
+/// Family of related [arguments].
+///
+/// By placing arguments in a logical group, you can create easier requirement and
+/// exclusion rules instead of having to list each argument individually, or when you want a rule
+/// to apply "any but not all" arguments.
+///
+/// For instance, you can make an entire `ArgGroup` required. If [`ArgGroup::multiple(true)`] is
+/// set, this means that at least one argument from that group must be present. If
+/// [`ArgGroup::multiple(false)`] is set (the default), one and *only* one must be present.
+///
+/// You can also do things such as name an entire `ArgGroup` as a [conflict] or [requirement] for
+/// another argument, meaning any of the arguments that belong to that group will cause a failure
+/// if present, or must be present respectively.
+///
+/// Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be
+/// present out of a given set. Imagine that you had multiple arguments, and you want one of them
+/// to be required, but making all of them required isn't feasible because perhaps they conflict
+/// with each other. For example, lets say that you were building an application where one could
+/// set a given version number by supplying a string with an option argument, i.e.
+/// `--set-ver v1.2.3`, you also wanted to support automatically using a previous version number
+/// and simply incrementing one of the three numbers. So you create three flags `--major`,
+/// `--minor`, and `--patch`. All of these arguments shouldn't be used at one time but you want to
+/// specify that *at least one* of them is used. For this, you can create a group.
+///
+/// Finally, you may use `ArgGroup`s to pull a value from a group of arguments when you don't care
+/// exactly which argument was actually used at runtime.
+///
+/// # Examples
+///
+/// The following example demonstrates using an `ArgGroup` to ensure that one, and only one, of
+/// the arguments from the specified group is present at runtime.
+///
+/// ```rust
+/// # use clap::{Command, arg, ArgGroup, error::ErrorKind};
+/// let result = Command::new("cmd")
+/// .arg(arg!(--"set-ver" <ver> "set the version manually"))
+/// .arg(arg!(--major "auto increase major"))
+/// .arg(arg!(--minor "auto increase minor"))
+/// .arg(arg!(--patch "auto increase patch"))
+/// .group(ArgGroup::new("vers")
+/// .args(["set-ver", "major", "minor", "patch"])
+/// .required(true))
+/// .try_get_matches_from(vec!["cmd", "--major", "--patch"]);
+/// // Because we used two args in the group it's an error
+/// assert!(result.is_err());
+/// let err = result.unwrap_err();
+/// assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
+/// ```
+///
+/// This next example shows a passing parse of the same scenario
+/// ```rust
+/// # use clap::{Command, arg, ArgGroup, Id};
+/// let result = Command::new("cmd")
+/// .arg(arg!(--"set-ver" <ver> "set the version manually"))
+/// .arg(arg!(--major "auto increase major"))
+/// .arg(arg!(--minor "auto increase minor"))
+/// .arg(arg!(--patch "auto increase patch"))
+/// .group(ArgGroup::new("vers")
+/// .args(["set-ver", "major", "minor","patch"])
+/// .required(true))
+/// .try_get_matches_from(vec!["cmd", "--major"]);
+/// assert!(result.is_ok());
+/// let matches = result.unwrap();
+/// // We may not know which of the args was used, so we can test for the group...
+/// assert!(matches.contains_id("vers"));
+/// // We can also ask the group which arg was used
+/// assert_eq!(matches
+/// .get_one::<Id>("vers")
+/// .expect("`vers` is required")
+/// .as_str(),
+/// "major"
+/// );
+/// // we could also alternatively check each arg individually (not shown here)
+/// ```
+/// [`ArgGroup::multiple(true)`]: ArgGroup::multiple()
+///
+/// [`ArgGroup::multiple(false)`]: ArgGroup::multiple()
+/// [arguments]: crate::Arg
+/// [conflict]: crate::Arg::conflicts_with()
+/// [requirement]: crate::Arg::requires()
+#[derive(Default, Clone, Debug, PartialEq, Eq)]
+pub struct ArgGroup {
+ pub(crate) id: Id,
+ pub(crate) args: Vec<Id>,
+ pub(crate) required: bool,
+ pub(crate) requires: Vec<Id>,
+ pub(crate) conflicts: Vec<Id>,
+ pub(crate) multiple: bool,
+}
+
+/// # Builder
+impl ArgGroup {
+ /// Create a `ArgGroup` using a unique name.
+ ///
+ /// The name will be used to get values from the group or refer to the group inside of conflict
+ /// and requirement rules.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, ArgGroup};
+ /// ArgGroup::new("config")
+ /// # ;
+ /// ```
+ pub fn new(id: impl Into<Id>) -> Self {
+ ArgGroup::default().id(id)
+ }
+
+ /// Sets the group name.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, ArgGroup};
+ /// ArgGroup::default().id("config")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn id(mut self, id: impl Into<Id>) -> Self {
+ self.id = id.into();
+ self
+ }
+
+ /// Adds an [argument] to this group by name
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, ArgAction};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("color")
+ /// .short('c')
+ /// .action(ArgAction::SetTrue))
+ /// .group(ArgGroup::new("req_flags")
+ /// .arg("flag")
+ /// .arg("color"))
+ /// .get_matches_from(vec!["myprog", "-f"]);
+ /// // maybe we don't know which of the two flags was used...
+ /// assert!(m.contains_id("req_flags"));
+ /// // but we can also check individually if needed
+ /// assert!(m.contains_id("flag"));
+ /// ```
+ /// [argument]: crate::Arg
+ #[must_use]
+ pub fn arg(mut self, arg_id: impl IntoResettable<Id>) -> Self {
+ if let Some(arg_id) = arg_id.into_resettable().into_option() {
+ self.args.push(arg_id);
+ } else {
+ self.args.clear();
+ }
+ self
+ }
+
+ /// Adds multiple [arguments] to this group by name
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, ArgAction};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("color")
+ /// .short('c')
+ /// .action(ArgAction::SetTrue))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(["flag", "color"]))
+ /// .get_matches_from(vec!["myprog", "-f"]);
+ /// // maybe we don't know which of the two flags was used...
+ /// assert!(m.contains_id("req_flags"));
+ /// // but we can also check individually if needed
+ /// assert!(m.contains_id("flag"));
+ /// ```
+ /// [arguments]: crate::Arg
+ #[must_use]
+ pub fn args(mut self, ns: impl IntoIterator<Item = impl Into<Id>>) -> Self {
+ for n in ns {
+ self = self.arg(n);
+ }
+ self
+ }
+
+ /// Getters for all args. It will return a vector of `Id`
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// # use clap::{ArgGroup};
+ /// let args: Vec<&str> = vec!["a1".into(), "a4".into()];
+ /// let grp = ArgGroup::new("program").args(&args);
+ ///
+ /// for (pos, arg) in grp.get_args().enumerate() {
+ /// assert_eq!(*arg, args[pos]);
+ /// }
+ /// ```
+ pub fn get_args(&self) -> impl Iterator<Item = &Id> {
+ self.args.iter()
+ }
+
+ /// Allows more than one of the [`Arg`]s in this group to be used. (Default: `false`)
+ ///
+ /// # Examples
+ ///
+ /// Notice in this example we use *both* the `-f` and `-c` flags which are both part of the
+ /// group
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, ArgAction};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("color")
+ /// .short('c')
+ /// .action(ArgAction::SetTrue))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(["flag", "color"])
+ /// .multiple(true))
+ /// .get_matches_from(vec!["myprog", "-f", "-c"]);
+ /// // maybe we don't know which of the two flags was used...
+ /// assert!(m.contains_id("req_flags"));
+ /// ```
+ /// In this next example, we show the default behavior (i.e. `multiple(false)) which will throw
+ /// an error if more than one of the args in the group was used.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction};
+ /// let result = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("color")
+ /// .short('c')
+ /// .action(ArgAction::SetTrue))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(["flag", "color"]))
+ /// .try_get_matches_from(vec!["myprog", "-f", "-c"]);
+ /// // Because we used both args in the group it's an error
+ /// assert!(result.is_err());
+ /// let err = result.unwrap_err();
+ /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
+ /// ```
+ ///
+ /// [`Arg`]: crate::Arg
+ #[inline]
+ #[must_use]
+ pub fn multiple(mut self, yes: bool) -> Self {
+ self.multiple = yes;
+ self
+ }
+
+ /// Return true if the group allows more than one of the arguments
+ /// in this group to be used. (Default: `false`)
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// # use clap::{ArgGroup};
+ /// let mut group = ArgGroup::new("myprog")
+ /// .args(["f", "c"])
+ /// .multiple(true);
+ ///
+ /// assert!(group.is_multiple());
+ /// ```
+ pub fn is_multiple(&mut self) -> bool {
+ self.multiple
+ }
+
+ /// Require an argument from the group to be present when parsing.
+ ///
+ /// This is unless conflicting with another argument. A required group will be displayed in
+ /// the usage string of the application in the format `<arg|arg2|arg3>`.
+ ///
+ /// **NOTE:** This setting only applies to the current [`Command`] / [`Subcommand`]s, and not
+ /// globally.
+ ///
+ /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with
+ /// `ArgGroup::required(true)` states, "One and *only one* arg must be used from this group.
+ /// Use of more than one arg is an error." Vice setting `ArgGroup::multiple(true)` which
+ /// states, '*At least* one arg from this group must be used. Using multiple is OK."
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction};
+ /// let result = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("color")
+ /// .short('c')
+ /// .action(ArgAction::SetTrue))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(["flag", "color"])
+ /// .required(true))
+ /// .try_get_matches_from(vec!["myprog"]);
+ /// // Because we didn't use any of the args in the group, it's an error
+ /// assert!(result.is_err());
+ /// let err = result.unwrap_err();
+ /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ ///
+ /// [`Subcommand`]: crate::Subcommand
+ /// [`ArgGroup::multiple`]: ArgGroup::multiple()
+ /// [`Command`]: crate::Command
+ #[inline]
+ #[must_use]
+ pub fn required(mut self, yes: bool) -> Self {
+ self.required = yes;
+ self
+ }
+
+ /// Specify an argument or group that must be present when this group is.
+ ///
+ /// This is not to be confused with a [required group]. Requirement rules function just like
+ /// [argument requirement rules], you can name other arguments or groups that must be present
+ /// when any one of the arguments from this group is used.
+ ///
+ /// **NOTE:** The name provided may be an argument or group name
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction};
+ /// let result = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("color")
+ /// .short('c')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("debug")
+ /// .short('d')
+ /// .action(ArgAction::SetTrue))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(["flag", "color"])
+ /// .requires("debug"))
+ /// .try_get_matches_from(vec!["myprog", "-c"]);
+ /// // because we used an arg from the group, and the group requires "-d" to be used, it's an
+ /// // error
+ /// assert!(result.is_err());
+ /// let err = result.unwrap_err();
+ /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [required group]: ArgGroup::required()
+ /// [argument requirement rules]: crate::Arg::requires()
+ #[must_use]
+ pub fn requires(mut self, id: impl IntoResettable<Id>) -> Self {
+ if let Some(id) = id.into_resettable().into_option() {
+ self.requires.push(id);
+ } else {
+ self.requires.clear();
+ }
+ self
+ }
+
+ /// Specify arguments or groups that must be present when this group is.
+ ///
+ /// This is not to be confused with a [required group]. Requirement rules function just like
+ /// [argument requirement rules], you can name other arguments or groups that must be present
+ /// when one of the arguments from this group is used.
+ ///
+ /// **NOTE:** The names provided may be an argument or group name
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction};
+ /// let result = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("color")
+ /// .short('c')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("debug")
+ /// .short('d')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("verb")
+ /// .short('v')
+ /// .action(ArgAction::SetTrue))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(["flag", "color"])
+ /// .requires_all(["debug", "verb"]))
+ /// .try_get_matches_from(vec!["myprog", "-c", "-d"]);
+ /// // because we used an arg from the group, and the group requires "-d" and "-v" to be used,
+ /// // yet we only used "-d" it's an error
+ /// assert!(result.is_err());
+ /// let err = result.unwrap_err();
+ /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
+ /// ```
+ /// [required group]: ArgGroup::required()
+ /// [argument requirement rules]: crate::Arg::requires_ifs()
+ #[must_use]
+ pub fn requires_all(mut self, ns: impl IntoIterator<Item = impl Into<Id>>) -> Self {
+ for n in ns {
+ self = self.requires(n);
+ }
+ self
+ }
+
+ /// Specify an argument or group that must **not** be present when this group is.
+ ///
+ /// Exclusion (aka conflict) rules function just like [argument exclusion rules], you can name
+ /// other arguments or groups that must *not* be present when one of the arguments from this
+ /// group are used.
+ ///
+ /// **NOTE:** The name provided may be an argument, or group name
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction};
+ /// let result = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("color")
+ /// .short('c')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("debug")
+ /// .short('d')
+ /// .action(ArgAction::SetTrue))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(["flag", "color"])
+ /// .conflicts_with("debug"))
+ /// .try_get_matches_from(vec!["myprog", "-c", "-d"]);
+ /// // because we used an arg from the group, and the group conflicts with "-d", it's an error
+ /// assert!(result.is_err());
+ /// let err = result.unwrap_err();
+ /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
+ /// ```
+ /// [argument exclusion rules]: crate::Arg::conflicts_with()
+ #[must_use]
+ pub fn conflicts_with(mut self, id: impl IntoResettable<Id>) -> Self {
+ if let Some(id) = id.into_resettable().into_option() {
+ self.conflicts.push(id);
+ } else {
+ self.conflicts.clear();
+ }
+ self
+ }
+
+ /// Specify arguments or groups that must **not** be present when this group is.
+ ///
+ /// Exclusion rules function just like [argument exclusion rules], you can name other arguments
+ /// or groups that must *not* be present when one of the arguments from this group are used.
+ ///
+ /// **NOTE:** The names provided may be an argument, or group name
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction};
+ /// let result = Command::new("myprog")
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("color")
+ /// .short('c')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("debug")
+ /// .short('d')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("verb")
+ /// .short('v')
+ /// .action(ArgAction::SetTrue))
+ /// .group(ArgGroup::new("req_flags")
+ /// .args(["flag", "color"])
+ /// .conflicts_with_all(["debug", "verb"]))
+ /// .try_get_matches_from(vec!["myprog", "-c", "-v"]);
+ /// // because we used an arg from the group, and the group conflicts with either "-v" or "-d"
+ /// // it's an error
+ /// assert!(result.is_err());
+ /// let err = result.unwrap_err();
+ /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
+ /// ```
+ ///
+ /// [argument exclusion rules]: crate::Arg::conflicts_with_all()
+ #[must_use]
+ pub fn conflicts_with_all(mut self, ns: impl IntoIterator<Item = impl Into<Id>>) -> Self {
+ for n in ns {
+ self = self.conflicts_with(n);
+ }
+ self
+ }
+}
+
+/// # Reflection
+impl ArgGroup {
+ /// Get the name of the group
+ #[inline]
+ pub fn get_id(&self) -> &Id {
+ &self.id
+ }
+
+ /// Reports whether [`ArgGroup::required`] is set
+ #[inline]
+ pub fn is_required_set(&self) -> bool {
+ self.required
+ }
+}
+
+impl From<&'_ ArgGroup> for ArgGroup {
+ fn from(g: &ArgGroup) -> Self {
+ g.clone()
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn groups() {
+ let g = ArgGroup::new("test")
+ .arg("a1")
+ .arg("a4")
+ .args(["a2", "a3"])
+ .required(true)
+ .conflicts_with("c1")
+ .conflicts_with_all(["c2", "c3"])
+ .conflicts_with("c4")
+ .requires("r1")
+ .requires_all(["r2", "r3"])
+ .requires("r4");
+
+ let args: Vec<Id> = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()];
+ let reqs: Vec<Id> = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()];
+ let confs: Vec<Id> = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()];
+
+ assert_eq!(g.args, args);
+ assert_eq!(g.requires, reqs);
+ assert_eq!(g.conflicts, confs);
+ }
+
+ #[test]
+ fn test_from() {
+ let g = ArgGroup::new("test")
+ .arg("a1")
+ .arg("a4")
+ .args(["a2", "a3"])
+ .required(true)
+ .conflicts_with("c1")
+ .conflicts_with_all(["c2", "c3"])
+ .conflicts_with("c4")
+ .requires("r1")
+ .requires_all(["r2", "r3"])
+ .requires("r4");
+
+ let args: Vec<Id> = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()];
+ let reqs: Vec<Id> = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()];
+ let confs: Vec<Id> = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()];
+
+ let g2 = ArgGroup::from(&g);
+ assert_eq!(g2.args, args);
+ assert_eq!(g2.requires, reqs);
+ assert_eq!(g2.conflicts, confs);
+ }
+
+ // This test will *fail to compile* if ArgGroup is not Send + Sync
+ #[test]
+ fn arg_group_send_sync() {
+ fn foo<T: Send + Sync>(_: T) {}
+ foo(ArgGroup::new("test"))
+ }
+
+ #[test]
+ fn arg_group_expose_is_multiple_helper() {
+ let args: Vec<Id> = vec!["a1".into(), "a4".into()];
+
+ let mut grp_multiple = ArgGroup::new("test_multiple").args(&args).multiple(true);
+ assert!(grp_multiple.is_multiple());
+
+ let mut grp_not_multiple = ArgGroup::new("test_multiple").args(&args).multiple(false);
+ assert!(!grp_not_multiple.is_multiple());
+ }
+
+ #[test]
+ fn arg_group_expose_get_args_helper() {
+ let args: Vec<Id> = vec!["a1".into(), "a4".into()];
+ let grp = ArgGroup::new("program").args(&args);
+
+ for (pos, arg) in grp.get_args().enumerate() {
+ assert_eq!(*arg, args[pos]);
+ }
+ }
+}
diff --git a/src/builder/arg_predicate.rs b/src/builder/arg_predicate.rs
new file mode 100644
index 0000000..bc79a11
--- /dev/null
+++ b/src/builder/arg_predicate.rs
@@ -0,0 +1,19 @@
+use crate::builder::OsStr;
+
+/// Operations to perform on argument values
+///
+/// These do not apply to [`ValueSource::DefaultValue`][crate::parser::ValueSource::DefaultValue]
+#[derive(Clone, Debug, PartialEq, Eq)]
+#[cfg_attr(feature = "unstable-v5", non_exhaustive)]
+pub enum ArgPredicate {
+ /// Is the argument present?
+ IsPresent,
+ /// Does the argument match the specified value?
+ Equals(OsStr),
+}
+
+impl<S: Into<OsStr>> From<S> for ArgPredicate {
+ fn from(other: S) -> Self {
+ Self::Equals(other.into())
+ }
+}
diff --git a/src/builder/arg_settings.rs b/src/builder/arg_settings.rs
new file mode 100644
index 0000000..b8bc069
--- /dev/null
+++ b/src/builder/arg_settings.rs
@@ -0,0 +1,145 @@
+// Std
+use std::ops::BitOr;
+
+// Third party
+use bitflags::bitflags;
+
+#[allow(unused)]
+use crate::Arg;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct ArgFlags(Flags);
+
+impl Default for ArgFlags {
+ fn default() -> Self {
+ Self::empty()
+ }
+}
+
+/// Various settings that apply to arguments and may be set, unset, and checked via getter/setter
+/// methods [`Arg::setting`], [`Arg::unset_setting`], and [`Arg::is_set`]. This is what the
+/// [`Arg`] methods which accept a `bool` use internally.
+///
+/// [`Arg`]: crate::Arg
+/// [`Arg::setting`]: crate::Arg::setting()
+/// [`Arg::unset_setting`]: crate::Arg::unset_setting()
+/// [`Arg::is_set`]: crate::Arg::is_set()
+#[derive(Debug, PartialEq, Copy, Clone)]
+#[non_exhaustive]
+pub(crate) enum ArgSettings {
+ Required,
+ Global,
+ Hidden,
+ NextLineHelp,
+ HidePossibleValues,
+ AllowHyphenValues,
+ AllowNegativeNumbers,
+ RequireEquals,
+ Last,
+ TrailingVarArg,
+ HideDefaultValue,
+ IgnoreCase,
+ #[cfg(feature = "env")]
+ HideEnv,
+ #[cfg(feature = "env")]
+ HideEnvValues,
+ HiddenShortHelp,
+ HiddenLongHelp,
+ Exclusive,
+}
+
+bitflags! {
+ struct Flags: u32 {
+ const REQUIRED = 1;
+ const GLOBAL = 1 << 3;
+ const HIDDEN = 1 << 4;
+ const TRAILING_VARARG = 1 << 5;
+ const ALLOW_NEG_NUMS = 1 << 6;
+ const NEXT_LINE_HELP = 1 << 7;
+ const DELIM_NOT_SET = 1 << 10;
+ const HIDE_POS_VALS = 1 << 11;
+ const ALLOW_TAC_VALS = 1 << 12;
+ const REQUIRE_EQUALS = 1 << 13;
+ const LAST = 1 << 14;
+ const HIDE_DEFAULT_VAL = 1 << 15;
+ const CASE_INSENSITIVE = 1 << 16;
+ #[cfg(feature = "env")]
+ const HIDE_ENV_VALS = 1 << 17;
+ const HIDDEN_SHORT_H = 1 << 18;
+ const HIDDEN_LONG_H = 1 << 19;
+ #[cfg(feature = "env")]
+ const HIDE_ENV = 1 << 21;
+ const EXCLUSIVE = 1 << 23;
+ const NO_OP = 0;
+ }
+}
+
+impl_settings! { ArgSettings, ArgFlags,
+ Required => Flags::REQUIRED,
+ Global => Flags::GLOBAL,
+ Hidden => Flags::HIDDEN,
+ NextLineHelp => Flags::NEXT_LINE_HELP,
+ HidePossibleValues => Flags::HIDE_POS_VALS,
+ AllowHyphenValues => Flags::ALLOW_TAC_VALS,
+ AllowNegativeNumbers => Flags::ALLOW_NEG_NUMS,
+ RequireEquals => Flags::REQUIRE_EQUALS,
+ Last => Flags::LAST,
+ TrailingVarArg => Flags::TRAILING_VARARG,
+ IgnoreCase => Flags::CASE_INSENSITIVE,
+ #[cfg(feature = "env")]
+ HideEnv => Flags::HIDE_ENV,
+ #[cfg(feature = "env")]
+ HideEnvValues => Flags::HIDE_ENV_VALS,
+ HideDefaultValue => Flags::HIDE_DEFAULT_VAL,
+ HiddenShortHelp => Flags::HIDDEN_SHORT_H,
+ HiddenLongHelp => Flags::HIDDEN_LONG_H,
+ Exclusive => Flags::EXCLUSIVE
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+ use crate::Arg;
+
+ #[test]
+ fn setting() {
+ let m = Arg::new("setting").setting(ArgSettings::Required);
+ assert!(m.is_required_set());
+ }
+
+ #[test]
+ fn unset_setting() {
+ let m = Arg::new("unset_setting").setting(ArgSettings::Required);
+ assert!(m.is_required_set());
+
+ let m = m.unset_setting(ArgSettings::Required);
+ assert!(!m.is_required_set(), "{m:#?}");
+ }
+
+ #[test]
+ fn setting_bitor() {
+ let m = Arg::new("setting_bitor")
+ .setting(ArgSettings::Required | ArgSettings::Hidden | ArgSettings::Last);
+
+ assert!(m.is_required_set());
+ assert!(m.is_hide_set());
+ assert!(m.is_last_set());
+ }
+
+ #[test]
+ fn unset_setting_bitor() {
+ let m = Arg::new("unset_setting_bitor")
+ .setting(ArgSettings::Required)
+ .setting(ArgSettings::Hidden)
+ .setting(ArgSettings::Last);
+
+ assert!(m.is_required_set());
+ assert!(m.is_hide_set());
+ assert!(m.is_last_set());
+
+ let m = m.unset_setting(ArgSettings::Required | ArgSettings::Hidden | ArgSettings::Last);
+ assert!(!m.is_required_set(), "{m:#?}");
+ assert!(!m.is_hide_set(), "{m:#?}");
+ assert!(!m.is_last_set(), "{m:#?}");
+ }
+}
diff --git a/src/builder/command.rs b/src/builder/command.rs
new file mode 100644
index 0000000..72a68dc
--- /dev/null
+++ b/src/builder/command.rs
@@ -0,0 +1,4705 @@
+#![cfg_attr(not(feature = "usage"), allow(unused_mut))]
+
+// Std
+use std::env;
+use std::ffi::OsString;
+use std::fmt;
+use std::io;
+use std::ops::Index;
+use std::path::Path;
+
+// Internal
+use crate::builder::app_settings::{AppFlags, AppSettings};
+use crate::builder::arg_settings::ArgSettings;
+use crate::builder::ArgAction;
+use crate::builder::IntoResettable;
+use crate::builder::PossibleValue;
+use crate::builder::Str;
+use crate::builder::StyledStr;
+use crate::builder::{Arg, ArgGroup, ArgPredicate};
+use crate::error::ErrorKind;
+use crate::error::Result as ClapResult;
+use crate::mkeymap::MKeyMap;
+use crate::output::fmt::Stream;
+use crate::output::{fmt::Colorizer, write_help, Usage};
+use crate::parser::{ArgMatcher, ArgMatches, Parser};
+use crate::util::ChildGraph;
+use crate::util::FlatMap;
+use crate::util::{color::ColorChoice, Id};
+use crate::{Error, INTERNAL_ERROR_MSG};
+
+#[cfg(debug_assertions)]
+use crate::builder::debug_asserts::assert_app;
+
+/// Build a command-line interface.
+///
+/// This includes defining arguments, subcommands, parser behavior, and help output.
+/// Once all configuration is complete,
+/// the [`Command::get_matches`] family of methods starts the runtime-parsing
+/// process. These methods then return information about the user supplied
+/// arguments (or lack thereof).
+///
+/// When deriving a [`Parser`][crate::Parser], you can use
+/// [`CommandFactory::command`][crate::CommandFactory::command] to access the
+/// `Command`.
+///
+/// - [Basic API][crate::Command#basic-api]
+/// - [Application-wide Settings][crate::Command#application-wide-settings]
+/// - [Command-specific Settings][crate::Command#command-specific-settings]
+/// - [Subcommand-specific Settings][crate::Command#subcommand-specific-settings]
+/// - [Reflection][crate::Command#reflection]
+///
+/// # Examples
+///
+/// ```no_run
+/// # use clap::{Command, Arg};
+/// let m = Command::new("My Program")
+/// .author("Me, me@mail.com")
+/// .version("1.0.2")
+/// .about("Explains in brief what the program does")
+/// .arg(
+/// Arg::new("in_file")
+/// )
+/// .after_help("Longer explanation to appear after the options when \
+/// displaying the help information from --help or -h")
+/// .get_matches();
+///
+/// // Your program logic starts here...
+/// ```
+/// [`Command::get_matches`]: Command::get_matches()
+#[derive(Debug, Clone)]
+pub struct Command {
+ name: Str,
+ long_flag: Option<Str>,
+ short_flag: Option<char>,
+ display_name: Option<String>,
+ bin_name: Option<String>,
+ author: Option<Str>,
+ version: Option<Str>,
+ long_version: Option<Str>,
+ about: Option<StyledStr>,
+ long_about: Option<StyledStr>,
+ before_help: Option<StyledStr>,
+ before_long_help: Option<StyledStr>,
+ after_help: Option<StyledStr>,
+ after_long_help: Option<StyledStr>,
+ aliases: Vec<(Str, bool)>, // (name, visible)
+ short_flag_aliases: Vec<(char, bool)>, // (name, visible)
+ long_flag_aliases: Vec<(Str, bool)>, // (name, visible)
+ usage_str: Option<StyledStr>,
+ usage_name: Option<String>,
+ help_str: Option<StyledStr>,
+ disp_ord: Option<usize>,
+ term_w: Option<usize>,
+ max_w: Option<usize>,
+ #[cfg(feature = "help")]
+ template: Option<StyledStr>,
+ settings: AppFlags,
+ g_settings: AppFlags,
+ args: MKeyMap,
+ subcommands: Vec<Command>,
+ replacers: FlatMap<Str, Vec<Str>>,
+ groups: Vec<ArgGroup>,
+ current_help_heading: Option<Str>,
+ current_disp_ord: Option<usize>,
+ subcommand_value_name: Option<Str>,
+ subcommand_heading: Option<Str>,
+ external_value_parser: Option<super::ValueParser>,
+ long_help_exists: bool,
+}
+
+/// # Basic API
+impl Command {
+ /// Creates a new instance of an `Command`.
+ ///
+ /// It is common, but not required, to use binary name as the `name`. This
+ /// name will only be displayed to the user when they request to print
+ /// version or help and usage information.
+ ///
+ /// See also [`command!`](crate::command!) and [`crate_name!`](crate::crate_name!).
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("My Program")
+ /// # ;
+ /// ```
+ pub fn new(name: impl Into<Str>) -> Self {
+ /// The actual implementation of `new`, non-generic to save code size.
+ ///
+ /// If we don't do this rustc will unnecessarily generate multiple versions
+ /// of this code.
+ fn new_inner(name: Str) -> Command {
+ Command {
+ name,
+ ..Default::default()
+ }
+ }
+
+ new_inner(name.into())
+ }
+
+ /// Adds an [argument] to the list of valid possibilities.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, arg, Arg};
+ /// Command::new("myprog")
+ /// // Adding a single "flag" argument with a short and help text, using Arg::new()
+ /// .arg(
+ /// Arg::new("debug")
+ /// .short('d')
+ /// .help("turns on debugging mode")
+ /// )
+ /// // Adding a single "option" argument with a short, a long, and help text using the less
+ /// // verbose Arg::from()
+ /// .arg(
+ /// arg!(-c --config <CONFIG> "Optionally sets a config file to use")
+ /// )
+ /// # ;
+ /// ```
+ /// [argument]: Arg
+ #[must_use]
+ pub fn arg(mut self, a: impl Into<Arg>) -> Self {
+ let arg = a.into();
+ self.arg_internal(arg);
+ self
+ }
+
+ fn arg_internal(&mut self, mut arg: Arg) {
+ if let Some(current_disp_ord) = self.current_disp_ord.as_mut() {
+ if !arg.is_positional() {
+ let current = *current_disp_ord;
+ arg.disp_ord.get_or_insert(current);
+ *current_disp_ord = current + 1;
+ }
+ }
+
+ arg.help_heading
+ .get_or_insert_with(|| self.current_help_heading.clone());
+ self.args.push(arg);
+ }
+
+ /// Adds multiple [arguments] to the list of valid possibilities.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, arg, Arg};
+ /// Command::new("myprog")
+ /// .args([
+ /// arg!("[debug] -d 'turns on debugging info'"),
+ /// Arg::new("input").help("the input file to use")
+ /// ])
+ /// # ;
+ /// ```
+ /// [arguments]: Arg
+ #[must_use]
+ pub fn args(mut self, args: impl IntoIterator<Item = impl Into<Arg>>) -> Self {
+ for arg in args {
+ self = self.arg(arg);
+ }
+ self
+ }
+
+ /// Allows one to mutate an [`Arg`] after it's been added to a [`Command`].
+ ///
+ /// This can be useful for modifying the auto-generated help or version arguments.
+ ///
+ /// # Panics
+ ///
+ /// If the argument is undefined
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ ///
+ /// let mut cmd = Command::new("foo")
+ /// .arg(Arg::new("bar")
+ /// .short('b')
+ /// .action(ArgAction::SetTrue))
+ /// .mut_arg("bar", |a| a.short('B'));
+ ///
+ /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]);
+ ///
+ /// // Since we changed `bar`'s short to "B" this should err as there
+ /// // is no `-b` anymore, only `-B`
+ ///
+ /// assert!(res.is_err());
+ ///
+ /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]);
+ /// assert!(res.is_ok());
+ /// ```
+ #[must_use]
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn mut_arg<F>(mut self, arg_id: impl AsRef<str>, f: F) -> Self
+ where
+ F: FnOnce(Arg) -> Arg,
+ {
+ let id = arg_id.as_ref();
+ let a = self
+ .args
+ .remove_by_name(id)
+ .unwrap_or_else(|| panic!("Argument `{id}` is undefined"));
+
+ self.args.push(f(a));
+ 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`].
+ ///
+ /// # Panics
+ ///
+ /// If the subcommand is undefined
+ ///
+ /// # 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<F>(mut self, name: impl AsRef<str>, f: F) -> Self
+ where
+ F: FnOnce(Self) -> Self,
+ {
+ let name = name.as_ref();
+ let pos = self.subcommands.iter().position(|s| s.name == name);
+
+ let subcmd = if let Some(idx) = pos {
+ self.subcommands.remove(idx)
+ } else {
+ panic!("Command `{name}` is undefined")
+ };
+
+ self.subcommands.push(f(subcmd));
+ self
+ }
+
+ /// Adds an [`ArgGroup`] to the application.
+ ///
+ /// [`ArgGroup`]s are a family of related arguments.
+ /// By placing them in a logical group, you can build easier requirement and exclusion rules.
+ ///
+ /// Example use cases:
+ /// - Make an entire [`ArgGroup`] required, meaning that one (and *only*
+ /// one) argument from that group must be present at runtime.
+ /// - Name an [`ArgGroup`] as a conflict to another argument.
+ /// Meaning any of the arguments that belong to that group will cause a failure if present with
+ /// the conflicting argument.
+ /// - Ensure exclusion between arguments.
+ /// - Extract a value from a group instead of determining exactly which argument was used.
+ ///
+ /// # Examples
+ ///
+ /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one,
+ /// of the arguments from the specified group is present at runtime.
+ ///
+ /// ```no_run
+ /// # use clap::{Command, arg, ArgGroup};
+ /// Command::new("cmd")
+ /// .arg(arg!("--set-ver [ver] 'set the version manually'"))
+ /// .arg(arg!("--major 'auto increase major'"))
+ /// .arg(arg!("--minor 'auto increase minor'"))
+ /// .arg(arg!("--patch 'auto increase patch'"))
+ /// .group(ArgGroup::new("vers")
+ /// .args(["set-ver", "major", "minor","patch"])
+ /// .required(true))
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn group(mut self, group: impl Into<ArgGroup>) -> Self {
+ self.groups.push(group.into());
+ self
+ }
+
+ /// Adds multiple [`ArgGroup`]s to the [`Command`] at once.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, arg, ArgGroup};
+ /// Command::new("cmd")
+ /// .arg(arg!("--set-ver [ver] 'set the version manually'"))
+ /// .arg(arg!("--major 'auto increase major'"))
+ /// .arg(arg!("--minor 'auto increase minor'"))
+ /// .arg(arg!("--patch 'auto increase patch'"))
+ /// .arg(arg!("-c [FILE] 'a config file'"))
+ /// .arg(arg!("-i [IFACE] 'an interface'"))
+ /// .groups([
+ /// ArgGroup::new("vers")
+ /// .args(["set-ver", "major", "minor","patch"])
+ /// .required(true),
+ /// ArgGroup::new("input")
+ /// .args(["c", "i"])
+ /// ])
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<ArgGroup>>) -> Self {
+ for g in groups.into_iter() {
+ self = self.group(g.into());
+ }
+ self
+ }
+
+ /// Adds a subcommand to the list of valid possibilities.
+ ///
+ /// Subcommands are effectively sub-[`Command`]s, because they can contain their own arguments,
+ /// subcommands, version, usage, etc. They also function just like [`Command`]s, in that they get
+ /// their own auto generated help, version, and usage.
+ ///
+ /// A subcommand's [`Command::name`] will be used for:
+ /// - The argument the user passes in
+ /// - Programmatically looking up the subcommand
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, arg};
+ /// Command::new("myprog")
+ /// .subcommand(Command::new("config")
+ /// .about("Controls configuration features")
+ /// .arg(arg!("<config> 'Required configuration file to use'")))
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn subcommand(self, subcmd: impl Into<Command>) -> Self {
+ let subcmd = subcmd.into();
+ self.subcommand_internal(subcmd)
+ }
+
+ fn subcommand_internal(mut self, mut subcmd: Self) -> Self {
+ if let Some(current_disp_ord) = self.current_disp_ord.as_mut() {
+ let current = *current_disp_ord;
+ subcmd.disp_ord.get_or_insert(current);
+ *current_disp_ord = current + 1;
+ }
+ self.subcommands.push(subcmd);
+ self
+ }
+
+ /// Adds multiple subcommands to the list of valid possibilities.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, };
+ /// # Command::new("myprog")
+ /// .subcommands( [
+ /// Command::new("config").about("Controls configuration functionality")
+ /// .arg(Arg::new("config_file")),
+ /// Command::new("debug").about("Controls debug functionality")])
+ /// # ;
+ /// ```
+ /// [`IntoIterator`]: std::iter::IntoIterator
+ #[must_use]
+ pub fn subcommands(mut self, subcmds: impl IntoIterator<Item = impl Into<Self>>) -> Self {
+ for subcmd in subcmds {
+ self = self.subcommand(subcmd);
+ }
+ self
+ }
+
+ /// Catch problems earlier in the development cycle.
+ ///
+ /// Most error states are handled as asserts under the assumption they are programming mistake
+ /// and not something to handle at runtime. Rather than relying on tests (manual or automated)
+ /// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those
+ /// asserts in a way convenient for running as a test.
+ ///
+ /// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive
+ /// testing of your CLI.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// fn cmd() -> Command {
+ /// Command::new("foo")
+ /// .arg(
+ /// Arg::new("bar").short('b').action(ArgAction::SetTrue)
+ /// )
+ /// }
+ ///
+ /// #[test]
+ /// fn verify_app() {
+ /// cmd().debug_assert();
+ /// }
+ ///
+ /// fn main() {
+ /// let m = cmd().get_matches_from(vec!["foo", "-b"]);
+ /// println!("{}", m.get_flag("bar"));
+ /// }
+ /// ```
+ pub fn debug_assert(mut self) {
+ self.build();
+ }
+
+ /// Custom error message for post-parsing validation
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, error::ErrorKind};
+ /// let mut cmd = Command::new("myprog");
+ /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case");
+ /// ```
+ pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error {
+ Error::raw(kind, message).format(self)
+ }
+
+ /// Parse [`env::args_os`], exiting on failure.
+ ///
+ /// # Panics
+ ///
+ /// If contradictory arguments or settings exist.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let matches = Command::new("myprog")
+ /// // Args and options go here...
+ /// .get_matches();
+ /// ```
+ /// [`env::args_os`]: std::env::args_os()
+ /// [`Command::try_get_matches_from_mut`]: Command::try_get_matches_from_mut()
+ #[inline]
+ pub fn get_matches(self) -> ArgMatches {
+ self.get_matches_from(env::args_os())
+ }
+
+ /// Parse [`env::args_os`], exiting on failure.
+ ///
+ /// Like [`Command::get_matches`] but doesn't consume the `Command`.
+ ///
+ /// # Panics
+ ///
+ /// If contradictory arguments or settings exist.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let mut cmd = Command::new("myprog")
+ /// // Args and options go here...
+ /// ;
+ /// let matches = cmd.get_matches_mut();
+ /// ```
+ /// [`env::args_os`]: std::env::args_os()
+ /// [`Command::get_matches`]: Command::get_matches()
+ pub fn get_matches_mut(&mut self) -> ArgMatches {
+ self.try_get_matches_from_mut(&mut env::args_os())
+ .unwrap_or_else(|e| e.exit())
+ }
+
+ /// Parse [`env::args_os`], returning a [`clap::Result`] on failure.
+ ///
+ /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
+ /// used. It will return a [`clap::Error`], where the [`kind`] is a
+ /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call
+ /// [`Error::exit`] or perform a [`std::process::exit`].
+ ///
+ /// # Panics
+ ///
+ /// If contradictory arguments or settings exist.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let matches = Command::new("myprog")
+ /// // Args and options go here...
+ /// .try_get_matches()
+ /// .unwrap_or_else(|e| e.exit());
+ /// ```
+ /// [`env::args_os`]: std::env::args_os()
+ /// [`Error::exit`]: crate::Error::exit()
+ /// [`std::process::exit`]: std::process::exit()
+ /// [`clap::Result`]: Result
+ /// [`clap::Error`]: crate::Error
+ /// [`kind`]: crate::Error
+ /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp
+ /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion
+ #[inline]
+ pub fn try_get_matches(self) -> ClapResult<ArgMatches> {
+ // Start the parsing
+ self.try_get_matches_from(env::args_os())
+ }
+
+ /// Parse the specified arguments, exiting on failure.
+ ///
+ /// **NOTE:** The first argument will be parsed as the binary name unless
+ /// [`Command::no_binary_name`] is used.
+ ///
+ /// # Panics
+ ///
+ /// If contradictory arguments or settings exist.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
+ ///
+ /// let matches = Command::new("myprog")
+ /// // Args and options go here...
+ /// .get_matches_from(arg_vec);
+ /// ```
+ /// [`Command::get_matches`]: Command::get_matches()
+ /// [`clap::Result`]: Result
+ /// [`Vec`]: std::vec::Vec
+ pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ self.try_get_matches_from_mut(itr).unwrap_or_else(|e| {
+ drop(self);
+ e.exit()
+ })
+ }
+
+ /// Parse the specified arguments, returning a [`clap::Result`] on failure.
+ ///
+ /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
+ /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
+ /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
+ /// perform a [`std::process::exit`] yourself.
+ ///
+ /// **NOTE:** The first argument will be parsed as the binary name unless
+ /// [`Command::no_binary_name`] is used.
+ ///
+ /// # Panics
+ ///
+ /// If contradictory arguments or settings exist.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
+ ///
+ /// let matches = Command::new("myprog")
+ /// // Args and options go here...
+ /// .try_get_matches_from(arg_vec)
+ /// .unwrap_or_else(|e| e.exit());
+ /// ```
+ /// [`Command::get_matches_from`]: Command::get_matches_from()
+ /// [`Command::try_get_matches`]: Command::try_get_matches()
+ /// [`Error::exit`]: crate::Error::exit()
+ /// [`std::process::exit`]: std::process::exit()
+ /// [`clap::Error`]: crate::Error
+ /// [`Error::exit`]: crate::Error::exit()
+ /// [`kind`]: crate::Error
+ /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp
+ /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion
+ /// [`clap::Result`]: Result
+ pub fn try_get_matches_from<I, T>(mut self, itr: I) -> ClapResult<ArgMatches>
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ self.try_get_matches_from_mut(itr)
+ }
+
+ /// Parse the specified arguments, returning a [`clap::Result`] on failure.
+ ///
+ /// Like [`Command::try_get_matches_from`] but doesn't consume the `Command`.
+ ///
+ /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
+ /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
+ /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
+ /// perform a [`std::process::exit`] yourself.
+ ///
+ /// **NOTE:** The first argument will be parsed as the binary name unless
+ /// [`Command::no_binary_name`] is used.
+ ///
+ /// # Panics
+ ///
+ /// If contradictory arguments or settings exist.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
+ ///
+ /// let mut cmd = Command::new("myprog");
+ /// // Args and options go here...
+ /// let matches = cmd.try_get_matches_from_mut(arg_vec)
+ /// .unwrap_or_else(|e| e.exit());
+ /// ```
+ /// [`Command::try_get_matches_from`]: Command::try_get_matches_from()
+ /// [`clap::Result`]: Result
+ /// [`clap::Error`]: crate::Error
+ /// [`kind`]: crate::Error
+ pub fn try_get_matches_from_mut<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches>
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ let mut raw_args = clap_lex::RawArgs::new(itr.into_iter());
+ let mut cursor = raw_args.cursor();
+
+ if self.settings.is_set(AppSettings::Multicall) {
+ if let Some(argv0) = raw_args.next_os(&mut cursor) {
+ let argv0 = Path::new(&argv0);
+ if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) {
+ // Stop borrowing command so we can get another mut ref to it.
+ let command = command.to_owned();
+ debug!(
+ "Command::try_get_matches_from_mut: Parsed command {} from argv",
+ command
+ );
+
+ debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it");
+ raw_args.insert(&cursor, [&command]);
+ debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name");
+ self.name = "".into();
+ self.bin_name = None;
+ return self._do_parse(&mut raw_args, cursor);
+ }
+ }
+ };
+
+ // Get the name of the program (argument 1 of env::args()) and determine the
+ // actual file
+ // that was used to execute the program. This is because a program called
+ // ./target/release/my_prog -a
+ // will have two arguments, './target/release/my_prog', '-a' but we don't want
+ // to display
+ // the full path when displaying help messages and such
+ if !self.settings.is_set(AppSettings::NoBinaryName) {
+ if let Some(name) = raw_args.next_os(&mut cursor) {
+ let p = Path::new(name);
+
+ if let Some(f) = p.file_name() {
+ if let Some(s) = f.to_str() {
+ if self.bin_name.is_none() {
+ self.bin_name = Some(s.to_owned());
+ }
+ }
+ }
+ }
+ }
+
+ self._do_parse(&mut raw_args, cursor)
+ }
+
+ /// Prints the short help message (`-h`) to [`io::stdout()`].
+ ///
+ /// See also [`Command::print_long_help`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// let mut cmd = Command::new("myprog");
+ /// cmd.print_help();
+ /// ```
+ /// [`io::stdout()`]: std::io::stdout()
+ pub fn print_help(&mut self) -> io::Result<()> {
+ self._build_self(false);
+ let color = self.color_help();
+
+ let mut styled = StyledStr::new();
+ let usage = Usage::new(self);
+ write_help(&mut styled, self, &usage, false);
+
+ let c = Colorizer::new(Stream::Stdout, color).with_content(styled);
+ c.print()
+ }
+
+ /// Prints the long help message (`--help`) to [`io::stdout()`].
+ ///
+ /// See also [`Command::print_help`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// let mut cmd = Command::new("myprog");
+ /// cmd.print_long_help();
+ /// ```
+ /// [`io::stdout()`]: std::io::stdout()
+ /// [`BufWriter`]: std::io::BufWriter
+ /// [`-h` (short)]: Arg::help()
+ /// [`--help` (long)]: Arg::long_help()
+ pub fn print_long_help(&mut self) -> io::Result<()> {
+ self._build_self(false);
+ let color = self.color_help();
+
+ let mut styled = StyledStr::new();
+ let usage = Usage::new(self);
+ write_help(&mut styled, self, &usage, true);
+
+ let c = Colorizer::new(Stream::Stdout, color).with_content(styled);
+ c.print()
+ }
+
+ /// Render the short help message (`-h`) to a [`StyledStr`]
+ ///
+ /// See also [`Command::render_long_help`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// use std::io;
+ /// let mut cmd = Command::new("myprog");
+ /// let mut out = io::stdout();
+ /// let help = cmd.render_help();
+ /// println!("{}", help);
+ /// ```
+ /// [`io::Write`]: std::io::Write
+ /// [`-h` (short)]: Arg::help()
+ /// [`--help` (long)]: Arg::long_help()
+ pub fn render_help(&mut self) -> StyledStr {
+ self._build_self(false);
+
+ let mut styled = StyledStr::new();
+ let usage = Usage::new(self);
+ write_help(&mut styled, self, &usage, false);
+ styled
+ }
+
+ /// Render the long help message (`--help`) to a [`StyledStr`].
+ ///
+ /// See also [`Command::render_help`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// use std::io;
+ /// let mut cmd = Command::new("myprog");
+ /// let mut out = io::stdout();
+ /// let help = cmd.render_long_help();
+ /// println!("{}", help);
+ /// ```
+ /// [`io::Write`]: std::io::Write
+ /// [`-h` (short)]: Arg::help()
+ /// [`--help` (long)]: Arg::long_help()
+ pub fn render_long_help(&mut self) -> StyledStr {
+ self._build_self(false);
+
+ let mut styled = StyledStr::new();
+ let usage = Usage::new(self);
+ write_help(&mut styled, self, &usage, true);
+ styled
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Command::render_help`")
+ )]
+ pub fn write_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> {
+ self._build_self(false);
+
+ let mut styled = StyledStr::new();
+ let usage = Usage::new(self);
+ write_help(&mut styled, self, &usage, false);
+ ok!(write!(w, "{styled}"));
+ w.flush()
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Command::render_long_help`")
+ )]
+ pub fn write_long_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> {
+ self._build_self(false);
+
+ let mut styled = StyledStr::new();
+ let usage = Usage::new(self);
+ write_help(&mut styled, self, &usage, true);
+ ok!(write!(w, "{styled}"));
+ w.flush()
+ }
+
+ /// Version message rendered as if the user ran `-V`.
+ ///
+ /// See also [`Command::render_long_version`].
+ ///
+ /// ### Coloring
+ ///
+ /// This function does not try to color the message nor it inserts any [ANSI escape codes].
+ ///
+ /// ### Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// use std::io;
+ /// let cmd = Command::new("myprog");
+ /// println!("{}", cmd.render_version());
+ /// ```
+ /// [`io::Write`]: std::io::Write
+ /// [`-V` (short)]: Command::version()
+ /// [`--version` (long)]: Command::long_version()
+ /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
+ pub fn render_version(&self) -> String {
+ self._render_version(false)
+ }
+
+ /// Version message rendered as if the user ran `--version`.
+ ///
+ /// See also [`Command::render_version`].
+ ///
+ /// ### Coloring
+ ///
+ /// This function does not try to color the message nor it inserts any [ANSI escape codes].
+ ///
+ /// ### Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// use std::io;
+ /// let cmd = Command::new("myprog");
+ /// println!("{}", cmd.render_long_version());
+ /// ```
+ /// [`io::Write`]: std::io::Write
+ /// [`-V` (short)]: Command::version()
+ /// [`--version` (long)]: Command::long_version()
+ /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
+ pub fn render_long_version(&self) -> String {
+ self._render_version(true)
+ }
+
+ /// Usage statement
+ ///
+ /// ### Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// use std::io;
+ /// let mut cmd = Command::new("myprog");
+ /// println!("{}", cmd.render_usage());
+ /// ```
+ pub fn render_usage(&mut self) -> StyledStr {
+ self.render_usage_().unwrap_or_default()
+ }
+
+ pub(crate) fn render_usage_(&mut self) -> Option<StyledStr> {
+ // If there are global arguments, or settings we need to propagate them down to subcommands
+ // before parsing incase we run into a subcommand
+ self._build_self(false);
+
+ Usage::new(self).create_usage_with_title(&[])
+ }
+}
+
+/// # Application-wide Settings
+///
+/// These settings will apply to the top-level command and all subcommands, by default. Some
+/// settings can be overridden in subcommands.
+impl Command {
+ /// Specifies that the parser should not assume the first argument passed is the binary name.
+ ///
+ /// This is normally the case when using a "daemon" style mode. For shells / REPLs, see
+ /// [`Command::multicall`][Command::multicall].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, arg};
+ /// let m = Command::new("myprog")
+ /// .no_binary_name(true)
+ /// .arg(arg!(<cmd> ... "commands to run"))
+ /// .get_matches_from(vec!["command", "set"]);
+ ///
+ /// let cmds: Vec<_> = m.get_many::<String>("cmd").unwrap().collect();
+ /// assert_eq!(cmds, ["command", "set"]);
+ /// ```
+ /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut()
+ #[inline]
+ pub fn no_binary_name(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::NoBinaryName)
+ } else {
+ self.unset_global_setting(AppSettings::NoBinaryName)
+ }
+ }
+
+ /// Try not to fail on parse errors, like missing option values.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, arg};
+ /// let cmd = Command::new("cmd")
+ /// .ignore_errors(true)
+ /// .arg(arg!(-c --config <FILE> "Sets a custom config file"))
+ /// .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file"))
+ /// .arg(arg!(f: -f "Flag"));
+ ///
+ /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]);
+ ///
+ /// assert!(r.is_ok(), "unexpected error: {:?}", r);
+ /// let m = r.unwrap();
+ /// assert_eq!(m.get_one::<String>("config").unwrap(), "file");
+ /// assert!(m.get_flag("f"));
+ /// assert_eq!(m.get_one::<String>("stuff"), None);
+ /// ```
+ #[inline]
+ pub fn ignore_errors(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::IgnoreErrors)
+ } else {
+ self.unset_global_setting(AppSettings::IgnoreErrors)
+ }
+ }
+
+ /// Replace prior occurrences of arguments rather than error
+ ///
+ /// For any argument that would conflict with itself by default (e.g.
+ /// [`ArgAction::Set`][ArgAction::Set], it will now override itself.
+ ///
+ /// This is the equivalent to saying the `foo` arg using [`Arg::overrides_with("foo")`] for all
+ /// defined arguments.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// [`Arg::overrides_with("foo")`]: crate::Arg::overrides_with()
+ #[inline]
+ pub fn args_override_self(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::AllArgsOverrideSelf)
+ } else {
+ self.unset_global_setting(AppSettings::AllArgsOverrideSelf)
+ }
+ }
+
+ /// Disables the automatic delimiting of values after `--` or when [`Command::trailing_var_arg`]
+ /// was used.
+ ///
+ /// **NOTE:** The same thing can be done manually by setting the final positional argument to
+ /// [`Arg::value_delimiter(None)`]. Using this setting is safer, because it's easier to locate
+ /// when making changes.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .dont_delimit_trailing_values(true)
+ /// .get_matches();
+ /// ```
+ ///
+ /// [`Arg::value_delimiter(None)`]: crate::Arg::value_delimiter()
+ #[inline]
+ pub fn dont_delimit_trailing_values(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::DontDelimitTrailingValues)
+ } else {
+ self.unset_global_setting(AppSettings::DontDelimitTrailingValues)
+ }
+ }
+
+ /// Sets when to color output.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// **NOTE:** Default behaviour is [`ColorChoice::Auto`].
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, ColorChoice};
+ /// Command::new("myprog")
+ /// .color(ColorChoice::Never)
+ /// .get_matches();
+ /// ```
+ /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto
+ #[cfg(feature = "color")]
+ #[inline]
+ #[must_use]
+ pub fn color(self, color: ColorChoice) -> Self {
+ let cmd = self
+ .unset_global_setting(AppSettings::ColorAuto)
+ .unset_global_setting(AppSettings::ColorAlways)
+ .unset_global_setting(AppSettings::ColorNever);
+ match color {
+ ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto),
+ ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways),
+ ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever),
+ }
+ }
+
+ /// Sets the terminal width at which to wrap help messages.
+ ///
+ /// Using `0` will ignore terminal widths and use source formatting.
+ ///
+ /// Defaults to current terminal width when `wrap_help` feature flag is enabled. If the flag
+ /// is disabled or it cannot be determined, the default is 100.
+ ///
+ /// **NOTE:** This setting applies globally and *not* on a per-command basis.
+ ///
+ /// **NOTE:** This requires the [`wrap_help` feature][crate::_features]
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .term_width(80)
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))]
+ pub fn term_width(mut self, width: usize) -> Self {
+ self.term_w = Some(width);
+ self
+ }
+
+ /// Limit the line length for wrapping help when using the current terminal's width.
+ ///
+ /// This only applies when [`term_width`][Command::term_width] is unset so that the current
+ /// terminal's width will be used. See [`Command::term_width`] for more details.
+ ///
+ /// Using `0` will ignore terminal widths and use source formatting (default).
+ ///
+ /// **NOTE:** This setting applies globally and *not* on a per-command basis.
+ ///
+ /// **NOTE:** This requires the [`wrap_help` feature][crate::_features]
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .max_term_width(100)
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))]
+ pub fn max_term_width(mut self, w: usize) -> Self {
+ self.max_w = Some(w);
+ self
+ }
+
+ /// Disables `-V` and `--version` flag.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, error::ErrorKind};
+ /// let res = Command::new("myprog")
+ /// .disable_version_flag(true)
+ /// .try_get_matches_from(vec![
+ /// "myprog", "-V"
+ /// ]);
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
+ /// ```
+ #[inline]
+ pub fn disable_version_flag(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::DisableVersionFlag)
+ } else {
+ self.unset_global_setting(AppSettings::DisableVersionFlag)
+ }
+ }
+
+ /// Specifies to use the version of the current command for all [`subcommands`].
+ ///
+ /// Defaults to `false`; subcommands have independent version strings from their parents.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .version("v1.1")
+ /// .propagate_version(true)
+ /// .subcommand(Command::new("test"))
+ /// .get_matches();
+ /// // running `$ myprog test --version` will display
+ /// // "myprog-test v1.1"
+ /// ```
+ ///
+ /// [`subcommands`]: crate::Command::subcommand()
+ #[inline]
+ pub fn propagate_version(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::PropagateVersion)
+ } else {
+ self.unset_global_setting(AppSettings::PropagateVersion)
+ }
+ }
+
+ /// Places the help string for all arguments and subcommands on the line after them.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .next_line_help(true)
+ /// .get_matches();
+ /// ```
+ #[inline]
+ pub fn next_line_help(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::NextLineHelp)
+ } else {
+ self.unset_global_setting(AppSettings::NextLineHelp)
+ }
+ }
+
+ /// Disables `-h` and `--help` flag.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, error::ErrorKind};
+ /// let res = Command::new("myprog")
+ /// .disable_help_flag(true)
+ /// .try_get_matches_from(vec![
+ /// "myprog", "-h"
+ /// ]);
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
+ /// ```
+ #[inline]
+ pub fn disable_help_flag(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::DisableHelpFlag)
+ } else {
+ self.unset_global_setting(AppSettings::DisableHelpFlag)
+ }
+ }
+
+ /// Disables the `help` [`subcommand`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, error::ErrorKind};
+ /// let res = Command::new("myprog")
+ /// .disable_help_subcommand(true)
+ /// // Normally, creating a subcommand causes a `help` subcommand to automatically
+ /// // be generated as well
+ /// .subcommand(Command::new("test"))
+ /// .try_get_matches_from(vec![
+ /// "myprog", "help"
+ /// ]);
+ /// assert!(res.is_err());
+ /// assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidSubcommand);
+ /// ```
+ ///
+ /// [`subcommand`]: crate::Command::subcommand()
+ #[inline]
+ pub fn disable_help_subcommand(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::DisableHelpSubcommand)
+ } else {
+ self.unset_global_setting(AppSettings::DisableHelpSubcommand)
+ }
+ }
+
+ /// Disables colorized help messages.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .disable_colored_help(true)
+ /// .get_matches();
+ /// ```
+ #[inline]
+ pub fn disable_colored_help(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::DisableColoredHelp)
+ } else {
+ self.unset_global_setting(AppSettings::DisableColoredHelp)
+ }
+ }
+
+ /// Panic if help descriptions are omitted.
+ ///
+ /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at
+ /// compile-time with `#![deny(missing_docs)]`
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .help_expected(true)
+ /// .arg(
+ /// Arg::new("foo").help("It does foo stuff")
+ /// // As required via `help_expected`, a help message was supplied
+ /// )
+ /// # .get_matches();
+ /// ```
+ ///
+ /// # Panics
+ ///
+ /// ```rust,no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myapp")
+ /// .help_expected(true)
+ /// .arg(
+ /// Arg::new("foo")
+ /// // Someone forgot to put .about("...") here
+ /// // Since the setting `help_expected` is activated, this will lead to
+ /// // a panic (if you are in debug mode)
+ /// )
+ /// # .get_matches();
+ ///```
+ #[inline]
+ pub fn help_expected(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::HelpExpected)
+ } else {
+ self.unset_global_setting(AppSettings::HelpExpected)
+ }
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "This is now the default")
+ )]
+ pub fn dont_collapse_args_in_usage(self, _yes: bool) -> Self {
+ self
+ }
+
+ /// Tells `clap` *not* to print possible values when displaying help information.
+ ///
+ /// This can be useful if there are many values, or they are explained elsewhere.
+ ///
+ /// To set this per argument, see
+ /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values].
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ #[inline]
+ pub fn hide_possible_values(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::HidePossibleValues)
+ } else {
+ self.unset_global_setting(AppSettings::HidePossibleValues)
+ }
+ }
+
+ /// Allow partial matches of long arguments or their [aliases].
+ ///
+ /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and
+ /// `--test`.
+ ///
+ /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match
+ /// `--te` to `--test` there could not also be another argument or alias `--temp` because both
+ /// start with `--te`
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// [aliases]: crate::Command::aliases()
+ #[inline]
+ pub fn infer_long_args(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::InferLongArgs)
+ } else {
+ self.unset_global_setting(AppSettings::InferLongArgs)
+ }
+ }
+
+ /// Allow partial matches of [subcommand] names and their [aliases].
+ ///
+ /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and
+ /// `test`.
+ ///
+ /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te`
+ /// to `test` there could not also be a subcommand or alias `temp` because both start with `te`
+ ///
+ /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when
+ /// designing CLIs which allow inferred subcommands and have potential positional/free
+ /// arguments whose values could start with the same characters as subcommands. If this is the
+ /// case, it's recommended to use settings such as [`Command::args_conflicts_with_subcommands`] in
+ /// conjunction with this setting.
+ ///
+ /// **NOTE:** This choice is propagated to all child subcommands.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("prog")
+ /// .infer_subcommands(true)
+ /// .subcommand(Command::new("test"))
+ /// .get_matches_from(vec![
+ /// "prog", "te"
+ /// ]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ ///
+ /// [subcommand]: crate::Command::subcommand()
+ /// [positional/free arguments]: crate::Arg::index()
+ /// [aliases]: crate::Command::aliases()
+ #[inline]
+ pub fn infer_subcommands(self, yes: bool) -> Self {
+ if yes {
+ self.global_setting(AppSettings::InferSubcommands)
+ } else {
+ self.unset_global_setting(AppSettings::InferSubcommands)
+ }
+ }
+}
+
+/// # Command-specific Settings
+///
+/// These apply only to the current command and are not inherited by subcommands.
+impl Command {
+ /// (Re)Sets the program's name.
+ ///
+ /// See [`Command::new`] for more details.
+ ///
+ /// # Examples
+ ///
+ /// ```ignore
+ /// let cmd = clap::command!()
+ /// .name("foo");
+ ///
+ /// // continued logic goes here, such as `cmd.get_matches()` etc.
+ /// ```
+ #[must_use]
+ pub fn name(mut self, name: impl Into<Str>) -> Self {
+ self.name = name.into();
+ self
+ }
+
+ /// Overrides the runtime-determined name of the binary for help and error messages.
+ ///
+ /// This should only be used when absolutely necessary, such as when the binary name for your
+ /// application is misleading, or perhaps *not* how the user should invoke your program.
+ ///
+ /// **Pro-tip:** When building things such as third party `cargo`
+ /// subcommands, this setting **should** be used!
+ ///
+ /// **NOTE:** This *does not* change or set the name of the binary file on
+ /// disk. It only changes what clap thinks the name is for the purposes of
+ /// error or help messages.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("My Program")
+ /// .bin_name("my_binary")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn bin_name(mut self, name: impl IntoResettable<String>) -> Self {
+ self.bin_name = name.into_resettable().into_option();
+ self
+ }
+
+ /// Overrides the runtime-determined display name of the program for help and error messages.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("My Program")
+ /// .display_name("my_program")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn display_name(mut self, name: impl IntoResettable<String>) -> Self {
+ self.display_name = name.into_resettable().into_option();
+ self
+ }
+
+ /// Sets the author(s) for the help message.
+ ///
+ /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to
+ /// automatically set your application's author(s) to the same thing as your
+ /// crate at compile time.
+ ///
+ /// **NOTE:** A custom [`help_template`][Command::help_template] is needed for author to show
+ /// up.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .author("Me, me@mymain.com")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn author(mut self, author: impl IntoResettable<Str>) -> Self {
+ self.author = author.into_resettable().into_option();
+ self
+ }
+
+ /// Sets the program's description for the short help (`-h`).
+ ///
+ /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`.
+ ///
+ /// **NOTE:** Only `Command::about` (short format) is used in completion
+ /// script generation in order to be concise.
+ ///
+ /// See also [`crate_description!`](crate::crate_description!).
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .about("Does really amazing things for great people")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn about(mut self, about: impl IntoResettable<StyledStr>) -> Self {
+ self.about = about.into_resettable().into_option();
+ self
+ }
+
+ /// Sets the program's description for the long help (`--help`).
+ ///
+ /// If [`Command::about`] is not specified, this message will be displayed for `-h`.
+ ///
+ /// **NOTE:** Only [`Command::about`] (short format) is used in completion
+ /// script generation in order to be concise.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .long_about(
+ /// "Does really amazing things to great people. Now let's talk a little
+ /// more in depth about how this subcommand really works. It may take about
+ /// a few lines of text, but that's ok!")
+ /// # ;
+ /// ```
+ /// [`Command::about`]: Command::about()
+ #[must_use]
+ pub fn long_about(mut self, long_about: impl IntoResettable<StyledStr>) -> Self {
+ self.long_about = long_about.into_resettable().into_option();
+ self
+ }
+
+ /// Free-form help text for after auto-generated short help (`-h`).
+ ///
+ /// This is often used to describe how to use the arguments, caveats to be noted, or license
+ /// and contact information.
+ ///
+ /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .after_help("Does really amazing things for great people... but be careful with -R!")
+ /// # ;
+ /// ```
+ ///
+ #[must_use]
+ pub fn after_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
+ self.after_help = help.into_resettable().into_option();
+ self
+ }
+
+ /// Free-form help text for after auto-generated long help (`--help`).
+ ///
+ /// This is often used to describe how to use the arguments, caveats to be noted, or license
+ /// and contact information.
+ ///
+ /// If [`Command::after_help`] is not specified, this message will be displayed for `-h`.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .after_long_help("Does really amazing things to great people... but be careful with -R, \
+ /// like, for real, be careful with this!")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn after_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
+ self.after_long_help = help.into_resettable().into_option();
+ self
+ }
+
+ /// Free-form help text for before auto-generated short help (`-h`).
+ ///
+ /// This is often used for header, copyright, or license information.
+ ///
+ /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .before_help("Some info I'd like to appear before the help info")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn before_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
+ self.before_help = help.into_resettable().into_option();
+ self
+ }
+
+ /// Free-form help text for before auto-generated long help (`--help`).
+ ///
+ /// This is often used for header, copyright, or license information.
+ ///
+ /// If [`Command::before_help`] is not specified, this message will be displayed for `-h`.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .before_long_help("Some verbose and long info I'd like to appear before the help info")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn before_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
+ self.before_long_help = help.into_resettable().into_option();
+ self
+ }
+
+ /// Sets the version for the short version (`-V`) and help messages.
+ ///
+ /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`.
+ ///
+ /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
+ /// automatically set your application's version to the same thing as your
+ /// crate at compile time.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .version("v0.1.24")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn version(mut self, ver: impl IntoResettable<Str>) -> Self {
+ self.version = ver.into_resettable().into_option();
+ self
+ }
+
+ /// Sets the version for the long version (`--version`) and help messages.
+ ///
+ /// If [`Command::version`] is not specified, this message will be displayed for `-V`.
+ ///
+ /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
+ /// automatically set your application's version to the same thing as your
+ /// crate at compile time.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .long_version(
+ /// "v0.1.24
+ /// commit: abcdef89726d
+ /// revision: 123
+ /// release: 2
+ /// binary: myprog")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn long_version(mut self, ver: impl IntoResettable<Str>) -> Self {
+ self.long_version = ver.into_resettable().into_option();
+ self
+ }
+
+ /// Overrides the `clap` generated usage string for help and error messages.
+ ///
+ /// **NOTE:** Using this setting disables `clap`s "context-aware" usage
+ /// 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 seven spaces.
+ /// - The last line must not end with a newline.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .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(mut self, usage: impl IntoResettable<StyledStr>) -> Self {
+ self.usage_str = usage.into_resettable().into_option();
+ self
+ }
+
+ /// Overrides the `clap` generated help message (both `-h` and `--help`).
+ ///
+ /// This should only be used when the auto-generated message does not suffice.
+ ///
+ /// **NOTE:** This **only** replaces the help message for the current
+ /// command, meaning if you are using subcommands, those help messages will
+ /// still be auto-generated unless you specify a [`Command::override_help`] for
+ /// them as well.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myapp")
+ /// .override_help("myapp v1.0\n\
+ /// Does awesome things\n\
+ /// (C) me@mail.com\n\n\
+ ///
+ /// Usage: myapp <opts> <command>\n\n\
+ ///
+ /// Options:\n\
+ /// -h, --help Display this message\n\
+ /// -V, --version Display version info\n\
+ /// -s <stuff> Do something with stuff\n\
+ /// -v Be verbose\n\n\
+ ///
+ /// Commands:\n\
+ /// help Print this message\n\
+ /// work Do some work")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn override_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
+ self.help_str = help.into_resettable().into_option();
+ self
+ }
+
+ /// Sets the help template to be used, overriding the default format.
+ ///
+ /// **NOTE:** The template system is by design very simple. Therefore, the
+ /// tags have to be written in the lowercase and without spacing.
+ ///
+ /// Tags are given inside curly brackets.
+ ///
+ /// Valid tags are:
+ ///
+ /// * `{name}` - Display name for the (sub-)command.
+ /// * `{bin}` - Binary name.(deprecated)
+ /// * `{version}` - Version number.
+ /// * `{author}` - Author information.
+ /// * `{author-with-newline}` - Author followed by `\n`.
+ /// * `{author-section}` - Author preceded and followed by `\n`.
+ /// * `{about}` - General description (from [`Command::about`] or
+ /// [`Command::long_about`]).
+ /// * `{about-with-newline}` - About followed by `\n`.
+ /// * `{about-section}` - About preceded and followed by '\n'.
+ /// * `{usage-heading}` - Automatically generated usage heading.
+ /// * `{usage}` - Automatically generated or given usage string.
+ /// * `{all-args}` - Help for all arguments (options, flags, positional
+ /// arguments, and subcommands) including titles.
+ /// * `{options}` - Help for options.
+ /// * `{positionals}` - Help for positional arguments.
+ /// * `{subcommands}` - Help for subcommands.
+ /// * `{tab}` - Standard tab sized used within clap
+ /// * `{after-help}` - Help from [`Command::after_help`] or [`Command::after_long_help`].
+ /// * `{before-help}` - Help from [`Command::before_help`] or [`Command::before_long_help`].
+ ///
+ /// # Examples
+ ///
+ /// For a very brief help:
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .version("1.0")
+ /// .help_template("{name} ({version}) - {usage}")
+ /// # ;
+ /// ```
+ ///
+ /// For showing more application context:
+ ///
+ /// ```no_run
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .version("1.0")
+ /// .help_template("\
+ /// {before-help}{name} {version}
+ /// {author-with-newline}{about-with-newline}
+ /// {usage-heading} {usage}
+ ///
+ /// {all-args}{after-help}
+ /// ")
+ /// # ;
+ /// ```
+ /// [`Command::about`]: Command::about()
+ /// [`Command::long_about`]: Command::long_about()
+ /// [`Command::after_help`]: Command::after_help()
+ /// [`Command::after_long_help`]: Command::after_long_help()
+ /// [`Command::before_help`]: Command::before_help()
+ /// [`Command::before_long_help`]: Command::before_long_help()
+ #[must_use]
+ #[cfg(feature = "help")]
+ pub fn help_template(mut self, s: impl IntoResettable<StyledStr>) -> Self {
+ self.template = s.into_resettable().into_option();
+ self
+ }
+
+ #[inline]
+ #[must_use]
+ pub(crate) fn setting<F>(mut self, setting: F) -> Self
+ where
+ F: Into<AppFlags>,
+ {
+ self.settings.insert(setting.into());
+ self
+ }
+
+ #[inline]
+ #[must_use]
+ pub(crate) fn unset_setting<F>(mut self, setting: F) -> Self
+ where
+ F: Into<AppFlags>,
+ {
+ self.settings.remove(setting.into());
+ self
+ }
+
+ #[inline]
+ #[must_use]
+ pub(crate) fn global_setting(mut self, setting: AppSettings) -> Self {
+ self.settings.set(setting);
+ self.g_settings.set(setting);
+ self
+ }
+
+ #[inline]
+ #[must_use]
+ pub(crate) fn unset_global_setting(mut self, setting: AppSettings) -> Self {
+ self.settings.unset(setting);
+ self.g_settings.unset(setting);
+ self
+ }
+
+ /// Set the default section heading for future args.
+ ///
+ /// This will be used for any arg that hasn't had [`Arg::help_heading`] called.
+ ///
+ /// This is useful if the default `Options` or `Arguments` headings are
+ /// not specific enough for one's use case.
+ ///
+ /// For subcommands, see [`Command::subcommand_help_heading`]
+ ///
+ /// [`Command::arg`]: Command::arg()
+ /// [`Arg::help_heading`]: crate::Arg::help_heading()
+ #[inline]
+ #[must_use]
+ pub fn next_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self {
+ self.current_help_heading = heading.into_resettable().into_option();
+ self
+ }
+
+ /// Change the starting value for assigning future display orders for ags.
+ ///
+ /// This will be used for any arg that hasn't had [`Arg::display_order`] called.
+ #[inline]
+ #[must_use]
+ pub fn next_display_order(mut self, disp_ord: impl IntoResettable<usize>) -> Self {
+ self.current_disp_ord = disp_ord.into_resettable().into_option();
+ self
+ }
+
+ /// Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands.
+ ///
+ /// **Note:** This is gated behind [`unstable-replace`](https://github.com/clap-rs/clap/issues/2836)
+ ///
+ /// When this method is used, `name` is removed from the CLI, and `target`
+ /// is inserted in its place. Parsing continues as if the user typed
+ /// `target` instead of `name`.
+ ///
+ /// This can be used to create "shortcuts" for subcommands, or if a
+ /// particular argument has the semantic meaning of several other specific
+ /// arguments and values.
+ ///
+ /// # Examples
+ ///
+ /// We'll start with the "subcommand short" example. In this example, let's
+ /// assume we have a program with a subcommand `module` which can be invoked
+ /// via `cmd module`. Now let's also assume `module` also has a subcommand
+ /// called `install` which can be invoked `cmd module install`. If for some
+ /// reason users needed to be able to reach `cmd module install` via the
+ /// short-hand `cmd install`, we'd have several options.
+ ///
+ /// We *could* create another sibling subcommand to `module` called
+ /// `install`, but then we would need to manage another subcommand and manually
+ /// dispatch to `cmd module install` handling code. This is error prone and
+ /// tedious.
+ ///
+ /// We could instead use [`Command::replace`] so that, when the user types `cmd
+ /// install`, `clap` will replace `install` with `module install` which will
+ /// end up getting parsed as if the user typed the entire incantation.
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// let m = Command::new("cmd")
+ /// .subcommand(Command::new("module")
+ /// .subcommand(Command::new("install")))
+ /// .replace("install", &["module", "install"])
+ /// .get_matches_from(vec!["cmd", "install"]);
+ ///
+ /// assert!(m.subcommand_matches("module").is_some());
+ /// assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some());
+ /// ```
+ ///
+ /// Now let's show an argument example!
+ ///
+ /// Let's assume we have an application with two flags `--save-context` and
+ /// `--save-runtime`. But often users end up needing to do *both* at the
+ /// same time. We can add a third flag `--save-all` which semantically means
+ /// the same thing as `cmd --save-context --save-runtime`. To implement that,
+ /// we have several options.
+ ///
+ /// We could create this third argument and manually check if that argument
+ /// and in our own consumer code handle the fact that both `--save-context`
+ /// and `--save-runtime` *should* have been used. But again this is error
+ /// prone and tedious. If we had code relying on checking `--save-context`
+ /// and we forgot to update that code to *also* check `--save-all` it'd mean
+ /// an error!
+ ///
+ /// Luckily we can use [`Command::replace`] so that when the user types
+ /// `--save-all`, `clap` will replace that argument with `--save-context
+ /// --save-runtime`, and parsing will continue like normal. Now all our code
+ /// that was originally checking for things like `--save-context` doesn't
+ /// need to change!
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("cmd")
+ /// .arg(Arg::new("save-context")
+ /// .long("save-context")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("save-runtime")
+ /// .long("save-runtime")
+ /// .action(ArgAction::SetTrue))
+ /// .replace("--save-all", &["--save-context", "--save-runtime"])
+ /// .get_matches_from(vec!["cmd", "--save-all"]);
+ ///
+ /// assert!(m.get_flag("save-context"));
+ /// assert!(m.get_flag("save-runtime"));
+ /// ```
+ ///
+ /// This can also be used with options, for example if our application with
+ /// `--save-*` above also had a `--format=TYPE` option. Let's say it
+ /// accepted `txt` or `json` values. However, when `--save-all` is used,
+ /// only `--format=json` is allowed, or valid. We could change the example
+ /// above to enforce this:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("cmd")
+ /// .arg(Arg::new("save-context")
+ /// .long("save-context")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("save-runtime")
+ /// .long("save-runtime")
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("format")
+ /// .long("format")
+ /// .action(ArgAction::Set)
+ /// .value_parser(["txt", "json"]))
+ /// .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"])
+ /// .get_matches_from(vec!["cmd", "--save-all"]);
+ ///
+ /// assert!(m.get_flag("save-context"));
+ /// assert!(m.get_flag("save-runtime"));
+ /// assert_eq!(m.get_one::<String>("format").unwrap(), "json");
+ /// ```
+ ///
+ /// [`Command::replace`]: Command::replace()
+ #[inline]
+ #[cfg(feature = "unstable-replace")]
+ #[must_use]
+ pub fn replace(
+ mut self,
+ name: impl Into<Str>,
+ target: impl IntoIterator<Item = impl Into<Str>>,
+ ) -> Self {
+ self.replacers
+ .insert(name.into(), target.into_iter().map(Into::into).collect());
+ self
+ }
+
+ /// Exit gracefully if no arguments are present (e.g. `$ myprog`).
+ ///
+ /// **NOTE:** [`subcommands`] count as arguments
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command};
+ /// Command::new("myprog")
+ /// .arg_required_else_help(true);
+ /// ```
+ ///
+ /// [`subcommands`]: crate::Command::subcommand()
+ /// [`Arg::default_value`]: crate::Arg::default_value()
+ #[inline]
+ pub fn arg_required_else_help(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::ArgRequiredElseHelp)
+ } else {
+ self.unset_setting(AppSettings::ArgRequiredElseHelp)
+ }
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_hyphen_values`")
+ )]
+ pub fn allow_hyphen_values(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::AllowHyphenValues)
+ } else {
+ self.unset_setting(AppSettings::AllowHyphenValues)
+ }
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_negative_numbers`")
+ )]
+ pub fn allow_negative_numbers(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::AllowNegativeNumbers)
+ } else {
+ self.unset_setting(AppSettings::AllowNegativeNumbers)
+ }
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Arg::trailing_var_arg`")
+ )]
+ pub fn trailing_var_arg(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::TrailingVarArg)
+ } else {
+ self.unset_setting(AppSettings::TrailingVarArg)
+ }
+ }
+
+ /// Allows one to implement two styles of CLIs where positionals can be used out of order.
+ ///
+ /// The first example is a CLI where the second to last positional argument is optional, but
+ /// the final positional argument is required. Such as `$ prog [optional] <required>` where one
+ /// of the two following usages is allowed:
+ ///
+ /// * `$ prog [optional] <required>`
+ /// * `$ prog <required>`
+ ///
+ /// This would otherwise not be allowed. This is useful when `[optional]` has a default value.
+ ///
+ /// **Note:** when using this style of "missing positionals" the final positional *must* be
+ /// [required] if `--` will not be used to skip to the final positional argument.
+ ///
+ /// **Note:** This style also only allows a single positional argument to be "skipped" without
+ /// the use of `--`. To skip more than one, see the second example.
+ ///
+ /// The second example is when one wants to skip multiple optional positional arguments, and use
+ /// of the `--` operator is OK (but not required if all arguments will be specified anyways).
+ ///
+ /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where
+ /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments).
+ ///
+ /// With this setting the following invocations are posisble:
+ ///
+ /// * `$ prog foo bar baz1 baz2 baz3`
+ /// * `$ prog foo -- baz1 baz2 baz3`
+ /// * `$ prog -- baz1 baz2 baz3`
+ ///
+ /// # Examples
+ ///
+ /// Style number one from above:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let m = Command::new("myprog")
+ /// .allow_missing_positional(true)
+ /// .arg(Arg::new("arg1"))
+ /// .arg(Arg::new("arg2")
+ /// .required(true))
+ /// .get_matches_from(vec![
+ /// "prog", "other"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("arg1"), None);
+ /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");
+ /// ```
+ ///
+ /// Now the same example, but using a default value for the first optional positional argument
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let m = Command::new("myprog")
+ /// .allow_missing_positional(true)
+ /// .arg(Arg::new("arg1")
+ /// .default_value("something"))
+ /// .arg(Arg::new("arg2")
+ /// .required(true))
+ /// .get_matches_from(vec![
+ /// "prog", "other"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("arg1").unwrap(), "something");
+ /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");
+ /// ```
+ ///
+ /// Style number two from above:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let m = Command::new("myprog")
+ /// .allow_missing_positional(true)
+ /// .arg(Arg::new("foo"))
+ /// .arg(Arg::new("bar"))
+ /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
+ /// .get_matches_from(vec![
+ /// "prog", "foo", "bar", "baz1", "baz2", "baz3"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("foo").unwrap(), "foo");
+ /// assert_eq!(m.get_one::<String>("bar").unwrap(), "bar");
+ /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
+ /// ```
+ ///
+ /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let m = Command::new("myprog")
+ /// .allow_missing_positional(true)
+ /// .arg(Arg::new("foo"))
+ /// .arg(Arg::new("bar"))
+ /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
+ /// .get_matches_from(vec![
+ /// "prog", "--", "baz1", "baz2", "baz3"
+ /// ]);
+ ///
+ /// assert_eq!(m.get_one::<String>("foo"), None);
+ /// assert_eq!(m.get_one::<String>("bar"), None);
+ /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
+ /// ```
+ ///
+ /// [required]: crate::Arg::required()
+ #[inline]
+ pub fn allow_missing_positional(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::AllowMissingPositional)
+ } else {
+ self.unset_setting(AppSettings::AllowMissingPositional)
+ }
+ }
+}
+
+/// # Subcommand-specific Settings
+impl Command {
+ /// Sets the short version of the subcommand flag without the preceding `-`.
+ ///
+ /// Allows the subcommand to be used as if it were an [`Arg::short`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let matches = Command::new("pacman")
+ /// .subcommand(
+ /// Command::new("sync").short_flag('S').arg(
+ /// Arg::new("search")
+ /// .short('s')
+ /// .long("search")
+ /// .action(ArgAction::SetTrue)
+ /// .help("search remote repositories for matching strings"),
+ /// ),
+ /// )
+ /// .get_matches_from(vec!["pacman", "-Ss"]);
+ ///
+ /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
+ /// let sync_matches = matches.subcommand_matches("sync").unwrap();
+ /// assert!(sync_matches.get_flag("search"));
+ /// ```
+ /// [`Arg::short`]: Arg::short()
+ #[must_use]
+ pub fn short_flag(mut self, short: impl IntoResettable<char>) -> Self {
+ self.short_flag = short.into_resettable().into_option();
+ self
+ }
+
+ /// Sets the long version of the subcommand flag without the preceding `--`.
+ ///
+ /// Allows the subcommand to be used as if it were an [`Arg::long`].
+ ///
+ /// **NOTE:** Any leading `-` characters will be stripped.
+ ///
+ /// # Examples
+ ///
+ /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading
+ /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however,
+ /// will *not* be stripped (i.e. `sync-file` is allowed).
+ ///
+ /// ```
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let matches = Command::new("pacman")
+ /// .subcommand(
+ /// Command::new("sync").long_flag("sync").arg(
+ /// Arg::new("search")
+ /// .short('s')
+ /// .long("search")
+ /// .action(ArgAction::SetTrue)
+ /// .help("search remote repositories for matching strings"),
+ /// ),
+ /// )
+ /// .get_matches_from(vec!["pacman", "--sync", "--search"]);
+ ///
+ /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
+ /// let sync_matches = matches.subcommand_matches("sync").unwrap();
+ /// assert!(sync_matches.get_flag("search"));
+ /// ```
+ ///
+ /// [`Arg::long`]: Arg::long()
+ #[must_use]
+ pub fn long_flag(mut self, long: impl Into<Str>) -> Self {
+ self.long_flag = Some(long.into());
+ self
+ }
+
+ /// Sets a hidden alias to this subcommand.
+ ///
+ /// This allows the subcommand to be accessed via *either* the original name, or this given
+ /// alias. This is more efficient and easier than creating multiple hidden subcommands as one
+ /// only needs to check for the existence of this command, and not all aliased variants.
+ ///
+ /// **NOTE:** Aliases defined with this method are *hidden* from the help
+ /// message. If you're looking for aliases that will be displayed in the help
+ /// message, see [`Command::visible_alias`].
+ ///
+ /// **NOTE:** When using aliases and checking for the existence of a
+ /// particular subcommand within an [`ArgMatches`] struct, one only needs to
+ /// search for the original name and not all aliases.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test")
+ /// .alias("do-stuff"))
+ /// .get_matches_from(vec!["myprog", "do-stuff"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`Command::visible_alias`]: Command::visible_alias()
+ #[must_use]
+ pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self {
+ if let Some(name) = name.into_resettable().into_option() {
+ self.aliases.push((name, false));
+ } else {
+ self.aliases.clear();
+ }
+ self
+ }
+
+ /// Add an alias, which functions as "hidden" short flag subcommand
+ ///
+ /// This will automatically dispatch as if this subcommand was used. This is more efficient,
+ /// and easier than creating multiple hidden subcommands as one only needs to check for the
+ /// existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").short_flag('t')
+ /// .short_flag_alias('d'))
+ /// .get_matches_from(vec!["myprog", "-d"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ #[must_use]
+ pub fn short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self {
+ if let Some(name) = name.into_resettable().into_option() {
+ debug_assert!(name != '-', "short alias name cannot be `-`");
+ self.short_flag_aliases.push((name, false));
+ } else {
+ self.short_flag_aliases.clear();
+ }
+ self
+ }
+
+ /// Add an alias, which functions as a "hidden" long flag subcommand.
+ ///
+ /// This will automatically dispatch as if this subcommand was used. This is more efficient,
+ /// and easier than creating multiple hidden subcommands as one only needs to check for the
+ /// existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").long_flag("test")
+ /// .long_flag_alias("testing"))
+ /// .get_matches_from(vec!["myprog", "--testing"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ #[must_use]
+ pub fn long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self {
+ if let Some(name) = name.into_resettable().into_option() {
+ self.long_flag_aliases.push((name, false));
+ } else {
+ self.long_flag_aliases.clear();
+ }
+ self
+ }
+
+ /// Sets multiple hidden aliases to this subcommand.
+ ///
+ /// This allows the subcommand to be accessed via *either* the original name or any of the
+ /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands
+ /// as one only needs to check for the existence of this command and not all aliased variants.
+ ///
+ /// **NOTE:** Aliases defined with this method are *hidden* from the help
+ /// message. If looking for aliases that will be displayed in the help
+ /// message, see [`Command::visible_aliases`].
+ ///
+ /// **NOTE:** When using aliases and checking for the existence of a
+ /// particular subcommand within an [`ArgMatches`] struct, one only needs to
+ /// search for the original name and not all aliases.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test")
+ /// .aliases(["do-stuff", "do-tests", "tests"]))
+ /// .arg(Arg::new("input")
+ /// .help("the file to add")
+ /// .required(false))
+ /// .get_matches_from(vec!["myprog", "do-tests"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`Command::visible_aliases`]: Command::visible_aliases()
+ #[must_use]
+ pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
+ self.aliases
+ .extend(names.into_iter().map(|n| (n.into(), false)));
+ self
+ }
+
+ /// Add aliases, which function as "hidden" short flag subcommands.
+ ///
+ /// These will automatically dispatch as if this subcommand was used. This is more efficient,
+ /// and easier than creating multiple hidden subcommands as one only needs to check for the
+ /// existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").short_flag('t')
+ /// .short_flag_aliases(['a', 'b', 'c']))
+ /// .arg(Arg::new("input")
+ /// .help("the file to add")
+ /// .required(false))
+ /// .get_matches_from(vec!["myprog", "-a"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ #[must_use]
+ pub fn short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self {
+ for s in names {
+ debug_assert!(s != '-', "short alias name cannot be `-`");
+ self.short_flag_aliases.push((s, false));
+ }
+ self
+ }
+
+ /// Add aliases, which function as "hidden" long flag subcommands.
+ ///
+ /// These will automatically dispatch as if this subcommand was used. This is more efficient,
+ /// and easier than creating multiple hidden subcommands as one only needs to check for the
+ /// existence of this command, and not all variants.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").long_flag("test")
+ /// .long_flag_aliases(["testing", "testall", "test_all"]))
+ /// .arg(Arg::new("input")
+ /// .help("the file to add")
+ /// .required(false))
+ /// .get_matches_from(vec!["myprog", "--testing"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ #[must_use]
+ pub fn long_flag_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
+ for s in names {
+ self = self.long_flag_alias(s)
+ }
+ self
+ }
+
+ /// Sets a visible alias to this subcommand.
+ ///
+ /// This allows the subcommand to be accessed via *either* the
+ /// original name or the given alias. This is more efficient and easier
+ /// than creating hidden subcommands as one only needs to check for
+ /// the existence of this command and not all aliased variants.
+ ///
+ /// **NOTE:** The alias defined with this method is *visible* from the help
+ /// message and displayed as if it were just another regular subcommand. If
+ /// looking for an alias that will not be displayed in the help message, see
+ /// [`Command::alias`].
+ ///
+ /// **NOTE:** When using aliases and checking for the existence of a
+ /// particular subcommand within an [`ArgMatches`] struct, one only needs to
+ /// search for the original name and not all aliases.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test")
+ /// .visible_alias("do-stuff"))
+ /// .get_matches_from(vec!["myprog", "do-stuff"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`Command::alias`]: Command::alias()
+ #[must_use]
+ pub fn visible_alias(mut self, name: impl IntoResettable<Str>) -> Self {
+ if let Some(name) = name.into_resettable().into_option() {
+ self.aliases.push((name, true));
+ } else {
+ self.aliases.clear();
+ }
+ self
+ }
+
+ /// Add an alias, which functions as "visible" short flag subcommand
+ ///
+ /// This will automatically dispatch as if this subcommand was used. This is more efficient,
+ /// and easier than creating multiple hidden subcommands as one only needs to check for the
+ /// existence of this command, and not all variants.
+ ///
+ /// See also [`Command::short_flag_alias`].
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").short_flag('t')
+ /// .visible_short_flag_alias('d'))
+ /// .get_matches_from(vec!["myprog", "-d"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`Command::short_flag_alias`]: Command::short_flag_alias()
+ #[must_use]
+ pub fn visible_short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self {
+ if let Some(name) = name.into_resettable().into_option() {
+ debug_assert!(name != '-', "short alias name cannot be `-`");
+ self.short_flag_aliases.push((name, true));
+ } else {
+ self.short_flag_aliases.clear();
+ }
+ self
+ }
+
+ /// Add an alias, which functions as a "visible" long flag subcommand.
+ ///
+ /// This will automatically dispatch as if this subcommand was used. This is more efficient,
+ /// and easier than creating multiple hidden subcommands as one only needs to check for the
+ /// existence of this command, and not all variants.
+ ///
+ /// See also [`Command::long_flag_alias`].
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").long_flag("test")
+ /// .visible_long_flag_alias("testing"))
+ /// .get_matches_from(vec!["myprog", "--testing"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`Command::long_flag_alias`]: Command::long_flag_alias()
+ #[must_use]
+ pub fn visible_long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self {
+ if let Some(name) = name.into_resettable().into_option() {
+ self.long_flag_aliases.push((name, true));
+ } else {
+ self.long_flag_aliases.clear();
+ }
+ self
+ }
+
+ /// Sets multiple visible aliases to this subcommand.
+ ///
+ /// This allows the subcommand to be accessed via *either* the
+ /// original name or any of the given aliases. This is more efficient and easier
+ /// than creating multiple hidden subcommands as one only needs to check for
+ /// the existence of this command and not all aliased variants.
+ ///
+ /// **NOTE:** The alias defined with this method is *visible* from the help
+ /// message and displayed as if it were just another regular subcommand. If
+ /// looking for an alias that will not be displayed in the help message, see
+ /// [`Command::alias`].
+ ///
+ /// **NOTE:** When using aliases, and checking for the existence of a
+ /// particular subcommand within an [`ArgMatches`] struct, one only needs to
+ /// search for the original name and not all aliases.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test")
+ /// .visible_aliases(["do-stuff", "tests"]))
+ /// .get_matches_from(vec!["myprog", "do-stuff"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`Command::alias`]: Command::alias()
+ #[must_use]
+ pub fn visible_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
+ self.aliases
+ .extend(names.into_iter().map(|n| (n.into(), true)));
+ self
+ }
+
+ /// Add aliases, which function as *visible* short flag subcommands.
+ ///
+ /// See [`Command::short_flag_aliases`].
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").short_flag('b')
+ /// .visible_short_flag_aliases(['t']))
+ /// .get_matches_from(vec!["myprog", "-t"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`Command::short_flag_aliases`]: Command::short_flag_aliases()
+ #[must_use]
+ pub fn visible_short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self {
+ for s in names {
+ debug_assert!(s != '-', "short alias name cannot be `-`");
+ self.short_flag_aliases.push((s, true));
+ }
+ self
+ }
+
+ /// Add aliases, which function as *visible* long flag subcommands.
+ ///
+ /// See [`Command::long_flag_aliases`].
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let m = Command::new("myprog")
+ /// .subcommand(Command::new("test").long_flag("test")
+ /// .visible_long_flag_aliases(["testing", "testall", "test_all"]))
+ /// .get_matches_from(vec!["myprog", "--testing"]);
+ /// assert_eq!(m.subcommand_name(), Some("test"));
+ /// ```
+ /// [`Command::long_flag_aliases`]: Command::long_flag_aliases()
+ #[must_use]
+ pub fn visible_long_flag_aliases(
+ mut self,
+ names: impl IntoIterator<Item = impl Into<Str>>,
+ ) -> Self {
+ for s in names {
+ self = self.visible_long_flag_alias(s);
+ }
+ self
+ }
+
+ /// Set the placement of this subcommand within the help.
+ ///
+ /// Subcommands with a lower value will be displayed first in the help message. Subcommands
+ /// with duplicate display orders will be displayed in order they are defined.
+ ///
+ /// This is helpful when one would like to emphasize frequently used subcommands, or prioritize
+ /// those towards the top of the list.
+ ///
+ /// **NOTE:** The default is 999 for all subcommands.
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::{Command, };
+ /// let m = Command::new("cust-ord")
+ /// .subcommand(Command::new("alpha") // typically subcommands are grouped
+ /// // alphabetically by name. Subcommands
+ /// // without a display_order have a value of
+ /// // 999 and are displayed alphabetically with
+ /// // all other 999 subcommands
+ /// .about("Some help and text"))
+ /// .subcommand(Command::new("beta")
+ /// .display_order(1) // In order to force this subcommand to appear *first*
+ /// // all we have to do is give it a value lower than 999.
+ /// // Any other subcommands with a value of 1 will be displayed
+ /// // alphabetically with this one...then 2 values, then 3, etc.
+ /// .about("I should be first!"))
+ /// .get_matches_from(vec![
+ /// "cust-ord", "--help"
+ /// ]);
+ /// ```
+ ///
+ /// The above example displays the following help message
+ ///
+ /// ```text
+ /// cust-ord
+ ///
+ /// Usage: cust-ord [OPTIONS]
+ ///
+ /// Commands:
+ /// beta I should be first!
+ /// alpha Some help and text
+ ///
+ /// Options:
+ /// -h, --help Print help
+ /// -V, --version Print version
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn display_order(mut self, ord: impl IntoResettable<usize>) -> Self {
+ self.disp_ord = ord.into_resettable().into_option();
+ self
+ }
+
+ /// Specifies that this [`subcommand`] should be hidden from help messages
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .subcommand(
+ /// Command::new("test").hide(true)
+ /// )
+ /// # ;
+ /// ```
+ ///
+ /// [`subcommand`]: crate::Command::subcommand()
+ #[inline]
+ pub fn hide(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::Hidden)
+ } else {
+ self.unset_setting(AppSettings::Hidden)
+ }
+ }
+
+ /// If no [`subcommand`] is present at runtime, error and exit gracefully.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, error::ErrorKind};
+ /// let err = Command::new("myprog")
+ /// .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);
+ /// # ;
+ /// ```
+ ///
+ /// [`subcommand`]: crate::Command::subcommand()
+ pub fn subcommand_required(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::SubcommandRequired)
+ } else {
+ self.unset_setting(AppSettings::SubcommandRequired)
+ }
+ }
+
+ /// Assume unexpected positional arguments are a [`subcommand`].
+ ///
+ /// Arguments will be stored in the `""` argument in the [`ArgMatches`]
+ ///
+ /// **NOTE:** Use this setting with caution,
+ /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand)
+ /// will **not** cause an error and instead be treated as a potential subcommand.
+ /// One should check for such cases manually and inform the user appropriately.
+ ///
+ /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with
+ /// `--`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use std::ffi::OsString;
+ /// # use clap::Command;
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let m = Command::new("myprog")
+ /// .allow_external_subcommands(true)
+ /// .get_matches_from(vec![
+ /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
+ /// ]);
+ ///
+ /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
+ /// // string argument name
+ /// match m.subcommand() {
+ /// Some((external, ext_m)) => {
+ /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
+ /// assert_eq!(external, "subcmd");
+ /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
+ /// },
+ /// _ => {},
+ /// }
+ /// ```
+ ///
+ /// [`subcommand`]: crate::Command::subcommand()
+ /// [`ArgMatches`]: crate::ArgMatches
+ /// [`ErrorKind::UnknownArgument`]: crate::error::ErrorKind::UnknownArgument
+ pub fn allow_external_subcommands(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::AllowExternalSubcommands)
+ } else {
+ self.unset_setting(AppSettings::AllowExternalSubcommands)
+ }
+ }
+
+ /// Specifies how to parse external subcommand arguments.
+ ///
+ /// The default parser is for `OsString`. This can be used to switch it to `String` or another
+ /// type.
+ ///
+ /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`]
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(unix), doc = " ```ignore")]
+ #[cfg_attr(unix, doc = " ```")]
+ /// # use std::ffi::OsString;
+ /// # use clap::Command;
+ /// # use clap::value_parser;
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let m = Command::new("myprog")
+ /// .allow_external_subcommands(true)
+ /// .get_matches_from(vec![
+ /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
+ /// ]);
+ ///
+ /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
+ /// // string argument name
+ /// match m.subcommand() {
+ /// Some((external, ext_m)) => {
+ /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
+ /// assert_eq!(external, "subcmd");
+ /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
+ /// },
+ /// _ => {},
+ /// }
+ /// ```
+ ///
+ /// ```
+ /// # use clap::Command;
+ /// # use clap::value_parser;
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let m = Command::new("myprog")
+ /// .external_subcommand_value_parser(value_parser!(String))
+ /// .get_matches_from(vec![
+ /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
+ /// ]);
+ ///
+ /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
+ /// // string argument name
+ /// match m.subcommand() {
+ /// Some((external, ext_m)) => {
+ /// let ext_args: Vec<_> = ext_m.get_many::<String>("").unwrap().collect();
+ /// assert_eq!(external, "subcmd");
+ /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
+ /// },
+ /// _ => {},
+ /// }
+ /// ```
+ ///
+ /// [`subcommands`]: crate::Command::subcommand()
+ pub fn external_subcommand_value_parser(
+ mut self,
+ parser: impl IntoResettable<super::ValueParser>,
+ ) -> Self {
+ self.external_value_parser = parser.into_resettable().into_option();
+ self
+ }
+
+ /// Specifies that use of an argument prevents the use of [`subcommands`].
+ ///
+ /// By default `clap` allows arguments between subcommands such
+ /// as `<cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args]`.
+ ///
+ /// This setting disables that functionality and says that arguments can
+ /// only follow the *final* subcommand. For instance using this setting
+ /// makes only the following invocations possible:
+ ///
+ /// * `<cmd> <subcmd> <subsubcmd> [subsubcmd_args]`
+ /// * `<cmd> <subcmd> [subcmd_args]`
+ /// * `<cmd> [cmd_args]`
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// Command::new("myprog")
+ /// .args_conflicts_with_subcommands(true);
+ /// ```
+ ///
+ /// [`subcommands`]: crate::Command::subcommand()
+ pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::ArgsNegateSubcommands)
+ } else {
+ self.unset_setting(AppSettings::ArgsNegateSubcommands)
+ }
+ }
+
+ /// Prevent subcommands from being consumed as an arguments value.
+ ///
+ /// By default, if an option taking multiple values is followed by a subcommand, the
+ /// subcommand will be parsed as another value.
+ ///
+ /// ```text
+ /// cmd --foo val1 val2 subcommand
+ /// --------- ----------
+ /// values another value
+ /// ```
+ ///
+ /// This setting instructs the parser to stop when encountering a subcommand instead of
+ /// greedily consuming arguments.
+ ///
+ /// ```text
+ /// cmd --foo val1 val2 subcommand
+ /// --------- ----------
+ /// values subcommand
+ /// ```
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg(
+ /// Arg::new("arg")
+ /// .long("arg")
+ /// .num_args(1..)
+ /// .action(ArgAction::Set),
+ /// );
+ ///
+ /// let matches = cmd
+ /// .clone()
+ /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
+ /// .unwrap();
+ /// assert_eq!(
+ /// matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
+ /// &["1", "2", "3", "sub"]
+ /// );
+ /// assert!(matches.subcommand_matches("sub").is_none());
+ ///
+ /// let matches = cmd
+ /// .subcommand_precedence_over_arg(true)
+ /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
+ /// .unwrap();
+ /// assert_eq!(
+ /// matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
+ /// &["1", "2", "3"]
+ /// );
+ /// assert!(matches.subcommand_matches("sub").is_some());
+ /// ```
+ pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::SubcommandPrecedenceOverArg)
+ } else {
+ self.unset_setting(AppSettings::SubcommandPrecedenceOverArg)
+ }
+ }
+
+ /// Allows [`subcommands`] to override all requirements of the parent command.
+ ///
+ /// For example, if you had a subcommand or top level application with a required argument
+ /// that is only required as long as there is no subcommand present,
+ /// using this setting would allow you to set those arguments to [`Arg::required(true)`]
+ /// and yet receive no error so long as the user uses a valid subcommand instead.
+ ///
+ /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements)
+ ///
+ /// # Examples
+ ///
+ /// This first example shows that it is an error to not use a required argument
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind};
+ /// let err = Command::new("myprog")
+ /// .subcommand_negates_reqs(true)
+ /// .arg(Arg::new("opt").required(true))
+ /// .subcommand(Command::new("test"))
+ /// .try_get_matches_from(vec![
+ /// "myprog"
+ /// ]);
+ /// assert!(err.is_err());
+ /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
+ /// # ;
+ /// ```
+ ///
+ /// This next example shows that it is no longer error to not use a required argument if a
+ /// valid subcommand is used.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind};
+ /// let noerr = Command::new("myprog")
+ /// .subcommand_negates_reqs(true)
+ /// .arg(Arg::new("opt").required(true))
+ /// .subcommand(Command::new("test"))
+ /// .try_get_matches_from(vec![
+ /// "myprog", "test"
+ /// ]);
+ /// assert!(noerr.is_ok());
+ /// # ;
+ /// ```
+ ///
+ /// [`Arg::required(true)`]: crate::Arg::required()
+ /// [`subcommands`]: crate::Command::subcommand()
+ pub fn subcommand_negates_reqs(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::SubcommandsNegateReqs)
+ } else {
+ self.unset_setting(AppSettings::SubcommandsNegateReqs)
+ }
+ }
+
+ /// Multiple-personality program dispatched on the binary name (`argv[0]`)
+ ///
+ /// A "multicall" executable is a single executable
+ /// that contains a variety of applets,
+ /// and decides which applet to run based on the name of the file.
+ /// The executable can be called from different names by creating hard links
+ /// or symbolic links to it.
+ ///
+ /// This is desirable for:
+ /// - Easy distribution, a single binary that can install hardlinks to access the different
+ /// personalities.
+ /// - Minimal binary size by sharing common code (e.g. standard library, clap)
+ /// - Custom shells or REPLs where there isn't a single top-level command
+ ///
+ /// Setting `multicall` will cause
+ /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if
+ /// [`Command::no_binary_name`][Command::no_binary_name] was set.
+ /// - Help and errors to report subcommands as if they were the top-level command
+ ///
+ /// When the subcommand is not present, there are several strategies you may employ, depending
+ /// on your needs:
+ /// - Let the error percolate up normally
+ /// - Print a specialized error message using the
+ /// [`Error::context`][crate::Error::context]
+ /// - Print the [help][Command::write_help] but this might be ambiguous
+ /// - Disable `multicall` and re-parse it
+ /// - Disable `multicall` and re-parse it with a specific subcommand
+ ///
+ /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand
+ /// might report the same error. Enable
+ /// [`allow_external_subcommands`][Command::allow_external_subcommands] if you want to specifically
+ /// get the unrecognized binary name.
+ ///
+ /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret
+ /// the command name in incompatible ways.
+ ///
+ /// **NOTE:** The multicall command cannot have arguments.
+ ///
+ /// **NOTE:** Applets are slightly semantically different from subcommands,
+ /// so it's recommended to use [`Command::subcommand_help_heading`] and
+ /// [`Command::subcommand_value_name`] to change the descriptive text as above.
+ ///
+ /// # Examples
+ ///
+ /// `hostname` is an example of a multicall executable.
+ /// Both `hostname` and `dnsdomainname` are provided by the same executable
+ /// and which behaviour to use is based on the executable file name.
+ ///
+ /// This is desirable when the executable has a primary purpose
+ /// but there is related functionality that would be convenient to provide
+ /// and implement it to be in the same executable.
+ ///
+ /// The name of the cmd is essentially unused
+ /// and may be the same as the name of a subcommand.
+ ///
+ /// The names of the immediate subcommands of the Command
+ /// are matched against the basename of the first argument,
+ /// which is conventionally the path of the executable.
+ ///
+ /// This does not allow the subcommand to be passed as the first non-path argument.
+ ///
+ /// ```rust
+ /// # use clap::{Command, error::ErrorKind};
+ /// let mut cmd = Command::new("hostname")
+ /// .multicall(true)
+ /// .subcommand(Command::new("hostname"))
+ /// .subcommand(Command::new("dnsdomainname"));
+ /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]);
+ /// assert!(m.is_err());
+ /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument);
+ /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]);
+ /// assert_eq!(m.subcommand_name(), Some("dnsdomainname"));
+ /// ```
+ ///
+ /// Busybox is another common example of a multicall executable
+ /// with a subcommmand for each applet that can be run directly,
+ /// e.g. with the `cat` applet being run by running `busybox cat`,
+ /// or with `cat` as a link to the `busybox` binary.
+ ///
+ /// This is desirable when the launcher program has additional options
+ /// or it is useful to run the applet without installing a symlink
+ /// e.g. to test the applet without installing it
+ /// or there may already be a command of that name installed.
+ ///
+ /// To make an applet usable as both a multicall link and a subcommand
+ /// the subcommands must be defined both in the top-level Command
+ /// and as subcommands of the "main" applet.
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// fn applet_commands() -> [Command; 2] {
+ /// [Command::new("true"), Command::new("false")]
+ /// }
+ /// let mut cmd = Command::new("busybox")
+ /// .multicall(true)
+ /// .subcommand(
+ /// Command::new("busybox")
+ /// .subcommand_value_name("APPLET")
+ /// .subcommand_help_heading("APPLETS")
+ /// .subcommands(applet_commands()),
+ /// )
+ /// .subcommands(applet_commands());
+ /// // When called from the executable's canonical name
+ /// // its applets can be matched as subcommands.
+ /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap();
+ /// assert_eq!(m.subcommand_name(), Some("busybox"));
+ /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true"));
+ /// // When called from a link named after an applet that applet is matched.
+ /// let m = cmd.get_matches_from(&["/usr/bin/true"]);
+ /// assert_eq!(m.subcommand_name(), Some("true"));
+ /// ```
+ ///
+ /// [`no_binary_name`]: crate::Command::no_binary_name
+ /// [`Command::subcommand_value_name`]: crate::Command::subcommand_value_name
+ /// [`Command::subcommand_help_heading`]: crate::Command::subcommand_help_heading
+ #[inline]
+ pub fn multicall(self, yes: bool) -> Self {
+ if yes {
+ self.setting(AppSettings::Multicall)
+ } else {
+ self.unset_setting(AppSettings::Multicall)
+ }
+ }
+
+ /// Sets the value name used for subcommands when printing usage and help.
+ ///
+ /// By default, this is "COMMAND".
+ ///
+ /// See also [`Command::subcommand_help_heading`]
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .subcommand(Command::new("sub1"))
+ /// .print_help()
+ /// # ;
+ /// ```
+ ///
+ /// will produce
+ ///
+ /// ```text
+ /// myprog
+ ///
+ /// Usage: myprog [COMMAND]
+ ///
+ /// Commands:
+ /// help Print this message or the help of the given subcommand(s)
+ /// sub1
+ ///
+ /// Options:
+ /// -h, --help Print help
+ /// -V, --version Print version
+ /// ```
+ ///
+ /// but usage of `subcommand_value_name`
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .subcommand(Command::new("sub1"))
+ /// .subcommand_value_name("THING")
+ /// .print_help()
+ /// # ;
+ /// ```
+ ///
+ /// will produce
+ ///
+ /// ```text
+ /// myprog
+ ///
+ /// Usage: myprog [THING]
+ ///
+ /// Commands:
+ /// help Print this message or the help of the given subcommand(s)
+ /// sub1
+ ///
+ /// Options:
+ /// -h, --help Print help
+ /// -V, --version Print version
+ /// ```
+ #[must_use]
+ pub fn subcommand_value_name(mut self, value_name: impl IntoResettable<Str>) -> Self {
+ self.subcommand_value_name = value_name.into_resettable().into_option();
+ self
+ }
+
+ /// Sets the help heading used for subcommands when printing usage and help.
+ ///
+ /// By default, this is "Commands".
+ ///
+ /// See also [`Command::subcommand_value_name`]
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .subcommand(Command::new("sub1"))
+ /// .print_help()
+ /// # ;
+ /// ```
+ ///
+ /// will produce
+ ///
+ /// ```text
+ /// myprog
+ ///
+ /// Usage: myprog [COMMAND]
+ ///
+ /// Commands:
+ /// help Print this message or the help of the given subcommand(s)
+ /// sub1
+ ///
+ /// Options:
+ /// -h, --help Print help
+ /// -V, --version Print version
+ /// ```
+ ///
+ /// but usage of `subcommand_help_heading`
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg};
+ /// Command::new("myprog")
+ /// .subcommand(Command::new("sub1"))
+ /// .subcommand_help_heading("Things")
+ /// .print_help()
+ /// # ;
+ /// ```
+ ///
+ /// will produce
+ ///
+ /// ```text
+ /// myprog
+ ///
+ /// Usage: myprog [COMMAND]
+ ///
+ /// Things:
+ /// help Print this message or the help of the given subcommand(s)
+ /// sub1
+ ///
+ /// Options:
+ /// -h, --help Print help
+ /// -V, --version Print version
+ /// ```
+ #[must_use]
+ pub fn subcommand_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self {
+ self.subcommand_heading = heading.into_resettable().into_option();
+ self
+ }
+}
+
+/// # Reflection
+impl Command {
+ #[inline]
+ #[cfg(feature = "usage")]
+ pub(crate) fn get_usage_name(&self) -> Option<&str> {
+ self.usage_name.as_deref()
+ }
+
+ /// Get the name of the binary.
+ #[inline]
+ pub fn get_display_name(&self) -> Option<&str> {
+ self.display_name.as_deref()
+ }
+
+ /// Get the name of the binary.
+ #[inline]
+ pub fn get_bin_name(&self) -> Option<&str> {
+ self.bin_name.as_deref()
+ }
+
+ /// Set binary name. Uses `&mut self` instead of `self`.
+ pub fn set_bin_name(&mut self, name: impl Into<String>) {
+ self.bin_name = Some(name.into());
+ }
+
+ /// Get the name of the cmd.
+ #[inline]
+ pub fn get_name(&self) -> &str {
+ self.name.as_str()
+ }
+
+ #[inline]
+ #[cfg(debug_assertions)]
+ pub(crate) fn get_name_str(&self) -> &Str {
+ &self.name
+ }
+
+ /// Get the version of the cmd.
+ #[inline]
+ pub fn get_version(&self) -> Option<&str> {
+ self.version.as_deref()
+ }
+
+ /// Get the long version of the cmd.
+ #[inline]
+ pub fn get_long_version(&self) -> Option<&str> {
+ self.long_version.as_deref()
+ }
+
+ /// Get the authors of the cmd.
+ #[inline]
+ pub fn get_author(&self) -> Option<&str> {
+ self.author.as_deref()
+ }
+
+ /// Get the short flag of the subcommand.
+ #[inline]
+ pub fn get_short_flag(&self) -> Option<char> {
+ self.short_flag
+ }
+
+ /// Get the long flag of the subcommand.
+ #[inline]
+ pub fn get_long_flag(&self) -> Option<&str> {
+ self.long_flag.as_deref()
+ }
+
+ /// Get the help message specified via [`Command::about`].
+ ///
+ /// [`Command::about`]: Command::about()
+ #[inline]
+ pub fn get_about(&self) -> Option<&StyledStr> {
+ self.about.as_ref()
+ }
+
+ /// Get the help message specified via [`Command::long_about`].
+ ///
+ /// [`Command::long_about`]: Command::long_about()
+ #[inline]
+ pub fn get_long_about(&self) -> Option<&StyledStr> {
+ self.long_about.as_ref()
+ }
+
+ /// Get the custom section heading specified via [`Command::next_help_heading`].
+ ///
+ /// [`Command::help_heading`]: Command::help_heading()
+ #[inline]
+ pub fn get_next_help_heading(&self) -> Option<&str> {
+ self.current_help_heading.as_deref()
+ }
+
+ /// Iterate through the *visible* aliases for this subcommand.
+ #[inline]
+ pub fn get_visible_aliases(&self) -> impl Iterator<Item = &str> + '_ {
+ self.aliases
+ .iter()
+ .filter(|(_, vis)| *vis)
+ .map(|a| a.0.as_str())
+ }
+
+ /// Iterate through the *visible* short aliases for this subcommand.
+ #[inline]
+ pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
+ self.short_flag_aliases
+ .iter()
+ .filter(|(_, vis)| *vis)
+ .map(|a| a.0)
+ }
+
+ /// Iterate through the *visible* long aliases for this subcommand.
+ #[inline]
+ pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ {
+ self.long_flag_aliases
+ .iter()
+ .filter(|(_, vis)| *vis)
+ .map(|a| a.0.as_str())
+ }
+
+ /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden.
+ #[inline]
+ pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> + '_ {
+ self.aliases.iter().map(|a| a.0.as_str())
+ }
+
+ /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden.
+ #[inline]
+ pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
+ self.short_flag_aliases.iter().map(|a| a.0)
+ }
+
+ /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden.
+ #[inline]
+ pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ {
+ self.long_flag_aliases.iter().map(|a| a.0.as_str())
+ }
+
+ #[inline]
+ pub(crate) fn is_set(&self, s: AppSettings) -> bool {
+ self.settings.is_set(s) || self.g_settings.is_set(s)
+ }
+
+ /// Should we color the output?
+ pub fn get_color(&self) -> ColorChoice {
+ debug!("Command::color: Color setting...");
+
+ if cfg!(feature = "color") {
+ if self.is_set(AppSettings::ColorNever) {
+ debug!("Never");
+ ColorChoice::Never
+ } else if self.is_set(AppSettings::ColorAlways) {
+ debug!("Always");
+ ColorChoice::Always
+ } else {
+ debug!("Auto");
+ ColorChoice::Auto
+ }
+ } else {
+ ColorChoice::Never
+ }
+ }
+
+ /// Iterate through the set of subcommands, getting a reference to each.
+ #[inline]
+ pub fn get_subcommands(&self) -> impl Iterator<Item = &Command> {
+ 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<Item = &mut Command> {
+ self.subcommands.iter_mut()
+ }
+
+ /// Returns `true` if this `Command` has subcommands.
+ #[inline]
+ pub fn has_subcommands(&self) -> bool {
+ !self.subcommands.is_empty()
+ }
+
+ /// Returns the help heading for listing subcommands.
+ #[inline]
+ pub fn get_subcommand_help_heading(&self) -> Option<&str> {
+ self.subcommand_heading.as_deref()
+ }
+
+ /// Returns the subcommand value name.
+ #[inline]
+ pub fn get_subcommand_value_name(&self) -> Option<&str> {
+ self.subcommand_value_name.as_deref()
+ }
+
+ /// Returns the help heading for listing subcommands.
+ #[inline]
+ pub fn get_before_help(&self) -> Option<&StyledStr> {
+ self.before_help.as_ref()
+ }
+
+ /// Returns the help heading for listing subcommands.
+ #[inline]
+ pub fn get_before_long_help(&self) -> Option<&StyledStr> {
+ self.before_long_help.as_ref()
+ }
+
+ /// Returns the help heading for listing subcommands.
+ #[inline]
+ pub fn get_after_help(&self) -> Option<&StyledStr> {
+ self.after_help.as_ref()
+ }
+
+ /// Returns the help heading for listing subcommands.
+ #[inline]
+ pub fn get_after_long_help(&self) -> Option<&StyledStr> {
+ self.after_long_help.as_ref()
+ }
+
+ /// Find subcommand such that its name or one of aliases equals `name`.
+ ///
+ /// This does not recurse through subcommands of subcommands.
+ #[inline]
+ pub fn find_subcommand(&self, name: impl AsRef<std::ffi::OsStr>) -> Option<&Command> {
+ let name = name.as_ref();
+ self.get_subcommands().find(|s| s.aliases_to(name))
+ }
+
+ /// Find subcommand such that its name or one of aliases equals `name`, returning
+ /// a mutable reference to the subcommand.
+ ///
+ /// This does not recurse through subcommands of subcommands.
+ #[inline]
+ pub fn find_subcommand_mut(
+ &mut self,
+ name: impl AsRef<std::ffi::OsStr>,
+ ) -> Option<&mut Command> {
+ let name = name.as_ref();
+ self.get_subcommands_mut().find(|s| s.aliases_to(name))
+ }
+
+ /// Iterate through the set of groups.
+ #[inline]
+ pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup> {
+ self.groups.iter()
+ }
+
+ /// Iterate through the set of arguments.
+ #[inline]
+ pub fn get_arguments(&self) -> impl Iterator<Item = &Arg> {
+ self.args.args()
+ }
+
+ /// Iterate through the *positionals* arguments.
+ #[inline]
+ pub fn get_positionals(&self) -> impl Iterator<Item = &Arg> {
+ self.get_arguments().filter(|a| a.is_positional())
+ }
+
+ /// Iterate through the *options*.
+ pub fn get_opts(&self) -> impl Iterator<Item = &Arg> {
+ self.get_arguments()
+ .filter(|a| a.is_takes_value_set() && !a.is_positional())
+ }
+
+ /// Get a list of all arguments the given argument conflicts with.
+ ///
+ /// If the provided argument is declared as global, the conflicts will be determined
+ /// based on the propagation rules of global arguments.
+ ///
+ /// ### Panics
+ ///
+ /// If the given arg contains a conflict with an argument that is unknown to
+ /// this `Command`.
+ pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
+ {
+ if arg.is_global_set() {
+ self.get_global_arg_conflicts_with(arg)
+ } else {
+ 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
+ }
+ }
+
+ // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with.
+ //
+ // This behavior follows the propagation rules of global arguments.
+ // It is useful for finding conflicts for arguments declared as global.
+ //
+ // ### Panics
+ //
+ // If the given arg contains a conflict with an argument that is unknown to
+ // this `Command`.
+ fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
+ {
+ arg.blacklist
+ .iter()
+ .map(|id| {
+ self.args
+ .args()
+ .chain(
+ self.get_subcommands_containing(arg)
+ .iter()
+ .flat_map(|x| x.args.args()),
+ )
+ .find(|arg| arg.get_id() == id)
+ .expect(
+ "Command::get_arg_conflicts_with: \
+ The passed arg conflicts with an arg unknown to the cmd",
+ )
+ })
+ .collect()
+ }
+
+ // Get a list of subcommands which contain the provided Argument
+ //
+ // This command will only include subcommands in its list for which the subcommands
+ // parent also contains the Argument.
+ //
+ // This search follows the propagation rules of global arguments.
+ // It is useful to finding subcommands, that have inherited a global argument.
+ //
+ // **NOTE:** In this case only Sucommand_1 will be included
+ // Subcommand_1 (contains Arg)
+ // Subcommand_1.1 (doesn't contain Arg)
+ // Subcommand_1.1.1 (contains Arg)
+ //
+ fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> {
+ let mut vec = std::vec::Vec::new();
+ for idx in 0..self.subcommands.len() {
+ if self.subcommands[idx]
+ .args
+ .args()
+ .any(|ar| ar.get_id() == arg.get_id())
+ {
+ vec.push(&self.subcommands[idx]);
+ vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg));
+ }
+ }
+ vec
+ }
+
+ /// Report whether [`Command::no_binary_name`] is set
+ pub fn is_no_binary_name_set(&self) -> bool {
+ self.is_set(AppSettings::NoBinaryName)
+ }
+
+ /// Report whether [`Command::ignore_errors`] is set
+ pub(crate) fn is_ignore_errors_set(&self) -> bool {
+ self.is_set(AppSettings::IgnoreErrors)
+ }
+
+ /// Report whether [`Command::dont_delimit_trailing_values`] is set
+ pub fn is_dont_delimit_trailing_values_set(&self) -> bool {
+ self.is_set(AppSettings::DontDelimitTrailingValues)
+ }
+
+ /// Report whether [`Command::disable_version_flag`] is set
+ pub fn is_disable_version_flag_set(&self) -> bool {
+ self.is_set(AppSettings::DisableVersionFlag)
+ || (self.version.is_none() && self.long_version.is_none())
+ }
+
+ /// Report whether [`Command::propagate_version`] is set
+ pub fn is_propagate_version_set(&self) -> bool {
+ self.is_set(AppSettings::PropagateVersion)
+ }
+
+ /// Report whether [`Command::next_line_help`] is set
+ pub fn is_next_line_help_set(&self) -> bool {
+ self.is_set(AppSettings::NextLineHelp)
+ }
+
+ /// Report whether [`Command::disable_help_flag`] is set
+ pub fn is_disable_help_flag_set(&self) -> bool {
+ self.is_set(AppSettings::DisableHelpFlag)
+ }
+
+ /// Report whether [`Command::disable_help_subcommand`] is set
+ pub fn is_disable_help_subcommand_set(&self) -> bool {
+ self.is_set(AppSettings::DisableHelpSubcommand)
+ }
+
+ /// Report whether [`Command::disable_colored_help`] is set
+ pub fn is_disable_colored_help_set(&self) -> bool {
+ self.is_set(AppSettings::DisableColoredHelp)
+ }
+
+ /// Report whether [`Command::help_expected`] is set
+ #[cfg(debug_assertions)]
+ pub(crate) fn is_help_expected_set(&self) -> bool {
+ self.is_set(AppSettings::HelpExpected)
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "This is now the default")
+ )]
+ pub fn is_dont_collapse_args_in_usage_set(&self) -> bool {
+ true
+ }
+
+ /// Report whether [`Command::infer_long_args`] is set
+ pub(crate) fn is_infer_long_args_set(&self) -> bool {
+ self.is_set(AppSettings::InferLongArgs)
+ }
+
+ /// Report whether [`Command::infer_subcommands`] is set
+ pub(crate) fn is_infer_subcommands_set(&self) -> bool {
+ self.is_set(AppSettings::InferSubcommands)
+ }
+
+ /// Report whether [`Command::arg_required_else_help`] is set
+ pub fn is_arg_required_else_help_set(&self) -> bool {
+ self.is_set(AppSettings::ArgRequiredElseHelp)
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "4.0.0",
+ note = "Replaced with `Arg::is_allow_hyphen_values_set`"
+ )
+ )]
+ pub(crate) fn is_allow_hyphen_values_set(&self) -> bool {
+ self.is_set(AppSettings::AllowHyphenValues)
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(
+ since = "4.0.0",
+ note = "Replaced with `Arg::is_allow_negative_numbers_set`"
+ )
+ )]
+ pub fn is_allow_negative_numbers_set(&self) -> bool {
+ self.is_set(AppSettings::AllowNegativeNumbers)
+ }
+
+ #[doc(hidden)]
+ #[cfg_attr(
+ feature = "deprecated",
+ deprecated(since = "4.0.0", note = "Replaced with `Arg::is_trailing_var_arg_set`")
+ )]
+ pub fn is_trailing_var_arg_set(&self) -> bool {
+ self.is_set(AppSettings::TrailingVarArg)
+ }
+
+ /// Report whether [`Command::allow_missing_positional`] is set
+ pub fn is_allow_missing_positional_set(&self) -> bool {
+ self.is_set(AppSettings::AllowMissingPositional)
+ }
+
+ /// Report whether [`Command::hide`] is set
+ pub fn is_hide_set(&self) -> bool {
+ self.is_set(AppSettings::Hidden)
+ }
+
+ /// Report whether [`Command::subcommand_required`] is set
+ pub fn is_subcommand_required_set(&self) -> bool {
+ self.is_set(AppSettings::SubcommandRequired)
+ }
+
+ /// Report whether [`Command::allow_external_subcommands`] is set
+ pub fn is_allow_external_subcommands_set(&self) -> bool {
+ self.is_set(AppSettings::AllowExternalSubcommands)
+ }
+
+ /// Configured parser for values passed to an external subcommand
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// let cmd = clap::Command::new("raw")
+ /// .external_subcommand_value_parser(clap::value_parser!(String));
+ /// let value_parser = cmd.get_external_subcommand_value_parser();
+ /// println!("{:?}", value_parser);
+ /// ```
+ pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> {
+ if !self.is_allow_external_subcommands_set() {
+ None
+ } else {
+ static DEFAULT: super::ValueParser = super::ValueParser::os_string();
+ Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT))
+ }
+ }
+
+ /// Report whether [`Command::args_conflicts_with_subcommands`] is set
+ pub fn is_args_conflicts_with_subcommands_set(&self) -> bool {
+ self.is_set(AppSettings::ArgsNegateSubcommands)
+ }
+
+ #[doc(hidden)]
+ pub fn is_args_override_self(&self) -> bool {
+ self.is_set(AppSettings::AllArgsOverrideSelf)
+ }
+
+ /// Report whether [`Command::subcommand_precedence_over_arg`] is set
+ pub fn is_subcommand_precedence_over_arg_set(&self) -> bool {
+ self.is_set(AppSettings::SubcommandPrecedenceOverArg)
+ }
+
+ /// Report whether [`Command::subcommand_negates_reqs`] is set
+ pub fn is_subcommand_negates_reqs_set(&self) -> bool {
+ self.is_set(AppSettings::SubcommandsNegateReqs)
+ }
+
+ /// Report whether [`Command::multicall`] is set
+ pub fn is_multicall_set(&self) -> bool {
+ self.is_set(AppSettings::Multicall)
+ }
+}
+
+// Internally used only
+impl Command {
+ pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> {
+ self.usage_str.as_ref()
+ }
+
+ pub(crate) fn get_override_help(&self) -> Option<&StyledStr> {
+ self.help_str.as_ref()
+ }
+
+ #[cfg(feature = "help")]
+ pub(crate) fn get_help_template(&self) -> Option<&StyledStr> {
+ self.template.as_ref()
+ }
+
+ #[cfg(feature = "help")]
+ pub(crate) fn get_term_width(&self) -> Option<usize> {
+ self.term_w
+ }
+
+ #[cfg(feature = "help")]
+ pub(crate) fn get_max_term_width(&self) -> Option<usize> {
+ self.max_w
+ }
+
+ pub(crate) fn get_replacement(&self, key: &str) -> Option<&[Str]> {
+ self.replacers.get(key).map(|v| v.as_slice())
+ }
+
+ pub(crate) fn get_keymap(&self) -> &MKeyMap {
+ &self.args
+ }
+
+ fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) {
+ global_arg_vec.extend(
+ self.args
+ .args()
+ .filter(|a| a.is_global_set())
+ .map(|ga| ga.id.clone()),
+ );
+ if let Some((id, matches)) = matches.subcommand() {
+ if let Some(used_sub) = self.find_subcommand(id) {
+ used_sub.get_used_global_args(matches, global_arg_vec);
+ }
+ }
+ }
+
+ fn _do_parse(
+ &mut self,
+ raw_args: &mut clap_lex::RawArgs,
+ args_cursor: clap_lex::ArgCursor,
+ ) -> ClapResult<ArgMatches> {
+ debug!("Command::_do_parse");
+
+ // If there are global arguments, or settings we need to propagate them down to subcommands
+ // before parsing in case we run into a subcommand
+ self._build_self(false);
+
+ let mut matcher = ArgMatcher::new(self);
+
+ // do the real parsing
+ let mut parser = Parser::new(self);
+ if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) {
+ if self.is_set(AppSettings::IgnoreErrors) {
+ debug!("Command::_do_parse: ignoring error: {}", error);
+ } else {
+ return Err(error);
+ }
+ }
+
+ let mut global_arg_vec = Default::default();
+ self.get_used_global_args(&matcher, &mut global_arg_vec);
+
+ matcher.propagate_globals(&global_arg_vec);
+
+ Ok(matcher.into_inner())
+ }
+
+ /// Prepare for introspecting on all included [`Command`]s
+ ///
+ /// Call this on the top-level [`Command`] when done building and before reading state for
+ /// cases like completions, custom help output, etc.
+ pub fn build(&mut self) {
+ self._build_recursive(true);
+ self._build_bin_names_internal();
+ }
+
+ pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) {
+ self._build_self(expand_help_tree);
+ for subcmd in self.get_subcommands_mut() {
+ subcmd._build_recursive(expand_help_tree);
+ }
+ }
+
+ pub(crate) fn _build_self(&mut self, expand_help_tree: bool) {
+ debug!("Command::_build: name={:?}", self.get_name());
+ if !self.settings.is_set(AppSettings::Built) {
+ // Make sure all the globally set flags apply to us as well
+ self.settings = self.settings | self.g_settings;
+
+ if self.is_multicall_set() {
+ self.settings.insert(AppSettings::SubcommandRequired.into());
+ self.settings.insert(AppSettings::DisableHelpFlag.into());
+ self.settings.insert(AppSettings::DisableVersionFlag.into());
+ }
+ if !cfg!(feature = "help") && self.get_override_help().is_none() {
+ self.settings.insert(AppSettings::DisableHelpFlag.into());
+ self.settings
+ .insert(AppSettings::DisableHelpSubcommand.into());
+ }
+ if self.is_set(AppSettings::ArgsNegateSubcommands) {
+ self.settings
+ .insert(AppSettings::SubcommandsNegateReqs.into());
+ }
+ if self.external_value_parser.is_some() {
+ self.settings
+ .insert(AppSettings::AllowExternalSubcommands.into());
+ }
+ if !self.has_subcommands() {
+ self.settings
+ .insert(AppSettings::DisableHelpSubcommand.into());
+ }
+
+ self._propagate();
+ self._check_help_and_version(expand_help_tree);
+ self._propagate_global_args();
+
+ let mut pos_counter = 1;
+ let hide_pv = self.is_set(AppSettings::HidePossibleValues);
+ for a in self.args.args_mut() {
+ // Fill in the groups
+ for g in &a.groups {
+ if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) {
+ ag.args.push(a.get_id().clone());
+ } else {
+ let mut ag = ArgGroup::new(g);
+ ag.args.push(a.get_id().clone());
+ self.groups.push(ag);
+ }
+ }
+
+ // Figure out implied settings
+ a._build();
+ if hide_pv && a.is_takes_value_set() {
+ a.settings.set(ArgSettings::HidePossibleValues);
+ }
+ if a.is_positional() && a.index.is_none() {
+ a.index = Some(pos_counter);
+ pos_counter += 1;
+ }
+ }
+
+ self.args._build();
+
+ #[allow(deprecated)]
+ {
+ let highest_idx = self
+ .get_keymap()
+ .keys()
+ .filter_map(|x| {
+ if let crate::mkeymap::KeyType::Position(n) = x {
+ Some(*n)
+ } else {
+ None
+ }
+ })
+ .max()
+ .unwrap_or(0);
+ let is_trailing_var_arg_set = self.is_trailing_var_arg_set();
+ let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set();
+ let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set();
+ for arg in self.args.args_mut() {
+ if is_allow_hyphen_values_set && arg.is_takes_value_set() {
+ arg.settings.insert(ArgSettings::AllowHyphenValues.into());
+ }
+ if is_allow_negative_numbers_set && arg.is_takes_value_set() {
+ arg.settings
+ .insert(ArgSettings::AllowNegativeNumbers.into());
+ }
+ if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) {
+ arg.settings.insert(ArgSettings::TrailingVarArg.into());
+ }
+ }
+ }
+
+ #[cfg(debug_assertions)]
+ assert_app(self);
+ self.settings.set(AppSettings::Built);
+ } else {
+ debug!("Command::_build: already built");
+ }
+ }
+
+ pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> {
+ use std::fmt::Write;
+
+ let mut mid_string = String::from(" ");
+ #[cfg(feature = "usage")]
+ 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 {
+ mid_string.push_str(&s.to_string());
+ mid_string.push(' ');
+ }
+ }
+ let is_multicall_set = self.is_multicall_set();
+
+ let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name));
+
+ // Display subcommand name, short and long in usage
+ let mut sc_names = String::new();
+ sc_names.push_str(sc.name.as_str());
+ let mut flag_subcmd = false;
+ if let Some(l) = sc.get_long_flag() {
+ write!(sc_names, "|--{l}").unwrap();
+ flag_subcmd = true;
+ }
+ if let Some(s) = sc.get_short_flag() {
+ write!(sc_names, "|-{s}").unwrap();
+ flag_subcmd = true;
+ }
+
+ if flag_subcmd {
+ sc_names = format!("{{{sc_names}}}");
+ }
+
+ let usage_name = self
+ .bin_name
+ .as_ref()
+ .map(|bin_name| format!("{bin_name}{mid_string}{sc_names}"))
+ .unwrap_or(sc_names);
+ sc.usage_name = Some(usage_name);
+
+ // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
+ // a space
+ let bin_name = format!(
+ "{}{}{}",
+ self.bin_name.as_deref().unwrap_or_default(),
+ if self.bin_name.is_some() { " " } else { "" },
+ &*sc.name
+ );
+ debug!(
+ "Command::_build_subcommand Setting bin_name of {} to {:?}",
+ sc.name, bin_name
+ );
+ sc.bin_name = Some(bin_name);
+
+ if sc.display_name.is_none() {
+ let self_display_name = if is_multicall_set {
+ self.display_name.as_deref().unwrap_or("")
+ } else {
+ self.display_name.as_deref().unwrap_or(&self.name)
+ };
+ let display_name = format!(
+ "{}{}{}",
+ self_display_name,
+ if !self_display_name.is_empty() {
+ "-"
+ } else {
+ ""
+ },
+ &*sc.name
+ );
+ debug!(
+ "Command::_build_subcommand Setting display_name of {} to {:?}",
+ sc.name, display_name
+ );
+ sc.display_name = Some(display_name);
+ }
+
+ // Ensure all args are built and ready to parse
+ sc._build_self(false);
+
+ Some(sc)
+ }
+
+ fn _build_bin_names_internal(&mut self) {
+ debug!("Command::_build_bin_names");
+
+ if !self.is_set(AppSettings::BinNameBuilt) {
+ let mut mid_string = String::from(" ");
+ #[cfg(feature = "usage")]
+ 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 {
+ mid_string.push_str(&s.to_string());
+ mid_string.push(' ');
+ }
+ }
+ let is_multicall_set = self.is_multicall_set();
+
+ let self_bin_name = if is_multicall_set {
+ self.bin_name.as_deref().unwrap_or("")
+ } else {
+ self.bin_name.as_deref().unwrap_or(&self.name)
+ }
+ .to_owned();
+
+ for mut sc in &mut self.subcommands {
+ debug!("Command::_build_bin_names:iter: bin_name set...");
+
+ if sc.usage_name.is_none() {
+ use std::fmt::Write;
+ // Display subcommand name, short and long in usage
+ let mut sc_names = String::new();
+ sc_names.push_str(sc.name.as_str());
+ let mut flag_subcmd = false;
+ if let Some(l) = sc.get_long_flag() {
+ write!(sc_names, "|--{l}").unwrap();
+ flag_subcmd = true;
+ }
+ if let Some(s) = sc.get_short_flag() {
+ write!(sc_names, "|-{s}").unwrap();
+ flag_subcmd = true;
+ }
+
+ if flag_subcmd {
+ sc_names = format!("{{{sc_names}}}");
+ }
+
+ let usage_name = format!("{self_bin_name}{mid_string}{sc_names}");
+ debug!(
+ "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
+ sc.name, usage_name
+ );
+ sc.usage_name = Some(usage_name);
+ } else {
+ debug!(
+ "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
+ sc.name, sc.usage_name
+ );
+ }
+
+ if sc.bin_name.is_none() {
+ let bin_name = format!(
+ "{}{}{}",
+ self_bin_name,
+ if !self_bin_name.is_empty() { " " } else { "" },
+ &*sc.name
+ );
+ debug!(
+ "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
+ sc.name, bin_name
+ );
+ sc.bin_name = Some(bin_name);
+ } else {
+ debug!(
+ "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
+ sc.name, sc.bin_name
+ );
+ }
+
+ if sc.display_name.is_none() {
+ let self_display_name = if is_multicall_set {
+ self.display_name.as_deref().unwrap_or("")
+ } else {
+ self.display_name.as_deref().unwrap_or(&self.name)
+ };
+ let display_name = format!(
+ "{}{}{}",
+ self_display_name,
+ if !self_display_name.is_empty() {
+ "-"
+ } else {
+ ""
+ },
+ &*sc.name
+ );
+ debug!(
+ "Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
+ sc.name, display_name
+ );
+ sc.display_name = Some(display_name);
+ } else {
+ debug!(
+ "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
+ sc.name, sc.display_name
+ );
+ }
+
+ sc._build_bin_names_internal();
+ }
+ self.set(AppSettings::BinNameBuilt);
+ } else {
+ debug!("Command::_build_bin_names: already built");
+ }
+ }
+
+ pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) {
+ if self.is_set(AppSettings::HelpExpected) || help_required_globally {
+ let args_missing_help: Vec<Id> = self
+ .args
+ .args()
+ .filter(|arg| arg.get_help().is_none() && arg.get_long_help().is_none())
+ .map(|arg| arg.get_id().clone())
+ .collect();
+
+ debug_assert!(args_missing_help.is_empty(),
+ "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}",
+ self.name,
+ args_missing_help.join(", ")
+ );
+ }
+
+ for sub_app in &self.subcommands {
+ sub_app._panic_on_missing_help(help_required_globally);
+ }
+ }
+
+ #[cfg(debug_assertions)]
+ pub(crate) fn two_args_of<F>(&self, condition: F) -> Option<(&Arg, &Arg)>
+ where
+ F: Fn(&Arg) -> bool,
+ {
+ two_elements_of(self.args.args().filter(|a: &&Arg| condition(a)))
+ }
+
+ // just in case
+ #[allow(unused)]
+ fn two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)>
+ where
+ F: Fn(&ArgGroup) -> bool,
+ {
+ two_elements_of(self.groups.iter().filter(|a| condition(a)))
+ }
+
+ /// Propagate global args
+ pub(crate) fn _propagate_global_args(&mut self) {
+ debug!("Command::_propagate_global_args:{}", self.name);
+
+ let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set();
+
+ for sc in &mut self.subcommands {
+ if sc.get_name() == "help" && autogenerated_help_subcommand {
+ // Avoid propagating args to the autogenerated help subtrees used in completion.
+ // This prevents args from showing up during help completions like
+ // `myapp help subcmd <TAB>`, which should only suggest subcommands and not args,
+ // while still allowing args to show up properly on the generated help message.
+ continue;
+ }
+
+ for a in self.args.args().filter(|a| a.is_global_set()) {
+ if sc.find(&a.id).is_some() {
+ debug!(
+ "Command::_propagate skipping {:?} to {}, already exists",
+ a.id,
+ sc.get_name(),
+ );
+ continue;
+ }
+
+ debug!(
+ "Command::_propagate pushing {:?} to {}",
+ a.id,
+ sc.get_name(),
+ );
+ sc.args.push(a.clone());
+ }
+ }
+ }
+
+ /// Propagate settings
+ pub(crate) fn _propagate(&mut self) {
+ debug!("Command::_propagate:{}", self.name);
+ let mut subcommands = std::mem::take(&mut self.subcommands);
+ for sc in &mut subcommands {
+ self._propagate_subcommand(sc);
+ }
+ self.subcommands = subcommands;
+ }
+
+ fn _propagate_subcommand(&self, sc: &mut Self) {
+ // We have to create a new scope in order to tell rustc the borrow of `sc` is
+ // done and to recursively call this method
+ {
+ if self.settings.is_set(AppSettings::PropagateVersion) {
+ if let Some(version) = self.version.as_ref() {
+ sc.version.get_or_insert_with(|| version.clone());
+ }
+ if let Some(long_version) = self.long_version.as_ref() {
+ sc.long_version.get_or_insert_with(|| long_version.clone());
+ }
+ }
+
+ sc.settings = sc.settings | self.g_settings;
+ sc.g_settings = sc.g_settings | self.g_settings;
+ sc.term_w = self.term_w;
+ sc.max_w = self.max_w;
+ }
+ }
+
+ pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) {
+ debug!(
+ "Command::_check_help_and_version:{} expand_help_tree={}",
+ self.name, expand_help_tree
+ );
+
+ self.long_help_exists = self.long_help_exists_();
+
+ if !self.is_disable_help_flag_set() {
+ debug!("Command::_check_help_and_version: Building default --help");
+ let mut arg = Arg::new(Id::HELP)
+ .short('h')
+ .long("help")
+ .action(ArgAction::Help);
+ if self.long_help_exists {
+ arg = arg
+ .help("Print help (see more with '--help')")
+ .long_help("Print help (see a summary with '-h')");
+ } else {
+ arg = arg.help("Print help");
+ }
+ // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
+ // `next_display_order`
+ self.args.push(arg);
+ }
+ if !self.is_disable_version_flag_set() {
+ debug!("Command::_check_help_and_version: Building default --version");
+ let arg = Arg::new(Id::VERSION)
+ .short('V')
+ .long("version")
+ .action(ArgAction::Version)
+ .help("Print version");
+ // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
+ // `next_display_order`
+ self.args.push(arg);
+ }
+
+ if !self.is_set(AppSettings::DisableHelpSubcommand) {
+ debug!("Command::_check_help_and_version: Building help subcommand");
+ let help_about = "Print this message or the help of the given subcommand(s)";
+
+ 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")
+ .about(help_about)
+ .global_setting(AppSettings::DisableHelpSubcommand)
+ .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));
+
+ let mut help_help_subcmd = Command::new("help").about(help_about);
+ help_help_subcmd.version = None;
+ help_help_subcmd.long_version = None;
+ help_help_subcmd = help_help_subcmd
+ .setting(AppSettings::DisableHelpFlag)
+ .setting(AppSettings::DisableVersionFlag);
+
+ help_subcmd.subcommand(help_help_subcmd)
+ } else {
+ Command::new("help").about(help_about).arg(
+ Arg::new("subcommand")
+ .action(ArgAction::Append)
+ .num_args(..)
+ .value_name("COMMAND")
+ .help("Print help for the subcommand(s)"),
+ )
+ };
+ self._propagate_subcommand(&mut help_subcmd);
+
+ // The parser acts like this is set, so let's set it so we don't falsely
+ // advertise it to the user
+ help_subcmd.version = None;
+ help_subcmd.long_version = None;
+ help_subcmd = help_subcmd
+ .setting(AppSettings::DisableHelpFlag)
+ .setting(AppSettings::DisableVersionFlag)
+ .unset_global_setting(AppSettings::PropagateVersion);
+
+ self.subcommands.push(help_subcmd);
+ }
+ }
+
+ fn _copy_subtree_for_help(&self) -> Command {
+ let mut cmd = Command::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));
+ if self.get_about().is_some() {
+ cmd = cmd.about(self.get_about().unwrap().clone());
+ }
+ cmd
+ }
+
+ pub(crate) fn _render_version(&self, use_long: bool) -> String {
+ debug!("Command::_render_version");
+
+ let ver = if use_long {
+ self.long_version
+ .as_deref()
+ .or(self.version.as_deref())
+ .unwrap_or_default()
+ } else {
+ self.version
+ .as_deref()
+ .or(self.long_version.as_deref())
+ .unwrap_or_default()
+ };
+ let display_name = self.get_display_name().unwrap_or_else(|| self.get_name());
+ format!("{display_name} {ver}\n")
+ }
+
+ pub(crate) fn format_group(&self, g: &Id) -> StyledStr {
+ let g_string = self
+ .unroll_args_in_group(g)
+ .iter()
+ .filter_map(|x| self.find(x))
+ .map(|x| {
+ if x.is_positional() {
+ // Print val_name for positional arguments. e.g. <file_name>
+ x.name_no_brackets()
+ } else {
+ // Print usage string for flags arguments, e.g. <--help>
+ x.to_string()
+ }
+ })
+ .collect::<Vec<_>>()
+ .join("|");
+ let mut styled = StyledStr::new();
+ styled.none("<");
+ styled.none(g_string);
+ styled.none(">");
+ styled
+ }
+}
+
+/// A workaround:
+/// <https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999>
+pub(crate) trait Captures<'a> {}
+impl<'a, T> Captures<'a> for T {}
+
+// Internal Query Methods
+impl Command {
+ /// Iterate through the *flags* & *options* arguments.
+ #[cfg(any(feature = "usage", feature = "help"))]
+ pub(crate) fn get_non_positionals(&self) -> impl Iterator<Item = &Arg> {
+ self.get_arguments().filter(|a| !a.is_positional())
+ }
+
+ pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg> {
+ self.args.args().find(|a| a.get_id() == arg_id)
+ }
+
+ #[inline]
+ pub(crate) fn contains_short(&self, s: char) -> bool {
+ debug_assert!(
+ self.is_set(AppSettings::Built),
+ "If Command::_build hasn't been called, manually search through Arg shorts"
+ );
+
+ self.args.contains(s)
+ }
+
+ #[inline]
+ pub(crate) fn set(&mut self, s: AppSettings) {
+ self.settings.set(s)
+ }
+
+ #[inline]
+ pub(crate) fn has_positionals(&self) -> bool {
+ self.get_positionals().next().is_some()
+ }
+
+ #[cfg(any(feature = "usage", feature = "help"))]
+ pub(crate) fn has_visible_subcommands(&self) -> bool {
+ self.subcommands
+ .iter()
+ .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden))
+ }
+
+ /// Check if this subcommand can be referred to as `name`. In other words,
+ /// check if `name` is the name of this subcommand or is one of its aliases.
+ #[inline]
+ pub(crate) fn aliases_to(&self, name: impl AsRef<std::ffi::OsStr>) -> bool {
+ let name = name.as_ref();
+ self.get_name() == name || self.get_all_aliases().any(|alias| alias == name)
+ }
+
+ /// Check if this subcommand can be referred to as `name`. In other words,
+ /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases.
+ #[inline]
+ pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool {
+ Some(flag) == self.short_flag
+ || self.get_all_short_flag_aliases().any(|alias| flag == alias)
+ }
+
+ /// Check if this subcommand can be referred to as `name`. In other words,
+ /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases.
+ #[inline]
+ pub(crate) fn long_flag_aliases_to(&self, flag: &str) -> bool {
+ match self.long_flag.as_ref() {
+ Some(long_flag) => {
+ long_flag == flag || self.get_all_long_flag_aliases().any(|alias| alias == flag)
+ }
+ None => self.get_all_long_flag_aliases().any(|alias| alias == flag),
+ }
+ }
+
+ #[cfg(debug_assertions)]
+ pub(crate) fn id_exists(&self, id: &Id) -> bool {
+ self.args.args().any(|x| x.get_id() == id) || self.groups.iter().any(|x| x.id == *id)
+ }
+
+ /// Iterate through the groups this arg is member of.
+ pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a {
+ debug!("Command::groups_for_arg: id={:?}", arg);
+ let arg = arg.clone();
+ self.groups
+ .iter()
+ .filter(move |grp| grp.args.iter().any(|a| a == &arg))
+ .map(|grp| grp.id.clone())
+ }
+
+ pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup> {
+ self.groups.iter().find(|g| g.id == *group_id)
+ }
+
+ /// Iterate through all the names of all subcommands (not recursively), including aliases.
+ /// Used for suggestions.
+ pub(crate) fn all_subcommand_names(&self) -> impl Iterator<Item = &str> + Captures {
+ self.get_subcommands().flat_map(|sc| {
+ let name = sc.get_name();
+ let aliases = sc.get_all_aliases();
+ std::iter::once(name).chain(aliases)
+ })
+ }
+
+ pub(crate) fn required_graph(&self) -> ChildGraph<Id> {
+ let mut reqs = ChildGraph::with_capacity(5);
+ for a in self.args.args().filter(|a| a.is_required_set()) {
+ reqs.insert(a.get_id().clone());
+ }
+ for group in &self.groups {
+ if group.required {
+ let idx = reqs.insert(group.id.clone());
+ for a in &group.requires {
+ reqs.insert_child(idx, a.clone());
+ }
+ }
+ }
+
+ reqs
+ }
+
+ pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec<Id> {
+ debug!("Command::unroll_args_in_group: group={:?}", group);
+ let mut g_vec = vec![group];
+ let mut args = vec![];
+
+ while let Some(g) = g_vec.pop() {
+ for n in self
+ .groups
+ .iter()
+ .find(|grp| grp.id == *g)
+ .expect(INTERNAL_ERROR_MSG)
+ .args
+ .iter()
+ {
+ debug!("Command::unroll_args_in_group:iter: entity={:?}", n);
+ if !args.contains(n) {
+ if self.find(n).is_some() {
+ debug!("Command::unroll_args_in_group:iter: this is an arg");
+ args.push(n.clone())
+ } else {
+ debug!("Command::unroll_args_in_group:iter: this is a group");
+ g_vec.push(n);
+ }
+ }
+ }
+ }
+
+ args
+ }
+
+ pub(crate) fn unroll_arg_requires<F>(&self, func: F, arg: &Id) -> Vec<Id>
+ where
+ F: Fn(&(ArgPredicate, Id)) -> Option<Id>,
+ {
+ let mut processed = vec![];
+ let mut r_vec = vec![arg];
+ let mut args = vec![];
+
+ while let Some(a) = r_vec.pop() {
+ if processed.contains(&a) {
+ continue;
+ }
+
+ processed.push(a);
+
+ if let Some(arg) = self.find(a) {
+ for r in arg.requires.iter().filter_map(&func) {
+ if let Some(req) = self.find(&r) {
+ if !req.requires.is_empty() {
+ r_vec.push(req.get_id())
+ }
+ }
+ args.push(r);
+ }
+ }
+ }
+
+ args
+ }
+
+ /// Find a flag subcommand name by short flag or an alias
+ pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> {
+ self.get_subcommands()
+ .find(|sc| sc.short_flag_aliases_to(c))
+ .map(|sc| sc.get_name())
+ }
+
+ /// Find a flag subcommand name by long flag or an alias
+ pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> {
+ self.get_subcommands()
+ .find(|sc| sc.long_flag_aliases_to(long))
+ .map(|sc| sc.get_name())
+ }
+
+ #[cfg(feature = "help")]
+ pub(crate) fn get_display_order(&self) -> usize {
+ self.disp_ord.unwrap_or(999)
+ }
+
+ pub(crate) fn write_help_err(&self, mut use_long: bool) -> StyledStr {
+ debug!(
+ "Command::write_help_err: {}, use_long={:?}",
+ self.get_display_name().unwrap_or_else(|| self.get_name()),
+ use_long && self.long_help_exists(),
+ );
+
+ use_long = use_long && self.long_help_exists();
+ let usage = Usage::new(self);
+
+ let mut styled = StyledStr::new();
+ write_help(&mut styled, self, &usage, use_long);
+
+ styled
+ }
+
+ pub(crate) fn write_version_err(&self, use_long: bool) -> StyledStr {
+ let msg = self._render_version(use_long);
+ let mut styled = StyledStr::new();
+ styled.none(msg);
+ styled
+ }
+
+ pub(crate) fn long_help_exists(&self) -> bool {
+ debug!("Command::long_help_exists: {}", self.long_help_exists);
+ self.long_help_exists
+ }
+
+ fn long_help_exists_(&self) -> bool {
+ debug!("Command::long_help_exists");
+ // In this case, both must be checked. This allows the retention of
+ // original formatting, but also ensures that the actual -h or --help
+ // specified by the user is sent through. If hide_short_help is not included,
+ // then items specified with hidden_short_help will also be hidden.
+ let should_long = |v: &Arg| {
+ !v.is_hide_set()
+ && (v.get_long_help().is_some()
+ || v.is_hide_long_help_set()
+ || v.is_hide_short_help_set()
+ || (!v.is_hide_possible_values_set()
+ && v.get_possible_values()
+ .iter()
+ .any(PossibleValue::should_show_help)))
+ };
+
+ // Subcommands aren't checked because we prefer short help for them, deferring to
+ // `cmd subcmd --help` for more.
+ self.get_long_about().is_some()
+ || self.get_before_long_help().is_some()
+ || self.get_after_long_help().is_some()
+ || self.get_arguments().any(should_long)
+ }
+
+ // Should we color the help?
+ pub(crate) fn color_help(&self) -> ColorChoice {
+ #[cfg(feature = "color")]
+ if self.is_disable_colored_help_set() {
+ return ColorChoice::Never;
+ }
+
+ self.get_color()
+ }
+}
+
+impl Default for Command {
+ fn default() -> Self {
+ Self {
+ name: Default::default(),
+ long_flag: Default::default(),
+ short_flag: Default::default(),
+ display_name: Default::default(),
+ bin_name: Default::default(),
+ author: Default::default(),
+ version: Default::default(),
+ long_version: Default::default(),
+ about: Default::default(),
+ long_about: Default::default(),
+ before_help: Default::default(),
+ before_long_help: Default::default(),
+ after_help: Default::default(),
+ after_long_help: Default::default(),
+ aliases: Default::default(),
+ short_flag_aliases: Default::default(),
+ long_flag_aliases: Default::default(),
+ usage_str: Default::default(),
+ usage_name: Default::default(),
+ help_str: Default::default(),
+ disp_ord: Default::default(),
+ term_w: Default::default(),
+ max_w: Default::default(),
+ #[cfg(feature = "help")]
+ template: Default::default(),
+ settings: Default::default(),
+ g_settings: Default::default(),
+ args: Default::default(),
+ subcommands: Default::default(),
+ replacers: Default::default(),
+ groups: Default::default(),
+ current_help_heading: Default::default(),
+ current_disp_ord: Some(0),
+ subcommand_value_name: Default::default(),
+ subcommand_heading: Default::default(),
+ external_value_parser: Default::default(),
+ long_help_exists: false,
+ }
+ }
+}
+
+impl Index<&'_ Id> for Command {
+ type Output = Arg;
+
+ fn index(&self, key: &Id) -> &Self::Output {
+ self.find(key).expect(INTERNAL_ERROR_MSG)
+ }
+}
+
+impl From<&'_ Command> for Command {
+ fn from(cmd: &'_ Command) -> Self {
+ cmd.clone()
+ }
+}
+
+impl fmt::Display for Command {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "{}", self.name)
+ }
+}
+
+fn two_elements_of<I, T>(mut iter: I) -> Option<(T, T)>
+where
+ I: Iterator<Item = T>,
+{
+ let first = iter.next();
+ let second = iter.next();
+
+ match (first, second) {
+ (Some(first), Some(second)) => Some((first, second)),
+ _ => None,
+ }
+}
+
+#[test]
+fn check_auto_traits() {
+ static_assertions::assert_impl_all!(Command: Send, Sync, Unpin);
+}
diff --git a/src/builder/debug_asserts.rs b/src/builder/debug_asserts.rs
new file mode 100644
index 0000000..86e3677
--- /dev/null
+++ b/src/builder/debug_asserts.rs
@@ -0,0 +1,876 @@
+use std::cmp::Ordering;
+
+use clap_lex::RawOsStr;
+
+use crate::builder::OsStr;
+use crate::builder::ValueRange;
+use crate::mkeymap::KeyType;
+use crate::util::FlatSet;
+use crate::util::Id;
+use crate::ArgAction;
+use crate::INTERNAL_ERROR_MSG;
+use crate::{Arg, Command, ValueHint};
+
+pub(crate) fn assert_app(cmd: &Command) {
+ debug!("Command::_debug_asserts");
+
+ let mut short_flags = vec![];
+ let mut long_flags = vec![];
+
+ // Invalid version flag settings
+ if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
+ // PropagateVersion is meaningless if there is no version
+ assert!(
+ !cmd.is_propagate_version_set(),
+ "Command {}: No version information via Command::version or Command::long_version to propagate",
+ cmd.get_name(),
+ );
+
+ // Used `Command::mut_arg("version", ..) but did not provide any version information to display
+ let version_needed = cmd
+ .get_arguments()
+ .filter(|x| matches!(x.get_action(), ArgAction::Version))
+ .map(|x| x.get_id())
+ .collect::<Vec<_>>();
+
+ assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
+ ,cmd.get_name()
+ );
+ }
+
+ for sc in cmd.get_subcommands() {
+ if let Some(s) = sc.get_short_flag().as_ref() {
+ short_flags.push(Flag::Command(format!("-{s}"), sc.get_name()));
+ }
+
+ for short_alias in sc.get_all_short_flag_aliases() {
+ short_flags.push(Flag::Command(format!("-{short_alias}"), sc.get_name()));
+ }
+
+ if let Some(l) = sc.get_long_flag().as_ref() {
+ assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
+ long_flags.push(Flag::Command(format!("--{l}"), sc.get_name()));
+ }
+
+ for long_alias in sc.get_all_long_flag_aliases() {
+ long_flags.push(Flag::Command(format!("--{long_alias}"), sc.get_name()));
+ }
+ }
+
+ for arg in cmd.get_arguments() {
+ assert_arg(arg);
+
+ assert!(
+ !cmd.is_multicall_set(),
+ "Command {}: Arguments like {} cannot be set on a multicall command",
+ cmd.get_name(),
+ arg.get_id()
+ );
+
+ if let Some(s) = arg.get_short() {
+ short_flags.push(Flag::Arg(format!("-{s}"), arg.get_id().as_str()));
+ }
+
+ for (short_alias, _) in &arg.short_aliases {
+ short_flags.push(Flag::Arg(format!("-{short_alias}"), arg.get_id().as_str()));
+ }
+
+ if let Some(l) = arg.get_long() {
+ assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
+ long_flags.push(Flag::Arg(format!("--{l}"), arg.get_id().as_str()));
+ }
+
+ for (long_alias, _) in &arg.aliases {
+ long_flags.push(Flag::Arg(format!("--{long_alias}"), arg.get_id().as_str()));
+ }
+
+ // Name conflicts
+ if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
+ panic!(
+ "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
+ cmd.get_name(),
+ arg.get_id(),
+ duplicate_tip(cmd, first, second),
+ );
+ }
+
+ // Long conflicts
+ if let Some(l) = arg.get_long() {
+ if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
+ panic!(
+ "Command {}: Long option names must be unique for each argument, \
+ but '--{}' is in use by both '{}' and '{}'{}",
+ cmd.get_name(),
+ l,
+ first.get_id(),
+ second.get_id(),
+ duplicate_tip(cmd, first, second)
+ )
+ }
+ }
+
+ // Short conflicts
+ if let Some(s) = arg.get_short() {
+ if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
+ panic!(
+ "Command {}: Short option names must be unique for each argument, \
+ but '-{}' is in use by both '{}' and '{}'{}",
+ cmd.get_name(),
+ s,
+ first.get_id(),
+ second.get_id(),
+ duplicate_tip(cmd, first, second),
+ )
+ }
+ }
+
+ // Index conflicts
+ if let Some(idx) = arg.index {
+ if let Some((first, second)) =
+ cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
+ {
+ panic!(
+ "Command {}: Argument '{}' has the same index as '{}' \
+ and they are both positional arguments\n\n\t \
+ Use `Arg::num_args(1..)` to allow one \
+ positional argument to take multiple values",
+ cmd.get_name(),
+ first.get_id(),
+ second.get_id()
+ )
+ }
+ }
+
+ // requires, r_if, r_unless
+ for req in &arg.requires {
+ assert!(
+ cmd.id_exists(&req.1),
+ "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
+ cmd.get_name(),
+ req.1,
+ arg.get_id(),
+ );
+ }
+
+ for req in &arg.r_ifs {
+ assert!(
+ !arg.is_required_set(),
+ "Argument {}: `required` conflicts with `required_if_eq*`",
+ arg.get_id()
+ );
+ assert!(
+ cmd.id_exists(&req.0),
+ "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
+ cmd.get_name(),
+ req.0,
+ arg.get_id()
+ );
+ }
+
+ for req in &arg.r_ifs_all {
+ assert!(
+ !arg.is_required_set(),
+ "Argument {}: `required` conflicts with `required_if_eq_all`",
+ arg.get_id()
+ );
+ assert!(
+ cmd.id_exists(&req.0),
+ "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
+ cmd.get_name(),
+ req.0,
+ arg.get_id()
+ );
+ }
+
+ for req in &arg.r_unless {
+ assert!(
+ !arg.is_required_set(),
+ "Argument {}: `required` conflicts with `required_unless*`",
+ arg.get_id()
+ );
+ assert!(
+ cmd.id_exists(req),
+ "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
+ cmd.get_name(),
+ req,
+ arg.get_id(),
+ );
+ }
+
+ for req in &arg.r_unless_all {
+ assert!(
+ !arg.is_required_set(),
+ "Argument {}: `required` conflicts with `required_unless*`",
+ arg.get_id()
+ );
+ assert!(
+ cmd.id_exists(req),
+ "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
+ cmd.get_name(),
+ req,
+ arg.get_id(),
+ );
+ }
+
+ // blacklist
+ for req in &arg.blacklist {
+ assert!(
+ cmd.id_exists(req),
+ "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
+ cmd.get_name(),
+ req,
+ arg.get_id(),
+ );
+ }
+
+ // overrides
+ for req in &arg.overrides {
+ assert!(
+ cmd.id_exists(req),
+ "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
+ cmd.get_name(),
+ req,
+ arg.get_id(),
+ );
+ }
+
+ if arg.is_last_set() {
+ assert!(
+ arg.get_long().is_none(),
+ "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
+ cmd.get_name(),
+ arg.get_id()
+ );
+ assert!(
+ arg.get_short().is_none(),
+ "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
+ cmd.get_name(),
+ arg.get_id()
+ );
+ }
+
+ assert!(
+ !(arg.is_required_set() && arg.is_global_set()),
+ "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
+ cmd.get_name(),
+ arg.get_id()
+ );
+
+ if arg.get_value_hint() == ValueHint::CommandWithArguments {
+ assert!(
+ arg.is_positional(),
+ "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
+ cmd.get_name(),
+ arg.get_id()
+ );
+
+ assert!(
+ arg.is_trailing_var_arg_set() || arg.is_last_set(),
+ "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
+ cmd.get_name(),
+ arg.get_id()
+ );
+ }
+ }
+
+ for group in cmd.get_groups() {
+ let derive_hint = if cfg!(feature = "derive") {
+ " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
+ } else {
+ ""
+ };
+
+ // Name conflicts
+ assert!(
+ cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
+ "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
+ cmd.get_name(),
+ group.get_id(),
+ derive_hint
+ );
+
+ // Groups should not have naming conflicts with Args
+ assert!(
+ !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
+ "Command {}: Argument group name '{}' must not conflict with argument name{}",
+ cmd.get_name(),
+ group.get_id(),
+ derive_hint
+ );
+
+ for arg in &group.args {
+ // Args listed inside groups should exist
+ assert!(
+ cmd.get_arguments().any(|x| x.get_id() == arg),
+ "Command {}: Argument group '{}' contains non-existent argument '{}'",
+ cmd.get_name(),
+ group.get_id(),
+ arg
+ );
+ }
+ }
+
+ // Conflicts between flags and subcommands
+
+ long_flags.sort_unstable();
+ short_flags.sort_unstable();
+
+ detect_duplicate_flags(&long_flags, "long");
+ detect_duplicate_flags(&short_flags, "short");
+
+ let mut subs = FlatSet::new();
+ for sc in cmd.get_subcommands() {
+ assert!(
+ subs.insert(sc.get_name()),
+ "Command {}: command name `{}` is duplicated",
+ cmd.get_name(),
+ sc.get_name()
+ );
+ for alias in sc.get_all_aliases() {
+ assert!(
+ subs.insert(alias),
+ "Command {}: command `{}` alias `{}` is duplicated",
+ cmd.get_name(),
+ sc.get_name(),
+ alias
+ );
+ }
+ }
+
+ _verify_positionals(cmd);
+
+ #[cfg(feature = "help")]
+ if let Some(help_template) = cmd.get_help_template() {
+ assert!(
+ !help_template.to_string().contains("{flags}"),
+ "Command {}: {}",
+ cmd.get_name(),
+ "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
+ );
+ assert!(
+ !help_template.to_string().contains("{unified}"),
+ "Command {}: {}",
+ cmd.get_name(),
+ "`{unified}` template variable was removed in clap3, use `{options}` instead"
+ );
+ #[cfg(feature = "unstable-v5")]
+ assert!(
+ !help_template.to_string().contains("{bin}"),
+ "Command {}: {}",
+ cmd.get_name(),
+ "`{bin}` template variable was removed in clap5, use `{name}` instead"
+ )
+ }
+
+ cmd._panic_on_missing_help(cmd.is_help_expected_set());
+ assert_app_flags(cmd);
+}
+
+fn duplicate_tip(cmd: &Command, first: &Arg, second: &Arg) -> &'static str {
+ if !cmd.is_disable_help_flag_set()
+ && (first.get_id() == Id::HELP || second.get_id() == Id::HELP)
+ {
+ " (call `cmd.disable_help_flag(true)` to remove the auto-generated `--help`)"
+ } else if !cmd.is_disable_version_flag_set()
+ && (first.get_id() == Id::VERSION || second.get_id() == Id::VERSION)
+ {
+ " (call `cmd.disable_version_flag(true)` to remove the auto-generated `--version`)"
+ } else {
+ ""
+ }
+}
+
+#[derive(Eq)]
+enum Flag<'a> {
+ Command(String, &'a str),
+ Arg(String, &'a str),
+}
+
+impl PartialEq for Flag<'_> {
+ fn eq(&self, other: &Flag) -> bool {
+ self.cmp(other) == Ordering::Equal
+ }
+}
+
+impl PartialOrd for Flag<'_> {
+ fn partial_cmp(&self, other: &Flag) -> Option<Ordering> {
+ use Flag::*;
+
+ match (self, other) {
+ (Command(s1, _), Command(s2, _))
+ | (Arg(s1, _), Arg(s2, _))
+ | (Command(s1, _), Arg(s2, _))
+ | (Arg(s1, _), Command(s2, _)) => {
+ if s1 == s2 {
+ Some(Ordering::Equal)
+ } else {
+ s1.partial_cmp(s2)
+ }
+ }
+ }
+ }
+}
+
+impl Ord for Flag<'_> {
+ fn cmp(&self, other: &Self) -> Ordering {
+ self.partial_cmp(other).unwrap()
+ }
+}
+
+fn detect_duplicate_flags(flags: &[Flag], short_or_long: &str) {
+ use Flag::*;
+
+ for (one, two) in find_duplicates(flags) {
+ match (one, two) {
+ (Command(flag, one), Command(_, another)) if one != another => panic!(
+ "the '{flag}' {short_or_long} flag is specified for both '{one}' and '{another}' subcommands"
+ ),
+
+ (Arg(flag, one), Arg(_, another)) if one != another => panic!(
+ "{short_or_long} option names must be unique, but '{flag}' is in use by both '{one}' and '{another}'"
+ ),
+
+ (Arg(flag, arg), Command(_, sub)) | (Command(flag, sub), Arg(_, arg)) => panic!(
+ "the '{flag}' {short_or_long} flag for the '{arg}' argument conflicts with the short flag \
+ for '{sub}' subcommand"
+ ),
+
+ _ => {}
+ }
+ }
+}
+
+/// Find duplicates in a sorted array.
+///
+/// The algorithm is simple: the array is sorted, duplicates
+/// must be placed next to each other, we can check only adjacent elements.
+fn find_duplicates<T: PartialEq>(slice: &[T]) -> impl Iterator<Item = (&T, &T)> {
+ slice.windows(2).filter_map(|w| {
+ if w[0] == w[1] {
+ Some((&w[0], &w[1]))
+ } else {
+ None
+ }
+ })
+}
+
+fn assert_app_flags(cmd: &Command) {
+ macro_rules! checker {
+ ($a:ident requires $($b:ident)|+) => {
+ if cmd.$a() {
+ let mut s = String::new();
+
+ $(
+ if !cmd.$b() {
+ use std::fmt::Write;
+ write!(&mut s, " AppSettings::{} is required when AppSettings::{} is set.\n", std::stringify!($b), std::stringify!($a)).unwrap();
+ }
+ )+
+
+ if !s.is_empty() {
+ panic!("{}", s)
+ }
+ }
+ };
+ ($a:ident conflicts $($b:ident)|+) => {
+ if cmd.$a() {
+ let mut s = String::new();
+
+ $(
+ if cmd.$b() {
+ use std::fmt::Write;
+ write!(&mut s, " AppSettings::{} conflicts with AppSettings::{}.\n", std::stringify!($b), std::stringify!($a)).unwrap();
+ }
+ )+
+
+ if !s.is_empty() {
+ panic!("{}\n{}", cmd.get_name(), s)
+ }
+ }
+ };
+ }
+
+ checker!(is_multicall_set conflicts is_no_binary_name_set);
+}
+
+#[cfg(debug_assertions)]
+fn _verify_positionals(cmd: &Command) -> bool {
+ debug!("Command::_verify_positionals");
+ // Because you must wait until all arguments have been supplied, this is the first chance
+ // to make assertions on positional argument indexes
+ //
+ // First we verify that the index highest supplied index, is equal to the number of
+ // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3
+ // but no 2)
+
+ let highest_idx = cmd
+ .get_keymap()
+ .keys()
+ .filter_map(|x| {
+ if let KeyType::Position(n) = x {
+ Some(*n)
+ } else {
+ None
+ }
+ })
+ .max()
+ .unwrap_or(0);
+
+ let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count();
+
+ assert!(
+ highest_idx == num_p,
+ "Found positional argument whose index is {highest_idx} but there \
+ are only {num_p} positional arguments defined",
+ );
+
+ for arg in cmd.get_arguments() {
+ if arg.index.unwrap_or(0) == highest_idx {
+ assert!(
+ !arg.is_trailing_var_arg_set() || !arg.is_last_set(),
+ "{}:{}: `Arg::trailing_var_arg` and `Arg::last` cannot be used together",
+ cmd.get_name(),
+ arg.get_id()
+ );
+
+ if arg.is_trailing_var_arg_set() {
+ assert!(
+ arg.is_multiple(),
+ "{}:{}: `Arg::trailing_var_arg` must accept multiple values",
+ cmd.get_name(),
+ arg.get_id()
+ );
+ }
+ } else {
+ assert!(
+ !arg.is_trailing_var_arg_set(),
+ "{}:{}: `Arg::trailing_var_arg` can only apply to last positional",
+ cmd.get_name(),
+ arg.get_id()
+ );
+ }
+ }
+
+ // Next we verify that only the highest index has takes multiple arguments (if any)
+ let only_highest = |a: &Arg| a.is_multiple() && (a.get_index().unwrap_or(0) != highest_idx);
+ if cmd.get_positionals().any(only_highest) {
+ // First we make sure if there is a positional that allows multiple values
+ // the one before it (second to last) has one of these:
+ // * a value terminator
+ // * ArgSettings::Last
+ // * The last arg is Required
+
+ // We can't pass the closure (it.next()) to the macro directly because each call to
+ // find() (iterator, not macro) gets called repeatedly.
+ let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)];
+ let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)];
+
+ // Either the final positional is required
+ // Or the second to last has a terminator or .last(true) set
+ let ok = last.is_required_set()
+ || (second_to_last.terminator.is_some() || second_to_last.is_last_set())
+ || last.is_last_set();
+ assert!(
+ ok,
+ "When using a positional argument with `.num_args(1..)` that is *not the \
+ last* positional argument, the last positional argument (i.e. the one \
+ with the highest index) *must* have .required(true) or .last(true) set."
+ );
+
+ // We make sure if the second to last is Multiple the last is ArgSettings::Last
+ let ok = second_to_last.is_multiple() || last.is_last_set();
+ assert!(
+ ok,
+ "Only the last positional argument, or second to last positional \
+ argument may be set to `.num_args(1..)`"
+ );
+
+ // Next we check how many have both Multiple and not a specific number of values set
+ let count = cmd
+ .get_positionals()
+ .filter(|p| {
+ p.is_multiple_values_set()
+ && !p.get_num_args().expect(INTERNAL_ERROR_MSG).is_fixed()
+ })
+ .count();
+ let ok = count <= 1
+ || (last.is_last_set()
+ && last.is_multiple()
+ && second_to_last.is_multiple()
+ && count == 2);
+ assert!(
+ ok,
+ "Only one positional argument with `.num_args(1..)` set is allowed per \
+ command, unless the second one also has .last(true) set"
+ );
+ }
+
+ let mut found = false;
+
+ if cmd.is_allow_missing_positional_set() {
+ // Check that if a required positional argument is found, all positions with a lower
+ // index are also required.
+ let mut foundx2 = false;
+
+ for p in cmd.get_positionals() {
+ if foundx2 && !p.is_required_set() {
+ assert!(
+ p.is_required_set(),
+ "Found non-required positional argument with a lower \
+ index than a required positional argument by two or more: {:?} \
+ index {:?}",
+ p.get_id(),
+ p.get_index()
+ );
+ } else if p.is_required_set() && !p.is_last_set() {
+ // Args that .last(true) don't count since they can be required and have
+ // positionals with a lower index that aren't required
+ // Imagine: prog <req1> [opt1] -- <req2>
+ // Both of these are valid invocations:
+ // $ prog r1 -- r2
+ // $ prog r1 o1 -- r2
+ if found {
+ foundx2 = true;
+ continue;
+ }
+ found = true;
+ continue;
+ } else {
+ found = false;
+ }
+ }
+ } else {
+ // Check that if a required positional argument is found, all positions with a lower
+ // index are also required
+ for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) {
+ if found {
+ assert!(
+ p.is_required_set(),
+ "Found non-required positional argument with a lower \
+ index than a required positional argument: {:?} index {:?}",
+ p.get_id(),
+ p.get_index()
+ );
+ } else if p.is_required_set() && !p.is_last_set() {
+ // Args that .last(true) don't count since they can be required and have
+ // positionals with a lower index that aren't required
+ // Imagine: prog <req1> [opt1] -- <req2>
+ // Both of these are valid invocations:
+ // $ prog r1 -- r2
+ // $ prog r1 o1 -- r2
+ found = true;
+ continue;
+ }
+ }
+ }
+ assert!(
+ cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2,
+ "Only one positional argument may have last(true) set. Found two."
+ );
+ if cmd
+ .get_positionals()
+ .any(|p| p.is_last_set() && p.is_required_set())
+ && cmd.has_subcommands()
+ && !cmd.is_subcommand_negates_reqs_set()
+ {
+ panic!(
+ "Having a required positional argument with .last(true) set *and* child \
+ subcommands without setting SubcommandsNegateReqs isn't compatible."
+ );
+ }
+
+ true
+}
+
+fn assert_arg(arg: &Arg) {
+ debug!("Arg::_debug_asserts:{}", arg.get_id());
+
+ // Self conflict
+ // TODO: this check should be recursive
+ assert!(
+ !arg.blacklist.iter().any(|x| x == arg.get_id()),
+ "Argument '{}' cannot conflict with itself",
+ arg.get_id(),
+ );
+
+ assert_eq!(
+ arg.get_action().takes_values(),
+ arg.is_takes_value_set(),
+ "Argument `{}`'s selected action {:?} contradicts `takes_value`",
+ arg.get_id(),
+ arg.get_action()
+ );
+ if let Some(action_type_id) = arg.get_action().value_type_id() {
+ assert_eq!(
+ action_type_id,
+ arg.get_value_parser().type_id(),
+ "Argument `{}`'s selected action {:?} contradicts `value_parser` ({:?})",
+ arg.get_id(),
+ arg.get_action(),
+ arg.get_value_parser()
+ );
+ }
+
+ if arg.get_value_hint() != ValueHint::Unknown {
+ assert!(
+ arg.is_takes_value_set(),
+ "Argument '{}' has value hint but takes no value",
+ arg.get_id()
+ );
+
+ if arg.get_value_hint() == ValueHint::CommandWithArguments {
+ assert!(
+ arg.is_multiple_values_set(),
+ "Argument '{}' uses hint CommandWithArguments and must accept multiple values",
+ arg.get_id()
+ )
+ }
+ }
+
+ if arg.index.is_some() {
+ assert!(
+ arg.is_positional(),
+ "Argument '{}' is a positional argument and can't have short or long name versions",
+ arg.get_id()
+ );
+ assert!(
+ arg.is_takes_value_set(),
+ "Argument '{}` is positional, it must take a value{}",
+ arg.get_id(),
+ if arg.get_id() == Id::HELP {
+ " (`mut_arg` no longer works with implicit `--help`)"
+ } else if arg.get_id() == Id::VERSION {
+ " (`mut_arg` no longer works with implicit `--version`)"
+ } else {
+ ""
+ }
+ );
+ }
+
+ let num_vals = arg.get_num_args().expect(INTERNAL_ERROR_MSG);
+ // This can be the cause of later asserts, so put this first
+ if num_vals != ValueRange::EMPTY {
+ // HACK: Don't check for flags to make the derive easier
+ let num_val_names = arg.get_value_names().unwrap_or(&[]).len();
+ if num_vals.max_values() < num_val_names {
+ panic!(
+ "Argument {}: Too many value names ({}) compared to `num_args` ({})",
+ arg.get_id(),
+ num_val_names,
+ num_vals
+ );
+ }
+ }
+
+ assert_eq!(
+ num_vals.takes_values(),
+ arg.is_takes_value_set(),
+ "Argument {}: mismatch between `num_args` ({}) and `takes_value`",
+ arg.get_id(),
+ num_vals,
+ );
+ assert_eq!(
+ num_vals.is_multiple(),
+ arg.is_multiple_values_set(),
+ "Argument {}: mismatch between `num_args` ({}) and `multiple_values`",
+ arg.get_id(),
+ num_vals,
+ );
+
+ if 1 < num_vals.min_values() {
+ assert!(
+ !arg.is_require_equals_set(),
+ "Argument {}: cannot accept more than 1 arg (num_args={}) with require_equals",
+ arg.get_id(),
+ num_vals
+ );
+ }
+
+ if num_vals == ValueRange::SINGLE {
+ assert!(
+ !arg.is_multiple_values_set(),
+ "Argument {}: mismatch between `num_args` and `multiple_values`",
+ arg.get_id()
+ );
+ }
+
+ assert_arg_flags(arg);
+
+ assert_defaults(arg, "default_value", arg.default_vals.iter());
+ assert_defaults(
+ arg,
+ "default_missing_value",
+ arg.default_missing_vals.iter(),
+ );
+ assert_defaults(
+ arg,
+ "default_value_if",
+ arg.default_vals_ifs
+ .iter()
+ .filter_map(|(_, _, default)| default.as_ref()),
+ );
+}
+
+fn assert_arg_flags(arg: &Arg) {
+ macro_rules! checker {
+ ($a:ident requires $($b:ident)|+) => {
+ if arg.$a() {
+ let mut s = String::new();
+
+ $(
+ if !arg.$b() {
+ use std::fmt::Write;
+ write!(&mut s, " Arg::{} is required when Arg::{} is set.\n", std::stringify!($b), std::stringify!($a)).unwrap();
+ }
+ )+
+
+ if !s.is_empty() {
+ panic!("Argument {:?}\n{}", arg.get_id(), s)
+ }
+ }
+ }
+ }
+
+ checker!(is_hide_possible_values_set requires is_takes_value_set);
+ checker!(is_allow_hyphen_values_set requires is_takes_value_set);
+ checker!(is_allow_negative_numbers_set requires is_takes_value_set);
+ checker!(is_require_equals_set requires is_takes_value_set);
+ checker!(is_last_set requires is_takes_value_set);
+ checker!(is_hide_default_value_set requires is_takes_value_set);
+ checker!(is_multiple_values_set requires is_takes_value_set);
+ checker!(is_ignore_case_set requires is_takes_value_set);
+}
+
+fn assert_defaults<'d>(
+ arg: &Arg,
+ field: &'static str,
+ defaults: impl IntoIterator<Item = &'d OsStr>,
+) {
+ for default_os in defaults {
+ let value_parser = arg.get_value_parser();
+ let assert_cmd = Command::new("assert");
+ if let Some(delim) = arg.get_value_delimiter() {
+ let default_os = RawOsStr::new(default_os);
+ for part in default_os.split(delim) {
+ if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), &part.to_os_str())
+ {
+ panic!(
+ "Argument `{}`'s {}={:?} failed validation: {}",
+ arg.get_id(),
+ field,
+ part.to_str_lossy(),
+ err
+ );
+ }
+ }
+ } else if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), default_os) {
+ panic!(
+ "Argument `{}`'s {}={:?} failed validation: {}",
+ arg.get_id(),
+ field,
+ default_os,
+ err
+ );
+ }
+ }
+}
diff --git a/src/builder/mod.rs b/src/builder/mod.rs
new file mode 100644
index 0000000..098ad57
--- /dev/null
+++ b/src/builder/mod.rs
@@ -0,0 +1,60 @@
+//! Define [`Command`] line [arguments][`Arg`]
+
+mod action;
+mod app_settings;
+mod arg;
+mod arg_group;
+mod arg_predicate;
+mod arg_settings;
+mod command;
+mod os_str;
+mod possible_value;
+mod range;
+mod resettable;
+mod str;
+mod styled_str;
+mod value_hint;
+mod value_parser;
+
+#[cfg(debug_assertions)]
+mod debug_asserts;
+
+#[cfg(test)]
+mod tests;
+
+pub use self::str::Str;
+pub use action::ArgAction;
+pub use arg::Arg;
+pub use arg_group::ArgGroup;
+pub use arg_predicate::ArgPredicate;
+pub use command::Command;
+pub use os_str::OsStr;
+pub use possible_value::PossibleValue;
+pub use range::ValueRange;
+pub use resettable::IntoResettable;
+pub use resettable::Resettable;
+pub use styled_str::StyledStr;
+pub use value_hint::ValueHint;
+pub use value_parser::_AutoValueParser;
+pub use value_parser::via_prelude;
+pub use value_parser::BoolValueParser;
+pub use value_parser::BoolishValueParser;
+pub use value_parser::EnumValueParser;
+pub use value_parser::FalseyValueParser;
+pub use value_parser::MapValueParser;
+pub use value_parser::NonEmptyStringValueParser;
+pub use value_parser::OsStringValueParser;
+pub use value_parser::PathBufValueParser;
+pub use value_parser::PossibleValuesParser;
+pub use value_parser::RangedI64ValueParser;
+pub use value_parser::RangedU64ValueParser;
+pub use value_parser::StringValueParser;
+pub use value_parser::TypedValueParser;
+pub use value_parser::ValueParser;
+pub use value_parser::ValueParserFactory;
+pub use value_parser::_AnonymousValueParser;
+
+#[allow(unused_imports)]
+pub(crate) use self::str::Inner as StrInner;
+pub(crate) use action::CountType;
+pub(crate) use arg_settings::{ArgFlags, ArgSettings};
diff --git a/src/builder/os_str.rs b/src/builder/os_str.rs
new file mode 100644
index 0000000..bb2370d
--- /dev/null
+++ b/src/builder/os_str.rs
@@ -0,0 +1,336 @@
+use crate::builder::Str;
+
+/// A UTF-8-encoded fixed string
+///
+/// **NOTE:** To support dynamic values (i.e. `OsString`), enable the [`string`
+/// feature][crate::_features]
+#[derive(Default, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
+pub struct OsStr {
+ name: Inner,
+}
+
+impl OsStr {
+ #[cfg(feature = "string")]
+ pub(crate) fn from_string(name: std::ffi::OsString) -> Self {
+ Self {
+ name: Inner::from_string(name),
+ }
+ }
+
+ #[cfg(feature = "string")]
+ pub(crate) fn from_ref(name: &std::ffi::OsStr) -> Self {
+ Self {
+ name: Inner::from_ref(name),
+ }
+ }
+
+ pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self {
+ Self {
+ name: Inner::from_static_ref(name),
+ }
+ }
+
+ /// Get the raw string as an `std::ffi::OsStr`
+ pub fn as_os_str(&self) -> &std::ffi::OsStr {
+ self.name.as_os_str()
+ }
+
+ /// Get the raw string as an `OsString`
+ pub fn to_os_string(&self) -> std::ffi::OsString {
+ self.as_os_str().to_owned()
+ }
+}
+
+impl From<&'_ OsStr> for OsStr {
+ fn from(id: &'_ OsStr) -> Self {
+ id.clone()
+ }
+}
+
+#[cfg(feature = "string")]
+impl From<Str> for OsStr {
+ fn from(id: Str) -> Self {
+ match id.into_inner() {
+ crate::builder::StrInner::Static(s) => Self::from_static_ref(std::ffi::OsStr::new(s)),
+ crate::builder::StrInner::Owned(s) => Self::from_ref(std::ffi::OsStr::new(s.as_ref())),
+ }
+ }
+}
+
+#[cfg(not(feature = "string"))]
+impl From<Str> for OsStr {
+ fn from(id: Str) -> Self {
+ Self::from_static_ref(std::ffi::OsStr::new(id.into_inner().0))
+ }
+}
+
+#[cfg(feature = "perf")]
+impl From<&'_ Str> for OsStr {
+ fn from(id: &'_ Str) -> Self {
+ match id.clone().into_inner() {
+ crate::builder::StrInner::Static(s) => Self::from_static_ref(std::ffi::OsStr::new(s)),
+ crate::builder::StrInner::Owned(s) => Self::from_ref(std::ffi::OsStr::new(s.as_ref())),
+ }
+ }
+}
+
+impl From<&'_ Str> for OsStr {
+ fn from(id: &'_ Str) -> Self {
+ id.clone().into()
+ }
+}
+
+#[cfg(feature = "string")]
+impl From<std::ffi::OsString> for OsStr {
+ fn from(name: std::ffi::OsString) -> Self {
+ Self::from_string(name)
+ }
+}
+
+#[cfg(feature = "string")]
+impl From<&'_ std::ffi::OsString> for OsStr {
+ fn from(name: &'_ std::ffi::OsString) -> Self {
+ Self::from_ref(name.as_os_str())
+ }
+}
+
+#[cfg(feature = "string")]
+impl From<std::string::String> for OsStr {
+ fn from(name: std::string::String) -> Self {
+ Self::from_string(name.into())
+ }
+}
+
+#[cfg(feature = "string")]
+impl From<&'_ std::string::String> for OsStr {
+ fn from(name: &'_ std::string::String) -> Self {
+ Self::from_ref(name.as_str().as_ref())
+ }
+}
+
+impl From<&'static std::ffi::OsStr> for OsStr {
+ fn from(name: &'static std::ffi::OsStr) -> Self {
+ Self::from_static_ref(name)
+ }
+}
+
+impl From<&'_ &'static std::ffi::OsStr> for OsStr {
+ fn from(name: &'_ &'static std::ffi::OsStr) -> Self {
+ Self::from_static_ref(name)
+ }
+}
+
+impl From<&'static str> for OsStr {
+ fn from(name: &'static str) -> Self {
+ Self::from_static_ref(name.as_ref())
+ }
+}
+
+impl From<&'_ &'static str> for OsStr {
+ fn from(name: &'_ &'static str) -> Self {
+ Self::from_static_ref((*name).as_ref())
+ }
+}
+
+impl From<OsStr> for std::ffi::OsString {
+ fn from(name: OsStr) -> Self {
+ name.name.into_os_string()
+ }
+}
+
+impl From<OsStr> for std::path::PathBuf {
+ fn from(name: OsStr) -> Self {
+ std::ffi::OsString::from(name).into()
+ }
+}
+
+impl std::fmt::Debug for OsStr {
+ #[inline]
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ std::fmt::Debug::fmt(self.as_os_str(), f)
+ }
+}
+
+impl std::ops::Deref for OsStr {
+ type Target = std::ffi::OsStr;
+
+ #[inline]
+ fn deref(&self) -> &std::ffi::OsStr {
+ self.as_os_str()
+ }
+}
+
+impl AsRef<std::ffi::OsStr> for OsStr {
+ #[inline]
+ fn as_ref(&self) -> &std::ffi::OsStr {
+ self.as_os_str()
+ }
+}
+
+impl AsRef<std::path::Path> for OsStr {
+ #[inline]
+ fn as_ref(&self) -> &std::path::Path {
+ std::path::Path::new(self)
+ }
+}
+
+impl std::borrow::Borrow<std::ffi::OsStr> for OsStr {
+ #[inline]
+ fn borrow(&self) -> &std::ffi::OsStr {
+ self.as_os_str()
+ }
+}
+
+impl PartialEq<str> for OsStr {
+ #[inline]
+ fn eq(&self, other: &str) -> bool {
+ PartialEq::eq(self.as_os_str(), other)
+ }
+}
+impl PartialEq<OsStr> for str {
+ #[inline]
+ fn eq(&self, other: &OsStr) -> bool {
+ PartialEq::eq(self, other.as_os_str())
+ }
+}
+
+impl PartialEq<&'_ str> for OsStr {
+ #[inline]
+ fn eq(&self, other: &&str) -> bool {
+ PartialEq::eq(self.as_os_str(), *other)
+ }
+}
+impl PartialEq<OsStr> for &'_ str {
+ #[inline]
+ fn eq(&self, other: &OsStr) -> bool {
+ PartialEq::eq(*self, other.as_os_str())
+ }
+}
+
+impl PartialEq<&'_ std::ffi::OsStr> for OsStr {
+ #[inline]
+ fn eq(&self, other: &&std::ffi::OsStr) -> bool {
+ PartialEq::eq(self.as_os_str(), *other)
+ }
+}
+impl PartialEq<OsStr> for &'_ std::ffi::OsStr {
+ #[inline]
+ fn eq(&self, other: &OsStr) -> bool {
+ PartialEq::eq(*self, other.as_os_str())
+ }
+}
+
+impl PartialEq<std::string::String> for OsStr {
+ #[inline]
+ fn eq(&self, other: &std::string::String) -> bool {
+ PartialEq::eq(self.as_os_str(), other.as_str())
+ }
+}
+impl PartialEq<OsStr> for std::string::String {
+ #[inline]
+ fn eq(&self, other: &OsStr) -> bool {
+ PartialEq::eq(self.as_str(), other.as_os_str())
+ }
+}
+
+impl PartialEq<std::ffi::OsString> for OsStr {
+ #[inline]
+ fn eq(&self, other: &std::ffi::OsString) -> bool {
+ PartialEq::eq(self.as_os_str(), other.as_os_str())
+ }
+}
+impl PartialEq<OsStr> for std::ffi::OsString {
+ #[inline]
+ fn eq(&self, other: &OsStr) -> bool {
+ PartialEq::eq(self.as_os_str(), other.as_os_str())
+ }
+}
+
+#[cfg(feature = "string")]
+pub(crate) mod inner {
+ #[derive(Clone)]
+ pub(crate) enum Inner {
+ Static(&'static std::ffi::OsStr),
+ Owned(Box<std::ffi::OsStr>),
+ }
+
+ impl Inner {
+ pub(crate) fn from_string(name: std::ffi::OsString) -> Self {
+ Self::Owned(name.into_boxed_os_str())
+ }
+
+ pub(crate) fn from_ref(name: &std::ffi::OsStr) -> Self {
+ Self::Owned(Box::from(name))
+ }
+
+ pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self {
+ Self::Static(name)
+ }
+
+ pub(crate) fn as_os_str(&self) -> &std::ffi::OsStr {
+ match self {
+ Self::Static(s) => s,
+ Self::Owned(s) => s.as_ref(),
+ }
+ }
+
+ pub(crate) fn into_os_string(self) -> std::ffi::OsString {
+ self.as_os_str().to_owned()
+ }
+ }
+}
+
+#[cfg(not(feature = "string"))]
+pub(crate) mod inner {
+ #[derive(Clone)]
+ pub(crate) struct Inner(&'static std::ffi::OsStr);
+
+ impl Inner {
+ pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self {
+ Self(name)
+ }
+
+ pub(crate) fn as_os_str(&self) -> &std::ffi::OsStr {
+ self.0
+ }
+
+ pub(crate) fn into_os_string(self) -> std::ffi::OsString {
+ self.as_os_str().to_owned()
+ }
+ }
+}
+
+pub(crate) use inner::Inner;
+
+impl Default for Inner {
+ fn default() -> Self {
+ Self::from_static_ref(std::ffi::OsStr::new(""))
+ }
+}
+
+impl PartialEq for Inner {
+ fn eq(&self, other: &Inner) -> bool {
+ self.as_os_str() == other.as_os_str()
+ }
+}
+
+impl PartialOrd for Inner {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ self.as_os_str().partial_cmp(other.as_os_str())
+ }
+}
+
+impl Ord for Inner {
+ fn cmp(&self, other: &Inner) -> std::cmp::Ordering {
+ self.as_os_str().cmp(other.as_os_str())
+ }
+}
+
+impl Eq for Inner {}
+
+impl std::hash::Hash for Inner {
+ #[inline]
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.as_os_str().hash(state);
+ }
+}
diff --git a/src/builder/possible_value.rs b/src/builder/possible_value.rs
new file mode 100644
index 0000000..7a313ad
--- /dev/null
+++ b/src/builder/possible_value.rs
@@ -0,0 +1,234 @@
+use crate::builder::IntoResettable;
+use crate::builder::Str;
+use crate::builder::StyledStr;
+use crate::util::eq_ignore_case;
+
+/// A possible value of an argument.
+///
+/// This is used for specifying [possible values] of [Args].
+///
+/// See also [`PossibleValuesParser`][crate::builder::PossibleValuesParser]
+///
+/// **NOTE:** Most likely you can use strings, rather than `PossibleValue` as it is only required
+/// to [hide] single values from help messages and shell completions or to attach [help] to
+/// possible values.
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::{Arg, builder::PossibleValue, ArgAction};
+/// let cfg = Arg::new("config")
+/// .action(ArgAction::Set)
+/// .value_name("FILE")
+/// .value_parser([
+/// PossibleValue::new("fast"),
+/// PossibleValue::new("slow").help("slower than fast"),
+/// PossibleValue::new("secret speed").hide(true)
+/// ]);
+/// ```
+///
+/// [Args]: crate::Arg
+/// [possible values]: crate::builder::ValueParser::possible_values
+/// [hide]: PossibleValue::hide()
+/// [help]: PossibleValue::help()
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct PossibleValue {
+ name: Str,
+ help: Option<StyledStr>,
+ aliases: Vec<Str>, // (name, visible)
+ hide: bool,
+}
+
+impl PossibleValue {
+ /// Create a [`PossibleValue`] with its name.
+ ///
+ /// The name will be used to decide whether this value was provided by the user to an argument.
+ ///
+ /// **NOTE:** In case it is not [hidden] it will also be shown in help messages for arguments
+ /// that use it as a [possible value] and have not hidden them through [`Arg::hide_possible_values(true)`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::builder::PossibleValue;
+ /// PossibleValue::new("fast")
+ /// # ;
+ /// ```
+ /// [hidden]: PossibleValue::hide
+ /// [possible value]: crate::builder::PossibleValuesParser
+ /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values()
+ pub fn new(name: impl Into<Str>) -> Self {
+ PossibleValue {
+ name: name.into(),
+ ..Default::default()
+ }
+ }
+
+ /// Sets the help description of the value.
+ ///
+ /// This is typically displayed in completions (where supported) and should be a short, one-line
+ /// description.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::builder::PossibleValue;
+ /// PossibleValue::new("slow")
+ /// .help("not fast")
+ /// # ;
+ /// ```
+ #[inline]
+ #[must_use]
+ pub fn help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
+ self.help = help.into_resettable().into_option();
+ self
+ }
+
+ /// Hides this value from help and shell completions.
+ ///
+ /// This is an alternative to hiding through [`Arg::hide_possible_values(true)`], if you only
+ /// want to hide some values.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::builder::PossibleValue;
+ /// PossibleValue::new("secret")
+ /// .hide(true)
+ /// # ;
+ /// ```
+ /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values()
+ #[inline]
+ #[must_use]
+ pub fn hide(mut self, yes: bool) -> Self {
+ self.hide = yes;
+ self
+ }
+
+ /// Sets a *hidden* alias for this argument value.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::builder::PossibleValue;
+ /// PossibleValue::new("slow")
+ /// .alias("not-fast")
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self {
+ if let Some(name) = name.into_resettable().into_option() {
+ self.aliases.push(name);
+ } else {
+ self.aliases.clear();
+ }
+ self
+ }
+
+ /// Sets multiple *hidden* aliases for this argument value.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::builder::PossibleValue;
+ /// PossibleValue::new("slow")
+ /// .aliases(["not-fast", "snake-like"])
+ /// # ;
+ /// ```
+ #[must_use]
+ pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
+ self.aliases.extend(names.into_iter().map(|a| a.into()));
+ self
+ }
+}
+
+/// Reflection
+impl PossibleValue {
+ /// Get the name of the argument value
+ #[inline]
+ pub fn get_name(&self) -> &str {
+ self.name.as_str()
+ }
+
+ /// Get the help specified for this argument, if any
+ #[inline]
+ pub fn get_help(&self) -> Option<&StyledStr> {
+ self.help.as_ref()
+ }
+
+ /// Get the help specified for this argument, if any and the argument
+ /// value is not hidden
+ #[inline]
+ #[cfg(feature = "help")]
+ pub(crate) fn get_visible_help(&self) -> Option<&StyledStr> {
+ if !self.hide {
+ self.get_help()
+ } else {
+ None
+ }
+ }
+
+ /// Report if [`PossibleValue::hide`] is set
+ #[inline]
+ pub fn is_hide_set(&self) -> bool {
+ self.hide
+ }
+
+ /// Report if PossibleValue is not hidden and has a help message
+ pub(crate) fn should_show_help(&self) -> bool {
+ !self.hide && self.help.is_some()
+ }
+
+ /// Get the name if argument value is not hidden, `None` otherwise,
+ /// but wrapped in quotes if it contains whitespace
+ #[cfg(feature = "help")]
+ pub(crate) fn get_visible_quoted_name(&self) -> Option<std::borrow::Cow<'_, str>> {
+ if !self.hide {
+ Some(if self.name.contains(char::is_whitespace) {
+ format!("{:?}", self.name).into()
+ } else {
+ self.name.as_str().into()
+ })
+ } else {
+ None
+ }
+ }
+
+ /// Returns all valid values of the argument value.
+ ///
+ /// Namely the name and all aliases.
+ pub fn get_name_and_aliases(&self) -> impl Iterator<Item = &str> + '_ {
+ std::iter::once(self.get_name()).chain(self.aliases.iter().map(|s| s.as_str()))
+ }
+
+ /// Tests if the value is valid for this argument value
+ ///
+ /// The value is valid if it is either the name or one of the aliases.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::builder::PossibleValue;
+ /// let arg_value = PossibleValue::new("fast").alias("not-slow");
+ ///
+ /// assert!(arg_value.matches("fast", false));
+ /// assert!(arg_value.matches("not-slow", false));
+ ///
+ /// assert!(arg_value.matches("FAST", true));
+ /// assert!(!arg_value.matches("FAST", false));
+ /// ```
+ pub fn matches(&self, value: &str, ignore_case: bool) -> bool {
+ if ignore_case {
+ self.get_name_and_aliases()
+ .any(|name| eq_ignore_case(name, value))
+ } else {
+ self.get_name_and_aliases().any(|name| name == value)
+ }
+ }
+}
+
+impl<S: Into<Str>> From<S> for PossibleValue {
+ fn from(s: S) -> Self {
+ Self::new(s)
+ }
+}
diff --git a/src/builder/range.rs b/src/builder/range.rs
new file mode 100644
index 0000000..6ecf053
--- /dev/null
+++ b/src/builder/range.rs
@@ -0,0 +1,283 @@
+/// Values per occurrence for an argument
+#[derive(Copy, Clone, PartialEq, Eq, Hash)]
+pub struct ValueRange {
+ start_inclusive: usize,
+ end_inclusive: usize,
+}
+
+impl ValueRange {
+ /// Nor argument values, or a flag
+ pub const EMPTY: Self = Self {
+ start_inclusive: 0,
+ end_inclusive: 0,
+ };
+
+ /// A single argument value, the most common case for options
+ pub const SINGLE: Self = Self {
+ start_inclusive: 1,
+ end_inclusive: 1,
+ };
+
+ /// Create a range
+ ///
+ /// # Panics
+ ///
+ /// If the end is less than the start
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use clap::builder::ValueRange;
+ /// let range = ValueRange::new(5);
+ /// let range = ValueRange::new(5..10);
+ /// let range = ValueRange::new(5..=10);
+ /// let range = ValueRange::new(5..);
+ /// let range = ValueRange::new(..10);
+ /// let range = ValueRange::new(..=10);
+ /// ```
+ ///
+ /// While this will panic:
+ /// ```should_panic
+ /// # use clap::builder::ValueRange;
+ /// let range = ValueRange::new(10..5); // Panics!
+ /// ```
+ pub fn new(range: impl Into<Self>) -> Self {
+ range.into()
+ }
+
+ pub(crate) fn raw(start_inclusive: usize, end_inclusive: usize) -> Self {
+ debug_assert!(start_inclusive <= end_inclusive);
+ Self {
+ start_inclusive,
+ end_inclusive,
+ }
+ }
+
+ /// Fewest number of values the argument accepts
+ pub fn min_values(&self) -> usize {
+ self.start_inclusive
+ }
+
+ /// Most number of values the argument accepts
+ pub fn max_values(&self) -> usize {
+ self.end_inclusive
+ }
+
+ /// Report whether the argument takes any values (ie is a flag)
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use clap::builder::ValueRange;
+ /// let range = ValueRange::new(5);
+ /// assert!(range.takes_values());
+ ///
+ /// let range = ValueRange::new(0);
+ /// assert!(!range.takes_values());
+ /// ```
+ pub fn takes_values(&self) -> bool {
+ self.end_inclusive != 0
+ }
+
+ pub(crate) fn is_unbounded(&self) -> bool {
+ self.end_inclusive == usize::MAX
+ }
+
+ pub(crate) fn is_fixed(&self) -> bool {
+ self.start_inclusive == self.end_inclusive
+ }
+
+ pub(crate) fn is_multiple(&self) -> bool {
+ self.start_inclusive != self.end_inclusive || 1 < self.start_inclusive
+ }
+
+ pub(crate) fn num_values(&self) -> Option<usize> {
+ self.is_fixed().then_some(self.start_inclusive)
+ }
+
+ pub(crate) fn accepts_more(&self, current: usize) -> bool {
+ current < self.end_inclusive
+ }
+}
+
+impl std::ops::RangeBounds<usize> for ValueRange {
+ fn start_bound(&self) -> std::ops::Bound<&usize> {
+ std::ops::Bound::Included(&self.start_inclusive)
+ }
+
+ fn end_bound(&self) -> std::ops::Bound<&usize> {
+ std::ops::Bound::Included(&self.end_inclusive)
+ }
+}
+
+impl Default for ValueRange {
+ fn default() -> Self {
+ Self::SINGLE
+ }
+}
+
+impl From<usize> for ValueRange {
+ fn from(fixed: usize) -> Self {
+ (fixed..=fixed).into()
+ }
+}
+
+impl From<std::ops::Range<usize>> for ValueRange {
+ fn from(range: std::ops::Range<usize>) -> Self {
+ let start_inclusive = range.start;
+ let end_inclusive = range.end.saturating_sub(1);
+ Self::raw(start_inclusive, end_inclusive)
+ }
+}
+
+impl From<std::ops::RangeFull> for ValueRange {
+ fn from(_: std::ops::RangeFull) -> Self {
+ let start_inclusive = 0;
+ let end_inclusive = usize::MAX;
+ Self::raw(start_inclusive, end_inclusive)
+ }
+}
+
+impl From<std::ops::RangeFrom<usize>> for ValueRange {
+ fn from(range: std::ops::RangeFrom<usize>) -> Self {
+ let start_inclusive = range.start;
+ let end_inclusive = usize::MAX;
+ Self::raw(start_inclusive, end_inclusive)
+ }
+}
+
+impl From<std::ops::RangeTo<usize>> for ValueRange {
+ fn from(range: std::ops::RangeTo<usize>) -> Self {
+ let start_inclusive = 0;
+ let end_inclusive = range.end.saturating_sub(1);
+ Self::raw(start_inclusive, end_inclusive)
+ }
+}
+
+impl From<std::ops::RangeInclusive<usize>> for ValueRange {
+ fn from(range: std::ops::RangeInclusive<usize>) -> Self {
+ let start_inclusive = *range.start();
+ let end_inclusive = *range.end();
+ Self::raw(start_inclusive, end_inclusive)
+ }
+}
+
+impl From<std::ops::RangeToInclusive<usize>> for ValueRange {
+ fn from(range: std::ops::RangeToInclusive<usize>) -> Self {
+ let start_inclusive = 0;
+ let end_inclusive = range.end;
+ Self::raw(start_inclusive, end_inclusive)
+ }
+}
+
+impl std::fmt::Display for ValueRange {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ ok!(self.start_inclusive.fmt(f));
+ if !self.is_fixed() {
+ ok!("..=".fmt(f));
+ ok!(self.end_inclusive.fmt(f));
+ }
+ Ok(())
+ }
+}
+
+impl std::fmt::Debug for ValueRange {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ write!(f, "{self}")
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ use std::ops::RangeBounds;
+
+ #[test]
+ fn from_fixed() {
+ let range: ValueRange = 5.into();
+ assert_eq!(range.start_bound(), std::ops::Bound::Included(&5));
+ assert_eq!(range.end_bound(), std::ops::Bound::Included(&5));
+ assert!(range.is_fixed());
+ assert!(range.is_multiple());
+ assert_eq!(range.num_values(), Some(5));
+ assert!(range.takes_values());
+ }
+
+ #[test]
+ fn from_fixed_empty() {
+ let range: ValueRange = 0.into();
+ assert_eq!(range.start_bound(), std::ops::Bound::Included(&0));
+ assert_eq!(range.end_bound(), std::ops::Bound::Included(&0));
+ assert!(range.is_fixed());
+ assert!(!range.is_multiple());
+ assert_eq!(range.num_values(), Some(0));
+ assert!(!range.takes_values());
+ }
+
+ #[test]
+ fn from_range() {
+ let range: ValueRange = (5..10).into();
+ assert_eq!(range.start_bound(), std::ops::Bound::Included(&5));
+ assert_eq!(range.end_bound(), std::ops::Bound::Included(&9));
+ assert!(!range.is_fixed());
+ assert!(range.is_multiple());
+ assert_eq!(range.num_values(), None);
+ assert!(range.takes_values());
+ }
+
+ #[test]
+ fn from_range_inclusive() {
+ let range: ValueRange = (5..=10).into();
+ assert_eq!(range.start_bound(), std::ops::Bound::Included(&5));
+ assert_eq!(range.end_bound(), std::ops::Bound::Included(&10));
+ assert!(!range.is_fixed());
+ assert!(range.is_multiple());
+ assert_eq!(range.num_values(), None);
+ assert!(range.takes_values());
+ }
+
+ #[test]
+ fn from_range_full() {
+ let range: ValueRange = (..).into();
+ assert_eq!(range.start_bound(), std::ops::Bound::Included(&0));
+ assert_eq!(range.end_bound(), std::ops::Bound::Included(&usize::MAX));
+ assert!(!range.is_fixed());
+ assert!(range.is_multiple());
+ assert_eq!(range.num_values(), None);
+ assert!(range.takes_values());
+ }
+
+ #[test]
+ fn from_range_from() {
+ let range: ValueRange = (5..).into();
+ assert_eq!(range.start_bound(), std::ops::Bound::Included(&5));
+ assert_eq!(range.end_bound(), std::ops::Bound::Included(&usize::MAX));
+ assert!(!range.is_fixed());
+ assert!(range.is_multiple());
+ assert_eq!(range.num_values(), None);
+ assert!(range.takes_values());
+ }
+
+ #[test]
+ fn from_range_to() {
+ let range: ValueRange = (..10).into();
+ assert_eq!(range.start_bound(), std::ops::Bound::Included(&0));
+ assert_eq!(range.end_bound(), std::ops::Bound::Included(&9));
+ assert!(!range.is_fixed());
+ assert!(range.is_multiple());
+ assert_eq!(range.num_values(), None);
+ assert!(range.takes_values());
+ }
+
+ #[test]
+ fn from_range_to_inclusive() {
+ let range: ValueRange = (..=10).into();
+ assert_eq!(range.start_bound(), std::ops::Bound::Included(&0));
+ assert_eq!(range.end_bound(), std::ops::Bound::Included(&10));
+ assert!(!range.is_fixed());
+ assert!(range.is_multiple());
+ assert_eq!(range.num_values(), None);
+ assert!(range.takes_values());
+ }
+}
diff --git a/src/builder/resettable.rs b/src/builder/resettable.rs
new file mode 100644
index 0000000..e0b82b1
--- /dev/null
+++ b/src/builder/resettable.rs
@@ -0,0 +1,211 @@
+// Unlike `impl Into<Option<T>>` or `Option<impl Into<T>>`, this isn't ambiguous for the `None`
+// case.
+
+use crate::builder::ArgAction;
+use crate::builder::OsStr;
+use crate::builder::Str;
+use crate::builder::StyledStr;
+use crate::builder::ValueHint;
+use crate::builder::ValueParser;
+use crate::builder::ValueRange;
+
+/// Clearable builder value
+///
+/// This allows a builder function to both accept any value that can [`Into::into`] `T` (like
+/// `&str` into `OsStr`) as well as `None` to reset it to the default. This is needed to
+/// workaround a limitation where you can't have a function argument that is `impl Into<Option<T>>`
+/// where `T` is `impl Into<S>` accept `None` as its type is ambiguous.
+///
+/// # Example
+///
+/// ```rust
+/// # use clap::Command;
+/// # use clap::Arg;
+/// fn common() -> Command {
+/// Command::new("cli")
+/// .arg(Arg::new("input").short('i').long("input"))
+/// }
+/// let mut command = common();
+/// command.mut_arg("input", |arg| arg.short(None));
+/// ```
+#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum Resettable<T> {
+ /// Overwrite builder value
+ Value(T),
+ /// Reset builder value
+ Reset,
+}
+
+impl<T> Resettable<T> {
+ pub(crate) fn into_option(self) -> Option<T> {
+ match self {
+ Self::Value(t) => Some(t),
+ Self::Reset => None,
+ }
+ }
+}
+
+impl<T> From<T> for Resettable<T> {
+ fn from(other: T) -> Self {
+ Self::Value(other)
+ }
+}
+
+impl<T> From<Option<T>> for Resettable<T> {
+ fn from(other: Option<T>) -> Self {
+ match other {
+ Some(inner) => Self::Value(inner),
+ None => Self::Reset,
+ }
+ }
+}
+
+/// Convert to the intended resettable type
+pub trait IntoResettable<T> {
+ /// Convert to the intended resettable type
+ fn into_resettable(self) -> Resettable<T>;
+}
+
+impl IntoResettable<char> for Option<char> {
+ fn into_resettable(self) -> Resettable<char> {
+ match self {
+ Some(s) => Resettable::Value(s),
+ None => Resettable::Reset,
+ }
+ }
+}
+
+impl IntoResettable<usize> for Option<usize> {
+ fn into_resettable(self) -> Resettable<usize> {
+ match self {
+ Some(s) => Resettable::Value(s),
+ None => Resettable::Reset,
+ }
+ }
+}
+
+impl IntoResettable<ArgAction> for Option<ArgAction> {
+ fn into_resettable(self) -> Resettable<ArgAction> {
+ match self {
+ Some(s) => Resettable::Value(s),
+ None => Resettable::Reset,
+ }
+ }
+}
+
+impl IntoResettable<ValueHint> for Option<ValueHint> {
+ fn into_resettable(self) -> Resettable<ValueHint> {
+ match self {
+ Some(s) => Resettable::Value(s),
+ None => Resettable::Reset,
+ }
+ }
+}
+
+impl IntoResettable<ValueParser> for Option<ValueParser> {
+ fn into_resettable(self) -> Resettable<ValueParser> {
+ match self {
+ Some(s) => Resettable::Value(s),
+ None => Resettable::Reset,
+ }
+ }
+}
+
+impl IntoResettable<StyledStr> for Option<&'static str> {
+ fn into_resettable(self) -> Resettable<StyledStr> {
+ match self {
+ Some(s) => Resettable::Value(s.into()),
+ None => Resettable::Reset,
+ }
+ }
+}
+
+impl IntoResettable<OsStr> for Option<&'static str> {
+ fn into_resettable(self) -> Resettable<OsStr> {
+ match self {
+ Some(s) => Resettable::Value(s.into()),
+ None => Resettable::Reset,
+ }
+ }
+}
+
+impl IntoResettable<Str> for Option<&'static str> {
+ fn into_resettable(self) -> Resettable<Str> {
+ match self {
+ Some(s) => Resettable::Value(s.into()),
+ None => Resettable::Reset,
+ }
+ }
+}
+
+impl<T> IntoResettable<T> for Resettable<T> {
+ fn into_resettable(self) -> Resettable<T> {
+ self
+ }
+}
+
+impl IntoResettable<char> for char {
+ fn into_resettable(self) -> Resettable<char> {
+ Resettable::Value(self)
+ }
+}
+
+impl IntoResettable<usize> for usize {
+ fn into_resettable(self) -> Resettable<usize> {
+ Resettable::Value(self)
+ }
+}
+
+impl IntoResettable<ArgAction> for ArgAction {
+ fn into_resettable(self) -> Resettable<ArgAction> {
+ Resettable::Value(self)
+ }
+}
+
+impl IntoResettable<ValueHint> for ValueHint {
+ fn into_resettable(self) -> Resettable<ValueHint> {
+ Resettable::Value(self)
+ }
+}
+
+impl<I: Into<ValueRange>> IntoResettable<ValueRange> for I {
+ fn into_resettable(self) -> Resettable<ValueRange> {
+ Resettable::Value(self.into())
+ }
+}
+
+impl<I: Into<ValueParser>> IntoResettable<ValueParser> for I {
+ fn into_resettable(self) -> Resettable<ValueParser> {
+ Resettable::Value(self.into())
+ }
+}
+
+impl<I: Into<String>> IntoResettable<String> for I {
+ fn into_resettable(self) -> Resettable<String> {
+ Resettable::Value(self.into())
+ }
+}
+
+impl<I: Into<StyledStr>> IntoResettable<StyledStr> for I {
+ fn into_resettable(self) -> Resettable<StyledStr> {
+ Resettable::Value(self.into())
+ }
+}
+
+impl<I: Into<OsStr>> IntoResettable<OsStr> for I {
+ fn into_resettable(self) -> Resettable<OsStr> {
+ Resettable::Value(self.into())
+ }
+}
+
+impl<I: Into<Str>> IntoResettable<Str> for I {
+ fn into_resettable(self) -> Resettable<Str> {
+ Resettable::Value(self.into())
+ }
+}
+
+impl<I: Into<crate::Id>> IntoResettable<crate::Id> for I {
+ fn into_resettable(self) -> Resettable<crate::Id> {
+ Resettable::Value(self.into())
+ }
+}
diff --git a/src/builder/str.rs b/src/builder/str.rs
new file mode 100644
index 0000000..be69c3f
--- /dev/null
+++ b/src/builder/str.rs
@@ -0,0 +1,310 @@
+/// A UTF-8-encoded fixed string
+///
+/// **NOTE:** To support dynamic values (i.e. `String`), enable the [`string`
+/// feature][crate::_features]
+#[derive(Default, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
+pub struct Str {
+ name: Inner,
+}
+
+impl Str {
+ #[cfg(feature = "string")]
+ pub(crate) fn from_string(name: std::string::String) -> Self {
+ Self {
+ name: Inner::from_string(name),
+ }
+ }
+
+ #[cfg(feature = "string")]
+ pub(crate) fn from_ref(name: &str) -> Self {
+ Self {
+ name: Inner::from_ref(name),
+ }
+ }
+
+ pub(crate) fn from_static_ref(name: &'static str) -> Self {
+ Self {
+ name: Inner::from_static_ref(name),
+ }
+ }
+
+ pub(crate) fn into_inner(self) -> Inner {
+ self.name
+ }
+
+ /// Get the raw string of the `Str`
+ pub fn as_str(&self) -> &str {
+ self.name.as_str()
+ }
+}
+
+impl From<&'_ Str> for Str {
+ fn from(id: &'_ Str) -> Self {
+ id.clone()
+ }
+}
+
+#[cfg(feature = "string")]
+impl From<std::string::String> for Str {
+ fn from(name: std::string::String) -> Self {
+ Self::from_string(name)
+ }
+}
+
+#[cfg(feature = "string")]
+impl From<&'_ std::string::String> for Str {
+ fn from(name: &'_ std::string::String) -> Self {
+ Self::from_ref(name.as_str())
+ }
+}
+
+impl From<&'static str> for Str {
+ fn from(name: &'static str) -> Self {
+ Self::from_static_ref(name)
+ }
+}
+
+impl From<&'_ &'static str> for Str {
+ fn from(name: &'_ &'static str) -> Self {
+ Self::from_static_ref(name)
+ }
+}
+
+impl From<Str> for String {
+ fn from(name: Str) -> Self {
+ name.name.into_string()
+ }
+}
+
+impl From<Str> for Vec<u8> {
+ fn from(name: Str) -> Self {
+ String::from(name).into()
+ }
+}
+
+impl From<Str> for std::ffi::OsString {
+ fn from(name: Str) -> Self {
+ String::from(name).into()
+ }
+}
+
+impl From<Str> for std::path::PathBuf {
+ fn from(name: Str) -> Self {
+ String::from(name).into()
+ }
+}
+
+impl std::fmt::Display for Str {
+ #[inline]
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ std::fmt::Display::fmt(self.as_str(), f)
+ }
+}
+
+impl std::fmt::Debug for Str {
+ #[inline]
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ std::fmt::Debug::fmt(self.as_str(), f)
+ }
+}
+
+impl std::ops::Deref for Str {
+ type Target = str;
+
+ #[inline]
+ fn deref(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl AsRef<str> for Str {
+ #[inline]
+ fn as_ref(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl AsRef<[u8]> for Str {
+ #[inline]
+ fn as_ref(&self) -> &[u8] {
+ self.as_bytes()
+ }
+}
+
+impl AsRef<std::ffi::OsStr> for Str {
+ #[inline]
+ fn as_ref(&self) -> &std::ffi::OsStr {
+ (**self).as_ref()
+ }
+}
+
+impl AsRef<std::path::Path> for Str {
+ #[inline]
+ fn as_ref(&self) -> &std::path::Path {
+ std::path::Path::new(self)
+ }
+}
+
+impl std::borrow::Borrow<str> for Str {
+ #[inline]
+ fn borrow(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl PartialEq<str> for Str {
+ #[inline]
+ fn eq(&self, other: &str) -> bool {
+ PartialEq::eq(self.as_str(), other)
+ }
+}
+impl PartialEq<Str> for str {
+ #[inline]
+ fn eq(&self, other: &Str) -> bool {
+ PartialEq::eq(self, other.as_str())
+ }
+}
+
+impl PartialEq<&'_ str> for Str {
+ #[inline]
+ fn eq(&self, other: &&str) -> bool {
+ PartialEq::eq(self.as_str(), *other)
+ }
+}
+impl PartialEq<Str> for &'_ str {
+ #[inline]
+ fn eq(&self, other: &Str) -> bool {
+ PartialEq::eq(*self, other.as_str())
+ }
+}
+
+impl PartialEq<std::ffi::OsStr> for Str {
+ #[inline]
+ fn eq(&self, other: &std::ffi::OsStr) -> bool {
+ PartialEq::eq(self.as_str(), other)
+ }
+}
+impl PartialEq<Str> for std::ffi::OsStr {
+ #[inline]
+ fn eq(&self, other: &Str) -> bool {
+ PartialEq::eq(self, other.as_str())
+ }
+}
+
+impl PartialEq<&'_ std::ffi::OsStr> for Str {
+ #[inline]
+ fn eq(&self, other: &&std::ffi::OsStr) -> bool {
+ PartialEq::eq(self.as_str(), *other)
+ }
+}
+impl PartialEq<Str> for &'_ std::ffi::OsStr {
+ #[inline]
+ fn eq(&self, other: &Str) -> bool {
+ PartialEq::eq(*self, other.as_str())
+ }
+}
+
+impl PartialEq<std::string::String> for Str {
+ #[inline]
+ fn eq(&self, other: &std::string::String) -> bool {
+ PartialEq::eq(self.as_str(), other.as_str())
+ }
+}
+impl PartialEq<Str> for std::string::String {
+ #[inline]
+ fn eq(&self, other: &Str) -> bool {
+ PartialEq::eq(self.as_str(), other.as_str())
+ }
+}
+
+#[cfg(feature = "string")]
+pub(crate) mod inner {
+ #[derive(Clone)]
+ pub(crate) enum Inner {
+ Static(&'static str),
+ Owned(Box<str>),
+ }
+
+ impl Inner {
+ pub(crate) fn from_string(name: std::string::String) -> Self {
+ Self::Owned(name.into_boxed_str())
+ }
+
+ pub(crate) fn from_ref(name: &str) -> Self {
+ Self::Owned(Box::from(name))
+ }
+
+ pub(crate) fn from_static_ref(name: &'static str) -> Self {
+ Self::Static(name)
+ }
+
+ pub(crate) fn as_str(&self) -> &str {
+ match self {
+ Self::Static(s) => s,
+ Self::Owned(s) => s.as_ref(),
+ }
+ }
+
+ pub(crate) fn into_string(self) -> String {
+ match self {
+ Self::Static(s) => s.to_owned(),
+ Self::Owned(s) => s.into(),
+ }
+ }
+ }
+}
+
+#[cfg(not(feature = "string"))]
+pub(crate) mod inner {
+ #[derive(Clone)]
+ pub(crate) struct Inner(pub(crate) &'static str);
+
+ impl Inner {
+ pub(crate) fn from_static_ref(name: &'static str) -> Self {
+ Self(name)
+ }
+
+ pub(crate) fn as_str(&self) -> &str {
+ self.0
+ }
+
+ pub(crate) fn into_string(self) -> String {
+ self.as_str().to_owned()
+ }
+ }
+}
+
+pub(crate) use inner::Inner;
+
+impl Default for Inner {
+ fn default() -> Self {
+ Self::from_static_ref("")
+ }
+}
+
+impl PartialEq for Inner {
+ fn eq(&self, other: &Inner) -> bool {
+ self.as_str() == other.as_str()
+ }
+}
+
+impl PartialOrd for Inner {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ self.as_str().partial_cmp(other.as_str())
+ }
+}
+
+impl Ord for Inner {
+ fn cmp(&self, other: &Inner) -> std::cmp::Ordering {
+ self.as_str().cmp(other.as_str())
+ }
+}
+
+impl Eq for Inner {}
+
+impl std::hash::Hash for Inner {
+ #[inline]
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.as_str().hash(state);
+ }
+}
diff --git a/src/builder/styled_str.rs b/src/builder/styled_str.rs
new file mode 100644
index 0000000..d36329d
--- /dev/null
+++ b/src/builder/styled_str.rs
@@ -0,0 +1,349 @@
+/// Terminal-styling container
+///
+/// For now, this is the same as a [`Str`][crate::builder::Str]. This exists to reserve space in
+/// the API for exposing terminal styling.
+#[derive(Clone, Default, Debug, PartialEq, Eq)]
+pub struct StyledStr {
+ #[cfg(feature = "color")]
+ pieces: Vec<(Option<Style>, String)>,
+ #[cfg(not(feature = "color"))]
+ pieces: String,
+}
+
+impl StyledStr {
+ /// Create an empty buffer
+ #[cfg(feature = "color")]
+ pub const fn new() -> Self {
+ Self { pieces: Vec::new() }
+ }
+
+ /// Create an empty buffer
+ #[cfg(not(feature = "color"))]
+ pub const fn new() -> Self {
+ Self {
+ pieces: String::new(),
+ }
+ }
+
+ /// Display using [ANSI Escape Code](https://en.wikipedia.org/wiki/ANSI_escape_code) styling
+ #[cfg(feature = "color")]
+ pub fn ansi(&self) -> impl std::fmt::Display + '_ {
+ AnsiDisplay { styled: self }
+ }
+
+ pub(crate) fn header(&mut self, msg: impl Into<String>) {
+ self.stylize_(Some(Style::Header), msg.into());
+ }
+
+ pub(crate) fn literal(&mut self, msg: impl Into<String>) {
+ self.stylize_(Some(Style::Literal), msg.into());
+ }
+
+ pub(crate) fn placeholder(&mut self, msg: impl Into<String>) {
+ self.stylize_(Some(Style::Placeholder), msg.into());
+ }
+
+ #[cfg_attr(not(feature = "error-context"), allow(dead_code))]
+ pub(crate) fn good(&mut self, msg: impl Into<String>) {
+ self.stylize_(Some(Style::Good), msg.into());
+ }
+
+ #[cfg_attr(not(feature = "error-context"), allow(dead_code))]
+ pub(crate) fn warning(&mut self, msg: impl Into<String>) {
+ self.stylize_(Some(Style::Warning), msg.into());
+ }
+
+ pub(crate) fn error(&mut self, msg: impl Into<String>) {
+ self.stylize_(Some(Style::Error), msg.into());
+ }
+
+ #[allow(dead_code)]
+ pub(crate) fn hint(&mut self, msg: impl Into<String>) {
+ self.stylize_(Some(Style::Hint), msg.into());
+ }
+
+ pub(crate) fn none(&mut self, msg: impl Into<String>) {
+ self.stylize_(None, msg.into());
+ }
+
+ pub(crate) fn stylize(&mut self, style: impl Into<Option<Style>>, msg: impl Into<String>) {
+ self.stylize_(style.into(), msg.into());
+ }
+
+ pub(crate) fn trim(&mut self) {
+ self.trim_start();
+ self.trim_end();
+ }
+
+ pub(crate) fn trim_start(&mut self) {
+ if let Some((_, item)) = self.iter_mut().next() {
+ *item = item.trim_start().to_owned();
+ }
+ }
+
+ #[cfg(feature = "color")]
+ pub(crate) fn trim_end(&mut self) {
+ if let Some((_, item)) = self.pieces.last_mut() {
+ *item = item.trim_end().to_owned();
+ }
+ }
+
+ #[cfg(not(feature = "color"))]
+ pub(crate) fn trim_end(&mut self) {
+ self.pieces = self.pieces.trim_end().to_owned();
+ }
+
+ #[cfg(feature = "help")]
+ pub(crate) fn indent(&mut self, initial: &str, trailing: &str) {
+ if let Some((_, first)) = self.iter_mut().next() {
+ first.insert_str(0, initial);
+ }
+ let mut line_sep = "\n".to_owned();
+ line_sep.push_str(trailing);
+ for (_, content) in self.iter_mut() {
+ *content = content.replace('\n', &line_sep);
+ }
+ }
+
+ #[cfg(all(not(feature = "wrap_help"), feature = "help"))]
+ pub(crate) fn wrap(&mut self, _hard_width: usize) {}
+
+ #[cfg(feature = "wrap_help")]
+ pub(crate) fn wrap(&mut self, hard_width: usize) {
+ let mut wrapper = crate::output::textwrap::wrap_algorithms::LineWrapper::new(hard_width);
+ for (_, content) in self.iter_mut() {
+ let mut total = Vec::new();
+ for (i, line) in content.split_inclusive('\n').enumerate() {
+ if 0 < i {
+ // start of a section does not imply newline
+ wrapper.reset();
+ }
+ let line = crate::output::textwrap::word_separators::find_words_ascii_space(line)
+ .collect::<Vec<_>>();
+ total.extend(wrapper.wrap(line));
+ }
+ let total = total.join("");
+ *content = total;
+ }
+
+ self.trim_end();
+ }
+
+ #[cfg(feature = "color")]
+ fn stylize_(&mut self, style: Option<Style>, msg: String) {
+ if !msg.is_empty() {
+ self.pieces.push((style, msg));
+ }
+ }
+
+ #[cfg(not(feature = "color"))]
+ fn stylize_(&mut self, _style: Option<Style>, msg: String) {
+ self.pieces.push_str(&msg);
+ }
+
+ #[inline(never)]
+ #[cfg(feature = "help")]
+ pub(crate) fn display_width(&self) -> usize {
+ let mut width = 0;
+ for (_, c) in self.iter() {
+ width += crate::output::display_width(c);
+ }
+ width
+ }
+
+ #[cfg(feature = "help")]
+ pub(crate) fn is_empty(&self) -> bool {
+ self.pieces.is_empty()
+ }
+
+ #[cfg(feature = "color")]
+ pub(crate) fn iter(&self) -> impl Iterator<Item = (Option<Style>, &str)> {
+ self.pieces.iter().map(|(s, c)| (*s, c.as_str()))
+ }
+
+ #[cfg(not(feature = "color"))]
+ pub(crate) fn iter(&self) -> impl Iterator<Item = (Option<Style>, &str)> {
+ [(None, self.pieces.as_str())].into_iter()
+ }
+
+ #[cfg(feature = "color")]
+ pub(crate) fn iter_mut(&mut self) -> impl Iterator<Item = (Option<Style>, &mut String)> {
+ self.pieces.iter_mut().map(|(s, c)| (*s, c))
+ }
+
+ #[cfg(not(feature = "color"))]
+ pub(crate) fn iter_mut(&mut self) -> impl Iterator<Item = (Option<Style>, &mut String)> {
+ [(None, &mut self.pieces)].into_iter()
+ }
+
+ #[cfg(feature = "color")]
+ pub(crate) fn into_iter(self) -> impl Iterator<Item = (Option<Style>, String)> {
+ self.pieces.into_iter()
+ }
+
+ #[cfg(not(feature = "color"))]
+ pub(crate) fn into_iter(self) -> impl Iterator<Item = (Option<Style>, String)> {
+ [(None, self.pieces)].into_iter()
+ }
+
+ pub(crate) fn extend(
+ &mut self,
+ other: impl IntoIterator<Item = (impl Into<Option<Style>>, impl Into<String>)>,
+ ) {
+ for (style, content) in other {
+ self.stylize(style.into(), content.into());
+ }
+ }
+
+ #[cfg(feature = "color")]
+ pub(crate) fn write_colored(&self, buffer: &mut termcolor::Buffer) -> std::io::Result<()> {
+ use std::io::Write;
+ use termcolor::WriteColor;
+
+ for (style, content) in &self.pieces {
+ let mut color = termcolor::ColorSpec::new();
+ match style {
+ Some(Style::Header) => {
+ color.set_bold(true);
+ color.set_underline(true);
+ }
+ Some(Style::Literal) => {
+ color.set_bold(true);
+ }
+ Some(Style::Placeholder) => {}
+ Some(Style::Good) => {
+ color.set_fg(Some(termcolor::Color::Green));
+ }
+ Some(Style::Warning) => {
+ color.set_fg(Some(termcolor::Color::Yellow));
+ }
+ Some(Style::Error) => {
+ color.set_fg(Some(termcolor::Color::Red));
+ color.set_bold(true);
+ }
+ Some(Style::Hint) => {
+ color.set_dimmed(true);
+ }
+ None => {}
+ }
+
+ ok!(buffer.set_color(&color));
+ ok!(buffer.write_all(content.as_bytes()));
+ ok!(buffer.reset());
+ }
+
+ Ok(())
+ }
+}
+
+impl Default for &'_ StyledStr {
+ fn default() -> Self {
+ static DEFAULT: StyledStr = StyledStr::new();
+ &DEFAULT
+ }
+}
+
+impl From<std::string::String> for StyledStr {
+ fn from(name: std::string::String) -> Self {
+ let mut styled = StyledStr::new();
+ styled.none(name);
+ styled
+ }
+}
+
+impl From<&'_ std::string::String> for StyledStr {
+ fn from(name: &'_ std::string::String) -> Self {
+ let mut styled = StyledStr::new();
+ styled.none(name);
+ styled
+ }
+}
+
+impl From<&'static str> for StyledStr {
+ fn from(name: &'static str) -> Self {
+ let mut styled = StyledStr::new();
+ styled.none(name);
+ styled
+ }
+}
+
+impl From<&'_ &'static str> for StyledStr {
+ fn from(name: &'_ &'static str) -> Self {
+ StyledStr::from(*name)
+ }
+}
+
+impl PartialOrd for StyledStr {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+impl Ord for StyledStr {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ self.iter().map(cmp_key).cmp(other.iter().map(cmp_key))
+ }
+}
+
+fn cmp_key(c: (Option<Style>, &str)) -> (Option<usize>, &str) {
+ let style = c.0.map(|s| s.as_usize());
+ let content = c.1;
+ (style, content)
+}
+
+/// Color-unaware printing. Never uses coloring.
+impl std::fmt::Display for StyledStr {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ for (_, content) in self.iter() {
+ ok!(std::fmt::Display::fmt(content, f));
+ }
+
+ Ok(())
+ }
+}
+
+#[cfg(feature = "color")]
+struct AnsiDisplay<'s> {
+ styled: &'s StyledStr,
+}
+
+#[cfg(feature = "color")]
+impl std::fmt::Display for AnsiDisplay<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ let mut buffer = termcolor::Buffer::ansi();
+ ok!(self
+ .styled
+ .write_colored(&mut buffer)
+ .map_err(|_| std::fmt::Error));
+ let buffer = buffer.into_inner();
+ let buffer = ok!(String::from_utf8(buffer).map_err(|_| std::fmt::Error));
+ ok!(std::fmt::Display::fmt(&buffer, f));
+
+ Ok(())
+ }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub(crate) enum Style {
+ Header,
+ Literal,
+ Placeholder,
+ Good,
+ Warning,
+ Error,
+ Hint,
+}
+
+impl Style {
+ fn as_usize(&self) -> usize {
+ match self {
+ Self::Header => 0,
+ Self::Literal => 1,
+ Self::Placeholder => 2,
+ Self::Good => 3,
+ Self::Warning => 4,
+ Self::Error => 5,
+ Self::Hint => 6,
+ }
+ }
+}
diff --git a/src/builder/tests.rs b/src/builder/tests.rs
new file mode 100644
index 0000000..15cb8c4
--- /dev/null
+++ b/src/builder/tests.rs
@@ -0,0 +1,56 @@
+use crate::Arg;
+use crate::Command;
+
+#[test]
+fn propagate_version() {
+ let mut cmd = Command::new("test")
+ .propagate_version(true)
+ .version("1.1")
+ .subcommand(Command::new("sub1"));
+ cmd._propagate();
+ assert_eq!(
+ cmd.get_subcommands().next().unwrap().get_version(),
+ Some("1.1")
+ );
+}
+
+#[test]
+fn global_setting() {
+ let mut cmd = Command::new("test")
+ .disable_version_flag(true)
+ .subcommand(Command::new("subcmd"));
+ cmd._propagate();
+ assert!(cmd
+ .get_subcommands()
+ .find(|s| s.get_name() == "subcmd")
+ .unwrap()
+ .is_disable_version_flag_set());
+}
+
+// This test will *fail to compile* if Command is not Send + Sync
+#[test]
+fn app_send_sync() {
+ fn foo<T: Send + Sync>(_: T) {}
+ foo(Command::new("test"))
+}
+
+#[test]
+fn issue_2090() {
+ let mut cmd = Command::new("cmd")
+ .disable_version_flag(true)
+ .subcommand(Command::new("sub"));
+ cmd._build_self(false);
+
+ assert!(cmd
+ .get_subcommands()
+ .next()
+ .unwrap()
+ .is_disable_version_flag_set());
+}
+
+// This test will *fail to compile* if Arg is not Send + Sync
+#[test]
+fn arg_send_sync() {
+ fn foo<T: Send + Sync>(_: T) {}
+ foo(Arg::new("test"))
+}
diff --git a/src/builder/value_hint.rs b/src/builder/value_hint.rs
new file mode 100644
index 0000000..ee286b1
--- /dev/null
+++ b/src/builder/value_hint.rs
@@ -0,0 +1,95 @@
+use std::str::FromStr;
+
+/// Provide shell with hint on how to complete an argument.
+///
+/// See [Arg::value_hint][crate::Arg::value_hint] to set this on an argument.
+///
+/// See the `clap_complete` crate for completion script generation.
+///
+/// Overview of which hints are supported by which shell:
+///
+/// | Hint | zsh | fish[^1]|
+/// | ---------------------- | --- | ------- |
+/// | `AnyPath` | Yes | Yes |
+/// | `FilePath` | Yes | Yes |
+/// | `DirPath` | Yes | Yes |
+/// | `ExecutablePath` | Yes | Partial |
+/// | `CommandName` | Yes | Yes |
+/// | `CommandString` | Yes | Partial |
+/// | `CommandWithArguments` | Yes | |
+/// | `Username` | Yes | Yes |
+/// | `Hostname` | Yes | Yes |
+/// | `Url` | Yes | |
+/// | `EmailAddress` | Yes | |
+///
+/// [^1]: fish completions currently only support named arguments (e.g. -o or --opt), not
+/// positional arguments.
+#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
+#[non_exhaustive]
+pub enum ValueHint {
+ /// Default value if hint is not specified. Follows shell default behavior, which is usually
+ /// auto-completing filenames.
+ Unknown,
+ /// None of the hints below apply. Disables shell completion for this argument.
+ Other,
+ /// Any existing path.
+ AnyPath,
+ /// Path to a file.
+ FilePath,
+ /// Path to a directory.
+ DirPath,
+ /// Path to an executable file.
+ ExecutablePath,
+ /// Name of a command, without arguments. May be relative to PATH, or full path to executable.
+ CommandName,
+ /// A single string containing a command and its arguments.
+ CommandString,
+ /// Capture the remaining arguments as a command name and arguments for that command. This is
+ /// common when writing shell wrappers that execute anther command, for example `sudo` or `env`.
+ ///
+ /// This hint is special, the argument must be a positional argument and have
+ /// [`.num_args(1..)`] and Command must use [`Command::trailing_var_arg(true)`]. The result is that the
+ /// command line `my_app ls -la /` will be parsed as `["ls", "-la", "/"]` and clap won't try to
+ /// parse the `-la` argument itself.
+ ///
+ /// [`Command::trailing_var_arg(true)`]: crate::Command::trailing_var_arg
+ /// [`.num_args(1..)`]: crate::Arg::num_args()
+ CommandWithArguments,
+ /// Name of a local operating system user.
+ Username,
+ /// Host name of a computer.
+ /// Shells usually parse `/etc/hosts` and `.ssh/known_hosts` to complete hostnames.
+ Hostname,
+ /// Complete web address.
+ Url,
+ /// Email address.
+ EmailAddress,
+}
+
+impl Default for ValueHint {
+ fn default() -> Self {
+ ValueHint::Unknown
+ }
+}
+
+impl FromStr for ValueHint {
+ type Err = String;
+ fn from_str(s: &str) -> Result<Self, <Self as FromStr>::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,
+ _ => return Err(format!("unknown ValueHint: `{s}`")),
+ })
+ }
+}
diff --git a/src/builder/value_parser.rs b/src/builder/value_parser.rs
new file mode 100644
index 0000000..191e8ae
--- /dev/null
+++ b/src/builder/value_parser.rs
@@ -0,0 +1,2435 @@
+use std::convert::TryInto;
+use std::ops::RangeBounds;
+
+use crate::parser::AnyValue;
+use crate::parser::AnyValueId;
+
+/// Parse/validate argument values
+///
+/// Specified with [`Arg::value_parser`][crate::Arg::value_parser].
+///
+/// `ValueParser` defines how to convert a raw argument value into a validated and typed value for
+/// use within an application.
+///
+/// See
+/// - [`value_parser!`][crate::value_parser] for automatically selecting an implementation for a given type
+/// - [`ValueParser::new`] for additional [`TypedValueParser`] that can be used
+///
+/// # Example
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("color")
+/// .long("color")
+/// .value_parser(["always", "auto", "never"])
+/// .default_value("auto")
+/// )
+/// .arg(
+/// clap::Arg::new("hostname")
+/// .long("hostname")
+/// .value_parser(clap::builder::NonEmptyStringValueParser::new())
+/// .action(clap::ArgAction::Set)
+/// .required(true)
+/// )
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(clap::value_parser!(u16).range(3000..))
+/// .action(clap::ArgAction::Set)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(
+/// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"]
+/// ).unwrap();
+///
+/// let color: &String = m.get_one("color")
+/// .expect("default");
+/// assert_eq!(color, "auto");
+///
+/// let hostname: &String = m.get_one("hostname")
+/// .expect("required");
+/// assert_eq!(hostname, "rust-lang.org");
+///
+/// let port: u16 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+pub struct ValueParser(ValueParserInner);
+
+enum ValueParserInner {
+ // Common enough to optimize and for possible values
+ Bool,
+ // Common enough to optimize
+ String,
+ // Common enough to optimize
+ OsString,
+ // Common enough to optimize
+ PathBuf,
+ Other(Box<dyn AnyValueParser>),
+}
+
+impl ValueParser {
+ /// Custom parser for argument values
+ ///
+ /// Pre-existing [`TypedValueParser`] implementations include:
+ /// - `Fn(&str) -> Result<T, E>`
+ /// - [`EnumValueParser`] and [`PossibleValuesParser`] for static enumerated values
+ /// - [`BoolishValueParser`] and [`FalseyValueParser`] for alternative `bool` implementations
+ /// - [`RangedI64ValueParser`] and [`RangedU64ValueParser`]
+ /// - [`NonEmptyStringValueParser`]
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// type EnvVar = (String, Option<String>);
+ /// fn parse_env_var(env: &str) -> Result<EnvVar, std::io::Error> {
+ /// if let Some((var, value)) = env.split_once('=') {
+ /// Ok((var.to_owned(), Some(value.to_owned())))
+ /// } else {
+ /// Ok((env.to_owned(), None))
+ /// }
+ /// }
+ ///
+ /// let mut cmd = clap::Command::new("raw")
+ /// .arg(
+ /// clap::Arg::new("env")
+ /// .value_parser(clap::builder::ValueParser::new(parse_env_var))
+ /// .required(true)
+ /// );
+ ///
+ /// let m = cmd.try_get_matches_from_mut(["cmd", "key=value"]).unwrap();
+ /// let port: &EnvVar = m.get_one("env")
+ /// .expect("required");
+ /// assert_eq!(*port, ("key".into(), Some("value".into())));
+ /// ```
+ pub fn new<P>(other: P) -> Self
+ where
+ P: TypedValueParser,
+ {
+ Self(ValueParserInner::Other(Box::new(other)))
+ }
+
+ /// [`bool`] parser for argument values
+ ///
+ /// See also:
+ /// - [`BoolishValueParser`] for different human readable bool representations
+ /// - [`FalseyValueParser`] for assuming non-false is true
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// let mut cmd = clap::Command::new("raw")
+ /// .arg(
+ /// clap::Arg::new("download")
+ /// .value_parser(clap::value_parser!(bool))
+ /// .required(true)
+ /// );
+ ///
+ /// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap();
+ /// let port: bool = *m.get_one("download")
+ /// .expect("required");
+ /// assert_eq!(port, true);
+ ///
+ /// assert!(cmd.try_get_matches_from_mut(["cmd", "forever"]).is_err());
+ /// ```
+ pub const fn bool() -> Self {
+ Self(ValueParserInner::Bool)
+ }
+
+ /// [`String`] parser for argument values
+ ///
+ /// See also:
+ /// - [`NonEmptyStringValueParser`]
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// let mut cmd = clap::Command::new("raw")
+ /// .arg(
+ /// clap::Arg::new("port")
+ /// .value_parser(clap::value_parser!(String))
+ /// .required(true)
+ /// );
+ ///
+ /// let m = cmd.try_get_matches_from_mut(["cmd", "80"]).unwrap();
+ /// let port: &String = m.get_one("port")
+ /// .expect("required");
+ /// assert_eq!(port, "80");
+ /// ```
+ pub const fn string() -> Self {
+ Self(ValueParserInner::String)
+ }
+
+ /// [`OsString`][std::ffi::OsString] parser for argument values
+ ///
+ /// # Example
+ ///
+ #[cfg_attr(not(unix), doc = " ```ignore")]
+ #[cfg_attr(unix, doc = " ```rust")]
+ /// # use clap::{Command, Arg, builder::ValueParser};
+ /// use std::ffi::OsString;
+ /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
+ /// let r = Command::new("myprog")
+ /// .arg(
+ /// Arg::new("arg")
+ /// .required(true)
+ /// .value_parser(ValueParser::os_string())
+ /// )
+ /// .try_get_matches_from(vec![
+ /// OsString::from("myprog"),
+ /// OsString::from_vec(vec![0xe9])
+ /// ]);
+ ///
+ /// assert!(r.is_ok());
+ /// let m = r.unwrap();
+ /// let arg: &OsString = m.get_one("arg")
+ /// .expect("required");
+ /// assert_eq!(arg.as_bytes(), &[0xe9]);
+ /// ```
+ pub const fn os_string() -> Self {
+ Self(ValueParserInner::OsString)
+ }
+
+ /// [`PathBuf`][std::path::PathBuf] parser for argument values
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// # use std::path::PathBuf;
+ /// # use std::path::Path;
+ /// let mut cmd = clap::Command::new("raw")
+ /// .arg(
+ /// clap::Arg::new("output")
+ /// .value_parser(clap::value_parser!(PathBuf))
+ /// .required(true)
+ /// );
+ ///
+ /// let m = cmd.try_get_matches_from_mut(["cmd", "hello.txt"]).unwrap();
+ /// let port: &PathBuf = m.get_one("output")
+ /// .expect("required");
+ /// assert_eq!(port, Path::new("hello.txt"));
+ ///
+ /// assert!(cmd.try_get_matches_from_mut(["cmd", ""]).is_err());
+ /// ```
+ pub const fn path_buf() -> Self {
+ Self(ValueParserInner::PathBuf)
+ }
+}
+
+impl ValueParser {
+ /// Parse into a `AnyValue`
+ ///
+ /// When `arg` is `None`, an external subcommand value is being parsed.
+ pub(crate) fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<AnyValue, crate::Error> {
+ self.any_value_parser().parse_ref(cmd, arg, value)
+ }
+
+ /// Describes the content of `AnyValue`
+ pub fn type_id(&self) -> AnyValueId {
+ self.any_value_parser().type_id()
+ }
+
+ /// Reflect on enumerated value properties
+ ///
+ /// Error checking should not be done with this; it is mostly targeted at user-facing
+ /// applications like errors and completion.
+ pub fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
+ self.any_value_parser().possible_values()
+ }
+
+ fn any_value_parser(&self) -> &dyn AnyValueParser {
+ match &self.0 {
+ ValueParserInner::Bool => &BoolValueParser {},
+ ValueParserInner::String => &StringValueParser {},
+ ValueParserInner::OsString => &OsStringValueParser {},
+ ValueParserInner::PathBuf => &PathBufValueParser {},
+ ValueParserInner::Other(o) => o.as_ref(),
+ }
+ }
+}
+
+/// Convert a [`TypedValueParser`] to [`ValueParser`]
+///
+/// # Example
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("hostname")
+/// .long("hostname")
+/// .value_parser(clap::builder::NonEmptyStringValueParser::new())
+/// .action(clap::ArgAction::Set)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(
+/// ["cmd", "--hostname", "rust-lang.org"]
+/// ).unwrap();
+///
+/// let hostname: &String = m.get_one("hostname")
+/// .expect("required");
+/// assert_eq!(hostname, "rust-lang.org");
+/// ```
+impl<P> From<P> for ValueParser
+where
+ P: TypedValueParser + Send + Sync + 'static,
+{
+ fn from(p: P) -> Self {
+ Self::new(p)
+ }
+}
+
+impl From<_AnonymousValueParser> for ValueParser {
+ fn from(p: _AnonymousValueParser) -> Self {
+ p.0
+ }
+}
+
+/// Create an `i64` [`ValueParser`] from a `N..M` range
+///
+/// See [`RangedI64ValueParser`] for more control over the output type.
+///
+/// See also [`RangedU64ValueParser`]
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(3000..4000)
+/// .action(clap::ArgAction::Set)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
+/// let port: i64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+impl From<std::ops::Range<i64>> for ValueParser {
+ fn from(value: std::ops::Range<i64>) -> Self {
+ let inner = RangedI64ValueParser::<i64>::new().range(value.start..value.end);
+ Self::from(inner)
+ }
+}
+
+/// Create an `i64` [`ValueParser`] from a `N..=M` range
+///
+/// See [`RangedI64ValueParser`] for more control over the output type.
+///
+/// See also [`RangedU64ValueParser`]
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(3000..=4000)
+/// .action(clap::ArgAction::Set)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
+/// let port: i64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+impl From<std::ops::RangeInclusive<i64>> for ValueParser {
+ fn from(value: std::ops::RangeInclusive<i64>) -> Self {
+ let inner = RangedI64ValueParser::<i64>::new().range(value.start()..=value.end());
+ Self::from(inner)
+ }
+}
+
+/// Create an `i64` [`ValueParser`] from a `N..` range
+///
+/// See [`RangedI64ValueParser`] for more control over the output type.
+///
+/// See also [`RangedU64ValueParser`]
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(3000..)
+/// .action(clap::ArgAction::Set)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
+/// let port: i64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+impl From<std::ops::RangeFrom<i64>> for ValueParser {
+ fn from(value: std::ops::RangeFrom<i64>) -> Self {
+ let inner = RangedI64ValueParser::<i64>::new().range(value.start..);
+ Self::from(inner)
+ }
+}
+
+/// Create an `i64` [`ValueParser`] from a `..M` range
+///
+/// See [`RangedI64ValueParser`] for more control over the output type.
+///
+/// See also [`RangedU64ValueParser`]
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(..3000)
+/// .action(clap::ArgAction::Set)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "80"]).unwrap();
+/// let port: i64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 80);
+/// ```
+impl From<std::ops::RangeTo<i64>> for ValueParser {
+ fn from(value: std::ops::RangeTo<i64>) -> Self {
+ let inner = RangedI64ValueParser::<i64>::new().range(..value.end);
+ Self::from(inner)
+ }
+}
+
+/// Create an `i64` [`ValueParser`] from a `..=M` range
+///
+/// See [`RangedI64ValueParser`] for more control over the output type.
+///
+/// See also [`RangedU64ValueParser`]
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(..=3000)
+/// .action(clap::ArgAction::Set)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "80"]).unwrap();
+/// let port: i64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 80);
+/// ```
+impl From<std::ops::RangeToInclusive<i64>> for ValueParser {
+ fn from(value: std::ops::RangeToInclusive<i64>) -> Self {
+ let inner = RangedI64ValueParser::<i64>::new().range(..=value.end);
+ Self::from(inner)
+ }
+}
+
+/// Create an `i64` [`ValueParser`] from a `..` range
+///
+/// See [`RangedI64ValueParser`] for more control over the output type.
+///
+/// See also [`RangedU64ValueParser`]
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(..)
+/// .action(clap::ArgAction::Set)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
+/// let port: i64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+impl From<std::ops::RangeFull> for ValueParser {
+ fn from(value: std::ops::RangeFull) -> Self {
+ let inner = RangedI64ValueParser::<i64>::new().range(value);
+ Self::from(inner)
+ }
+}
+
+/// Create a [`ValueParser`] with [`PossibleValuesParser`]
+///
+/// See [`PossibleValuesParser`] for more flexibility in creating the
+/// [`PossibleValue`][crate::builder::PossibleValue]s.
+///
+/// # Examples
+///
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("color")
+/// .long("color")
+/// .value_parser(["always", "auto", "never"])
+/// .default_value("auto")
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(
+/// ["cmd", "--color", "never"]
+/// ).unwrap();
+///
+/// let color: &String = m.get_one("color")
+/// .expect("default");
+/// assert_eq!(color, "never");
+/// ```
+impl<P, const C: usize> From<[P; C]> for ValueParser
+where
+ P: Into<super::PossibleValue>,
+{
+ fn from(values: [P; C]) -> Self {
+ let inner = PossibleValuesParser::from(values);
+ Self::from(inner)
+ }
+}
+
+/// Create a [`ValueParser`] with [`PossibleValuesParser`]
+///
+/// See [`PossibleValuesParser`] for more flexibility in creating the
+/// [`PossibleValue`][crate::builder::PossibleValue]s.
+///
+/// # Examples
+///
+/// ```rust
+/// let possible = vec!["always", "auto", "never"];
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("color")
+/// .long("color")
+/// .value_parser(possible)
+/// .default_value("auto")
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(
+/// ["cmd", "--color", "never"]
+/// ).unwrap();
+///
+/// let color: &String = m.get_one("color")
+/// .expect("default");
+/// assert_eq!(color, "never");
+/// ```
+impl<P> From<Vec<P>> for ValueParser
+where
+ P: Into<super::PossibleValue>,
+{
+ fn from(values: Vec<P>) -> Self {
+ let inner = PossibleValuesParser::from(values);
+ Self::from(inner)
+ }
+}
+
+impl std::fmt::Debug for ValueParser {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
+ match &self.0 {
+ ValueParserInner::Bool => f.debug_struct("ValueParser::bool").finish(),
+ ValueParserInner::String => f.debug_struct("ValueParser::string").finish(),
+ ValueParserInner::OsString => f.debug_struct("ValueParser::os_string").finish(),
+ ValueParserInner::PathBuf => f.debug_struct("ValueParser::path_buf").finish(),
+ ValueParserInner::Other(o) => write!(f, "ValueParser::other({:?})", o.type_id()),
+ }
+ }
+}
+
+impl Clone for ValueParser {
+ fn clone(&self) -> Self {
+ Self(match &self.0 {
+ ValueParserInner::Bool => ValueParserInner::Bool,
+ ValueParserInner::String => ValueParserInner::String,
+ ValueParserInner::OsString => ValueParserInner::OsString,
+ ValueParserInner::PathBuf => ValueParserInner::PathBuf,
+ ValueParserInner::Other(o) => ValueParserInner::Other(o.clone_any()),
+ })
+ }
+}
+
+/// A type-erased wrapper for [`TypedValueParser`].
+trait AnyValueParser: Send + Sync + 'static {
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<AnyValue, crate::Error>;
+
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<AnyValue, crate::Error>;
+
+ /// Describes the content of `AnyValue`
+ fn type_id(&self) -> AnyValueId;
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>>;
+
+ fn clone_any(&self) -> Box<dyn AnyValueParser>;
+}
+
+impl<T, P> AnyValueParser for P
+where
+ T: std::any::Any + Clone + Send + Sync + 'static,
+ P: TypedValueParser<Value = T>,
+{
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<AnyValue, crate::Error> {
+ let value = ok!(TypedValueParser::parse_ref(self, cmd, arg, value));
+ Ok(AnyValue::new(value))
+ }
+
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<AnyValue, crate::Error> {
+ let value = ok!(TypedValueParser::parse(self, cmd, arg, value));
+ Ok(AnyValue::new(value))
+ }
+
+ fn type_id(&self) -> AnyValueId {
+ AnyValueId::of::<T>()
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
+ P::possible_values(self)
+ }
+
+ fn clone_any(&self) -> Box<dyn AnyValueParser> {
+ Box::new(self.clone())
+ }
+}
+
+/// Parse/validate argument values
+///
+/// As alternatives to implementing `TypedValueParser`,
+/// - Use `Fn(&str) -> Result<T, E>` which implements `TypedValueParser`
+/// - [`TypedValueParser::map`] or [`TypedValueParser::try_map`] to adapt an existing `TypedValueParser`
+///
+/// See `ValueParserFactory` to register `TypedValueParser::Value` with
+/// [`value_parser!`][crate::value_parser].
+///
+/// # Example
+///
+#[cfg_attr(not(feature = "error-context"), doc = " ```ignore")]
+#[cfg_attr(feature = "error-context", doc = " ```")]
+/// # use clap::error::ErrorKind;
+/// # use clap::error::ContextKind;
+/// # use clap::error::ContextValue;
+/// #[derive(Clone)]
+/// struct Custom(u32);
+///
+/// #[derive(Clone)]
+/// struct CustomValueParser;
+///
+/// impl clap::builder::TypedValueParser for CustomValueParser {
+/// type Value = Custom;
+///
+/// fn parse_ref(
+/// &self,
+/// cmd: &clap::Command,
+/// arg: Option<&clap::Arg>,
+/// value: &std::ffi::OsStr,
+/// ) -> Result<Self::Value, clap::Error> {
+/// let inner = clap::value_parser!(u32);
+/// let val = inner.parse_ref(cmd, arg, value)?;
+///
+/// const INVALID_VALUE: u32 = 10;
+/// if val == INVALID_VALUE {
+/// let mut err = clap::Error::new(ErrorKind::ValueValidation)
+/// .with_cmd(cmd);
+/// if let Some(arg) = arg {
+/// err.insert(ContextKind::InvalidArg, ContextValue::String(arg.to_string()));
+/// }
+/// err.insert(ContextKind::InvalidValue, ContextValue::String(INVALID_VALUE.to_string()));
+/// return Err(err);
+/// }
+///
+/// Ok(Custom(val))
+/// }
+/// }
+/// ```
+pub trait TypedValueParser: Clone + Send + Sync + 'static {
+ /// Argument's value type
+ type Value: Send + Sync + Clone;
+
+ /// Parse the argument value
+ ///
+ /// When `arg` is `None`, an external subcommand value is being parsed.
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error>;
+
+ /// Parse the argument value
+ ///
+ /// When `arg` is `None`, an external subcommand value is being parsed.
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<Self::Value, crate::Error> {
+ self.parse_ref(cmd, arg, &value)
+ }
+
+ /// Reflect on enumerated value properties
+ ///
+ /// Error checking should not be done with this; it is mostly targeted at user-facing
+ /// applications like errors and completion.
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
+ None
+ }
+
+ /// Adapt a `TypedValueParser` from one value to another
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// # use clap::builder::TypedValueParser as _;
+ /// # use clap::builder::BoolishValueParser;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("flag")
+ /// .long("flag")
+ /// .action(clap::ArgAction::SetTrue)
+ /// .value_parser(
+ /// BoolishValueParser::new()
+ /// .map(|b| -> usize {
+ /// if b { 10 } else { 5 }
+ /// })
+ /// )
+ /// );
+ ///
+ /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_one::<usize>("flag").copied(),
+ /// Some(10)
+ /// );
+ ///
+ /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_one::<usize>("flag").copied(),
+ /// Some(5)
+ /// );
+ /// ```
+ fn map<T, F>(self, func: F) -> MapValueParser<Self, F>
+ where
+ T: Send + Sync + Clone,
+ F: Fn(Self::Value) -> T + Clone,
+ {
+ MapValueParser::new(self, func)
+ }
+
+ /// Adapt a `TypedValueParser` from one value to another
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// # use std::ffi::OsString;
+ /// # use std::ffi::OsStr;
+ /// # use std::path::PathBuf;
+ /// # use std::path::Path;
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// # use clap::builder::TypedValueParser as _;
+ /// # use clap::builder::OsStringValueParser;
+ /// let cmd = Command::new("mycmd")
+ /// .arg(
+ /// Arg::new("flag")
+ /// .long("flag")
+ /// .value_parser(
+ /// OsStringValueParser::new()
+ /// .try_map(verify_ext)
+ /// )
+ /// );
+ ///
+ /// fn verify_ext(os: OsString) -> Result<PathBuf, &'static str> {
+ /// let path = PathBuf::from(os);
+ /// if path.extension() != Some(OsStr::new("rs")) {
+ /// return Err("only Rust files are supported");
+ /// }
+ /// Ok(path)
+ /// }
+ ///
+ /// let error = cmd.clone().try_get_matches_from(["mycmd", "--flag", "foo.txt"]).unwrap_err();
+ /// error.print();
+ ///
+ /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "foo.rs"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_one::<PathBuf>("flag").map(|s| s.as_path()),
+ /// Some(Path::new("foo.rs"))
+ /// );
+ /// ```
+ fn try_map<T, E, F>(self, func: F) -> TryMapValueParser<Self, F>
+ where
+ F: Fn(Self::Value) -> Result<T, E> + Clone + Send + Sync + 'static,
+ T: Send + Sync + Clone,
+ E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
+ {
+ TryMapValueParser::new(self, func)
+ }
+}
+
+impl<F, T, E> TypedValueParser for F
+where
+ F: Fn(&str) -> Result<T, E> + Clone + Send + Sync + 'static,
+ E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
+ T: Send + Sync + Clone,
+{
+ type Value = T;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = ok!(value.to_str().ok_or_else(|| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ }));
+ let value = ok!((self)(value).map_err(|e| {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ crate::Error::value_validation(arg, value.to_owned(), e.into()).with_cmd(cmd)
+ }));
+ Ok(value)
+ }
+}
+
+/// Implementation for [`ValueParser::string`]
+///
+/// Useful for composing new [`TypedValueParser`]s
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct StringValueParser {}
+
+impl StringValueParser {
+ /// Implementation for [`ValueParser::string`]
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl TypedValueParser for StringValueParser {
+ type Value = String;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ TypedValueParser::parse(self, cmd, arg, value.to_owned())
+ }
+
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ _arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = ok!(value.into_string().map_err(|_| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ }));
+ Ok(value)
+ }
+}
+
+impl Default for StringValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Implementation for [`ValueParser::os_string`]
+///
+/// Useful for composing new [`TypedValueParser`]s
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct OsStringValueParser {}
+
+impl OsStringValueParser {
+ /// Implementation for [`ValueParser::os_string`]
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl TypedValueParser for OsStringValueParser {
+ type Value = std::ffi::OsString;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ TypedValueParser::parse(self, cmd, arg, value.to_owned())
+ }
+
+ fn parse(
+ &self,
+ _cmd: &crate::Command,
+ _arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<Self::Value, crate::Error> {
+ Ok(value)
+ }
+}
+
+impl Default for OsStringValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Implementation for [`ValueParser::path_buf`]
+///
+/// Useful for composing new [`TypedValueParser`]s
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct PathBufValueParser {}
+
+impl PathBufValueParser {
+ /// Implementation for [`ValueParser::path_buf`]
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl TypedValueParser for PathBufValueParser {
+ type Value = std::path::PathBuf;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ TypedValueParser::parse(self, cmd, arg, value.to_owned())
+ }
+
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<Self::Value, crate::Error> {
+ if value.is_empty() {
+ return Err(crate::Error::empty_value(
+ cmd,
+ &[],
+ arg.map(ToString::to_string)
+ .unwrap_or_else(|| "...".to_owned()),
+ ));
+ }
+ Ok(Self::Value::from(value))
+ }
+}
+
+impl Default for PathBufValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Parse an [`ValueEnum`][crate::ValueEnum] value.
+///
+/// See also:
+/// - [`PossibleValuesParser`]
+///
+/// # Example
+///
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::ColorChoice;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+///
+/// // Usage
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("color")
+/// .value_parser(clap::builder::EnumValueParser::<ColorChoice>::new())
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "always"]).unwrap();
+/// let port: ColorChoice = *m.get_one("color")
+/// .expect("required");
+/// assert_eq!(port, ColorChoice::Always);
+///
+/// // Semantics
+/// let value_parser = clap::builder::EnumValueParser::<ColorChoice>::new();
+/// // or
+/// let value_parser = clap::value_parser!(ColorChoice);
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("always")).unwrap(), ColorChoice::Always);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("auto")).unwrap(), ColorChoice::Auto);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("never")).unwrap(), ColorChoice::Never);
+/// ```
+#[derive(Clone, Debug)]
+pub struct EnumValueParser<E: crate::ValueEnum + Clone + Send + Sync + 'static>(
+ std::marker::PhantomData<E>,
+);
+
+impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> EnumValueParser<E> {
+ /// Parse an [`ValueEnum`][crate::ValueEnum]
+ pub fn new() -> Self {
+ let phantom: std::marker::PhantomData<E> = Default::default();
+ Self(phantom)
+ }
+}
+
+impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> TypedValueParser for EnumValueParser<E> {
+ type Value = E;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false);
+ let possible_vals = || {
+ E::value_variants()
+ .iter()
+ .filter_map(|v| v.to_possible_value())
+ .filter(|v| !v.is_hide_set())
+ .map(|v| v.get_name().to_owned())
+ .collect::<Vec<_>>()
+ };
+
+ let value = ok!(value.to_str().ok_or_else(|| {
+ crate::Error::invalid_value(
+ cmd,
+ value.to_string_lossy().into_owned(),
+ &possible_vals(),
+ arg.map(ToString::to_string)
+ .unwrap_or_else(|| "...".to_owned()),
+ )
+ }));
+ let value = ok!(E::value_variants()
+ .iter()
+ .find(|v| {
+ v.to_possible_value()
+ .expect("ValueEnum::value_variants contains only values with a corresponding ValueEnum::to_possible_value")
+ .matches(value, ignore_case)
+ })
+ .ok_or_else(|| {
+ crate::Error::invalid_value(
+ cmd,
+ value.to_owned(),
+ &possible_vals(),
+ arg.map(ToString::to_string)
+ .unwrap_or_else(|| "...".to_owned()),
+ )
+ }))
+ .clone();
+ Ok(value)
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
+ Some(Box::new(
+ E::value_variants()
+ .iter()
+ .filter_map(|v| v.to_possible_value()),
+ ))
+ }
+}
+
+impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> Default for EnumValueParser<E> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Verify the value is from an enumerated set of [`PossibleValue`][crate::builder::PossibleValue].
+///
+/// See also:
+/// - [`EnumValueParser`] for directly supporting [`ValueEnum`][crate::ValueEnum] types
+/// - [`TypedValueParser::map`] for adapting values to a more specialized type, like an external
+/// enums that can't implement [`ValueEnum`][crate::ValueEnum]
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("color")
+/// .value_parser(clap::builder::PossibleValuesParser::new(["always", "auto", "never"]))
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "always"]).unwrap();
+/// let port: &String = m.get_one("color")
+/// .expect("required");
+/// assert_eq!(port, "always");
+/// ```
+///
+/// Semantics:
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+/// let value_parser = clap::builder::PossibleValuesParser::new(["always", "auto", "never"]);
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("always")).unwrap(), "always");
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("auto")).unwrap(), "auto");
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("never")).unwrap(), "never");
+/// ```
+#[derive(Clone, Debug)]
+pub struct PossibleValuesParser(Vec<super::PossibleValue>);
+
+impl PossibleValuesParser {
+ /// Verify the value is from an enumerated set pf [`PossibleValue`][crate::builder::PossibleValue].
+ pub fn new(values: impl Into<PossibleValuesParser>) -> Self {
+ values.into()
+ }
+}
+
+impl TypedValueParser for PossibleValuesParser {
+ type Value = String;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ TypedValueParser::parse(self, cmd, arg, value.to_owned())
+ }
+
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<String, crate::Error> {
+ let value = ok!(value.into_string().map_err(|_| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ }));
+
+ let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false);
+ if self.0.iter().any(|v| v.matches(&value, ignore_case)) {
+ Ok(value)
+ } else {
+ let possible_vals = self
+ .0
+ .iter()
+ .filter(|v| !v.is_hide_set())
+ .map(|v| v.get_name().to_owned())
+ .collect::<Vec<_>>();
+
+ Err(crate::Error::invalid_value(
+ cmd,
+ value,
+ &possible_vals,
+ arg.map(ToString::to_string)
+ .unwrap_or_else(|| "...".to_owned()),
+ ))
+ }
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
+ Some(Box::new(self.0.iter().cloned()))
+ }
+}
+
+impl<I, T> From<I> for PossibleValuesParser
+where
+ I: IntoIterator<Item = T>,
+ T: Into<super::PossibleValue>,
+{
+ fn from(values: I) -> Self {
+ Self(values.into_iter().map(|t| t.into()).collect())
+ }
+}
+
+/// Parse number that fall within a range of values
+///
+/// **NOTE:** To capture negative values, you will also need to set
+/// [`Arg::allow_negative_numbers`][crate::Arg::allow_negative_numbers] or
+/// [`Arg::allow_hyphen_values`][crate::Arg::allow_hyphen_values].
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(clap::value_parser!(u16).range(3000..))
+/// .action(clap::ArgAction::Set)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
+/// let port: u16 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+///
+/// Semantics:
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+/// let value_parser = clap::builder::RangedI64ValueParser::<i32>::new().range(-1..200);
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-200")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("300")).is_err());
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("-1")).unwrap(), -1);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), 0);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("50")).unwrap(), 50);
+/// ```
+#[derive(Copy, Clone, Debug)]
+pub struct RangedI64ValueParser<T: std::convert::TryFrom<i64> + Clone + Send + Sync = i64> {
+ bounds: (std::ops::Bound<i64>, std::ops::Bound<i64>),
+ target: std::marker::PhantomData<T>,
+}
+
+impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync> RangedI64ValueParser<T> {
+ /// Select full range of `i64`
+ pub fn new() -> Self {
+ Self::from(..)
+ }
+
+ /// Narrow the supported range
+ pub fn range<B: RangeBounds<i64>>(mut self, range: B) -> Self {
+ // Consideration: when the user does `value_parser!(u8).range()`
+ // - Avoid programming mistakes by accidentally expanding the range
+ // - Make it convenient to limit the range like with `..10`
+ let start = match range.start_bound() {
+ l @ std::ops::Bound::Included(i) => {
+ debug_assert!(
+ self.bounds.contains(i),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ l @ std::ops::Bound::Excluded(i) => {
+ debug_assert!(
+ self.bounds.contains(&i.saturating_add(1)),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ std::ops::Bound::Unbounded => self.bounds.start_bound().cloned(),
+ };
+ let end = match range.end_bound() {
+ l @ std::ops::Bound::Included(i) => {
+ debug_assert!(
+ self.bounds.contains(i),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ l @ std::ops::Bound::Excluded(i) => {
+ debug_assert!(
+ self.bounds.contains(&i.saturating_sub(1)),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ std::ops::Bound::Unbounded => self.bounds.end_bound().cloned(),
+ };
+ self.bounds = (start, end);
+ self
+ }
+
+ fn format_bounds(&self) -> String {
+ let mut result = match self.bounds.0 {
+ std::ops::Bound::Included(i) => i.to_string(),
+ std::ops::Bound::Excluded(i) => i.saturating_add(1).to_string(),
+ std::ops::Bound::Unbounded => i64::MIN.to_string(),
+ };
+ result.push_str("..");
+ match self.bounds.1 {
+ std::ops::Bound::Included(i) => {
+ result.push('=');
+ result.push_str(&i.to_string());
+ }
+ std::ops::Bound::Excluded(i) => {
+ result.push_str(&i.to_string());
+ }
+ std::ops::Bound::Unbounded => {
+ result.push_str(&i64::MAX.to_string());
+ }
+ }
+ result
+ }
+}
+
+impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync + 'static> TypedValueParser
+ for RangedI64ValueParser<T>
+where
+ <T as std::convert::TryFrom<i64>>::Error: Send + Sync + 'static + std::error::Error + ToString,
+{
+ type Value = T;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ raw_value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = ok!(raw_value.to_str().ok_or_else(|| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ }));
+ let value = ok!(value.parse::<i64>().map_err(|err| {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ crate::Error::value_validation(
+ arg,
+ raw_value.to_string_lossy().into_owned(),
+ err.into(),
+ )
+ .with_cmd(cmd)
+ }));
+ if !self.bounds.contains(&value) {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ return Err(crate::Error::value_validation(
+ arg,
+ raw_value.to_string_lossy().into_owned(),
+ format!("{} is not in {}", value, self.format_bounds()).into(),
+ )
+ .with_cmd(cmd));
+ }
+
+ let value: Result<Self::Value, _> = value.try_into();
+ let value = ok!(value.map_err(|err| {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ crate::Error::value_validation(
+ arg,
+ raw_value.to_string_lossy().into_owned(),
+ err.into(),
+ )
+ .with_cmd(cmd)
+ }));
+
+ Ok(value)
+ }
+}
+
+impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync, B: RangeBounds<i64>> From<B>
+ for RangedI64ValueParser<T>
+{
+ fn from(range: B) -> Self {
+ Self {
+ bounds: (range.start_bound().cloned(), range.end_bound().cloned()),
+ target: Default::default(),
+ }
+ }
+}
+
+impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync> Default for RangedI64ValueParser<T> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Parse number that fall within a range of values
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("port")
+/// .long("port")
+/// .value_parser(clap::value_parser!(u64).range(3000..))
+/// .action(clap::ArgAction::Set)
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap();
+/// let port: u64 = *m.get_one("port")
+/// .expect("required");
+/// assert_eq!(port, 3001);
+/// ```
+///
+/// Semantics:
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+/// let value_parser = clap::builder::RangedU64ValueParser::<u32>::new().range(0..200);
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-200")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("300")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-1")).is_err());
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), 0);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("50")).unwrap(), 50);
+/// ```
+#[derive(Copy, Clone, Debug)]
+pub struct RangedU64ValueParser<T: std::convert::TryFrom<u64> = u64> {
+ bounds: (std::ops::Bound<u64>, std::ops::Bound<u64>),
+ target: std::marker::PhantomData<T>,
+}
+
+impl<T: std::convert::TryFrom<u64>> RangedU64ValueParser<T> {
+ /// Select full range of `u64`
+ pub fn new() -> Self {
+ Self::from(..)
+ }
+
+ /// Narrow the supported range
+ pub fn range<B: RangeBounds<u64>>(mut self, range: B) -> Self {
+ // Consideration: when the user does `value_parser!(u8).range()`
+ // - Avoid programming mistakes by accidentally expanding the range
+ // - Make it convenient to limit the range like with `..10`
+ let start = match range.start_bound() {
+ l @ std::ops::Bound::Included(i) => {
+ debug_assert!(
+ self.bounds.contains(i),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ l @ std::ops::Bound::Excluded(i) => {
+ debug_assert!(
+ self.bounds.contains(&i.saturating_add(1)),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ std::ops::Bound::Unbounded => self.bounds.start_bound().cloned(),
+ };
+ let end = match range.end_bound() {
+ l @ std::ops::Bound::Included(i) => {
+ debug_assert!(
+ self.bounds.contains(i),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ l @ std::ops::Bound::Excluded(i) => {
+ debug_assert!(
+ self.bounds.contains(&i.saturating_sub(1)),
+ "{} must be in {:?}",
+ i,
+ self.bounds
+ );
+ l.cloned()
+ }
+ std::ops::Bound::Unbounded => self.bounds.end_bound().cloned(),
+ };
+ self.bounds = (start, end);
+ self
+ }
+
+ fn format_bounds(&self) -> String {
+ let mut result = match self.bounds.0 {
+ std::ops::Bound::Included(i) => i.to_string(),
+ std::ops::Bound::Excluded(i) => i.saturating_add(1).to_string(),
+ std::ops::Bound::Unbounded => u64::MIN.to_string(),
+ };
+ result.push_str("..");
+ match self.bounds.1 {
+ std::ops::Bound::Included(i) => {
+ result.push('=');
+ result.push_str(&i.to_string());
+ }
+ std::ops::Bound::Excluded(i) => {
+ result.push_str(&i.to_string());
+ }
+ std::ops::Bound::Unbounded => {
+ result.push_str(&u64::MAX.to_string());
+ }
+ }
+ result
+ }
+}
+
+impl<T: std::convert::TryFrom<u64> + Clone + Send + Sync + 'static> TypedValueParser
+ for RangedU64ValueParser<T>
+where
+ <T as std::convert::TryFrom<u64>>::Error: Send + Sync + 'static + std::error::Error + ToString,
+{
+ type Value = T;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ raw_value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = ok!(raw_value.to_str().ok_or_else(|| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ }));
+ let value = ok!(value.parse::<u64>().map_err(|err| {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ crate::Error::value_validation(
+ arg,
+ raw_value.to_string_lossy().into_owned(),
+ err.into(),
+ )
+ .with_cmd(cmd)
+ }));
+ if !self.bounds.contains(&value) {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ return Err(crate::Error::value_validation(
+ arg,
+ raw_value.to_string_lossy().into_owned(),
+ format!("{} is not in {}", value, self.format_bounds()).into(),
+ )
+ .with_cmd(cmd));
+ }
+
+ let value: Result<Self::Value, _> = value.try_into();
+ let value = ok!(value.map_err(|err| {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ crate::Error::value_validation(
+ arg,
+ raw_value.to_string_lossy().into_owned(),
+ err.into(),
+ )
+ .with_cmd(cmd)
+ }));
+
+ Ok(value)
+ }
+}
+
+impl<T: std::convert::TryFrom<u64>, B: RangeBounds<u64>> From<B> for RangedU64ValueParser<T> {
+ fn from(range: B) -> Self {
+ Self {
+ bounds: (range.start_bound().cloned(), range.end_bound().cloned()),
+ target: Default::default(),
+ }
+ }
+}
+
+impl<T: std::convert::TryFrom<u64>> Default for RangedU64ValueParser<T> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Implementation for [`ValueParser::bool`]
+///
+/// Useful for composing new [`TypedValueParser`]s
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct BoolValueParser {}
+
+impl BoolValueParser {
+ /// Implementation for [`ValueParser::bool`]
+ pub fn new() -> Self {
+ Self {}
+ }
+
+ fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> {
+ ["true", "false"]
+ .iter()
+ .copied()
+ .map(crate::builder::PossibleValue::new)
+ }
+}
+
+impl TypedValueParser for BoolValueParser {
+ type Value = bool;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = if value == std::ffi::OsStr::new("true") {
+ true
+ } else if value == std::ffi::OsStr::new("false") {
+ false
+ } else {
+ // Intentionally showing hidden as we hide all of them
+ let possible_vals = Self::possible_values()
+ .map(|v| v.get_name().to_owned())
+ .collect::<Vec<_>>();
+
+ return Err(crate::Error::invalid_value(
+ cmd,
+ value.to_string_lossy().into_owned(),
+ &possible_vals,
+ arg.map(ToString::to_string)
+ .unwrap_or_else(|| "...".to_owned()),
+ ));
+ };
+ Ok(value)
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
+ Some(Box::new(Self::possible_values()))
+ }
+}
+
+impl Default for BoolValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Parse false-like string values, everything else is `true`
+///
+/// See also:
+/// - [`ValueParser::bool`] for assuming non-false is true
+/// - [`BoolishValueParser`] for different human readable bool representations
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("append")
+/// .value_parser(clap::builder::FalseyValueParser::new())
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap();
+/// let port: bool = *m.get_one("append")
+/// .expect("required");
+/// assert_eq!(port, true);
+/// ```
+///
+/// Semantics:
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+/// let value_parser = clap::builder::FalseyValueParser::new();
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).unwrap(), true);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("100")).unwrap(), true);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("false")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("No")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oFF")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), false);
+/// ```
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct FalseyValueParser {}
+
+impl FalseyValueParser {
+ /// Parse false-like string values, everything else is `true`
+ pub fn new() -> Self {
+ Self {}
+ }
+
+ fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> {
+ crate::util::TRUE_LITERALS
+ .iter()
+ .chain(crate::util::FALSE_LITERALS.iter())
+ .copied()
+ .map(|l| crate::builder::PossibleValue::new(l).hide(l != "true" && l != "false"))
+ }
+}
+
+impl TypedValueParser for FalseyValueParser {
+ type Value = bool;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ _arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = ok!(value.to_str().ok_or_else(|| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ }));
+ let value = if value.is_empty() {
+ false
+ } else {
+ crate::util::str_to_bool(value).unwrap_or(true)
+ };
+ Ok(value)
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
+ Some(Box::new(Self::possible_values()))
+ }
+}
+
+impl Default for FalseyValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Parse bool-like string values, everything else is `true`
+///
+/// See also:
+/// - [`ValueParser::bool`] for different human readable bool representations
+/// - [`FalseyValueParser`] for assuming non-false is true
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("append")
+/// .value_parser(clap::builder::BoolishValueParser::new())
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap();
+/// let port: bool = *m.get_one("append")
+/// .expect("required");
+/// assert_eq!(port, true);
+/// ```
+///
+/// Semantics:
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+/// let value_parser = clap::builder::BoolishValueParser::new();
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("100")).is_err());
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("true")).unwrap(), true);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("Yes")).unwrap(), true);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oN")).unwrap(), true);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("1")).unwrap(), true);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("false")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("No")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oFF")).unwrap(), false);
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), false);
+/// ```
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct BoolishValueParser {}
+
+impl BoolishValueParser {
+ /// Parse bool-like string values, everything else is `true`
+ pub fn new() -> Self {
+ Self {}
+ }
+
+ fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> {
+ crate::util::TRUE_LITERALS
+ .iter()
+ .chain(crate::util::FALSE_LITERALS.iter())
+ .copied()
+ .map(|l| crate::builder::PossibleValue::new(l).hide(l != "true" && l != "false"))
+ }
+}
+
+impl TypedValueParser for BoolishValueParser {
+ type Value = bool;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = ok!(value.to_str().ok_or_else(|| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ }));
+ let value = ok!(crate::util::str_to_bool(value).ok_or_else(|| {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ crate::Error::value_validation(arg, value.to_owned(), "value was not a boolean".into())
+ .with_cmd(cmd)
+ }));
+ Ok(value)
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
+ Some(Box::new(Self::possible_values()))
+ }
+}
+
+impl Default for BoolishValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Parse non-empty string values
+///
+/// See also:
+/// - [`ValueParser::string`]
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("append")
+/// .value_parser(clap::builder::NonEmptyStringValueParser::new())
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap();
+/// let port: &String = m.get_one("append")
+/// .expect("required");
+/// assert_eq!(port, "true");
+/// ```
+///
+/// Semantics:
+/// ```rust
+/// # use std::ffi::OsStr;
+/// # use clap::builder::TypedValueParser;
+/// # let cmd = clap::Command::new("test");
+/// # let arg = None;
+/// let value_parser = clap::builder::NonEmptyStringValueParser::new();
+/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).unwrap(), "random");
+/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err());
+/// ```
+#[derive(Copy, Clone, Debug)]
+#[non_exhaustive]
+pub struct NonEmptyStringValueParser {}
+
+impl NonEmptyStringValueParser {
+ /// Parse non-empty string values
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl TypedValueParser for NonEmptyStringValueParser {
+ type Value = String;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ if value.is_empty() {
+ return Err(crate::Error::empty_value(
+ cmd,
+ &[],
+ arg.map(ToString::to_string)
+ .unwrap_or_else(|| "...".to_owned()),
+ ));
+ }
+ let value = ok!(value.to_str().ok_or_else(|| {
+ crate::Error::invalid_utf8(
+ cmd,
+ crate::output::Usage::new(cmd).create_usage_with_title(&[]),
+ )
+ }));
+ Ok(value.to_owned())
+ }
+}
+
+impl Default for NonEmptyStringValueParser {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Adapt a `TypedValueParser` from one value to another
+///
+/// See [`TypedValueParser::map`]
+#[derive(Clone, Debug)]
+pub struct MapValueParser<P, F> {
+ parser: P,
+ func: F,
+}
+
+impl<P, F, T> MapValueParser<P, F>
+where
+ P: TypedValueParser,
+ P::Value: Send + Sync + Clone,
+ F: Fn(P::Value) -> T + Clone,
+ T: Send + Sync + Clone,
+{
+ fn new(parser: P, func: F) -> Self {
+ Self { parser, func }
+ }
+}
+
+impl<P, F, T> TypedValueParser for MapValueParser<P, F>
+where
+ P: TypedValueParser,
+ P::Value: Send + Sync + Clone,
+ F: Fn(P::Value) -> T + Clone + Send + Sync + 'static,
+ T: Send + Sync + Clone,
+{
+ type Value = T;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = ok!(self.parser.parse_ref(cmd, arg, value));
+ let value = (self.func)(value);
+ Ok(value)
+ }
+
+ fn parse(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: std::ffi::OsString,
+ ) -> Result<Self::Value, crate::Error> {
+ let value = ok!(self.parser.parse(cmd, arg, value));
+ let value = (self.func)(value);
+ Ok(value)
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
+ self.parser.possible_values()
+ }
+}
+
+/// Adapt a `TypedValueParser` from one value to another
+///
+/// See [`TypedValueParser::try_map`]
+#[derive(Clone, Debug)]
+pub struct TryMapValueParser<P, F> {
+ parser: P,
+ func: F,
+}
+
+impl<P, F, T, E> TryMapValueParser<P, F>
+where
+ P: TypedValueParser,
+ P::Value: Send + Sync + Clone,
+ F: Fn(P::Value) -> Result<T, E> + Clone + Send + Sync + 'static,
+ T: Send + Sync + Clone,
+ E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
+{
+ fn new(parser: P, func: F) -> Self {
+ Self { parser, func }
+ }
+}
+
+impl<P, F, T, E> TypedValueParser for TryMapValueParser<P, F>
+where
+ P: TypedValueParser,
+ P::Value: Send + Sync + Clone,
+ F: Fn(P::Value) -> Result<T, E> + Clone + Send + Sync + 'static,
+ T: Send + Sync + Clone,
+ E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
+{
+ type Value = T;
+
+ fn parse_ref(
+ &self,
+ cmd: &crate::Command,
+ arg: Option<&crate::Arg>,
+ value: &std::ffi::OsStr,
+ ) -> Result<Self::Value, crate::Error> {
+ let mid_value = ok!(self.parser.parse_ref(cmd, arg, value));
+ let value = ok!((self.func)(mid_value).map_err(|e| {
+ let arg = arg
+ .map(|a| a.to_string())
+ .unwrap_or_else(|| "...".to_owned());
+ crate::Error::value_validation(arg, value.to_string_lossy().into_owned(), e.into())
+ .with_cmd(cmd)
+ }));
+ Ok(value)
+ }
+
+ fn possible_values(
+ &self,
+ ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> {
+ self.parser.possible_values()
+ }
+}
+
+/// Register a type with [value_parser!][crate::value_parser!]
+///
+/// # Example
+///
+/// ```rust
+/// #[derive(Copy, Clone, Debug)]
+/// pub struct Custom(u32);
+///
+/// impl clap::builder::ValueParserFactory for Custom {
+/// type Parser = CustomValueParser;
+/// fn value_parser() -> Self::Parser {
+/// CustomValueParser
+/// }
+/// }
+///
+/// #[derive(Clone, Debug)]
+/// pub struct CustomValueParser;
+/// impl clap::builder::TypedValueParser for CustomValueParser {
+/// type Value = Custom;
+///
+/// fn parse_ref(
+/// &self,
+/// cmd: &clap::Command,
+/// arg: Option<&clap::Arg>,
+/// value: &std::ffi::OsStr,
+/// ) -> Result<Self::Value, clap::Error> {
+/// let inner = clap::value_parser!(u32);
+/// let val = inner.parse_ref(cmd, arg, value)?;
+/// Ok(Custom(val))
+/// }
+/// }
+///
+/// let parser: CustomValueParser = clap::value_parser!(Custom);
+/// ```
+pub trait ValueParserFactory {
+ /// Generated parser, usually [`ValueParser`].
+ ///
+ /// It should at least be a type that supports `Into<ValueParser>`. A non-`ValueParser` type
+ /// allows the caller to do further initialization on the parser.
+ type Parser;
+
+ /// Create the specified [`Self::Parser`]
+ fn value_parser() -> Self::Parser;
+}
+impl ValueParserFactory for String {
+ type Parser = ValueParser;
+ fn value_parser() -> Self::Parser {
+ ValueParser::string() // Default `clap_derive` to optimized implementation
+ }
+}
+impl ValueParserFactory for std::ffi::OsString {
+ type Parser = ValueParser;
+ fn value_parser() -> Self::Parser {
+ ValueParser::os_string() // Default `clap_derive` to optimized implementation
+ }
+}
+impl ValueParserFactory for std::path::PathBuf {
+ type Parser = ValueParser;
+ fn value_parser() -> Self::Parser {
+ ValueParser::path_buf() // Default `clap_derive` to optimized implementation
+ }
+}
+impl ValueParserFactory for bool {
+ type Parser = ValueParser;
+ fn value_parser() -> Self::Parser {
+ ValueParser::bool() // Default `clap_derive` to optimized implementation
+ }
+}
+impl ValueParserFactory for u8 {
+ type Parser = RangedI64ValueParser<u8>;
+ fn value_parser() -> Self::Parser {
+ let start: i64 = u8::MIN.into();
+ let end: i64 = u8::MAX.into();
+ RangedI64ValueParser::new().range(start..=end)
+ }
+}
+impl ValueParserFactory for i8 {
+ type Parser = RangedI64ValueParser<i8>;
+ fn value_parser() -> Self::Parser {
+ let start: i64 = i8::MIN.into();
+ let end: i64 = i8::MAX.into();
+ RangedI64ValueParser::new().range(start..=end)
+ }
+}
+impl ValueParserFactory for u16 {
+ type Parser = RangedI64ValueParser<u16>;
+ fn value_parser() -> Self::Parser {
+ let start: i64 = u16::MIN.into();
+ let end: i64 = u16::MAX.into();
+ RangedI64ValueParser::new().range(start..=end)
+ }
+}
+impl ValueParserFactory for i16 {
+ type Parser = RangedI64ValueParser<i16>;
+ fn value_parser() -> Self::Parser {
+ let start: i64 = i16::MIN.into();
+ let end: i64 = i16::MAX.into();
+ RangedI64ValueParser::new().range(start..=end)
+ }
+}
+impl ValueParserFactory for u32 {
+ type Parser = RangedI64ValueParser<u32>;
+ fn value_parser() -> Self::Parser {
+ let start: i64 = u32::MIN.into();
+ let end: i64 = u32::MAX.into();
+ RangedI64ValueParser::new().range(start..=end)
+ }
+}
+impl ValueParserFactory for i32 {
+ type Parser = RangedI64ValueParser<i32>;
+ fn value_parser() -> Self::Parser {
+ let start: i64 = i32::MIN.into();
+ let end: i64 = i32::MAX.into();
+ RangedI64ValueParser::new().range(start..=end)
+ }
+}
+impl ValueParserFactory for i64 {
+ type Parser = RangedI64ValueParser<i64>;
+ fn value_parser() -> Self::Parser {
+ RangedI64ValueParser::new()
+ }
+}
+impl ValueParserFactory for u64 {
+ type Parser = RangedU64ValueParser<u64>;
+ fn value_parser() -> Self::Parser {
+ RangedU64ValueParser::new()
+ }
+}
+
+#[doc(hidden)]
+#[derive(Debug)]
+pub struct _AutoValueParser<T>(std::marker::PhantomData<T>);
+
+impl<T> _AutoValueParser<T> {
+ #[doc(hidden)]
+ #[allow(clippy::new_without_default)]
+ pub fn new() -> Self {
+ Self(Default::default())
+ }
+}
+
+/// Unstable [`ValueParser`]
+///
+/// Implementation may change to more specific instance in the future
+#[doc(hidden)]
+#[derive(Debug)]
+pub struct _AnonymousValueParser(ValueParser);
+
+#[doc(hidden)]
+pub mod via_prelude {
+ use super::*;
+
+ #[doc(hidden)]
+ pub trait _ValueParserViaFactory: private::_ValueParserViaFactorySealed {
+ type Parser;
+ fn value_parser(&self) -> Self::Parser;
+ }
+ impl<P: ValueParserFactory> _ValueParserViaFactory for &&&&&&_AutoValueParser<P> {
+ type Parser = P::Parser;
+ fn value_parser(&self) -> Self::Parser {
+ P::value_parser()
+ }
+ }
+
+ #[doc(hidden)]
+ pub trait _ValueParserViaValueEnum: private::_ValueParserViaValueEnumSealed {
+ type Output;
+
+ fn value_parser(&self) -> Self::Output;
+ }
+ impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> _ValueParserViaValueEnum
+ for &&&&&_AutoValueParser<E>
+ {
+ type Output = EnumValueParser<E>;
+
+ fn value_parser(&self) -> Self::Output {
+ EnumValueParser::<E>::new()
+ }
+ }
+
+ #[doc(hidden)]
+ pub trait _ValueParserViaFromOsString: private::_ValueParserViaFromOsStringSealed {
+ fn value_parser(&self) -> _AnonymousValueParser;
+ }
+ impl<FromOsString> _ValueParserViaFromOsString for &&&&_AutoValueParser<FromOsString>
+ where
+ FromOsString: From<std::ffi::OsString> + std::any::Any + Clone + Send + Sync + 'static,
+ {
+ fn value_parser(&self) -> _AnonymousValueParser {
+ _AnonymousValueParser(
+ OsStringValueParser::new()
+ .map(|s| FromOsString::from(s))
+ .into(),
+ )
+ }
+ }
+
+ #[doc(hidden)]
+ pub trait _ValueParserViaFromOsStr: private::_ValueParserViaFromOsStrSealed {
+ fn value_parser(&self) -> _AnonymousValueParser;
+ }
+ impl<FromOsStr> _ValueParserViaFromOsStr for &&&_AutoValueParser<FromOsStr>
+ where
+ FromOsStr:
+ for<'s> From<&'s std::ffi::OsStr> + std::any::Any + Clone + Send + Sync + 'static,
+ {
+ fn value_parser(&self) -> _AnonymousValueParser {
+ _AnonymousValueParser(
+ OsStringValueParser::new()
+ .map(|s| FromOsStr::from(&s))
+ .into(),
+ )
+ }
+ }
+
+ #[doc(hidden)]
+ pub trait _ValueParserViaFromString: private::_ValueParserViaFromStringSealed {
+ fn value_parser(&self) -> _AnonymousValueParser;
+ }
+ impl<FromString> _ValueParserViaFromString for &&_AutoValueParser<FromString>
+ where
+ FromString: From<String> + std::any::Any + Clone + Send + Sync + 'static,
+ {
+ fn value_parser(&self) -> _AnonymousValueParser {
+ _AnonymousValueParser(StringValueParser::new().map(|s| FromString::from(s)).into())
+ }
+ }
+
+ #[doc(hidden)]
+ pub trait _ValueParserViaFromStr: private::_ValueParserViaFromStrSealed {
+ fn value_parser(&self) -> _AnonymousValueParser;
+ }
+ impl<FromStr> _ValueParserViaFromStr for &_AutoValueParser<FromStr>
+ where
+ FromStr: for<'s> From<&'s str> + std::any::Any + Clone + Send + Sync + 'static,
+ {
+ fn value_parser(&self) -> _AnonymousValueParser {
+ _AnonymousValueParser(StringValueParser::new().map(|s| FromStr::from(&s)).into())
+ }
+ }
+
+ #[doc(hidden)]
+ pub trait _ValueParserViaParse: private::_ValueParserViaParseSealed {
+ fn value_parser(&self) -> _AnonymousValueParser;
+ }
+ impl<Parse> _ValueParserViaParse for _AutoValueParser<Parse>
+ where
+ Parse: std::str::FromStr + std::any::Any + Clone + Send + Sync + 'static,
+ <Parse as std::str::FromStr>::Err: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
+ {
+ fn value_parser(&self) -> _AnonymousValueParser {
+ let func: fn(&str) -> Result<Parse, <Parse as std::str::FromStr>::Err> =
+ Parse::from_str;
+ _AnonymousValueParser(ValueParser::new(func))
+ }
+ }
+}
+
+/// Select a [`ValueParser`] implementation from the intended type
+///
+/// Supported types
+/// - [`ValueParserFactory` types][ValueParserFactory], including
+/// - [Native types][ValueParser]: `bool`, `String`, `OsString`, `PathBuf`
+/// - [Ranged numeric types][RangedI64ValueParser]: `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`
+/// - [`ValueEnum` types][crate::ValueEnum]
+/// - [`From<OsString>` types][std::convert::From] and [`From<&OsStr>` types][std::convert::From]
+/// - [`From<String>` types][std::convert::From] and [`From<&str>` types][std::convert::From]
+/// - [`FromStr` types][std::str::FromStr], including usize, isize
+///
+/// # Example
+///
+/// Usage:
+/// ```rust
+/// # use std::path::PathBuf;
+/// # use std::path::Path;
+/// let mut cmd = clap::Command::new("raw")
+/// .arg(
+/// clap::Arg::new("output")
+/// .value_parser(clap::value_parser!(PathBuf))
+/// .required(true)
+/// );
+///
+/// let m = cmd.try_get_matches_from_mut(["cmd", "file.txt"]).unwrap();
+/// let port: &PathBuf = m.get_one("output")
+/// .expect("required");
+/// assert_eq!(port, Path::new("file.txt"));
+/// ```
+///
+/// Example mappings:
+/// ```rust
+/// # use clap::ColorChoice;
+/// // Built-in types
+/// let parser = clap::value_parser!(String);
+/// assert_eq!(format!("{:?}", parser), "ValueParser::string");
+/// let parser = clap::value_parser!(std::ffi::OsString);
+/// assert_eq!(format!("{:?}", parser), "ValueParser::os_string");
+/// let parser = clap::value_parser!(std::path::PathBuf);
+/// assert_eq!(format!("{:?}", parser), "ValueParser::path_buf");
+/// clap::value_parser!(u16).range(3000..);
+/// clap::value_parser!(u64).range(3000..);
+///
+/// // FromStr types
+/// let parser = clap::value_parser!(usize);
+/// assert_eq!(format!("{:?}", parser), "_AnonymousValueParser(ValueParser::other(usize))");
+///
+/// // ValueEnum types
+/// clap::value_parser!(ColorChoice);
+/// ```
+#[macro_export]
+macro_rules! value_parser {
+ ($name:ty) => {{
+ use $crate::builder::via_prelude::*;
+ let auto = $crate::builder::_AutoValueParser::<$name>::new();
+ (&&&&&&auto).value_parser()
+ }};
+}
+
+mod private {
+ use super::*;
+
+ // Prefer these so `clap_derive` defaults to optimized implementations
+ pub trait _ValueParserViaSelfSealed {}
+ impl<P: Into<ValueParser>> _ValueParserViaSelfSealed for &&&&&&&_AutoValueParser<P> {}
+
+ pub trait _ValueParserViaFactorySealed {}
+ impl<P: ValueParserFactory> _ValueParserViaFactorySealed for &&&&&&_AutoValueParser<P> {}
+
+ pub trait _ValueParserViaValueEnumSealed {}
+ impl<E: crate::ValueEnum> _ValueParserViaValueEnumSealed for &&&&&_AutoValueParser<E> {}
+
+ pub trait _ValueParserViaFromOsStringSealed {}
+ impl<FromOsString> _ValueParserViaFromOsStringSealed for &&&&_AutoValueParser<FromOsString> where
+ FromOsString: From<std::ffi::OsString> + std::any::Any + Send + Sync + 'static
+ {
+ }
+
+ pub trait _ValueParserViaFromOsStrSealed {}
+ impl<FromOsStr> _ValueParserViaFromOsStrSealed for &&&_AutoValueParser<FromOsStr> where
+ FromOsStr: for<'s> From<&'s std::ffi::OsStr> + std::any::Any + Send + Sync + 'static
+ {
+ }
+
+ pub trait _ValueParserViaFromStringSealed {}
+ impl<FromString> _ValueParserViaFromStringSealed for &&_AutoValueParser<FromString> where
+ FromString: From<String> + std::any::Any + Send + Sync + 'static
+ {
+ }
+
+ pub trait _ValueParserViaFromStrSealed {}
+ impl<FromStr> _ValueParserViaFromStrSealed for &_AutoValueParser<FromStr> where
+ FromStr: for<'s> From<&'s str> + std::any::Any + Send + Sync + 'static
+ {
+ }
+
+ pub trait _ValueParserViaParseSealed {}
+ impl<Parse> _ValueParserViaParseSealed for _AutoValueParser<Parse>
+ where
+ Parse: std::str::FromStr + std::any::Any + Send + Sync + 'static,
+ <Parse as std::str::FromStr>::Err: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
+ {
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn ensure_typed_applies_to_parse() {
+ fn parse(_: &str) -> Result<usize, std::io::Error> {
+ Ok(10)
+ }
+ let cmd = crate::Command::new("cmd");
+ let arg = None;
+ assert_eq!(
+ TypedValueParser::parse_ref(&parse, &cmd, arg, std::ffi::OsStr::new("foo")).unwrap(),
+ 10
+ );
+ }
+}
diff --git a/src/completions/bash.rs b/src/completions/bash.rs
deleted file mode 100644
index b712a68..0000000
--- a/src/completions/bash.rs
+++ /dev/null
@@ -1,222 +0,0 @@
-// Std
-use std::io::Write;
-
-// Internal
-use app::parser::Parser;
-use args::OptBuilder;
-use completions;
-
-pub struct BashGen<'a, 'b>
-where
- 'a: 'b,
-{
- p: &'b Parser<'a, 'b>,
-}
-
-impl<'a, 'b> BashGen<'a, 'b> {
- pub fn new(p: &'b Parser<'a, 'b>) -> Self {
- BashGen { p: p }
- }
-
- pub fn generate_to<W: Write>(&self, buf: &mut W) {
- w!(
- buf,
- format!(
- r#"_{name}() {{
- local i cur prev opts cmds
- COMPREPLY=()
- cur="${{COMP_WORDS[COMP_CWORD]}}"
- prev="${{COMP_WORDS[COMP_CWORD-1]}}"
- cmd=""
- opts=""
-
- for i in ${{COMP_WORDS[@]}}
- do
- case "${{i}}" in
- {name})
- cmd="{name}"
- ;;
- {subcmds}
- *)
- ;;
- esac
- done
-
- case "${{cmd}}" in
- {name})
- opts="{name_opts}"
- if [[ ${{cur}} == -* || ${{COMP_CWORD}} -eq 1 ]] ; then
- COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") )
- return 0
- fi
- case "${{prev}}" in
- {name_opts_details}
- *)
- COMPREPLY=()
- ;;
- esac
- COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") )
- return 0
- ;;
- {subcmd_details}
- esac
-}}
-
-complete -F _{name} -o bashdefault -o default {name}
-"#,
- name = self.p.meta.bin_name.as_ref().unwrap(),
- name_opts = self.all_options_for_path(self.p.meta.bin_name.as_ref().unwrap()),
- name_opts_details =
- self.option_details_for_path(self.p.meta.bin_name.as_ref().unwrap()),
- subcmds = self.all_subcommands(),
- subcmd_details = self.subcommand_details()
- )
- .as_bytes()
- );
- }
-
- fn all_subcommands(&self) -> String {
- debugln!("BashGen::all_subcommands;");
- let mut subcmds = String::new();
- let scs = completions::all_subcommand_names(self.p);
-
- for sc in &scs {
- subcmds = format!(
- r#"{}
- {name})
- cmd+="__{fn_name}"
- ;;"#,
- subcmds,
- name = sc,
- fn_name = sc.replace("-", "__")
- );
- }
-
- subcmds
- }
-
- fn subcommand_details(&self) -> String {
- debugln!("BashGen::subcommand_details;");
- let mut subcmd_dets = String::new();
- let mut scs = completions::get_all_subcommand_paths(self.p, true);
- scs.sort();
- scs.dedup();
-
- for sc in &scs {
- subcmd_dets = format!(
- r#"{}
- {subcmd})
- opts="{sc_opts}"
- if [[ ${{cur}} == -* || ${{COMP_CWORD}} -eq {level} ]] ; then
- COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") )
- return 0
- fi
- case "${{prev}}" in
- {opts_details}
- *)
- COMPREPLY=()
- ;;
- esac
- COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") )
- return 0
- ;;"#,
- subcmd_dets,
- subcmd = sc.replace("-", "__"),
- sc_opts = self.all_options_for_path(&*sc),
- level = sc.split("__").map(|_| 1).fold(0, |acc, n| acc + n),
- opts_details = self.option_details_for_path(&*sc)
- );
- }
-
- subcmd_dets
- }
-
- fn option_details_for_path(&self, path: &str) -> String {
- debugln!("BashGen::option_details_for_path: path={}", path);
- let mut p = self.p;
- for sc in path.split("__").skip(1) {
- debugln!("BashGen::option_details_for_path:iter: sc={}", sc);
- p = &find_subcmd!(p, sc).unwrap().p;
- }
- let mut opts = String::new();
- for o in p.opts() {
- if let Some(l) = o.s.long {
- opts = format!(
- "{}
- --{})
- COMPREPLY=({})
- return 0
- ;;",
- opts,
- l,
- self.vals_for(o)
- );
- }
- if let Some(s) = o.s.short {
- opts = format!(
- "{}
- -{})
- COMPREPLY=({})
- return 0
- ;;",
- opts,
- s,
- self.vals_for(o)
- );
- }
- }
- opts
- }
-
- fn vals_for(&self, o: &OptBuilder) -> String {
- debugln!("BashGen::vals_for: o={}", o.b.name);
- use args::AnyArg;
- if let Some(vals) = o.possible_vals() {
- format!(r#"$(compgen -W "{}" -- "${{cur}}")"#, vals.join(" "))
- } else {
- String::from(r#"$(compgen -f "${cur}")"#)
- }
- }
-
- fn all_options_for_path(&self, path: &str) -> String {
- debugln!("BashGen::all_options_for_path: path={}", path);
- let mut p = self.p;
- for sc in path.split("__").skip(1) {
- debugln!("BashGen::all_options_for_path:iter: sc={}", sc);
- p = &find_subcmd!(p, sc).unwrap().p;
- }
- let mut opts = shorts!(p).fold(String::new(), |acc, s| format!("{} -{}", acc, s));
- opts = format!(
- "{} {}",
- opts,
- longs!(p).fold(String::new(), |acc, l| format!("{} --{}", acc, l))
- );
- opts = format!(
- "{} {}",
- opts,
- p.positionals
- .values()
- .fold(String::new(), |acc, p| format!("{} {}", acc, p))
- );
- opts = format!(
- "{} {}",
- opts,
- p.subcommands
- .iter()
- .fold(String::new(), |acc, s| format!("{} {}", acc, s.p.meta.name))
- );
- for sc in &p.subcommands {
- if let Some(ref aliases) = sc.p.meta.aliases {
- opts = format!(
- "{} {}",
- opts,
- aliases
- .iter()
- .map(|&(n, _)| n)
- .fold(String::new(), |acc, a| format!("{} {}", acc, a))
- );
- }
- }
- opts
- }
-}
diff --git a/src/completions/elvish.rs b/src/completions/elvish.rs
deleted file mode 100644
index 12be03d..0000000
--- a/src/completions/elvish.rs
+++ /dev/null
@@ -1,128 +0,0 @@
-// Std
-use std::io::Write;
-
-// Internal
-use app::parser::Parser;
-use INTERNAL_ERROR_MSG;
-
-pub struct ElvishGen<'a, 'b>
-where
- 'a: 'b,
-{
- p: &'b Parser<'a, 'b>,
-}
-
-impl<'a, 'b> ElvishGen<'a, 'b> {
- pub fn new(p: &'b Parser<'a, 'b>) -> Self {
- ElvishGen { p: p }
- }
-
- pub fn generate_to<W: Write>(&self, buf: &mut W) {
- let bin_name = self.p.meta.bin_name.as_ref().unwrap();
-
- let mut names = vec![];
- let subcommands_cases = generate_inner(self.p, "", &mut names);
-
- let result = format!(
- r#"
-edit:completion:arg-completer[{bin_name}] = [@words]{{
- fn spaces [n]{{
- repeat $n ' ' | joins ''
- }}
- fn cand [text desc]{{
- edit:complex-candidate $text &display-suffix=' '(spaces (- 14 (wcswidth $text)))$desc
- }}
- command = '{bin_name}'
- for word $words[1:-1] {{
- if (has-prefix $word '-') {{
- break
- }}
- command = $command';'$word
- }}
- completions = [{subcommands_cases}
- ]
- $completions[$command]
-}}
-"#,
- bin_name = bin_name,
- subcommands_cases = subcommands_cases
- );
-
- w!(buf, result.as_bytes());
- }
-}
-
-// Escape string inside single quotes
-fn escape_string(string: &str) -> String {
- string.replace("'", "''")
-}
-
-fn get_tooltip<T: ToString>(help: Option<&str>, data: T) -> String {
- match help {
- Some(help) => escape_string(help),
- _ => data.to_string(),
- }
-}
-
-fn generate_inner<'a, 'b, 'p>(
- p: &'p Parser<'a, 'b>,
- previous_command_name: &str,
- names: &mut Vec<&'p str>,
-) -> String {
- debugln!("ElvishGen::generate_inner;");
- let command_name = if previous_command_name.is_empty() {
- p.meta.bin_name.as_ref().expect(INTERNAL_ERROR_MSG).clone()
- } else {
- format!("{};{}", previous_command_name, &p.meta.name)
- };
-
- let mut completions = String::new();
- let preamble = String::from("\n cand ");
-
- for option in p.opts() {
- if let Some(data) = option.s.short {
- let tooltip = get_tooltip(option.b.help, data);
- completions.push_str(&preamble);
- completions.push_str(format!("-{} '{}'", data, tooltip).as_str());
- }
- if let Some(data) = option.s.long {
- let tooltip = get_tooltip(option.b.help, data);
- completions.push_str(&preamble);
- completions.push_str(format!("--{} '{}'", data, tooltip).as_str());
- }
- }
-
- for flag in p.flags() {
- if let Some(data) = flag.s.short {
- let tooltip = get_tooltip(flag.b.help, data);
- completions.push_str(&preamble);
- completions.push_str(format!("-{} '{}'", data, tooltip).as_str());
- }
- if let Some(data) = flag.s.long {
- let tooltip = get_tooltip(flag.b.help, data);
- completions.push_str(&preamble);
- completions.push_str(format!("--{} '{}'", data, tooltip).as_str());
- }
- }
-
- for subcommand in &p.subcommands {
- let data = &subcommand.p.meta.name;
- let tooltip = get_tooltip(subcommand.p.meta.about, data);
- completions.push_str(&preamble);
- completions.push_str(format!("{} '{}'", data, tooltip).as_str());
- }
-
- let mut subcommands_cases = format!(
- r"
- &'{}'= {{{}
- }}",
- &command_name, completions
- );
-
- for subcommand in &p.subcommands {
- let subcommand_subcommands_cases = generate_inner(&subcommand.p, &command_name, names);
- subcommands_cases.push_str(&subcommand_subcommands_cases);
- }
-
- subcommands_cases
-}
diff --git a/src/completions/fish.rs b/src/completions/fish.rs
deleted file mode 100644
index a2bf888..0000000
--- a/src/completions/fish.rs
+++ /dev/null
@@ -1,103 +0,0 @@
-// Std
-use std::io::Write;
-
-// Internal
-use app::parser::Parser;
-
-pub struct FishGen<'a, 'b>
-where
- 'a: 'b,
-{
- p: &'b Parser<'a, 'b>,
-}
-
-impl<'a, 'b> FishGen<'a, 'b> {
- pub fn new(p: &'b Parser<'a, 'b>) -> Self {
- FishGen { p: p }
- }
-
- pub fn generate_to<W: Write>(&self, buf: &mut W) {
- let command = self.p.meta.bin_name.as_ref().unwrap();
- let mut buffer = String::new();
- gen_fish_inner(command, self, command, &mut buffer);
- w!(buf, buffer.as_bytes());
- }
-}
-
-// Escape string inside single quotes
-fn escape_string(string: &str) -> String {
- string.replace("\\", "\\\\").replace("'", "\\'")
-}
-
-fn gen_fish_inner(root_command: &str, comp_gen: &FishGen, subcommand: &str, buffer: &mut String) {
- debugln!("FishGen::gen_fish_inner;");
- // example :
- //
- // complete
- // -c {command}
- // -d "{description}"
- // -s {short}
- // -l {long}
- // -a "{possible_arguments}"
- // -r # if require parameter
- // -f # don't use file completion
- // -n "__fish_use_subcommand" # complete for command "myprog"
- // -n "__fish_seen_subcommand_from subcmd1" # complete for command "myprog subcmd1"
-
- let mut basic_template = format!("complete -c {} -n ", root_command);
- if root_command == subcommand {
- basic_template.push_str("\"__fish_use_subcommand\"");
- } else {
- basic_template.push_str(format!("\"__fish_seen_subcommand_from {}\"", subcommand).as_str());
- }
-
- for option in comp_gen.p.opts() {
- let mut template = basic_template.clone();
- if let Some(data) = option.s.short {
- template.push_str(format!(" -s {}", data).as_str());
- }
- if let Some(data) = option.s.long {
- template.push_str(format!(" -l {}", data).as_str());
- }
- if let Some(data) = option.b.help {
- template.push_str(format!(" -d '{}'", escape_string(data)).as_str());
- }
- if let Some(ref data) = option.v.possible_vals {
- template.push_str(format!(" -r -f -a \"{}\"", data.join(" ")).as_str());
- }
- buffer.push_str(template.as_str());
- buffer.push_str("\n");
- }
-
- for flag in comp_gen.p.flags() {
- let mut template = basic_template.clone();
- if let Some(data) = flag.s.short {
- template.push_str(format!(" -s {}", data).as_str());
- }
- if let Some(data) = flag.s.long {
- template.push_str(format!(" -l {}", data).as_str());
- }
- if let Some(data) = flag.b.help {
- template.push_str(format!(" -d '{}'", escape_string(data)).as_str());
- }
- buffer.push_str(template.as_str());
- buffer.push_str("\n");
- }
-
- for subcommand in &comp_gen.p.subcommands {
- let mut template = basic_template.clone();
- template.push_str(" -f");
- template.push_str(format!(" -a \"{}\"", &subcommand.p.meta.name).as_str());
- if let Some(data) = subcommand.p.meta.about {
- template.push_str(format!(" -d '{}'", escape_string(data)).as_str())
- }
- buffer.push_str(template.as_str());
- buffer.push_str("\n");
- }
-
- // generate options of subcommands
- for subcommand in &comp_gen.p.subcommands {
- let sub_comp_gen = FishGen::new(&subcommand.p);
- gen_fish_inner(root_command, &sub_comp_gen, &subcommand.to_string(), buffer);
- }
-}
diff --git a/src/completions/macros.rs b/src/completions/macros.rs
deleted file mode 100644
index 3a69de5..0000000
--- a/src/completions/macros.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-macro_rules! w {
- ($buf:expr, $to_w:expr) => {
- match $buf.write_all($to_w) {
- Ok(..) => (),
- Err(..) => panic!("Failed to write to completions file"),
- }
- };
-}
-
-macro_rules! get_zsh_arg_conflicts {
- ($p:ident, $arg:ident, $msg:ident) => {
- if let Some(conf_vec) = $arg.blacklist() {
- let mut v = vec![];
- for arg_name in conf_vec {
- let arg = $p.find_any_arg(arg_name).expect($msg);
- if let Some(s) = arg.short() {
- v.push(format!("-{}", s));
- }
- if let Some(l) = arg.long() {
- v.push(format!("--{}", l));
- }
- }
- v.join(" ")
- } else {
- String::new()
- }
- };
-}
diff --git a/src/completions/mod.rs b/src/completions/mod.rs
deleted file mode 100644
index 99d4005..0000000
--- a/src/completions/mod.rs
+++ /dev/null
@@ -1,182 +0,0 @@
-#[macro_use]
-mod macros;
-mod bash;
-mod elvish;
-mod fish;
-mod powershell;
-mod shell;
-mod zsh;
-
-// Std
-use std::io::Write;
-
-// Internal
-use self::bash::BashGen;
-use self::elvish::ElvishGen;
-use self::fish::FishGen;
-use self::powershell::PowerShellGen;
-pub use self::shell::Shell;
-use self::zsh::ZshGen;
-use app::parser::Parser;
-
-pub struct ComplGen<'a, 'b>
-where
- 'a: 'b,
-{
- p: &'b Parser<'a, 'b>,
-}
-
-impl<'a, 'b> ComplGen<'a, 'b> {
- pub fn new(p: &'b Parser<'a, 'b>) -> Self {
- ComplGen { p: p }
- }
-
- pub fn generate<W: Write>(&self, for_shell: Shell, buf: &mut W) {
- match for_shell {
- Shell::Bash => BashGen::new(self.p).generate_to(buf),
- Shell::Fish => FishGen::new(self.p).generate_to(buf),
- Shell::Zsh => ZshGen::new(self.p).generate_to(buf),
- Shell::PowerShell => PowerShellGen::new(self.p).generate_to(buf),
- Shell::Elvish => ElvishGen::new(self.p).generate_to(buf),
- }
- }
-}
-
-// Gets all subcommands including child subcommands in the form of 'name' where the name
-// is a single word (i.e. "install") of the path to said subcommand (i.e.
-// "rustup toolchain install")
-//
-// Also note, aliases are treated as their own subcommands but duplicates of whatever they're
-// aliasing.
-pub fn all_subcommand_names(p: &Parser) -> Vec<String> {
- debugln!("all_subcommand_names;");
- let mut subcmds: Vec<_> = subcommands_of(p)
- .iter()
- .map(|&(ref n, _)| n.clone())
- .collect();
- for sc_v in p.subcommands.iter().map(|s| all_subcommand_names(&s.p)) {
- subcmds.extend(sc_v);
- }
- subcmds.sort();
- subcmds.dedup();
- subcmds
-}
-
-// Gets all subcommands including child subcommands in the form of ('name', 'bin_name') where the name
-// is a single word (i.e. "install") of the path and full bin_name of said subcommand (i.e.
-// "rustup toolchain install")
-//
-// Also note, aliases are treated as their own subcommands but duplicates of whatever they're
-// aliasing.
-pub fn all_subcommands(p: &Parser) -> Vec<(String, String)> {
- debugln!("all_subcommands;");
- let mut subcmds: Vec<_> = subcommands_of(p);
- for sc_v in p.subcommands.iter().map(|s| all_subcommands(&s.p)) {
- subcmds.extend(sc_v);
- }
- subcmds
-}
-
-// Gets all subcommands excluding child subcommands in the form of (name, bin_name) where the name
-// is a single word (i.e. "install") and the bin_name is a space delineated list of the path to said
-// subcommand (i.e. "rustup toolchain install")
-//
-// Also note, aliases are treated as their own subcommands but duplicates of whatever they're
-// aliasing.
-pub fn subcommands_of(p: &Parser) -> Vec<(String, String)> {
- debugln!(
- "subcommands_of: name={}, bin_name={}",
- p.meta.name,
- p.meta.bin_name.as_ref().unwrap()
- );
- let mut subcmds = vec![];
-
- debugln!(
- "subcommands_of: Has subcommands...{:?}",
- p.has_subcommands()
- );
- if !p.has_subcommands() {
- let mut ret = vec![];
- debugln!("subcommands_of: Looking for aliases...");
- if let Some(ref aliases) = p.meta.aliases {
- for &(n, _) in aliases {
- debugln!("subcommands_of:iter:iter: Found alias...{}", n);
- let mut als_bin_name: Vec<_> =
- p.meta.bin_name.as_ref().unwrap().split(' ').collect();
- als_bin_name.push(n);
- let old = als_bin_name.len() - 2;
- als_bin_name.swap_remove(old);
- ret.push((n.to_owned(), als_bin_name.join(" ")));
- }
- }
- return ret;
- }
- for sc in &p.subcommands {
- debugln!(
- "subcommands_of:iter: name={}, bin_name={}",
- sc.p.meta.name,
- sc.p.meta.bin_name.as_ref().unwrap()
- );
-
- debugln!("subcommands_of:iter: Looking for aliases...");
- if let Some(ref aliases) = sc.p.meta.aliases {
- for &(n, _) in aliases {
- debugln!("subcommands_of:iter:iter: Found alias...{}", n);
- let mut als_bin_name: Vec<_> =
- p.meta.bin_name.as_ref().unwrap().split(' ').collect();
- als_bin_name.push(n);
- let old = als_bin_name.len() - 2;
- als_bin_name.swap_remove(old);
- subcmds.push((n.to_owned(), als_bin_name.join(" ")));
- }
- }
- subcmds.push((
- sc.p.meta.name.clone(),
- sc.p.meta.bin_name.as_ref().unwrap().clone(),
- ));
- }
- subcmds
-}
-
-pub fn get_all_subcommand_paths(p: &Parser, first: bool) -> Vec<String> {
- debugln!("get_all_subcommand_paths;");
- let mut subcmds = vec![];
- if !p.has_subcommands() {
- if !first {
- let name = &*p.meta.name;
- let path = p.meta.bin_name.as_ref().unwrap().clone().replace(" ", "__");
- let mut ret = vec![path.clone()];
- if let Some(ref aliases) = p.meta.aliases {
- for &(n, _) in aliases {
- ret.push(path.replace(name, n));
- }
- }
- return ret;
- }
- return vec![];
- }
- for sc in &p.subcommands {
- let name = &*sc.p.meta.name;
- let path =
- sc.p.meta
- .bin_name
- .as_ref()
- .unwrap()
- .clone()
- .replace(" ", "__");
- subcmds.push(path.clone());
- if let Some(ref aliases) = sc.p.meta.aliases {
- for &(n, _) in aliases {
- subcmds.push(path.replace(name, n));
- }
- }
- }
- for sc_v in p
- .subcommands
- .iter()
- .map(|s| get_all_subcommand_paths(&s.p, false))
- {
- subcmds.extend(sc_v);
- }
- subcmds
-}
diff --git a/src/completions/powershell.rs b/src/completions/powershell.rs
deleted file mode 100644
index 5fafd8d..0000000
--- a/src/completions/powershell.rs
+++ /dev/null
@@ -1,166 +0,0 @@
-// Std
-use std::io::Write;
-
-// Internal
-use app::parser::Parser;
-use INTERNAL_ERROR_MSG;
-
-pub struct PowerShellGen<'a, 'b>
-where
- 'a: 'b,
-{
- p: &'b Parser<'a, 'b>,
-}
-
-impl<'a, 'b> PowerShellGen<'a, 'b> {
- pub fn new(p: &'b Parser<'a, 'b>) -> Self {
- PowerShellGen { p: p }
- }
-
- pub fn generate_to<W: Write>(&self, buf: &mut W) {
- let bin_name = self.p.meta.bin_name.as_ref().unwrap();
-
- let mut names = vec![];
- let subcommands_cases = generate_inner(self.p, "", &mut names);
-
- let result = format!(
- r#"
-using namespace System.Management.Automation
-using namespace System.Management.Automation.Language
-
-Register-ArgumentCompleter -Native -CommandName '{bin_name}' -ScriptBlock {{
- param($wordToComplete, $commandAst, $cursorPosition)
-
- $commandElements = $commandAst.CommandElements
- $command = @(
- '{bin_name}'
- for ($i = 1; $i -lt $commandElements.Count; $i++) {{
- $element = $commandElements[$i]
- if ($element -isnot [StringConstantExpressionAst] -or
- $element.StringConstantType -ne [StringConstantType]::BareWord -or
- $element.Value.StartsWith('-')) {{
- break
- }}
- $element.Value
- }}) -join ';'
-
- $completions = @(switch ($command) {{{subcommands_cases}
- }})
-
- $completions.Where{{ $_.CompletionText -like "$wordToComplete*" }} |
- Sort-Object -Property ListItemText
-}}
-"#,
- bin_name = bin_name,
- subcommands_cases = subcommands_cases
- );
-
- w!(buf, result.as_bytes());
- }
-}
-
-// Escape string inside single quotes
-fn escape_string(string: &str) -> String {
- string.replace("'", "''")
-}
-
-fn get_tooltip<T: ToString>(help: Option<&str>, data: T) -> String {
- match help {
- Some(help) => escape_string(help),
- _ => data.to_string(),
- }
-}
-
-fn generate_inner<'a, 'b, 'p>(
- p: &'p Parser<'a, 'b>,
- previous_command_name: &str,
- names: &mut Vec<&'p str>,
-) -> String {
- debugln!("PowerShellGen::generate_inner;");
- let command_name = if previous_command_name.is_empty() {
- p.meta.bin_name.as_ref().expect(INTERNAL_ERROR_MSG).clone()
- } else {
- format!("{};{}", previous_command_name, &p.meta.name)
- };
-
- let mut completions = String::new();
- let preamble = String::from("\n [CompletionResult]::new(");
-
- for option in p.opts() {
- if let Some(data) = option.s.short {
- let tooltip = get_tooltip(option.b.help, data);
- completions.push_str(&preamble);
- completions.push_str(
- format!(
- "'-{}', '{}', {}, '{}')",
- data, data, "[CompletionResultType]::ParameterName", tooltip
- )
- .as_str(),
- );
- }
- if let Some(data) = option.s.long {
- let tooltip = get_tooltip(option.b.help, data);
- completions.push_str(&preamble);
- completions.push_str(
- format!(
- "'--{}', '{}', {}, '{}')",
- data, data, "[CompletionResultType]::ParameterName", tooltip
- )
- .as_str(),
- );
- }
- }
-
- for flag in p.flags() {
- if let Some(data) = flag.s.short {
- let tooltip = get_tooltip(flag.b.help, data);
- completions.push_str(&preamble);
- completions.push_str(
- format!(
- "'-{}', '{}', {}, '{}')",
- data, data, "[CompletionResultType]::ParameterName", tooltip
- )
- .as_str(),
- );
- }
- if let Some(data) = flag.s.long {
- let tooltip = get_tooltip(flag.b.help, data);
- completions.push_str(&preamble);
- completions.push_str(
- format!(
- "'--{}', '{}', {}, '{}')",
- data, data, "[CompletionResultType]::ParameterName", tooltip
- )
- .as_str(),
- );
- }
- }
-
- for subcommand in &p.subcommands {
- let data = &subcommand.p.meta.name;
- let tooltip = get_tooltip(subcommand.p.meta.about, data);
- completions.push_str(&preamble);
- completions.push_str(
- format!(
- "'{}', '{}', {}, '{}')",
- data, data, "[CompletionResultType]::ParameterValue", tooltip
- )
- .as_str(),
- );
- }
-
- let mut subcommands_cases = format!(
- r"
- '{}' {{{}
- break
- }}",
- &command_name, completions
- );
-
- for subcommand in &p.subcommands {
- let subcommand_subcommands_cases = generate_inner(&subcommand.p, &command_name, names);
- subcommands_cases.push_str(&subcommand_subcommands_cases);
- }
-
- subcommands_cases
-}
diff --git a/src/completions/shell.rs b/src/completions/shell.rs
deleted file mode 100644
index 80999e6..0000000
--- a/src/completions/shell.rs
+++ /dev/null
@@ -1,56 +0,0 @@
-#[allow(deprecated, unused_imports)]
-use std::ascii::AsciiExt;
-use std::fmt;
-use std::str::FromStr;
-
-/// Describes which shell to produce a completions file for
-#[cfg_attr(feature = "lints", allow(enum_variant_names))]
-#[derive(Debug, Copy, Clone)]
-pub enum Shell {
- /// Generates a .bash completion file for the Bourne Again SHell (BASH)
- Bash,
- /// Generates a .fish completion file for the Friendly Interactive SHell (fish)
- Fish,
- /// Generates a completion file for the Z SHell (ZSH)
- Zsh,
- /// Generates a completion file for PowerShell
- PowerShell,
- /// Generates a completion file for Elvish
- Elvish,
-}
-
-impl Shell {
- /// A list of possible variants in `&'static str` form
- pub fn variants() -> [&'static str; 5] {
- ["zsh", "bash", "fish", "powershell", "elvish"]
- }
-}
-
-impl FromStr for Shell {
- type Err = String;
-
- fn from_str(s: &str) -> Result<Self, Self::Err> {
- match s {
- "ZSH" | _ if s.eq_ignore_ascii_case("zsh") => Ok(Shell::Zsh),
- "FISH" | _ if s.eq_ignore_ascii_case("fish") => Ok(Shell::Fish),
- "BASH" | _ if s.eq_ignore_ascii_case("bash") => Ok(Shell::Bash),
- "POWERSHELL" | _ if s.eq_ignore_ascii_case("powershell") => Ok(Shell::PowerShell),
- "ELVISH" | _ if s.eq_ignore_ascii_case("elvish") => Ok(Shell::Elvish),
- _ => Err(String::from(
- "[valid values: bash, fish, zsh, powershell, elvish]",
- )),
- }
- }
-}
-
-impl fmt::Display for Shell {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match *self {
- Shell::Bash => write!(f, "BASH"),
- Shell::Fish => write!(f, "FISH"),
- Shell::Zsh => write!(f, "ZSH"),
- Shell::PowerShell => write!(f, "POWERSHELL"),
- Shell::Elvish => write!(f, "ELVISH"),
- }
- }
-}
diff --git a/src/completions/zsh.rs b/src/completions/zsh.rs
deleted file mode 100644
index 14cf2b6..0000000
--- a/src/completions/zsh.rs
+++ /dev/null
@@ -1,485 +0,0 @@
-// Std
-#[allow(deprecated, unused_imports)]
-use std::ascii::AsciiExt;
-use std::io::Write;
-
-// Internal
-use app::parser::Parser;
-use app::App;
-use args::{AnyArg, ArgSettings};
-use completions;
-use INTERNAL_ERROR_MSG;
-
-pub struct ZshGen<'a, 'b>
-where
- 'a: 'b,
-{
- p: &'b Parser<'a, 'b>,
-}
-
-impl<'a, 'b> ZshGen<'a, 'b> {
- pub fn new(p: &'b Parser<'a, 'b>) -> Self {
- debugln!("ZshGen::new;");
- ZshGen { p: p }
- }
-
- pub fn generate_to<W: Write>(&self, buf: &mut W) {
- debugln!("ZshGen::generate_to;");
- w!(
- buf,
- format!(
- "\
-#compdef {name}
-
-autoload -U is-at-least
-
-_{name}() {{
- typeset -A opt_args
- typeset -a _arguments_options
- local ret=1
-
- if is-at-least 5.2; then
- _arguments_options=(-s -S -C)
- else
- _arguments_options=(-s -C)
- fi
-
- local context curcontext=\"$curcontext\" state line
- {initial_args}
- {subcommands}
-}}
-
-{subcommand_details}
-
-_{name} \"$@\"",
- name = self.p.meta.bin_name.as_ref().unwrap(),
- initial_args = get_args_of(self.p),
- subcommands = get_subcommands_of(self.p),
- subcommand_details = subcommand_details(self.p)
- )
- .as_bytes()
- );
- }
-}
-
-// Displays the commands of a subcommand
-// (( $+functions[_[bin_name_underscore]_commands] )) ||
-// _[bin_name_underscore]_commands() {
-// local commands; commands=(
-// '[arg_name]:[arg_help]'
-// )
-// _describe -t commands '[bin_name] commands' commands "$@"
-//
-// Where the following variables are present:
-// [bin_name_underscore]: The full space delineated bin_name, where spaces have been replaced by
-// underscore characters
-// [arg_name]: The name of the subcommand
-// [arg_help]: The help message of the subcommand
-// [bin_name]: The full space delineated bin_name
-//
-// Here's a snippet from rustup:
-//
-// (( $+functions[_rustup_commands] )) ||
-// _rustup_commands() {
-// local commands; commands=(
-// 'show:Show the active and installed toolchains'
-// 'update:Update Rust toolchains'
-// # ... snip for brevity
-// 'help:Prints this message or the help of the given subcommand(s)'
-// )
-// _describe -t commands 'rustup commands' commands "$@"
-//
-fn subcommand_details(p: &Parser) -> String {
- debugln!("ZshGen::subcommand_details;");
- // First we do ourself
- let mut ret = vec![format!(
- "\
-(( $+functions[_{bin_name_underscore}_commands] )) ||
-_{bin_name_underscore}_commands() {{
- local commands; commands=(
- {subcommands_and_args}
- )
- _describe -t commands '{bin_name} commands' commands \"$@\"
-}}",
- bin_name_underscore = p.meta.bin_name.as_ref().unwrap().replace(" ", "__"),
- bin_name = p.meta.bin_name.as_ref().unwrap(),
- subcommands_and_args = subcommands_of(p)
- )];
-
- // Next we start looping through all the children, grandchildren, etc.
- let mut all_subcommands = completions::all_subcommands(p);
- all_subcommands.sort();
- all_subcommands.dedup();
- for &(_, ref bin_name) in &all_subcommands {
- debugln!("ZshGen::subcommand_details:iter: bin_name={}", bin_name);
- ret.push(format!(
- "\
-(( $+functions[_{bin_name_underscore}_commands] )) ||
-_{bin_name_underscore}_commands() {{
- local commands; commands=(
- {subcommands_and_args}
- )
- _describe -t commands '{bin_name} commands' commands \"$@\"
-}}",
- bin_name_underscore = bin_name.replace(" ", "__"),
- bin_name = bin_name,
- subcommands_and_args = subcommands_of(parser_of(p, bin_name))
- ));
- }
-
- ret.join("\n")
-}
-
-// Generates subcommand completions in form of
-//
-// '[arg_name]:[arg_help]'
-//
-// Where:
-// [arg_name]: the subcommand's name
-// [arg_help]: the help message of the subcommand
-//
-// A snippet from rustup:
-// 'show:Show the active and installed toolchains'
-// 'update:Update Rust toolchains'
-fn subcommands_of(p: &Parser) -> String {
- debugln!("ZshGen::subcommands_of;");
- let mut ret = vec![];
- fn add_sc(sc: &App, n: &str, ret: &mut Vec<String>) {
- debugln!("ZshGen::add_sc;");
- let s = format!(
- "\"{name}:{help}\" \\",
- name = n,
- help =
- sc.p.meta
- .about
- .unwrap_or("")
- .replace("[", "\\[")
- .replace("]", "\\]")
- );
- if !s.is_empty() {
- ret.push(s);
- }
- }
-
- // The subcommands
- for sc in p.subcommands() {
- debugln!("ZshGen::subcommands_of:iter: subcommand={}", sc.p.meta.name);
- add_sc(sc, &sc.p.meta.name, &mut ret);
- if let Some(ref v) = sc.p.meta.aliases {
- for alias in v.iter().filter(|&&(_, vis)| vis).map(|&(n, _)| n) {
- add_sc(sc, alias, &mut ret);
- }
- }
- }
-
- ret.join("\n")
-}
-
-// Get's the subcommand section of a completion file
-// This looks roughly like:
-//
-// case $state in
-// ([bin_name]_args)
-// curcontext=\"${curcontext%:*:*}:[name_hyphen]-command-$words[1]:\"
-// case $line[1] in
-//
-// ([name])
-// _arguments -C -s -S \
-// [subcommand_args]
-// && ret=0
-//
-// [RECURSIVE_CALLS]
-//
-// ;;",
-//
-// [repeat]
-//
-// esac
-// ;;
-// esac",
-//
-// Where the following variables are present:
-// [name] = The subcommand name in the form of "install" for "rustup toolchain install"
-// [bin_name] = The full space delineated bin_name such as "rustup toolchain install"
-// [name_hyphen] = The full space delineated bin_name, but replace spaces with hyphens
-// [repeat] = From the same recursive calls, but for all subcommands
-// [subcommand_args] = The same as zsh::get_args_of
-fn get_subcommands_of(p: &Parser) -> String {
- debugln!("get_subcommands_of;");
-
- debugln!(
- "get_subcommands_of: Has subcommands...{:?}",
- p.has_subcommands()
- );
- if !p.has_subcommands() {
- return String::new();
- }
-
- let sc_names = completions::subcommands_of(p);
-
- let mut subcmds = vec![];
- for &(ref name, ref bin_name) in &sc_names {
- let mut v = vec![format!("({})", name)];
- let subcommand_args = get_args_of(parser_of(p, &*bin_name));
- if !subcommand_args.is_empty() {
- v.push(subcommand_args);
- }
- let subcommands = get_subcommands_of(parser_of(p, &*bin_name));
- if !subcommands.is_empty() {
- v.push(subcommands);
- }
- v.push(String::from(";;"));
- subcmds.push(v.join("\n"));
- }
-
- format!(
- "case $state in
- ({name})
- words=($line[{pos}] \"${{words[@]}}\")
- (( CURRENT += 1 ))
- curcontext=\"${{curcontext%:*:*}}:{name_hyphen}-command-$line[{pos}]:\"
- case $line[{pos}] in
- {subcommands}
- esac
- ;;
-esac",
- name = p.meta.name,
- name_hyphen = p.meta.bin_name.as_ref().unwrap().replace(" ", "-"),
- subcommands = subcmds.join("\n"),
- pos = p.positionals().len() + 1
- )
-}
-
-fn parser_of<'a, 'b>(p: &'b Parser<'a, 'b>, sc: &str) -> &'b Parser<'a, 'b> {
- debugln!("parser_of: sc={}", sc);
- if sc == p.meta.bin_name.as_ref().unwrap_or(&String::new()) {
- return p;
- }
- &p.find_subcommand(sc).expect(INTERNAL_ERROR_MSG).p
-}
-
-// Writes out the args section, which ends up being the flags, opts and postionals, and a jump to
-// another ZSH function if there are subcommands.
-// The structer works like this:
-// ([conflicting_args]) [multiple] arg [takes_value] [[help]] [: :(possible_values)]
-// ^-- list '-v -h' ^--'*' ^--'+' ^-- list 'one two three'
-//
-// An example from the rustup command:
-//
-// _arguments -C -s -S \
-// '(-h --help --verbose)-v[Enable verbose output]' \
-// '(-V -v --version --verbose --help)-h[Prints help information]' \
-// # ... snip for brevity
-// ':: :_rustup_commands' \ # <-- displays subcommands
-// '*::: :->rustup' \ # <-- displays subcommand args and child subcommands
-// && ret=0
-//
-// The args used for _arguments are as follows:
-// -C: modify the $context internal variable
-// -s: Allow stacking of short args (i.e. -a -b -c => -abc)
-// -S: Do not complete anything after '--' and treat those as argument values
-fn get_args_of(p: &Parser) -> String {
- debugln!("get_args_of;");
- let mut ret = vec![String::from("_arguments \"${_arguments_options[@]}\" \\")];
- let opts = write_opts_of(p);
- let flags = write_flags_of(p);
- let positionals = write_positionals_of(p);
- let sc_or_a = if p.has_subcommands() {
- format!(
- "\":: :_{name}_commands\" \\",
- name = p.meta.bin_name.as_ref().unwrap().replace(" ", "__")
- )
- } else {
- String::new()
- };
- let sc = if p.has_subcommands() {
- format!("\"*::: :->{name}\" \\", name = p.meta.name)
- } else {
- String::new()
- };
-
- if !opts.is_empty() {
- ret.push(opts);
- }
- if !flags.is_empty() {
- ret.push(flags);
- }
- if !positionals.is_empty() {
- ret.push(positionals);
- }
- if !sc_or_a.is_empty() {
- ret.push(sc_or_a);
- }
- if !sc.is_empty() {
- ret.push(sc);
- }
- ret.push(String::from("&& ret=0"));
-
- ret.join("\n")
-}
-
-// Escape help string inside single quotes and brackets
-fn escape_help(string: &str) -> String {
- string
- .replace("\\", "\\\\")
- .replace("'", "'\\''")
- .replace("[", "\\[")
- .replace("]", "\\]")
-}
-
-// Escape value string inside single quotes and parentheses
-fn escape_value(string: &str) -> String {
- string
- .replace("\\", "\\\\")
- .replace("'", "'\\''")
- .replace("(", "\\(")
- .replace(")", "\\)")
- .replace(" ", "\\ ")
-}
-
-fn write_opts_of(p: &Parser) -> String {
- debugln!("write_opts_of;");
- let mut ret = vec![];
- for o in p.opts() {
- debugln!("write_opts_of:iter: o={}", o.name());
- let help = o.help().map_or(String::new(), escape_help);
- let mut conflicts = get_zsh_arg_conflicts!(p, o, INTERNAL_ERROR_MSG);
- conflicts = if conflicts.is_empty() {
- String::new()
- } else {
- format!("({})", conflicts)
- };
-
- let multiple = if o.is_set(ArgSettings::Multiple) {
- "*"
- } else {
- ""
- };
- let pv = if let Some(pv_vec) = o.possible_vals() {
- format!(
- ": :({})",
- pv_vec
- .iter()
- .map(|v| escape_value(*v))
- .collect::<Vec<String>>()
- .join(" ")
- )
- } else {
- String::new()
- };
- if let Some(short) = o.short() {
- let s = format!(
- "'{conflicts}{multiple}-{arg}+[{help}]{possible_values}' \\",
- conflicts = conflicts,
- multiple = multiple,
- arg = short,
- possible_values = pv,
- help = help
- );
-
- debugln!("write_opts_of:iter: Wrote...{}", &*s);
- ret.push(s);
- }
- if let Some(long) = o.long() {
- let l = format!(
- "'{conflicts}{multiple}--{arg}=[{help}]{possible_values}' \\",
- conflicts = conflicts,
- multiple = multiple,
- arg = long,
- possible_values = pv,
- help = help
- );
-
- debugln!("write_opts_of:iter: Wrote...{}", &*l);
- ret.push(l);
- }
- }
-
- ret.join("\n")
-}
-
-fn write_flags_of(p: &Parser) -> String {
- debugln!("write_flags_of;");
- let mut ret = vec![];
- for f in p.flags() {
- debugln!("write_flags_of:iter: f={}", f.name());
- let help = f.help().map_or(String::new(), escape_help);
- let mut conflicts = get_zsh_arg_conflicts!(p, f, INTERNAL_ERROR_MSG);
- conflicts = if conflicts.is_empty() {
- String::new()
- } else {
- format!("({})", conflicts)
- };
-
- let multiple = if f.is_set(ArgSettings::Multiple) {
- "*"
- } else {
- ""
- };
- if let Some(short) = f.short() {
- let s = format!(
- "'{conflicts}{multiple}-{arg}[{help}]' \\",
- multiple = multiple,
- conflicts = conflicts,
- arg = short,
- help = help
- );
-
- debugln!("write_flags_of:iter: Wrote...{}", &*s);
- ret.push(s);
- }
-
- if let Some(long) = f.long() {
- let l = format!(
- "'{conflicts}{multiple}--{arg}[{help}]' \\",
- conflicts = conflicts,
- multiple = multiple,
- arg = long,
- help = help
- );
-
- debugln!("write_flags_of:iter: Wrote...{}", &*l);
- ret.push(l);
- }
- }
-
- ret.join("\n")
-}
-
-fn write_positionals_of(p: &Parser) -> String {
- debugln!("write_positionals_of;");
- let mut ret = vec![];
- for arg in p.positionals() {
- debugln!("write_positionals_of:iter: arg={}", arg.b.name);
- let a = format!(
- "'{optional}:{name}{help}:{action}' \\",
- optional = if !arg.b.is_set(ArgSettings::Required) {
- ":"
- } else {
- ""
- },
- name = arg.b.name,
- help = arg
- .b
- .help
- .map_or("".to_owned(), |v| " -- ".to_owned() + v)
- .replace("[", "\\[")
- .replace("]", "\\]"),
- action = arg.possible_vals().map_or("_files".to_owned(), |values| {
- format!(
- "({})",
- values
- .iter()
- .map(|v| escape_value(*v))
- .collect::<Vec<String>>()
- .join(" ")
- )
- })
- );
-
- debugln!("write_positionals_of:iter: Wrote...{}", a);
- ret.push(a);
- }
-
- ret.join("\n")
-}
diff --git a/src/derive.rs b/src/derive.rs
new file mode 100644
index 0000000..98bb012
--- /dev/null
+++ b/src/derive.rs
@@ -0,0 +1,471 @@
+//! This module contains traits that are usable with the `#[derive(...)].`
+//! macros in [`clap_derive`].
+
+use crate::builder::PossibleValue;
+use crate::{ArgMatches, Command, Error};
+
+use std::ffi::OsString;
+
+/// Parse command-line arguments into `Self`.
+///
+/// The primary one-stop-shop trait used to create an instance of a `clap`
+/// [`Command`], conduct the parsing, and turn the resulting [`ArgMatches`] back
+/// into concrete instance of the user struct.
+///
+/// This trait is primarily a convenience on top of [`FromArgMatches`] +
+/// [`CommandFactory`] which uses those two underlying traits to build the two
+/// fundamental functions `parse` which uses the `std::env::args_os` iterator,
+/// and `parse_from` which allows the consumer to supply the iterator (along
+/// with fallible options for each).
+///
+/// See also [`Subcommand`] and [`Args`].
+///
+/// See the [derive reference](crate::_derive) for attributes and best practices.
+///
+/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features]
+///
+/// # Examples
+///
+/// The following example creates a `Context` struct that would be used
+/// throughout the application representing the normalized values coming from
+/// the CLI.
+///
+#[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+#[cfg_attr(feature = "derive", doc = " ```")]
+/// /// My super CLI
+/// #[derive(clap::Parser)]
+/// #[command(name = "demo")]
+/// struct Context {
+/// /// More verbose output
+/// #[arg(long)]
+/// verbose: bool,
+/// /// An optional name
+/// #[arg(short, long)]
+/// name: Option<String>,
+/// }
+/// ```
+///
+/// The equivalent [`Command`] struct + `From` implementation:
+///
+/// ```rust
+/// # use clap::{Command, Arg, ArgMatches, ArgAction};
+/// Command::new("demo")
+/// .about("My super CLI")
+/// .arg(Arg::new("verbose")
+/// .long("verbose")
+/// .action(ArgAction::SetTrue)
+/// .help("More verbose output"))
+/// .arg(Arg::new("name")
+/// .long("name")
+/// .short('n')
+/// .help("An optional name")
+/// .action(ArgAction::Set));
+///
+/// struct Context {
+/// verbose: bool,
+/// name: Option<String>,
+/// }
+///
+/// impl From<ArgMatches> for Context {
+/// fn from(m: ArgMatches) -> Self {
+/// Context {
+/// verbose: m.get_flag("verbose"),
+/// name: m.get_one::<String>("name").cloned(),
+/// }
+/// }
+/// }
+/// ```
+///
+pub trait Parser: FromArgMatches + CommandFactory + Sized {
+ /// Parse from `std::env::args_os()`, exit on error
+ fn parse() -> Self {
+ let mut matches = <Self as CommandFactory>::command().get_matches();
+ let res = <Self as FromArgMatches>::from_arg_matches_mut(&mut matches)
+ .map_err(format_error::<Self>);
+ match res {
+ Ok(s) => s,
+ Err(e) => {
+ // Since this is more of a development-time error, we aren't doing as fancy of a quit
+ // as `get_matches`
+ e.exit()
+ }
+ }
+ }
+
+ /// Parse from `std::env::args_os()`, return Err on error.
+ fn try_parse() -> Result<Self, Error> {
+ let mut matches = ok!(<Self as CommandFactory>::command().try_get_matches());
+ <Self as FromArgMatches>::from_arg_matches_mut(&mut matches).map_err(format_error::<Self>)
+ }
+
+ /// Parse from iterator, exit on error
+ fn parse_from<I, T>(itr: I) -> Self
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ let mut matches = <Self as CommandFactory>::command().get_matches_from(itr);
+ let res = <Self as FromArgMatches>::from_arg_matches_mut(&mut matches)
+ .map_err(format_error::<Self>);
+ match res {
+ Ok(s) => s,
+ Err(e) => {
+ // Since this is more of a development-time error, we aren't doing as fancy of a quit
+ // as `get_matches_from`
+ e.exit()
+ }
+ }
+ }
+
+ /// Parse from iterator, return Err on error.
+ fn try_parse_from<I, T>(itr: I) -> Result<Self, Error>
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ let mut matches = ok!(<Self as CommandFactory>::command().try_get_matches_from(itr));
+ <Self as FromArgMatches>::from_arg_matches_mut(&mut matches).map_err(format_error::<Self>)
+ }
+
+ /// Update from iterator, exit on error
+ fn update_from<I, T>(&mut self, itr: I)
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ let mut matches = <Self as CommandFactory>::command_for_update().get_matches_from(itr);
+ let res = <Self as FromArgMatches>::update_from_arg_matches_mut(self, &mut matches)
+ .map_err(format_error::<Self>);
+ if let Err(e) = res {
+ // Since this is more of a development-time error, we aren't doing as fancy of a quit
+ // as `get_matches_from`
+ e.exit()
+ }
+ }
+
+ /// Update from iterator, return Err on error.
+ fn try_update_from<I, T>(&mut self, itr: I) -> Result<(), Error>
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<OsString> + Clone,
+ {
+ let mut matches =
+ ok!(<Self as CommandFactory>::command_for_update().try_get_matches_from(itr));
+ <Self as FromArgMatches>::update_from_arg_matches_mut(self, &mut matches)
+ .map_err(format_error::<Self>)
+ }
+}
+
+/// Create a [`Command`] relevant for a user-defined container.
+///
+/// Derived as part of [`Parser`].
+pub trait CommandFactory: Sized {
+ /// Build a [`Command`] that can instantiate `Self`.
+ ///
+ /// See [`FromArgMatches::from_arg_matches_mut`] for instantiating `Self`.
+ fn command() -> Command;
+ /// Build a [`Command`] that can update `self`.
+ ///
+ /// See [`FromArgMatches::update_from_arg_matches_mut`] for updating `self`.
+ fn command_for_update() -> Command;
+}
+
+/// Converts an instance of [`ArgMatches`] to a user-defined container.
+///
+/// Derived as part of [`Parser`], [`Args`], and [`Subcommand`].
+pub trait FromArgMatches: Sized {
+ /// Instantiate `Self` from [`ArgMatches`], parsing the arguments as needed.
+ ///
+ /// Motivation: If our application had two CLI options, `--name
+ /// <STRING>` and the flag `--debug`, we may create a struct as follows:
+ ///
+ #[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+ #[cfg_attr(feature = "derive", doc = " ```no_run")]
+ /// struct Context {
+ /// name: String,
+ /// debug: bool
+ /// }
+ /// ```
+ ///
+ /// We then need to convert the `ArgMatches` that `clap` generated into our struct.
+ /// `from_arg_matches` serves as the equivalent of:
+ ///
+ #[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+ #[cfg_attr(feature = "derive", doc = " ```no_run")]
+ /// # use clap::ArgMatches;
+ /// # struct Context {
+ /// # name: String,
+ /// # debug: bool
+ /// # }
+ /// impl From<ArgMatches> for Context {
+ /// fn from(m: ArgMatches) -> Self {
+ /// Context {
+ /// name: m.get_one::<String>("name").unwrap().clone(),
+ /// debug: m.get_flag("debug"),
+ /// }
+ /// }
+ /// }
+ /// ```
+ fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error>;
+
+ /// Instantiate `Self` from [`ArgMatches`], parsing the arguments as needed.
+ ///
+ /// Motivation: If our application had two CLI options, `--name
+ /// <STRING>` and the flag `--debug`, we may create a struct as follows:
+ ///
+ #[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+ #[cfg_attr(feature = "derive", doc = " ```no_run")]
+ /// struct Context {
+ /// name: String,
+ /// debug: bool
+ /// }
+ /// ```
+ ///
+ /// We then need to convert the `ArgMatches` that `clap` generated into our struct.
+ /// `from_arg_matches_mut` serves as the equivalent of:
+ ///
+ #[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+ #[cfg_attr(feature = "derive", doc = " ```no_run")]
+ /// # use clap::ArgMatches;
+ /// # struct Context {
+ /// # name: String,
+ /// # debug: bool
+ /// # }
+ /// impl From<ArgMatches> for Context {
+ /// fn from(m: ArgMatches) -> Self {
+ /// Context {
+ /// name: m.get_one::<String>("name").unwrap().to_string(),
+ /// debug: m.get_flag("debug"),
+ /// }
+ /// }
+ /// }
+ /// ```
+ fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error> {
+ Self::from_arg_matches(matches)
+ }
+
+ /// Assign values from `ArgMatches` to `self`.
+ fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error>;
+
+ /// Assign values from `ArgMatches` to `self`.
+ fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> {
+ self.update_from_arg_matches(matches)
+ }
+}
+
+/// Parse a set of arguments into a user-defined container.
+///
+/// Implementing this trait lets a parent container delegate argument parsing behavior to `Self`.
+/// with:
+/// - `#[command(flatten)] args: ChildArgs`: Attribute can only be used with struct fields that impl
+/// `Args`.
+/// - `Variant(ChildArgs)`: No attribute is used with enum variants that impl `Args`.
+///
+/// See the [derive reference](crate::_derive) for attributes and best practices.
+///
+/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features]
+///
+/// # Example
+///
+#[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+#[cfg_attr(feature = "derive", doc = " ```")]
+/// #[derive(clap::Parser)]
+/// struct Args {
+/// #[command(flatten)]
+/// logging: LogArgs,
+/// }
+///
+/// #[derive(clap::Args)]
+/// struct LogArgs {
+/// #[arg(long, short = 'v', action = clap::ArgAction::Count)]
+/// verbose: u8,
+/// }
+/// ```
+pub trait Args: FromArgMatches + Sized {
+ /// Report the [`ArgGroup::id`][crate::ArgGroup::id] for this set of arguments
+ fn group_id() -> Option<crate::Id> {
+ None
+ }
+ /// Append to [`Command`] so it can instantiate `Self`.
+ ///
+ /// See also [`CommandFactory`].
+ fn augment_args(cmd: Command) -> Command;
+ /// Append to [`Command`] so it can update `self`.
+ ///
+ /// This is used to implement `#[command(flatten)]`
+ ///
+ /// See also [`CommandFactory`].
+ fn augment_args_for_update(cmd: Command) -> Command;
+}
+
+/// Parse a sub-command into a user-defined enum.
+///
+/// Implementing this trait lets a parent container delegate subcommand behavior to `Self`.
+/// with:
+/// - `#[command(subcommand)] field: SubCmd`: Attribute can be used with either struct fields or enum
+/// variants that impl `Subcommand`.
+/// - `#[command(flatten)] Variant(SubCmd)`: Attribute can only be used with enum variants that impl
+/// `Subcommand`.
+///
+/// See the [derive reference](crate::_derive) for attributes and best practices.
+///
+/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features]
+///
+/// # Example
+///
+#[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+#[cfg_attr(feature = "derive", doc = " ```")]
+/// #[derive(clap::Parser)]
+/// struct Args {
+/// #[command(subcommand)]
+/// action: Action,
+/// }
+///
+/// #[derive(clap::Subcommand)]
+/// enum Action {
+/// Add,
+/// Remove,
+/// }
+/// ```
+pub trait Subcommand: FromArgMatches + Sized {
+ /// Append to [`Command`] so it can instantiate `Self`.
+ ///
+ /// See also [`CommandFactory`].
+ fn augment_subcommands(cmd: Command) -> Command;
+ /// Append to [`Command`] so it can update `self`.
+ ///
+ /// This is used to implement `#[command(flatten)]`
+ ///
+ /// See also [`CommandFactory`].
+ fn augment_subcommands_for_update(cmd: Command) -> Command;
+ /// Test whether `Self` can parse a specific subcommand
+ fn has_subcommand(name: &str) -> bool;
+}
+
+/// Parse arguments into enums.
+///
+/// When deriving [`Parser`], a field whose type implements `ValueEnum` can have the attribute
+/// `#[arg(value_enum)]` which will
+/// - Call [`EnumValueParser`][crate::builder::EnumValueParser]
+/// - Allowing using the `#[arg(default_value_t)]` attribute without implementing `Display`.
+///
+/// See the [derive reference](crate::_derive) for attributes and best practices.
+///
+/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features]
+///
+/// # Example
+///
+#[cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+#[cfg_attr(feature = "derive", doc = " ```")]
+/// #[derive(clap::Parser)]
+/// struct Args {
+/// #[arg(value_enum)]
+/// level: Level,
+/// }
+///
+/// #[derive(clap::ValueEnum, Clone)]
+/// enum Level {
+/// Debug,
+/// Info,
+/// Warning,
+/// Error,
+/// }
+/// ```
+pub trait ValueEnum: Sized + Clone {
+ /// All possible argument values, in display order.
+ fn value_variants<'a>() -> &'a [Self];
+
+ /// Parse an argument into `Self`.
+ fn from_str(input: &str, ignore_case: bool) -> Result<Self, String> {
+ Self::value_variants()
+ .iter()
+ .find(|v| {
+ v.to_possible_value()
+ .expect("ValueEnum::value_variants contains only values with a corresponding ValueEnum::to_possible_value")
+ .matches(input, ignore_case)
+ })
+ .cloned()
+ .ok_or_else(|| format!("invalid variant: {input}"))
+ }
+
+ /// The canonical argument value.
+ ///
+ /// The value is `None` for skipped variants.
+ fn to_possible_value(&self) -> Option<PossibleValue>;
+}
+
+impl<T: Parser> Parser for Box<T> {
+ fn parse() -> Self {
+ Box::new(<T as Parser>::parse())
+ }
+
+ fn try_parse() -> Result<Self, Error> {
+ <T as Parser>::try_parse().map(Box::new)
+ }
+
+ fn parse_from<I, It>(itr: I) -> Self
+ where
+ I: IntoIterator<Item = It>,
+ It: Into<OsString> + Clone,
+ {
+ Box::new(<T as Parser>::parse_from(itr))
+ }
+
+ fn try_parse_from<I, It>(itr: I) -> Result<Self, Error>
+ where
+ I: IntoIterator<Item = It>,
+ It: Into<OsString> + Clone,
+ {
+ <T as Parser>::try_parse_from(itr).map(Box::new)
+ }
+}
+
+impl<T: CommandFactory> CommandFactory for Box<T> {
+ fn command<'help>() -> Command {
+ <T as CommandFactory>::command()
+ }
+ fn command_for_update<'help>() -> Command {
+ <T as CommandFactory>::command_for_update()
+ }
+}
+
+impl<T: FromArgMatches> FromArgMatches for Box<T> {
+ fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
+ <T as FromArgMatches>::from_arg_matches(matches).map(Box::new)
+ }
+ fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error> {
+ <T as FromArgMatches>::from_arg_matches_mut(matches).map(Box::new)
+ }
+ fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
+ <T as FromArgMatches>::update_from_arg_matches(self, matches)
+ }
+ fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> {
+ <T as FromArgMatches>::update_from_arg_matches_mut(self, matches)
+ }
+}
+
+impl<T: Args> Args for Box<T> {
+ fn augment_args(cmd: Command) -> Command {
+ <T as Args>::augment_args(cmd)
+ }
+ fn augment_args_for_update(cmd: Command) -> Command {
+ <T as Args>::augment_args_for_update(cmd)
+ }
+}
+
+impl<T: Subcommand> Subcommand for Box<T> {
+ fn augment_subcommands(cmd: Command) -> Command {
+ <T as Subcommand>::augment_subcommands(cmd)
+ }
+ fn augment_subcommands_for_update(cmd: Command) -> Command {
+ <T as Subcommand>::augment_subcommands_for_update(cmd)
+ }
+ fn has_subcommand(name: &str) -> bool {
+ <T as Subcommand>::has_subcommand(name)
+ }
+}
+
+fn format_error<I: CommandFactory>(err: crate::Error) -> crate::Error {
+ let mut cmd = I::command();
+ err.format(&mut cmd)
+}
diff --git a/src/error/context.rs b/src/error/context.rs
new file mode 100644
index 0000000..045923c
--- /dev/null
+++ b/src/error/context.rs
@@ -0,0 +1,114 @@
+/// Semantics for a piece of error information
+#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
+#[non_exhaustive]
+#[cfg(feature = "error-context")]
+pub enum ContextKind {
+ /// The cause of the error
+ InvalidSubcommand,
+ /// The cause of the error
+ InvalidArg,
+ /// Existing arguments
+ PriorArg,
+ /// Accepted subcommands
+ ValidSubcommand,
+ /// Accepted values
+ ValidValue,
+ /// Rejected values
+ InvalidValue,
+ /// Number of values present
+ ActualNumValues,
+ /// Number of allowed values
+ ExpectedNumValues,
+ /// Minimum number of allowed values
+ MinValues,
+ /// Potential fix for the user
+ SuggestedCommand,
+ /// Potential fix for the user
+ SuggestedSubcommand,
+ /// Potential fix for the user
+ SuggestedArg,
+ /// Potential fix for the user
+ SuggestedValue,
+ /// Trailing argument
+ TrailingArg,
+ /// Potential fix for the user
+ Suggested,
+ /// A usage string
+ Usage,
+ /// An opaque message to the user
+ Custom,
+}
+
+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,
+ }
+ }
+}
+
+impl std::fmt::Display for ContextKind {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ self.as_str().unwrap_or_default().fmt(f)
+ }
+}
+
+/// A piece of error information
+#[derive(Clone, Debug, PartialEq, Eq)]
+#[non_exhaustive]
+#[cfg(feature = "error-context")]
+pub enum ContextValue {
+ /// [`ContextKind`] is self-sufficient, no additional information needed
+ None,
+ /// A single value
+ Bool(bool),
+ /// A single value
+ String(String),
+ /// Many values
+ Strings(Vec<String>),
+ /// A single value
+ StyledStr(crate::builder::StyledStr),
+ /// many value
+ StyledStrs(Vec<crate::builder::StyledStr>),
+ /// A single value
+ Number(isize),
+}
+
+impl std::fmt::Display for ContextValue {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::None => "".fmt(f),
+ Self::Bool(v) => v.fmt(f),
+ Self::String(v) => v.fmt(f),
+ Self::Strings(v) => v.join(", ").fmt(f),
+ Self::StyledStr(v) => v.fmt(f),
+ Self::StyledStrs(v) => {
+ for (i, v) in v.iter().enumerate() {
+ if i != 0 {
+ ", ".fmt(f)?;
+ }
+ v.fmt(f)?;
+ }
+ Ok(())
+ }
+ Self::Number(v) => v.fmt(f),
+ }
+ }
+}
diff --git a/src/error/format.rs b/src/error/format.rs
new file mode 100644
index 0000000..d3ce6c6
--- /dev/null
+++ b/src/error/format.rs
@@ -0,0 +1,468 @@
+#![allow(missing_copy_implementations)]
+#![allow(missing_debug_implementations)]
+#![cfg_attr(not(feature = "error-context"), allow(dead_code))]
+#![cfg_attr(not(feature = "error-context"), allow(unused_imports))]
+
+use crate::builder::Command;
+use crate::builder::StyledStr;
+#[cfg(feature = "error-context")]
+use crate::error::ContextKind;
+#[cfg(feature = "error-context")]
+use crate::error::ContextValue;
+use crate::error::ErrorKind;
+use crate::output::TAB;
+
+/// Defines how to format an error for displaying to the user
+pub trait ErrorFormatter: Sized {
+ /// Stylize the error for the terminal
+ fn format_error(error: &crate::error::Error<Self>) -> StyledStr;
+}
+
+/// Report [`ErrorKind`]
+///
+/// No context is included.
+///
+/// **NOTE:** Consider removing the [`error-context`][crate::_features] default feature if using this to remove all
+/// overhead for [`RichFormatter`].
+#[non_exhaustive]
+pub struct KindFormatter;
+
+impl ErrorFormatter for KindFormatter {
+ fn format_error(error: &crate::error::Error<Self>) -> StyledStr {
+ let mut styled = StyledStr::new();
+ start_error(&mut styled);
+ if let Some(msg) = error.kind().as_str() {
+ styled.none(msg.to_owned());
+ } else if let Some(source) = error.inner.source.as_ref() {
+ styled.none(source.to_string());
+ } else {
+ styled.none("unknown cause");
+ }
+ styled.none("\n");
+ styled
+ }
+}
+
+/// Richly formatted error context
+///
+/// This follows the [rustc diagnostic style guide](https://rustc-dev-guide.rust-lang.org/diagnostics.html#suggestion-style-guide).
+#[non_exhaustive]
+#[cfg(feature = "error-context")]
+pub struct RichFormatter;
+
+#[cfg(feature = "error-context")]
+impl ErrorFormatter for RichFormatter {
+ fn format_error(error: &crate::error::Error<Self>) -> StyledStr {
+ let mut styled = StyledStr::new();
+ start_error(&mut styled);
+
+ if !write_dynamic_context(error, &mut styled) {
+ if let Some(msg) = error.kind().as_str() {
+ styled.none(msg.to_owned());
+ } else if let Some(source) = error.inner.source.as_ref() {
+ styled.none(source.to_string());
+ } else {
+ styled.none("unknown cause");
+ }
+ }
+
+ let mut suggested = false;
+ if let Some(valid) = error.get(ContextKind::SuggestedSubcommand) {
+ styled.none("\n");
+ if !suggested {
+ styled.none("\n");
+ suggested = true;
+ }
+ did_you_mean(&mut styled, "subcommand", valid);
+ }
+ if let Some(valid) = error.get(ContextKind::SuggestedArg) {
+ styled.none("\n");
+ if !suggested {
+ styled.none("\n");
+ suggested = true;
+ }
+ did_you_mean(&mut styled, "argument", valid);
+ }
+ if let Some(valid) = error.get(ContextKind::SuggestedValue) {
+ styled.none("\n");
+ if !suggested {
+ styled.none("\n");
+ suggested = true;
+ }
+ did_you_mean(&mut styled, "value", valid);
+ }
+ let suggestions = error.get(ContextKind::Suggested);
+ if let Some(ContextValue::StyledStrs(suggestions)) = suggestions {
+ if !suggested {
+ styled.none("\n");
+ }
+ for suggestion in suggestions {
+ styled.none("\n");
+ styled.none(TAB);
+ styled.good("note: ");
+ styled.extend(suggestion.iter());
+ }
+ }
+
+ let usage = error.get(ContextKind::Usage);
+ if let Some(ContextValue::StyledStr(usage)) = usage {
+ put_usage(&mut styled, usage.clone());
+ }
+
+ try_help(&mut styled, error.inner.help_flag);
+
+ styled
+ }
+}
+
+fn start_error(styled: &mut StyledStr) {
+ styled.error("error:");
+ styled.none(" ");
+}
+
+#[must_use]
+#[cfg(feature = "error-context")]
+fn write_dynamic_context(error: &crate::error::Error, styled: &mut StyledStr) -> bool {
+ match error.kind() {
+ ErrorKind::ArgumentConflict => {
+ let invalid_arg = error.get(ContextKind::InvalidArg);
+ let prior_arg = error.get(ContextKind::PriorArg);
+ if let (Some(ContextValue::String(invalid_arg)), Some(prior_arg)) =
+ (invalid_arg, prior_arg)
+ {
+ if ContextValue::String(invalid_arg.clone()) == *prior_arg {
+ styled.none("the argument '");
+ styled.warning(invalid_arg);
+ styled.none("' cannot be used multiple times");
+ } else {
+ styled.none("the argument '");
+ styled.warning(invalid_arg);
+ styled.none("' cannot be used with");
+
+ match prior_arg {
+ ContextValue::Strings(values) => {
+ styled.none(":");
+ for v in values {
+ styled.none("\n");
+ styled.none(TAB);
+ styled.warning(&**v);
+ }
+ }
+ ContextValue::String(value) => {
+ styled.none(" '");
+ styled.warning(value);
+ styled.none("'");
+ }
+ _ => {
+ styled.none(" one or more of the other specified arguments");
+ }
+ }
+ }
+ true
+ } else {
+ false
+ }
+ }
+ ErrorKind::NoEquals => {
+ let invalid_arg = error.get(ContextKind::InvalidArg);
+ if let Some(ContextValue::String(invalid_arg)) = invalid_arg {
+ styled.none("equal sign is needed when assigning values to '");
+ styled.warning(invalid_arg);
+ styled.none("'");
+ true
+ } else {
+ false
+ }
+ }
+ ErrorKind::InvalidValue => {
+ let invalid_arg = error.get(ContextKind::InvalidArg);
+ let invalid_value = error.get(ContextKind::InvalidValue);
+ if let (
+ Some(ContextValue::String(invalid_arg)),
+ Some(ContextValue::String(invalid_value)),
+ ) = (invalid_arg, invalid_value)
+ {
+ if invalid_value.is_empty() {
+ styled.none("a value is required for '");
+ styled.warning(invalid_arg);
+ styled.none("' but none was supplied");
+ } else {
+ styled.none("invalid value '");
+ styled.none(invalid_value);
+ styled.none("' for '");
+ styled.warning(invalid_arg);
+ styled.none("'");
+ }
+
+ let possible_values = error.get(ContextKind::ValidValue);
+ if let Some(ContextValue::Strings(possible_values)) = possible_values {
+ if !possible_values.is_empty() {
+ styled.none("\n");
+ styled.none(TAB);
+ styled.none("[possible values: ");
+ if let Some((last, elements)) = possible_values.split_last() {
+ for v in elements {
+ styled.good(escape(v));
+ styled.none(", ");
+ }
+ styled.good(escape(last));
+ }
+ styled.none("]");
+ }
+ }
+ true
+ } else {
+ false
+ }
+ }
+ ErrorKind::InvalidSubcommand => {
+ let invalid_sub = error.get(ContextKind::InvalidSubcommand);
+ if let Some(ContextValue::String(invalid_sub)) = invalid_sub {
+ styled.none("unrecognized subcommand '");
+ styled.warning(invalid_sub);
+ styled.none("'");
+ true
+ } else {
+ false
+ }
+ }
+ ErrorKind::MissingRequiredArgument => {
+ let invalid_arg = error.get(ContextKind::InvalidArg);
+ if let Some(ContextValue::Strings(invalid_arg)) = invalid_arg {
+ styled.none("the following required arguments were not provided:");
+ for v in invalid_arg {
+ styled.none("\n");
+ styled.none(TAB);
+ styled.good(&**v);
+ }
+ true
+ } else {
+ false
+ }
+ }
+ ErrorKind::MissingSubcommand => {
+ let invalid_sub = error.get(ContextKind::InvalidSubcommand);
+ if let Some(ContextValue::String(invalid_sub)) = invalid_sub {
+ styled.none("'");
+ styled.warning(invalid_sub);
+ styled.none("' requires a subcommand but one was not provided");
+
+ let possible_values = error.get(ContextKind::ValidSubcommand);
+ if let Some(ContextValue::Strings(possible_values)) = possible_values {
+ if !possible_values.is_empty() {
+ styled.none("\n");
+ styled.none(TAB);
+ styled.none("[subcommands: ");
+ if let Some((last, elements)) = possible_values.split_last() {
+ for v in elements {
+ styled.good(escape(v));
+ styled.none(", ");
+ }
+ styled.good(escape(last));
+ }
+ styled.none("]");
+ }
+ }
+
+ true
+ } else {
+ false
+ }
+ }
+ ErrorKind::InvalidUtf8 => false,
+ ErrorKind::TooManyValues => {
+ let invalid_arg = error.get(ContextKind::InvalidArg);
+ let invalid_value = error.get(ContextKind::InvalidValue);
+ if let (
+ Some(ContextValue::String(invalid_arg)),
+ Some(ContextValue::String(invalid_value)),
+ ) = (invalid_arg, invalid_value)
+ {
+ styled.none("unexpected value '");
+ styled.warning(invalid_value);
+ styled.none("' for '");
+ styled.warning(invalid_arg);
+ styled.none("' found; no more were expected");
+ true
+ } else {
+ false
+ }
+ }
+ ErrorKind::TooFewValues => {
+ let invalid_arg = error.get(ContextKind::InvalidArg);
+ let actual_num_values = error.get(ContextKind::ActualNumValues);
+ let min_values = error.get(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 = singular_or_plural(*actual_num_values as usize);
+ styled.warning(min_values.to_string());
+ styled.none(" more values required by '");
+ styled.warning(invalid_arg);
+ styled.none("'; only ");
+ styled.warning(actual_num_values.to_string());
+ styled.none(were_provided);
+ true
+ } else {
+ false
+ }
+ }
+ ErrorKind::ValueValidation => {
+ let invalid_arg = error.get(ContextKind::InvalidArg);
+ let invalid_value = error.get(ContextKind::InvalidValue);
+ if let (
+ Some(ContextValue::String(invalid_arg)),
+ Some(ContextValue::String(invalid_value)),
+ ) = (invalid_arg, invalid_value)
+ {
+ styled.none("invalid value '");
+ styled.warning(invalid_value);
+ styled.none("' for '");
+ styled.warning(invalid_arg);
+ if let Some(source) = error.inner.source.as_deref() {
+ styled.none("': ");
+ styled.none(source.to_string());
+ } else {
+ styled.none("'");
+ }
+ true
+ } else {
+ false
+ }
+ }
+ ErrorKind::WrongNumberOfValues => {
+ let invalid_arg = error.get(ContextKind::InvalidArg);
+ let actual_num_values = error.get(ContextKind::ActualNumValues);
+ let num_values = error.get(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 = singular_or_plural(*actual_num_values as usize);
+ styled.warning(num_values.to_string());
+ styled.none(" values required for '");
+ styled.warning(invalid_arg);
+ styled.none("' but ");
+ styled.warning(actual_num_values.to_string());
+ styled.none(were_provided);
+ true
+ } else {
+ false
+ }
+ }
+ ErrorKind::UnknownArgument => {
+ let invalid_arg = error.get(ContextKind::InvalidArg);
+ if let Some(ContextValue::String(invalid_arg)) = invalid_arg {
+ styled.none("unexpected argument '");
+ styled.warning(invalid_arg.to_string());
+ styled.none("' found");
+ true
+ } else {
+ false
+ }
+ }
+ ErrorKind::DisplayHelp
+ | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
+ | ErrorKind::DisplayVersion
+ | ErrorKind::Io
+ | ErrorKind::Format => false,
+ }
+}
+
+pub(crate) fn format_error_message(
+ message: &str,
+ cmd: Option<&Command>,
+ usage: Option<StyledStr>,
+) -> StyledStr {
+ let mut styled = StyledStr::new();
+ start_error(&mut styled);
+ styled.none(message);
+ if let Some(usage) = usage {
+ put_usage(&mut styled, usage);
+ }
+ if let Some(cmd) = cmd {
+ try_help(&mut styled, get_help_flag(cmd));
+ }
+ styled
+}
+
+/// 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"
+ }
+}
+
+fn put_usage(styled: &mut StyledStr, usage: StyledStr) {
+ styled.none("\n\n");
+ styled.extend(usage.into_iter());
+}
+
+pub(crate) 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(styled: &mut StyledStr, help: Option<&str>) {
+ if let Some(help) = help {
+ styled.none("\n\nFor more information, try '");
+ styled.literal(help.to_owned());
+ styled.none("'.\n");
+ } else {
+ styled.none("\n");
+ }
+}
+
+#[cfg(feature = "error-context")]
+fn did_you_mean(styled: &mut StyledStr, context: &str, valid: &ContextValue) {
+ if let ContextValue::String(valid) = valid {
+ styled.none(TAB);
+ styled.good("note: ");
+ styled.none(context);
+ styled.none(" '");
+ styled.good(valid);
+ styled.none("' exists");
+ } else if let ContextValue::Strings(valid) = valid {
+ styled.none(TAB);
+ styled.good("note: ");
+ styled.none(context);
+ if valid.len() > 1 {
+ styled.none("s");
+ }
+ styled.none(" ");
+ for (i, valid) in valid.iter().enumerate() {
+ if i != 0 {
+ styled.none(", ");
+ }
+ styled.none("'");
+ styled.good(valid);
+ styled.none("'");
+ }
+ if valid.len() == 1 {
+ styled.none(" exists");
+ } else {
+ styled.none(" exist");
+ }
+ }
+}
+
+fn escape(s: impl AsRef<str>) -> String {
+ let s = s.as_ref();
+ if s.contains(char::is_whitespace) {
+ format!("{s:?}")
+ } else {
+ s.to_owned()
+ }
+}
diff --git a/src/error/kind.rs b/src/error/kind.rs
new file mode 100644
index 0000000..1859237
--- /dev/null
+++ b/src/error/kind.rs
@@ -0,0 +1,348 @@
+/// Command line argument parser kind of error
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
+#[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, error::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, error::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, error::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 doesn't use equals for an option that requires equal
+ /// sign to provide values.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let res = Command::new("prog")
+ /// .arg(Arg::new("color")
+ /// .action(ArgAction::Set)
+ /// .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, error::ErrorKind, value_parser};
+ /// 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")
+ /// .value_parser(value_parser!(u8)))
+ /// .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::num_args`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind};
+ /// let result = Command::new("prog")
+ /// .arg(Arg::new("arg")
+ /// .num_args(1..=2))
+ /// .try_get_matches_from(vec!["prog", "too", "many", "values"]);
+ /// assert!(result.is_err());
+ /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooManyValues);
+ /// ```
+ /// [`Arg::num_args`]: crate::Arg::num_args()
+ TooManyValues,
+
+ /// Occurs when the user provides fewer values for an argument than were defined by setting
+ /// [`Arg::num_args`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind};
+ /// let result = Command::new("prog")
+ /// .arg(Arg::new("some_opt")
+ /// .long("opt")
+ /// .num_args(3..))
+ /// .try_get_matches_from(vec!["prog", "--opt", "too", "few"]);
+ /// assert!(result.is_err());
+ /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooFewValues);
+ /// ```
+ /// [`Arg::num_args`]: crate::Arg::num_args()
+ TooFewValues,
+
+ /// Occurs when the user provides a different number of values for an argument than what's
+ /// been defined by setting [`Arg::num_args`] or than was implicitly set by
+ /// [`Arg::value_names`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
+ /// let result = Command::new("prog")
+ /// .arg(Arg::new("some_opt")
+ /// .long("opt")
+ /// .action(ArgAction::Set)
+ /// .num_args(2))
+ /// .try_get_matches_from(vec!["prog", "--opt", "wrong"]);
+ /// assert!(result.is_err());
+ /// assert_eq!(result.unwrap_err().kind(), ErrorKind::WrongNumberOfValues);
+ /// ```
+ ///
+ /// [`Arg::num_args`]: crate::Arg::num_args()
+ /// [`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, error::ErrorKind, ArgAction};
+ /// let result = Command::new("prog")
+ /// .arg(Arg::new("debug")
+ /// .long("debug")
+ /// .action(ArgAction::SetTrue)
+ /// .conflicts_with("color"))
+ /// .arg(Arg::new("color")
+ /// .long("color")
+ /// .action(ArgAction::SetTrue))
+ /// .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, error::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, error::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 a value containing invalid UTF-8.
+ ///
+ /// To allow arbitrary data
+ /// - Set [`Arg::value_parser(value_parser!(OsString))`] for argument values
+ /// - Set [`Command::external_subcommand_value_parser`] 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, error::ErrorKind, ArgAction};
+ /// # use std::os::unix::ffi::OsStringExt;
+ /// # use std::ffi::OsString;
+ /// let result = Command::new("prog")
+ /// .arg(Arg::new("utf8")
+ /// .short('u')
+ /// .action(ArgAction::Set))
+ /// .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::external_subcommand_value_parser`]: crate::Command::external_subcommand_value_parser
+ 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
+ ///
+ #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
+ #[cfg_attr(feature = "help", doc = " ```")]
+ /// # use clap::{Command, Arg, error::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, error::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, error::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,
+
+ /// 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("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"),
+ 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::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,
+ }
+ }
+}
+
+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/src/error/mod.rs b/src/error/mod.rs
new file mode 100644
index 0000000..2d8bf62
--- /dev/null
+++ b/src/error/mod.rs
@@ -0,0 +1,876 @@
+//! Error reporting
+
+#![cfg_attr(not(feature = "error-context"), allow(dead_code))]
+#![cfg_attr(not(feature = "error-context"), allow(unused_imports))]
+#![cfg_attr(not(feature = "error-context"), allow(unused_variables))]
+#![cfg_attr(not(feature = "error-context"), allow(unused_mut))]
+#![cfg_attr(not(feature = "error-context"), allow(clippy::let_and_return))]
+
+// Std
+use std::{
+ borrow::Cow,
+ convert::From,
+ error,
+ fmt::{self, Debug, Display, Formatter},
+ io::{self},
+ result::Result as StdResult,
+};
+
+// Internal
+use crate::builder::StyledStr;
+use crate::output::fmt::Colorizer;
+use crate::output::fmt::Stream;
+use crate::parser::features::suggestions;
+use crate::util::FlatMap;
+use crate::util::{color::ColorChoice, safe_exit, SUCCESS_CODE, USAGE_CODE};
+use crate::Command;
+
+#[cfg(feature = "error-context")]
+mod context;
+mod format;
+mod kind;
+
+pub use format::ErrorFormatter;
+pub use format::KindFormatter;
+pub use kind::ErrorKind;
+
+#[cfg(feature = "error-context")]
+pub use context::ContextKind;
+#[cfg(feature = "error-context")]
+pub use context::ContextValue;
+#[cfg(feature = "error-context")]
+pub use format::RichFormatter;
+
+#[cfg(not(feature = "error-context"))]
+pub use KindFormatter as DefaultFormatter;
+#[cfg(feature = "error-context")]
+pub use RichFormatter as DefaultFormatter;
+
+/// 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
+pub struct Error<F: ErrorFormatter = DefaultFormatter> {
+ inner: Box<ErrorInner>,
+ phantom: std::marker::PhantomData<F>,
+}
+
+#[derive(Debug)]
+struct ErrorInner {
+ kind: ErrorKind,
+ #[cfg(feature = "error-context")]
+ context: FlatMap<ContextKind, ContextValue>,
+ message: Option<Message>,
+ source: Option<Box<dyn error::Error + Send + Sync>>,
+ help_flag: Option<&'static str>,
+ color_when: ColorChoice,
+ color_help_when: ColorChoice,
+ backtrace: Option<Backtrace>,
+}
+
+impl<F: ErrorFormatter> Error<F> {
+ /// 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(false);
+ let usage = cmd.render_usage_();
+ if let Some(message) = self.inner.message.as_mut() {
+ message.format(cmd, usage);
+ }
+ self.with_cmd(cmd)
+ }
+
+ /// Create an error with a pre-defined message
+ ///
+ /// See also
+ /// - [`Error::insert`]
+ /// - [`Error::with_cmd`]
+ ///
+ /// # Example
+ ///
+ #[cfg_attr(not(feature = "error-context"), doc = " ```ignore")]
+ #[cfg_attr(feature = "error-context", doc = " ```")]
+ /// # use clap::error::ErrorKind;
+ /// # use clap::error::ContextKind;
+ /// # use clap::error::ContextValue;
+ ///
+ /// let cmd = clap::Command::new("prog");
+ ///
+ /// let mut err = clap::Error::new(ErrorKind::ValueValidation)
+ /// .with_cmd(&cmd);
+ /// err.insert(ContextKind::InvalidArg, ContextValue::String("--foo".to_owned()));
+ /// err.insert(ContextKind::InvalidValue, ContextValue::String("bar".to_owned()));
+ ///
+ /// err.print();
+ /// ```
+ pub fn new(kind: ErrorKind) -> Self {
+ Self {
+ inner: Box::new(ErrorInner {
+ kind,
+ #[cfg(feature = "error-context")]
+ context: FlatMap::new(),
+ message: None,
+ source: None,
+ help_flag: None,
+ color_when: ColorChoice::Never,
+ color_help_when: ColorChoice::Never,
+ backtrace: Backtrace::new(),
+ }),
+ phantom: Default::default(),
+ }
+ }
+
+ /// Apply [`Command`]'s formatting to the error
+ ///
+ /// Generally, this is used with [`Error::new`]
+ pub fn with_cmd(self, cmd: &Command) -> Self {
+ self.set_color(cmd.get_color())
+ .set_colored_help(cmd.color_help())
+ .set_help_flag(format::get_help_flag(cmd))
+ }
+
+ /// Apply an alternative formatter to the error
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// # use clap::Command;
+ /// # use clap::Arg;
+ /// # use clap::error::KindFormatter;
+ /// let cmd = Command::new("foo")
+ /// .arg(Arg::new("input").required(true));
+ /// let matches = cmd
+ /// .try_get_matches_from(["foo", "input.txt"])
+ /// .map_err(|e| e.apply::<KindFormatter>())
+ /// .unwrap_or_else(|e| e.exit());
+ /// ```
+ pub fn apply<EF: ErrorFormatter>(self) -> Error<EF> {
+ Error {
+ inner: self.inner,
+ phantom: Default::default(),
+ }
+ }
+
+ /// Type of error for programmatic processing
+ pub fn kind(&self) -> ErrorKind {
+ self.inner.kind
+ }
+
+ /// Additional information to further qualify the error
+ #[cfg(feature = "error-context")]
+ pub fn context(&self) -> impl Iterator<Item = (ContextKind, &ContextValue)> {
+ self.inner.context.iter().map(|(k, v)| (*k, v))
+ }
+
+ /// Lookup a piece of context
+ #[inline(never)]
+ #[cfg(feature = "error-context")]
+ pub fn get(&self, kind: ContextKind) -> Option<&ContextValue> {
+ self.inner.context.get(&kind)
+ }
+
+ /// Insert a piece of context
+ #[inline(never)]
+ #[cfg(feature = "error-context")]
+ pub fn insert(&mut self, kind: ContextKind, value: ContextValue) -> Option<ContextValue> {
+ self.inner.context.insert(kind, value)
+ }
+
+ /// 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();
+
+ 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<()> {
+ let style = self.formatted();
+ let color_when = if matches!(
+ self.kind(),
+ ErrorKind::DisplayHelp | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand,
+ ) {
+ self.inner.color_help_when
+ } else {
+ self.inner.color_when
+ };
+ let c = Colorizer::new(self.stream(), color_when).with_content(style.into_owned());
+ c.print()
+ }
+
+ /// Render the error message to a [`StyledStr`].
+ ///
+ /// # Example
+ /// ```no_run
+ /// use clap::Command;
+ ///
+ /// match Command::new("Command").try_get_matches() {
+ /// Ok(matches) => {
+ /// // do_something
+ /// },
+ /// Err(err) => {
+ /// let err = err.render();
+ /// println!("{}", err);
+ /// // do_something
+ /// },
+ /// };
+ /// ```
+ pub fn render(&self) -> StyledStr {
+ self.formatted().into_owned()
+ }
+
+ #[inline(never)]
+ fn for_app(kind: ErrorKind, cmd: &Command, styled: StyledStr) -> Self {
+ Self::new(kind).set_message(styled).with_cmd(cmd)
+ }
+
+ pub(crate) fn set_message(mut self, message: impl Into<Message>) -> Self {
+ self.inner.message = Some(message.into());
+ 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_colored_help(mut self, color_help_when: ColorChoice) -> Self {
+ self.inner.color_help_when = color_help_when;
+ self
+ }
+
+ pub(crate) fn set_help_flag(mut self, help_flag: Option<&'static str>) -> Self {
+ self.inner.help_flag = help_flag;
+ self
+ }
+
+ /// Does not verify if `ContextKind` is already present
+ #[inline(never)]
+ #[cfg(feature = "error-context")]
+ pub(crate) fn insert_context_unchecked(
+ mut self,
+ kind: ContextKind,
+ value: ContextValue,
+ ) -> Self {
+ self.inner.context.insert_unchecked(kind, value);
+ self
+ }
+
+ /// Does not verify if `ContextKind` is already present
+ #[inline(never)]
+ #[cfg(feature = "error-context")]
+ pub(crate) fn extend_context_unchecked<const N: usize>(
+ mut self,
+ context: [(ContextKind, ContextValue); N],
+ ) -> Self {
+ self.inner.context.extend_unchecked(context);
+ self
+ }
+
+ pub(crate) fn display_help(cmd: &Command, styled: StyledStr) -> Self {
+ Self::for_app(ErrorKind::DisplayHelp, cmd, styled)
+ }
+
+ pub(crate) fn display_help_error(cmd: &Command, styled: StyledStr) -> Self {
+ Self::for_app(
+ ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand,
+ cmd,
+ styled,
+ )
+ }
+
+ pub(crate) fn display_version(cmd: &Command, styled: StyledStr) -> Self {
+ Self::for_app(ErrorKind::DisplayVersion, cmd, styled)
+ }
+
+ pub(crate) fn argument_conflict(
+ cmd: &Command,
+ arg: String,
+ mut others: Vec<String>,
+ usage: Option<StyledStr>,
+ ) -> Self {
+ let mut err = Self::new(ErrorKind::ArgumentConflict).with_cmd(cmd);
+
+ #[cfg(feature = "error-context")]
+ {
+ let others = match others.len() {
+ 0 => ContextValue::None,
+ 1 => ContextValue::String(others.pop().unwrap()),
+ _ => ContextValue::Strings(others),
+ };
+ err = err.extend_context_unchecked([
+ (ContextKind::InvalidArg, ContextValue::String(arg)),
+ (ContextKind::PriorArg, others),
+ ]);
+ if let Some(usage) = usage {
+ err = err
+ .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage));
+ }
+ }
+
+ err
+ }
+
+ pub(crate) fn empty_value(cmd: &Command, good_vals: &[String], arg: String) -> Self {
+ Self::invalid_value(cmd, "".to_owned(), good_vals, arg)
+ }
+
+ pub(crate) fn no_equals(cmd: &Command, arg: String, usage: Option<StyledStr>) -> Self {
+ let mut err = Self::new(ErrorKind::NoEquals).with_cmd(cmd);
+
+ #[cfg(feature = "error-context")]
+ {
+ err = err
+ .extend_context_unchecked([(ContextKind::InvalidArg, ContextValue::String(arg))]);
+ if let Some(usage) = usage {
+ err = err
+ .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage));
+ }
+ }
+
+ err
+ }
+
+ pub(crate) fn invalid_value(
+ cmd: &Command,
+ bad_val: String,
+ good_vals: &[String],
+ arg: String,
+ ) -> Self {
+ let suggestion = suggestions::did_you_mean(&bad_val, good_vals.iter()).pop();
+ let mut err = Self::new(ErrorKind::InvalidValue).with_cmd(cmd);
+
+ #[cfg(feature = "error-context")]
+ {
+ err = err.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: Vec<String>,
+ name: String,
+ usage: Option<StyledStr>,
+ ) -> Self {
+ let mut err = Self::new(ErrorKind::InvalidSubcommand).with_cmd(cmd);
+
+ #[cfg(feature = "error-context")]
+ {
+ let mut styled_suggestion = StyledStr::new();
+ styled_suggestion.none("to pass '");
+ styled_suggestion.warning(&subcmd);
+ styled_suggestion.none("' as a value, use '");
+ styled_suggestion.good(name);
+ styled_suggestion.good(" -- ");
+ styled_suggestion.good(&subcmd);
+ styled_suggestion.none("'");
+
+ err = err.extend_context_unchecked([
+ (ContextKind::InvalidSubcommand, ContextValue::String(subcmd)),
+ (
+ ContextKind::SuggestedSubcommand,
+ ContextValue::Strings(did_you_mean),
+ ),
+ (
+ ContextKind::Suggested,
+ ContextValue::StyledStrs(vec![styled_suggestion]),
+ ),
+ ]);
+ if let Some(usage) = usage {
+ err = err
+ .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage));
+ }
+ }
+
+ err
+ }
+
+ pub(crate) fn unrecognized_subcommand(
+ cmd: &Command,
+ subcmd: String,
+ usage: Option<StyledStr>,
+ ) -> Self {
+ let mut err = Self::new(ErrorKind::InvalidSubcommand).with_cmd(cmd);
+
+ #[cfg(feature = "error-context")]
+ {
+ err = err.extend_context_unchecked([(
+ ContextKind::InvalidSubcommand,
+ ContextValue::String(subcmd),
+ )]);
+ if let Some(usage) = usage {
+ err = err
+ .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage));
+ }
+ }
+
+ err
+ }
+
+ pub(crate) fn missing_required_argument(
+ cmd: &Command,
+ required: Vec<String>,
+ usage: Option<StyledStr>,
+ ) -> Self {
+ let mut err = Self::new(ErrorKind::MissingRequiredArgument).with_cmd(cmd);
+
+ #[cfg(feature = "error-context")]
+ {
+ err = err.extend_context_unchecked([(
+ ContextKind::InvalidArg,
+ ContextValue::Strings(required),
+ )]);
+ if let Some(usage) = usage {
+ err = err
+ .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage));
+ }
+ }
+
+ err
+ }
+
+ pub(crate) fn missing_subcommand(
+ cmd: &Command,
+ parent: String,
+ available: Vec<String>,
+ usage: Option<StyledStr>,
+ ) -> Self {
+ let mut err = Self::new(ErrorKind::MissingSubcommand).with_cmd(cmd);
+
+ #[cfg(feature = "error-context")]
+ {
+ err = err.extend_context_unchecked([
+ (ContextKind::InvalidSubcommand, ContextValue::String(parent)),
+ (
+ ContextKind::ValidSubcommand,
+ ContextValue::Strings(available),
+ ),
+ ]);
+ if let Some(usage) = usage {
+ err = err
+ .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage));
+ }
+ }
+
+ err
+ }
+
+ pub(crate) fn invalid_utf8(cmd: &Command, usage: Option<StyledStr>) -> Self {
+ let mut err = Self::new(ErrorKind::InvalidUtf8).with_cmd(cmd);
+
+ #[cfg(feature = "error-context")]
+ {
+ if let Some(usage) = usage {
+ err = err
+ .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage));
+ }
+ }
+
+ err
+ }
+
+ pub(crate) fn too_many_values(
+ cmd: &Command,
+ val: String,
+ arg: String,
+ usage: Option<StyledStr>,
+ ) -> Self {
+ let mut err = Self::new(ErrorKind::TooManyValues).with_cmd(cmd);
+
+ #[cfg(feature = "error-context")]
+ {
+ err = err.extend_context_unchecked([
+ (ContextKind::InvalidArg, ContextValue::String(arg)),
+ (ContextKind::InvalidValue, ContextValue::String(val)),
+ ]);
+ if let Some(usage) = usage {
+ err = err
+ .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage));
+ }
+ }
+
+ err
+ }
+
+ pub(crate) fn too_few_values(
+ cmd: &Command,
+ arg: String,
+ min_vals: usize,
+ curr_vals: usize,
+ usage: Option<StyledStr>,
+ ) -> Self {
+ let mut err = Self::new(ErrorKind::TooFewValues).with_cmd(cmd);
+
+ #[cfg(feature = "error-context")]
+ {
+ err = err.extend_context_unchecked([
+ (ContextKind::InvalidArg, ContextValue::String(arg)),
+ (
+ ContextKind::MinValues,
+ ContextValue::Number(min_vals as isize),
+ ),
+ (
+ ContextKind::ActualNumValues,
+ ContextValue::Number(curr_vals as isize),
+ ),
+ ]);
+ if let Some(usage) = usage {
+ err = err
+ .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage));
+ }
+ }
+
+ err
+ }
+
+ pub(crate) fn value_validation(
+ arg: String,
+ val: String,
+ err: Box<dyn error::Error + Send + Sync>,
+ ) -> Self {
+ let mut err = Self::new(ErrorKind::ValueValidation).set_source(err);
+
+ #[cfg(feature = "error-context")]
+ {
+ err = err.extend_context_unchecked([
+ (ContextKind::InvalidArg, ContextValue::String(arg)),
+ (ContextKind::InvalidValue, ContextValue::String(val)),
+ ]);
+ }
+
+ err
+ }
+
+ pub(crate) fn wrong_number_of_values(
+ cmd: &Command,
+ arg: String,
+ num_vals: usize,
+ curr_vals: usize,
+ usage: Option<StyledStr>,
+ ) -> Self {
+ let mut err = Self::new(ErrorKind::WrongNumberOfValues).with_cmd(cmd);
+
+ #[cfg(feature = "error-context")]
+ {
+ err = err.extend_context_unchecked([
+ (ContextKind::InvalidArg, ContextValue::String(arg)),
+ (
+ ContextKind::ExpectedNumValues,
+ ContextValue::Number(num_vals as isize),
+ ),
+ (
+ ContextKind::ActualNumValues,
+ ContextValue::Number(curr_vals as isize),
+ ),
+ ]);
+ if let Some(usage) = usage {
+ err = err
+ .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage));
+ }
+ }
+
+ err
+ }
+
+ pub(crate) fn unknown_argument(
+ cmd: &Command,
+ arg: String,
+ did_you_mean: Option<(String, Option<String>)>,
+ suggested_trailing_arg: bool,
+ usage: Option<StyledStr>,
+ ) -> Self {
+ let mut err = Self::new(ErrorKind::UnknownArgument).with_cmd(cmd);
+
+ #[cfg(feature = "error-context")]
+ {
+ let mut suggestions = vec![];
+ if suggested_trailing_arg {
+ let mut styled_suggestion = StyledStr::new();
+ styled_suggestion.none("to pass '");
+ styled_suggestion.warning(&arg);
+ styled_suggestion.none("' as a value, use '");
+ styled_suggestion.good("-- ");
+ styled_suggestion.good(&arg);
+ styled_suggestion.none("'");
+ suggestions.push(styled_suggestion);
+ }
+
+ err = err
+ .extend_context_unchecked([(ContextKind::InvalidArg, ContextValue::String(arg))]);
+ if let Some(usage) = usage {
+ err = err
+ .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage));
+ }
+ match did_you_mean {
+ Some((flag, Some(sub))) => {
+ let mut styled_suggestion = StyledStr::new();
+ styled_suggestion.none("'");
+ styled_suggestion.good(sub);
+ styled_suggestion.none(" ");
+ styled_suggestion.good("--");
+ styled_suggestion.good(flag);
+ styled_suggestion.none("' exists");
+ suggestions.push(styled_suggestion);
+ }
+ Some((flag, None)) => {
+ err = err.insert_context_unchecked(
+ ContextKind::SuggestedArg,
+ ContextValue::String(format!("--{flag}")),
+ );
+ }
+ None => {}
+ }
+ if !suggestions.is_empty() {
+ err = err.insert_context_unchecked(
+ ContextKind::Suggested,
+ ContextValue::StyledStrs(suggestions),
+ );
+ }
+ }
+
+ err
+ }
+
+ pub(crate) fn unnecessary_double_dash(
+ cmd: &Command,
+ arg: String,
+ usage: Option<StyledStr>,
+ ) -> Self {
+ let mut err = Self::new(ErrorKind::UnknownArgument).with_cmd(cmd);
+
+ #[cfg(feature = "error-context")]
+ {
+ let mut styled_suggestion = StyledStr::new();
+ styled_suggestion.none("subcommand '");
+ styled_suggestion.good(&arg);
+ styled_suggestion.none("' exists; to use it, remove the '");
+ styled_suggestion.warning("--");
+ styled_suggestion.none("' before it");
+
+ err = err.extend_context_unchecked([
+ (ContextKind::InvalidArg, ContextValue::String(arg)),
+ (
+ ContextKind::Suggested,
+ ContextValue::StyledStrs(vec![styled_suggestion]),
+ ),
+ ]);
+ if let Some(usage) = usage {
+ err = err
+ .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage));
+ }
+ }
+
+ err
+ }
+
+ fn formatted(&self) -> Cow<'_, StyledStr> {
+ if let Some(message) = self.inner.message.as_ref() {
+ message.formatted()
+ } else {
+ let styled = F::format_error(self);
+ Cow::Owned(styled)
+ }
+ }
+}
+
+impl<F: ErrorFormatter> From<io::Error> for Error<F> {
+ fn from(e: io::Error) -> Self {
+ Error::raw(ErrorKind::Io, e)
+ }
+}
+
+impl<F: ErrorFormatter> From<fmt::Error> for Error<F> {
+ fn from(e: fmt::Error) -> Self {
+ Error::raw(ErrorKind::Format, e)
+ }
+}
+
+impl<F: ErrorFormatter> std::fmt::Debug for Error<F> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
+ self.inner.fmt(f)
+ }
+}
+
+impl<F: ErrorFormatter> error::Error for Error<F> {
+ #[allow(trivial_casts)]
+ fn source(&self) -> Option<&(dyn error::Error + 'static)> {
+ self.inner.source.as_ref().map(|e| e.as_ref() as _)
+ }
+}
+
+impl<F: ErrorFormatter> Display for Error<F> {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ // Assuming `self.message` already has a trailing newline, from `try_help` or similar
+ ok!(write!(f, "{}", self.formatted()));
+ if let Some(backtrace) = self.inner.backtrace.as_ref() {
+ ok!(writeln!(f));
+ ok!(writeln!(f, "Backtrace:"));
+ ok!(writeln!(f, "{backtrace}"));
+ }
+ Ok(())
+ }
+}
+
+#[derive(Clone, Debug)]
+pub(crate) enum Message {
+ Raw(String),
+ Formatted(StyledStr),
+}
+
+impl Message {
+ fn format(&mut self, cmd: &Command, usage: Option<StyledStr>) {
+ match self {
+ Message::Raw(s) => {
+ let mut message = String::new();
+ std::mem::swap(s, &mut message);
+
+ let styled = format::format_error_message(&message, Some(cmd), usage);
+
+ *self = Self::Formatted(styled);
+ }
+ Message::Formatted(_) => {}
+ }
+ }
+
+ fn formatted(&self) -> Cow<StyledStr> {
+ match self {
+ Message::Raw(s) => {
+ let styled = format::format_error_message(s, None, None);
+
+ Cow::Owned(styled)
+ }
+ Message::Formatted(s) => Cow::Borrowed(s),
+ }
+ }
+}
+
+impl From<String> for Message {
+ fn from(inner: String) -> Self {
+ Self::Raw(inner)
+ }
+}
+
+impl From<StyledStr> for Message {
+ fn from(inner: StyledStr) -> 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(())
+ }
+}
+
+#[test]
+fn check_auto_traits() {
+ static_assertions::assert_impl_all!(Error: Send, Sync, Unpin);
+}
diff --git a/src/errors.rs b/src/errors.rs
deleted file mode 100644
index 1f86720..0000000
--- a/src/errors.rs
+++ /dev/null
@@ -1,918 +0,0 @@
-// Std
-use std::convert::From;
-use std::error::Error as StdError;
-use std::fmt as std_fmt;
-use std::fmt::Display;
-use std::io::{self, Write};
-use std::process;
-use std::result::Result as StdResult;
-
-// Internal
-use args::AnyArg;
-use fmt::{ColorWhen, Colorizer, ColorizerOption};
-use suggestions;
-
-/// Short hand for [`Result`] type
-///
-/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
-pub type Result<T> = StdResult<T, Error>;
-
-/// Command line argument parser kind of error
-#[derive(Debug, Copy, Clone, PartialEq)]
-pub enum ErrorKind {
- /// Occurs when an [`Arg`] has a set of possible values,
- /// and the user provides a value which isn't in that set.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let result = App::new("prog")
- /// .arg(Arg::with_name("speed")
- /// .possible_value("fast")
- /// .possible_value("slow"))
- /// .get_matches_from_safe(vec!["prog", "other"]);
- /// assert!(result.is_err());
- /// assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidValue);
- /// ```
- /// [`Arg`]: ./struct.Arg.html
- InvalidValue,
-
- /// Occurs when a user provides a flag, option, argument or subcommand which isn't defined.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let result = App::new("prog")
- /// .arg(Arg::from_usage("--flag 'some flag'"))
- /// .get_matches_from_safe(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::{App, Arg, ErrorKind, SubCommand};
- /// let result = App::new("prog")
- /// .subcommand(SubCommand::with_name("config")
- /// .about("Used for configuration")
- /// .arg(Arg::with_name("config_file")
- /// .help("The configuration file to use")
- /// .index(1)))
- /// .get_matches_from_safe(vec!["prog", "confi"]);
- /// assert!(result.is_err());
- /// assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidSubcommand);
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.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::{App, Arg, ErrorKind, SubCommand};
- /// let result = App::new("prog")
- /// .subcommand(SubCommand::with_name("config")
- /// .about("Used for configuration")
- /// .arg(Arg::with_name("config_file")
- /// .help("The configuration file to use")
- /// .index(1)))
- /// .get_matches_from_safe(vec!["prog", "help", "nothing"]);
- /// assert!(result.is_err());
- /// assert_eq!(result.unwrap_err().kind, ErrorKind::UnrecognizedSubcommand);
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`InvalidSubcommand`]: ./enum.ErrorKind.html#variant.InvalidSubcommand
- /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument
- UnrecognizedSubcommand,
-
- /// Occurs when the user provides an empty value for an option that does not allow empty
- /// values.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let res = App::new("prog")
- /// .arg(Arg::with_name("color")
- /// .long("color")
- /// .empty_values(false))
- /// .get_matches_from_safe(vec!["prog", "--color="]);
- /// assert!(res.is_err());
- /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue);
- /// ```
- EmptyValue,
-
- /// Occurs when the user provides a value for an argument with a custom validation and the
- /// value fails that validation.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// fn is_numeric(val: String) -> Result<(), String> {
- /// match val.parse::<i64>() {
- /// Ok(..) => Ok(()),
- /// Err(..) => Err(String::from("Value wasn't a number!")),
- /// }
- /// }
- ///
- /// let result = App::new("prog")
- /// .arg(Arg::with_name("num")
- /// .validator(is_numeric))
- /// .get_matches_from_safe(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::{App, Arg, ErrorKind};
- /// let result = App::new("prog")
- /// .arg(Arg::with_name("arg")
- /// .multiple(true)
- /// .max_values(2))
- /// .get_matches_from_safe(vec!["prog", "too", "many", "values"]);
- /// assert!(result.is_err());
- /// assert_eq!(result.unwrap_err().kind, ErrorKind::TooManyValues);
- /// ```
- /// [`Arg::max_values`]: ./struct.Arg.html#method.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::{App, Arg, ErrorKind};
- /// let result = App::new("prog")
- /// .arg(Arg::with_name("some_opt")
- /// .long("opt")
- /// .min_values(3))
- /// .get_matches_from_safe(vec!["prog", "--opt", "too", "few"]);
- /// assert!(result.is_err());
- /// assert_eq!(result.unwrap_err().kind, ErrorKind::TooFewValues);
- /// ```
- /// [`Arg::min_values`]: ./struct.Arg.html#method.min_values
- TooFewValues,
-
- /// 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::{App, Arg, ErrorKind};
- /// let result = App::new("prog")
- /// .arg(Arg::with_name("some_opt")
- /// .long("opt")
- /// .takes_value(true)
- /// .number_of_values(2))
- /// .get_matches_from_safe(vec!["prog", "--opt", "wrong"]);
- /// assert!(result.is_err());
- /// assert_eq!(result.unwrap_err().kind, ErrorKind::WrongNumberOfValues);
- /// ```
- ///
- /// [`Arg::number_of_values`]: ./struct.Arg.html#method.number_of_values
- /// [`Arg::value_names`]: ./struct.Arg.html#method.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::{App, Arg, ErrorKind};
- /// let result = App::new("prog")
- /// .arg(Arg::with_name("debug")
- /// .long("debug")
- /// .conflicts_with("color"))
- /// .arg(Arg::with_name("color")
- /// .long("color"))
- /// .get_matches_from_safe(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::{App, Arg, ErrorKind};
- /// let result = App::new("prog")
- /// .arg(Arg::with_name("debug")
- /// .required(true))
- /// .get_matches_from_safe(vec!["prog"]);
- /// assert!(result.is_err());
- /// assert_eq!(result.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
- /// ```
- MissingRequiredArgument,
-
- /// Occurs when a subcommand is required (as defined by [`AppSettings::SubcommandRequired`]),
- /// but the user does not provide one.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, AppSettings, SubCommand, ErrorKind};
- /// let err = App::new("prog")
- /// .setting(AppSettings::SubcommandRequired)
- /// .subcommand(SubCommand::with_name("test"))
- /// .get_matches_from_safe(vec![
- /// "myprog",
- /// ]);
- /// assert!(err.is_err());
- /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand);
- /// # ;
- /// ```
- /// [`AppSettings::SubcommandRequired`]: ./enum.AppSettings.html#variant.SubcommandRequired
- MissingSubcommand,
-
- /// Occurs when either an argument or [`SubCommand`] is required, as defined by
- /// [`AppSettings::ArgRequiredElseHelp`], but the user did not provide one.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, AppSettings, ErrorKind, SubCommand};
- /// let result = App::new("prog")
- /// .setting(AppSettings::ArgRequiredElseHelp)
- /// .subcommand(SubCommand::with_name("config")
- /// .about("Used for configuration")
- /// .arg(Arg::with_name("config_file")
- /// .help("The configuration file to use")))
- /// .get_matches_from_safe(vec!["prog"]);
- /// assert!(result.is_err());
- /// assert_eq!(result.unwrap_err().kind, ErrorKind::MissingArgumentOrSubcommand);
- /// ```
- /// [`SubCommand`]: ./struct.SubCommand.html
- /// [`AppSettings::ArgRequiredElseHelp`]: ./enum.AppSettings.html#variant.ArgRequiredElseHelp
- MissingArgumentOrSubcommand,
-
- /// Occurs when the user provides multiple values to an argument which doesn't allow that.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let result = App::new("prog")
- /// .arg(Arg::with_name("debug")
- /// .long("debug")
- /// .multiple(false))
- /// .get_matches_from_safe(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 for an argument and
- /// [`AppSettings::StrictUtf8`] is set.
- ///
- /// # Platform Specific
- ///
- /// Non-Windows platforms only (such as Linux, Unix, macOS, etc.)
- ///
- /// # Examples
- ///
- #[cfg_attr(not(unix), doc = " ```ignore")]
- #[cfg_attr(unix, doc = " ```")]
- /// # use clap::{App, Arg, ErrorKind, AppSettings};
- /// # use std::os::unix::ffi::OsStringExt;
- /// # use std::ffi::OsString;
- /// let result = App::new("prog")
- /// .setting(AppSettings::StrictUtf8)
- /// .arg(Arg::with_name("utf8")
- /// .short("u")
- /// .takes_value(true))
- /// .get_matches_from_safe(vec![OsString::from("myprog"),
- /// OsString::from("-u"),
- /// OsString::from_vec(vec![0xE9])]);
- /// assert!(result.is_err());
- /// assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidUtf8);
- /// ```
- /// [`AppSettings::StrictUtf8`]: ./enum.AppSettings.html#variant.StrictUtf8
- 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::{App, Arg, ErrorKind};
- /// let result = App::new("prog")
- /// .get_matches_from_safe(vec!["prog", "--help"]);
- /// assert!(result.is_err());
- /// assert_eq!(result.unwrap_err().kind, ErrorKind::HelpDisplayed);
- /// ```
- HelpDisplayed,
-
- /// Not a true "error" as it means `--version` or similar was used.
- /// The message will be sent to `stdout`.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # use clap::{App, Arg, ErrorKind};
- /// let result = App::new("prog")
- /// .get_matches_from_safe(vec!["prog", "--version"]);
- /// assert!(result.is_err());
- /// assert_eq!(result.unwrap_err().kind, ErrorKind::VersionDisplayed);
- /// ```
- VersionDisplayed,
-
- /// Occurs when using the [`value_t!`] and [`values_t!`] macros 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.
- /// [`value_t!`]: ./macro.value_t!.html
- /// [`values_t!`]: ./macro.values_t!.html
- ArgumentNotFound,
-
- /// Represents an [I/O error].
- /// Can occur when writing to `stderr` or `stdout` or reading a configuration file.
- /// [I/O error]: https://doc.rust-lang.org/std/io/struct.Error.html
- Io,
-
- /// Represents a [Format error] (which is a part of [`Display`]).
- /// Typically caused by writing to `stderr` or `stdout`.
- ///
- /// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
- /// [Format error]: https://doc.rust-lang.org/std/fmt/struct.Error.html
- Format,
-}
-
-/// Command Line Argument Parser Error
-#[derive(Debug)]
-pub struct Error {
- /// Formatted error message
- pub message: String,
- /// The type of error
- pub kind: ErrorKind,
- /// Any additional information passed along, such as the argument name that caused the error
- pub info: Option<Vec<String>>,
-}
-
-impl Error {
- /// Should the message be written to `stdout` or not
- pub fn use_stderr(&self) -> bool {
- match self.kind {
- ErrorKind::HelpDisplayed | ErrorKind::VersionDisplayed => false,
- _ => true,
- }
- }
-
- /// Prints the error to `stderr` and exits with a status of `1`
- pub fn exit(&self) -> ! {
- if self.use_stderr() {
- wlnerr!("{}", self.message);
- process::exit(1);
- }
- let out = io::stdout();
- writeln!(&mut out.lock(), "{}", self.message).expect("Error writing Error to stdout");
- process::exit(0);
- }
-
- #[doc(hidden)]
- pub fn write_to<W: Write>(&self, w: &mut W) -> io::Result<()> {
- write!(w, "{}", self.message)
- }
-
- #[doc(hidden)]
- pub fn argument_conflict<O, U>(
- arg: &AnyArg,
- other: Option<O>,
- usage: U,
- color: ColorWhen,
- ) -> Self
- where
- O: Into<String>,
- U: Display,
- {
- let mut v = vec![arg.name().to_owned()];
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!(
- "{} The argument '{}' cannot be used with {}\n\n\
- {}\n\n\
- For more information try {}",
- c.error("error:"),
- c.warning(&*arg.to_string()),
- match other {
- Some(name) => {
- let n = name.into();
- v.push(n.clone());
- c.warning(format!("'{}'", n))
- }
- None => c.none("one or more of the other specified arguments".to_owned()),
- },
- usage,
- c.good("--help")
- ),
- kind: ErrorKind::ArgumentConflict,
- info: Some(v),
- }
- }
-
- #[doc(hidden)]
- pub fn empty_value<U>(arg: &AnyArg, usage: U, color: ColorWhen) -> Self
- where
- U: Display,
- {
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!(
- "{} The argument '{}' requires a value but none was supplied\
- \n\n\
- {}\n\n\
- For more information try {}",
- c.error("error:"),
- c.warning(arg.to_string()),
- usage,
- c.good("--help")
- ),
- kind: ErrorKind::EmptyValue,
- info: Some(vec![arg.name().to_owned()]),
- }
- }
-
- #[doc(hidden)]
- pub fn invalid_value<B, G, U>(
- bad_val: B,
- good_vals: &[G],
- arg: &AnyArg,
- usage: U,
- color: ColorWhen,
- ) -> Self
- where
- B: AsRef<str>,
- G: AsRef<str> + Display,
- U: Display,
- {
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- let suffix = suggestions::did_you_mean_value_suffix(bad_val.as_ref(), good_vals.iter());
-
- let mut sorted = vec![];
- for v in good_vals {
- let val = format!("{}", c.good(v));
- sorted.push(val);
- }
- sorted.sort();
- let valid_values = sorted.join(", ");
- Error {
- message: format!(
- "{} '{}' isn't a valid value for '{}'\n\t\
- [possible values: {}]\n\
- {}\n\n\
- {}\n\n\
- For more information try {}",
- c.error("error:"),
- c.warning(bad_val.as_ref()),
- c.warning(arg.to_string()),
- valid_values,
- suffix.0,
- usage,
- c.good("--help")
- ),
- kind: ErrorKind::InvalidValue,
- info: Some(vec![arg.name().to_owned(), bad_val.as_ref().to_owned()]),
- }
- }
-
- #[doc(hidden)]
- pub fn invalid_subcommand<S, D, N, U>(
- subcmd: S,
- did_you_mean: D,
- name: N,
- usage: U,
- color: ColorWhen,
- ) -> Self
- where
- S: Into<String>,
- D: AsRef<str> + Display,
- N: Display,
- U: Display,
- {
- let s = subcmd.into();
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!(
- "{} The subcommand '{}' wasn't recognized\n\t\
- Did you mean '{}'?\n\n\
- If you believe you received this message in error, try \
- re-running with '{} {} {}'\n\n\
- {}\n\n\
- For more information try {}",
- c.error("error:"),
- c.warning(&*s),
- c.good(did_you_mean.as_ref()),
- name,
- c.good("--"),
- &*s,
- usage,
- c.good("--help")
- ),
- kind: ErrorKind::InvalidSubcommand,
- info: Some(vec![s]),
- }
- }
-
- #[doc(hidden)]
- pub fn unrecognized_subcommand<S, N>(subcmd: S, name: N, color: ColorWhen) -> Self
- where
- S: Into<String>,
- N: Display,
- {
- let s = subcmd.into();
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!(
- "{} The subcommand '{}' wasn't recognized\n\n\
- {}\n\t\
- {} help <subcommands>...\n\n\
- For more information try {}",
- c.error("error:"),
- c.warning(&*s),
- c.warning("USAGE:"),
- name,
- c.good("--help")
- ),
- kind: ErrorKind::UnrecognizedSubcommand,
- info: Some(vec![s]),
- }
- }
-
- #[doc(hidden)]
- pub fn missing_required_argument<R, U>(required: R, usage: U, color: ColorWhen) -> Self
- where
- R: Display,
- U: Display,
- {
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!(
- "{} The following required arguments were not provided:{}\n\n\
- {}\n\n\
- For more information try {}",
- c.error("error:"),
- required,
- usage,
- c.good("--help")
- ),
- kind: ErrorKind::MissingRequiredArgument,
- info: None,
- }
- }
-
- #[doc(hidden)]
- pub fn missing_subcommand<N, U>(name: N, usage: U, color: ColorWhen) -> Self
- where
- N: AsRef<str> + Display,
- U: Display,
- {
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!(
- "{} '{}' requires a subcommand, but one was not provided\n\n\
- {}\n\n\
- For more information try {}",
- c.error("error:"),
- c.warning(name),
- usage,
- c.good("--help")
- ),
- kind: ErrorKind::MissingSubcommand,
- info: None,
- }
- }
-
- #[doc(hidden)]
- pub fn invalid_utf8<U>(usage: U, color: ColorWhen) -> Self
- where
- U: Display,
- {
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!(
- "{} Invalid UTF-8 was detected in one or more arguments\n\n\
- {}\n\n\
- For more information try {}",
- c.error("error:"),
- usage,
- c.good("--help")
- ),
- kind: ErrorKind::InvalidUtf8,
- info: None,
- }
- }
-
- #[doc(hidden)]
- pub fn too_many_values<V, U>(val: V, arg: &AnyArg, usage: U, color: ColorWhen) -> Self
- where
- V: AsRef<str> + Display + ToOwned,
- U: Display,
- {
- let v = val.as_ref();
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!(
- "{} The value '{}' was provided to '{}', but it wasn't expecting \
- any more values\n\n\
- {}\n\n\
- For more information try {}",
- c.error("error:"),
- c.warning(v),
- c.warning(arg.to_string()),
- usage,
- c.good("--help")
- ),
- kind: ErrorKind::TooManyValues,
- info: Some(vec![arg.name().to_owned(), v.to_owned()]),
- }
- }
-
- #[doc(hidden)]
- pub fn too_few_values<U>(
- arg: &AnyArg,
- min_vals: u64,
- curr_vals: usize,
- usage: U,
- color: ColorWhen,
- ) -> Self
- where
- U: Display,
- {
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!(
- "{} The argument '{}' requires at least {} values, but only {} w{} \
- provided\n\n\
- {}\n\n\
- For more information try {}",
- c.error("error:"),
- c.warning(arg.to_string()),
- c.warning(min_vals.to_string()),
- c.warning(curr_vals.to_string()),
- if curr_vals > 1 { "ere" } else { "as" },
- usage,
- c.good("--help")
- ),
- kind: ErrorKind::TooFewValues,
- info: Some(vec![arg.name().to_owned()]),
- }
- }
-
- #[doc(hidden)]
- pub fn value_validation(arg: Option<&AnyArg>, err: String, color: ColorWhen) -> Self {
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!(
- "{} Invalid value{}: {}",
- c.error("error:"),
- if let Some(a) = arg {
- format!(" for '{}'", c.warning(a.to_string()))
- } else {
- "".to_string()
- },
- err
- ),
- kind: ErrorKind::ValueValidation,
- info: None,
- }
- }
-
- #[doc(hidden)]
- pub fn value_validation_auto(err: String) -> Self {
- let n: Option<&AnyArg> = None;
- Error::value_validation(n, err, ColorWhen::Auto)
- }
-
- #[doc(hidden)]
- pub fn wrong_number_of_values<S, U>(
- arg: &AnyArg,
- num_vals: u64,
- curr_vals: usize,
- suffix: S,
- usage: U,
- color: ColorWhen,
- ) -> Self
- where
- S: Display,
- U: Display,
- {
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!(
- "{} The argument '{}' requires {} values, but {} w{} \
- provided\n\n\
- {}\n\n\
- For more information try {}",
- c.error("error:"),
- c.warning(arg.to_string()),
- c.warning(num_vals.to_string()),
- c.warning(curr_vals.to_string()),
- suffix,
- usage,
- c.good("--help")
- ),
- kind: ErrorKind::WrongNumberOfValues,
- info: Some(vec![arg.name().to_owned()]),
- }
- }
-
- #[doc(hidden)]
- pub fn unexpected_multiple_usage<U>(arg: &AnyArg, usage: U, color: ColorWhen) -> Self
- where
- U: Display,
- {
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!(
- "{} The argument '{}' was provided more than once, but cannot \
- be used multiple times\n\n\
- {}\n\n\
- For more information try {}",
- c.error("error:"),
- c.warning(arg.to_string()),
- usage,
- c.good("--help")
- ),
- kind: ErrorKind::UnexpectedMultipleUsage,
- info: Some(vec![arg.name().to_owned()]),
- }
- }
-
- #[doc(hidden)]
- pub fn unknown_argument<A, U>(arg: A, did_you_mean: &str, usage: U, color: ColorWhen) -> Self
- where
- A: Into<String>,
- U: Display,
- {
- let a = arg.into();
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!(
- "{} Found argument '{}' which wasn't expected, or isn't valid in \
- this context{}\n\
- {}\n\n\
- For more information try {}",
- c.error("error:"),
- c.warning(&*a),
- if did_you_mean.is_empty() {
- "\n".to_owned()
- } else {
- format!("{}\n", did_you_mean)
- },
- usage,
- c.good("--help")
- ),
- kind: ErrorKind::UnknownArgument,
- info: Some(vec![a]),
- }
- }
-
- #[doc(hidden)]
- pub fn io_error(e: &Error, color: ColorWhen) -> Self {
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: color,
- });
- Error {
- message: format!("{} {}", c.error("error:"), e.description()),
- kind: ErrorKind::Io,
- info: None,
- }
- }
-
- #[doc(hidden)]
- pub fn argument_not_found_auto<A>(arg: A) -> Self
- where
- A: Into<String>,
- {
- let a = arg.into();
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: ColorWhen::Auto,
- });
- Error {
- message: format!(
- "{} The argument '{}' wasn't found",
- c.error("error:"),
- a.clone()
- ),
- kind: ErrorKind::ArgumentNotFound,
- info: Some(vec![a]),
- }
- }
-
- /// Create an error with a custom description.
- ///
- /// This can be used in combination with `Error::exit` to exit your program
- /// with a custom error message.
- pub fn with_description(description: &str, kind: ErrorKind) -> Self {
- let c = Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: ColorWhen::Auto,
- });
- Error {
- message: format!("{} {}", c.error("error:"), description),
- kind: kind,
- info: None,
- }
- }
-}
-
-impl StdError for Error {
- fn description(&self) -> &str {
- &*self.message
- }
-}
-
-impl Display for Error {
- fn fmt(&self, f: &mut std_fmt::Formatter) -> std_fmt::Result {
- writeln!(f, "{}", self.message)
- }
-}
-
-impl From<io::Error> for Error {
- fn from(e: io::Error) -> Self {
- Error::with_description(e.description(), ErrorKind::Io)
- }
-}
-
-impl From<std_fmt::Error> for Error {
- fn from(e: std_fmt::Error) -> Self {
- Error::with_description(e.description(), ErrorKind::Format)
- }
-}
diff --git a/src/fmt.rs b/src/fmt.rs
deleted file mode 100644
index fa8b633..0000000
--- a/src/fmt.rs
+++ /dev/null
@@ -1,194 +0,0 @@
-#[cfg(all(feature = "color", not(target_os = "windows")))]
-use ansi_term::ANSIString;
-
-#[cfg(all(feature = "color", not(target_os = "windows")))]
-use ansi_term::Colour::{Green, Red, Yellow};
-
-#[cfg(feature = "color")]
-use atty;
-use std::env;
-use std::fmt;
-
-#[doc(hidden)]
-#[derive(Debug, Copy, Clone, PartialEq)]
-pub enum ColorWhen {
- Auto,
- Always,
- Never,
-}
-
-#[cfg(feature = "color")]
-pub fn is_a_tty(stderr: bool) -> bool {
- debugln!("is_a_tty: stderr={:?}", stderr);
- let stream = if stderr {
- atty::Stream::Stderr
- } else {
- atty::Stream::Stdout
- };
- atty::is(stream)
-}
-
-#[cfg(not(feature = "color"))]
-pub fn is_a_tty(_: bool) -> bool {
- debugln!("is_a_tty;");
- false
-}
-
-pub fn is_term_dumb() -> bool {
- env::var("TERM").ok() == Some(String::from("dumb"))
-}
-
-#[doc(hidden)]
-pub struct ColorizerOption {
- pub use_stderr: bool,
- pub when: ColorWhen,
-}
-
-#[doc(hidden)]
-pub struct Colorizer {
- when: ColorWhen,
-}
-
-macro_rules! color {
- ($_self:ident, $c:ident, $m:expr) => {
- match $_self.when {
- ColorWhen::Auto => Format::$c($m),
- ColorWhen::Always => Format::$c($m),
- ColorWhen::Never => Format::None($m),
- }
- };
-}
-
-impl Colorizer {
- pub fn new(option: ColorizerOption) -> Colorizer {
- let is_a_tty = is_a_tty(option.use_stderr);
- let is_term_dumb = is_term_dumb();
- Colorizer {
- when: match option.when {
- ColorWhen::Auto if is_a_tty && !is_term_dumb => ColorWhen::Auto,
- ColorWhen::Auto => ColorWhen::Never,
- when => when,
- },
- }
- }
-
- pub fn good<T>(&self, msg: T) -> Format<T>
- where
- T: fmt::Display + AsRef<str>,
- {
- debugln!("Colorizer::good;");
- color!(self, Good, msg)
- }
-
- pub fn warning<T>(&self, msg: T) -> Format<T>
- where
- T: fmt::Display + AsRef<str>,
- {
- debugln!("Colorizer::warning;");
- color!(self, Warning, msg)
- }
-
- pub fn error<T>(&self, msg: T) -> Format<T>
- where
- T: fmt::Display + AsRef<str>,
- {
- debugln!("Colorizer::error;");
- color!(self, Error, msg)
- }
-
- pub fn none<T>(&self, msg: T) -> Format<T>
- where
- T: fmt::Display + AsRef<str>,
- {
- debugln!("Colorizer::none;");
- Format::None(msg)
- }
-}
-
-impl Default for Colorizer {
- fn default() -> Self {
- Colorizer::new(ColorizerOption {
- use_stderr: true,
- when: ColorWhen::Auto,
- })
- }
-}
-
-/// Defines styles for different types of error messages. Defaults to Error=Red, Warning=Yellow,
-/// and Good=Green
-#[derive(Debug)]
-#[doc(hidden)]
-pub enum Format<T> {
- /// Defines the style used for errors, defaults to Red
- Error(T),
- /// Defines the style used for warnings, defaults to Yellow
- Warning(T),
- /// Defines the style used for good values, defaults to Green
- Good(T),
- /// Defines no formatting style
- None(T),
-}
-
-#[cfg(all(feature = "color", not(target_os = "windows")))]
-impl<T: AsRef<str>> Format<T> {
- fn format(&self) -> ANSIString {
- match *self {
- Format::Error(ref e) => Red.bold().paint(e.as_ref()),
- Format::Warning(ref e) => Yellow.paint(e.as_ref()),
- Format::Good(ref e) => Green.paint(e.as_ref()),
- Format::None(ref e) => ANSIString::from(e.as_ref()),
- }
- }
-}
-
-#[cfg(any(not(feature = "color"), target_os = "windows"))]
-#[cfg_attr(feature = "lints", allow(match_same_arms))]
-impl<T: fmt::Display> Format<T> {
- fn format(&self) -> &T {
- match *self {
- Format::Error(ref e) => e,
- Format::Warning(ref e) => e,
- Format::Good(ref e) => e,
- Format::None(ref e) => e,
- }
- }
-}
-
-#[cfg(all(feature = "color", not(target_os = "windows")))]
-impl<T: AsRef<str>> fmt::Display for Format<T> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "{}", &self.format())
- }
-}
-
-#[cfg(any(not(feature = "color"), target_os = "windows"))]
-impl<T: fmt::Display> fmt::Display for Format<T> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "{}", &self.format())
- }
-}
-
-#[cfg(all(test, feature = "color", not(target_os = "windows")))]
-mod test {
- use super::Format;
- use ansi_term::ANSIString;
- use ansi_term::Colour::{Green, Red, Yellow};
-
- #[test]
- fn colored_output() {
- let err = Format::Error("error");
- assert_eq!(
- &*format!("{}", err),
- &*format!("{}", Red.bold().paint("error"))
- );
- let good = Format::Good("good");
- assert_eq!(&*format!("{}", good), &*format!("{}", Green.paint("good")));
- let warn = Format::Warning("warn");
- assert_eq!(&*format!("{}", warn), &*format!("{}", Yellow.paint("warn")));
- let none = Format::None("none");
- assert_eq!(
- &*format!("{}", none),
- &*format!("{}", ANSIString::from("none"))
- );
- }
-}
diff --git a/src/lib.rs b/src/lib.rs
index 7dbb0f0..ab2d9d4 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,638 +1,154 @@
-// Copyright ⓒ 2015-2016 Kevin B. Knapp and [`clap-rs` contributors](https://github.com/clap-rs/clap/blob/v2.33.1/CONTRIBUTORS.md).
+// 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.
-//! `clap` is a simple-to-use, efficient, and full-featured library for parsing command line
-//! arguments and subcommands when writing console/terminal applications.
+//! > **Command Line Argument Parser for Rust**
//!
-//! ## About
+//! Quick Links:
+//! - Derive [tutorial][_derive::_tutorial] and [reference][_derive]
+//! - Builder [tutorial][_tutorial] and [reference](index.html)
+//! - [Cookbook][_cookbook]
+//! - [FAQ][_faq]
+//! - [Discussions](https://github.com/clap-rs/clap/discussions)
//!
-//! `clap` is used to parse *and validate* the string of command line arguments provided by the user
-//! at runtime. You provide the list of valid possibilities, and `clap` handles the rest. This means
-//! you focus on your *applications* functionality, and less on the parsing and validating of
-//! arguments.
+//! ## Aspirations
//!
-//! `clap` also provides the traditional version and help switches (or flags) 'for free' meaning
-//! automatically with no configuration. It does this by checking the list of valid possibilities you
-//! supplied and adding only the ones you haven't already defined. If you are using subcommands,
-//! `clap` will also auto-generate a `help` subcommand for you in addition to the traditional flags.
+//! - Out of the box, users get a polished CLI experience
+//! - Including common argument behavior, help generation, suggested fixes for users, colored output, [shell completions](https://github.com/clap-rs/clap/tree/master/clap_complete), etc
+//! - Flexible enough to port your existing CLI interface
+//! - However, we won't necessarily streamline support for each use case
+//! - Reasonable parse performance
+//! - Resilient maintainership, including
+//! - Willing to break compatibility rather than batching up breaking changes in large releases
+//! - Leverage feature flags to keep to one active branch
+//! - Being under [WG-CLI](https://github.com/rust-cli/team/) to increase the bus factor
+//! - We follow semver and will wait about 6-9 months between major breaking changes
+//! - We will support the last two minor Rust releases (MSRV, currently 1.64.0)
//!
-//! Once `clap` parses the user provided string of arguments, it returns the matches along with any
-//! applicable values. If the user made an error or typo, `clap` informs them of the mistake and
-//! exits gracefully (or returns a `Result` type and allows you to perform any clean up prior to
-//! exit). Because of this, you can make reasonable assumptions in your code about the validity of
-//! the arguments.
+//! While these aspirations can be at odds with fast build times and low binary
+//! size, we will still strive to keep these reasonable for the flexibility you
+//! get. Check out the
+//! [argparse-benchmarks](https://github.com/rust-cli/argparse-benchmarks-rs) for
+//! CLI parsers optimized for other use cases.
//!
+//! ## Example
//!
-//! ## Quick Example
-//!
-//! The following examples show a quick example of some of the very basic functionality of `clap`.
-//! For more advanced usage, such as requirements, conflicts, groups, multiple values and
-//! occurrences see the [documentation](https://docs.rs/clap/), [examples/] directory of
-//! this repository or the [video tutorials].
-//!
-//! **NOTE:** All of these examples are functionally the same, but show different styles in which to
-//! use `clap`
-//!
-//! The first example shows a method that allows more advanced configuration options (not shown in
-//! this small example), or even dynamically generating arguments when desired. The downside is it's
-//! more verbose.
-//!
-//! ```no_run
-//! // (Full example with detailed comments in examples/01b_quick_example.rs)
-//! //
-//! // This example demonstrates clap's full 'builder pattern' style of creating arguments which is
-//! // more verbose, but allows easier editing, and at times more advanced options, or the possibility
-//! // to generate arguments dynamically.
-//! extern crate clap;
-//! use clap::{Arg, App, SubCommand};
-//!
-//! fn main() {
-//! let matches = App::new("My Super Program")
-//! .version("1.0")
-//! .author("Kevin K. <kbknapp@gmail.com>")
-//! .about("Does awesome things")
-//! .arg(Arg::with_name("config")
-//! .short("c")
-//! .long("config")
-//! .value_name("FILE")
-//! .help("Sets a custom config file")
-//! .takes_value(true))
-//! .arg(Arg::with_name("INPUT")
-//! .help("Sets the input file to use")
-//! .required(true)
-//! .index(1))
-//! .arg(Arg::with_name("v")
-//! .short("v")
-//! .multiple(true)
-//! .help("Sets the level of verbosity"))
-//! .subcommand(SubCommand::with_name("test")
-//! .about("controls testing features")
-//! .version("1.3")
-//! .author("Someone E. <someone_else@other.com>")
-//! .arg(Arg::with_name("debug")
-//! .short("d")
-//! .help("print debug information verbosely")))
-//! .get_matches();
-//!
-//! // Gets a value for config if supplied by user, or defaults to "default.conf"
-//! let config = matches.value_of("config").unwrap_or("default.conf");
-//! println!("Value for config: {}", config);
-//!
-//! // Calling .unwrap() is safe here because "INPUT" is required (if "INPUT" wasn't
-//! // required we could have used an 'if let' to conditionally get the value)
-//! println!("Using input file: {}", matches.value_of("INPUT").unwrap());
-//!
-//! // Vary the output based on how many times the user used the "verbose" flag
-//! // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v'
-//! match matches.occurrences_of("v") {
-//! 0 => println!("No verbose info"),
-//! 1 => println!("Some verbose info"),
-//! 2 => println!("Tons of verbose info"),
-//! 3 | _ => println!("Don't be crazy"),
-//! }
-//!
-//! // You can handle information about subcommands by requesting their matches by name
-//! // (as below), requesting just the name used, or both at the same time
-//! if let Some(matches) = matches.subcommand_matches("test") {
-//! if matches.is_present("debug") {
-//! println!("Printing debug info...");
-//! } else {
-//! println!("Printing normally...");
-//! }
-//! }
-//!
-//! // more program logic goes here...
-//! }
-//! ```
-//!
-//! The next example shows a far less verbose method, but sacrifices some of the advanced
-//! configuration options (not shown in this small example). This method also takes a *very* minor
-//! runtime penalty.
-//!
-//! ```no_run
-//! // (Full example with detailed comments in examples/01a_quick_example.rs)
-//! //
-//! // This example demonstrates clap's "usage strings" method of creating arguments
-//! // which is less verbose
-//! extern crate clap;
-//! use clap::{Arg, App, SubCommand};
-//!
-//! fn main() {
-//! let matches = App::new("myapp")
-//! .version("1.0")
-//! .author("Kevin K. <kbknapp@gmail.com>")
-//! .about("Does awesome things")
-//! .args_from_usage(
-//! "-c, --config=[FILE] 'Sets a custom config file'
-//! <INPUT> 'Sets the input file to use'
-//! -v... 'Sets the level of verbosity'")
-//! .subcommand(SubCommand::with_name("test")
-//! .about("controls testing features")
-//! .version("1.3")
-//! .author("Someone E. <someone_else@other.com>")
-//! .arg_from_usage("-d, --debug 'Print debug information'"))
-//! .get_matches();
-//!
-//! // Same as previous example...
-//! }
-//! ```
-//!
-//! This third method shows how you can use a YAML file to build your CLI and keep your Rust source
-//! tidy or support multiple localized translations by having different YAML files for each
-//! localization.
-//!
-//! First, create the `cli.yml` file to hold your CLI options, but it could be called anything we
-//! like:
-//!
-//! ```yaml
-//! name: myapp
-//! version: "1.0"
-//! author: Kevin K. <kbknapp@gmail.com>
-//! about: Does awesome things
-//! args:
-//! - config:
-//! short: c
-//! long: config
-//! value_name: FILE
-//! help: Sets a custom config file
-//! takes_value: true
-//! - INPUT:
-//! help: Sets the input file to use
-//! required: true
-//! index: 1
-//! - verbose:
-//! short: v
-//! multiple: true
-//! help: Sets the level of verbosity
-//! subcommands:
-//! - test:
-//! about: controls testing features
-//! version: "1.3"
-//! author: Someone E. <someone_else@other.com>
-//! args:
-//! - debug:
-//! short: d
-//! help: print debug information
+//! Run
+//! ```console
+//! $ cargo add clap --features derive
//! ```
+//! *(See also [feature flag reference][_features])*
//!
-//! Since this feature requires additional dependencies that not everyone may want, it is *not*
-//! compiled in by default and we need to enable a feature flag in Cargo.toml:
-//!
-//! Simply change your `clap = "~2.27.0"` to `clap = {version = "~2.27.0", features = ["yaml"]}`.
-//!
-//! At last we create our `main.rs` file just like we would have with the previous two examples:
-//!
-//! ```ignore
-//! // (Full example with detailed comments in examples/17_yaml.rs)
-//! //
-//! // This example demonstrates clap's building from YAML style of creating arguments which is far
-//! // more clean, but takes a very small performance hit compared to the other two methods.
-//! #[macro_use]
-//! extern crate clap;
-//! use clap::App;
-//!
-//! fn main() {
-//! // The YAML file is found relative to the current file, similar to how modules are found
-//! let yaml = load_yaml!("cli.yml");
-//! let matches = App::from_yaml(yaml).get_matches();
-//!
-//! // Same as previous examples...
-//! }
+//! Then define your CLI in `main.rs`:
+#![cfg_attr(not(feature = "derive"), doc = " ```ignore")]
+#![cfg_attr(feature = "derive", doc = " ```no_run")]
+#![doc = include_str!("../examples/demo.rs")]
//! ```
//!
-//! Finally there is a macro version, which is like a hybrid approach offering the speed of the
-//! builder pattern (the first example), but without all the verbosity.
+//! And try it out:
+#![doc = include_str!("../examples/demo.md")]
//!
-//! ```no_run
-//! #[macro_use]
-//! extern crate clap;
+//! See also the derive [tutorial][_derive::_tutorial] and [reference][_derive]
//!
-//! fn main() {
-//! let matches = clap_app!(myapp =>
-//! (version: "1.0")
-//! (author: "Kevin K. <kbknapp@gmail.com>")
-//! (about: "Does awesome things")
-//! (@arg CONFIG: -c --config +takes_value "Sets a custom config file")
-//! (@arg INPUT: +required "Sets the input file to use")
-//! (@arg debug: -d ... "Sets the level of debugging information")
-//! (@subcommand test =>
-//! (about: "controls testing features")
-//! (version: "1.3")
-//! (author: "Someone E. <someone_else@other.com>")
-//! (@arg verbose: -v --verbose "Print test information verbosely")
-//! )
-//! ).get_matches();
-//!
-//! // Same as before...
-//! }
-//! ```
-//!
-//! If you were to compile any of the above programs and run them with the flag `--help` or `-h` (or
-//! `help` subcommand, since we defined `test` as a subcommand) the following would be output
-//!
-//! ```text
-//! $ myprog --help
-//! My Super Program 1.0
-//! Kevin K. <kbknapp@gmail.com>
-//! Does awesome things
-//!
-//! USAGE:
-//! MyApp [FLAGS] [OPTIONS] <INPUT> [SUBCOMMAND]
-//!
-//! FLAGS:
-//! -h, --help Prints this message
-//! -v Sets the level of verbosity
-//! -V, --version Prints version information
-//!
-//! OPTIONS:
-//! -c, --config <FILE> Sets a custom config file
-//!
-//! ARGS:
-//! INPUT The input file to use
-//!
-//! SUBCOMMANDS:
-//! help Prints this message
-//! test Controls testing features
-//! ```
+//! ### Related Projects
//!
-//! **NOTE:** You could also run `myapp test --help` to see similar output and options for the
-//! `test` subcommand.
+//! Augment clap:
+//! - [wild](https://crates.io/crates/wild) for supporting wildcards (`*`) on Windows like you do Linux
+//! - [argfile](https://crates.io/crates/argfile) for loading additional arguments from a file (aka response files)
+//! - [shadow-rs](https://crates.io/crates/shadow-rs) for generating `Command::long_version`
+//! - [clap_mangen](https://crates.io/crates/clap_mangen) for generating man page source (roff)
+//! - [clap_complete](https://crates.io/crates/clap_complete) for shell completion support
//!
-//! ## Try it!
-//!
-//! ### Pre-Built Test
-//!
-//! To try out the pre-built example, use the following steps:
-//!
-//! * Clone the repository `$ git clone https://github.com/clap-rs/clap && cd clap-rs/tests`
-//! * Compile the example `$ cargo build --release`
-//! * Run the help info `$ ./target/release/claptests --help`
-//! * Play with the arguments!
-//!
-//! ### BYOB (Build Your Own Binary)
-//!
-//! To test out `clap`'s default auto-generated help/version follow these steps:
-//!
-//! * Create a new cargo project `$ cargo new fake --bin && cd fake`
-//! * Add `clap` to your `Cargo.toml`
-//!
-//! ```toml
-//! [dependencies]
-//! clap = "2"
-//! ```
-//!
-//! * Add the following to your `src/main.rs`
-//!
-//! ```no_run
-//! extern crate clap;
-//! use clap::App;
-//!
-//! fn main() {
-//! App::new("fake").version("v1.0-beta").get_matches();
-//! }
-//! ```
-//!
-//! * Build your program `$ cargo build --release`
-//! * Run with help or version `$ ./target/release/fake --help` or `$ ./target/release/fake
-//! --version`
-//!
-//! ## Usage
-//!
-//! For full usage, add `clap` as a dependency in your `Cargo.toml` (it is **highly** recommended to
-//! use the `~major.minor.patch` style versions in your `Cargo.toml`, for more information see
-//! [Compatibility Policy](#compatibility-policy)) to use from crates.io:
-//!
-//! ```toml
-//! [dependencies]
-//! clap = "~2.27.0"
-//! ```
-//!
-//! Or get the latest changes from the master branch at github:
-//!
-//! ```toml
-//! [dependencies.clap]
-//! git = "https://github.com/clap-rs/clap.git"
-//! ```
-//!
-//! Add `extern crate clap;` to your crate root.
-//!
-//! Define a list of valid arguments for your program (see the
-//! [documentation](https://docs.rs/clap/) or [examples/] directory of this repo)
-//!
-//! Then run `cargo build` or `cargo update && cargo build` for your project.
-//!
-//! ### Optional Dependencies / Features
-//!
-//! #### Features enabled by default
-//!
-//! * `suggestions`: Turns on the `Did you mean '--myoption'?` feature for when users make typos. (builds dependency `strsim`)
-//! * `color`: Turns on colored error messages. This feature only works on non-Windows OSs. (builds dependency `ansi-term` and `atty`)
-//! * `wrap_help`: Wraps the help at the actual terminal width when
-//! available, instead of 120 characters. (builds dependency `textwrap`
-//! with feature `term_size`)
-//!
-//! To disable these, add this to your `Cargo.toml`:
-//!
-//! ```toml
-//! [dependencies.clap]
-//! version = "~2.27.0"
-//! default-features = false
-//! ```
-//!
-//! You can also selectively enable only the features you'd like to include, by adding:
-//!
-//! ```toml
-//! [dependencies.clap]
-//! version = "~2.27.0"
-//! default-features = false
-//!
-//! # Cherry-pick the features you'd like to use
-//! features = [ "suggestions", "color" ]
-//! ```
+//! CLI Helpers
+//! - [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag)
+//! - [clap-cargo](https://crates.io/crates/clap-cargo)
+//! - [concolor-clap](https://crates.io/crates/concolor-clap)
//!
-//! #### Opt-in features
+//! Testing
+//! - [`trycmd`](https://crates.io/crates/trycmd): Bulk snapshot testing
+//! - [`snapbox`](https://crates.io/crates/snapbox): Specialized snapshot testing
+//! - [`assert_cmd`](https://crates.io/crates/assert_cmd) and [`assert_fs`](https://crates.io/crates/assert_fs): Customized testing
//!
-//! * **"yaml"**: Enables building CLIs from YAML documents. (builds dependency `yaml-rust`)
-//! * **"unstable"**: Enables unstable `clap` features that may change from release to release
+//! Documentation:
+//! - [Command-line Apps for Rust](https://rust-cli.github.io/book/index.html) book
//!
-//! ### Dependencies Tree
-//!
-//! The following graphic depicts `clap`s dependency graph (generated using
-//! [cargo-graph](https://github.com/kbknapp/cargo-graph)).
-//!
-//! * **Dashed** Line: Optional dependency
-//! * **Red** Color: **NOT** included by default (must use cargo `features` to enable)
-//! * **Blue** Color: Dev dependency, only used while developing.
-//!
-//! ![clap dependencies](https://github.com/clap-rs/clap/blob/v2.33.1/clap_dep_graph.png)
-//!
-//! ### More Information
-//!
-//! You can find complete documentation on the [docs.rs](https://docs.rs/clap/) for this project.
-//!
-//! You can also find usage examples in the [examples/] directory of this repo.
-//!
-//! #### Video Tutorials
-//!
-//! There's also the video tutorial series [Argument Parsing with Rust v2][video tutorials].
-//!
-//! These videos slowly trickle out as I finish them and currently a work in progress.
-//!
-//! ## How to Contribute
-//!
-//! Contributions are always welcome! And there is a multitude of ways in which you can help
-//! depending on what you like to do, or are good at. Anything from documentation, code cleanup,
-//! issue completion, new features, you name it, even filing issues is contributing and greatly
-//! appreciated!
-//!
-//! Another really great way to help is if you find an interesting, or helpful way in which to use
-//! `clap`. You can either add it to the [examples/] directory, or file an issue and tell
-//! me. I'm all about giving credit where credit is due :)
-//!
-//! Please read [CONTRIBUTING.md](https://github.com/clap-rs/clap/blob/v2.33.1/.github/CONTRIBUTING.md) before you start contributing.
-//!
-//!
-//! ### Testing Code
-//!
-//! To test with all features both enabled and disabled, you can run theese commands:
-//!
-//! ```text
-//! $ cargo test --no-default-features
-//! $ cargo test --features "yaml unstable"
-//! ```
-//!
-//! Alternatively, if you have [`just`](https://github.com/casey/just) installed you can run the
-//! prebuilt recipes. *Not* using `just` is perfectly fine as well, it simply bundles commands
-//! automatically.
-//!
-//! For example, to test the code, as above simply run:
-//!
-//! ```text
-//! $ just run-tests
-//! ```
-//!
-//! From here on, I will list the appropriate `cargo` command as well as the `just` command.
-//!
-//! Sometimes it's helpful to only run a subset of the tests, which can be done via:
-//!
-//! ```text
-//! $ cargo test --test <test_name>
-//!
-//! # Or
-//!
-//! $ just run-test <test_name>
-//! ```
-//!
-//! ### Linting Code
-//!
-//! During the CI process `clap` runs against many different lints using
-//! [`clippy`](https://github.com/Manishearth/rust-clippy). In order to check if these lints pass on
-//! your own computer prior to submitting a PR you'll need a nightly compiler.
-//!
-//! In order to check the code for lints run either:
-//!
-//! ```text
-//! $ rustup override add nightly
-//! $ cargo build --features lints
-//! $ rustup override remove
-//!
-//! # Or
-//!
-//! $ just lint
-//! ```
-//!
-//! ### Debugging Code
-//!
-//! Another helpful technique is to see the `clap` debug output while developing features. In order
-//! to see the debug output while running the full test suite or individual tests, run:
-//!
-//! ```text
-//! $ cargo test --features debug
-//!
-//! # Or for individual tests
-//! $ cargo test --test <test_name> --features debug
-//!
-//! # The corresponding just command for individual debugging tests is:
-//! $ just debug <test_name>
-//! ```
-//!
-//! ### Goals
-//!
-//! There are a few goals of `clap` that I'd like to maintain throughout contributions. If your
-//! proposed changes break, or go against any of these goals we'll discuss the changes further
-//! before merging (but will *not* be ignored, all contributes are welcome!). These are by no means
-//! hard-and-fast rules, as I'm no expert and break them myself from time to time (even if by
-//! mistake or ignorance).
-//!
-//! * Remain backwards compatible when possible
-//! - If backwards compatibility *must* be broken, use deprecation warnings if at all possible before
-//! removing legacy code - This does not apply for security concerns
-//! * Parse arguments quickly
-//! - Parsing of arguments shouldn't slow down usage of the main program - This is also true of
-//! generating help and usage information (although *slightly* less stringent, as the program is about
-//! to exit)
-//! * Try to be cognizant of memory usage
-//! - Once parsing is complete, the memory footprint of `clap` should be low since the main program
-//! is the star of the show
-//! * `panic!` on *developer* error, exit gracefully on *end-user* error
-//!
-//! ### Compatibility Policy
-//!
-//! Because `clap` takes `SemVer` and compatibility seriously, this is the official policy regarding
-//! breaking changes and previous versions of Rust.
-//!
-//! `clap` will pin the minimum required version of Rust to the CI builds. Bumping the minimum
-//! version of Rust is considered a minor breaking change, meaning *at a minimum* the minor version
-//! of `clap` will be bumped.
-//!
-//! In order to keep from being surprised by breaking changes, it is **highly** recommended to use
-//! the `~major.minor.patch` style in your `Cargo.toml`:
-//!
-//! ```toml
-//! [dependencies] clap = "~2.27.0"
-//! ```
-//!
-//! This will cause *only* the patch version to be updated upon a `cargo update` call, and therefore
-//! cannot break due to new features, or bumped minimum versions of Rust.
-//!
-//! #### Minimum Version of Rust
-//!
-//! `clap` will officially support current stable Rust, minus two releases, but may work with prior
-//! releases as well. For example, current stable Rust at the time of this writing is 1.21.0,
-//! meaning `clap` is guaranteed to compile with 1.19.0 and beyond. At the 1.22.0 release, `clap`
-//! will be guaranteed to compile with 1.20.0 and beyond, etc.
-//!
-//! Upon bumping the minimum version of Rust (assuming it's within the stable-2 range), it *must* be
-//! clearly annotated in the `CHANGELOG.md`
-//!
-//! ## License
-//!
-//! `clap` is licensed under the MIT license. Please read the [LICENSE-MIT][license] file in
-//! this repository for more information.
-//!
-//! [examples/]: https://github.com/clap-rs/clap/tree/v2.33.1/examples
-//! [video tutorials]: https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U
-//! [license]: https://github.com/clap-rs/clap/blob/v2.33.1/LICENSE-MIT
-#![crate_type = "lib"]
-#![doc(html_root_url = "https://docs.rs/clap/2.33.3")]
-#![deny(
+#![cfg_attr(docsrs, feature(doc_auto_cfg))]
+#![doc(html_logo_url = "https://raw.githubusercontent.com/clap-rs/clap/master/assets/clap.png")]
+#![warn(
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
- unused_import_braces,
- unused_allocation
-)]
-// Lints we'd like to deny but are currently failing for upstream crates
-// unused_qualifications (bitflags, clippy)
-// trivial_numeric_casts (bitflags)
-#![cfg_attr(
- not(any(feature = "lints", feature = "nightly")),
- forbid(unstable_features)
+ unused_allocation,
+ trivial_numeric_casts,
+ clippy::single_char_pattern
)]
-#![cfg_attr(feature = "lints", feature(plugin))]
-#![cfg_attr(feature = "lints", plugin(clippy))]
-// Need to disable deny(warnings) while deprecations are active
-// #![cfg_attr(feature = "lints", deny(warnings))]
-#![cfg_attr(feature = "lints", allow(cyclomatic_complexity))]
-#![cfg_attr(feature = "lints", allow(doc_markdown))]
-#![cfg_attr(feature = "lints", allow(explicit_iter_loop))]
+#![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)]
+// Breaks up parallelism that clarifies intent
+#![allow(clippy::collapsible_else_if)]
-#[cfg(all(feature = "color", not(target_os = "windows")))]
-extern crate ansi_term;
-#[cfg(feature = "color")]
-extern crate atty;
-#[macro_use]
-extern crate bitflags;
-#[cfg(feature = "suggestions")]
-extern crate strsim;
-#[cfg(feature = "wrap_help")]
-extern crate term_size;
-extern crate textwrap;
-#[cfg(feature = "vec_map")]
-extern crate vec_map;
-#[cfg(feature = "yaml")]
-extern crate yaml_rust;
-
-pub use app::{App, AppSettings};
-pub use args::{Arg, ArgGroup, ArgMatches, ArgSettings, OsValues, SubCommand, Values};
-pub use completions::Shell;
-pub use errors::{Error, ErrorKind, Result};
-pub use fmt::Format;
-#[cfg(feature = "yaml")]
-pub use yaml_rust::YamlLoader;
+#[cfg(not(feature = "std"))]
+compile_error!("`std` feature is currently required to build `clap`");
-#[macro_use]
-mod macros;
-mod app;
-mod args;
-mod completions;
-mod errors;
-mod fmt;
-mod map;
-mod osstringext;
-mod strext;
-mod suggestions;
-mod usage_parser;
+pub use crate::builder::ArgAction;
+pub use crate::builder::Command;
+pub use crate::builder::ValueHint;
+pub use crate::builder::{Arg, ArgGroup};
+pub use crate::parser::ArgMatches;
+pub use crate::util::color::ColorChoice;
+pub use crate::util::Id;
-const INTERNAL_ERROR_MSG: &'static str = "Fatal internal error. Please consider filing a bug \
- report at https://github.com/clap-rs/clap/issues";
-const INVALID_UTF8: &'static str = "unexpected invalid UTF-8 code point";
+/// Command Line Argument Parser Error
+///
+/// See [`Command::error`] to create an error.
+///
+/// [`Command::error`]: crate::Command::error
+pub type Error = crate::error::Error<crate::error::DefaultFormatter>;
-#[cfg(unstable)]
-pub use derive::{ArgEnum, ClapApp, FromArgMatches, IntoApp};
+pub use crate::derive::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
-#[cfg(unstable)]
-mod derive {
- /// @TODO @release @docs
- pub trait ClapApp: IntoApp + FromArgMatches + Sized {
- /// @TODO @release @docs
- fn parse() -> Self {
- Self::from_argmatches(Self::into_app().get_matches())
- }
+#[cfg(feature = "derive")]
+#[doc(hidden)]
+pub use clap_derive::{self, *};
- /// @TODO @release @docs
- fn parse_from<I, T>(argv: I) -> Self
- where
- I: IntoIterator<Item = T>,
- T: Into<OsString> + Clone,
- {
- Self::from_argmatches(Self::into_app().get_matches_from(argv))
- }
+#[cfg(feature = "unstable-doc")]
+pub mod _cookbook;
+#[cfg(feature = "unstable-doc")]
+pub mod _derive;
+#[cfg(feature = "unstable-doc")]
+pub mod _faq;
+#[cfg(feature = "unstable-doc")]
+pub mod _features;
+#[cfg(feature = "unstable-doc")]
+pub mod _tutorial;
- /// @TODO @release @docs
- fn try_parse() -> Result<Self, clap::Error> {
- Self::try_from_argmatches(Self::into_app().get_matches_safe()?)
- }
+#[doc(hidden)]
+pub mod __macro_refs {
+ #[cfg(any(feature = "derive", feature = "cargo"))]
+ #[doc(hidden)]
+ pub use once_cell;
+}
- /// @TODO @release @docs
- fn try_parse_from<I, T>(argv: I) -> Result<Self, clap::Error>
- where
- I: IntoIterator<Item = T>,
- T: Into<OsString> + Clone,
- {
- Self::try_from_argmatches(Self::into_app().get_matches_from_safe(argv)?)
- }
- }
+#[macro_use]
+#[allow(missing_docs)]
+mod macros;
- /// @TODO @release @docs
- pub trait IntoApp {
- /// @TODO @release @docs
- fn into_app<'a, 'b>() -> clap::App<'a, 'b>;
- }
+mod derive;
- /// @TODO @release @docs
- pub trait FromArgMatches: Sized {
- /// @TODO @release @docs
- fn from_argmatches<'a>(matches: clap::ArgMatches<'a>) -> Self;
+pub mod builder;
+pub mod error;
+pub mod parser;
- /// @TODO @release @docs
- fn try_from_argmatches<'a>(matches: clap::ArgMatches<'a>) -> Result<Self, clap::Error>;
- }
+mod mkeymap;
+mod output;
+mod util;
- /// @TODO @release @docs
- pub trait ArgEnum {}
-}
+const INTERNAL_ERROR_MSG: &str = "Fatal internal error. Please consider filing a bug \
+ report at https://github.com/clap-rs/clap/issues";
diff --git a/src/macros.rs b/src/macros.rs
index 4583ea7..8addab3 100644
--- a/src/macros.rs
+++ b/src/macros.rs
@@ -1,422 +1,3 @@
-/// A convenience macro for loading the YAML file at compile time (relative to the current file,
-/// like modules work). That YAML object can then be passed to this function.
-///
-/// # Panics
-///
-/// The YAML file must be properly formatted or this function will panic!(). A good way to
-/// ensure this doesn't happen is to run your program with the `--help` switch. If this passes
-/// without error, you needn't worry because the YAML is properly formatted.
-///
-/// # Examples
-///
-/// The following example shows how to load a properly formatted YAML file to build an instance
-/// of an `App` struct.
-///
-/// ```ignore
-/// # #[macro_use]
-/// # extern crate clap;
-/// # use clap::App;
-/// # fn main() {
-/// let yml = load_yaml!("app.yml");
-/// let app = App::from_yaml(yml);
-///
-/// // continued logic goes here, such as `app.get_matches()` etc.
-/// # }
-/// ```
-#[cfg(feature = "yaml")]
-#[macro_export]
-macro_rules! load_yaml {
- ($yml:expr) => {
- &::clap::YamlLoader::load_from_str(include_str!($yml)).expect("failed to load YAML file")[0]
- };
-}
-
-/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] from an
-/// argument value. This macro returns a `Result<T,String>` which allows you as the developer to
-/// decide what you'd like to do on a failed parse. There are two types of errors, parse failures
-/// and those where the argument wasn't present (such as a non-required argument). You can use
-/// it to get a single value, or a iterator as with the [`ArgMatches::values_of`]
-///
-/// # Examples
-///
-/// ```no_run
-/// # #[macro_use]
-/// # extern crate clap;
-/// # use clap::App;
-/// # fn main() {
-/// let matches = App::new("myapp")
-/// .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'")
-/// .get_matches();
-///
-/// let len = value_t!(matches.value_of("length"), u32).unwrap_or_else(|e| e.exit());
-/// let also_len = value_t!(matches, "length", u32).unwrap_or_else(|e| e.exit());
-///
-/// println!("{} + 2: {}", len, len + 2);
-/// # }
-/// ```
-/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
-/// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
-/// [`Result<T,String>`]: https://doc.rust-lang.org/std/result/enum.Result.html
-#[macro_export]
-macro_rules! value_t {
- ($m:ident, $v:expr, $t:ty) => {
- value_t!($m.value_of($v), $t)
- };
- ($m:ident.value_of($v:expr), $t:ty) => {
- if let Some(v) = $m.value_of($v) {
- match v.parse::<$t>() {
- Ok(val) => Ok(val),
- Err(_) => Err(::clap::Error::value_validation_auto(format!(
- "The argument '{}' isn't a valid value",
- v
- ))),
- }
- } else {
- Err(::clap::Error::argument_not_found_auto($v))
- }
- };
-}
-
-/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] or
-/// exiting upon error, instead of returning a [`Result`] type.
-///
-/// **NOTE:** This macro is for backwards compatibility sake. Prefer
-/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`]
-///
-/// # Examples
-///
-/// ```no_run
-/// # #[macro_use]
-/// # extern crate clap;
-/// # use clap::App;
-/// # fn main() {
-/// let matches = App::new("myapp")
-/// .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'")
-/// .get_matches();
-///
-/// let len = value_t_or_exit!(matches.value_of("length"), u32);
-/// let also_len = value_t_or_exit!(matches, "length", u32);
-///
-/// println!("{} + 2: {}", len, len + 2);
-/// # }
-/// ```
-/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
-/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
-/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.value_t!.html
-#[macro_export]
-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) => {
- if let Some(v) = $m.value_of($v) {
- match v.parse::<$t>() {
- Ok(val) => val,
- Err(_) => ::clap::Error::value_validation_auto(format!(
- "The argument '{}' isn't a valid value",
- v
- ))
- .exit(),
- }
- } else {
- ::clap::Error::argument_not_found_auto($v).exit()
- }
- };
-}
-
-/// Convenience macro getting a typed value [`Vec<T>`] where `T` implements [`std::str::FromStr`]
-/// This macro returns a [`clap::Result<Vec<T>>`] which allows you as the developer to decide
-/// what you'd like to do on a failed parse.
-///
-/// # Examples
-///
-/// ```no_run
-/// # #[macro_use]
-/// # extern crate clap;
-/// # use clap::App;
-/// # fn main() {
-/// let matches = App::new("myapp")
-/// .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'")
-/// .get_matches();
-///
-/// let vals = values_t!(matches.values_of("seq"), u32).unwrap_or_else(|e| e.exit());
-/// for v in &vals {
-/// println!("{} + 2: {}", v, v + 2);
-/// }
-///
-/// let vals = values_t!(matches, "seq", u32).unwrap_or_else(|e| e.exit());
-/// for v in &vals {
-/// println!("{} + 2: {}", v, v + 2);
-/// }
-/// # }
-/// ```
-/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
-/// [`Vec<T>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
-/// [`clap::Result<Vec<T>>`]: ./type.Result.html
-#[macro_export]
-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) => {
- if let Some(vals) = $m.values_of($v) {
- let mut tmp = vec![];
- let mut err = None;
- for pv in vals {
- match pv.parse::<$t>() {
- Ok(rv) => tmp.push(rv),
- Err(..) => {
- err = Some(::clap::Error::value_validation_auto(format!(
- "The argument '{}' isn't a valid value",
- pv
- )));
- break;
- }
- }
- }
- match err {
- Some(e) => Err(e),
- None => Ok(tmp),
- }
- } else {
- Err(::clap::Error::argument_not_found_auto($v))
- }
- };
-}
-
-/// Convenience macro getting a typed value [`Vec<T>`] where `T` implements [`std::str::FromStr`]
-/// or exiting upon error.
-///
-/// **NOTE:** This macro is for backwards compatibility sake. Prefer
-/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`]
-///
-/// # Examples
-///
-/// ```no_run
-/// # #[macro_use]
-/// # extern crate clap;
-/// # use clap::App;
-/// # fn main() {
-/// let matches = App::new("myapp")
-/// .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'")
-/// .get_matches();
-///
-/// let vals = values_t_or_exit!(matches.values_of("seq"), u32);
-/// for v in &vals {
-/// println!("{} + 2: {}", v, v + 2);
-/// }
-///
-/// // type for example only
-/// let vals: Vec<u32> = values_t_or_exit!(matches, "seq", u32);
-/// for v in &vals {
-/// println!("{} + 2: {}", v, v + 2);
-/// }
-/// # }
-/// ```
-/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.values_t!.html
-/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
-/// [`Vec<T>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
-#[macro_export]
-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) => {
- if let Some(vals) = $m.values_of($v) {
- vals.map(|v| {
- v.parse::<$t>().unwrap_or_else(|_| {
- ::clap::Error::value_validation_auto(format!(
- "One or more arguments aren't valid values"
- ))
- .exit()
- })
- })
- .collect::<Vec<$t>>()
- } else {
- ::clap::Error::argument_not_found_auto($v).exit()
- }
- };
-}
-
-// _clap_count_exprs! is derived from https://github.com/DanielKeep/rust-grabbag
-// commit: 82a35ca5d9a04c3b920622d542104e3310ee5b07
-// License: MIT
-// Copyright ⓒ 2015 grabbag contributors.
-// Licensed under the MIT license (see LICENSE or <http://opensource.org
-// /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
-// <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
-// files in the project carrying such notice may not be copied, modified,
-// or distributed except according to those terms.
-//
-/// Counts the number of comma-delimited expressions passed to it. The result is a compile-time
-/// evaluable expression, suitable for use as a static array size, or the value of a `const`.
-///
-/// # Examples
-///
-/// ```
-/// # #[macro_use] extern crate clap;
-/// # fn main() {
-/// const COUNT: usize = _clap_count_exprs!(a, 5+1, "hi there!".into_string());
-/// assert_eq!(COUNT, 3);
-/// # }
-/// ```
-#[macro_export]
-macro_rules! _clap_count_exprs {
- () => { 0 };
- ($e:expr) => { 1 };
- ($e:expr, $($es:expr),+) => { 1 + $crate::_clap_count_exprs!($($es),*) };
-}
-
-/// Convenience macro to generate more complete enums with variants to be used as a type when
-/// parsing arguments. This enum also provides a `variants()` function which can be used to
-/// retrieve a `Vec<&'static str>` of the variant names, as well as implementing [`FromStr`] and
-/// [`Display`] automatically.
-///
-/// **NOTE:** Case insensitivity is supported for ASCII characters only. It's highly recommended to
-/// use [`Arg::case_insensitive(true)`] for args that will be used with these enums
-///
-/// **NOTE:** This macro automatically implements [`std::str::FromStr`] and [`std::fmt::Display`]
-///
-/// **NOTE:** These enums support pub (or not) and uses of the `#[derive()]` traits
-///
-/// # Examples
-///
-/// ```rust
-/// # #[macro_use]
-/// # extern crate clap;
-/// # use clap::{App, Arg};
-/// arg_enum!{
-/// #[derive(PartialEq, Debug)]
-/// pub enum Foo {
-/// Bar,
-/// Baz,
-/// Qux
-/// }
-/// }
-/// // Foo enum can now be used via Foo::Bar, or Foo::Baz, etc
-/// // and implements std::str::FromStr to use with the value_t! macros
-/// fn main() {
-/// let m = App::new("app")
-/// .arg(Arg::from_usage("<foo> 'the foo'")
-/// .possible_values(&Foo::variants())
-/// .case_insensitive(true))
-/// .get_matches_from(vec![
-/// "app", "baz"
-/// ]);
-/// let f = value_t!(m, "foo", Foo).unwrap_or_else(|e| e.exit());
-///
-/// assert_eq!(f, Foo::Baz);
-/// }
-/// ```
-/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
-/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
-/// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
-/// [`std::fmt::Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
-/// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.case_insensitive
-#[macro_export]
-macro_rules! arg_enum {
- (@as_item $($i:item)*) => ($($i)*);
- (@impls ( $($tts:tt)* ) -> ($e:ident, $($v:ident),+)) => {
- 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)*,)+ } ) => {
- arg_enum!(@impls
- ($(#[$($m),+])+
- pub enum $e {
- $($v$(=$val)*),+
- }) -> ($e, $($v),+)
- );
- };
- ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
- arg_enum!(@impls
- ($(#[$($m),+])+
- pub enum $e {
- $($v$(=$val)*),+
- }) -> ($e, $($v),+)
- );
- };
- ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
- arg_enum!(@impls
- ($(#[$($m),+])+
- enum $e {
- $($v$(=$val)*),+
- }) -> ($e, $($v),+)
- );
- };
- ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
- arg_enum!(@impls
- ($(#[$($m),+])+
- enum $e {
- $($v$(=$val)*),+
- }) -> ($e, $($v),+)
- );
- };
- (pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
- arg_enum!(@impls
- (pub enum $e {
- $($v$(=$val)*),+
- }) -> ($e, $($v),+)
- );
- };
- (pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
- arg_enum!(@impls
- (pub enum $e {
- $($v$(=$val)*),+
- }) -> ($e, $($v),+)
- );
- };
- (enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
- arg_enum!(@impls
- (enum $e {
- $($v$(=$val)*),+
- }) -> ($e, $($v),+)
- );
- };
- (enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
- 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`
///
@@ -425,22 +6,22 @@ macro_rules! arg_enum {
/// ```no_run
/// # #[macro_use]
/// # extern crate clap;
-/// # use clap::App;
+/// # use clap::Command;
/// # fn main() {
-/// let m = App::new("app")
+/// let m = Command::new("cmd")
/// .version(crate_version!())
/// .get_matches();
/// # }
/// ```
-#[cfg(not(feature = "no_cargo"))]
+#[cfg(feature = "cargo")]
#[macro_export]
macro_rules! crate_version {
() => {
- "2.33.3"
+ "4.1.8"
};
}
-/// Allows you to pull the authors for the app from your Cargo.toml at
+/// 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>"`
///
@@ -454,53 +35,29 @@ macro_rules! crate_version {
/// ```no_run
/// # #[macro_use]
/// # extern crate clap;
-/// # use clap::App;
+/// # use clap::Command;
/// # fn main() {
-/// let m = App::new("app")
+/// let m = Command::new("cmd")
/// .author(crate_authors!("\n"))
/// .get_matches();
/// # }
/// ```
-#[cfg(not(feature = "no_cargo"))]
+#[cfg(feature = "cargo")]
#[macro_export]
macro_rules! crate_authors {
($sep:expr) => {{
- use std::ops::Deref;
- #[allow(deprecated)]
- use std::sync::{Once, ONCE_INIT};
-
- #[allow(missing_copy_implementations)]
- #[allow(dead_code)]
- struct CargoAuthors {
- __private_field: (),
- };
-
- impl Deref for CargoAuthors {
- type Target = str;
-
- #[allow(unsafe_code)]
- fn deref(&self) -> &'static str {
- #[allow(deprecated)]
- static ONCE: Once = ONCE_INIT;
- static mut VALUE: *const String = 0 as *const String;
-
- unsafe {
- ONCE.call_once(|| {
- let s = ["Kevin K. <kbknapp@gmail.com>"].join(":").replace(':', $sep);
- VALUE = Box::into_raw(Box::new(s));
- });
-
- &(*VALUE)[..]
- }
- }
- }
-
- &*CargoAuthors {
- __private_field: (),
+ static authors: &str = .join(":");
+ if authors.contains(':') {
+ static CACHED: clap::__macro_refs::once_cell::sync::Lazy<String> =
+ clap::__macro_refs::once_cell::sync::Lazy::new(|| authors.replace(':', $sep));
+ let s: &'static str = &*CACHED;
+ s
+ } else {
+ authors
}
}};
() => {
- ["Kevin K. <kbknapp@gmail.com>"].join(":")
+ .join(":")
};
}
@@ -511,35 +68,41 @@ macro_rules! crate_authors {
/// ```no_run
/// # #[macro_use]
/// # extern crate clap;
-/// # use clap::App;
+/// # use clap::Command;
/// # fn main() {
-/// let m = App::new("app")
+/// let m = Command::new("cmd")
/// .about(crate_description!())
/// .get_matches();
/// # }
/// ```
-#[cfg(not(feature = "no_cargo"))]
+#[cfg(feature = "cargo")]
#[macro_export]
macro_rules! crate_description {
() => {
- "A simple to use, efficient, and full-featured Command Line Argument Parser\n"
+ "A simple to use, efficient, and full-featured Command Line Argument Parser"
};
}
/// Allows you to pull the name from your Cargo.toml at compile time.
///
+/// **NOTE:** This macro extracts the name from an environment variable `CARGO_PKG_NAME`.
+/// When the crate name is set to something different from the package name,
+/// use environment variables `CARGO_CRATE_NAME` or `CARGO_BIN_NAME`.
+/// See [the Cargo Book](https://doc.rust-lang.org/cargo/reference/environment-variables.html)
+/// for more information.
+///
/// # Examples
///
/// ```no_run
/// # #[macro_use]
/// # extern crate clap;
-/// # use clap::App;
+/// # use clap::Command;
/// # fn main() {
-/// let m = App::new(crate_name!())
+/// let m = Command::new(crate_name!())
/// .get_matches();
/// # }
/// ```
-#[cfg(not(feature = "no_cargo"))]
+#[cfg(feature = "cargo")]
#[macro_export]
macro_rules! crate_name {
() => {
@@ -547,17 +110,12 @@ macro_rules! crate_name {
};
}
-/// Allows you to build the `App` instance from your Cargo.toml at compile time.
-///
-/// Equivalent to using the `crate_*!` macros with their respective fields.
-///
-/// Provided separator is for the [`crate_authors!`](macro.crate_authors.html) macro,
-/// refer to the documentation therefor.
+/// 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.
///
-/// **Pro Tip:** In some cases you can "trick" the compiler into triggering a rebuild when your
+/// 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");`
///
@@ -567,560 +125,552 @@ macro_rules! crate_name {
/// # #[macro_use]
/// # extern crate clap;
/// # fn main() {
-/// let m = app_from_crate!().get_matches();
+/// let m = command!().get_matches();
/// # }
/// ```
-#[cfg(not(feature = "no_cargo"))]
+#[cfg(feature = "cargo")]
#[macro_export]
-macro_rules! app_from_crate {
- () => {
- $crate::App::new(crate_name!())
- .version(crate_version!())
- .author(crate_authors!())
- .about(crate_description!())
- };
- ($sep:expr) => {
- $crate::App::new(crate_name!())
- .version(crate_version!())
- .author(crate_authors!($sep))
- .about(crate_description!())
- };
-}
+macro_rules! command {
+ () => {{
+ $crate::command!($crate::crate_name!())
+ }};
+ ($name:expr) => {{
+ let mut cmd = $crate::Command::new($name).version($crate::crate_version!());
-/// Build `App`, `Arg`s, `SubCommand`s and `Group`s with Usage-string like input
-/// but without the associated parsing runtime cost.
-///
-/// `clap_app!` also supports several shorthand syntaxes.
-///
-/// # Examples
-///
-/// ```no_run
-/// # #[macro_use]
-/// # extern crate clap;
-/// # fn main() {
-/// let matches = clap_app!(myapp =>
-/// (version: "1.0")
-/// (author: "Kevin K. <kbknapp@gmail.com>")
-/// (about: "Does awesome things")
-/// (@arg CONFIG: -c --config +takes_value "Sets a custom config file")
-/// (@arg INPUT: +required "Sets the input file to use")
-/// (@arg debug: -d ... "Sets the level of debugging information")
-/// (@group difficulty =>
-/// (@arg hard: -h --hard "Sets hard mode")
-/// (@arg normal: -n --normal "Sets normal mode")
-/// (@arg easy: -e --easy "Sets easy mode")
-/// )
-/// (@subcommand test =>
-/// (about: "controls testing features")
-/// (version: "1.3")
-/// (author: "Someone E. <someone_else@other.com>")
-/// (@arg verbose: -v --verbose "Print test information verbosely")
-/// )
-/// )
-/// .get_matches();
-/// # }
-/// ```
-/// # Shorthand Syntax for Args
-///
-/// * A single hyphen followed by a character (such as `-c`) sets the [`Arg::short`]
-/// * A double hyphen followed by a character or word (such as `--config`) sets [`Arg::long`]
-/// * If one wishes to use a [`Arg::long`] with a hyphen inside (i.e. `--config-file`), you
-/// must use `--("config-file")` due to limitations of the Rust macro system.
-/// * Three dots (`...`) sets [`Arg::multiple(true)`]
-/// * Angled brackets after either a short or long will set [`Arg::value_name`] and
-/// `Arg::required(true)` such as `--config <FILE>` = `Arg::value_name("FILE")` and
-/// `Arg::required(true)`
-/// * Square brackets after either a short or long will set [`Arg::value_name`] and
-/// `Arg::required(false)` such as `--config [FILE]` = `Arg::value_name("FILE")` and
-/// `Arg::required(false)`
-/// * There are short hand syntaxes for Arg methods that accept booleans
-/// * A plus sign will set that method to `true` such as `+required` = `Arg::required(true)`
-/// * An exclamation will set that method to `false` such as `!required` = `Arg::required(false)`
-/// * A `#{min, max}` will set [`Arg::min_values(min)`] and [`Arg::max_values(max)`]
-/// * An asterisk (`*`) will set `Arg::required(true)`
-/// * Curly brackets around a `fn` will set [`Arg::validator`] as in `{fn}` = `Arg::validator(fn)`
-/// * An Arg method that accepts a string followed by square brackets will set that method such as
-/// `conflicts_with[FOO]` will set `Arg::conflicts_with("FOO")` (note the lack of quotes around
-/// `FOO` in the macro)
-/// * An Arg method that takes a string and can be set multiple times (such as
-/// [`Arg::conflicts_with`]) followed by square brackets and a list of values separated by spaces
-/// will set that method such as `conflicts_with[FOO BAR BAZ]` will set
-/// `Arg::conflicts_with("FOO")`, `Arg::conflicts_with("BAR")`, and `Arg::conflicts_with("BAZ")`
-/// (note the lack of quotes around the values in the macro)
-///
-/// # Shorthand Syntax for Groups
-///
-/// * There are short hand syntaxes for `ArgGroup` methods that accept booleans
-/// * A plus sign will set that method to `true` such as `+required` = `ArgGroup::required(true)`
-/// * An exclamation will set that method to `false` such as `!required` = `ArgGroup::required(false)`
-///
-/// [`Arg::short`]: ./struct.Arg.html#method.short
-/// [`Arg::long`]: ./struct.Arg.html#method.long
-/// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
-/// [`Arg::value_name`]: ./struct.Arg.html#method.value_name
-/// [`Arg::min_values(min)`]: ./struct.Arg.html#method.min_values
-/// [`Arg::max_values(max)`]: ./struct.Arg.html#method.max_values
-/// [`Arg::validator`]: ./struct.Arg.html#method.validator
-/// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with
-#[macro_export]
-macro_rules! clap_app {
- (@app ($builder:expr)) => { $builder };
- (@app ($builder:expr) (@arg ($name:expr): $($tail:tt)*) $($tt:tt)*) => {
- clap_app!{ @app
- ($builder.arg(
- clap_app!{ @arg ($crate::Arg::with_name($name)) (-) $($tail)* }))
- $($tt)*
+ let author = $crate::crate_authors!();
+ if !author.is_empty() {
+ cmd = cmd.author(author)
}
- };
- (@app ($builder:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => {
- clap_app!{ @app
- ($builder.arg(
- clap_app!{ @arg ($crate::Arg::with_name(stringify!($name))) (-) $($tail)* }))
- $($tt)*
+
+ 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");
+ }};
+}
+
+#[doc(hidden)]
+#[macro_export]
+macro_rules! arg_impl {
+ ( @string $val:ident ) => {
+ stringify!($val)
};
- (@app ($builder:expr) (@setting $setting:ident) $($tt:tt)*) => {
- clap_app!{ @app
- ($builder.setting($crate::AppSettings::$setting))
- $($tt)*
- }
+ ( @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");
};
-// Treat the application builder as an argument to set its attributes
- (@app ($builder:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => {
- clap_app!{ @app (clap_app!{ @arg ($builder) $($attr)* }) $($tt)* }
+ ( @string ) => {
+ None
};
- (@app ($builder:expr) (@group $name:ident => $($tail:tt)*) $($tt:tt)*) => {
- clap_app!{ @app
- (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name))) $($tail)* })
- $($tt)*
+
+ ( @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)*
+ ) => {{
+ debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values");
+ debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`");
+
+ let mut arg = $arg;
+ let long = $crate::arg_impl! { @string $long };
+ if arg.get_id() == "" {
+ arg = arg.id(long);
}
- };
- (@app ($builder:expr) (@group $name:ident !$ident:ident => $($tail:tt)*) $($tt:tt)*) => {
- clap_app!{ @app
- (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(false)) $($tail)* })
- $($tt)*
+ let action = $crate::ArgAction::SetTrue;
+ let arg = arg
+ .long(long)
+ .action(action);
+ let arg = $crate::arg_impl! {
+ @arg (arg) $($tail)*
+ };
+ arg
+ }};
+ (
+ @arg
+ ($arg:expr)
+ --$long:literal
+ $($tail:tt)*
+ ) => {{
+ debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values");
+ debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`");
+
+ let mut arg = $arg;
+ let long = $crate::arg_impl! { @string $long };
+ if arg.get_id() == "" {
+ arg = arg.id(long);
}
- };
- (@app ($builder:expr) (@group $name:ident +$ident:ident => $($tail:tt)*) $($tt:tt)*) => {
- clap_app!{ @app
- (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(true)) $($tail)* })
- $($tt)*
+ let action = $crate::ArgAction::SetTrue;
+ let arg = arg
+ .long(long)
+ .action(action);
+ let arg = $crate::arg_impl! {
+ @arg (arg) $($tail)*
+ };
+ arg
+ }};
+ (
+ @arg
+ ($arg:expr)
+ -$short:ident
+ $($tail:tt)*
+ ) => {{
+ 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");
+ debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`");
+
+ let action = $crate::ArgAction::SetTrue;
+ let arg = $arg
+ .short($crate::arg_impl! { @char $short })
+ .action(action);
+ let arg = $crate::arg_impl! {
+ @arg (arg) $($tail)*
+ };
+ arg
+ }};
+ (
+ @arg
+ ($arg:expr)
+ -$short:literal
+ $($tail:tt)*
+ ) => {{
+ 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");
+ debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`");
+
+ let action = $crate::ArgAction::SetTrue;
+ let arg = $arg
+ .short($crate::arg_impl! { @char $short })
+ .action(action);
+ let arg = $crate::arg_impl! {
+ @arg (arg) $($tail)*
+ };
+ arg
+ }};
+ (
+ @arg
+ ($arg:expr)
+ <$value_name:ident>
+ $($tail:tt)*
+ ) => {{
+ debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags 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(true);
}
- };
-// Handle subcommand creation
- (@app ($builder:expr) (@subcommand $name:ident => $($tail:tt)*) $($tt:tt)*) => {
- clap_app!{ @app
- ($builder.subcommand(
- clap_app!{ @app ($crate::SubCommand::with_name(stringify!($name))) $($tail)* }
- ))
- $($tt)*
+
+ let value_name = $crate::arg_impl! { @string $value_name };
+ if arg.get_id() == "" {
+ arg = arg.id(value_name);
}
- };
-// Yaml like function calls - used for setting various meta directly against the app
- (@app ($builder:expr) ($ident:ident: $($v:expr),*) $($tt:tt)*) => {
-// clap_app!{ @app ($builder.$ident($($v),*)) $($tt)* }
- clap_app!{ @app
- ($builder.$ident($($v),*))
- $($tt)*
+ let arg = arg
+ .value_name(value_name)
+ .action($crate::ArgAction::Set);
+ let arg = $crate::arg_impl! {
+ @arg (arg) $($tail)*
+ };
+ arg
+ }};
+ (
+ @arg
+ ($arg:expr)
+ <$value_name:literal>
+ $($tail:tt)*
+ ) => {{
+ debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags 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(true);
}
- };
-// 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)*) => {
- clap_app!{ @group ($builder, clap_app!{ @arg ($group) (-) $($attr)* }) $($tt)* }
- };
- (@group ($builder:expr, $group:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => {
- clap_app!{ @group
- (clap_app!{ @app ($builder) (@arg $name: $($tail)*) },
- $group.arg(stringify!($name)))
- $($tt)*
+ let value_name = $crate::arg_impl! { @string $value_name };
+ if arg.get_id() == "" {
+ arg = arg.id(value_name);
+ }
+ let arg = arg
+ .value_name(value_name)
+ .action($crate::ArgAction::Set);
+ let arg = $crate::arg_impl! {
+ @arg (arg) $($tail)*
+ };
+ arg
+ }};
+ (
+ @arg
+ ($arg:expr)
+ [$value_name:ident]
+ $($tail:tt)*
+ ) => {{
+ debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags 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.num_args(0..=1);
}
- };
-// 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)*) => {
- clap_app!{ @arg ($arg.long($long)) $modes $($tail)* }
- };
- (@arg ($arg:expr) $modes:tt --$long:ident $($tail:tt)*) => {
- clap_app!{ @arg ($arg.long(stringify!($long))) $modes $($tail)* }
- };
- (@arg ($arg:expr) $modes:tt -$short:ident $($tail:tt)*) => {
- clap_app!{ @arg ($arg.short(stringify!($short))) $modes $($tail)* }
- };
- (@arg ($arg:expr) (-) <$var:ident> $($tail:tt)*) => {
- clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value +required $($tail)* }
- };
- (@arg ($arg:expr) (+) <$var:ident> $($tail:tt)*) => {
- clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* }
- };
- (@arg ($arg:expr) (-) [$var:ident] $($tail:tt)*) => {
- clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value $($tail)* }
- };
- (@arg ($arg:expr) (+) [$var:ident] $($tail:tt)*) => {
- clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* }
- };
- (@arg ($arg:expr) $modes:tt ... $($tail:tt)*) => {
- clap_app!{ @arg ($arg) $modes +multiple $($tail)* }
- };
-// Shorthand magic
- (@arg ($arg:expr) $modes:tt #{$n:expr, $m:expr} $($tail:tt)*) => {
- clap_app!{ @arg ($arg) $modes min_values($n) max_values($m) $($tail)* }
- };
- (@arg ($arg:expr) $modes:tt * $($tail:tt)*) => {
- clap_app!{ @arg ($arg) $modes +required $($tail)* }
- };
-// !foo -> .foo(false)
- (@arg ($arg:expr) $modes:tt !$ident:ident $($tail:tt)*) => {
- clap_app!{ @arg ($arg.$ident(false)) $modes $($tail)* }
- };
-// +foo -> .foo(true)
- (@arg ($arg:expr) $modes:tt +$ident:ident $($tail:tt)*) => {
- clap_app!{ @arg ($arg.$ident(true)) $modes $($tail)* }
- };
-// Validator
- (@arg ($arg:expr) $modes:tt {$fn_:expr} $($tail:tt)*) => {
- clap_app!{ @arg ($arg.validator($fn_)) $modes $($tail)* }
- };
- (@as_expr $expr:expr) => { $expr };
-// Help
- (@arg ($arg:expr) $modes:tt $desc:tt) => { $arg.help(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)*) => {
- 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)*) => {
- 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)*) => {
- clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* }
- };
+ let value_name = $crate::arg_impl! { @string $value_name };
+ if arg.get_id() == "" {
+ arg = arg.id(value_name);
+ }
+ let arg = arg
+ .value_name(value_name)
+ .action($crate::ArgAction::Set);
+ let arg = $crate::arg_impl! {
+ @arg (arg) $($tail)*
+ };
+ arg
+ }};
+ (
+ @arg
+ ($arg:expr)
+ [$value_name:literal]
+ $($tail:tt)*
+ ) => {{
+ debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags 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.num_args(0..=1);
+ }
-// Build a subcommand outside of an app.
- (@subcommand $name:ident => $($tail:tt)*) => {
- clap_app!{ @app ($crate::SubCommand::with_name(stringify!($name))) $($tail)* }
- };
-// Start the magic
- (($name:expr) => $($tail:tt)*) => {{
- clap_app!{ @app ($crate::App::new($name)) $($tail)*}
+ let value_name = $crate::arg_impl! { @string $value_name };
+ if arg.get_id() == "" {
+ arg = arg.id(value_name);
+ }
+ let arg = arg
+ .value_name(value_name)
+ .action($crate::ArgAction::Set);
+ let arg = $crate::arg_impl! {
+ @arg (arg) $($tail)*
+ };
+ arg
+ }};
+ (
+ @arg
+ ($arg:expr)
+ ...
+ $($tail:tt)*
+ ) => {{
+ let arg = match $arg.get_action() {
+ $crate::ArgAction::Set => {
+ if $arg.get_long().is_none() && $arg.get_short().is_none() {
+ $arg.num_args(1..)
+ // Allow collecting arguments interleaved with flags
+ .action($crate::ArgAction::Append)
+ } else {
+ $arg.action($crate::ArgAction::Append)
+ }
+ },
+ $crate::ArgAction::SetTrue | $crate::ArgAction::Help | $crate::ArgAction::Version => {
+ $arg.action($crate::ArgAction::Count)
+ }
+ action => {
+ panic!("Unexpected action {:?}", action)
+ }
+ };
+ let arg = $crate::arg_impl! {
+ @arg (arg) $($tail)*
+ };
+ arg
}};
+ (
+ @arg
+ ($arg:expr)
+ $help:literal
+ ) => {{
+ $arg.help($help)
+ }};
+ (
+ @arg
+ ($arg:expr)
+ ) => {{
+ $arg
+ }};
+}
- ($name:ident => $($tail:tt)*) => {{
- clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)*}
+/// 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::id`][crate::Arg::id].
+///
+/// ### 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"`.
+///
+/// **NOTE:** Dashes in the long name (e.g. `--foo-bar`) is not supported and quoting is required
+/// (e.g. `--"foo-bar"`).
+///
+/// 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 [`ArgAction::Count`][crate::ArgAction::Count] and [`ArgAction::Append`][crate::ArgAction::Append].
+///
+/// ### 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};
+/// let cmd = 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")
+/// ]);
+///
+/// let m = cmd.try_get_matches_from(["prog", "--config", "file.toml"]).unwrap();
+/// assert_eq!(m.get_one::<String>("config").unwrap(), "file.toml");
+/// assert_eq!(*m.get_one::<u8>("debug").unwrap(), 0);
+/// assert_eq!(m.get_one::<String>("input"), None);
+/// ```
+/// [`Arg`]: crate::Arg
+#[macro_export]
+macro_rules! arg {
+ ( $name:ident: $($tail:tt)+ ) => {{
+ let arg = $crate::Arg::new($crate::arg_impl! { @string $name });
+ let arg = $crate::arg_impl! {
+ @arg (arg) $($tail)+
+ };
+ arg
+ }};
+ ( $($tail:tt)+ ) => {{
+ let arg = $crate::Arg::default();
+ let arg = $crate::arg_impl! {
+ @arg (arg) $($tail)+
+ };
+ debug_assert_ne!(arg.get_id(), "", "Without a value or long flag, the `name:` prefix is required");
+ arg
}};
}
macro_rules! impl_settings {
- ($n:ident, $($v:ident => $c:path),+) => {
- pub fn set(&mut self, s: $n) {
- match s {
- $($n::$v => self.0.insert($c)),+
+ ($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())
}
- }
- pub fn unset(&mut self, s: $n) {
- match s {
- $($n::$v => self.0.remove($c)),+
+ #[allow(dead_code)]
+ pub(crate) fn insert(&mut self, rhs: Self) {
+ self.0.insert(rhs.0);
}
- }
- pub fn is_set(&self, s: $n) -> bool {
- match s {
- $($n::$v => self.0.contains($c)),+
+ #[allow(dead_code)]
+ pub(crate) fn remove(&mut self, rhs: Self) {
+ self.0.remove(rhs.0);
}
- }
- };
-}
-
-// 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")]
-#[cfg_attr(feature = "debug", macro_use)]
-#[cfg_attr(feature = "debug", allow(unused_macros))]
-mod debug_macros {
- macro_rules! debugln {
- ($fmt:expr) => (println!(concat!("DEBUG:clap:", $fmt)));
- ($fmt:expr, $($arg:tt)*) => (println!(concat!("DEBUG:clap:",$fmt), $($arg)*));
- }
- macro_rules! sdebugln {
- ($fmt:expr) => (println!($fmt));
- ($fmt:expr, $($arg:tt)*) => (println!($fmt, $($arg)*));
- }
- macro_rules! debug {
- ($fmt:expr) => (print!(concat!("DEBUG:clap:", $fmt)));
- ($fmt:expr, $($arg:tt)*) => (print!(concat!("DEBUG:clap:",$fmt), $($arg)*));
- }
- macro_rules! sdebug {
- ($fmt:expr) => (print!($fmt));
- ($fmt:expr, $($arg:tt)*) => (print!($fmt, $($arg)*));
- }
-}
-#[cfg(not(feature = "debug"))]
-#[cfg_attr(not(feature = "debug"), macro_use)]
-mod debug_macros {
- macro_rules! debugln {
- ($fmt:expr) => {};
- ($fmt:expr, $($arg:tt)*) => {};
- }
- macro_rules! sdebugln {
- ($fmt:expr) => {};
- ($fmt:expr, $($arg:tt)*) => {};
- }
- macro_rules! debug {
- ($fmt:expr) => {};
- ($fmt:expr, $($arg:tt)*) => {};
- }
-}
-
-// Helper/deduplication macro for printing the correct number of spaces in help messages
-// used in:
-// src/args/arg_builder/*.rs
-// src/app/mod.rs
-macro_rules! write_nspaces {
- ($dst:expr, $num:expr) => {{
- debugln!("write_spaces!: num={}", $num);
- for _ in 0..$num {
- $dst.write_all(b" ")?;
- }
- }};
-}
-
-// convenience macro for remove an item from a vec
-//macro_rules! vec_remove_all {
-// ($vec:expr, $to_rem:expr) => {
-// debugln!("vec_remove_all! to_rem={:?}", $to_rem);
-// for i in (0 .. $vec.len()).rev() {
-// let should_remove = $to_rem.any(|name| name == &$vec[i]);
-// if should_remove { $vec.swap_remove(i); }
-// }
-// };
-//}
-macro_rules! find_from {
- ($_self:expr, $arg_name:expr, $from:ident, $matcher:expr) => {{
- let mut ret = None;
- for k in $matcher.arg_names() {
- if let Some(f) = find_by_name!($_self, k, flags, iter) {
- if let Some(ref v) = f.$from() {
- if v.contains($arg_name) {
- ret = Some(f.to_string());
- }
+ #[allow(dead_code)]
+ pub(crate) fn set(&mut self, s: $settings) {
+ match s {
+ $(
+ $(#[$inner $($args)*])*
+ $settings::$setting => self.0.insert($flag),
+ )*
}
}
- if let Some(o) = find_by_name!($_self, k, opts, iter) {
- if let Some(ref v) = o.$from() {
- if v.contains(&$arg_name) {
- ret = Some(o.to_string());
- }
+
+ #[allow(dead_code)]
+ pub(crate) fn unset(&mut self, s: $settings) {
+ match s {
+ $(
+ $(#[$inner $($args)*])*
+ $settings::$setting => self.0.remove($flag),
+ )*
}
}
- if let Some(pos) = find_by_name!($_self, k, positionals, values) {
- if let Some(ref v) = pos.$from() {
- if v.contains($arg_name) {
- ret = Some(pos.b.name.to_owned());
- }
+
+ #[allow(dead_code)]
+ pub(crate) fn is_set(&self, s: $settings) -> bool {
+ match s {
+ $(
+ $(#[$inner $($args)*])*
+ $settings::$setting => self.0.contains($flag),
+ )*
}
}
}
- ret
- }};
-}
-//macro_rules! find_name_from {
-// ($_self:expr, $arg_name:expr, $from:ident, $matcher:expr) => {{
-// let mut ret = None;
-// for k in $matcher.arg_names() {
-// if let Some(f) = find_by_name!($_self, k, flags, iter) {
-// if let Some(ref v) = f.$from() {
-// if v.contains($arg_name) {
-// ret = Some(f.b.name);
-// }
-// }
-// }
-// if let Some(o) = find_by_name!($_self, k, opts, iter) {
-// if let Some(ref v) = o.$from() {
-// if v.contains(&$arg_name) {
-// ret = Some(o.b.name);
-// }
-// }
-// }
-// if let Some(pos) = find_by_name!($_self, k, positionals, values) {
-// if let Some(ref v) = pos.$from() {
-// if v.contains($arg_name) {
-// ret = Some(pos.b.name);
-// }
-// }
-// }
-// }
-// ret
-// }};
-//}
+ impl BitOr for $flags {
+ type Output = Self;
-macro_rules! find_any_by_name {
- ($p:expr, $name:expr) => {{
- fn as_trait_obj<'a, 'b, T: AnyArg<'a, 'b>>(x: &T) -> &AnyArg<'a, 'b> {
- x
+ fn bitor(mut self, rhs: Self) -> Self::Output {
+ self.0.insert(rhs.0);
+ self
+ }
}
- find_by_name!($p, $name, flags, iter)
- .map(as_trait_obj)
- .or(find_by_name!($p, $name, opts, iter)
- .map(as_trait_obj)
- .or(find_by_name!($p, $name, positionals, values).map(as_trait_obj)))
- }};
-}
-// Finds an arg by name
-macro_rules! find_by_name {
- ($p:expr, $name:expr, $what:ident, $how:ident) => {
- $p.$what.$how().find(|o| o.b.name == $name)
- };
-}
-
-// Finds an option including if it's aliased
-macro_rules! find_opt_by_long {
- (@os $_self:ident, $long:expr) => {{
- _find_by_long!($_self, $long, opts)
- }};
- ($_self:ident, $long:expr) => {{
- _find_by_long!($_self, $long, opts)
- }};
-}
-
-macro_rules! find_flag_by_long {
- (@os $_self:ident, $long:expr) => {{
- _find_by_long!($_self, $long, flags)
- }};
- ($_self:ident, $long:expr) => {{
- _find_by_long!($_self, $long, flags)
- }};
-}
-
-macro_rules! _find_by_long {
- ($_self:ident, $long:expr, $what:ident) => {{
- $_self
- .$what
- .iter()
- .filter(|a| a.s.long.is_some())
- .find(|a| {
- a.s.long.unwrap() == $long
- || (a.s.aliases.is_some()
- && a.s
- .aliases
- .as_ref()
- .unwrap()
- .iter()
- .any(|&(alias, _)| alias == $long))
- })
- }};
-}
-
-// Finds an option
-macro_rules! find_opt_by_short {
- ($_self:ident, $short:expr) => {{
- _find_by_short!($_self, $short, opts)
- }};
-}
-macro_rules! find_flag_by_short {
- ($_self:ident, $short:expr) => {{
- _find_by_short!($_self, $short, flags)
- }};
-}
+ impl From<$settings> for $flags {
+ fn from(setting: $settings) -> Self {
+ let mut flags = $flags::empty();
+ flags.set(setting);
+ flags
+ }
+ }
-macro_rules! _find_by_short {
- ($_self:ident, $short:expr, $what:ident) => {{
- $_self
- .$what
- .iter()
- .filter(|a| a.s.short.is_some())
- .find(|a| a.s.short.unwrap() == $short)
- }};
-}
+ impl BitOr<$settings> for $flags {
+ type Output = Self;
-macro_rules! find_subcmd {
- ($_self:expr, $sc:expr) => {{
- $_self.subcommands.iter().find(|s| {
- &*s.p.meta.name == $sc
- || (s.p.meta.aliases.is_some()
- && s.p
- .meta
- .aliases
- .as_ref()
- .unwrap()
- .iter()
- .any(|&(n, _)| n == $sc))
- })
- }};
-}
+ fn bitor(mut self, rhs: $settings) -> Self::Output {
+ self.set(rhs);
+ self
+ }
+ }
-macro_rules! shorts {
- ($_self:ident) => {{
- _shorts_longs!($_self, short)
- }};
-}
+ impl BitOr for $settings {
+ type Output = $flags;
-macro_rules! longs {
- ($_self:ident) => {{
- _shorts_longs!($_self, long)
- }};
+ fn bitor(self, rhs: Self) -> Self::Output {
+ let mut flags = $flags::empty();
+ flags.set(self);
+ flags.set(rhs);
+ flags
+ }
+ }
+ }
}
-macro_rules! _shorts_longs {
- ($_self:ident, $what:ident) => {{
- $_self
- .flags
- .iter()
- .filter(|f| f.s.$what.is_some())
- .map(|f| f.s.$what.as_ref().unwrap())
- .chain(
- $_self
- .opts
- .iter()
- .filter(|o| o.s.$what.is_some())
- .map(|o| o.s.$what.as_ref().unwrap()),
- )
- }};
+#[cfg(feature = "debug")]
+macro_rules! debug {
+ ($($arg:tt)*) => ({
+ let prefix = format!("[{:>w$}] \t", module_path!(), w = 28);
+ let body = format!($($arg)*);
+ let mut styled = $crate::builder::StyledStr::new();
+ styled.hint(prefix);
+ styled.hint(body);
+ styled.none("\n");
+ let color = $crate::output::fmt::Colorizer::new($crate::output::fmt::Stream::Stderr, $crate::ColorChoice::Auto).with_content(styled);
+ let _ = color.print();
+ })
}
-macro_rules! arg_names {
- ($_self:ident) => {{
- _names!(@args $_self)
- }};
+#[cfg(not(feature = "debug"))]
+macro_rules! debug {
+ ($($arg:tt)*) => {};
}
-macro_rules! sc_names {
- ($_self:ident) => {{
- _names!(@sc $_self)
- }};
+macro_rules! ok {
+ ($expr:expr) => {
+ match $expr {
+ Ok(val) => val,
+ Err(err) => {
+ return Err(err);
+ }
+ }
+ };
}
-macro_rules! _names {
- (@args $_self:ident) => {{
- $_self.flags.iter().map(|f| &*f.b.name).chain(
- $_self
- .opts
- .iter()
- .map(|o| &*o.b.name)
- .chain($_self.positionals.values().map(|p| &*p.b.name)),
- )
- }};
- (@sc $_self:ident) => {{
- $_self.subcommands.iter().map(|s| &*s.p.meta.name).chain(
- $_self
- .subcommands
- .iter()
- .filter(|s| s.p.meta.aliases.is_some())
- .flat_map(|s| s.p.meta.aliases.as_ref().unwrap().iter().map(|&(n, _)| n)),
- )
- }};
+macro_rules! some {
+ ($expr:expr) => {
+ match $expr {
+ Some(val) => val,
+ None => {
+ return None;
+ }
+ }
+ };
}
diff --git a/src/map.rs b/src/map.rs
deleted file mode 100644
index 1349783..0000000
--- a/src/map.rs
+++ /dev/null
@@ -1,88 +0,0 @@
-#[cfg(feature = "vec_map")]
-pub use vec_map::{Values, VecMap};
-
-#[cfg(not(feature = "vec_map"))]
-pub use self::vec_map::{Values, VecMap};
-
-#[cfg(not(feature = "vec_map"))]
-mod vec_map {
- use std::collections::btree_map;
- use std::collections::BTreeMap;
- use std::fmt::{self, Debug, Formatter};
-
- #[derive(Clone, Default, Debug)]
- pub struct VecMap<V> {
- inner: BTreeMap<usize, V>,
- }
-
- impl<V> VecMap<V> {
- pub fn new() -> Self {
- VecMap {
- inner: Default::default(),
- }
- }
-
- pub fn len(&self) -> usize {
- self.inner.len()
- }
-
- pub fn is_empty(&self) -> bool {
- self.inner.is_empty()
- }
-
- pub fn insert(&mut self, key: usize, value: V) -> Option<V> {
- self.inner.insert(key, value)
- }
-
- pub fn values(&self) -> Values<V> {
- self.inner.values()
- }
-
- pub fn iter(&self) -> Iter<V> {
- Iter {
- inner: self.inner.iter(),
- }
- }
-
- pub fn contains_key(&self, key: usize) -> bool {
- self.inner.contains_key(&key)
- }
-
- pub fn entry(&mut self, key: usize) -> Entry<V> {
- self.inner.entry(key)
- }
-
- pub fn get(&self, key: usize) -> Option<&V> {
- self.inner.get(&key)
- }
- }
-
- pub type Values<'a, V> = btree_map::Values<'a, usize, V>;
-
- pub type Entry<'a, V> = btree_map::Entry<'a, usize, V>;
-
- #[derive(Clone)]
- pub struct Iter<'a, V: 'a> {
- inner: btree_map::Iter<'a, usize, V>,
- }
-
- impl<'a, V: 'a + Debug> Debug for Iter<'a, V> {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- f.debug_list().entries(self.inner.clone()).finish()
- }
- }
-
- impl<'a, V: 'a> Iterator for Iter<'a, V> {
- type Item = (usize, &'a V);
-
- fn next(&mut self) -> Option<Self::Item> {
- self.inner.next().map(|(k, v)| (*k, v))
- }
- }
-
- impl<'a, V: 'a> DoubleEndedIterator for Iter<'a, V> {
- fn next_back(&mut self) -> Option<Self::Item> {
- self.inner.next_back().map(|(k, v)| (*k, v))
- }
- }
-}
diff --git a/src/mkeymap.rs b/src/mkeymap.rs
new file mode 100644
index 0000000..a54fae4
--- /dev/null
+++ b/src/mkeymap.rs
@@ -0,0 +1,177 @@
+use std::iter::Iterator;
+use std::ops::Index;
+
+use crate::builder::OsStr;
+use crate::Arg;
+use crate::INTERNAL_ERROR_MSG;
+
+#[derive(PartialEq, Eq, Debug, Clone)]
+pub(crate) struct Key {
+ key: KeyType,
+ index: usize,
+}
+
+#[derive(Default, PartialEq, Eq, Debug, Clone)]
+pub(crate) struct MKeyMap {
+ /// All of the arguments.
+ args: Vec<Arg>,
+
+ // Cache part:
+ /// Will be set after `_build()`.
+ keys: Vec<Key>,
+}
+
+#[derive(Debug, PartialEq, Eq, Hash, Clone)]
+pub(crate) enum KeyType {
+ Short(char),
+ Long(OsStr),
+ Position(usize),
+}
+
+impl KeyType {
+ pub(crate) fn is_position(&self) -> bool {
+ matches!(self, KeyType::Position(_))
+ }
+}
+
+impl PartialEq<usize> for KeyType {
+ fn eq(&self, rhs: &usize) -> bool {
+ match self {
+ KeyType::Position(x) => x == rhs,
+ _ => false,
+ }
+ }
+}
+
+impl PartialEq<&str> for KeyType {
+ fn eq(&self, rhs: &&str) -> bool {
+ match self {
+ KeyType::Long(l) => l == rhs,
+ _ => false,
+ }
+ }
+}
+
+impl PartialEq<str> for KeyType {
+ fn eq(&self, rhs: &str) -> bool {
+ match self {
+ KeyType::Long(l) => l == rhs,
+ _ => false,
+ }
+ }
+}
+
+impl PartialEq<OsStr> for KeyType {
+ fn eq(&self, rhs: &OsStr) -> bool {
+ match self {
+ KeyType::Long(l) => l == rhs,
+ _ => false,
+ }
+ }
+}
+
+impl PartialEq<char> for KeyType {
+ fn eq(&self, rhs: &char) -> bool {
+ match self {
+ KeyType::Short(c) => c == rhs,
+ _ => false,
+ }
+ }
+}
+
+impl MKeyMap {
+ /// If any arg has corresponding key in this map, we can search the key with
+ /// u64(for positional argument), char(for short flag), &str and OsString
+ /// (for long flag)
+ pub(crate) fn contains<K>(&self, key: K) -> bool
+ where
+ KeyType: PartialEq<K>,
+ {
+ self.keys.iter().any(|x| x.key == key)
+ }
+
+ /// Push an argument in the map.
+ pub(crate) fn push(&mut self, new_arg: Arg) {
+ self.args.push(new_arg);
+ }
+
+ /// Find the arg have corresponding key in this map, we can search the key
+ /// with u64(for positional argument), char(for short flag), &str and
+ /// OsString (for long flag)
+ pub(crate) fn get<K: ?Sized>(&self, key: &K) -> Option<&Arg>
+ where
+ KeyType: PartialEq<K>,
+ {
+ self.keys
+ .iter()
+ .find(|k| &k.key == key)
+ .map(|k| &self.args[k.index])
+ }
+
+ /// Return iterators of all keys.
+ pub(crate) fn keys(&self) -> impl Iterator<Item = &KeyType> {
+ self.keys.iter().map(|x| &x.key)
+ }
+
+ /// Return iterators of all args.
+ pub(crate) fn args(&self) -> impl Iterator<Item = &Arg> {
+ self.args.iter()
+ }
+
+ /// Return mutable iterators of all args.
+ pub(crate) fn args_mut(&mut self) -> impl Iterator<Item = &mut Arg> {
+ self.args.iter_mut()
+ }
+
+ /// We need a lazy build here since some we may change args after creating
+ /// the map, you can checkout who uses `args_mut`.
+ pub(crate) fn _build(&mut self) {
+ for (i, arg) in self.args.iter().enumerate() {
+ append_keys(&mut self.keys, arg, i);
+ }
+ }
+
+ /// Remove an arg in the graph by Id, usually used by `mut_arg`. Return
+ /// `Some(arg)` if removed.
+ pub(crate) fn remove_by_name(&mut self, name: &str) -> Option<Arg> {
+ self.args
+ .iter()
+ .position(|arg| arg.id == name)
+ // since it's a cold function, using this wouldn't hurt much
+ .map(|i| self.args.remove(i))
+ }
+}
+
+impl Index<&'_ KeyType> for MKeyMap {
+ type Output = Arg;
+
+ fn index(&self, key: &KeyType) -> &Self::Output {
+ self.get(key).expect(INTERNAL_ERROR_MSG)
+ }
+}
+
+/// Generate key types for an specific Arg.
+fn append_keys(keys: &mut Vec<Key>, arg: &Arg, index: usize) {
+ if let Some(pos_index) = arg.index {
+ let key = KeyType::Position(pos_index);
+ keys.push(Key { key, index });
+ } else {
+ if let Some(short) = arg.short {
+ let key = KeyType::Short(short);
+ keys.push(Key { key, index });
+ }
+ if let Some(long) = arg.long.clone() {
+ let key = KeyType::Long(long.into());
+ keys.push(Key { key, index });
+ }
+
+ for (short, _) in arg.short_aliases.iter() {
+ let key = KeyType::Short(*short);
+ keys.push(Key { key, index });
+ }
+ for (long, _) in arg.aliases.iter() {
+ let key = KeyType::Long(long.into());
+ keys.push(Key { key, index });
+ }
+ }
+}
diff --git a/src/osstringext.rs b/src/osstringext.rs
deleted file mode 100644
index ee0de30..0000000
--- a/src/osstringext.rs
+++ /dev/null
@@ -1,200 +0,0 @@
-use std::ffi::OsStr;
-#[cfg(not(any(target_os = "windows", target_arch = "wasm32")))]
-use std::os::unix::ffi::OsStrExt;
-#[cfg(any(target_os = "windows", target_arch = "wasm32"))]
-use INVALID_UTF8;
-
-#[cfg(any(target_os = "windows", target_arch = "wasm32"))]
-pub trait OsStrExt3 {
- fn from_bytes(b: &[u8]) -> &Self;
- fn as_bytes(&self) -> &[u8];
-}
-
-#[doc(hidden)]
-pub trait OsStrExt2 {
- fn starts_with(&self, s: &[u8]) -> bool;
- fn split_at_byte(&self, b: u8) -> (&OsStr, &OsStr);
- fn split_at(&self, i: usize) -> (&OsStr, &OsStr);
- fn trim_left_matches(&self, b: u8) -> &OsStr;
- fn contains_byte(&self, b: u8) -> bool;
- fn split(&self, b: u8) -> OsSplit;
-}
-
-// A starts-with implementation that does not panic when the OsStr contains
-// invalid Unicode.
-//
-// A Windows OsStr is usually UTF-16. If `prefix` is valid UTF-8, we can
-// re-encode it as UTF-16, and ask whether `osstr` starts with the same series
-// of u16 code units. If `prefix` is not valid UTF-8, then this comparison
-// isn't meaningful, and we just return false.
-#[cfg(target_os = "windows")]
-fn windows_osstr_starts_with(osstr: &OsStr, prefix: &[u8]) -> bool {
- use std::os::windows::ffi::OsStrExt;
- let prefix_str = if let Ok(s) = std::str::from_utf8(prefix) {
- s
- } else {
- return false;
- };
- let mut osstr_units = osstr.encode_wide();
- let mut prefix_units = prefix_str.encode_utf16();
- loop {
- match (osstr_units.next(), prefix_units.next()) {
- // These code units match. Keep looping.
- (Some(o), Some(p)) if o == p => continue,
- // We've reached the end of the prefix. It's a match.
- (_, None) => return true,
- // Otherwise, it's not a match.
- _ => return false,
- }
- }
-}
-
-#[test]
-#[cfg(target_os = "windows")]
-fn test_windows_osstr_starts_with() {
- use std::ffi::OsString;
- use std::os::windows::ffi::OsStringExt;
-
- fn from_ascii(ascii: &[u8]) -> OsString {
- let u16_vec: Vec<u16> = ascii.iter().map(|&c| c as u16).collect();
- OsString::from_wide(&u16_vec)
- }
-
- // Test all the basic cases.
- assert!(windows_osstr_starts_with(&from_ascii(b"abcdef"), b"abc"));
- assert!(windows_osstr_starts_with(&from_ascii(b"abcdef"), b"abcdef"));
- assert!(!windows_osstr_starts_with(&from_ascii(b"abcdef"), b"def"));
- assert!(!windows_osstr_starts_with(&from_ascii(b"abc"), b"abcd"));
-
- // Test the case where the candidate prefix is not valid UTF-8. Note that a
- // standalone \xff byte is valid ASCII but not valid UTF-8. Thus although
- // these strings look identical, they do not match.
- assert!(!windows_osstr_starts_with(&from_ascii(b"\xff"), b"\xff"));
-
- // Test the case where the OsString is not valid UTF-16. It should still be
- // possible to match the valid characters at the front.
- //
- // UTF-16 surrogate characters are only valid in pairs. Including one on
- // the end by itself makes this invalid UTF-16.
- let surrogate_char: u16 = 0xDC00;
- let mut invalid_unicode =
- OsString::from_wide(&['a' as u16, 'b' as u16, 'c' as u16, surrogate_char]);
- assert!(
- invalid_unicode.to_str().is_none(),
- "This string is invalid Unicode, and conversion to &str should fail.",
- );
- assert!(windows_osstr_starts_with(&invalid_unicode, b"abc"));
- assert!(!windows_osstr_starts_with(&invalid_unicode, b"abcd"));
-}
-
-#[cfg(any(target_os = "windows", target_arch = "wasm32"))]
-impl OsStrExt3 for OsStr {
- fn from_bytes(b: &[u8]) -> &Self {
- use std::mem;
- unsafe { mem::transmute(b) }
- }
- fn as_bytes(&self) -> &[u8] {
- self.to_str().map(|s| s.as_bytes()).expect(INVALID_UTF8)
- }
-}
-
-impl OsStrExt2 for OsStr {
- fn starts_with(&self, s: &[u8]) -> bool {
- #[cfg(target_os = "windows")]
- {
- // On Windows, the as_bytes() method will panic if the OsStr
- // contains invalid Unicode. To avoid this, we use a
- // Windows-specific starts-with function that doesn't rely on
- // as_bytes(). This is necessary for Windows command line
- // applications to handle non-Unicode arguments successfully. This
- // allows common cases like `clap.exe [invalid]` to succeed, though
- // cases that require string splitting will still fail, like
- // `clap.exe --arg=[invalid]`. Note that this entire module is
- // replaced in Clap 3.x, so this workaround is specific to the 2.x
- // branch.
- return windows_osstr_starts_with(self, s);
- }
- self.as_bytes().starts_with(s)
- }
-
- fn contains_byte(&self, byte: u8) -> bool {
- for b in self.as_bytes() {
- if b == &byte {
- return true;
- }
- }
- false
- }
-
- fn split_at_byte(&self, byte: u8) -> (&OsStr, &OsStr) {
- for (i, b) in self.as_bytes().iter().enumerate() {
- if b == &byte {
- return (
- OsStr::from_bytes(&self.as_bytes()[..i]),
- OsStr::from_bytes(&self.as_bytes()[i + 1..]),
- );
- }
- }
- (
- &*self,
- OsStr::from_bytes(&self.as_bytes()[self.len()..self.len()]),
- )
- }
-
- fn trim_left_matches(&self, byte: u8) -> &OsStr {
- let mut found = false;
- for (i, b) in self.as_bytes().iter().enumerate() {
- if b != &byte {
- return OsStr::from_bytes(&self.as_bytes()[i..]);
- } else {
- found = true;
- }
- }
- if found {
- return OsStr::from_bytes(&self.as_bytes()[self.len()..]);
- }
- &*self
- }
-
- fn split_at(&self, i: usize) -> (&OsStr, &OsStr) {
- (
- OsStr::from_bytes(&self.as_bytes()[..i]),
- OsStr::from_bytes(&self.as_bytes()[i..]),
- )
- }
-
- fn split(&self, b: u8) -> OsSplit {
- OsSplit {
- sep: b,
- val: self.as_bytes(),
- pos: 0,
- }
- }
-}
-
-#[doc(hidden)]
-#[derive(Clone, Debug)]
-pub struct OsSplit<'a> {
- sep: u8,
- val: &'a [u8],
- pos: usize,
-}
-
-impl<'a> Iterator for OsSplit<'a> {
- type Item = &'a OsStr;
-
- fn next(&mut self) -> Option<&'a OsStr> {
- debugln!("OsSplit::next: self={:?}", self);
- if self.pos == self.val.len() {
- return None;
- }
- let start = self.pos;
- for b in &self.val[start..] {
- self.pos += 1;
- if *b == self.sep {
- return Some(OsStr::from_bytes(&self.val[start..self.pos - 1]));
- }
- }
- Some(OsStr::from_bytes(&self.val[start..]))
- }
-}
diff --git a/src/output/fmt.rs b/src/output/fmt.rs
new file mode 100644
index 0000000..b5d0153
--- /dev/null
+++ b/src/output/fmt.rs
@@ -0,0 +1,90 @@
+use crate::builder::StyledStr;
+use crate::util::color::ColorChoice;
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub(crate) enum Stream {
+ Stdout,
+ Stderr,
+}
+
+#[derive(Clone, Debug)]
+pub(crate) struct Colorizer {
+ stream: Stream,
+ #[allow(unused)]
+ color_when: ColorChoice,
+ content: StyledStr,
+}
+
+impl Colorizer {
+ pub(crate) fn new(stream: Stream, color_when: ColorChoice) -> Self {
+ Colorizer {
+ stream,
+ color_when,
+ content: Default::default(),
+ }
+ }
+
+ pub(crate) fn with_content(mut self, content: StyledStr) -> Self {
+ self.content = content;
+ self
+ }
+}
+
+/// Printing methods.
+impl Colorizer {
+ #[cfg(feature = "color")]
+ pub(crate) fn print(&self) -> std::io::Result<()> {
+ use termcolor::{BufferWriter, ColorChoice as DepColorChoice};
+
+ let color_when = match self.color_when {
+ ColorChoice::Always => DepColorChoice::Always,
+ ColorChoice::Auto if is_a_tty(self.stream) => DepColorChoice::Auto,
+ _ => DepColorChoice::Never,
+ };
+
+ let writer = match self.stream {
+ Stream::Stderr => BufferWriter::stderr(color_when),
+ Stream::Stdout => BufferWriter::stdout(color_when),
+ };
+
+ let mut buffer = writer.buffer();
+ ok!(self.content.write_colored(&mut buffer));
+ writer.print(&buffer)
+ }
+
+ #[cfg(not(feature = "color"))]
+ pub(crate) fn print(&self) -> std::io::Result<()> {
+ use std::io::Write;
+
+ // [e]println can't be used here because it panics
+ // if something went wrong. We don't want that.
+ match self.stream {
+ Stream::Stdout => {
+ let stdout = std::io::stdout();
+ let mut stdout = stdout.lock();
+ write!(stdout, "{}", self)
+ }
+ Stream::Stderr => {
+ let stderr = std::io::stderr();
+ let mut stderr = stderr.lock();
+ write!(stderr, "{}", self)
+ }
+ }
+ }
+}
+
+/// Color-unaware printing. Never uses coloring.
+impl std::fmt::Display for Colorizer {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ self.content.fmt(f)
+ }
+}
+
+#[cfg(feature = "color")]
+fn is_a_tty(stream: Stream) -> bool {
+ use is_terminal::IsTerminal;
+ match stream {
+ Stream::Stdout => std::io::stdout().is_terminal(),
+ Stream::Stderr => std::io::stderr().is_terminal(),
+ }
+}
diff --git a/src/output/help.rs b/src/output/help.rs
new file mode 100644
index 0000000..4e4fdbf
--- /dev/null
+++ b/src/output/help.rs
@@ -0,0 +1,43 @@
+#![cfg_attr(not(feature = "help"), allow(unused_variables))]
+
+// Internal
+use crate::builder::Command;
+use crate::builder::StyledStr;
+use crate::output::Usage;
+
+/// Writes the parser help to the wrapped stream.
+pub(crate) fn write_help(writer: &mut StyledStr, cmd: &Command, usage: &Usage<'_>, use_long: bool) {
+ debug!("write_help");
+
+ if let Some(h) = cmd.get_override_help() {
+ writer.extend(h.iter());
+ } else {
+ #[cfg(feature = "help")]
+ {
+ use super::AutoHelp;
+ use super::HelpTemplate;
+ if let Some(tmpl) = cmd.get_help_template() {
+ for (style, content) in tmpl.iter() {
+ if style.is_none() {
+ HelpTemplate::new(writer, cmd, usage, use_long)
+ .write_templated_help(content);
+ } else {
+ writer.stylize(style, content);
+ }
+ }
+ } else {
+ AutoHelp::new(writer, cmd, usage, use_long).write_help();
+ }
+ }
+
+ #[cfg(not(feature = "help"))]
+ {
+ debug!("write_help: no help, `Command::override_help` and `help` is missing");
+ }
+ }
+
+ // Remove any extra lines caused by book keeping
+ writer.trim();
+ // Ensure there is still a trailing newline
+ writer.none("\n");
+}
diff --git a/src/output/help_template.rs b/src/output/help_template.rs
new file mode 100644
index 0000000..4c7adda
--- /dev/null
+++ b/src/output/help_template.rs
@@ -0,0 +1,1065 @@
+// Std
+use std::borrow::Cow;
+use std::cmp;
+use std::usize;
+
+// Internal
+use crate::builder::PossibleValue;
+use crate::builder::Str;
+use crate::builder::StyledStr;
+use crate::builder::{Arg, Command};
+use crate::output::display_width;
+use crate::output::wrap;
+use crate::output::Usage;
+use crate::output::TAB;
+use crate::output::TAB_WIDTH;
+use crate::util::FlatSet;
+
+/// `clap` auto-generated help writer
+pub(crate) struct AutoHelp<'cmd, 'writer> {
+ template: HelpTemplate<'cmd, 'writer>,
+}
+
+// Public Functions
+impl<'cmd, 'writer> AutoHelp<'cmd, 'writer> {
+ /// Create a new `HelpTemplate` instance.
+ pub(crate) fn new(
+ writer: &'writer mut StyledStr,
+ cmd: &'cmd Command,
+ usage: &'cmd Usage<'cmd>,
+ use_long: bool,
+ ) -> Self {
+ Self {
+ template: HelpTemplate::new(writer, cmd, usage, use_long),
+ }
+ }
+
+ pub(crate) fn write_help(&mut self) {
+ let pos = self
+ .template
+ .cmd
+ .get_positionals()
+ .any(|arg| should_show_arg(self.template.use_long, arg));
+ let non_pos = self
+ .template
+ .cmd
+ .get_non_positionals()
+ .any(|arg| should_show_arg(self.template.use_long, arg));
+ let subcmds = self.template.cmd.has_visible_subcommands();
+
+ let template = if non_pos || pos || subcmds {
+ DEFAULT_TEMPLATE
+ } else {
+ DEFAULT_NO_ARGS_TEMPLATE
+ };
+ self.template.write_templated_help(template);
+ }
+}
+
+const DEFAULT_TEMPLATE: &str = "\
+{before-help}{about-with-newline}
+{usage-heading} {usage}
+
+{all-args}{after-help}\
+ ";
+
+const DEFAULT_NO_ARGS_TEMPLATE: &str = "\
+{before-help}{about-with-newline}
+{usage-heading} {usage}{after-help}\
+ ";
+
+/// `clap` HelpTemplate Writer.
+///
+/// Wraps a writer stream providing different methods to generate help for `clap` objects.
+pub(crate) struct HelpTemplate<'cmd, 'writer> {
+ writer: &'writer mut StyledStr,
+ cmd: &'cmd Command,
+ usage: &'cmd Usage<'cmd>,
+ next_line_help: bool,
+ term_w: usize,
+ use_long: bool,
+}
+
+// Public Functions
+impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
+ /// Create a new `HelpTemplate` instance.
+ pub(crate) fn new(
+ writer: &'writer mut StyledStr,
+ cmd: &'cmd Command,
+ usage: &'cmd Usage<'cmd>,
+ use_long: bool,
+ ) -> Self {
+ debug!(
+ "HelpTemplate::new cmd={}, use_long={}",
+ cmd.get_name(),
+ use_long
+ );
+ let term_w = match cmd.get_term_width() {
+ Some(0) => usize::MAX,
+ Some(w) => w,
+ None => {
+ let (current_width, _h) = dimensions();
+ let current_width = current_width.unwrap_or(100);
+ let max_width = match cmd.get_max_term_width() {
+ None | Some(0) => usize::MAX,
+ Some(mw) => mw,
+ };
+ cmp::min(current_width, max_width)
+ }
+ };
+ let next_line_help = cmd.is_next_line_help_set();
+
+ HelpTemplate {
+ writer,
+ cmd,
+ usage,
+ next_line_help,
+ term_w,
+ use_long,
+ }
+ }
+
+ /// Write help to stream for the parser in the format defined by the template.
+ ///
+ /// For details about the template language see [`Command::help_template`].
+ ///
+ /// [`Command::help_template`]: Command::help_template()
+ pub(crate) fn write_templated_help(&mut self, template: &str) {
+ debug!("HelpTemplate::write_templated_help");
+
+ let mut parts = template.split('{');
+ if let Some(first) = parts.next() {
+ self.none(first);
+ }
+ for part in parts {
+ if let Some((tag, rest)) = part.split_once('}') {
+ match tag {
+ "name" => {
+ self.write_display_name();
+ }
+ #[cfg(not(feature = "unstable-v5"))]
+ "bin" => {
+ self.write_bin_name();
+ }
+ "version" => {
+ self.write_version();
+ }
+ "author" => {
+ self.write_author(false, false);
+ }
+ "author-with-newline" => {
+ self.write_author(false, true);
+ }
+ "author-section" => {
+ self.write_author(true, true);
+ }
+ "about" => {
+ self.write_about(false, false);
+ }
+ "about-with-newline" => {
+ self.write_about(false, true);
+ }
+ "about-section" => {
+ self.write_about(true, true);
+ }
+ "usage-heading" => {
+ self.header("Usage:");
+ }
+ "usage" => {
+ self.writer.extend(
+ self.usage
+ .create_usage_no_title(&[])
+ .unwrap_or_default()
+ .into_iter(),
+ );
+ }
+ "all-args" => {
+ self.write_all_args();
+ }
+ "options" => {
+ // Include even those with a heading as we don't have a good way of
+ // handling help_heading in the template.
+ self.write_args(
+ &self.cmd.get_non_positionals().collect::<Vec<_>>(),
+ "options",
+ option_sort_key,
+ );
+ }
+ "positionals" => {
+ self.write_args(
+ &self.cmd.get_positionals().collect::<Vec<_>>(),
+ "positionals",
+ positional_sort_key,
+ );
+ }
+ "subcommands" => {
+ self.write_subcommands(self.cmd);
+ }
+ "tab" => {
+ self.none(TAB);
+ }
+ "after-help" => {
+ self.write_after_help();
+ }
+ "before-help" => {
+ self.write_before_help();
+ }
+ _ => {
+ self.none("{");
+ self.none(tag);
+ self.none("}");
+ }
+ }
+ self.none(rest);
+ }
+ }
+ }
+}
+
+/// Basic template methods
+impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
+ /// Writes binary name of a Parser Object to the wrapped stream.
+ fn write_display_name(&mut self) {
+ debug!("HelpTemplate::write_display_name");
+
+ let display_name = wrap(
+ &self
+ .cmd
+ .get_display_name()
+ .unwrap_or_else(|| self.cmd.get_name())
+ .replace("{n}", "\n"),
+ self.term_w,
+ );
+ self.none(&display_name);
+ }
+
+ /// Writes binary name of a Parser Object to the wrapped stream.
+ fn write_bin_name(&mut self) {
+ debug!("HelpTemplate::write_bin_name");
+
+ let bin_name = if let Some(bn) = self.cmd.get_bin_name() {
+ if bn.contains(' ') {
+ // In case we're dealing with subcommands i.e. git mv is translated to git-mv
+ bn.replace(' ', "-")
+ } else {
+ wrap(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
+ }
+ } else {
+ wrap(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
+ };
+ self.none(&bin_name);
+ }
+
+ fn write_version(&mut self) {
+ let version = self
+ .cmd
+ .get_version()
+ .or_else(|| self.cmd.get_long_version());
+ if let Some(output) = version {
+ self.none(wrap(output, self.term_w));
+ }
+ }
+
+ fn write_author(&mut self, before_new_line: bool, after_new_line: bool) {
+ if let Some(author) = self.cmd.get_author() {
+ if before_new_line {
+ self.none("\n");
+ }
+ self.none(wrap(author, self.term_w));
+ if after_new_line {
+ self.none("\n");
+ }
+ }
+ }
+
+ fn write_about(&mut self, before_new_line: bool, after_new_line: bool) {
+ let about = if self.use_long {
+ self.cmd.get_long_about().or_else(|| self.cmd.get_about())
+ } else {
+ self.cmd.get_about()
+ };
+ if let Some(output) = about {
+ if before_new_line {
+ self.none("\n");
+ }
+ let mut output = output.clone();
+ replace_newline_var(&mut output);
+ output.wrap(self.term_w);
+ self.writer.extend(output.into_iter());
+ if after_new_line {
+ self.none("\n");
+ }
+ }
+ }
+
+ fn write_before_help(&mut self) {
+ debug!("HelpTemplate::write_before_help");
+ let before_help = if self.use_long {
+ self.cmd
+ .get_before_long_help()
+ .or_else(|| self.cmd.get_before_help())
+ } else {
+ self.cmd.get_before_help()
+ };
+ if let Some(output) = before_help {
+ let mut output = output.clone();
+ replace_newline_var(&mut output);
+ output.wrap(self.term_w);
+ self.writer.extend(output.into_iter());
+ self.none("\n\n");
+ }
+ }
+
+ fn write_after_help(&mut self) {
+ debug!("HelpTemplate::write_after_help");
+ let after_help = if self.use_long {
+ self.cmd
+ .get_after_long_help()
+ .or_else(|| self.cmd.get_after_help())
+ } else {
+ self.cmd.get_after_help()
+ };
+ if let Some(output) = after_help {
+ self.none("\n\n");
+ let mut output = output.clone();
+ replace_newline_var(&mut output);
+ output.wrap(self.term_w);
+ self.writer.extend(output.into_iter());
+ }
+ }
+}
+
+/// Arg handling
+impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
+ /// Writes help for all arguments (options, flags, args, subcommands)
+ /// including titles of a Parser Object to the wrapped stream.
+ pub(crate) fn write_all_args(&mut self) {
+ debug!("HelpTemplate::write_all_args");
+ let pos = self
+ .cmd
+ .get_positionals()
+ .filter(|a| a.get_help_heading().is_none())
+ .filter(|arg| should_show_arg(self.use_long, arg))
+ .collect::<Vec<_>>();
+ let non_pos = self
+ .cmd
+ .get_non_positionals()
+ .filter(|a| a.get_help_heading().is_none())
+ .filter(|arg| should_show_arg(self.use_long, arg))
+ .collect::<Vec<_>>();
+ let subcmds = self.cmd.has_visible_subcommands();
+
+ let custom_headings = self
+ .cmd
+ .get_arguments()
+ .filter_map(|arg| arg.get_help_heading())
+ .collect::<FlatSet<_>>();
+
+ let mut first = true;
+
+ if subcmds {
+ if !first {
+ self.none("\n\n");
+ }
+ first = false;
+ let default_help_heading = Str::from("Commands");
+ self.header(
+ self.cmd
+ .get_subcommand_help_heading()
+ .unwrap_or(&default_help_heading),
+ );
+ self.header(":\n");
+
+ self.write_subcommands(self.cmd);
+ }
+
+ if !pos.is_empty() {
+ if !first {
+ self.none("\n\n");
+ }
+ first = false;
+ // Write positional args if any
+ self.header("Arguments:\n");
+ self.write_args(&pos, "Arguments", positional_sort_key);
+ }
+
+ if !non_pos.is_empty() {
+ if !first {
+ self.none("\n\n");
+ }
+ first = false;
+ self.header("Options:\n");
+ self.write_args(&non_pos, "Options", option_sort_key);
+ }
+ if !custom_headings.is_empty() {
+ for heading in custom_headings {
+ let args = self
+ .cmd
+ .get_arguments()
+ .filter(|a| {
+ if let Some(help_heading) = a.get_help_heading() {
+ return help_heading == heading;
+ }
+ false
+ })
+ .filter(|arg| should_show_arg(self.use_long, arg))
+ .collect::<Vec<_>>();
+
+ if !args.is_empty() {
+ if !first {
+ self.none("\n\n");
+ }
+ first = false;
+ self.header(format!("{heading}:\n"));
+ self.write_args(&args, heading, option_sort_key);
+ }
+ }
+ }
+ }
+ /// Sorts arguments by length and display order and write their help to the wrapped stream.
+ fn write_args(&mut self, args: &[&Arg], _category: &str, sort_key: ArgSortKey) {
+ debug!("HelpTemplate::write_args {}", _category);
+ // The shortest an arg can legally be is 2 (i.e. '-x')
+ let mut longest = 2;
+ let mut ord_v = Vec::new();
+
+ // Determine the longest
+ for &arg in args.iter().filter(|arg| {
+ // If it's NextLineHelp we don't care to compute how long it is because it may be
+ // NextLineHelp on purpose simply *because* it's so long and would throw off all other
+ // args alignment
+ should_show_arg(self.use_long, arg)
+ }) {
+ if longest_filter(arg) {
+ longest = longest.max(display_width(&arg.to_string()));
+ debug!(
+ "HelpTemplate::write_args: arg={:?} longest={}",
+ arg.get_id(),
+ longest
+ );
+ }
+
+ let key = (sort_key)(arg);
+ ord_v.push((key, arg));
+ }
+ ord_v.sort_by(|a, b| a.0.cmp(&b.0));
+
+ let next_line_help = self.will_args_wrap(args, longest);
+
+ for (i, (_, arg)) in ord_v.iter().enumerate() {
+ if i != 0 {
+ self.none("\n");
+ if next_line_help && self.use_long {
+ self.none("\n");
+ }
+ }
+ self.write_arg(arg, next_line_help, longest);
+ }
+ }
+
+ /// Writes help for an argument to the wrapped stream.
+ fn write_arg(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
+ let spec_vals = &self.spec_vals(arg);
+
+ self.none(TAB);
+ self.short(arg);
+ self.long(arg);
+ self.writer.extend(arg.stylize_arg_suffix(None).into_iter());
+ self.align_to_about(arg, next_line_help, longest);
+
+ let about = if self.use_long {
+ arg.get_long_help()
+ .or_else(|| arg.get_help())
+ .unwrap_or_default()
+ } else {
+ arg.get_help()
+ .or_else(|| arg.get_long_help())
+ .unwrap_or_default()
+ };
+
+ self.help(Some(arg), about, spec_vals, next_line_help, longest);
+ }
+
+ /// Writes argument's short command to the wrapped stream.
+ fn short(&mut self, arg: &Arg) {
+ debug!("HelpTemplate::short");
+
+ if let Some(s) = arg.get_short() {
+ self.literal(format!("-{s}"));
+ } else if arg.get_long().is_some() {
+ self.none(" ");
+ }
+ }
+
+ /// Writes argument's long command to the wrapped stream.
+ fn long(&mut self, arg: &Arg) {
+ debug!("HelpTemplate::long");
+ if let Some(long) = arg.get_long() {
+ if arg.get_short().is_some() {
+ self.none(", ");
+ }
+ self.literal(format!("--{long}"));
+ }
+ }
+
+ /// Write alignment padding between arg's switches/values and its about message.
+ fn align_to_about(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
+ debug!(
+ "HelpTemplate::align_to_about: arg={}, next_line_help={}, longest={}",
+ arg.get_id(),
+ next_line_help,
+ longest
+ );
+ if self.use_long || next_line_help {
+ // long help prints messages on the next line so it doesn't need to align text
+ debug!("HelpTemplate::align_to_about: printing long help so skip alignment");
+ } else if !arg.is_positional() {
+ let self_len = display_width(&arg.to_string());
+ // Since we're writing spaces from the tab point we first need to know if we
+ // had a long and short, or just short
+ let padding = if arg.get_long().is_some() {
+ // Only account 4 after the val
+ TAB_WIDTH
+ } else {
+ // Only account for ', --' + 4 after the val
+ TAB_WIDTH + 4
+ };
+ let spcs = longest + padding - self_len;
+ debug!(
+ "HelpTemplate::align_to_about: positional=false arg_len={}, spaces={}",
+ self_len, spcs
+ );
+
+ self.spaces(spcs);
+ } else {
+ let self_len = display_width(&arg.to_string());
+ let padding = TAB_WIDTH;
+ let spcs = longest + padding - self_len;
+ debug!(
+ "HelpTemplate::align_to_about: positional=true arg_len={}, spaces={}",
+ self_len, spcs
+ );
+
+ self.spaces(spcs);
+ }
+ }
+
+ /// Writes argument's help to the wrapped stream.
+ fn help(
+ &mut self,
+ arg: Option<&Arg>,
+ about: &StyledStr,
+ spec_vals: &str,
+ next_line_help: bool,
+ longest: usize,
+ ) {
+ debug!("HelpTemplate::help");
+
+ // Is help on next line, if so then indent
+ if next_line_help {
+ debug!("HelpTemplate::help: Next Line...{:?}", next_line_help);
+ self.none("\n");
+ self.none(TAB);
+ self.none(NEXT_LINE_INDENT);
+ }
+
+ let spaces = if next_line_help {
+ TAB.len() + NEXT_LINE_INDENT.len()
+ } else if let Some(true) = arg.map(|a| a.is_positional()) {
+ longest + TAB_WIDTH * 2
+ } else {
+ longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
+ };
+ let trailing_indent = spaces; // Don't indent any further than the first line is indented
+ let trailing_indent = self.get_spaces(trailing_indent);
+
+ let mut help = about.clone();
+ replace_newline_var(&mut help);
+ if !spec_vals.is_empty() {
+ if !help.is_empty() {
+ let sep = if self.use_long && arg.is_some() {
+ "\n\n"
+ } else {
+ " "
+ };
+ help.none(sep);
+ }
+ help.none(spec_vals);
+ }
+ let avail_chars = self.term_w.saturating_sub(spaces);
+ debug!(
+ "HelpTemplate::help: help_width={}, spaces={}, avail={}",
+ spaces,
+ help.display_width(),
+ avail_chars
+ );
+ help.wrap(avail_chars);
+ help.indent("", &trailing_indent);
+ let help_is_empty = help.is_empty();
+ self.writer.extend(help.into_iter());
+ if let Some(arg) = arg {
+ const DASH_SPACE: usize = "- ".len();
+ const COLON_SPACE: usize = ": ".len();
+ let possible_vals = arg.get_possible_values();
+ if self.use_long
+ && !arg.is_hide_possible_values_set()
+ && possible_vals.iter().any(PossibleValue::should_show_help)
+ {
+ debug!(
+ "HelpTemplate::help: Found possible vals...{:?}",
+ possible_vals
+ );
+ if !help_is_empty {
+ self.none("\n\n");
+ self.spaces(spaces);
+ }
+ self.none("Possible values:");
+ let longest = possible_vals
+ .iter()
+ .filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name)))
+ .max()
+ .expect("Only called with possible value");
+ let help_longest = possible_vals
+ .iter()
+ .filter_map(|f| f.get_visible_help().map(|h| h.display_width()))
+ .max()
+ .expect("Only called with possible value with help");
+ // should new line
+ let taken = longest + spaces + DASH_SPACE;
+
+ let possible_value_new_line =
+ self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest;
+
+ let spaces = spaces + TAB_WIDTH - DASH_SPACE;
+ let trailing_indent = if possible_value_new_line {
+ spaces + DASH_SPACE
+ } else {
+ spaces + longest + DASH_SPACE + COLON_SPACE
+ };
+ let trailing_indent = self.get_spaces(trailing_indent);
+
+ for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
+ self.none("\n");
+ self.spaces(spaces);
+ self.none("- ");
+ self.literal(pv.get_name());
+ if let Some(help) = pv.get_help() {
+ debug!("HelpTemplate::help: Possible Value help");
+
+ if possible_value_new_line {
+ self.none(":\n");
+ self.spaces(trailing_indent.len());
+ } else {
+ self.none(": ");
+ // To align help messages
+ self.spaces(longest - display_width(pv.get_name()));
+ }
+
+ let avail_chars = if self.term_w > trailing_indent.len() {
+ self.term_w - trailing_indent.len()
+ } else {
+ usize::MAX
+ };
+
+ let mut help = help.clone();
+ replace_newline_var(&mut help);
+ help.wrap(avail_chars);
+ help.indent("", &trailing_indent);
+ self.writer.extend(help.into_iter());
+ }
+ }
+ }
+ }
+ }
+
+ /// Will use next line help on writing args.
+ fn will_args_wrap(&self, args: &[&Arg], longest: usize) -> bool {
+ args.iter()
+ .filter(|arg| should_show_arg(self.use_long, arg))
+ .any(|arg| {
+ let spec_vals = &self.spec_vals(arg);
+ self.arg_next_line_help(arg, spec_vals, longest)
+ })
+ }
+
+ fn arg_next_line_help(&self, arg: &Arg, spec_vals: &str, longest: usize) -> bool {
+ if self.next_line_help || arg.is_next_line_help_set() || self.use_long {
+ // setting_next_line
+ true
+ } else {
+ // force_next_line
+ let h = arg.get_help().unwrap_or_default();
+ let h_w = h.display_width() + display_width(spec_vals);
+ let taken = if arg.is_positional() {
+ longest + TAB_WIDTH * 2
+ } else {
+ longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
+ };
+ self.term_w >= taken
+ && (taken as f32 / self.term_w as f32) > 0.40
+ && h_w > (self.term_w - taken)
+ }
+ }
+
+ fn spec_vals(&self, a: &Arg) -> String {
+ debug!("HelpTemplate::spec_vals: a={}", a);
+ let mut spec_vals = Vec::new();
+ #[cfg(feature = "env")]
+ if let Some(ref env) = a.env {
+ if !a.is_hide_env_set() {
+ debug!(
+ "HelpTemplate::spec_vals: Found environment variable...[{:?}:{:?}]",
+ env.0, env.1
+ );
+ let env_val = if !a.is_hide_env_values_set() {
+ format!(
+ "={}",
+ env.1
+ .as_ref()
+ .map(|s| s.to_string_lossy())
+ .unwrap_or_default()
+ )
+ } else {
+ Default::default()
+ };
+ let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val);
+ spec_vals.push(env_info);
+ }
+ }
+ if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() {
+ debug!(
+ "HelpTemplate::spec_vals: Found default value...[{:?}]",
+ a.default_vals
+ );
+
+ let pvs = a
+ .default_vals
+ .iter()
+ .map(|pvs| pvs.to_string_lossy())
+ .map(|pvs| {
+ if pvs.contains(char::is_whitespace) {
+ Cow::from(format!("{pvs:?}"))
+ } else {
+ pvs
+ }
+ })
+ .collect::<Vec<_>>()
+ .join(" ");
+
+ spec_vals.push(format!("[default: {pvs}]"));
+ }
+
+ let als = a
+ .aliases
+ .iter()
+ .filter(|&als| als.1) // visible
+ .map(|als| als.0.as_str()) // name
+ .collect::<Vec<_>>()
+ .join(", ");
+ if !als.is_empty() {
+ debug!("HelpTemplate::spec_vals: Found aliases...{:?}", a.aliases);
+ spec_vals.push(format!("[aliases: {als}]"));
+ }
+
+ let als = a
+ .short_aliases
+ .iter()
+ .filter(|&als| als.1) // visible
+ .map(|&als| als.0.to_string()) // name
+ .collect::<Vec<_>>()
+ .join(", ");
+ if !als.is_empty() {
+ debug!(
+ "HelpTemplate::spec_vals: Found short aliases...{:?}",
+ a.short_aliases
+ );
+ spec_vals.push(format!("[short aliases: {als}]"));
+ }
+
+ let possible_vals = a.get_possible_values();
+ if !(a.is_hide_possible_values_set()
+ || possible_vals.is_empty()
+ || self.use_long && possible_vals.iter().any(PossibleValue::should_show_help))
+ {
+ debug!(
+ "HelpTemplate::spec_vals: Found possible vals...{:?}",
+ possible_vals
+ );
+
+ let pvs = possible_vals
+ .iter()
+ .filter_map(PossibleValue::get_visible_quoted_name)
+ .collect::<Vec<_>>()
+ .join(", ");
+
+ spec_vals.push(format!("[possible values: {pvs}]"));
+ }
+ let connector = if self.use_long { "\n" } else { " " };
+ spec_vals.join(connector)
+ }
+
+ fn header<T: Into<String>>(&mut self, msg: T) {
+ self.writer.header(msg);
+ }
+
+ fn literal<T: Into<String>>(&mut self, msg: T) {
+ self.writer.literal(msg);
+ }
+
+ fn none<T: Into<String>>(&mut self, msg: T) {
+ self.writer.none(msg);
+ }
+
+ fn get_spaces(&self, n: usize) -> String {
+ " ".repeat(n)
+ }
+
+ fn spaces(&mut self, n: usize) {
+ self.none(self.get_spaces(n));
+ }
+}
+
+/// Subcommand handling
+impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
+ /// Writes help for subcommands of a Parser Object to the wrapped stream.
+ fn write_subcommands(&mut self, cmd: &Command) {
+ debug!("HelpTemplate::write_subcommands");
+ // The shortest an arg can legally be is 2 (i.e. '-x')
+ let mut longest = 2;
+ let mut ord_v = Vec::new();
+ for subcommand in cmd
+ .get_subcommands()
+ .filter(|subcommand| should_show_subcommand(subcommand))
+ {
+ let mut styled = StyledStr::new();
+ styled.literal(subcommand.get_name());
+ if let Some(short) = subcommand.get_short_flag() {
+ styled.none(", ");
+ styled.literal(format!("-{short}"));
+ }
+ if let Some(long) = subcommand.get_long_flag() {
+ styled.none(", ");
+ styled.literal(format!("--{long}"));
+ }
+ longest = longest.max(styled.display_width());
+ ord_v.push((subcommand.get_display_order(), styled, subcommand));
+ }
+ ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));
+
+ debug!("HelpTemplate::write_subcommands longest = {}", longest);
+
+ let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest);
+
+ let mut first = true;
+ for (_, sc_str, sc) in ord_v {
+ if first {
+ first = false;
+ } else {
+ self.none("\n");
+ }
+ self.write_subcommand(sc_str, sc, next_line_help, longest);
+ }
+ }
+
+ /// Will use next line help on writing subcommands.
+ fn will_subcommands_wrap<'a>(
+ &self,
+ subcommands: impl IntoIterator<Item = &'a Command>,
+ longest: usize,
+ ) -> bool {
+ subcommands
+ .into_iter()
+ .filter(|&subcommand| should_show_subcommand(subcommand))
+ .any(|subcommand| {
+ let spec_vals = &self.sc_spec_vals(subcommand);
+ self.subcommand_next_line_help(subcommand, spec_vals, longest)
+ })
+ }
+
+ fn write_subcommand(
+ &mut self,
+ sc_str: StyledStr,
+ cmd: &Command,
+ next_line_help: bool,
+ longest: usize,
+ ) {
+ debug!("HelpTemplate::write_subcommand");
+
+ let spec_vals = &self.sc_spec_vals(cmd);
+
+ let about = cmd
+ .get_about()
+ .or_else(|| cmd.get_long_about())
+ .unwrap_or_default();
+
+ self.subcmd(sc_str, next_line_help, longest);
+ self.help(None, about, spec_vals, next_line_help, longest)
+ }
+
+ fn sc_spec_vals(&self, a: &Command) -> String {
+ debug!("HelpTemplate::sc_spec_vals: a={}", a.get_name());
+ let mut spec_vals = vec![];
+
+ let mut short_als = a
+ .get_visible_short_flag_aliases()
+ .map(|a| format!("-{a}"))
+ .collect::<Vec<_>>();
+ let als = a.get_visible_aliases().map(|s| s.to_string());
+ short_als.extend(als);
+ let all_als = short_als.join(", ");
+ if !all_als.is_empty() {
+ debug!(
+ "HelpTemplate::spec_vals: Found aliases...{:?}",
+ a.get_all_aliases().collect::<Vec<_>>()
+ );
+ debug!(
+ "HelpTemplate::spec_vals: Found short flag aliases...{:?}",
+ a.get_all_short_flag_aliases().collect::<Vec<_>>()
+ );
+ spec_vals.push(format!("[aliases: {all_als}]"));
+ }
+
+ spec_vals.join(" ")
+ }
+
+ fn subcommand_next_line_help(&self, cmd: &Command, spec_vals: &str, longest: usize) -> bool {
+ if self.next_line_help | self.use_long {
+ // setting_next_line
+ true
+ } else {
+ // force_next_line
+ let h = cmd.get_about().unwrap_or_default();
+ let h_w = h.display_width() + display_width(spec_vals);
+ let taken = longest + TAB_WIDTH * 2;
+ self.term_w >= taken
+ && (taken as f32 / self.term_w as f32) > 0.40
+ && h_w > (self.term_w - taken)
+ }
+ }
+
+ /// Writes subcommand to the wrapped stream.
+ fn subcmd(&mut self, sc_str: StyledStr, next_line_help: bool, longest: usize) {
+ let width = sc_str.display_width();
+
+ self.none(TAB);
+ self.writer.extend(sc_str.into_iter());
+ if !next_line_help {
+ self.spaces(longest + TAB_WIDTH - width);
+ }
+ }
+}
+
+const NEXT_LINE_INDENT: &str = " ";
+
+type ArgSortKey = fn(arg: &Arg) -> (usize, String);
+
+fn positional_sort_key(arg: &Arg) -> (usize, String) {
+ (arg.get_index().unwrap_or(0), String::new())
+}
+
+fn option_sort_key(arg: &Arg) -> (usize, String) {
+ // Formatting key like this to ensure that:
+ // 1. Argument has long flags are printed just after short flags.
+ // 2. For two args both have short flags like `-c` and `-C`, the
+ // `-C` arg is printed just after the `-c` arg
+ // 3. For args without short or long flag, print them at last(sorted
+ // by arg name).
+ // Example order: -a, -b, -B, -s, --select-file, --select-folder, -x
+
+ let key = if let Some(x) = arg.get_short() {
+ let mut s = x.to_ascii_lowercase().to_string();
+ s.push(if x.is_ascii_lowercase() { '0' } else { '1' });
+ s
+ } else if let Some(x) = arg.get_long() {
+ x.to_string()
+ } else {
+ let mut s = '{'.to_string();
+ s.push_str(arg.get_id().as_str());
+ s
+ };
+ (arg.get_display_order(), key)
+}
+
+pub(crate) fn dimensions() -> (Option<usize>, Option<usize>) {
+ #[cfg(not(feature = "wrap_help"))]
+ return (None, None);
+
+ #[cfg(feature = "wrap_help")]
+ terminal_size::terminal_size()
+ .map(|(w, h)| (Some(w.0.into()), Some(h.0.into())))
+ .unwrap_or_else(|| (parse_env("COLUMNS"), parse_env("LINES")))
+}
+
+#[cfg(feature = "wrap_help")]
+fn parse_env(var: &str) -> Option<usize> {
+ some!(some!(std::env::var_os(var)).to_str())
+ .parse::<usize>()
+ .ok()
+}
+
+fn should_show_arg(use_long: bool, arg: &Arg) -> bool {
+ debug!(
+ "should_show_arg: use_long={:?}, arg={}",
+ use_long,
+ arg.get_id()
+ );
+ if arg.is_hide_set() {
+ return false;
+ }
+ (!arg.is_hide_long_help_set() && use_long)
+ || (!arg.is_hide_short_help_set() && !use_long)
+ || arg.is_next_line_help_set()
+}
+
+fn should_show_subcommand(subcommand: &Command) -> bool {
+ !subcommand.is_hide_set()
+}
+
+fn replace_newline_var(styled: &mut StyledStr) {
+ for (_, content) in styled.iter_mut() {
+ *content = content.replace("{n}", "\n");
+ }
+}
+
+fn longest_filter(arg: &Arg) -> bool {
+ arg.is_takes_value_set() || arg.get_long().is_some() || arg.get_short().is_none()
+}
+
+#[cfg(test)]
+mod test {
+ #[test]
+ #[cfg(feature = "wrap_help")]
+ fn wrap_help_last_word() {
+ use super::*;
+
+ let help = String::from("foo bar baz");
+ assert_eq!(wrap(&help, 5), "foo\nbar\nbaz");
+ }
+
+ #[test]
+ #[cfg(feature = "unicode")]
+ fn display_width_handles_non_ascii() {
+ use super::*;
+
+ // Popular Danish tongue-twister, the name of a fruit dessert.
+ let text = "rødgrød med fløde";
+ assert_eq!(display_width(text), 17);
+ // Note that the string width is smaller than the string
+ // length. This is due to the precomposed non-ASCII letters:
+ assert_eq!(text.len(), 20);
+ }
+
+ #[test]
+ #[cfg(feature = "unicode")]
+ fn display_width_handles_emojis() {
+ use super::*;
+
+ let text = "😂";
+ // There is a single `char`...
+ assert_eq!(text.chars().count(), 1);
+ // but it is double-width:
+ assert_eq!(display_width(text), 2);
+ // This is much less than the byte length:
+ assert_eq!(text.len(), 4);
+ }
+}
diff --git a/src/output/mod.rs b/src/output/mod.rs
new file mode 100644
index 0000000..b358711
--- /dev/null
+++ b/src/output/mod.rs
@@ -0,0 +1,23 @@
+mod help;
+#[cfg(feature = "help")]
+mod help_template;
+mod usage;
+
+pub(crate) mod fmt;
+#[cfg(feature = "help")]
+pub(crate) mod textwrap;
+
+pub(crate) use self::help::write_help;
+#[cfg(feature = "help")]
+pub(crate) use self::help_template::AutoHelp;
+#[cfg(feature = "help")]
+pub(crate) use self::help_template::HelpTemplate;
+#[cfg(feature = "help")]
+pub(crate) use self::textwrap::core::display_width;
+#[cfg(feature = "help")]
+pub(crate) use self::textwrap::wrap;
+pub(crate) use self::usage::Usage;
+
+pub(crate) const TAB: &str = " ";
+#[cfg(feature = "help")]
+pub(crate) const TAB_WIDTH: usize = TAB.len();
diff --git a/src/output/textwrap/core.rs b/src/output/textwrap/core.rs
new file mode 100644
index 0000000..25c9eb6
--- /dev/null
+++ b/src/output/textwrap/core.rs
@@ -0,0 +1,158 @@
+/// Compute the display width of `text`
+///
+/// # Examples
+///
+/// **Note:** When the `unicode` Cargo feature is disabled, all characters are presumed to take up
+/// 1 width. With the feature enabled, function will correctly deal with [combining characters] in
+/// their decomposed form (see [Unicode equivalence]).
+///
+/// An example of a decomposed character is “é”, which can be decomposed into: “e” followed by a
+/// combining acute accent: “◌́”. Without the `unicode` Cargo feature, every `char` has a width of
+/// 1. This includes the combining accent:
+///
+/// ## Emojis and CJK Characters
+///
+/// Characters such as emojis and [CJK characters] used in the
+/// Chinese, Japanese, and Korean languages are seen as double-width,
+/// even if the `unicode-width` feature is disabled:
+///
+/// # Limitations
+///
+/// The displayed width of a string cannot always be computed from the
+/// string alone. This is because the width depends on the rendering
+/// engine used. This is particularly visible with [emoji modifier
+/// sequences] where a base emoji is modified with, e.g., skin tone or
+/// hair color modifiers. It is up to the rendering engine to detect
+/// this and to produce a suitable emoji.
+///
+/// A simple example is “❤️”, which consists of “❤” (U+2764: Black
+/// Heart Symbol) followed by U+FE0F (Variation Selector-16). By
+/// itself, “❤” is a black heart, but if you follow it with the
+/// variant selector, you may get a wider red heart.
+///
+/// A more complex example would be “👨‍🦰” which should depict a man
+/// with red hair. Here the computed width is too large — and the
+/// width differs depending on the use of the `unicode-width` feature:
+///
+/// This happens because the grapheme consists of three code points:
+/// “👨” (U+1F468: Man), Zero Width Joiner (U+200D), and “🦰”
+/// (U+1F9B0: Red Hair). You can see them above in the test. With
+/// `unicode-width` enabled, the ZWJ is correctly seen as having zero
+/// width, without it is counted as a double-width character.
+///
+/// ## Terminal Support
+///
+/// Modern browsers typically do a great job at combining characters
+/// as shown above, but terminals often struggle more. As an example,
+/// Gnome Terminal version 3.38.1, shows “❤️” as a big red heart, but
+/// shows "👨‍🦰" as “👨🦰”.
+///
+/// [combining characters]: https://en.wikipedia.org/wiki/Combining_character
+/// [Unicode equivalence]: https://en.wikipedia.org/wiki/Unicode_equivalence
+/// [CJK characters]: https://en.wikipedia.org/wiki/CJK_characters
+/// [emoji modifier sequences]: https://unicode.org/emoji/charts/full-emoji-modifiers.html
+#[inline(never)]
+pub(crate) fn display_width(text: &str) -> usize {
+ let mut width = 0;
+
+ let mut control_sequence = false;
+ let control_terminate: char = 'm';
+
+ for ch in text.chars() {
+ if ch.is_ascii_control() {
+ control_sequence = true;
+ } else if control_sequence && ch == control_terminate {
+ control_sequence = false;
+ continue;
+ }
+
+ if !control_sequence {
+ width += ch_width(ch);
+ }
+ }
+ width
+}
+
+#[cfg(feature = "unicode")]
+fn ch_width(ch: char) -> usize {
+ unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0)
+}
+
+#[cfg(not(feature = "unicode"))]
+fn ch_width(_: char) -> usize {
+ 1
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[cfg(feature = "unicode")]
+ use unicode_width::UnicodeWidthChar;
+
+ #[test]
+ fn emojis_have_correct_width() {
+ use unic_emoji_char::is_emoji;
+
+ // Emojis in the Basic Latin (ASCII) and Latin-1 Supplement
+ // blocks all have a width of 1 column. This includes
+ // characters such as '#' and '©'.
+ for ch in '\u{1}'..'\u{FF}' {
+ if is_emoji(ch) {
+ let desc = format!("{:?} U+{:04X}", ch, ch as u32);
+
+ #[cfg(feature = "unicode")]
+ assert_eq!(ch.width().unwrap(), 1, "char: {}", desc);
+
+ #[cfg(not(feature = "unicode"))]
+ assert_eq!(ch_width(ch), 1, "char: {desc}");
+ }
+ }
+
+ // Emojis in the remaining blocks of the Basic Multilingual
+ // Plane (BMP), in the Supplementary Multilingual Plane (SMP),
+ // and in the Supplementary Ideographic Plane (SIP), are all 1
+ // or 2 columns wide when unicode-width is used, and always 2
+ // columns wide otherwise. This includes all of our favorite
+ // emojis such as 😊.
+ for ch in '\u{FF}'..'\u{2FFFF}' {
+ if is_emoji(ch) {
+ let desc = format!("{:?} U+{:04X}", ch, ch as u32);
+
+ #[cfg(feature = "unicode")]
+ assert!(ch.width().unwrap() <= 2, "char: {}", desc);
+
+ #[cfg(not(feature = "unicode"))]
+ assert_eq!(ch_width(ch), 1, "char: {desc}");
+ }
+ }
+
+ // The remaining planes contain almost no assigned code points
+ // and thus also no emojis.
+ }
+
+ #[test]
+ #[cfg(feature = "unicode")]
+ fn display_width_works() {
+ assert_eq!("Café Plain".len(), 11); // “é” is two bytes
+ assert_eq!(display_width("Café Plain"), 10);
+ }
+
+ #[test]
+ #[cfg(feature = "unicode")]
+ fn display_width_narrow_emojis() {
+ assert_eq!(display_width("⁉"), 1);
+ }
+
+ #[test]
+ #[cfg(feature = "unicode")]
+ fn display_width_narrow_emojis_variant_selector() {
+ assert_eq!(display_width("⁉\u{fe0f}"), 1);
+ }
+
+ #[test]
+ #[cfg(feature = "unicode")]
+ fn display_width_emojis() {
+ assert_eq!(display_width("😂😭🥺🤣✨😍🙏🥰😊🔥"), 20);
+ }
+}
diff --git a/src/output/textwrap/mod.rs b/src/output/textwrap/mod.rs
new file mode 100644
index 0000000..d14d3fe
--- /dev/null
+++ b/src/output/textwrap/mod.rs
@@ -0,0 +1,122 @@
+//! Fork of `textwrap` crate
+//!
+//! Benefits of forking:
+//! - Pull in only what we need rather than relying on the compiler to remove what we don't need
+//! - `LineWrapper` is able to incrementally wrap which will help with `StyledStr
+
+pub(crate) mod core;
+#[cfg(feature = "wrap_help")]
+pub(crate) mod word_separators;
+#[cfg(feature = "wrap_help")]
+pub(crate) mod wrap_algorithms;
+
+#[cfg(feature = "wrap_help")]
+pub(crate) fn wrap(content: &str, hard_width: usize) -> String {
+ let mut wrapper = wrap_algorithms::LineWrapper::new(hard_width);
+ let mut total = Vec::new();
+ for line in content.split_inclusive('\n') {
+ wrapper.reset();
+ let line = word_separators::find_words_ascii_space(line).collect::<Vec<_>>();
+ total.extend(wrapper.wrap(line));
+ }
+ total.join("")
+}
+
+#[cfg(not(feature = "wrap_help"))]
+pub(crate) fn wrap(content: &str, _hard_width: usize) -> String {
+ content.to_owned()
+}
+
+#[cfg(test)]
+#[cfg(feature = "wrap_help")]
+mod test {
+ /// Compatibility shim to keep textwrap's tests
+ fn wrap(content: &str, hard_width: usize) -> Vec<String> {
+ super::wrap(content, hard_width)
+ .trim_end()
+ .split('\n')
+ .map(|s| s.to_owned())
+ .collect::<Vec<_>>()
+ }
+
+ #[test]
+ fn no_wrap() {
+ assert_eq!(wrap("foo", 10), vec!["foo"]);
+ }
+
+ #[test]
+ fn wrap_simple() {
+ assert_eq!(wrap("foo bar baz", 5), vec!["foo", "bar", "baz"]);
+ }
+
+ #[test]
+ fn to_be_or_not() {
+ assert_eq!(
+ wrap("To be, or not to be, that is the question.", 10),
+ vec!["To be, or", "not to be,", "that is", "the", "question."]
+ );
+ }
+
+ #[test]
+ fn multiple_words_on_first_line() {
+ assert_eq!(wrap("foo bar baz", 10), vec!["foo bar", "baz"]);
+ }
+
+ #[test]
+ fn long_word() {
+ assert_eq!(wrap("foo", 0), vec!["foo"]);
+ }
+
+ #[test]
+ fn long_words() {
+ assert_eq!(wrap("foo bar", 0), vec!["foo", "bar"]);
+ }
+
+ #[test]
+ fn max_width() {
+ assert_eq!(wrap("foo bar", usize::MAX), vec!["foo bar"]);
+
+ let text = "Hello there! This is some English text. \
+ It should not be wrapped given the extents below.";
+ assert_eq!(wrap(text, usize::MAX), vec![text]);
+ }
+
+ #[test]
+ fn leading_whitespace() {
+ assert_eq!(wrap(" foo bar", 6), vec![" foo", "bar"]);
+ }
+
+ #[test]
+ fn leading_whitespace_empty_first_line() {
+ // If there is no space for the first word, the first line
+ // will be empty. This is because the string is split into
+ // words like [" ", "foobar ", "baz"], which puts "foobar " on
+ // the second line. We never output trailing whitespace
+ assert_eq!(wrap(" foobar baz", 6), vec!["", "foobar", "baz"]);
+ }
+
+ #[test]
+ fn trailing_whitespace() {
+ // Whitespace is only significant inside a line. After a line
+ // gets too long and is broken, the first word starts in
+ // column zero and is not indented.
+ assert_eq!(wrap("foo bar baz ", 5), vec!["foo", "bar", "baz"]);
+ }
+
+ #[test]
+ fn issue_99() {
+ // We did not reset the in_whitespace flag correctly and did
+ // not handle single-character words after a line break.
+ assert_eq!(
+ wrap("aaabbbccc x yyyzzzwww", 9),
+ vec!["aaabbbccc", "x", "yyyzzzwww"]
+ );
+ }
+
+ #[test]
+ fn issue_129() {
+ // The dash is an em-dash which takes up four bytes. We used
+ // to panic since we tried to index into the character.
+ assert_eq!(wrap("x – x", 1), vec!["x", "–", "x"]);
+ }
+}
diff --git a/src/output/textwrap/word_separators.rs b/src/output/textwrap/word_separators.rs
new file mode 100644
index 0000000..ac09231
--- /dev/null
+++ b/src/output/textwrap/word_separators.rs
@@ -0,0 +1,91 @@
+pub(crate) fn find_words_ascii_space(line: &str) -> impl Iterator<Item = &'_ str> + '_ {
+ let mut start = 0;
+ let mut in_whitespace = false;
+ let mut char_indices = line.char_indices();
+
+ std::iter::from_fn(move || {
+ for (idx, ch) in char_indices.by_ref() {
+ if in_whitespace && ch != ' ' {
+ let word = &line[start..idx];
+ start = idx;
+ in_whitespace = ch == ' ';
+ return Some(word);
+ }
+
+ in_whitespace = ch == ' ';
+ }
+
+ if start < line.len() {
+ let word = &line[start..];
+ start = line.len();
+ return Some(word);
+ }
+
+ None
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ macro_rules! test_find_words {
+ ($ascii_name:ident,
+ $([ $line:expr, $ascii_words:expr ]),+) => {
+ #[test]
+ fn $ascii_name() {
+ $(
+ let expected_words: Vec<&str> = $ascii_words.to_vec();
+ let actual_words = find_words_ascii_space($line)
+ .collect::<Vec<_>>();
+ assert_eq!(actual_words, expected_words, "Line: {:?}", $line);
+ )+
+ }
+ };
+ }
+
+ test_find_words!(ascii_space_empty, ["", []]);
+
+ test_find_words!(ascii_single_word, ["foo", ["foo"]]);
+
+ test_find_words!(ascii_two_words, ["foo bar", ["foo ", "bar"]]);
+
+ test_find_words!(
+ ascii_multiple_words,
+ ["foo bar", ["foo ", "bar"]],
+ ["x y z", ["x ", "y ", "z"]]
+ );
+
+ test_find_words!(ascii_only_whitespace, [" ", [" "]], [" ", [" "]]);
+
+ test_find_words!(
+ ascii_inter_word_whitespace,
+ ["foo bar", ["foo ", "bar"]]
+ );
+
+ test_find_words!(ascii_trailing_whitespace, ["foo ", ["foo "]]);
+
+ test_find_words!(ascii_leading_whitespace, [" foo", [" ", "foo"]]);
+
+ test_find_words!(
+ ascii_multi_column_char,
+ ["\u{1f920}", ["\u{1f920}"]] // cowboy emoji 🤠
+ );
+
+ test_find_words!(
+ ascii_hyphens,
+ ["foo-bar", ["foo-bar"]],
+ ["foo- bar", ["foo- ", "bar"]],
+ ["foo - bar", ["foo ", "- ", "bar"]],
+ ["foo -bar", ["foo ", "-bar"]]
+ );
+
+ test_find_words!(ascii_newline, ["foo\nbar", ["foo\nbar"]]);
+
+ test_find_words!(ascii_tab, ["foo\tbar", ["foo\tbar"]]);
+
+ test_find_words!(
+ ascii_non_breaking_space,
+ ["foo\u{00A0}bar", ["foo\u{00A0}bar"]]
+ );
+}
diff --git a/src/output/textwrap/wrap_algorithms.rs b/src/output/textwrap/wrap_algorithms.rs
new file mode 100644
index 0000000..019cc04
--- /dev/null
+++ b/src/output/textwrap/wrap_algorithms.rs
@@ -0,0 +1,44 @@
+use super::core::display_width;
+
+#[derive(Debug)]
+pub(crate) struct LineWrapper {
+ line_width: usize,
+ hard_width: usize,
+}
+
+impl LineWrapper {
+ pub(crate) fn new(hard_width: usize) -> Self {
+ Self {
+ line_width: 0,
+ hard_width,
+ }
+ }
+
+ pub(crate) fn reset(&mut self) {
+ self.line_width = 0;
+ }
+
+ pub(crate) fn wrap<'w>(&mut self, mut words: Vec<&'w str>) -> Vec<&'w str> {
+ let mut i = 0;
+ while i < words.len() {
+ let word = &words[i];
+ let trimmed = word.trim_end();
+ let word_width = display_width(trimmed);
+ let trimmed_delta = word.len() - trimmed.len();
+ if i != 0 && self.hard_width < self.line_width + word_width {
+ if 0 < i {
+ let last = i - 1;
+ let trimmed = words[last].trim_end();
+ words[last] = trimmed;
+ }
+ words.insert(i, "\n");
+ i += 1;
+ self.reset();
+ }
+ self.line_width += word_width + trimmed_delta;
+
+ i += 1;
+ }
+ words
+ }
+}
diff --git a/src/output/usage.rs b/src/output/usage.rs
new file mode 100644
index 0000000..145fce1
--- /dev/null
+++ b/src/output/usage.rs
@@ -0,0 +1,441 @@
+#![cfg_attr(not(feature = "usage"), allow(unused_imports))]
+#![cfg_attr(not(feature = "usage"), allow(unused_variables))]
+#![cfg_attr(not(feature = "usage"), allow(clippy::manual_map))]
+#![cfg_attr(not(feature = "usage"), allow(dead_code))]
+
+// Internal
+use crate::builder::StyledStr;
+use crate::builder::{ArgPredicate, Command};
+use crate::parser::ArgMatcher;
+use crate::util::ChildGraph;
+use crate::util::FlatSet;
+use crate::util::Id;
+
+static DEFAULT_SUB_VALUE_NAME: &str = "COMMAND";
+
+pub(crate) struct Usage<'cmd> {
+ cmd: &'cmd Command,
+ required: Option<&'cmd ChildGraph<Id>>,
+}
+
+impl<'cmd> Usage<'cmd> {
+ pub(crate) fn new(cmd: &'cmd Command) -> Self {
+ Usage {
+ cmd,
+ required: None,
+ }
+ }
+
+ pub(crate) fn required(mut self, required: &'cmd ChildGraph<Id>) -> Self {
+ self.required = Some(required);
+ self
+ }
+
+ // Creates a usage string for display. This happens just after all arguments were parsed, but before
+ // any subcommands have been parsed (so as to give subcommands their own usage recursively)
+ pub(crate) fn create_usage_with_title(&self, used: &[Id]) -> Option<StyledStr> {
+ debug!("Usage::create_usage_with_title");
+ let usage = some!(self.create_usage_no_title(used));
+
+ let mut styled = StyledStr::new();
+ styled.header("Usage:");
+ styled.none(" ");
+ styled.extend(usage.into_iter());
+ Some(styled)
+ }
+
+ // Creates a usage string (*without title*) if one was not provided by the user manually.
+ pub(crate) fn create_usage_no_title(&self, used: &[Id]) -> Option<StyledStr> {
+ debug!("Usage::create_usage_no_title");
+ if let Some(u) = self.cmd.get_override_usage() {
+ Some(u.clone())
+ } else {
+ #[cfg(feature = "usage")]
+ {
+ if used.is_empty() {
+ Some(self.create_help_usage(true))
+ } else {
+ Some(self.create_smart_usage(used))
+ }
+ }
+
+ #[cfg(not(feature = "usage"))]
+ {
+ None
+ }
+ }
+ }
+}
+
+#[cfg(feature = "usage")]
+impl<'cmd> Usage<'cmd> {
+ // Creates a usage string for display in help messages (i.e. not for errors)
+ fn create_help_usage(&self, incl_reqs: bool) -> StyledStr {
+ debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs);
+ let mut styled = StyledStr::new();
+ let name = self
+ .cmd
+ .get_usage_name()
+ .or_else(|| self.cmd.get_bin_name())
+ .unwrap_or_else(|| self.cmd.get_name());
+ styled.literal(name);
+
+ if self.needs_options_tag() {
+ styled.placeholder(" [OPTIONS]");
+ }
+
+ self.write_args(&[], !incl_reqs, &mut styled);
+
+ // incl_reqs is only false when this function is called recursively
+ if self.cmd.has_visible_subcommands() && incl_reqs
+ || self.cmd.is_allow_external_subcommands_set()
+ {
+ let placeholder = self
+ .cmd
+ .get_subcommand_value_name()
+ .unwrap_or(DEFAULT_SUB_VALUE_NAME);
+ if self.cmd.is_subcommand_negates_reqs_set()
+ || self.cmd.is_args_conflicts_with_subcommands_set()
+ {
+ styled.none("\n");
+ styled.none(" ");
+ if self.cmd.is_args_conflicts_with_subcommands_set() {
+ // Short-circuit full usage creation since no args will be relevant
+ styled.literal(name);
+ } else {
+ styled.extend(self.create_help_usage(false).into_iter());
+ }
+ styled.placeholder(" <");
+ styled.placeholder(placeholder);
+ styled.placeholder(">");
+ } else if self.cmd.is_subcommand_required_set() {
+ styled.placeholder(" <");
+ styled.placeholder(placeholder);
+ styled.placeholder(">");
+ } else {
+ styled.placeholder(" [");
+ styled.placeholder(placeholder);
+ styled.placeholder("]");
+ }
+ }
+ styled.trim();
+ debug!("Usage::create_help_usage: usage={}", styled);
+ styled
+ }
+
+ // Creates a context aware usage string, or "smart usage" from currently used
+ // args, and requirements
+ fn create_smart_usage(&self, used: &[Id]) -> StyledStr {
+ debug!("Usage::create_smart_usage");
+ let mut styled = StyledStr::new();
+
+ styled.literal(
+ self.cmd
+ .get_usage_name()
+ .or_else(|| self.cmd.get_bin_name())
+ .unwrap_or_else(|| self.cmd.get_name()),
+ );
+
+ self.write_args(used, false, &mut styled);
+
+ if self.cmd.is_subcommand_required_set() {
+ styled.placeholder(" <");
+ styled.placeholder(
+ self.cmd
+ .get_subcommand_value_name()
+ .unwrap_or(DEFAULT_SUB_VALUE_NAME),
+ );
+ styled.placeholder(">");
+ }
+ styled
+ }
+
+ // Determines if we need the `[OPTIONS]` tag in the usage string
+ fn needs_options_tag(&self) -> bool {
+ debug!("Usage::needs_options_tag");
+ 'outer: for f in self.cmd.get_non_positionals() {
+ debug!("Usage::needs_options_tag:iter: f={}", f.get_id());
+
+ // Don't print `[OPTIONS]` just for help or version
+ if f.get_long() == Some("help") || f.get_long() == Some("version") {
+ debug!("Usage::needs_options_tag:iter Option is built-in");
+ continue;
+ }
+
+ if f.is_hide_set() {
+ debug!("Usage::needs_options_tag:iter Option is hidden");
+ continue;
+ }
+ if f.is_required_set() {
+ debug!("Usage::needs_options_tag:iter Option is required");
+ continue;
+ }
+ for grp_s in self.cmd.groups_for_arg(f.get_id()) {
+ debug!("Usage::needs_options_tag:iter:iter: grp_s={:?}", grp_s);
+ if self.cmd.get_groups().any(|g| g.id == grp_s && g.required) {
+ debug!("Usage::needs_options_tag:iter:iter: Group is required");
+ continue 'outer;
+ }
+ }
+
+ debug!("Usage::needs_options_tag:iter: [OPTIONS] required");
+ return true;
+ }
+
+ debug!("Usage::needs_options_tag: [OPTIONS] not required");
+ false
+ }
+
+ // Returns the required args in usage string form by fully unrolling all groups
+ pub(crate) fn write_args(&self, incls: &[Id], force_optional: bool, styled: &mut StyledStr) {
+ for required in self.get_args(incls, force_optional) {
+ styled.none(" ");
+ styled.extend(required.into_iter());
+ }
+ }
+
+ pub(crate) fn get_args(&self, incls: &[Id], force_optional: bool) -> Vec<StyledStr> {
+ debug!("Usage::get_args: incls={:?}", incls,);
+
+ let required_owned;
+ let required = if let Some(required) = self.required {
+ required
+ } else {
+ required_owned = self.cmd.required_graph();
+ &required_owned
+ };
+
+ let mut unrolled_reqs = Vec::new();
+ for a in required.iter() {
+ let is_relevant = |(val, req_arg): &(ArgPredicate, Id)| -> Option<Id> {
+ let required = match val {
+ ArgPredicate::Equals(_) => false,
+ ArgPredicate::IsPresent => true,
+ };
+ required.then(|| req_arg.clone())
+ };
+
+ for aa in self.cmd.unroll_arg_requires(is_relevant, a) {
+ // if we don't check for duplicates here this causes duplicate error messages
+ // see https://github.com/clap-rs/clap/issues/2770
+ unrolled_reqs.push(aa);
+ }
+ // always include the required arg itself. it will not be enumerated
+ // by unroll_requirements_for_arg.
+ unrolled_reqs.push(a.clone());
+ }
+ debug!("Usage::get_args: unrolled_reqs={:?}", unrolled_reqs);
+
+ let mut required_groups_members = FlatSet::new();
+ let mut required_groups = FlatSet::new();
+ for req in unrolled_reqs.iter().chain(incls.iter()) {
+ if self.cmd.find_group(req).is_some() {
+ let group_members = self.cmd.unroll_args_in_group(req);
+ let elem = self.cmd.format_group(req);
+ required_groups.insert(elem);
+ required_groups_members.extend(group_members);
+ } else {
+ debug_assert!(self.cmd.find(req).is_some());
+ }
+ }
+
+ let mut required_opts = FlatSet::new();
+ let mut required_positionals = Vec::new();
+ for req in unrolled_reqs.iter().chain(incls.iter()) {
+ if let Some(arg) = self.cmd.find(req) {
+ if required_groups_members.contains(arg.get_id()) {
+ continue;
+ }
+
+ let stylized = arg.stylized(Some(!force_optional));
+ if let Some(index) = arg.get_index() {
+ let new_len = index + 1;
+ if required_positionals.len() < new_len {
+ required_positionals.resize(new_len, None);
+ }
+ required_positionals[index] = Some(stylized);
+ } else {
+ required_opts.insert(stylized);
+ }
+ } else {
+ debug_assert!(self.cmd.find_group(req).is_some());
+ }
+ }
+
+ for pos in self.cmd.get_positionals() {
+ if pos.is_hide_set() {
+ continue;
+ }
+ if required_groups_members.contains(pos.get_id()) {
+ continue;
+ }
+
+ let index = pos.get_index().unwrap();
+ let new_len = index + 1;
+ if required_positionals.len() < new_len {
+ required_positionals.resize(new_len, None);
+ }
+ if required_positionals[index].is_some() {
+ if pos.is_last_set() {
+ let styled = required_positionals[index].take().unwrap();
+ let mut new = StyledStr::new();
+ new.literal("-- ");
+ new.extend(styled.into_iter());
+ required_positionals[index] = Some(new);
+ }
+ } else {
+ let mut styled;
+ if pos.is_last_set() {
+ styled = StyledStr::new();
+ styled.literal("[-- ");
+ styled.extend(pos.stylized(Some(true)).into_iter());
+ styled.literal("]");
+ } else {
+ styled = pos.stylized(Some(false));
+ }
+ required_positionals[index] = Some(styled);
+ }
+ if pos.is_last_set() && force_optional {
+ required_positionals[index] = None;
+ }
+ }
+
+ let mut ret_val = Vec::new();
+ if !force_optional {
+ ret_val.extend(required_opts);
+ ret_val.extend(required_groups);
+ }
+ for pos in required_positionals.into_iter().flatten() {
+ ret_val.push(pos);
+ }
+
+ debug!("Usage::get_args: ret_val={:?}", ret_val);
+ ret_val
+ }
+
+ pub(crate) fn get_required_usage_from(
+ &self,
+ incls: &[Id],
+ matcher: Option<&ArgMatcher>,
+ incl_last: bool,
+ ) -> Vec<StyledStr> {
+ debug!(
+ "Usage::get_required_usage_from: incls={:?}, matcher={:?}, incl_last={:?}",
+ incls,
+ matcher.is_some(),
+ incl_last
+ );
+
+ let required_owned;
+ let required = if let Some(required) = self.required {
+ required
+ } else {
+ required_owned = self.cmd.required_graph();
+ &required_owned
+ };
+
+ let mut unrolled_reqs = Vec::new();
+ for a in required.iter() {
+ let is_relevant = |(val, req_arg): &(ArgPredicate, Id)| -> Option<Id> {
+ let required = match val {
+ ArgPredicate::Equals(_) => {
+ if let Some(matcher) = matcher {
+ matcher.check_explicit(a, val)
+ } else {
+ false
+ }
+ }
+ ArgPredicate::IsPresent => true,
+ };
+ required.then(|| req_arg.clone())
+ };
+
+ for aa in self.cmd.unroll_arg_requires(is_relevant, a) {
+ // if we don't check for duplicates here this causes duplicate error messages
+ // see https://github.com/clap-rs/clap/issues/2770
+ unrolled_reqs.push(aa);
+ }
+ // always include the required arg itself. it will not be enumerated
+ // by unroll_requirements_for_arg.
+ unrolled_reqs.push(a.clone());
+ }
+ debug!(
+ "Usage::get_required_usage_from: unrolled_reqs={:?}",
+ unrolled_reqs
+ );
+
+ let mut required_groups_members = FlatSet::new();
+ let mut required_groups = FlatSet::new();
+ for req in unrolled_reqs.iter().chain(incls.iter()) {
+ if 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 {
+ continue;
+ }
+
+ let elem = self.cmd.format_group(req);
+ required_groups.insert(elem);
+ required_groups_members.extend(group_members);
+ } else {
+ debug_assert!(self.cmd.find(req).is_some());
+ }
+ }
+
+ let mut required_opts = FlatSet::new();
+ let mut required_positionals = Vec::new();
+ for req in unrolled_reqs.iter().chain(incls.iter()) {
+ if let Some(arg) = self.cmd.find(req) {
+ if required_groups_members.contains(arg.get_id()) {
+ continue;
+ }
+
+ 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 {
+ continue;
+ }
+
+ let stylized = arg.stylized(Some(true));
+ if let Some(index) = arg.get_index() {
+ if !arg.is_last_set() || incl_last {
+ let new_len = index + 1;
+ if required_positionals.len() < new_len {
+ required_positionals.resize(new_len, None);
+ }
+ required_positionals[index] = Some(stylized);
+ }
+ } else {
+ required_opts.insert(stylized);
+ }
+ } else {
+ debug_assert!(self.cmd.find_group(req).is_some());
+ }
+ }
+
+ let mut ret_val = Vec::new();
+ ret_val.extend(required_opts);
+ ret_val.extend(required_groups);
+ for pos in required_positionals.into_iter().flatten() {
+ ret_val.push(pos);
+ }
+
+ debug!("Usage::get_required_usage_from: ret_val={:?}", ret_val);
+ ret_val
+ }
+}
diff --git a/src/parser/arg_matcher.rs b/src/parser/arg_matcher.rs
new file mode 100644
index 0000000..d584689
--- /dev/null
+++ b/src/parser/arg_matcher.rs
@@ -0,0 +1,248 @@
+// Std
+use std::ffi::OsString;
+use std::mem;
+use std::ops::Deref;
+
+// Internal
+use crate::builder::{Arg, ArgPredicate, Command};
+use crate::parser::AnyValue;
+use crate::parser::Identifier;
+use crate::parser::PendingArg;
+use crate::parser::{ArgMatches, MatchedArg, SubCommand, ValueSource};
+use crate::util::FlatMap;
+use crate::util::Id;
+use crate::INTERNAL_ERROR_MSG;
+
+#[derive(Debug, Default)]
+pub(crate) struct ArgMatcher {
+ matches: ArgMatches,
+ pending: Option<PendingArg>,
+}
+
+impl ArgMatcher {
+ pub(crate) fn new(_cmd: &Command) -> Self {
+ ArgMatcher {
+ matches: ArgMatches {
+ #[cfg(debug_assertions)]
+ valid_args: {
+ let args = _cmd.get_arguments().map(|a| a.get_id().clone());
+ let groups = _cmd.get_groups().map(|g| g.get_id().clone());
+ args.chain(groups).collect()
+ },
+ #[cfg(debug_assertions)]
+ valid_subcommands: _cmd
+ .get_subcommands()
+ .map(|sc| sc.get_name_str().clone())
+ .collect(),
+ ..Default::default()
+ },
+ pending: None,
+ }
+ }
+
+ pub(crate) fn into_inner(self) -> ArgMatches {
+ self.matches
+ }
+
+ pub(crate) fn propagate_globals(&mut self, global_arg_vec: &[Id]) {
+ debug!(
+ "ArgMatcher::get_global_values: global_arg_vec={:?}",
+ global_arg_vec
+ );
+ let mut vals_map = FlatMap::new();
+ self.fill_in_global_values(global_arg_vec, &mut vals_map);
+ }
+
+ fn fill_in_global_values(
+ &mut self,
+ global_arg_vec: &[Id],
+ vals_map: &mut FlatMap<Id, MatchedArg>,
+ ) {
+ for global_arg in global_arg_vec {
+ if let Some(ma) = self.get(global_arg) {
+ // We have to check if the parent's global arg wasn't used but still exists
+ // such as from a default value.
+ //
+ // For example, `myprog subcommand --global-arg=value` where `--global-arg` defines
+ // 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.source() > ma.source() {
+ parent_ma
+ } else {
+ ma
+ }
+ } else {
+ ma
+ }
+ .clone();
+ vals_map.insert(global_arg.clone(), to_update);
+ }
+ }
+ if let Some(ref mut sc) = self.matches.subcommand {
+ let mut am = ArgMatcher {
+ matches: mem::take(&mut sc.matches),
+ pending: None,
+ };
+ am.fill_in_global_values(global_arg_vec, vals_map);
+ mem::swap(&mut am.matches, &mut sc.matches);
+ }
+
+ for (name, matched_arg) in vals_map.iter_mut() {
+ self.matches.args.insert(name.clone(), matched_arg.clone());
+ }
+ }
+
+ pub(crate) fn get(&self, arg: &Id) -> Option<&MatchedArg> {
+ self.matches.args.get(arg)
+ }
+
+ pub(crate) fn get_mut(&mut self, arg: &Id) -> Option<&mut MatchedArg> {
+ self.matches.args.get_mut(arg)
+ }
+
+ pub(crate) fn remove(&mut self, arg: &Id) -> bool {
+ self.matches.args.remove(arg).is_some()
+ }
+
+ pub(crate) fn contains(&self, arg: &Id) -> bool {
+ self.matches.args.contains_key(arg)
+ }
+
+ pub(crate) fn arg_ids(&self) -> std::slice::Iter<'_, Id> {
+ self.matches.args.keys()
+ }
+
+ pub(crate) fn args(&self) -> crate::util::flat_map::Iter<'_, Id, MatchedArg> {
+ self.matches.args.iter()
+ }
+
+ pub(crate) fn entry(&mut self, arg: Id) -> crate::util::Entry<Id, MatchedArg> {
+ self.matches.args.entry(arg)
+ }
+
+ pub(crate) fn subcommand(&mut self, sc: SubCommand) {
+ self.matches.subcommand = Some(Box::new(sc));
+ }
+
+ pub(crate) fn subcommand_name(&self) -> Option<&str> {
+ self.matches.subcommand_name()
+ }
+
+ pub(crate) fn check_explicit(&self, arg: &Id, predicate: &ArgPredicate) -> bool {
+ self.get(arg).map_or(false, |a| a.check_explicit(predicate))
+ }
+
+ pub(crate) fn start_custom_arg(&mut self, arg: &Arg, source: ValueSource) {
+ let id = arg.get_id().clone();
+ debug!(
+ "ArgMatcher::start_custom_arg: id={:?}, source={:?}",
+ id, source
+ );
+ let ma = self.entry(id).or_insert(MatchedArg::new_arg(arg));
+ debug_assert_eq!(ma.type_id(), Some(arg.get_value_parser().type_id()));
+ ma.set_source(source);
+ ma.new_val_group();
+ }
+
+ pub(crate) fn start_custom_group(&mut self, id: Id, source: ValueSource) {
+ debug!(
+ "ArgMatcher::start_custom_arg: id={:?}, source={:?}",
+ id, source
+ );
+ let ma = self.entry(id).or_insert(MatchedArg::new_group());
+ debug_assert_eq!(ma.type_id(), None);
+ ma.set_source(source);
+ ma.new_val_group();
+ }
+
+ pub(crate) fn start_occurrence_of_external(&mut self, cmd: &crate::Command) {
+ let id = Id::from_static_ref(Id::EXTERNAL);
+ debug!("ArgMatcher::start_occurrence_of_external: id={:?}", id,);
+ let ma = self.entry(id).or_insert(MatchedArg::new_external(cmd));
+ debug_assert_eq!(
+ ma.type_id(),
+ Some(
+ cmd.get_external_subcommand_value_parser()
+ .expect(INTERNAL_ERROR_MSG)
+ .type_id()
+ )
+ );
+ ma.set_source(ValueSource::CommandLine);
+ ma.new_val_group();
+ }
+
+ pub(crate) fn add_val_to(&mut self, arg: &Id, val: AnyValue, raw_val: OsString) {
+ let ma = self.get_mut(arg).expect(INTERNAL_ERROR_MSG);
+ ma.append_val(val, raw_val);
+ }
+
+ pub(crate) fn add_index_to(&mut self, arg: &Id, idx: usize) {
+ let ma = self.get_mut(arg).expect(INTERNAL_ERROR_MSG);
+ ma.push_index(idx);
+ }
+
+ pub(crate) fn needs_more_vals(&self, o: &Arg) -> bool {
+ let num_pending = self
+ .pending
+ .as_ref()
+ .and_then(|p| (p.id == *o.get_id()).then_some(p.raw_vals.len()))
+ .unwrap_or(0);
+ debug!(
+ "ArgMatcher::needs_more_vals: o={}, pending={}",
+ o.get_id(),
+ num_pending
+ );
+ let expected = o.get_num_args().expect(INTERNAL_ERROR_MSG);
+ debug!(
+ "ArgMatcher::needs_more_vals: expected={}, actual={}",
+ expected, num_pending
+ );
+ expected.accepts_more(num_pending)
+ }
+
+ pub(crate) fn pending_arg_id(&self) -> Option<&Id> {
+ self.pending.as_ref().map(|p| &p.id)
+ }
+
+ pub(crate) fn pending_values_mut(
+ &mut self,
+ id: &Id,
+ ident: Option<Identifier>,
+ trailing_values: bool,
+ ) -> &mut Vec<OsString> {
+ let pending = self.pending.get_or_insert_with(|| PendingArg {
+ id: id.clone(),
+ ident,
+ raw_vals: Default::default(),
+ trailing_idx: None,
+ });
+ debug_assert_eq!(pending.id, *id, "{INTERNAL_ERROR_MSG}");
+ if ident.is_some() {
+ debug_assert_eq!(pending.ident, ident, "{INTERNAL_ERROR_MSG}");
+ }
+ if trailing_values {
+ pending.trailing_idx.get_or_insert(pending.raw_vals.len());
+ }
+ &mut pending.raw_vals
+ }
+
+ pub(crate) fn start_trailing(&mut self) {
+ if let Some(pending) = &mut self.pending {
+ // Allow asserting its started on subsequent calls
+ pending.trailing_idx.get_or_insert(pending.raw_vals.len());
+ }
+ }
+
+ pub(crate) fn take_pending(&mut self) -> Option<PendingArg> {
+ self.pending.take()
+ }
+}
+
+impl Deref for ArgMatcher {
+ type Target = ArgMatches;
+
+ fn deref(&self) -> &Self::Target {
+ &self.matches
+ }
+}
diff --git a/src/parser/error.rs b/src/parser/error.rs
new file mode 100644
index 0000000..66b2bc7
--- /dev/null
+++ b/src/parser/error.rs
@@ -0,0 +1,61 @@
+/// 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 {
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub(crate) fn unwrap<T>(id: &str, 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 {expected:?}, need to downcast to {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")
+ }
+ }
+ }
+}
+
+#[test]
+fn check_auto_traits() {
+ static_assertions::assert_impl_all!(
+ MatchesError: Send,
+ Sync,
+ std::panic::RefUnwindSafe,
+ std::panic::UnwindSafe,
+ Unpin
+ );
+}
diff --git a/src/parser/features/mod.rs b/src/parser/features/mod.rs
new file mode 100644
index 0000000..bdeb766
--- /dev/null
+++ b/src/parser/features/mod.rs
@@ -0,0 +1 @@
+pub(crate) mod suggestions;
diff --git a/src/parser/features/suggestions.rs b/src/parser/features/suggestions.rs
new file mode 100644
index 0000000..b8bb7ad
--- /dev/null
+++ b/src/parser/features/suggestions.rs
@@ -0,0 +1,167 @@
+#[cfg(feature = "suggestions")]
+use std::cmp::Ordering;
+
+// Internal
+use crate::builder::Command;
+
+/// Find strings from an iterable of `possible_values` similar to a given value `v`
+/// Returns a Vec of all possible values that exceed a similarity threshold
+/// sorted by ascending similarity, most similar comes last
+#[cfg(feature = "suggestions")]
+pub(crate) fn did_you_mean<T, I>(v: &str, possible_values: I) -> Vec<String>
+where
+ T: AsRef<str>,
+ I: IntoIterator<Item = T>,
+{
+ let mut candidates: Vec<(f64, String)> = possible_values
+ .into_iter()
+ // GH #4660: using `jaro` because `jaro_winkler` implementation in `strsim-rs` is wrong
+ // causing strings with common prefix >=10 to be considered perfectly similar
+ .map(|pv| (strsim::jaro(v, pv.as_ref()), pv.as_ref().to_owned()))
+ // Confidence of 0.7 so that bar -> baz is suggested
+ .filter(|(confidence, _)| *confidence > 0.7)
+ .collect();
+ candidates.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal));
+ candidates.into_iter().map(|(_, pv)| pv).collect()
+}
+
+#[cfg(not(feature = "suggestions"))]
+pub(crate) fn did_you_mean<T, I>(_: &str, _: I) -> Vec<String>
+where
+ T: AsRef<str>,
+ I: IntoIterator<Item = T>,
+{
+ Vec::new()
+}
+
+/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase
+pub(crate) fn did_you_mean_flag<'a, 'help, I, T>(
+ arg: &str,
+ remaining_args: &[&std::ffi::OsStr],
+ longs: I,
+ subcommands: impl IntoIterator<Item = &'a mut Command>,
+) -> Option<(String, Option<String>)>
+where
+ 'help: 'a,
+ T: AsRef<str>,
+ I: IntoIterator<Item = T>,
+{
+ use crate::mkeymap::KeyType;
+
+ match did_you_mean(arg, longs).pop() {
+ Some(candidate) => Some((candidate, None)),
+ None => subcommands
+ .into_iter()
+ .filter_map(|subcommand| {
+ subcommand._build_self(false);
+
+ let longs = subcommand.get_keymap().keys().filter_map(|a| {
+ if let KeyType::Long(v) = a {
+ Some(v.to_string_lossy().into_owned())
+ } else {
+ None
+ }
+ });
+
+ let subcommand_name = subcommand.get_name();
+
+ let candidate = some!(did_you_mean(arg, longs).pop());
+ let score = some!(remaining_args.iter().position(|x| subcommand_name == *x));
+ Some((score, (candidate, Some(subcommand_name.to_string()))))
+ })
+ .min_by_key(|(x, _)| *x)
+ .map(|(_, suggestion)| suggestion),
+ }
+}
+
+#[cfg(all(test, feature = "suggestions"))]
+mod test {
+ use super::*;
+
+ #[test]
+ fn missing_letter() {
+ let p_vals = ["test", "possible", "values"];
+ assert_eq!(did_you_mean("tst", p_vals.iter()), vec!["test"]);
+ }
+
+ #[test]
+ fn ambiguous() {
+ let p_vals = ["test", "temp", "possible", "values"];
+ assert_eq!(did_you_mean("te", p_vals.iter()), vec!["test", "temp"]);
+ }
+
+ #[test]
+ fn unrelated() {
+ let p_vals = ["test", "possible", "values"];
+ assert_eq!(
+ did_you_mean("hahaahahah", p_vals.iter()),
+ Vec::<String>::new()
+ );
+ }
+
+ #[test]
+ fn best_fit() {
+ let p_vals = [
+ "test",
+ "possible",
+ "values",
+ "alignmentStart",
+ "alignmentScore",
+ ];
+ assert_eq!(
+ did_you_mean("alignmentScorr", p_vals.iter()),
+ vec!["alignmentStart", "alignmentScore"]
+ );
+ }
+
+ #[test]
+ fn best_fit_long_common_prefix_issue_4660() {
+ let p_vals = ["alignmentScore", "alignmentStart"];
+ assert_eq!(
+ did_you_mean("alignmentScorr", p_vals.iter()),
+ vec!["alignmentStart", "alignmentScore"]
+ );
+ }
+
+ #[test]
+ fn flag_missing_letter() {
+ let p_vals = ["test", "possible", "values"];
+ assert_eq!(
+ did_you_mean_flag("tst", &[], p_vals.iter(), []),
+ Some(("test".to_owned(), None))
+ );
+ }
+
+ #[test]
+ fn flag_ambiguous() {
+ let p_vals = ["test", "temp", "possible", "values"];
+ assert_eq!(
+ did_you_mean_flag("te", &[], p_vals.iter(), []),
+ Some(("temp".to_owned(), None))
+ );
+ }
+
+ #[test]
+ fn flag_unrelated() {
+ let p_vals = ["test", "possible", "values"];
+ assert_eq!(
+ did_you_mean_flag("hahaahahah", &[], p_vals.iter(), []),
+ None
+ );
+ }
+
+ #[test]
+ fn flag_best_fit() {
+ let p_vals = [
+ "test",
+ "possible",
+ "values",
+ "alignmentStart",
+ "alignmentScore",
+ ];
+ assert_eq!(
+ did_you_mean_flag("alignmentScorr", &[], p_vals.iter(), []),
+ Some(("alignmentScore".to_owned(), None))
+ );
+ }
+}
diff --git a/src/parser/matches/any_value.rs b/src/parser/matches/any_value.rs
new file mode 100644
index 0000000..dc7a3e9
--- /dev/null
+++ b/src/parser/matches/any_value.rs
@@ -0,0 +1,112 @@
+#[derive(Clone)]
+pub(crate) struct AnyValue {
+ inner: std::sync::Arc<dyn std::any::Any + Send + Sync + 'static>,
+ // While we can extract `TypeId` from `inner`, the debug repr is of a number, so let's track
+ // the type_name in debug builds.
+ id: AnyValueId,
+}
+
+impl AnyValue {
+ pub(crate) fn new<V: std::any::Any + Clone + Send + Sync + 'static>(inner: V) -> Self {
+ let id = AnyValueId::of::<V>();
+ let inner = std::sync::Arc::new(inner);
+ Self { inner, id }
+ }
+
+ pub(crate) fn downcast_ref<T: std::any::Any + Clone + Send + Sync + 'static>(
+ &self,
+ ) -> Option<&T> {
+ self.inner.downcast_ref::<T>()
+ }
+
+ pub(crate) fn downcast_into<T: std::any::Any + Clone + Send + Sync>(self) -> Result<T, Self> {
+ let id = self.id;
+ let value =
+ ok!(std::sync::Arc::downcast::<T>(self.inner).map_err(|inner| Self { inner, id }));
+ let value = std::sync::Arc::try_unwrap(value).unwrap_or_else(|arc| (*arc).clone());
+ Ok(value)
+ }
+
+ pub(crate) fn type_id(&self) -> AnyValueId {
+ self.id
+ }
+}
+
+impl std::fmt::Debug for AnyValue {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
+ f.debug_struct("AnyValue").field("inner", &self.id).finish()
+ }
+}
+
+#[derive(Copy, Clone)]
+pub struct AnyValueId {
+ type_id: std::any::TypeId,
+ #[cfg(debug_assertions)]
+ type_name: &'static str,
+}
+
+impl AnyValueId {
+ pub(crate) fn of<A: ?Sized + 'static>() -> Self {
+ Self {
+ type_id: std::any::TypeId::of::<A>(),
+ #[cfg(debug_assertions)]
+ type_name: std::any::type_name::<A>(),
+ }
+ }
+}
+
+impl PartialEq for AnyValueId {
+ fn eq(&self, other: &Self) -> bool {
+ self.type_id == other.type_id
+ }
+}
+
+impl Eq for AnyValueId {}
+
+impl PartialOrd for AnyValueId {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ self.type_id.partial_cmp(&other.type_id)
+ }
+}
+
+impl Ord for AnyValueId {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ self.type_id.cmp(&other.type_id)
+ }
+}
+
+impl std::hash::Hash for AnyValueId {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.type_id.hash(state);
+ }
+}
+
+impl std::fmt::Debug for AnyValueId {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
+ #[cfg(not(debug_assertions))]
+ {
+ self.type_id.fmt(f)
+ }
+ #[cfg(debug_assertions)]
+ {
+ f.debug_struct(self.type_name).finish()
+ }
+ }
+}
+
+impl<'a, A: ?Sized + 'static> From<&'a A> for AnyValueId {
+ fn from(_: &'a A) -> Self {
+ Self::of::<A>()
+ }
+}
+
+#[cfg(test)]
+mod test {
+ #[test]
+ #[cfg(debug_assertions)]
+ fn debug_impl() {
+ use super::*;
+
+ assert_eq!(format!("{:?}", AnyValue::new(5)), "AnyValue { inner: i32 }");
+ }
+}
diff --git a/src/parser/matches/arg_matches.rs b/src/parser/matches/arg_matches.rs
new file mode 100644
index 0000000..13ceea3
--- /dev/null
+++ b/src/parser/matches/arg_matches.rs
@@ -0,0 +1,1967 @@
+// Std
+use std::any::Any;
+use std::ffi::{OsStr, OsString};
+use std::fmt::Debug;
+use std::iter::{Cloned, Flatten, Map};
+use std::slice::Iter;
+
+// Internal
+#[cfg(debug_assertions)]
+use crate::builder::Str;
+use crate::parser::AnyValue;
+use crate::parser::AnyValueId;
+use crate::parser::MatchedArg;
+use crate::parser::MatchesError;
+use crate::parser::ValueSource;
+use crate::util::FlatMap;
+use crate::util::Id;
+use crate::INTERNAL_ERROR_MSG;
+
+/// Container for parse results.
+///
+/// Used to get information about the arguments that were supplied to the program at runtime by
+/// the user. New instances of this struct are obtained by using the [`Command::get_matches`] family of
+/// methods.
+///
+/// # Examples
+///
+/// ```no_run
+/// # use clap::{Command, Arg, ArgAction};
+/// # use clap::parser::ValueSource;
+/// let matches = Command::new("MyApp")
+/// .arg(Arg::new("out")
+/// .long("output")
+/// .required(true)
+/// .action(ArgAction::Set)
+/// .default_value("-"))
+/// .arg(Arg::new("cfg")
+/// .short('c')
+/// .action(ArgAction::Set))
+/// .get_matches(); // builds the instance of ArgMatches
+///
+/// // to get information about the "cfg" argument we created, such as the value supplied we use
+/// // various ArgMatches methods, such as [ArgMatches::get_one]
+/// if let Some(c) = matches.get_one::<String>("cfg") {
+/// println!("Value for -c: {}", c);
+/// }
+///
+/// // The ArgMatches::get_one method returns an Option because the user may not have supplied
+/// // that argument at runtime. But if we specified that the argument was "required" as we did
+/// // with the "out" argument, we can safely unwrap because `clap` verifies that was actually
+/// // used at runtime.
+/// println!("Value for --output: {}", matches.get_one::<String>("out").unwrap());
+///
+/// // You can check the presence of an argument's values
+/// if matches.contains_id("out") {
+/// // However, if you want to know where the value came from
+/// if matches.value_source("out").expect("checked contains_id") == ValueSource::CommandLine {
+/// println!("`out` set by user");
+/// } else {
+/// println!("`out` is defaulted");
+/// }
+/// }
+/// ```
+/// [`Command::get_matches`]: crate::Command::get_matches()
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct ArgMatches {
+ #[cfg(debug_assertions)]
+ pub(crate) valid_args: Vec<Id>,
+ #[cfg(debug_assertions)]
+ pub(crate) valid_subcommands: Vec<Str>,
+ pub(crate) args: FlatMap<Id, MatchedArg>,
+ pub(crate) subcommand: Option<Box<SubCommand>>,
+}
+
+/// # Arguments
+impl ArgMatches {
+ /// Gets the value of a specific option or positional argument.
+ ///
+ /// i.e. an argument that [takes an additional value][crate::Arg::num_args] at runtime.
+ ///
+ /// Returns an error if the wrong type was used.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set.
+ /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime.
+ ///
+ /// # Panic
+ ///
+ /// If the argument definition and access mismatch. To handle this case programmatically, see
+ /// [`ArgMatches::try_get_one`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, value_parser, ArgAction};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("port")
+ /// .value_parser(value_parser!(usize))
+ /// .action(ArgAction::Set)
+ /// .required(true))
+ /// .get_matches_from(vec!["myapp", "2020"]);
+ ///
+ /// let port: usize = *m
+ /// .get_one("port")
+ /// .expect("`port`is required");
+ /// assert_eq!(port, 2020);
+ /// ```
+ /// [positional]: crate::Arg::index()
+ /// [`default_value`]: crate::Arg::default_value()
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn get_one<T: Any + Clone + Send + Sync + 'static>(&self, id: &str) -> Option<&T> {
+ MatchesError::unwrap(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
+ /// );
+ /// ```
+ #[cfg_attr(debug_assertions, 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"]).unwrap();
+ /// assert!(matches.contains_id("flag"));
+ /// assert_eq!(
+ /// matches.get_flag("flag"),
+ /// true
+ /// );
+ /// ```
+ #[cfg_attr(debug_assertions, 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.
+ ///
+ /// Returns an error if the wrong type was used.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// # Panic
+ ///
+ /// If the argument definition and access mismatch. To handle this case programmatically, see
+ /// [`ArgMatches::try_get_many`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, value_parser, ArgAction};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("ports")
+ /// .action(ArgAction::Append)
+ /// .value_parser(value_parser!(usize))
+ /// .short('p')
+ /// .required(true))
+ /// .get_matches_from(vec![
+ /// "myprog", "-p", "22", "-p", "80", "-p", "2020"
+ /// ]);
+ /// let vals: Vec<usize> = m.get_many("ports")
+ /// .expect("`port`is required")
+ /// .copied()
+ /// .collect();
+ /// assert_eq!(vals, [22, 80, 2020]);
+ /// ```
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn get_many<T: Any + Clone + Send + Sync + 'static>(
+ &self,
+ id: &str,
+ ) -> Option<ValuesRef<T>> {
+ MatchesError::unwrap(id, self.try_get_many(id))
+ }
+
+ /// Iterate over the values passed to each occurrence of an option.
+ ///
+ /// Each item is itself an iterator containing the arguments passed to a single occurrence
+ /// of the option.
+ ///
+ /// If the option doesn't support multiple occurrences, or there was only a single occurrence,
+ /// the iterator will only contain a single item.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// # Panics
+ ///
+ /// If the argument definition and access mismatch. To handle this case programmatically, see
+ /// [`ArgMatches::try_get_occurrences`].
+ ///
+ /// # Examples
+ /// ```rust
+ /// # use clap::{Command,Arg, ArgAction, value_parser};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("x")
+ /// .short('x')
+ /// .num_args(2)
+ /// .action(ArgAction::Append)
+ /// .value_parser(value_parser!(String)))
+ /// .get_matches_from(vec![
+ /// "myprog", "-x", "a", "b", "-x", "c", "d"]);
+ /// let vals: Vec<Vec<&String>> = m.get_occurrences("x").unwrap().map(Iterator::collect).collect();
+ /// assert_eq!(vals, [["a", "b"], ["c", "d"]]);
+ /// ```
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn get_occurrences<T: Any + Clone + Send + Sync + 'static>(
+ &self,
+ id: &str,
+ ) -> Option<OccurrencesRef<T>> {
+ MatchesError::unwrap(id, self.try_get_occurrences(id))
+ }
+
+ /// Iterate over the original argument values.
+ ///
+ /// An `OsStr` on Unix-like systems is any series of bytes, regardless of whether or not they
+ /// contain valid UTF-8. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid
+ /// filename on a Unix system as an argument value may contain invalid UTF-8.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// # Panic
+ ///
+ /// If the argument definition and access mismatch. To handle this case programmatically, see
+ /// [`ArgMatches::try_get_raw`].
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(unix), doc = " ```ignore")]
+ #[cfg_attr(unix, doc = " ```")]
+ /// # use clap::{Command, arg, value_parser};
+ /// # use std::ffi::{OsStr,OsString};
+ /// # use std::os::unix::ffi::{OsStrExt,OsStringExt};
+ /// use std::path::PathBuf;
+ ///
+ /// let m = Command::new("utf8")
+ /// .arg(arg!(<arg> ... "some arg").value_parser(value_parser!(PathBuf)))
+ /// .get_matches_from(vec![OsString::from("myprog"),
+ /// // "Hi"
+ /// OsString::from_vec(vec![b'H', b'i']),
+ /// // "{0xe9}!"
+ /// OsString::from_vec(vec![0xe9, b'!'])]);
+ ///
+ /// let mut itr = m.get_raw("arg")
+ /// .expect("`port`is required")
+ /// .into_iter();
+ /// assert_eq!(itr.next(), Some(OsStr::new("Hi")));
+ /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!'])));
+ /// assert_eq!(itr.next(), None);
+ /// ```
+ /// [`Iterator`]: std::iter::Iterator
+ /// [`OsSt`]: std::ffi::OsStr
+ /// [values]: OsValues
+ /// [`String`]: std::string::String
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn get_raw(&self, id: &str) -> Option<RawValues<'_>> {
+ MatchesError::unwrap(id, self.try_get_raw(id))
+ }
+
+ /// Iterate over the original values for each occurrence of an option.
+ ///
+ /// Similar to [`ArgMatches::get_occurrences`] but returns raw values.
+ ///
+ /// An `OsStr` on Unix-like systems is any series of bytes, regardless of whether or not they
+ /// contain valid UTF-8. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid
+ /// filename on a Unix system as an argument value may contain invalid UTF-8.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// # Panic
+ ///
+ /// If the argument definition and access mismatch. To handle this case programmatically, see
+ /// [`ArgMatches::try_get_raw_occurrences`].
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(unix), doc = " ```ignore")]
+ #[cfg_attr(unix, doc = " ```")]
+ /// # use clap::{Command, arg, value_parser, ArgAction, Arg};
+ /// # use std::ffi::{OsStr,OsString};
+ /// # use std::os::unix::ffi::{OsStrExt,OsStringExt};
+ /// use std::path::PathBuf;
+ ///
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("x")
+ /// .short('x')
+ /// .num_args(2)
+ /// .action(ArgAction::Append)
+ /// .value_parser(value_parser!(PathBuf)))
+ /// .get_matches_from(vec![OsString::from("myprog"),
+ /// OsString::from("-x"),
+ /// OsString::from("a"), OsString::from("b"),
+ /// OsString::from("-x"),
+ /// OsString::from("c"),
+ /// // "{0xe9}!"
+ /// OsString::from_vec(vec![0xe9, b'!'])]);
+ /// let mut itr = m.get_raw_occurrences("x")
+ /// .expect("`-x`is required")
+ /// .map(Iterator::collect::<Vec<_>>);
+ /// assert_eq!(itr.next(), Some(vec![OsStr::new("a"), OsStr::new("b")]));
+ /// assert_eq!(itr.next(), Some(vec![OsStr::new("c"), OsStr::from_bytes(&[0xe9, b'!'])]));
+ /// assert_eq!(itr.next(), None);
+ /// ```
+ /// [`Iterator`]: std::iter::Iterator
+ /// [`OsStr`]: std::ffi::OsStr
+ /// [values]: OsValues
+ /// [`String`]: std::string::String
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn get_raw_occurrences(&self, id: &str) -> Option<RawOccurrences<'_>> {
+ MatchesError::unwrap(id, self.try_get_raw_occurrences(id))
+ }
+
+ /// Returns the value of a specific option or positional argument.
+ ///
+ /// i.e. an argument that [takes an additional value][crate::Arg::num_args] at runtime.
+ ///
+ /// Returns an error if the wrong type was used. No item will have been removed.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set.
+ /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime.
+ ///
+ /// # Panic
+ ///
+ /// If the argument definition and access mismatch. To handle this case programmatically, see
+ /// [`ArgMatches::try_remove_one`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, value_parser, ArgAction};
+ /// let mut m = Command::new("myprog")
+ /// .arg(Arg::new("file")
+ /// .required(true)
+ /// .action(ArgAction::Set))
+ /// .get_matches_from(vec![
+ /// "myprog", "file.txt",
+ /// ]);
+ /// let vals: String = m.remove_one("file")
+ /// .expect("`file`is required");
+ /// assert_eq!(vals, "file.txt");
+ /// ```
+ /// [positional]: crate::Arg::index()
+ /// [`default_value`]: crate::Arg::default_value()
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn remove_one<T: Any + Clone + Send + Sync + 'static>(&mut self, id: &str) -> Option<T> {
+ MatchesError::unwrap(id, self.try_remove_one(id))
+ }
+
+ /// Return values of a specific option or positional argument.
+ ///
+ /// i.e. an argument that takes multiple values at runtime.
+ ///
+ /// Returns an error if the wrong type was used. No item will have been removed.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// # Panic
+ ///
+ /// If the argument definition and access mismatch. To handle this case programmatically, see
+ /// [`ArgMatches::try_remove_many`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, value_parser, ArgAction};
+ /// let mut m = Command::new("myprog")
+ /// .arg(Arg::new("file")
+ /// .action(ArgAction::Append)
+ /// .num_args(1..)
+ /// .required(true))
+ /// .get_matches_from(vec![
+ /// "myprog", "file1.txt", "file2.txt", "file3.txt", "file4.txt",
+ /// ]);
+ /// let vals: Vec<String> = m.remove_many("file")
+ /// .expect("`file`is required")
+ /// .collect();
+ /// assert_eq!(vals, ["file1.txt", "file2.txt", "file3.txt", "file4.txt"]);
+ /// ```
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn remove_many<T: Any + Clone + Send + Sync + 'static>(
+ &mut self,
+ id: &str,
+ ) -> Option<Values<T>> {
+ MatchesError::unwrap(id, self.try_remove_many(id))
+ }
+
+ /// Return values for each occurrence of an option.
+ ///
+ /// Each item is itself an iterator containing the arguments passed to a single occurrence of
+ /// the option.
+ ///
+ /// If the option doesn't support multiple occurrences, or there was only a single occurrence,
+ /// the iterator will only contain a single item.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// # Panic
+ ///
+ /// If the argument definition and access mismatch. To handle this case programmatically, see
+ /// [`ArgMatches::try_remove_occurrences`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, value_parser, ArgAction};
+ /// let mut m = Command::new("myprog")
+ /// .arg(Arg::new("x")
+ /// .short('x')
+ /// .num_args(2)
+ /// .action(ArgAction::Append)
+ /// .value_parser(value_parser!(String)))
+ /// .get_matches_from(vec![
+ /// "myprog", "-x", "a", "b", "-x", "c", "d"]);
+ /// let vals: Vec<Vec<String>> = m.remove_occurrences("x").unwrap().map(Iterator::collect).collect();
+ /// assert_eq!(vals, [["a", "b"], ["c", "d"]]);
+ /// ```
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn remove_occurrences<T: Any + Clone + Send + Sync + 'static>(
+ &mut self,
+ id: &str,
+ ) -> Option<Occurrences<T>> {
+ MatchesError::unwrap(id, self.try_remove_occurrences(id))
+ }
+
+ /// Check if values are present for the argument or group id
+ ///
+ /// *NOTE:* This will always return `true` if [`default_value`] has been set.
+ /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime.
+ ///
+ /// # Panics
+ ///
+ /// If `id` is not a valid argument or group name. To handle this case programmatically, see
+ /// [`ArgMatches::try_contains_id`].
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("debug")
+ /// .short('d')
+ /// .action(ArgAction::SetTrue))
+ /// .get_matches_from(vec![
+ /// "myprog", "-d"
+ /// ]);
+ ///
+ /// assert!(m.contains_id("debug"));
+ /// ```
+ ///
+ /// [`default_value`]: crate::Arg::default_value()
+ pub fn contains_id(&self, id: &str) -> bool {
+ MatchesError::unwrap(id, self.try_contains_id(id))
+ }
+
+ /// Iterate over [`Arg`][crate::Arg] and [`ArgGroup`][crate::ArgGroup] [`Id`][crate::Id]s via [`ArgMatches::ids`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use clap::{Command, arg, value_parser};
+ ///
+ /// let m = Command::new("myprog")
+ /// .arg(arg!(--color <when>)
+ /// .value_parser(["auto", "always", "never"]))
+ /// .arg(arg!(--config <path>)
+ /// .value_parser(value_parser!(std::path::PathBuf)))
+ /// .get_matches_from(["myprog", "--config=config.toml", "--color=auto"]);
+ /// assert_eq!(m.ids().len(), 2);
+ /// assert_eq!(
+ /// m.ids()
+ /// .map(|id| id.as_str())
+ /// .collect::<Vec<_>>(),
+ /// ["config", "color"]
+ /// );
+ /// ```
+ pub fn ids(&self) -> IdsRef<'_> {
+ IdsRef {
+ iter: self.args.keys(),
+ }
+ }
+
+ /// Check if any args were present on the command line
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let mut cmd = Command::new("myapp")
+ /// .arg(Arg::new("output")
+ /// .action(ArgAction::Set));
+ ///
+ /// let m = cmd
+ /// .try_get_matches_from_mut(vec!["myapp", "something"])
+ /// .unwrap();
+ /// assert!(m.args_present());
+ ///
+ /// let m = cmd
+ /// .try_get_matches_from_mut(vec!["myapp"])
+ /// .unwrap();
+ /// assert!(! m.args_present());
+ pub fn args_present(&self) -> bool {
+ !self.args.is_empty()
+ }
+
+ /// Get an [`Iterator`] over groups of values of a specific option.
+ ///
+ /// specifically grouped by the occurrences of the options.
+ ///
+ /// Each group is a `Vec<&str>` containing the arguments passed to a single occurrence
+ /// of the option.
+ ///
+ /// If the option doesn't support multiple occurrences, or there was only a single occurrence,
+ /// the iterator will only contain a single item.
+ ///
+ /// Returns `None` if the option wasn't present.
+ ///
+ /// # Panics
+ ///
+ /// If the value is invalid UTF-8.
+ ///
+ /// If `id` is not a valid argument or group id.
+ ///
+ /// # Examples
+ /// ```rust
+ /// # use clap::{Command,Arg, ArgAction};
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("exec")
+ /// .short('x')
+ /// .num_args(1..)
+ /// .action(ArgAction::Append)
+ /// .value_terminator(";"))
+ /// .get_matches_from(vec![
+ /// "myprog", "-x", "echo", "hi", ";", "-x", "echo", "bye"]);
+ /// let vals: Vec<Vec<&str>> = m.grouped_values_of("exec").unwrap().collect();
+ /// assert_eq!(vals, [["echo", "hi"], ["echo", "bye"]]);
+ /// ```
+ /// [`Iterator`]: std::iter::Iterator
+ #[cfg(feature = "unstable-grouped")]
+ #[cfg_attr(debug_assertions, track_caller)]
+ #[deprecated(
+ since = "4.1.0",
+ note = "Use get_occurrences or remove_occurrences instead"
+ )]
+ #[allow(deprecated)]
+ pub fn grouped_values_of(&self, id: &str) -> Option<GroupedValues> {
+ let arg = some!(self.get_arg(id));
+ let v = GroupedValues {
+ iter: arg.vals().map(|g| g.iter().map(unwrap_string).collect()),
+ len: arg.vals().len(),
+ };
+ Some(v)
+ }
+
+ /// Report where argument value came from
+ ///
+ /// # Panics
+ ///
+ /// If `id` is not a valid argument or group id.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// # use clap::parser::ValueSource;
+ /// let m = Command::new("myprog")
+ /// .arg(Arg::new("debug")
+ /// .short('d')
+ /// .action(ArgAction::SetTrue))
+ /// .get_matches_from(vec![
+ /// "myprog", "-d"
+ /// ]);
+ ///
+ /// assert_eq!(m.value_source("debug"), Some(ValueSource::CommandLine));
+ /// ```
+ ///
+ /// [`default_value`]: crate::Arg::default_value()
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn value_source(&self, id: &str) -> Option<ValueSource> {
+ let value = self.get_arg(id);
+
+ value.and_then(MatchedArg::source)
+ }
+
+ /// The first index of that an argument showed up.
+ ///
+ /// Indices are similar to argv indices, but are not exactly 1:1.
+ ///
+ /// For flags (i.e. those arguments which don't have an associated value), indices refer
+ /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices
+ /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the
+ /// index for `val` would be recorded. This is by design.
+ ///
+ /// Besides the flag/option discrepancy, the primary difference between an argv index and clap
+ /// index, is that clap continues counting once all arguments have properly separated, whereas
+ /// an argv index does not.
+ ///
+ /// The examples should clear this up.
+ ///
+ /// *NOTE:* If an argument is allowed multiple times, this method will only give the *first*
+ /// index. See [`ArgMatches::indices_of`].
+ ///
+ /// # Panics
+ ///
+ /// If `id` is not a valid argument or group id.
+ ///
+ /// # Examples
+ ///
+ /// The argv indices are listed in the comments below. See how they correspond to the clap
+ /// indices. Note that if it's not listed in a clap index, this is because it's not saved in
+ /// in an `ArgMatches` struct for querying.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .action(ArgAction::Set))
+ /// .get_matches_from(vec!["myapp", "-f", "-o", "val"]);
+ /// // ARGV indices: ^0 ^1 ^2 ^3
+ /// // clap indices: ^1 ^3
+ ///
+ /// assert_eq!(m.index_of("flag"), Some(1));
+ /// assert_eq!(m.index_of("option"), Some(3));
+ /// ```
+ ///
+ /// Now notice, if we use one of the other styles of options:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .action(ArgAction::Set))
+ /// .get_matches_from(vec!["myapp", "-f", "-o=val"]);
+ /// // ARGV indices: ^0 ^1 ^2
+ /// // clap indices: ^1 ^3
+ ///
+ /// assert_eq!(m.index_of("flag"), Some(1));
+ /// assert_eq!(m.index_of("option"), Some(3));
+ /// ```
+ ///
+ /// Things become much more complicated, or clear if we look at a more complex combination of
+ /// flags. Let's also throw in the final option style for good measure.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("flag2")
+ /// .short('F')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("flag3")
+ /// .short('z')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .action(ArgAction::Set))
+ /// .get_matches_from(vec!["myapp", "-fzF", "-oval"]);
+ /// // ARGV indices: ^0 ^1 ^2
+ /// // clap indices: ^1,2,3 ^5
+ /// //
+ /// // clap sees the above as 'myapp -f -z -F -o val'
+ /// // ^0 ^1 ^2 ^3 ^4 ^5
+ /// assert_eq!(m.index_of("flag"), Some(1));
+ /// assert_eq!(m.index_of("flag2"), Some(3));
+ /// assert_eq!(m.index_of("flag3"), Some(2));
+ /// assert_eq!(m.index_of("option"), Some(5));
+ /// ```
+ ///
+ /// One final combination of flags/options to see how they combine:
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("flag2")
+ /// .short('F')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("flag3")
+ /// .short('z')
+ /// .action(ArgAction::SetTrue))
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .action(ArgAction::Set))
+ /// .get_matches_from(vec!["myapp", "-fzFoval"]);
+ /// // ARGV indices: ^0 ^1
+ /// // clap indices: ^1,2,3^5
+ /// //
+ /// // clap sees the above as 'myapp -f -z -F -o val'
+ /// // ^0 ^1 ^2 ^3 ^4 ^5
+ /// assert_eq!(m.index_of("flag"), Some(1));
+ /// assert_eq!(m.index_of("flag2"), Some(3));
+ /// assert_eq!(m.index_of("flag3"), Some(2));
+ /// assert_eq!(m.index_of("option"), Some(5));
+ /// ```
+ ///
+ /// The last part to mention is when values are sent in multiple groups with a [delimiter].
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .value_delimiter(',')
+ /// .num_args(1..))
+ /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
+ /// // ARGV indices: ^0 ^1
+ /// // clap indices: ^2 ^3 ^4
+ /// //
+ /// // clap sees the above as 'myapp -o val1 val2 val3'
+ /// // ^0 ^1 ^2 ^3 ^4
+ /// assert_eq!(m.index_of("option"), Some(2));
+ /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]);
+ /// ```
+ /// [delimiter]: crate::Arg::value_delimiter()
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn index_of(&self, id: &str) -> Option<usize> {
+ let arg = some!(self.get_arg(id));
+ let i = some!(arg.get_index(0));
+ Some(i)
+ }
+
+ /// All indices an argument appeared at when parsing.
+ ///
+ /// Indices are similar to argv indices, but are not exactly 1:1.
+ ///
+ /// For flags (i.e. those arguments which don't have an associated value), indices refer
+ /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices
+ /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the
+ /// index for `val` would be recorded. This is by design.
+ ///
+ /// *NOTE:* For more information about how clap indices compared to argv indices, see
+ /// [`ArgMatches::index_of`]
+ ///
+ /// # Panics
+ ///
+ /// If `id` is not a valid argument or group id.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .value_delimiter(','))
+ /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
+ /// // ARGV indices: ^0 ^1
+ /// // clap indices: ^2 ^3 ^4
+ /// //
+ /// // clap sees the above as 'myapp -o val1 val2 val3'
+ /// // ^0 ^1 ^2 ^3 ^4
+ /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]);
+ /// ```
+ ///
+ /// Another quick example is when flags and options are used together
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .action(ArgAction::Set)
+ /// .action(ArgAction::Append))
+ /// .arg(Arg::new("flag")
+ /// .short('f')
+ /// .action(ArgAction::Count))
+ /// .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]);
+ /// // ARGV indices: ^0 ^1 ^2 ^3 ^4 ^5 ^6
+ /// // clap indices: ^2 ^3 ^5 ^6
+ ///
+ /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 5]);
+ /// assert_eq!(m.indices_of("flag").unwrap().collect::<Vec<_>>(), &[6]);
+ /// ```
+ ///
+ /// One final example, which is an odd case; if we *don't* use value delimiter as we did with
+ /// the first example above instead of `val1`, `val2` and `val3` all being distinc values, they
+ /// would all be a single value of `val1,val2,val3`, in which case they'd only receive a single
+ /// index.
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let m = Command::new("myapp")
+ /// .arg(Arg::new("option")
+ /// .short('o')
+ /// .action(ArgAction::Set)
+ /// .num_args(1..))
+ /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
+ /// // ARGV indices: ^0 ^1
+ /// // clap indices: ^2
+ /// //
+ /// // clap sees the above as 'myapp -o "val1,val2,val3"'
+ /// // ^0 ^1 ^2
+ /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2]);
+ /// ```
+ /// [`ArgMatches::index_of`]: ArgMatches::index_of()
+ /// [delimiter]: Arg::value_delimiter()
+ #[cfg_attr(debug_assertions, track_caller)]
+ pub fn indices_of(&self, id: &str) -> Option<Indices<'_>> {
+ let arg = some!(self.get_arg(id));
+ let i = Indices {
+ iter: arg.indices(),
+ len: arg.num_vals(),
+ };
+ Some(i)
+ }
+}
+
+/// # Subcommands
+impl ArgMatches {
+ /// The name and `ArgMatches` of the current [subcommand].
+ ///
+ /// Subcommand values are put in a child [`ArgMatches`]
+ ///
+ /// Returns `None` if the subcommand wasn't present at runtime,
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let app_m = Command::new("git")
+ /// .subcommand(Command::new("clone"))
+ /// .subcommand(Command::new("push"))
+ /// .subcommand(Command::new("commit"))
+ /// .get_matches();
+ ///
+ /// match app_m.subcommand() {
+ /// Some(("clone", sub_m)) => {}, // clone was used
+ /// Some(("push", sub_m)) => {}, // push was used
+ /// Some(("commit", sub_m)) => {}, // commit was used
+ /// _ => {}, // Either no subcommand or one not tested for...
+ /// }
+ /// ```
+ ///
+ /// Another useful scenario is when you want to support third party, or external, subcommands.
+ /// In these cases you can't know the subcommand name ahead of time, so use a variable instead
+ /// with pattern matching!
+ ///
+ /// ```rust
+ /// # use std::ffi::OsString;
+ /// # use std::ffi::OsStr;
+ /// # use clap::Command;
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let app_m = Command::new("myprog")
+ /// .allow_external_subcommands(true)
+ /// .get_matches_from(vec![
+ /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
+ /// ]);
+ ///
+ /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
+ /// // string argument name
+ /// match app_m.subcommand() {
+ /// Some((external, sub_m)) => {
+ /// let ext_args: Vec<&OsStr> = sub_m.get_many::<OsString>("")
+ /// .unwrap().map(|s| s.as_os_str()).collect();
+ /// assert_eq!(external, "subcmd");
+ /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
+ /// },
+ /// _ => {},
+ /// }
+ /// ```
+ /// [subcommand]: crate::Command::subcommand
+ #[inline]
+ pub fn subcommand(&self) -> Option<(&str, &ArgMatches)> {
+ self.subcommand.as_ref().map(|sc| (&*sc.name, &sc.matches))
+ }
+
+ /// Return the name and `ArgMatches` of the current [subcommand].
+ ///
+ /// Subcommand values are put in a child [`ArgMatches`]
+ ///
+ /// Returns `None` if the subcommand wasn't present at runtime,
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let mut app_m = Command::new("git")
+ /// .subcommand(Command::new("clone"))
+ /// .subcommand(Command::new("push"))
+ /// .subcommand(Command::new("commit"))
+ /// .subcommand_required(true)
+ /// .get_matches();
+ ///
+ /// let (name, sub_m) = app_m.remove_subcommand().expect("required");
+ /// match (name.as_str(), sub_m) {
+ /// ("clone", sub_m) => {}, // clone was used
+ /// ("push", sub_m) => {}, // push was used
+ /// ("commit", sub_m) => {}, // commit was used
+ /// (name, _) => unimplemented!("{}", name),
+ /// }
+ /// ```
+ ///
+ /// Another useful scenario is when you want to support third party, or external, subcommands.
+ /// In these cases you can't know the subcommand name ahead of time, so use a variable instead
+ /// with pattern matching!
+ ///
+ /// ```rust
+ /// # use std::ffi::OsString;
+ /// # use clap::Command;
+ /// // Assume there is an external subcommand named "subcmd"
+ /// let mut app_m = Command::new("myprog")
+ /// .allow_external_subcommands(true)
+ /// .get_matches_from(vec![
+ /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
+ /// ]);
+ ///
+ /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
+ /// // string argument name
+ /// match app_m.remove_subcommand() {
+ /// Some((external, mut sub_m)) => {
+ /// let ext_args: Vec<OsString> = sub_m.remove_many("")
+ /// .expect("`file`is required")
+ /// .collect();
+ /// assert_eq!(external, "subcmd");
+ /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
+ /// },
+ /// _ => {},
+ /// }
+ /// ```
+ /// [subcommand]: crate::Command::subcommand
+ pub fn remove_subcommand(&mut self) -> Option<(String, ArgMatches)> {
+ self.subcommand.take().map(|sc| (sc.name, sc.matches))
+ }
+
+ /// The `ArgMatches` for the current [subcommand].
+ ///
+ /// Subcommand values are put in a child [`ArgMatches`]
+ ///
+ /// Returns `None` if the subcommand wasn't present at runtime,
+ ///
+ /// # Panics
+ ///
+ /// If `id` is not a valid subcommand.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// # use clap::{Command, Arg, ArgAction};
+ /// let app_m = Command::new("myprog")
+ /// .arg(Arg::new("debug")
+ /// .short('d')
+ /// .action(ArgAction::SetTrue)
+ /// )
+ /// .subcommand(Command::new("test")
+ /// .arg(Arg::new("opt")
+ /// .long("option")
+ /// .action(ArgAction::Set)))
+ /// .get_matches_from(vec![
+ /// "myprog", "-d", "test", "--option", "val"
+ /// ]);
+ ///
+ /// // Both parent commands, and child subcommands can have arguments present at the same times
+ /// assert!(app_m.get_flag("debug"));
+ ///
+ /// // Get the subcommand's ArgMatches instance
+ /// if let Some(sub_m) = app_m.subcommand_matches("test") {
+ /// // Use the struct like normal
+ /// assert_eq!(sub_m.get_one::<String>("opt").map(|s| s.as_str()), Some("val"));
+ /// }
+ /// ```
+ ///
+ /// [subcommand]: crate::Command::subcommand
+ /// [`Command`]: crate::Command
+ pub fn subcommand_matches(&self, name: &str) -> Option<&ArgMatches> {
+ self.get_subcommand(name).map(|sc| &sc.matches)
+ }
+
+ /// The name of the current [subcommand].
+ ///
+ /// Returns `None` if the subcommand wasn't present at runtime,
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use clap::{Command, Arg, };
+ /// let app_m = Command::new("git")
+ /// .subcommand(Command::new("clone"))
+ /// .subcommand(Command::new("push"))
+ /// .subcommand(Command::new("commit"))
+ /// .get_matches();
+ ///
+ /// match app_m.subcommand_name() {
+ /// Some("clone") => {}, // clone was used
+ /// Some("push") => {}, // push was used
+ /// Some("commit") => {}, // commit was used
+ /// _ => {}, // Either no subcommand or one not tested for...
+ /// }
+ /// ```
+ /// [subcommand]: crate::Command::subcommand
+ /// [`Command`]: crate::Command
+ #[inline]
+ pub fn subcommand_name(&self) -> Option<&str> {
+ self.subcommand.as_ref().map(|sc| &*sc.name)
+ }
+
+ /// Check if a subcommand can be queried
+ ///
+ /// By default, `ArgMatches` functions assert on undefined `Id`s to help catch programmer
+ /// mistakes. In some context, this doesn't work, so users can use this function to check
+ /// before they do a query on `ArgMatches`.
+ #[inline]
+ #[doc(hidden)]
+ pub fn is_valid_subcommand(&self, _name: &str) -> bool {
+ #[cfg(debug_assertions)]
+ {
+ _name.is_empty() || self.valid_subcommands.iter().any(|s| *s == _name)
+ }
+ #[cfg(not(debug_assertions))]
+ {
+ true
+ }
+ }
+}
+
+/// # Advanced
+impl ArgMatches {
+ /// Non-panicking version of [`ArgMatches::get_one`]
+ pub fn try_get_one<T: Any + Clone + Send + Sync + 'static>(
+ &self,
+ id: &str,
+ ) -> Result<Option<&T>, MatchesError> {
+ let arg = ok!(self.try_get_arg_t::<T>(id));
+ let value = match arg.and_then(|a| a.first()) {
+ Some(value) => value,
+ None => {
+ return Ok(None);
+ }
+ };
+ Ok(value
+ .downcast_ref::<T>()
+ .map(Some)
+ .expect(INTERNAL_ERROR_MSG)) // enforced by `try_get_arg_t`
+ }
+
+ /// Non-panicking version of [`ArgMatches::get_many`]
+ pub fn try_get_many<T: Any + Clone + Send + Sync + 'static>(
+ &self,
+ id: &str,
+ ) -> Result<Option<ValuesRef<T>>, MatchesError> {
+ let arg = match ok!(self.try_get_arg_t::<T>(id)) {
+ Some(arg) => arg,
+ None => return Ok(None),
+ };
+ let len = arg.num_vals();
+ let values = arg.vals_flatten();
+ let values = ValuesRef {
+ // enforced by `try_get_arg_t`
+ iter: values.map(unwrap_downcast_ref),
+ len,
+ };
+ Ok(Some(values))
+ }
+
+ /// Non-panicking version of [`ArgMatches::get_occurrences`]
+ pub fn try_get_occurrences<T: Any + Clone + Send + Sync + 'static>(
+ &self,
+ id: &str,
+ ) -> Result<Option<OccurrencesRef<T>>, MatchesError> {
+ let arg = match ok!(self.try_get_arg_t::<T>(id)) {
+ Some(arg) => arg,
+ None => return Ok(None),
+ };
+ let values = arg.vals();
+ Ok(Some(OccurrencesRef {
+ iter: values.map(|g| OccurrenceValuesRef {
+ iter: g.iter().map(unwrap_downcast_ref),
+ }),
+ }))
+ }
+
+ /// Non-panicking version of [`ArgMatches::get_raw`]
+ pub fn try_get_raw(&self, id: &str) -> Result<Option<RawValues<'_>>, MatchesError> {
+ let arg = match ok!(self.try_get_arg(id)) {
+ Some(arg) => arg,
+ None => return Ok(None),
+ };
+ let len = arg.num_vals();
+ let values = arg.raw_vals_flatten();
+ let values = RawValues {
+ iter: values.map(OsString::as_os_str),
+ len,
+ };
+ Ok(Some(values))
+ }
+
+ /// Non-panicking version of [`ArgMatches::get_raw_occurrences`]
+ pub fn try_get_raw_occurrences(
+ &self,
+ id: &str,
+ ) -> Result<Option<RawOccurrences<'_>>, MatchesError> {
+ let arg = match ok!(self.try_get_arg(id)) {
+ Some(arg) => arg,
+ None => return Ok(None),
+ };
+ let values = arg.raw_vals();
+ let occurrences = RawOccurrences {
+ iter: values.map(|g| RawOccurrenceValues {
+ iter: g.iter().map(OsString::as_os_str),
+ }),
+ };
+ Ok(Some(occurrences))
+ }
+
+ /// Non-panicking version of [`ArgMatches::remove_one`]
+ pub fn try_remove_one<T: Any + Clone + Send + Sync + 'static>(
+ &mut self,
+ id: &str,
+ ) -> Result<Option<T>, MatchesError> {
+ match ok!(self.try_remove_arg_t::<T>(id)) {
+ Some(values) => Ok(values
+ .into_vals_flatten()
+ // enforced by `try_get_arg_t`
+ .map(unwrap_downcast_into)
+ .next()),
+ None => Ok(None),
+ }
+ }
+
+ /// Non-panicking version of [`ArgMatches::remove_many`]
+ pub fn try_remove_many<T: Any + Clone + Send + Sync + 'static>(
+ &mut self,
+ id: &str,
+ ) -> Result<Option<Values<T>>, MatchesError> {
+ let arg = match ok!(self.try_remove_arg_t::<T>(id)) {
+ Some(arg) => arg,
+ None => return Ok(None),
+ };
+ let len = arg.num_vals();
+ let values = arg.into_vals_flatten();
+ let values = Values {
+ // enforced by `try_get_arg_t`
+ iter: values.map(unwrap_downcast_into),
+ len,
+ };
+ Ok(Some(values))
+ }
+
+ /// Non-panicking version of [`ArgMatches::remove_occurrences`]
+ pub fn try_remove_occurrences<T: Any + Clone + Send + Sync + 'static>(
+ &mut self,
+ id: &str,
+ ) -> Result<Option<Occurrences<T>>, MatchesError> {
+ let arg = match ok!(self.try_remove_arg_t::<T>(id)) {
+ Some(arg) => arg,
+ None => return Ok(None),
+ };
+ let values = arg.into_vals();
+ let occurrences = Occurrences {
+ iter: values.into_iter().map(|g| OccurrenceValues {
+ iter: g.into_iter().map(unwrap_downcast_into),
+ }),
+ };
+ Ok(Some(occurrences))
+ }
+
+ /// Non-panicking version of [`ArgMatches::contains_id`]
+ pub fn try_contains_id(&self, id: &str) -> Result<bool, MatchesError> {
+ ok!(self.verify_arg(id));
+
+ let presence = self.args.contains_key(id);
+ Ok(presence)
+ }
+}
+
+// Private methods
+impl ArgMatches {
+ #[inline]
+ fn try_get_arg(&self, arg: &str) -> Result<Option<&MatchedArg>, MatchesError> {
+ ok!(self.verify_arg(arg));
+ Ok(self.args.get(arg))
+ }
+
+ #[inline]
+ fn try_get_arg_t<T: Any + Send + Sync + 'static>(
+ &self,
+ arg: &str,
+ ) -> Result<Option<&MatchedArg>, MatchesError> {
+ let arg = match ok!(self.try_get_arg(arg)) {
+ Some(arg) => arg,
+ None => {
+ return Ok(None);
+ }
+ };
+ ok!(self.verify_arg_t::<T>(arg));
+ Ok(Some(arg))
+ }
+
+ #[inline]
+ fn try_remove_arg_t<T: Any + Send + Sync + 'static>(
+ &mut self,
+ arg: &str,
+ ) -> Result<Option<MatchedArg>, MatchesError> {
+ ok!(self.verify_arg(arg));
+ let (id, matched) = match self.args.remove_entry(arg) {
+ Some((id, matched)) => (id, matched),
+ None => {
+ return Ok(None);
+ }
+ };
+
+ let expected = AnyValueId::of::<T>();
+ let actual = matched.infer_type_id(expected);
+ if actual == expected {
+ Ok(Some(matched))
+ } else {
+ self.args.insert(id, matched);
+ Err(MatchesError::Downcast { actual, expected })
+ }
+ }
+
+ fn verify_arg_t<T: Any + Send + Sync + 'static>(
+ &self,
+ arg: &MatchedArg,
+ ) -> Result<(), MatchesError> {
+ let expected = AnyValueId::of::<T>();
+ let actual = arg.infer_type_id(expected);
+ if expected == actual {
+ Ok(())
+ } else {
+ Err(MatchesError::Downcast { actual, expected })
+ }
+ }
+
+ #[inline]
+ fn verify_arg(&self, _arg: &str) -> Result<(), MatchesError> {
+ #[cfg(debug_assertions)]
+ {
+ if _arg == Id::EXTERNAL || self.valid_args.iter().any(|s| *s == _arg) {
+ } else {
+ debug!(
+ "`{:?}` is not an id of an argument or a group.\n\
+ Make sure you're using the name of the argument itself \
+ and not the name of short or long flags.",
+ _arg
+ );
+ return Err(MatchesError::UnknownArgument {});
+ }
+ }
+ Ok(())
+ }
+
+ #[inline]
+ #[cfg_attr(debug_assertions, track_caller)]
+ fn get_arg<'s>(&'s self, arg: &str) -> Option<&'s MatchedArg> {
+ #[cfg(debug_assertions)]
+ {
+ if arg == Id::EXTERNAL || self.valid_args.iter().any(|s| *s == arg) {
+ } else {
+ panic!(
+ "`{arg:?}` is not an id of an argument or a group.\n\
+ Make sure you're using the name of the argument itself \
+ and not the name of short or long flags."
+ );
+ }
+ }
+
+ self.args.get(arg)
+ }
+
+ #[inline]
+ #[cfg_attr(debug_assertions, track_caller)]
+ fn get_subcommand(&self, name: &str) -> Option<&SubCommand> {
+ #[cfg(debug_assertions)]
+ {
+ if name.is_empty() || self.valid_subcommands.iter().any(|s| *s == name) {
+ } else {
+ panic!("`{name}` is not a name of a subcommand.");
+ }
+ }
+
+ if let Some(ref sc) = self.subcommand {
+ if sc.name == name {
+ return Some(sc);
+ }
+ }
+
+ None
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct SubCommand {
+ pub(crate) name: String,
+ pub(crate) matches: ArgMatches,
+}
+
+/// Iterate over [`Arg`][crate::Arg] and [`ArgGroup`][crate::ArgGroup] [`Id`][crate::Id]s via [`ArgMatches::ids`].
+///
+/// # Examples
+///
+/// ```
+/// # use clap::{Command, arg, value_parser};
+///
+/// let m = Command::new("myprog")
+/// .arg(arg!(--color <when>)
+/// .value_parser(["auto", "always", "never"]))
+/// .arg(arg!(--config <path>)
+/// .value_parser(value_parser!(std::path::PathBuf)))
+/// .get_matches_from(["myprog", "--config=config.toml", "--color=auto"]);
+/// assert_eq!(
+/// m.ids()
+/// .map(|id| id.as_str())
+/// .collect::<Vec<_>>(),
+/// ["config", "color"]
+/// );
+/// ```
+#[derive(Clone, Debug)]
+pub struct IdsRef<'a> {
+ iter: std::slice::Iter<'a, Id>,
+}
+
+impl<'a> Iterator for IdsRef<'a> {
+ type Item = &'a Id;
+
+ fn next(&mut self) -> Option<&'a Id> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+}
+
+impl<'a> DoubleEndedIterator for IdsRef<'a> {
+ fn next_back(&mut self) -> Option<&'a Id> {
+ self.iter.next_back()
+ }
+}
+
+impl<'a> ExactSizeIterator for IdsRef<'a> {}
+
+/// Iterate over multiple values for an argument via [`ArgMatches::remove_many`].
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::{Command, Arg, ArgAction};
+/// let mut m = Command::new("myapp")
+/// .arg(Arg::new("output")
+/// .short('o')
+/// .action(ArgAction::Append))
+/// .get_matches_from(vec!["myapp", "-o", "val1", "-o", "val2"]);
+///
+/// let mut values = m.remove_many::<String>("output")
+/// .unwrap();
+///
+/// assert_eq!(values.next(), Some(String::from("val1")));
+/// assert_eq!(values.next(), Some(String::from("val2")));
+/// assert_eq!(values.next(), None);
+/// ```
+#[derive(Clone, Debug)]
+pub struct Values<T> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Flatten<std::vec::IntoIter<Vec<AnyValue>>>, fn(AnyValue) -> T>,
+ len: usize,
+}
+
+impl<T> Iterator for Values<T> {
+ type Item = T;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
+ }
+}
+
+impl<T> DoubleEndedIterator for Values<T> {
+ fn next_back(&mut self) -> Option<Self::Item> {
+ self.iter.next_back()
+ }
+}
+
+impl<T> ExactSizeIterator for Values<T> {}
+
+/// Creates an empty iterator.
+impl<T> Default for Values<T> {
+ fn default() -> Self {
+ let empty: Vec<Vec<AnyValue>> = Default::default();
+ Values {
+ iter: empty.into_iter().flatten().map(|_| unreachable!()),
+ len: 0,
+ }
+ }
+}
+
+/// Iterate over multiple values for an argument via [`ArgMatches::get_many`].
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::{Command, Arg, ArgAction};
+/// let m = Command::new("myapp")
+/// .arg(Arg::new("output")
+/// .short('o')
+/// .action(ArgAction::Append))
+/// .get_matches_from(vec!["myapp", "-o", "val1", "-o", "val2"]);
+///
+/// let mut values = m.get_many::<String>("output")
+/// .unwrap()
+/// .map(|s| s.as_str());
+///
+/// assert_eq!(values.next(), Some("val1"));
+/// assert_eq!(values.next(), Some("val2"));
+/// assert_eq!(values.next(), None);
+/// ```
+#[derive(Clone, Debug)]
+pub struct ValuesRef<'a, T> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Flatten<Iter<'a, Vec<AnyValue>>>, fn(&AnyValue) -> &T>,
+ len: usize,
+}
+
+impl<'a, T: 'a> Iterator for ValuesRef<'a, T> {
+ type Item = &'a T;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
+ }
+}
+
+impl<'a, T: 'a> DoubleEndedIterator for ValuesRef<'a, T> {
+ fn next_back(&mut self) -> Option<Self::Item> {
+ self.iter.next_back()
+ }
+}
+
+impl<'a, T: 'a> ExactSizeIterator for ValuesRef<'a, T> {}
+
+/// Creates an empty iterator.
+impl<'a, T: 'a> Default for ValuesRef<'a, T> {
+ fn default() -> Self {
+ static EMPTY: [Vec<AnyValue>; 0] = [];
+ ValuesRef {
+ iter: EMPTY[..].iter().flatten().map(|_| unreachable!()),
+ len: 0,
+ }
+ }
+}
+
+/// Iterate over raw argument values via [`ArgMatches::get_raw`].
+///
+/// # Examples
+///
+#[cfg_attr(not(unix), doc = " ```ignore")]
+#[cfg_attr(unix, doc = " ```")]
+/// # use clap::{Command, arg, value_parser};
+/// use std::ffi::OsString;
+/// use std::os::unix::ffi::{OsStrExt,OsStringExt};
+///
+/// let m = Command::new("utf8")
+/// .arg(arg!(<arg> "some arg")
+/// .value_parser(value_parser!(OsString)))
+/// .get_matches_from(vec![OsString::from("myprog"),
+/// // "Hi {0xe9}!"
+/// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
+/// assert_eq!(
+/// &*m.get_raw("arg")
+/// .unwrap()
+/// .next().unwrap()
+/// .as_bytes(),
+/// [b'H', b'i', b' ', 0xe9, b'!']
+/// );
+/// ```
+#[derive(Clone, Debug)]
+pub struct RawValues<'a> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Flatten<Iter<'a, Vec<OsString>>>, fn(&OsString) -> &OsStr>,
+ len: usize,
+}
+
+impl<'a> Iterator for RawValues<'a> {
+ type Item = &'a OsStr;
+
+ fn next(&mut self) -> Option<&'a OsStr> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
+ }
+}
+
+impl<'a> DoubleEndedIterator for RawValues<'a> {
+ fn next_back(&mut self) -> Option<&'a OsStr> {
+ self.iter.next_back()
+ }
+}
+
+impl<'a> ExactSizeIterator for RawValues<'a> {}
+
+/// Creates an empty iterator.
+impl Default for RawValues<'_> {
+ fn default() -> Self {
+ static EMPTY: [Vec<OsString>; 0] = [];
+ RawValues {
+ iter: EMPTY[..].iter().flatten().map(|_| unreachable!()),
+ len: 0,
+ }
+ }
+}
+
+// The following were taken and adapted from vec_map source
+// repo: https://github.com/contain-rs/vec-map
+// commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33
+// license: MIT - Copyright (c) 2015 The Rust Project Developers
+
+#[derive(Clone, Debug)]
+#[deprecated(since = "4.1.0", note = "Use Occurrences instead")]
+pub struct GroupedValues<'a> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Iter<'a, Vec<AnyValue>>, fn(&Vec<AnyValue>) -> Vec<&str>>,
+ len: usize,
+}
+
+#[allow(deprecated)]
+impl<'a> Iterator for GroupedValues<'a> {
+ type Item = Vec<&'a str>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
+ }
+}
+
+#[allow(deprecated)]
+impl<'a> DoubleEndedIterator for GroupedValues<'a> {
+ fn next_back(&mut self) -> Option<Self::Item> {
+ self.iter.next_back()
+ }
+}
+
+#[allow(deprecated)]
+impl<'a> ExactSizeIterator for GroupedValues<'a> {}
+
+/// Creates an empty iterator. Used for `unwrap_or_default()`.
+#[allow(deprecated)]
+impl<'a> Default for GroupedValues<'a> {
+ fn default() -> Self {
+ static EMPTY: [Vec<AnyValue>; 0] = [];
+ GroupedValues {
+ iter: EMPTY[..].iter().map(|_| unreachable!()),
+ len: 0,
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct Occurrences<T> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<std::vec::IntoIter<Vec<AnyValue>>, fn(Vec<AnyValue>) -> OccurrenceValues<T>>,
+}
+
+impl<T> Iterator for Occurrences<T> {
+ type Item = OccurrenceValues<T>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.iter.next()
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+}
+
+impl<T> DoubleEndedIterator for Occurrences<T> {
+ fn next_back(&mut self) -> Option<Self::Item> {
+ self.iter.next_back()
+ }
+}
+
+impl<T> ExactSizeIterator for Occurrences<T> {}
+
+impl<T> Default for Occurrences<T> {
+ fn default() -> Self {
+ let empty: Vec<Vec<AnyValue>> = Default::default();
+ Occurrences {
+ iter: empty.into_iter().map(|_| unreachable!()),
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct OccurrenceValues<T> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<std::vec::IntoIter<AnyValue>, fn(AnyValue) -> T>,
+}
+
+impl<T> Iterator for OccurrenceValues<T> {
+ type Item = T;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.iter.next()
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+}
+
+impl<T> DoubleEndedIterator for OccurrenceValues<T> {
+ fn next_back(&mut self) -> Option<Self::Item> {
+ self.iter.next_back()
+ }
+}
+
+impl<T> ExactSizeIterator for OccurrenceValues<T> {}
+
+#[derive(Clone, Debug)]
+pub struct OccurrencesRef<'a, T> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Iter<'a, Vec<AnyValue>>, fn(&Vec<AnyValue>) -> OccurrenceValuesRef<'_, T>>,
+}
+
+impl<'a, T> Iterator for OccurrencesRef<'a, T>
+where
+ Self: 'a,
+{
+ type Item = OccurrenceValuesRef<'a, T>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.iter.next()
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+}
+
+impl<'a, T> DoubleEndedIterator for OccurrencesRef<'a, T>
+where
+ Self: 'a,
+{
+ fn next_back(&mut self) -> Option<Self::Item> {
+ self.iter.next_back()
+ }
+}
+
+impl<'a, T> ExactSizeIterator for OccurrencesRef<'a, T> where Self: 'a {}
+impl<'a, T> Default for OccurrencesRef<'a, T> {
+ fn default() -> Self {
+ static EMPTY: [Vec<AnyValue>; 0] = [];
+ OccurrencesRef {
+ iter: EMPTY[..].iter().map(|_| unreachable!()),
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct OccurrenceValuesRef<'a, T> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Iter<'a, AnyValue>, fn(&AnyValue) -> &T>,
+}
+
+impl<'a, T> Iterator for OccurrenceValuesRef<'a, T>
+where
+ Self: 'a,
+{
+ type Item = &'a T;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.iter.next()
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+}
+
+impl<'a, T> DoubleEndedIterator for OccurrenceValuesRef<'a, T>
+where
+ Self: 'a,
+{
+ fn next_back(&mut self) -> Option<Self::Item> {
+ self.iter.next_back()
+ }
+}
+
+impl<'a, T> ExactSizeIterator for OccurrenceValuesRef<'a, T> where Self: 'a {}
+
+#[derive(Clone, Debug)]
+pub struct RawOccurrences<'a> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Iter<'a, Vec<OsString>>, fn(&Vec<OsString>) -> RawOccurrenceValues<'_>>,
+}
+
+impl<'a> Iterator for RawOccurrences<'a> {
+ type Item = RawOccurrenceValues<'a>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.iter.next()
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+}
+
+impl<'a> DoubleEndedIterator for RawOccurrences<'a> {
+ fn next_back(&mut self) -> Option<Self::Item> {
+ self.iter.next_back()
+ }
+}
+
+impl<'a> ExactSizeIterator for RawOccurrences<'a> {}
+
+impl<'a> Default for RawOccurrences<'a> {
+ fn default() -> Self {
+ static EMPTY: [Vec<OsString>; 0] = [];
+ RawOccurrences {
+ iter: EMPTY[..].iter().map(|_| unreachable!()),
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct RawOccurrenceValues<'a> {
+ #[allow(clippy::type_complexity)]
+ iter: Map<Iter<'a, OsString>, fn(&OsString) -> &OsStr>,
+}
+
+impl<'a> Iterator for RawOccurrenceValues<'a>
+where
+ Self: 'a,
+{
+ type Item = &'a OsStr;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.iter.next()
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+}
+
+impl<'a> DoubleEndedIterator for RawOccurrenceValues<'a>
+where
+ Self: 'a,
+{
+ fn next_back(&mut self) -> Option<Self::Item> {
+ self.iter.next_back()
+ }
+}
+
+impl<'a> ExactSizeIterator for RawOccurrenceValues<'a> {}
+
+/// Iterate over indices for where an argument appeared when parsing, via [`ArgMatches::indices_of`]
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::{Command, Arg, ArgAction};
+/// let m = Command::new("myapp")
+/// .arg(Arg::new("output")
+/// .short('o')
+/// .num_args(1..)
+/// .action(ArgAction::Set))
+/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]);
+///
+/// let mut indices = m.indices_of("output").unwrap();
+///
+/// assert_eq!(indices.next(), Some(2));
+/// assert_eq!(indices.next(), Some(3));
+/// assert_eq!(indices.next(), None);
+/// ```
+/// [`ArgMatches::indices_of`]: ArgMatches::indices_of()
+#[derive(Clone, Debug)]
+pub struct Indices<'a> {
+ iter: Cloned<Iter<'a, usize>>,
+ len: usize,
+}
+
+impl<'a> Iterator for Indices<'a> {
+ type Item = usize;
+
+ fn next(&mut self) -> Option<usize> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.len, Some(self.len))
+ }
+}
+
+impl<'a> DoubleEndedIterator for Indices<'a> {
+ fn next_back(&mut self) -> Option<usize> {
+ self.iter.next_back()
+ }
+}
+
+impl<'a> ExactSizeIterator for Indices<'a> {}
+
+/// Creates an empty iterator.
+impl<'a> Default for Indices<'a> {
+ fn default() -> Self {
+ static EMPTY: [usize; 0] = [];
+ // This is never called because the iterator is empty:
+ Indices {
+ iter: EMPTY[..].iter().cloned(),
+ len: 0,
+ }
+ }
+}
+
+#[cfg_attr(debug_assertions, track_caller)]
+#[inline]
+#[cfg(feature = "unstable-grouped")]
+fn unwrap_string(value: &AnyValue) -> &str {
+ match value.downcast_ref::<String>() {
+ Some(value) => value,
+ None => {
+ panic!("Must use `_os` lookups with `Arg::allow_invalid_utf8`",)
+ }
+ }
+}
+
+#[track_caller]
+fn unwrap_downcast_ref<T: Any + Clone + Send + Sync + 'static>(value: &AnyValue) -> &T {
+ value.downcast_ref().expect(INTERNAL_ERROR_MSG)
+}
+
+#[track_caller]
+fn unwrap_downcast_into<T: Any + Clone + Send + Sync + 'static>(value: AnyValue) -> T {
+ value.downcast_into().expect(INTERNAL_ERROR_MSG)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ use crate::ArgAction;
+
+ #[test]
+ fn check_auto_traits() {
+ static_assertions::assert_impl_all!(ArgMatches: Send, Sync, Unpin);
+ }
+
+ #[test]
+ fn test_default_raw_values() {
+ let mut values: RawValues = Default::default();
+ assert_eq!(values.next(), None);
+ }
+
+ #[test]
+ fn test_default_indices() {
+ let mut indices: Indices = Indices::default();
+ assert_eq!(indices.next(), None);
+ }
+
+ #[test]
+ fn test_default_indices_with_shorter_lifetime() {
+ let matches = ArgMatches::default();
+ let mut indices = matches.indices_of("").unwrap_or_default();
+ assert_eq!(indices.next(), None);
+ }
+
+ #[test]
+ fn values_exact_size() {
+ let l = crate::Command::new("test")
+ .arg(
+ crate::Arg::new("POTATO")
+ .action(ArgAction::Set)
+ .num_args(1..)
+ .required(true),
+ )
+ .try_get_matches_from(["test", "one"])
+ .unwrap()
+ .get_many::<String>("POTATO")
+ .expect("present")
+ .count();
+ assert_eq!(l, 1);
+ }
+
+ #[test]
+ fn os_values_exact_size() {
+ let l = crate::Command::new("test")
+ .arg(
+ crate::Arg::new("POTATO")
+ .action(ArgAction::Set)
+ .num_args(1..)
+ .value_parser(crate::builder::ValueParser::os_string())
+ .required(true),
+ )
+ .try_get_matches_from(["test", "one"])
+ .unwrap()
+ .get_many::<std::ffi::OsString>("POTATO")
+ .expect("present")
+ .count();
+ assert_eq!(l, 1);
+ }
+
+ #[test]
+ fn indices_exact_size() {
+ let l = crate::Command::new("test")
+ .arg(
+ crate::Arg::new("POTATO")
+ .action(ArgAction::Set)
+ .num_args(1..)
+ .required(true),
+ )
+ .try_get_matches_from(["test", "one"])
+ .unwrap()
+ .indices_of("POTATO")
+ .expect("present")
+ .len();
+ assert_eq!(l, 1);
+ }
+}
diff --git a/src/parser/matches/matched_arg.rs b/src/parser/matches/matched_arg.rs
new file mode 100644
index 0000000..901990c
--- /dev/null
+++ b/src/parser/matches/matched_arg.rs
@@ -0,0 +1,225 @@
+// Std
+use std::{
+ ffi::{OsStr, OsString},
+ iter::{Cloned, Flatten},
+ slice::Iter,
+};
+
+use crate::builder::ArgPredicate;
+use crate::parser::AnyValue;
+use crate::parser::AnyValueId;
+use crate::parser::ValueSource;
+use crate::util::eq_ignore_case;
+use crate::INTERNAL_ERROR_MSG;
+
+#[derive(Debug, Clone)]
+pub(crate) struct MatchedArg {
+ source: Option<ValueSource>,
+ indices: Vec<usize>,
+ type_id: Option<AnyValueId>,
+ vals: Vec<Vec<AnyValue>>,
+ raw_vals: Vec<Vec<OsString>>,
+ ignore_case: bool,
+}
+
+impl MatchedArg {
+ pub(crate) fn new_arg(arg: &crate::Arg) -> Self {
+ let ignore_case = arg.is_ignore_case_set();
+ Self {
+ source: None,
+ indices: Vec::new(),
+ type_id: Some(arg.get_value_parser().type_id()),
+ vals: Vec::new(),
+ raw_vals: Vec::new(),
+ ignore_case,
+ }
+ }
+
+ pub(crate) fn new_group() -> Self {
+ let ignore_case = false;
+ Self {
+ source: None,
+ indices: Vec::new(),
+ type_id: None,
+ vals: Vec::new(),
+ raw_vals: Vec::new(),
+ ignore_case,
+ }
+ }
+
+ pub(crate) fn new_external(cmd: &crate::Command) -> Self {
+ let ignore_case = false;
+ Self {
+ source: None,
+ indices: Vec::new(),
+ type_id: Some(
+ cmd.get_external_subcommand_value_parser()
+ .expect(INTERNAL_ERROR_MSG)
+ .type_id(),
+ ),
+ vals: Vec::new(),
+ raw_vals: Vec::new(),
+ ignore_case,
+ }
+ }
+
+ pub(crate) fn indices(&self) -> Cloned<Iter<'_, usize>> {
+ self.indices.iter().cloned()
+ }
+
+ pub(crate) fn get_index(&self, index: usize) -> Option<usize> {
+ self.indices.get(index).cloned()
+ }
+
+ pub(crate) fn push_index(&mut self, index: usize) {
+ self.indices.push(index)
+ }
+
+ pub(crate) fn vals(&self) -> Iter<Vec<AnyValue>> {
+ self.vals.iter()
+ }
+
+ pub(crate) fn into_vals(self) -> Vec<Vec<AnyValue>> {
+ self.vals
+ }
+
+ pub(crate) fn vals_flatten(&self) -> Flatten<Iter<Vec<AnyValue>>> {
+ self.vals.iter().flatten()
+ }
+
+ pub(crate) fn into_vals_flatten(self) -> Flatten<std::vec::IntoIter<Vec<AnyValue>>> {
+ self.vals.into_iter().flatten()
+ }
+
+ pub(crate) fn raw_vals(&self) -> Iter<Vec<OsString>> {
+ self.raw_vals.iter()
+ }
+
+ pub(crate) fn raw_vals_flatten(&self) -> Flatten<Iter<Vec<OsString>>> {
+ self.raw_vals.iter().flatten()
+ }
+
+ pub(crate) fn first(&self) -> Option<&AnyValue> {
+ self.vals_flatten().next()
+ }
+
+ #[cfg(test)]
+ pub(crate) fn first_raw(&self) -> Option<&OsString> {
+ self.raw_vals_flatten().next()
+ }
+
+ pub(crate) fn new_val_group(&mut self) {
+ self.vals.push(vec![]);
+ self.raw_vals.push(vec![]);
+ }
+
+ pub(crate) fn append_val(&mut self, val: AnyValue, raw_val: OsString) {
+ // We assume there is always a group created before.
+ self.vals.last_mut().expect(INTERNAL_ERROR_MSG).push(val);
+ self.raw_vals
+ .last_mut()
+ .expect(INTERNAL_ERROR_MSG)
+ .push(raw_val);
+ }
+
+ pub(crate) fn num_vals(&self) -> usize {
+ self.vals.iter().map(|v| v.len()).sum()
+ }
+
+ // Will be used later
+ #[allow(dead_code)]
+ pub(crate) fn num_vals_last_group(&self) -> usize {
+ self.vals.last().map(|x| x.len()).unwrap_or(0)
+ }
+
+ pub(crate) fn all_val_groups_empty(&self) -> bool {
+ self.vals.iter().flatten().count() == 0
+ }
+
+ pub(crate) fn check_explicit(&self, predicate: &ArgPredicate) -> bool {
+ if self.source.map(|s| !s.is_explicit()).unwrap_or(false) {
+ return false;
+ }
+
+ match predicate {
+ ArgPredicate::Equals(val) => self.raw_vals_flatten().any(|v| {
+ if self.ignore_case {
+ // If `v` isn't utf8, it can't match `val`, so `OsStr::to_str` should be fine
+ eq_ignore_case(&v.to_string_lossy(), &val.to_string_lossy())
+ } else {
+ OsString::as_os_str(v) == OsStr::new(val)
+ }
+ }),
+ ArgPredicate::IsPresent => true,
+ }
+ }
+
+ pub(crate) fn source(&self) -> Option<ValueSource> {
+ self.source
+ }
+
+ pub(crate) fn set_source(&mut self, source: ValueSource) {
+ if let Some(existing) = self.source {
+ self.source = Some(existing.max(source));
+ } else {
+ self.source = Some(source)
+ }
+ }
+
+ pub(crate) fn type_id(&self) -> Option<AnyValueId> {
+ self.type_id
+ }
+
+ pub(crate) fn infer_type_id(&self, expected: AnyValueId) -> AnyValueId {
+ self.type_id()
+ .or_else(|| {
+ self.vals_flatten()
+ .map(|v| v.type_id())
+ .find(|actual| *actual != expected)
+ })
+ .unwrap_or(expected)
+ }
+}
+
+impl PartialEq for MatchedArg {
+ fn eq(&self, other: &MatchedArg) -> bool {
+ let MatchedArg {
+ source: self_source,
+ indices: self_indices,
+ type_id: self_type_id,
+ vals: _,
+ raw_vals: self_raw_vals,
+ ignore_case: self_ignore_case,
+ } = self;
+ let MatchedArg {
+ source: other_source,
+ indices: other_indices,
+ type_id: other_type_id,
+ vals: _,
+ raw_vals: other_raw_vals,
+ ignore_case: other_ignore_case,
+ } = other;
+ self_source == other_source
+ && self_indices == other_indices
+ && self_type_id == other_type_id
+ && self_raw_vals == other_raw_vals
+ && self_ignore_case == other_ignore_case
+ }
+}
+
+impl Eq for MatchedArg {}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_grouped_vals_first() {
+ let mut m = MatchedArg::new_group();
+ m.new_val_group();
+ m.new_val_group();
+ m.append_val(AnyValue::new(String::from("bbb")), "bbb".into());
+ m.append_val(AnyValue::new(String::from("ccc")), "ccc".into());
+ assert_eq!(m.first_raw(), Some(&OsString::from("bbb")));
+ }
+}
diff --git a/src/parser/matches/mod.rs b/src/parser/matches/mod.rs
new file mode 100644
index 0000000..0e3474f
--- /dev/null
+++ b/src/parser/matches/mod.rs
@@ -0,0 +1,16 @@
+mod any_value;
+mod arg_matches;
+mod matched_arg;
+mod value_source;
+
+pub use any_value::AnyValueId;
+pub use arg_matches::IdsRef;
+pub use arg_matches::RawValues;
+pub use arg_matches::Values;
+pub use arg_matches::ValuesRef;
+pub use arg_matches::{ArgMatches, Indices};
+pub use value_source::ValueSource;
+
+pub(crate) use any_value::AnyValue;
+pub(crate) use arg_matches::SubCommand;
+pub(crate) use matched_arg::MatchedArg;
diff --git a/src/parser/matches/value_source.rs b/src/parser/matches/value_source.rs
new file mode 100644
index 0000000..db45d9c
--- /dev/null
+++ b/src/parser/matches/value_source.rs
@@ -0,0 +1,17 @@
+/// Origin of the argument's value
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+#[non_exhaustive]
+pub enum ValueSource {
+ /// Value came [`Arg::default_value`][crate::Arg::default_value]
+ DefaultValue,
+ /// Value came [`Arg::env`][crate::Arg::env]
+ EnvVariable,
+ /// Value was passed in on the command-line
+ CommandLine,
+}
+
+impl ValueSource {
+ pub(crate) fn is_explicit(self) -> bool {
+ self != Self::DefaultValue
+ }
+}
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
new file mode 100644
index 0000000..c99e74f
--- /dev/null
+++ b/src/parser/mod.rs
@@ -0,0 +1,27 @@
+//! [`Command`][crate::Command] line argument parser
+
+mod arg_matcher;
+mod error;
+mod matches;
+#[allow(clippy::module_inception)]
+mod parser;
+mod validator;
+
+pub(crate) mod features;
+
+pub(crate) use self::arg_matcher::ArgMatcher;
+pub(crate) use self::matches::AnyValue;
+pub(crate) use self::matches::AnyValueId;
+pub(crate) use self::matches::{MatchedArg, SubCommand};
+pub(crate) use self::parser::Identifier;
+pub(crate) use self::parser::PendingArg;
+pub(crate) use self::parser::{ParseState, Parser};
+pub(crate) use self::validator::get_possible_values_cli;
+pub(crate) use self::validator::Validator;
+
+pub use self::matches::IdsRef;
+pub use self::matches::RawValues;
+pub use self::matches::Values;
+pub use self::matches::ValuesRef;
+pub use self::matches::{ArgMatches, Indices, ValueSource};
+pub use error::MatchesError;
diff --git a/src/parser/parser.rs b/src/parser/parser.rs
new file mode 100644
index 0000000..2579034
--- /dev/null
+++ b/src/parser/parser.rs
@@ -0,0 +1,1642 @@
+// Std
+use std::{
+ cell::Cell,
+ ffi::{OsStr, OsString},
+};
+
+// Third Party
+use clap_lex::RawOsStr;
+use clap_lex::RawOsString;
+
+// Internal
+use crate::builder::{Arg, Command};
+use crate::error::Error as ClapError;
+use crate::error::Result as ClapResult;
+use crate::mkeymap::KeyType;
+use crate::output::Usage;
+use crate::parser::features::suggestions;
+use crate::parser::AnyValue;
+use crate::parser::{ArgMatcher, SubCommand};
+use crate::parser::{Validator, ValueSource};
+use crate::util::Id;
+use crate::ArgAction;
+use crate::INTERNAL_ERROR_MSG;
+
+pub(crate) struct Parser<'cmd> {
+ cmd: &'cmd mut Command,
+ cur_idx: Cell<usize>,
+ /// Index of the previous flag subcommand in a group of flags.
+ flag_subcmd_at: Option<usize>,
+ /// Counter indicating the number of items to skip
+ /// when revisiting the group of flags which includes the flag subcommand.
+ flag_subcmd_skip: usize,
+}
+
+// Initializing Methods
+impl<'cmd> Parser<'cmd> {
+ pub(crate) fn new(cmd: &'cmd mut Command) -> Self {
+ Parser {
+ cmd,
+ cur_idx: Cell::new(0),
+ flag_subcmd_at: None,
+ flag_subcmd_skip: 0,
+ }
+ }
+}
+
+// Parsing Methods
+impl<'cmd> Parser<'cmd> {
+ // The actual parsing function
+ #[allow(clippy::cognitive_complexity)]
+ pub(crate) fn get_matches_with(
+ &mut self,
+ matcher: &mut ArgMatcher,
+ raw_args: &mut clap_lex::RawArgs,
+ mut args_cursor: clap_lex::ArgCursor,
+ ) -> ClapResult<()> {
+ debug!("Parser::get_matches_with");
+ // Verify all positional assertions pass
+
+ let mut subcmd_name: Option<String> = None;
+ let mut keep_state = false;
+ let mut parse_state = ParseState::ValuesDone;
+ let mut pos_counter = 1;
+
+ // Already met any valid arg(then we shouldn't expect subcommands after it).
+ let mut valid_arg_found = false;
+ // If the user already passed '--'. Meaning only positional args follow.
+ let mut trailing_values = false;
+
+ // Count of positional args
+ let positional_count = self
+ .cmd
+ .get_keymap()
+ .keys()
+ .filter(|x| x.is_position())
+ .count();
+ // If any arg sets .last(true)
+ let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set());
+
+ while let Some(arg_os) = raw_args.next(&mut args_cursor) {
+ // Recover the replaced items if any.
+ if let Some(replaced_items) = arg_os
+ .to_value()
+ .ok()
+ .and_then(|a| self.cmd.get_replacement(a))
+ {
+ debug!(
+ "Parser::get_matches_with: found replacer: {:?}, target: {:?}",
+ arg_os, replaced_items
+ );
+ raw_args.insert(&args_cursor, replaced_items);
+ continue;
+ }
+
+ debug!(
+ "Parser::get_matches_with: Begin parsing '{:?}' ({:?})",
+ arg_os.to_value_os(),
+ arg_os.to_value_os().as_raw_bytes()
+ );
+
+ // Has the user already passed '--'? Meaning only positional args follow
+ if !trailing_values {
+ if self.cmd.is_subcommand_precedence_over_arg_set()
+ || !matches!(parse_state, ParseState::Opt(_) | ParseState::Pos(_))
+ {
+ // Does the arg match a subcommand name, or any of its aliases (if defined)
+ let sc_name = self.possible_subcommand(arg_os.to_value(), valid_arg_found);
+ debug!("Parser::get_matches_with: sc={:?}", sc_name);
+ if let Some(sc_name) = sc_name {
+ if sc_name == "help" && !self.cmd.is_disable_help_subcommand_set() {
+ ok!(self.parse_help_subcommand(raw_args.remaining(&mut args_cursor)));
+ unreachable!("`parse_help_subcommand` always errors");
+ } else {
+ subcmd_name = Some(sc_name.to_owned());
+ }
+ break;
+ }
+ }
+
+ if arg_os.is_escape() {
+ if matches!(&parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
+ self.cmd[opt].is_allow_hyphen_values_set())
+ {
+ // ParseResult::MaybeHyphenValue, do nothing
+ } else {
+ debug!("Parser::get_matches_with: setting TrailingVals=true");
+ trailing_values = true;
+ matcher.start_trailing();
+ continue;
+ }
+ } else if let Some((long_arg, long_value)) = arg_os.to_long() {
+ let parse_result = ok!(self.parse_long_arg(
+ matcher,
+ long_arg,
+ long_value,
+ &parse_state,
+ pos_counter,
+ &mut valid_arg_found,
+ ));
+ debug!(
+ "Parser::get_matches_with: After parse_long_arg {:?}",
+ parse_result
+ );
+ match parse_result {
+ ParseResult::NoArg => {
+ unreachable!("`to_long` always has the flag specified")
+ }
+ ParseResult::ValuesDone => {
+ parse_state = ParseState::ValuesDone;
+ continue;
+ }
+ ParseResult::Opt(id) => {
+ parse_state = ParseState::Opt(id);
+ continue;
+ }
+ ParseResult::FlagSubCommand(name) => {
+ debug!(
+ "Parser::get_matches_with: FlagSubCommand found in long arg {:?}",
+ &name
+ );
+ subcmd_name = Some(name);
+ break;
+ }
+ ParseResult::EqualsNotProvided { arg } => {
+ let _ = self.resolve_pending(matcher);
+ return Err(ClapError::no_equals(
+ self.cmd,
+ arg,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+ ParseResult::NoMatchingArg { arg } => {
+ let _ = self.resolve_pending(matcher);
+ let remaining_args: Vec<_> =
+ raw_args.remaining(&mut args_cursor).collect();
+ return Err(self.did_you_mean_error(
+ &arg,
+ matcher,
+ &remaining_args,
+ trailing_values,
+ ));
+ }
+ ParseResult::UnneededAttachedValue { rest, used, arg } => {
+ let _ = self.resolve_pending(matcher);
+ return Err(ClapError::too_many_values(
+ self.cmd,
+ rest,
+ arg,
+ Usage::new(self.cmd).create_usage_with_title(&used),
+ ));
+ }
+ ParseResult::MaybeHyphenValue => {
+ // Maybe a hyphen value, do nothing.
+ }
+ ParseResult::AttachedValueNotConsumed => {
+ unreachable!()
+ }
+ }
+ } else if let Some(short_arg) = arg_os.to_short() {
+ // Arg looks like a short flag, and not a possible number
+
+ // Try to parse short args like normal, if allow_hyphen_values or
+ // AllowNegativeNumbers is set, parse_short_arg will *not* throw
+ // an error, and instead return Ok(None)
+ let parse_result = ok!(self.parse_short_arg(
+ matcher,
+ short_arg,
+ &parse_state,
+ pos_counter,
+ &mut valid_arg_found,
+ ));
+ // If it's None, we then check if one of those two AppSettings was set
+ debug!(
+ "Parser::get_matches_with: After parse_short_arg {:?}",
+ parse_result
+ );
+ match parse_result {
+ ParseResult::NoArg => {
+ // Is a single dash `-`, try positional.
+ }
+ ParseResult::ValuesDone => {
+ parse_state = ParseState::ValuesDone;
+ continue;
+ }
+ ParseResult::Opt(id) => {
+ parse_state = ParseState::Opt(id);
+ continue;
+ }
+ ParseResult::FlagSubCommand(name) => {
+ // If there are more short flags to be processed, we should keep the state, and later
+ // revisit the current group of short flags skipping the subcommand.
+ keep_state = self
+ .flag_subcmd_at
+ .map(|at| {
+ raw_args
+ .seek(&mut args_cursor, clap_lex::SeekFrom::Current(-1));
+ // Since we are now saving the current state, the number of flags to skip during state recovery should
+ // be the current index (`cur_idx`) minus ONE UNIT TO THE LEFT of the starting position.
+ self.flag_subcmd_skip = self.cur_idx.get() - at + 1;
+ })
+ .is_some();
+
+ debug!(
+ "Parser::get_matches_with:FlagSubCommandShort: subcmd_name={}, keep_state={}, flag_subcmd_skip={}",
+ name,
+ keep_state,
+ self.flag_subcmd_skip
+ );
+
+ subcmd_name = Some(name);
+ break;
+ }
+ ParseResult::EqualsNotProvided { arg } => {
+ let _ = self.resolve_pending(matcher);
+ return Err(ClapError::no_equals(
+ self.cmd,
+ arg,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+ ParseResult::NoMatchingArg { arg } => {
+ let _ = self.resolve_pending(matcher);
+ // We already know it looks like a flag
+ let suggested_trailing_arg =
+ !trailing_values && self.cmd.has_positionals();
+ return Err(ClapError::unknown_argument(
+ self.cmd,
+ arg,
+ None,
+ suggested_trailing_arg,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+ ParseResult::MaybeHyphenValue => {
+ // Maybe a hyphen value, do nothing.
+ }
+ ParseResult::UnneededAttachedValue { .. }
+ | ParseResult::AttachedValueNotConsumed => unreachable!(),
+ }
+ }
+
+ if let ParseState::Opt(id) = &parse_state {
+ // Assume this is a value of a previous arg.
+
+ // get the option so we can check the settings
+ let arg = &self.cmd[id];
+ let parse_result = if let Some(parse_result) =
+ self.check_terminator(arg, arg_os.to_value_os())
+ {
+ parse_result
+ } else {
+ let trailing_values = false;
+ let arg_values = matcher.pending_values_mut(id, None, trailing_values);
+ arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
+ if matcher.needs_more_vals(arg) {
+ ParseResult::Opt(arg.get_id().clone())
+ } else {
+ ParseResult::ValuesDone
+ }
+ };
+ parse_state = match parse_result {
+ ParseResult::Opt(id) => ParseState::Opt(id),
+ ParseResult::ValuesDone => ParseState::ValuesDone,
+ _ => unreachable!(),
+ };
+ // get the next value from the iterator
+ continue;
+ }
+ }
+
+ // 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.get_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.get_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);
+ // Its already considered a positional, we don't need to suggest turning it
+ // into one
+ let suggested_trailing_arg = false;
+ return Err(ClapError::unknown_argument(
+ self.cmd,
+ arg_os.display().to_string(),
+ None,
+ suggested_trailing_arg,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+
+ if arg.is_trailing_var_arg_set() {
+ trailing_values = true;
+ }
+
+ if matcher.pending_arg_id() != Some(arg.get_id()) || !arg.is_multiple_values_set() {
+ ok!(self.resolve_pending(matcher));
+ }
+ if let Some(_parse_result) = self.check_terminator(arg, arg_os.to_value_os()) {
+ debug!(
+ "Parser::get_matches_with: ignoring terminator result {:?}",
+ _parse_result
+ );
+ } else {
+ let arg_values = matcher.pending_values_mut(
+ arg.get_id(),
+ Some(Identifier::Index),
+ trailing_values,
+ );
+ arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
+ }
+
+ // Only increment the positional counter if it doesn't allow multiples
+ if !arg.is_multiple() {
+ pos_counter += 1;
+ parse_state = ParseState::ValuesDone;
+ } else {
+ parse_state = ParseState::Pos(arg.get_id().clone());
+ }
+ valid_arg_found = true;
+ } else if let Some(external_parser) =
+ self.cmd.get_external_subcommand_value_parser().cloned()
+ {
+ // Get external subcommand name
+ let sc_name = match arg_os.to_value() {
+ Ok(s) => s.to_owned(),
+ Err(_) => {
+ let _ = self.resolve_pending(matcher);
+ return Err(ClapError::invalid_utf8(
+ self.cmd,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+ };
+
+ // Collect the external subcommand args
+ let mut sc_m = ArgMatcher::new(self.cmd);
+ sc_m.start_occurrence_of_external(self.cmd);
+
+ for raw_val in raw_args.remaining(&mut args_cursor) {
+ let val = ok!(external_parser.parse_ref(self.cmd, None, raw_val));
+ let external_id = Id::from_static_ref(Id::EXTERNAL);
+ sc_m.add_val_to(&external_id, val, raw_val.to_os_string());
+ }
+
+ matcher.subcommand(SubCommand {
+ name: sc_name,
+ matches: sc_m.into_inner(),
+ });
+
+ ok!(self.resolve_pending(matcher));
+ #[cfg(feature = "env")]
+ ok!(self.add_env(matcher));
+ ok!(self.add_defaults(matcher));
+ return Validator::new(self.cmd).validate(parse_state, matcher);
+ } else {
+ // Start error processing
+ let _ = self.resolve_pending(matcher);
+ return Err(self.match_arg_error(&arg_os, valid_arg_found, trailing_values));
+ }
+ }
+
+ if let Some(ref pos_sc_name) = subcmd_name {
+ let sc_name = self
+ .cmd
+ .find_subcommand(pos_sc_name)
+ .expect(INTERNAL_ERROR_MSG)
+ .get_name()
+ .to_owned();
+ ok!(self.parse_subcommand(&sc_name, matcher, raw_args, args_cursor, keep_state));
+ }
+
+ ok!(self.resolve_pending(matcher));
+ #[cfg(feature = "env")]
+ ok!(self.add_env(matcher));
+ ok!(self.add_defaults(matcher));
+ Validator::new(self.cmd).validate(parse_state, matcher)
+ }
+
+ fn match_arg_error(
+ &self,
+ arg_os: &clap_lex::ParsedArg<'_>,
+ valid_arg_found: bool,
+ trailing_values: bool,
+ ) -> ClapError {
+ // If argument follows a `--`
+ if trailing_values {
+ // If the arg matches a subcommand name, or any of its aliases (if defined)
+ if self
+ .possible_subcommand(arg_os.to_value(), valid_arg_found)
+ .is_some()
+ {
+ return ClapError::unnecessary_double_dash(
+ self.cmd,
+ arg_os.display().to_string(),
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ );
+ }
+ }
+
+ if !(self.cmd.is_args_conflicts_with_subcommands_set() && valid_arg_found) {
+ let candidates = suggestions::did_you_mean(
+ &arg_os.display().to_string(),
+ self.cmd.all_subcommand_names(),
+ );
+ // If the argument looks like a subcommand.
+ if !candidates.is_empty() {
+ return ClapError::invalid_subcommand(
+ self.cmd,
+ arg_os.display().to_string(),
+ candidates,
+ self.cmd
+ .get_bin_name()
+ .unwrap_or_else(|| self.cmd.get_name())
+ .to_owned(),
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ );
+ }
+
+ // If the argument must be a subcommand.
+ if self.cmd.has_subcommands()
+ && (!self.cmd.has_positionals() || self.cmd.is_infer_subcommands_set())
+ {
+ return ClapError::unrecognized_subcommand(
+ self.cmd,
+ arg_os.display().to_string(),
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ );
+ }
+ }
+
+ let suggested_trailing_arg = !trailing_values
+ && self.cmd.has_positionals()
+ && (arg_os.is_long() || arg_os.is_short());
+ ClapError::unknown_argument(
+ self.cmd,
+ arg_os.display().to_string(),
+ None,
+ suggested_trailing_arg,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ )
+ }
+
+ // Checks if the arg matches a subcommand name, or any of its aliases (if defined)
+ fn possible_subcommand(
+ &self,
+ arg: Result<&str, &RawOsStr>,
+ valid_arg_found: bool,
+ ) -> Option<&str> {
+ debug!("Parser::possible_subcommand: arg={:?}", arg);
+ let arg = some!(arg.ok());
+
+ if !(self.cmd.is_args_conflicts_with_subcommands_set() && valid_arg_found) {
+ if self.cmd.is_infer_subcommands_set() {
+ // For subcommand `test`, we accepts it's prefix: `t`, `te`,
+ // `tes` and `test`.
+ let v = self
+ .cmd
+ .all_subcommand_names()
+ .filter(|s| s.starts_with(arg))
+ .collect::<Vec<_>>();
+
+ if v.len() == 1 {
+ return Some(v[0]);
+ }
+
+ // If there is any ambiguity, fallback to non-infer subcommand
+ // search.
+ }
+ if let Some(sc) = self.cmd.find_subcommand(arg) {
+ return Some(sc.get_name());
+ }
+ }
+ None
+ }
+
+ // Checks if the arg matches a long flag subcommand name, or any of its aliases (if defined)
+ fn possible_long_flag_subcommand(&self, arg: &str) -> Option<&str> {
+ debug!("Parser::possible_long_flag_subcommand: arg={:?}", arg);
+ if self.cmd.is_infer_subcommands_set() {
+ let options = self
+ .cmd
+ .get_subcommands()
+ .fold(Vec::new(), |mut options, sc| {
+ if let Some(long) = sc.get_long_flag() {
+ if long.starts_with(arg) {
+ options.push(long);
+ }
+ options.extend(sc.get_all_aliases().filter(|alias| alias.starts_with(arg)))
+ }
+ options
+ });
+ if options.len() == 1 {
+ return Some(options[0]);
+ }
+
+ for sc in options {
+ if sc == arg {
+ return Some(sc);
+ }
+ }
+ } else if let Some(sc_name) = self.cmd.find_long_subcmd(arg) {
+ return Some(sc_name);
+ }
+ None
+ }
+
+ fn parse_help_subcommand(
+ &self,
+ cmds: impl Iterator<Item = &'cmd OsStr>,
+ ) -> ClapResult<std::convert::Infallible> {
+ debug!("Parser::parse_help_subcommand");
+
+ let mut cmd = self.cmd.clone();
+ let sc = {
+ let mut sc = &mut cmd;
+
+ for cmd in cmds {
+ sc = if let Some(sc_name) =
+ sc.find_subcommand(cmd).map(|sc| sc.get_name().to_owned())
+ {
+ sc._build_subcommand(&sc_name).unwrap()
+ } else {
+ return Err(ClapError::unrecognized_subcommand(
+ sc,
+ cmd.to_string_lossy().into_owned(),
+ Usage::new(sc).create_usage_with_title(&[]),
+ ));
+ };
+ }
+
+ sc
+ };
+ let parser = Parser::new(sc);
+
+ Err(parser.help_err(true))
+ }
+
+ fn is_new_arg(&self, next: &clap_lex::ParsedArg<'_>, current_positional: &Arg) -> bool {
+ #![allow(clippy::needless_bool)] // Prefer consistent if/else-if ladder
+
+ debug!(
+ "Parser::is_new_arg: {:?}:{}",
+ next.to_value_os(),
+ current_positional.get_id()
+ );
+
+ if self.cmd[current_positional.get_id()].is_allow_hyphen_values_set()
+ || (self.cmd[current_positional.get_id()].is_allow_negative_numbers_set()
+ && next.is_number())
+ {
+ // If allow hyphen, this isn't a new arg.
+ debug!("Parser::is_new_arg: Allow hyphen");
+ false
+ } else if next.is_long() {
+ // If this is a long flag, this is a new arg.
+ debug!("Parser::is_new_arg: --<something> found");
+ true
+ } else if next.is_short() {
+ // If this is a short flag, this is a new arg. But a singe '-' by
+ // itself is a value and typically means "stdin" on unix systems.
+ debug!("Parser::is_new_arg: -<something> found");
+ true
+ } else {
+ // Nothing special, this is a value.
+ debug!("Parser::is_new_arg: value");
+ false
+ }
+ }
+
+ fn parse_subcommand(
+ &mut self,
+ sc_name: &str,
+ matcher: &mut ArgMatcher,
+ raw_args: &mut clap_lex::RawArgs,
+ args_cursor: clap_lex::ArgCursor,
+ keep_state: bool,
+ ) -> ClapResult<()> {
+ debug!("Parser::parse_subcommand");
+
+ let partial_parsing_enabled = self.cmd.is_ignore_errors_set();
+
+ if let Some(sc) = self.cmd._build_subcommand(sc_name) {
+ let mut sc_matcher = ArgMatcher::new(sc);
+
+ debug!(
+ "Parser::parse_subcommand: About to parse sc={}",
+ sc.get_name()
+ );
+
+ {
+ let mut p = Parser::new(sc);
+ // HACK: maintain indexes between parsers
+ // FlagSubCommand short arg needs to revisit the current short args, but skip the subcommand itself
+ if keep_state {
+ p.cur_idx.set(self.cur_idx.get());
+ p.flag_subcmd_at = self.flag_subcmd_at;
+ p.flag_subcmd_skip = self.flag_subcmd_skip;
+ }
+ if let Err(error) = p.get_matches_with(&mut sc_matcher, raw_args, args_cursor) {
+ if partial_parsing_enabled {
+ debug!(
+ "Parser::parse_subcommand: ignored error in subcommand {}: {:?}",
+ sc_name, error
+ );
+ } else {
+ return Err(error);
+ }
+ }
+ }
+ matcher.subcommand(SubCommand {
+ name: sc.get_name().to_owned(),
+ matches: sc_matcher.into_inner(),
+ });
+ }
+ Ok(())
+ }
+
+ fn parse_long_arg(
+ &mut self,
+ matcher: &mut ArgMatcher,
+ long_arg: Result<&str, &RawOsStr>,
+ long_value: Option<&RawOsStr>,
+ parse_state: &ParseState,
+ pos_counter: usize,
+ valid_arg_found: &mut bool,
+ ) -> ClapResult<ParseResult> {
+ // maybe here lifetime should be 'a
+ debug!("Parser::parse_long_arg");
+
+ #[allow(clippy::blocks_in_if_conditions)]
+ if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
+ self.cmd[opt].is_allow_hyphen_values_set())
+ {
+ debug!("Parser::parse_long_arg: prior arg accepts hyphenated values",);
+ return Ok(ParseResult::MaybeHyphenValue);
+ }
+
+ debug!("Parser::parse_long_arg: Does it contain '='...");
+ let long_arg = match long_arg {
+ Ok(long_arg) => long_arg,
+ Err(long_arg) => {
+ return Ok(ParseResult::NoMatchingArg {
+ arg: long_arg.to_str_lossy().into_owned(),
+ });
+ }
+ };
+ if long_arg.is_empty() {
+ 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) {
+ debug!("Parser::parse_long_arg: Found valid arg or flag '{}'", arg);
+ Some((long_arg, arg))
+ } else if self.cmd.is_infer_long_args_set() {
+ self.cmd.get_arguments().find_map(|a| {
+ if let Some(long) = a.get_long() {
+ if long.starts_with(long_arg) {
+ return Some((long, a));
+ }
+ }
+ a.aliases
+ .iter()
+ .find_map(|(alias, _)| alias.starts_with(long_arg).then(|| (alias.as_str(), a)))
+ })
+ } else {
+ None
+ };
+
+ if let Some((_long_arg, arg)) = arg {
+ let ident = Identifier::Long;
+ *valid_arg_found = true;
+ if arg.is_takes_value_set() {
+ debug!(
+ "Parser::parse_long_arg({:?}): Found an arg with value '{:?}'",
+ long_arg, &long_value
+ );
+ let has_eq = long_value.is_some();
+ self.parse_opt_value(ident, long_value, arg, matcher, has_eq)
+ } else if let Some(rest) = long_value {
+ let required = self.cmd.required_graph();
+ debug!(
+ "Parser::parse_long_arg({:?}): Got invalid literal `{:?}`",
+ long_arg, rest
+ );
+ let mut used: Vec<Id> = matcher
+ .arg_ids()
+ .filter(|arg_id| {
+ matcher.check_explicit(arg_id, &crate::builder::ArgPredicate::IsPresent)
+ })
+ .filter(|&n| {
+ self.cmd.find(n).map_or(true, |a| {
+ !(a.is_hide_set() || required.contains(a.get_id()))
+ })
+ })
+ .cloned()
+ .collect();
+ used.push(arg.get_id().clone());
+
+ Ok(ParseResult::UnneededAttachedValue {
+ rest: rest.to_str_lossy().into_owned(),
+ used,
+ arg: arg.to_string(),
+ })
+ } else {
+ debug!("Parser::parse_long_arg({:?}): Presence validated", long_arg);
+ let trailing_idx = None;
+ self.react(
+ Some(ident),
+ ValueSource::CommandLine,
+ arg,
+ vec![],
+ trailing_idx,
+ matcher,
+ )
+ }
+ } else if let Some(sc_name) = self.possible_long_flag_subcommand(long_arg) {
+ Ok(ParseResult::FlagSubCommand(sc_name.to_string()))
+ } else if self
+ .cmd
+ .get_keymap()
+ .get(&pos_counter)
+ .map_or(false, |arg| {
+ arg.is_allow_hyphen_values_set() && !arg.is_last_set()
+ })
+ {
+ debug!(
+ "Parser::parse_long_args: positional at {} allows hyphens",
+ pos_counter
+ );
+ Ok(ParseResult::MaybeHyphenValue)
+ } else {
+ Ok(ParseResult::NoMatchingArg {
+ arg: long_arg.to_owned(),
+ })
+ }
+ }
+
+ fn parse_short_arg(
+ &mut self,
+ matcher: &mut ArgMatcher,
+ mut short_arg: clap_lex::ShortFlags<'_>,
+ parse_state: &ParseState,
+ // change this to possible pos_arg when removing the usage of &mut Parser.
+ pos_counter: usize,
+ valid_arg_found: &mut bool,
+ ) -> ClapResult<ParseResult> {
+ debug!("Parser::parse_short_arg: short_arg={:?}", short_arg);
+
+ #[allow(clippy::blocks_in_if_conditions)]
+ if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt)
+ if self.cmd[opt].is_allow_hyphen_values_set() || (self.cmd[opt].is_allow_negative_numbers_set() && short_arg.is_number()))
+ {
+ debug!("Parser::parse_short_args: prior arg accepts hyphenated values",);
+ return Ok(ParseResult::MaybeHyphenValue);
+ } else if self
+ .cmd
+ .get_keymap()
+ .get(&pos_counter)
+ .map_or(false, |arg| arg.is_allow_negative_numbers_set())
+ && short_arg.is_number()
+ {
+ debug!("Parser::parse_short_arg: negative number");
+ return Ok(ParseResult::MaybeHyphenValue);
+ } else if self
+ .cmd
+ .get_keymap()
+ .get(&pos_counter)
+ .map_or(false, |arg| {
+ arg.is_allow_hyphen_values_set() && !arg.is_last_set()
+ })
+ && short_arg
+ .clone()
+ .any(|c| !c.map(|c| self.cmd.contains_short(c)).unwrap_or_default())
+ {
+ debug!(
+ "Parser::parse_short_args: positional at {} allows hyphens",
+ pos_counter
+ );
+ return Ok(ParseResult::MaybeHyphenValue);
+ }
+
+ let mut ret = ParseResult::NoArg;
+
+ let skip = self.flag_subcmd_skip;
+ self.flag_subcmd_skip = 0;
+ let res = short_arg.advance_by(skip);
+ debug_assert_eq!(
+ res,
+ Ok(()),
+ "tracking of `flag_subcmd_skip` is off for `{short_arg:?}`"
+ );
+ while let Some(c) = short_arg.next_flag() {
+ let c = match c {
+ Ok(c) => c,
+ Err(rest) => {
+ return Ok(ParseResult::NoMatchingArg {
+ arg: format!("-{}", rest.to_str_lossy()),
+ });
+ }
+ };
+ debug!("Parser::parse_short_arg:iter:{}", c);
+
+ // Check for matching short options, and return the name if there is no trailing
+ // concatenated value: -oval
+ // Option: -o
+ // Value: val
+ if let Some(arg) = self.cmd.get_keymap().get(&c) {
+ let ident = Identifier::Short;
+ debug!(
+ "Parser::parse_short_arg:iter:{}: Found valid opt or flag",
+ c
+ );
+ *valid_arg_found = true;
+ if !arg.is_takes_value_set() {
+ let arg_values = Vec::new();
+ let trailing_idx = None;
+ ret = ok!(self.react(
+ Some(ident),
+ ValueSource::CommandLine,
+ arg,
+ arg_values,
+ trailing_idx,
+ matcher,
+ ));
+ continue;
+ }
+
+ // Check for trailing concatenated value
+ //
+ // Cloning the iterator, so we rollback if it isn't there.
+ let val = short_arg.clone().next_value_os().unwrap_or_default();
+ debug!(
+ "Parser::parse_short_arg:iter:{}: val={:?} (bytes), val={:?} (ascii), short_arg={:?}",
+ c, val, val.as_raw_bytes(), short_arg
+ );
+ let val = Some(val).filter(|v| !v.is_empty());
+
+ // Default to "we're expecting a value later".
+ //
+ // If attached value is not consumed, we may have more short
+ // flags to parse, continue.
+ //
+ // e.g. `-xvf`, when require_equals && x.min_vals == 0, we don't
+ // consume the `vf`, even if it's provided as value.
+ let (val, has_eq) = if let Some(val) = val.and_then(|v| v.strip_prefix('=')) {
+ (Some(val), true)
+ } else {
+ (val, false)
+ };
+ match ok!(self.parse_opt_value(ident, val, arg, matcher, has_eq)) {
+ ParseResult::AttachedValueNotConsumed => continue,
+ x => return Ok(x),
+ }
+ }
+
+ return if let Some(sc_name) = self.cmd.find_short_subcmd(c) {
+ debug!("Parser::parse_short_arg:iter:{}: subcommand={}", c, sc_name);
+ // Make sure indices get updated before reading `self.cur_idx`
+ ok!(self.resolve_pending(matcher));
+ self.cur_idx.set(self.cur_idx.get() + 1);
+ debug!("Parser::parse_short_arg: cur_idx:={}", self.cur_idx.get());
+
+ let name = sc_name.to_string();
+ // Get the index of the previously saved flag subcommand in the group of flags (if exists).
+ // If it is a new flag subcommand, then the formentioned index should be the current one
+ // (ie. `cur_idx`), and should be registered.
+ let cur_idx = self.cur_idx.get();
+ self.flag_subcmd_at.get_or_insert(cur_idx);
+ let done_short_args = short_arg.is_empty();
+ if done_short_args {
+ self.flag_subcmd_at = None;
+ }
+ Ok(ParseResult::FlagSubCommand(name))
+ } else {
+ Ok(ParseResult::NoMatchingArg {
+ arg: format!("-{c}"),
+ })
+ };
+ }
+ Ok(ret)
+ }
+
+ fn parse_opt_value(
+ &self,
+ ident: Identifier,
+ attached_value: Option<&RawOsStr>,
+ arg: &Arg,
+ matcher: &mut ArgMatcher,
+ has_eq: bool,
+ ) -> ClapResult<ParseResult> {
+ debug!(
+ "Parser::parse_opt_value; arg={}, val={:?}, has_eq={:?}",
+ arg.get_id(),
+ attached_value,
+ has_eq
+ );
+ debug!("Parser::parse_opt_value; arg.settings={:?}", arg.settings);
+
+ debug!("Parser::parse_opt_value; Checking for val...");
+ // require_equals is set, but no '=' is provided, try throwing error.
+ if arg.is_require_equals_set() && !has_eq {
+ if arg.get_min_vals() == 0 {
+ debug!("Requires equals, but min_vals == 0");
+ let arg_values = Vec::new();
+ let trailing_idx = None;
+ let react_result = ok!(self.react(
+ Some(ident),
+ ValueSource::CommandLine,
+ arg,
+ arg_values,
+ trailing_idx,
+ matcher,
+ ));
+ debug_assert_eq!(react_result, ParseResult::ValuesDone);
+ if attached_value.is_some() {
+ Ok(ParseResult::AttachedValueNotConsumed)
+ } else {
+ Ok(ParseResult::ValuesDone)
+ }
+ } else {
+ debug!("Requires equals but not provided. Error.");
+ Ok(ParseResult::EqualsNotProvided {
+ arg: arg.to_string(),
+ })
+ }
+ } else if let Some(v) = attached_value {
+ let arg_values = vec![v.to_os_str().into_owned()];
+ let trailing_idx = None;
+ let react_result = ok!(self.react(
+ Some(ident),
+ ValueSource::CommandLine,
+ arg,
+ arg_values,
+ trailing_idx,
+ matcher,
+ ));
+ debug_assert_eq!(react_result, ParseResult::ValuesDone);
+ // Attached are always done
+ Ok(ParseResult::ValuesDone)
+ } else {
+ debug!("Parser::parse_opt_value: More arg vals required...");
+ ok!(self.resolve_pending(matcher));
+ let trailing_values = false;
+ matcher.pending_values_mut(arg.get_id(), Some(ident), trailing_values);
+ Ok(ParseResult::Opt(arg.get_id().clone()))
+ }
+ }
+
+ fn check_terminator(&self, arg: &Arg, val: &RawOsStr) -> Option<ParseResult> {
+ if Some(val)
+ == arg
+ .terminator
+ .as_ref()
+ .map(|s| RawOsStr::from_str(s.as_str()))
+ {
+ debug!("Parser::check_terminator: terminator={:?}", arg.terminator);
+ Some(ParseResult::ValuesDone)
+ } else {
+ None
+ }
+ }
+
+ fn push_arg_values(
+ &self,
+ arg: &Arg,
+ raw_vals: Vec<OsString>,
+ matcher: &mut ArgMatcher,
+ ) -> ClapResult<()> {
+ debug!("Parser::push_arg_values: {:?}", raw_vals);
+
+ for raw_val in raw_vals {
+ // update the current index because each value is a distinct index to clap
+ self.cur_idx.set(self.cur_idx.get() + 1);
+ debug!(
+ "Parser::add_single_val_to_arg: cur_idx:={}",
+ self.cur_idx.get()
+ );
+ let value_parser = arg.get_value_parser();
+ let val = ok!(value_parser.parse_ref(self.cmd, Some(arg), &raw_val));
+
+ matcher.add_val_to(arg.get_id(), val, raw_val);
+ matcher.add_index_to(arg.get_id(), self.cur_idx.get());
+ }
+
+ Ok(())
+ }
+
+ fn resolve_pending(&self, matcher: &mut ArgMatcher) -> ClapResult<()> {
+ let pending = match matcher.take_pending() {
+ Some(pending) => pending,
+ None => {
+ return Ok(());
+ }
+ };
+
+ debug!("Parser::resolve_pending: id={:?}", pending.id);
+ let arg = self.cmd.find(&pending.id).expect(INTERNAL_ERROR_MSG);
+ let _ = ok!(self.react(
+ pending.ident,
+ ValueSource::CommandLine,
+ arg,
+ pending.raw_vals,
+ pending.trailing_idx,
+ matcher,
+ ));
+
+ Ok(())
+ }
+
+ fn react(
+ &self,
+ ident: Option<Identifier>,
+ source: ValueSource,
+ arg: &Arg,
+ mut raw_vals: Vec<OsString>,
+ mut trailing_idx: Option<usize>,
+ matcher: &mut ArgMatcher,
+ ) -> ClapResult<ParseResult> {
+ ok!(self.resolve_pending(matcher));
+
+ debug!(
+ "Parser::react action={:?}, identifier={:?}, source={:?}",
+ arg.get_action(),
+ ident,
+ source
+ );
+
+ // Process before `default_missing_values` to avoid it counting as values from the command
+ // line
+ if source == ValueSource::CommandLine {
+ ok!(self.verify_num_args(arg, &raw_vals));
+ }
+
+ if raw_vals.is_empty() {
+ // We assume this case is valid: require equals, but min_vals == 0.
+ if !arg.default_missing_vals.is_empty() {
+ debug!("Parser::react: has default_missing_vals");
+ trailing_idx = None;
+ raw_vals.extend(
+ arg.default_missing_vals
+ .iter()
+ .map(|s| s.as_os_str().to_owned()),
+ );
+ }
+ }
+
+ if let Some(val_delim) = arg.get_value_delimiter() {
+ if self.cmd.is_dont_delimit_trailing_values_set() && trailing_idx == Some(0) {
+ // Nothing to do
+ } else {
+ let mut split_raw_vals = Vec::with_capacity(raw_vals.len());
+ for (i, raw_val) in raw_vals.into_iter().enumerate() {
+ let raw_val = RawOsString::new(raw_val);
+ if !raw_val.contains(val_delim)
+ || (self.cmd.is_dont_delimit_trailing_values_set()
+ && trailing_idx == Some(i))
+ {
+ split_raw_vals.push(raw_val.into_os_string());
+ } else {
+ split_raw_vals
+ .extend(raw_val.split(val_delim).map(|x| x.to_os_str().into_owned()));
+ }
+ }
+ raw_vals = split_raw_vals
+ }
+ }
+
+ match arg.get_action() {
+ ArgAction::Set => {
+ if source == ValueSource::CommandLine
+ && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long))
+ {
+ // Record flag's index
+ self.cur_idx.set(self.cur_idx.get() + 1);
+ debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
+ }
+ if matcher.remove(arg.get_id())
+ && !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
+ {
+ return Err(ClapError::argument_conflict(
+ self.cmd,
+ arg.to_string(),
+ vec![arg.to_string()],
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+ self.start_custom_arg(matcher, arg, source);
+ ok!(self.push_arg_values(arg, raw_vals, matcher));
+ if cfg!(debug_assertions) && matcher.needs_more_vals(arg) {
+ debug!(
+ "Parser::react not enough values passed in, leaving it to the validator to complain",
+ );
+ }
+ Ok(ParseResult::ValuesDone)
+ }
+ ArgAction::Append => {
+ if source == ValueSource::CommandLine
+ && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long))
+ {
+ // Record flag's index
+ self.cur_idx.set(self.cur_idx.get() + 1);
+ debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
+ }
+ self.start_custom_arg(matcher, arg, source);
+ ok!(self.push_arg_values(arg, raw_vals, matcher));
+ if cfg!(debug_assertions) && matcher.needs_more_vals(arg) {
+ debug!(
+ "Parser::react not enough values passed in, leaving it to the validator to complain",
+ );
+ }
+ Ok(ParseResult::ValuesDone)
+ }
+ ArgAction::SetTrue => {
+ let raw_vals = if raw_vals.is_empty() {
+ vec![OsString::from("true")]
+ } else {
+ raw_vals
+ };
+
+ if matcher.remove(arg.get_id())
+ && !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
+ {
+ return Err(ClapError::argument_conflict(
+ self.cmd,
+ arg.to_string(),
+ vec![arg.to_string()],
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+ self.start_custom_arg(matcher, arg, source);
+ ok!(self.push_arg_values(arg, raw_vals, matcher));
+ Ok(ParseResult::ValuesDone)
+ }
+ ArgAction::SetFalse => {
+ let raw_vals = if raw_vals.is_empty() {
+ vec![OsString::from("false")]
+ } else {
+ raw_vals
+ };
+
+ if matcher.remove(arg.get_id())
+ && !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
+ {
+ return Err(ClapError::argument_conflict(
+ self.cmd,
+ arg.to_string(),
+ vec![arg.to_string()],
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+ self.start_custom_arg(matcher, arg, source);
+ ok!(self.push_arg_values(arg, raw_vals, matcher));
+ Ok(ParseResult::ValuesDone)
+ }
+ ArgAction::Count => {
+ let raw_vals = if raw_vals.is_empty() {
+ let existing_value = *matcher
+ .get_one::<crate::builder::CountType>(arg.get_id().as_str())
+ .unwrap_or(&0);
+ let next_value = existing_value.saturating_add(1);
+ vec![OsString::from(next_value.to_string())]
+ } else {
+ raw_vals
+ };
+
+ matcher.remove(arg.get_id());
+ self.start_custom_arg(matcher, arg, source);
+ ok!(self.push_arg_values(arg, raw_vals, matcher));
+ Ok(ParseResult::ValuesDone)
+ }
+ ArgAction::Help => {
+ let use_long = match ident {
+ Some(Identifier::Long) => true,
+ Some(Identifier::Short) => false,
+ Some(Identifier::Index) => true,
+ None => true,
+ };
+ debug!("Help: use_long={}", use_long);
+ Err(self.help_err(use_long))
+ }
+ ArgAction::Version => {
+ let use_long = match ident {
+ Some(Identifier::Long) => true,
+ Some(Identifier::Short) => false,
+ Some(Identifier::Index) => true,
+ None => true,
+ };
+ debug!("Version: use_long={}", use_long);
+ Err(self.version_err(use_long))
+ }
+ }
+ }
+
+ fn verify_num_args(&self, arg: &Arg, raw_vals: &[OsString]) -> ClapResult<()> {
+ if self.cmd.is_ignore_errors_set() {
+ return Ok(());
+ }
+
+ let actual = raw_vals.len();
+ let expected = arg.get_num_args().expect(INTERNAL_ERROR_MSG);
+
+ if 0 < expected.min_values() && actual == 0 {
+ // Issue 665 (https://github.com/clap-rs/clap/issues/665)
+ // Issue 1105 (https://github.com/clap-rs/clap/issues/1105)
+ return Err(ClapError::empty_value(
+ self.cmd,
+ &super::get_possible_values_cli(arg)
+ .iter()
+ .filter(|pv| !pv.is_hide_set())
+ .map(|n| n.get_name().to_owned())
+ .collect::<Vec<_>>(),
+ arg.to_string(),
+ ));
+ } else if let Some(expected) = expected.num_values() {
+ if expected != actual {
+ debug!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues");
+ return Err(ClapError::wrong_number_of_values(
+ self.cmd,
+ arg.to_string(),
+ expected,
+ actual,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+ } else if actual < expected.min_values() {
+ return Err(ClapError::too_few_values(
+ self.cmd,
+ arg.to_string(),
+ expected.min_values(),
+ actual,
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ } else if expected.max_values() < actual {
+ debug!("Validator::validate_arg_num_vals: Sending error TooManyValues");
+ return Err(ClapError::too_many_values(
+ self.cmd,
+ raw_vals
+ .last()
+ .expect(INTERNAL_ERROR_MSG)
+ .to_string_lossy()
+ .into_owned(),
+ arg.to_string(),
+ Usage::new(self.cmd).create_usage_with_title(&[]),
+ ));
+ }
+
+ Ok(())
+ }
+
+ fn remove_overrides(&self, arg: &Arg, matcher: &mut ArgMatcher) {
+ debug!("Parser::remove_overrides: id={:?}", arg.id);
+ for override_id in &arg.overrides {
+ debug!("Parser::remove_overrides:iter:{:?}: removing", override_id);
+ matcher.remove(override_id);
+ }
+
+ // Override anything that can override us
+ let mut transitive = Vec::new();
+ for arg_id in matcher.arg_ids() {
+ if let Some(overrider) = self.cmd.find(arg_id) {
+ if overrider.overrides.contains(arg.get_id()) {
+ transitive.push(overrider.get_id());
+ }
+ }
+ }
+ for overrider_id in transitive {
+ debug!("Parser::remove_overrides:iter:{:?}: removing", overrider_id);
+ matcher.remove(overrider_id);
+ }
+ }
+
+ #[cfg(feature = "env")]
+ fn add_env(&mut self, matcher: &mut ArgMatcher) -> ClapResult<()> {
+ debug!("Parser::add_env");
+
+ for arg in self.cmd.get_arguments() {
+ // Use env only if the arg was absent among command line args,
+ // early return if this is not the case.
+ if matcher.contains(&arg.id) {
+ debug!("Parser::add_env: Skipping existing arg `{}`", arg);
+ continue;
+ }
+
+ debug!("Parser::add_env: Checking arg `{}`", arg);
+ if let Some((_, Some(ref val))) = arg.env {
+ debug!("Parser::add_env: Found an opt with value={:?}", val);
+ let arg_values = vec![val.to_owned()];
+ let trailing_idx = None;
+ let _ = ok!(self.react(
+ None,
+ ValueSource::EnvVariable,
+ arg,
+ arg_values,
+ trailing_idx,
+ matcher,
+ ));
+ }
+ }
+
+ Ok(())
+ }
+
+ fn add_defaults(&self, matcher: &mut ArgMatcher) -> ClapResult<()> {
+ debug!("Parser::add_defaults");
+
+ for arg in self.cmd.get_arguments() {
+ debug!("Parser::add_defaults:iter:{}:", arg.get_id());
+ ok!(self.add_default_value(arg, matcher));
+ }
+
+ Ok(())
+ }
+
+ fn add_default_value(&self, arg: &Arg, matcher: &mut ArgMatcher) -> ClapResult<()> {
+ if !arg.default_vals_ifs.is_empty() {
+ debug!("Parser::add_default_value: has conditional defaults");
+ if !matcher.contains(arg.get_id()) {
+ for (id, val, default) in arg.default_vals_ifs.iter() {
+ let add = if let Some(a) = matcher.get(id) {
+ match val {
+ crate::builder::ArgPredicate::Equals(v) => {
+ a.raw_vals_flatten().any(|value| v == value)
+ }
+ crate::builder::ArgPredicate::IsPresent => true,
+ }
+ } else {
+ false
+ };
+
+ if add {
+ if let Some(default) = default {
+ let arg_values = vec![default.to_os_string()];
+ let trailing_idx = None;
+ let _ = ok!(self.react(
+ None,
+ ValueSource::DefaultValue,
+ arg,
+ arg_values,
+ trailing_idx,
+ matcher,
+ ));
+ }
+ return Ok(());
+ }
+ }
+ }
+ } else {
+ debug!("Parser::add_default_value: doesn't have conditional defaults");
+ }
+
+ if !arg.default_vals.is_empty() {
+ debug!(
+ "Parser::add_default_value:iter:{}: has default vals",
+ arg.get_id()
+ );
+ if matcher.contains(arg.get_id()) {
+ debug!("Parser::add_default_value:iter:{}: was used", arg.get_id());
+ // do nothing
+ } else {
+ debug!(
+ "Parser::add_default_value:iter:{}: wasn't used",
+ arg.get_id()
+ );
+ let arg_values: Vec<_> = arg
+ .default_vals
+ .iter()
+ .map(crate::builder::OsStr::to_os_string)
+ .collect();
+ let trailing_idx = None;
+ let _ = ok!(self.react(
+ None,
+ ValueSource::DefaultValue,
+ arg,
+ arg_values,
+ trailing_idx,
+ matcher,
+ ));
+ }
+ } else {
+ debug!(
+ "Parser::add_default_value:iter:{}: doesn't have default vals",
+ arg.get_id()
+ );
+
+ // do nothing
+ }
+
+ Ok(())
+ }
+
+ fn start_custom_arg(&self, matcher: &mut ArgMatcher, arg: &Arg, source: ValueSource) {
+ if source == ValueSource::CommandLine {
+ // With each new occurrence, remove overrides from prior occurrences
+ self.remove_overrides(arg, matcher);
+ }
+ matcher.start_custom_arg(arg, source);
+ if source.is_explicit() {
+ for group in self.cmd.groups_for_arg(arg.get_id()) {
+ matcher.start_custom_group(group.clone(), source);
+ matcher.add_val_to(
+ &group,
+ AnyValue::new(arg.get_id().clone()),
+ OsString::from(arg.get_id().as_str()),
+ );
+ }
+ }
+ }
+}
+
+// Error, Help, and Version Methods
+impl<'cmd> Parser<'cmd> {
+ /// Is only used for the long flag(which is the only one needs fuzzy searching)
+ fn did_you_mean_error(
+ &mut self,
+ arg: &str,
+ matcher: &mut ArgMatcher,
+ remaining_args: &[&OsStr],
+ trailing_values: bool,
+ ) -> ClapError {
+ debug!("Parser::did_you_mean_error: arg={}", arg);
+ // Didn't match a flag or option
+ let longs = self
+ .cmd
+ .get_keymap()
+ .keys()
+ .filter_map(|x| match x {
+ KeyType::Long(l) => Some(l.to_string_lossy().into_owned()),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+ debug!("Parser::did_you_mean_error: longs={:?}", longs);
+
+ let did_you_mean = suggestions::did_you_mean_flag(
+ arg,
+ remaining_args,
+ longs.iter().map(|x| &x[..]),
+ self.cmd.get_subcommands_mut(),
+ );
+
+ // Add the arg to the matches to build a proper usage string
+ if let Some((name, _)) = did_you_mean.as_ref() {
+ if let Some(arg) = self.cmd.get_keymap().get(&name.as_ref()) {
+ self.start_custom_arg(matcher, arg, ValueSource::CommandLine);
+ }
+ }
+
+ let required = self.cmd.required_graph();
+ let used: Vec<Id> = matcher
+ .arg_ids()
+ .filter(|arg_id| {
+ matcher.check_explicit(arg_id, &crate::builder::ArgPredicate::IsPresent)
+ })
+ .filter(|n| self.cmd.find(n).map_or(true, |a| !a.is_hide_set()))
+ .cloned()
+ .collect();
+
+ // `did_you_mean` is a lot more likely and should cause us to skip the `--` suggestion
+ //
+ // In theory, this is only called for `--long`s, so we don't need to check
+ let suggested_trailing_arg =
+ did_you_mean.is_none() && !trailing_values && self.cmd.has_positionals();
+ ClapError::unknown_argument(
+ self.cmd,
+ format!("--{arg}"),
+ did_you_mean,
+ suggested_trailing_arg,
+ Usage::new(self.cmd)
+ .required(&required)
+ .create_usage_with_title(&used),
+ )
+ }
+
+ fn help_err(&self, use_long: bool) -> ClapError {
+ let styled = self.cmd.write_help_err(use_long);
+ ClapError::display_help(self.cmd, styled)
+ }
+
+ fn version_err(&self, use_long: bool) -> ClapError {
+ let styled = self.cmd.write_version_err(use_long);
+ ClapError::display_version(self.cmd, styled)
+ }
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) enum ParseState {
+ ValuesDone,
+ Opt(Id),
+ Pos(Id),
+}
+
+/// Recoverable Parsing results.
+#[derive(Debug, PartialEq, Clone)]
+#[must_use]
+enum ParseResult {
+ FlagSubCommand(String),
+ Opt(Id),
+ ValuesDone,
+ /// Value attached to the short flag is not consumed(e.g. 'u' for `-cu` is
+ /// not consumed).
+ AttachedValueNotConsumed,
+ /// This long flag doesn't need a value but is provided one.
+ UnneededAttachedValue {
+ rest: String,
+ used: Vec<Id>,
+ arg: String,
+ },
+ /// This flag might be an hyphen Value.
+ MaybeHyphenValue,
+ /// Equals required but not provided.
+ EqualsNotProvided {
+ arg: String,
+ },
+ /// Failed to match a Arg.
+ NoMatchingArg {
+ arg: String,
+ },
+ /// No argument found e.g. parser is given `-` when parsing a flag.
+ NoArg,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct PendingArg {
+ pub(crate) id: Id,
+ pub(crate) ident: Option<Identifier>,
+ pub(crate) raw_vals: Vec<OsString>,
+ pub(crate) trailing_idx: Option<usize>,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub(crate) enum Identifier {
+ Short,
+ Long,
+ Index,
+}
diff --git a/src/parser/validator.rs b/src/parser/validator.rs
new file mode 100644
index 0000000..49d28a3
--- /dev/null
+++ b/src/parser/validator.rs
@@ -0,0 +1,562 @@
+// Internal
+use crate::builder::StyledStr;
+use crate::builder::{Arg, ArgGroup, ArgPredicate, Command, PossibleValue};
+use crate::error::{Error, Result as ClapResult};
+use crate::output::Usage;
+use crate::parser::{ArgMatcher, ParseState};
+use crate::util::ChildGraph;
+use crate::util::FlatMap;
+use crate::util::FlatSet;
+use crate::util::Id;
+use crate::INTERNAL_ERROR_MSG;
+
+pub(crate) struct Validator<'cmd> {
+ cmd: &'cmd Command,
+ required: ChildGraph<Id>,
+}
+
+impl<'cmd> Validator<'cmd> {
+ pub(crate) fn new(cmd: &'cmd Command) -> Self {
+ let required = cmd.required_graph();
+ Validator { cmd, required }
+ }
+
+ pub(crate) fn validate(
+ &mut self,
+ parse_state: ParseState,
+ matcher: &mut ArgMatcher,
+ ) -> ClapResult<()> {
+ debug!("Validator::validate");
+ let conflicts = Conflicts::with_args(self.cmd, matcher);
+ let has_subcmd = matcher.subcommand_name().is_some();
+
+ if let ParseState::Opt(a) = parse_state {
+ debug!("Validator::validate: needs_val_of={:?}", a);
+
+ let o = &self.cmd[&a];
+ let should_err = if let Some(v) = matcher.args.get(o.get_id()) {
+ v.all_val_groups_empty() && o.get_min_vals() != 0
+ } else {
+ true
+ };
+ if should_err {
+ return Err(Error::empty_value(
+ self.cmd,
+ &get_possible_values_cli(o)
+ .iter()
+ .filter(|pv| !pv.is_hide_set())
+ .map(|n| n.get_name().to_owned())
+ .collect::<Vec<_>>(),
+ o.to_string(),
+ ));
+ }
+ }
+
+ if !has_subcmd && self.cmd.is_arg_required_else_help_set() {
+ let num_user_values = matcher
+ .args()
+ .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent))
+ .count();
+ if num_user_values == 0 {
+ let message = self.cmd.write_help_err(false);
+ return Err(Error::display_help_error(self.cmd, message));
+ }
+ }
+ if !has_subcmd && self.cmd.is_subcommand_required_set() {
+ let bn = self
+ .cmd
+ .get_bin_name()
+ .unwrap_or_else(|| self.cmd.get_name());
+ return Err(Error::missing_subcommand(
+ self.cmd,
+ bn.to_string(),
+ self.cmd
+ .all_subcommand_names()
+ .map(|s| s.to_owned())
+ .collect::<Vec<_>>(),
+ Usage::new(self.cmd)
+ .required(&self.required)
+ .create_usage_with_title(&[]),
+ ));
+ }
+
+ ok!(self.validate_conflicts(matcher, &conflicts));
+ if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) {
+ ok!(self.validate_required(matcher, &conflicts));
+ }
+
+ Ok(())
+ }
+
+ fn validate_conflicts(
+ &mut self,
+ matcher: &ArgMatcher,
+ conflicts: &Conflicts,
+ ) -> ClapResult<()> {
+ debug!("Validator::validate_conflicts");
+
+ ok!(self.validate_exclusive(matcher));
+
+ for (arg_id, _) in matcher
+ .args()
+ .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent))
+ .filter(|(arg_id, _)| self.cmd.find(arg_id).is_some())
+ {
+ debug!("Validator::validate_conflicts::iter: id={:?}", arg_id);
+ let conflicts = conflicts.gather_conflicts(self.cmd, arg_id);
+ ok!(self.build_conflict_err(arg_id, &conflicts, matcher));
+ }
+
+ Ok(())
+ }
+
+ fn validate_exclusive(&self, matcher: &ArgMatcher) -> ClapResult<()> {
+ debug!("Validator::validate_exclusive");
+ let args_count = matcher
+ .args()
+ .filter(|(arg_id, matched)| {
+ matched.check_explicit(&crate::builder::ArgPredicate::IsPresent)
+ // Avoid including our own groups by checking none of them. If a group is present, the
+ // args for the group will be.
+ && self.cmd.find(arg_id).is_some()
+ })
+ .count();
+ if args_count <= 1 {
+ // Nothing present to conflict with
+ return Ok(());
+ }
+
+ matcher
+ .args()
+ .filter(|(_, matched)| matched.check_explicit(&crate::builder::ArgPredicate::IsPresent))
+ .filter_map(|(id, _)| {
+ debug!("Validator::validate_exclusive:iter:{:?}", id);
+ self.cmd
+ .find(id)
+ // Find `arg`s which are exclusive but also appear with other args.
+ .filter(|&arg| arg.is_exclusive_set() && args_count > 1)
+ })
+ // Throw an error for the first conflict found.
+ .try_for_each(|arg| {
+ Err(Error::argument_conflict(
+ self.cmd,
+ arg.to_string(),
+ Vec::new(),
+ Usage::new(self.cmd)
+ .required(&self.required)
+ .create_usage_with_title(&[]),
+ ))
+ })
+ }
+
+ fn build_conflict_err(
+ &self,
+ name: &Id,
+ conflict_ids: &[Id],
+ matcher: &ArgMatcher,
+ ) -> ClapResult<()> {
+ if conflict_ids.is_empty() {
+ return Ok(());
+ }
+
+ debug!("Validator::build_conflict_err: name={:?}", name);
+ let mut seen = FlatSet::new();
+ let conflicts = conflict_ids
+ .iter()
+ .flat_map(|c_id| {
+ if self.cmd.find_group(c_id).is_some() {
+ self.cmd.unroll_args_in_group(c_id)
+ } else {
+ vec![c_id.clone()]
+ }
+ })
+ .filter_map(|c_id| {
+ seen.insert(c_id.clone()).then(|| {
+ let c_arg = self.cmd.find(&c_id).expect(INTERNAL_ERROR_MSG);
+ c_arg.to_string()
+ })
+ })
+ .collect();
+
+ let former_arg = self.cmd.find(name).expect(INTERNAL_ERROR_MSG);
+ let usg = self.build_conflict_err_usage(matcher, conflict_ids);
+ Err(Error::argument_conflict(
+ self.cmd,
+ former_arg.to_string(),
+ conflicts,
+ usg,
+ ))
+ }
+
+ fn build_conflict_err_usage(
+ &self,
+ matcher: &ArgMatcher,
+ conflicting_keys: &[Id],
+ ) -> Option<StyledStr> {
+ let used_filtered: Vec<Id> = matcher
+ .args()
+ .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent))
+ .map(|(n, _)| n)
+ .filter(|n| {
+ // Filter out the args we don't want to specify.
+ self.cmd.find(n).map_or(false, |a| !a.is_hide_set())
+ })
+ .filter(|key| !conflicting_keys.contains(key))
+ .cloned()
+ .collect();
+ let required: Vec<Id> = used_filtered
+ .iter()
+ .filter_map(|key| self.cmd.find(key))
+ .flat_map(|arg| arg.requires.iter().map(|item| &item.1))
+ .filter(|key| !used_filtered.contains(key) && !conflicting_keys.contains(key))
+ .chain(used_filtered.iter())
+ .cloned()
+ .collect();
+ Usage::new(self.cmd)
+ .required(&self.required)
+ .create_usage_with_title(&required)
+ }
+
+ fn gather_requires(&mut self, matcher: &ArgMatcher) {
+ debug!("Validator::gather_requires");
+ for (name, matched) in matcher
+ .args()
+ .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent))
+ {
+ debug!("Validator::gather_requires:iter:{:?}", name);
+ if let Some(arg) = self.cmd.find(name) {
+ let is_relevant = |(val, req_arg): &(ArgPredicate, Id)| -> Option<Id> {
+ let required = matched.check_explicit(val);
+ required.then(|| req_arg.clone())
+ };
+
+ for req in self.cmd.unroll_arg_requires(is_relevant, arg.get_id()) {
+ self.required.insert(req);
+ }
+ } else if let Some(g) = self.cmd.find_group(name) {
+ debug!("Validator::gather_requires:iter:{:?}:group", name);
+ for r in &g.requires {
+ self.required.insert(r.clone());
+ }
+ }
+ }
+ }
+
+ fn validate_required(&mut self, matcher: &ArgMatcher, conflicts: &Conflicts) -> ClapResult<()> {
+ debug!("Validator::validate_required: required={:?}", self.required);
+ self.gather_requires(matcher);
+
+ let mut missing_required = Vec::new();
+ let mut highest_index = 0;
+
+ let is_exclusive_present = matcher
+ .args()
+ .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent))
+ .any(|(id, _)| {
+ self.cmd
+ .find(id)
+ .map(|arg| arg.is_exclusive_set())
+ .unwrap_or_default()
+ });
+ debug!(
+ "Validator::validate_required: is_exclusive_present={}",
+ is_exclusive_present
+ );
+
+ for arg_or_group in self
+ .required
+ .iter()
+ .filter(|r| !matcher.check_explicit(r, &ArgPredicate::IsPresent))
+ {
+ debug!("Validator::validate_required:iter:aog={:?}", arg_or_group);
+ if let Some(arg) = self.cmd.find(arg_or_group) {
+ debug!("Validator::validate_required:iter: This is an arg");
+ if !is_exclusive_present && !self.is_missing_required_ok(arg, conflicts) {
+ debug!(
+ "Validator::validate_required:iter: Missing {:?}",
+ arg.get_id()
+ );
+ missing_required.push(arg.get_id().clone());
+ if !arg.is_last_set() {
+ highest_index = highest_index.max(arg.get_index().unwrap_or(0));
+ }
+ }
+ } else if let Some(group) = self.cmd.find_group(arg_or_group) {
+ debug!("Validator::validate_required:iter: This is a group");
+ if !self
+ .cmd
+ .unroll_args_in_group(&group.id)
+ .iter()
+ .any(|a| matcher.check_explicit(a, &ArgPredicate::IsPresent))
+ {
+ debug!(
+ "Validator::validate_required:iter: Missing {:?}",
+ group.get_id()
+ );
+ missing_required.push(group.get_id().clone());
+ }
+ }
+ }
+
+ // Validate the conditionally required args
+ for a in self
+ .cmd
+ .get_arguments()
+ .filter(|a| !matcher.check_explicit(a.get_id(), &ArgPredicate::IsPresent))
+ {
+ let mut required = false;
+
+ for (other, val) in &a.r_ifs {
+ if matcher.check_explicit(other, &ArgPredicate::Equals(val.into())) {
+ debug!(
+ "Validator::validate_required:iter: Missing {:?}",
+ a.get_id()
+ );
+ required = true;
+ }
+ }
+
+ let match_all = a.r_ifs_all.iter().all(|(other, val)| {
+ matcher.check_explicit(other, &ArgPredicate::Equals(val.into()))
+ });
+ if match_all && !a.r_ifs_all.is_empty() {
+ debug!(
+ "Validator::validate_required:iter: Missing {:?}",
+ a.get_id()
+ );
+ required = true;
+ }
+
+ if (!a.r_unless.is_empty() || !a.r_unless_all.is_empty())
+ && self.fails_arg_required_unless(a, matcher)
+ {
+ debug!(
+ "Validator::validate_required:iter: Missing {:?}",
+ a.get_id()
+ );
+ required = true;
+ }
+
+ if required {
+ missing_required.push(a.get_id().clone());
+ if !a.is_last_set() {
+ highest_index = highest_index.max(a.get_index().unwrap_or(0));
+ }
+ }
+ }
+
+ // For display purposes, include all of the preceding positional arguments
+ if !self.cmd.is_allow_missing_positional_set() {
+ for pos in self
+ .cmd
+ .get_positionals()
+ .filter(|a| !matcher.check_explicit(a.get_id(), &ArgPredicate::IsPresent))
+ {
+ if pos.get_index() < Some(highest_index) {
+ debug!(
+ "Validator::validate_required:iter: Missing {:?}",
+ pos.get_id()
+ );
+ missing_required.push(pos.get_id().clone());
+ }
+ }
+ }
+
+ if !missing_required.is_empty() {
+ ok!(self.missing_required_error(matcher, missing_required));
+ }
+
+ Ok(())
+ }
+
+ fn is_missing_required_ok(&self, a: &Arg, conflicts: &Conflicts) -> bool {
+ debug!("Validator::is_missing_required_ok: {}", a.get_id());
+ if !conflicts.gather_conflicts(self.cmd, a.get_id()).is_empty() {
+ debug!("Validator::is_missing_required_ok: true (self)");
+ return true;
+ }
+ for group_id in self.cmd.groups_for_arg(a.get_id()) {
+ if !conflicts.gather_conflicts(self.cmd, &group_id).is_empty() {
+ debug!("Validator::is_missing_required_ok: true ({})", group_id);
+ return true;
+ }
+ }
+ false
+ }
+
+ // Failing a required unless means, the arg's "unless" wasn't present, and neither were they
+ fn fails_arg_required_unless(&self, a: &Arg, matcher: &ArgMatcher) -> bool {
+ debug!("Validator::fails_arg_required_unless: a={:?}", a.get_id());
+ let exists = |id| matcher.check_explicit(id, &ArgPredicate::IsPresent);
+
+ (a.r_unless_all.is_empty() || !a.r_unless_all.iter().all(exists))
+ && !a.r_unless.iter().any(exists)
+ }
+
+ // `req_args`: an arg to include in the error even if not used
+ fn missing_required_error(
+ &self,
+ matcher: &ArgMatcher,
+ raw_req_args: Vec<Id>,
+ ) -> ClapResult<()> {
+ debug!("Validator::missing_required_error; incl={:?}", raw_req_args);
+ debug!(
+ "Validator::missing_required_error: reqs={:?}",
+ self.required
+ );
+
+ let usg = Usage::new(self.cmd).required(&self.required);
+
+ let req_args = {
+ #[cfg(feature = "usage")]
+ {
+ usg.get_required_usage_from(&raw_req_args, Some(matcher), true)
+ .into_iter()
+ .map(|s| s.to_string())
+ .collect::<Vec<_>>()
+ }
+
+ #[cfg(not(feature = "usage"))]
+ {
+ raw_req_args
+ .iter()
+ .map(|id| {
+ if let Some(arg) = self.cmd.find(id) {
+ arg.to_string()
+ } else if let Some(_group) = self.cmd.find_group(id) {
+ self.cmd.format_group(id).to_string()
+ } else {
+ debug_assert!(false, "id={:?} is unknown", id);
+ "".to_owned()
+ }
+ })
+ .collect::<Vec<_>>()
+ }
+ };
+
+ debug!(
+ "Validator::missing_required_error: req_args={:#?}",
+ req_args
+ );
+
+ let used: Vec<Id> = matcher
+ .args()
+ .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent))
+ .map(|(n, _)| n)
+ .filter(|n| {
+ // Filter out the args we don't want to specify.
+ self.cmd.find(n).map_or(false, |a| !a.is_hide_set())
+ })
+ .cloned()
+ .chain(raw_req_args)
+ .collect();
+
+ Err(Error::missing_required_argument(
+ self.cmd,
+ req_args,
+ usg.create_usage_with_title(&used),
+ ))
+ }
+}
+
+#[derive(Default, Clone, Debug)]
+struct Conflicts {
+ potential: FlatMap<Id, Vec<Id>>,
+}
+
+impl Conflicts {
+ fn with_args(cmd: &Command, matcher: &ArgMatcher) -> Self {
+ let mut potential = FlatMap::new();
+ potential.extend_unchecked(
+ matcher
+ .args()
+ .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent))
+ .map(|(id, _)| {
+ let conf = gather_direct_conflicts(cmd, id);
+ (id.clone(), conf)
+ }),
+ );
+ Self { potential }
+ }
+
+ fn gather_conflicts(&self, cmd: &Command, arg_id: &Id) -> Vec<Id> {
+ debug!("Conflicts::gather_conflicts: arg={:?}", arg_id);
+ let mut conflicts = Vec::new();
+
+ let arg_id_conflicts_storage;
+ let arg_id_conflicts = if let Some(arg_id_conflicts) = self.get_direct_conflicts(arg_id) {
+ arg_id_conflicts
+ } else {
+ // `is_missing_required_ok` is a case where we check not-present args for conflicts
+ arg_id_conflicts_storage = gather_direct_conflicts(cmd, arg_id);
+ &arg_id_conflicts_storage
+ };
+ for (other_arg_id, other_arg_id_conflicts) in self.potential.iter() {
+ if arg_id == other_arg_id {
+ continue;
+ }
+
+ if arg_id_conflicts.contains(other_arg_id) {
+ conflicts.push(other_arg_id.clone());
+ }
+ if other_arg_id_conflicts.contains(arg_id) {
+ conflicts.push(other_arg_id.clone());
+ }
+ }
+
+ debug!("Conflicts::gather_conflicts: conflicts={:?}", conflicts);
+ conflicts
+ }
+
+ fn get_direct_conflicts(&self, arg_id: &Id) -> Option<&[Id]> {
+ self.potential.get(arg_id).map(Vec::as_slice)
+ }
+}
+
+fn gather_direct_conflicts(cmd: &Command, id: &Id) -> Vec<Id> {
+ let conf = if let Some(arg) = cmd.find(id) {
+ gather_arg_direct_conflicts(cmd, arg)
+ } else if let Some(group) = cmd.find_group(id) {
+ gather_group_direct_conflicts(group)
+ } else {
+ debug_assert!(false, "id={id:?} is unknown");
+ Vec::new()
+ };
+ debug!("Conflicts::gather_direct_conflicts id={id:?}, conflicts={conf:?}",);
+ conf
+}
+
+fn gather_arg_direct_conflicts(cmd: &Command, arg: &Arg) -> Vec<Id> {
+ let mut conf = arg.blacklist.clone();
+ for group_id in cmd.groups_for_arg(arg.get_id()) {
+ let group = cmd.find_group(&group_id).expect(INTERNAL_ERROR_MSG);
+ conf.extend(group.conflicts.iter().cloned());
+ if !group.multiple {
+ for member_id in &group.args {
+ if member_id != arg.get_id() {
+ conf.push(member_id.clone());
+ }
+ }
+ }
+ }
+
+ // Overrides are implicitly conflicts
+ conf.extend(arg.overrides.iter().cloned());
+
+ conf
+}
+
+fn gather_group_direct_conflicts(group: &ArgGroup) -> Vec<Id> {
+ group.conflicts.clone()
+}
+
+pub(crate) fn get_possible_values_cli(a: &Arg) -> Vec<PossibleValue> {
+ if !a.is_takes_value_set() {
+ vec![]
+ } else {
+ a.get_value_parser()
+ .possible_values()
+ .map(|pvs| pvs.collect())
+ .unwrap_or_default()
+ }
+}
diff --git a/src/strext.rs b/src/strext.rs
deleted file mode 100644
index 6f81367..0000000
--- a/src/strext.rs
+++ /dev/null
@@ -1,16 +0,0 @@
-pub trait _StrExt {
- fn _is_char_boundary(&self, index: usize) -> bool;
-}
-
-impl _StrExt for str {
- #[inline]
- fn _is_char_boundary(&self, index: usize) -> bool {
- if index == self.len() {
- return true;
- }
- match self.as_bytes().get(index) {
- None => false,
- Some(&b) => b < 128 || b >= 192,
- }
- }
-}
diff --git a/src/suggestions.rs b/src/suggestions.rs
deleted file mode 100644
index 1157b26..0000000
--- a/src/suggestions.rs
+++ /dev/null
@@ -1,147 +0,0 @@
-use app::App;
-// Third Party
-#[cfg(feature = "suggestions")]
-use strsim;
-
-// Internal
-use fmt::Format;
-
-/// Produces a string from a given list of possible values which is similar to
-/// the passed in value `v` with a certain confidence.
-/// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield
-/// `Some("foo")`, whereas "blark" would yield `None`.
-#[cfg(feature = "suggestions")]
-#[cfg_attr(feature = "lints", allow(needless_lifetimes))]
-pub fn did_you_mean<'a, T: ?Sized, I>(v: &str, possible_values: I) -> Option<&'a str>
-where
- T: AsRef<str> + 'a,
- I: IntoIterator<Item = &'a T>,
-{
- let mut candidate: Option<(f64, &str)> = None;
- for pv in possible_values {
- let confidence = strsim::jaro_winkler(v, pv.as_ref());
- if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence))
- {
- candidate = Some((confidence, pv.as_ref()));
- }
- }
- match candidate {
- None => None,
- Some((_, candidate)) => Some(candidate),
- }
-}
-
-#[cfg(not(feature = "suggestions"))]
-pub fn did_you_mean<'a, T: ?Sized, I>(_: &str, _: I) -> Option<&'a str>
-where
- T: AsRef<str> + 'a,
- I: IntoIterator<Item = &'a T>,
-{
- None
-}
-
-/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase
-#[cfg_attr(feature = "lints", allow(needless_lifetimes))]
-pub fn did_you_mean_flag_suffix<'z, T, I>(
- arg: &str,
- args_rest: &'z [&str],
- longs: I,
- subcommands: &'z [App],
-) -> (String, Option<&'z str>)
-where
- T: AsRef<str> + 'z,
- I: IntoIterator<Item = &'z T>,
-{
- if let Some(candidate) = did_you_mean(arg, longs) {
- let suffix = format!(
- "\n\tDid you mean {}{}?",
- Format::Good("--"),
- Format::Good(candidate)
- );
- return (suffix, Some(candidate));
- }
-
- subcommands
- .into_iter()
- .filter_map(|subcommand| {
- let opts = subcommand
- .p
- .flags
- .iter()
- .filter_map(|f| f.s.long)
- .chain(subcommand.p.opts.iter().filter_map(|o| o.s.long));
-
- let candidate = match did_you_mean(arg, opts) {
- Some(candidate) => candidate,
- None => return None,
- };
- let score = match args_rest.iter().position(|x| *x == subcommand.get_name()) {
- Some(score) => score,
- None => return None,
- };
-
- let suffix = format!(
- "\n\tDid you mean to put '{}{}' after the subcommand '{}'?",
- Format::Good("--"),
- Format::Good(candidate),
- Format::Good(subcommand.get_name())
- );
-
- Some((score, (suffix, Some(candidate))))
- })
- .min_by_key(|&(score, _)| score)
- .map(|(_, suggestion)| suggestion)
- .unwrap_or_else(|| (String::new(), None))
-}
-
-/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase
-pub fn did_you_mean_value_suffix<'z, T, I>(arg: &str, values: I) -> (String, Option<&'z str>)
-where
- T: AsRef<str> + 'z,
- I: IntoIterator<Item = &'z T>,
-{
- match did_you_mean(arg, values) {
- Some(candidate) => {
- let suffix = format!("\n\tDid you mean '{}'?", Format::Good(candidate));
- (suffix, Some(candidate))
- }
- None => (String::new(), None),
- }
-}
-
-#[cfg(all(test, features = "suggestions"))]
-mod test {
- use super::*;
-
- #[test]
- fn possible_values_match() {
- let p_vals = ["test", "possible", "values"];
- assert_eq!(did_you_mean("tst", p_vals.iter()), Some("test"));
- }
-
- #[test]
- fn possible_values_nomatch() {
- let p_vals = ["test", "possible", "values"];
- assert!(did_you_mean("hahaahahah", p_vals.iter()).is_none());
- }
-
- #[test]
- fn suffix_long() {
- let p_vals = ["test", "possible", "values"];
- let suffix = "\n\tDid you mean \'--test\'?";
- assert_eq!(
- did_you_mean_flag_suffix("tst", p_vals.iter(), []),
- (suffix, Some("test"))
- );
- }
-
- #[test]
- fn suffix_enum() {
- let p_vals = ["test", "possible", "values"];
- let suffix = "\n\tDid you mean \'test\'?";
- assert_eq!(
- did_you_mean_value_suffix("tst", p_vals.iter()),
- (suffix, Some("test"))
- );
- }
-}
diff --git a/src/usage_parser.rs b/src/usage_parser.rs
deleted file mode 100644
index 0a383eb..0000000
--- a/src/usage_parser.rs
+++ /dev/null
@@ -1,1358 +0,0 @@
-// Internal
-use args::settings::ArgSettings;
-use args::Arg;
-use map::VecMap;
-use INTERNAL_ERROR_MSG;
-
-#[derive(PartialEq, Debug)]
-enum UsageToken {
- Name,
- ValName,
- Short,
- Long,
- Help,
- Multiple,
- Unknown,
-}
-
-#[doc(hidden)]
-#[derive(Debug)]
-pub struct UsageParser<'a> {
- usage: &'a str,
- pos: usize,
- start: usize,
- prev: UsageToken,
- explicit_name_set: bool,
-}
-
-impl<'a> UsageParser<'a> {
- fn new(usage: &'a str) -> Self {
- debugln!("UsageParser::new: usage={:?}", usage);
- UsageParser {
- usage: usage,
- pos: 0,
- start: 0,
- prev: UsageToken::Unknown,
- explicit_name_set: false,
- }
- }
-
- pub fn from_usage(usage: &'a str) -> Self {
- debugln!("UsageParser::from_usage;");
- UsageParser::new(usage)
- }
-
- pub fn parse(mut self) -> Arg<'a, 'a> {
- debugln!("UsageParser::parse;");
- let mut arg = Arg::default();
- loop {
- debugln!("UsageParser::parse:iter: pos={};", self.pos);
- self.stop_at(token);
- if let Some(&c) = self.usage.as_bytes().get(self.pos) {
- match c {
- b'-' => self.short_or_long(&mut arg),
- b'.' => self.multiple(&mut arg),
- b'\'' => self.help(&mut arg),
- _ => self.name(&mut arg),
- }
- } else {
- break;
- }
- }
- debug_assert!(
- !arg.b.name.is_empty(),
- format!(
- "No name found for Arg when parsing usage string: {}",
- self.usage
- )
- );
- arg.v.num_vals = match arg.v.val_names {
- Some(ref v) if v.len() >= 2 => Some(v.len() as u64),
- _ => None,
- };
- debugln!("UsageParser::parse: vals...{:?}", arg.v.val_names);
- arg
- }
-
- fn name(&mut self, arg: &mut Arg<'a, 'a>) {
- debugln!("UsageParser::name;");
- if *self
- .usage
- .as_bytes()
- .get(self.pos)
- .expect(INTERNAL_ERROR_MSG)
- == b'<'
- && !self.explicit_name_set
- {
- arg.setb(ArgSettings::Required);
- }
- self.pos += 1;
- self.stop_at(name_end);
- let name = &self.usage[self.start..self.pos];
- if self.prev == UsageToken::Unknown {
- debugln!("UsageParser::name: setting name...{}", name);
- arg.b.name = name;
- if arg.s.long.is_none() && arg.s.short.is_none() {
- debugln!("UsageParser::name: explicit name set...");
- self.explicit_name_set = true;
- self.prev = UsageToken::Name;
- }
- } else {
- debugln!("UsageParser::name: setting val name...{}", name);
- if let Some(ref mut v) = arg.v.val_names {
- let len = v.len();
- v.insert(len, name);
- } else {
- let mut v = VecMap::new();
- v.insert(0, name);
- arg.v.val_names = Some(v);
- arg.setb(ArgSettings::TakesValue);
- }
- self.prev = UsageToken::ValName;
- }
- }
-
- fn stop_at<F>(&mut self, f: F)
- where
- F: Fn(u8) -> bool,
- {
- debugln!("UsageParser::stop_at;");
- self.start = self.pos;
- self.pos += self.usage[self.start..]
- .bytes()
- .take_while(|&b| f(b))
- .count();
- }
-
- fn short_or_long(&mut self, arg: &mut Arg<'a, 'a>) {
- debugln!("UsageParser::short_or_long;");
- self.pos += 1;
- if *self
- .usage
- .as_bytes()
- .get(self.pos)
- .expect(INTERNAL_ERROR_MSG)
- == b'-'
- {
- self.pos += 1;
- self.long(arg);
- return;
- }
- self.short(arg)
- }
-
- fn long(&mut self, arg: &mut Arg<'a, 'a>) {
- debugln!("UsageParser::long;");
- self.stop_at(long_end);
- let name = &self.usage[self.start..self.pos];
- if !self.explicit_name_set {
- debugln!("UsageParser::long: setting name...{}", name);
- arg.b.name = name;
- }
- debugln!("UsageParser::long: setting long...{}", name);
- arg.s.long = Some(name);
- self.prev = UsageToken::Long;
- }
-
- fn short(&mut self, arg: &mut Arg<'a, 'a>) {
- debugln!("UsageParser::short;");
- let start = &self.usage[self.pos..];
- let short = start.chars().nth(0).expect(INTERNAL_ERROR_MSG);
- debugln!("UsageParser::short: setting short...{}", short);
- arg.s.short = Some(short);
- if arg.b.name.is_empty() {
- // --long takes precedence but doesn't set self.explicit_name_set
- let name = &start[..short.len_utf8()];
- debugln!("UsageParser::short: setting name...{}", name);
- arg.b.name = name;
- }
- self.prev = UsageToken::Short;
- }
-
- // "something..."
- fn multiple(&mut self, arg: &mut Arg) {
- debugln!("UsageParser::multiple;");
- let mut dot_counter = 1;
- let start = self.pos;
- let mut bytes = self.usage[start..].bytes();
- while bytes.next() == Some(b'.') {
- dot_counter += 1;
- self.pos += 1;
- if dot_counter == 3 {
- debugln!("UsageParser::multiple: setting multiple");
- arg.setb(ArgSettings::Multiple);
- if arg.is_set(ArgSettings::TakesValue) {
- arg.setb(ArgSettings::UseValueDelimiter);
- arg.unsetb(ArgSettings::ValueDelimiterNotSet);
- if arg.v.val_delim.is_none() {
- arg.v.val_delim = Some(',');
- }
- }
- self.prev = UsageToken::Multiple;
- self.pos += 1;
- break;
- }
- }
- }
-
- fn help(&mut self, arg: &mut Arg<'a, 'a>) {
- debugln!("UsageParser::help;");
- self.stop_at(help_start);
- self.start = self.pos + 1;
- self.pos = self.usage.len() - 1;
- debugln!(
- "UsageParser::help: setting help...{}",
- &self.usage[self.start..self.pos]
- );
- arg.b.help = Some(&self.usage[self.start..self.pos]);
- self.pos += 1; // Move to next byte to keep from thinking ending ' is a start
- self.prev = UsageToken::Help;
- }
-}
-
-#[inline]
-fn name_end(b: u8) -> bool {
- b != b']' && b != b'>'
-}
-
-#[inline]
-fn token(b: u8) -> bool {
- b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'-'
-}
-
-#[inline]
-fn long_end(b: u8) -> bool {
- b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'=' && b != b' '
-}
-
-#[inline]
-fn help_start(b: u8) -> bool {
- b != b'\''
-}
-
-#[cfg(test)]
-mod test {
- use args::Arg;
- use args::ArgSettings;
-
- #[test]
- fn create_flag_usage() {
- let a = Arg::from_usage("[flag] -f 'some help info'");
- assert_eq!(a.b.name, "flag");
- assert_eq!(a.s.short.unwrap(), 'f');
- assert!(a.s.long.is_none());
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(!a.is_set(ArgSettings::Multiple));
- assert!(a.v.val_names.is_none());
- assert!(a.v.num_vals.is_none());
-
- let b = Arg::from_usage("[flag] --flag 'some help info'");
- assert_eq!(b.b.name, "flag");
- assert_eq!(b.s.long.unwrap(), "flag");
- assert!(b.s.short.is_none());
- assert_eq!(b.b.help.unwrap(), "some help info");
- assert!(!b.is_set(ArgSettings::Multiple));
- assert!(a.v.val_names.is_none());
- assert!(a.v.num_vals.is_none());
-
- let b = Arg::from_usage("--flag 'some help info'");
- assert_eq!(b.b.name, "flag");
- assert_eq!(b.s.long.unwrap(), "flag");
- assert!(b.s.short.is_none());
- assert_eq!(b.b.help.unwrap(), "some help info");
- assert!(!b.is_set(ArgSettings::Multiple));
- assert!(b.v.val_names.is_none());
- assert!(b.v.num_vals.is_none());
-
- let c = Arg::from_usage("[flag] -f --flag 'some help info'");
- assert_eq!(c.b.name, "flag");
- assert_eq!(c.s.short.unwrap(), 'f');
- assert_eq!(c.s.long.unwrap(), "flag");
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(!c.is_set(ArgSettings::Multiple));
- assert!(c.v.val_names.is_none());
- assert!(c.v.num_vals.is_none());
-
- let d = Arg::from_usage("[flag] -f... 'some help info'");
- assert_eq!(d.b.name, "flag");
- assert_eq!(d.s.short.unwrap(), 'f');
- assert!(d.s.long.is_none());
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(d.is_set(ArgSettings::Multiple));
- assert!(d.v.val_names.is_none());
- assert!(d.v.num_vals.is_none());
-
- let e = Arg::from_usage("[flag] -f --flag... 'some help info'");
- assert_eq!(e.b.name, "flag");
- assert_eq!(e.s.long.unwrap(), "flag");
- assert_eq!(e.s.short.unwrap(), 'f');
- assert_eq!(e.b.help.unwrap(), "some help info");
- assert!(e.is_set(ArgSettings::Multiple));
- assert!(e.v.val_names.is_none());
- assert!(e.v.num_vals.is_none());
-
- let e = Arg::from_usage("-f --flag... 'some help info'");
- assert_eq!(e.b.name, "flag");
- assert_eq!(e.s.long.unwrap(), "flag");
- assert_eq!(e.s.short.unwrap(), 'f');
- assert_eq!(e.b.help.unwrap(), "some help info");
- assert!(e.is_set(ArgSettings::Multiple));
- assert!(e.v.val_names.is_none());
- assert!(e.v.num_vals.is_none());
-
- let e = Arg::from_usage("--flags");
- assert_eq!(e.b.name, "flags");
- assert_eq!(e.s.long.unwrap(), "flags");
- assert!(e.v.val_names.is_none());
- assert!(e.v.num_vals.is_none());
-
- let e = Arg::from_usage("--flags...");
- assert_eq!(e.b.name, "flags");
- assert_eq!(e.s.long.unwrap(), "flags");
- assert!(e.is_set(ArgSettings::Multiple));
- assert!(e.v.val_names.is_none());
- assert!(e.v.num_vals.is_none());
-
- let e = Arg::from_usage("[flags] -f");
- assert_eq!(e.b.name, "flags");
- assert_eq!(e.s.short.unwrap(), 'f');
- assert!(e.v.val_names.is_none());
- assert!(e.v.num_vals.is_none());
-
- let e = Arg::from_usage("[flags] -f...");
- assert_eq!(e.b.name, "flags");
- assert_eq!(e.s.short.unwrap(), 'f');
- assert!(e.is_set(ArgSettings::Multiple));
- assert!(e.v.val_names.is_none());
- assert!(e.v.num_vals.is_none());
-
- let a = Arg::from_usage("-f 'some help info'");
- assert_eq!(a.b.name, "f");
- assert_eq!(a.s.short.unwrap(), 'f');
- assert!(a.s.long.is_none());
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(!a.is_set(ArgSettings::Multiple));
- assert!(a.v.val_names.is_none());
- assert!(a.v.num_vals.is_none());
-
- let e = Arg::from_usage("-f");
- assert_eq!(e.b.name, "f");
- assert_eq!(e.s.short.unwrap(), 'f');
- assert!(e.v.val_names.is_none());
- assert!(e.v.num_vals.is_none());
-
- let e = Arg::from_usage("-f...");
- assert_eq!(e.b.name, "f");
- assert_eq!(e.s.short.unwrap(), 'f');
- assert!(e.is_set(ArgSettings::Multiple));
- assert!(e.v.val_names.is_none());
- assert!(e.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage0() {
- // Short only
- let a = Arg::from_usage("[option] -o [opt] 'some help info'");
- assert_eq!(a.b.name, "option");
- assert_eq!(a.s.short.unwrap(), 'o');
- assert!(a.s.long.is_none());
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(!a.is_set(ArgSettings::Multiple));
- assert!(a.is_set(ArgSettings::TakesValue));
- assert!(!a.is_set(ArgSettings::Required));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage1() {
- let b = Arg::from_usage("-o [opt] 'some help info'");
- assert_eq!(b.b.name, "o");
- assert_eq!(b.s.short.unwrap(), 'o');
- assert!(b.s.long.is_none());
- assert_eq!(b.b.help.unwrap(), "some help info");
- assert!(!b.is_set(ArgSettings::Multiple));
- assert!(b.is_set(ArgSettings::TakesValue));
- assert!(!b.is_set(ArgSettings::Required));
- assert_eq!(
- b.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(b.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage2() {
- let c = Arg::from_usage("<option> -o <opt> 'some help info'");
- assert_eq!(c.b.name, "option");
- assert_eq!(c.s.short.unwrap(), 'o');
- assert!(c.s.long.is_none());
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(!c.is_set(ArgSettings::Multiple));
- assert!(c.is_set(ArgSettings::TakesValue));
- assert!(c.is_set(ArgSettings::Required));
- assert_eq!(
- c.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage3() {
- let d = Arg::from_usage("-o <opt> 'some help info'");
- assert_eq!(d.b.name, "o");
- assert_eq!(d.s.short.unwrap(), 'o');
- assert!(d.s.long.is_none());
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(!d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(d.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage4() {
- let a = Arg::from_usage("[option] -o [opt]... 'some help info'");
- assert_eq!(a.b.name, "option");
- assert_eq!(a.s.short.unwrap(), 'o');
- assert!(a.s.long.is_none());
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(a.is_set(ArgSettings::Multiple));
- assert!(a.is_set(ArgSettings::TakesValue));
- assert!(!a.is_set(ArgSettings::Required));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage5() {
- let a = Arg::from_usage("[option]... -o [opt] 'some help info'");
- assert_eq!(a.b.name, "option");
- assert_eq!(a.s.short.unwrap(), 'o');
- assert!(a.s.long.is_none());
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(a.is_set(ArgSettings::Multiple));
- assert!(a.is_set(ArgSettings::TakesValue));
- assert!(!a.is_set(ArgSettings::Required));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage6() {
- let b = Arg::from_usage("-o [opt]... 'some help info'");
- assert_eq!(b.b.name, "o");
- assert_eq!(b.s.short.unwrap(), 'o');
- assert!(b.s.long.is_none());
- assert_eq!(b.b.help.unwrap(), "some help info");
- assert!(b.is_set(ArgSettings::Multiple));
- assert!(b.is_set(ArgSettings::TakesValue));
- assert!(!b.is_set(ArgSettings::Required));
- assert_eq!(
- b.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(b.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage7() {
- let c = Arg::from_usage("<option> -o <opt>... 'some help info'");
- assert_eq!(c.b.name, "option");
- assert_eq!(c.s.short.unwrap(), 'o');
- assert!(c.s.long.is_none());
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(c.is_set(ArgSettings::TakesValue));
- assert!(c.is_set(ArgSettings::Required));
- assert_eq!(
- c.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage8() {
- let c = Arg::from_usage("<option>... -o <opt> 'some help info'");
- assert_eq!(c.b.name, "option");
- assert_eq!(c.s.short.unwrap(), 'o');
- assert!(c.s.long.is_none());
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(c.is_set(ArgSettings::TakesValue));
- assert!(c.is_set(ArgSettings::Required));
- assert_eq!(
- c.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage9() {
- let d = Arg::from_usage("-o <opt>... 'some help info'");
- assert_eq!(d.b.name, "o");
- assert_eq!(d.s.short.unwrap(), 'o');
- assert!(d.s.long.is_none());
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(d.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long1() {
- let a = Arg::from_usage("[option] --opt [opt] 'some help info'");
- assert_eq!(a.b.name, "option");
- assert_eq!(a.s.long.unwrap(), "opt");
- assert!(a.s.short.is_none());
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(!a.is_set(ArgSettings::Multiple));
- assert!(a.is_set(ArgSettings::TakesValue));
- assert!(!a.is_set(ArgSettings::Required));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long2() {
- let b = Arg::from_usage("--opt [option] 'some help info'");
- assert_eq!(b.b.name, "opt");
- assert_eq!(b.s.long.unwrap(), "opt");
- assert!(b.s.short.is_none());
- assert_eq!(b.b.help.unwrap(), "some help info");
- assert!(!b.is_set(ArgSettings::Multiple));
- assert!(b.is_set(ArgSettings::TakesValue));
- assert!(!b.is_set(ArgSettings::Required));
- assert_eq!(
- b.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(b.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long3() {
- let c = Arg::from_usage("<option> --opt <opt> 'some help info'");
- assert_eq!(c.b.name, "option");
- assert_eq!(c.s.long.unwrap(), "opt");
- assert!(c.s.short.is_none());
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(!c.is_set(ArgSettings::Multiple));
- assert!(c.is_set(ArgSettings::TakesValue));
- assert!(c.is_set(ArgSettings::Required));
- assert_eq!(
- c.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long4() {
- let d = Arg::from_usage("--opt <option> 'some help info'");
- assert_eq!(d.b.name, "opt");
- assert_eq!(d.s.long.unwrap(), "opt");
- assert!(d.s.short.is_none());
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(!d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(d.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long5() {
- let a = Arg::from_usage("[option] --opt [opt]... 'some help info'");
- assert_eq!(a.b.name, "option");
- assert_eq!(a.s.long.unwrap(), "opt");
- assert!(a.s.short.is_none());
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(a.is_set(ArgSettings::Multiple));
- assert!(a.is_set(ArgSettings::TakesValue));
- assert!(!a.is_set(ArgSettings::Required));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long6() {
- let a = Arg::from_usage("[option]... --opt [opt] 'some help info'");
- assert_eq!(a.b.name, "option");
- assert_eq!(a.s.long.unwrap(), "opt");
- assert!(a.s.short.is_none());
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(a.is_set(ArgSettings::Multiple));
- assert!(a.is_set(ArgSettings::TakesValue));
- assert!(!a.is_set(ArgSettings::Required));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long7() {
- let b = Arg::from_usage("--opt [option]... 'some help info'");
- assert_eq!(b.b.name, "opt");
- assert_eq!(b.s.long.unwrap(), "opt");
- assert!(b.s.short.is_none());
- assert_eq!(b.b.help.unwrap(), "some help info");
- assert!(b.is_set(ArgSettings::Multiple));
- assert!(b.is_set(ArgSettings::TakesValue));
- assert!(!b.is_set(ArgSettings::Required));
- assert_eq!(
- b.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(b.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long8() {
- let c = Arg::from_usage("<option> --opt <opt>... 'some help info'");
- assert_eq!(c.b.name, "option");
- assert_eq!(c.s.long.unwrap(), "opt");
- assert!(c.s.short.is_none());
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(c.is_set(ArgSettings::TakesValue));
- assert!(c.is_set(ArgSettings::Required));
- assert_eq!(
- c.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long9() {
- let c = Arg::from_usage("<option>... --opt <opt> 'some help info'");
- assert_eq!(c.b.name, "option");
- assert_eq!(c.s.long.unwrap(), "opt");
- assert!(c.s.short.is_none());
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(c.is_set(ArgSettings::TakesValue));
- assert!(c.is_set(ArgSettings::Required));
- assert_eq!(
- c.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long10() {
- let d = Arg::from_usage("--opt <option>... 'some help info'");
- assert_eq!(d.b.name, "opt");
- assert_eq!(d.s.long.unwrap(), "opt");
- assert!(d.s.short.is_none());
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(d.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long_equals1() {
- let a = Arg::from_usage("[option] --opt=[opt] 'some help info'");
- assert_eq!(a.b.name, "option");
- assert_eq!(a.s.long.unwrap(), "opt");
- assert!(a.s.short.is_none());
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(!a.is_set(ArgSettings::Multiple));
- assert!(a.is_set(ArgSettings::TakesValue));
- assert!(!a.is_set(ArgSettings::Required));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long_equals2() {
- let b = Arg::from_usage("--opt=[option] 'some help info'");
- assert_eq!(b.b.name, "opt");
- assert_eq!(b.s.long.unwrap(), "opt");
- assert!(b.s.short.is_none());
- assert_eq!(b.b.help.unwrap(), "some help info");
- assert!(!b.is_set(ArgSettings::Multiple));
- assert!(b.is_set(ArgSettings::TakesValue));
- assert!(!b.is_set(ArgSettings::Required));
- assert_eq!(
- b.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(b.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long_equals3() {
- let c = Arg::from_usage("<option> --opt=<opt> 'some help info'");
- assert_eq!(c.b.name, "option");
- assert_eq!(c.s.long.unwrap(), "opt");
- assert!(c.s.short.is_none());
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(!c.is_set(ArgSettings::Multiple));
- assert!(c.is_set(ArgSettings::TakesValue));
- assert!(c.is_set(ArgSettings::Required));
- assert_eq!(
- c.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long_equals4() {
- let d = Arg::from_usage("--opt=<option> 'some help info'");
- assert_eq!(d.b.name, "opt");
- assert_eq!(d.s.long.unwrap(), "opt");
- assert!(d.s.short.is_none());
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(!d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(d.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long_equals5() {
- let a = Arg::from_usage("[option] --opt=[opt]... 'some help info'");
- assert_eq!(a.b.name, "option");
- assert_eq!(a.s.long.unwrap(), "opt");
- assert!(a.s.short.is_none());
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(a.is_set(ArgSettings::Multiple));
- assert!(a.is_set(ArgSettings::TakesValue));
- assert!(!a.is_set(ArgSettings::Required));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long_equals6() {
- let a = Arg::from_usage("[option]... --opt=[opt] 'some help info'");
- assert_eq!(a.b.name, "option");
- assert_eq!(a.s.long.unwrap(), "opt");
- assert!(a.s.short.is_none());
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(a.is_set(ArgSettings::Multiple));
- assert!(a.is_set(ArgSettings::TakesValue));
- assert!(!a.is_set(ArgSettings::Required));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long_equals7() {
- let b = Arg::from_usage("--opt=[option]... 'some help info'");
- assert_eq!(b.b.name, "opt");
- assert_eq!(b.s.long.unwrap(), "opt");
- assert!(b.s.short.is_none());
- assert_eq!(b.b.help.unwrap(), "some help info");
- assert!(b.is_set(ArgSettings::Multiple));
- assert!(b.is_set(ArgSettings::TakesValue));
- assert!(!b.is_set(ArgSettings::Required));
- assert_eq!(
- b.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(b.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long_equals8() {
- let c = Arg::from_usage("<option> --opt=<opt>... 'some help info'");
- assert_eq!(c.b.name, "option");
- assert_eq!(c.s.long.unwrap(), "opt");
- assert!(c.s.short.is_none());
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(c.is_set(ArgSettings::TakesValue));
- assert!(c.is_set(ArgSettings::Required));
- assert_eq!(
- c.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long_equals9() {
- let c = Arg::from_usage("<option>... --opt=<opt> 'some help info'");
- assert_eq!(c.b.name, "option");
- assert_eq!(c.s.long.unwrap(), "opt");
- assert!(c.s.short.is_none());
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(c.is_set(ArgSettings::TakesValue));
- assert!(c.is_set(ArgSettings::Required));
- assert_eq!(
- c.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_long_equals10() {
- let d = Arg::from_usage("--opt=<option>... 'some help info'");
- assert_eq!(d.b.name, "opt");
- assert_eq!(d.s.long.unwrap(), "opt");
- assert!(d.s.short.is_none());
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(d.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both1() {
- let a = Arg::from_usage("[option] -o --opt [option] 'some help info'");
- assert_eq!(a.b.name, "option");
- assert_eq!(a.s.long.unwrap(), "opt");
- assert_eq!(a.s.short.unwrap(), 'o');
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(!a.is_set(ArgSettings::Multiple));
- assert!(a.is_set(ArgSettings::TakesValue));
- assert!(!a.is_set(ArgSettings::Required));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both2() {
- let b = Arg::from_usage("-o --opt [option] 'some help info'");
- assert_eq!(b.b.name, "opt");
- assert_eq!(b.s.long.unwrap(), "opt");
- assert_eq!(b.s.short.unwrap(), 'o');
- assert_eq!(b.b.help.unwrap(), "some help info");
- assert!(!b.is_set(ArgSettings::Multiple));
- assert!(b.is_set(ArgSettings::TakesValue));
- assert!(!b.is_set(ArgSettings::Required));
- assert_eq!(
- b.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(b.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both3() {
- let c = Arg::from_usage("<option> -o --opt <opt> 'some help info'");
- assert_eq!(c.b.name, "option");
- assert_eq!(c.s.long.unwrap(), "opt");
- assert_eq!(c.s.short.unwrap(), 'o');
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(!c.is_set(ArgSettings::Multiple));
- assert!(c.is_set(ArgSettings::TakesValue));
- assert!(c.is_set(ArgSettings::Required));
- assert_eq!(
- c.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both4() {
- let d = Arg::from_usage("-o --opt <option> 'some help info'");
- assert_eq!(d.b.name, "opt");
- assert_eq!(d.s.long.unwrap(), "opt");
- assert_eq!(d.s.short.unwrap(), 'o');
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(!d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(d.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both5() {
- let a = Arg::from_usage("[option]... -o --opt [option] 'some help info'");
- assert_eq!(a.b.name, "option");
- assert_eq!(a.s.long.unwrap(), "opt");
- assert_eq!(a.s.short.unwrap(), 'o');
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(a.is_set(ArgSettings::Multiple));
- assert!(a.is_set(ArgSettings::TakesValue));
- assert!(!a.is_set(ArgSettings::Required));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both6() {
- let b = Arg::from_usage("-o --opt [option]... 'some help info'");
- assert_eq!(b.b.name, "opt");
- assert_eq!(b.s.long.unwrap(), "opt");
- assert_eq!(b.s.short.unwrap(), 'o');
- assert_eq!(b.b.help.unwrap(), "some help info");
- assert!(b.is_set(ArgSettings::Multiple));
- assert!(b.is_set(ArgSettings::TakesValue));
- assert!(!b.is_set(ArgSettings::Required));
- assert_eq!(
- b.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(b.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both7() {
- let c = Arg::from_usage("<option>... -o --opt <opt> 'some help info'");
- assert_eq!(c.b.name, "option");
- assert_eq!(c.s.long.unwrap(), "opt");
- assert_eq!(c.s.short.unwrap(), 'o');
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(c.is_set(ArgSettings::TakesValue));
- assert!(c.is_set(ArgSettings::Required));
- assert_eq!(
- c.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both8() {
- let d = Arg::from_usage("-o --opt <option>... 'some help info'");
- assert_eq!(d.b.name, "opt");
- assert_eq!(d.s.long.unwrap(), "opt");
- assert_eq!(d.s.short.unwrap(), 'o');
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(d.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both_equals1() {
- let a = Arg::from_usage("[option] -o --opt=[option] 'some help info'");
- assert_eq!(a.b.name, "option");
- assert_eq!(a.s.long.unwrap(), "opt");
- assert_eq!(a.s.short.unwrap(), 'o');
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(!a.is_set(ArgSettings::Multiple));
- assert!(a.is_set(ArgSettings::TakesValue));
- assert!(!a.is_set(ArgSettings::Required));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both_equals2() {
- let b = Arg::from_usage("-o --opt=[option] 'some help info'");
- assert_eq!(b.b.name, "opt");
- assert_eq!(b.s.long.unwrap(), "opt");
- assert_eq!(b.s.short.unwrap(), 'o');
- assert_eq!(b.b.help.unwrap(), "some help info");
- assert!(!b.is_set(ArgSettings::Multiple));
- assert!(b.is_set(ArgSettings::TakesValue));
- assert!(!b.is_set(ArgSettings::Required));
- assert_eq!(
- b.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(b.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both_equals3() {
- let c = Arg::from_usage("<option> -o --opt=<opt> 'some help info'");
- assert_eq!(c.b.name, "option");
- assert_eq!(c.s.long.unwrap(), "opt");
- assert_eq!(c.s.short.unwrap(), 'o');
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(!c.is_set(ArgSettings::Multiple));
- assert!(c.is_set(ArgSettings::TakesValue));
- assert!(c.is_set(ArgSettings::Required));
- assert_eq!(
- c.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both_equals4() {
- let d = Arg::from_usage("-o --opt=<option> 'some help info'");
- assert_eq!(d.b.name, "opt");
- assert_eq!(d.s.long.unwrap(), "opt");
- assert_eq!(d.s.short.unwrap(), 'o');
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(!d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(d.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both_equals5() {
- let a = Arg::from_usage("[option]... -o --opt=[option] 'some help info'");
- assert_eq!(a.b.name, "option");
- assert_eq!(a.s.long.unwrap(), "opt");
- assert_eq!(a.s.short.unwrap(), 'o');
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(a.is_set(ArgSettings::Multiple));
- assert!(a.is_set(ArgSettings::TakesValue));
- assert!(!a.is_set(ArgSettings::Required));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both_equals6() {
- let b = Arg::from_usage("-o --opt=[option]... 'some help info'");
- assert_eq!(b.b.name, "opt");
- assert_eq!(b.s.long.unwrap(), "opt");
- assert_eq!(b.s.short.unwrap(), 'o');
- assert_eq!(b.b.help.unwrap(), "some help info");
- assert!(b.is_set(ArgSettings::Multiple));
- assert!(b.is_set(ArgSettings::TakesValue));
- assert!(!b.is_set(ArgSettings::Required));
- assert_eq!(
- b.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(b.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both_equals7() {
- let c = Arg::from_usage("<option>... -o --opt=<opt> 'some help info'");
- assert_eq!(c.b.name, "option");
- assert_eq!(c.s.long.unwrap(), "opt");
- assert_eq!(c.s.short.unwrap(), 'o');
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(c.is_set(ArgSettings::TakesValue));
- assert!(c.is_set(ArgSettings::Required));
- assert_eq!(
- c.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"opt"]
- );
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_usage_both_equals8() {
- let d = Arg::from_usage("-o --opt=<option>... 'some help info'");
- assert_eq!(d.b.name, "opt");
- assert_eq!(d.s.long.unwrap(), "opt");
- assert_eq!(d.s.short.unwrap(), 'o');
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"option"]
- );
- assert!(d.v.num_vals.is_none());
- }
-
- #[test]
- fn create_option_with_vals1() {
- let d = Arg::from_usage("-o <file> <mode> 'some help info'");
- assert_eq!(d.b.name, "o");
- assert!(d.s.long.is_none());
- assert_eq!(d.s.short.unwrap(), 'o');
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(!d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"file", &"mode"]
- );
- assert_eq!(d.v.num_vals.unwrap(), 2);
- }
-
- #[test]
- fn create_option_with_vals2() {
- let d = Arg::from_usage("-o <file> <mode>... 'some help info'");
- assert_eq!(d.b.name, "o");
- assert!(d.s.long.is_none());
- assert_eq!(d.s.short.unwrap(), 'o');
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"file", &"mode"]
- );
- assert_eq!(d.v.num_vals.unwrap(), 2);
- }
-
- #[test]
- fn create_option_with_vals3() {
- let d = Arg::from_usage("--opt <file> <mode>... 'some help info'");
- assert_eq!(d.b.name, "opt");
- assert!(d.s.short.is_none());
- assert_eq!(d.s.long.unwrap(), "opt");
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"file", &"mode"]
- );
- assert_eq!(d.v.num_vals.unwrap(), 2);
- }
-
- #[test]
- fn create_option_with_vals4() {
- let d = Arg::from_usage("[myopt] --opt <file> <mode> 'some help info'");
- assert_eq!(d.b.name, "myopt");
- assert!(d.s.short.is_none());
- assert_eq!(d.s.long.unwrap(), "opt");
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(!d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(!d.is_set(ArgSettings::Required));
- assert_eq!(
- d.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"file", &"mode"]
- );
- assert_eq!(d.v.num_vals.unwrap(), 2);
- }
-
- #[test]
- fn create_option_with_vals5() {
- let d = Arg::from_usage("--opt <file> <mode> 'some help info'");
- assert_eq!(d.b.name, "opt");
- assert!(d.s.short.is_none());
- assert_eq!(d.s.long.unwrap(), "opt");
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(!d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::TakesValue));
- assert!(d.is_set(ArgSettings::Required));
- assert_eq!(d.v.num_vals.unwrap(), 2);
- }
-
- #[test]
- fn create_positional_usage() {
- let a = Arg::from_usage("[pos] 'some help info'");
- assert_eq!(a.b.name, "pos");
- assert_eq!(a.b.help.unwrap(), "some help info");
- assert!(!a.is_set(ArgSettings::Multiple));
- assert!(!a.is_set(ArgSettings::Required));
- assert!(a.v.val_names.is_none());
- assert!(a.v.num_vals.is_none());
- }
-
- #[test]
- fn create_positional_usage0() {
- let b = Arg::from_usage("<pos> 'some help info'");
- assert_eq!(b.b.name, "pos");
- assert_eq!(b.b.help.unwrap(), "some help info");
- assert!(!b.is_set(ArgSettings::Multiple));
- assert!(b.is_set(ArgSettings::Required));
- assert!(b.v.val_names.is_none());
- assert!(b.v.num_vals.is_none());
- }
-
- #[test]
- fn pos_mult_help() {
- let c = Arg::from_usage("[pos]... 'some help info'");
- assert_eq!(c.b.name, "pos");
- assert_eq!(c.b.help.unwrap(), "some help info");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(!c.is_set(ArgSettings::Required));
- assert!(c.v.val_names.is_none());
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn pos_help_lit_single_quote() {
- let c = Arg::from_usage("[pos]... 'some help\' info'");
- assert_eq!(c.b.name, "pos");
- assert_eq!(c.b.help.unwrap(), "some help' info");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(!c.is_set(ArgSettings::Required));
- assert!(c.v.val_names.is_none());
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn pos_help_double_lit_single_quote() {
- let c = Arg::from_usage("[pos]... 'some \'help\' info'");
- assert_eq!(c.b.name, "pos");
- assert_eq!(c.b.help.unwrap(), "some 'help' info");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(!c.is_set(ArgSettings::Required));
- assert!(c.v.val_names.is_none());
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn pos_help_newline() {
- let c = Arg::from_usage(
- "[pos]... 'some help{n}\
- info'",
- );
- assert_eq!(c.b.name, "pos");
- assert_eq!(c.b.help.unwrap(), "some help{n}info");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(!c.is_set(ArgSettings::Required));
- assert!(c.v.val_names.is_none());
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn pos_help_newline_lit_sq() {
- let c = Arg::from_usage(
- "[pos]... 'some help\' stuff{n}\
- info'",
- );
- assert_eq!(c.b.name, "pos");
- assert_eq!(c.b.help.unwrap(), "some help' stuff{n}info");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(!c.is_set(ArgSettings::Required));
- assert!(c.v.val_names.is_none());
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn pos_req_mult_help() {
- let d = Arg::from_usage("<pos>... 'some help info'");
- assert_eq!(d.b.name, "pos");
- assert_eq!(d.b.help.unwrap(), "some help info");
- assert!(d.is_set(ArgSettings::Multiple));
- assert!(d.is_set(ArgSettings::Required));
- assert!(d.v.val_names.is_none());
- assert!(d.v.num_vals.is_none());
- }
-
- #[test]
- fn pos_req() {
- let b = Arg::from_usage("<pos>");
- assert_eq!(b.b.name, "pos");
- assert!(!b.is_set(ArgSettings::Multiple));
- assert!(b.is_set(ArgSettings::Required));
- assert!(b.v.val_names.is_none());
- assert!(b.v.num_vals.is_none());
- }
-
- #[test]
- fn pos_mult() {
- let c = Arg::from_usage("[pos]...");
- assert_eq!(c.b.name, "pos");
- assert!(c.is_set(ArgSettings::Multiple));
- assert!(!c.is_set(ArgSettings::Required));
- assert!(c.v.val_names.is_none());
- assert!(c.v.num_vals.is_none());
- }
-
- #[test]
- fn nonascii() {
- let a = Arg::from_usage("<ASCII> 'üñíčöĐ€'");
- assert_eq!(a.b.name, "ASCII");
- assert_eq!(a.b.help, Some("üñíčöĐ€"));
- let a = Arg::from_usage("<üñíčöĐ€> 'ASCII'");
- assert_eq!(a.b.name, "üñíčöĐ€");
- assert_eq!(a.b.help, Some("ASCII"));
- let a = Arg::from_usage("<üñíčöĐ€> 'üñíčöĐ€'");
- assert_eq!(a.b.name, "üñíčöĐ€");
- assert_eq!(a.b.help, Some("üñíčöĐ€"));
- let a = Arg::from_usage("-ø 'ø'");
- assert_eq!(a.b.name, "ø");
- assert_eq!(a.s.short, Some('ø'));
- assert_eq!(a.b.help, Some("ø"));
- let a = Arg::from_usage("--üñíčöĐ€ 'Nōṫ ASCII'");
- assert_eq!(a.b.name, "üñíčöĐ€");
- assert_eq!(a.s.long, Some("üñíčöĐ€"));
- assert_eq!(a.b.help, Some("Nōṫ ASCII"));
- let a = Arg::from_usage("[ñämê] --ôpt=[üñíčöĐ€] 'hælp'");
- assert_eq!(a.b.name, "ñämê");
- assert_eq!(a.s.long, Some("ôpt"));
- assert_eq!(
- a.v.val_names.unwrap().values().collect::<Vec<_>>(),
- [&"üñíčöĐ€"]
- );
- assert_eq!(a.b.help, Some("hælp"));
- }
-}
diff --git a/src/util/color.rs b/src/util/color.rs
new file mode 100644
index 0000000..5a0a8ce
--- /dev/null
+++ b/src/util/color.rs
@@ -0,0 +1,103 @@
+use crate::builder::PossibleValue;
+use crate::derive::ValueEnum;
+
+/// Represents the color preferences for program output
+#[derive(Debug, Copy, Clone, Eq, PartialEq)]
+pub enum ColorChoice {
+ /// Enables colored output only when the output is going to a terminal or TTY.
+ ///
+ /// **NOTE:** This is the default behavior of `clap`.
+ ///
+ /// # Platform Specific
+ ///
+ /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms).
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(feature = "color"), doc = " ```ignore")]
+ #[cfg_attr(feature = "color", doc = " ```no_run")]
+ /// # use clap::{Command, ColorChoice};
+ /// Command::new("myprog")
+ /// .color(ColorChoice::Auto)
+ /// .get_matches();
+ /// ```
+ Auto,
+
+ /// Enables colored output regardless of whether or not the output is going to a terminal/TTY.
+ ///
+ /// # Platform Specific
+ ///
+ /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms).
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(feature = "color"), doc = " ```ignore")]
+ #[cfg_attr(feature = "color", doc = " ```no_run")]
+ /// # use clap::{Command, ColorChoice};
+ /// Command::new("myprog")
+ /// .color(ColorChoice::Always)
+ /// .get_matches();
+ /// ```
+ Always,
+
+ /// Disables colored output no matter if the output is going to a terminal/TTY, or not.
+ ///
+ /// # Platform Specific
+ ///
+ /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms)
+ ///
+ /// # Examples
+ ///
+ #[cfg_attr(not(feature = "color"), doc = " ```ignore")]
+ #[cfg_attr(feature = "color", doc = " ```no_run")]
+ /// # use clap::{Command, ColorChoice};
+ /// Command::new("myprog")
+ /// .color(ColorChoice::Never)
+ /// .get_matches();
+ /// ```
+ Never,
+}
+
+impl Default for ColorChoice {
+ fn default() -> Self {
+ Self::Auto
+ }
+}
+
+impl std::fmt::Display for ColorChoice {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ self.to_possible_value()
+ .expect("no values are skipped")
+ .get_name()
+ .fmt(f)
+ }
+}
+
+impl std::str::FromStr for ColorChoice {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ for variant in Self::value_variants() {
+ if variant.to_possible_value().unwrap().matches(s, false) {
+ return Ok(*variant);
+ }
+ }
+ Err(format!("invalid variant: {s}"))
+ }
+}
+
+impl ValueEnum for ColorChoice {
+ fn value_variants<'a>() -> &'a [Self] {
+ &[Self::Auto, Self::Always, Self::Never]
+ }
+
+ fn to_possible_value(&self) -> Option<PossibleValue> {
+ Some(match self {
+ Self::Auto => {
+ PossibleValue::new("auto").help("Use colored output if writing to a terminal/TTY")
+ }
+ Self::Always => PossibleValue::new("always").help("Always use colored output"),
+ Self::Never => PossibleValue::new("never").help("Never use colored output"),
+ })
+ }
+}
diff --git a/src/util/flat_map.rs b/src/util/flat_map.rs
new file mode 100644
index 0000000..468f0a9
--- /dev/null
+++ b/src/util/flat_map.rs
@@ -0,0 +1,254 @@
+#![allow(dead_code)]
+
+use std::borrow::Borrow;
+
+/// Flat (Vec) backed map
+///
+/// This preserves insertion order
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct FlatMap<K, V> {
+ keys: Vec<K>,
+ values: Vec<V>,
+}
+
+impl<K: PartialEq + Eq, V> FlatMap<K, V> {
+ pub(crate) fn new() -> Self {
+ Default::default()
+ }
+
+ pub(crate) fn insert(&mut self, key: K, mut value: V) -> Option<V> {
+ for (index, existing) in self.keys.iter().enumerate() {
+ if *existing == key {
+ std::mem::swap(&mut self.values[index], &mut value);
+ return Some(value);
+ }
+ }
+
+ self.insert_unchecked(key, value);
+ None
+ }
+
+ pub(crate) fn insert_unchecked(&mut self, key: K, value: V) {
+ self.keys.push(key);
+ self.values.push(value);
+ }
+
+ pub(crate) fn extend_unchecked(&mut self, iter: impl IntoIterator<Item = (K, V)>) {
+ for (key, value) in iter {
+ self.insert_unchecked(key, value);
+ }
+ }
+
+ pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
+ where
+ K: Borrow<Q>,
+ Q: Eq,
+ {
+ for existing in &self.keys {
+ if existing.borrow() == key {
+ return true;
+ }
+ }
+ false
+ }
+
+ pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
+ where
+ K: Borrow<Q>,
+ Q: std::hash::Hash + Eq,
+ {
+ self.remove_entry(key).map(|(_, v)| v)
+ }
+
+ pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
+ where
+ K: Borrow<Q>,
+ Q: std::hash::Hash + Eq,
+ {
+ let index = some!(self
+ .keys
+ .iter()
+ .enumerate()
+ .find_map(|(i, k)| (k.borrow() == key).then_some(i)));
+ let key = self.keys.remove(index);
+ let value = self.values.remove(index);
+ Some((key, value))
+ }
+
+ pub(crate) fn is_empty(&self) -> bool {
+ self.keys.is_empty()
+ }
+
+ pub fn entry(&mut self, key: K) -> Entry<K, V> {
+ for (index, existing) in self.keys.iter().enumerate() {
+ if *existing == key {
+ return Entry::Occupied(OccupiedEntry { v: self, index });
+ }
+ }
+ Entry::Vacant(VacantEntry { v: self, key })
+ }
+
+ pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
+ where
+ K: Borrow<Q>,
+ Q: Eq,
+ {
+ for (index, existing) in self.keys.iter().enumerate() {
+ if existing.borrow() == k {
+ return Some(&self.values[index]);
+ }
+ }
+ None
+ }
+
+ pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
+ where
+ K: Borrow<Q>,
+ Q: Eq,
+ {
+ for (index, existing) in self.keys.iter().enumerate() {
+ if existing.borrow() == k {
+ return Some(&mut self.values[index]);
+ }
+ }
+ None
+ }
+
+ pub fn keys(&self) -> std::slice::Iter<'_, K> {
+ self.keys.iter()
+ }
+
+ pub fn iter(&self) -> Iter<K, V> {
+ Iter {
+ keys: self.keys.iter(),
+ values: self.values.iter(),
+ }
+ }
+
+ pub fn iter_mut(&mut self) -> IterMut<K, V> {
+ IterMut {
+ keys: self.keys.iter_mut(),
+ values: self.values.iter_mut(),
+ }
+ }
+}
+
+impl<K: PartialEq + Eq, V> Default for FlatMap<K, V> {
+ fn default() -> Self {
+ Self {
+ keys: Default::default(),
+ values: Default::default(),
+ }
+ }
+}
+
+pub enum Entry<'a, K: 'a, V: 'a> {
+ Vacant(VacantEntry<'a, K, V>),
+ Occupied(OccupiedEntry<'a, K, V>),
+}
+
+impl<'a, K: 'a, V: 'a> Entry<'a, K, V> {
+ pub fn or_insert(self, default: V) -> &'a mut V {
+ match self {
+ Entry::Occupied(entry) => &mut entry.v.values[entry.index],
+ Entry::Vacant(entry) => {
+ entry.v.keys.push(entry.key);
+ entry.v.values.push(default);
+ entry.v.values.last_mut().unwrap()
+ }
+ }
+ }
+
+ pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
+ match self {
+ Entry::Occupied(entry) => &mut entry.v.values[entry.index],
+ Entry::Vacant(entry) => {
+ entry.v.keys.push(entry.key);
+ entry.v.values.push(default());
+ entry.v.values.last_mut().unwrap()
+ }
+ }
+ }
+}
+
+pub struct VacantEntry<'a, K: 'a, V: 'a> {
+ v: &'a mut FlatMap<K, V>,
+ key: K,
+}
+
+pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
+ v: &'a mut FlatMap<K, V>,
+ index: usize,
+}
+
+pub struct Iter<'a, K: 'a, V: 'a> {
+ keys: std::slice::Iter<'a, K>,
+ values: std::slice::Iter<'a, V>,
+}
+
+impl<'a, K, V> Iterator for Iter<'a, K, V> {
+ type Item = (&'a K, &'a V);
+
+ fn next(&mut self) -> Option<(&'a K, &'a V)> {
+ match self.keys.next() {
+ Some(k) => {
+ let v = self.values.next().unwrap();
+ Some((k, v))
+ }
+ None => None,
+ }
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.keys.size_hint()
+ }
+}
+
+impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> {
+ fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
+ match self.keys.next_back() {
+ Some(k) => {
+ let v = self.values.next_back().unwrap();
+ Some((k, v))
+ }
+ None => None,
+ }
+ }
+}
+
+impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {}
+
+pub struct IterMut<'a, K: 'a, V: 'a> {
+ keys: std::slice::IterMut<'a, K>,
+ values: std::slice::IterMut<'a, V>,
+}
+
+impl<'a, K, V> Iterator for IterMut<'a, K, V> {
+ type Item = (&'a K, &'a mut V);
+
+ fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
+ match self.keys.next() {
+ Some(k) => {
+ let v = self.values.next().unwrap();
+ Some((k, v))
+ }
+ None => None,
+ }
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.keys.size_hint()
+ }
+}
+
+impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
+ fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
+ match self.keys.next_back() {
+ Some(k) => {
+ let v = self.values.next_back().unwrap();
+ Some((k, v))
+ }
+ None => None,
+ }
+ }
+}
+
+impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {}
diff --git a/src/util/flat_set.rs b/src/util/flat_set.rs
new file mode 100644
index 0000000..3e0b23d
--- /dev/null
+++ b/src/util/flat_set.rs
@@ -0,0 +1,107 @@
+#![allow(dead_code)]
+
+use std::borrow::Borrow;
+
+/// Flat (Vec) backed set
+///
+/// This preserves insertion order
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct FlatSet<T> {
+ inner: Vec<T>,
+}
+
+impl<T: PartialEq + Eq> FlatSet<T> {
+ pub(crate) fn new() -> Self {
+ Default::default()
+ }
+
+ pub(crate) fn insert(&mut self, value: T) -> bool {
+ for existing in &self.inner {
+ if *existing == value {
+ return false;
+ }
+ }
+ self.inner.push(value);
+ true
+ }
+
+ pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
+ where
+ T: Borrow<Q>,
+ Q: Eq,
+ {
+ for existing in &self.inner {
+ if existing.borrow() == value {
+ return true;
+ }
+ }
+ false
+ }
+
+ pub fn retain<F>(&mut self, f: F)
+ where
+ F: FnMut(&T) -> bool,
+ {
+ self.inner.retain(f);
+ }
+
+ pub(crate) fn is_empty(&self) -> bool {
+ self.inner.is_empty()
+ }
+
+ pub(crate) fn iter(&self) -> std::slice::Iter<'_, T> {
+ self.inner.iter()
+ }
+
+ pub fn sort_by_key<K, F>(&mut self, f: F)
+ where
+ F: FnMut(&T) -> K,
+ K: Ord,
+ {
+ self.inner.sort_by_key(f);
+ }
+}
+
+impl<T: PartialEq + Eq> Default for FlatSet<T> {
+ fn default() -> Self {
+ Self {
+ inner: Default::default(),
+ }
+ }
+}
+
+impl<T: PartialEq + Eq> IntoIterator for FlatSet<T> {
+ type Item = T;
+ type IntoIter = std::vec::IntoIter<T>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.inner.into_iter()
+ }
+}
+
+impl<'s, T: PartialEq + Eq> IntoIterator for &'s FlatSet<T> {
+ type Item = &'s T;
+ type IntoIter = std::slice::Iter<'s, T>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.inner.iter()
+ }
+}
+
+impl<T: PartialEq + Eq> Extend<T> for FlatSet<T> {
+ fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
+ for value in iter {
+ self.insert(value);
+ }
+ }
+}
+
+impl<T: PartialEq + Eq> FromIterator<T> for FlatSet<T> {
+ fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
+ let mut set = Self::new();
+ for value in iter {
+ set.insert(value);
+ }
+ set
+ }
+}
diff --git a/src/util/graph.rs b/src/util/graph.rs
new file mode 100644
index 0000000..d646400
--- /dev/null
+++ b/src/util/graph.rs
@@ -0,0 +1,49 @@
+#[derive(Debug)]
+struct Child<T> {
+ id: T,
+ children: Vec<usize>,
+}
+
+impl<T> Child<T> {
+ fn new(id: T) -> Self {
+ Child {
+ id,
+ children: vec![],
+ }
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct ChildGraph<T>(Vec<Child<T>>);
+
+impl<T> ChildGraph<T>
+where
+ T: Sized + PartialEq + Clone,
+{
+ pub(crate) fn with_capacity(s: usize) -> Self {
+ ChildGraph(Vec::with_capacity(s))
+ }
+
+ pub(crate) fn insert(&mut self, req: T) -> usize {
+ self.0.iter().position(|e| e.id == req).unwrap_or_else(|| {
+ let idx = self.0.len();
+ self.0.push(Child::new(req));
+ idx
+ })
+ }
+
+ pub(crate) fn insert_child(&mut self, parent: usize, child: T) -> usize {
+ let c_idx = self.0.len();
+ self.0.push(Child::new(child));
+ self.0[parent].children.push(c_idx);
+ c_idx
+ }
+
+ pub(crate) fn iter(&self) -> impl Iterator<Item = &T> {
+ self.0.iter().map(|r| &r.id)
+ }
+
+ pub(crate) fn contains(&self, req: &T) -> bool {
+ self.0.iter().any(|r| r.id == *req)
+ }
+}
diff --git a/src/util/id.rs b/src/util/id.rs
new file mode 100644
index 0000000..710d2ea
--- /dev/null
+++ b/src/util/id.rs
@@ -0,0 +1,164 @@
+use crate::builder::Str;
+
+/// [`Arg`][crate::Arg] or [`ArgGroup`][crate::ArgGroup] identifier
+///
+/// This is used for accessing the value in [`ArgMatches`][crate::ArgMatches] or defining
+/// relationships between `Arg`s and `ArgGroup`s with functions like
+/// [`Arg::conflicts_with`][crate::Arg::conflicts_with].
+#[derive(Default, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
+pub struct Id(Str);
+
+impl Id {
+ pub(crate) const HELP: &'static str = "help";
+ pub(crate) const VERSION: &'static str = "version";
+ pub(crate) const EXTERNAL: &'static str = "";
+
+ pub(crate) fn from_static_ref(name: &'static str) -> Self {
+ Self(Str::from_static_ref(name))
+ }
+
+ /// Get the raw string of the `Id`
+ pub fn as_str(&self) -> &str {
+ self.0.as_str()
+ }
+
+ pub(crate) fn as_internal_str(&self) -> &Str {
+ &self.0
+ }
+}
+
+impl From<&'_ Id> for Id {
+ fn from(id: &'_ Id) -> Self {
+ id.clone()
+ }
+}
+
+impl From<Str> for Id {
+ fn from(name: Str) -> Self {
+ Self(name)
+ }
+}
+
+impl From<&'_ Str> for Id {
+ fn from(name: &'_ Str) -> Self {
+ Self(name.into())
+ }
+}
+
+#[cfg(feature = "string")]
+impl From<std::string::String> for Id {
+ fn from(name: std::string::String) -> Self {
+ Self(name.into())
+ }
+}
+
+#[cfg(feature = "string")]
+impl From<&'_ std::string::String> for Id {
+ fn from(name: &'_ std::string::String) -> Self {
+ Self(name.into())
+ }
+}
+
+impl From<&'static str> for Id {
+ fn from(name: &'static str) -> Self {
+ Self(name.into())
+ }
+}
+
+impl From<&'_ &'static str> for Id {
+ fn from(name: &'_ &'static str) -> Self {
+ Self(name.into())
+ }
+}
+
+impl From<Id> for Str {
+ fn from(name: Id) -> Self {
+ name.0
+ }
+}
+
+impl From<Id> for String {
+ fn from(name: Id) -> Self {
+ Str::from(name).into()
+ }
+}
+
+impl std::fmt::Display for Id {
+ #[inline]
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ std::fmt::Display::fmt(self.as_str(), f)
+ }
+}
+
+impl std::fmt::Debug for Id {
+ #[inline]
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ std::fmt::Debug::fmt(self.as_str(), f)
+ }
+}
+
+impl AsRef<str> for Id {
+ #[inline]
+ fn as_ref(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl std::borrow::Borrow<str> for Id {
+ #[inline]
+ fn borrow(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl PartialEq<str> for Id {
+ #[inline]
+ fn eq(&self, other: &str) -> bool {
+ PartialEq::eq(self.as_str(), other)
+ }
+}
+impl PartialEq<Id> for str {
+ #[inline]
+ fn eq(&self, other: &Id) -> bool {
+ PartialEq::eq(self, other.as_str())
+ }
+}
+
+impl PartialEq<&'_ str> for Id {
+ #[inline]
+ fn eq(&self, other: &&str) -> bool {
+ PartialEq::eq(self.as_str(), *other)
+ }
+}
+impl PartialEq<Id> for &'_ str {
+ #[inline]
+ fn eq(&self, other: &Id) -> bool {
+ PartialEq::eq(*self, other.as_str())
+ }
+}
+
+impl PartialEq<Str> for Id {
+ #[inline]
+ fn eq(&self, other: &Str) -> bool {
+ PartialEq::eq(self.as_str(), other.as_str())
+ }
+}
+impl PartialEq<Id> for Str {
+ #[inline]
+ fn eq(&self, other: &Id) -> bool {
+ PartialEq::eq(self.as_str(), other.as_str())
+ }
+}
+
+impl PartialEq<std::string::String> for Id {
+ #[inline]
+ fn eq(&self, other: &std::string::String) -> bool {
+ PartialEq::eq(self.as_str(), other.as_str())
+ }
+}
+impl PartialEq<Id> for std::string::String {
+ #[inline]
+ fn eq(&self, other: &Id) -> bool {
+ PartialEq::eq(other, self)
+ }
+}
diff --git a/src/util/mod.rs b/src/util/mod.rs
new file mode 100644
index 0000000..e6a8f70
--- /dev/null
+++ b/src/util/mod.rs
@@ -0,0 +1,44 @@
+#![allow(clippy::single_component_path_imports)]
+
+pub(crate) mod flat_map;
+pub(crate) mod flat_set;
+mod graph;
+mod id;
+mod str_to_bool;
+
+pub use self::id::Id;
+
+pub(crate) use self::flat_map::Entry;
+pub(crate) use self::flat_map::FlatMap;
+pub(crate) use self::flat_set::FlatSet;
+pub(crate) use self::graph::ChildGraph;
+pub(crate) use self::str_to_bool::str_to_bool;
+pub(crate) use self::str_to_bool::FALSE_LITERALS;
+pub(crate) use self::str_to_bool::TRUE_LITERALS;
+
+pub(crate) mod color;
+
+pub(crate) const SUCCESS_CODE: i32 = 0;
+// While sysexists.h defines EX_USAGE as 64, this doesn't seem to be used much in practice but
+// instead 2 seems to be frequently used.
+// Examples
+// - GNU `ls` returns 2
+// - Python's `argparse` returns 2
+pub(crate) const USAGE_CODE: i32 = 2;
+
+pub(crate) fn safe_exit(code: i32) -> ! {
+ use std::io::Write;
+
+ let _ = std::io::stdout().lock().flush();
+ let _ = std::io::stderr().lock().flush();
+
+ std::process::exit(code)
+}
+
+#[cfg(not(feature = "unicode"))]
+pub(crate) fn eq_ignore_case(left: &str, right: &str) -> bool {
+ left.eq_ignore_ascii_case(right)
+}
+
+#[cfg(feature = "unicode")]
+pub(crate) use unicase::eq as eq_ignore_case;
diff --git a/src/util/str_to_bool.rs b/src/util/str_to_bool.rs
new file mode 100644
index 0000000..1fbdc75
--- /dev/null
+++ b/src/util/str_to_bool.rs
@@ -0,0 +1,21 @@
+/// True values are `y`, `yes`, `t`, `true`, `on`, and `1`.
+pub(crate) const TRUE_LITERALS: [&str; 6] = ["y", "yes", "t", "true", "on", "1"];
+
+/// False values are `n`, `no`, `f`, `false`, `off`, and `0`.
+pub(crate) const FALSE_LITERALS: [&str; 6] = ["n", "no", "f", "false", "off", "0"];
+
+/// Converts a string literal representation of truth to true or false.
+///
+/// `false` values are `n`, `no`, `f`, `false`, `off`, and `0` (case insensitive).
+///
+/// Any other value will be considered as `true`.
+pub(crate) fn str_to_bool(val: impl AsRef<str>) -> Option<bool> {
+ let pat: &str = &val.as_ref().to_lowercase();
+ if TRUE_LITERALS.contains(&pat) {
+ Some(true)
+ } else if FALSE_LITERALS.contains(&pat) {
+ Some(false)
+ } else {
+ None
+ }
+}