From 631cd5845e8de329d0e227aaa707d7ea228b8f8f Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 17 Apr 2024 14:20:29 +0200 Subject: Merging upstream version 1.70.0+dfsg1. Signed-off-by: Daniel Baumann --- vendor/clap/.cargo-checksum.json | 2 +- vendor/clap/Cargo.lock | 348 +- vendor/clap/Cargo.toml | 111 +- vendor/clap/examples/cargo-example-derive.rs | 8 +- vendor/clap/examples/derive_ref/augment_args.rs | 2 +- .../examples/derive_ref/augment_subcommands.rs | 2 +- .../clap/examples/derive_ref/flatten_hand_args.rs | 2 +- vendor/clap/examples/derive_ref/hand_subcommand.rs | 4 +- vendor/clap/examples/derive_ref/interop_tests.md | 2 +- vendor/clap/examples/git-derive.md | 4 +- vendor/clap/examples/git-derive.rs | 22 +- vendor/clap/examples/git.rs | 14 +- vendor/clap/examples/pacman.rs | 10 +- vendor/clap/examples/repl.rs | 2 +- vendor/clap/examples/tutorial_derive/01_quick.rs | 2 +- .../examples/tutorial_derive/03_04_subcommands.rs | 2 +- .../tutorial_derive/03_04_subcommands_alt.rs | 4 +- .../examples/tutorial_derive/04_02_validate.rs | 2 +- .../examples/tutorial_derive/04_03_relations.rs | 47 +- .../clap/examples/tutorial_derive/04_04_custom.rs | 6 +- vendor/clap/examples/typed-derive.rs | 4 +- vendor/clap/src/_derive/_tutorial.rs | 7 +- vendor/clap/src/_derive/mod.rs | 14 +- vendor/clap/src/_features.rs | 1 - 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 | 47 +- 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 - 78 files changed, 326 insertions(+), 27225 deletions(-) delete mode 100644 vendor/clap/src/builder/action.rs delete mode 100644 vendor/clap/src/builder/app_settings.rs delete mode 100644 vendor/clap/src/builder/arg.rs delete mode 100644 vendor/clap/src/builder/arg_group.rs delete mode 100644 vendor/clap/src/builder/arg_predicate.rs delete mode 100644 vendor/clap/src/builder/arg_settings.rs delete mode 100644 vendor/clap/src/builder/command.rs delete mode 100644 vendor/clap/src/builder/debug_asserts.rs delete mode 100644 vendor/clap/src/builder/mod.rs delete mode 100644 vendor/clap/src/builder/os_str.rs delete mode 100644 vendor/clap/src/builder/possible_value.rs delete mode 100644 vendor/clap/src/builder/range.rs delete mode 100644 vendor/clap/src/builder/resettable.rs delete mode 100644 vendor/clap/src/builder/str.rs delete mode 100644 vendor/clap/src/builder/styled_str.rs delete mode 100644 vendor/clap/src/builder/tests.rs delete mode 100644 vendor/clap/src/builder/value_hint.rs delete mode 100644 vendor/clap/src/builder/value_parser.rs delete mode 100644 vendor/clap/src/derive.rs delete mode 100644 vendor/clap/src/error/context.rs delete mode 100644 vendor/clap/src/error/format.rs delete mode 100644 vendor/clap/src/error/kind.rs delete mode 100644 vendor/clap/src/error/mod.rs delete mode 100644 vendor/clap/src/macros.rs delete mode 100644 vendor/clap/src/mkeymap.rs delete mode 100644 vendor/clap/src/output/fmt.rs delete mode 100644 vendor/clap/src/output/help.rs delete mode 100644 vendor/clap/src/output/help_template.rs delete mode 100644 vendor/clap/src/output/mod.rs delete mode 100644 vendor/clap/src/output/textwrap/core.rs delete mode 100644 vendor/clap/src/output/textwrap/mod.rs delete mode 100644 vendor/clap/src/output/textwrap/word_separators.rs delete mode 100644 vendor/clap/src/output/textwrap/wrap_algorithms.rs delete mode 100644 vendor/clap/src/output/usage.rs delete mode 100644 vendor/clap/src/parser/arg_matcher.rs delete mode 100644 vendor/clap/src/parser/error.rs delete mode 100644 vendor/clap/src/parser/features/mod.rs delete mode 100644 vendor/clap/src/parser/features/suggestions.rs delete mode 100644 vendor/clap/src/parser/matches/any_value.rs delete mode 100644 vendor/clap/src/parser/matches/arg_matches.rs delete mode 100644 vendor/clap/src/parser/matches/matched_arg.rs delete mode 100644 vendor/clap/src/parser/matches/mod.rs delete mode 100644 vendor/clap/src/parser/matches/value_source.rs delete mode 100644 vendor/clap/src/parser/mod.rs delete mode 100644 vendor/clap/src/parser/parser.rs delete mode 100644 vendor/clap/src/parser/validator.rs delete mode 100644 vendor/clap/src/util/color.rs delete mode 100644 vendor/clap/src/util/flat_map.rs delete mode 100644 vendor/clap/src/util/flat_set.rs delete mode 100644 vendor/clap/src/util/graph.rs delete mode 100644 vendor/clap/src/util/id.rs delete mode 100644 vendor/clap/src/util/mod.rs delete 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 index 33af0d9b8..0d9659727 100644 --- a/vendor/clap/.cargo-checksum.json +++ b/vendor/clap/.cargo-checksum.json @@ -1 +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 +{"files":{"Cargo.lock":"efdd550ec17322a1abba8d5f2fe9085627b052455d9597997736b12b9eac733e","Cargo.toml":"c4879d893da7dd63f004a1e3725a094abaa9538c1d32b7be6459bd324b867b0d","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"0d687e1f07b58fe68bda74668ff6326125e5e5efa184cce755cd84ac535b7058","README.md":"bcb96a3aedd4da85e24e201a4922e435928b0c0a2f97fd5843d0793a54e6a09f","examples/README.md":"c5f45032ee7acda0c5f98db456cbf4f9b0362d62dc81218fcf03bcdfbd19af05","examples/cargo-example-derive.md":"66d7455f08a038872f42d9d45f9b47ebbdbf9366fafa16b749ece8ba5bdcfcce","examples/cargo-example-derive.rs":"748ba54fb553e797996014e706320b62fad645acca50565a4c6fcd40e8aa1128","examples/cargo-example.md":"60a1d0f253142de5003a9474b28a5a8324a9860fc646af6309d84594d97356bd","examples/cargo-example.rs":"34bf69f18327e443b1c5fe49ff13de27004b2094e2385346708c3ac2595f9095","examples/demo.md":"6c00568794ff99007ab0f08bf7e06fe521cb1f2f0fab30c219f16c6f54bf638d","examples/demo.rs":"08cdd247b47a5202de9b7df7c1f3e7e30da975e56256d930d9db0f6c36741933","examples/derive_ref/augment_args.rs":"274bbe3c91d72609289274a22330067dd0ab42eb9bc3c44c94ed6da149ed56eb","examples/derive_ref/augment_subcommands.rs":"f202fd8a836552c53bb4b33a652b577f254726334f8a72f5fac0526937ab15ef","examples/derive_ref/flatten_hand_args.rs":"d3783fdea6297ffef23939df913ece655670b617f39addfab5147dc217e70fb1","examples/derive_ref/hand_subcommand.rs":"be49b475f86862295eb4d0a00086d5874896f9a66f28cca8fcdf6548943beba7","examples/derive_ref/interop_tests.md":"aaf307e313c3926b14f1265199ab18665bb3dea723729a7e6cbf3b237fa73941","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":"d214127af66033e0de4f9da869eb7e6ca073e7c7d7fdf8b6792cba75d39d68e9","examples/git-derive.rs":"4b0a28ef89e2c1578a9f134325495d303663d3cfcacb900ef6efcd38ef5fca44","examples/git.md":"449a75c1e0c7b2dd948b856c81a868f6b8f0c300667b17ec5dd638c6739d2175","examples/git.rs":"539c6d2f3156fb488520b63c57a6ac9e6c4bbf3842d5e09b038fcbfa5700eec7","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":"e2183dd3c60f7c3949be6f3d21c85bf8a6b2a14913b675649a770be21c764eda","examples/repl.rs":"76e64e69e860689adb2ff25b65e2c2b1842da88e4adf119b84d3c022f3699195","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":"e00b44cd37ec6c618c94886438a18b3fc4dd507bdda483d177d7e50657d00c83","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":"dc1676288d344d3e1c84e1cf966efd3710fd8b960d241b2983d9c0c5768d51bc","examples/tutorial_derive/03_04_subcommands_alt.rs":"6f72b64d40a6bfdd0efea7091369ed4bc211c6bece930a661c8b57db5d869611","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":"14dceb712b19ee28ea2c5acb53f19eaa507a9c7f85aa1bdf2b88f711ff983d5a","examples/tutorial_derive/04_03_relations.md":"15172a1e5b056ee30b6ab1fbe848c71d8499b06aa74ce30219275989034c76ac","examples/tutorial_derive/04_03_relations.rs":"c6391c46ddc5ca73423f1d290b590eff8a5280ffa6a98b198cda8d256b9d2c3f","examples/tutorial_derive/04_04_custom.md":"f96f4ced9cce7e04e5150c2906cac315bce04a5319cab080917dd976cb815bdc","examples/tutorial_derive/04_04_custom.rs":"fa5082c4e895bb73eb8ed0bcf2c1e0ca84e76240392aa1d618bec5aca36a8166","examples/tutorial_derive/05_01_assert.rs":"04927db39bdecc354f88ecbe6366b565e0f1a01c8de7c78e8db717b1e847596f","examples/typed-derive.md":"3522e2e3ef044b2acba75f0b6e17654830d06603e912cd86383bae639928644a","examples/typed-derive.rs":"1f5dd29dd923984f9a95a8e8ded7e1664fd32300a6cd9ee40a2df0ee10f86f9c","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":"89b08033092861c28c451d87bdaeeccbacb6edfb5c7e99b310d9dded0f3cbc72","src/_derive/mod.rs":"1646ca7212d9713a6051ea8af4a9c381726d3f76639ab148116d5bb8c1dea656","src/_faq.rs":"52f274439b3608a6fea5b2d0096ee36869603afc505767fb44e7f7823162f5e0","src/_features.rs":"1ad6c43256efcd1fa9b42f837e79f252412d6691332b5317081e31a29a717a76","src/_tutorial.rs":"8df9053446205651b689da84836841697c00a3f67780e8e3d4ba1c2457a1ca5b","src/bin/stdio-fixture.rs":"52fbd22450981ab4e8dddce9fbd45242f403f63b08acecc5c1336fb6ba245297","src/lib.rs":"f197cf34e8b6a51cae23f79a08919a3d5a7358169533a96857d6f494dcbc837b"},"package":"046ae530c528f252094e4a77886ee1374437744b2bff1497aa898bbddbbb29b3"} \ No newline at end of file diff --git a/vendor/clap/Cargo.lock b/vendor/clap/Cargo.lock index 025f72672..ed72b87d3 100644 --- a/vendor/clap/Cargo.lock +++ b/vendor/clap/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "addr2line" -version = "0.17.0" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b" +checksum = "a76fd60b23679b7d19bd066031410fb7e458ccc5e958eb5c325888ce4baedc97" dependencies = [ "gimli", ] @@ -17,6 +17,46 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" +[[package]] +name = "anstream" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2abc612600451a4beeff27bf046474b29f7eab30b15846975949f30f9e54afad" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-wincon", + "concolor-override", + "concolor-query", + "is-terminal", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23ea9e81bd02e310c216d080f6223c179012256e5151c41db88d12c88a1684d2" + +[[package]] +name = "anstyle-parse" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7d1bb534e9efed14f3e5f44e7dd1a4f709384023a4165199a4241e18dff0116" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-wincon" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3127af6145b149f3287bb9a0d10ad9c5692dba8c53ad48285e5bec4063834fa" +dependencies = [ + "anstyle", + "windows-sys 0.45.0", +] + [[package]] name = "autocfg" version = "1.1.0" @@ -25,9 +65,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "backtrace" -version = "0.3.66" +version = "0.3.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cab84319d616cfb654d03394f38ab7e6f0919e181b1b57e1fd15e7fb4077d9a7" +checksum = "233d376d6d185f2a3093e58f283f60f880315b6c60075b01f36b3b85154564ca" dependencies = [ "addr2line", "cc", @@ -38,6 +78,15 @@ dependencies = [ "rustc-demangle", ] +[[package]] +name = "basic-toml" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e819b667739967cd44d308b8c7b71305d8bb0729ac44a248aa08f33d01950b4" +dependencies = [ + "serde", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -58,37 +107,46 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "clap" -version = "4.1.4" +version = "4.2.1" dependencies = [ - "backtrace", - "bitflags", + "clap_builder", "clap_derive", - "clap_lex", "humantime", - "is-terminal", "once_cell", "rustversion", "shlex", "snapbox", "static_assertions", - "strsim", - "termcolor", - "terminal_size", "trybuild", "trycmd", "unic-emoji-char", +] + +[[package]] +name = "clap_builder" +version = "4.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "223163f58c9a40c3b0a43e1c4b50a9ce09f007ea2cb1ec258a687945b4b7929f" +dependencies = [ + "anstream", + "anstyle", + "backtrace", + "bitflags", + "clap_lex", + "once_cell", + "strsim", + "terminal_size", "unicase", "unicode-width", ] [[package]] name = "clap_derive" -version = "4.1.0" +version = "4.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "684a277d672e91966334af371f1a7b5833f9aa00b07c84e92fbce95e00208ce8" +checksum = "3f9644cd56d6b87dbe899ef8b053e331c0637664e9e21a33dfcdc36093f5c5c4" dependencies = [ "heck", - "proc-macro-error", "proc-macro2", "quote", "syn", @@ -96,29 +154,24 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.3.1" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "783fe232adfca04f90f56201b26d79682d4cd2625e0bc7290b95123afe558ade" -dependencies = [ - "os_str_bytes", -] +checksum = "8a2dd5a6fe8c6e3502f568a6353e5273bbb15193ad9a89e457b9970798efbea1" [[package]] -name = "concolor" -version = "0.0.11" +name = "concolor-override" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "318d6c16e73b3a900eb212ad6a82fc7d298c5ab8184c7a9998646455bc474a16" -dependencies = [ - "bitflags", - "concolor-query", - "is-terminal", -] +checksum = "a855d4a1978dc52fb0536a04d384c2c0c1aa273597f08b77c8c4d3b2eec6037f" [[package]] name = "concolor-query" -version = "0.1.0" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82a90734b3d5dcf656e7624cca6bce9c3a90ee11f900e80141a7427ccfb3d317" +checksum = "88d11d52c3d7ca2e6d0040212be9e4dbbcd78b6447f535b6b561f449427944cf" +dependencies = [ + "windows-sys 0.45.0", +] [[package]] name = "crossbeam-channel" @@ -204,9 +257,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.26.2" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22030e2c5a68ec659fde1e949a745124b48e6fa8b045b7ed5bd1fe4ccc5c4e5d" +checksum = "ad0a93d233ebf96623465aad4046a8d3aa4da22d4f4beba5388838c8a434bbb4" [[package]] name = "glob" @@ -237,12 +290,9 @@ dependencies = [ [[package]] name = "hermit-abi" -version = "0.2.6" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" -dependencies = [ - "libc", -] +checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" [[package]] name = "humantime" @@ -277,28 +327,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46112a93252b123d31a119a8d1a1ac19deac4fac6e0e8b0df58f0d4e5870e63c" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.42.0", ] [[package]] name = "is-terminal" -version = "0.4.1" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "927609f78c2913a6f6ac3c27a4fe87f43e2a35367c0c4b0f8265e8f49a104330" +checksum = "21b6b32576413a8e69b90e952e4a026476040d81017b80445deda5f2d3921857" dependencies = [ - "hermit-abi 0.2.6", + "hermit-abi 0.3.1", "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", + "windows-sys 0.45.0", ] [[package]] @@ -345,22 +386,13 @@ dependencies = [ [[package]] name = "miniz_oxide" -version = "0.5.3" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f5c75688da582b8ffc1f1799e9db273f32133c49e048f614d22ec3256773ccc" +checksum = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa" 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" @@ -379,9 +411,9 @@ dependencies = [ [[package]] name = "object" -version = "0.29.0" +version = "0.30.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21158b2c33aa6d4561f1c0a6ea283ca92bc54802a93b263e910746d679a7eb53" +checksum = "ea86265d3d3dcb6a27fc51bd29a4bf387fae9d2986b823079d4986af253eb439" dependencies = [ "memchr", ] @@ -402,50 +434,20 @@ dependencies = [ "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" +version = "1.0.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +checksum = "ba466839c78239c09faf015484e5cc04860f88242cff4d03eb038f04b4699b73" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.21" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" dependencies = [ "proc-macro2", ] @@ -491,14 +493,14 @@ dependencies = [ "io-lifetimes", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.42.0", ] [[package]] name = "rustversion" -version = "1.0.9" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97477e48b4cf8603ad5f7aaf897467cf42ab4218a38ef76fb14c2d6773a6d6a8" +checksum = "4f3208ce4d8448b3f3e7d168a73f5e0c43a61e32930de3bceeccedb388b6bf06" [[package]] name = "ryu" @@ -514,18 +516,18 @@ checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" [[package]] name = "serde" -version = "1.0.147" +version = "1.0.158" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d193d69bae983fc11a79df82342761dfbf28a99fc8d203dca4c3c1b590948965" +checksum = "771d4d9c4163ee138805e12c710dd365e4f44be8be0503cb1bb9eb989425d9c9" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.147" +version = "1.0.158" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f1d362ca8fc9c3e3a7484440752472d68a6caa98f1ab81d99b5dfe517cec852" +checksum = "e801c1712f48475582b7696ac71e0ca34ebb30e09338425384269d9717c62cad" dependencies = [ "proc-macro2", "quote", @@ -543,6 +545,15 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_spanned" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0efd8caf556a6cebd3b285caf480045fcc1ac04f6bd786b09a6f11af30c4fcf4" +dependencies = [ + "serde", +] + [[package]] name = "shlex" version = "1.1.0" @@ -557,26 +568,30 @@ checksum = "62ac7f900db32bf3fd12e0117dd3dc4da74bc52ebaac97f39668446d89694803" [[package]] name = "snapbox" -version = "0.4.4" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34eced5a65e76d5a00047986a83c65f80dc666faa27b5138f331659e2ca6bcf5" +checksum = "9615402f9cff539301119bdf2c2f328739cf2b45c2116666618fb6ac399f75bb" dependencies = [ - "concolor", + "anstream", + "anstyle", + "escargot", "libc", "normalize-line-endings", "os_pipe", "similar", "snapbox-macros", "wait-timeout", - "windows-sys", - "yansi", + "windows-sys 0.45.0", ] [[package]] name = "snapbox-macros" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "485e65c1203eb37244465e857d15a26d3a85a5410648ccb53b18bd44cb3a7336" +checksum = "f8e40c667388ed1cb5060f545d0013bf0a23efdfa6c5c3e9ef592de391cd860f" +dependencies = [ + "anstream", +] [[package]] name = "static_assertions" @@ -592,9 +607,9 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" [[package]] name = "syn" -version = "1.0.103" +version = "2.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" +checksum = "bcc02725fd69ab9f26eab07fad303e2497fad6fb9eba4f96c4d1687bdf704ad9" dependencies = [ "proc-macro2", "quote", @@ -617,62 +632,52 @@ 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", + "windows-sys 0.42.0", ] [[package]] name = "toml_datetime" -version = "0.5.0" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "808b51e57d0ef8f71115d8f3a01e7d3750d01c79cac4b3eda910f4389fdf92fd" +checksum = "3ab8ed2edee10b50132aed5f331333428b011c99402b5a534154ed15746f9622" dependencies = [ "serde", ] [[package]] name = "toml_edit" -version = "0.17.1" +version = "0.19.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a34cc558345efd7e88b9eda9626df2138b80bb46a7606f695e751c892bc7dac6" +checksum = "9a1eb0622d28f4b9c90adc4ea4b2b46b47663fde9ac5fafcb14a1369d5508825" dependencies = [ "indexmap", - "itertools", - "nom8", "serde", + "serde_spanned", "toml_datetime", + "winnow", ] [[package]] name = "trybuild" -version = "1.0.73" +version = "1.0.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed01de3de062db82c0920b5cabe804f88d599a3f217932292597c678c903754d" +checksum = "a44da5a6f2164c8e14d3bbc0657d69c5966af9f5f6930d4f600b1f5c4a673413" dependencies = [ + "basic-toml", "glob", "once_cell", "serde", "serde_derive", "serde_json", "termcolor", - "toml", ] [[package]] name = "trycmd" -version = "0.14.9" +version = "0.14.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a050cd97463d2f8df73e65b122dadb7f04ea31f0bd53a1306ea915cbb156849" +checksum = "32564b3f936a9ebedf5cc07dcf1e7e661204766d35f92c03bf347b099d84e783" dependencies = [ - "escargot", "glob", "humantime", "humantime-serde", @@ -735,9 +740,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.5" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" +checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" [[package]] name = "unicode-width" @@ -745,6 +750,12 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" +[[package]] +name = "utf8parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" + [[package]] name = "version_check" version = "0.9.4" @@ -806,50 +817,77 @@ dependencies = [ "windows_x86_64_msvc", ] +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.42.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2522491fbfcd58cc84d47aeb2958948c4b8982e9a2d8a2a35bbaed431390e7" +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" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e" +checksum = "8c9864e83243fdec7fc9c5444389dcbbfd258f745e7853198f365e3c4968a608" [[package]] name = "windows_aarch64_msvc" -version = "0.42.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4" +checksum = "4c8b1b673ffc16c47a9ff48570a9d85e25d265735c503681332589af6253c6c7" [[package]] name = "windows_i686_gnu" -version = "0.42.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7" +checksum = "de3887528ad530ba7bdbb1faa8275ec7a1155a45ffa57c37993960277145d640" [[package]] name = "windows_i686_msvc" -version = "0.42.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246" +checksum = "bf4d1122317eddd6ff351aa852118a2418ad4214e6613a50e0191f7004372605" [[package]] name = "windows_x86_64_gnu" -version = "0.42.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed" +checksum = "c1040f221285e17ebccbc2591ffdc2d44ee1f9186324dd3e84e99ac68d699c45" [[package]] name = "windows_x86_64_gnullvm" -version = "0.42.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028" +checksum = "628bfdf232daa22b0d64fdb62b09fcc36bb01f05a3939e20ab73aaf9470d0463" [[package]] name = "windows_x86_64_msvc" -version = "0.42.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" +checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd" [[package]] -name = "yansi" -version = "0.5.1" +name = "winnow" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" +checksum = "faf09497b8f8b5ac5d3bb4d05c0a99be20f26fd3d5f2db7b0716e946d5103658" +dependencies = [ + "memchr", +] diff --git a/vendor/clap/Cargo.toml b/vendor/clap/Cargo.toml index f5b7b8f94..d2c7f409c 100644 --- a/vendor/clap/Cargo.toml +++ b/vendor/clap/Cargo.toml @@ -13,7 +13,7 @@ edition = "2021" rust-version = "1.64.0" name = "clap" -version = "4.1.4" +version = "4.2.1" include = [ "build.rs", "src/**/*", @@ -89,6 +89,16 @@ replace = """ [Unreleased]: https://github.com/clap-rs/clap/compare/{{tag_name}}...HEAD""" exactly = 1 +[[package.metadata.release.pre-release-replacements]] +file = "CITATION.cff" +search = "^date-released: ....-..-.." +replace = "date-released: {{date}}" + +[[package.metadata.release.pre-release-replacements]] +file = "CITATION.cff" +search = '^version: .+\..+\..+' +replace = "version: {{version}}" + [profile.bench] lto = true codegen-units = 1 @@ -355,68 +365,38 @@ 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_builder] +version = "=4.2.1" +default-features = false [dependencies.clap_derive] -version = "=4.1.0" -optional = true - -[dependencies.clap_lex] -version = "0.3.0" - -[dependencies.is-terminal] -version = "0.4.1" +version = "=4.2.0" 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" +version = "2.1.0" [dev-dependencies.rustversion] -version = "1" +version = "1.0.12" [dev-dependencies.shlex] version = "1.1.0" [dev-dependencies.snapbox] -version = "0.4" +version = "0.4.10" [dev-dependencies.static_assertions] version = "1.1.0" [dev-dependencies.trybuild] -version = "1.0.73" +version = "1.0.77" [dev-dependencies.trycmd] -version = "0.14.9" +version = "0.14.15" features = [ "color-auto", "diff", @@ -428,14 +408,11 @@ default-features = false version = "0.9.0" [features] -cargo = ["dep:once_cell"] -color = [ - "dep:is-terminal", - "dep:termcolor", -] +cargo = ["clap_builder/cargo"] +color = ["clap_builder/color"] debug = [ + "clap_builder/debug", "clap_derive?/debug", - "dep:backtrace", ] default = [ "std", @@ -445,41 +422,29 @@ default = [ "error-context", "suggestions", ] -deprecated = ["clap_derive?/deprecated"] +deprecated = [ + "clap_builder/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", -] +env = ["clap_builder/env"] +error-context = ["clap_builder/error-context"] +help = ["clap_builder/help"] +std = ["clap_builder/std"] +string = ["clap_builder/string"] +suggestions = ["clap_builder/suggestions"] +unicode = ["clap_builder/unicode"] unstable-doc = [ + "clap_builder/unstable-doc", "derive", - "cargo", - "wrap_help", - "env", - "unicode", - "string", - "unstable-replace", ] -unstable-grouped = [] -unstable-replace = [] unstable-v5 = [ + "clap_builder/unstable-v5", "clap_derive?/unstable-v5", "deprecated", ] -usage = [] -wrap_help = [ - "help", - "dep:terminal_size", -] +usage = ["clap_builder/usage"] +wrap_help = ["clap_builder/wrap_help"] diff --git a/vendor/clap/examples/cargo-example-derive.rs b/vendor/clap/examples/cargo-example-derive.rs index d9603db89..dfdd799fc 100644 --- a/vendor/clap/examples/cargo-example-derive.rs +++ b/vendor/clap/examples/cargo-example-derive.rs @@ -3,18 +3,18 @@ use clap::Parser; #[derive(Parser)] // requires `derive` feature #[command(name = "cargo")] #[command(bin_name = "cargo")] -enum Cargo { - ExampleDerive(ExampleDerive), +enum CargoCli { + ExampleDerive(ExampleDeriveArgs), } #[derive(clap::Args)] #[command(author, version, about, long_about = None)] -struct ExampleDerive { +struct ExampleDeriveArgs { #[arg(long)] manifest_path: Option, } fn main() { - let Cargo::ExampleDerive(args) = Cargo::parse(); + let CargoCli::ExampleDerive(args) = CargoCli::parse(); println!("{:?}", args.manifest_path); } diff --git a/vendor/clap/examples/derive_ref/augment_args.rs b/vendor/clap/examples/derive_ref/augment_args.rs index 458beb44c..39d837cfa 100644 --- a/vendor/clap/examples/derive_ref/augment_args.rs +++ b/vendor/clap/examples/derive_ref/augment_args.rs @@ -23,5 +23,5 @@ fn main() { let derived_matches = DerivedArgs::from_arg_matches(&matches) .map_err(|err| err.exit()) .unwrap(); - println!("Value of derived: {:#?}", derived_matches); + 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 index 577527500..51cbe75d2 100644 --- a/vendor/clap/examples/derive_ref/augment_subcommands.rs +++ b/vendor/clap/examples/derive_ref/augment_subcommands.rs @@ -17,5 +17,5 @@ fn main() { let derived_subcommands = Subcommands::from_arg_matches(&matches) .map_err(|err| err.exit()) .unwrap(); - println!("Derived subcommands: {:#?}", derived_subcommands); + 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 index 2ceeb7c0f..36aac0932 100644 --- a/vendor/clap/examples/derive_ref/flatten_hand_args.rs +++ b/vendor/clap/examples/derive_ref/flatten_hand_args.rs @@ -87,5 +87,5 @@ struct Cli { fn main() { let args = Cli::parse(); - println!("{:#?}", args); + println!("{args:#?}"); } diff --git a/vendor/clap/examples/derive_ref/hand_subcommand.rs b/vendor/clap/examples/derive_ref/hand_subcommand.rs index 5ea169cd1..ebaa60d5d 100644 --- a/vendor/clap/examples/derive_ref/hand_subcommand.rs +++ b/vendor/clap/examples/derive_ref/hand_subcommand.rs @@ -69,11 +69,11 @@ impl Subcommand for CliSub { struct Cli { #[arg(short, long)] top_level: bool, - #[clap(subcommand)] + #[command(subcommand)] subcommand: CliSub, } fn main() { let args = Cli::parse(); - println!("{:#?}", args); + println!("{args:#?}"); } diff --git a/vendor/clap/examples/derive_ref/interop_tests.md b/vendor/clap/examples/derive_ref/interop_tests.md index a7bcc7e7d..b29e2d52d 100644 --- a/vendor/clap/examples/derive_ref/interop_tests.md +++ b/vendor/clap/examples/derive_ref/interop_tests.md @@ -142,7 +142,7 @@ $ interop_hand_subcommand add --unknown ? failed error: unexpected argument '--unknown' found - note: to pass '--unknown' as a value, use '-- --unknown' + tip: to pass '--unknown' as a value, use '-- --unknown' Usage: interop_hand_subcommand[EXE] add [NAME]... diff --git a/vendor/clap/examples/git-derive.md b/vendor/clap/examples/git-derive.md index b5c4794d3..57edb612e 100644 --- a/vendor/clap/examples/git-derive.md +++ b/vendor/clap/examples/git-derive.md @@ -102,13 +102,13 @@ Options: -h, --help Print help $ git-derive stash -m "Prototype" -Pushing StashPush { message: Some("Prototype") } +Pushing StashPushArgs { message: Some("Prototype") } $ git-derive stash pop Popping None $ git-derive stash push -m "Prototype" -Pushing StashPush { message: Some("Prototype") } +Pushing StashPushArgs { message: Some("Prototype") } $ git-derive stash pop Popping None diff --git a/vendor/clap/examples/git-derive.rs b/vendor/clap/examples/git-derive.rs index 519982d1b..ad82e0cea 100644 --- a/vendor/clap/examples/git-derive.rs +++ b/vendor/clap/examples/git-derive.rs @@ -53,7 +53,7 @@ enum Commands { #[arg(required = true)] path: Vec, }, - Stash(Stash), + Stash(StashArgs), #[command(external_subcommand)] External(Vec), } @@ -76,23 +76,23 @@ impl std::fmt::Display for ColorWhen { #[derive(Debug, Args)] #[command(args_conflicts_with_subcommands = true)] -struct Stash { +struct StashArgs { #[command(subcommand)] command: Option, #[command(flatten)] - push: StashPush, + push: StashPushArgs, } #[derive(Debug, Subcommand)] enum StashCommands { - Push(StashPush), + Push(StashPushArgs), Pop { stash: Option }, Apply { stash: Option }, } #[derive(Debug, Args)] -struct StashPush { +struct StashPushArgs { #[arg(short, long)] message: Option, } @@ -102,7 +102,7 @@ fn main() { match args.command { Commands::Clone { remote } => { - println!("Cloning {}", remote); + println!("Cloning {remote}"); } Commands::Diff { mut base, @@ -136,22 +136,22 @@ fn main() { ); } Commands::Push { remote } => { - println!("Pushing to {}", remote); + println!("Pushing to {remote}"); } Commands::Add { path } => { - println!("Adding {:?}", 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); + println!("Pushing {push:?}"); } StashCommands::Pop { stash } => { - println!("Popping {:?}", stash); + println!("Popping {stash:?}"); } StashCommands::Apply { stash } => { - println!("Applying {:?}", stash); + println!("Applying {stash:?}"); } } } diff --git a/vendor/clap/examples/git.rs b/vendor/clap/examples/git.rs index 8a2fcc72d..bd05e5315 100644 --- a/vendor/clap/examples/git.rs +++ b/vendor/clap/examples/git.rs @@ -86,7 +86,7 @@ fn main() { let base = base.unwrap_or("stage"); let head = head.unwrap_or("worktree"); let path = path.unwrap_or(""); - println!("Diffing {}..{} {} (color={})", base, head, path, color); + println!("Diffing {base}..{head} {path} (color={color})"); } Some(("push", sub_matches)) => { println!( @@ -100,22 +100,22 @@ fn main() { .into_iter() .flatten() .collect::>(); - println!("Adding {:?}", paths); + 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); + println!("Applying {stash:?}"); } ("pop", sub_matches) => { let stash = sub_matches.get_one::("STASH"); - println!("Popping {:?}", stash); + println!("Popping {stash:?}"); } ("push", sub_matches) => { let message = sub_matches.get_one::("message"); - println!("Pushing {:?}", message); + println!("Pushing {message:?}"); } (name, _) => { unreachable!("Unsupported subcommand `{}`", name) @@ -128,9 +128,9 @@ fn main() { .into_iter() .flatten() .collect::>(); - println!("Calling out to {:?} with {:?}", ext, args); + println!("Calling out to {ext:?} with {args:?}"); } - _ => unreachable!(), // If all subcommands are defined above, anything else is unreachabe!() + _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable!() } // Continued program logic goes here... diff --git a/vendor/clap/examples/pacman.rs b/vendor/clap/examples/pacman.rs index 12e7ffaf2..7ab30db95 100644 --- a/vendor/clap/examples/pacman.rs +++ b/vendor/clap/examples/pacman.rs @@ -78,7 +78,7 @@ fn main() { .map(|s| s.as_str()) .collect(); let values = packages.join(", "); - println!("Searching for {}...", values); + println!("Searching for {values}..."); return; } @@ -90,18 +90,18 @@ fn main() { let values = packages.join(", "); if sync_matches.get_flag("info") { - println!("Retrieving info for {}...", values); + println!("Retrieving info for {values}..."); } else { - println!("Installing {}...", values); + 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); + 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); + println!("Searching Locally for {comma_sep}..."); } else { println!("Displaying all locally installed packages..."); } diff --git a/vendor/clap/examples/repl.rs b/vendor/clap/examples/repl.rs index ef2659115..2806ac8e9 100644 --- a/vendor/clap/examples/repl.rs +++ b/vendor/clap/examples/repl.rs @@ -17,7 +17,7 @@ fn main() -> Result<(), String> { } } Err(err) => { - write!(std::io::stdout(), "{}", err).map_err(|e| e.to_string())?; + write!(std::io::stdout(), "{err}").map_err(|e| e.to_string())?; std::io::stdout().flush().map_err(|e| e.to_string())?; } } diff --git a/vendor/clap/examples/tutorial_derive/01_quick.rs b/vendor/clap/examples/tutorial_derive/01_quick.rs index 960e7ea18..0edcd251f 100644 --- a/vendor/clap/examples/tutorial_derive/01_quick.rs +++ b/vendor/clap/examples/tutorial_derive/01_quick.rs @@ -35,7 +35,7 @@ fn main() { // 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); + println!("Value for name: {name}"); } if let Some(config_path) = cli.config.as_deref() { diff --git a/vendor/clap/examples/tutorial_derive/03_04_subcommands.rs b/vendor/clap/examples/tutorial_derive/03_04_subcommands.rs index 279a5fff5..da7c644c7 100644 --- a/vendor/clap/examples/tutorial_derive/03_04_subcommands.rs +++ b/vendor/clap/examples/tutorial_derive/03_04_subcommands.rs @@ -21,7 +21,7 @@ fn main() { // matches just as you would the top level cmd match &cli.command { Commands::Add { name } => { - println!("'myapp add' was used, name is: {:?}", 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 index 8b70dba0a..80b0ec6b9 100644 --- a/vendor/clap/examples/tutorial_derive/03_04_subcommands_alt.rs +++ b/vendor/clap/examples/tutorial_derive/03_04_subcommands_alt.rs @@ -11,11 +11,11 @@ struct Cli { #[derive(Subcommand)] enum Commands { /// Adds files to myapp - Add(Add), + Add(AddArgs), } #[derive(Args)] -struct Add { +struct AddArgs { name: Option, } diff --git a/vendor/clap/examples/tutorial_derive/04_02_validate.rs b/vendor/clap/examples/tutorial_derive/04_02_validate.rs index 513084dff..3391d5b72 100644 --- a/vendor/clap/examples/tutorial_derive/04_02_validate.rs +++ b/vendor/clap/examples/tutorial_derive/04_02_validate.rs @@ -21,7 +21,7 @@ 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))?; + .map_err(|_| format!("`{s}` isn't a port number"))?; if PORT_RANGE.contains(&port) { Ok(port as u16) } else { diff --git a/vendor/clap/examples/tutorial_derive/04_03_relations.rs b/vendor/clap/examples/tutorial_derive/04_03_relations.rs index e36609570..8657ebe83 100644 --- a/vendor/clap/examples/tutorial_derive/04_03_relations.rs +++ b/vendor/clap/examples/tutorial_derive/04_03_relations.rs @@ -1,13 +1,26 @@ -use clap::{ArgGroup, Parser}; +use clap::{Args, 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 { + #[command(flatten)] + vers: Vers, + + /// 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, +} + +#[derive(Args)] +#[group(required = true, multiple = false)] +struct Vers { /// set version manually #[arg(long, value_name = "VER")] set_ver: Option, @@ -23,17 +36,6 @@ struct Cli { /// 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() { @@ -45,21 +47,22 @@ fn main() { 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() { + let vers = &cli.vers; + let version = if let Some(ver) = vers.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); + let (maj, min, pat) = (vers.major, vers.minor, vers.patch); match (maj, min, pat) { (true, _, _) => major += 1, (_, true, _) => minor += 1, (_, _, true) => patch += 1, _ => unreachable!(), }; - format!("{}.{}.{}", major, minor, patch) + format!("{major}.{minor}.{patch}") }; - println!("Version: {}", version); + println!("Version: {version}"); // Check for usage of -c if let Some(config) = cli.config.as_deref() { @@ -67,6 +70,6 @@ fn main() { .input_file .as_deref() .unwrap_or_else(|| cli.spec_in.as_deref().unwrap()); - println!("Doing work using input {} and config {}", input, config); + println!("Doing work using input {input} and config {config}"); } } diff --git a/vendor/clap/examples/tutorial_derive/04_04_custom.rs b/vendor/clap/examples/tutorial_derive/04_04_custom.rs index cbc460f19..a84b5ed5f 100644 --- a/vendor/clap/examples/tutorial_derive/04_04_custom.rs +++ b/vendor/clap/examples/tutorial_derive/04_04_custom.rs @@ -66,10 +66,10 @@ fn main() { .exit(); } }; - format!("{}.{}.{}", major, minor, patch) + format!("{major}.{minor}.{patch}") }; - println!("Version: {}", version); + println!("Version: {version}"); // Check for usage of -c if let Some(config) = cli.config.as_deref() { @@ -86,6 +86,6 @@ fn main() { ) .exit() }); - println!("Doing work using input {} and config {}", input, config); + println!("Doing work using input {input} and config {config}"); } } diff --git a/vendor/clap/examples/typed-derive.rs b/vendor/clap/examples/typed-derive.rs index bdf8a5809..8d7a84e96 100644 --- a/vendor/clap/examples/typed-derive.rs +++ b/vendor/clap/examples/typed-derive.rs @@ -54,7 +54,7 @@ where { let pos = s .find('=') - .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?; + .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{s}`"))?; Ok((s[..pos].parse()?, s[pos + 1..].parse()?)) } @@ -98,5 +98,5 @@ mod foreign_crate { fn main() { let args = Args::parse(); - println!("{:?}", args); + println!("{args:?}"); } diff --git a/vendor/clap/src/_derive/_tutorial.rs b/vendor/clap/src/_derive/_tutorial.rs index eb95c8754..8d00b03ec 100644 --- a/vendor/clap/src/_derive/_tutorial.rs +++ b/vendor/clap/src/_derive/_tutorial.rs @@ -75,7 +75,7 @@ #![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]: +//! accept multiple values, use [`Append`][crate::ArgAction::Append] via `Vec`: //! ```rust #![doc = include_str!("../../examples/tutorial_derive/03_03_positional_mult.rs")] //! ``` @@ -98,7 +98,7 @@ #![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]: +//! accept multiple occurrences, use [`Append`][crate::ArgAction::Append] via `Vec`: //! ```rust #![doc = include_str!("../../examples/tutorial_derive/03_02_option_mult.rs")] //! ``` @@ -202,6 +202,9 @@ //! want one of them to be required, but making all of them required isn't feasible because perhaps //! they conflict with each other. //! +//! [`ArgGroup`][crate::ArgGroup]s are automatically created for a `struct` with its +//! [`ArgGroup::id`][crate::ArgGroup::id] being the struct's name. +//! //! ```rust #![doc = include_str!("../../examples/tutorial_derive/04_03_relations.rs")] //! ``` diff --git a/vendor/clap/src/_derive/mod.rs b/vendor/clap/src/_derive/mod.rs index a92b7c87b..2e4a4902d 100644 --- a/vendor/clap/src/_derive/mod.rs +++ b/vendor/clap/src/_derive/mod.rs @@ -194,7 +194,14 @@ //! These correspond to the [`ArgGroup`][crate::ArgGroup] which is implicitly created for each //! `Args` derive. //! -//! At the moment, only `#[group(skip)]` is supported +//! **Raw attributes:** Any [`ArgGroup` method][crate::ArgGroup] can also be used as an attribute, see [Terminology](#terminology) for syntax. +//! - e.g. `#[group(required = true)]` would translate to `arg_group.required(true)` +//! +//! **Magic attributes**: +//! - `id = `: [`ArgGroup::id`][crate::ArgGroup::id] +//! - When not present: struct's name is used +//! - `skip [= ]`: Ignore this field, filling in with `` +//! - Without ``: fills the field with `Default::default()` //! //! ### Arg Attributes //! @@ -205,7 +212,7 @@ //! //! **Magic attributes**: //! - `id = `: [`Arg::id`][crate::Arg::id] -//! - When not present: case-converted field name is used +//! - When not present: field's 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!] @@ -284,6 +291,9 @@ //! //! Notes: //! - For custom type behavior, you can override the implied attributes/settings and/or set additional ones +//! - To force any inferred type (like `Vec`) to be treated as `T`, you can refer to the type +//! by another means, like using `std::vec::Vec` instead of `Vec`. For improving this, see +//! [#4626](https://github.com/clap-rs/clap/issues/4626). //! - `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..)` //! diff --git a/vendor/clap/src/_features.rs b/vendor/clap/src/_features.rs index 2f551e792..b47ee259c 100644 --- a/vendor/clap/src/_features.rs +++ b/vendor/clap/src/_features.rs @@ -25,5 +25,4 @@ //! //! **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/builder/action.rs b/vendor/clap/src/builder/action.rs deleted file mode 100644 index 9739f8800..000000000 --- a/vendor/clap/src/builder/action.rs +++ /dev/null @@ -1,344 +0,0 @@ -/// 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 deleted file mode 100644 index 7a9ff8c69..000000000 --- a/vendor/clap/src/builder/app_settings.rs +++ /dev/null @@ -1,172 +0,0 @@ -// 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 deleted file mode 100644 index ca2d6acbc..000000000 --- a/vendor/clap/src/builder/arg.rs +++ /dev/null @@ -1,4647 +0,0 @@ -// 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 deleted file mode 100644 index a6386a1c0..000000000 --- a/vendor/clap/src/builder/arg_group.rs +++ /dev/null @@ -1,596 +0,0 @@ -// 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 deleted file mode 100644 index bc79a11b7..000000000 --- a/vendor/clap/src/builder/arg_predicate.rs +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 0f63e4396..000000000 --- a/vendor/clap/src/builder/arg_settings.rs +++ /dev/null @@ -1,145 +0,0 @@ -// 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 deleted file mode 100644 index fc2c983e4..000000000 --- a/vendor/clap/src/builder/command.rs +++ /dev/null @@ -1,4703 +0,0 @@ -#![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 deleted file mode 100644 index bfebbb4c4..000000000 --- a/vendor/clap/src/builder/debug_asserts.rs +++ /dev/null @@ -1,887 +0,0 @@ -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 deleted file mode 100644 index 098ad576e..000000000 --- a/vendor/clap/src/builder/mod.rs +++ /dev/null @@ -1,60 +0,0 @@ -//! 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 deleted file mode 100644 index bb2370deb..000000000 --- a/vendor/clap/src/builder/os_str.rs +++ /dev/null @@ -1,336 +0,0 @@ -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 deleted file mode 100644 index 7a313ad25..000000000 --- a/vendor/clap/src/builder/possible_value.rs +++ /dev/null @@ -1,234 +0,0 @@ -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 deleted file mode 100644 index 3f077bd86..000000000 --- a/vendor/clap/src/builder/range.rs +++ /dev/null @@ -1,283 +0,0 @@ -/// 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 deleted file mode 100644 index e0b82b11b..000000000 --- a/vendor/clap/src/builder/resettable.rs +++ /dev/null @@ -1,211 +0,0 @@ -// 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 deleted file mode 100644 index c6689d310..000000000 --- a/vendor/clap/src/builder/str.rs +++ /dev/null @@ -1,307 +0,0 @@ -/// 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 deleted file mode 100644 index d36329dee..000000000 --- a/vendor/clap/src/builder/styled_str.rs +++ /dev/null @@ -1,349 +0,0 @@ -/// 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