From 64d98f8ee037282c35007b64c2649055c56af1db Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 17 Apr 2024 14:19:03 +0200 Subject: Merging upstream version 1.68.2+dfsg1. Signed-off-by: Daniel Baumann --- vendor/clap/.cargo-checksum.json | 1 + vendor/clap/Cargo.lock | 855 ++++ vendor/clap/Cargo.toml | 485 ++ vendor/clap/LICENSE-APACHE | 201 + vendor/clap/LICENSE-MIT | 21 + vendor/clap/README.md | 43 + vendor/clap/examples/README.md | 16 + vendor/clap/examples/cargo-example-derive.md | 38 + vendor/clap/examples/cargo-example-derive.rs | 20 + vendor/clap/examples/cargo-example.md | 38 + vendor/clap/examples/cargo-example.rs | 18 + vendor/clap/examples/demo.md | 17 + vendor/clap/examples/demo.rs | 22 + vendor/clap/examples/derive_ref/augment_args.rs | 27 + .../examples/derive_ref/augment_subcommands.rs | 21 + .../clap/examples/derive_ref/flatten_hand_args.rs | 91 + vendor/clap/examples/derive_ref/hand_subcommand.rs | 79 + vendor/clap/examples/derive_ref/interop_tests.md | 248 ++ vendor/clap/examples/escaped-positional-derive.md | 60 + vendor/clap/examples/escaped-positional-derive.rs | 25 + vendor/clap/examples/escaped-positional.md | 60 + vendor/clap/examples/escaped-positional.rs | 32 + vendor/clap/examples/find.md | 45 + vendor/clap/examples/find.rs | 99 + vendor/clap/examples/git-derive.md | 159 + vendor/clap/examples/git-derive.rs | 164 + vendor/clap/examples/git.md | 157 + vendor/clap/examples/git.rs | 137 + vendor/clap/examples/multicall-busybox.md | 39 + vendor/clap/examples/multicall-busybox.rs | 47 + vendor/clap/examples/multicall-hostname.md | 10 + vendor/clap/examples/multicall-hostname.rs | 17 + vendor/clap/examples/pacman.md | 79 + vendor/clap/examples/pacman.rs | 111 + vendor/clap/examples/repl.rs | 92 + vendor/clap/examples/tutorial_builder/01_quick.md | 35 + vendor/clap/examples/tutorial_builder/01_quick.rs | 60 + .../examples/tutorial_builder/02_app_settings.md | 17 + .../examples/tutorial_builder/02_app_settings.rs | 18 + vendor/clap/examples/tutorial_builder/02_apps.md | 16 + vendor/clap/examples/tutorial_builder/02_apps.rs | 20 + vendor/clap/examples/tutorial_builder/02_crate.md | 16 + vendor/clap/examples/tutorial_builder/02_crate.rs | 18 + .../examples/tutorial_builder/03_01_flag_bool.md | 26 + .../examples/tutorial_builder/03_01_flag_bool.rs | 14 + .../examples/tutorial_builder/03_01_flag_count.md | 21 + .../examples/tutorial_builder/03_01_flag_count.rs | 14 + .../clap/examples/tutorial_builder/03_02_option.md | 30 + .../clap/examples/tutorial_builder/03_02_option.rs | 9 + .../examples/tutorial_builder/03_02_option_mult.md | 30 + .../examples/tutorial_builder/03_02_option_mult.rs | 14 + .../examples/tutorial_builder/03_03_positional.md | 20 + .../examples/tutorial_builder/03_03_positional.rs | 9 + .../tutorial_builder/03_03_positional_mult.md | 23 + .../tutorial_builder/03_03_positional_mult.rs | 15 + .../examples/tutorial_builder/03_04_subcommands.md | 58 + .../examples/tutorial_builder/03_04_subcommands.rs | 22 + .../tutorial_builder/03_05_default_values.md | 20 + .../tutorial_builder/03_05_default_values.rs | 18 + .../clap/examples/tutorial_builder/04_01_enum.md | 47 + .../clap/examples/tutorial_builder/04_01_enum.rs | 66 + .../examples/tutorial_builder/04_01_possible.md | 27 + .../examples/tutorial_builder/04_01_possible.rs | 26 + .../clap/examples/tutorial_builder/04_02_parse.md | 29 + .../clap/examples/tutorial_builder/04_02_parse.rs | 17 + .../examples/tutorial_builder/04_02_validate.md | 29 + .../examples/tutorial_builder/04_02_validate.rs | 36 + .../examples/tutorial_builder/04_03_relations.md | 53 + .../examples/tutorial_builder/04_03_relations.rs | 78 + .../clap/examples/tutorial_builder/04_04_custom.md | 52 + .../clap/examples/tutorial_builder/04_04_custom.rs | 84 + .../clap/examples/tutorial_builder/05_01_assert.rs | 25 + vendor/clap/examples/tutorial_derive/01_quick.md | 35 + vendor/clap/examples/tutorial_derive/01_quick.rs | 68 + .../examples/tutorial_derive/02_app_settings.md | 17 + .../examples/tutorial_derive/02_app_settings.rs | 18 + vendor/clap/examples/tutorial_derive/02_apps.md | 16 + vendor/clap/examples/tutorial_derive/02_apps.rs | 20 + vendor/clap/examples/tutorial_derive/02_crate.md | 16 + vendor/clap/examples/tutorial_derive/02_crate.rs | 17 + .../examples/tutorial_derive/03_01_flag_bool.md | 26 + .../examples/tutorial_derive/03_01_flag_bool.rs | 14 + .../examples/tutorial_derive/03_01_flag_count.md | 21 + .../examples/tutorial_derive/03_01_flag_count.rs | 14 + .../clap/examples/tutorial_derive/03_02_option.md | 30 + .../clap/examples/tutorial_derive/03_02_option.rs | 14 + .../examples/tutorial_derive/03_02_option_mult.md | 30 + .../examples/tutorial_derive/03_02_option_mult.rs | 14 + .../examples/tutorial_derive/03_03_positional.md | 20 + .../examples/tutorial_derive/03_03_positional.rs | 13 + .../tutorial_derive/03_03_positional_mult.md | 23 + .../tutorial_derive/03_03_positional_mult.rs | 13 + .../examples/tutorial_derive/03_04_subcommands.md | 58 + .../examples/tutorial_derive/03_04_subcommands.rs | 27 + .../tutorial_derive/03_04_subcommands_alt.rs | 32 + .../tutorial_derive/03_05_default_values.md | 20 + .../tutorial_derive/03_05_default_values.rs | 14 + vendor/clap/examples/tutorial_derive/04_01_enum.md | 47 + vendor/clap/examples/tutorial_derive/04_01_enum.rs | 32 + .../clap/examples/tutorial_derive/04_02_parse.md | 29 + .../clap/examples/tutorial_derive/04_02_parse.rs | 15 + .../examples/tutorial_derive/04_02_validate.md | 29 + .../examples/tutorial_derive/04_02_validate.rs | 34 + .../examples/tutorial_derive/04_03_relations.md | 53 + .../examples/tutorial_derive/04_03_relations.rs | 72 + .../clap/examples/tutorial_derive/04_04_custom.md | 52 + .../clap/examples/tutorial_derive/04_04_custom.rs | 91 + .../clap/examples/tutorial_derive/05_01_assert.rs | 20 + vendor/clap/examples/typed-derive.md | 131 + vendor/clap/examples/typed-derive.rs | 102 + vendor/clap/src/_cookbook/cargo_example.rs | 7 + vendor/clap/src/_cookbook/cargo_example_derive.rs | 7 + vendor/clap/src/_cookbook/escaped_positional.rs | 7 + .../src/_cookbook/escaped_positional_derive.rs | 7 + vendor/clap/src/_cookbook/find.rs | 7 + vendor/clap/src/_cookbook/git.rs | 7 + vendor/clap/src/_cookbook/git_derive.rs | 7 + vendor/clap/src/_cookbook/mod.rs | 61 + vendor/clap/src/_cookbook/multicall_busybox.rs | 7 + vendor/clap/src/_cookbook/multicall_hostname.rs | 7 + vendor/clap/src/_cookbook/pacman.rs | 7 + vendor/clap/src/_cookbook/repl.rs | 5 + vendor/clap/src/_cookbook/typed_derive.rs | 7 + vendor/clap/src/_derive/_tutorial.rs | 226 + vendor/clap/src/_derive/mod.rs | 480 ++ vendor/clap/src/_faq.rs | 95 + vendor/clap/src/_features.rs | 29 + vendor/clap/src/_tutorial.rs | 222 + vendor/clap/src/bin/stdio-fixture.rs | 15 + vendor/clap/src/builder/action.rs | 344 ++ vendor/clap/src/builder/app_settings.rs | 172 + vendor/clap/src/builder/arg.rs | 4647 +++++++++++++++++++ vendor/clap/src/builder/arg_group.rs | 596 +++ vendor/clap/src/builder/arg_predicate.rs | 19 + vendor/clap/src/builder/arg_settings.rs | 145 + vendor/clap/src/builder/command.rs | 4703 ++++++++++++++++++++ vendor/clap/src/builder/debug_asserts.rs | 887 ++++ vendor/clap/src/builder/mod.rs | 60 + vendor/clap/src/builder/os_str.rs | 336 ++ vendor/clap/src/builder/possible_value.rs | 234 + vendor/clap/src/builder/range.rs | 283 ++ vendor/clap/src/builder/resettable.rs | 211 + vendor/clap/src/builder/str.rs | 307 ++ vendor/clap/src/builder/styled_str.rs | 349 ++ vendor/clap/src/builder/tests.rs | 56 + vendor/clap/src/builder/value_hint.rs | 95 + vendor/clap/src/builder/value_parser.rs | 2435 ++++++++++ vendor/clap/src/derive.rs | 471 ++ vendor/clap/src/error/context.rs | 114 + vendor/clap/src/error/format.rs | 468 ++ vendor/clap/src/error/kind.rs | 348 ++ vendor/clap/src/error/mod.rs | 876 ++++ vendor/clap/src/lib.rs | 154 + vendor/clap/src/macros.rs | 676 +++ vendor/clap/src/mkeymap.rs | 177 + vendor/clap/src/output/fmt.rs | 90 + vendor/clap/src/output/help.rs | 43 + vendor/clap/src/output/help_template.rs | 1065 +++++ vendor/clap/src/output/mod.rs | 23 + vendor/clap/src/output/textwrap/core.rs | 158 + vendor/clap/src/output/textwrap/mod.rs | 122 + vendor/clap/src/output/textwrap/word_separators.rs | 91 + vendor/clap/src/output/textwrap/wrap_algorithms.rs | 44 + vendor/clap/src/output/usage.rs | 441 ++ vendor/clap/src/parser/arg_matcher.rs | 248 ++ vendor/clap/src/parser/error.rs | 65 + vendor/clap/src/parser/features/mod.rs | 1 + vendor/clap/src/parser/features/suggestions.rs | 167 + vendor/clap/src/parser/matches/any_value.rs | 112 + vendor/clap/src/parser/matches/arg_matches.rs | 1968 ++++++++ vendor/clap/src/parser/matches/matched_arg.rs | 225 + vendor/clap/src/parser/matches/mod.rs | 16 + vendor/clap/src/parser/matches/value_source.rs | 17 + vendor/clap/src/parser/mod.rs | 27 + vendor/clap/src/parser/parser.rs | 1643 +++++++ vendor/clap/src/parser/validator.rs | 565 +++ vendor/clap/src/util/color.rs | 103 + vendor/clap/src/util/flat_map.rs | 254 ++ vendor/clap/src/util/flat_set.rs | 107 + vendor/clap/src/util/graph.rs | 49 + vendor/clap/src/util/id.rs | 164 + vendor/clap/src/util/mod.rs | 44 + vendor/clap/src/util/str_to_bool.rs | 21 + 183 files changed, 34229 insertions(+) create mode 100644 vendor/clap/.cargo-checksum.json create mode 100644 vendor/clap/Cargo.lock create mode 100644 vendor/clap/Cargo.toml create mode 100644 vendor/clap/LICENSE-APACHE create mode 100644 vendor/clap/LICENSE-MIT create mode 100644 vendor/clap/README.md create mode 100644 vendor/clap/examples/README.md create mode 100644 vendor/clap/examples/cargo-example-derive.md create mode 100644 vendor/clap/examples/cargo-example-derive.rs create mode 100644 vendor/clap/examples/cargo-example.md create mode 100644 vendor/clap/examples/cargo-example.rs create mode 100644 vendor/clap/examples/demo.md create mode 100644 vendor/clap/examples/demo.rs create mode 100644 vendor/clap/examples/derive_ref/augment_args.rs create mode 100644 vendor/clap/examples/derive_ref/augment_subcommands.rs create mode 100644 vendor/clap/examples/derive_ref/flatten_hand_args.rs create mode 100644 vendor/clap/examples/derive_ref/hand_subcommand.rs create mode 100644 vendor/clap/examples/derive_ref/interop_tests.md create mode 100644 vendor/clap/examples/escaped-positional-derive.md create mode 100644 vendor/clap/examples/escaped-positional-derive.rs create mode 100644 vendor/clap/examples/escaped-positional.md create mode 100644 vendor/clap/examples/escaped-positional.rs create mode 100644 vendor/clap/examples/find.md create mode 100644 vendor/clap/examples/find.rs create mode 100644 vendor/clap/examples/git-derive.md create mode 100644 vendor/clap/examples/git-derive.rs create mode 100644 vendor/clap/examples/git.md create mode 100644 vendor/clap/examples/git.rs create mode 100644 vendor/clap/examples/multicall-busybox.md create mode 100644 vendor/clap/examples/multicall-busybox.rs create mode 100644 vendor/clap/examples/multicall-hostname.md create mode 100644 vendor/clap/examples/multicall-hostname.rs create mode 100644 vendor/clap/examples/pacman.md create mode 100644 vendor/clap/examples/pacman.rs create mode 100644 vendor/clap/examples/repl.rs create mode 100644 vendor/clap/examples/tutorial_builder/01_quick.md create mode 100644 vendor/clap/examples/tutorial_builder/01_quick.rs create mode 100644 vendor/clap/examples/tutorial_builder/02_app_settings.md create mode 100644 vendor/clap/examples/tutorial_builder/02_app_settings.rs create mode 100644 vendor/clap/examples/tutorial_builder/02_apps.md create mode 100644 vendor/clap/examples/tutorial_builder/02_apps.rs create mode 100644 vendor/clap/examples/tutorial_builder/02_crate.md create mode 100644 vendor/clap/examples/tutorial_builder/02_crate.rs create mode 100644 vendor/clap/examples/tutorial_builder/03_01_flag_bool.md create mode 100644 vendor/clap/examples/tutorial_builder/03_01_flag_bool.rs create mode 100644 vendor/clap/examples/tutorial_builder/03_01_flag_count.md create mode 100644 vendor/clap/examples/tutorial_builder/03_01_flag_count.rs create mode 100644 vendor/clap/examples/tutorial_builder/03_02_option.md create mode 100644 vendor/clap/examples/tutorial_builder/03_02_option.rs create mode 100644 vendor/clap/examples/tutorial_builder/03_02_option_mult.md create mode 100644 vendor/clap/examples/tutorial_builder/03_02_option_mult.rs create mode 100644 vendor/clap/examples/tutorial_builder/03_03_positional.md create mode 100644 vendor/clap/examples/tutorial_builder/03_03_positional.rs create mode 100644 vendor/clap/examples/tutorial_builder/03_03_positional_mult.md create mode 100644 vendor/clap/examples/tutorial_builder/03_03_positional_mult.rs create mode 100644 vendor/clap/examples/tutorial_builder/03_04_subcommands.md create mode 100644 vendor/clap/examples/tutorial_builder/03_04_subcommands.rs create mode 100644 vendor/clap/examples/tutorial_builder/03_05_default_values.md create mode 100644 vendor/clap/examples/tutorial_builder/03_05_default_values.rs create mode 100644 vendor/clap/examples/tutorial_builder/04_01_enum.md create mode 100644 vendor/clap/examples/tutorial_builder/04_01_enum.rs create mode 100644 vendor/clap/examples/tutorial_builder/04_01_possible.md create mode 100644 vendor/clap/examples/tutorial_builder/04_01_possible.rs create mode 100644 vendor/clap/examples/tutorial_builder/04_02_parse.md create mode 100644 vendor/clap/examples/tutorial_builder/04_02_parse.rs create mode 100644 vendor/clap/examples/tutorial_builder/04_02_validate.md create mode 100644 vendor/clap/examples/tutorial_builder/04_02_validate.rs create mode 100644 vendor/clap/examples/tutorial_builder/04_03_relations.md create mode 100644 vendor/clap/examples/tutorial_builder/04_03_relations.rs create mode 100644 vendor/clap/examples/tutorial_builder/04_04_custom.md create mode 100644 vendor/clap/examples/tutorial_builder/04_04_custom.rs create mode 100644 vendor/clap/examples/tutorial_builder/05_01_assert.rs create mode 100644 vendor/clap/examples/tutorial_derive/01_quick.md create mode 100644 vendor/clap/examples/tutorial_derive/01_quick.rs create mode 100644 vendor/clap/examples/tutorial_derive/02_app_settings.md create mode 100644 vendor/clap/examples/tutorial_derive/02_app_settings.rs create mode 100644 vendor/clap/examples/tutorial_derive/02_apps.md create mode 100644 vendor/clap/examples/tutorial_derive/02_apps.rs create mode 100644 vendor/clap/examples/tutorial_derive/02_crate.md create mode 100644 vendor/clap/examples/tutorial_derive/02_crate.rs create mode 100644 vendor/clap/examples/tutorial_derive/03_01_flag_bool.md create mode 100644 vendor/clap/examples/tutorial_derive/03_01_flag_bool.rs create mode 100644 vendor/clap/examples/tutorial_derive/03_01_flag_count.md create mode 100644 vendor/clap/examples/tutorial_derive/03_01_flag_count.rs create mode 100644 vendor/clap/examples/tutorial_derive/03_02_option.md create mode 100644 vendor/clap/examples/tutorial_derive/03_02_option.rs create mode 100644 vendor/clap/examples/tutorial_derive/03_02_option_mult.md create mode 100644 vendor/clap/examples/tutorial_derive/03_02_option_mult.rs create mode 100644 vendor/clap/examples/tutorial_derive/03_03_positional.md create mode 100644 vendor/clap/examples/tutorial_derive/03_03_positional.rs create mode 100644 vendor/clap/examples/tutorial_derive/03_03_positional_mult.md create mode 100644 vendor/clap/examples/tutorial_derive/03_03_positional_mult.rs create mode 100644 vendor/clap/examples/tutorial_derive/03_04_subcommands.md create mode 100644 vendor/clap/examples/tutorial_derive/03_04_subcommands.rs create mode 100644 vendor/clap/examples/tutorial_derive/03_04_subcommands_alt.rs create mode 100644 vendor/clap/examples/tutorial_derive/03_05_default_values.md create mode 100644 vendor/clap/examples/tutorial_derive/03_05_default_values.rs create mode 100644 vendor/clap/examples/tutorial_derive/04_01_enum.md create mode 100644 vendor/clap/examples/tutorial_derive/04_01_enum.rs create mode 100644 vendor/clap/examples/tutorial_derive/04_02_parse.md create mode 100644 vendor/clap/examples/tutorial_derive/04_02_parse.rs create mode 100644 vendor/clap/examples/tutorial_derive/04_02_validate.md create mode 100644 vendor/clap/examples/tutorial_derive/04_02_validate.rs create mode 100644 vendor/clap/examples/tutorial_derive/04_03_relations.md create mode 100644 vendor/clap/examples/tutorial_derive/04_03_relations.rs create mode 100644 vendor/clap/examples/tutorial_derive/04_04_custom.md create mode 100644 vendor/clap/examples/tutorial_derive/04_04_custom.rs create mode 100644 vendor/clap/examples/tutorial_derive/05_01_assert.rs create mode 100644 vendor/clap/examples/typed-derive.md create mode 100644 vendor/clap/examples/typed-derive.rs create mode 100644 vendor/clap/src/_cookbook/cargo_example.rs create mode 100644 vendor/clap/src/_cookbook/cargo_example_derive.rs create mode 100644 vendor/clap/src/_cookbook/escaped_positional.rs create mode 100644 vendor/clap/src/_cookbook/escaped_positional_derive.rs create mode 100644 vendor/clap/src/_cookbook/find.rs create mode 100644 vendor/clap/src/_cookbook/git.rs create mode 100644 vendor/clap/src/_cookbook/git_derive.rs create mode 100644 vendor/clap/src/_cookbook/mod.rs create mode 100644 vendor/clap/src/_cookbook/multicall_busybox.rs create mode 100644 vendor/clap/src/_cookbook/multicall_hostname.rs create mode 100644 vendor/clap/src/_cookbook/pacman.rs create mode 100644 vendor/clap/src/_cookbook/repl.rs create mode 100644 vendor/clap/src/_cookbook/typed_derive.rs create mode 100644 vendor/clap/src/_derive/_tutorial.rs create mode 100644 vendor/clap/src/_derive/mod.rs create mode 100644 vendor/clap/src/_faq.rs create mode 100644 vendor/clap/src/_features.rs create mode 100644 vendor/clap/src/_tutorial.rs create mode 100644 vendor/clap/src/bin/stdio-fixture.rs create mode 100644 vendor/clap/src/builder/action.rs create mode 100644 vendor/clap/src/builder/app_settings.rs create mode 100644 vendor/clap/src/builder/arg.rs create mode 100644 vendor/clap/src/builder/arg_group.rs create mode 100644 vendor/clap/src/builder/arg_predicate.rs create mode 100644 vendor/clap/src/builder/arg_settings.rs create mode 100644 vendor/clap/src/builder/command.rs create mode 100644 vendor/clap/src/builder/debug_asserts.rs create mode 100644 vendor/clap/src/builder/mod.rs create mode 100644 vendor/clap/src/builder/os_str.rs create mode 100644 vendor/clap/src/builder/possible_value.rs create mode 100644 vendor/clap/src/builder/range.rs create mode 100644 vendor/clap/src/builder/resettable.rs create mode 100644 vendor/clap/src/builder/str.rs create mode 100644 vendor/clap/src/builder/styled_str.rs create mode 100644 vendor/clap/src/builder/tests.rs create mode 100644 vendor/clap/src/builder/value_hint.rs create mode 100644 vendor/clap/src/builder/value_parser.rs create mode 100644 vendor/clap/src/derive.rs create mode 100644 vendor/clap/src/error/context.rs create mode 100644 vendor/clap/src/error/format.rs create mode 100644 vendor/clap/src/error/kind.rs create mode 100644 vendor/clap/src/error/mod.rs create mode 100644 vendor/clap/src/lib.rs create mode 100644 vendor/clap/src/macros.rs create mode 100644 vendor/clap/src/mkeymap.rs create mode 100644 vendor/clap/src/output/fmt.rs create mode 100644 vendor/clap/src/output/help.rs create mode 100644 vendor/clap/src/output/help_template.rs create mode 100644 vendor/clap/src/output/mod.rs create mode 100644 vendor/clap/src/output/textwrap/core.rs create mode 100644 vendor/clap/src/output/textwrap/mod.rs create mode 100644 vendor/clap/src/output/textwrap/word_separators.rs create mode 100644 vendor/clap/src/output/textwrap/wrap_algorithms.rs create mode 100644 vendor/clap/src/output/usage.rs create mode 100644 vendor/clap/src/parser/arg_matcher.rs create mode 100644 vendor/clap/src/parser/error.rs create mode 100644 vendor/clap/src/parser/features/mod.rs create mode 100644 vendor/clap/src/parser/features/suggestions.rs create mode 100644 vendor/clap/src/parser/matches/any_value.rs create mode 100644 vendor/clap/src/parser/matches/arg_matches.rs create mode 100644 vendor/clap/src/parser/matches/matched_arg.rs create mode 100644 vendor/clap/src/parser/matches/mod.rs create mode 100644 vendor/clap/src/parser/matches/value_source.rs create mode 100644 vendor/clap/src/parser/mod.rs create mode 100644 vendor/clap/src/parser/parser.rs create mode 100644 vendor/clap/src/parser/validator.rs create mode 100644 vendor/clap/src/util/color.rs create mode 100644 vendor/clap/src/util/flat_map.rs create mode 100644 vendor/clap/src/util/flat_set.rs create mode 100644 vendor/clap/src/util/graph.rs create mode 100644 vendor/clap/src/util/id.rs create mode 100644 vendor/clap/src/util/mod.rs create mode 100644 vendor/clap/src/util/str_to_bool.rs (limited to 'vendor/clap') diff --git a/vendor/clap/.cargo-checksum.json b/vendor/clap/.cargo-checksum.json new file mode 100644 index 000000000..33af0d9b8 --- /dev/null +++ b/vendor/clap/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"1d79751fc0b97cd3192dcac94537016d7d1617f7f37fad6142911719efdc422e","Cargo.toml":"fac13ee176f38edefd6c5e53ad1b2224cd4e17ed21f836e7ea63756a35657239","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"0d687e1f07b58fe68bda74668ff6326125e5e5efa184cce755cd84ac535b7058","README.md":"bcb96a3aedd4da85e24e201a4922e435928b0c0a2f97fd5843d0793a54e6a09f","examples/README.md":"c5f45032ee7acda0c5f98db456cbf4f9b0362d62dc81218fcf03bcdfbd19af05","examples/cargo-example-derive.md":"66d7455f08a038872f42d9d45f9b47ebbdbf9366fafa16b749ece8ba5bdcfcce","examples/cargo-example-derive.rs":"82055cd4f6f54ea7f6fee3b73ac3fca32092aed0d7dde4d3a83f47682518fc3a","examples/cargo-example.md":"60a1d0f253142de5003a9474b28a5a8324a9860fc646af6309d84594d97356bd","examples/cargo-example.rs":"34bf69f18327e443b1c5fe49ff13de27004b2094e2385346708c3ac2595f9095","examples/demo.md":"6c00568794ff99007ab0f08bf7e06fe521cb1f2f0fab30c219f16c6f54bf638d","examples/demo.rs":"08cdd247b47a5202de9b7df7c1f3e7e30da975e56256d930d9db0f6c36741933","examples/derive_ref/augment_args.rs":"9f713581ab1cc3d85b383cdb7e50d92367a5e3f496dcb4e17d6589648acc68c7","examples/derive_ref/augment_subcommands.rs":"3ef37b369472bf4eb14bd4dfedb27f4fe855a4cd1b26013db876cf478fea5f8b","examples/derive_ref/flatten_hand_args.rs":"7afc2e13c386901e8028469ed53e85ee936f5641c37bcedb4f8ce0708fb8f01b","examples/derive_ref/hand_subcommand.rs":"776f7b1775f53f44f5f7de1eca5fedcc5846e8cac78c3f5b3ce2cca1390c2ca4","examples/derive_ref/interop_tests.md":"a7aa095c7c51b444361e57ebd1a48595a9bf4c301a4402e349c1be2490b5183d","examples/escaped-positional-derive.md":"fb4b4351ceb43ef0c25048e8603dab6fdf4391b84e9b3ad9593602fa89abc572","examples/escaped-positional-derive.rs":"4fe5f9dfbd15d3efcff7ff9b214d00c189ac0592e30b297b154df789e49dbfa3","examples/escaped-positional.md":"b44e23e5706eb815e7875825be815a370f2ba38e41d7998ea762d0ef1fb2ba56","examples/escaped-positional.rs":"e1e784bb90805ef3412f002d9660c979ebbd2d59eb609ceb7f8926c0ad8e7c31","examples/find.md":"acb72e150f9feeb5d7828163f0e36ff5004ae667f6ddbb06d2838a75037177ee","examples/find.rs":"8a1e91ab5b23777df0d45ab66241be802de75876eedeeeefddef4b04ff6689e5","examples/git-derive.md":"2d7adcd662446fa13e3c156c33371abb7129eb8d177bed3367d54e755f5b6cca","examples/git-derive.rs":"6496e26e580ee2bd9015d61101c7bb4a3f36c83a1402cedc6c453bc9e72f7341","examples/git.md":"449a75c1e0c7b2dd948b856c81a868f6b8f0c300667b17ec5dd638c6739d2175","examples/git.rs":"8ca385a5275a8d5b6fae3fed184c779ac50129b0394a7f534678b0301f66ba03","examples/multicall-busybox.md":"b8e8a89312e2088b6dd1fac5b5b92266fda9b82c40a650dae2d41b5fcc253594","examples/multicall-busybox.rs":"0be842810003f69de33c9e65258f74a5d1ec742fb0ebc8a49fdebfecc861c408","examples/multicall-hostname.md":"1dedcdcc9927c08cebee11fa01fda7a730f5ddf5227c4902e1eb5ff847a80346","examples/multicall-hostname.rs":"cc58a924dd2e57281f36e30481a1cbc8186952adbf149f9e1e13f9c673614fd9","examples/pacman.md":"a050be1727605a4202faf69db7f991bf974bba51ce0fbd41413de68e6a4af5aa","examples/pacman.rs":"5a7c0b332b456da29e41b6a6a5cd22034382940c2f604465e0d1a49d806cd889","examples/repl.rs":"3a63163a97d58eb27e4abc2f7d945abd659739d732c6a31bbbcb1c55e740eb6b","examples/tutorial_builder/01_quick.md":"d2a242a6ba832cdb0a2b6f55d428d62e7048f6b7d8d8f4a75f7923da85628ca8","examples/tutorial_builder/01_quick.rs":"bd45a5eca1927bcc35b3c946a9aa19dd37d17358c21eec48178a6f77d93d5200","examples/tutorial_builder/02_app_settings.md":"4e7097deb0eb8e926978ef383b0da4bda33966d4e760ac0d258cd4127a054fba","examples/tutorial_builder/02_app_settings.rs":"c050d19fa8c0ecefde73746200fb513da0dd78d904011a1c0a75835fd9c172b3","examples/tutorial_builder/02_apps.md":"3cbc7010e0214d047d98104dadb76ee02ec3c5bba868758e35aebb2fdfd0fa22","examples/tutorial_builder/02_apps.rs":"e654126b44161d5b20ce2e576a6022f027060d003e07ae74c7bbdeddd6fcb880","examples/tutorial_builder/02_crate.md":"995dc62680b9d7c1983c673bf5775c07ae96175db186b5313c0d614308569ec0","examples/tutorial_builder/02_crate.rs":"b0bdc601133bf9e566231dd6be439d0ce82b6911ca53ae4b5c1b5da62eb2acd8","examples/tutorial_builder/03_01_flag_bool.md":"326d8267ce6fcc62e95fdb19f77bdc959067e41af48c7d6e465c0eafe2db741c","examples/tutorial_builder/03_01_flag_bool.rs":"d49b30b527faa6a383b334e572d546fab5c4b298a5549842073ab42a33a05c94","examples/tutorial_builder/03_01_flag_count.md":"c34ff091d239f5861a868bda051322774340be9a63dea32cbfabe8c0cc4dfd94","examples/tutorial_builder/03_01_flag_count.rs":"a003825bc045d4d89265344cfb00082da379150e72fc5d16b33ee93ec9ec0927","examples/tutorial_builder/03_02_option.md":"f436d35a7f2aece1a30f0258f44ae09166fb4faae3b6623beb6a824d2ed234fd","examples/tutorial_builder/03_02_option.rs":"13e58e3f922ef79bb4f3cec63f84dc906bb20ea8bbd33e5ca3cb8cfce847095a","examples/tutorial_builder/03_02_option_mult.md":"c83e0f52f97f38154be30ac34d7d60b9271fd8a0dcab629929ee785d3baa07a2","examples/tutorial_builder/03_02_option_mult.rs":"bd3e522d6ff4a1a9f5849924650acf8ea8afc1f4c3ba633e45926a479f54b7c7","examples/tutorial_builder/03_03_positional.md":"dc2e13cf897e2e2d2b397a1ab739bfd290ec04f437128030eb7f6f609b910be7","examples/tutorial_builder/03_03_positional.rs":"582ffa5b056363a74d2ba966d212fbd6b00f42fe42f0e71ae95009fe75746349","examples/tutorial_builder/03_03_positional_mult.md":"f1d03ca58d9ee75ec9a4cc980006a666e2c529ab6f7deaf6bd88b3fbaf09fc07","examples/tutorial_builder/03_03_positional_mult.rs":"271a9ee04038244fdf378c6a603af9d4cb6a401d82f9e28928c2e7ad971aff10","examples/tutorial_builder/03_04_subcommands.md":"51f725938c4e0a7970185d8fe40c903d477e7c62c2e430c1316a442a8b8a237a","examples/tutorial_builder/03_04_subcommands.rs":"a309a332004edbed6dc14b64b1ba6cc0cd42871f3c5b8da7daab772764839c68","examples/tutorial_builder/03_05_default_values.md":"c30c72c85190aaddc06a7c0ed1cf87356eb81f03284b0e9c5f47d4f233d06a00","examples/tutorial_builder/03_05_default_values.rs":"96c8bd0004cf0dc0338851ccf4ae3309ec49e61cc90f41bcf912207eac95ea18","examples/tutorial_builder/04_01_enum.md":"c89cef996c17aa909031233b283349b23427c065b634d43ee82b974f4f28d1c6","examples/tutorial_builder/04_01_enum.rs":"6af29d8545e149d699f8212f17fdd9ffff7e3cf9ab1356971305b7a3f61e8b85","examples/tutorial_builder/04_01_possible.md":"e16ec1ee5e7a67ab040afd4c87c3ebf84e5ab229491b73f3da337160a0dd14bb","examples/tutorial_builder/04_01_possible.rs":"3d781b26d257061b55a957744c2dbd99c1d2346c151230fb18fe5f576d19585c","examples/tutorial_builder/04_02_parse.md":"d02e8e79e96c2def7a2576a5acc06ba539061a221960ce89eeca1a51e52ef317","examples/tutorial_builder/04_02_parse.rs":"a65f596341e65f41d555b38a6f5e22a5e03aac6faa4e8b3e3c85fa0e0935a2d7","examples/tutorial_builder/04_02_validate.md":"3f9f29b3629f0d20d8ff149ec721ee67a4baad39c12e2e379d472865c6cf682f","examples/tutorial_builder/04_02_validate.rs":"51d157b0e88db3531b560ea9a19885a9b95b5e469b2ea840004cc67dc7efe901","examples/tutorial_builder/04_03_relations.md":"cfc6a4ee6d6912566773c9c86b92466725e8eb90c5c765d7cb603f2ffd0d911a","examples/tutorial_builder/04_03_relations.rs":"bb9330a95ac5962dd1d4619936ae2bbeb60d8ed991d2ec4dc328b130992ec9a2","examples/tutorial_builder/04_04_custom.md":"11581660afa0679cda9355965cf55e0a282da9184f8d2eec97a415f48878002e","examples/tutorial_builder/04_04_custom.rs":"01966511bf069913904bcb410e808c69e2d0c2b084e01515e06650b2cde8f814","examples/tutorial_builder/05_01_assert.rs":"06abd491d53065c5c590732414df6c21c1fc0e2fe7e5793a916bca26c08fb6fd","examples/tutorial_derive/01_quick.md":"345bbe0689766fd83929826bffc32c9067c8e97c42fb7390db2620931bd27834","examples/tutorial_derive/01_quick.rs":"9b130f1a77ccaeca5fb9099c748cb3f90f6130dae258f8a48de739d495612cb7","examples/tutorial_derive/02_app_settings.md":"7b3ef753653be837d6c7d92c805a8238dd61fce2fc46d58b860c3771dbfec113","examples/tutorial_derive/02_app_settings.rs":"23679bfe015a35a31e48c50a46d031a424fdb3ced7d35a787a35763addd932b9","examples/tutorial_derive/02_apps.md":"166b48034c788304ce9d3f48f91dd7b1b7e18a6d66f689114ba618d79b60cc24","examples/tutorial_derive/02_apps.rs":"9dc8a352dacd46e46ed325f1c64054cda6793b295317baf212691acb683d8eb3","examples/tutorial_derive/02_crate.md":"c15606793151791bddf5763f660a913f799303e8de4c1d28334449d0d184681d","examples/tutorial_derive/02_crate.rs":"8096171c44d7582d23f3f9732c017fb09bfa697bf0fe8c9736f27f27e060e4e1","examples/tutorial_derive/03_01_flag_bool.md":"7ffa235eb4bc61aaa15d63d4301250e2a6635520c02a55aa6294afe6798f39a0","examples/tutorial_derive/03_01_flag_bool.rs":"2a71de11b6362609bd3e59e81ec8c50de0f45d76e5e14507ab243b35e576574d","examples/tutorial_derive/03_01_flag_count.md":"02e6dc26d00cc82109350ca7910e4962007b91fe82fde1c8b86ae49dc4428a76","examples/tutorial_derive/03_01_flag_count.rs":"09715f20ef0c138e9d330b412c0fc3776601dfaaf0399abbc4e853cf0dc68142","examples/tutorial_derive/03_02_option.md":"3ff91da5ee7bb987bf3e4e66ab1148973664ca9b50b9dd97d40b76f623a0f607","examples/tutorial_derive/03_02_option.rs":"4b6a052257bb74818a22d55f9251060ae82b8a79d109b8ef1c1db786e46035e6","examples/tutorial_derive/03_02_option_mult.md":"7a98b02fc3ddf9506134d6bb04d7967b234dac694c2a4e65398e69d53b0e9240","examples/tutorial_derive/03_02_option_mult.rs":"e4683aa309a1d4e301a93fb57338e33f7f64c117390e3013bdbfe5387f7f12ea","examples/tutorial_derive/03_03_positional.md":"52a5c10dccc3774a29e1fe6f7ff87d44eaee67d723404ddcbec24f32b7b0f048","examples/tutorial_derive/03_03_positional.rs":"ed20f87f79e707f0d37428f5b0bb1e3eef92c91bb8b5a240bfb96700fc9333e3","examples/tutorial_derive/03_03_positional_mult.md":"00e3fc665835a4df1190a5ecb7c854b1259ab2324966d69ac40770cde8e2dd21","examples/tutorial_derive/03_03_positional_mult.rs":"a24ab54fbd7569f41b89693ee82c583efd2278af811f7d16326063877700853c","examples/tutorial_derive/03_04_subcommands.md":"cba5801949524b8127c05364abadfd0f261b9e55c7e881337aebc76767173670","examples/tutorial_derive/03_04_subcommands.rs":"aad4492c7824eb41890b272040211ff9867a84ff28faa4755448d1a94b7a5e38","examples/tutorial_derive/03_04_subcommands_alt.rs":"869f81f8823161a6706671fe56047a37b6e3ceacc193a00bedef3539b12ae260","examples/tutorial_derive/03_05_default_values.md":"b09e17bf0322311801881f53d9b86e5179163d4b05263988a79fd7d2b5c1eb79","examples/tutorial_derive/03_05_default_values.rs":"525fc5b62634c1a264896bc14349d62268870a30148f559635272b7578b15196","examples/tutorial_derive/04_01_enum.md":"fa1deb854c06f6ca921b53e9fd98eaf8ff0a641095a592552537ed74197ef801","examples/tutorial_derive/04_01_enum.rs":"20ae81993a8d8af4cebb2a6c424d2df0bda8cb9d252e7151927462857539d89c","examples/tutorial_derive/04_02_parse.md":"a87492c5d6fb9817345f67389142282394c525fbeade3a2750b84d949cba1c7e","examples/tutorial_derive/04_02_parse.rs":"25fbe9a2621cda28a108aadb22d48d09eec8b5f5e58abc22e4628ec13ddfb2c2","examples/tutorial_derive/04_02_validate.md":"8f83fdf4ccb89550c0df20eef49358cb222ca1a7404c18e3eafed6413c0e1313","examples/tutorial_derive/04_02_validate.rs":"b6d06e36545e3915dd44c933b8b439b7e08282dc64784e67c646962cc5c5f738","examples/tutorial_derive/04_03_relations.md":"15172a1e5b056ee30b6ab1fbe848c71d8499b06aa74ce30219275989034c76ac","examples/tutorial_derive/04_03_relations.rs":"f82465426f5a623ffa3fa2dae4f97331f00f5b382947f460e66c0e12fb561cd9","examples/tutorial_derive/04_04_custom.md":"f96f4ced9cce7e04e5150c2906cac315bce04a5319cab080917dd976cb815bdc","examples/tutorial_derive/04_04_custom.rs":"fbb60536d2799c46ab8fe1681ff2197827176041882b20a62770b5cb93f20857","examples/tutorial_derive/05_01_assert.rs":"04927db39bdecc354f88ecbe6366b565e0f1a01c8de7c78e8db717b1e847596f","examples/typed-derive.md":"3522e2e3ef044b2acba75f0b6e17654830d06603e912cd86383bae639928644a","examples/typed-derive.rs":"0ad9575c63a091dd018b7f5888f1a6b732f5f417a3d62345ed14762baa575e83","src/_cookbook/cargo_example.rs":"fe7594a5233e9106a159aa1f5d5f0cde0d844356f630d55c78b8ef322327d4e5","src/_cookbook/cargo_example_derive.rs":"badf3e931ef5d5b7f5addc4912aca057ba83ee6302c43d7eeecd1661673fd407","src/_cookbook/escaped_positional.rs":"2789d8fea126355805b29e76b52c6cea4982565014087a46e0d48e4ddfbed7ab","src/_cookbook/escaped_positional_derive.rs":"802d0b672f4ed48152235d4a26a64c97fa921b361177bdd3a1a33cbac96f665d","src/_cookbook/find.rs":"6152ad5df466adc6de56bddb0f01930b4e4db1997fa972b055217cc7d6748a0a","src/_cookbook/git.rs":"372977252a22fc776e3acaa4629e964114ccd6a49b8ef334d2b6646f12e8b5ee","src/_cookbook/git_derive.rs":"4ab7c0197efda06607ca60c2a85ea743aed3494f5fe9e408d935ea0500a345fc","src/_cookbook/mod.rs":"a8f69fa55207d276471298acc7e22f2f08558dcaa826efbfe4ca8cf66ada2034","src/_cookbook/multicall_busybox.rs":"56176b4fa15e7a39c433706971d4e68aaf26ddc2a5790078b6dbe722ee13efee","src/_cookbook/multicall_hostname.rs":"907f8decf81ea4d4cbf81639ea4cd2f925eda64d4831454a7656369b65522780","src/_cookbook/pacman.rs":"863125b2d3d7931a9e4541c8ab1242b8bfcb421d8b5c604ea681efd805f68da7","src/_cookbook/repl.rs":"1393209b2cc5c203296d57c5a065b764b4318be7855e48baf16de851e250cf90","src/_cookbook/typed_derive.rs":"3d28e78cd0b068b4fcb32a7fea6244de176f2fe75dfcb59e99c33b66a7ae4864","src/_derive/_tutorial.rs":"310cbe86e58d4c89efa96f7b4c2c4c84fe58b6dc71714220c4c69153994c8545","src/_derive/mod.rs":"50243742d456ce7ecf1a8cc277de7b4d04ebd04e2c32201f82d408a1b8c4f4aa","src/_faq.rs":"52f274439b3608a6fea5b2d0096ee36869603afc505767fb44e7f7823162f5e0","src/_features.rs":"5451d701fdbef0e97bde371f189a744cbdb37b268e8fcc865371856e7b2bf12b","src/_tutorial.rs":"8df9053446205651b689da84836841697c00a3f67780e8e3d4ba1c2457a1ca5b","src/bin/stdio-fixture.rs":"52fbd22450981ab4e8dddce9fbd45242f403f63b08acecc5c1336fb6ba245297","src/builder/action.rs":"4a5fa5cfe724ae0a3417c649f0cb2c337858a2ec7d94dd4723c3eab65df13d6a","src/builder/app_settings.rs":"cd415ef9eb8f7b810b0aad53049d9e8c92ea4036d45862ce3d3e701ef613a36c","src/builder/arg.rs":"093471e38a1777eec2da07b515b7f84d873885b6bf8d3d5eae706d38187cfddd","src/builder/arg_group.rs":"bbde2d95e4aa1ac3e59752863b69efe4ddf837f6a751b2241005f0f8ab67f49f","src/builder/arg_predicate.rs":"4fe55fdd0441acb1577f28188c86f920df4863f451a7dcad8e050dbb6e1e7516","src/builder/arg_settings.rs":"d784f25352a24d7c4f2c488ae18c428bffee23d69caa09c0f994ff92edb2008c","src/builder/command.rs":"3c633d70cf05bad5a3c2173385b58348541dc9e250cf6208438b11e639f708ee","src/builder/debug_asserts.rs":"ae524d4a61f7a555218905e50ef51d25552b05a774f1b7df7ee4ca47b943a2b4","src/builder/mod.rs":"5e4d7928401a7047bcd17fef98b4cae251e89b7c9b966e65441ea493daabd11a","src/builder/os_str.rs":"f24139b66a6e53dfe45c60c1aa72b201ad65df90540aa73e2b2d4d1c79ac2fb4","src/builder/possible_value.rs":"dfa67084cbcf8c282dcf9a486c33ea7f3a6ff295030d7c1a962b49f4430749e8","src/builder/range.rs":"5c3bb8b5eb6e419858ef642c3b1a4d11ff800ca5b73470508f79040056757247","src/builder/resettable.rs":"67907df3cf1457a69e6ebf01be3c3c20137487aa9f05864a46acf6dd9c52f58d","src/builder/str.rs":"e227b657fdaa6946bef14f12dfee61ff3da3626e7f8a07b607e9f57e5db87eb3","src/builder/styled_str.rs":"49ce459592f1dbd9665face11ac0d82e362e37a1f7235ee49ea2c6caba98ca1f","src/builder/tests.rs":"565f5efd38c6596e55fa1c077a11cc07be94ca201527963d27fd42ddce6dbbe8","src/builder/value_hint.rs":"1acfc657879c4290e1fe811719c3ae5d13b208ac13b7e87587299534f665463a","src/builder/value_parser.rs":"657ad121cb2b191de1681b4fae758357f0922956b16b836e00b4bcb8394c272a","src/derive.rs":"3a078a6b88aa12aa99cfddf524c08bb79a003f6fd672ef65b41f4cf8ce2da457","src/error/context.rs":"156d2611a349ce826378476c9dcb3242a01ad834a095baad096a10cc2f73e1ed","src/error/format.rs":"c85ce1bbc0566424d52013f767caac15de2aed56849f77bd270abb8d010482e7","src/error/kind.rs":"8ac0115f035db9afe740e9a0b23536324352fbc1e306da67b777d403217a1d58","src/error/mod.rs":"5116a1b2d84d5845b9438265441498069c44f5b9cd7c13495d7ff5aeca5b0cc5","src/lib.rs":"89733c22228ff65d69be9d1722e940a39023862b225c568333cab80eea02293e","src/macros.rs":"6d7fe40956579453dd92e6a099f516862859e89bbb0da42e07e8ced17acd76ff","src/mkeymap.rs":"396450f20e6e09cb5a32c0ee7cee859e1a1f483b6f2febd34d7f0f6392ffe523","src/output/fmt.rs":"ba0c2c0623b0a63fff4a2b3f2f29054961ca2c56031e8c4a879864d957e2323d","src/output/help.rs":"48e56ec2b36ec6b428817ff40f2b2abea5dff3b91e6da1ba003951dcabf01d5e","src/output/help_template.rs":"0eba048de4fab96f4f3e3141268687ca6033dcd0332e39a1e0493a161f246a6c","src/output/mod.rs":"74ea52be8981c30d10fda3f6c80cf51aafb15700de99aa73bc94700bca25ae11","src/output/textwrap/core.rs":"8d2fd48581458c741558d6bc2cbcfc48f3bf0102156f75f604a7d1168aecfd5a","src/output/textwrap/mod.rs":"95e9f51bc98630634ae8b8a5f553efbdba05cb9cdb01d394aa293afb5d90803f","src/output/textwrap/word_separators.rs":"0bb065943ae639117a3813ff38587421a0eed24f2bcf92854657383d4b7bbfce","src/output/textwrap/wrap_algorithms.rs":"6c347cbba8e20d7ebcb85631318e1e51e9ac4e31fcb812ce5a5c9153eea0bc93","src/output/usage.rs":"238fc59bab0a16bd7e09f9ac39bda70de7fae378e20b4b21044fdf3d7b21a2ff","src/parser/arg_matcher.rs":"f714c1be4817ea5e6cdebe0c6cb6c41ffa7a4dde78d4a49afcd10c507b61b52e","src/parser/error.rs":"1067e17b8396b9d9a69262b6e3fc22361a5de79b6b6d57dbadbb6218f5376cec","src/parser/features/mod.rs":"6ed075e97af56bff22f22ed1ee83ff6479360e05f9d3661a3145f822c242b694","src/parser/features/suggestions.rs":"832b62f927f9f4ffb95abdcef09c8b675045aab0b5471bae484e5d07f18f7621","src/parser/matches/any_value.rs":"4706ddf9dc19e45b3a679a68851a3f9c45690e22775548edf217dddde723de97","src/parser/matches/arg_matches.rs":"9bc02d6539f005d4279336badd0ff4cb28647da6e7aae8280aa4f15ee10d22ce","src/parser/matches/matched_arg.rs":"4d699f3d9c001078053ce1b6600c5538492a5b4d8d65bf1d6fe4fafec5af0eb1","src/parser/matches/mod.rs":"c2eb45719f77f3add51b37154be28f5d86b4239b0b3b68406bebb0ee2a664815","src/parser/matches/value_source.rs":"ecb9e09db06579489daa9cbcf351381041dff7c5e2956fb96052b70b9360955b","src/parser/mod.rs":"fa9e3019d3271483a5243b24a5c8f078b4265d1b3e5735651127af11a2c2b81b","src/parser/parser.rs":"d49fecda8ab25deed693b66f2ed8be3c611beb28b82fef688c02b0829452c7be","src/parser/validator.rs":"c60e8c4eb50c6d6a4fbc4b04d6eebcfd98b98cd58d04ba69fca4cde279da69b9","src/util/color.rs":"ed7d637def9bb130fffa7a64d24ffaef8e8498959d10339a1200aba1d56da60d","src/util/flat_map.rs":"89e6471d099485f943ed7331626db6fddd75598f2c98623a13f262ff1a08b509","src/util/flat_set.rs":"334f3b8a72a897fbabd68f2330a8ecc18af74492036822b2e3764d461ddf31b4","src/util/graph.rs":"f35396b6e2a427377dcbbca69b1b98737d89684a3834cfda98cbf8cc70ff9c2f","src/util/id.rs":"5f025a05e4752ef7d610d6490f4a83ab489b1e5038c1a15067c0be51caafde87","src/util/mod.rs":"4c2e1e68d93a7f523e877c9313edea88983ea4364b33a9867c25723669872cd9","src/util/str_to_bool.rs":"1ce90b4939a884eeefc73392722bdfcf906e3070c4398e1557c586c10c684cd0"},"package":"f13b9c79b5d1dd500d20ef541215a6423c75829ef43117e1b4d17fd8af0b5d76"} \ No newline at end of file diff --git a/vendor/clap/Cargo.lock b/vendor/clap/Cargo.lock new file mode 100644 index 000000000..025f72672 --- /dev/null +++ b/vendor/clap/Cargo.lock @@ -0,0 +1,855 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "addr2line" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "backtrace" +version = "0.3.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab84319d616cfb654d03394f38ab7e6f0919e181b1b57e1fd15e7fb4077d9a7" +dependencies = [ + "addr2line", + "cc", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "cc" +version = "1.0.73" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "clap" +version = "4.1.4" +dependencies = [ + "backtrace", + "bitflags", + "clap_derive", + "clap_lex", + "humantime", + "is-terminal", + "once_cell", + "rustversion", + "shlex", + "snapbox", + "static_assertions", + "strsim", + "termcolor", + "terminal_size", + "trybuild", + "trycmd", + "unic-emoji-char", + "unicase", + "unicode-width", +] + +[[package]] +name = "clap_derive" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "684a277d672e91966334af371f1a7b5833f9aa00b07c84e92fbce95e00208ce8" +dependencies = [ + "heck", + "proc-macro-error", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "783fe232adfca04f90f56201b26d79682d4cd2625e0bc7290b95123afe558ade" +dependencies = [ + "os_str_bytes", +] + +[[package]] +name = "concolor" +version = "0.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "318d6c16e73b3a900eb212ad6a82fc7d298c5ab8184c7a9998646455bc474a16" +dependencies = [ + "bitflags", + "concolor-query", + "is-terminal", +] + +[[package]] +name = "concolor-query" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82a90734b3d5dcf656e7624cca6bce9c3a90ee11f900e80141a7427ccfb3d317" + +[[package]] +name = "crossbeam-channel" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2dd04ddaf88237dc3b8d8f9a3c1004b506b54b3313403944054d23c0870c521" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "715e8152b692bba2d374b53d4875445368fdf21a94751410af607a5ac677d1fc" +dependencies = [ + "cfg-if", + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f916dfc5d356b0ed9dae65f1db9fc9770aa2851d2662b988ccf4fe3516e86348" +dependencies = [ + "autocfg", + "cfg-if", + "crossbeam-utils", + "memoffset", + "scopeguard", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edbafec5fa1f196ca66527c1b12c2ec4745ca14b50f1ad8f9f6f720b55d11fac" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "either" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797" + +[[package]] +name = "errno" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1" +dependencies = [ + "errno-dragonfly", + "libc", + "winapi", +] + +[[package]] +name = "errno-dragonfly" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "escargot" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5584ba17d7ab26a8a7284f13e5bd196294dd2f2d79773cff29b9e9edef601a6" +dependencies = [ + "log", + "once_cell", + "serde", + "serde_json", +] + +[[package]] +name = "gimli" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22030e2c5a68ec659fde1e949a745124b48e6fa8b045b7ed5bd1fe4ccc5c4e5d" + +[[package]] +name = "glob" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "heck" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "hermit-abi" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" +dependencies = [ + "libc", +] + +[[package]] +name = "humantime" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" + +[[package]] +name = "humantime-serde" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57a3db5ea5923d99402c94e9feb261dc5ee9b4efa158b0315f788cf549cc200c" +dependencies = [ + "humantime", + "serde", +] + +[[package]] +name = "indexmap" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e" +dependencies = [ + "autocfg", + "hashbrown", +] + +[[package]] +name = "io-lifetimes" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46112a93252b123d31a119a8d1a1ac19deac4fac6e0e8b0df58f0d4e5870e63c" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "is-terminal" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "927609f78c2913a6f6ac3c27a4fe87f43e2a35367c0c4b0f8265e8f49a104330" +dependencies = [ + "hermit-abi 0.2.6", + "io-lifetimes", + "rustix", + "windows-sys", +] + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4217ad341ebadf8d8e724e264f13e593e0648f5b3e94b3896a5df283be015ecc" + +[[package]] +name = "libc" +version = "0.2.137" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89" + +[[package]] +name = "linux-raw-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f9f08d8963a6c613f4b1a78f4f4a4dbfadf8e6545b2d72861731e4858b8b47f" + +[[package]] +name = "log" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" + +[[package]] +name = "memoffset" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miniz_oxide" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f5c75688da582b8ffc1f1799e9db273f32133c49e048f614d22ec3256773ccc" +dependencies = [ + "adler", +] + +[[package]] +name = "nom8" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae01545c9c7fc4486ab7debaf2aad7003ac19431791868fb2e8066df97fad2f8" +dependencies = [ + "memchr", +] + +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + +[[package]] +name = "num_cpus" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6058e64324c71e02bc2b150e4f3bc8286db6c83092132ffa3f6b1eab0f9def5" +dependencies = [ + "hermit-abi 0.1.19", + "libc", +] + +[[package]] +name = "object" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21158b2c33aa6d4561f1c0a6ea283ca92bc54802a93b263e910746d679a7eb53" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860" + +[[package]] +name = "os_pipe" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dceb7e43f59c35ee1548045b2c72945a5a3bb6ce6d6f07cdc13dc8f6bc4930a" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "os_str_bytes" +version = "6.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ff7415e9ae3fff1225851df9e0d9e4e5479f947619774677a63572e55e80eff" + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rayon" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd99e5772ead8baa5215278c9b15bf92087709e9c1b2d1f97cdb5a183c933a7d" +dependencies = [ + "autocfg", + "crossbeam-deque", + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "258bcdb5ac6dad48491bb2992db6b7cf74878b0384908af124823d118c99683f" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-utils", + "num_cpus", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342" + +[[package]] +name = "rustix" +version = "0.36.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb93e85278e08bb5788653183213d3a60fc242b10cb9be96586f5a73dcb67c23" +dependencies = [ + "bitflags", + "errno", + "io-lifetimes", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97477e48b4cf8603ad5f7aaf897467cf42ab4218a38ef76fb14c2d6773a6d6a8" + +[[package]] +name = "ryu" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "serde" +version = "1.0.147" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d193d69bae983fc11a79df82342761dfbf28a99fc8d203dca4c3c1b590948965" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.147" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f1d362ca8fc9c3e3a7484440752472d68a6caa98f1ab81d99b5dfe517cec852" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce777b7b150d76b9cf60d28b55f5847135a003f7d7350c6be7a773508ce7d45" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b2853a4d09f215c24cc5489c992ce46052d359b5109343cbafbf26bc62f8a3" + +[[package]] +name = "similar" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62ac7f900db32bf3fd12e0117dd3dc4da74bc52ebaac97f39668446d89694803" + +[[package]] +name = "snapbox" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34eced5a65e76d5a00047986a83c65f80dc666faa27b5138f331659e2ca6bcf5" +dependencies = [ + "concolor", + "libc", + "normalize-line-endings", + "os_pipe", + "similar", + "snapbox-macros", + "wait-timeout", + "windows-sys", + "yansi", +] + +[[package]] +name = "snapbox-macros" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "485e65c1203eb37244465e857d15a26d3a85a5410648ccb53b18bd44cb3a7336" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "syn" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "termcolor" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "terminal_size" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb20089a8ba2b69debd491f8d2d023761cbf196e999218c591fa1e7e15a21907" +dependencies = [ + "rustix", + "windows-sys", +] + +[[package]] +name = "toml" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "808b51e57d0ef8f71115d8f3a01e7d3750d01c79cac4b3eda910f4389fdf92fd" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a34cc558345efd7e88b9eda9626df2138b80bb46a7606f695e751c892bc7dac6" +dependencies = [ + "indexmap", + "itertools", + "nom8", + "serde", + "toml_datetime", +] + +[[package]] +name = "trybuild" +version = "1.0.73" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed01de3de062db82c0920b5cabe804f88d599a3f217932292597c678c903754d" +dependencies = [ + "glob", + "once_cell", + "serde", + "serde_derive", + "serde_json", + "termcolor", + "toml", +] + +[[package]] +name = "trycmd" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a050cd97463d2f8df73e65b122dadb7f04ea31f0bd53a1306ea915cbb156849" +dependencies = [ + "escargot", + "glob", + "humantime", + "humantime-serde", + "rayon", + "serde", + "shlex", + "snapbox", + "toml_edit", +] + +[[package]] +name = "unic-char-property" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" +dependencies = [ + "unic-char-range", +] + +[[package]] +name = "unic-char-range" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" + +[[package]] +name = "unic-common" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" + +[[package]] +name = "unic-emoji-char" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b07221e68897210270a38bde4babb655869637af0f69407f96053a34f76494d" +dependencies = [ + "unic-char-property", + "unic-char-range", + "unic-ucd-version", +] + +[[package]] +name = "unic-ucd-version" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" +dependencies = [ + "unic-common", +] + +[[package]] +name = "unicase" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" +dependencies = [ + "version_check", +] + +[[package]] +name = "unicode-ident" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" + +[[package]] +name = "unicode-width" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "wait-timeout" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6" +dependencies = [ + "libc", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" + +[[package]] +name = "yansi" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" diff --git a/vendor/clap/Cargo.toml b/vendor/clap/Cargo.toml new file mode 100644 index 000000000..f5b7b8f94 --- /dev/null +++ b/vendor/clap/Cargo.toml @@ -0,0 +1,485 @@ +# 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.64.0" +name = "clap" +version = "4.1.4" +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", +] + +[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 = "" +replace = """ + +## [Unreleased] - ReleaseDate +""" +exactly = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "" +replace = """ + +[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 = "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.2" + +[dependencies.clap_derive] +version = "=4.1.0" +optional = true + +[dependencies.clap_lex] +version = "0.3.0" + +[dependencies.is-terminal] +version = "0.4.1" +optional = true + +[dependencies.once_cell] +version = "1.12.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.unicase] +version = "2.6" +optional = true + +[dependencies.unicode-width] +version = "0.1.9" +optional = true + +[dev-dependencies.humantime] +version = "2" + +[dev-dependencies.rustversion] +version = "1" + +[dev-dependencies.shlex] +version = "1.1.0" + +[dev-dependencies.snapbox] +version = "0.4" + +[dev-dependencies.static_assertions] +version = "1.1.0" + +[dev-dependencies.trybuild] +version = "1.0.73" + +[dev-dependencies.trycmd] +version = "0.14.9" +features = [ + "color-auto", + "diff", + "examples", +] +default-features = false + +[dev-dependencies.unic-emoji-char] +version = "0.9.0" + +[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/vendor/clap/LICENSE-APACHE b/vendor/clap/LICENSE-APACHE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/vendor/clap/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/vendor/clap/LICENSE-MIT b/vendor/clap/LICENSE-MIT new file mode 100644 index 000000000..7b05b8453 --- /dev/null +++ b/vendor/clap/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/vendor/clap/README.md b/vendor/clap/README.md new file mode 100644 index 000000000..b1298f80e --- /dev/null +++ b/vendor/clap/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/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) + +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 + + +### Gold + +[![](https://opencollective.com/clap/tiers/gold.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) + + +### Silver + +[![](https://opencollective.com/clap/tiers/silver.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) + + +### Bronze + +[![](https://opencollective.com/clap/tiers/bronze.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) + + +### Backer + +[![](https://opencollective.com/clap/tiers/backer.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) diff --git a/vendor/clap/examples/README.md b/vendor/clap/examples/README.md new file mode 100644 index 000000000..f98c370c8 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/cargo-example-derive.md b/vendor/clap/examples/cargo-example-derive.md new file mode 100644 index 000000000..a3dcef386 --- /dev/null +++ b/vendor/clap/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 + +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 + -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/vendor/clap/examples/cargo-example-derive.rs b/vendor/clap/examples/cargo-example-derive.rs new file mode 100644 index 000000000..d9603db89 --- /dev/null +++ b/vendor/clap/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 Cargo { + ExampleDerive(ExampleDerive), +} + +#[derive(clap::Args)] +#[command(author, version, about, long_about = None)] +struct ExampleDerive { + #[arg(long)] + manifest_path: Option, +} + +fn main() { + let Cargo::ExampleDerive(args) = Cargo::parse(); + println!("{:?}", args.manifest_path); +} diff --git a/vendor/clap/examples/cargo-example.md b/vendor/clap/examples/cargo-example.md new file mode 100644 index 000000000..edf8ee18a --- /dev/null +++ b/vendor/clap/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 + +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 + -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/vendor/clap/examples/cargo-example.rs b/vendor/clap/examples/cargo-example.rs new file mode 100644 index 000000000..b0861a630 --- /dev/null +++ b/vendor/clap/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" ) + .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::("manifest-path"); + println!("{:?}", manifest_path); +} diff --git a/vendor/clap/examples/demo.md b/vendor/clap/examples/demo.md new file mode 100644 index 000000000..772d98dca --- /dev/null +++ b/vendor/clap/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 + +Options: + -n, --name Name of the person to greet + -c, --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/vendor/clap/examples/demo.rs b/vendor/clap/examples/demo.rs new file mode 100644 index 000000000..8e4304a2e --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/derive_ref/augment_args.rs b/vendor/clap/examples/derive_ref/augment_args.rs new file mode 100644 index 000000000..458beb44c --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/derive_ref/augment_subcommands.rs b/vendor/clap/examples/derive_ref/augment_subcommands.rs new file mode 100644 index 000000000..577527500 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/derive_ref/flatten_hand_args.rs b/vendor/clap/examples/derive_ref/flatten_hand_args.rs new file mode 100644 index 000000000..2ceeb7c0f --- /dev/null +++ b/vendor/clap/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, +} + +impl FromArgMatches for CliArgs { + fn from_arg_matches(matches: &ArgMatches) -> Result { + let mut matches = matches.clone(); + Self::from_arg_matches_mut(&mut matches) + } + fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result { + Ok(Self { + foo: matches.get_flag("foo"), + bar: matches.get_flag("bar"), + quuz: matches.remove_one::("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::("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/vendor/clap/examples/derive_ref/hand_subcommand.rs b/vendor/clap/examples/derive_ref/hand_subcommand.rs new file mode 100644 index 000000000..5ea169cd1 --- /dev/null +++ b/vendor/clap/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, +} +#[derive(Parser, Debug)] +struct RemoveArgs { + #[arg(short, long)] + force: bool, + name: Vec, +} + +#[derive(Debug)] +enum CliSub { + Add(AddArgs), + Remove(RemoveArgs), +} + +impl FromArgMatches for CliSub { + fn from_arg_matches(matches: &ArgMatches) -> Result { + 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, + #[clap(subcommand)] + subcommand: CliSub, +} + +fn main() { + let args = Cli::parse(); + println!("{:#?}", args); +} diff --git a/vendor/clap/examples/derive_ref/interop_tests.md b/vendor/clap/examples/derive_ref/interop_tests.md new file mode 100644 index 000000000..a7bcc7e7d --- /dev/null +++ b/vendor/clap/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] + +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] + +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/vendor/clap/examples/escaped-positional-derive.md b/vendor/clap/examples/escaped-positional-derive.md new file mode 100644 index 000000000..82990b59f --- /dev/null +++ b/vendor/clap/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] [-- ...] + +Arguments: + [SLOP]... + +Options: + -f + -p + -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] [-- ...] + +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/vendor/clap/examples/escaped-positional-derive.rs b/vendor/clap/examples/escaped-positional-derive.rs new file mode 100644 index 000000000..719b3d6c2 --- /dev/null +++ b/vendor/clap/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, + + #[arg(last = true)] + slop: Vec, +} + +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/vendor/clap/examples/escaped-positional.md b/vendor/clap/examples/escaped-positional.md new file mode 100644 index 000000000..d94e3993c --- /dev/null +++ b/vendor/clap/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] [-- ...] + +Arguments: + [SLOP]... + +Options: + -f + -p + -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] [-- ...] + +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/vendor/clap/examples/escaped-positional.rs b/vendor/clap/examples/escaped-positional.rs new file mode 100644 index 000000000..d107e47db --- /dev/null +++ b/vendor/clap/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 ).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::("pea")); + // 'slops' values: Some(["sloppy", "slop", "slop"]) + println!( + "'slops' values: {:?}", + matches + .get_many::("slop") + .map(|vals| vals.collect::>()) + .unwrap_or_default() + ); + + // Continued program logic goes here... +} diff --git a/vendor/clap/examples/find.md b/vendor/clap/examples/find.md new file mode 100644 index 000000000..e9b1a86f8 --- /dev/null +++ b/vendor/clap/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 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/vendor/clap/examples/find.rs b/vendor/clap/examples/find.rs new file mode 100644 index 000000000..e073e702d --- /dev/null +++ b/vendor/clap/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 "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::(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::(matches, id, &mut values) { + continue; + } + if Self::extract::(matches, id, &mut values) { + continue; + } + unimplemented!("unknown type for {}: {:?}", id, matches); + } + values.into_values().collect::>() + } + + fn extract + Send + Sync + 'static>( + matches: &ArgMatches, + id: &clap::Id, + output: &mut BTreeMap, + ) -> bool { + match matches.try_get_many::(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 for Value { + fn from(other: String) -> Self { + Self::String(other) + } +} + +impl From for Value { + fn from(other: bool) -> Self { + Self::Bool(other) + } +} diff --git a/vendor/clap/examples/git-derive.md b/vendor/clap/examples/git-derive.md new file mode 100644 index 000000000..b5c4794d3 --- /dev/null +++ b/vendor/clap/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] + +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] + +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 ... + +Arguments: + ... Stuff to add + +Options: + -h, --help Print help + +``` + +A basic argument: +```console +$ git-derive add +? failed +adds things + +Usage: git-derive[EXE] add ... + +Arguments: + ... 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 + +Commands: + push + pop + apply + help Print this message or the help of the given subcommand(s) + +Options: + -m, --message + -h, --help Print help + +$ git-derive stash push -h +Usage: git-derive[EXE] stash push [OPTIONS] + +Options: + -m, --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 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"] + +``` + +Last argument: +```console +$ git-derive diff --help +Compare two commits + +Usage: git-derive[EXE] diff [OPTIONS] [COMMIT] [COMMIT] [-- ] + +Arguments: + [COMMIT] + [COMMIT] + [PATH] + +Options: + --color[=] [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/vendor/clap/examples/git-derive.rs b/vendor/clap/examples/git-derive.rs new file mode 100644 index 000000000..519982d1b --- /dev/null +++ b/vendor/clap/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, + #[arg(value_name = "COMMIT")] + head: Option, + #[arg(last = true)] + path: Option, + #[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, + }, + Stash(Stash), + #[command(external_subcommand)] + External(Vec), +} + +#[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 Stash { + #[command(subcommand)] + command: Option, + + #[command(flatten)] + push: StashPush, +} + +#[derive(Debug, Subcommand)] +enum StashCommands { + Push(StashPush), + Pop { stash: Option }, + Apply { stash: Option }, +} + +#[derive(Debug, Args)] +struct StashPush { + #[arg(short, long)] + message: Option, +} + +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/vendor/clap/examples/git.md b/vendor/clap/examples/git.md new file mode 100644 index 000000000..d90b2e8e0 --- /dev/null +++ b/vendor/clap/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] + +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] + +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 ... + +Arguments: + ... Stuff to add + +Options: + -h, --help Print help + +``` + +A basic argument: +```console +$ git add +? failed +adds things + +Usage: git[EXE] add ... + +Arguments: + ... 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 + +Commands: + push + pop + apply + help Print this message or the help of the given subcommand(s) + +Options: + -m, --message + -h, --help Print help + +$ git stash push -h +Usage: git[EXE] stash push [OPTIONS] + +Options: + -m, --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] [-- ] + +Arguments: + [COMMIT] + [COMMIT] + [PATH] + +Options: + --color[=] [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/vendor/clap/examples/git.rs b/vendor/clap/examples/git.rs new file mode 100644 index 000000000..8a2fcc72d --- /dev/null +++ b/vendor/clap/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!( "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 ) + .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!( "The remote to target")) + .arg_required_else_help(true), + ) + .subcommand( + Command::new("add") + .about("adds things") + .arg_required_else_help(true) + .arg(arg!( ... "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 { + vec![arg!(-m --message )] +} + +fn main() { + let matches = cli().get_matches(); + + match matches.subcommand() { + Some(("clone", sub_matches)) => { + println!( + "Cloning {}", + sub_matches.get_one::("REMOTE").expect("required") + ); + } + Some(("diff", sub_matches)) => { + let color = sub_matches + .get_one::("color") + .map(|s| s.as_str()) + .expect("defaulted in clap"); + + let mut base = sub_matches.get_one::("base").map(|s| s.as_str()); + let mut head = sub_matches.get_one::("head").map(|s| s.as_str()); + let mut path = sub_matches.get_one::("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 {}..{} {} (color={})", base, head, path, color); + } + Some(("push", sub_matches)) => { + println!( + "Pushing to {}", + sub_matches.get_one::("REMOTE").expect("required") + ); + } + Some(("add", sub_matches)) => { + let paths = sub_matches + .get_many::("PATH") + .into_iter() + .flatten() + .collect::>(); + 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::("STASH"); + println!("Applying {:?}", stash); + } + ("pop", sub_matches) => { + let stash = sub_matches.get_one::("STASH"); + println!("Popping {:?}", stash); + } + ("push", sub_matches) => { + let message = sub_matches.get_one::("message"); + println!("Pushing {:?}", message); + } + (name, _) => { + unreachable!("Unsupported subcommand `{}`", name) + } + } + } + Some((ext, sub_matches)) => { + let args = sub_matches + .get_many::("") + .into_iter() + .flatten() + .collect::>(); + 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/vendor/clap/examples/multicall-busybox.md b/vendor/clap/examples/multicall-busybox.md new file mode 100644 index 000000000..e84b26351 --- /dev/null +++ b/vendor/clap/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 hardlinks for all subcommands in path + -h, --help Print help + +``` diff --git a/vendor/clap/examples/multicall-busybox.rs b/vendor/clap/examples/multicall-busybox.rs new file mode 100644 index 000000000..9260e1d70 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/multicall-hostname.md b/vendor/clap/examples/multicall-hostname.md new file mode 100644 index 000000000..0df1274e1 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/multicall-hostname.rs b/vendor/clap/examples/multicall-hostname.rs new file mode 100644 index 000000000..b57680a5c --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/pacman.md b/vendor/clap/examples/pacman.md new file mode 100644 index 000000000..b02cf8f1b --- /dev/null +++ b/vendor/clap/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] + +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 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 ...' cannot be used with '--info' + +Usage: pacman[EXE] {sync|--sync|-S} --search ... ... + +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/vendor/clap/examples/pacman.rs b/vendor/clap/examples/pacman.rs new file mode 100644 index 000000000..12e7ffaf2 --- /dev/null +++ b/vendor/clap/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::("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::("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::("info") { + let comma_sep = packages.map(|s| s.as_str()).collect::>().join(", "); + println!("Retrieving info for {}...", comma_sep); + } else if let Some(queries) = query_matches.get_many::("search") { + let comma_sep = queries.map(|s| s.as_str()).collect::>().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/vendor/clap/examples/repl.rs b/vendor/clap/examples/repl.rs new file mode 100644 index 000000000..ef2659115 --- /dev/null +++ b/vendor/clap/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 { + 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 { + 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/vendor/clap/examples/tutorial_builder/01_quick.md b/vendor/clap/examples/tutorial_builder/01_quick.md new file mode 100644 index 000000000..bdba15cd2 --- /dev/null +++ b/vendor/clap/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 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/vendor/clap/examples/tutorial_builder/01_quick.rs b/vendor/clap/examples/tutorial_builder/01_quick.rs new file mode 100644 index 000000000..8126e335e --- /dev/null +++ b/vendor/clap/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 "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::("name") { + println!("Value for name: {}", name); + } + + if let Some(config_path) = matches.get_one::("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::("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/vendor/clap/examples/tutorial_builder/02_app_settings.md b/vendor/clap/examples/tutorial_builder/02_app_settings.md new file mode 100644 index 000000000..3ac9a95e7 --- /dev/null +++ b/vendor/clap/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 --one + +Options: + --two + + --one + + -h, --help + Print help + -V, --version + Print version + +``` diff --git a/vendor/clap/examples/tutorial_builder/02_app_settings.rs b/vendor/clap/examples/tutorial_builder/02_app_settings.rs new file mode 100644 index 000000000..4e30ec9a5 --- /dev/null +++ b/vendor/clap/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 ).required(true).action(ArgAction::Set)) + .arg(arg!(--one ).required(true).action(ArgAction::Set)) + .get_matches(); + + println!( + "two: {:?}", + matches.get_one::("two").expect("required") + ); + println!( + "one: {:?}", + matches.get_one::("one").expect("required") + ); +} diff --git a/vendor/clap/examples/tutorial_builder/02_apps.md b/vendor/clap/examples/tutorial_builder/02_apps.md new file mode 100644 index 000000000..1f8b071b1 --- /dev/null +++ b/vendor/clap/examples/tutorial_builder/02_apps.md @@ -0,0 +1,16 @@ +```console +$ 02_apps --help +Does awesome things + +Usage: 02_apps[EXE] --two --one + +Options: + --two + --one + -h, --help Print help + -V, --version Print version + +$ 02_apps --version +MyApp 1.0 + +``` diff --git a/vendor/clap/examples/tutorial_builder/02_apps.rs b/vendor/clap/examples/tutorial_builder/02_apps.rs new file mode 100644 index 000000000..7d98e6cfe --- /dev/null +++ b/vendor/clap/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. ") + .about("Does awesome things") + .arg(arg!(--two ).required(true)) + .arg(arg!(--one ).required(true)) + .get_matches(); + + println!( + "two: {:?}", + matches.get_one::("two").expect("required") + ); + println!( + "one: {:?}", + matches.get_one::("one").expect("required") + ); +} diff --git a/vendor/clap/examples/tutorial_builder/02_crate.md b/vendor/clap/examples/tutorial_builder/02_crate.md new file mode 100644 index 000000000..a0d21b3ec --- /dev/null +++ b/vendor/clap/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 --one + +Options: + --two + --one + -h, --help Print help + -V, --version Print version + +$ 02_crate --version +clap [..] + +``` diff --git a/vendor/clap/examples/tutorial_builder/02_crate.rs b/vendor/clap/examples/tutorial_builder/02_crate.rs new file mode 100644 index 000000000..ad6bb4713 --- /dev/null +++ b/vendor/clap/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 ).required(true)) + .arg(arg!(--one ).required(true)) + .get_matches(); + + println!( + "two: {:?}", + matches.get_one::("two").expect("required") + ); + println!( + "one: {:?}", + matches.get_one::("one").expect("required") + ); +} diff --git a/vendor/clap/examples/tutorial_builder/03_01_flag_bool.md b/vendor/clap/examples/tutorial_builder/03_01_flag_bool.md new file mode 100644 index 000000000..feec8e0a7 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_builder/03_01_flag_bool.rs b/vendor/clap/examples/tutorial_builder/03_01_flag_bool.rs new file mode 100644 index 000000000..03f2f1756 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_builder/03_01_flag_count.md b/vendor/clap/examples/tutorial_builder/03_01_flag_count.md new file mode 100644 index 000000000..5e964b67a --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_builder/03_01_flag_count.rs b/vendor/clap/examples/tutorial_builder/03_01_flag_count.rs new file mode 100644 index 000000000..492f7d4c1 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_builder/03_02_option.md b/vendor/clap/examples/tutorial_builder/03_02_option.md new file mode 100644 index 000000000..42b81fd42 --- /dev/null +++ b/vendor/clap/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 + -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/vendor/clap/examples/tutorial_builder/03_02_option.rs b/vendor/clap/examples/tutorial_builder/03_02_option.rs new file mode 100644 index 000000000..e9ba3e41a --- /dev/null +++ b/vendor/clap/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::("name")); +} diff --git a/vendor/clap/examples/tutorial_builder/03_02_option_mult.md b/vendor/clap/examples/tutorial_builder/03_02_option_mult.md new file mode 100644 index 000000000..659748e4d --- /dev/null +++ b/vendor/clap/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 + -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/vendor/clap/examples/tutorial_builder/03_02_option_mult.rs b/vendor/clap/examples/tutorial_builder/03_02_option_mult.rs new file mode 100644 index 000000000..1370477eb --- /dev/null +++ b/vendor/clap/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::("name")); +} diff --git a/vendor/clap/examples/tutorial_builder/03_03_positional.md b/vendor/clap/examples/tutorial_builder/03_03_positional.md new file mode 100644 index 000000000..d8d49f39b --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_builder/03_03_positional.rs b/vendor/clap/examples/tutorial_builder/03_03_positional.rs new file mode 100644 index 000000000..f652d27ca --- /dev/null +++ b/vendor/clap/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::("name")); +} diff --git a/vendor/clap/examples/tutorial_builder/03_03_positional_mult.md b/vendor/clap/examples/tutorial_builder/03_03_positional_mult.md new file mode 100644 index 000000000..174ddd9f7 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_builder/03_03_positional_mult.rs b/vendor/clap/examples/tutorial_builder/03_03_positional_mult.rs new file mode 100644 index 000000000..bcd288d8d --- /dev/null +++ b/vendor/clap/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::("name") + .unwrap_or_default() + .map(|v| v.as_str()) + .collect::>(); + + println!("names: {:?}", &args); +} diff --git a/vendor/clap/examples/tutorial_builder/03_04_subcommands.md b/vendor/clap/examples/tutorial_builder/03_04_subcommands.md new file mode 100644 index 000000000..7c73add71 --- /dev/null +++ b/vendor/clap/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] + +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] + +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/vendor/clap/examples/tutorial_builder/03_04_subcommands.rs b/vendor/clap/examples/tutorial_builder/03_04_subcommands.rs new file mode 100644 index 000000000..fbe23809e --- /dev/null +++ b/vendor/clap/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::("NAME") + ), + _ => unreachable!("Exhausted list of subcommands and subcommand_required prevents `None`"), + } +} diff --git a/vendor/clap/examples/tutorial_builder/03_05_default_values.md b/vendor/clap/examples/tutorial_builder/03_05_default_values.md new file mode 100644 index 000000000..b62a41550 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_builder/03_05_default_values.rs b/vendor/clap/examples/tutorial_builder/03_05_default_values.rs new file mode 100644 index 000000000..d259ee06e --- /dev/null +++ b/vendor/clap/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::("PORT") + .expect("default ensures there is always a value") + ); +} diff --git a/vendor/clap/examples/tutorial_builder/04_01_enum.md b/vendor/clap/examples/tutorial_builder/04_01_enum.md new file mode 100644 index 000000000..ec4c0aea1 --- /dev/null +++ b/vendor/clap/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] + +Arguments: + + 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] + +Arguments: + 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 '' + [possible values: fast, slow] + +For more information, try '--help'. + +``` diff --git a/vendor/clap/examples/tutorial_builder/04_01_enum.rs b/vendor/clap/examples/tutorial_builder/04_01_enum.rs new file mode 100644 index 000000000..1afa018a1 --- /dev/null +++ b/vendor/clap/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 { + 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 { + 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!() + .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") + .expect("'MODE' is required and parsing will fail if its missing") + { + Mode::Fast => { + println!("Hare"); + } + Mode::Slow => { + println!("Tortoise"); + } + } +} diff --git a/vendor/clap/examples/tutorial_builder/04_01_possible.md b/vendor/clap/examples/tutorial_builder/04_01_possible.md new file mode 100644 index 000000000..fa2c83539 --- /dev/null +++ b/vendor/clap/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] + +Arguments: + 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 '' + [possible values: fast, slow] + +For more information, try '--help'. + +``` diff --git a/vendor/clap/examples/tutorial_builder/04_01_possible.rs b/vendor/clap/examples/tutorial_builder/04_01_possible.rs new file mode 100644 index 000000000..3da7aca74 --- /dev/null +++ b/vendor/clap/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!() + .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::("MODE") + .expect("'MODE' is required and parsing will fail if its missing") + .as_str() + { + "fast" => { + println!("Hare"); + } + "slow" => { + println!("Tortoise"); + } + _ => unreachable!(), + } +} diff --git a/vendor/clap/examples/tutorial_builder/04_02_parse.md b/vendor/clap/examples/tutorial_builder/04_02_parse.md new file mode 100644 index 000000000..af03e95cb --- /dev/null +++ b/vendor/clap/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] + +Arguments: + 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 '': invalid digit found in string + +For more information, try '--help'. + +$ 04_02_parse_derive 0 +? failed +error: invalid value '0' for '': 0 is not in 1..=65535 + +For more information, try '--help'. + +``` diff --git a/vendor/clap/examples/tutorial_builder/04_02_parse.rs b/vendor/clap/examples/tutorial_builder/04_02_parse.rs new file mode 100644 index 000000000..13f41a18e --- /dev/null +++ b/vendor/clap/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!() + .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::("PORT") + .expect("'PORT' is required and parsing will fail if its missing"); + println!("PORT = {}", port); +} diff --git a/vendor/clap/examples/tutorial_builder/04_02_validate.md b/vendor/clap/examples/tutorial_builder/04_02_validate.md new file mode 100644 index 000000000..949072bee --- /dev/null +++ b/vendor/clap/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] + +Arguments: + 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 '': `foobar` isn't a port number + +For more information, try '--help'. + +$ 04_02_validate 0 +? failed +error: invalid value '0' for '': port not in range 1-65535 + +For more information, try '--help'. + +``` diff --git a/vendor/clap/examples/tutorial_builder/04_02_validate.rs b/vendor/clap/examples/tutorial_builder/04_02_validate.rs new file mode 100644 index 000000000..4690e8e12 --- /dev/null +++ b/vendor/clap/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!() + .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::("PORT") + .expect("'PORT' is required and parsing will fail if its missing"); + println!("PORT = {}", port); +} + +const PORT_RANGE: RangeInclusive = 1..=65535; + +fn port_in_range(s: &str) -> Result { + 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/vendor/clap/examples/tutorial_builder/04_03_relations.md b/vendor/clap/examples/tutorial_builder/04_03_relations.md new file mode 100644 index 000000000..dd0c35a68 --- /dev/null +++ b/vendor/clap/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 |--major|--minor|--patch> [INPUT_FILE] + +Arguments: + [INPUT_FILE] some regular input + +Options: + --set-ver set version manually + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --spec-in some special input argument + -c + -h, --help Print help + -V, --version Print version + +$ 04_03_relations +? failed +error: the following required arguments were not provided: + <--set-ver |--major|--minor|--patch> + +Usage: 04_03_relations[EXE] <--set-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 |--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: + > + +Usage: 04_03_relations[EXE] -c <--set-ver |--major|--minor|--patch> > + +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/vendor/clap/examples/tutorial_builder/04_03_relations.rs b/vendor/clap/examples/tutorial_builder/04_03_relations.rs new file mode 100644 index 000000000..9d2d3d8d9 --- /dev/null +++ b/vendor/clap/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" "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" "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 ) + .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::("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::("INPUT_FILE") + .unwrap_or_else(|| matches.get_one::("spec-in").unwrap()) + .display(); + println!( + "Doing work using input {} and config {}", + input, + matches.get_one::("config").unwrap().display() + ); + } +} diff --git a/vendor/clap/examples/tutorial_builder/04_04_custom.md b/vendor/clap/examples/tutorial_builder/04_04_custom.md new file mode 100644 index 000000000..0a83eb9b8 --- /dev/null +++ b/vendor/clap/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 set version manually + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --spec-in some special input argument + -c + -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/vendor/clap/examples/tutorial_builder/04_04_custom.rs b/vendor/clap/examples/tutorial_builder/04_04_custom.rs new file mode 100644 index 000000000..ebbae67dc --- /dev/null +++ b/vendor/clap/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" "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" "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 ).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::("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::("INPUT_FILE") + .or_else(|| matches.get_one::("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::("config").unwrap().display() + ); + } +} diff --git a/vendor/clap/examples/tutorial_builder/05_01_assert.rs b/vendor/clap/examples/tutorial_builder/05_01_assert.rs new file mode 100644 index 000000000..90c0a6383 --- /dev/null +++ b/vendor/clap/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::("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!() + .help("Network port to use") + .value_parser(value_parser!(usize)), + ) +} + +#[test] +fn verify_cmd() { + cmd().debug_assert(); +} diff --git a/vendor/clap/examples/tutorial_derive/01_quick.md b/vendor/clap/examples/tutorial_derive/01_quick.md new file mode 100644 index 000000000..21bbfe1a6 --- /dev/null +++ b/vendor/clap/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 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/vendor/clap/examples/tutorial_derive/01_quick.rs b/vendor/clap/examples/tutorial_derive/01_quick.rs new file mode 100644 index 000000000..960e7ea18 --- /dev/null +++ b/vendor/clap/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, + + /// Sets a custom config file + #[arg(short, long, value_name = "FILE")] + config: Option, + + /// Turn debugging information on + #[arg(short, long, action = clap::ArgAction::Count)] + debug: u8, + + #[command(subcommand)] + command: Option, +} + +#[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/vendor/clap/examples/tutorial_derive/02_app_settings.md b/vendor/clap/examples/tutorial_derive/02_app_settings.md new file mode 100644 index 000000000..90da3ae19 --- /dev/null +++ b/vendor/clap/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 --one + +Options: + --two + + --one + + -h, --help + Print help + -V, --version + Print version + +``` diff --git a/vendor/clap/examples/tutorial_derive/02_app_settings.rs b/vendor/clap/examples/tutorial_derive/02_app_settings.rs new file mode 100644 index 000000000..abea13d19 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_derive/02_apps.md b/vendor/clap/examples/tutorial_derive/02_apps.md new file mode 100644 index 000000000..b5ae1147f --- /dev/null +++ b/vendor/clap/examples/tutorial_derive/02_apps.md @@ -0,0 +1,16 @@ +```console +$ 02_apps_derive --help +Does awesome things + +Usage: 02_apps_derive[EXE] --two --one + +Options: + --two + --one + -h, --help Print help + -V, --version Print version + +$ 02_apps_derive --version +MyApp 1.0 + +``` diff --git a/vendor/clap/examples/tutorial_derive/02_apps.rs b/vendor/clap/examples/tutorial_derive/02_apps.rs new file mode 100644 index 000000000..75455efce --- /dev/null +++ b/vendor/clap/examples/tutorial_derive/02_apps.rs @@ -0,0 +1,20 @@ +use clap::Parser; + +#[derive(Parser)] +#[command(name = "MyApp")] +#[command(author = "Kevin K. ")] +#[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/vendor/clap/examples/tutorial_derive/02_crate.md b/vendor/clap/examples/tutorial_derive/02_crate.md new file mode 100644 index 000000000..3f6446064 --- /dev/null +++ b/vendor/clap/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 --one + +Options: + --two + --one + -h, --help Print help + -V, --version Print version + +$ 02_crate_derive --version +clap [..] + +``` diff --git a/vendor/clap/examples/tutorial_derive/02_crate.rs b/vendor/clap/examples/tutorial_derive/02_crate.rs new file mode 100644 index 000000000..33a7a4ee0 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_derive/03_01_flag_bool.md b/vendor/clap/examples/tutorial_derive/03_01_flag_bool.md new file mode 100644 index 000000000..976226003 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_derive/03_01_flag_bool.rs b/vendor/clap/examples/tutorial_derive/03_01_flag_bool.rs new file mode 100644 index 000000000..4f68fc834 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_derive/03_01_flag_count.md b/vendor/clap/examples/tutorial_derive/03_01_flag_count.md new file mode 100644 index 000000000..56ef9cafd --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_derive/03_01_flag_count.rs b/vendor/clap/examples/tutorial_derive/03_01_flag_count.rs new file mode 100644 index 000000000..2b8a453ed --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_derive/03_02_option.md b/vendor/clap/examples/tutorial_derive/03_02_option.md new file mode 100644 index 000000000..24e272aa8 --- /dev/null +++ b/vendor/clap/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 + -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/vendor/clap/examples/tutorial_derive/03_02_option.rs b/vendor/clap/examples/tutorial_derive/03_02_option.rs new file mode 100644 index 000000000..aad8ef10b --- /dev/null +++ b/vendor/clap/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, +} + +fn main() { + let cli = Cli::parse(); + + println!("name: {:?}", cli.name.as_deref()); +} diff --git a/vendor/clap/examples/tutorial_derive/03_02_option_mult.md b/vendor/clap/examples/tutorial_derive/03_02_option_mult.md new file mode 100644 index 000000000..cd2fe1301 --- /dev/null +++ b/vendor/clap/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 + -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/vendor/clap/examples/tutorial_derive/03_02_option_mult.rs b/vendor/clap/examples/tutorial_derive/03_02_option_mult.rs new file mode 100644 index 000000000..1caa440aa --- /dev/null +++ b/vendor/clap/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, +} + +fn main() { + let cli = Cli::parse(); + + println!("name: {:?}", cli.name); +} diff --git a/vendor/clap/examples/tutorial_derive/03_03_positional.md b/vendor/clap/examples/tutorial_derive/03_03_positional.md new file mode 100644 index 000000000..9437c246f --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_derive/03_03_positional.rs b/vendor/clap/examples/tutorial_derive/03_03_positional.rs new file mode 100644 index 000000000..cf5f4054f --- /dev/null +++ b/vendor/clap/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, +} + +fn main() { + let cli = Cli::parse(); + + println!("name: {:?}", cli.name.as_deref()); +} diff --git a/vendor/clap/examples/tutorial_derive/03_03_positional_mult.md b/vendor/clap/examples/tutorial_derive/03_03_positional_mult.md new file mode 100644 index 000000000..8f295e02b --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_derive/03_03_positional_mult.rs b/vendor/clap/examples/tutorial_derive/03_03_positional_mult.rs new file mode 100644 index 000000000..bd57a55c8 --- /dev/null +++ b/vendor/clap/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, +} + +fn main() { + let cli = Cli::parse(); + + println!("name: {:?}", cli.name); +} diff --git a/vendor/clap/examples/tutorial_derive/03_04_subcommands.md b/vendor/clap/examples/tutorial_derive/03_04_subcommands.md new file mode 100644 index 000000000..1fbac8fa3 --- /dev/null +++ b/vendor/clap/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] + +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`: +```console +$ 03_04_subcommands_derive +? failed +A simple to use, efficient, and full-featured Command Line Argument Parser + +Usage: 03_04_subcommands_derive[EXE] + +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/vendor/clap/examples/tutorial_derive/03_04_subcommands.rs b/vendor/clap/examples/tutorial_derive/03_04_subcommands.rs new file mode 100644 index 000000000..279a5fff5 --- /dev/null +++ b/vendor/clap/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 }, +} + +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/vendor/clap/examples/tutorial_derive/03_04_subcommands_alt.rs b/vendor/clap/examples/tutorial_derive/03_04_subcommands_alt.rs new file mode 100644 index 000000000..8b70dba0a --- /dev/null +++ b/vendor/clap/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(Add), +} + +#[derive(Args)] +struct Add { + name: Option, +} + +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/vendor/clap/examples/tutorial_derive/03_05_default_values.md b/vendor/clap/examples/tutorial_derive/03_05_default_values.md new file mode 100644 index 000000000..994cb3328 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_derive/03_05_default_values.rs b/vendor/clap/examples/tutorial_derive/03_05_default_values.rs new file mode 100644 index 000000000..bc33a931a --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_derive/04_01_enum.md b/vendor/clap/examples/tutorial_derive/04_01_enum.md new file mode 100644 index 000000000..89db08c96 --- /dev/null +++ b/vendor/clap/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] + +Arguments: + + 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] + +Arguments: + 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 '' + [possible values: fast, slow] + +For more information, try '--help'. + +``` diff --git a/vendor/clap/examples/tutorial_derive/04_01_enum.rs b/vendor/clap/examples/tutorial_derive/04_01_enum.rs new file mode 100644 index 000000000..41410a3bd --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_derive/04_02_parse.md b/vendor/clap/examples/tutorial_derive/04_02_parse.md new file mode 100644 index 000000000..573b43cc7 --- /dev/null +++ b/vendor/clap/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] + +Arguments: + 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 '': invalid digit found in string + +For more information, try '--help'. + +$ 04_02_parse_derive 0 +? failed +error: invalid value '0' for '': 0 is not in 1..=65535 + +For more information, try '--help'. + +``` diff --git a/vendor/clap/examples/tutorial_derive/04_02_parse.rs b/vendor/clap/examples/tutorial_derive/04_02_parse.rs new file mode 100644 index 000000000..a40c6828b --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/tutorial_derive/04_02_validate.md b/vendor/clap/examples/tutorial_derive/04_02_validate.md new file mode 100644 index 000000000..f8835fdca --- /dev/null +++ b/vendor/clap/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] + +Arguments: + 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 '': `foobar` isn't a port number + +For more information, try '--help'. + +$ 04_02_validate_derive 0 +? failed +error: invalid value '0' for '': port not in range 1-65535 + +For more information, try '--help'. + +``` diff --git a/vendor/clap/examples/tutorial_derive/04_02_validate.rs b/vendor/clap/examples/tutorial_derive/04_02_validate.rs new file mode 100644 index 000000000..513084dff --- /dev/null +++ b/vendor/clap/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 = 1..=65535; + +fn port_in_range(s: &str) -> Result { + 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/vendor/clap/examples/tutorial_derive/04_03_relations.md b/vendor/clap/examples/tutorial_derive/04_03_relations.md new file mode 100644 index 000000000..6eafb9fbb --- /dev/null +++ b/vendor/clap/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 |--major|--minor|--patch> [INPUT_FILE] + +Arguments: + [INPUT_FILE] some regular input + +Options: + --set-ver set version manually + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --spec-in some special input argument + -c + -h, --help Print help + -V, --version Print version + +$ 04_03_relations_derive +? failed +error: the following required arguments were not provided: + <--set-ver |--major|--minor|--patch> + +Usage: 04_03_relations_derive[EXE] <--set-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 |--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: + > + +Usage: 04_03_relations_derive[EXE] -c <--set-ver |--major|--minor|--patch> > + +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/vendor/clap/examples/tutorial_derive/04_03_relations.rs b/vendor/clap/examples/tutorial_derive/04_03_relations.rs new file mode 100644 index 000000000..e36609570 --- /dev/null +++ b/vendor/clap/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, + + /// 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, + + /// some special input argument + #[arg(long, group = "input")] + spec_in: Option, + + #[arg(short, requires = "input")] + config: Option, +} + +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/vendor/clap/examples/tutorial_derive/04_04_custom.md b/vendor/clap/examples/tutorial_derive/04_04_custom.md new file mode 100644 index 000000000..c601e9fb4 --- /dev/null +++ b/vendor/clap/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 set version manually + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --spec-in some special input argument + -c + -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/vendor/clap/examples/tutorial_derive/04_04_custom.rs b/vendor/clap/examples/tutorial_derive/04_04_custom.rs new file mode 100644 index 000000000..cbc460f19 --- /dev/null +++ b/vendor/clap/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, + + /// 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, + + /// some special input argument + #[arg(long)] + spec_in: Option, + + #[arg(short)] + config: Option, +} + +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 {} and config {}", input, config); + } +} diff --git a/vendor/clap/examples/tutorial_derive/05_01_assert.rs b/vendor/clap/examples/tutorial_derive/05_01_assert.rs new file mode 100644 index 000000000..42ebda9a1 --- /dev/null +++ b/vendor/clap/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/vendor/clap/examples/typed-derive.md b/vendor/clap/examples/typed-derive.md new file mode 100644 index 000000000..bf7a56a53 --- /dev/null +++ b/vendor/clap/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 Implicitly using `std::str::FromStr` + -I Allow invalid UTF-8 paths + --bind Handle IP addresses + --sleep Allow human-readable durations + -D Hand-written parser for tuples + --port Support for discrete numbers [default: 22] [possible values: 22, 80] + --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 ': 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 ': 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 ': 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 ': 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 ': 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 ' but none was supplied + [possible values: 22, 80] + +For more information, try '--help'. + +$ typed-derive --port 3000 +? failed +error: invalid value '3000' for '--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 ' 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 ' + [possible values: info, debug, info, warn, error] + +For more information, try '--help'. + +``` diff --git a/vendor/clap/examples/typed-derive.rs b/vendor/clap/examples/typed-derive.rs new file mode 100644 index 000000000..bdf8a5809 --- /dev/null +++ b/vendor/clap/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, + + /// Allow invalid UTF-8 paths + #[arg(short = 'I', value_name = "DIR", value_hint = clap::ValueHint::DirPath)] + include: Option, + + /// Handle IP addresses + #[arg(long)] + bind: Option, + + /// Allow human-readable durations + #[arg(long)] + sleep: Option, + + /// Hand-written parser for tuples + #[arg(short = 'D', value_parser = parse_key_val::)] + 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::().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::().unwrap()), + )] + log_level: foreign_crate::LogLevel, +} + +/// Parse a single key-value pair +fn parse_key_val(s: &str) -> Result<(T, U), Box> +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 { + 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/vendor/clap/src/_cookbook/cargo_example.rs b/vendor/clap/src/_cookbook/cargo_example.rs new file mode 100644 index 000000000..ec5d582db --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_cookbook/cargo_example_derive.rs b/vendor/clap/src/_cookbook/cargo_example_derive.rs new file mode 100644 index 000000000..d49f956f9 --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_cookbook/escaped_positional.rs b/vendor/clap/src/_cookbook/escaped_positional.rs new file mode 100644 index 000000000..99a3f83f3 --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_cookbook/escaped_positional_derive.rs b/vendor/clap/src/_cookbook/escaped_positional_derive.rs new file mode 100644 index 000000000..e6f99ad17 --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_cookbook/find.rs b/vendor/clap/src/_cookbook/find.rs new file mode 100644 index 000000000..2ca11c665 --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_cookbook/git.rs b/vendor/clap/src/_cookbook/git.rs new file mode 100644 index 000000000..03a926ca8 --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_cookbook/git_derive.rs b/vendor/clap/src/_cookbook/git_derive.rs new file mode 100644 index 000000000..d3119736d --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_cookbook/mod.rs b/vendor/clap/src/_cookbook/mod.rs new file mode 100644 index 000000000..dacb1219a --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_cookbook/multicall_busybox.rs b/vendor/clap/src/_cookbook/multicall_busybox.rs new file mode 100644 index 000000000..e3384d682 --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_cookbook/multicall_hostname.rs b/vendor/clap/src/_cookbook/multicall_hostname.rs new file mode 100644 index 000000000..9777654dc --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_cookbook/pacman.rs b/vendor/clap/src/_cookbook/pacman.rs new file mode 100644 index 000000000..880c58158 --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_cookbook/repl.rs b/vendor/clap/src/_cookbook/repl.rs new file mode 100644 index 000000000..549ec8259 --- /dev/null +++ b/vendor/clap/src/_cookbook/repl.rs @@ -0,0 +1,5 @@ +//! # Example: Command REPL (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/repl.rs")] +//! ``` diff --git a/vendor/clap/src/_cookbook/typed_derive.rs b/vendor/clap/src/_cookbook/typed_derive.rs new file mode 100644 index 000000000..a5fd15ff8 --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_derive/_tutorial.rs b/vendor/clap/src/_derive/_tutorial.rs new file mode 100644 index 000000000..eb95c8754 --- /dev/null +++ b/vendor/clap/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]: +//! ```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]: +//! ```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/vendor/clap/src/_derive/mod.rs b/vendor/clap/src/_derive/mod.rs new file mode 100644 index 000000000..a92b7c87b --- /dev/null +++ b/vendor/clap/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 +//! ` = ` though some use `()` instead. See the specific +//! magic attributes documentation for details. This allows users to access the +//! raw behavior of an attribute via `()` 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 = `: [`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 [= ]`: [`Command::version`][crate::Command::version] +//! - When not present: no version set +//! - Without ``: defaults to [crate `version`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field) +//! - `author [= ]`: [`Command::author`][crate::Command::author] +//! - When not present: no author set +//! - Without ``: defaults to [crate `authors`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field) +//! - `about [= ]`: [`Command::about`][crate::Command::about] +//! - When not present: [Doc comment summary](#doc-comments) +//! - Without ``: [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[ = ]`: [`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 = `: 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 = `: 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)` or `Variant(Vec)` +//! +//! 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`, 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 = `: [`Arg::id`][crate::Arg::id] +//! - When not present: case-converted field name is used +//! - `value_parser [= ]`: [`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 [= ]`: [`Arg::action`][crate::Arg::action] +//! - When not present: will auto-select an action based on the field type +//! - `help = `: [`Arg::help`][crate::Arg::help] +//! - When not present: [Doc comment summary](#doc-comments) +//! - `long_help[ = ]`: [`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 [= ]`: [`Arg::short`][crate::Arg::short] +//! - When not present: no short set +//! - Without ``: defaults to first character in the case-converted field name +//! - `long [= ]`: [`Arg::long`][crate::Arg::long] +//! - When not present: no long set +//! - Without ``: defaults to the case-converted field name +//! - `env [= ]`: [`Arg::env`][crate::Arg::env] (needs [`env` feature][crate::_features] enabled) +//! - When not present: no env set +//! - Without ``: 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 [= ]`: Ignore this field, filling in with `` +//! - Without ``: fills the field with `Default::default()` +//! - `default_value = `: [`Arg::default_value`][crate::Arg::default_value] and [`Arg::required(false)`][crate::Arg::required] +//! - `default_value_t [= ]`: [`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 ``, relies on `Default::default()` +//! - `default_values_t = `: [`Arg::default_values`][crate::Arg::default_values] and [`Arg::required(false)`][crate::Arg::required] +//! - Requires field arg to be of type `Vec` and `T` to implement `std::fmt::Display` or `#[arg(value_enum)]` +//! - `` must implement `IntoIterator` +//! - `default_value_os_t [= ]`: [`Arg::default_value_os`][crate::Arg::default_value_os] and [`Arg::required(false)`][crate::Arg::required] +//! - Requires `std::convert::Into` or `#[arg(value_enum)]` +//! - Without ``, relies on `Default::default()` +//! - `default_values_os_t = `: [`Arg::default_values_os`][crate::Arg::default_values_os] and [`Arg::required(false)`][crate::Arg::required] +//! - Requires field arg to be of type `Vec` and `T` to implement `std::convert::Into` or `#[arg(value_enum)]` +//! - `` must implement `IntoIterator` +//! +//! ### ValueEnum Attributes +//! +//! - `rename_all = `: 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 = `: [`PossibleValue::new`][crate::builder::PossibleValue::new] +//! - When not present: case-converted field name is used +//! - `help = `: [`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` | optional argument | `.action(ArgAction::Set).required(false)` | +//! | `Option>` | optional value for optional argument | `.action(ArgAction::Set).required(false).num_args(0..=1)` | +//! | `T` | required argument | `.action(ArgAction::Set).required(!has_default)` | +//! | `Vec` | `0..` occurrences of argument | `.action(ArgAction::Append).required(false)` | +//! | `Option>` | `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>` 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/vendor/clap/src/_faq.rs b/vendor/clap/src/_faq.rs new file mode 100644 index 000000000..70e7ca5bc --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_features.rs b/vendor/clap/src/_features.rs new file mode 100644 index 000000000..2f551e792 --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/_tutorial.rs b/vendor/clap/src/_tutorial.rs new file mode 100644 index 000000000..4605ec9a1 --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/bin/stdio-fixture.rs b/vendor/clap/src/bin/stdio-fixture.rs new file mode 100644 index 000000000..3a60d1338 --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/builder/action.rs b/vendor/clap/src/builder/action.rs new file mode 100644 index 000000000..9739f8800 --- /dev/null +++ b/vendor/clap/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` +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::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), + /// 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::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), + /// 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::("flag").copied(), + /// Some(10) + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_one::("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 { + 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 { + use crate::parser::AnyValueId; + + match self { + Self::Set => None, + Self::Append => None, + Self::SetTrue => None, + Self::SetFalse => None, + Self::Count => Some(AnyValueId::of::()), + Self::Help => None, + Self::Version => None, + } + } +} + +pub(crate) type CountType = u8; diff --git a/vendor/clap/src/builder/app_settings.rs b/vendor/clap/src/builder/app_settings.rs new file mode 100644 index 000000000..7a9ff8c69 --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/builder/arg.rs b/vendor/clap/src/builder/arg.rs new file mode 100644 index 000000000..ca2d6acbc --- /dev/null +++ b/vendor/clap/src/builder/arg.rs @@ -0,0 +1,4647 @@ +// 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 "Provides an input file to the program"); +/// ``` +#[derive(Default, Clone)] +pub struct Arg { + pub(crate) id: Id, + pub(crate) help: Option, + pub(crate) long_help: Option, + pub(crate) action: Option, + pub(crate) value_parser: Option, + pub(crate) blacklist: Vec, + pub(crate) settings: ArgFlags, + pub(crate) overrides: Vec, + pub(crate) groups: Vec, + 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, + pub(crate) r_unless_all: Vec, + pub(crate) short: Option, + pub(crate) long: Option, + pub(crate) aliases: Vec<(Str, bool)>, // (name, visible) + pub(crate) short_aliases: Vec<(char, bool)>, // (name, visible) + pub(crate) disp_ord: Option, + pub(crate) val_names: Vec, + pub(crate) num_vals: Option, + pub(crate) val_delim: Option, + pub(crate) default_vals: Vec, + pub(crate) default_vals_ifs: Vec<(Id, ArgPredicate, Option)>, + pub(crate) default_missing_vals: Vec, + #[cfg(feature = "env")] + pub(crate) env: Option<(OsStr, Option)>, + pub(crate) terminator: Option, + pub(crate) index: Option, + pub(crate) help_heading: Option>, + pub(crate) value_hint: Option, +} + +/// # 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) -> 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) -> 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::("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::("host").map(String::as_str), Some("wikipedia.org")); + /// ``` + #[inline] + #[must_use] + pub fn short(mut self, s: impl IntoResettable) -> 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::("cfg").map(String::as_str), Some("file.toml")); + /// ``` + #[inline] + #[must_use] + pub fn long(mut self, l: impl IntoResettable) -> 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::("test").unwrap(), "cool"); + /// ``` + #[must_use] + pub fn alias(mut self, name: impl IntoResettable) -> 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::("test").unwrap(), "cool"); + /// ``` + #[must_use] + pub fn short_alias(mut self, name: impl IntoResettable) -> 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>) -> 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) -> 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::("test").unwrap(), "coffee"); + /// ``` + /// [`Command::alias`]: Arg::alias() + #[must_use] + pub fn visible_alias(mut self, name: impl IntoResettable) -> 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::("test").unwrap(), "coffee"); + /// ``` + #[must_use] + pub fn visible_short_alias(mut self, name: impl IntoResettable) -> 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>) -> 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) -> 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::("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) -> 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!( ... "commands to run").trailing_var_arg(true)) + /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]); + /// + /// let trail: Vec<_> = m.get_many::("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] [-- ]` 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::("third").unwrap(), "three"); + /// assert_eq!(m.get_one::("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) -> 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(mut self, setting: F) -> Self + where + F: Into, + { + self.settings.insert(setting.into()); + self + } + + #[inline] + #[must_use] + pub(crate) fn unset_setting(mut self, setting: F) -> Self + where + F: Into, + { + 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::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), + /// vec!["value"] + /// ); + /// ``` + #[inline] + #[must_use] + pub fn action(mut self, action: impl IntoResettable) -> 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` + /// - `[&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) -> 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 ` 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::("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::("mode").unwrap(), "fast"); + /// + /// let m = cmd.clone() + /// .get_matches_from(vec![ + /// "prog", "--mode", + /// ]); + /// assert_eq!(m.get_one::("mode").unwrap(), "slow"); + /// + /// let m = cmd.clone() + /// .get_matches_from(vec![ + /// "prog", + /// ]); + /// assert_eq!(m.get_one::("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::("file").unwrap_or_default().map(|v| v.as_str()).collect::>(), + /// 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::("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::("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// assert_eq!(m.get_one::("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::("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// assert_eq!(m.get_one::("word").unwrap(), "word"); + /// ``` + #[inline] + #[must_use] + pub fn num_args(mut self, qty: impl IntoResettable) -> 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 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) -> 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 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>) -> 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) -> 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::("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::("option").unwrap().collect::>(); + /// 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::("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::("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::("config").unwrap().collect::>(), ["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) -> 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::("cmds").unwrap().collect(); + /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]); + /// assert_eq!(m.get_one::("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) -> 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::("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::("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) -> 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) -> 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>) -> 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>) -> 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::("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::("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::("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::("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::("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::("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) -> 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) -> 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>) -> 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>, + ) -> 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::("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::("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::("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::("flag").unwrap().collect::>(), 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) -> 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) -> 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) -> 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) -> 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 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 + /// + #[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 I should be first! + /// -o, --long-option Some help and text + /// ``` + /// [positional arguments]: Arg::index() + /// [index]: Arg::index() + #[inline] + #[must_use] + pub fn display_order(mut self, ord: impl IntoResettable) -> 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) -> 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 + /// 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) -> 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>) -> 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::("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::("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::("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::("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::("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, + predicate: impl Into, + default: impl IntoResettable, + ) -> 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, + predicate: impl Into, + default: impl IntoResettable, + ) -> 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::("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::("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::("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, + impl Into, + impl IntoResettable, + ), + >, + ) -> 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, + impl Into, + impl IntoResettable, + ), + >, + ) -> 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) -> 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>, + ) -> 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>, + ) -> 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, val: impl Into) -> 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, impl Into)>, + ) -> 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, impl Into)>, + ) -> 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, arg_id: impl Into) -> 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 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, impl Into)>, + ) -> 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>) -> 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) -> 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>) -> 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) -> 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>) -> 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 { + self.short + } + + /// Get visible short aliases for this argument, if any + #[inline] + pub fn get_visible_short_aliases(&self) -> Option> { + 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> { + 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> { + 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> { + 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> { + 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> { + 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 { + 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 { + 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 { + 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 { + 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::() { + 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::>() + .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) -> 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) -> 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 ` ` + 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 { + 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 "); + } + + #[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 ..."); + } + + #[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 [...]"); + } + + #[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 ..."); + } + + #[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 [...]"); + } + + #[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 ..."); + } + + #[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 []"); + } + + #[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 "); + } + + #[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 ..."); + } + + #[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 "); + } + + #[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 "); + } + + #[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 "); + } + + #[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 "); + } + + // 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(), "..."); + } + + #[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(), "..."); + } + + #[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(), "..."); + } + + #[test] + fn positional_display_required() { + let mut p = Arg::new("pos").index(1).required(true); + p._build(); + + assert_eq!(p.to_string(), ""); + } + + #[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(), " "); + } + + #[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(), " "); + } +} diff --git a/vendor/clap/src/builder/arg_group.rs b/vendor/clap/src/builder/arg_group.rs new file mode 100644 index 000000000..a6386a1c0 --- /dev/null +++ b/vendor/clap/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" "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" "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::("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, + pub(crate) required: bool, + pub(crate) requires: Vec, + pub(crate) conflicts: Vec, + 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) -> 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) -> 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) -> 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>) -> 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 { + 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 ``. + /// + /// **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) -> 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>) -> 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) -> 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>) -> 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 = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; + let reqs: Vec = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; + let confs: Vec = 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 = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; + let reqs: Vec = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; + let confs: Vec = 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) {} + foo(ArgGroup::new("test")) + } + + #[test] + fn arg_group_expose_is_multiple_helper() { + let args: Vec = 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 = 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/vendor/clap/src/builder/arg_predicate.rs b/vendor/clap/src/builder/arg_predicate.rs new file mode 100644 index 000000000..bc79a11b7 --- /dev/null +++ b/vendor/clap/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> From for ArgPredicate { + fn from(other: S) -> Self { + Self::Equals(other.into()) + } +} diff --git a/vendor/clap/src/builder/arg_settings.rs b/vendor/clap/src/builder/arg_settings.rs new file mode 100644 index 000000000..0f63e4396 --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/builder/command.rs b/vendor/clap/src/builder/command.rs new file mode 100644 index 000000000..fc2c983e4 --- /dev/null +++ b/vendor/clap/src/builder/command.rs @@ -0,0 +1,4703 @@ +#![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, + short_flag: Option, + display_name: Option, + bin_name: Option, + author: Option, + version: Option, + long_version: Option, + about: Option, + long_about: Option, + before_help: Option, + before_long_help: Option, + after_help: Option, + after_long_help: Option, + 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, + usage_name: Option, + help_str: Option, + disp_ord: Option, + term_w: Option, + max_w: Option, + #[cfg(feature = "help")] + template: Option, + settings: AppFlags, + g_settings: AppFlags, + args: MKeyMap, + subcommands: Vec, + replacers: FlatMap>, + groups: Vec, + current_help_heading: Option, + current_disp_ord: Option, + subcommand_value_name: Option, + subcommand_heading: Option, + external_value_parser: Option, + 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) -> 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 "Optionally sets a config file to use") + /// ) + /// # ; + /// ``` + /// [argument]: Arg + #[must_use] + pub fn arg(mut self, a: impl Into) -> 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>) -> 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(mut self, arg_id: impl AsRef, 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 `{}` is undefined", id)); + + 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(mut self, name: impl AsRef, 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 `{}` is undefined", name) + }; + + 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) -> 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>) -> 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!(" 'Required configuration file to use'"))) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn subcommand(self, subcmd: impl Into) -> 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>) -> 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 { + // 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(mut self, itr: I) -> ArgMatches + where + I: IntoIterator, + T: Into + 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(mut self, itr: I) -> ClapResult + where + I: IntoIterator, + T: Into + 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(&mut self, itr: I) -> ClapResult + where + I: IntoIterator, + T: Into + 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(&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(&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 { + // 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!( ... "commands to run")) + /// .get_matches_from(vec!["command", "set"]); + /// + /// let cmds: Vec<_> = m.get_many::("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 "Sets a custom config file")) + /// .arg(arg!(-x --stuff "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::("config").unwrap(), "file"); + /// assert!(m.get_flag("f")); + /// assert_eq!(m.get_one::("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) -> 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) -> 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) -> 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) -> 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) -> 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) -> 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) -> 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) -> 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) -> 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) -> 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) -> 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) -> 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] ") + /// # ; + /// ``` + /// + /// Or for multiple usage lines: + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .override_usage( + /// "myapp -X [-a] [-b] \n \ + /// myapp -Y [-c] \n \ + /// myapp -Z [-d|-e]" + /// ) + /// # ; + /// ``` + /// + /// [`ArgMatches::usage`]: ArgMatches::usage() + #[must_use] + pub fn override_usage(mut self, usage: impl IntoResettable) -> 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 \n\n\ + /// + /// Options:\n\ + /// -h, --help Display this message\n\ + /// -V, --version Display version info\n\ + /// -s 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) -> 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) -> Self { + self.template = s.into_resettable().into_option(); + self + } + + #[inline] + #[must_use] + pub(crate) fn setting(mut self, setting: F) -> Self + where + F: Into, + { + self.settings.insert(setting.into()); + self + } + + #[inline] + #[must_use] + pub(crate) fn unset_setting(mut self, setting: F) -> Self + where + F: Into, + { + 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) -> 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) -> 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::("format").unwrap(), "json"); + /// ``` + /// + /// [`Command::replace`]: Command::replace() + #[inline] + #[cfg(feature = "unstable-replace")] + #[must_use] + pub fn replace( + mut self, + name: impl Into, + target: impl IntoIterator>, + ) -> 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] ` where one + /// of the two following usages is allowed: + /// + /// * `$ prog [optional] ` + /// * `$ prog ` + /// + /// 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::("arg1"), None); + /// assert_eq!(m.get_one::("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::("arg1").unwrap(), "something"); + /// assert_eq!(m.get_one::("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::("foo").unwrap(), "foo"); + /// assert_eq!(m.get_one::("bar").unwrap(), "bar"); + /// assert_eq!(m.get_many::("baz").unwrap().collect::>(), &["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::("foo"), None); + /// assert_eq!(m.get_one::("bar"), None); + /// assert_eq!(m.get_many::("baz").unwrap().collect::>(), &["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) -> 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) -> 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) -> 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) -> 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) -> 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>) -> 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) -> 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>) -> 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) -> 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) -> 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) -> 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>) -> 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) -> 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>, + ) -> 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 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 + /// + #[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) -> 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::("").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::("").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::("").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, + ) -> 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_args] [subcmd_args] [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: + /// + /// * ` [subsubcmd_args]` + /// * ` [subcmd_args]` + /// * ` [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::("arg").unwrap().collect::>(), + /// &["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::("arg").unwrap().collect::>(), + /// &["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) -> 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) -> 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) { + 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 { + 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 + '_ { + 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 + '_ { + 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 + '_ { + 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 + '_ { + 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 + '_ { + 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 + '_ { + 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 { + 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 { + 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) -> 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, + ) -> 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 { + self.groups.iter() + } + + /// Iterate through the set of arguments. + #[inline] + pub fn get_arguments(&self) -> impl Iterator { + self.args.args() + } + + /// Iterate through the *positionals* arguments. + #[inline] + pub fn get_positionals(&self) -> impl Iterator { + self.get_arguments().filter(|a| a.is_positional()) + } + + /// Iterate through the *options*. + pub fn get_opts(&self) -> impl Iterator { + 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 { + self.term_w + } + + #[cfg(feature = "help")] + pub(crate) fn get_max_term_width(&self) -> Option { + 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) { + 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 { + 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 + [] + 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 = 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(&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(&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 `, 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!("{} {}\n", display_name, ver) + } + + 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. + x.name_no_brackets() + } else { + // Print usage string for flags arguments, e.g. <--help> + x.to_string() + } + }) + .collect::>() + .join("|"); + let mut styled = StyledStr::new(); + styled.none("<"); + styled.none(g_string); + styled.none(">"); + styled + } +} + +/// A workaround: +/// +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 { + 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) -> 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 + '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 + 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 { + 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 { + 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(&self, func: F, arg: &Id) -> Vec + where + F: Fn(&(ArgPredicate, Id)) -> Option, + { + 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.get_long_help().is_some() + || v.is_hide_long_help_set() + || v.is_hide_short_help_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(mut iter: I) -> Option<(T, T)> +where + I: Iterator, +{ + 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/vendor/clap/src/builder/debug_asserts.rs b/vendor/clap/src/builder/debug_asserts.rs new file mode 100644 index 000000000..bfebbb4c4 --- /dev/null +++ b/vendor/clap/src/builder/debug_asserts.rs @@ -0,0 +1,887 @@ +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::>(); + + 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 { + 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(slice: &[T]) -> impl Iterator { + 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 {} but there \ + are only {} positional arguments defined", + highest_idx, + num_p + ); + + 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 [opt1] -- + // 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 [opt1] -- + // 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, +) { + 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/vendor/clap/src/builder/mod.rs b/vendor/clap/src/builder/mod.rs new file mode 100644 index 000000000..098ad576e --- /dev/null +++ b/vendor/clap/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/vendor/clap/src/builder/os_str.rs b/vendor/clap/src/builder/os_str.rs new file mode 100644 index 000000000..bb2370deb --- /dev/null +++ b/vendor/clap/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 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 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 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 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 for std::ffi::OsString { + fn from(name: OsStr) -> Self { + name.name.into_os_string() + } +} + +impl From 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 for OsStr { + #[inline] + fn as_ref(&self) -> &std::ffi::OsStr { + self.as_os_str() + } +} + +impl AsRef for OsStr { + #[inline] + fn as_ref(&self) -> &std::path::Path { + std::path::Path::new(self) + } +} + +impl std::borrow::Borrow for OsStr { + #[inline] + fn borrow(&self) -> &std::ffi::OsStr { + self.as_os_str() + } +} + +impl PartialEq for OsStr { + #[inline] + fn eq(&self, other: &str) -> bool { + PartialEq::eq(self.as_os_str(), other) + } +} +impl PartialEq 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 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 for &'_ std::ffi::OsStr { + #[inline] + fn eq(&self, other: &OsStr) -> bool { + PartialEq::eq(*self, other.as_os_str()) + } +} + +impl PartialEq for OsStr { + #[inline] + fn eq(&self, other: &std::string::String) -> bool { + PartialEq::eq(self.as_os_str(), other.as_str()) + } +} +impl PartialEq for std::string::String { + #[inline] + fn eq(&self, other: &OsStr) -> bool { + PartialEq::eq(self.as_str(), other.as_os_str()) + } +} + +impl PartialEq for OsStr { + #[inline] + fn eq(&self, other: &std::ffi::OsString) -> bool { + PartialEq::eq(self.as_os_str(), other.as_os_str()) + } +} +impl PartialEq 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), + } + + 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 { + 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(&self, state: &mut H) { + self.as_os_str().hash(state); + } +} diff --git a/vendor/clap/src/builder/possible_value.rs b/vendor/clap/src/builder/possible_value.rs new file mode 100644 index 000000000..7a313ad25 --- /dev/null +++ b/vendor/clap/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, + aliases: Vec, // (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) -> 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) -> 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) -> 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>) -> 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> { + 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 + '_ { + 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> From for PossibleValue { + fn from(s: S) -> Self { + Self::new(s) + } +} diff --git a/vendor/clap/src/builder/range.rs b/vendor/clap/src/builder/range.rs new file mode 100644 index 000000000..3f077bd86 --- /dev/null +++ b/vendor/clap/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 { + 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 { + 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 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 for ValueRange { + fn from(fixed: usize) -> Self { + (fixed..=fixed).into() + } +} + +impl From> for ValueRange { + fn from(range: std::ops::Range) -> Self { + let start_inclusive = range.start; + let end_inclusive = range.end.saturating_sub(1); + Self::raw(start_inclusive, end_inclusive) + } +} + +impl From 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> for ValueRange { + fn from(range: std::ops::RangeFrom) -> Self { + let start_inclusive = range.start; + let end_inclusive = usize::MAX; + Self::raw(start_inclusive, end_inclusive) + } +} + +impl From> for ValueRange { + fn from(range: std::ops::RangeTo) -> Self { + let start_inclusive = 0; + let end_inclusive = range.end.saturating_sub(1); + Self::raw(start_inclusive, end_inclusive) + } +} + +impl From> for ValueRange { + fn from(range: std::ops::RangeInclusive) -> Self { + let start_inclusive = *range.start(); + let end_inclusive = *range.end(); + Self::raw(start_inclusive, end_inclusive) + } +} + +impl From> for ValueRange { + fn from(range: std::ops::RangeToInclusive) -> 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/vendor/clap/src/builder/resettable.rs b/vendor/clap/src/builder/resettable.rs new file mode 100644 index 000000000..e0b82b11b --- /dev/null +++ b/vendor/clap/src/builder/resettable.rs @@ -0,0 +1,211 @@ +// Unlike `impl Into>` or `Option>`, 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>` +/// where `T` is `impl Into` 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 { + /// Overwrite builder value + Value(T), + /// Reset builder value + Reset, +} + +impl Resettable { + pub(crate) fn into_option(self) -> Option { + match self { + Self::Value(t) => Some(t), + Self::Reset => None, + } + } +} + +impl From for Resettable { + fn from(other: T) -> Self { + Self::Value(other) + } +} + +impl From> for Resettable { + fn from(other: Option) -> Self { + match other { + Some(inner) => Self::Value(inner), + None => Self::Reset, + } + } +} + +/// Convert to the intended resettable type +pub trait IntoResettable { + /// Convert to the intended resettable type + fn into_resettable(self) -> Resettable; +} + +impl IntoResettable for Option { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option<&'static str> { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s.into()), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option<&'static str> { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s.into()), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option<&'static str> { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s.into()), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Resettable { + fn into_resettable(self) -> Resettable { + self + } +} + +impl IntoResettable for char { + fn into_resettable(self) -> Resettable { + Resettable::Value(self) + } +} + +impl IntoResettable for usize { + fn into_resettable(self) -> Resettable { + Resettable::Value(self) + } +} + +impl IntoResettable for ArgAction { + fn into_resettable(self) -> Resettable { + Resettable::Value(self) + } +} + +impl IntoResettable for ValueHint { + fn into_resettable(self) -> Resettable { + Resettable::Value(self) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} diff --git a/vendor/clap/src/builder/str.rs b/vendor/clap/src/builder/str.rs new file mode 100644 index 000000000..c6689d310 --- /dev/null +++ b/vendor/clap/src/builder/str.rs @@ -0,0 +1,307 @@ +/// 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 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 for String { + fn from(name: Str) -> Self { + name.name.into_string() + } +} + +impl From for Vec { + fn from(name: Str) -> Self { + String::from(name).into() + } +} + +impl From for std::ffi::OsString { + fn from(name: Str) -> Self { + String::from(name).into() + } +} + +impl From 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 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 for Str { + #[inline] + fn as_ref(&self) -> &std::ffi::OsStr { + (**self).as_ref() + } +} + +impl AsRef for Str { + #[inline] + fn as_ref(&self) -> &std::path::Path { + std::path::Path::new(self) + } +} + +impl std::borrow::Borrow for Str { + #[inline] + fn borrow(&self) -> &str { + self.as_str() + } +} + +impl PartialEq for Str { + #[inline] + fn eq(&self, other: &str) -> bool { + PartialEq::eq(self.as_str(), other) + } +} +impl PartialEq 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 for &'_ str { + #[inline] + fn eq(&self, other: &Str) -> bool { + PartialEq::eq(*self, other.as_str()) + } +} + +impl PartialEq for Str { + #[inline] + fn eq(&self, other: &std::ffi::OsStr) -> bool { + PartialEq::eq(self.as_str(), other) + } +} +impl PartialEq 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 for &'_ std::ffi::OsStr { + #[inline] + fn eq(&self, other: &Str) -> bool { + PartialEq::eq(*self, other.as_str()) + } +} + +impl PartialEq for Str { + #[inline] + fn eq(&self, other: &std::string::String) -> bool { + PartialEq::eq(self.as_str(), other.as_str()) + } +} +impl PartialEq 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), + } + + 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 { + self.as_str().to_owned() + } + } +} + +#[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 { + 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(&self, state: &mut H) { + self.as_str().hash(state); + } +} diff --git a/vendor/clap/src/builder/styled_str.rs b/vendor/clap/src/builder/styled_str.rs new file mode 100644 index 000000000..d36329dee --- /dev/null +++ b/vendor/clap/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