diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:20:29 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:20:29 +0000 |
commit | 631cd5845e8de329d0e227aaa707d7ea228b8f8f (patch) | |
tree | a1b87c8f8cad01cf18f7c5f57a08f102771ed303 /vendor/clap | |
parent | Adding debian version 1.69.0+dfsg1-1. (diff) | |
download | rustc-631cd5845e8de329d0e227aaa707d7ea228b8f8f.tar.xz rustc-631cd5845e8de329d0e227aaa707d7ea228b8f8f.zip |
Merging upstream version 1.70.0+dfsg1.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/clap')
78 files changed, 326 insertions, 27225 deletions
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", ] @@ -18,6 +18,46 @@ 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" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -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", @@ -39,6 +79,15 @@ dependencies = [ ] [[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" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -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,23 +386,14 @@ 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" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -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", ] @@ -403,49 +435,19 @@ dependencies = [ ] [[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", @@ -544,6 +546,15 @@ dependencies = [ ] [[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" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -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" @@ -746,6 +751,12 @@ 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" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -807,49 +818,76 @@ dependencies = [ ] [[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<std::path::PathBuf>, } 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<PathBuf>, }, - Stash(Stash), + Stash(StashArgs), #[command(external_subcommand)] External(Vec<OsString>), } @@ -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<StashCommands>, #[command(flatten)] - push: StashPush, + push: StashPushArgs, } #[derive(Debug, Subcommand)] enum StashCommands { - Push(StashPush), + Push(StashPushArgs), Pop { stash: Option<String> }, Apply { stash: Option<String> }, } #[derive(Debug, Args)] -struct StashPush { +struct StashPushArgs { #[arg(short, long)] message: Option<String>, } @@ -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::<Vec<_>>(); - 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::<String>("STASH"); - println!("Applying {:?}", stash); + println!("Applying {stash:?}"); } ("pop", sub_matches) => { let stash = sub_matches.get_one::<String>("STASH"); - println!("Popping {:?}", stash); + println!("Popping {stash:?}"); } ("push", sub_matches) => { let message = sub_matches.get_one::<String>("message"); - println!("Pushing {:?}", message); + println!("Pushing {message:?}"); } (name, _) => { unreachable!("Unsupported subcommand `{}`", name) @@ -128,9 +128,9 @@ fn main() { .into_iter() .flatten() .collect::<Vec<_>>(); - 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::<String>("info") { let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", "); - println!("Retrieving info for {}...", comma_sep); + println!("Retrieving info for {comma_sep}..."); } else if let Some(queries) = query_matches.get_many::<String>("search") { let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", "); - println!("Searching Locally for {}...", comma_sep); + 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<String>, } 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<usize> = 1..=65535; fn port_in_range(s: &str) -> Result<u16, String> { let port: usize = s .parse() - .map_err(|_| format!("`{}` isn't a port number", s))?; + .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<String>, + + /// some special input argument + #[arg(long, group = "input")] + spec_in: Option<String>, + + #[arg(short, requires = "input")] + config: Option<String>, +} + +#[derive(Args)] +#[group(required = true, multiple = false)] +struct Vers { /// set version manually #[arg(long, value_name = "VER")] set_ver: Option<String>, @@ -23,17 +36,6 @@ struct Cli { /// auto inc patch #[arg(long)] patch: bool, - - /// some regular input - #[arg(group = "input")] - input_file: Option<String>, - - /// some special input argument - #[arg(long, group = "input")] - spec_in: Option<String>, - - #[arg(short, requires = "input")] - config: Option<String>, } fn main() { @@ -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 = <expr>`: [`ArgGroup::id`][crate::ArgGroup::id] +//! - When not present: struct's name is used +//! - `skip [= <expr>]`: Ignore this field, filling in with `<expr>` +//! - Without `<expr>`: fills the field with `Default::default()` //! //! ### Arg Attributes //! @@ -205,7 +212,7 @@ //! //! **Magic attributes**: //! - `id = <expr>`: [`Arg::id`][crate::Arg::id] -//! - When not present: case-converted field name is used +//! - When not present: field's name is used //! - `value_parser [= <expr>]`: [`Arg::value_parser`][crate::Arg::value_parser] //! - When not present: will auto-select an implementation based on the field type using //! [`value_parser!`][crate::value_parser!] @@ -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<T>`) 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<Vec<T>>` will be `None` instead of `vec![]` if no arguments are provided. //! - This gives the user some flexibility in designing their argument, like with `num_args(0..)` //! 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<dyn ...>` -pub enum ArgAction { - /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches] - /// - /// **NOTE:** If the argument has previously been seen, it will result in a - /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless - /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::Set) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(), - /// vec!["value"] - /// ); - /// ``` - Set, - /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::Append) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value1", "--flag", "value2"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(), - /// vec!["value1", "value2"] - /// ); - /// ``` - Append, - /// When encountered, act as if `"true"` was encountered on the command-line - /// - /// If no [`default_value`][super::Arg::default_value] is set, it will be `false`. - /// - /// No value is allowed. To optionally accept a value, see - /// [`Arg::default_missing_value`][super::Arg::default_missing_value] - /// - /// **NOTE:** If the argument has previously been seen, it will result in a - /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless - /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::SetTrue) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_flag("flag"), - /// true - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_flag("flag"), - /// false - /// ); - /// ``` - /// - /// You can use [`TypedValueParser::map`][crate::builder::TypedValueParser::map] to have the - /// flag control an application-specific type: - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// # use clap::builder::TypedValueParser as _; - /// # use clap::builder::BoolishValueParser; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::SetTrue) - /// .value_parser( - /// BoolishValueParser::new() - /// .map(|b| -> usize { - /// if b { 10 } else { 5 } - /// }) - /// ) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_one::<usize>("flag").copied(), - /// Some(10) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_one::<usize>("flag").copied(), - /// Some(5) - /// ); - /// ``` - SetTrue, - /// When encountered, act as if `"false"` was encountered on the command-line - /// - /// If no [`default_value`][super::Arg::default_value] is set, it will be `true`. - /// - /// No value is allowed. To optionally accept a value, see - /// [`Arg::default_missing_value`][super::Arg::default_missing_value] - /// - /// **NOTE:** If the argument has previously been seen, it will result in a - /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless - /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::SetFalse) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_flag("flag"), - /// false - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_flag("flag"), - /// true - /// ); - /// ``` - SetFalse, - /// When encountered, increment a `u8` counter - /// - /// If no [`default_value`][super::Arg::default_value] is set, it will be `0`. - /// - /// No value is allowed. To optionally accept a value, see - /// [`Arg::default_missing_value`][super::Arg::default_missing_value] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::Count) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_count("flag"), - /// 2 - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_count("flag"), - /// 0 - /// ); - /// ``` - Count, - /// When encountered, display [`Command::print_help`][super::Command::print_help] - /// - /// Depending on the flag, [`Command::print_long_help`][super::Command::print_long_help] may be shown - /// - /// # Examples - /// - #[cfg_attr(not(feature = "help"), doc = " ```ignore")] - #[cfg_attr(feature = "help", doc = " ```")] - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("special-help") - /// .short('?') - /// .action(clap::ArgAction::Help) - /// ); - /// - /// // Existing help still exists - /// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); - /// - /// // New help available - /// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); - /// ``` - Help, - /// When encountered, display [`Command::version`][super::Command::version] - /// - /// Depending on the flag, [`Command::long_version`][super::Command::long_version] may be shown - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .version("1.0.0") - /// .arg( - /// Arg::new("special-version") - /// .long("special-version") - /// .action(clap::ArgAction::Version) - /// ); - /// - /// // Existing help still exists - /// let err = cmd.clone().try_get_matches_from(["mycmd", "--version"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion); - /// - /// // New help available - /// let err = cmd.try_get_matches_from(["mycmd", "--special-version"]).unwrap_err(); - /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion); - /// ``` - Version, -} - -impl ArgAction { - /// Returns whether this action accepts values on the command-line - /// - /// [`default_values`][super::Arg::default_values] and [`env`][super::Arg::env] may still be - /// processed. - pub fn takes_values(&self) -> bool { - match self { - Self::Set => true, - Self::Append => true, - Self::SetTrue => false, - Self::SetFalse => false, - Self::Count => false, - Self::Help => false, - Self::Version => false, - } - } - - pub(crate) fn default_value(&self) -> Option<&'static std::ffi::OsStr> { - match self { - Self::Set => None, - Self::Append => None, - Self::SetTrue => Some(std::ffi::OsStr::new("false")), - Self::SetFalse => Some(std::ffi::OsStr::new("true")), - Self::Count => Some(std::ffi::OsStr::new("0")), - Self::Help => None, - Self::Version => None, - } - } - - pub(crate) fn default_missing_value(&self) -> Option<&'static std::ffi::OsStr> { - match self { - Self::Set => None, - Self::Append => None, - Self::SetTrue => Some(std::ffi::OsStr::new("true")), - Self::SetFalse => Some(std::ffi::OsStr::new("false")), - Self::Count => None, - Self::Help => None, - Self::Version => None, - } - } - - pub(crate) fn default_value_parser(&self) -> Option<super::ValueParser> { - match self { - Self::Set => None, - Self::Append => None, - Self::SetTrue => Some(super::ValueParser::bool()), - Self::SetFalse => Some(super::ValueParser::bool()), - Self::Count => Some(crate::value_parser!(u8).into()), - Self::Help => None, - Self::Version => None, - } - } - - #[cfg(debug_assertions)] - pub(crate) fn value_type_id(&self) -> Option<crate::parser::AnyValueId> { - use crate::parser::AnyValueId; - - match self { - Self::Set => None, - Self::Append => None, - Self::SetTrue => None, - Self::SetFalse => None, - Self::Count => Some(AnyValueId::of::<CountType>()), - Self::Help => None, - Self::Version => None, - } - } -} - -pub(crate) type CountType = u8; diff --git a/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 <FILE> "Provides an input file to the program"); -/// ``` -#[derive(Default, Clone)] -pub struct Arg { - pub(crate) id: Id, - pub(crate) help: Option<StyledStr>, - pub(crate) long_help: Option<StyledStr>, - pub(crate) action: Option<ArgAction>, - pub(crate) value_parser: Option<super::ValueParser>, - pub(crate) blacklist: Vec<Id>, - pub(crate) settings: ArgFlags, - pub(crate) overrides: Vec<Id>, - pub(crate) groups: Vec<Id>, - pub(crate) requires: Vec<(ArgPredicate, Id)>, - pub(crate) r_ifs: Vec<(Id, OsStr)>, - pub(crate) r_ifs_all: Vec<(Id, OsStr)>, - pub(crate) r_unless: Vec<Id>, - pub(crate) r_unless_all: Vec<Id>, - pub(crate) short: Option<char>, - pub(crate) long: Option<Str>, - pub(crate) aliases: Vec<(Str, bool)>, // (name, visible) - pub(crate) short_aliases: Vec<(char, bool)>, // (name, visible) - pub(crate) disp_ord: Option<usize>, - pub(crate) val_names: Vec<Str>, - pub(crate) num_vals: Option<ValueRange>, - pub(crate) val_delim: Option<char>, - pub(crate) default_vals: Vec<OsStr>, - pub(crate) default_vals_ifs: Vec<(Id, ArgPredicate, Option<OsStr>)>, - pub(crate) default_missing_vals: Vec<OsStr>, - #[cfg(feature = "env")] - pub(crate) env: Option<(OsStr, Option<OsString>)>, - pub(crate) terminator: Option<Str>, - pub(crate) index: Option<usize>, - pub(crate) help_heading: Option<Option<Str>>, - pub(crate) value_hint: Option<ValueHint>, -} - -/// # Basic API -impl Arg { - /// Create a new [`Arg`] with a unique name. - /// - /// The name is used to check whether or not the argument was used at - /// runtime, get values, set relationships with other args, etc.. - /// - /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::action(ArgAction::Set)`]) - /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also - /// be displayed when the user prints the usage/help information of the program. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("config") - /// # ; - /// ``` - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - pub fn new(id: impl Into<Id>) -> Self { - Arg::default().id(id) - } - - /// Set the identifier used for referencing this argument in the clap API. - /// - /// See [`Arg::new`] for more details. - #[must_use] - pub fn id(mut self, id: impl Into<Id>) -> Self { - self.id = id.into(); - self - } - - /// Sets the short version of the argument without the preceding `-`. - /// - /// By default `V` and `h` are used by the auto-generated `version` and `help` arguments, - /// respectively. You will need to disable the auto-generated flags - /// ([`disable_help_flag`][crate::Command::disable_help_flag], - /// [`disable_version_flag`][crate::Command::disable_version_flag]) and define your own. - /// - /// # Examples - /// - /// When calling `short`, use a single valid UTF-8 character which will allow using the - /// argument via a single hyphen (`-`) such as `-c`: - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("config") - /// .short('c') - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "-c", "file.toml" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("config").map(String::as_str), Some("file.toml")); - /// ``` - /// - /// To use `-h` for your own flag and still have help: - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .disable_help_flag(true) - /// .arg(Arg::new("host") - /// .short('h') - /// .long("host")) - /// .arg(Arg::new("help") - /// .long("help") - /// .global(true) - /// .action(ArgAction::Help)) - /// .get_matches_from(vec![ - /// "prog", "-h", "wikipedia.org" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("host").map(String::as_str), Some("wikipedia.org")); - /// ``` - #[inline] - #[must_use] - pub fn short(mut self, s: impl IntoResettable<char>) -> Self { - if let Some(s) = s.into_resettable().into_option() { - debug_assert!(s != '-', "short option name cannot be `-`"); - self.short = Some(s); - } else { - self.short = None; - } - self - } - - /// Sets the long version of the argument without the preceding `--`. - /// - /// By default `version` and `help` are used by the auto-generated `version` and `help` - /// arguments, respectively. You may use the word `version` or `help` for the long form of your - /// own arguments, in which case `clap` simply will not assign those to the auto-generated - /// `version` or `help` arguments. - /// - /// **NOTE:** Any leading `-` characters will be stripped - /// - /// # Examples - /// - /// To set `long` use a word containing valid UTF-8. If you supply a double leading - /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however, - /// will *not* be stripped (i.e. `config-file` is allowed). - /// - /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config` - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "--config", "file.toml" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("cfg").map(String::as_str), Some("file.toml")); - /// ``` - #[inline] - #[must_use] - pub fn long(mut self, l: impl IntoResettable<Str>) -> Self { - self.long = l.into_resettable().into_option(); - self - } - - /// Add an alias, which functions as a hidden long flag. - /// - /// This is more efficient, and easier than creating multiple hidden arguments as one only - /// needs to check for the existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .alias("alias") - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "--alias", "cool" - /// ]); - /// assert_eq!(m.get_one::<String>("test").unwrap(), "cool"); - /// ``` - #[must_use] - pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.aliases.push((name, false)); - } else { - self.aliases.clear(); - } - self - } - - /// Add an alias, which functions as a hidden short flag. - /// - /// This is more efficient, and easier than creating multiple hidden arguments as one only - /// needs to check for the existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .short('t') - /// .short_alias('e') - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "-e", "cool" - /// ]); - /// assert_eq!(m.get_one::<String>("test").unwrap(), "cool"); - /// ``` - #[must_use] - pub fn short_alias(mut self, name: impl IntoResettable<char>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - debug_assert!(name != '-', "short alias name cannot be `-`"); - self.short_aliases.push((name, false)); - } else { - self.short_aliases.clear(); - } - self - } - - /// Add aliases, which function as hidden long flags. - /// - /// This is more efficient, and easier than creating multiple hidden subcommands as one only - /// needs to check for the existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .aliases(["do-stuff", "do-tests", "tests"]) - /// .action(ArgAction::SetTrue) - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec![ - /// "prog", "--do-tests" - /// ]); - /// assert_eq!(m.get_flag("test"), true); - /// ``` - #[must_use] - pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - self.aliases - .extend(names.into_iter().map(|x| (x.into(), false))); - self - } - - /// Add aliases, which functions as a hidden short flag. - /// - /// This is more efficient, and easier than creating multiple hidden subcommands as one only - /// needs to check for the existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .short('t') - /// .short_aliases(['e', 's']) - /// .action(ArgAction::SetTrue) - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec![ - /// "prog", "-s" - /// ]); - /// assert_eq!(m.get_flag("test"), true); - /// ``` - #[must_use] - pub fn short_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self { - for s in names { - debug_assert!(s != '-', "short alias name cannot be `-`"); - self.short_aliases.push((s, false)); - } - self - } - - /// Add an alias, which functions as a visible long flag. - /// - /// Like [`Arg::alias`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .visible_alias("something-awesome") - /// .long("test") - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "--something-awesome", "coffee" - /// ]); - /// assert_eq!(m.get_one::<String>("test").unwrap(), "coffee"); - /// ``` - /// [`Command::alias`]: Arg::alias() - #[must_use] - pub fn visible_alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.aliases.push((name, true)); - } else { - self.aliases.clear(); - } - self - } - - /// Add an alias, which functions as a visible short flag. - /// - /// Like [`Arg::short_alias`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .visible_short_alias('t') - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "-t", "coffee" - /// ]); - /// assert_eq!(m.get_one::<String>("test").unwrap(), "coffee"); - /// ``` - #[must_use] - pub fn visible_short_alias(mut self, name: impl IntoResettable<char>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - debug_assert!(name != '-', "short alias name cannot be `-`"); - self.short_aliases.push((name, true)); - } else { - self.short_aliases.clear(); - } - self - } - - /// Add aliases, which function as visible long flags. - /// - /// Like [`Arg::aliases`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .action(ArgAction::SetTrue) - /// .visible_aliases(["something", "awesome", "cool"])) - /// .get_matches_from(vec![ - /// "prog", "--awesome" - /// ]); - /// assert_eq!(m.get_flag("test"), true); - /// ``` - /// [`Command::aliases`]: Arg::aliases() - #[must_use] - pub fn visible_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - self.aliases - .extend(names.into_iter().map(|n| (n.into(), true))); - self - } - - /// Add aliases, which function as visible short flags. - /// - /// Like [`Arg::short_aliases`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("test") - /// .long("test") - /// .action(ArgAction::SetTrue) - /// .visible_short_aliases(['t', 'e'])) - /// .get_matches_from(vec![ - /// "prog", "-t" - /// ]); - /// assert_eq!(m.get_flag("test"), true); - /// ``` - #[must_use] - pub fn visible_short_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self { - for n in names { - debug_assert!(n != '-', "short alias name cannot be `-`"); - self.short_aliases.push((n, true)); - } - self - } - - /// Specifies the index of a positional argument **starting at** 1. - /// - /// **NOTE:** The index refers to position according to **other positional argument**. It does - /// not define position in the argument list as a whole. - /// - /// **NOTE:** You can optionally leave off the `index` method, and the index will be - /// assigned in order of evaluation. Utilizing the `index` method allows for setting - /// indexes out of order - /// - /// **NOTE:** This is only meant to be used for positional arguments and shouldn't to be used - /// with [`Arg::short`] or [`Arg::long`]. - /// - /// **NOTE:** When utilized with [`Arg::num_args(1..)`], only the **last** positional argument - /// may be defined as having a variable number of arguments (i.e. with the highest index) - /// - /// # Panics - /// - /// [`Command`] will [`panic!`] if indexes are skipped (such as defining `index(1)` and `index(3)` - /// but not `index(2)`, or a positional argument is defined as multiple and is not the highest - /// index - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("config") - /// .index(1) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("mode") - /// .index(1)) - /// .arg(Arg::new("debug") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .get_matches_from(vec![ - /// "prog", "--debug", "fast" - /// ]); - /// - /// assert!(m.contains_id("mode")); - /// assert_eq!(m.get_one::<String>("mode").unwrap(), "fast"); // notice index(1) means "first positional" - /// // *not* first argument - /// ``` - /// [`Arg::short`]: Arg::short() - /// [`Arg::long`]: Arg::long() - /// [`Arg::num_args(true)`]: Arg::num_args() - /// [`Command`]: crate::Command - #[inline] - #[must_use] - pub fn index(mut self, idx: impl IntoResettable<usize>) -> Self { - self.index = idx.into_resettable().into_option(); - self - } - - /// This is a "VarArg" and everything that follows should be captured by it, as if the user had - /// used a `--`. - /// - /// **NOTE:** To start the trailing "VarArg" on unknown flags (and not just a positional - /// value), set [`allow_hyphen_values`][Arg::allow_hyphen_values]. Either way, users still - /// have the option to explicitly escape ambiguous arguments with `--`. - /// - /// **NOTE:** [`Arg::value_delimiter`] still applies if set. - /// - /// **NOTE:** Setting this requires [`Arg::num_args(..)`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, arg}; - /// let m = Command::new("myprog") - /// .arg(arg!(<cmd> ... "commands to run").trailing_var_arg(true)) - /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]); - /// - /// let trail: Vec<_> = m.get_many::<String>("cmd").unwrap().collect(); - /// assert_eq!(trail, ["arg1", "-r", "val1"]); - /// ``` - /// [`Arg::num_args(..)`]: crate::Arg::num_args() - pub fn trailing_var_arg(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::TrailingVarArg) - } else { - self.unset_setting(ArgSettings::TrailingVarArg) - } - } - - /// This arg is the last, or final, positional argument (i.e. has the highest - /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args -- - /// last_arg`). - /// - /// Even, if no other arguments are left to parse, if the user omits the `--` syntax - /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also - /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with - /// the `--` syntax is otherwise not possible. - /// - /// **NOTE:** This will change the usage string to look like `$ prog [OPTIONS] [-- <ARG>]` if - /// `ARG` is marked as `.last(true)`. - /// - /// **NOTE:** This setting will imply [`crate::Command::dont_collapse_args_in_usage`] because failing - /// to set this can make the usage string very confusing. - /// - /// **NOTE**: This setting only applies to positional arguments, and has no effect on OPTIONS - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// **CAUTION:** Using this setting *and* having child subcommands is not - /// recommended with the exception of *also* using - /// [`crate::Command::args_conflicts_with_subcommands`] - /// (or [`crate::Command::subcommand_negates_reqs`] if the argument marked `Last` is also - /// marked [`Arg::required`]) - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Arg, ArgAction}; - /// Arg::new("args") - /// .action(ArgAction::Set) - /// .last(true) - /// # ; - /// ``` - /// - /// Setting `last` ensures the arg has the highest [index] of all positional args - /// and requires that the `--` syntax be used to access it early. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("first")) - /// .arg(Arg::new("second")) - /// .arg(Arg::new("third") - /// .action(ArgAction::Set) - /// .last(true)) - /// .try_get_matches_from(vec![ - /// "prog", "one", "--", "three" - /// ]); - /// - /// assert!(res.is_ok()); - /// let m = res.unwrap(); - /// assert_eq!(m.get_one::<String>("third").unwrap(), "three"); - /// assert_eq!(m.get_one::<String>("second"), None); - /// ``` - /// - /// Even if the positional argument marked `Last` is the only argument left to parse, - /// failing to use the `--` syntax results in an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("first")) - /// .arg(Arg::new("second")) - /// .arg(Arg::new("third") - /// .action(ArgAction::Set) - /// .last(true)) - /// .try_get_matches_from(vec![ - /// "prog", "one", "two", "three" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - /// [index]: Arg::index() - /// [`UnknownArgument`]: crate::error::ErrorKind::UnknownArgument - #[inline] - #[must_use] - pub fn last(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Last) - } else { - self.unset_setting(ArgSettings::Last) - } - } - - /// Specifies that the argument must be present. - /// - /// Required by default means it is required, when no other conflicting rules or overrides have - /// been evaluated. Conflicting rules take precedence over being required. - /// - /// **Pro tip:** Flags (i.e. not positional, or arguments that take values) shouldn't be - /// required by default. This is because if a flag were to be required, it should simply be - /// implied. No additional information is required from user. Flags by their very nature are - /// simply boolean on/off switches. The only time a user *should* be required to use a flag - /// is if the operation is destructive in nature, and the user is essentially proving to you, - /// "Yes, I know what I'm doing." - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required(true) - /// # ; - /// ``` - /// - /// Setting required requires that the argument be used at runtime. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required(true) - /// .action(ArgAction::Set) - /// .long("config")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf", - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting required and then *not* supplying that argument at runtime is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required(true) - /// .action(ArgAction::Set) - /// .long("config")) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - #[inline] - #[must_use] - pub fn required(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Required) - } else { - self.unset_setting(ArgSettings::Required) - } - } - - /// Sets an argument that is required when this one is present - /// - /// i.e. when using this argument, the following argument *must* be present. - /// - /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .requires("input") - /// # ; - /// ``` - /// - /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the - /// defining argument is used. If the defining argument isn't used, the other argument isn't - /// required - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .requires("input") - /// .long("config")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required - /// ``` - /// - /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .requires("input") - /// .long("config")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [override]: Arg::overrides_with() - #[must_use] - pub fn requires(mut self, arg_id: impl IntoResettable<Id>) -> Self { - if let Some(arg_id) = arg_id.into_resettable().into_option() { - self.requires.push((ArgPredicate::IsPresent, arg_id)); - } else { - self.requires.clear(); - } - self - } - - /// This argument must be passed alone; it conflicts with all other arguments. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .exclusive(true) - /// # ; - /// ``` - /// - /// Setting an exclusive argument and having any other arguments present at runtime - /// is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("exclusive") - /// .action(ArgAction::Set) - /// .exclusive(true) - /// .long("exclusive")) - /// .arg(Arg::new("debug") - /// .long("debug")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog", "--exclusive", "file.conf", "file.txt" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); - /// ``` - #[inline] - #[must_use] - pub fn exclusive(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Exclusive) - } else { - self.unset_setting(ArgSettings::Exclusive) - } - } - - /// Specifies that an argument can be matched to all child [`Subcommand`]s. - /// - /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however - /// their values once a user uses them will be propagated back up to parents. In effect, this - /// means one should *define* all global arguments at the top level, however it doesn't matter - /// where the user *uses* the global argument. - /// - /// # Examples - /// - /// Assume an application with two subcommands, and you'd like to define a - /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't - /// want to clutter the source with three duplicate [`Arg`] definitions. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("verb") - /// .long("verbose") - /// .short('v') - /// .action(ArgAction::SetTrue) - /// .global(true)) - /// .subcommand(Command::new("test")) - /// .subcommand(Command::new("do-stuff")) - /// .get_matches_from(vec![ - /// "prog", "do-stuff", "--verbose" - /// ]); - /// - /// assert_eq!(m.subcommand_name(), Some("do-stuff")); - /// let sub_m = m.subcommand_matches("do-stuff").unwrap(); - /// assert_eq!(sub_m.get_flag("verb"), true); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - #[inline] - #[must_use] - pub fn global(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Global) - } else { - self.unset_setting(ArgSettings::Global) - } - } - - #[inline] - pub(crate) fn is_set(&self, s: ArgSettings) -> bool { - self.settings.is_set(s) - } - - #[inline] - #[must_use] - pub(crate) fn setting<F>(mut self, setting: F) -> Self - where - F: Into<ArgFlags>, - { - self.settings.insert(setting.into()); - self - } - - #[inline] - #[must_use] - pub(crate) fn unset_setting<F>(mut self, setting: F) -> Self - where - F: Into<ArgFlags>, - { - self.settings.remove(setting.into()); - self - } -} - -/// # Value Handling -impl Arg { - /// Specify how to react to an argument when parsing it. - /// - /// [ArgAction][crate::ArgAction] controls things like - /// - Overwriting previous values with new ones - /// - Appending new values to all previous ones - /// - Counting how many times a flag occurs - /// - /// The default action is `ArgAction::Set` - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::Append) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(), - /// vec!["value"] - /// ); - /// ``` - #[inline] - #[must_use] - pub fn action(mut self, action: impl IntoResettable<ArgAction>) -> Self { - self.action = action.into_resettable().into_option(); - self - } - - /// Specify the typed behavior of the argument. - /// - /// This allows parsing and validating a value before storing it into - /// [`ArgMatches`][crate::ArgMatches] as the given type. - /// - /// Possible value parsers include: - /// - [`value_parser!(T)`][crate::value_parser!] for auto-selecting a value parser for a given type - /// - Or [range expressions like `0..=1`][std::ops::RangeBounds] as a shorthand for [`RangedI64ValueParser`][crate::builder::RangedI64ValueParser] - /// - `Fn(&str) -> Result<T, E>` - /// - `[&str]` and [`PossibleValuesParser`][crate::builder::PossibleValuesParser] for static enumerated values - /// - [`BoolishValueParser`][crate::builder::BoolishValueParser], and [`FalseyValueParser`][crate::builder::FalseyValueParser] for alternative `bool` implementations - /// - [`NonEmptyStringValueParser`][crate::builder::NonEmptyStringValueParser] for basic validation for strings - /// - or any other [`TypedValueParser`][crate::builder::TypedValueParser] implementation - /// - /// The default value is [`ValueParser::string`][crate::builder::ValueParser::string]. - /// - /// ```rust - /// # use clap::ArgAction; - /// let mut cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("color") - /// .long("color") - /// .value_parser(["always", "auto", "never"]) - /// .default_value("auto") - /// ) - /// .arg( - /// clap::Arg::new("hostname") - /// .long("hostname") - /// .value_parser(clap::builder::NonEmptyStringValueParser::new()) - /// .action(ArgAction::Set) - /// .required(true) - /// ) - /// .arg( - /// clap::Arg::new("port") - /// .long("port") - /// .value_parser(clap::value_parser!(u16).range(3000..)) - /// .action(ArgAction::Set) - /// .required(true) - /// ); - /// - /// let m = cmd.try_get_matches_from_mut( - /// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"] - /// ).unwrap(); - /// - /// let color: &String = m.get_one("color") - /// .expect("default"); - /// assert_eq!(color, "auto"); - /// - /// let hostname: &String = m.get_one("hostname") - /// .expect("required"); - /// assert_eq!(hostname, "rust-lang.org"); - /// - /// let port: u16 = *m.get_one("port") - /// .expect("required"); - /// assert_eq!(port, 3001); - /// ``` - pub fn value_parser(mut self, parser: impl IntoResettable<super::ValueParser>) -> Self { - self.value_parser = parser.into_resettable().into_option(); - self - } - - /// Specifies the number of arguments parsed per occurrence - /// - /// For example, if you had a `-f <file>` argument where you wanted exactly 3 'files' you would - /// set `.num_args(3)`, and this argument wouldn't be satisfied unless the user - /// provided 3 and only 3 values. - /// - /// Users may specify values for arguments in any of the following methods - /// - /// - Using a space such as `-o value` or `--option value` - /// - Using an equals and no space such as `-o=value` or `--option=value` - /// - Use a short and no space such as `-ovalue` - /// - /// **WARNING:** - /// - /// Setting a variable number of values (e.g. `1..=10`) for an argument without - /// other details can be dangerous in some circumstances. Because multiple values are - /// allowed, `--option val1 val2 val3` is perfectly valid. Be careful when designing a CLI - /// where **positional arguments** or **subcommands** are *also* expected as `clap` will continue - /// parsing *values* until one of the following happens: - /// - /// - It reaches the maximum number of values - /// - It reaches a specific number of values - /// - It finds another flag or option (i.e. something that starts with a `-`) - /// - It reaches the [`Arg::value_terminator`] if set - /// - /// Alternatively, - /// - Use a delimiter between values with [Arg::value_delimiter] - /// - Require a flag occurrence per value with [`ArgAction::Append`] - /// - Require positional arguments to appear after `--` with [`Arg::last`] - /// - /// # Examples - /// - /// Option: - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("mode") - /// .long("mode") - /// .num_args(1)) - /// .get_matches_from(vec![ - /// "prog", "--mode", "fast" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("mode").unwrap(), "fast"); - /// ``` - /// - /// Flag/option hybrid (see also [default_missing_value][Arg::default_missing_value]) - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let cmd = Command::new("prog") - /// .arg(Arg::new("mode") - /// .long("mode") - /// .default_missing_value("slow") - /// .default_value("plaid") - /// .num_args(0..=1)); - /// - /// let m = cmd.clone() - /// .get_matches_from(vec![ - /// "prog", "--mode", "fast" - /// ]); - /// assert_eq!(m.get_one::<String>("mode").unwrap(), "fast"); - /// - /// let m = cmd.clone() - /// .get_matches_from(vec![ - /// "prog", "--mode", - /// ]); - /// assert_eq!(m.get_one::<String>("mode").unwrap(), "slow"); - /// - /// let m = cmd.clone() - /// .get_matches_from(vec![ - /// "prog", - /// ]); - /// assert_eq!(m.get_one::<String>("mode").unwrap(), "plaid"); - /// ``` - /// - /// Tuples - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let cmd = Command::new("prog") - /// .arg(Arg::new("file") - /// .action(ArgAction::Set) - /// .num_args(2) - /// .short('F')); - /// - /// let m = cmd.clone() - /// .get_matches_from(vec![ - /// "prog", "-F", "in-file", "out-file" - /// ]); - /// assert_eq!( - /// m.get_many::<String>("file").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(), - /// vec!["in-file", "out-file"] - /// ); - /// - /// let res = cmd.clone() - /// .try_get_matches_from(vec![ - /// "prog", "-F", "file1" - /// ]); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::WrongNumberOfValues); - /// ``` - /// - /// A common mistake is to define an option which allows multiple values and a positional - /// argument. - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let cmd = Command::new("prog") - /// .arg(Arg::new("file") - /// .action(ArgAction::Set) - /// .num_args(0..) - /// .short('F')) - /// .arg(Arg::new("word")); - /// - /// let m = cmd.clone().get_matches_from(vec![ - /// "prog", "-F", "file1", "file2", "file3", "word" - /// ]); - /// let files: Vec<_> = m.get_many::<String>("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?! - /// assert!(!m.contains_id("word")); // but we clearly used word! - /// - /// // but this works - /// let m = cmd.clone().get_matches_from(vec![ - /// "prog", "word", "-F", "file1", "file2", "file3", - /// ]); - /// let files: Vec<_> = m.get_many::<String>("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// assert_eq!(m.get_one::<String>("word").unwrap(), "word"); - /// ``` - /// The problem is `clap` doesn't know when to stop parsing values for "file". - /// - /// A solution for the example above is to limit how many values with a maximum, or specific - /// number, or to say [`ArgAction::Append`] is ok, but multiple values are not. - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("file") - /// .action(ArgAction::Append) - /// .short('F')) - /// .arg(Arg::new("word")) - /// .get_matches_from(vec![ - /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word" - /// ]); - /// - /// let files: Vec<_> = m.get_many::<String>("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// assert_eq!(m.get_one::<String>("word").unwrap(), "word"); - /// ``` - #[inline] - #[must_use] - pub fn num_args(mut self, qty: impl IntoResettable<ValueRange>) -> Self { - self.num_vals = qty.into_resettable().into_option(); - self - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::num_args`") - )] - pub fn number_of_values(self, qty: usize) -> Self { - self.num_args(qty) - } - - /// Placeholder for the argument's value in the help message / usage. - /// - /// This name is cosmetic only; the name is **not** used to access arguments. - /// This setting can be very helpful when describing the type of input the user should be - /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to - /// use all capital letters for the value name. - /// - /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("cfg") - /// .long("config") - /// .value_name("FILE") - /// # ; - /// ``` - /// - #[cfg_attr(not(feature = "help"), doc = " ```ignore")] - #[cfg_attr(feature = "help", doc = " ```")] - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("config") - /// .long("config") - /// .value_name("FILE") - /// .help("Some help text")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// Running the above program produces the following output - /// - /// ```text - /// valnames - /// - /// Usage: valnames [OPTIONS] - /// - /// Options: - /// --config <FILE> Some help text - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - /// [positional]: Arg::index() - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - #[inline] - #[must_use] - pub fn value_name(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.value_names([name]) - } else { - self.val_names.clear(); - self - } - } - - /// Placeholders for the argument's values in the help message / usage. - /// - /// These names are cosmetic only, used for help and usage strings only. The names are **not** - /// used to access arguments. The values of the arguments are accessed in numeric order (i.e. - /// if you specify two names `one` and `two` `one` will be the first matched value, `two` will - /// be the second). - /// - /// This setting can be very helpful when describing the type of input the user should be - /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to - /// use all capital letters for the value name. - /// - /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or - /// multiple value names in order to not throw off the help text alignment of all options. - /// - /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`] and [`Arg::num_args(1..)`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("speed") - /// .short('s') - /// .value_names(["fast", "slow"]); - /// ``` - /// - #[cfg_attr(not(feature = "help"), doc = " ```ignore")] - #[cfg_attr(feature = "help", doc = " ```")] - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("io") - /// .long("io-files") - /// .value_names(["INFILE", "OUTFILE"])) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// Running the above program produces the following output - /// - /// ```text - /// valnames - /// - /// Usage: valnames [OPTIONS] - /// - /// Options: - /// -h, --help Print help information - /// --io-files <INFILE> <OUTFILE> Some help text - /// -V, --version Print version information - /// ``` - /// [`Arg::next_line_help(true)`]: Arg::next_line_help() - /// [`Arg::num_args`]: Arg::num_args() - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`Arg::num_args(1..)`]: Arg::num_args() - #[must_use] - pub fn value_names(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - self.val_names = names.into_iter().map(|s| s.into()).collect(); - self - } - - /// Provide the shell a hint about how to complete this argument. - /// - /// See [`ValueHint`][crate::ValueHint] for more information. - /// - /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`]. - /// - /// For example, to take a username as argument: - /// - /// ``` - /// # use clap::{Arg, ValueHint}; - /// Arg::new("user") - /// .short('u') - /// .long("user") - /// .value_hint(ValueHint::Username); - /// ``` - /// - /// To take a full command line and its arguments (for example, when writing a command wrapper): - /// - /// ``` - /// # use clap::{Command, Arg, ValueHint, ArgAction}; - /// Command::new("prog") - /// .trailing_var_arg(true) - /// .arg( - /// Arg::new("command") - /// .action(ArgAction::Set) - /// .num_args(1..) - /// .value_hint(ValueHint::CommandWithArguments) - /// ); - /// ``` - #[must_use] - pub fn value_hint(mut self, value_hint: impl IntoResettable<ValueHint>) -> Self { - self.value_hint = value_hint.into_resettable().into_option(); - self - } - - /// Match values against [`PossibleValuesParser`][crate::builder::PossibleValuesParser] without matching case. - /// - /// When other arguments are conditionally required based on the - /// value of a case-insensitive argument, the equality check done - /// by [`Arg::required_if_eq`], [`Arg::required_if_eq_any`], or - /// [`Arg::required_if_eq_all`] is case-insensitive. - /// - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// **NOTE:** To do unicode case folding, enable the `unicode` feature flag. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("pv") - /// .arg(Arg::new("option") - /// .long("option") - /// .action(ArgAction::Set) - /// .ignore_case(true) - /// .value_parser(["test123"])) - /// .get_matches_from(vec![ - /// "pv", "--option", "TeSt123", - /// ]); - /// - /// assert!(m.get_one::<String>("option").unwrap().eq_ignore_ascii_case("test123")); - /// ``` - /// - /// This setting also works when multiple values can be defined: - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("pv") - /// .arg(Arg::new("option") - /// .short('o') - /// .long("option") - /// .action(ArgAction::Set) - /// .ignore_case(true) - /// .num_args(1..) - /// .value_parser(["test123", "test321"])) - /// .get_matches_from(vec![ - /// "pv", "--option", "TeSt123", "teST123", "tESt321" - /// ]); - /// - /// let matched_vals = m.get_many::<String>("option").unwrap().collect::<Vec<_>>(); - /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]); - /// ``` - #[inline] - #[must_use] - pub fn ignore_case(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::IgnoreCase) - } else { - self.unset_setting(ArgSettings::IgnoreCase) - } - } - - /// Allows values which start with a leading hyphen (`-`) - /// - /// To limit values to just numbers, see - /// [`allow_negative_numbers`][Arg::allow_negative_numbers]. - /// - /// See also [`trailing_var_arg`][Arg::trailing_var_arg]. - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// **WARNING:** Prior arguments with `allow_hyphen_values(true)` get precedence over known - /// flags but known flags get precedence over the next possible positional argument with - /// `allow_hyphen_values(true)`. When combined with [`Arg::num_args(..)`], - /// [`Arg::value_terminator`] is one way to ensure processing stops. - /// - /// **WARNING**: Take caution when using this setting combined with another argument using - /// [`Arg::num_args`], as this becomes ambiguous `$ prog --arg -- -- val`. All - /// three `--, --, val` will be values when the user may have thought the second `--` would - /// constitute the normal, "Only positional args follow" idiom. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("pat") - /// .action(ArgAction::Set) - /// .allow_hyphen_values(true) - /// .long("pattern")) - /// .get_matches_from(vec![ - /// "prog", "--pattern", "-file" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("pat").unwrap(), "-file"); - /// ``` - /// - /// Not setting `Arg::allow_hyphen_values(true)` and supplying a value which starts with a - /// hyphen is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("pat") - /// .action(ArgAction::Set) - /// .long("pattern")) - /// .try_get_matches_from(vec![ - /// "prog", "--pattern", "-file" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - /// [`Arg::num_args(1)`]: Arg::num_args() - #[inline] - #[must_use] - pub fn allow_hyphen_values(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::AllowHyphenValues) - } else { - self.unset_setting(ArgSettings::AllowHyphenValues) - } - } - - /// Allows negative numbers to pass as values. - /// - /// This is similar to [`Arg::allow_hyphen_values`] except that it only allows numbers, - /// all other undefined leading hyphens will fail to parse. - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let res = Command::new("myprog") - /// .arg(Arg::new("num").allow_negative_numbers(true)) - /// .try_get_matches_from(vec![ - /// "myprog", "-20" - /// ]); - /// assert!(res.is_ok()); - /// let m = res.unwrap(); - /// assert_eq!(m.get_one::<String>("num").unwrap(), "-20"); - /// ``` - #[inline] - pub fn allow_negative_numbers(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::AllowNegativeNumbers) - } else { - self.unset_setting(ArgSettings::AllowNegativeNumbers) - } - } - - /// Requires that options use the `--option=val` syntax - /// - /// i.e. an equals between the option and associated value. - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// # Examples - /// - /// Setting `require_equals` requires that the option have an equals sign between - /// it and the associated value. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .require_equals(true) - /// .long("config")) - /// .try_get_matches_from(vec![ - /// "prog", "--config=file.conf" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting `require_equals` and *not* supplying the equals will cause an - /// error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .require_equals(true) - /// .long("config")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals); - /// ``` - #[inline] - #[must_use] - pub fn require_equals(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::RequireEquals) - } else { - self.unset_setting(ArgSettings::RequireEquals) - } - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::value_delimiter`") - )] - pub fn use_value_delimiter(mut self, yes: bool) -> Self { - if yes { - self.val_delim.get_or_insert(','); - } else { - self.val_delim = None; - } - self - } - - /// Allow grouping of multiple values via a delimiter. - /// - /// i.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`, - /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the - /// value delimiter for all arguments that accept values (options and positional arguments) - /// - /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("config") - /// .short('c') - /// .long("config") - /// .value_delimiter(',')) - /// .get_matches_from(vec![ - /// "prog", "--config=val1,val2,val3" - /// ]); - /// - /// assert_eq!(m.get_many::<String>("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]) - /// ``` - /// [`Arg::value_delimiter(',')`]: Arg::value_delimiter() - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - #[inline] - #[must_use] - pub fn value_delimiter(mut self, d: impl IntoResettable<char>) -> Self { - self.val_delim = d.into_resettable().into_option(); - self - } - - /// Sentinel to **stop** parsing multiple values of a given argument. - /// - /// By default when - /// one sets [`num_args(1..)`] on an argument, clap will continue parsing values for that - /// argument until it reaches another valid argument, or one of the other more specific settings - /// for multiple values is used (such as [`num_args`]). - /// - /// **NOTE:** This setting only applies to [options] and [positional arguments] - /// - /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one - /// of the values - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// Arg::new("vals") - /// .action(ArgAction::Set) - /// .num_args(1..) - /// .value_terminator(";") - /// # ; - /// ``` - /// - /// The following example uses two arguments, a sequence of commands, and the location in which - /// to perform them - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cmds") - /// .action(ArgAction::Set) - /// .num_args(1..) - /// .allow_hyphen_values(true) - /// .value_terminator(";")) - /// .arg(Arg::new("location")) - /// .get_matches_from(vec![ - /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap" - /// ]); - /// let cmds: Vec<_> = m.get_many::<String>("cmds").unwrap().collect(); - /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]); - /// assert_eq!(m.get_one::<String>("location").unwrap(), "/home/clap"); - /// ``` - /// [options]: Arg::action - /// [positional arguments]: Arg::index() - /// [`num_args(1..)`]: Arg::num_args() - /// [`num_args`]: Arg::num_args() - #[inline] - #[must_use] - pub fn value_terminator(mut self, term: impl IntoResettable<Str>) -> Self { - self.terminator = term.into_resettable().into_option(); - self - } - - /// Consume all following arguments. - /// - /// Do not be parse them individually, but rather pass them in entirety. - /// - /// It is worth noting that setting this requires all values to come after a `--` to indicate - /// they should all be captured. For example: - /// - /// ```text - /// --foo something -- -v -v -v -b -b -b --baz -q -u -x - /// ``` - /// - /// Will result in everything after `--` to be considered one raw argument. This behavior - /// may not be exactly what you are expecting and using [`crate::Command::trailing_var_arg`] - /// may be more appropriate. - /// - /// **NOTE:** Implicitly sets [`Arg::action(ArgAction::Set)`] [`Arg::num_args(1..)`], - /// [`Arg::allow_hyphen_values(true)`], and [`Arg::last(true)`] when set to `true`. - /// - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`Arg::num_args(1..)`]: Arg::num_args() - /// [`Arg::allow_hyphen_values(true)`]: Arg::allow_hyphen_values() - /// [`Arg::last(true)`]: Arg::last() - #[inline] - #[must_use] - pub fn raw(mut self, yes: bool) -> Self { - if yes { - self.num_vals.get_or_insert_with(|| (1..).into()); - } - self.allow_hyphen_values(yes).last(yes) - } - - /// Value for the argument when not present. - /// - /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::contains_id`] will - /// still return `true`. If you wish to determine whether the argument was used at runtime or - /// not, consider [`ArgMatches::value_source`][crate::ArgMatches::value_source]. - /// - /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly - /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg - /// at runtime. `Arg::default_value_if` however only takes effect when the user has not provided - /// a value at runtime **and** these other conditions are met as well. If you have set - /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide this arg - /// at runtime, nor were the conditions met for `Arg::default_value_if`, the `Arg::default_value` - /// will be applied. - /// - /// **NOTE:** This implicitly sets [`Arg::action(ArgAction::Set)`]. - /// - /// # Examples - /// - /// First we use the default value without providing any value at runtime. - /// - /// ```rust - /// # use clap::{Command, Arg, parser::ValueSource}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .long("myopt") - /// .default_value("myval")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("opt").unwrap(), "myval"); - /// assert!(m.contains_id("opt")); - /// assert_eq!(m.value_source("opt"), Some(ValueSource::DefaultValue)); - /// ``` - /// - /// Next we provide a value at runtime to override the default. - /// - /// ```rust - /// # use clap::{Command, Arg, parser::ValueSource}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .long("myopt") - /// .default_value("myval")) - /// .get_matches_from(vec![ - /// "prog", "--myopt=non_default" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("opt").unwrap(), "non_default"); - /// assert!(m.contains_id("opt")); - /// assert_eq!(m.value_source("opt"), Some(ValueSource::CommandLine)); - /// ``` - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`ArgMatches::contains_id`]: crate::ArgMatches::contains_id() - /// [`Arg::default_value_if`]: Arg::default_value_if() - #[inline] - #[must_use] - pub fn default_value(mut self, val: impl IntoResettable<OsStr>) -> Self { - if let Some(val) = val.into_resettable().into_option() { - self.default_values([val]) - } else { - self.default_vals.clear(); - self - } - } - - #[inline] - #[must_use] - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value`") - )] - pub fn default_value_os(self, val: impl Into<OsStr>) -> Self { - self.default_values([val]) - } - - /// Value for the argument when not present. - /// - /// See [`Arg::default_value`]. - /// - /// [`Arg::default_value`]: Arg::default_value() - #[inline] - #[must_use] - pub fn default_values(mut self, vals: impl IntoIterator<Item = impl Into<OsStr>>) -> Self { - self.default_vals = vals.into_iter().map(|s| s.into()).collect(); - self - } - - #[inline] - #[must_use] - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::default_values`") - )] - pub fn default_values_os(self, vals: impl IntoIterator<Item = impl Into<OsStr>>) -> Self { - self.default_values(vals) - } - - /// Value for the argument when the flag is present but no value is specified. - /// - /// This configuration option is often used to give the user a shortcut and allow them to - /// efficiently specify an option argument without requiring an explicitly value. The `--color` - /// argument is a common example. By, supplying an default, such as `default_missing_value("always")`, - /// the user can quickly just add `--color` to the command line to produce the desired color output. - /// - /// **NOTE:** using this configuration option requires the use of the - /// [`.num_args(0..N)`][Arg::num_args] and the - /// [`.require_equals(true)`][Arg::require_equals] configuration option. These are required in - /// order to unambiguously determine what, if any, value was supplied for the argument. - /// - /// # Examples - /// - /// For POSIX style `--color`: - /// ```rust - /// # use clap::{Command, Arg, parser::ValueSource}; - /// fn cli() -> Command { - /// Command::new("prog") - /// .arg(Arg::new("color").long("color") - /// .value_name("WHEN") - /// .value_parser(["always", "auto", "never"]) - /// .default_value("auto") - /// .num_args(0..=1) - /// .require_equals(true) - /// .default_missing_value("always") - /// .help("Specify WHEN to colorize output.") - /// ) - /// } - /// - /// // first, we'll provide no arguments - /// let m = cli().get_matches_from(vec![ - /// "prog" - /// ]); - /// assert_eq!(m.get_one::<String>("color").unwrap(), "auto"); - /// assert_eq!(m.value_source("color"), Some(ValueSource::DefaultValue)); - /// - /// // next, we'll provide a runtime value to override the default (as usually done). - /// let m = cli().get_matches_from(vec![ - /// "prog", "--color=never" - /// ]); - /// assert_eq!(m.get_one::<String>("color").unwrap(), "never"); - /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine)); - /// - /// // finally, we will use the shortcut and only provide the argument without a value. - /// let m = cli().get_matches_from(vec![ - /// "prog", "--color" - /// ]); - /// assert_eq!(m.get_one::<String>("color").unwrap(), "always"); - /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine)); - /// ``` - /// - /// For bool literals: - /// ```rust - /// # use clap::{Command, Arg, parser::ValueSource, value_parser}; - /// fn cli() -> Command { - /// Command::new("prog") - /// .arg(Arg::new("create").long("create") - /// .value_name("BOOL") - /// .value_parser(value_parser!(bool)) - /// .num_args(0..=1) - /// .require_equals(true) - /// .default_missing_value("true") - /// ) - /// } - /// - /// // first, we'll provide no arguments - /// let m = cli().get_matches_from(vec![ - /// "prog" - /// ]); - /// assert_eq!(m.get_one::<bool>("create").copied(), None); - /// - /// // next, we'll provide a runtime value to override the default (as usually done). - /// let m = cli().get_matches_from(vec![ - /// "prog", "--create=false" - /// ]); - /// assert_eq!(m.get_one::<bool>("create").copied(), Some(false)); - /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine)); - /// - /// // finally, we will use the shortcut and only provide the argument without a value. - /// let m = cli().get_matches_from(vec![ - /// "prog", "--create" - /// ]); - /// assert_eq!(m.get_one::<bool>("create").copied(), Some(true)); - /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine)); - /// ``` - /// - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`Arg::default_value`]: Arg::default_value() - #[inline] - #[must_use] - pub fn default_missing_value(mut self, val: impl IntoResettable<OsStr>) -> Self { - if let Some(val) = val.into_resettable().into_option() { - self.default_missing_values_os([val]) - } else { - self.default_missing_vals.clear(); - self - } - } - - /// Value for the argument when the flag is present but no value is specified. - /// - /// See [`Arg::default_missing_value`]. - /// - /// [`Arg::default_missing_value`]: Arg::default_missing_value() - /// [`OsStr`]: std::ffi::OsStr - #[inline] - #[must_use] - pub fn default_missing_value_os(self, val: impl Into<OsStr>) -> Self { - self.default_missing_values_os([val]) - } - - /// Value for the argument when the flag is present but no value is specified. - /// - /// See [`Arg::default_missing_value`]. - /// - /// [`Arg::default_missing_value`]: Arg::default_missing_value() - #[inline] - #[must_use] - pub fn default_missing_values(self, vals: impl IntoIterator<Item = impl Into<OsStr>>) -> Self { - self.default_missing_values_os(vals) - } - - /// Value for the argument when the flag is present but no value is specified. - /// - /// See [`Arg::default_missing_values`]. - /// - /// [`Arg::default_missing_values`]: Arg::default_missing_values() - /// [`OsStr`]: std::ffi::OsStr - #[inline] - #[must_use] - pub fn default_missing_values_os( - mut self, - vals: impl IntoIterator<Item = impl Into<OsStr>>, - ) -> Self { - self.default_missing_vals = vals.into_iter().map(|s| s.into()).collect(); - self - } - - /// Read from `name` environment variable when argument is not present. - /// - /// If it is not present in the environment, then default - /// rules will apply. - /// - /// If user sets the argument in the environment: - /// - When [`Arg::action(ArgAction::Set)`] is not set, the flag is considered raised. - /// - When [`Arg::action(ArgAction::Set)`] is set, - /// [`ArgMatches::get_one`][crate::ArgMatches::get_one] will - /// return value of the environment variable. - /// - /// If user doesn't set the argument in the environment: - /// - When [`Arg::action(ArgAction::Set)`] is not set, the flag is considered off. - /// - When [`Arg::action(ArgAction::Set)`] is set, - /// [`ArgMatches::get_one`][crate::ArgMatches::get_one] will - /// return the default specified. - /// - /// # Examples - /// - /// In this example, we show the variable coming from the environment: - /// - /// ```rust - /// # use std::env; - /// # use clap::{Command, Arg, ArgAction}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .env("MY_FLAG") - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("flag").unwrap(), "env"); - /// ``` - /// - /// In this example, because `prog` is a flag that accepts an optional, case-insensitive - /// boolean literal. - /// - /// Note that the value parser controls how flags are parsed. In this case we've selected - /// [`FalseyValueParser`][crate::builder::FalseyValueParser]. A `false` literal is `n`, `no`, - /// `f`, `false`, `off` or `0`. An absent environment variable will also be considered as - /// `false`. Anything else will considered as `true`. - /// - /// ```rust - /// # use std::env; - /// # use clap::{Command, Arg, ArgAction}; - /// # use clap::builder::FalseyValueParser; - /// - /// env::set_var("TRUE_FLAG", "true"); - /// env::set_var("FALSE_FLAG", "0"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("true_flag") - /// .long("true_flag") - /// .action(ArgAction::SetTrue) - /// .value_parser(FalseyValueParser::new()) - /// .env("TRUE_FLAG")) - /// .arg(Arg::new("false_flag") - /// .long("false_flag") - /// .action(ArgAction::SetTrue) - /// .value_parser(FalseyValueParser::new()) - /// .env("FALSE_FLAG")) - /// .arg(Arg::new("absent_flag") - /// .long("absent_flag") - /// .action(ArgAction::SetTrue) - /// .value_parser(FalseyValueParser::new()) - /// .env("ABSENT_FLAG")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(m.get_flag("true_flag")); - /// assert!(!m.get_flag("false_flag")); - /// assert!(!m.get_flag("absent_flag")); - /// ``` - /// - /// In this example, we show the variable coming from an option on the CLI: - /// - /// ```rust - /// # use std::env; - /// # use clap::{Command, Arg, ArgAction}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .env("MY_FLAG") - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "prog", "--flag", "opt" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("flag").unwrap(), "opt"); - /// ``` - /// - /// In this example, we show the variable coming from the environment even with the - /// presence of a default: - /// - /// ```rust - /// # use std::env; - /// # use clap::{Command, Arg, ArgAction}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .env("MY_FLAG") - /// .action(ArgAction::Set) - /// .default_value("default")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("flag").unwrap(), "env"); - /// ``` - /// - /// In this example, we show the use of multiple values in a single environment variable: - /// - /// ```rust - /// # use std::env; - /// # use clap::{Command, Arg, ArgAction}; - /// - /// env::set_var("MY_FLAG_MULTI", "env1,env2"); - /// - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .env("MY_FLAG_MULTI") - /// .action(ArgAction::Set) - /// .num_args(1..) - /// .value_delimiter(',')) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.get_many::<String>("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]); - /// ``` - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`Arg::value_delimiter(',')`]: Arg::value_delimiter() - #[cfg(feature = "env")] - #[inline] - #[must_use] - pub fn env(mut self, name: impl IntoResettable<OsStr>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - let value = env::var_os(&name); - self.env = Some((name, value)); - } else { - self.env = None; - } - self - } - - #[cfg(feature = "env")] - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::env`") - )] - pub fn env_os(self, name: impl Into<OsStr>) -> Self { - self.env(name) - } -} - -/// # Help -impl Arg { - /// Sets the description of the argument for short help (`-h`). - /// - /// Typically, this is a short (one line) description of the arg. - /// - /// If [`Arg::long_help`] is not specified, this message will be displayed for `--help`. - /// - /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise - /// - /// # Examples - /// - /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to - /// include a newline in the help text and have the following text be properly aligned with all - /// the other help text. - /// - /// Setting `help` displays a short message to the side of the argument when the user passes - /// `-h` or `--help` (by default). - /// - #[cfg_attr(not(feature = "help"), doc = " ```ignore")] - #[cfg_attr(feature = "help", doc = " ```")] - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```notrust - /// helptest - /// - /// Usage: helptest [OPTIONS] - /// - /// Options: - /// --config Some help text describing the --config arg - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - /// [`Arg::long_help`]: Arg::long_help() - #[inline] - #[must_use] - pub fn help(mut self, h: impl IntoResettable<StyledStr>) -> Self { - self.help = h.into_resettable().into_option(); - self - } - - /// Sets the description of the argument for long help (`--help`). - /// - /// Typically this a more detailed (multi-line) message - /// that describes the arg. - /// - /// If [`Arg::help`] is not specified, this message will be displayed for `-h`. - /// - /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise - /// - /// # Examples - /// - /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to - /// include a newline in the help text and have the following text be properly aligned with all - /// the other help text. - /// - /// Setting `help` displays a short message to the side of the argument when the user passes - /// `-h` or `--help` (by default). - /// - #[cfg_attr(not(feature = "help"), doc = " ```ignore")] - #[cfg_attr(feature = "help", doc = " ```")] - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .long_help( - /// "The config file used by the myprog must be in JSON format - /// with only valid keys and may not contain other nonsense - /// that cannot be read by this program. Obviously I'm going on - /// and on, so I'll stop now.")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```text - /// prog - /// - /// Usage: prog [OPTIONS] - /// - /// Options: - /// --config - /// The config file used by the myprog must be in JSON format - /// with only valid keys and may not contain other nonsense - /// that cannot be read by this program. Obviously I'm going on - /// and on, so I'll stop now. - /// - /// -h, --help - /// Print help information - /// - /// -V, --version - /// Print version information - /// ``` - /// [`Arg::help`]: Arg::help() - #[inline] - #[must_use] - pub fn long_help(mut self, h: impl IntoResettable<StyledStr>) -> Self { - self.long_help = h.into_resettable().into_option(); - self - } - - /// Allows custom ordering of args within the help message. - /// - /// Args with a lower value will be displayed first in the help message. This is helpful when - /// one would like to emphasise frequently used args, or prioritize those towards the top of - /// the list. Args with duplicate display orders will be displayed in 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 <b> I should be first! - /// -o, --long-option <a> Some help and text - /// ``` - /// [positional arguments]: Arg::index() - /// [index]: Arg::index() - #[inline] - #[must_use] - pub fn display_order(mut self, ord: impl IntoResettable<usize>) -> Self { - self.disp_ord = ord.into_resettable().into_option(); - self - } - - /// Override the [current] help section. - /// - /// [current]: crate::Command::next_help_heading - #[inline] - #[must_use] - pub fn help_heading(mut self, heading: impl IntoResettable<Str>) -> Self { - self.help_heading = Some(heading.into_resettable().into_option()); - self - } - - /// Render the [help][Arg::help] on the line after the argument. - /// - /// This can be helpful for arguments with very long or complex help messages. - /// This can also be helpful for arguments with very long flag names, or many/long value names. - /// - /// **NOTE:** To apply this setting to all arguments and subcommands, consider using - /// [`crate::Command::next_line_help`] - /// - /// # Examples - /// - #[cfg_attr(not(feature = "help"), doc = " ```ignore")] - #[cfg_attr(feature = "help", doc = " ```")] - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .long("long-option-flag") - /// .short('o') - /// .action(ArgAction::Set) - /// .next_line_help(true) - /// .value_names(["value1", "value2"]) - /// .help("Some really long help and complex\n\ - /// help that makes more sense to be\n\ - /// on a line after the option")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays the following help message - /// - /// ```text - /// nlh - /// - /// Usage: nlh [OPTIONS] - /// - /// Options: - /// -h, --help Print help information - /// -V, --version Print version information - /// -o, --long-option-flag <value1> <value2> - /// Some really long help and complex - /// help that makes more sense to be - /// on a line after the option - /// ``` - #[inline] - #[must_use] - pub fn next_line_help(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::NextLineHelp) - } else { - self.unset_setting(ArgSettings::NextLineHelp) - } - } - - /// Do not display the argument in help message. - /// - /// **NOTE:** This does **not** hide the argument from usage strings on error - /// - /// # Examples - /// - /// Setting `Hidden` will hide the argument when displaying help text - /// - #[cfg_attr(not(feature = "help"), doc = " ```ignore")] - #[cfg_attr(feature = "help", doc = " ```")] - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```text - /// helptest - /// - /// Usage: helptest [OPTIONS] - /// - /// Options: - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - #[inline] - #[must_use] - pub fn hide(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::Hidden) - } else { - self.unset_setting(ArgSettings::Hidden) - } - } - - /// Do not display the [possible values][crate::builder::ValueParser::possible_values] in the help message. - /// - /// This is useful for args with many values, or ones which are explained elsewhere in the - /// help text. - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// To set this for all arguments, see - /// [`Command::hide_possible_values`][crate::Command::hide_possible_values]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("mode") - /// .long("mode") - /// .value_parser(["fast", "slow"]) - /// .action(ArgAction::Set) - /// .hide_possible_values(true)); - /// ``` - /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of - /// the help text would be omitted. - #[inline] - #[must_use] - pub fn hide_possible_values(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HidePossibleValues) - } else { - self.unset_setting(ArgSettings::HidePossibleValues) - } - } - - /// Do not display the default value of the argument in the help message. - /// - /// This is useful when default behavior of an arg is explained elsewhere in the help text. - /// - /// **NOTE:** Setting this requires [taking values][Arg::num_args] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("connect") - /// .arg(Arg::new("host") - /// .long("host") - /// .default_value("localhost") - /// .action(ArgAction::Set) - /// .hide_default_value(true)); - /// - /// ``` - /// - /// If we were to run the above program with `--help` the `[default: localhost]` portion of - /// the help text would be omitted. - #[inline] - #[must_use] - pub fn hide_default_value(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HideDefaultValue) - } else { - self.unset_setting(ArgSettings::HideDefaultValue) - } - } - - /// Do not display in help the environment variable name. - /// - /// This is useful when the variable option is explained elsewhere in the help text. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("mode") - /// .long("mode") - /// .env("MODE") - /// .action(ArgAction::Set) - /// .hide_env(true)); - /// ``` - /// - /// If we were to run the above program with `--help` the `[env: MODE]` portion of the help - /// text would be omitted. - #[cfg(feature = "env")] - #[inline] - #[must_use] - pub fn hide_env(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HideEnv) - } else { - self.unset_setting(ArgSettings::HideEnv) - } - } - - /// Do not display in help any values inside the associated ENV variables for the argument. - /// - /// This is useful when ENV vars contain sensitive values. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("connect") - /// .arg(Arg::new("host") - /// .long("host") - /// .env("CONNECT") - /// .action(ArgAction::Set) - /// .hide_env_values(true)); - /// - /// ``` - /// - /// If we were to run the above program with `$ CONNECT=super_secret connect --help` the - /// `[default: CONNECT=super_secret]` portion of the help text would be omitted. - #[cfg(feature = "env")] - #[inline] - #[must_use] - pub fn hide_env_values(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HideEnvValues) - } else { - self.unset_setting(ArgSettings::HideEnvValues) - } - } - - /// Hides an argument from short help (`-h`). - /// - /// **NOTE:** This does **not** hide the argument from usage strings on error - /// - /// **NOTE:** Setting this option will cause next-line-help output style to be used - /// when long help (`--help`) is called. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Arg::new("debug") - /// .hide_short_help(true); - /// ``` - /// - /// Setting `hide_short_help(true)` will hide the argument when displaying short help text - /// - #[cfg_attr(not(feature = "help"), doc = " ```ignore")] - #[cfg_attr(feature = "help", doc = " ```")] - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide_short_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "-h" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```text - /// helptest - /// - /// Usage: helptest [OPTIONS] - /// - /// Options: - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - /// - /// However, when --help is called - /// - #[cfg_attr(not(feature = "help"), doc = " ```ignore")] - #[cfg_attr(feature = "help", doc = " ```")] - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide_short_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// Then the following would be displayed - /// - /// ```text - /// helptest - /// - /// Usage: helptest [OPTIONS] - /// - /// Options: - /// --config Some help text describing the --config arg - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - #[inline] - #[must_use] - pub fn hide_short_help(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HiddenShortHelp) - } else { - self.unset_setting(ArgSettings::HiddenShortHelp) - } - } - - /// Hides an argument from long help (`--help`). - /// - /// **NOTE:** This does **not** hide the argument from usage strings on error - /// - /// **NOTE:** Setting this option will cause next-line-help output style to be used - /// when long help (`--help`) is called. - /// - /// # Examples - /// - /// Setting `hide_long_help(true)` will hide the argument when displaying long help text - /// - #[cfg_attr(not(feature = "help"), doc = " ```ignore")] - #[cfg_attr(feature = "help", doc = " ```")] - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide_long_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```text - /// helptest - /// - /// Usage: helptest [OPTIONS] - /// - /// Options: - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - /// - /// However, when -h is called - /// - #[cfg_attr(not(feature = "help"), doc = " ```ignore")] - #[cfg_attr(feature = "help", doc = " ```")] - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .long("config") - /// .hide_long_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "-h" - /// ]); - /// ``` - /// - /// Then the following would be displayed - /// - /// ```text - /// helptest - /// - /// Usage: helptest [OPTIONS] - /// - /// OPTIONS: - /// --config Some help text describing the --config arg - /// -h, --help Print help information - /// -V, --version Print version information - /// ``` - #[inline] - #[must_use] - pub fn hide_long_help(self, yes: bool) -> Self { - if yes { - self.setting(ArgSettings::HiddenLongHelp) - } else { - self.unset_setting(ArgSettings::HiddenLongHelp) - } - } -} - -/// # Advanced Argument Relations -impl Arg { - /// The name of the [`ArgGroup`] the argument belongs to. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// Arg::new("debug") - /// .long("debug") - /// .action(ArgAction::SetTrue) - /// .group("mode") - /// # ; - /// ``` - /// - /// Multiple arguments can be a member of a single group and then the group checked as if it - /// was one of said arguments. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("debug") - /// .long("debug") - /// .action(ArgAction::SetTrue) - /// .group("mode")) - /// .arg(Arg::new("verbose") - /// .long("verbose") - /// .action(ArgAction::SetTrue) - /// .group("mode")) - /// .get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// assert!(m.contains_id("mode")); - /// ``` - /// - /// [`ArgGroup`]: crate::ArgGroup - #[must_use] - pub fn group(mut self, group_id: impl IntoResettable<Id>) -> Self { - if let Some(group_id) = group_id.into_resettable().into_option() { - self.groups.push(group_id); - } else { - self.groups.clear(); - } - self - } - - /// The names of [`ArgGroup`]'s the argument belongs to. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// Arg::new("debug") - /// .long("debug") - /// .action(ArgAction::SetTrue) - /// .groups(["mode", "verbosity"]) - /// # ; - /// ``` - /// - /// Arguments can be members of multiple groups and then the group checked as if it - /// was one of said arguments. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("debug") - /// .long("debug") - /// .action(ArgAction::SetTrue) - /// .groups(["mode", "verbosity"])) - /// .arg(Arg::new("verbose") - /// .long("verbose") - /// .action(ArgAction::SetTrue) - /// .groups(["mode", "verbosity"])) - /// .get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// assert!(m.contains_id("mode")); - /// assert!(m.contains_id("verbosity")); - /// ``` - /// - /// [`ArgGroup`]: crate::ArgGroup - #[must_use] - pub fn groups(mut self, group_ids: impl IntoIterator<Item = impl Into<Id>>) -> Self { - self.groups.extend(group_ids.into_iter().map(Into::into)); - self - } - - /// Specifies the value of the argument if `arg` has been used at runtime. - /// - /// If `default` is set to `None`, `default_value` will be removed. - /// - /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly - /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg - /// at runtime. This setting however only takes effect when the user has not provided a value at - /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value` - /// and `Arg::default_value_if`, and the user **did not** provide this arg at runtime, nor were - /// the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be applied. - /// - /// **NOTE:** This implicitly sets [`Arg::action(ArgAction::Set)`]. - /// - /// # Examples - /// - /// First we use the default value only if another arg is present at runtime. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// # use clap::builder::{ArgPredicate}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_if("flag", ArgPredicate::IsPresent, Some("default"))) - /// .get_matches_from(vec![ - /// "prog", "--flag" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other").unwrap(), "default"); - /// ``` - /// - /// Next we run the same test, but without providing `--flag`. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_if("flag", "true", Some("default"))) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other"), None); - /// ``` - /// - /// Now lets only use the default value if `--opt` contains the value `special`. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .action(ArgAction::Set) - /// .long("opt")) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_if("opt", "special", Some("default"))) - /// .get_matches_from(vec![ - /// "prog", "--opt", "special" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other").unwrap(), "default"); - /// ``` - /// - /// We can run the same test and provide any value *other than* `special` and we won't get a - /// default value. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("opt") - /// .action(ArgAction::Set) - /// .long("opt")) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_if("opt", "special", Some("default"))) - /// .get_matches_from(vec![ - /// "prog", "--opt", "hahaha" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other"), None); - /// ``` - /// - /// If we want to unset the default value for an Arg based on the presence or - /// value of some other Arg. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value("default") - /// .default_value_if("flag", "true", None)) - /// .get_matches_from(vec![ - /// "prog", "--flag" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other"), None); - /// ``` - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`Arg::default_value`]: Arg::default_value() - #[must_use] - pub fn default_value_if( - mut self, - arg_id: impl Into<Id>, - predicate: impl Into<ArgPredicate>, - default: impl IntoResettable<OsStr>, - ) -> Self { - self.default_vals_ifs.push(( - arg_id.into(), - predicate.into(), - default.into_resettable().into_option(), - )); - self - } - - #[must_use] - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_if`") - )] - pub fn default_value_if_os( - self, - arg_id: impl Into<Id>, - predicate: impl Into<ArgPredicate>, - default: impl IntoResettable<OsStr>, - ) -> Self { - self.default_value_if(arg_id, predicate, default) - } - - /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`]. - /// - /// The method takes a slice of tuples in the `(arg, predicate, default)` format. - /// - /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first - /// if multiple conditions are true, the first one found will be applied and the ultimate value. - /// - /// # Examples - /// - /// First we use the default value only if another arg is present at runtime. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("opt") - /// .long("opt") - /// .action(ArgAction::Set)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_ifs([ - /// ("flag", "true", Some("default")), - /// ("opt", "channal", Some("chan")), - /// ])) - /// .get_matches_from(vec![ - /// "prog", "--opt", "channal" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other").unwrap(), "chan"); - /// ``` - /// - /// Next we run the same test, but without providing `--flag`. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_ifs([ - /// ("flag", "true", Some("default")), - /// ("opt", "channal", Some("chan")), - /// ])) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other"), None); - /// ``` - /// - /// We can also see that these values are applied in order, and if more than one condition is - /// true, only the first evaluated "wins" - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// # use clap::builder::ArgPredicate; - /// let m = Command::new("prog") - /// .arg(Arg::new("flag") - /// .long("flag") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("opt") - /// .long("opt") - /// .action(ArgAction::Set)) - /// .arg(Arg::new("other") - /// .long("other") - /// .default_value_ifs([ - /// ("flag", ArgPredicate::IsPresent, Some("default")), - /// ("opt", ArgPredicate::Equals("channal".into()), Some("chan")), - /// ])) - /// .get_matches_from(vec![ - /// "prog", "--opt", "channal", "--flag" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("other").unwrap(), "default"); - /// ``` - /// [`Arg::action(ArgAction::Set)`]: Arg::action() - /// [`Arg::default_value_if`]: Arg::default_value_if() - #[must_use] - pub fn default_value_ifs( - mut self, - ifs: impl IntoIterator< - Item = ( - impl Into<Id>, - impl Into<ArgPredicate>, - impl IntoResettable<OsStr>, - ), - >, - ) -> Self { - for (arg, predicate, default) in ifs { - self = self.default_value_if(arg, predicate, default); - } - self - } - - #[must_use] - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_ifs`") - )] - pub fn default_value_ifs_os( - self, - ifs: impl IntoIterator< - Item = ( - impl Into<Id>, - impl Into<ArgPredicate>, - impl IntoResettable<OsStr>, - ), - >, - ) -> Self { - self.default_value_ifs(ifs) - } - - /// Set this arg as [required] as long as the specified argument is not present at runtime. - /// - /// **Pro Tip:** Using `Arg::required_unless_present` implies [`Arg::required`] and is therefore not - /// mandatory to also set. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required_unless_present("debug") - /// # ; - /// ``` - /// - /// In the following example, the required argument is *not* provided, - /// but it's not an error because the `unless` arg has been supplied. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present("dbg") - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .try_get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting `Arg::required_unless_present(name)` and *not* supplying `name` or this arg is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present("dbg") - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug")) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: Arg::required() - #[must_use] - pub fn required_unless_present(mut self, arg_id: impl IntoResettable<Id>) -> Self { - if let Some(arg_id) = arg_id.into_resettable().into_option() { - self.r_unless.push(arg_id); - } else { - self.r_unless.clear(); - } - self - } - - /// Sets this arg as [required] unless *all* of the specified arguments are present at runtime. - /// - /// In other words, parsing will succeed only if user either - /// * supplies the `self` arg. - /// * supplies *all* of the `names` arguments. - /// - /// **NOTE:** If you wish for this argument to only be required unless *any of* these args are - /// present see [`Arg::required_unless_present_any`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required_unless_present_all(["cfg", "dbg"]) - /// # ; - /// ``` - /// - /// In the following example, the required argument is *not* provided, but it's not an error - /// because *all* of the `names` args have been supplied. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present_all(["dbg", "infile"]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("infile") - /// .short('i') - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog", "--debug", "-i", "file" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required_unless_present_all(names)`] and *not* supplying - /// either *all* of `unless` args or the `self` arg is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present_all(["dbg", "infile"]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("infile") - /// .short('i') - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: Arg::required() - /// [`Arg::required_unless_present_any`]: Arg::required_unless_present_any() - /// [`Arg::required_unless_present_all(names)`]: Arg::required_unless_present_all() - #[must_use] - pub fn required_unless_present_all( - mut self, - names: impl IntoIterator<Item = impl Into<Id>>, - ) -> Self { - self.r_unless_all.extend(names.into_iter().map(Into::into)); - self - } - - /// Sets this arg as [required] unless *any* of the specified arguments are present at runtime. - /// - /// In other words, parsing will succeed only if user either - /// * supplies the `self` arg. - /// * supplies *one or more* of the `unless` arguments. - /// - /// **NOTE:** If you wish for this argument to be required unless *all of* these args are - /// present see [`Arg::required_unless_present_all`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required_unless_present_any(["cfg", "dbg"]) - /// # ; - /// ``` - /// - /// Setting [`Arg::required_unless_present_any(names)`] requires that the argument be used at runtime - /// *unless* *at least one of* the args in `names` are present. In the following example, the - /// required argument is *not* provided, but it's not an error because one the `unless` args - /// have been supplied. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present_any(["dbg", "infile"]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("infile") - /// .short('i') - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required_unless_present_any(names)`] and *not* supplying *at least one of* `names` - /// or this arg is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_unless_present_any(["dbg", "infile"]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("dbg") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("infile") - /// .short('i') - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: Arg::required() - /// [`Arg::required_unless_present_any(names)`]: Arg::required_unless_present_any() - /// [`Arg::required_unless_present_all`]: Arg::required_unless_present_all() - #[must_use] - pub fn required_unless_present_any( - mut self, - names: impl IntoIterator<Item = impl Into<Id>>, - ) -> Self { - self.r_unless.extend(names.into_iter().map(Into::into)); - self - } - - /// This argument is [required] only if the specified `arg` is present at runtime and its value - /// equals `val`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required_if_eq("other_arg", "value") - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .required_if_eq("other", "special") - /// .long("config")) - /// .arg(Arg::new("other") - /// .long("other") - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog", "--other", "not-special" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required - /// - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .required_if_eq("other", "special") - /// .long("config")) - /// .arg(Arg::new("other") - /// .long("other") - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog", "--other", "special" - /// ]); - /// - /// // We did use --other=special so "cfg" had become required but was missing. - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .required_if_eq("other", "special") - /// .long("config")) - /// .arg(Arg::new("other") - /// .long("other") - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog", "--other", "SPECIAL" - /// ]); - /// - /// // By default, the comparison is case-sensitive, so "cfg" wasn't required - /// assert!(res.is_ok()); - /// - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .required_if_eq("other", "special") - /// .long("config")) - /// .arg(Arg::new("other") - /// .long("other") - /// .ignore_case(true) - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![ - /// "prog", "--other", "SPECIAL" - /// ]); - /// - /// // However, case-insensitive comparisons can be enabled. This typically occurs when using Arg::possible_values(). - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [required]: Arg::required() - #[must_use] - pub fn required_if_eq(mut self, arg_id: impl Into<Id>, val: impl Into<OsStr>) -> Self { - self.r_ifs.push((arg_id.into(), val.into())); - self - } - - /// Specify this argument is [required] based on multiple conditions. - /// - /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become - /// valid if one of the specified `arg`'s value equals its corresponding `val`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required_if_eq_any([ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// # ; - /// ``` - /// - /// Setting `Arg::required_if_eq_any([(arg, val)])` makes this arg required if any of the `arg`s - /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is - /// anything other than `val`, this argument isn't required. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_if_eq_any([ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("extra") - /// .action(ArgAction::Set) - /// .long("extra")) - /// .arg(Arg::new("option") - /// .action(ArgAction::Set) - /// .long("option")) - /// .try_get_matches_from(vec![ - /// "prog", "--option", "other" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required - /// ``` - /// - /// Setting `Arg::required_if_eq_any([(arg, val)])` and having any of the `arg`s used with its - /// value of `val` but *not* using this arg is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_if_eq_any([ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("extra") - /// .action(ArgAction::Set) - /// .long("extra")) - /// .arg(Arg::new("option") - /// .action(ArgAction::Set) - /// .long("option")) - /// .try_get_matches_from(vec![ - /// "prog", "--option", "spec" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [required]: Arg::required() - #[must_use] - pub fn required_if_eq_any( - mut self, - ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>, - ) -> Self { - self.r_ifs - .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into()))); - self - } - - /// Specify this argument is [required] based on multiple conditions. - /// - /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become - /// valid if every one of the specified `arg`'s value equals its corresponding `val`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .required_if_eq_all([ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// # ; - /// ``` - /// - /// Setting `Arg::required_if_eq_all([(arg, val)])` makes this arg required if all of the `arg`s - /// are used at runtime and every value is equal to its corresponding `val`. If the `arg`'s value is - /// anything other than `val`, this argument isn't required. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_if_eq_all([ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("extra") - /// .action(ArgAction::Set) - /// .long("extra")) - /// .arg(Arg::new("option") - /// .action(ArgAction::Set) - /// .long("option")) - /// .try_get_matches_from(vec![ - /// "prog", "--option", "spec" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required - /// ``` - /// - /// Setting `Arg::required_if_eq_all([(arg, val)])` and having all of the `arg`s used with its - /// value of `val` but *not* using this arg is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .required_if_eq_all([ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .action(ArgAction::Set) - /// .long("config")) - /// .arg(Arg::new("extra") - /// .action(ArgAction::Set) - /// .long("extra")) - /// .arg(Arg::new("option") - /// .action(ArgAction::Set) - /// .long("option")) - /// .try_get_matches_from(vec![ - /// "prog", "--extra", "val", "--option", "spec" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: Arg::required() - #[must_use] - pub fn required_if_eq_all( - mut self, - ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>, - ) -> Self { - self.r_ifs_all - .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into()))); - self - } - - /// Require another argument if this arg matches the [`ArgPredicate`] - /// - /// This method takes `value, another_arg` pair. At runtime, clap will check - /// if this arg (`self`) matches the [`ArgPredicate`]. - /// If it does, `another_arg` will be marked as required. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .requires_if("val", "arg") - /// # ; - /// ``` - /// - /// Setting `Arg::requires_if(val, arg)` requires that the `arg` be used at runtime if the - /// defining argument's value is equal to `val`. If the defining argument is anything other than - /// `val`, the other argument isn't required. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .requires_if("my.cfg", "other") - /// .long("config")) - /// .arg(Arg::new("other")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "some.cfg" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required - /// ``` - /// - /// Setting `Arg::requires_if(val, arg)` and setting the value to `val` but *not* supplying - /// `arg` is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .requires_if("my.cfg", "input") - /// .long("config")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "my.cfg" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [override]: Arg::overrides_with() - #[must_use] - pub fn requires_if(mut self, val: impl Into<ArgPredicate>, arg_id: impl Into<Id>) -> Self { - self.requires.push((val.into(), arg_id.into())); - self - } - - /// Allows multiple conditional requirements. - /// - /// The requirement will only become valid if this arg's value matches the - /// [`ArgPredicate`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .requires_ifs([ - /// ("val", "arg"), - /// ("other_val", "arg2"), - /// ]) - /// # ; - /// ``` - /// - /// Setting `Arg::requires_ifs(["val", "arg"])` requires that the `arg` be used at runtime if the - /// defining argument's value is equal to `val`. If the defining argument's value is anything other - /// than `val`, `arg` isn't required. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .requires_ifs([ - /// ("special.conf", "opt"), - /// ("other.conf", "other"), - /// ]) - /// .long("config")) - /// .arg(Arg::new("opt") - /// .long("option") - /// .action(ArgAction::Set)) - /// .arg(Arg::new("other")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "special.conf" - /// ]); - /// - /// assert!(res.is_err()); // We used --config=special.conf so --option <val> is required - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// - /// Setting `Arg::requires_ifs` with [`ArgPredicate::IsPresent`] and *not* supplying all the - /// arguments is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction, builder::ArgPredicate}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .requires_ifs([ - /// (ArgPredicate::IsPresent, "input"), - /// (ArgPredicate::IsPresent, "output"), - /// ]) - /// .long("config")) - /// .arg(Arg::new("input")) - /// .arg(Arg::new("output")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf", "in.txt" - /// ]); - /// - /// assert!(res.is_err()); - /// // We didn't use output - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// - /// [`Arg::requires(name)`]: Arg::requires() - /// [Conflicting]: Arg::conflicts_with() - /// [override]: Arg::overrides_with() - #[must_use] - pub fn requires_ifs( - mut self, - ifs: impl IntoIterator<Item = (impl Into<ArgPredicate>, impl Into<Id>)>, - ) -> Self { - self.requires - .extend(ifs.into_iter().map(|(val, arg)| (val.into(), arg.into()))); - self - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::requires_ifs`") - )] - pub fn requires_all(self, ids: impl IntoIterator<Item = impl Into<Id>>) -> Self { - self.requires_ifs(ids.into_iter().map(|id| (ArgPredicate::IsPresent, id))) - } - - /// This argument is mutually exclusive with the specified argument. - /// - /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules - /// only need to be set for one of the two arguments, they do not need to be set for each. - /// - /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments - /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not - /// need to also do B.conflicts_with(A)) - /// - /// **NOTE:** [`Arg::conflicts_with_all(names)`] allows specifying an argument which conflicts with more than one argument. - /// - /// **NOTE** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. - /// - /// **NOTE:** All arguments implicitly conflict with themselves. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .conflicts_with("debug") - /// # ; - /// ``` - /// - /// Setting conflicting argument, and having both arguments present at runtime is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .conflicts_with("debug") - /// .long("config")) - /// .arg(Arg::new("debug") - /// .long("debug") - /// .action(ArgAction::SetTrue)) - /// .try_get_matches_from(vec![ - /// "prog", "--debug", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); - /// ``` - /// - /// [`Arg::conflicts_with_all(names)`]: Arg::conflicts_with_all() - /// [`Arg::exclusive(true)`]: Arg::exclusive() - #[must_use] - pub fn conflicts_with(mut self, arg_id: impl IntoResettable<Id>) -> Self { - if let Some(arg_id) = arg_id.into_resettable().into_option() { - self.blacklist.push(arg_id); - } else { - self.blacklist.clear(); - } - self - } - - /// This argument is mutually exclusive with the specified arguments. - /// - /// See [`Arg::conflicts_with`]. - /// - /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules - /// only need to be set for one of the two arguments, they do not need to be set for each. - /// - /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments - /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need - /// need to also do B.conflicts_with(A)) - /// - /// **NOTE:** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::new("config") - /// .conflicts_with_all(["debug", "input"]) - /// # ; - /// ``` - /// - /// Setting conflicting argument, and having any of the arguments present at runtime with a - /// conflicting argument is an error. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("cfg") - /// .action(ArgAction::Set) - /// .conflicts_with_all(["debug", "input"]) - /// .long("config")) - /// .arg(Arg::new("debug") - /// .long("debug")) - /// .arg(Arg::new("input")) - /// .try_get_matches_from(vec![ - /// "prog", "--config", "file.conf", "file.txt" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); - /// ``` - /// [`Arg::conflicts_with`]: Arg::conflicts_with() - /// [`Arg::exclusive(true)`]: Arg::exclusive() - #[must_use] - pub fn conflicts_with_all(mut self, names: impl IntoIterator<Item = impl Into<Id>>) -> Self { - self.blacklist.extend(names.into_iter().map(Into::into)); - self - } - - /// Sets an overridable argument. - /// - /// i.e. this argument and the following argument - /// will override each other in POSIX style (whichever argument was specified at runtime - /// **last** "wins") - /// - /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any - /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed - /// - /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, arg}; - /// let m = Command::new("prog") - /// .arg(arg!(-f --flag "some flag") - /// .conflicts_with("debug")) - /// .arg(arg!(-d --debug "other flag")) - /// .arg(arg!(-c --color "third flag") - /// .overrides_with("flag")) - /// .get_matches_from(vec![ - /// "prog", "-f", "-d", "-c"]); - /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color - /// - /// assert!(m.get_flag("color")); - /// assert!(m.get_flag("debug")); // even though flag conflicts with debug, it's as if flag - /// // was never used because it was overridden with color - /// assert!(!m.get_flag("flag")); - /// ``` - #[must_use] - pub fn overrides_with(mut self, arg_id: impl IntoResettable<Id>) -> Self { - if let Some(arg_id) = arg_id.into_resettable().into_option() { - self.overrides.push(arg_id); - } else { - self.overrides.clear(); - } - self - } - - /// Sets multiple mutually overridable arguments by name. - /// - /// i.e. this argument and the following argument will override each other in POSIX style - /// (whichever argument was specified at runtime **last** "wins") - /// - /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any - /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed - /// - /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with_all`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, arg}; - /// let m = Command::new("prog") - /// .arg(arg!(-f --flag "some flag") - /// .conflicts_with("color")) - /// .arg(arg!(-d --debug "other flag")) - /// .arg(arg!(-c --color "third flag") - /// .overrides_with_all(["flag", "debug"])) - /// .get_matches_from(vec![ - /// "prog", "-f", "-d", "-c"]); - /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color - /// - /// assert!(m.get_flag("color")); // even though flag conflicts with color, it's as if flag - /// // and debug were never used because they were overridden - /// // with color - /// assert!(!m.get_flag("debug")); - /// assert!(!m.get_flag("flag")); - /// ``` - #[must_use] - pub fn overrides_with_all(mut self, names: impl IntoIterator<Item = impl Into<Id>>) -> Self { - self.overrides.extend(names.into_iter().map(Into::into)); - self - } -} - -/// # Reflection -impl Arg { - /// Get the name of the argument - #[inline] - pub fn get_id(&self) -> &Id { - &self.id - } - - /// Get the help specified for this argument, if any - #[inline] - pub fn get_help(&self) -> Option<&StyledStr> { - self.help.as_ref() - } - - /// Get the long help specified for this argument, if any - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// let arg = Arg::new("foo").long_help("long help"); - /// assert_eq!(Some("long help".to_owned()), arg.get_long_help().map(|s| s.to_string())); - /// ``` - /// - #[inline] - pub fn get_long_help(&self) -> Option<&StyledStr> { - self.long_help.as_ref() - } - - /// Get the help heading specified for this argument, if any - #[inline] - pub fn get_help_heading(&self) -> Option<&str> { - self.help_heading - .as_ref() - .map(|s| s.as_deref()) - .unwrap_or_default() - } - - /// Get the short option name for this argument, if any - #[inline] - pub fn get_short(&self) -> Option<char> { - self.short - } - - /// Get visible short aliases for this argument, if any - #[inline] - pub fn get_visible_short_aliases(&self) -> Option<Vec<char>> { - if self.short_aliases.is_empty() { - None - } else { - Some( - self.short_aliases - .iter() - .filter_map(|(c, v)| if *v { Some(c) } else { None }) - .copied() - .collect(), - ) - } - } - - /// Get *all* short aliases for this argument, if any, both visible and hidden. - #[inline] - pub fn get_all_short_aliases(&self) -> Option<Vec<char>> { - if self.short_aliases.is_empty() { - None - } else { - Some(self.short_aliases.iter().map(|(s, _)| s).copied().collect()) - } - } - - /// Get the short option name and its visible aliases, if any - #[inline] - pub fn get_short_and_visible_aliases(&self) -> Option<Vec<char>> { - let mut shorts = match self.short { - Some(short) => vec![short], - None => return None, - }; - if let Some(aliases) = self.get_visible_short_aliases() { - shorts.extend(aliases); - } - Some(shorts) - } - - /// Get the long option name for this argument, if any - #[inline] - pub fn get_long(&self) -> Option<&str> { - self.long.as_deref() - } - - /// Get visible aliases for this argument, if any - #[inline] - pub fn get_visible_aliases(&self) -> Option<Vec<&str>> { - if self.aliases.is_empty() { - None - } else { - Some( - self.aliases - .iter() - .filter_map(|(s, v)| if *v { Some(s.as_str()) } else { None }) - .collect(), - ) - } - } - - /// Get *all* aliases for this argument, if any, both visible and hidden. - #[inline] - pub fn get_all_aliases(&self) -> Option<Vec<&str>> { - if self.aliases.is_empty() { - None - } else { - Some(self.aliases.iter().map(|(s, _)| s.as_str()).collect()) - } - } - - /// Get the long option name and its visible aliases, if any - #[inline] - pub fn get_long_and_visible_aliases(&self) -> Option<Vec<&str>> { - let mut longs = match self.get_long() { - Some(long) => vec![long], - None => return None, - }; - if let Some(aliases) = self.get_visible_aliases() { - longs.extend(aliases); - } - Some(longs) - } - - /// Get the names of possible values for this argument. Only useful for user - /// facing applications, such as building help messages or man files - pub fn get_possible_values(&self) -> Vec<PossibleValue> { - if !self.is_takes_value_set() { - vec![] - } else { - self.get_value_parser() - .possible_values() - .map(|pvs| pvs.collect()) - .unwrap_or_default() - } - } - - /// Get the names of values for this argument. - #[inline] - pub fn get_value_names(&self) -> Option<&[Str]> { - if self.val_names.is_empty() { - None - } else { - Some(&self.val_names) - } - } - - /// Get the number of values for this argument. - #[inline] - pub fn get_num_args(&self) -> Option<ValueRange> { - self.num_vals - } - - #[inline] - pub(crate) fn get_min_vals(&self) -> usize { - self.get_num_args().expect(INTERNAL_ERROR_MSG).min_values() - } - - /// Get the delimiter between multiple values - #[inline] - pub fn get_value_delimiter(&self) -> Option<char> { - self.val_delim - } - - /// Get the value terminator for this argument. The value_terminator is a value - /// that terminates parsing of multi-valued arguments. - #[inline] - pub fn get_value_terminator(&self) -> Option<&Str> { - self.terminator.as_ref() - } - - /// Get the index of this argument, if any - #[inline] - pub fn get_index(&self) -> Option<usize> { - self.index - } - - /// Get the value hint of this argument - pub fn get_value_hint(&self) -> ValueHint { - self.value_hint.unwrap_or_else(|| { - if self.is_takes_value_set() { - let type_id = self.get_value_parser().type_id(); - if type_id == crate::parser::AnyValueId::of::<std::path::PathBuf>() { - ValueHint::AnyPath - } else { - ValueHint::default() - } - } else { - ValueHint::default() - } - }) - } - - /// Get the environment variable name specified for this argument, if any - /// - /// # Examples - /// - /// ```rust - /// # use std::ffi::OsStr; - /// # use clap::Arg; - /// let arg = Arg::new("foo").env("ENVIRONMENT"); - /// assert_eq!(arg.get_env(), Some(OsStr::new("ENVIRONMENT"))); - /// ``` - #[cfg(feature = "env")] - pub fn get_env(&self) -> Option<&std::ffi::OsStr> { - self.env.as_ref().map(|x| x.0.as_os_str()) - } - - /// Get the default values specified for this argument, if any - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// let arg = Arg::new("foo").default_value("default value"); - /// assert_eq!(arg.get_default_values(), &["default value"]); - /// ``` - pub fn get_default_values(&self) -> &[OsStr] { - &self.default_vals - } - - /// Checks whether this argument is a positional or not. - /// - /// # Examples - /// - /// ``` - /// # use clap::Arg; - /// let arg = Arg::new("foo"); - /// assert_eq!(arg.is_positional(), true); - /// - /// let arg = Arg::new("foo").long("foo"); - /// assert_eq!(arg.is_positional(), false); - /// ``` - pub fn is_positional(&self) -> bool { - self.get_long().is_none() && self.get_short().is_none() - } - - /// Reports whether [`Arg::required`] is set - pub fn is_required_set(&self) -> bool { - self.is_set(ArgSettings::Required) - } - - pub(crate) fn is_multiple_values_set(&self) -> bool { - self.get_num_args().unwrap_or_default().is_multiple() - } - - pub(crate) fn is_takes_value_set(&self) -> bool { - self.get_action().takes_values() - } - - /// Report whether [`Arg::allow_hyphen_values`] is set - pub fn is_allow_hyphen_values_set(&self) -> bool { - self.is_set(ArgSettings::AllowHyphenValues) - } - - /// Report whether [`Arg::allow_negative_numbers`] is set - pub fn is_allow_negative_numbers_set(&self) -> bool { - self.is_set(ArgSettings::AllowNegativeNumbers) - } - - /// Behavior when parsing the argument - pub fn get_action(&self) -> &super::ArgAction { - const DEFAULT: super::ArgAction = super::ArgAction::Set; - self.action.as_ref().unwrap_or(&DEFAULT) - } - - /// Configured parser for argument values - /// - /// # Example - /// - /// ```rust - /// let cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("port") - /// .value_parser(clap::value_parser!(usize)) - /// ); - /// let value_parser = cmd.get_arguments() - /// .find(|a| a.get_id() == "port").unwrap() - /// .get_value_parser(); - /// println!("{:?}", value_parser); - /// ``` - pub fn get_value_parser(&self) -> &super::ValueParser { - if let Some(value_parser) = self.value_parser.as_ref() { - value_parser - } else { - static DEFAULT: super::ValueParser = super::ValueParser::string(); - &DEFAULT - } - } - - /// Report whether [`Arg::global`] is set - pub fn is_global_set(&self) -> bool { - self.is_set(ArgSettings::Global) - } - - /// Report whether [`Arg::next_line_help`] is set - pub fn is_next_line_help_set(&self) -> bool { - self.is_set(ArgSettings::NextLineHelp) - } - - /// Report whether [`Arg::hide`] is set - pub fn is_hide_set(&self) -> bool { - self.is_set(ArgSettings::Hidden) - } - - /// Report whether [`Arg::hide_default_value`] is set - pub fn is_hide_default_value_set(&self) -> bool { - self.is_set(ArgSettings::HideDefaultValue) - } - - /// Report whether [`Arg::hide_possible_values`] is set - pub fn is_hide_possible_values_set(&self) -> bool { - self.is_set(ArgSettings::HidePossibleValues) - } - - /// Report whether [`Arg::hide_env`] is set - #[cfg(feature = "env")] - pub fn is_hide_env_set(&self) -> bool { - self.is_set(ArgSettings::HideEnv) - } - - /// Report whether [`Arg::hide_env_values`] is set - #[cfg(feature = "env")] - pub fn is_hide_env_values_set(&self) -> bool { - self.is_set(ArgSettings::HideEnvValues) - } - - /// Report whether [`Arg::hide_short_help`] is set - pub fn is_hide_short_help_set(&self) -> bool { - self.is_set(ArgSettings::HiddenShortHelp) - } - - /// Report whether [`Arg::hide_long_help`] is set - pub fn is_hide_long_help_set(&self) -> bool { - self.is_set(ArgSettings::HiddenLongHelp) - } - - /// Report whether [`Arg::require_equals`] is set - pub fn is_require_equals_set(&self) -> bool { - self.is_set(ArgSettings::RequireEquals) - } - - /// Reports whether [`Arg::exclusive`] is set - pub fn is_exclusive_set(&self) -> bool { - self.is_set(ArgSettings::Exclusive) - } - - /// Report whether [`Arg::trailing_var_arg`] is set - pub fn is_trailing_var_arg_set(&self) -> bool { - self.is_set(ArgSettings::TrailingVarArg) - } - - /// Reports whether [`Arg::last`] is set - pub fn is_last_set(&self) -> bool { - self.is_set(ArgSettings::Last) - } - - /// Reports whether [`Arg::ignore_case`] is set - pub fn is_ignore_case_set(&self) -> bool { - self.is_set(ArgSettings::IgnoreCase) - } -} - -/// # Internally used only -impl Arg { - pub(crate) fn _build(&mut self) { - if self.action.is_none() { - if self.num_vals == Some(ValueRange::EMPTY) { - let action = super::ArgAction::SetTrue; - self.action = Some(action); - } else { - let action = - if self.is_positional() && self.num_vals.unwrap_or_default().is_unbounded() { - // Allow collecting arguments interleaved with flags - // - // Bounded values are probably a group and the user should explicitly opt-in to - // Append - super::ArgAction::Append - } else { - super::ArgAction::Set - }; - self.action = Some(action); - } - } - if let Some(action) = self.action.as_ref() { - if let Some(default_value) = action.default_value() { - if self.default_vals.is_empty() { - self.default_vals = vec![default_value.into()]; - } - } - if let Some(default_value) = action.default_missing_value() { - if self.default_missing_vals.is_empty() { - self.default_missing_vals = vec![default_value.into()]; - } - } - } - - if self.value_parser.is_none() { - if let Some(default) = self.action.as_ref().and_then(|a| a.default_value_parser()) { - self.value_parser = Some(default); - } else { - self.value_parser = Some(super::ValueParser::string()); - } - } - - let val_names_len = self.val_names.len(); - if val_names_len > 1 { - self.num_vals.get_or_insert(val_names_len.into()); - } else { - let nargs = if self.get_action().takes_values() { - ValueRange::SINGLE - } else { - ValueRange::EMPTY - }; - self.num_vals.get_or_insert(nargs); - } - } - - // Used for positionals when printing - pub(crate) fn name_no_brackets(&self) -> String { - debug!("Arg::name_no_brackets:{}", self.get_id()); - let delim = " "; - if !self.val_names.is_empty() { - debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names); - - if self.val_names.len() > 1 { - self.val_names - .iter() - .map(|n| format!("<{}>", n)) - .collect::<Vec<_>>() - .join(delim) - } else { - self.val_names - .first() - .expect(INTERNAL_ERROR_MSG) - .as_str() - .to_owned() - } - } else { - debug!("Arg::name_no_brackets: just name"); - self.get_id().as_str().to_owned() - } - } - - pub(crate) fn stylized(&self, required: Option<bool>) -> StyledStr { - let mut styled = StyledStr::new(); - // Write the name such --long or -l - if let Some(l) = self.get_long() { - styled.literal("--"); - styled.literal(l); - } else if let Some(s) = self.get_short() { - styled.literal("-"); - styled.literal(s); - } - styled.extend(self.stylize_arg_suffix(required).into_iter()); - styled - } - - pub(crate) fn stylize_arg_suffix(&self, required: Option<bool>) -> StyledStr { - let mut styled = StyledStr::new(); - - let mut need_closing_bracket = false; - if self.is_takes_value_set() && !self.is_positional() { - let is_optional_val = self.get_min_vals() == 0; - if self.is_require_equals_set() { - if is_optional_val { - need_closing_bracket = true; - styled.placeholder("[="); - } else { - styled.literal("="); - } - } else if is_optional_val { - need_closing_bracket = true; - styled.placeholder(" ["); - } else { - styled.placeholder(" "); - } - } - if self.is_takes_value_set() || self.is_positional() { - let required = required.unwrap_or_else(|| self.is_required_set()); - let arg_val = self.render_arg_val(required); - styled.placeholder(arg_val); - } else if matches!(*self.get_action(), ArgAction::Count) { - styled.placeholder("..."); - } - if need_closing_bracket { - styled.placeholder("]"); - } - - styled - } - - /// Write the values such as `<name1> <name2>` - fn render_arg_val(&self, required: bool) -> String { - let mut rendered = String::new(); - - let num_vals = self.get_num_args().unwrap_or_else(|| 1.into()); - - let mut val_names = if self.val_names.is_empty() { - vec![self.id.as_internal_str().to_owned()] - } else { - self.val_names.clone() - }; - if val_names.len() == 1 { - let min = num_vals.min_values().max(1); - let val_name = val_names.pop().unwrap(); - val_names = vec![val_name; min]; - } - - debug_assert!(self.is_takes_value_set()); - for (n, val_name) in val_names.iter().enumerate() { - let arg_name = if self.is_positional() && (num_vals.min_values() == 0 || !required) { - format!("[{}]", val_name) - } else { - format!("<{}>", val_name) - }; - - if n != 0 { - rendered.push(' '); - } - rendered.push_str(&arg_name); - } - - let mut extra_values = false; - extra_values |= val_names.len() < num_vals.max_values(); - if self.is_positional() && matches!(*self.get_action(), ArgAction::Append) { - extra_values = true; - } - if extra_values { - rendered.push_str("..."); - } - - rendered - } - - /// Either multiple values or occurrences - pub(crate) fn is_multiple(&self) -> bool { - self.is_multiple_values_set() || matches!(*self.get_action(), ArgAction::Append) - } - - #[cfg(feature = "help")] - pub(crate) fn get_display_order(&self) -> usize { - self.disp_ord.unwrap_or(999) - } -} - -impl From<&'_ Arg> for Arg { - fn from(a: &Arg) -> Self { - a.clone() - } -} - -impl PartialEq for Arg { - fn eq(&self, other: &Arg) -> bool { - self.get_id() == other.get_id() - } -} - -impl PartialOrd for Arg { - fn partial_cmp(&self, other: &Self) -> Option<Ordering> { - Some(self.cmp(other)) - } -} - -impl Ord for Arg { - fn cmp(&self, other: &Arg) -> Ordering { - self.get_id().cmp(other.get_id()) - } -} - -impl Eq for Arg {} - -impl Display for Arg { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - self.stylized(None).fmt(f) - } -} - -impl fmt::Debug for Arg { - fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { - let mut ds = f.debug_struct("Arg"); - - #[allow(unused_mut)] - let mut ds = ds - .field("id", &self.id) - .field("help", &self.help) - .field("long_help", &self.long_help) - .field("action", &self.action) - .field("value_parser", &self.value_parser) - .field("blacklist", &self.blacklist) - .field("settings", &self.settings) - .field("overrides", &self.overrides) - .field("groups", &self.groups) - .field("requires", &self.requires) - .field("r_ifs", &self.r_ifs) - .field("r_unless", &self.r_unless) - .field("short", &self.short) - .field("long", &self.long) - .field("aliases", &self.aliases) - .field("short_aliases", &self.short_aliases) - .field("disp_ord", &self.disp_ord) - .field("val_names", &self.val_names) - .field("num_vals", &self.num_vals) - .field("val_delim", &self.val_delim) - .field("default_vals", &self.default_vals) - .field("default_vals_ifs", &self.default_vals_ifs) - .field("terminator", &self.terminator) - .field("index", &self.index) - .field("help_heading", &self.help_heading) - .field("value_hint", &self.value_hint) - .field("default_missing_vals", &self.default_missing_vals); - - #[cfg(feature = "env")] - { - ds = ds.field("env", &self.env); - } - - ds.finish() - } -} - -// Flags -#[cfg(test)] -mod test { - use super::Arg; - use super::ArgAction; - - #[test] - fn flag_display_long() { - let mut f = Arg::new("flg").long("flag").action(ArgAction::SetTrue); - f._build(); - - assert_eq!(f.to_string(), "--flag"); - } - - #[test] - fn flag_display_short() { - let mut f2 = Arg::new("flg").short('f').action(ArgAction::SetTrue); - f2._build(); - - assert_eq!(f2.to_string(), "-f"); - } - - #[test] - fn flag_display_count() { - let mut f2 = Arg::new("flg").long("flag").action(ArgAction::Count); - f2._build(); - - assert_eq!(f2.to_string(), "--flag..."); - } - - #[test] - fn flag_display_single_alias() { - let mut f = Arg::new("flg") - .long("flag") - .visible_alias("als") - .action(ArgAction::SetTrue); - f._build(); - - assert_eq!(f.to_string(), "--flag") - } - - #[test] - fn flag_display_multiple_aliases() { - let mut f = Arg::new("flg").short('f').action(ArgAction::SetTrue); - f.aliases = vec![ - ("alias_not_visible".into(), false), - ("f2".into(), true), - ("f3".into(), true), - ("f4".into(), true), - ]; - f._build(); - - assert_eq!(f.to_string(), "-f"); - } - - #[test] - fn flag_display_single_short_alias() { - let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue); - f.short_aliases = vec![('b', true)]; - f._build(); - - assert_eq!(f.to_string(), "-a") - } - - #[test] - fn flag_display_multiple_short_aliases() { - let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue); - f.short_aliases = vec![('b', false), ('c', true), ('d', true), ('e', true)]; - f._build(); - - assert_eq!(f.to_string(), "-a"); - } - - // Options - - #[test] - fn option_display_multiple_occurrences() { - let mut o = Arg::new("opt").long("option").action(ArgAction::Append); - o._build(); - - assert_eq!(o.to_string(), "--option <opt>"); - } - - #[test] - fn option_display_multiple_values() { - let mut o = Arg::new("opt") - .long("option") - .action(ArgAction::Set) - .num_args(1..); - o._build(); - - assert_eq!(o.to_string(), "--option <opt>..."); - } - - #[test] - fn option_display_zero_or_more_values() { - let mut o = Arg::new("opt") - .long("option") - .action(ArgAction::Set) - .num_args(0..); - o._build(); - - assert_eq!(o.to_string(), "--option [<opt>...]"); - } - - #[test] - fn option_display_one_or_more_values() { - let mut o = Arg::new("opt") - .long("option") - .action(ArgAction::Set) - .num_args(1..); - o._build(); - - assert_eq!(o.to_string(), "--option <opt>..."); - } - - #[test] - fn option_display_zero_or_more_values_with_value_name() { - let mut o = Arg::new("opt") - .short('o') - .action(ArgAction::Set) - .num_args(0..) - .value_names(["file"]); - o._build(); - - assert_eq!(o.to_string(), "-o [<file>...]"); - } - - #[test] - fn option_display_one_or_more_values_with_value_name() { - let mut o = Arg::new("opt") - .short('o') - .action(ArgAction::Set) - .num_args(1..) - .value_names(["file"]); - o._build(); - - assert_eq!(o.to_string(), "-o <file>..."); - } - - #[test] - fn option_display_optional_value() { - let mut o = Arg::new("opt") - .long("option") - .action(ArgAction::Set) - .num_args(0..=1); - o._build(); - - assert_eq!(o.to_string(), "--option [<opt>]"); - } - - #[test] - fn option_display_value_names() { - let mut o = Arg::new("opt") - .short('o') - .action(ArgAction::Set) - .value_names(["file", "name"]); - o._build(); - - assert_eq!(o.to_string(), "-o <file> <name>"); - } - - #[test] - fn option_display3() { - let mut o = Arg::new("opt") - .short('o') - .num_args(1..) - .action(ArgAction::Set) - .value_names(["file", "name"]); - o._build(); - - assert_eq!(o.to_string(), "-o <file> <name>..."); - } - - #[test] - fn option_display_single_alias() { - let mut o = Arg::new("opt") - .long("option") - .action(ArgAction::Set) - .visible_alias("als"); - o._build(); - - assert_eq!(o.to_string(), "--option <opt>"); - } - - #[test] - fn option_display_multiple_aliases() { - let mut o = Arg::new("opt") - .long("option") - .action(ArgAction::Set) - .visible_aliases(["als2", "als3", "als4"]) - .alias("als_not_visible"); - o._build(); - - assert_eq!(o.to_string(), "--option <opt>"); - } - - #[test] - fn option_display_single_short_alias() { - let mut o = Arg::new("opt") - .short('a') - .action(ArgAction::Set) - .visible_short_alias('b'); - o._build(); - - assert_eq!(o.to_string(), "-a <opt>"); - } - - #[test] - fn option_display_multiple_short_aliases() { - let mut o = Arg::new("opt") - .short('a') - .action(ArgAction::Set) - .visible_short_aliases(['b', 'c', 'd']) - .short_alias('e'); - o._build(); - - assert_eq!(o.to_string(), "-a <opt>"); - } - - // Positionals - - #[test] - fn positional_display_multiple_values() { - let mut p = Arg::new("pos").index(1).num_args(1..); - p._build(); - - assert_eq!(p.to_string(), "[pos]..."); - } - - #[test] - fn positional_display_multiple_values_required() { - let mut p = Arg::new("pos").index(1).num_args(1..).required(true); - p._build(); - - assert_eq!(p.to_string(), "<pos>..."); - } - - #[test] - fn positional_display_zero_or_more_values() { - let mut p = Arg::new("pos").index(1).num_args(0..); - p._build(); - - assert_eq!(p.to_string(), "[pos]..."); - } - - #[test] - fn positional_display_one_or_more_values() { - let mut p = Arg::new("pos").index(1).num_args(1..); - p._build(); - - assert_eq!(p.to_string(), "[pos]..."); - } - - #[test] - fn positional_display_one_or_more_values_required() { - let mut p = Arg::new("pos").index(1).num_args(1..).required(true); - p._build(); - - assert_eq!(p.to_string(), "<pos>..."); - } - - #[test] - fn positional_display_optional_value() { - let mut p = Arg::new("pos") - .index(1) - .num_args(0..=1) - .action(ArgAction::Set); - p._build(); - - assert_eq!(p.to_string(), "[pos]"); - } - - #[test] - fn positional_display_multiple_occurrences() { - let mut p = Arg::new("pos").index(1).action(ArgAction::Append); - p._build(); - - assert_eq!(p.to_string(), "[pos]..."); - } - - #[test] - fn positional_display_multiple_occurrences_required() { - let mut p = Arg::new("pos") - .index(1) - .action(ArgAction::Append) - .required(true); - p._build(); - - assert_eq!(p.to_string(), "<pos>..."); - } - - #[test] - fn positional_display_required() { - let mut p = Arg::new("pos").index(1).required(true); - p._build(); - - assert_eq!(p.to_string(), "<pos>"); - } - - #[test] - fn positional_display_val_names() { - let mut p = Arg::new("pos").index(1).value_names(["file1", "file2"]); - p._build(); - - assert_eq!(p.to_string(), "[file1] [file2]"); - } - - #[test] - fn positional_display_val_names_required() { - let mut p = Arg::new("pos") - .index(1) - .value_names(["file1", "file2"]) - .required(true); - p._build(); - - assert_eq!(p.to_string(), "<file1> <file2>"); - } - - #[test] - fn positional_display_val_names_req() { - let mut p = Arg::new("pos") - .index(1) - .required(true) - .value_names(["file1", "file2"]); - p._build(); - - assert_eq!(p.to_string(), "<file1> <file2>"); - } -} diff --git a/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" <ver> "set the version manually")) -/// .arg(arg!(--major "auto increase major")) -/// .arg(arg!(--minor "auto increase minor")) -/// .arg(arg!(--patch "auto increase patch")) -/// .group(ArgGroup::new("vers") -/// .args(["set-ver", "major", "minor", "patch"]) -/// .required(true)) -/// .try_get_matches_from(vec!["cmd", "--major", "--patch"]); -/// // Because we used two args in the group it's an error -/// assert!(result.is_err()); -/// let err = result.unwrap_err(); -/// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); -/// ``` -/// -/// This next example shows a passing parse of the same scenario -/// ```rust -/// # use clap::{Command, arg, ArgGroup, Id}; -/// let result = Command::new("cmd") -/// .arg(arg!(--"set-ver" <ver> "set the version manually")) -/// .arg(arg!(--major "auto increase major")) -/// .arg(arg!(--minor "auto increase minor")) -/// .arg(arg!(--patch "auto increase patch")) -/// .group(ArgGroup::new("vers") -/// .args(["set-ver", "major", "minor","patch"]) -/// .required(true)) -/// .try_get_matches_from(vec!["cmd", "--major"]); -/// assert!(result.is_ok()); -/// let matches = result.unwrap(); -/// // We may not know which of the args was used, so we can test for the group... -/// assert!(matches.contains_id("vers")); -/// // We can also ask the group which arg was used -/// assert_eq!(matches -/// .get_one::<Id>("vers") -/// .expect("`vers` is required") -/// .as_str(), -/// "major" -/// ); -/// // we could also alternatively check each arg individually (not shown here) -/// ``` -/// [`ArgGroup::multiple(true)`]: ArgGroup::multiple() -/// -/// [`ArgGroup::multiple(false)`]: ArgGroup::multiple() -/// [arguments]: crate::Arg -/// [conflict]: crate::Arg::conflicts_with() -/// [requirement]: crate::Arg::requires() -#[derive(Default, Clone, Debug, PartialEq, Eq)] -pub struct ArgGroup { - pub(crate) id: Id, - pub(crate) args: Vec<Id>, - pub(crate) required: bool, - pub(crate) requires: Vec<Id>, - pub(crate) conflicts: Vec<Id>, - pub(crate) multiple: bool, -} - -/// # Builder -impl ArgGroup { - /// Create a `ArgGroup` using a unique name. - /// - /// The name will be used to get values from the group or refer to the group inside of conflict - /// and requirement rules. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, ArgGroup}; - /// ArgGroup::new("config") - /// # ; - /// ``` - pub fn new(id: impl Into<Id>) -> Self { - ArgGroup::default().id(id) - } - - /// Sets the group name. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, ArgGroup}; - /// ArgGroup::default().id("config") - /// # ; - /// ``` - #[must_use] - pub fn id(mut self, id: impl Into<Id>) -> Self { - self.id = id.into(); - self - } - - /// Adds an [argument] to this group by name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, ArgAction}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .arg("flag") - /// .arg("color")) - /// .get_matches_from(vec!["myprog", "-f"]); - /// // maybe we don't know which of the two flags was used... - /// assert!(m.contains_id("req_flags")); - /// // but we can also check individually if needed - /// assert!(m.contains_id("flag")); - /// ``` - /// [argument]: crate::Arg - #[must_use] - pub fn arg(mut self, arg_id: impl IntoResettable<Id>) -> Self { - if let Some(arg_id) = arg_id.into_resettable().into_option() { - self.args.push(arg_id); - } else { - self.args.clear(); - } - self - } - - /// Adds multiple [arguments] to this group by name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, ArgAction}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"])) - /// .get_matches_from(vec!["myprog", "-f"]); - /// // maybe we don't know which of the two flags was used... - /// assert!(m.contains_id("req_flags")); - /// // but we can also check individually if needed - /// assert!(m.contains_id("flag")); - /// ``` - /// [arguments]: crate::Arg - #[must_use] - pub fn args(mut self, ns: impl IntoIterator<Item = impl Into<Id>>) -> Self { - for n in ns { - self = self.arg(n); - } - self - } - - /// Getters for all args. It will return a vector of `Id` - /// - /// # Example - /// - /// ```rust - /// # use clap::{ArgGroup}; - /// let args: Vec<&str> = vec!["a1".into(), "a4".into()]; - /// let grp = ArgGroup::new("program").args(&args); - /// - /// for (pos, arg) in grp.get_args().enumerate() { - /// assert_eq!(*arg, args[pos]); - /// } - /// ``` - pub fn get_args(&self) -> impl Iterator<Item = &Id> { - self.args.iter() - } - - /// Allows more than one of the [`Arg`]s in this group to be used. (Default: `false`) - /// - /// # Examples - /// - /// Notice in this example we use *both* the `-f` and `-c` flags which are both part of the - /// group - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, ArgAction}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"]) - /// .multiple(true)) - /// .get_matches_from(vec!["myprog", "-f", "-c"]); - /// // maybe we don't know which of the two flags was used... - /// assert!(m.contains_id("req_flags")); - /// ``` - /// In this next example, we show the default behavior (i.e. `multiple(false)) which will throw - /// an error if more than one of the args in the group was used. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"])) - /// .try_get_matches_from(vec!["myprog", "-f", "-c"]); - /// // Because we used both args in the group it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); - /// ``` - /// - /// [`Arg`]: crate::Arg - #[inline] - #[must_use] - pub fn multiple(mut self, yes: bool) -> Self { - self.multiple = yes; - self - } - - /// Return true if the group allows more than one of the arguments - /// in this group to be used. (Default: `false`) - /// - /// # Example - /// - /// ```rust - /// # use clap::{ArgGroup}; - /// let mut group = ArgGroup::new("myprog") - /// .args(["f", "c"]) - /// .multiple(true); - /// - /// assert!(group.is_multiple()); - /// ``` - pub fn is_multiple(&mut self) -> bool { - self.multiple - } - - /// Require an argument from the group to be present when parsing. - /// - /// This is unless conflicting with another argument. A required group will be displayed in - /// the usage string of the application in the format `<arg|arg2|arg3>`. - /// - /// **NOTE:** This setting only applies to the current [`Command`] / [`Subcommand`]s, and not - /// globally. - /// - /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with - /// `ArgGroup::required(true)` states, "One and *only one* arg must be used from this group. - /// Use of more than one arg is an error." Vice setting `ArgGroup::multiple(true)` which - /// states, '*At least* one arg from this group must be used. Using multiple is OK." - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"]) - /// .required(true)) - /// .try_get_matches_from(vec!["myprog"]); - /// // Because we didn't use any of the args in the group, it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - /// [`ArgGroup::multiple`]: ArgGroup::multiple() - /// [`Command`]: crate::Command - #[inline] - #[must_use] - pub fn required(mut self, yes: bool) -> Self { - self.required = yes; - self - } - - /// Specify an argument or group that must be present when this group is. - /// - /// This is not to be confused with a [required group]. Requirement rules function just like - /// [argument requirement rules], you can name other arguments or groups that must be present - /// when any one of the arguments from this group is used. - /// - /// **NOTE:** The name provided may be an argument or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("debug") - /// .short('d') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"]) - /// .requires("debug")) - /// .try_get_matches_from(vec!["myprog", "-c"]); - /// // because we used an arg from the group, and the group requires "-d" to be used, it's an - /// // error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required group]: ArgGroup::required() - /// [argument requirement rules]: crate::Arg::requires() - #[must_use] - pub fn requires(mut self, id: impl IntoResettable<Id>) -> Self { - if let Some(id) = id.into_resettable().into_option() { - self.requires.push(id); - } else { - self.requires.clear(); - } - self - } - - /// Specify arguments or groups that must be present when this group is. - /// - /// This is not to be confused with a [required group]. Requirement rules function just like - /// [argument requirement rules], you can name other arguments or groups that must be present - /// when one of the arguments from this group is used. - /// - /// **NOTE:** The names provided may be an argument or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("debug") - /// .short('d') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("verb") - /// .short('v') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"]) - /// .requires_all(["debug", "verb"])) - /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); - /// // because we used an arg from the group, and the group requires "-d" and "-v" to be used, - /// // yet we only used "-d" it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); - /// ``` - /// [required group]: ArgGroup::required() - /// [argument requirement rules]: crate::Arg::requires_ifs() - #[must_use] - pub fn requires_all(mut self, ns: impl IntoIterator<Item = impl Into<Id>>) -> Self { - for n in ns { - self = self.requires(n); - } - self - } - - /// Specify an argument or group that must **not** be present when this group is. - /// - /// Exclusion (aka conflict) rules function just like [argument exclusion rules], you can name - /// other arguments or groups that must *not* be present when one of the arguments from this - /// group are used. - /// - /// **NOTE:** The name provided may be an argument, or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("debug") - /// .short('d') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"]) - /// .conflicts_with("debug")) - /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); - /// // because we used an arg from the group, and the group conflicts with "-d", it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); - /// ``` - /// [argument exclusion rules]: crate::Arg::conflicts_with() - #[must_use] - pub fn conflicts_with(mut self, id: impl IntoResettable<Id>) -> Self { - if let Some(id) = id.into_resettable().into_option() { - self.conflicts.push(id); - } else { - self.conflicts.clear(); - } - self - } - - /// Specify arguments or groups that must **not** be present when this group is. - /// - /// Exclusion rules function just like [argument exclusion rules], you can name other arguments - /// or groups that must *not* be present when one of the arguments from this group are used. - /// - /// **NOTE:** The names provided may be an argument, or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; - /// let result = Command::new("myprog") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("color") - /// .short('c') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("debug") - /// .short('d') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("verb") - /// .short('v') - /// .action(ArgAction::SetTrue)) - /// .group(ArgGroup::new("req_flags") - /// .args(["flag", "color"]) - /// .conflicts_with_all(["debug", "verb"])) - /// .try_get_matches_from(vec!["myprog", "-c", "-v"]); - /// // because we used an arg from the group, and the group conflicts with either "-v" or "-d" - /// // it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); - /// ``` - /// - /// [argument exclusion rules]: crate::Arg::conflicts_with_all() - #[must_use] - pub fn conflicts_with_all(mut self, ns: impl IntoIterator<Item = impl Into<Id>>) -> Self { - for n in ns { - self = self.conflicts_with(n); - } - self - } -} - -/// # Reflection -impl ArgGroup { - /// Get the name of the group - #[inline] - pub fn get_id(&self) -> &Id { - &self.id - } - - /// Reports whether [`ArgGroup::required`] is set - #[inline] - pub fn is_required_set(&self) -> bool { - self.required - } -} - -impl From<&'_ ArgGroup> for ArgGroup { - fn from(g: &ArgGroup) -> Self { - g.clone() - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn groups() { - let g = ArgGroup::new("test") - .arg("a1") - .arg("a4") - .args(["a2", "a3"]) - .required(true) - .conflicts_with("c1") - .conflicts_with_all(["c2", "c3"]) - .conflicts_with("c4") - .requires("r1") - .requires_all(["r2", "r3"]) - .requires("r4"); - - let args: Vec<Id> = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; - let reqs: Vec<Id> = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; - let confs: Vec<Id> = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; - - assert_eq!(g.args, args); - assert_eq!(g.requires, reqs); - assert_eq!(g.conflicts, confs); - } - - #[test] - fn test_from() { - let g = ArgGroup::new("test") - .arg("a1") - .arg("a4") - .args(["a2", "a3"]) - .required(true) - .conflicts_with("c1") - .conflicts_with_all(["c2", "c3"]) - .conflicts_with("c4") - .requires("r1") - .requires_all(["r2", "r3"]) - .requires("r4"); - - let args: Vec<Id> = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; - let reqs: Vec<Id> = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; - let confs: Vec<Id> = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; - - let g2 = ArgGroup::from(&g); - assert_eq!(g2.args, args); - assert_eq!(g2.requires, reqs); - assert_eq!(g2.conflicts, confs); - } - - // This test will *fail to compile* if ArgGroup is not Send + Sync - #[test] - fn arg_group_send_sync() { - fn foo<T: Send + Sync>(_: T) {} - foo(ArgGroup::new("test")) - } - - #[test] - fn arg_group_expose_is_multiple_helper() { - let args: Vec<Id> = vec!["a1".into(), "a4".into()]; - - let mut grp_multiple = ArgGroup::new("test_multiple").args(&args).multiple(true); - assert!(grp_multiple.is_multiple()); - - let mut grp_not_multiple = ArgGroup::new("test_multiple").args(&args).multiple(false); - assert!(!grp_not_multiple.is_multiple()); - } - - #[test] - fn arg_group_expose_get_args_helper() { - let args: Vec<Id> = vec!["a1".into(), "a4".into()]; - let grp = ArgGroup::new("program").args(&args); - - for (pos, arg) in grp.get_args().enumerate() { - assert_eq!(*arg, args[pos]); - } - } -} diff --git a/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<S: Into<OsStr>> From<S> 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<Str>, - short_flag: Option<char>, - display_name: Option<String>, - bin_name: Option<String>, - author: Option<Str>, - version: Option<Str>, - long_version: Option<Str>, - about: Option<StyledStr>, - long_about: Option<StyledStr>, - before_help: Option<StyledStr>, - before_long_help: Option<StyledStr>, - after_help: Option<StyledStr>, - after_long_help: Option<StyledStr>, - aliases: Vec<(Str, bool)>, // (name, visible) - short_flag_aliases: Vec<(char, bool)>, // (name, visible) - long_flag_aliases: Vec<(Str, bool)>, // (name, visible) - usage_str: Option<StyledStr>, - usage_name: Option<String>, - help_str: Option<StyledStr>, - disp_ord: Option<usize>, - term_w: Option<usize>, - max_w: Option<usize>, - #[cfg(feature = "help")] - template: Option<StyledStr>, - settings: AppFlags, - g_settings: AppFlags, - args: MKeyMap, - subcommands: Vec<Command>, - replacers: FlatMap<Str, Vec<Str>>, - groups: Vec<ArgGroup>, - current_help_heading: Option<Str>, - current_disp_ord: Option<usize>, - subcommand_value_name: Option<Str>, - subcommand_heading: Option<Str>, - external_value_parser: Option<super::ValueParser>, - long_help_exists: bool, -} - -/// # Basic API -impl Command { - /// Creates a new instance of an `Command`. - /// - /// It is common, but not required, to use binary name as the `name`. This - /// name will only be displayed to the user when they request to print - /// version or help and usage information. - /// - /// See also [`command!`](crate::command!) and [`crate_name!`](crate::crate_name!). - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("My Program") - /// # ; - /// ``` - pub fn new(name: impl Into<Str>) -> Self { - /// The actual implementation of `new`, non-generic to save code size. - /// - /// If we don't do this rustc will unnecessarily generate multiple versions - /// of this code. - fn new_inner(name: Str) -> Command { - Command { - name, - ..Default::default() - } - } - - new_inner(name.into()) - } - - /// Adds an [argument] to the list of valid possibilities. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, arg, Arg}; - /// Command::new("myprog") - /// // Adding a single "flag" argument with a short and help text, using Arg::new() - /// .arg( - /// Arg::new("debug") - /// .short('d') - /// .help("turns on debugging mode") - /// ) - /// // Adding a single "option" argument with a short, a long, and help text using the less - /// // verbose Arg::from() - /// .arg( - /// arg!(-c --config <CONFIG> "Optionally sets a config file to use") - /// ) - /// # ; - /// ``` - /// [argument]: Arg - #[must_use] - pub fn arg(mut self, a: impl Into<Arg>) -> Self { - let arg = a.into(); - self.arg_internal(arg); - self - } - - fn arg_internal(&mut self, mut arg: Arg) { - if let Some(current_disp_ord) = self.current_disp_ord.as_mut() { - if !arg.is_positional() { - let current = *current_disp_ord; - arg.disp_ord.get_or_insert(current); - *current_disp_ord = current + 1; - } - } - - arg.help_heading - .get_or_insert_with(|| self.current_help_heading.clone()); - self.args.push(arg); - } - - /// Adds multiple [arguments] to the list of valid possibilities. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, arg, Arg}; - /// Command::new("myprog") - /// .args([ - /// arg!("[debug] -d 'turns on debugging info'"), - /// Arg::new("input").help("the input file to use") - /// ]) - /// # ; - /// ``` - /// [arguments]: Arg - #[must_use] - pub fn args(mut self, args: impl IntoIterator<Item = impl Into<Arg>>) -> Self { - for arg in args { - self = self.arg(arg); - } - self - } - - /// Allows one to mutate an [`Arg`] after it's been added to a [`Command`]. - /// - /// This can be useful for modifying the auto-generated help or version arguments. - /// - /// # Panics - /// - /// If the argument is undefined - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// - /// let mut cmd = Command::new("foo") - /// .arg(Arg::new("bar") - /// .short('b') - /// .action(ArgAction::SetTrue)) - /// .mut_arg("bar", |a| a.short('B')); - /// - /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]); - /// - /// // Since we changed `bar`'s short to "B" this should err as there - /// // is no `-b` anymore, only `-B` - /// - /// assert!(res.is_err()); - /// - /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]); - /// assert!(res.is_ok()); - /// ``` - #[must_use] - #[cfg_attr(debug_assertions, track_caller)] - pub fn mut_arg<F>(mut self, arg_id: impl AsRef<str>, f: F) -> Self - where - F: FnOnce(Arg) -> Arg, - { - let id = arg_id.as_ref(); - let a = self - .args - .remove_by_name(id) - .unwrap_or_else(|| panic!("Argument `{}` 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<F>(mut self, name: impl AsRef<str>, f: F) -> Self - where - F: FnOnce(Self) -> Self, - { - let name = name.as_ref(); - let pos = self.subcommands.iter().position(|s| s.name == name); - - let subcmd = if let Some(idx) = pos { - self.subcommands.remove(idx) - } else { - panic!("Command `{}` 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<ArgGroup>) -> Self { - self.groups.push(group.into()); - self - } - - /// Adds multiple [`ArgGroup`]s to the [`Command`] at once. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, arg, ArgGroup}; - /// Command::new("cmd") - /// .arg(arg!("--set-ver [ver] 'set the version manually'")) - /// .arg(arg!("--major 'auto increase major'")) - /// .arg(arg!("--minor 'auto increase minor'")) - /// .arg(arg!("--patch 'auto increase patch'")) - /// .arg(arg!("-c [FILE] 'a config file'")) - /// .arg(arg!("-i [IFACE] 'an interface'")) - /// .groups([ - /// ArgGroup::new("vers") - /// .args(["set-ver", "major", "minor","patch"]) - /// .required(true), - /// ArgGroup::new("input") - /// .args(["c", "i"]) - /// ]) - /// # ; - /// ``` - #[must_use] - pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<ArgGroup>>) -> Self { - for g in groups.into_iter() { - self = self.group(g.into()); - } - self - } - - /// Adds a subcommand to the list of valid possibilities. - /// - /// Subcommands are effectively sub-[`Command`]s, because they can contain their own arguments, - /// subcommands, version, usage, etc. They also function just like [`Command`]s, in that they get - /// their own auto generated help, version, and usage. - /// - /// A subcommand's [`Command::name`] will be used for: - /// - The argument the user passes in - /// - Programmatically looking up the subcommand - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("config") - /// .about("Controls configuration features") - /// .arg(arg!("<config> 'Required configuration file to use'"))) - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn subcommand(self, subcmd: impl Into<Command>) -> Self { - let subcmd = subcmd.into(); - self.subcommand_internal(subcmd) - } - - fn subcommand_internal(mut self, mut subcmd: Self) -> Self { - if let Some(current_disp_ord) = self.current_disp_ord.as_mut() { - let current = *current_disp_ord; - subcmd.disp_ord.get_or_insert(current); - *current_disp_ord = current + 1; - } - self.subcommands.push(subcmd); - self - } - - /// Adds multiple subcommands to the list of valid possibilities. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, }; - /// # Command::new("myprog") - /// .subcommands( [ - /// Command::new("config").about("Controls configuration functionality") - /// .arg(Arg::new("config_file")), - /// Command::new("debug").about("Controls debug functionality")]) - /// # ; - /// ``` - /// [`IntoIterator`]: std::iter::IntoIterator - #[must_use] - pub fn subcommands(mut self, subcmds: impl IntoIterator<Item = impl Into<Self>>) -> Self { - for subcmd in subcmds { - self = self.subcommand(subcmd); - } - self - } - - /// Catch problems earlier in the development cycle. - /// - /// Most error states are handled as asserts under the assumption they are programming mistake - /// and not something to handle at runtime. Rather than relying on tests (manual or automated) - /// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those - /// asserts in a way convenient for running as a test. - /// - /// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive - /// testing of your CLI. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// fn cmd() -> Command { - /// Command::new("foo") - /// .arg( - /// Arg::new("bar").short('b').action(ArgAction::SetTrue) - /// ) - /// } - /// - /// #[test] - /// fn verify_app() { - /// cmd().debug_assert(); - /// } - /// - /// fn main() { - /// let m = cmd().get_matches_from(vec!["foo", "-b"]); - /// println!("{}", m.get_flag("bar")); - /// } - /// ``` - pub fn debug_assert(mut self) { - self.build(); - } - - /// Custom error message for post-parsing validation - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, error::ErrorKind}; - /// let mut cmd = Command::new("myprog"); - /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case"); - /// ``` - pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error { - Error::raw(kind, message).format(self) - } - - /// Parse [`env::args_os`], exiting on failure. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let matches = Command::new("myprog") - /// // Args and options go here... - /// .get_matches(); - /// ``` - /// [`env::args_os`]: std::env::args_os() - /// [`Command::try_get_matches_from_mut`]: Command::try_get_matches_from_mut() - #[inline] - pub fn get_matches(self) -> ArgMatches { - self.get_matches_from(env::args_os()) - } - - /// Parse [`env::args_os`], exiting on failure. - /// - /// Like [`Command::get_matches`] but doesn't consume the `Command`. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let mut cmd = Command::new("myprog") - /// // Args and options go here... - /// ; - /// let matches = cmd.get_matches_mut(); - /// ``` - /// [`env::args_os`]: std::env::args_os() - /// [`Command::get_matches`]: Command::get_matches() - pub fn get_matches_mut(&mut self) -> ArgMatches { - self.try_get_matches_from_mut(&mut env::args_os()) - .unwrap_or_else(|e| e.exit()) - } - - /// Parse [`env::args_os`], returning a [`clap::Result`] on failure. - /// - /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are - /// used. It will return a [`clap::Error`], where the [`kind`] is a - /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call - /// [`Error::exit`] or perform a [`std::process::exit`]. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let matches = Command::new("myprog") - /// // Args and options go here... - /// .try_get_matches() - /// .unwrap_or_else(|e| e.exit()); - /// ``` - /// [`env::args_os`]: std::env::args_os() - /// [`Error::exit`]: crate::Error::exit() - /// [`std::process::exit`]: std::process::exit() - /// [`clap::Result`]: Result - /// [`clap::Error`]: crate::Error - /// [`kind`]: crate::Error - /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp - /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion - #[inline] - pub fn try_get_matches(self) -> ClapResult<ArgMatches> { - // Start the parsing - self.try_get_matches_from(env::args_os()) - } - - /// Parse the specified arguments, exiting on failure. - /// - /// **NOTE:** The first argument will be parsed as the binary name unless - /// [`Command::no_binary_name`] is used. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; - /// - /// let matches = Command::new("myprog") - /// // Args and options go here... - /// .get_matches_from(arg_vec); - /// ``` - /// [`Command::get_matches`]: Command::get_matches() - /// [`clap::Result`]: Result - /// [`Vec`]: std::vec::Vec - pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches - where - I: IntoIterator<Item = T>, - T: Into<OsString> + Clone, - { - self.try_get_matches_from_mut(itr).unwrap_or_else(|e| { - drop(self); - e.exit() - }) - } - - /// Parse the specified arguments, returning a [`clap::Result`] on failure. - /// - /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are - /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] - /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or - /// perform a [`std::process::exit`] yourself. - /// - /// **NOTE:** The first argument will be parsed as the binary name unless - /// [`Command::no_binary_name`] is used. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; - /// - /// let matches = Command::new("myprog") - /// // Args and options go here... - /// .try_get_matches_from(arg_vec) - /// .unwrap_or_else(|e| e.exit()); - /// ``` - /// [`Command::get_matches_from`]: Command::get_matches_from() - /// [`Command::try_get_matches`]: Command::try_get_matches() - /// [`Error::exit`]: crate::Error::exit() - /// [`std::process::exit`]: std::process::exit() - /// [`clap::Error`]: crate::Error - /// [`Error::exit`]: crate::Error::exit() - /// [`kind`]: crate::Error - /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp - /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion - /// [`clap::Result`]: Result - pub fn try_get_matches_from<I, T>(mut self, itr: I) -> ClapResult<ArgMatches> - where - I: IntoIterator<Item = T>, - T: Into<OsString> + Clone, - { - self.try_get_matches_from_mut(itr) - } - - /// Parse the specified arguments, returning a [`clap::Result`] on failure. - /// - /// Like [`Command::try_get_matches_from`] but doesn't consume the `Command`. - /// - /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are - /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] - /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or - /// perform a [`std::process::exit`] yourself. - /// - /// **NOTE:** The first argument will be parsed as the binary name unless - /// [`Command::no_binary_name`] is used. - /// - /// # Panics - /// - /// If contradictory arguments or settings exist. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; - /// - /// let mut cmd = Command::new("myprog"); - /// // Args and options go here... - /// let matches = cmd.try_get_matches_from_mut(arg_vec) - /// .unwrap_or_else(|e| e.exit()); - /// ``` - /// [`Command::try_get_matches_from`]: Command::try_get_matches_from() - /// [`clap::Result`]: Result - /// [`clap::Error`]: crate::Error - /// [`kind`]: crate::Error - pub fn try_get_matches_from_mut<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches> - where - I: IntoIterator<Item = T>, - T: Into<OsString> + Clone, - { - let mut raw_args = clap_lex::RawArgs::new(itr.into_iter()); - let mut cursor = raw_args.cursor(); - - if self.settings.is_set(AppSettings::Multicall) { - if let Some(argv0) = raw_args.next_os(&mut cursor) { - let argv0 = Path::new(&argv0); - if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) { - // Stop borrowing command so we can get another mut ref to it. - let command = command.to_owned(); - debug!( - "Command::try_get_matches_from_mut: Parsed command {} from argv", - command - ); - - debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it"); - raw_args.insert(&cursor, [&command]); - debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name"); - self.name = "".into(); - self.bin_name = None; - return self._do_parse(&mut raw_args, cursor); - } - } - }; - - // Get the name of the program (argument 1 of env::args()) and determine the - // actual file - // that was used to execute the program. This is because a program called - // ./target/release/my_prog -a - // will have two arguments, './target/release/my_prog', '-a' but we don't want - // to display - // the full path when displaying help messages and such - if !self.settings.is_set(AppSettings::NoBinaryName) { - if let Some(name) = raw_args.next_os(&mut cursor) { - let p = Path::new(name); - - if let Some(f) = p.file_name() { - if let Some(s) = f.to_str() { - if self.bin_name.is_none() { - self.bin_name = Some(s.to_owned()); - } - } - } - } - } - - self._do_parse(&mut raw_args, cursor) - } - - /// Prints the short help message (`-h`) to [`io::stdout()`]. - /// - /// See also [`Command::print_long_help`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// let mut cmd = Command::new("myprog"); - /// cmd.print_help(); - /// ``` - /// [`io::stdout()`]: std::io::stdout() - pub fn print_help(&mut self) -> io::Result<()> { - self._build_self(false); - let color = self.color_help(); - - let mut styled = StyledStr::new(); - let usage = Usage::new(self); - write_help(&mut styled, self, &usage, false); - - let c = Colorizer::new(Stream::Stdout, color).with_content(styled); - c.print() - } - - /// Prints the long help message (`--help`) to [`io::stdout()`]. - /// - /// See also [`Command::print_help`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// let mut cmd = Command::new("myprog"); - /// cmd.print_long_help(); - /// ``` - /// [`io::stdout()`]: std::io::stdout() - /// [`BufWriter`]: std::io::BufWriter - /// [`-h` (short)]: Arg::help() - /// [`--help` (long)]: Arg::long_help() - pub fn print_long_help(&mut self) -> io::Result<()> { - self._build_self(false); - let color = self.color_help(); - - let mut styled = StyledStr::new(); - let usage = Usage::new(self); - write_help(&mut styled, self, &usage, true); - - let c = Colorizer::new(Stream::Stdout, color).with_content(styled); - c.print() - } - - /// Render the short help message (`-h`) to a [`StyledStr`] - /// - /// See also [`Command::render_long_help`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// use std::io; - /// let mut cmd = Command::new("myprog"); - /// let mut out = io::stdout(); - /// let help = cmd.render_help(); - /// println!("{}", help); - /// ``` - /// [`io::Write`]: std::io::Write - /// [`-h` (short)]: Arg::help() - /// [`--help` (long)]: Arg::long_help() - pub fn render_help(&mut self) -> StyledStr { - self._build_self(false); - - let mut styled = StyledStr::new(); - let usage = Usage::new(self); - write_help(&mut styled, self, &usage, false); - styled - } - - /// Render the long help message (`--help`) to a [`StyledStr`]. - /// - /// See also [`Command::render_help`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// use std::io; - /// let mut cmd = Command::new("myprog"); - /// let mut out = io::stdout(); - /// let help = cmd.render_long_help(); - /// println!("{}", help); - /// ``` - /// [`io::Write`]: std::io::Write - /// [`-h` (short)]: Arg::help() - /// [`--help` (long)]: Arg::long_help() - pub fn render_long_help(&mut self) -> StyledStr { - self._build_self(false); - - let mut styled = StyledStr::new(); - let usage = Usage::new(self); - write_help(&mut styled, self, &usage, true); - styled - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Command::render_help`") - )] - pub fn write_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> { - self._build_self(false); - - let mut styled = StyledStr::new(); - let usage = Usage::new(self); - write_help(&mut styled, self, &usage, false); - ok!(write!(w, "{}", styled)); - w.flush() - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Command::render_long_help`") - )] - pub fn write_long_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> { - self._build_self(false); - - let mut styled = StyledStr::new(); - let usage = Usage::new(self); - write_help(&mut styled, self, &usage, true); - ok!(write!(w, "{}", styled)); - w.flush() - } - - /// Version message rendered as if the user ran `-V`. - /// - /// See also [`Command::render_long_version`]. - /// - /// ### Coloring - /// - /// This function does not try to color the message nor it inserts any [ANSI escape codes]. - /// - /// ### Examples - /// - /// ```rust - /// # use clap::Command; - /// use std::io; - /// let cmd = Command::new("myprog"); - /// println!("{}", cmd.render_version()); - /// ``` - /// [`io::Write`]: std::io::Write - /// [`-V` (short)]: Command::version() - /// [`--version` (long)]: Command::long_version() - /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code - pub fn render_version(&self) -> String { - self._render_version(false) - } - - /// Version message rendered as if the user ran `--version`. - /// - /// See also [`Command::render_version`]. - /// - /// ### Coloring - /// - /// This function does not try to color the message nor it inserts any [ANSI escape codes]. - /// - /// ### Examples - /// - /// ```rust - /// # use clap::Command; - /// use std::io; - /// let cmd = Command::new("myprog"); - /// println!("{}", cmd.render_long_version()); - /// ``` - /// [`io::Write`]: std::io::Write - /// [`-V` (short)]: Command::version() - /// [`--version` (long)]: Command::long_version() - /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code - pub fn render_long_version(&self) -> String { - self._render_version(true) - } - - /// Usage statement - /// - /// ### Examples - /// - /// ```rust - /// # use clap::Command; - /// use std::io; - /// let mut cmd = Command::new("myprog"); - /// println!("{}", cmd.render_usage()); - /// ``` - pub fn render_usage(&mut self) -> StyledStr { - self.render_usage_().unwrap_or_default() - } - - pub(crate) fn render_usage_(&mut self) -> Option<StyledStr> { - // If there are global arguments, or settings we need to propagate them down to subcommands - // before parsing incase we run into a subcommand - self._build_self(false); - - Usage::new(self).create_usage_with_title(&[]) - } -} - -/// # Application-wide Settings -/// -/// These settings will apply to the top-level command and all subcommands, by default. Some -/// settings can be overridden in subcommands. -impl Command { - /// Specifies that the parser should not assume the first argument passed is the binary name. - /// - /// This is normally the case when using a "daemon" style mode. For shells / REPLs, see - /// [`Command::multicall`][Command::multicall]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, arg}; - /// let m = Command::new("myprog") - /// .no_binary_name(true) - /// .arg(arg!(<cmd> ... "commands to run")) - /// .get_matches_from(vec!["command", "set"]); - /// - /// let cmds: Vec<_> = m.get_many::<String>("cmd").unwrap().collect(); - /// assert_eq!(cmds, ["command", "set"]); - /// ``` - /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut() - #[inline] - pub fn no_binary_name(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::NoBinaryName) - } else { - self.unset_global_setting(AppSettings::NoBinaryName) - } - } - - /// Try not to fail on parse errors, like missing option values. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, arg}; - /// let cmd = Command::new("cmd") - /// .ignore_errors(true) - /// .arg(arg!(-c --config <FILE> "Sets a custom config file")) - /// .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file")) - /// .arg(arg!(f: -f "Flag")); - /// - /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]); - /// - /// assert!(r.is_ok(), "unexpected error: {:?}", r); - /// let m = r.unwrap(); - /// assert_eq!(m.get_one::<String>("config").unwrap(), "file"); - /// assert!(m.get_flag("f")); - /// assert_eq!(m.get_one::<String>("stuff"), None); - /// ``` - #[inline] - pub fn ignore_errors(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::IgnoreErrors) - } else { - self.unset_global_setting(AppSettings::IgnoreErrors) - } - } - - /// Replace prior occurrences of arguments rather than error - /// - /// For any argument that would conflict with itself by default (e.g. - /// [`ArgAction::Set`][ArgAction::Set], it will now override itself. - /// - /// This is the equivalent to saying the `foo` arg using [`Arg::overrides_with("foo")`] for all - /// defined arguments. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// [`Arg::overrides_with("foo")`]: crate::Arg::overrides_with() - #[inline] - pub fn args_override_self(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::AllArgsOverrideSelf) - } else { - self.unset_global_setting(AppSettings::AllArgsOverrideSelf) - } - } - - /// Disables the automatic delimiting of values after `--` or when [`Command::trailing_var_arg`] - /// was used. - /// - /// **NOTE:** The same thing can be done manually by setting the final positional argument to - /// [`Arg::value_delimiter(None)`]. Using this setting is safer, because it's easier to locate - /// when making changes. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .dont_delimit_trailing_values(true) - /// .get_matches(); - /// ``` - /// - /// [`Arg::value_delimiter(None)`]: crate::Arg::value_delimiter() - #[inline] - pub fn dont_delimit_trailing_values(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DontDelimitTrailingValues) - } else { - self.unset_global_setting(AppSettings::DontDelimitTrailingValues) - } - } - - /// Sets when to color output. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// **NOTE:** Default behaviour is [`ColorChoice::Auto`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, ColorChoice}; - /// Command::new("myprog") - /// .color(ColorChoice::Never) - /// .get_matches(); - /// ``` - /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto - #[cfg(feature = "color")] - #[inline] - #[must_use] - pub fn color(self, color: ColorChoice) -> Self { - let cmd = self - .unset_global_setting(AppSettings::ColorAuto) - .unset_global_setting(AppSettings::ColorAlways) - .unset_global_setting(AppSettings::ColorNever); - match color { - ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto), - ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways), - ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever), - } - } - - /// Sets the terminal width at which to wrap help messages. - /// - /// Using `0` will ignore terminal widths and use source formatting. - /// - /// Defaults to current terminal width when `wrap_help` feature flag is enabled. If the flag - /// is disabled or it cannot be determined, the default is 100. - /// - /// **NOTE:** This setting applies globally and *not* on a per-command basis. - /// - /// **NOTE:** This requires the [`wrap_help` feature][crate::_features] - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .term_width(80) - /// # ; - /// ``` - #[inline] - #[must_use] - #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))] - pub fn term_width(mut self, width: usize) -> Self { - self.term_w = Some(width); - self - } - - /// Limit the line length for wrapping help when using the current terminal's width. - /// - /// This only applies when [`term_width`][Command::term_width] is unset so that the current - /// terminal's width will be used. See [`Command::term_width`] for more details. - /// - /// Using `0` will ignore terminal widths and use source formatting (default). - /// - /// **NOTE:** This setting applies globally and *not* on a per-command basis. - /// - /// **NOTE:** This requires the [`wrap_help` feature][crate::_features] - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .max_term_width(100) - /// # ; - /// ``` - #[inline] - #[must_use] - #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))] - pub fn max_term_width(mut self, w: usize) -> Self { - self.max_w = Some(w); - self - } - - /// Disables `-V` and `--version` flag. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, error::ErrorKind}; - /// let res = Command::new("myprog") - /// .disable_version_flag(true) - /// .try_get_matches_from(vec![ - /// "myprog", "-V" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - #[inline] - pub fn disable_version_flag(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DisableVersionFlag) - } else { - self.unset_global_setting(AppSettings::DisableVersionFlag) - } - } - - /// Specifies to use the version of the current command for all [`subcommands`]. - /// - /// Defaults to `false`; subcommands have independent version strings from their parents. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .version("v1.1") - /// .propagate_version(true) - /// .subcommand(Command::new("test")) - /// .get_matches(); - /// // running `$ myprog test --version` will display - /// // "myprog-test v1.1" - /// ``` - /// - /// [`subcommands`]: crate::Command::subcommand() - #[inline] - pub fn propagate_version(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::PropagateVersion) - } else { - self.unset_global_setting(AppSettings::PropagateVersion) - } - } - - /// Places the help string for all arguments and subcommands on the line after them. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .next_line_help(true) - /// .get_matches(); - /// ``` - #[inline] - pub fn next_line_help(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::NextLineHelp) - } else { - self.unset_global_setting(AppSettings::NextLineHelp) - } - } - - /// Disables `-h` and `--help` flag. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, error::ErrorKind}; - /// let res = Command::new("myprog") - /// .disable_help_flag(true) - /// .try_get_matches_from(vec![ - /// "myprog", "-h" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - #[inline] - pub fn disable_help_flag(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DisableHelpFlag) - } else { - self.unset_global_setting(AppSettings::DisableHelpFlag) - } - } - - /// Disables the `help` [`subcommand`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, error::ErrorKind}; - /// let res = Command::new("myprog") - /// .disable_help_subcommand(true) - /// // Normally, creating a subcommand causes a `help` subcommand to automatically - /// // be generated as well - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog", "help" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidSubcommand); - /// ``` - /// - /// [`subcommand`]: crate::Command::subcommand() - #[inline] - pub fn disable_help_subcommand(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DisableHelpSubcommand) - } else { - self.unset_global_setting(AppSettings::DisableHelpSubcommand) - } - } - - /// Disables colorized help messages. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .disable_colored_help(true) - /// .get_matches(); - /// ``` - #[inline] - pub fn disable_colored_help(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::DisableColoredHelp) - } else { - self.unset_global_setting(AppSettings::DisableColoredHelp) - } - } - - /// Panic if help descriptions are omitted. - /// - /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at - /// compile-time with `#![deny(missing_docs)]` - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .help_expected(true) - /// .arg( - /// Arg::new("foo").help("It does foo stuff") - /// // As required via `help_expected`, a help message was supplied - /// ) - /// # .get_matches(); - /// ``` - /// - /// # Panics - /// - /// ```rust,no_run - /// # use clap::{Command, Arg}; - /// Command::new("myapp") - /// .help_expected(true) - /// .arg( - /// Arg::new("foo") - /// // Someone forgot to put .about("...") here - /// // Since the setting `help_expected` is activated, this will lead to - /// // a panic (if you are in debug mode) - /// ) - /// # .get_matches(); - ///``` - #[inline] - pub fn help_expected(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::HelpExpected) - } else { - self.unset_global_setting(AppSettings::HelpExpected) - } - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "This is now the default") - )] - pub fn dont_collapse_args_in_usage(self, _yes: bool) -> Self { - self - } - - /// Tells `clap` *not* to print possible values when displaying help information. - /// - /// This can be useful if there are many values, or they are explained elsewhere. - /// - /// To set this per argument, see - /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values]. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - #[inline] - pub fn hide_possible_values(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::HidePossibleValues) - } else { - self.unset_global_setting(AppSettings::HidePossibleValues) - } - } - - /// Allow partial matches of long arguments or their [aliases]. - /// - /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and - /// `--test`. - /// - /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match - /// `--te` to `--test` there could not also be another argument or alias `--temp` because both - /// start with `--te` - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// [aliases]: crate::Command::aliases() - #[inline] - pub fn infer_long_args(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::InferLongArgs) - } else { - self.unset_global_setting(AppSettings::InferLongArgs) - } - } - - /// Allow partial matches of [subcommand] names and their [aliases]. - /// - /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and - /// `test`. - /// - /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te` - /// to `test` there could not also be a subcommand or alias `temp` because both start with `te` - /// - /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when - /// designing CLIs which allow inferred subcommands and have potential positional/free - /// arguments whose values could start with the same characters as subcommands. If this is the - /// case, it's recommended to use settings such as [`Command::args_conflicts_with_subcommands`] in - /// conjunction with this setting. - /// - /// **NOTE:** This choice is propagated to all child subcommands. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let m = Command::new("prog") - /// .infer_subcommands(true) - /// .subcommand(Command::new("test")) - /// .get_matches_from(vec![ - /// "prog", "te" - /// ]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// - /// [subcommand]: crate::Command::subcommand() - /// [positional/free arguments]: crate::Arg::index() - /// [aliases]: crate::Command::aliases() - #[inline] - pub fn infer_subcommands(self, yes: bool) -> Self { - if yes { - self.global_setting(AppSettings::InferSubcommands) - } else { - self.unset_global_setting(AppSettings::InferSubcommands) - } - } -} - -/// # Command-specific Settings -/// -/// These apply only to the current command and are not inherited by subcommands. -impl Command { - /// (Re)Sets the program's name. - /// - /// See [`Command::new`] for more details. - /// - /// # Examples - /// - /// ```ignore - /// let cmd = clap::command!() - /// .name("foo"); - /// - /// // continued logic goes here, such as `cmd.get_matches()` etc. - /// ``` - #[must_use] - pub fn name(mut self, name: impl Into<Str>) -> Self { - self.name = name.into(); - self - } - - /// Overrides the runtime-determined name of the binary for help and error messages. - /// - /// This should only be used when absolutely necessary, such as when the binary name for your - /// application is misleading, or perhaps *not* how the user should invoke your program. - /// - /// **Pro-tip:** When building things such as third party `cargo` - /// subcommands, this setting **should** be used! - /// - /// **NOTE:** This *does not* change or set the name of the binary file on - /// disk. It only changes what clap thinks the name is for the purposes of - /// error or help messages. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("My Program") - /// .bin_name("my_binary") - /// # ; - /// ``` - #[must_use] - pub fn bin_name(mut self, name: impl IntoResettable<String>) -> Self { - self.bin_name = name.into_resettable().into_option(); - self - } - - /// Overrides the runtime-determined display name of the program for help and error messages. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("My Program") - /// .display_name("my_program") - /// # ; - /// ``` - #[must_use] - pub fn display_name(mut self, name: impl IntoResettable<String>) -> Self { - self.display_name = name.into_resettable().into_option(); - self - } - - /// Sets the author(s) for the help message. - /// - /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to - /// automatically set your application's author(s) to the same thing as your - /// crate at compile time. - /// - /// **NOTE:** A custom [`help_template`][Command::help_template] is needed for author to show - /// up. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .author("Me, me@mymain.com") - /// # ; - /// ``` - #[must_use] - pub fn author(mut self, author: impl IntoResettable<Str>) -> Self { - self.author = author.into_resettable().into_option(); - self - } - - /// Sets the program's description for the short help (`-h`). - /// - /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`. - /// - /// **NOTE:** Only `Command::about` (short format) is used in completion - /// script generation in order to be concise. - /// - /// See also [`crate_description!`](crate::crate_description!). - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .about("Does really amazing things for great people") - /// # ; - /// ``` - #[must_use] - pub fn about(mut self, about: impl IntoResettable<StyledStr>) -> Self { - self.about = about.into_resettable().into_option(); - self - } - - /// Sets the program's description for the long help (`--help`). - /// - /// If [`Command::about`] is not specified, this message will be displayed for `-h`. - /// - /// **NOTE:** Only [`Command::about`] (short format) is used in completion - /// script generation in order to be concise. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .long_about( - /// "Does really amazing things to great people. Now let's talk a little - /// more in depth about how this subcommand really works. It may take about - /// a few lines of text, but that's ok!") - /// # ; - /// ``` - /// [`Command::about`]: Command::about() - #[must_use] - pub fn long_about(mut self, long_about: impl IntoResettable<StyledStr>) -> Self { - self.long_about = long_about.into_resettable().into_option(); - self - } - - /// Free-form help text for after auto-generated short help (`-h`). - /// - /// This is often used to describe how to use the arguments, caveats to be noted, or license - /// and contact information. - /// - /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .after_help("Does really amazing things for great people... but be careful with -R!") - /// # ; - /// ``` - /// - #[must_use] - pub fn after_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { - self.after_help = help.into_resettable().into_option(); - self - } - - /// Free-form help text for after auto-generated long help (`--help`). - /// - /// This is often used to describe how to use the arguments, caveats to be noted, or license - /// and contact information. - /// - /// If [`Command::after_help`] is not specified, this message will be displayed for `-h`. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .after_long_help("Does really amazing things to great people... but be careful with -R, \ - /// like, for real, be careful with this!") - /// # ; - /// ``` - #[must_use] - pub fn after_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { - self.after_long_help = help.into_resettable().into_option(); - self - } - - /// Free-form help text for before auto-generated short help (`-h`). - /// - /// This is often used for header, copyright, or license information. - /// - /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .before_help("Some info I'd like to appear before the help info") - /// # ; - /// ``` - #[must_use] - pub fn before_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { - self.before_help = help.into_resettable().into_option(); - self - } - - /// Free-form help text for before auto-generated long help (`--help`). - /// - /// This is often used for header, copyright, or license information. - /// - /// If [`Command::before_help`] is not specified, this message will be displayed for `-h`. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .before_long_help("Some verbose and long info I'd like to appear before the help info") - /// # ; - /// ``` - #[must_use] - pub fn before_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { - self.before_long_help = help.into_resettable().into_option(); - self - } - - /// Sets the version for the short version (`-V`) and help messages. - /// - /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`. - /// - /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to - /// automatically set your application's version to the same thing as your - /// crate at compile time. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .version("v0.1.24") - /// # ; - /// ``` - #[must_use] - pub fn version(mut self, ver: impl IntoResettable<Str>) -> Self { - self.version = ver.into_resettable().into_option(); - self - } - - /// Sets the version for the long version (`--version`) and help messages. - /// - /// If [`Command::version`] is not specified, this message will be displayed for `-V`. - /// - /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to - /// automatically set your application's version to the same thing as your - /// crate at compile time. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .long_version( - /// "v0.1.24 - /// commit: abcdef89726d - /// revision: 123 - /// release: 2 - /// binary: myprog") - /// # ; - /// ``` - #[must_use] - pub fn long_version(mut self, ver: impl IntoResettable<Str>) -> Self { - self.long_version = ver.into_resettable().into_option(); - self - } - - /// Overrides the `clap` generated usage string for help and error messages. - /// - /// **NOTE:** Using this setting disables `clap`s "context-aware" usage - /// strings. After this setting is set, this will be *the only* usage string - /// displayed to the user! - /// - /// **NOTE:** Multiple usage lines may be present in the usage argument, but - /// some rules need to be followed to ensure the usage lines are formatted - /// correctly by the default help formatter: - /// - /// - Do not indent the first usage line. - /// - Indent all subsequent usage lines with seven spaces. - /// - The last line must not end with a newline. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .override_usage("myapp [-clDas] <some_file>") - /// # ; - /// ``` - /// - /// Or for multiple usage lines: - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .override_usage( - /// "myapp -X [-a] [-b] <file>\n \ - /// myapp -Y [-c] <file1> <file2>\n \ - /// myapp -Z [-d|-e]" - /// ) - /// # ; - /// ``` - /// - /// [`ArgMatches::usage`]: ArgMatches::usage() - #[must_use] - pub fn override_usage(mut self, usage: impl IntoResettable<StyledStr>) -> Self { - self.usage_str = usage.into_resettable().into_option(); - self - } - - /// Overrides the `clap` generated help message (both `-h` and `--help`). - /// - /// This should only be used when the auto-generated message does not suffice. - /// - /// **NOTE:** This **only** replaces the help message for the current - /// command, meaning if you are using subcommands, those help messages will - /// still be auto-generated unless you specify a [`Command::override_help`] for - /// them as well. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myapp") - /// .override_help("myapp v1.0\n\ - /// Does awesome things\n\ - /// (C) me@mail.com\n\n\ - /// - /// Usage: myapp <opts> <command>\n\n\ - /// - /// Options:\n\ - /// -h, --help Display this message\n\ - /// -V, --version Display version info\n\ - /// -s <stuff> Do something with stuff\n\ - /// -v Be verbose\n\n\ - /// - /// Commands:\n\ - /// help Print this message\n\ - /// work Do some work") - /// # ; - /// ``` - #[must_use] - pub fn override_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { - self.help_str = help.into_resettable().into_option(); - self - } - - /// Sets the help template to be used, overriding the default format. - /// - /// **NOTE:** The template system is by design very simple. Therefore, the - /// tags have to be written in the lowercase and without spacing. - /// - /// Tags are given inside curly brackets. - /// - /// Valid tags are: - /// - /// * `{name}` - Display name for the (sub-)command. - /// * `{bin}` - Binary name.(deprecated) - /// * `{version}` - Version number. - /// * `{author}` - Author information. - /// * `{author-with-newline}` - Author followed by `\n`. - /// * `{author-section}` - Author preceded and followed by `\n`. - /// * `{about}` - General description (from [`Command::about`] or - /// [`Command::long_about`]). - /// * `{about-with-newline}` - About followed by `\n`. - /// * `{about-section}` - About preceded and followed by '\n'. - /// * `{usage-heading}` - Automatically generated usage heading. - /// * `{usage}` - Automatically generated or given usage string. - /// * `{all-args}` - Help for all arguments (options, flags, positional - /// arguments, and subcommands) including titles. - /// * `{options}` - Help for options. - /// * `{positionals}` - Help for positional arguments. - /// * `{subcommands}` - Help for subcommands. - /// * `{tab}` - Standard tab sized used within clap - /// * `{after-help}` - Help from [`Command::after_help`] or [`Command::after_long_help`]. - /// * `{before-help}` - Help from [`Command::before_help`] or [`Command::before_long_help`]. - /// - /// # Examples - /// - /// For a very brief help: - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .version("1.0") - /// .help_template("{name} ({version}) - {usage}") - /// # ; - /// ``` - /// - /// For showing more application context: - /// - /// ```no_run - /// # use clap::Command; - /// Command::new("myprog") - /// .version("1.0") - /// .help_template("\ - /// {before-help}{name} {version} - /// {author-with-newline}{about-with-newline} - /// {usage-heading} {usage} - /// - /// {all-args}{after-help} - /// ") - /// # ; - /// ``` - /// [`Command::about`]: Command::about() - /// [`Command::long_about`]: Command::long_about() - /// [`Command::after_help`]: Command::after_help() - /// [`Command::after_long_help`]: Command::after_long_help() - /// [`Command::before_help`]: Command::before_help() - /// [`Command::before_long_help`]: Command::before_long_help() - #[must_use] - #[cfg(feature = "help")] - pub fn help_template(mut self, s: impl IntoResettable<StyledStr>) -> Self { - self.template = s.into_resettable().into_option(); - self - } - - #[inline] - #[must_use] - pub(crate) fn setting<F>(mut self, setting: F) -> Self - where - F: Into<AppFlags>, - { - self.settings.insert(setting.into()); - self - } - - #[inline] - #[must_use] - pub(crate) fn unset_setting<F>(mut self, setting: F) -> Self - where - F: Into<AppFlags>, - { - self.settings.remove(setting.into()); - self - } - - #[inline] - #[must_use] - pub(crate) fn global_setting(mut self, setting: AppSettings) -> Self { - self.settings.set(setting); - self.g_settings.set(setting); - self - } - - #[inline] - #[must_use] - pub(crate) fn unset_global_setting(mut self, setting: AppSettings) -> Self { - self.settings.unset(setting); - self.g_settings.unset(setting); - self - } - - /// Set the default section heading for future args. - /// - /// This will be used for any arg that hasn't had [`Arg::help_heading`] called. - /// - /// This is useful if the default `Options` or `Arguments` headings are - /// not specific enough for one's use case. - /// - /// For subcommands, see [`Command::subcommand_help_heading`] - /// - /// [`Command::arg`]: Command::arg() - /// [`Arg::help_heading`]: crate::Arg::help_heading() - #[inline] - #[must_use] - pub fn next_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self { - self.current_help_heading = heading.into_resettable().into_option(); - self - } - - /// Change the starting value for assigning future display orders for ags. - /// - /// This will be used for any arg that hasn't had [`Arg::display_order`] called. - #[inline] - #[must_use] - pub fn next_display_order(mut self, disp_ord: impl IntoResettable<usize>) -> Self { - self.current_disp_ord = disp_ord.into_resettable().into_option(); - self - } - - /// Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands. - /// - /// **Note:** This is gated behind [`unstable-replace`](https://github.com/clap-rs/clap/issues/2836) - /// - /// When this method is used, `name` is removed from the CLI, and `target` - /// is inserted in its place. Parsing continues as if the user typed - /// `target` instead of `name`. - /// - /// This can be used to create "shortcuts" for subcommands, or if a - /// particular argument has the semantic meaning of several other specific - /// arguments and values. - /// - /// # Examples - /// - /// We'll start with the "subcommand short" example. In this example, let's - /// assume we have a program with a subcommand `module` which can be invoked - /// via `cmd module`. Now let's also assume `module` also has a subcommand - /// called `install` which can be invoked `cmd module install`. If for some - /// reason users needed to be able to reach `cmd module install` via the - /// short-hand `cmd install`, we'd have several options. - /// - /// We *could* create another sibling subcommand to `module` called - /// `install`, but then we would need to manage another subcommand and manually - /// dispatch to `cmd module install` handling code. This is error prone and - /// tedious. - /// - /// We could instead use [`Command::replace`] so that, when the user types `cmd - /// install`, `clap` will replace `install` with `module install` which will - /// end up getting parsed as if the user typed the entire incantation. - /// - /// ```rust - /// # use clap::Command; - /// let m = Command::new("cmd") - /// .subcommand(Command::new("module") - /// .subcommand(Command::new("install"))) - /// .replace("install", &["module", "install"]) - /// .get_matches_from(vec!["cmd", "install"]); - /// - /// assert!(m.subcommand_matches("module").is_some()); - /// assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some()); - /// ``` - /// - /// Now let's show an argument example! - /// - /// Let's assume we have an application with two flags `--save-context` and - /// `--save-runtime`. But often users end up needing to do *both* at the - /// same time. We can add a third flag `--save-all` which semantically means - /// the same thing as `cmd --save-context --save-runtime`. To implement that, - /// we have several options. - /// - /// We could create this third argument and manually check if that argument - /// and in our own consumer code handle the fact that both `--save-context` - /// and `--save-runtime` *should* have been used. But again this is error - /// prone and tedious. If we had code relying on checking `--save-context` - /// and we forgot to update that code to *also* check `--save-all` it'd mean - /// an error! - /// - /// Luckily we can use [`Command::replace`] so that when the user types - /// `--save-all`, `clap` will replace that argument with `--save-context - /// --save-runtime`, and parsing will continue like normal. Now all our code - /// that was originally checking for things like `--save-context` doesn't - /// need to change! - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("cmd") - /// .arg(Arg::new("save-context") - /// .long("save-context") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("save-runtime") - /// .long("save-runtime") - /// .action(ArgAction::SetTrue)) - /// .replace("--save-all", &["--save-context", "--save-runtime"]) - /// .get_matches_from(vec!["cmd", "--save-all"]); - /// - /// assert!(m.get_flag("save-context")); - /// assert!(m.get_flag("save-runtime")); - /// ``` - /// - /// This can also be used with options, for example if our application with - /// `--save-*` above also had a `--format=TYPE` option. Let's say it - /// accepted `txt` or `json` values. However, when `--save-all` is used, - /// only `--format=json` is allowed, or valid. We could change the example - /// above to enforce this: - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("cmd") - /// .arg(Arg::new("save-context") - /// .long("save-context") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("save-runtime") - /// .long("save-runtime") - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("format") - /// .long("format") - /// .action(ArgAction::Set) - /// .value_parser(["txt", "json"])) - /// .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"]) - /// .get_matches_from(vec!["cmd", "--save-all"]); - /// - /// assert!(m.get_flag("save-context")); - /// assert!(m.get_flag("save-runtime")); - /// assert_eq!(m.get_one::<String>("format").unwrap(), "json"); - /// ``` - /// - /// [`Command::replace`]: Command::replace() - #[inline] - #[cfg(feature = "unstable-replace")] - #[must_use] - pub fn replace( - mut self, - name: impl Into<Str>, - target: impl IntoIterator<Item = impl Into<Str>>, - ) -> Self { - self.replacers - .insert(name.into(), target.into_iter().map(Into::into).collect()); - self - } - - /// Exit gracefully if no arguments are present (e.g. `$ myprog`). - /// - /// **NOTE:** [`subcommands`] count as arguments - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command}; - /// Command::new("myprog") - /// .arg_required_else_help(true); - /// ``` - /// - /// [`subcommands`]: crate::Command::subcommand() - /// [`Arg::default_value`]: crate::Arg::default_value() - #[inline] - pub fn arg_required_else_help(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::ArgRequiredElseHelp) - } else { - self.unset_setting(AppSettings::ArgRequiredElseHelp) - } - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_hyphen_values`") - )] - pub fn allow_hyphen_values(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::AllowHyphenValues) - } else { - self.unset_setting(AppSettings::AllowHyphenValues) - } - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_negative_numbers`") - )] - pub fn allow_negative_numbers(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::AllowNegativeNumbers) - } else { - self.unset_setting(AppSettings::AllowNegativeNumbers) - } - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::trailing_var_arg`") - )] - pub fn trailing_var_arg(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::TrailingVarArg) - } else { - self.unset_setting(AppSettings::TrailingVarArg) - } - } - - /// Allows one to implement two styles of CLIs where positionals can be used out of order. - /// - /// The first example is a CLI where the second to last positional argument is optional, but - /// the final positional argument is required. Such as `$ prog [optional] <required>` where one - /// of the two following usages is allowed: - /// - /// * `$ prog [optional] <required>` - /// * `$ prog <required>` - /// - /// This would otherwise not be allowed. This is useful when `[optional]` has a default value. - /// - /// **Note:** when using this style of "missing positionals" the final positional *must* be - /// [required] if `--` will not be used to skip to the final positional argument. - /// - /// **Note:** This style also only allows a single positional argument to be "skipped" without - /// the use of `--`. To skip more than one, see the second example. - /// - /// The second example is when one wants to skip multiple optional positional arguments, and use - /// of the `--` operator is OK (but not required if all arguments will be specified anyways). - /// - /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where - /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments). - /// - /// With this setting the following invocations are posisble: - /// - /// * `$ prog foo bar baz1 baz2 baz3` - /// * `$ prog foo -- baz1 baz2 baz3` - /// * `$ prog -- baz1 baz2 baz3` - /// - /// # Examples - /// - /// Style number one from above: - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_missing_positional(true) - /// .arg(Arg::new("arg1")) - /// .arg(Arg::new("arg2") - /// .required(true)) - /// .get_matches_from(vec![ - /// "prog", "other" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("arg1"), None); - /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other"); - /// ``` - /// - /// Now the same example, but using a default value for the first optional positional argument - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_missing_positional(true) - /// .arg(Arg::new("arg1") - /// .default_value("something")) - /// .arg(Arg::new("arg2") - /// .required(true)) - /// .get_matches_from(vec![ - /// "prog", "other" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("arg1").unwrap(), "something"); - /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other"); - /// ``` - /// - /// Style number two from above: - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_missing_positional(true) - /// .arg(Arg::new("foo")) - /// .arg(Arg::new("bar")) - /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..)) - /// .get_matches_from(vec![ - /// "prog", "foo", "bar", "baz1", "baz2", "baz3" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("foo").unwrap(), "foo"); - /// assert_eq!(m.get_one::<String>("bar").unwrap(), "bar"); - /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]); - /// ``` - /// - /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_missing_positional(true) - /// .arg(Arg::new("foo")) - /// .arg(Arg::new("bar")) - /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..)) - /// .get_matches_from(vec![ - /// "prog", "--", "baz1", "baz2", "baz3" - /// ]); - /// - /// assert_eq!(m.get_one::<String>("foo"), None); - /// assert_eq!(m.get_one::<String>("bar"), None); - /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]); - /// ``` - /// - /// [required]: crate::Arg::required() - #[inline] - pub fn allow_missing_positional(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::AllowMissingPositional) - } else { - self.unset_setting(AppSettings::AllowMissingPositional) - } - } -} - -/// # Subcommand-specific Settings -impl Command { - /// Sets the short version of the subcommand flag without the preceding `-`. - /// - /// Allows the subcommand to be used as if it were an [`Arg::short`]. - /// - /// # Examples - /// - /// ``` - /// # use clap::{Command, Arg, ArgAction}; - /// let matches = Command::new("pacman") - /// .subcommand( - /// Command::new("sync").short_flag('S').arg( - /// Arg::new("search") - /// .short('s') - /// .long("search") - /// .action(ArgAction::SetTrue) - /// .help("search remote repositories for matching strings"), - /// ), - /// ) - /// .get_matches_from(vec!["pacman", "-Ss"]); - /// - /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); - /// let sync_matches = matches.subcommand_matches("sync").unwrap(); - /// assert!(sync_matches.get_flag("search")); - /// ``` - /// [`Arg::short`]: Arg::short() - #[must_use] - pub fn short_flag(mut self, short: impl IntoResettable<char>) -> Self { - self.short_flag = short.into_resettable().into_option(); - self - } - - /// Sets the long version of the subcommand flag without the preceding `--`. - /// - /// Allows the subcommand to be used as if it were an [`Arg::long`]. - /// - /// **NOTE:** Any leading `-` characters will be stripped. - /// - /// # Examples - /// - /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading - /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however, - /// will *not* be stripped (i.e. `sync-file` is allowed). - /// - /// ``` - /// # use clap::{Command, Arg, ArgAction}; - /// let matches = Command::new("pacman") - /// .subcommand( - /// Command::new("sync").long_flag("sync").arg( - /// Arg::new("search") - /// .short('s') - /// .long("search") - /// .action(ArgAction::SetTrue) - /// .help("search remote repositories for matching strings"), - /// ), - /// ) - /// .get_matches_from(vec!["pacman", "--sync", "--search"]); - /// - /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); - /// let sync_matches = matches.subcommand_matches("sync").unwrap(); - /// assert!(sync_matches.get_flag("search")); - /// ``` - /// - /// [`Arg::long`]: Arg::long() - #[must_use] - pub fn long_flag(mut self, long: impl Into<Str>) -> Self { - self.long_flag = Some(long.into()); - self - } - - /// Sets a hidden alias to this subcommand. - /// - /// This allows the subcommand to be accessed via *either* the original name, or this given - /// alias. This is more efficient and easier than creating multiple hidden subcommands as one - /// only needs to check for the existence of this command, and not all aliased variants. - /// - /// **NOTE:** Aliases defined with this method are *hidden* from the help - /// message. If you're looking for aliases that will be displayed in the help - /// message, see [`Command::visible_alias`]. - /// - /// **NOTE:** When using aliases and checking for the existence of a - /// particular subcommand within an [`ArgMatches`] struct, one only needs to - /// search for the original name and not all aliases. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test") - /// .alias("do-stuff")) - /// .get_matches_from(vec!["myprog", "do-stuff"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::visible_alias`]: Command::visible_alias() - #[must_use] - pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.aliases.push((name, false)); - } else { - self.aliases.clear(); - } - self - } - - /// Add an alias, which functions as "hidden" short flag subcommand - /// - /// This will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").short_flag('t') - /// .short_flag_alias('d')) - /// .get_matches_from(vec!["myprog", "-d"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - #[must_use] - pub fn short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - debug_assert!(name != '-', "short alias name cannot be `-`"); - self.short_flag_aliases.push((name, false)); - } else { - self.short_flag_aliases.clear(); - } - self - } - - /// Add an alias, which functions as a "hidden" long flag subcommand. - /// - /// This will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").long_flag("test") - /// .long_flag_alias("testing")) - /// .get_matches_from(vec!["myprog", "--testing"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - #[must_use] - pub fn long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.long_flag_aliases.push((name, false)); - } else { - self.long_flag_aliases.clear(); - } - self - } - - /// Sets multiple hidden aliases to this subcommand. - /// - /// This allows the subcommand to be accessed via *either* the original name or any of the - /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands - /// as one only needs to check for the existence of this command and not all aliased variants. - /// - /// **NOTE:** Aliases defined with this method are *hidden* from the help - /// message. If looking for aliases that will be displayed in the help - /// message, see [`Command::visible_aliases`]. - /// - /// **NOTE:** When using aliases and checking for the existence of a - /// particular subcommand within an [`ArgMatches`] struct, one only needs to - /// search for the original name and not all aliases. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test") - /// .aliases(["do-stuff", "do-tests", "tests"])) - /// .arg(Arg::new("input") - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec!["myprog", "do-tests"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::visible_aliases`]: Command::visible_aliases() - #[must_use] - pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - self.aliases - .extend(names.into_iter().map(|n| (n.into(), false))); - self - } - - /// Add aliases, which function as "hidden" short flag subcommands. - /// - /// These will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").short_flag('t') - /// .short_flag_aliases(['a', 'b', 'c'])) - /// .arg(Arg::new("input") - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec!["myprog", "-a"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - #[must_use] - pub fn short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self { - for s in names { - debug_assert!(s != '-', "short alias name cannot be `-`"); - self.short_flag_aliases.push((s, false)); - } - self - } - - /// Add aliases, which function as "hidden" long flag subcommands. - /// - /// These will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").long_flag("test") - /// .long_flag_aliases(["testing", "testall", "test_all"])) - /// .arg(Arg::new("input") - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec!["myprog", "--testing"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - #[must_use] - pub fn long_flag_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - for s in names { - self = self.long_flag_alias(s) - } - self - } - - /// Sets a visible alias to this subcommand. - /// - /// This allows the subcommand to be accessed via *either* the - /// original name or the given alias. This is more efficient and easier - /// than creating hidden subcommands as one only needs to check for - /// the existence of this command and not all aliased variants. - /// - /// **NOTE:** The alias defined with this method is *visible* from the help - /// message and displayed as if it were just another regular subcommand. If - /// looking for an alias that will not be displayed in the help message, see - /// [`Command::alias`]. - /// - /// **NOTE:** When using aliases and checking for the existence of a - /// particular subcommand within an [`ArgMatches`] struct, one only needs to - /// search for the original name and not all aliases. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test") - /// .visible_alias("do-stuff")) - /// .get_matches_from(vec!["myprog", "do-stuff"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::alias`]: Command::alias() - #[must_use] - pub fn visible_alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.aliases.push((name, true)); - } else { - self.aliases.clear(); - } - self - } - - /// Add an alias, which functions as "visible" short flag subcommand - /// - /// This will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// See also [`Command::short_flag_alias`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").short_flag('t') - /// .visible_short_flag_alias('d')) - /// .get_matches_from(vec!["myprog", "-d"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::short_flag_alias`]: Command::short_flag_alias() - #[must_use] - pub fn visible_short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - debug_assert!(name != '-', "short alias name cannot be `-`"); - self.short_flag_aliases.push((name, true)); - } else { - self.short_flag_aliases.clear(); - } - self - } - - /// Add an alias, which functions as a "visible" long flag subcommand. - /// - /// This will automatically dispatch as if this subcommand was used. This is more efficient, - /// and easier than creating multiple hidden subcommands as one only needs to check for the - /// existence of this command, and not all variants. - /// - /// See also [`Command::long_flag_alias`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").long_flag("test") - /// .visible_long_flag_alias("testing")) - /// .get_matches_from(vec!["myprog", "--testing"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::long_flag_alias`]: Command::long_flag_alias() - #[must_use] - pub fn visible_long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.long_flag_aliases.push((name, true)); - } else { - self.long_flag_aliases.clear(); - } - self - } - - /// Sets multiple visible aliases to this subcommand. - /// - /// This allows the subcommand to be accessed via *either* the - /// original name or any of the given aliases. This is more efficient and easier - /// than creating multiple hidden subcommands as one only needs to check for - /// the existence of this command and not all aliased variants. - /// - /// **NOTE:** The alias defined with this method is *visible* from the help - /// message and displayed as if it were just another regular subcommand. If - /// looking for an alias that will not be displayed in the help message, see - /// [`Command::alias`]. - /// - /// **NOTE:** When using aliases, and checking for the existence of a - /// particular subcommand within an [`ArgMatches`] struct, one only needs to - /// search for the original name and not all aliases. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test") - /// .visible_aliases(["do-stuff", "tests"])) - /// .get_matches_from(vec!["myprog", "do-stuff"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::alias`]: Command::alias() - #[must_use] - pub fn visible_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - self.aliases - .extend(names.into_iter().map(|n| (n.into(), true))); - self - } - - /// Add aliases, which function as *visible* short flag subcommands. - /// - /// See [`Command::short_flag_aliases`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").short_flag('b') - /// .visible_short_flag_aliases(['t'])) - /// .get_matches_from(vec!["myprog", "-t"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::short_flag_aliases`]: Command::short_flag_aliases() - #[must_use] - pub fn visible_short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self { - for s in names { - debug_assert!(s != '-', "short alias name cannot be `-`"); - self.short_flag_aliases.push((s, true)); - } - self - } - - /// Add aliases, which function as *visible* long flag subcommands. - /// - /// See [`Command::long_flag_aliases`]. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let m = Command::new("myprog") - /// .subcommand(Command::new("test").long_flag("test") - /// .visible_long_flag_aliases(["testing", "testall", "test_all"])) - /// .get_matches_from(vec!["myprog", "--testing"]); - /// assert_eq!(m.subcommand_name(), Some("test")); - /// ``` - /// [`Command::long_flag_aliases`]: Command::long_flag_aliases() - #[must_use] - pub fn visible_long_flag_aliases( - mut self, - names: impl IntoIterator<Item = impl Into<Str>>, - ) -> Self { - for s in names { - self = self.visible_long_flag_alias(s); - } - self - } - - /// Set the placement of this subcommand within the help. - /// - /// Subcommands with a lower value will be displayed first in the help message. Subcommands - /// with duplicate display orders will be displayed in 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<usize>) -> Self { - self.disp_ord = ord.into_resettable().into_option(); - self - } - - /// Specifies that this [`subcommand`] should be hidden from help messages - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand( - /// Command::new("test").hide(true) - /// ) - /// # ; - /// ``` - /// - /// [`subcommand`]: crate::Command::subcommand() - #[inline] - pub fn hide(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::Hidden) - } else { - self.unset_setting(AppSettings::Hidden) - } - } - - /// If no [`subcommand`] is present at runtime, error and exit gracefully. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, error::ErrorKind}; - /// let err = Command::new("myprog") - /// .subcommand_required(true) - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog", - /// ]); - /// assert!(err.is_err()); - /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); - /// # ; - /// ``` - /// - /// [`subcommand`]: crate::Command::subcommand() - pub fn subcommand_required(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::SubcommandRequired) - } else { - self.unset_setting(AppSettings::SubcommandRequired) - } - } - - /// Assume unexpected positional arguments are a [`subcommand`]. - /// - /// Arguments will be stored in the `""` argument in the [`ArgMatches`] - /// - /// **NOTE:** Use this setting with caution, - /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand) - /// will **not** cause an error and instead be treated as a potential subcommand. - /// One should check for such cases manually and inform the user appropriately. - /// - /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with - /// `--`. - /// - /// # Examples - /// - /// ```rust - /// # use std::ffi::OsString; - /// # use clap::Command; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_external_subcommands(true) - /// .get_matches_from(vec![ - /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" - /// ]); - /// - /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty - /// // string argument name - /// match m.subcommand() { - /// Some((external, ext_m)) => { - /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// - /// [`subcommand`]: crate::Command::subcommand() - /// [`ArgMatches`]: crate::ArgMatches - /// [`ErrorKind::UnknownArgument`]: crate::error::ErrorKind::UnknownArgument - pub fn allow_external_subcommands(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::AllowExternalSubcommands) - } else { - self.unset_setting(AppSettings::AllowExternalSubcommands) - } - } - - /// Specifies how to parse external subcommand arguments. - /// - /// The default parser is for `OsString`. This can be used to switch it to `String` or another - /// type. - /// - /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`] - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use std::ffi::OsString; - /// # use clap::Command; - /// # use clap::value_parser; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .allow_external_subcommands(true) - /// .get_matches_from(vec![ - /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" - /// ]); - /// - /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty - /// // string argument name - /// match m.subcommand() { - /// Some((external, ext_m)) => { - /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// - /// ``` - /// # use clap::Command; - /// # use clap::value_parser; - /// // Assume there is an external subcommand named "subcmd" - /// let m = Command::new("myprog") - /// .external_subcommand_value_parser(value_parser!(String)) - /// .get_matches_from(vec![ - /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" - /// ]); - /// - /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty - /// // string argument name - /// match m.subcommand() { - /// Some((external, ext_m)) => { - /// let ext_args: Vec<_> = ext_m.get_many::<String>("").unwrap().collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// - /// [`subcommands`]: crate::Command::subcommand() - pub fn external_subcommand_value_parser( - mut self, - parser: impl IntoResettable<super::ValueParser>, - ) -> Self { - self.external_value_parser = parser.into_resettable().into_option(); - self - } - - /// Specifies that use of an argument prevents the use of [`subcommands`]. - /// - /// By default `clap` allows arguments between subcommands such - /// as `<cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args]`. - /// - /// This setting disables that functionality and says that arguments can - /// only follow the *final* subcommand. For instance using this setting - /// makes only the following invocations possible: - /// - /// * `<cmd> <subcmd> <subsubcmd> [subsubcmd_args]` - /// * `<cmd> <subcmd> [subcmd_args]` - /// * `<cmd> [cmd_args]` - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// Command::new("myprog") - /// .args_conflicts_with_subcommands(true); - /// ``` - /// - /// [`subcommands`]: crate::Command::subcommand() - pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::ArgsNegateSubcommands) - } else { - self.unset_setting(AppSettings::ArgsNegateSubcommands) - } - } - - /// Prevent subcommands from being consumed as an arguments value. - /// - /// By default, if an option taking multiple values is followed by a subcommand, the - /// subcommand will be parsed as another value. - /// - /// ```text - /// cmd --foo val1 val2 subcommand - /// --------- ---------- - /// values another value - /// ``` - /// - /// This setting instructs the parser to stop when encountering a subcommand instead of - /// greedily consuming arguments. - /// - /// ```text - /// cmd --foo val1 val2 subcommand - /// --------- ---------- - /// values subcommand - /// ``` - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg( - /// Arg::new("arg") - /// .long("arg") - /// .num_args(1..) - /// .action(ArgAction::Set), - /// ); - /// - /// let matches = cmd - /// .clone() - /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) - /// .unwrap(); - /// assert_eq!( - /// matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(), - /// &["1", "2", "3", "sub"] - /// ); - /// assert!(matches.subcommand_matches("sub").is_none()); - /// - /// let matches = cmd - /// .subcommand_precedence_over_arg(true) - /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) - /// .unwrap(); - /// assert_eq!( - /// matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(), - /// &["1", "2", "3"] - /// ); - /// assert!(matches.subcommand_matches("sub").is_some()); - /// ``` - pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::SubcommandPrecedenceOverArg) - } else { - self.unset_setting(AppSettings::SubcommandPrecedenceOverArg) - } - } - - /// Allows [`subcommands`] to override all requirements of the parent command. - /// - /// For example, if you had a subcommand or top level application with a required argument - /// that is only required as long as there is no subcommand present, - /// using this setting would allow you to set those arguments to [`Arg::required(true)`] - /// and yet receive no error so long as the user uses a valid subcommand instead. - /// - /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements) - /// - /// # Examples - /// - /// This first example shows that it is an error to not use a required argument - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind}; - /// let err = Command::new("myprog") - /// .subcommand_negates_reqs(true) - /// .arg(Arg::new("opt").required(true)) - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog" - /// ]); - /// assert!(err.is_err()); - /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// # ; - /// ``` - /// - /// This next example shows that it is no longer error to not use a required argument if a - /// valid subcommand is used. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind}; - /// let noerr = Command::new("myprog") - /// .subcommand_negates_reqs(true) - /// .arg(Arg::new("opt").required(true)) - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog", "test" - /// ]); - /// assert!(noerr.is_ok()); - /// # ; - /// ``` - /// - /// [`Arg::required(true)`]: crate::Arg::required() - /// [`subcommands`]: crate::Command::subcommand() - pub fn subcommand_negates_reqs(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::SubcommandsNegateReqs) - } else { - self.unset_setting(AppSettings::SubcommandsNegateReqs) - } - } - - /// Multiple-personality program dispatched on the binary name (`argv[0]`) - /// - /// A "multicall" executable is a single executable - /// that contains a variety of applets, - /// and decides which applet to run based on the name of the file. - /// The executable can be called from different names by creating hard links - /// or symbolic links to it. - /// - /// This is desirable for: - /// - Easy distribution, a single binary that can install hardlinks to access the different - /// personalities. - /// - Minimal binary size by sharing common code (e.g. standard library, clap) - /// - Custom shells or REPLs where there isn't a single top-level command - /// - /// Setting `multicall` will cause - /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if - /// [`Command::no_binary_name`][Command::no_binary_name] was set. - /// - Help and errors to report subcommands as if they were the top-level command - /// - /// When the subcommand is not present, there are several strategies you may employ, depending - /// on your needs: - /// - Let the error percolate up normally - /// - Print a specialized error message using the - /// [`Error::context`][crate::Error::context] - /// - Print the [help][Command::write_help] but this might be ambiguous - /// - Disable `multicall` and re-parse it - /// - Disable `multicall` and re-parse it with a specific subcommand - /// - /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand - /// might report the same error. Enable - /// [`allow_external_subcommands`][Command::allow_external_subcommands] if you want to specifically - /// get the unrecognized binary name. - /// - /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret - /// the command name in incompatible ways. - /// - /// **NOTE:** The multicall command cannot have arguments. - /// - /// **NOTE:** Applets are slightly semantically different from subcommands, - /// so it's recommended to use [`Command::subcommand_help_heading`] and - /// [`Command::subcommand_value_name`] to change the descriptive text as above. - /// - /// # Examples - /// - /// `hostname` is an example of a multicall executable. - /// Both `hostname` and `dnsdomainname` are provided by the same executable - /// and which behaviour to use is based on the executable file name. - /// - /// This is desirable when the executable has a primary purpose - /// but there is related functionality that would be convenient to provide - /// and implement it to be in the same executable. - /// - /// The name of the cmd is essentially unused - /// and may be the same as the name of a subcommand. - /// - /// The names of the immediate subcommands of the Command - /// are matched against the basename of the first argument, - /// which is conventionally the path of the executable. - /// - /// This does not allow the subcommand to be passed as the first non-path argument. - /// - /// ```rust - /// # use clap::{Command, error::ErrorKind}; - /// let mut cmd = Command::new("hostname") - /// .multicall(true) - /// .subcommand(Command::new("hostname")) - /// .subcommand(Command::new("dnsdomainname")); - /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]); - /// assert!(m.is_err()); - /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]); - /// assert_eq!(m.subcommand_name(), Some("dnsdomainname")); - /// ``` - /// - /// Busybox is another common example of a multicall executable - /// with a subcommmand for each applet that can be run directly, - /// e.g. with the `cat` applet being run by running `busybox cat`, - /// or with `cat` as a link to the `busybox` binary. - /// - /// This is desirable when the launcher program has additional options - /// or it is useful to run the applet without installing a symlink - /// e.g. to test the applet without installing it - /// or there may already be a command of that name installed. - /// - /// To make an applet usable as both a multicall link and a subcommand - /// the subcommands must be defined both in the top-level Command - /// and as subcommands of the "main" applet. - /// - /// ```rust - /// # use clap::Command; - /// fn applet_commands() -> [Command; 2] { - /// [Command::new("true"), Command::new("false")] - /// } - /// let mut cmd = Command::new("busybox") - /// .multicall(true) - /// .subcommand( - /// Command::new("busybox") - /// .subcommand_value_name("APPLET") - /// .subcommand_help_heading("APPLETS") - /// .subcommands(applet_commands()), - /// ) - /// .subcommands(applet_commands()); - /// // When called from the executable's canonical name - /// // its applets can be matched as subcommands. - /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap(); - /// assert_eq!(m.subcommand_name(), Some("busybox")); - /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true")); - /// // When called from a link named after an applet that applet is matched. - /// let m = cmd.get_matches_from(&["/usr/bin/true"]); - /// assert_eq!(m.subcommand_name(), Some("true")); - /// ``` - /// - /// [`no_binary_name`]: crate::Command::no_binary_name - /// [`Command::subcommand_value_name`]: crate::Command::subcommand_value_name - /// [`Command::subcommand_help_heading`]: crate::Command::subcommand_help_heading - #[inline] - pub fn multicall(self, yes: bool) -> Self { - if yes { - self.setting(AppSettings::Multicall) - } else { - self.unset_setting(AppSettings::Multicall) - } - } - - /// Sets the value name used for subcommands when printing usage and help. - /// - /// By default, this is "COMMAND". - /// - /// See also [`Command::subcommand_help_heading`] - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("sub1")) - /// .print_help() - /// # ; - /// ``` - /// - /// will produce - /// - /// ```text - /// myprog - /// - /// Usage: myprog [COMMAND] - /// - /// Commands: - /// help Print this message or the help of the given subcommand(s) - /// sub1 - /// - /// Options: - /// -h, --help Print help - /// -V, --version Print version - /// ``` - /// - /// but usage of `subcommand_value_name` - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("sub1")) - /// .subcommand_value_name("THING") - /// .print_help() - /// # ; - /// ``` - /// - /// will produce - /// - /// ```text - /// myprog - /// - /// Usage: myprog [THING] - /// - /// Commands: - /// help Print this message or the help of the given subcommand(s) - /// sub1 - /// - /// Options: - /// -h, --help Print help - /// -V, --version Print version - /// ``` - #[must_use] - pub fn subcommand_value_name(mut self, value_name: impl IntoResettable<Str>) -> Self { - self.subcommand_value_name = value_name.into_resettable().into_option(); - self - } - - /// Sets the help heading used for subcommands when printing usage and help. - /// - /// By default, this is "Commands". - /// - /// See also [`Command::subcommand_value_name`] - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("sub1")) - /// .print_help() - /// # ; - /// ``` - /// - /// will produce - /// - /// ```text - /// myprog - /// - /// Usage: myprog [COMMAND] - /// - /// Commands: - /// help Print this message or the help of the given subcommand(s) - /// sub1 - /// - /// Options: - /// -h, --help Print help - /// -V, --version Print version - /// ``` - /// - /// but usage of `subcommand_help_heading` - /// - /// ```no_run - /// # use clap::{Command, Arg}; - /// Command::new("myprog") - /// .subcommand(Command::new("sub1")) - /// .subcommand_help_heading("Things") - /// .print_help() - /// # ; - /// ``` - /// - /// will produce - /// - /// ```text - /// myprog - /// - /// Usage: myprog [COMMAND] - /// - /// Things: - /// help Print this message or the help of the given subcommand(s) - /// sub1 - /// - /// Options: - /// -h, --help Print help - /// -V, --version Print version - /// ``` - #[must_use] - pub fn subcommand_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self { - self.subcommand_heading = heading.into_resettable().into_option(); - self - } -} - -/// # Reflection -impl Command { - #[inline] - #[cfg(feature = "usage")] - pub(crate) fn get_usage_name(&self) -> Option<&str> { - self.usage_name.as_deref() - } - - /// Get the name of the binary. - #[inline] - pub fn get_display_name(&self) -> Option<&str> { - self.display_name.as_deref() - } - - /// Get the name of the binary. - #[inline] - pub fn get_bin_name(&self) -> Option<&str> { - self.bin_name.as_deref() - } - - /// Set binary name. Uses `&mut self` instead of `self`. - pub fn set_bin_name(&mut self, name: impl Into<String>) { - self.bin_name = Some(name.into()); - } - - /// Get the name of the cmd. - #[inline] - pub fn get_name(&self) -> &str { - self.name.as_str() - } - - #[inline] - #[cfg(debug_assertions)] - pub(crate) fn get_name_str(&self) -> &Str { - &self.name - } - - /// Get the version of the cmd. - #[inline] - pub fn get_version(&self) -> Option<&str> { - self.version.as_deref() - } - - /// Get the long version of the cmd. - #[inline] - pub fn get_long_version(&self) -> Option<&str> { - self.long_version.as_deref() - } - - /// Get the authors of the cmd. - #[inline] - pub fn get_author(&self) -> Option<&str> { - self.author.as_deref() - } - - /// Get the short flag of the subcommand. - #[inline] - pub fn get_short_flag(&self) -> Option<char> { - self.short_flag - } - - /// Get the long flag of the subcommand. - #[inline] - pub fn get_long_flag(&self) -> Option<&str> { - self.long_flag.as_deref() - } - - /// Get the help message specified via [`Command::about`]. - /// - /// [`Command::about`]: Command::about() - #[inline] - pub fn get_about(&self) -> Option<&StyledStr> { - self.about.as_ref() - } - - /// Get the help message specified via [`Command::long_about`]. - /// - /// [`Command::long_about`]: Command::long_about() - #[inline] - pub fn get_long_about(&self) -> Option<&StyledStr> { - self.long_about.as_ref() - } - - /// Get the custom section heading specified via [`Command::next_help_heading`]. - /// - /// [`Command::help_heading`]: Command::help_heading() - #[inline] - pub fn get_next_help_heading(&self) -> Option<&str> { - self.current_help_heading.as_deref() - } - - /// Iterate through the *visible* aliases for this subcommand. - #[inline] - pub fn get_visible_aliases(&self) -> impl Iterator<Item = &str> + '_ { - self.aliases - .iter() - .filter(|(_, vis)| *vis) - .map(|a| a.0.as_str()) - } - - /// Iterate through the *visible* short aliases for this subcommand. - #[inline] - pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ { - self.short_flag_aliases - .iter() - .filter(|(_, vis)| *vis) - .map(|a| a.0) - } - - /// Iterate through the *visible* long aliases for this subcommand. - #[inline] - pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ { - self.long_flag_aliases - .iter() - .filter(|(_, vis)| *vis) - .map(|a| a.0.as_str()) - } - - /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden. - #[inline] - pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> + '_ { - self.aliases.iter().map(|a| a.0.as_str()) - } - - /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden. - #[inline] - pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ { - self.short_flag_aliases.iter().map(|a| a.0) - } - - /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden. - #[inline] - pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ { - self.long_flag_aliases.iter().map(|a| a.0.as_str()) - } - - #[inline] - pub(crate) fn is_set(&self, s: AppSettings) -> bool { - self.settings.is_set(s) || self.g_settings.is_set(s) - } - - /// Should we color the output? - pub fn get_color(&self) -> ColorChoice { - debug!("Command::color: Color setting..."); - - if cfg!(feature = "color") { - if self.is_set(AppSettings::ColorNever) { - debug!("Never"); - ColorChoice::Never - } else if self.is_set(AppSettings::ColorAlways) { - debug!("Always"); - ColorChoice::Always - } else { - debug!("Auto"); - ColorChoice::Auto - } - } else { - ColorChoice::Never - } - } - - /// Iterate through the set of subcommands, getting a reference to each. - #[inline] - pub fn get_subcommands(&self) -> impl Iterator<Item = &Command> { - self.subcommands.iter() - } - - /// Iterate through the set of subcommands, getting a mutable reference to each. - #[inline] - pub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut Command> { - self.subcommands.iter_mut() - } - - /// Returns `true` if this `Command` has subcommands. - #[inline] - pub fn has_subcommands(&self) -> bool { - !self.subcommands.is_empty() - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_subcommand_help_heading(&self) -> Option<&str> { - self.subcommand_heading.as_deref() - } - - /// Returns the subcommand value name. - #[inline] - pub fn get_subcommand_value_name(&self) -> Option<&str> { - self.subcommand_value_name.as_deref() - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_before_help(&self) -> Option<&StyledStr> { - self.before_help.as_ref() - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_before_long_help(&self) -> Option<&StyledStr> { - self.before_long_help.as_ref() - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_after_help(&self) -> Option<&StyledStr> { - self.after_help.as_ref() - } - - /// Returns the help heading for listing subcommands. - #[inline] - pub fn get_after_long_help(&self) -> Option<&StyledStr> { - self.after_long_help.as_ref() - } - - /// Find subcommand such that its name or one of aliases equals `name`. - /// - /// This does not recurse through subcommands of subcommands. - #[inline] - pub fn find_subcommand(&self, name: impl AsRef<std::ffi::OsStr>) -> Option<&Command> { - let name = name.as_ref(); - self.get_subcommands().find(|s| s.aliases_to(name)) - } - - /// Find subcommand such that its name or one of aliases equals `name`, returning - /// a mutable reference to the subcommand. - /// - /// This does not recurse through subcommands of subcommands. - #[inline] - pub fn find_subcommand_mut( - &mut self, - name: impl AsRef<std::ffi::OsStr>, - ) -> Option<&mut Command> { - let name = name.as_ref(); - self.get_subcommands_mut().find(|s| s.aliases_to(name)) - } - - /// Iterate through the set of groups. - #[inline] - pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup> { - self.groups.iter() - } - - /// Iterate through the set of arguments. - #[inline] - pub fn get_arguments(&self) -> impl Iterator<Item = &Arg> { - self.args.args() - } - - /// Iterate through the *positionals* arguments. - #[inline] - pub fn get_positionals(&self) -> impl Iterator<Item = &Arg> { - self.get_arguments().filter(|a| a.is_positional()) - } - - /// Iterate through the *options*. - pub fn get_opts(&self) -> impl Iterator<Item = &Arg> { - self.get_arguments() - .filter(|a| a.is_takes_value_set() && !a.is_positional()) - } - - /// Get a list of all arguments the given argument conflicts with. - /// - /// If the provided argument is declared as global, the conflicts will be determined - /// based on the propagation rules of global arguments. - /// - /// ### Panics - /// - /// If the given arg contains a conflict with an argument that is unknown to - /// this `Command`. - pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator - { - if arg.is_global_set() { - self.get_global_arg_conflicts_with(arg) - } else { - let mut result = Vec::new(); - for id in arg.blacklist.iter() { - if let Some(arg) = self.find(id) { - result.push(arg); - } else if let Some(group) = self.find_group(id) { - result.extend( - self.unroll_args_in_group(&group.id) - .iter() - .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)), - ); - } else { - panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd"); - } - } - result - } - } - - // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with. - // - // This behavior follows the propagation rules of global arguments. - // It is useful for finding conflicts for arguments declared as global. - // - // ### Panics - // - // If the given arg contains a conflict with an argument that is unknown to - // this `Command`. - fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator - { - arg.blacklist - .iter() - .map(|id| { - self.args - .args() - .chain( - self.get_subcommands_containing(arg) - .iter() - .flat_map(|x| x.args.args()), - ) - .find(|arg| arg.get_id() == id) - .expect( - "Command::get_arg_conflicts_with: \ - The passed arg conflicts with an arg unknown to the cmd", - ) - }) - .collect() - } - - // Get a list of subcommands which contain the provided Argument - // - // This command will only include subcommands in its list for which the subcommands - // parent also contains the Argument. - // - // This search follows the propagation rules of global arguments. - // It is useful to finding subcommands, that have inherited a global argument. - // - // **NOTE:** In this case only Sucommand_1 will be included - // Subcommand_1 (contains Arg) - // Subcommand_1.1 (doesn't contain Arg) - // Subcommand_1.1.1 (contains Arg) - // - fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> { - let mut vec = std::vec::Vec::new(); - for idx in 0..self.subcommands.len() { - if self.subcommands[idx] - .args - .args() - .any(|ar| ar.get_id() == arg.get_id()) - { - vec.push(&self.subcommands[idx]); - vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg)); - } - } - vec - } - - /// Report whether [`Command::no_binary_name`] is set - pub fn is_no_binary_name_set(&self) -> bool { - self.is_set(AppSettings::NoBinaryName) - } - - /// Report whether [`Command::ignore_errors`] is set - pub(crate) fn is_ignore_errors_set(&self) -> bool { - self.is_set(AppSettings::IgnoreErrors) - } - - /// Report whether [`Command::dont_delimit_trailing_values`] is set - pub fn is_dont_delimit_trailing_values_set(&self) -> bool { - self.is_set(AppSettings::DontDelimitTrailingValues) - } - - /// Report whether [`Command::disable_version_flag`] is set - pub fn is_disable_version_flag_set(&self) -> bool { - self.is_set(AppSettings::DisableVersionFlag) - || (self.version.is_none() && self.long_version.is_none()) - } - - /// Report whether [`Command::propagate_version`] is set - pub fn is_propagate_version_set(&self) -> bool { - self.is_set(AppSettings::PropagateVersion) - } - - /// Report whether [`Command::next_line_help`] is set - pub fn is_next_line_help_set(&self) -> bool { - self.is_set(AppSettings::NextLineHelp) - } - - /// Report whether [`Command::disable_help_flag`] is set - pub fn is_disable_help_flag_set(&self) -> bool { - self.is_set(AppSettings::DisableHelpFlag) - } - - /// Report whether [`Command::disable_help_subcommand`] is set - pub fn is_disable_help_subcommand_set(&self) -> bool { - self.is_set(AppSettings::DisableHelpSubcommand) - } - - /// Report whether [`Command::disable_colored_help`] is set - pub fn is_disable_colored_help_set(&self) -> bool { - self.is_set(AppSettings::DisableColoredHelp) - } - - /// Report whether [`Command::help_expected`] is set - #[cfg(debug_assertions)] - pub(crate) fn is_help_expected_set(&self) -> bool { - self.is_set(AppSettings::HelpExpected) - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "This is now the default") - )] - pub fn is_dont_collapse_args_in_usage_set(&self) -> bool { - true - } - - /// Report whether [`Command::infer_long_args`] is set - pub(crate) fn is_infer_long_args_set(&self) -> bool { - self.is_set(AppSettings::InferLongArgs) - } - - /// Report whether [`Command::infer_subcommands`] is set - pub(crate) fn is_infer_subcommands_set(&self) -> bool { - self.is_set(AppSettings::InferSubcommands) - } - - /// Report whether [`Command::arg_required_else_help`] is set - pub fn is_arg_required_else_help_set(&self) -> bool { - self.is_set(AppSettings::ArgRequiredElseHelp) - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "4.0.0", - note = "Replaced with `Arg::is_allow_hyphen_values_set`" - ) - )] - pub(crate) fn is_allow_hyphen_values_set(&self) -> bool { - self.is_set(AppSettings::AllowHyphenValues) - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated( - since = "4.0.0", - note = "Replaced with `Arg::is_allow_negative_numbers_set`" - ) - )] - pub fn is_allow_negative_numbers_set(&self) -> bool { - self.is_set(AppSettings::AllowNegativeNumbers) - } - - #[doc(hidden)] - #[cfg_attr( - feature = "deprecated", - deprecated(since = "4.0.0", note = "Replaced with `Arg::is_trailing_var_arg_set`") - )] - pub fn is_trailing_var_arg_set(&self) -> bool { - self.is_set(AppSettings::TrailingVarArg) - } - - /// Report whether [`Command::allow_missing_positional`] is set - pub fn is_allow_missing_positional_set(&self) -> bool { - self.is_set(AppSettings::AllowMissingPositional) - } - - /// Report whether [`Command::hide`] is set - pub fn is_hide_set(&self) -> bool { - self.is_set(AppSettings::Hidden) - } - - /// Report whether [`Command::subcommand_required`] is set - pub fn is_subcommand_required_set(&self) -> bool { - self.is_set(AppSettings::SubcommandRequired) - } - - /// Report whether [`Command::allow_external_subcommands`] is set - pub fn is_allow_external_subcommands_set(&self) -> bool { - self.is_set(AppSettings::AllowExternalSubcommands) - } - - /// Configured parser for values passed to an external subcommand - /// - /// # Example - /// - /// ```rust - /// let cmd = clap::Command::new("raw") - /// .external_subcommand_value_parser(clap::value_parser!(String)); - /// let value_parser = cmd.get_external_subcommand_value_parser(); - /// println!("{:?}", value_parser); - /// ``` - pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> { - if !self.is_allow_external_subcommands_set() { - None - } else { - static DEFAULT: super::ValueParser = super::ValueParser::os_string(); - Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT)) - } - } - - /// Report whether [`Command::args_conflicts_with_subcommands`] is set - pub fn is_args_conflicts_with_subcommands_set(&self) -> bool { - self.is_set(AppSettings::ArgsNegateSubcommands) - } - - #[doc(hidden)] - pub fn is_args_override_self(&self) -> bool { - self.is_set(AppSettings::AllArgsOverrideSelf) - } - - /// Report whether [`Command::subcommand_precedence_over_arg`] is set - pub fn is_subcommand_precedence_over_arg_set(&self) -> bool { - self.is_set(AppSettings::SubcommandPrecedenceOverArg) - } - - /// Report whether [`Command::subcommand_negates_reqs`] is set - pub fn is_subcommand_negates_reqs_set(&self) -> bool { - self.is_set(AppSettings::SubcommandsNegateReqs) - } - - /// Report whether [`Command::multicall`] is set - pub fn is_multicall_set(&self) -> bool { - self.is_set(AppSettings::Multicall) - } -} - -// Internally used only -impl Command { - pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> { - self.usage_str.as_ref() - } - - pub(crate) fn get_override_help(&self) -> Option<&StyledStr> { - self.help_str.as_ref() - } - - #[cfg(feature = "help")] - pub(crate) fn get_help_template(&self) -> Option<&StyledStr> { - self.template.as_ref() - } - - #[cfg(feature = "help")] - pub(crate) fn get_term_width(&self) -> Option<usize> { - self.term_w - } - - #[cfg(feature = "help")] - pub(crate) fn get_max_term_width(&self) -> Option<usize> { - self.max_w - } - - pub(crate) fn get_replacement(&self, key: &str) -> Option<&[Str]> { - self.replacers.get(key).map(|v| v.as_slice()) - } - - pub(crate) fn get_keymap(&self) -> &MKeyMap { - &self.args - } - - fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) { - global_arg_vec.extend( - self.args - .args() - .filter(|a| a.is_global_set()) - .map(|ga| ga.id.clone()), - ); - if let Some((id, matches)) = matches.subcommand() { - if let Some(used_sub) = self.find_subcommand(id) { - used_sub.get_used_global_args(matches, global_arg_vec); - } - } - } - - fn _do_parse( - &mut self, - raw_args: &mut clap_lex::RawArgs, - args_cursor: clap_lex::ArgCursor, - ) -> ClapResult<ArgMatches> { - debug!("Command::_do_parse"); - - // If there are global arguments, or settings we need to propagate them down to subcommands - // before parsing in case we run into a subcommand - self._build_self(false); - - let mut matcher = ArgMatcher::new(self); - - // do the real parsing - let mut parser = Parser::new(self); - if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) { - if self.is_set(AppSettings::IgnoreErrors) { - debug!("Command::_do_parse: ignoring error: {}", error); - } else { - return Err(error); - } - } - - let mut global_arg_vec = Default::default(); - self.get_used_global_args(&matcher, &mut global_arg_vec); - - matcher.propagate_globals(&global_arg_vec); - - Ok(matcher.into_inner()) - } - - /// Prepare for introspecting on all included [`Command`]s - /// - /// Call this on the top-level [`Command`] when done building and before reading state for - /// cases like completions, custom help output, etc. - pub fn build(&mut self) { - self._build_recursive(true); - self._build_bin_names_internal(); - } - - pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) { - self._build_self(expand_help_tree); - for subcmd in self.get_subcommands_mut() { - subcmd._build_recursive(expand_help_tree); - } - } - - pub(crate) fn _build_self(&mut self, expand_help_tree: bool) { - debug!("Command::_build: name={:?}", self.get_name()); - if !self.settings.is_set(AppSettings::Built) { - // Make sure all the globally set flags apply to us as well - self.settings = self.settings | self.g_settings; - - if self.is_multicall_set() { - self.settings.insert(AppSettings::SubcommandRequired.into()); - self.settings.insert(AppSettings::DisableHelpFlag.into()); - self.settings.insert(AppSettings::DisableVersionFlag.into()); - } - if !cfg!(feature = "help") && self.get_override_help().is_none() { - self.settings.insert(AppSettings::DisableHelpFlag.into()); - self.settings - .insert(AppSettings::DisableHelpSubcommand.into()); - } - if self.is_set(AppSettings::ArgsNegateSubcommands) { - self.settings - .insert(AppSettings::SubcommandsNegateReqs.into()); - } - if self.external_value_parser.is_some() { - self.settings - .insert(AppSettings::AllowExternalSubcommands.into()); - } - if !self.has_subcommands() { - self.settings - .insert(AppSettings::DisableHelpSubcommand.into()); - } - - self._propagate(); - self._check_help_and_version(expand_help_tree); - self._propagate_global_args(); - - let mut pos_counter = 1; - let hide_pv = self.is_set(AppSettings::HidePossibleValues); - for a in self.args.args_mut() { - // Fill in the groups - for g in &a.groups { - if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) { - ag.args.push(a.get_id().clone()); - } else { - let mut ag = ArgGroup::new(g); - ag.args.push(a.get_id().clone()); - self.groups.push(ag); - } - } - - // Figure out implied settings - a._build(); - if hide_pv && a.is_takes_value_set() { - a.settings.set(ArgSettings::HidePossibleValues); - } - if a.is_positional() && a.index.is_none() { - a.index = Some(pos_counter); - pos_counter += 1; - } - } - - self.args._build(); - - #[allow(deprecated)] - { - let highest_idx = self - .get_keymap() - .keys() - .filter_map(|x| { - if let crate::mkeymap::KeyType::Position(n) = x { - Some(*n) - } else { - None - } - }) - .max() - .unwrap_or(0); - let is_trailing_var_arg_set = self.is_trailing_var_arg_set(); - let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set(); - let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set(); - for arg in self.args.args_mut() { - if is_allow_hyphen_values_set && arg.is_takes_value_set() { - arg.settings.insert(ArgSettings::AllowHyphenValues.into()); - } - if is_allow_negative_numbers_set && arg.is_takes_value_set() { - arg.settings - .insert(ArgSettings::AllowNegativeNumbers.into()); - } - if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) { - arg.settings.insert(ArgSettings::TrailingVarArg.into()); - } - } - } - - #[cfg(debug_assertions)] - assert_app(self); - self.settings.set(AppSettings::Built); - } else { - debug!("Command::_build: already built"); - } - } - - pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> { - use std::fmt::Write; - - let mut mid_string = String::from(" "); - #[cfg(feature = "usage")] - if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set() - { - let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) - - for s in &reqs { - mid_string.push_str(&s.to_string()); - mid_string.push(' '); - } - } - let is_multicall_set = self.is_multicall_set(); - - let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name)); - - // Display subcommand name, short and long in usage - let mut sc_names = String::new(); - sc_names.push_str(sc.name.as_str()); - let mut flag_subcmd = false; - if let Some(l) = sc.get_long_flag() { - write!(sc_names, "|--{}", l).unwrap(); - flag_subcmd = true; - } - if let Some(s) = sc.get_short_flag() { - write!(sc_names, "|-{}", s).unwrap(); - flag_subcmd = true; - } - - if flag_subcmd { - sc_names = format!("{{{}}}", sc_names); - } - - let usage_name = self - .bin_name - .as_ref() - .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names)) - .unwrap_or(sc_names); - sc.usage_name = Some(usage_name); - - // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by - // a space - let bin_name = format!( - "{}{}{}", - self.bin_name.as_deref().unwrap_or_default(), - if self.bin_name.is_some() { " " } else { "" }, - &*sc.name - ); - debug!( - "Command::_build_subcommand Setting bin_name of {} to {:?}", - sc.name, bin_name - ); - sc.bin_name = Some(bin_name); - - if sc.display_name.is_none() { - let self_display_name = if is_multicall_set { - self.display_name.as_deref().unwrap_or("") - } else { - self.display_name.as_deref().unwrap_or(&self.name) - }; - let display_name = format!( - "{}{}{}", - self_display_name, - if !self_display_name.is_empty() { - "-" - } else { - "" - }, - &*sc.name - ); - debug!( - "Command::_build_subcommand Setting display_name of {} to {:?}", - sc.name, display_name - ); - sc.display_name = Some(display_name); - } - - // Ensure all args are built and ready to parse - sc._build_self(false); - - Some(sc) - } - - fn _build_bin_names_internal(&mut self) { - debug!("Command::_build_bin_names"); - - if !self.is_set(AppSettings::BinNameBuilt) { - let mut mid_string = String::from(" "); - #[cfg(feature = "usage")] - if !self.is_subcommand_negates_reqs_set() - && !self.is_args_conflicts_with_subcommands_set() - { - let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) - - for s in &reqs { - mid_string.push_str(&s.to_string()); - mid_string.push(' '); - } - } - let is_multicall_set = self.is_multicall_set(); - - let self_bin_name = if is_multicall_set { - self.bin_name.as_deref().unwrap_or("") - } else { - self.bin_name.as_deref().unwrap_or(&self.name) - } - .to_owned(); - - for mut sc in &mut self.subcommands { - debug!("Command::_build_bin_names:iter: bin_name set..."); - - if sc.usage_name.is_none() { - use std::fmt::Write; - // Display subcommand name, short and long in usage - let mut sc_names = String::new(); - sc_names.push_str(sc.name.as_str()); - let mut flag_subcmd = false; - if let Some(l) = sc.get_long_flag() { - write!(sc_names, "|--{}", l).unwrap(); - flag_subcmd = true; - } - if let Some(s) = sc.get_short_flag() { - write!(sc_names, "|-{}", s).unwrap(); - flag_subcmd = true; - } - - if flag_subcmd { - sc_names = format!("{{{}}}", sc_names); - } - - let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names); - debug!( - "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}", - sc.name, usage_name - ); - sc.usage_name = Some(usage_name); - } else { - debug!( - "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})", - sc.name, sc.usage_name - ); - } - - if sc.bin_name.is_none() { - let bin_name = format!( - "{}{}{}", - self_bin_name, - if !self_bin_name.is_empty() { " " } else { "" }, - &*sc.name - ); - debug!( - "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}", - sc.name, bin_name - ); - sc.bin_name = Some(bin_name); - } else { - debug!( - "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})", - sc.name, sc.bin_name - ); - } - - if sc.display_name.is_none() { - let self_display_name = if is_multicall_set { - self.display_name.as_deref().unwrap_or("") - } else { - self.display_name.as_deref().unwrap_or(&self.name) - }; - let display_name = format!( - "{}{}{}", - self_display_name, - if !self_display_name.is_empty() { - "-" - } else { - "" - }, - &*sc.name - ); - debug!( - "Command::_build_bin_names:iter: Setting display_name of {} to {:?}", - sc.name, display_name - ); - sc.display_name = Some(display_name); - } else { - debug!( - "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})", - sc.name, sc.display_name - ); - } - - sc._build_bin_names_internal(); - } - self.set(AppSettings::BinNameBuilt); - } else { - debug!("Command::_build_bin_names: already built"); - } - } - - pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) { - if self.is_set(AppSettings::HelpExpected) || help_required_globally { - let args_missing_help: Vec<Id> = self - .args - .args() - .filter(|arg| arg.get_help().is_none() && arg.get_long_help().is_none()) - .map(|arg| arg.get_id().clone()) - .collect(); - - debug_assert!(args_missing_help.is_empty(), - "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}", - self.name, - args_missing_help.join(", ") - ); - } - - for sub_app in &self.subcommands { - sub_app._panic_on_missing_help(help_required_globally); - } - } - - #[cfg(debug_assertions)] - pub(crate) fn two_args_of<F>(&self, condition: F) -> Option<(&Arg, &Arg)> - where - F: Fn(&Arg) -> bool, - { - two_elements_of(self.args.args().filter(|a: &&Arg| condition(a))) - } - - // just in case - #[allow(unused)] - fn two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)> - where - F: Fn(&ArgGroup) -> bool, - { - two_elements_of(self.groups.iter().filter(|a| condition(a))) - } - - /// Propagate global args - pub(crate) fn _propagate_global_args(&mut self) { - debug!("Command::_propagate_global_args:{}", self.name); - - let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set(); - - for sc in &mut self.subcommands { - if sc.get_name() == "help" && autogenerated_help_subcommand { - // Avoid propagating args to the autogenerated help subtrees used in completion. - // This prevents args from showing up during help completions like - // `myapp help subcmd <TAB>`, which should only suggest subcommands and not args, - // while still allowing args to show up properly on the generated help message. - continue; - } - - for a in self.args.args().filter(|a| a.is_global_set()) { - if sc.find(&a.id).is_some() { - debug!( - "Command::_propagate skipping {:?} to {}, already exists", - a.id, - sc.get_name(), - ); - continue; - } - - debug!( - "Command::_propagate pushing {:?} to {}", - a.id, - sc.get_name(), - ); - sc.args.push(a.clone()); - } - } - } - - /// Propagate settings - pub(crate) fn _propagate(&mut self) { - debug!("Command::_propagate:{}", self.name); - let mut subcommands = std::mem::take(&mut self.subcommands); - for sc in &mut subcommands { - self._propagate_subcommand(sc); - } - self.subcommands = subcommands; - } - - fn _propagate_subcommand(&self, sc: &mut Self) { - // We have to create a new scope in order to tell rustc the borrow of `sc` is - // done and to recursively call this method - { - if self.settings.is_set(AppSettings::PropagateVersion) { - if let Some(version) = self.version.as_ref() { - sc.version.get_or_insert_with(|| version.clone()); - } - if let Some(long_version) = self.long_version.as_ref() { - sc.long_version.get_or_insert_with(|| long_version.clone()); - } - } - - sc.settings = sc.settings | self.g_settings; - sc.g_settings = sc.g_settings | self.g_settings; - sc.term_w = self.term_w; - sc.max_w = self.max_w; - } - } - - pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) { - debug!( - "Command::_check_help_and_version:{} expand_help_tree={}", - self.name, expand_help_tree - ); - - self.long_help_exists = self.long_help_exists_(); - - if !self.is_disable_help_flag_set() { - debug!("Command::_check_help_and_version: Building default --help"); - let mut arg = Arg::new(Id::HELP) - .short('h') - .long("help") - .action(ArgAction::Help); - if self.long_help_exists { - arg = arg - .help("Print help (see more with '--help')") - .long_help("Print help (see a summary with '-h')"); - } else { - arg = arg.help("Print help"); - } - // Avoiding `arg_internal` to not be sensitive to `next_help_heading` / - // `next_display_order` - self.args.push(arg); - } - if !self.is_disable_version_flag_set() { - debug!("Command::_check_help_and_version: Building default --version"); - let arg = Arg::new(Id::VERSION) - .short('V') - .long("version") - .action(ArgAction::Version) - .help("Print version"); - // Avoiding `arg_internal` to not be sensitive to `next_help_heading` / - // `next_display_order` - self.args.push(arg); - } - - if !self.is_set(AppSettings::DisableHelpSubcommand) { - debug!("Command::_check_help_and_version: Building help subcommand"); - let help_about = "Print this message or the help of the given subcommand(s)"; - - let mut help_subcmd = if expand_help_tree { - // Slow code path to recursively clone all other subcommand subtrees under help - let help_subcmd = Command::new("help") - .about(help_about) - .global_setting(AppSettings::DisableHelpSubcommand) - .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); - - let mut help_help_subcmd = Command::new("help").about(help_about); - help_help_subcmd.version = None; - help_help_subcmd.long_version = None; - help_help_subcmd = help_help_subcmd - .setting(AppSettings::DisableHelpFlag) - .setting(AppSettings::DisableVersionFlag); - - help_subcmd.subcommand(help_help_subcmd) - } else { - Command::new("help").about(help_about).arg( - Arg::new("subcommand") - .action(ArgAction::Append) - .num_args(..) - .value_name("COMMAND") - .help("Print help for the subcommand(s)"), - ) - }; - self._propagate_subcommand(&mut help_subcmd); - - // The parser acts like this is set, so let's set it so we don't falsely - // advertise it to the user - help_subcmd.version = None; - help_subcmd.long_version = None; - help_subcmd = help_subcmd - .setting(AppSettings::DisableHelpFlag) - .setting(AppSettings::DisableVersionFlag) - .unset_global_setting(AppSettings::PropagateVersion); - - self.subcommands.push(help_subcmd); - } - } - - fn _copy_subtree_for_help(&self) -> Command { - let mut cmd = Command::new(self.name.clone()) - .hide(self.is_hide_set()) - .global_setting(AppSettings::DisableHelpFlag) - .global_setting(AppSettings::DisableVersionFlag) - .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); - if self.get_about().is_some() { - cmd = cmd.about(self.get_about().unwrap().clone()); - } - cmd - } - - pub(crate) fn _render_version(&self, use_long: bool) -> String { - debug!("Command::_render_version"); - - let ver = if use_long { - self.long_version - .as_deref() - .or(self.version.as_deref()) - .unwrap_or_default() - } else { - self.version - .as_deref() - .or(self.long_version.as_deref()) - .unwrap_or_default() - }; - let display_name = self.get_display_name().unwrap_or_else(|| self.get_name()); - format!("{} {}\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. <file_name> - x.name_no_brackets() - } else { - // Print usage string for flags arguments, e.g. <--help> - x.to_string() - } - }) - .collect::<Vec<_>>() - .join("|"); - let mut styled = StyledStr::new(); - styled.none("<"); - styled.none(g_string); - styled.none(">"); - styled - } -} - -/// A workaround: -/// <https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999> -pub(crate) trait Captures<'a> {} -impl<'a, T> Captures<'a> for T {} - -// Internal Query Methods -impl Command { - /// Iterate through the *flags* & *options* arguments. - #[cfg(any(feature = "usage", feature = "help"))] - pub(crate) fn get_non_positionals(&self) -> impl Iterator<Item = &Arg> { - self.get_arguments().filter(|a| !a.is_positional()) - } - - pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg> { - self.args.args().find(|a| a.get_id() == arg_id) - } - - #[inline] - pub(crate) fn contains_short(&self, s: char) -> bool { - debug_assert!( - self.is_set(AppSettings::Built), - "If Command::_build hasn't been called, manually search through Arg shorts" - ); - - self.args.contains(s) - } - - #[inline] - pub(crate) fn set(&mut self, s: AppSettings) { - self.settings.set(s) - } - - #[inline] - pub(crate) fn has_positionals(&self) -> bool { - self.get_positionals().next().is_some() - } - - #[cfg(any(feature = "usage", feature = "help"))] - pub(crate) fn has_visible_subcommands(&self) -> bool { - self.subcommands - .iter() - .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden)) - } - - /// Check if this subcommand can be referred to as `name`. In other words, - /// check if `name` is the name of this subcommand or is one of its aliases. - #[inline] - pub(crate) fn aliases_to(&self, name: impl AsRef<std::ffi::OsStr>) -> bool { - let name = name.as_ref(); - self.get_name() == name || self.get_all_aliases().any(|alias| alias == name) - } - - /// Check if this subcommand can be referred to as `name`. In other words, - /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases. - #[inline] - pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool { - Some(flag) == self.short_flag - || self.get_all_short_flag_aliases().any(|alias| flag == alias) - } - - /// Check if this subcommand can be referred to as `name`. In other words, - /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases. - #[inline] - pub(crate) fn long_flag_aliases_to(&self, flag: &str) -> bool { - match self.long_flag.as_ref() { - Some(long_flag) => { - long_flag == flag || self.get_all_long_flag_aliases().any(|alias| alias == flag) - } - None => self.get_all_long_flag_aliases().any(|alias| alias == flag), - } - } - - #[cfg(debug_assertions)] - pub(crate) fn id_exists(&self, id: &Id) -> bool { - self.args.args().any(|x| x.get_id() == id) || self.groups.iter().any(|x| x.id == *id) - } - - /// Iterate through the groups this arg is member of. - pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a { - debug!("Command::groups_for_arg: id={:?}", arg); - let arg = arg.clone(); - self.groups - .iter() - .filter(move |grp| grp.args.iter().any(|a| a == &arg)) - .map(|grp| grp.id.clone()) - } - - pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup> { - self.groups.iter().find(|g| g.id == *group_id) - } - - /// Iterate through all the names of all subcommands (not recursively), including aliases. - /// Used for suggestions. - pub(crate) fn all_subcommand_names(&self) -> impl Iterator<Item = &str> + Captures { - self.get_subcommands().flat_map(|sc| { - let name = sc.get_name(); - let aliases = sc.get_all_aliases(); - std::iter::once(name).chain(aliases) - }) - } - - pub(crate) fn required_graph(&self) -> ChildGraph<Id> { - let mut reqs = ChildGraph::with_capacity(5); - for a in self.args.args().filter(|a| a.is_required_set()) { - reqs.insert(a.get_id().clone()); - } - for group in &self.groups { - if group.required { - let idx = reqs.insert(group.id.clone()); - for a in &group.requires { - reqs.insert_child(idx, a.clone()); - } - } - } - - reqs - } - - pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec<Id> { - debug!("Command::unroll_args_in_group: group={:?}", group); - let mut g_vec = vec![group]; - let mut args = vec![]; - - while let Some(g) = g_vec.pop() { - for n in self - .groups - .iter() - .find(|grp| grp.id == *g) - .expect(INTERNAL_ERROR_MSG) - .args - .iter() - { - debug!("Command::unroll_args_in_group:iter: entity={:?}", n); - if !args.contains(n) { - if self.find(n).is_some() { - debug!("Command::unroll_args_in_group:iter: this is an arg"); - args.push(n.clone()) - } else { - debug!("Command::unroll_args_in_group:iter: this is a group"); - g_vec.push(n); - } - } - } - } - - args - } - - pub(crate) fn unroll_arg_requires<F>(&self, func: F, arg: &Id) -> Vec<Id> - where - F: Fn(&(ArgPredicate, Id)) -> Option<Id>, - { - let mut processed = vec![]; - let mut r_vec = vec![arg]; - let mut args = vec![]; - - while let Some(a) = r_vec.pop() { - if processed.contains(&a) { - continue; - } - - processed.push(a); - - if let Some(arg) = self.find(a) { - for r in arg.requires.iter().filter_map(&func) { - if let Some(req) = self.find(&r) { - if !req.requires.is_empty() { - r_vec.push(req.get_id()) - } - } - args.push(r); - } - } - } - - args - } - - /// Find a flag subcommand name by short flag or an alias - pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> { - self.get_subcommands() - .find(|sc| sc.short_flag_aliases_to(c)) - .map(|sc| sc.get_name()) - } - - /// Find a flag subcommand name by long flag or an alias - pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> { - self.get_subcommands() - .find(|sc| sc.long_flag_aliases_to(long)) - .map(|sc| sc.get_name()) - } - - #[cfg(feature = "help")] - pub(crate) fn get_display_order(&self) -> usize { - self.disp_ord.unwrap_or(999) - } - - pub(crate) fn write_help_err(&self, mut use_long: bool) -> StyledStr { - debug!( - "Command::write_help_err: {}, use_long={:?}", - self.get_display_name().unwrap_or_else(|| self.get_name()), - use_long && self.long_help_exists(), - ); - - use_long = use_long && self.long_help_exists(); - let usage = Usage::new(self); - - let mut styled = StyledStr::new(); - write_help(&mut styled, self, &usage, use_long); - - styled - } - - pub(crate) fn write_version_err(&self, use_long: bool) -> StyledStr { - let msg = self._render_version(use_long); - let mut styled = StyledStr::new(); - styled.none(msg); - styled - } - - pub(crate) fn long_help_exists(&self) -> bool { - debug!("Command::long_help_exists: {}", self.long_help_exists); - self.long_help_exists - } - - fn long_help_exists_(&self) -> bool { - debug!("Command::long_help_exists"); - // In this case, both must be checked. This allows the retention of - // original formatting, but also ensures that the actual -h or --help - // specified by the user is sent through. If hide_short_help is not included, - // then items specified with hidden_short_help will also be hidden. - let should_long = |v: &Arg| { - v.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<I, T>(mut iter: I) -> Option<(T, T)> -where - I: Iterator<Item = T>, -{ - let first = iter.next(); - let second = iter.next(); - - match (first, second) { - (Some(first), Some(second)) => Some((first, second)), - _ => None, - } -} - -#[test] -fn check_auto_traits() { - static_assertions::assert_impl_all!(Command: Send, Sync, Unpin); -} diff --git a/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::<Vec<_>>(); - - assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version" - ,cmd.get_name() - ); - } - - for sc in cmd.get_subcommands() { - if let Some(s) = sc.get_short_flag().as_ref() { - short_flags.push(Flag::Command(format!("-{}", s), sc.get_name())); - } - - for short_alias in sc.get_all_short_flag_aliases() { - short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name())); - } - - if let Some(l) = sc.get_long_flag().as_ref() { - assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l); - long_flags.push(Flag::Command(format!("--{}", l), sc.get_name())); - } - - for long_alias in sc.get_all_long_flag_aliases() { - long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name())); - } - } - - for arg in cmd.get_arguments() { - assert_arg(arg); - - assert!( - !cmd.is_multicall_set(), - "Command {}: Arguments like {} cannot be set on a multicall command", - cmd.get_name(), - arg.get_id() - ); - - if let Some(s) = arg.get_short() { - short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str())); - } - - for (short_alias, _) in &arg.short_aliases { - short_flags.push(Flag::Arg( - format!("-{}", short_alias), - arg.get_id().as_str(), - )); - } - - if let Some(l) = arg.get_long() { - assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l); - long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str())); - } - - for (long_alias, _) in &arg.aliases { - long_flags.push(Flag::Arg( - format!("--{}", long_alias), - arg.get_id().as_str(), - )); - } - - // Name conflicts - if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) { - panic!( - "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}", - cmd.get_name(), - arg.get_id(), - duplicate_tip(cmd, first, second), - ); - } - - // Long conflicts - if let Some(l) = arg.get_long() { - if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) { - panic!( - "Command {}: Long option names must be unique for each argument, \ - but '--{}' is in use by both '{}' and '{}'{}", - cmd.get_name(), - l, - first.get_id(), - second.get_id(), - duplicate_tip(cmd, first, second) - ) - } - } - - // Short conflicts - if let Some(s) = arg.get_short() { - if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) { - panic!( - "Command {}: Short option names must be unique for each argument, \ - but '-{}' is in use by both '{}' and '{}'{}", - cmd.get_name(), - s, - first.get_id(), - second.get_id(), - duplicate_tip(cmd, first, second), - ) - } - } - - // Index conflicts - if let Some(idx) = arg.index { - if let Some((first, second)) = - cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx)) - { - panic!( - "Command {}: Argument '{}' has the same index as '{}' \ - and they are both positional arguments\n\n\t \ - Use `Arg::num_args(1..)` to allow one \ - positional argument to take multiple values", - cmd.get_name(), - first.get_id(), - second.get_id() - ) - } - } - - // requires, r_if, r_unless - for req in &arg.requires { - assert!( - cmd.id_exists(&req.1), - "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist", - cmd.get_name(), - req.1, - arg.get_id(), - ); - } - - for req in &arg.r_ifs { - assert!( - !arg.is_required_set(), - "Argument {}: `required` conflicts with `required_if_eq*`", - arg.get_id() - ); - assert!( - cmd.id_exists(&req.0), - "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist", - cmd.get_name(), - req.0, - arg.get_id() - ); - } - - for req in &arg.r_ifs_all { - assert!( - !arg.is_required_set(), - "Argument {}: `required` conflicts with `required_if_eq_all`", - arg.get_id() - ); - assert!( - cmd.id_exists(&req.0), - "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist", - cmd.get_name(), - req.0, - arg.get_id() - ); - } - - for req in &arg.r_unless { - assert!( - !arg.is_required_set(), - "Argument {}: `required` conflicts with `required_unless*`", - arg.get_id() - ); - assert!( - cmd.id_exists(req), - "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist", - cmd.get_name(), - req, - arg.get_id(), - ); - } - - for req in &arg.r_unless_all { - assert!( - !arg.is_required_set(), - "Argument {}: `required` conflicts with `required_unless*`", - arg.get_id() - ); - assert!( - cmd.id_exists(req), - "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist", - cmd.get_name(), - req, - arg.get_id(), - ); - } - - // blacklist - for req in &arg.blacklist { - assert!( - cmd.id_exists(req), - "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist", - cmd.get_name(), - req, - arg.get_id(), - ); - } - - // overrides - for req in &arg.overrides { - assert!( - cmd.id_exists(req), - "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist", - cmd.get_name(), - req, - arg.get_id(), - ); - } - - if arg.is_last_set() { - assert!( - arg.get_long().is_none(), - "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.", - cmd.get_name(), - arg.get_id() - ); - assert!( - arg.get_short().is_none(), - "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.", - cmd.get_name(), - arg.get_id() - ); - } - - assert!( - !(arg.is_required_set() && arg.is_global_set()), - "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required", - cmd.get_name(), - arg.get_id() - ); - - if arg.get_value_hint() == ValueHint::CommandWithArguments { - assert!( - arg.is_positional(), - "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.", - cmd.get_name(), - arg.get_id() - ); - - assert!( - arg.is_trailing_var_arg_set() || arg.is_last_set(), - "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.", - cmd.get_name(), - arg.get_id() - ); - } - } - - for group in cmd.get_groups() { - let derive_hint = if cfg!(feature = "derive") { - " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`" - } else { - "" - }; - - // Name conflicts - assert!( - cmd.get_groups().filter(|x| x.id == group.id).count() < 2, - "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}", - cmd.get_name(), - group.get_id(), - derive_hint - ); - - // Groups should not have naming conflicts with Args - assert!( - !cmd.get_arguments().any(|x| x.get_id() == group.get_id()), - "Command {}: Argument group name '{}' must not conflict with argument name{}", - cmd.get_name(), - group.get_id(), - derive_hint - ); - - for arg in &group.args { - // Args listed inside groups should exist - assert!( - cmd.get_arguments().any(|x| x.get_id() == arg), - "Command {}: Argument group '{}' contains non-existent argument '{}'", - cmd.get_name(), - group.get_id(), - arg - ); - } - } - - // Conflicts between flags and subcommands - - long_flags.sort_unstable(); - short_flags.sort_unstable(); - - detect_duplicate_flags(&long_flags, "long"); - detect_duplicate_flags(&short_flags, "short"); - - let mut subs = FlatSet::new(); - for sc in cmd.get_subcommands() { - assert!( - subs.insert(sc.get_name()), - "Command {}: command name `{}` is duplicated", - cmd.get_name(), - sc.get_name() - ); - for alias in sc.get_all_aliases() { - assert!( - subs.insert(alias), - "Command {}: command `{}` alias `{}` is duplicated", - cmd.get_name(), - sc.get_name(), - alias - ); - } - } - - _verify_positionals(cmd); - - #[cfg(feature = "help")] - if let Some(help_template) = cmd.get_help_template() { - assert!( - !help_template.to_string().contains("{flags}"), - "Command {}: {}", - cmd.get_name(), - "`{flags}` template variable was removed in clap3, they are now included in `{options}`", - ); - assert!( - !help_template.to_string().contains("{unified}"), - "Command {}: {}", - cmd.get_name(), - "`{unified}` template variable was removed in clap3, use `{options}` instead" - ); - #[cfg(feature = "unstable-v5")] - assert!( - !help_template.to_string().contains("{bin}"), - "Command {}: {}", - cmd.get_name(), - "`{bin}` template variable was removed in clap5, use `{name}` instead" - ) - } - - cmd._panic_on_missing_help(cmd.is_help_expected_set()); - assert_app_flags(cmd); -} - -fn duplicate_tip(cmd: &Command, first: &Arg, second: &Arg) -> &'static str { - if !cmd.is_disable_help_flag_set() - && (first.get_id() == Id::HELP || second.get_id() == Id::HELP) - { - " (call `cmd.disable_help_flag(true)` to remove the auto-generated `--help`)" - } else if !cmd.is_disable_version_flag_set() - && (first.get_id() == Id::VERSION || second.get_id() == Id::VERSION) - { - " (call `cmd.disable_version_flag(true)` to remove the auto-generated `--version`)" - } else { - "" - } -} - -#[derive(Eq)] -enum Flag<'a> { - Command(String, &'a str), - Arg(String, &'a str), -} - -impl PartialEq for Flag<'_> { - fn eq(&self, other: &Flag) -> bool { - self.cmp(other) == Ordering::Equal - } -} - -impl PartialOrd for Flag<'_> { - fn partial_cmp(&self, other: &Flag) -> Option<Ordering> { - use Flag::*; - - match (self, other) { - (Command(s1, _), Command(s2, _)) - | (Arg(s1, _), Arg(s2, _)) - | (Command(s1, _), Arg(s2, _)) - | (Arg(s1, _), Command(s2, _)) => { - if s1 == s2 { - Some(Ordering::Equal) - } else { - s1.partial_cmp(s2) - } - } - } - } -} - -impl Ord for Flag<'_> { - fn cmp(&self, other: &Self) -> Ordering { - self.partial_cmp(other).unwrap() - } -} - -fn detect_duplicate_flags(flags: &[Flag], short_or_long: &str) { - use Flag::*; - - for (one, two) in find_duplicates(flags) { - match (one, two) { - (Command(flag, one), Command(_, another)) if one != another => panic!( - "the '{}' {} flag is specified for both '{}' and '{}' subcommands", - flag, short_or_long, one, another - ), - - (Arg(flag, one), Arg(_, another)) if one != another => panic!( - "{} option names must be unique, but '{}' is in use by both '{}' and '{}'", - short_or_long, flag, one, another - ), - - (Arg(flag, arg), Command(_, sub)) | (Command(flag, sub), Arg(_, arg)) => panic!( - "the '{}' {} flag for the '{}' argument conflicts with the short flag \ - for '{}' subcommand", - flag, short_or_long, arg, sub - ), - - _ => {} - } - } -} - -/// Find duplicates in a sorted array. -/// -/// The algorithm is simple: the array is sorted, duplicates -/// must be placed next to each other, we can check only adjacent elements. -fn find_duplicates<T: PartialEq>(slice: &[T]) -> impl Iterator<Item = (&T, &T)> { - slice.windows(2).filter_map(|w| { - if w[0] == w[1] { - Some((&w[0], &w[1])) - } else { - None - } - }) -} - -fn assert_app_flags(cmd: &Command) { - macro_rules! checker { - ($a:ident requires $($b:ident)|+) => { - if cmd.$a() { - let mut s = String::new(); - - $( - if !cmd.$b() { - 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 <req1> [opt1] -- <req2> - // Both of these are valid invocations: - // $ prog r1 -- r2 - // $ prog r1 o1 -- r2 - if found { - foundx2 = true; - continue; - } - found = true; - continue; - } else { - found = false; - } - } - } else { - // Check that if a required positional argument is found, all positions with a lower - // index are also required - for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) { - if found { - assert!( - p.is_required_set(), - "Found non-required positional argument with a lower \ - index than a required positional argument: {:?} index {:?}", - p.get_id(), - p.get_index() - ); - } else if p.is_required_set() && !p.is_last_set() { - // Args that .last(true) don't count since they can be required and have - // positionals with a lower index that aren't required - // Imagine: prog <req1> [opt1] -- <req2> - // Both of these are valid invocations: - // $ prog r1 -- r2 - // $ prog r1 o1 -- r2 - found = true; - continue; - } - } - } - assert!( - cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2, - "Only one positional argument may have last(true) set. Found two." - ); - if cmd - .get_positionals() - .any(|p| p.is_last_set() && p.is_required_set()) - && cmd.has_subcommands() - && !cmd.is_subcommand_negates_reqs_set() - { - panic!( - "Having a required positional argument with .last(true) set *and* child \ - subcommands without setting SubcommandsNegateReqs isn't compatible." - ); - } - - true -} - -fn assert_arg(arg: &Arg) { - debug!("Arg::_debug_asserts:{}", arg.get_id()); - - // Self conflict - // TODO: this check should be recursive - assert!( - !arg.blacklist.iter().any(|x| x == arg.get_id()), - "Argument '{}' cannot conflict with itself", - arg.get_id(), - ); - - assert_eq!( - arg.get_action().takes_values(), - arg.is_takes_value_set(), - "Argument `{}`'s selected action {:?} contradicts `takes_value`", - arg.get_id(), - arg.get_action() - ); - if let Some(action_type_id) = arg.get_action().value_type_id() { - assert_eq!( - action_type_id, - arg.get_value_parser().type_id(), - "Argument `{}`'s selected action {:?} contradicts `value_parser` ({:?})", - arg.get_id(), - arg.get_action(), - arg.get_value_parser() - ); - } - - if arg.get_value_hint() != ValueHint::Unknown { - assert!( - arg.is_takes_value_set(), - "Argument '{}' has value hint but takes no value", - arg.get_id() - ); - - if arg.get_value_hint() == ValueHint::CommandWithArguments { - assert!( - arg.is_multiple_values_set(), - "Argument '{}' uses hint CommandWithArguments and must accept multiple values", - arg.get_id() - ) - } - } - - if arg.index.is_some() { - assert!( - arg.is_positional(), - "Argument '{}' is a positional argument and can't have short or long name versions", - arg.get_id() - ); - assert!( - arg.is_takes_value_set(), - "Argument '{}` is positional, it must take a value{}", - arg.get_id(), - if arg.get_id() == Id::HELP { - " (`mut_arg` no longer works with implicit `--help`)" - } else if arg.get_id() == Id::VERSION { - " (`mut_arg` no longer works with implicit `--version`)" - } else { - "" - } - ); - } - - let num_vals = arg.get_num_args().expect(INTERNAL_ERROR_MSG); - // This can be the cause of later asserts, so put this first - if num_vals != ValueRange::EMPTY { - // HACK: Don't check for flags to make the derive easier - let num_val_names = arg.get_value_names().unwrap_or(&[]).len(); - if num_vals.max_values() < num_val_names { - panic!( - "Argument {}: Too many value names ({}) compared to `num_args` ({})", - arg.get_id(), - num_val_names, - num_vals - ); - } - } - - assert_eq!( - num_vals.takes_values(), - arg.is_takes_value_set(), - "Argument {}: mismatch between `num_args` ({}) and `takes_value`", - arg.get_id(), - num_vals, - ); - assert_eq!( - num_vals.is_multiple(), - arg.is_multiple_values_set(), - "Argument {}: mismatch between `num_args` ({}) and `multiple_values`", - arg.get_id(), - num_vals, - ); - - if 1 < num_vals.min_values() { - assert!( - !arg.is_require_equals_set(), - "Argument {}: cannot accept more than 1 arg (num_args={}) with require_equals", - arg.get_id(), - num_vals - ); - } - - if num_vals == ValueRange::SINGLE { - assert!( - !arg.is_multiple_values_set(), - "Argument {}: mismatch between `num_args` and `multiple_values`", - arg.get_id() - ); - } - - assert_arg_flags(arg); - - assert_defaults(arg, "default_value", arg.default_vals.iter()); - assert_defaults( - arg, - "default_missing_value", - arg.default_missing_vals.iter(), - ); - assert_defaults( - arg, - "default_value_if", - arg.default_vals_ifs - .iter() - .filter_map(|(_, _, default)| default.as_ref()), - ); -} - -fn assert_arg_flags(arg: &Arg) { - macro_rules! checker { - ($a:ident requires $($b:ident)|+) => { - if arg.$a() { - let mut s = String::new(); - - $( - if !arg.$b() { - use std::fmt::Write; - write!(&mut s, " Arg::{} is required when Arg::{} is set.\n", std::stringify!($b), std::stringify!($a)).unwrap(); - } - )+ - - if !s.is_empty() { - panic!("Argument {:?}\n{}", arg.get_id(), s) - } - } - } - } - - checker!(is_hide_possible_values_set requires is_takes_value_set); - checker!(is_allow_hyphen_values_set requires is_takes_value_set); - checker!(is_allow_negative_numbers_set requires is_takes_value_set); - checker!(is_require_equals_set requires is_takes_value_set); - checker!(is_last_set requires is_takes_value_set); - checker!(is_hide_default_value_set requires is_takes_value_set); - checker!(is_multiple_values_set requires is_takes_value_set); - checker!(is_ignore_case_set requires is_takes_value_set); -} - -fn assert_defaults<'d>( - arg: &Arg, - field: &'static str, - defaults: impl IntoIterator<Item = &'d OsStr>, -) { - for default_os in defaults { - let value_parser = arg.get_value_parser(); - let assert_cmd = Command::new("assert"); - if let Some(delim) = arg.get_value_delimiter() { - let default_os = RawOsStr::new(default_os); - for part in default_os.split(delim) { - if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), &part.to_os_str()) - { - panic!( - "Argument `{}`'s {}={:?} failed validation: {}", - arg.get_id(), - field, - part.to_str_lossy(), - err - ); - } - } - } else if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), default_os) { - panic!( - "Argument `{}`'s {}={:?} failed validation: {}", - arg.get_id(), - field, - default_os, - err - ); - } - } -} diff --git a/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<Str> for OsStr { - fn from(id: Str) -> Self { - match id.into_inner() { - crate::builder::StrInner::Static(s) => Self::from_static_ref(std::ffi::OsStr::new(s)), - crate::builder::StrInner::Owned(s) => Self::from_ref(std::ffi::OsStr::new(s.as_ref())), - } - } -} - -#[cfg(not(feature = "string"))] -impl From<Str> for OsStr { - fn from(id: Str) -> Self { - Self::from_static_ref(std::ffi::OsStr::new(id.into_inner().0)) - } -} - -#[cfg(feature = "perf")] -impl From<&'_ Str> for OsStr { - fn from(id: &'_ Str) -> Self { - match id.clone().into_inner() { - crate::builder::StrInner::Static(s) => Self::from_static_ref(std::ffi::OsStr::new(s)), - crate::builder::StrInner::Owned(s) => Self::from_ref(std::ffi::OsStr::new(s.as_ref())), - } - } -} - -impl From<&'_ Str> for OsStr { - fn from(id: &'_ Str) -> Self { - id.clone().into() - } -} - -#[cfg(feature = "string")] -impl From<std::ffi::OsString> for OsStr { - fn from(name: std::ffi::OsString) -> Self { - Self::from_string(name) - } -} - -#[cfg(feature = "string")] -impl From<&'_ std::ffi::OsString> for OsStr { - fn from(name: &'_ std::ffi::OsString) -> Self { - Self::from_ref(name.as_os_str()) - } -} - -#[cfg(feature = "string")] -impl From<std::string::String> for OsStr { - fn from(name: std::string::String) -> Self { - Self::from_string(name.into()) - } -} - -#[cfg(feature = "string")] -impl From<&'_ std::string::String> for OsStr { - fn from(name: &'_ std::string::String) -> Self { - Self::from_ref(name.as_str().as_ref()) - } -} - -impl From<&'static std::ffi::OsStr> for OsStr { - fn from(name: &'static std::ffi::OsStr) -> Self { - Self::from_static_ref(name) - } -} - -impl From<&'_ &'static std::ffi::OsStr> for OsStr { - fn from(name: &'_ &'static std::ffi::OsStr) -> Self { - Self::from_static_ref(name) - } -} - -impl From<&'static str> for OsStr { - fn from(name: &'static str) -> Self { - Self::from_static_ref(name.as_ref()) - } -} - -impl From<&'_ &'static str> for OsStr { - fn from(name: &'_ &'static str) -> Self { - Self::from_static_ref((*name).as_ref()) - } -} - -impl From<OsStr> for std::ffi::OsString { - fn from(name: OsStr) -> Self { - name.name.into_os_string() - } -} - -impl From<OsStr> for std::path::PathBuf { - fn from(name: OsStr) -> Self { - std::ffi::OsString::from(name).into() - } -} - -impl std::fmt::Debug for OsStr { - #[inline] - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Debug::fmt(self.as_os_str(), f) - } -} - -impl std::ops::Deref for OsStr { - type Target = std::ffi::OsStr; - - #[inline] - fn deref(&self) -> &std::ffi::OsStr { - self.as_os_str() - } -} - -impl AsRef<std::ffi::OsStr> for OsStr { - #[inline] - fn as_ref(&self) -> &std::ffi::OsStr { - self.as_os_str() - } -} - -impl AsRef<std::path::Path> for OsStr { - #[inline] - fn as_ref(&self) -> &std::path::Path { - std::path::Path::new(self) - } -} - -impl std::borrow::Borrow<std::ffi::OsStr> for OsStr { - #[inline] - fn borrow(&self) -> &std::ffi::OsStr { - self.as_os_str() - } -} - -impl PartialEq<str> for OsStr { - #[inline] - fn eq(&self, other: &str) -> bool { - PartialEq::eq(self.as_os_str(), other) - } -} -impl PartialEq<OsStr> for str { - #[inline] - fn eq(&self, other: &OsStr) -> bool { - PartialEq::eq(self, other.as_os_str()) - } -} - -impl PartialEq<&'_ str> for OsStr { - #[inline] - fn eq(&self, other: &&str) -> bool { - PartialEq::eq(self.as_os_str(), *other) - } -} -impl PartialEq<OsStr> for &'_ str { - #[inline] - fn eq(&self, other: &OsStr) -> bool { - PartialEq::eq(*self, other.as_os_str()) - } -} - -impl PartialEq<&'_ std::ffi::OsStr> for OsStr { - #[inline] - fn eq(&self, other: &&std::ffi::OsStr) -> bool { - PartialEq::eq(self.as_os_str(), *other) - } -} -impl PartialEq<OsStr> for &'_ std::ffi::OsStr { - #[inline] - fn eq(&self, other: &OsStr) -> bool { - PartialEq::eq(*self, other.as_os_str()) - } -} - -impl PartialEq<std::string::String> for OsStr { - #[inline] - fn eq(&self, other: &std::string::String) -> bool { - PartialEq::eq(self.as_os_str(), other.as_str()) - } -} -impl PartialEq<OsStr> for std::string::String { - #[inline] - fn eq(&self, other: &OsStr) -> bool { - PartialEq::eq(self.as_str(), other.as_os_str()) - } -} - -impl PartialEq<std::ffi::OsString> for OsStr { - #[inline] - fn eq(&self, other: &std::ffi::OsString) -> bool { - PartialEq::eq(self.as_os_str(), other.as_os_str()) - } -} -impl PartialEq<OsStr> for std::ffi::OsString { - #[inline] - fn eq(&self, other: &OsStr) -> bool { - PartialEq::eq(self.as_os_str(), other.as_os_str()) - } -} - -#[cfg(feature = "string")] -pub(crate) mod inner { - #[derive(Clone)] - pub(crate) enum Inner { - Static(&'static std::ffi::OsStr), - Owned(Box<std::ffi::OsStr>), - } - - impl Inner { - pub(crate) fn from_string(name: std::ffi::OsString) -> Self { - Self::Owned(name.into_boxed_os_str()) - } - - pub(crate) fn from_ref(name: &std::ffi::OsStr) -> Self { - Self::Owned(Box::from(name)) - } - - pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self { - Self::Static(name) - } - - pub(crate) fn as_os_str(&self) -> &std::ffi::OsStr { - match self { - Self::Static(s) => s, - Self::Owned(s) => s.as_ref(), - } - } - - pub(crate) fn into_os_string(self) -> std::ffi::OsString { - self.as_os_str().to_owned() - } - } -} - -#[cfg(not(feature = "string"))] -pub(crate) mod inner { - #[derive(Clone)] - pub(crate) struct Inner(&'static std::ffi::OsStr); - - impl Inner { - pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self { - Self(name) - } - - pub(crate) fn as_os_str(&self) -> &std::ffi::OsStr { - self.0 - } - - pub(crate) fn into_os_string(self) -> std::ffi::OsString { - self.as_os_str().to_owned() - } - } -} - -pub(crate) use inner::Inner; - -impl Default for Inner { - fn default() -> Self { - Self::from_static_ref(std::ffi::OsStr::new("")) - } -} - -impl PartialEq for Inner { - fn eq(&self, other: &Inner) -> bool { - self.as_os_str() == other.as_os_str() - } -} - -impl PartialOrd for Inner { - fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { - self.as_os_str().partial_cmp(other.as_os_str()) - } -} - -impl Ord for Inner { - fn cmp(&self, other: &Inner) -> std::cmp::Ordering { - self.as_os_str().cmp(other.as_os_str()) - } -} - -impl Eq for Inner {} - -impl std::hash::Hash for Inner { - #[inline] - fn hash<H: std::hash::Hasher>(&self, state: &mut H) { - self.as_os_str().hash(state); - } -} diff --git a/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<StyledStr>, - aliases: Vec<Str>, // (name, visible) - hide: bool, -} - -impl PossibleValue { - /// Create a [`PossibleValue`] with its name. - /// - /// The name will be used to decide whether this value was provided by the user to an argument. - /// - /// **NOTE:** In case it is not [hidden] it will also be shown in help messages for arguments - /// that use it as a [possible value] and have not hidden them through [`Arg::hide_possible_values(true)`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::builder::PossibleValue; - /// PossibleValue::new("fast") - /// # ; - /// ``` - /// [hidden]: PossibleValue::hide - /// [possible value]: crate::builder::PossibleValuesParser - /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() - pub fn new(name: impl Into<Str>) -> Self { - PossibleValue { - name: name.into(), - ..Default::default() - } - } - - /// Sets the help description of the value. - /// - /// This is typically displayed in completions (where supported) and should be a short, one-line - /// description. - /// - /// # Examples - /// - /// ```rust - /// # use clap::builder::PossibleValue; - /// PossibleValue::new("slow") - /// .help("not fast") - /// # ; - /// ``` - #[inline] - #[must_use] - pub fn help(mut self, help: impl IntoResettable<StyledStr>) -> Self { - self.help = help.into_resettable().into_option(); - self - } - - /// Hides this value from help and shell completions. - /// - /// This is an alternative to hiding through [`Arg::hide_possible_values(true)`], if you only - /// want to hide some values. - /// - /// # Examples - /// - /// ```rust - /// # use clap::builder::PossibleValue; - /// PossibleValue::new("secret") - /// .hide(true) - /// # ; - /// ``` - /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() - #[inline] - #[must_use] - pub fn hide(mut self, yes: bool) -> Self { - self.hide = yes; - self - } - - /// Sets a *hidden* alias for this argument value. - /// - /// # Examples - /// - /// ```rust - /// # use clap::builder::PossibleValue; - /// PossibleValue::new("slow") - /// .alias("not-fast") - /// # ; - /// ``` - #[must_use] - pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self { - if let Some(name) = name.into_resettable().into_option() { - self.aliases.push(name); - } else { - self.aliases.clear(); - } - self - } - - /// Sets multiple *hidden* aliases for this argument value. - /// - /// # Examples - /// - /// ```rust - /// # use clap::builder::PossibleValue; - /// PossibleValue::new("slow") - /// .aliases(["not-fast", "snake-like"]) - /// # ; - /// ``` - #[must_use] - pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { - self.aliases.extend(names.into_iter().map(|a| a.into())); - self - } -} - -/// Reflection -impl PossibleValue { - /// Get the name of the argument value - #[inline] - pub fn get_name(&self) -> &str { - self.name.as_str() - } - - /// Get the help specified for this argument, if any - #[inline] - pub fn get_help(&self) -> Option<&StyledStr> { - self.help.as_ref() - } - - /// Get the help specified for this argument, if any and the argument - /// value is not hidden - #[inline] - #[cfg(feature = "help")] - pub(crate) fn get_visible_help(&self) -> Option<&StyledStr> { - if !self.hide { - self.get_help() - } else { - None - } - } - - /// Report if [`PossibleValue::hide`] is set - #[inline] - pub fn is_hide_set(&self) -> bool { - self.hide - } - - /// Report if PossibleValue is not hidden and has a help message - pub(crate) fn should_show_help(&self) -> bool { - !self.hide && self.help.is_some() - } - - /// Get the name if argument value is not hidden, `None` otherwise, - /// but wrapped in quotes if it contains whitespace - #[cfg(feature = "help")] - pub(crate) fn get_visible_quoted_name(&self) -> Option<std::borrow::Cow<'_, str>> { - if !self.hide { - Some(if self.name.contains(char::is_whitespace) { - format!("{:?}", self.name).into() - } else { - self.name.as_str().into() - }) - } else { - None - } - } - - /// Returns all valid values of the argument value. - /// - /// Namely the name and all aliases. - pub fn get_name_and_aliases(&self) -> impl Iterator<Item = &str> + '_ { - std::iter::once(self.get_name()).chain(self.aliases.iter().map(|s| s.as_str())) - } - - /// Tests if the value is valid for this argument value - /// - /// The value is valid if it is either the name or one of the aliases. - /// - /// # Examples - /// - /// ```rust - /// # use clap::builder::PossibleValue; - /// let arg_value = PossibleValue::new("fast").alias("not-slow"); - /// - /// assert!(arg_value.matches("fast", false)); - /// assert!(arg_value.matches("not-slow", false)); - /// - /// assert!(arg_value.matches("FAST", true)); - /// assert!(!arg_value.matches("FAST", false)); - /// ``` - pub fn matches(&self, value: &str, ignore_case: bool) -> bool { - if ignore_case { - self.get_name_and_aliases() - .any(|name| eq_ignore_case(name, value)) - } else { - self.get_name_and_aliases().any(|name| name == value) - } - } -} - -impl<S: Into<Str>> From<S> for PossibleValue { - fn from(s: S) -> Self { - Self::new(s) - } -} diff --git a/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>) -> Self { - range.into() - } - - pub(crate) fn raw(start_inclusive: usize, end_inclusive: usize) -> Self { - debug_assert!(start_inclusive <= end_inclusive); - Self { - start_inclusive, - end_inclusive, - } - } - - /// Fewest number of values the argument accepts - pub fn min_values(&self) -> usize { - self.start_inclusive - } - - /// Most number of values the argument accepts - pub fn max_values(&self) -> usize { - self.end_inclusive - } - - /// Report whether the argument takes any values (ie is a flag) - /// - /// # Examples - /// - /// ``` - /// # use clap::builder::ValueRange; - /// let range = ValueRange::new(5); - /// assert!(range.takes_values()); - /// - /// let range = ValueRange::new(0); - /// assert!(!range.takes_values()); - /// ``` - pub fn takes_values(&self) -> bool { - self.end_inclusive != 0 - } - - pub(crate) fn is_unbounded(&self) -> bool { - self.end_inclusive == usize::MAX - } - - pub(crate) fn is_fixed(&self) -> bool { - self.start_inclusive == self.end_inclusive - } - - pub(crate) fn is_multiple(&self) -> bool { - self.start_inclusive != self.end_inclusive || 1 < self.start_inclusive - } - - pub(crate) fn num_values(&self) -> Option<usize> { - self.is_fixed().then_some(self.start_inclusive) - } - - pub(crate) fn accepts_more(&self, current: usize) -> bool { - current < self.end_inclusive - } -} - -impl std::ops::RangeBounds<usize> for ValueRange { - fn start_bound(&self) -> std::ops::Bound<&usize> { - std::ops::Bound::Included(&self.start_inclusive) - } - - fn end_bound(&self) -> std::ops::Bound<&usize> { - std::ops::Bound::Included(&self.end_inclusive) - } -} - -impl Default for ValueRange { - fn default() -> Self { - Self::SINGLE - } -} - -impl From<usize> for ValueRange { - fn from(fixed: usize) -> Self { - (fixed..=fixed).into() - } -} - -impl From<std::ops::Range<usize>> for ValueRange { - fn from(range: std::ops::Range<usize>) -> Self { - let start_inclusive = range.start; - let end_inclusive = range.end.saturating_sub(1); - Self::raw(start_inclusive, end_inclusive) - } -} - -impl From<std::ops::RangeFull> for ValueRange { - fn from(_: std::ops::RangeFull) -> Self { - let start_inclusive = 0; - let end_inclusive = usize::MAX; - Self::raw(start_inclusive, end_inclusive) - } -} - -impl From<std::ops::RangeFrom<usize>> for ValueRange { - fn from(range: std::ops::RangeFrom<usize>) -> Self { - let start_inclusive = range.start; - let end_inclusive = usize::MAX; - Self::raw(start_inclusive, end_inclusive) - } -} - -impl From<std::ops::RangeTo<usize>> for ValueRange { - fn from(range: std::ops::RangeTo<usize>) -> Self { - let start_inclusive = 0; - let end_inclusive = range.end.saturating_sub(1); - Self::raw(start_inclusive, end_inclusive) - } -} - -impl From<std::ops::RangeInclusive<usize>> for ValueRange { - fn from(range: std::ops::RangeInclusive<usize>) -> Self { - let start_inclusive = *range.start(); - let end_inclusive = *range.end(); - Self::raw(start_inclusive, end_inclusive) - } -} - -impl From<std::ops::RangeToInclusive<usize>> for ValueRange { - fn from(range: std::ops::RangeToInclusive<usize>) -> Self { - let start_inclusive = 0; - let end_inclusive = range.end; - Self::raw(start_inclusive, end_inclusive) - } -} - -impl std::fmt::Display for ValueRange { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - ok!(self.start_inclusive.fmt(f)); - if !self.is_fixed() { - ok!("..=".fmt(f)); - ok!(self.end_inclusive.fmt(f)); - } - Ok(()) - } -} - -impl std::fmt::Debug for ValueRange { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{}", self) - } -} - -#[cfg(test)] -mod test { - use super::*; - - use std::ops::RangeBounds; - - #[test] - fn from_fixed() { - let range: ValueRange = 5.into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&5)); - assert!(range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), Some(5)); - assert!(range.takes_values()); - } - - #[test] - fn from_fixed_empty() { - let range: ValueRange = 0.into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&0)); - assert!(range.is_fixed()); - assert!(!range.is_multiple()); - assert_eq!(range.num_values(), Some(0)); - assert!(!range.takes_values()); - } - - #[test] - fn from_range() { - let range: ValueRange = (5..10).into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&9)); - assert!(!range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), None); - assert!(range.takes_values()); - } - - #[test] - fn from_range_inclusive() { - let range: ValueRange = (5..=10).into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&10)); - assert!(!range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), None); - assert!(range.takes_values()); - } - - #[test] - fn from_range_full() { - let range: ValueRange = (..).into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&usize::MAX)); - assert!(!range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), None); - assert!(range.takes_values()); - } - - #[test] - fn from_range_from() { - let range: ValueRange = (5..).into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&usize::MAX)); - assert!(!range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), None); - assert!(range.takes_values()); - } - - #[test] - fn from_range_to() { - let range: ValueRange = (..10).into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&9)); - assert!(!range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), None); - assert!(range.takes_values()); - } - - #[test] - fn from_range_to_inclusive() { - let range: ValueRange = (..=10).into(); - assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); - assert_eq!(range.end_bound(), std::ops::Bound::Included(&10)); - assert!(!range.is_fixed()); - assert!(range.is_multiple()); - assert_eq!(range.num_values(), None); - assert!(range.takes_values()); - } -} diff --git a/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<Option<T>>` or `Option<impl Into<T>>`, this isn't ambiguous for the `None` -// case. - -use crate::builder::ArgAction; -use crate::builder::OsStr; -use crate::builder::Str; -use crate::builder::StyledStr; -use crate::builder::ValueHint; -use crate::builder::ValueParser; -use crate::builder::ValueRange; - -/// Clearable builder value -/// -/// This allows a builder function to both accept any value that can [`Into::into`] `T` (like -/// `&str` into `OsStr`) as well as `None` to reset it to the default. This is needed to -/// workaround a limitation where you can't have a function argument that is `impl Into<Option<T>>` -/// where `T` is `impl Into<S>` accept `None` as its type is ambiguous. -/// -/// # Example -/// -/// ```rust -/// # use clap::Command; -/// # use clap::Arg; -/// fn common() -> Command { -/// Command::new("cli") -/// .arg(Arg::new("input").short('i').long("input")) -/// } -/// let mut command = common(); -/// command.mut_arg("input", |arg| arg.short(None)); -/// ``` -#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum Resettable<T> { - /// Overwrite builder value - Value(T), - /// Reset builder value - Reset, -} - -impl<T> Resettable<T> { - pub(crate) fn into_option(self) -> Option<T> { - match self { - Self::Value(t) => Some(t), - Self::Reset => None, - } - } -} - -impl<T> From<T> for Resettable<T> { - fn from(other: T) -> Self { - Self::Value(other) - } -} - -impl<T> From<Option<T>> for Resettable<T> { - fn from(other: Option<T>) -> Self { - match other { - Some(inner) => Self::Value(inner), - None => Self::Reset, - } - } -} - -/// Convert to the intended resettable type -pub trait IntoResettable<T> { - /// Convert to the intended resettable type - fn into_resettable(self) -> Resettable<T>; -} - -impl IntoResettable<char> for Option<char> { - fn into_resettable(self) -> Resettable<char> { - match self { - Some(s) => Resettable::Value(s), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<usize> for Option<usize> { - fn into_resettable(self) -> Resettable<usize> { - match self { - Some(s) => Resettable::Value(s), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<ArgAction> for Option<ArgAction> { - fn into_resettable(self) -> Resettable<ArgAction> { - match self { - Some(s) => Resettable::Value(s), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<ValueHint> for Option<ValueHint> { - fn into_resettable(self) -> Resettable<ValueHint> { - match self { - Some(s) => Resettable::Value(s), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<ValueParser> for Option<ValueParser> { - fn into_resettable(self) -> Resettable<ValueParser> { - match self { - Some(s) => Resettable::Value(s), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<StyledStr> for Option<&'static str> { - fn into_resettable(self) -> Resettable<StyledStr> { - match self { - Some(s) => Resettable::Value(s.into()), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<OsStr> for Option<&'static str> { - fn into_resettable(self) -> Resettable<OsStr> { - match self { - Some(s) => Resettable::Value(s.into()), - None => Resettable::Reset, - } - } -} - -impl IntoResettable<Str> for Option<&'static str> { - fn into_resettable(self) -> Resettable<Str> { - match self { - Some(s) => Resettable::Value(s.into()), - None => Resettable::Reset, - } - } -} - -impl<T> IntoResettable<T> for Resettable<T> { - fn into_resettable(self) -> Resettable<T> { - self - } -} - -impl IntoResettable<char> for char { - fn into_resettable(self) -> Resettable<char> { - Resettable::Value(self) - } -} - -impl IntoResettable<usize> for usize { - fn into_resettable(self) -> Resettable<usize> { - Resettable::Value(self) - } -} - -impl IntoResettable<ArgAction> for ArgAction { - fn into_resettable(self) -> Resettable<ArgAction> { - Resettable::Value(self) - } -} - -impl IntoResettable<ValueHint> for ValueHint { - fn into_resettable(self) -> Resettable<ValueHint> { - Resettable::Value(self) - } -} - -impl<I: Into<ValueRange>> IntoResettable<ValueRange> for I { - fn into_resettable(self) -> Resettable<ValueRange> { - Resettable::Value(self.into()) - } -} - -impl<I: Into<ValueParser>> IntoResettable<ValueParser> for I { - fn into_resettable(self) -> Resettable<ValueParser> { - Resettable::Value(self.into()) - } -} - -impl<I: Into<String>> IntoResettable<String> for I { - fn into_resettable(self) -> Resettable<String> { - Resettable::Value(self.into()) - } -} - -impl<I: Into<StyledStr>> IntoResettable<StyledStr> for I { - fn into_resettable(self) -> Resettable<StyledStr> { - Resettable::Value(self.into()) - } -} - -impl<I: Into<OsStr>> IntoResettable<OsStr> for I { - fn into_resettable(self) -> Resettable<OsStr> { - Resettable::Value(self.into()) - } -} - -impl<I: Into<Str>> IntoResettable<Str> for I { - fn into_resettable(self) -> Resettable<Str> { - Resettable::Value(self.into()) - } -} - -impl<I: Into<crate::Id>> IntoResettable<crate::Id> for I { - fn into_resettable(self) -> Resettable<crate::Id> { - Resettable::Value(self.into()) - } -} diff --git a/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<std::string::String> for Str { - fn from(name: std::string::String) -> Self { - Self::from_string(name) - } -} - -#[cfg(feature = "string")] -impl From<&'_ std::string::String> for Str { - fn from(name: &'_ std::string::String) -> Self { - Self::from_ref(name.as_str()) - } -} - -impl From<&'static str> for Str { - fn from(name: &'static str) -> Self { - Self::from_static_ref(name) - } -} - -impl From<&'_ &'static str> for Str { - fn from(name: &'_ &'static str) -> Self { - Self::from_static_ref(name) - } -} - -impl From<Str> for String { - fn from(name: Str) -> Self { - name.name.into_string() - } -} - -impl From<Str> for Vec<u8> { - fn from(name: Str) -> Self { - String::from(name).into() - } -} - -impl From<Str> for std::ffi::OsString { - fn from(name: Str) -> Self { - String::from(name).into() - } -} - -impl From<Str> for std::path::PathBuf { - fn from(name: Str) -> Self { - String::from(name).into() - } -} - -impl std::fmt::Display for Str { - #[inline] - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Display::fmt(self.as_str(), f) - } -} - -impl std::fmt::Debug for Str { - #[inline] - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Debug::fmt(self.as_str(), f) - } -} - -impl std::ops::Deref for Str { - type Target = str; - - #[inline] - fn deref(&self) -> &str { - self.as_str() - } -} - -impl AsRef<str> for Str { - #[inline] - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl AsRef<[u8]> for Str { - #[inline] - fn as_ref(&self) -> &[u8] { - self.as_bytes() - } -} - -impl AsRef<std::ffi::OsStr> for Str { - #[inline] - fn as_ref(&self) -> &std::ffi::OsStr { - (**self).as_ref() - } -} - -impl AsRef<std::path::Path> for Str { - #[inline] - fn as_ref(&self) -> &std::path::Path { - std::path::Path::new(self) - } -} - -impl std::borrow::Borrow<str> for Str { - #[inline] - fn borrow(&self) -> &str { - self.as_str() - } -} - -impl PartialEq<str> for Str { - #[inline] - fn eq(&self, other: &str) -> bool { - PartialEq::eq(self.as_str(), other) - } -} -impl PartialEq<Str> for str { - #[inline] - fn eq(&self, other: &Str) -> bool { - PartialEq::eq(self, other.as_str()) - } -} - -impl PartialEq<&'_ str> for Str { - #[inline] - fn eq(&self, other: &&str) -> bool { - PartialEq::eq(self.as_str(), *other) - } -} -impl PartialEq<Str> for &'_ str { - #[inline] - fn eq(&self, other: &Str) -> bool { - PartialEq::eq(*self, other.as_str()) - } -} - -impl PartialEq<std::ffi::OsStr> for Str { - #[inline] - fn eq(&self, other: &std::ffi::OsStr) -> bool { - PartialEq::eq(self.as_str(), other) - } -} -impl PartialEq<Str> for std::ffi::OsStr { - #[inline] - fn eq(&self, other: &Str) -> bool { - PartialEq::eq(self, other.as_str()) - } -} - -impl PartialEq<&'_ std::ffi::OsStr> for Str { - #[inline] - fn eq(&self, other: &&std::ffi::OsStr) -> bool { - PartialEq::eq(self.as_str(), *other) - } -} -impl PartialEq<Str> for &'_ std::ffi::OsStr { - #[inline] - fn eq(&self, other: &Str) -> bool { - PartialEq::eq(*self, other.as_str()) - } -} - -impl PartialEq<std::string::String> for Str { - #[inline] - fn eq(&self, other: &std::string::String) -> bool { - PartialEq::eq(self.as_str(), other.as_str()) - } -} -impl PartialEq<Str> for std::string::String { - #[inline] - fn eq(&self, other: &Str) -> bool { - PartialEq::eq(self.as_str(), other.as_str()) - } -} - -#[cfg(feature = "string")] -pub(crate) mod inner { - #[derive(Clone)] - pub(crate) enum Inner { - Static(&'static str), - Owned(Box<str>), - } - - impl Inner { - pub(crate) fn from_string(name: std::string::String) -> Self { - Self::Owned(name.into_boxed_str()) - } - - pub(crate) fn from_ref(name: &str) -> Self { - Self::Owned(Box::from(name)) - } - - pub(crate) fn from_static_ref(name: &'static str) -> Self { - Self::Static(name) - } - - pub(crate) fn as_str(&self) -> &str { - match self { - Self::Static(s) => s, - Self::Owned(s) => s.as_ref(), - } - } - - pub(crate) fn into_string(self) -> String { - 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<std::cmp::Ordering> { - self.as_str().partial_cmp(other.as_str()) - } -} - -impl Ord for Inner { - fn cmp(&self, other: &Inner) -> std::cmp::Ordering { - self.as_str().cmp(other.as_str()) - } -} - -impl Eq for Inner {} - -impl std::hash::Hash for Inner { - #[inline] - fn hash<H: std::hash::Hasher>(&self, state: &mut H) { - self.as_str().hash(state); - } -} diff --git a/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<Style>, String)>, - #[cfg(not(feature = "color"))] - pieces: String, -} - -impl StyledStr { - /// Create an empty buffer - #[cfg(feature = "color")] - pub const fn new() -> Self { - Self { pieces: Vec::new() } - } - - /// Create an empty buffer - #[cfg(not(feature = "color"))] - pub const fn new() -> Self { - Self { - pieces: String::new(), - } - } - - /// Display using [ANSI Escape Code](https://en.wikipedia.org/wiki/ANSI_escape_code) styling - #[cfg(feature = "color")] - pub fn ansi(&self) -> impl std::fmt::Display + '_ { - AnsiDisplay { styled: self } - } - - pub(crate) fn header(&mut self, msg: impl Into<String>) { - self.stylize_(Some(Style::Header), msg.into()); - } - - pub(crate) fn literal(&mut self, msg: impl Into<String>) { - self.stylize_(Some(Style::Literal), msg.into()); - } - - pub(crate) fn placeholder(&mut self, msg: impl Into<String>) { - self.stylize_(Some(Style::Placeholder), msg.into()); - } - - #[cfg_attr(not(feature = "error-context"), allow(dead_code))] - pub(crate) fn good(&mut self, msg: impl Into<String>) { - self.stylize_(Some(Style::Good), msg.into()); - } - - #[cfg_attr(not(feature = "error-context"), allow(dead_code))] - pub(crate) fn warning(&mut self, msg: impl Into<String>) { - self.stylize_(Some(Style::Warning), msg.into()); - } - - pub(crate) fn error(&mut self, msg: impl Into<String>) { - self.stylize_(Some(Style::Error), msg.into()); - } - - #[allow(dead_code)] - pub(crate) fn hint(&mut self, msg: impl Into<String>) { - self.stylize_(Some(Style::Hint), msg.into()); - } - - pub(crate) fn none(&mut self, msg: impl Into<String>) { - self.stylize_(None, msg.into()); - } - - pub(crate) fn stylize(&mut self, style: impl Into<Option<Style>>, msg: impl Into<String>) { - self.stylize_(style.into(), msg.into()); - } - - pub(crate) fn trim(&mut self) { - self.trim_start(); - self.trim_end(); - } - - pub(crate) fn trim_start(&mut self) { - if let Some((_, item)) = self.iter_mut().next() { - *item = item.trim_start().to_owned(); - } - } - - #[cfg(feature = "color")] - pub(crate) fn trim_end(&mut self) { - if let Some((_, item)) = self.pieces.last_mut() { - *item = item.trim_end().to_owned(); - } - } - - #[cfg(not(feature = "color"))] - pub(crate) fn trim_end(&mut self) { - self.pieces = self.pieces.trim_end().to_owned(); - } - - #[cfg(feature = "help")] - pub(crate) fn indent(&mut self, initial: &str, trailing: &str) { - if let Some((_, first)) = self.iter_mut().next() { - first.insert_str(0, initial); - } - let mut line_sep = "\n".to_owned(); - line_sep.push_str(trailing); - for (_, content) in self.iter_mut() { - *content = content.replace('\n', &line_sep); - } - } - - #[cfg(all(not(feature = "wrap_help"), feature = "help"))] - pub(crate) fn wrap(&mut self, _hard_width: usize) {} - - #[cfg(feature = "wrap_help")] - pub(crate) fn wrap(&mut self, hard_width: usize) { - let mut wrapper = crate::output::textwrap::wrap_algorithms::LineWrapper::new(hard_width); - for (_, content) in self.iter_mut() { - let mut total = Vec::new(); - for (i, line) in content.split_inclusive('\n').enumerate() { - if 0 < i { - // start of a section does not imply newline - wrapper.reset(); - } - let line = crate::output::textwrap::word_separators::find_words_ascii_space(line) - .collect::<Vec<_>>(); - total.extend(wrapper.wrap(line)); - } - let total = total.join(""); - *content = total; - } - - self.trim_end(); - } - - #[cfg(feature = "color")] - fn stylize_(&mut self, style: Option<Style>, msg: String) { - if !msg.is_empty() { - self.pieces.push((style, msg)); - } - } - - #[cfg(not(feature = "color"))] - fn stylize_(&mut self, _style: Option<Style>, msg: String) { - self.pieces.push_str(&msg); - } - - #[inline(never)] - #[cfg(feature = "help")] - pub(crate) fn display_width(&self) -> usize { - let mut width = 0; - for (_, c) in self.iter() { - width += crate::output::display_width(c); - } - width - } - - #[cfg(feature = "help")] - pub(crate) fn is_empty(&self) -> bool { - self.pieces.is_empty() - } - - #[cfg(feature = "color")] - pub(crate) fn iter(&self) -> impl Iterator<Item = (Option<Style>, &str)> { - self.pieces.iter().map(|(s, c)| (*s, c.as_str())) - } - - #[cfg(not(feature = "color"))] - pub(crate) fn iter(&self) -> impl Iterator<Item = (Option<Style>, &str)> { - [(None, self.pieces.as_str())].into_iter() - } - - #[cfg(feature = "color")] - pub(crate) fn iter_mut(&mut self) -> impl Iterator<Item = (Option<Style>, &mut String)> { - self.pieces.iter_mut().map(|(s, c)| (*s, c)) - } - - #[cfg(not(feature = "color"))] - pub(crate) fn iter_mut(&mut self) -> impl Iterator<Item = (Option<Style>, &mut String)> { - [(None, &mut self.pieces)].into_iter() - } - - #[cfg(feature = "color")] - pub(crate) fn into_iter(self) -> impl Iterator<Item = (Option<Style>, String)> { - self.pieces.into_iter() - } - - #[cfg(not(feature = "color"))] - pub(crate) fn into_iter(self) -> impl Iterator<Item = (Option<Style>, String)> { - [(None, self.pieces)].into_iter() - } - - pub(crate) fn extend( - &mut self, - other: impl IntoIterator<Item = (impl Into<Option<Style>>, impl Into<String>)>, - ) { - for (style, content) in other { - self.stylize(style.into(), content.into()); - } - } - - #[cfg(feature = "color")] - pub(crate) fn write_colored(&self, buffer: &mut termcolor::Buffer) -> std::io::Result<()> { - use std::io::Write; - use termcolor::WriteColor; - - for (style, content) in &self.pieces { - let mut color = termcolor::ColorSpec::new(); - match style { - Some(Style::Header) => { - color.set_bold(true); - color.set_underline(true); - } - Some(Style::Literal) => { - color.set_bold(true); - } - Some(Style::Placeholder) => {} - Some(Style::Good) => { - color.set_fg(Some(termcolor::Color::Green)); - } - Some(Style::Warning) => { - color.set_fg(Some(termcolor::Color::Yellow)); - } - Some(Style::Error) => { - color.set_fg(Some(termcolor::Color::Red)); - color.set_bold(true); - } - Some(Style::Hint) => { - color.set_dimmed(true); - } - None => {} - } - - ok!(buffer.set_color(&color)); - ok!(buffer.write_all(content.as_bytes())); - ok!(buffer.reset()); - } - - Ok(()) - } -} - -impl Default for &'_ StyledStr { - fn default() -> Self { - static DEFAULT: StyledStr = StyledStr::new(); - &DEFAULT - } -} - -impl From<std::string::String> for StyledStr { - fn from(name: std::string::String) -> Self { - let mut styled = StyledStr::new(); - styled.none(name); - styled - } -} - -impl From<&'_ std::string::String> for StyledStr { - fn from(name: &'_ std::string::String) -> Self { - let mut styled = StyledStr::new(); - styled.none(name); - styled - } -} - -impl From<&'static str> for StyledStr { - fn from(name: &'static str) -> Self { - let mut styled = StyledStr::new(); - styled.none(name); - styled - } -} - -impl From<&'_ &'static str> for StyledStr { - fn from(name: &'_ &'static str) -> Self { - StyledStr::from(*name) - } -} - -impl PartialOrd for StyledStr { - fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { - Some(self.cmp(other)) - } -} - -impl Ord for StyledStr { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.iter().map(cmp_key).cmp(other.iter().map(cmp_key)) - } -} - -fn cmp_key(c: (Option<Style>, &str)) -> (Option<usize>, &str) { - let style = c.0.map(|s| s.as_usize()); - let content = c.1; - (style, content) -} - -/// Color-unaware printing. Never uses coloring. -impl std::fmt::Display for StyledStr { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - for (_, content) in self.iter() { - ok!(std::fmt::Display::fmt(content, f)); - } - - Ok(()) - } -} - -#[cfg(feature = "color")] -struct AnsiDisplay<'s> { - styled: &'s StyledStr, -} - -#[cfg(feature = "color")] -impl std::fmt::Display for AnsiDisplay<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - let mut buffer = termcolor::Buffer::ansi(); - ok!(self - .styled - .write_colored(&mut buffer) - .map_err(|_| std::fmt::Error)); - let buffer = buffer.into_inner(); - let buffer = ok!(String::from_utf8(buffer).map_err(|_| std::fmt::Error)); - ok!(std::fmt::Display::fmt(&buffer, f)); - - Ok(()) - } -} - -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub(crate) enum Style { - Header, - Literal, - Placeholder, - Good, - Warning, - Error, - Hint, -} - -impl Style { - fn as_usize(&self) -> usize { - match self { - Self::Header => 0, - Self::Literal => 1, - Self::Placeholder => 2, - Self::Good => 3, - Self::Warning => 4, - Self::Error => 5, - Self::Hint => 6, - } - } -} diff --git a/vendor/clap/src/builder/tests.rs b/vendor/clap/src/builder/tests.rs deleted file mode 100644 index 15cb8c4f4..000000000 --- a/vendor/clap/src/builder/tests.rs +++ /dev/null @@ -1,56 +0,0 @@ -use crate::Arg; -use crate::Command; - -#[test] -fn propagate_version() { - let mut cmd = Command::new("test") - .propagate_version(true) - .version("1.1") - .subcommand(Command::new("sub1")); - cmd._propagate(); - assert_eq!( - cmd.get_subcommands().next().unwrap().get_version(), - Some("1.1") - ); -} - -#[test] -fn global_setting() { - let mut cmd = Command::new("test") - .disable_version_flag(true) - .subcommand(Command::new("subcmd")); - cmd._propagate(); - assert!(cmd - .get_subcommands() - .find(|s| s.get_name() == "subcmd") - .unwrap() - .is_disable_version_flag_set()); -} - -// This test will *fail to compile* if Command is not Send + Sync -#[test] -fn app_send_sync() { - fn foo<T: Send + Sync>(_: T) {} - foo(Command::new("test")) -} - -#[test] -fn issue_2090() { - let mut cmd = Command::new("cmd") - .disable_version_flag(true) - .subcommand(Command::new("sub")); - cmd._build_self(false); - - assert!(cmd - .get_subcommands() - .next() - .unwrap() - .is_disable_version_flag_set()); -} - -// This test will *fail to compile* if Arg is not Send + Sync -#[test] -fn arg_send_sync() { - fn foo<T: Send + Sync>(_: T) {} - foo(Arg::new("test")) -} diff --git a/vendor/clap/src/builder/value_hint.rs b/vendor/clap/src/builder/value_hint.rs deleted file mode 100644 index 812d5d866..000000000 --- a/vendor/clap/src/builder/value_hint.rs +++ /dev/null @@ -1,95 +0,0 @@ -use std::str::FromStr; - -/// Provide shell with hint on how to complete an argument. -/// -/// See [Arg::value_hint][crate::Arg::value_hint] to set this on an argument. -/// -/// See the `clap_complete` crate for completion script generation. -/// -/// Overview of which hints are supported by which shell: -/// -/// | Hint | zsh | fish[^1]| -/// | ---------------------- | --- | ------- | -/// | `AnyPath` | Yes | Yes | -/// | `FilePath` | Yes | Yes | -/// | `DirPath` | Yes | Yes | -/// | `ExecutablePath` | Yes | Partial | -/// | `CommandName` | Yes | Yes | -/// | `CommandString` | Yes | Partial | -/// | `CommandWithArguments` | Yes | | -/// | `Username` | Yes | Yes | -/// | `Hostname` | Yes | Yes | -/// | `Url` | Yes | | -/// | `EmailAddress` | Yes | | -/// -/// [^1]: fish completions currently only support named arguments (e.g. -o or --opt), not -/// positional arguments. -#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] -#[non_exhaustive] -pub enum ValueHint { - /// Default value if hint is not specified. Follows shell default behavior, which is usually - /// auto-completing filenames. - Unknown, - /// None of the hints below apply. Disables shell completion for this argument. - Other, - /// Any existing path. - AnyPath, - /// Path to a file. - FilePath, - /// Path to a directory. - DirPath, - /// Path to an executable file. - ExecutablePath, - /// Name of a command, without arguments. May be relative to PATH, or full path to executable. - CommandName, - /// A single string containing a command and its arguments. - CommandString, - /// Capture the remaining arguments as a command name and arguments for that command. This is - /// common when writing shell wrappers that execute anther command, for example `sudo` or `env`. - /// - /// This hint is special, the argument must be a positional argument and have - /// [`.num_args(1..)`] and Command must use [`Command::trailing_var_arg(true)`]. The result is that the - /// command line `my_app ls -la /` will be parsed as `["ls", "-la", "/"]` and clap won't try to - /// parse the `-la` argument itself. - /// - /// [`Command::trailing_var_arg(true)`]: crate::Command::trailing_var_arg - /// [`.num_args(1..)`]: crate::Arg::num_args() - CommandWithArguments, - /// Name of a local operating system user. - Username, - /// Host name of a computer. - /// Shells usually parse `/etc/hosts` and `.ssh/known_hosts` to complete hostnames. - Hostname, - /// Complete web address. - Url, - /// Email address. - EmailAddress, -} - -impl Default for ValueHint { - fn default() -> Self { - ValueHint::Unknown - } -} - -impl FromStr for ValueHint { - type Err = String; - fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> { - Ok(match &*s.to_ascii_lowercase() { - "unknown" => ValueHint::Unknown, - "other" => ValueHint::Other, - "anypath" => ValueHint::AnyPath, - "filepath" => ValueHint::FilePath, - "dirpath" => ValueHint::DirPath, - "executablepath" => ValueHint::ExecutablePath, - "commandname" => ValueHint::CommandName, - "commandstring" => ValueHint::CommandString, - "commandwitharguments" => ValueHint::CommandWithArguments, - "username" => ValueHint::Username, - "hostname" => ValueHint::Hostname, - "url" => ValueHint::Url, - "emailaddress" => ValueHint::EmailAddress, - _ => return Err(format!("unknown ValueHint: `{}`", s)), - }) - } -} diff --git a/vendor/clap/src/builder/value_parser.rs b/vendor/clap/src/builder/value_parser.rs deleted file mode 100644 index 191e8ae76..000000000 --- a/vendor/clap/src/builder/value_parser.rs +++ /dev/null @@ -1,2435 +0,0 @@ -use std::convert::TryInto; -use std::ops::RangeBounds; - -use crate::parser::AnyValue; -use crate::parser::AnyValueId; - -/// Parse/validate argument values -/// -/// Specified with [`Arg::value_parser`][crate::Arg::value_parser]. -/// -/// `ValueParser` defines how to convert a raw argument value into a validated and typed value for -/// use within an application. -/// -/// See -/// - [`value_parser!`][crate::value_parser] for automatically selecting an implementation for a given type -/// - [`ValueParser::new`] for additional [`TypedValueParser`] that can be used -/// -/// # Example -/// -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("color") -/// .long("color") -/// .value_parser(["always", "auto", "never"]) -/// .default_value("auto") -/// ) -/// .arg( -/// clap::Arg::new("hostname") -/// .long("hostname") -/// .value_parser(clap::builder::NonEmptyStringValueParser::new()) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ) -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(clap::value_parser!(u16).range(3000..)) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut( -/// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"] -/// ).unwrap(); -/// -/// let color: &String = m.get_one("color") -/// .expect("default"); -/// assert_eq!(color, "auto"); -/// -/// let hostname: &String = m.get_one("hostname") -/// .expect("required"); -/// assert_eq!(hostname, "rust-lang.org"); -/// -/// let port: u16 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -pub struct ValueParser(ValueParserInner); - -enum ValueParserInner { - // Common enough to optimize and for possible values - Bool, - // Common enough to optimize - String, - // Common enough to optimize - OsString, - // Common enough to optimize - PathBuf, - Other(Box<dyn AnyValueParser>), -} - -impl ValueParser { - /// Custom parser for argument values - /// - /// Pre-existing [`TypedValueParser`] implementations include: - /// - `Fn(&str) -> Result<T, E>` - /// - [`EnumValueParser`] and [`PossibleValuesParser`] for static enumerated values - /// - [`BoolishValueParser`] and [`FalseyValueParser`] for alternative `bool` implementations - /// - [`RangedI64ValueParser`] and [`RangedU64ValueParser`] - /// - [`NonEmptyStringValueParser`] - /// - /// # Example - /// - /// ```rust - /// type EnvVar = (String, Option<String>); - /// fn parse_env_var(env: &str) -> Result<EnvVar, std::io::Error> { - /// if let Some((var, value)) = env.split_once('=') { - /// Ok((var.to_owned(), Some(value.to_owned()))) - /// } else { - /// Ok((env.to_owned(), None)) - /// } - /// } - /// - /// let mut cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("env") - /// .value_parser(clap::builder::ValueParser::new(parse_env_var)) - /// .required(true) - /// ); - /// - /// let m = cmd.try_get_matches_from_mut(["cmd", "key=value"]).unwrap(); - /// let port: &EnvVar = m.get_one("env") - /// .expect("required"); - /// assert_eq!(*port, ("key".into(), Some("value".into()))); - /// ``` - pub fn new<P>(other: P) -> Self - where - P: TypedValueParser, - { - Self(ValueParserInner::Other(Box::new(other))) - } - - /// [`bool`] parser for argument values - /// - /// See also: - /// - [`BoolishValueParser`] for different human readable bool representations - /// - [`FalseyValueParser`] for assuming non-false is true - /// - /// # Example - /// - /// ```rust - /// let mut cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("download") - /// .value_parser(clap::value_parser!(bool)) - /// .required(true) - /// ); - /// - /// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap(); - /// let port: bool = *m.get_one("download") - /// .expect("required"); - /// assert_eq!(port, true); - /// - /// assert!(cmd.try_get_matches_from_mut(["cmd", "forever"]).is_err()); - /// ``` - pub const fn bool() -> Self { - Self(ValueParserInner::Bool) - } - - /// [`String`] parser for argument values - /// - /// See also: - /// - [`NonEmptyStringValueParser`] - /// - /// # Example - /// - /// ```rust - /// let mut cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("port") - /// .value_parser(clap::value_parser!(String)) - /// .required(true) - /// ); - /// - /// let m = cmd.try_get_matches_from_mut(["cmd", "80"]).unwrap(); - /// let port: &String = m.get_one("port") - /// .expect("required"); - /// assert_eq!(port, "80"); - /// ``` - pub const fn string() -> Self { - Self(ValueParserInner::String) - } - - /// [`OsString`][std::ffi::OsString] parser for argument values - /// - /// # Example - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```rust")] - /// # use clap::{Command, Arg, builder::ValueParser}; - /// use std::ffi::OsString; - /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; - /// let r = Command::new("myprog") - /// .arg( - /// Arg::new("arg") - /// .required(true) - /// .value_parser(ValueParser::os_string()) - /// ) - /// .try_get_matches_from(vec![ - /// OsString::from("myprog"), - /// OsString::from_vec(vec![0xe9]) - /// ]); - /// - /// assert!(r.is_ok()); - /// let m = r.unwrap(); - /// let arg: &OsString = m.get_one("arg") - /// .expect("required"); - /// assert_eq!(arg.as_bytes(), &[0xe9]); - /// ``` - pub const fn os_string() -> Self { - Self(ValueParserInner::OsString) - } - - /// [`PathBuf`][std::path::PathBuf] parser for argument values - /// - /// # Example - /// - /// ```rust - /// # use std::path::PathBuf; - /// # use std::path::Path; - /// let mut cmd = clap::Command::new("raw") - /// .arg( - /// clap::Arg::new("output") - /// .value_parser(clap::value_parser!(PathBuf)) - /// .required(true) - /// ); - /// - /// let m = cmd.try_get_matches_from_mut(["cmd", "hello.txt"]).unwrap(); - /// let port: &PathBuf = m.get_one("output") - /// .expect("required"); - /// assert_eq!(port, Path::new("hello.txt")); - /// - /// assert!(cmd.try_get_matches_from_mut(["cmd", ""]).is_err()); - /// ``` - pub const fn path_buf() -> Self { - Self(ValueParserInner::PathBuf) - } -} - -impl ValueParser { - /// Parse into a `AnyValue` - /// - /// When `arg` is `None`, an external subcommand value is being parsed. - pub(crate) fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<AnyValue, crate::Error> { - self.any_value_parser().parse_ref(cmd, arg, value) - } - - /// Describes the content of `AnyValue` - pub fn type_id(&self) -> AnyValueId { - self.any_value_parser().type_id() - } - - /// Reflect on enumerated value properties - /// - /// Error checking should not be done with this; it is mostly targeted at user-facing - /// applications like errors and completion. - pub fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - self.any_value_parser().possible_values() - } - - fn any_value_parser(&self) -> &dyn AnyValueParser { - match &self.0 { - ValueParserInner::Bool => &BoolValueParser {}, - ValueParserInner::String => &StringValueParser {}, - ValueParserInner::OsString => &OsStringValueParser {}, - ValueParserInner::PathBuf => &PathBufValueParser {}, - ValueParserInner::Other(o) => o.as_ref(), - } - } -} - -/// Convert a [`TypedValueParser`] to [`ValueParser`] -/// -/// # Example -/// -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("hostname") -/// .long("hostname") -/// .value_parser(clap::builder::NonEmptyStringValueParser::new()) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut( -/// ["cmd", "--hostname", "rust-lang.org"] -/// ).unwrap(); -/// -/// let hostname: &String = m.get_one("hostname") -/// .expect("required"); -/// assert_eq!(hostname, "rust-lang.org"); -/// ``` -impl<P> From<P> for ValueParser -where - P: TypedValueParser + Send + Sync + 'static, -{ - fn from(p: P) -> Self { - Self::new(p) - } -} - -impl From<_AnonymousValueParser> for ValueParser { - fn from(p: _AnonymousValueParser) -> Self { - p.0 - } -} - -/// Create an `i64` [`ValueParser`] from a `N..M` range -/// -/// See [`RangedI64ValueParser`] for more control over the output type. -/// -/// See also [`RangedU64ValueParser`] -/// -/// # Examples -/// -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(3000..4000) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap(); -/// let port: i64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -impl From<std::ops::Range<i64>> for ValueParser { - fn from(value: std::ops::Range<i64>) -> Self { - let inner = RangedI64ValueParser::<i64>::new().range(value.start..value.end); - Self::from(inner) - } -} - -/// Create an `i64` [`ValueParser`] from a `N..=M` range -/// -/// See [`RangedI64ValueParser`] for more control over the output type. -/// -/// See also [`RangedU64ValueParser`] -/// -/// # Examples -/// -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(3000..=4000) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap(); -/// let port: i64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -impl From<std::ops::RangeInclusive<i64>> for ValueParser { - fn from(value: std::ops::RangeInclusive<i64>) -> Self { - let inner = RangedI64ValueParser::<i64>::new().range(value.start()..=value.end()); - Self::from(inner) - } -} - -/// Create an `i64` [`ValueParser`] from a `N..` range -/// -/// See [`RangedI64ValueParser`] for more control over the output type. -/// -/// See also [`RangedU64ValueParser`] -/// -/// # Examples -/// -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(3000..) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap(); -/// let port: i64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -impl From<std::ops::RangeFrom<i64>> for ValueParser { - fn from(value: std::ops::RangeFrom<i64>) -> Self { - let inner = RangedI64ValueParser::<i64>::new().range(value.start..); - Self::from(inner) - } -} - -/// Create an `i64` [`ValueParser`] from a `..M` range -/// -/// See [`RangedI64ValueParser`] for more control over the output type. -/// -/// See also [`RangedU64ValueParser`] -/// -/// # Examples -/// -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(..3000) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "80"]).unwrap(); -/// let port: i64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 80); -/// ``` -impl From<std::ops::RangeTo<i64>> for ValueParser { - fn from(value: std::ops::RangeTo<i64>) -> Self { - let inner = RangedI64ValueParser::<i64>::new().range(..value.end); - Self::from(inner) - } -} - -/// Create an `i64` [`ValueParser`] from a `..=M` range -/// -/// See [`RangedI64ValueParser`] for more control over the output type. -/// -/// See also [`RangedU64ValueParser`] -/// -/// # Examples -/// -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(..=3000) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "80"]).unwrap(); -/// let port: i64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 80); -/// ``` -impl From<std::ops::RangeToInclusive<i64>> for ValueParser { - fn from(value: std::ops::RangeToInclusive<i64>) -> Self { - let inner = RangedI64ValueParser::<i64>::new().range(..=value.end); - Self::from(inner) - } -} - -/// Create an `i64` [`ValueParser`] from a `..` range -/// -/// See [`RangedI64ValueParser`] for more control over the output type. -/// -/// See also [`RangedU64ValueParser`] -/// -/// # Examples -/// -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(..) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap(); -/// let port: i64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -impl From<std::ops::RangeFull> for ValueParser { - fn from(value: std::ops::RangeFull) -> Self { - let inner = RangedI64ValueParser::<i64>::new().range(value); - Self::from(inner) - } -} - -/// Create a [`ValueParser`] with [`PossibleValuesParser`] -/// -/// See [`PossibleValuesParser`] for more flexibility in creating the -/// [`PossibleValue`][crate::builder::PossibleValue]s. -/// -/// # Examples -/// -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("color") -/// .long("color") -/// .value_parser(["always", "auto", "never"]) -/// .default_value("auto") -/// ); -/// -/// let m = cmd.try_get_matches_from_mut( -/// ["cmd", "--color", "never"] -/// ).unwrap(); -/// -/// let color: &String = m.get_one("color") -/// .expect("default"); -/// assert_eq!(color, "never"); -/// ``` -impl<P, const C: usize> From<[P; C]> for ValueParser -where - P: Into<super::PossibleValue>, -{ - fn from(values: [P; C]) -> Self { - let inner = PossibleValuesParser::from(values); - Self::from(inner) - } -} - -/// Create a [`ValueParser`] with [`PossibleValuesParser`] -/// -/// See [`PossibleValuesParser`] for more flexibility in creating the -/// [`PossibleValue`][crate::builder::PossibleValue]s. -/// -/// # Examples -/// -/// ```rust -/// let possible = vec!["always", "auto", "never"]; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("color") -/// .long("color") -/// .value_parser(possible) -/// .default_value("auto") -/// ); -/// -/// let m = cmd.try_get_matches_from_mut( -/// ["cmd", "--color", "never"] -/// ).unwrap(); -/// -/// let color: &String = m.get_one("color") -/// .expect("default"); -/// assert_eq!(color, "never"); -/// ``` -impl<P> From<Vec<P>> for ValueParser -where - P: Into<super::PossibleValue>, -{ - fn from(values: Vec<P>) -> Self { - let inner = PossibleValuesParser::from(values); - Self::from(inner) - } -} - -impl std::fmt::Debug for ValueParser { - fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { - match &self.0 { - ValueParserInner::Bool => f.debug_struct("ValueParser::bool").finish(), - ValueParserInner::String => f.debug_struct("ValueParser::string").finish(), - ValueParserInner::OsString => f.debug_struct("ValueParser::os_string").finish(), - ValueParserInner::PathBuf => f.debug_struct("ValueParser::path_buf").finish(), - ValueParserInner::Other(o) => write!(f, "ValueParser::other({:?})", o.type_id()), - } - } -} - -impl Clone for ValueParser { - fn clone(&self) -> Self { - Self(match &self.0 { - ValueParserInner::Bool => ValueParserInner::Bool, - ValueParserInner::String => ValueParserInner::String, - ValueParserInner::OsString => ValueParserInner::OsString, - ValueParserInner::PathBuf => ValueParserInner::PathBuf, - ValueParserInner::Other(o) => ValueParserInner::Other(o.clone_any()), - }) - } -} - -/// A type-erased wrapper for [`TypedValueParser`]. -trait AnyValueParser: Send + Sync + 'static { - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<AnyValue, crate::Error>; - - fn parse( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<AnyValue, crate::Error>; - - /// Describes the content of `AnyValue` - fn type_id(&self) -> AnyValueId; - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>>; - - fn clone_any(&self) -> Box<dyn AnyValueParser>; -} - -impl<T, P> AnyValueParser for P -where - T: std::any::Any + Clone + Send + Sync + 'static, - P: TypedValueParser<Value = T>, -{ - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<AnyValue, crate::Error> { - let value = ok!(TypedValueParser::parse_ref(self, cmd, arg, value)); - Ok(AnyValue::new(value)) - } - - fn parse( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<AnyValue, crate::Error> { - let value = ok!(TypedValueParser::parse(self, cmd, arg, value)); - Ok(AnyValue::new(value)) - } - - fn type_id(&self) -> AnyValueId { - AnyValueId::of::<T>() - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - P::possible_values(self) - } - - fn clone_any(&self) -> Box<dyn AnyValueParser> { - Box::new(self.clone()) - } -} - -/// Parse/validate argument values -/// -/// As alternatives to implementing `TypedValueParser`, -/// - Use `Fn(&str) -> Result<T, E>` which implements `TypedValueParser` -/// - [`TypedValueParser::map`] or [`TypedValueParser::try_map`] to adapt an existing `TypedValueParser` -/// -/// See `ValueParserFactory` to register `TypedValueParser::Value` with -/// [`value_parser!`][crate::value_parser]. -/// -/// # Example -/// -#[cfg_attr(not(feature = "error-context"), doc = " ```ignore")] -#[cfg_attr(feature = "error-context", doc = " ```")] -/// # use clap::error::ErrorKind; -/// # use clap::error::ContextKind; -/// # use clap::error::ContextValue; -/// #[derive(Clone)] -/// struct Custom(u32); -/// -/// #[derive(Clone)] -/// struct CustomValueParser; -/// -/// impl clap::builder::TypedValueParser for CustomValueParser { -/// type Value = Custom; -/// -/// fn parse_ref( -/// &self, -/// cmd: &clap::Command, -/// arg: Option<&clap::Arg>, -/// value: &std::ffi::OsStr, -/// ) -> Result<Self::Value, clap::Error> { -/// let inner = clap::value_parser!(u32); -/// let val = inner.parse_ref(cmd, arg, value)?; -/// -/// const INVALID_VALUE: u32 = 10; -/// if val == INVALID_VALUE { -/// let mut err = clap::Error::new(ErrorKind::ValueValidation) -/// .with_cmd(cmd); -/// if let Some(arg) = arg { -/// err.insert(ContextKind::InvalidArg, ContextValue::String(arg.to_string())); -/// } -/// err.insert(ContextKind::InvalidValue, ContextValue::String(INVALID_VALUE.to_string())); -/// return Err(err); -/// } -/// -/// Ok(Custom(val)) -/// } -/// } -/// ``` -pub trait TypedValueParser: Clone + Send + Sync + 'static { - /// Argument's value type - type Value: Send + Sync + Clone; - - /// Parse the argument value - /// - /// When `arg` is `None`, an external subcommand value is being parsed. - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error>; - - /// Parse the argument value - /// - /// When `arg` is `None`, an external subcommand value is being parsed. - fn parse( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<Self::Value, crate::Error> { - self.parse_ref(cmd, arg, &value) - } - - /// Reflect on enumerated value properties - /// - /// Error checking should not be done with this; it is mostly targeted at user-facing - /// applications like errors and completion. - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - None - } - - /// Adapt a `TypedValueParser` from one value to another - /// - /// # Example - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// # use clap::builder::TypedValueParser as _; - /// # use clap::builder::BoolishValueParser; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::SetTrue) - /// .value_parser( - /// BoolishValueParser::new() - /// .map(|b| -> usize { - /// if b { 10 } else { 5 } - /// }) - /// ) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_one::<usize>("flag").copied(), - /// Some(10) - /// ); - /// - /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_one::<usize>("flag").copied(), - /// Some(5) - /// ); - /// ``` - fn map<T, F>(self, func: F) -> MapValueParser<Self, F> - where - T: Send + Sync + Clone, - F: Fn(Self::Value) -> T + Clone, - { - MapValueParser::new(self, func) - } - - /// Adapt a `TypedValueParser` from one value to another - /// - /// # Example - /// - /// ```rust - /// # use std::ffi::OsString; - /// # use std::ffi::OsStr; - /// # use std::path::PathBuf; - /// # use std::path::Path; - /// # use clap::Command; - /// # use clap::Arg; - /// # use clap::builder::TypedValueParser as _; - /// # use clap::builder::OsStringValueParser; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .value_parser( - /// OsStringValueParser::new() - /// .try_map(verify_ext) - /// ) - /// ); - /// - /// fn verify_ext(os: OsString) -> Result<PathBuf, &'static str> { - /// let path = PathBuf::from(os); - /// if path.extension() != Some(OsStr::new("rs")) { - /// return Err("only Rust files are supported"); - /// } - /// Ok(path) - /// } - /// - /// let error = cmd.clone().try_get_matches_from(["mycmd", "--flag", "foo.txt"]).unwrap_err(); - /// error.print(); - /// - /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "foo.rs"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_one::<PathBuf>("flag").map(|s| s.as_path()), - /// Some(Path::new("foo.rs")) - /// ); - /// ``` - fn try_map<T, E, F>(self, func: F) -> TryMapValueParser<Self, F> - where - F: Fn(Self::Value) -> Result<T, E> + Clone + Send + Sync + 'static, - T: Send + Sync + Clone, - E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, - { - TryMapValueParser::new(self, func) - } -} - -impl<F, T, E> TypedValueParser for F -where - F: Fn(&str) -> Result<T, E> + Clone + Send + Sync + 'static, - E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, - T: Send + Sync + Clone, -{ - type Value = T; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(value.to_str().ok_or_else(|| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - let value = ok!((self)(value).map_err(|e| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation(arg, value.to_owned(), e.into()).with_cmd(cmd) - })); - Ok(value) - } -} - -/// Implementation for [`ValueParser::string`] -/// -/// Useful for composing new [`TypedValueParser`]s -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct StringValueParser {} - -impl StringValueParser { - /// Implementation for [`ValueParser::string`] - pub fn new() -> Self { - Self {} - } -} - -impl TypedValueParser for StringValueParser { - type Value = String; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - TypedValueParser::parse(self, cmd, arg, value.to_owned()) - } - - fn parse( - &self, - cmd: &crate::Command, - _arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(value.into_string().map_err(|_| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - Ok(value) - } -} - -impl Default for StringValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Implementation for [`ValueParser::os_string`] -/// -/// Useful for composing new [`TypedValueParser`]s -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct OsStringValueParser {} - -impl OsStringValueParser { - /// Implementation for [`ValueParser::os_string`] - pub fn new() -> Self { - Self {} - } -} - -impl TypedValueParser for OsStringValueParser { - type Value = std::ffi::OsString; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - TypedValueParser::parse(self, cmd, arg, value.to_owned()) - } - - fn parse( - &self, - _cmd: &crate::Command, - _arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<Self::Value, crate::Error> { - Ok(value) - } -} - -impl Default for OsStringValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Implementation for [`ValueParser::path_buf`] -/// -/// Useful for composing new [`TypedValueParser`]s -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct PathBufValueParser {} - -impl PathBufValueParser { - /// Implementation for [`ValueParser::path_buf`] - pub fn new() -> Self { - Self {} - } -} - -impl TypedValueParser for PathBufValueParser { - type Value = std::path::PathBuf; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - TypedValueParser::parse(self, cmd, arg, value.to_owned()) - } - - fn parse( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<Self::Value, crate::Error> { - if value.is_empty() { - return Err(crate::Error::empty_value( - cmd, - &[], - arg.map(ToString::to_string) - .unwrap_or_else(|| "...".to_owned()), - )); - } - Ok(Self::Value::from(value)) - } -} - -impl Default for PathBufValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Parse an [`ValueEnum`][crate::ValueEnum] value. -/// -/// See also: -/// - [`PossibleValuesParser`] -/// -/// # Example -/// -/// ```rust -/// # use std::ffi::OsStr; -/// # use clap::ColorChoice; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// -/// // Usage -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("color") -/// .value_parser(clap::builder::EnumValueParser::<ColorChoice>::new()) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "always"]).unwrap(); -/// let port: ColorChoice = *m.get_one("color") -/// .expect("required"); -/// assert_eq!(port, ColorChoice::Always); -/// -/// // Semantics -/// let value_parser = clap::builder::EnumValueParser::<ColorChoice>::new(); -/// // or -/// let value_parser = clap::value_parser!(ColorChoice); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err()); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("always")).unwrap(), ColorChoice::Always); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("auto")).unwrap(), ColorChoice::Auto); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("never")).unwrap(), ColorChoice::Never); -/// ``` -#[derive(Clone, Debug)] -pub struct EnumValueParser<E: crate::ValueEnum + Clone + Send + Sync + 'static>( - std::marker::PhantomData<E>, -); - -impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> EnumValueParser<E> { - /// Parse an [`ValueEnum`][crate::ValueEnum] - pub fn new() -> Self { - let phantom: std::marker::PhantomData<E> = Default::default(); - Self(phantom) - } -} - -impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> TypedValueParser for EnumValueParser<E> { - type Value = E; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false); - let possible_vals = || { - E::value_variants() - .iter() - .filter_map(|v| v.to_possible_value()) - .filter(|v| !v.is_hide_set()) - .map(|v| v.get_name().to_owned()) - .collect::<Vec<_>>() - }; - - let value = ok!(value.to_str().ok_or_else(|| { - crate::Error::invalid_value( - cmd, - value.to_string_lossy().into_owned(), - &possible_vals(), - arg.map(ToString::to_string) - .unwrap_or_else(|| "...".to_owned()), - ) - })); - let value = ok!(E::value_variants() - .iter() - .find(|v| { - v.to_possible_value() - .expect("ValueEnum::value_variants contains only values with a corresponding ValueEnum::to_possible_value") - .matches(value, ignore_case) - }) - .ok_or_else(|| { - crate::Error::invalid_value( - cmd, - value.to_owned(), - &possible_vals(), - arg.map(ToString::to_string) - .unwrap_or_else(|| "...".to_owned()), - ) - })) - .clone(); - Ok(value) - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - Some(Box::new( - E::value_variants() - .iter() - .filter_map(|v| v.to_possible_value()), - )) - } -} - -impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> Default for EnumValueParser<E> { - fn default() -> Self { - Self::new() - } -} - -/// Verify the value is from an enumerated set of [`PossibleValue`][crate::builder::PossibleValue]. -/// -/// See also: -/// - [`EnumValueParser`] for directly supporting [`ValueEnum`][crate::ValueEnum] types -/// - [`TypedValueParser::map`] for adapting values to a more specialized type, like an external -/// enums that can't implement [`ValueEnum`][crate::ValueEnum] -/// -/// # Example -/// -/// Usage: -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("color") -/// .value_parser(clap::builder::PossibleValuesParser::new(["always", "auto", "never"])) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "always"]).unwrap(); -/// let port: &String = m.get_one("color") -/// .expect("required"); -/// assert_eq!(port, "always"); -/// ``` -/// -/// Semantics: -/// ```rust -/// # use std::ffi::OsStr; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// let value_parser = clap::builder::PossibleValuesParser::new(["always", "auto", "never"]); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err()); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("always")).unwrap(), "always"); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("auto")).unwrap(), "auto"); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("never")).unwrap(), "never"); -/// ``` -#[derive(Clone, Debug)] -pub struct PossibleValuesParser(Vec<super::PossibleValue>); - -impl PossibleValuesParser { - /// Verify the value is from an enumerated set pf [`PossibleValue`][crate::builder::PossibleValue]. - pub fn new(values: impl Into<PossibleValuesParser>) -> Self { - values.into() - } -} - -impl TypedValueParser for PossibleValuesParser { - type Value = String; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - TypedValueParser::parse(self, cmd, arg, value.to_owned()) - } - - fn parse( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<String, crate::Error> { - let value = ok!(value.into_string().map_err(|_| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - - let ignore_case = arg.map(|a| a.is_ignore_case_set()).unwrap_or(false); - if self.0.iter().any(|v| v.matches(&value, ignore_case)) { - Ok(value) - } else { - let possible_vals = self - .0 - .iter() - .filter(|v| !v.is_hide_set()) - .map(|v| v.get_name().to_owned()) - .collect::<Vec<_>>(); - - Err(crate::Error::invalid_value( - cmd, - value, - &possible_vals, - arg.map(ToString::to_string) - .unwrap_or_else(|| "...".to_owned()), - )) - } - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - Some(Box::new(self.0.iter().cloned())) - } -} - -impl<I, T> From<I> for PossibleValuesParser -where - I: IntoIterator<Item = T>, - T: Into<super::PossibleValue>, -{ - fn from(values: I) -> Self { - Self(values.into_iter().map(|t| t.into()).collect()) - } -} - -/// Parse number that fall within a range of values -/// -/// **NOTE:** To capture negative values, you will also need to set -/// [`Arg::allow_negative_numbers`][crate::Arg::allow_negative_numbers] or -/// [`Arg::allow_hyphen_values`][crate::Arg::allow_hyphen_values]. -/// -/// # Example -/// -/// Usage: -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(clap::value_parser!(u16).range(3000..)) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap(); -/// let port: u16 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -/// -/// Semantics: -/// ```rust -/// # use std::ffi::OsStr; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// let value_parser = clap::builder::RangedI64ValueParser::<i32>::new().range(-1..200); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-200")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("300")).is_err()); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("-1")).unwrap(), -1); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), 0); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("50")).unwrap(), 50); -/// ``` -#[derive(Copy, Clone, Debug)] -pub struct RangedI64ValueParser<T: std::convert::TryFrom<i64> + Clone + Send + Sync = i64> { - bounds: (std::ops::Bound<i64>, std::ops::Bound<i64>), - target: std::marker::PhantomData<T>, -} - -impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync> RangedI64ValueParser<T> { - /// Select full range of `i64` - pub fn new() -> Self { - Self::from(..) - } - - /// Narrow the supported range - pub fn range<B: RangeBounds<i64>>(mut self, range: B) -> Self { - // Consideration: when the user does `value_parser!(u8).range()` - // - Avoid programming mistakes by accidentally expanding the range - // - Make it convenient to limit the range like with `..10` - let start = match range.start_bound() { - l @ std::ops::Bound::Included(i) => { - debug_assert!( - self.bounds.contains(i), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - l @ std::ops::Bound::Excluded(i) => { - debug_assert!( - self.bounds.contains(&i.saturating_add(1)), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - std::ops::Bound::Unbounded => self.bounds.start_bound().cloned(), - }; - let end = match range.end_bound() { - l @ std::ops::Bound::Included(i) => { - debug_assert!( - self.bounds.contains(i), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - l @ std::ops::Bound::Excluded(i) => { - debug_assert!( - self.bounds.contains(&i.saturating_sub(1)), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - std::ops::Bound::Unbounded => self.bounds.end_bound().cloned(), - }; - self.bounds = (start, end); - self - } - - fn format_bounds(&self) -> String { - let mut result = match self.bounds.0 { - std::ops::Bound::Included(i) => i.to_string(), - std::ops::Bound::Excluded(i) => i.saturating_add(1).to_string(), - std::ops::Bound::Unbounded => i64::MIN.to_string(), - }; - result.push_str(".."); - match self.bounds.1 { - std::ops::Bound::Included(i) => { - result.push('='); - result.push_str(&i.to_string()); - } - std::ops::Bound::Excluded(i) => { - result.push_str(&i.to_string()); - } - std::ops::Bound::Unbounded => { - result.push_str(&i64::MAX.to_string()); - } - } - result - } -} - -impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync + 'static> TypedValueParser - for RangedI64ValueParser<T> -where - <T as std::convert::TryFrom<i64>>::Error: Send + Sync + 'static + std::error::Error + ToString, -{ - type Value = T; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - raw_value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(raw_value.to_str().ok_or_else(|| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - let value = ok!(value.parse::<i64>().map_err(|err| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation( - arg, - raw_value.to_string_lossy().into_owned(), - err.into(), - ) - .with_cmd(cmd) - })); - if !self.bounds.contains(&value) { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - return Err(crate::Error::value_validation( - arg, - raw_value.to_string_lossy().into_owned(), - format!("{} is not in {}", value, self.format_bounds()).into(), - ) - .with_cmd(cmd)); - } - - let value: Result<Self::Value, _> = value.try_into(); - let value = ok!(value.map_err(|err| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation( - arg, - raw_value.to_string_lossy().into_owned(), - err.into(), - ) - .with_cmd(cmd) - })); - - Ok(value) - } -} - -impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync, B: RangeBounds<i64>> From<B> - for RangedI64ValueParser<T> -{ - fn from(range: B) -> Self { - Self { - bounds: (range.start_bound().cloned(), range.end_bound().cloned()), - target: Default::default(), - } - } -} - -impl<T: std::convert::TryFrom<i64> + Clone + Send + Sync> Default for RangedI64ValueParser<T> { - fn default() -> Self { - Self::new() - } -} - -/// Parse number that fall within a range of values -/// -/// # Example -/// -/// Usage: -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("port") -/// .long("port") -/// .value_parser(clap::value_parser!(u64).range(3000..)) -/// .action(clap::ArgAction::Set) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "--port", "3001"]).unwrap(); -/// let port: u64 = *m.get_one("port") -/// .expect("required"); -/// assert_eq!(port, 3001); -/// ``` -/// -/// Semantics: -/// ```rust -/// # use std::ffi::OsStr; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// let value_parser = clap::builder::RangedU64ValueParser::<u32>::new().range(0..200); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-200")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("300")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("-1")).is_err()); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), 0); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("50")).unwrap(), 50); -/// ``` -#[derive(Copy, Clone, Debug)] -pub struct RangedU64ValueParser<T: std::convert::TryFrom<u64> = u64> { - bounds: (std::ops::Bound<u64>, std::ops::Bound<u64>), - target: std::marker::PhantomData<T>, -} - -impl<T: std::convert::TryFrom<u64>> RangedU64ValueParser<T> { - /// Select full range of `u64` - pub fn new() -> Self { - Self::from(..) - } - - /// Narrow the supported range - pub fn range<B: RangeBounds<u64>>(mut self, range: B) -> Self { - // Consideration: when the user does `value_parser!(u8).range()` - // - Avoid programming mistakes by accidentally expanding the range - // - Make it convenient to limit the range like with `..10` - let start = match range.start_bound() { - l @ std::ops::Bound::Included(i) => { - debug_assert!( - self.bounds.contains(i), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - l @ std::ops::Bound::Excluded(i) => { - debug_assert!( - self.bounds.contains(&i.saturating_add(1)), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - std::ops::Bound::Unbounded => self.bounds.start_bound().cloned(), - }; - let end = match range.end_bound() { - l @ std::ops::Bound::Included(i) => { - debug_assert!( - self.bounds.contains(i), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - l @ std::ops::Bound::Excluded(i) => { - debug_assert!( - self.bounds.contains(&i.saturating_sub(1)), - "{} must be in {:?}", - i, - self.bounds - ); - l.cloned() - } - std::ops::Bound::Unbounded => self.bounds.end_bound().cloned(), - }; - self.bounds = (start, end); - self - } - - fn format_bounds(&self) -> String { - let mut result = match self.bounds.0 { - std::ops::Bound::Included(i) => i.to_string(), - std::ops::Bound::Excluded(i) => i.saturating_add(1).to_string(), - std::ops::Bound::Unbounded => u64::MIN.to_string(), - }; - result.push_str(".."); - match self.bounds.1 { - std::ops::Bound::Included(i) => { - result.push('='); - result.push_str(&i.to_string()); - } - std::ops::Bound::Excluded(i) => { - result.push_str(&i.to_string()); - } - std::ops::Bound::Unbounded => { - result.push_str(&u64::MAX.to_string()); - } - } - result - } -} - -impl<T: std::convert::TryFrom<u64> + Clone + Send + Sync + 'static> TypedValueParser - for RangedU64ValueParser<T> -where - <T as std::convert::TryFrom<u64>>::Error: Send + Sync + 'static + std::error::Error + ToString, -{ - type Value = T; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - raw_value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(raw_value.to_str().ok_or_else(|| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - let value = ok!(value.parse::<u64>().map_err(|err| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation( - arg, - raw_value.to_string_lossy().into_owned(), - err.into(), - ) - .with_cmd(cmd) - })); - if !self.bounds.contains(&value) { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - return Err(crate::Error::value_validation( - arg, - raw_value.to_string_lossy().into_owned(), - format!("{} is not in {}", value, self.format_bounds()).into(), - ) - .with_cmd(cmd)); - } - - let value: Result<Self::Value, _> = value.try_into(); - let value = ok!(value.map_err(|err| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation( - arg, - raw_value.to_string_lossy().into_owned(), - err.into(), - ) - .with_cmd(cmd) - })); - - Ok(value) - } -} - -impl<T: std::convert::TryFrom<u64>, B: RangeBounds<u64>> From<B> for RangedU64ValueParser<T> { - fn from(range: B) -> Self { - Self { - bounds: (range.start_bound().cloned(), range.end_bound().cloned()), - target: Default::default(), - } - } -} - -impl<T: std::convert::TryFrom<u64>> Default for RangedU64ValueParser<T> { - fn default() -> Self { - Self::new() - } -} - -/// Implementation for [`ValueParser::bool`] -/// -/// Useful for composing new [`TypedValueParser`]s -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct BoolValueParser {} - -impl BoolValueParser { - /// Implementation for [`ValueParser::bool`] - pub fn new() -> Self { - Self {} - } - - fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> { - ["true", "false"] - .iter() - .copied() - .map(crate::builder::PossibleValue::new) - } -} - -impl TypedValueParser for BoolValueParser { - type Value = bool; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = if value == std::ffi::OsStr::new("true") { - true - } else if value == std::ffi::OsStr::new("false") { - false - } else { - // Intentionally showing hidden as we hide all of them - let possible_vals = Self::possible_values() - .map(|v| v.get_name().to_owned()) - .collect::<Vec<_>>(); - - return Err(crate::Error::invalid_value( - cmd, - value.to_string_lossy().into_owned(), - &possible_vals, - arg.map(ToString::to_string) - .unwrap_or_else(|| "...".to_owned()), - )); - }; - Ok(value) - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - Some(Box::new(Self::possible_values())) - } -} - -impl Default for BoolValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Parse false-like string values, everything else is `true` -/// -/// See also: -/// - [`ValueParser::bool`] for assuming non-false is true -/// - [`BoolishValueParser`] for different human readable bool representations -/// -/// # Example -/// -/// Usage: -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("append") -/// .value_parser(clap::builder::FalseyValueParser::new()) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap(); -/// let port: bool = *m.get_one("append") -/// .expect("required"); -/// assert_eq!(port, true); -/// ``` -/// -/// Semantics: -/// ```rust -/// # use std::ffi::OsStr; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// let value_parser = clap::builder::FalseyValueParser::new(); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).unwrap(), true); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("100")).unwrap(), true); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("false")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("No")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oFF")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), false); -/// ``` -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct FalseyValueParser {} - -impl FalseyValueParser { - /// Parse false-like string values, everything else is `true` - pub fn new() -> Self { - Self {} - } - - fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> { - crate::util::TRUE_LITERALS - .iter() - .chain(crate::util::FALSE_LITERALS.iter()) - .copied() - .map(|l| crate::builder::PossibleValue::new(l).hide(l != "true" && l != "false")) - } -} - -impl TypedValueParser for FalseyValueParser { - type Value = bool; - - fn parse_ref( - &self, - cmd: &crate::Command, - _arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(value.to_str().ok_or_else(|| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - let value = if value.is_empty() { - false - } else { - crate::util::str_to_bool(value).unwrap_or(true) - }; - Ok(value) - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - Some(Box::new(Self::possible_values())) - } -} - -impl Default for FalseyValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Parse bool-like string values, everything else is `true` -/// -/// See also: -/// - [`ValueParser::bool`] for different human readable bool representations -/// - [`FalseyValueParser`] for assuming non-false is true -/// -/// # Example -/// -/// Usage: -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("append") -/// .value_parser(clap::builder::BoolishValueParser::new()) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap(); -/// let port: bool = *m.get_one("append") -/// .expect("required"); -/// assert_eq!(port, true); -/// ``` -/// -/// Semantics: -/// ```rust -/// # use std::ffi::OsStr; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// let value_parser = clap::builder::BoolishValueParser::new(); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err()); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("100")).is_err()); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("true")).unwrap(), true); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("Yes")).unwrap(), true); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oN")).unwrap(), true); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("1")).unwrap(), true); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("false")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("No")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("oFF")).unwrap(), false); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("0")).unwrap(), false); -/// ``` -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct BoolishValueParser {} - -impl BoolishValueParser { - /// Parse bool-like string values, everything else is `true` - pub fn new() -> Self { - Self {} - } - - fn possible_values() -> impl Iterator<Item = crate::builder::PossibleValue> { - crate::util::TRUE_LITERALS - .iter() - .chain(crate::util::FALSE_LITERALS.iter()) - .copied() - .map(|l| crate::builder::PossibleValue::new(l).hide(l != "true" && l != "false")) - } -} - -impl TypedValueParser for BoolishValueParser { - type Value = bool; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(value.to_str().ok_or_else(|| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - let value = ok!(crate::util::str_to_bool(value).ok_or_else(|| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation(arg, value.to_owned(), "value was not a boolean".into()) - .with_cmd(cmd) - })); - Ok(value) - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - Some(Box::new(Self::possible_values())) - } -} - -impl Default for BoolishValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Parse non-empty string values -/// -/// See also: -/// - [`ValueParser::string`] -/// -/// # Example -/// -/// Usage: -/// ```rust -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("append") -/// .value_parser(clap::builder::NonEmptyStringValueParser::new()) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "true"]).unwrap(); -/// let port: &String = m.get_one("append") -/// .expect("required"); -/// assert_eq!(port, "true"); -/// ``` -/// -/// Semantics: -/// ```rust -/// # use std::ffi::OsStr; -/// # use clap::builder::TypedValueParser; -/// # let cmd = clap::Command::new("test"); -/// # let arg = None; -/// let value_parser = clap::builder::NonEmptyStringValueParser::new(); -/// assert_eq!(value_parser.parse_ref(&cmd, arg, OsStr::new("random")).unwrap(), "random"); -/// assert!(value_parser.parse_ref(&cmd, arg, OsStr::new("")).is_err()); -/// ``` -#[derive(Copy, Clone, Debug)] -#[non_exhaustive] -pub struct NonEmptyStringValueParser {} - -impl NonEmptyStringValueParser { - /// Parse non-empty string values - pub fn new() -> Self { - Self {} - } -} - -impl TypedValueParser for NonEmptyStringValueParser { - type Value = String; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - if value.is_empty() { - return Err(crate::Error::empty_value( - cmd, - &[], - arg.map(ToString::to_string) - .unwrap_or_else(|| "...".to_owned()), - )); - } - let value = ok!(value.to_str().ok_or_else(|| { - crate::Error::invalid_utf8( - cmd, - crate::output::Usage::new(cmd).create_usage_with_title(&[]), - ) - })); - Ok(value.to_owned()) - } -} - -impl Default for NonEmptyStringValueParser { - fn default() -> Self { - Self::new() - } -} - -/// Adapt a `TypedValueParser` from one value to another -/// -/// See [`TypedValueParser::map`] -#[derive(Clone, Debug)] -pub struct MapValueParser<P, F> { - parser: P, - func: F, -} - -impl<P, F, T> MapValueParser<P, F> -where - P: TypedValueParser, - P::Value: Send + Sync + Clone, - F: Fn(P::Value) -> T + Clone, - T: Send + Sync + Clone, -{ - fn new(parser: P, func: F) -> Self { - Self { parser, func } - } -} - -impl<P, F, T> TypedValueParser for MapValueParser<P, F> -where - P: TypedValueParser, - P::Value: Send + Sync + Clone, - F: Fn(P::Value) -> T + Clone + Send + Sync + 'static, - T: Send + Sync + Clone, -{ - type Value = T; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(self.parser.parse_ref(cmd, arg, value)); - let value = (self.func)(value); - Ok(value) - } - - fn parse( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: std::ffi::OsString, - ) -> Result<Self::Value, crate::Error> { - let value = ok!(self.parser.parse(cmd, arg, value)); - let value = (self.func)(value); - Ok(value) - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - self.parser.possible_values() - } -} - -/// Adapt a `TypedValueParser` from one value to another -/// -/// See [`TypedValueParser::try_map`] -#[derive(Clone, Debug)] -pub struct TryMapValueParser<P, F> { - parser: P, - func: F, -} - -impl<P, F, T, E> TryMapValueParser<P, F> -where - P: TypedValueParser, - P::Value: Send + Sync + Clone, - F: Fn(P::Value) -> Result<T, E> + Clone + Send + Sync + 'static, - T: Send + Sync + Clone, - E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, -{ - fn new(parser: P, func: F) -> Self { - Self { parser, func } - } -} - -impl<P, F, T, E> TypedValueParser for TryMapValueParser<P, F> -where - P: TypedValueParser, - P::Value: Send + Sync + Clone, - F: Fn(P::Value) -> Result<T, E> + Clone + Send + Sync + 'static, - T: Send + Sync + Clone, - E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, -{ - type Value = T; - - fn parse_ref( - &self, - cmd: &crate::Command, - arg: Option<&crate::Arg>, - value: &std::ffi::OsStr, - ) -> Result<Self::Value, crate::Error> { - let mid_value = ok!(self.parser.parse_ref(cmd, arg, value)); - let value = ok!((self.func)(mid_value).map_err(|e| { - let arg = arg - .map(|a| a.to_string()) - .unwrap_or_else(|| "...".to_owned()); - crate::Error::value_validation(arg, value.to_string_lossy().into_owned(), e.into()) - .with_cmd(cmd) - })); - Ok(value) - } - - fn possible_values( - &self, - ) -> Option<Box<dyn Iterator<Item = crate::builder::PossibleValue> + '_>> { - self.parser.possible_values() - } -} - -/// Register a type with [value_parser!][crate::value_parser!] -/// -/// # Example -/// -/// ```rust -/// #[derive(Copy, Clone, Debug)] -/// pub struct Custom(u32); -/// -/// impl clap::builder::ValueParserFactory for Custom { -/// type Parser = CustomValueParser; -/// fn value_parser() -> Self::Parser { -/// CustomValueParser -/// } -/// } -/// -/// #[derive(Clone, Debug)] -/// pub struct CustomValueParser; -/// impl clap::builder::TypedValueParser for CustomValueParser { -/// type Value = Custom; -/// -/// fn parse_ref( -/// &self, -/// cmd: &clap::Command, -/// arg: Option<&clap::Arg>, -/// value: &std::ffi::OsStr, -/// ) -> Result<Self::Value, clap::Error> { -/// let inner = clap::value_parser!(u32); -/// let val = inner.parse_ref(cmd, arg, value)?; -/// Ok(Custom(val)) -/// } -/// } -/// -/// let parser: CustomValueParser = clap::value_parser!(Custom); -/// ``` -pub trait ValueParserFactory { - /// Generated parser, usually [`ValueParser`]. - /// - /// It should at least be a type that supports `Into<ValueParser>`. A non-`ValueParser` type - /// allows the caller to do further initialization on the parser. - type Parser; - - /// Create the specified [`Self::Parser`] - fn value_parser() -> Self::Parser; -} -impl ValueParserFactory for String { - type Parser = ValueParser; - fn value_parser() -> Self::Parser { - ValueParser::string() // Default `clap_derive` to optimized implementation - } -} -impl ValueParserFactory for std::ffi::OsString { - type Parser = ValueParser; - fn value_parser() -> Self::Parser { - ValueParser::os_string() // Default `clap_derive` to optimized implementation - } -} -impl ValueParserFactory for std::path::PathBuf { - type Parser = ValueParser; - fn value_parser() -> Self::Parser { - ValueParser::path_buf() // Default `clap_derive` to optimized implementation - } -} -impl ValueParserFactory for bool { - type Parser = ValueParser; - fn value_parser() -> Self::Parser { - ValueParser::bool() // Default `clap_derive` to optimized implementation - } -} -impl ValueParserFactory for u8 { - type Parser = RangedI64ValueParser<u8>; - fn value_parser() -> Self::Parser { - let start: i64 = u8::MIN.into(); - let end: i64 = u8::MAX.into(); - RangedI64ValueParser::new().range(start..=end) - } -} -impl ValueParserFactory for i8 { - type Parser = RangedI64ValueParser<i8>; - fn value_parser() -> Self::Parser { - let start: i64 = i8::MIN.into(); - let end: i64 = i8::MAX.into(); - RangedI64ValueParser::new().range(start..=end) - } -} -impl ValueParserFactory for u16 { - type Parser = RangedI64ValueParser<u16>; - fn value_parser() -> Self::Parser { - let start: i64 = u16::MIN.into(); - let end: i64 = u16::MAX.into(); - RangedI64ValueParser::new().range(start..=end) - } -} -impl ValueParserFactory for i16 { - type Parser = RangedI64ValueParser<i16>; - fn value_parser() -> Self::Parser { - let start: i64 = i16::MIN.into(); - let end: i64 = i16::MAX.into(); - RangedI64ValueParser::new().range(start..=end) - } -} -impl ValueParserFactory for u32 { - type Parser = RangedI64ValueParser<u32>; - fn value_parser() -> Self::Parser { - let start: i64 = u32::MIN.into(); - let end: i64 = u32::MAX.into(); - RangedI64ValueParser::new().range(start..=end) - } -} -impl ValueParserFactory for i32 { - type Parser = RangedI64ValueParser<i32>; - fn value_parser() -> Self::Parser { - let start: i64 = i32::MIN.into(); - let end: i64 = i32::MAX.into(); - RangedI64ValueParser::new().range(start..=end) - } -} -impl ValueParserFactory for i64 { - type Parser = RangedI64ValueParser<i64>; - fn value_parser() -> Self::Parser { - RangedI64ValueParser::new() - } -} -impl ValueParserFactory for u64 { - type Parser = RangedU64ValueParser<u64>; - fn value_parser() -> Self::Parser { - RangedU64ValueParser::new() - } -} - -#[doc(hidden)] -#[derive(Debug)] -pub struct _AutoValueParser<T>(std::marker::PhantomData<T>); - -impl<T> _AutoValueParser<T> { - #[doc(hidden)] - #[allow(clippy::new_without_default)] - pub fn new() -> Self { - Self(Default::default()) - } -} - -/// Unstable [`ValueParser`] -/// -/// Implementation may change to more specific instance in the future -#[doc(hidden)] -#[derive(Debug)] -pub struct _AnonymousValueParser(ValueParser); - -#[doc(hidden)] -pub mod via_prelude { - use super::*; - - #[doc(hidden)] - pub trait _ValueParserViaFactory: private::_ValueParserViaFactorySealed { - type Parser; - fn value_parser(&self) -> Self::Parser; - } - impl<P: ValueParserFactory> _ValueParserViaFactory for &&&&&&_AutoValueParser<P> { - type Parser = P::Parser; - fn value_parser(&self) -> Self::Parser { - P::value_parser() - } - } - - #[doc(hidden)] - pub trait _ValueParserViaValueEnum: private::_ValueParserViaValueEnumSealed { - type Output; - - fn value_parser(&self) -> Self::Output; - } - impl<E: crate::ValueEnum + Clone + Send + Sync + 'static> _ValueParserViaValueEnum - for &&&&&_AutoValueParser<E> - { - type Output = EnumValueParser<E>; - - fn value_parser(&self) -> Self::Output { - EnumValueParser::<E>::new() - } - } - - #[doc(hidden)] - pub trait _ValueParserViaFromOsString: private::_ValueParserViaFromOsStringSealed { - fn value_parser(&self) -> _AnonymousValueParser; - } - impl<FromOsString> _ValueParserViaFromOsString for &&&&_AutoValueParser<FromOsString> - where - FromOsString: From<std::ffi::OsString> + std::any::Any + Clone + Send + Sync + 'static, - { - fn value_parser(&self) -> _AnonymousValueParser { - _AnonymousValueParser( - OsStringValueParser::new() - .map(|s| FromOsString::from(s)) - .into(), - ) - } - } - - #[doc(hidden)] - pub trait _ValueParserViaFromOsStr: private::_ValueParserViaFromOsStrSealed { - fn value_parser(&self) -> _AnonymousValueParser; - } - impl<FromOsStr> _ValueParserViaFromOsStr for &&&_AutoValueParser<FromOsStr> - where - FromOsStr: - for<'s> From<&'s std::ffi::OsStr> + std::any::Any + Clone + Send + Sync + 'static, - { - fn value_parser(&self) -> _AnonymousValueParser { - _AnonymousValueParser( - OsStringValueParser::new() - .map(|s| FromOsStr::from(&s)) - .into(), - ) - } - } - - #[doc(hidden)] - pub trait _ValueParserViaFromString: private::_ValueParserViaFromStringSealed { - fn value_parser(&self) -> _AnonymousValueParser; - } - impl<FromString> _ValueParserViaFromString for &&_AutoValueParser<FromString> - where - FromString: From<String> + std::any::Any + Clone + Send + Sync + 'static, - { - fn value_parser(&self) -> _AnonymousValueParser { - _AnonymousValueParser(StringValueParser::new().map(|s| FromString::from(s)).into()) - } - } - - #[doc(hidden)] - pub trait _ValueParserViaFromStr: private::_ValueParserViaFromStrSealed { - fn value_parser(&self) -> _AnonymousValueParser; - } - impl<FromStr> _ValueParserViaFromStr for &_AutoValueParser<FromStr> - where - FromStr: for<'s> From<&'s str> + std::any::Any + Clone + Send + Sync + 'static, - { - fn value_parser(&self) -> _AnonymousValueParser { - _AnonymousValueParser(StringValueParser::new().map(|s| FromStr::from(&s)).into()) - } - } - - #[doc(hidden)] - pub trait _ValueParserViaParse: private::_ValueParserViaParseSealed { - fn value_parser(&self) -> _AnonymousValueParser; - } - impl<Parse> _ValueParserViaParse for _AutoValueParser<Parse> - where - Parse: std::str::FromStr + std::any::Any + Clone + Send + Sync + 'static, - <Parse as std::str::FromStr>::Err: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, - { - fn value_parser(&self) -> _AnonymousValueParser { - let func: fn(&str) -> Result<Parse, <Parse as std::str::FromStr>::Err> = - Parse::from_str; - _AnonymousValueParser(ValueParser::new(func)) - } - } -} - -/// Select a [`ValueParser`] implementation from the intended type -/// -/// Supported types -/// - [`ValueParserFactory` types][ValueParserFactory], including -/// - [Native types][ValueParser]: `bool`, `String`, `OsString`, `PathBuf` -/// - [Ranged numeric types][RangedI64ValueParser]: `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64` -/// - [`ValueEnum` types][crate::ValueEnum] -/// - [`From<OsString>` types][std::convert::From] and [`From<&OsStr>` types][std::convert::From] -/// - [`From<String>` types][std::convert::From] and [`From<&str>` types][std::convert::From] -/// - [`FromStr` types][std::str::FromStr], including usize, isize -/// -/// # Example -/// -/// Usage: -/// ```rust -/// # use std::path::PathBuf; -/// # use std::path::Path; -/// let mut cmd = clap::Command::new("raw") -/// .arg( -/// clap::Arg::new("output") -/// .value_parser(clap::value_parser!(PathBuf)) -/// .required(true) -/// ); -/// -/// let m = cmd.try_get_matches_from_mut(["cmd", "file.txt"]).unwrap(); -/// let port: &PathBuf = m.get_one("output") -/// .expect("required"); -/// assert_eq!(port, Path::new("file.txt")); -/// ``` -/// -/// Example mappings: -/// ```rust -/// # use clap::ColorChoice; -/// // Built-in types -/// let parser = clap::value_parser!(String); -/// assert_eq!(format!("{:?}", parser), "ValueParser::string"); -/// let parser = clap::value_parser!(std::ffi::OsString); -/// assert_eq!(format!("{:?}", parser), "ValueParser::os_string"); -/// let parser = clap::value_parser!(std::path::PathBuf); -/// assert_eq!(format!("{:?}", parser), "ValueParser::path_buf"); -/// clap::value_parser!(u16).range(3000..); -/// clap::value_parser!(u64).range(3000..); -/// -/// // FromStr types -/// let parser = clap::value_parser!(usize); -/// assert_eq!(format!("{:?}", parser), "_AnonymousValueParser(ValueParser::other(usize))"); -/// -/// // ValueEnum types -/// clap::value_parser!(ColorChoice); -/// ``` -#[macro_export] -macro_rules! value_parser { - ($name:ty) => {{ - use $crate::builder::via_prelude::*; - let auto = $crate::builder::_AutoValueParser::<$name>::new(); - (&&&&&&auto).value_parser() - }}; -} - -mod private { - use super::*; - - // Prefer these so `clap_derive` defaults to optimized implementations - pub trait _ValueParserViaSelfSealed {} - impl<P: Into<ValueParser>> _ValueParserViaSelfSealed for &&&&&&&_AutoValueParser<P> {} - - pub trait _ValueParserViaFactorySealed {} - impl<P: ValueParserFactory> _ValueParserViaFactorySealed for &&&&&&_AutoValueParser<P> {} - - pub trait _ValueParserViaValueEnumSealed {} - impl<E: crate::ValueEnum> _ValueParserViaValueEnumSealed for &&&&&_AutoValueParser<E> {} - - pub trait _ValueParserViaFromOsStringSealed {} - impl<FromOsString> _ValueParserViaFromOsStringSealed for &&&&_AutoValueParser<FromOsString> where - FromOsString: From<std::ffi::OsString> + std::any::Any + Send + Sync + 'static - { - } - - pub trait _ValueParserViaFromOsStrSealed {} - impl<FromOsStr> _ValueParserViaFromOsStrSealed for &&&_AutoValueParser<FromOsStr> where - FromOsStr: for<'s> From<&'s std::ffi::OsStr> + std::any::Any + Send + Sync + 'static - { - } - - pub trait _ValueParserViaFromStringSealed {} - impl<FromString> _ValueParserViaFromStringSealed for &&_AutoValueParser<FromString> where - FromString: From<String> + std::any::Any + Send + Sync + 'static - { - } - - pub trait _ValueParserViaFromStrSealed {} - impl<FromStr> _ValueParserViaFromStrSealed for &_AutoValueParser<FromStr> where - FromStr: for<'s> From<&'s str> + std::any::Any + Send + Sync + 'static - { - } - - pub trait _ValueParserViaParseSealed {} - impl<Parse> _ValueParserViaParseSealed for _AutoValueParser<Parse> - where - Parse: std::str::FromStr + std::any::Any + Send + Sync + 'static, - <Parse as std::str::FromStr>::Err: Into<Box<dyn std::error::Error + Send + Sync + 'static>>, - { - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn ensure_typed_applies_to_parse() { - fn parse(_: &str) -> Result<usize, std::io::Error> { - Ok(10) - } - let cmd = crate::Command::new("cmd"); - let arg = None; - assert_eq!( - TypedValueParser::parse_ref(&parse, &cmd, arg, std::ffi::OsStr::new("foo")).unwrap(), - 10 - ); - } -} diff --git a/vendor/clap/src/derive.rs b/vendor/clap/src/derive.rs deleted file mode 100644 index a30f2da50..000000000 --- a/vendor/clap/src/derive.rs +++ /dev/null @@ -1,471 +0,0 @@ -//! This module contains traits that are usable with the `#[derive(...)].` -//! macros in [`clap_derive`]. - -use crate::builder::PossibleValue; -use crate::{ArgMatches, Command, Error}; - -use std::ffi::OsString; - -/// Parse command-line arguments into `Self`. -/// -/// The primary one-stop-shop trait used to create an instance of a `clap` -/// [`Command`], conduct the parsing, and turn the resulting [`ArgMatches`] back -/// into concrete instance of the user struct. -/// -/// This trait is primarily a convenience on top of [`FromArgMatches`] + -/// [`CommandFactory`] which uses those two underlying traits to build the two -/// fundamental functions `parse` which uses the `std::env::args_os` iterator, -/// and `parse_from` which allows the consumer to supply the iterator (along -/// with fallible options for each). -/// -/// See also [`Subcommand`] and [`Args`]. -/// -/// See the [derive reference](crate::_derive) for attributes and best practices. -/// -/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] -/// -/// # Examples -/// -/// The following example creates a `Context` struct that would be used -/// throughout the application representing the normalized values coming from -/// the CLI. -/// -#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] -#[cfg_attr(feature = "derive", doc = " ```")] -/// /// My super CLI -/// #[derive(clap::Parser)] -/// #[command(name = "demo")] -/// struct Context { -/// /// More verbose output -/// #[arg(long)] -/// verbose: bool, -/// /// An optional name -/// #[arg(short, long)] -/// name: Option<String>, -/// } -/// ``` -/// -/// The equivalent [`Command`] struct + `From` implementation: -/// -/// ```rust -/// # use clap::{Command, Arg, ArgMatches, ArgAction}; -/// Command::new("demo") -/// .about("My super CLI") -/// .arg(Arg::new("verbose") -/// .long("verbose") -/// .action(ArgAction::SetTrue) -/// .help("More verbose output")) -/// .arg(Arg::new("name") -/// .long("name") -/// .short('n') -/// .help("An optional name") -/// .action(ArgAction::Set)); -/// -/// struct Context { -/// verbose: bool, -/// name: Option<String>, -/// } -/// -/// impl From<ArgMatches> for Context { -/// fn from(m: ArgMatches) -> Self { -/// Context { -/// verbose: m.get_flag("verbose"), -/// name: m.get_one::<String>("name").cloned(), -/// } -/// } -/// } -/// ``` -/// -pub trait Parser: FromArgMatches + CommandFactory + Sized { - /// Parse from `std::env::args_os()`, exit on error - fn parse() -> Self { - let mut matches = <Self as CommandFactory>::command().get_matches(); - let res = <Self as FromArgMatches>::from_arg_matches_mut(&mut matches) - .map_err(format_error::<Self>); - match res { - Ok(s) => s, - Err(e) => { - // Since this is more of a development-time error, we aren't doing as fancy of a quit - // as `get_matches` - e.exit() - } - } - } - - /// Parse from `std::env::args_os()`, return Err on error. - fn try_parse() -> Result<Self, Error> { - let mut matches = ok!(<Self as CommandFactory>::command().try_get_matches()); - <Self as FromArgMatches>::from_arg_matches_mut(&mut matches).map_err(format_error::<Self>) - } - - /// Parse from iterator, exit on error - fn parse_from<I, T>(itr: I) -> Self - where - I: IntoIterator<Item = T>, - T: Into<OsString> + Clone, - { - let mut matches = <Self as CommandFactory>::command().get_matches_from(itr); - let res = <Self as FromArgMatches>::from_arg_matches_mut(&mut matches) - .map_err(format_error::<Self>); - match res { - Ok(s) => s, - Err(e) => { - // Since this is more of a development-time error, we aren't doing as fancy of a quit - // as `get_matches_from` - e.exit() - } - } - } - - /// Parse from iterator, return Err on error. - fn try_parse_from<I, T>(itr: I) -> Result<Self, Error> - where - I: IntoIterator<Item = T>, - T: Into<OsString> + Clone, - { - let mut matches = ok!(<Self as CommandFactory>::command().try_get_matches_from(itr)); - <Self as FromArgMatches>::from_arg_matches_mut(&mut matches).map_err(format_error::<Self>) - } - - /// Update from iterator, exit on error - fn update_from<I, T>(&mut self, itr: I) - where - I: IntoIterator<Item = T>, - T: Into<OsString> + Clone, - { - let mut matches = <Self as CommandFactory>::command_for_update().get_matches_from(itr); - let res = <Self as FromArgMatches>::update_from_arg_matches_mut(self, &mut matches) - .map_err(format_error::<Self>); - if let Err(e) = res { - // Since this is more of a development-time error, we aren't doing as fancy of a quit - // as `get_matches_from` - e.exit() - } - } - - /// Update from iterator, return Err on error. - fn try_update_from<I, T>(&mut self, itr: I) -> Result<(), Error> - where - I: IntoIterator<Item = T>, - T: Into<OsString> + Clone, - { - let mut matches = - ok!(<Self as CommandFactory>::command_for_update().try_get_matches_from(itr)); - <Self as FromArgMatches>::update_from_arg_matches_mut(self, &mut matches) - .map_err(format_error::<Self>) - } -} - -/// Create a [`Command`] relevant for a user-defined container. -/// -/// Derived as part of [`Parser`]. -pub trait CommandFactory: Sized { - /// Build a [`Command`] that can instantiate `Self`. - /// - /// See [`FromArgMatches::from_arg_matches_mut`] for instantiating `Self`. - fn command() -> Command; - /// Build a [`Command`] that can update `self`. - /// - /// See [`FromArgMatches::update_from_arg_matches_mut`] for updating `self`. - fn command_for_update() -> Command; -} - -/// Converts an instance of [`ArgMatches`] to a user-defined container. -/// -/// Derived as part of [`Parser`], [`Args`], and [`Subcommand`]. -pub trait FromArgMatches: Sized { - /// Instantiate `Self` from [`ArgMatches`], parsing the arguments as needed. - /// - /// Motivation: If our application had two CLI options, `--name - /// <STRING>` and the flag `--debug`, we may create a struct as follows: - /// - #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] - #[cfg_attr(feature = "derive", doc = " ```no_run")] - /// struct Context { - /// name: String, - /// debug: bool - /// } - /// ``` - /// - /// We then need to convert the `ArgMatches` that `clap` generated into our struct. - /// `from_arg_matches` serves as the equivalent of: - /// - #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] - #[cfg_attr(feature = "derive", doc = " ```no_run")] - /// # use clap::ArgMatches; - /// # struct Context { - /// # name: String, - /// # debug: bool - /// # } - /// impl From<ArgMatches> for Context { - /// fn from(m: ArgMatches) -> Self { - /// Context { - /// name: m.get_one::<String>("name").unwrap().clone(), - /// debug: m.get_flag("debug"), - /// } - /// } - /// } - /// ``` - fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error>; - - /// Instantiate `Self` from [`ArgMatches`], parsing the arguments as needed. - /// - /// Motivation: If our application had two CLI options, `--name - /// <STRING>` and the flag `--debug`, we may create a struct as follows: - /// - #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] - #[cfg_attr(feature = "derive", doc = " ```no_run")] - /// struct Context { - /// name: String, - /// debug: bool - /// } - /// ``` - /// - /// We then need to convert the `ArgMatches` that `clap` generated into our struct. - /// `from_arg_matches_mut` serves as the equivalent of: - /// - #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] - #[cfg_attr(feature = "derive", doc = " ```no_run")] - /// # use clap::ArgMatches; - /// # struct Context { - /// # name: String, - /// # debug: bool - /// # } - /// impl From<ArgMatches> for Context { - /// fn from(m: ArgMatches) -> Self { - /// Context { - /// name: m.get_one::<String>("name").unwrap().to_string(), - /// debug: m.get_flag("debug"), - /// } - /// } - /// } - /// ``` - fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error> { - Self::from_arg_matches(matches) - } - - /// Assign values from `ArgMatches` to `self`. - fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error>; - - /// Assign values from `ArgMatches` to `self`. - fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> { - self.update_from_arg_matches(matches) - } -} - -/// Parse a set of arguments into a user-defined container. -/// -/// Implementing this trait lets a parent container delegate argument parsing behavior to `Self`. -/// with: -/// - `#[command(flatten)] args: ChildArgs`: Attribute can only be used with struct fields that impl -/// `Args`. -/// - `Variant(ChildArgs)`: No attribute is used with enum variants that impl `Args`. -/// -/// See the [derive reference](crate::_derive) for attributes and best practices. -/// -/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] -/// -/// # Example -/// -#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] -#[cfg_attr(feature = "derive", doc = " ```")] -/// #[derive(clap::Parser)] -/// struct Args { -/// #[command(flatten)] -/// logging: LogArgs, -/// } -/// -/// #[derive(clap::Args)] -/// struct LogArgs { -/// #[arg(long, short = 'v', action = clap::ArgAction::Count)] -/// verbose: u8, -/// } -/// ``` -pub trait Args: FromArgMatches + Sized { - /// Report the [`ArgGroup::id`][crate::ArgGroup::id] for this set of arguments - fn group_id() -> Option<crate::Id> { - None - } - /// Append to [`Command`] so it can instantiate `Self`. - /// - /// See also [`CommandFactory`]. - fn augment_args(cmd: Command) -> Command; - /// Append to [`Command`] so it can update `self`. - /// - /// This is used to implement `#[command(flatten)]` - /// - /// See also [`CommandFactory`]. - fn augment_args_for_update(cmd: Command) -> Command; -} - -/// Parse a sub-command into a user-defined enum. -/// -/// Implementing this trait lets a parent container delegate subcommand behavior to `Self`. -/// with: -/// - `#[command(subcommand)] field: SubCmd`: Attribute can be used with either struct fields or enum -/// variants that impl `Subcommand`. -/// - `#[command(flatten)] Variant(SubCmd)`: Attribute can only be used with enum variants that impl -/// `Subcommand`. -/// -/// See the [derive reference](crate::_derive) for attributes and best practices. -/// -/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] -/// -/// # Example -/// -#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] -#[cfg_attr(feature = "derive", doc = " ```")] -/// #[derive(clap::Parser)] -/// struct Args { -/// #[command(subcommand)] -/// action: Action, -/// } -/// -/// #[derive(clap::Subcommand)] -/// enum Action { -/// Add, -/// Remove, -/// } -/// ``` -pub trait Subcommand: FromArgMatches + Sized { - /// Append to [`Command`] so it can instantiate `Self`. - /// - /// See also [`CommandFactory`]. - fn augment_subcommands(cmd: Command) -> Command; - /// Append to [`Command`] so it can update `self`. - /// - /// This is used to implement `#[command(flatten)]` - /// - /// See also [`CommandFactory`]. - fn augment_subcommands_for_update(cmd: Command) -> Command; - /// Test whether `Self` can parse a specific subcommand - fn has_subcommand(name: &str) -> bool; -} - -/// Parse arguments into enums. -/// -/// When deriving [`Parser`], a field whose type implements `ValueEnum` can have the attribute -/// `#[arg(value_enum)]` which will -/// - Call [`EnumValueParser`][crate::builder::EnumValueParser] -/// - Allowing using the `#[arg(default_value_t)]` attribute without implementing `Display`. -/// -/// See the [derive reference](crate::_derive) for attributes and best practices. -/// -/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] -/// -/// # Example -/// -#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] -#[cfg_attr(feature = "derive", doc = " ```")] -/// #[derive(clap::Parser)] -/// struct Args { -/// #[arg(value_enum)] -/// level: Level, -/// } -/// -/// #[derive(clap::ValueEnum, Clone)] -/// enum Level { -/// Debug, -/// Info, -/// Warning, -/// Error, -/// } -/// ``` -pub trait ValueEnum: Sized + Clone { - /// All possible argument values, in display order. - fn value_variants<'a>() -> &'a [Self]; - - /// Parse an argument into `Self`. - fn from_str(input: &str, ignore_case: bool) -> Result<Self, String> { - Self::value_variants() - .iter() - .find(|v| { - v.to_possible_value() - .expect("ValueEnum::value_variants contains only values with a corresponding ValueEnum::to_possible_value") - .matches(input, ignore_case) - }) - .cloned() - .ok_or_else(|| format!("invalid variant: {}", input)) - } - - /// The canonical argument value. - /// - /// The value is `None` for skipped variants. - fn to_possible_value(&self) -> Option<PossibleValue>; -} - -impl<T: Parser> Parser for Box<T> { - fn parse() -> Self { - Box::new(<T as Parser>::parse()) - } - - fn try_parse() -> Result<Self, Error> { - <T as Parser>::try_parse().map(Box::new) - } - - fn parse_from<I, It>(itr: I) -> Self - where - I: IntoIterator<Item = It>, - It: Into<OsString> + Clone, - { - Box::new(<T as Parser>::parse_from(itr)) - } - - fn try_parse_from<I, It>(itr: I) -> Result<Self, Error> - where - I: IntoIterator<Item = It>, - It: Into<OsString> + Clone, - { - <T as Parser>::try_parse_from(itr).map(Box::new) - } -} - -impl<T: CommandFactory> CommandFactory for Box<T> { - fn command<'help>() -> Command { - <T as CommandFactory>::command() - } - fn command_for_update<'help>() -> Command { - <T as CommandFactory>::command_for_update() - } -} - -impl<T: FromArgMatches> FromArgMatches for Box<T> { - fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> { - <T as FromArgMatches>::from_arg_matches(matches).map(Box::new) - } - fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error> { - <T as FromArgMatches>::from_arg_matches_mut(matches).map(Box::new) - } - fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> { - <T as FromArgMatches>::update_from_arg_matches(self, matches) - } - fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> { - <T as FromArgMatches>::update_from_arg_matches_mut(self, matches) - } -} - -impl<T: Args> Args for Box<T> { - fn augment_args(cmd: Command) -> Command { - <T as Args>::augment_args(cmd) - } - fn augment_args_for_update(cmd: Command) -> Command { - <T as Args>::augment_args_for_update(cmd) - } -} - -impl<T: Subcommand> Subcommand for Box<T> { - fn augment_subcommands(cmd: Command) -> Command { - <T as Subcommand>::augment_subcommands(cmd) - } - fn augment_subcommands_for_update(cmd: Command) -> Command { - <T as Subcommand>::augment_subcommands_for_update(cmd) - } - fn has_subcommand(name: &str) -> bool { - <T as Subcommand>::has_subcommand(name) - } -} - -fn format_error<I: CommandFactory>(err: crate::Error) -> crate::Error { - let mut cmd = I::command(); - err.format(&mut cmd) -} diff --git a/vendor/clap/src/error/context.rs b/vendor/clap/src/error/context.rs deleted file mode 100644 index 045923c47..000000000 --- a/vendor/clap/src/error/context.rs +++ /dev/null @@ -1,114 +0,0 @@ -/// Semantics for a piece of error information -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] -#[non_exhaustive] -#[cfg(feature = "error-context")] -pub enum ContextKind { - /// The cause of the error - InvalidSubcommand, - /// The cause of the error - InvalidArg, - /// Existing arguments - PriorArg, - /// Accepted subcommands - ValidSubcommand, - /// Accepted values - ValidValue, - /// Rejected values - InvalidValue, - /// Number of values present - ActualNumValues, - /// Number of allowed values - ExpectedNumValues, - /// Minimum number of allowed values - MinValues, - /// Potential fix for the user - SuggestedCommand, - /// Potential fix for the user - SuggestedSubcommand, - /// Potential fix for the user - SuggestedArg, - /// Potential fix for the user - SuggestedValue, - /// Trailing argument - TrailingArg, - /// Potential fix for the user - Suggested, - /// A usage string - Usage, - /// An opaque message to the user - Custom, -} - -impl ContextKind { - /// End-user description of the error case, where relevant - pub fn as_str(self) -> Option<&'static str> { - match self { - Self::InvalidSubcommand => Some("Invalid Subcommand"), - Self::InvalidArg => Some("Invalid Argument"), - Self::PriorArg => Some("Prior Argument"), - Self::ValidSubcommand => Some("Valid Subcommand"), - Self::ValidValue => Some("Valid Value"), - Self::InvalidValue => Some("Invalid Value"), - Self::ActualNumValues => Some("Actual Number of Values"), - Self::ExpectedNumValues => Some("Expected Number of Values"), - Self::MinValues => Some("Minimum Number of Values"), - Self::SuggestedCommand => Some("Suggested Command"), - Self::SuggestedSubcommand => Some("Suggested Subcommand"), - Self::SuggestedArg => Some("Suggested Argument"), - Self::SuggestedValue => Some("Suggested Value"), - Self::TrailingArg => Some("Trailing Argument"), - Self::Suggested => Some("Suggested"), - Self::Usage => None, - Self::Custom => None, - } - } -} - -impl std::fmt::Display for ContextKind { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.as_str().unwrap_or_default().fmt(f) - } -} - -/// A piece of error information -#[derive(Clone, Debug, PartialEq, Eq)] -#[non_exhaustive] -#[cfg(feature = "error-context")] -pub enum ContextValue { - /// [`ContextKind`] is self-sufficient, no additional information needed - None, - /// A single value - Bool(bool), - /// A single value - String(String), - /// Many values - Strings(Vec<String>), - /// A single value - StyledStr(crate::builder::StyledStr), - /// many value - StyledStrs(Vec<crate::builder::StyledStr>), - /// A single value - Number(isize), -} - -impl std::fmt::Display for ContextValue { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::None => "".fmt(f), - Self::Bool(v) => v.fmt(f), - Self::String(v) => v.fmt(f), - Self::Strings(v) => v.join(", ").fmt(f), - Self::StyledStr(v) => v.fmt(f), - Self::StyledStrs(v) => { - for (i, v) in v.iter().enumerate() { - if i != 0 { - ", ".fmt(f)?; - } - v.fmt(f)?; - } - Ok(()) - } - Self::Number(v) => v.fmt(f), - } - } -} diff --git a/vendor/clap/src/error/format.rs b/vendor/clap/src/error/format.rs deleted file mode 100644 index 98d34b7ef..000000000 --- a/vendor/clap/src/error/format.rs +++ /dev/null @@ -1,468 +0,0 @@ -#![allow(missing_copy_implementations)] -#![allow(missing_debug_implementations)] -#![cfg_attr(not(feature = "error-context"), allow(dead_code))] -#![cfg_attr(not(feature = "error-context"), allow(unused_imports))] - -use crate::builder::Command; -use crate::builder::StyledStr; -#[cfg(feature = "error-context")] -use crate::error::ContextKind; -#[cfg(feature = "error-context")] -use crate::error::ContextValue; -use crate::error::ErrorKind; -use crate::output::TAB; - -/// Defines how to format an error for displaying to the user -pub trait ErrorFormatter: Sized { - /// Stylize the error for the terminal - fn format_error(error: &crate::error::Error<Self>) -> StyledStr; -} - -/// Report [`ErrorKind`] -/// -/// No context is included. -/// -/// **NOTE:** Consider removing the [`error-context`][crate::_features] default feature if using this to remove all -/// overhead for [`RichFormatter`]. -#[non_exhaustive] -pub struct KindFormatter; - -impl ErrorFormatter for KindFormatter { - fn format_error(error: &crate::error::Error<Self>) -> StyledStr { - let mut styled = StyledStr::new(); - start_error(&mut styled); - if let Some(msg) = error.kind().as_str() { - styled.none(msg.to_owned()); - } else if let Some(source) = error.inner.source.as_ref() { - styled.none(source.to_string()); - } else { - styled.none("unknown cause"); - } - styled.none("\n"); - styled - } -} - -/// Richly formatted error context -/// -/// This follows the [rustc diagnostic style guide](https://rustc-dev-guide.rust-lang.org/diagnostics.html#suggestion-style-guide). -#[non_exhaustive] -#[cfg(feature = "error-context")] -pub struct RichFormatter; - -#[cfg(feature = "error-context")] -impl ErrorFormatter for RichFormatter { - fn format_error(error: &crate::error::Error<Self>) -> StyledStr { - let mut styled = StyledStr::new(); - start_error(&mut styled); - - if !write_dynamic_context(error, &mut styled) { - if let Some(msg) = error.kind().as_str() { - styled.none(msg.to_owned()); - } else if let Some(source) = error.inner.source.as_ref() { - styled.none(source.to_string()); - } else { - styled.none("unknown cause"); - } - } - - let mut suggested = false; - if let Some(valid) = error.get(ContextKind::SuggestedSubcommand) { - styled.none("\n"); - if !suggested { - styled.none("\n"); - suggested = true; - } - did_you_mean(&mut styled, "subcommand", valid); - } - if let Some(valid) = error.get(ContextKind::SuggestedArg) { - styled.none("\n"); - if !suggested { - styled.none("\n"); - suggested = true; - } - did_you_mean(&mut styled, "argument", valid); - } - if let Some(valid) = error.get(ContextKind::SuggestedValue) { - styled.none("\n"); - if !suggested { - styled.none("\n"); - suggested = true; - } - did_you_mean(&mut styled, "value", valid); - } - let suggestions = error.get(ContextKind::Suggested); - if let Some(ContextValue::StyledStrs(suggestions)) = suggestions { - if !suggested { - styled.none("\n"); - } - for suggestion in suggestions { - styled.none("\n"); - styled.none(TAB); - styled.good("note: "); - styled.extend(suggestion.iter()); - } - } - - let usage = error.get(ContextKind::Usage); - if let Some(ContextValue::StyledStr(usage)) = usage { - put_usage(&mut styled, usage.clone()); - } - - try_help(&mut styled, error.inner.help_flag); - - styled - } -} - -fn start_error(styled: &mut StyledStr) { - styled.error("error:"); - styled.none(" "); -} - -#[must_use] -#[cfg(feature = "error-context")] -fn write_dynamic_context(error: &crate::error::Error, styled: &mut StyledStr) -> bool { - match error.kind() { - ErrorKind::ArgumentConflict => { - let invalid_arg = error.get(ContextKind::InvalidArg); - let prior_arg = error.get(ContextKind::PriorArg); - if let (Some(ContextValue::String(invalid_arg)), Some(prior_arg)) = - (invalid_arg, prior_arg) - { - if ContextValue::String(invalid_arg.clone()) == *prior_arg { - styled.none("the argument '"); - styled.warning(invalid_arg); - styled.none("' cannot be used multiple times"); - } else { - styled.none("the argument '"); - styled.warning(invalid_arg); - styled.none("' cannot be used with"); - - match prior_arg { - ContextValue::Strings(values) => { - styled.none(":"); - for v in values { - styled.none("\n"); - styled.none(TAB); - styled.warning(&**v); - } - } - ContextValue::String(value) => { - styled.none(" '"); - styled.warning(value); - styled.none("'"); - } - _ => { - styled.none(" one or more of the other specified arguments"); - } - } - } - true - } else { - false - } - } - ErrorKind::NoEquals => { - let invalid_arg = error.get(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - styled.none("equal sign is needed when assigning values to '"); - styled.warning(invalid_arg); - styled.none("'"); - true - } else { - false - } - } - ErrorKind::InvalidValue => { - let invalid_arg = error.get(ContextKind::InvalidArg); - let invalid_value = error.get(ContextKind::InvalidValue); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::String(invalid_value)), - ) = (invalid_arg, invalid_value) - { - if invalid_value.is_empty() { - styled.none("a value is required for '"); - styled.warning(invalid_arg); - styled.none("' but none was supplied"); - } else { - styled.none("invalid value '"); - styled.none(invalid_value); - styled.none("' for '"); - styled.warning(invalid_arg); - styled.none("'"); - } - - let possible_values = error.get(ContextKind::ValidValue); - if let Some(ContextValue::Strings(possible_values)) = possible_values { - if !possible_values.is_empty() { - styled.none("\n"); - styled.none(TAB); - styled.none("[possible values: "); - if let Some((last, elements)) = possible_values.split_last() { - for v in elements { - styled.good(escape(v)); - styled.none(", "); - } - styled.good(escape(last)); - } - styled.none("]"); - } - } - true - } else { - false - } - } - ErrorKind::InvalidSubcommand => { - let invalid_sub = error.get(ContextKind::InvalidSubcommand); - if let Some(ContextValue::String(invalid_sub)) = invalid_sub { - styled.none("unrecognized subcommand '"); - styled.warning(invalid_sub); - styled.none("'"); - true - } else { - false - } - } - ErrorKind::MissingRequiredArgument => { - let invalid_arg = error.get(ContextKind::InvalidArg); - if let Some(ContextValue::Strings(invalid_arg)) = invalid_arg { - styled.none("the following required arguments were not provided:"); - for v in invalid_arg { - styled.none("\n"); - styled.none(TAB); - styled.good(&**v); - } - true - } else { - false - } - } - ErrorKind::MissingSubcommand => { - let invalid_sub = error.get(ContextKind::InvalidSubcommand); - if let Some(ContextValue::String(invalid_sub)) = invalid_sub { - styled.none("'"); - styled.warning(invalid_sub); - styled.none("' requires a subcommand but one was not provided"); - - let possible_values = error.get(ContextKind::ValidSubcommand); - if let Some(ContextValue::Strings(possible_values)) = possible_values { - if !possible_values.is_empty() { - styled.none("\n"); - styled.none(TAB); - styled.none("[subcommands: "); - if let Some((last, elements)) = possible_values.split_last() { - for v in elements { - styled.good(escape(v)); - styled.none(", "); - } - styled.good(escape(last)); - } - styled.none("]"); - } - } - - true - } else { - false - } - } - ErrorKind::InvalidUtf8 => false, - ErrorKind::TooManyValues => { - let invalid_arg = error.get(ContextKind::InvalidArg); - let invalid_value = error.get(ContextKind::InvalidValue); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::String(invalid_value)), - ) = (invalid_arg, invalid_value) - { - styled.none("unexpected value '"); - styled.warning(invalid_value); - styled.none("' for '"); - styled.warning(invalid_arg); - styled.none("' found; no more were expected"); - true - } else { - false - } - } - ErrorKind::TooFewValues => { - let invalid_arg = error.get(ContextKind::InvalidArg); - let actual_num_values = error.get(ContextKind::ActualNumValues); - let min_values = error.get(ContextKind::MinValues); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::Number(actual_num_values)), - Some(ContextValue::Number(min_values)), - ) = (invalid_arg, actual_num_values, min_values) - { - let were_provided = singular_or_plural(*actual_num_values as usize); - styled.warning(min_values.to_string()); - styled.none(" more values required by '"); - styled.warning(invalid_arg); - styled.none("'; only "); - styled.warning(actual_num_values.to_string()); - styled.none(were_provided); - true - } else { - false - } - } - ErrorKind::ValueValidation => { - let invalid_arg = error.get(ContextKind::InvalidArg); - let invalid_value = error.get(ContextKind::InvalidValue); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::String(invalid_value)), - ) = (invalid_arg, invalid_value) - { - styled.none("invalid value '"); - styled.warning(invalid_value); - styled.none("' for '"); - styled.warning(invalid_arg); - if let Some(source) = error.inner.source.as_deref() { - styled.none("': "); - styled.none(source.to_string()); - } else { - styled.none("'"); - } - true - } else { - false - } - } - ErrorKind::WrongNumberOfValues => { - let invalid_arg = error.get(ContextKind::InvalidArg); - let actual_num_values = error.get(ContextKind::ActualNumValues); - let num_values = error.get(ContextKind::ExpectedNumValues); - if let ( - Some(ContextValue::String(invalid_arg)), - Some(ContextValue::Number(actual_num_values)), - Some(ContextValue::Number(num_values)), - ) = (invalid_arg, actual_num_values, num_values) - { - let were_provided = singular_or_plural(*actual_num_values as usize); - styled.warning(num_values.to_string()); - styled.none(" values required for '"); - styled.warning(invalid_arg); - styled.none("' but "); - styled.warning(actual_num_values.to_string()); - styled.none(were_provided); - true - } else { - false - } - } - ErrorKind::UnknownArgument => { - let invalid_arg = error.get(ContextKind::InvalidArg); - if let Some(ContextValue::String(invalid_arg)) = invalid_arg { - styled.none("unexpected argument '"); - styled.warning(invalid_arg.to_string()); - styled.none("' found"); - true - } else { - false - } - } - ErrorKind::DisplayHelp - | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand - | ErrorKind::DisplayVersion - | ErrorKind::Io - | ErrorKind::Format => false, - } -} - -pub(crate) fn format_error_message( - message: &str, - cmd: Option<&Command>, - usage: Option<StyledStr>, -) -> StyledStr { - let mut styled = StyledStr::new(); - start_error(&mut styled); - styled.none(message); - if let Some(usage) = usage { - put_usage(&mut styled, usage); - } - if let Some(cmd) = cmd { - try_help(&mut styled, get_help_flag(cmd)); - } - styled -} - -/// Returns the singular or plural form on the verb to be based on the argument's value. -fn singular_or_plural(n: usize) -> &'static str { - if n > 1 { - " were provided" - } else { - " was provided" - } -} - -fn put_usage(styled: &mut StyledStr, usage: StyledStr) { - styled.none("\n\n"); - styled.extend(usage.into_iter()); -} - -pub(crate) fn get_help_flag(cmd: &Command) -> Option<&'static str> { - if !cmd.is_disable_help_flag_set() { - Some("--help") - } else if cmd.has_subcommands() && !cmd.is_disable_help_subcommand_set() { - Some("help") - } else { - None - } -} - -fn try_help(styled: &mut StyledStr, help: Option<&str>) { - if let Some(help) = help { - styled.none("\n\nFor more information, try '"); - styled.literal(help.to_owned()); - styled.none("'.\n"); - } else { - styled.none("\n"); - } -} - -#[cfg(feature = "error-context")] -fn did_you_mean(styled: &mut StyledStr, context: &str, valid: &ContextValue) { - if let ContextValue::String(valid) = valid { - styled.none(TAB); - styled.good("note: "); - styled.none(context); - styled.none(" '"); - styled.good(valid); - styled.none("' exists"); - } else if let ContextValue::Strings(valid) = valid { - styled.none(TAB); - styled.good("note: "); - styled.none(context); - if valid.len() > 1 { - styled.none("s"); - } - styled.none(" "); - for (i, valid) in valid.iter().enumerate() { - if i != 0 { - styled.none(", "); - } - styled.none("'"); - styled.good(valid); - styled.none("'"); - } - if valid.len() == 1 { - styled.none(" exists"); - } else { - styled.none(" exist"); - } - } -} - -fn escape(s: impl AsRef<str>) -> String { - let s = s.as_ref(); - if s.contains(char::is_whitespace) { - format!("{:?}", s) - } else { - s.to_owned() - } -} diff --git a/vendor/clap/src/error/kind.rs b/vendor/clap/src/error/kind.rs deleted file mode 100644 index 1859237a2..000000000 --- a/vendor/clap/src/error/kind.rs +++ /dev/null @@ -1,348 +0,0 @@ -/// Command line argument parser kind of error -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -#[non_exhaustive] -pub enum ErrorKind { - /// Occurs when an [`Arg`][crate::Arg] has a set of possible values, - /// and the user provides a value which isn't in that set. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("speed") - /// .value_parser(["fast", "slow"])) - /// .try_get_matches_from(vec!["prog", "other"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidValue); - /// ``` - InvalidValue, - - /// Occurs when a user provides a flag, option, argument or subcommand which isn't defined. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, arg, error::ErrorKind}; - /// let result = Command::new("prog") - /// .arg(arg!(--flag "some flag")) - /// .try_get_matches_from(vec!["prog", "--other"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::UnknownArgument); - /// ``` - UnknownArgument, - - /// Occurs when the user provides an unrecognized [`Subcommand`] which meets the threshold for - /// being similar enough to an existing subcommand. - /// If it doesn't meet the threshold, or the 'suggestions' feature is disabled, - /// the more general [`UnknownArgument`] error is returned. - /// - /// # Examples - /// - #[cfg_attr(not(feature = "suggestions"), doc = " ```no_run")] - #[cfg_attr(feature = "suggestions", doc = " ```")] - /// # use clap::{Command, Arg, error::ErrorKind, }; - /// let result = Command::new("prog") - /// .subcommand(Command::new("config") - /// .about("Used for configuration") - /// .arg(Arg::new("config_file") - /// .help("The configuration file to use"))) - /// .try_get_matches_from(vec!["prog", "confi"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidSubcommand); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - /// [`UnknownArgument`]: ErrorKind::UnknownArgument - InvalidSubcommand, - - /// Occurs when the user doesn't use equals for an option that requires equal - /// sign to provide values. - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let res = Command::new("prog") - /// .arg(Arg::new("color") - /// .action(ArgAction::Set) - /// .require_equals(true) - /// .long("color")) - /// .try_get_matches_from(vec!["prog", "--color", "red"]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals); - /// ``` - NoEquals, - - /// Occurs when the user provides a value for an argument with a custom validation and the - /// value fails that validation. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, value_parser}; - /// fn is_numeric(val: &str) -> Result<(), String> { - /// match val.parse::<i64>() { - /// Ok(..) => Ok(()), - /// Err(..) => Err(String::from("value wasn't a number!")), - /// } - /// } - /// - /// let result = Command::new("prog") - /// .arg(Arg::new("num") - /// .value_parser(value_parser!(u8))) - /// .try_get_matches_from(vec!["prog", "NotANumber"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::ValueValidation); - /// ``` - ValueValidation, - - /// Occurs when a user provides more values for an argument than were defined by setting - /// [`Arg::num_args`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("arg") - /// .num_args(1..=2)) - /// .try_get_matches_from(vec!["prog", "too", "many", "values"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooManyValues); - /// ``` - /// [`Arg::num_args`]: crate::Arg::num_args() - TooManyValues, - - /// Occurs when the user provides fewer values for an argument than were defined by setting - /// [`Arg::num_args`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("some_opt") - /// .long("opt") - /// .num_args(3..)) - /// .try_get_matches_from(vec!["prog", "--opt", "too", "few"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooFewValues); - /// ``` - /// [`Arg::num_args`]: crate::Arg::num_args() - TooFewValues, - - /// Occurs when the user provides a different number of values for an argument than what's - /// been defined by setting [`Arg::num_args`] or than was implicitly set by - /// [`Arg::value_names`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let result = Command::new("prog") - /// .arg(Arg::new("some_opt") - /// .long("opt") - /// .action(ArgAction::Set) - /// .num_args(2)) - /// .try_get_matches_from(vec!["prog", "--opt", "wrong"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::WrongNumberOfValues); - /// ``` - /// - /// [`Arg::num_args`]: crate::Arg::num_args() - /// [`Arg::value_names`]: crate::Arg::value_names() - WrongNumberOfValues, - - /// Occurs when the user provides two values which conflict with each other and can't be used - /// together. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// let result = Command::new("prog") - /// .arg(Arg::new("debug") - /// .long("debug") - /// .action(ArgAction::SetTrue) - /// .conflicts_with("color")) - /// .arg(Arg::new("color") - /// .long("color") - /// .action(ArgAction::SetTrue)) - /// .try_get_matches_from(vec!["prog", "--debug", "--color"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::ArgumentConflict); - /// ``` - ArgumentConflict, - - /// Occurs when the user does not provide one or more required arguments. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind}; - /// let result = Command::new("prog") - /// .arg(Arg::new("debug") - /// .required(true)) - /// .try_get_matches_from(vec!["prog"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); - /// ``` - MissingRequiredArgument, - - /// Occurs when a subcommand is required (as defined by [`Command::subcommand_required`]), - /// but the user does not provide one. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, error::ErrorKind}; - /// let err = Command::new("prog") - /// .subcommand_required(true) - /// .subcommand(Command::new("test")) - /// .try_get_matches_from(vec![ - /// "myprog", - /// ]); - /// assert!(err.is_err()); - /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); - /// # ; - /// ``` - /// - /// [`Command::subcommand_required`]: crate::Command::subcommand_required - MissingSubcommand, - - /// Occurs when the user provides a value containing invalid UTF-8. - /// - /// To allow arbitrary data - /// - Set [`Arg::value_parser(value_parser!(OsString))`] for argument values - /// - Set [`Command::external_subcommand_value_parser`] for external-subcommand - /// values - /// - /// # Platform Specific - /// - /// Non-Windows platforms only (such as Linux, Unix, OSX, etc.) - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; - /// # use std::os::unix::ffi::OsStringExt; - /// # use std::ffi::OsString; - /// let result = Command::new("prog") - /// .arg(Arg::new("utf8") - /// .short('u') - /// .action(ArgAction::Set)) - /// .try_get_matches_from(vec![OsString::from("myprog"), - /// OsString::from("-u"), - /// OsString::from_vec(vec![0xE9])]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidUtf8); - /// ``` - /// - /// [`Arg::allow_invalid_utf8`]: crate::Arg::allow_invalid_utf8 - /// [`Command::external_subcommand_value_parser`]: crate::Command::external_subcommand_value_parser - InvalidUtf8, - - /// Not a true "error" as it means `--help` or similar was used. - /// The help message will be sent to `stdout`. - /// - /// **Note**: If the help is displayed due to an error (such as missing subcommands) it will - /// be sent to `stderr` instead of `stdout`. - /// - /// # Examples - /// - #[cfg_attr(not(feature = "help"), doc = " ```ignore")] - #[cfg_attr(feature = "help", doc = " ```")] - /// # use clap::{Command, Arg, error::ErrorKind}; - /// let result = Command::new("prog") - /// .try_get_matches_from(vec!["prog", "--help"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayHelp); - /// ``` - DisplayHelp, - - /// Occurs when either an argument or a [`Subcommand`] is required, as defined by - /// [`Command::arg_required_else_help`] , but the user did not provide - /// one. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind, }; - /// let result = Command::new("prog") - /// .arg_required_else_help(true) - /// .subcommand(Command::new("config") - /// .about("Used for configuration") - /// .arg(Arg::new("config_file") - /// .help("The configuration file to use"))) - /// .try_get_matches_from(vec!["prog"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand); - /// ``` - /// - /// [`Subcommand`]: crate::Subcommand - /// [`Command::arg_required_else_help`]: crate::Command::arg_required_else_help - DisplayHelpOnMissingArgumentOrSubcommand, - - /// Not a true "error" as it means `--version` or similar was used. - /// The message will be sent to `stdout`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, error::ErrorKind}; - /// let result = Command::new("prog") - /// .version("3.0") - /// .try_get_matches_from(vec!["prog", "--version"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayVersion); - /// ``` - DisplayVersion, - - /// Represents an [I/O error]. - /// Can occur when writing to `stderr` or `stdout` or reading a configuration file. - /// - /// [I/O error]: std::io::Error - Io, - - /// Represents a [Format error] (which is a part of [`Display`]). - /// Typically caused by writing to `stderr` or `stdout`. - /// - /// [`Display`]: std::fmt::Display - /// [Format error]: std::fmt::Error - Format, -} - -impl ErrorKind { - /// End-user description of the error case, where relevant - pub fn as_str(self) -> Option<&'static str> { - match self { - Self::InvalidValue => Some("one of the values isn't valid for an argument"), - Self::UnknownArgument => Some("unexpected argument found"), - Self::InvalidSubcommand => Some("unrecognized subcommand"), - Self::NoEquals => Some("equal is needed when assigning values to one of the arguments"), - Self::ValueValidation => Some("invalid value for one of the arguments"), - Self::TooManyValues => Some("unexpected value for an argument found"), - Self::TooFewValues => Some("more values required for an argument"), - Self::WrongNumberOfValues => Some("too many or too few values for an argument"), - Self::ArgumentConflict => { - Some("an argument cannot be used with one or more of the other specified arguments") - } - Self::MissingRequiredArgument => { - Some("one or more required arguments were not provided") - } - Self::MissingSubcommand => Some("a subcommand is required but one was not provided"), - Self::InvalidUtf8 => Some("invalid UTF-8 was detected in one or more arguments"), - Self::DisplayHelp => None, - Self::DisplayHelpOnMissingArgumentOrSubcommand => None, - Self::DisplayVersion => None, - Self::Io => None, - Self::Format => None, - } - } -} - -impl std::fmt::Display for ErrorKind { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.as_str().unwrap_or_default().fmt(f) - } -} diff --git a/vendor/clap/src/error/mod.rs b/vendor/clap/src/error/mod.rs deleted file mode 100644 index 9c8828574..000000000 --- a/vendor/clap/src/error/mod.rs +++ /dev/null @@ -1,876 +0,0 @@ -//! Error reporting - -#![cfg_attr(not(feature = "error-context"), allow(dead_code))] -#![cfg_attr(not(feature = "error-context"), allow(unused_imports))] -#![cfg_attr(not(feature = "error-context"), allow(unused_variables))] -#![cfg_attr(not(feature = "error-context"), allow(unused_mut))] -#![cfg_attr(not(feature = "error-context"), allow(clippy::let_and_return))] - -// Std -use std::{ - borrow::Cow, - convert::From, - error, - fmt::{self, Debug, Display, Formatter}, - io::{self}, - result::Result as StdResult, -}; - -// Internal -use crate::builder::StyledStr; -use crate::output::fmt::Colorizer; -use crate::output::fmt::Stream; -use crate::parser::features::suggestions; -use crate::util::FlatMap; -use crate::util::{color::ColorChoice, safe_exit, SUCCESS_CODE, USAGE_CODE}; -use crate::Command; - -#[cfg(feature = "error-context")] -mod context; -mod format; -mod kind; - -pub use format::ErrorFormatter; -pub use format::KindFormatter; -pub use kind::ErrorKind; - -#[cfg(feature = "error-context")] -pub use context::ContextKind; -#[cfg(feature = "error-context")] -pub use context::ContextValue; -#[cfg(feature = "error-context")] -pub use format::RichFormatter; - -#[cfg(not(feature = "error-context"))] -pub use KindFormatter as DefaultFormatter; -#[cfg(feature = "error-context")] -pub use RichFormatter as DefaultFormatter; - -/// Short hand for [`Result`] type -/// -/// [`Result`]: std::result::Result -pub type Result<T, E = Error> = StdResult<T, E>; - -/// Command Line Argument Parser Error -/// -/// See [`Command::error`] to create an error. -/// -/// [`Command::error`]: crate::Command::error -pub struct Error<F: ErrorFormatter = DefaultFormatter> { - inner: Box<ErrorInner>, - phantom: std::marker::PhantomData<F>, -} - -#[derive(Debug)] -struct ErrorInner { - kind: ErrorKind, - #[cfg(feature = "error-context")] - context: FlatMap<ContextKind, ContextValue>, - message: Option<Message>, - source: Option<Box<dyn error::Error + Send + Sync>>, - help_flag: Option<&'static str>, - color_when: ColorChoice, - color_help_when: ColorChoice, - backtrace: Option<Backtrace>, -} - -impl<F: ErrorFormatter> Error<F> { - /// Create an unformatted error - /// - /// This is for you need to pass the error up to - /// a place that has access to the `Command` at which point you can call [`Error::format`]. - /// - /// Prefer [`Command::error`] for generating errors. - /// - /// [`Command::error`]: crate::Command::error - pub fn raw(kind: ErrorKind, message: impl std::fmt::Display) -> Self { - Self::new(kind).set_message(message.to_string()) - } - - /// Format the existing message with the Command's context - #[must_use] - pub fn format(mut self, cmd: &mut Command) -> Self { - cmd._build_self(false); - let usage = cmd.render_usage_(); - if let Some(message) = self.inner.message.as_mut() { - message.format(cmd, usage); - } - self.with_cmd(cmd) - } - - /// Create an error with a pre-defined message - /// - /// See also - /// - [`Error::insert`] - /// - [`Error::with_cmd`] - /// - /// # Example - /// - #[cfg_attr(not(feature = "error-context"), doc = " ```ignore")] - #[cfg_attr(feature = "error-context", doc = " ```")] - /// # use clap::error::ErrorKind; - /// # use clap::error::ContextKind; - /// # use clap::error::ContextValue; - /// - /// let cmd = clap::Command::new("prog"); - /// - /// let mut err = clap::Error::new(ErrorKind::ValueValidation) - /// .with_cmd(&cmd); - /// err.insert(ContextKind::InvalidArg, ContextValue::String("--foo".to_owned())); - /// err.insert(ContextKind::InvalidValue, ContextValue::String("bar".to_owned())); - /// - /// err.print(); - /// ``` - pub fn new(kind: ErrorKind) -> Self { - Self { - inner: Box::new(ErrorInner { - kind, - #[cfg(feature = "error-context")] - context: FlatMap::new(), - message: None, - source: None, - help_flag: None, - color_when: ColorChoice::Never, - color_help_when: ColorChoice::Never, - backtrace: Backtrace::new(), - }), - phantom: Default::default(), - } - } - - /// Apply [`Command`]'s formatting to the error - /// - /// Generally, this is used with [`Error::new`] - pub fn with_cmd(self, cmd: &Command) -> Self { - self.set_color(cmd.get_color()) - .set_colored_help(cmd.color_help()) - .set_help_flag(format::get_help_flag(cmd)) - } - - /// Apply an alternative formatter to the error - /// - /// # Example - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// # use clap::error::KindFormatter; - /// let cmd = Command::new("foo") - /// .arg(Arg::new("input").required(true)); - /// let matches = cmd - /// .try_get_matches_from(["foo", "input.txt"]) - /// .map_err(|e| e.apply::<KindFormatter>()) - /// .unwrap_or_else(|e| e.exit()); - /// ``` - pub fn apply<EF: ErrorFormatter>(self) -> Error<EF> { - Error { - inner: self.inner, - phantom: Default::default(), - } - } - - /// Type of error for programmatic processing - pub fn kind(&self) -> ErrorKind { - self.inner.kind - } - - /// Additional information to further qualify the error - #[cfg(feature = "error-context")] - pub fn context(&self) -> impl Iterator<Item = (ContextKind, &ContextValue)> { - self.inner.context.iter().map(|(k, v)| (*k, v)) - } - - /// Lookup a piece of context - #[inline(never)] - #[cfg(feature = "error-context")] - pub fn get(&self, kind: ContextKind) -> Option<&ContextValue> { - self.inner.context.get(&kind) - } - - /// Insert a piece of context - #[inline(never)] - #[cfg(feature = "error-context")] - pub fn insert(&mut self, kind: ContextKind, value: ContextValue) -> Option<ContextValue> { - self.inner.context.insert(kind, value) - } - - /// Should the message be written to `stdout` or not? - #[inline] - pub fn use_stderr(&self) -> bool { - self.stream() == Stream::Stderr - } - - pub(crate) fn stream(&self) -> Stream { - match self.kind() { - ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => Stream::Stdout, - _ => Stream::Stderr, - } - } - - /// Prints the error and exits. - /// - /// Depending on the error kind, this either prints to `stderr` and exits with a status of `2` - /// or prints to `stdout` and exits with a status of `0`. - pub fn exit(&self) -> ! { - if self.use_stderr() { - // Swallow broken pipe errors - let _ = self.print(); - - safe_exit(USAGE_CODE); - } - - // Swallow broken pipe errors - let _ = self.print(); - safe_exit(SUCCESS_CODE) - } - - /// Prints formatted and colored error to `stdout` or `stderr` according to its error kind - /// - /// # Example - /// ```no_run - /// use clap::Command; - /// - /// match Command::new("Command").try_get_matches() { - /// Ok(matches) => { - /// // do_something - /// }, - /// Err(err) => { - /// err.print().expect("Error writing Error"); - /// // do_something - /// }, - /// }; - /// ``` - pub fn print(&self) -> io::Result<()> { - let style = self.formatted(); - let color_when = if matches!( - self.kind(), - ErrorKind::DisplayHelp | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand, - ) { - self.inner.color_help_when - } else { - self.inner.color_when - }; - let c = Colorizer::new(self.stream(), color_when).with_content(style.into_owned()); - c.print() - } - - /// Render the error message to a [`StyledStr`]. - /// - /// # Example - /// ```no_run - /// use clap::Command; - /// - /// match Command::new("Command").try_get_matches() { - /// Ok(matches) => { - /// // do_something - /// }, - /// Err(err) => { - /// let err = err.render(); - /// println!("{}", err); - /// // do_something - /// }, - /// }; - /// ``` - pub fn render(&self) -> StyledStr { - self.formatted().into_owned() - } - - #[inline(never)] - fn for_app(kind: ErrorKind, cmd: &Command, styled: StyledStr) -> Self { - Self::new(kind).set_message(styled).with_cmd(cmd) - } - - pub(crate) fn set_message(mut self, message: impl Into<Message>) -> Self { - self.inner.message = Some(message.into()); - self - } - - pub(crate) fn set_source(mut self, source: Box<dyn error::Error + Send + Sync>) -> Self { - self.inner.source = Some(source); - self - } - - pub(crate) fn set_color(mut self, color_when: ColorChoice) -> Self { - self.inner.color_when = color_when; - self - } - - pub(crate) fn set_colored_help(mut self, color_help_when: ColorChoice) -> Self { - self.inner.color_help_when = color_help_when; - self - } - - pub(crate) fn set_help_flag(mut self, help_flag: Option<&'static str>) -> Self { - self.inner.help_flag = help_flag; - self - } - - /// Does not verify if `ContextKind` is already present - #[inline(never)] - #[cfg(feature = "error-context")] - pub(crate) fn insert_context_unchecked( - mut self, - kind: ContextKind, - value: ContextValue, - ) -> Self { - self.inner.context.insert_unchecked(kind, value); - self - } - - /// Does not verify if `ContextKind` is already present - #[inline(never)] - #[cfg(feature = "error-context")] - pub(crate) fn extend_context_unchecked<const N: usize>( - mut self, - context: [(ContextKind, ContextValue); N], - ) -> Self { - self.inner.context.extend_unchecked(context); - self - } - - pub(crate) fn display_help(cmd: &Command, styled: StyledStr) -> Self { - Self::for_app(ErrorKind::DisplayHelp, cmd, styled) - } - - pub(crate) fn display_help_error(cmd: &Command, styled: StyledStr) -> Self { - Self::for_app( - ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand, - cmd, - styled, - ) - } - - pub(crate) fn display_version(cmd: &Command, styled: StyledStr) -> Self { - Self::for_app(ErrorKind::DisplayVersion, cmd, styled) - } - - pub(crate) fn argument_conflict( - cmd: &Command, - arg: String, - mut others: Vec<String>, - usage: Option<StyledStr>, - ) -> Self { - let mut err = Self::new(ErrorKind::ArgumentConflict).with_cmd(cmd); - - #[cfg(feature = "error-context")] - { - let others = match others.len() { - 0 => ContextValue::None, - 1 => ContextValue::String(others.pop().unwrap()), - _ => ContextValue::Strings(others), - }; - err = err.extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::PriorArg, others), - ]); - if let Some(usage) = usage { - err = err - .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage)); - } - } - - err - } - - pub(crate) fn empty_value(cmd: &Command, good_vals: &[String], arg: String) -> Self { - Self::invalid_value(cmd, "".to_owned(), good_vals, arg) - } - - pub(crate) fn no_equals(cmd: &Command, arg: String, usage: Option<StyledStr>) -> Self { - let mut err = Self::new(ErrorKind::NoEquals).with_cmd(cmd); - - #[cfg(feature = "error-context")] - { - err = err - .extend_context_unchecked([(ContextKind::InvalidArg, ContextValue::String(arg))]); - if let Some(usage) = usage { - err = err - .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage)); - } - } - - err - } - - pub(crate) fn invalid_value( - cmd: &Command, - bad_val: String, - good_vals: &[String], - arg: String, - ) -> Self { - let suggestion = suggestions::did_you_mean(&bad_val, good_vals.iter()).pop(); - let mut err = Self::new(ErrorKind::InvalidValue).with_cmd(cmd); - - #[cfg(feature = "error-context")] - { - err = err.extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::InvalidValue, ContextValue::String(bad_val)), - ( - ContextKind::ValidValue, - ContextValue::Strings(good_vals.iter().map(|s| (*s).to_owned()).collect()), - ), - ]); - if let Some(suggestion) = suggestion { - err = err.insert_context_unchecked( - ContextKind::SuggestedValue, - ContextValue::String(suggestion), - ); - } - } - - err - } - - pub(crate) fn invalid_subcommand( - cmd: &Command, - subcmd: String, - did_you_mean: Vec<String>, - name: String, - usage: Option<StyledStr>, - ) -> Self { - let mut err = Self::new(ErrorKind::InvalidSubcommand).with_cmd(cmd); - - #[cfg(feature = "error-context")] - { - let mut styled_suggestion = StyledStr::new(); - styled_suggestion.none("to pass '"); - styled_suggestion.warning(&subcmd); - styled_suggestion.none("' as a value, use '"); - styled_suggestion.good(name); - styled_suggestion.good(" -- "); - styled_suggestion.good(&subcmd); - styled_suggestion.none("'"); - - err = err.extend_context_unchecked([ - (ContextKind::InvalidSubcommand, ContextValue::String(subcmd)), - ( - ContextKind::SuggestedSubcommand, - ContextValue::Strings(did_you_mean), - ), - ( - ContextKind::Suggested, - ContextValue::StyledStrs(vec![styled_suggestion]), - ), - ]); - if let Some(usage) = usage { - err = err - .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage)); - } - } - - err - } - - pub(crate) fn unrecognized_subcommand( - cmd: &Command, - subcmd: String, - usage: Option<StyledStr>, - ) -> Self { - let mut err = Self::new(ErrorKind::InvalidSubcommand).with_cmd(cmd); - - #[cfg(feature = "error-context")] - { - err = err.extend_context_unchecked([( - ContextKind::InvalidSubcommand, - ContextValue::String(subcmd), - )]); - if let Some(usage) = usage { - err = err - .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage)); - } - } - - err - } - - pub(crate) fn missing_required_argument( - cmd: &Command, - required: Vec<String>, - usage: Option<StyledStr>, - ) -> Self { - let mut err = Self::new(ErrorKind::MissingRequiredArgument).with_cmd(cmd); - - #[cfg(feature = "error-context")] - { - err = err.extend_context_unchecked([( - ContextKind::InvalidArg, - ContextValue::Strings(required), - )]); - if let Some(usage) = usage { - err = err - .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage)); - } - } - - err - } - - pub(crate) fn missing_subcommand( - cmd: &Command, - parent: String, - available: Vec<String>, - usage: Option<StyledStr>, - ) -> Self { - let mut err = Self::new(ErrorKind::MissingSubcommand).with_cmd(cmd); - - #[cfg(feature = "error-context")] - { - err = err.extend_context_unchecked([ - (ContextKind::InvalidSubcommand, ContextValue::String(parent)), - ( - ContextKind::ValidSubcommand, - ContextValue::Strings(available), - ), - ]); - if let Some(usage) = usage { - err = err - .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage)); - } - } - - err - } - - pub(crate) fn invalid_utf8(cmd: &Command, usage: Option<StyledStr>) -> Self { - let mut err = Self::new(ErrorKind::InvalidUtf8).with_cmd(cmd); - - #[cfg(feature = "error-context")] - { - if let Some(usage) = usage { - err = err - .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage)); - } - } - - err - } - - pub(crate) fn too_many_values( - cmd: &Command, - val: String, - arg: String, - usage: Option<StyledStr>, - ) -> Self { - let mut err = Self::new(ErrorKind::TooManyValues).with_cmd(cmd); - - #[cfg(feature = "error-context")] - { - err = err.extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::InvalidValue, ContextValue::String(val)), - ]); - if let Some(usage) = usage { - err = err - .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage)); - } - } - - err - } - - pub(crate) fn too_few_values( - cmd: &Command, - arg: String, - min_vals: usize, - curr_vals: usize, - usage: Option<StyledStr>, - ) -> Self { - let mut err = Self::new(ErrorKind::TooFewValues).with_cmd(cmd); - - #[cfg(feature = "error-context")] - { - err = err.extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - ( - ContextKind::MinValues, - ContextValue::Number(min_vals as isize), - ), - ( - ContextKind::ActualNumValues, - ContextValue::Number(curr_vals as isize), - ), - ]); - if let Some(usage) = usage { - err = err - .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage)); - } - } - - err - } - - pub(crate) fn value_validation( - arg: String, - val: String, - err: Box<dyn error::Error + Send + Sync>, - ) -> Self { - let mut err = Self::new(ErrorKind::ValueValidation).set_source(err); - - #[cfg(feature = "error-context")] - { - err = err.extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - (ContextKind::InvalidValue, ContextValue::String(val)), - ]); - } - - err - } - - pub(crate) fn wrong_number_of_values( - cmd: &Command, - arg: String, - num_vals: usize, - curr_vals: usize, - usage: Option<StyledStr>, - ) -> Self { - let mut err = Self::new(ErrorKind::WrongNumberOfValues).with_cmd(cmd); - - #[cfg(feature = "error-context")] - { - err = err.extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - ( - ContextKind::ExpectedNumValues, - ContextValue::Number(num_vals as isize), - ), - ( - ContextKind::ActualNumValues, - ContextValue::Number(curr_vals as isize), - ), - ]); - if let Some(usage) = usage { - err = err - .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage)); - } - } - - err - } - - pub(crate) fn unknown_argument( - cmd: &Command, - arg: String, - did_you_mean: Option<(String, Option<String>)>, - suggested_trailing_arg: bool, - usage: Option<StyledStr>, - ) -> Self { - let mut err = Self::new(ErrorKind::UnknownArgument).with_cmd(cmd); - - #[cfg(feature = "error-context")] - { - let mut suggestions = vec![]; - if suggested_trailing_arg { - let mut styled_suggestion = StyledStr::new(); - styled_suggestion.none("to pass '"); - styled_suggestion.warning(&arg); - styled_suggestion.none("' as a value, use '"); - styled_suggestion.good("-- "); - styled_suggestion.good(&arg); - styled_suggestion.none("'"); - suggestions.push(styled_suggestion); - } - - err = err - .extend_context_unchecked([(ContextKind::InvalidArg, ContextValue::String(arg))]); - if let Some(usage) = usage { - err = err - .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage)); - } - match did_you_mean { - Some((flag, Some(sub))) => { - let mut styled_suggestion = StyledStr::new(); - styled_suggestion.none("'"); - styled_suggestion.good(sub); - styled_suggestion.none(" "); - styled_suggestion.good("--"); - styled_suggestion.good(flag); - styled_suggestion.none("' exists"); - suggestions.push(styled_suggestion); - } - Some((flag, None)) => { - err = err.insert_context_unchecked( - ContextKind::SuggestedArg, - ContextValue::String(format!("--{}", flag)), - ); - } - None => {} - } - if !suggestions.is_empty() { - err = err.insert_context_unchecked( - ContextKind::Suggested, - ContextValue::StyledStrs(suggestions), - ); - } - } - - err - } - - pub(crate) fn unnecessary_double_dash( - cmd: &Command, - arg: String, - usage: Option<StyledStr>, - ) -> Self { - let mut err = Self::new(ErrorKind::UnknownArgument).with_cmd(cmd); - - #[cfg(feature = "error-context")] - { - let mut styled_suggestion = StyledStr::new(); - styled_suggestion.none("subcommand '"); - styled_suggestion.good(&arg); - styled_suggestion.none("' exists; to use it, remove the '"); - styled_suggestion.warning("--"); - styled_suggestion.none("' before it"); - - err = err.extend_context_unchecked([ - (ContextKind::InvalidArg, ContextValue::String(arg)), - ( - ContextKind::Suggested, - ContextValue::StyledStrs(vec![styled_suggestion]), - ), - ]); - if let Some(usage) = usage { - err = err - .insert_context_unchecked(ContextKind::Usage, ContextValue::StyledStr(usage)); - } - } - - err - } - - fn formatted(&self) -> Cow<'_, StyledStr> { - if let Some(message) = self.inner.message.as_ref() { - message.formatted() - } else { - let styled = F::format_error(self); - Cow::Owned(styled) - } - } -} - -impl<F: ErrorFormatter> From<io::Error> for Error<F> { - fn from(e: io::Error) -> Self { - Error::raw(ErrorKind::Io, e) - } -} - -impl<F: ErrorFormatter> From<fmt::Error> for Error<F> { - fn from(e: fmt::Error) -> Self { - Error::raw(ErrorKind::Format, e) - } -} - -impl<F: ErrorFormatter> std::fmt::Debug for Error<F> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { - self.inner.fmt(f) - } -} - -impl<F: ErrorFormatter> error::Error for Error<F> { - #[allow(trivial_casts)] - fn source(&self) -> Option<&(dyn error::Error + 'static)> { - self.inner.source.as_ref().map(|e| e.as_ref() as _) - } -} - -impl<F: ErrorFormatter> Display for Error<F> { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - // Assuming `self.message` already has a trailing newline, from `try_help` or similar - ok!(write!(f, "{}", self.formatted())); - if let Some(backtrace) = self.inner.backtrace.as_ref() { - ok!(writeln!(f)); - ok!(writeln!(f, "Backtrace:")); - ok!(writeln!(f, "{}", backtrace)); - } - Ok(()) - } -} - -#[derive(Clone, Debug)] -pub(crate) enum Message { - Raw(String), - Formatted(StyledStr), -} - -impl Message { - fn format(&mut self, cmd: &Command, usage: Option<StyledStr>) { - match self { - Message::Raw(s) => { - let mut message = String::new(); - std::mem::swap(s, &mut message); - - let styled = format::format_error_message(&message, Some(cmd), usage); - - *self = Self::Formatted(styled); - } - Message::Formatted(_) => {} - } - } - - fn formatted(&self) -> Cow<StyledStr> { - match self { - Message::Raw(s) => { - let styled = format::format_error_message(s, None, None); - - Cow::Owned(styled) - } - Message::Formatted(s) => Cow::Borrowed(s), - } - } -} - -impl From<String> for Message { - fn from(inner: String) -> Self { - Self::Raw(inner) - } -} - -impl From<StyledStr> for Message { - fn from(inner: StyledStr) -> Self { - Self::Formatted(inner) - } -} - -#[cfg(feature = "debug")] -#[derive(Debug)] -struct Backtrace(backtrace::Backtrace); - -#[cfg(feature = "debug")] -impl Backtrace { - fn new() -> Option<Self> { - Some(Self(backtrace::Backtrace::new())) - } -} - -#[cfg(feature = "debug")] -impl Display for Backtrace { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - // `backtrace::Backtrace` uses `Debug` instead of `Display` - write!(f, "{:?}", self.0) - } -} - -#[cfg(not(feature = "debug"))] -#[derive(Debug)] -struct Backtrace; - -#[cfg(not(feature = "debug"))] -impl Backtrace { - fn new() -> Option<Self> { - None - } -} - -#[cfg(not(feature = "debug"))] -impl Display for Backtrace { - fn fmt(&self, _: &mut Formatter) -> fmt::Result { - Ok(()) - } -} - -#[test] -fn check_auto_traits() { - static_assertions::assert_impl_all!(Error: Send, Sync, Unpin); -} diff --git a/vendor/clap/src/lib.rs b/vendor/clap/src/lib.rs index ab2d9d475..8e6d1fd6e 100644 --- a/vendor/clap/src/lib.rs +++ b/vendor/clap/src/lib.rs @@ -41,9 +41,10 @@ //! *(See also [feature flag reference][_features])* //! //! Then define your CLI in `main.rs`: -#![cfg_attr(not(feature = "derive"), doc = " ```ignore")] -#![cfg_attr(feature = "derive", doc = " ```no_run")] +//! ```rust +//! # #[cfg(feature = "derive")] { #![doc = include_str!("../examples/demo.rs")] +//! # } //! ``` //! //! And try it out: @@ -94,26 +95,7 @@ // Breaks up parallelism that clarifies intent #![allow(clippy::collapsible_else_if)] -#[cfg(not(feature = "std"))] -compile_error!("`std` feature is currently required to build `clap`"); - -pub use crate::builder::ArgAction; -pub use crate::builder::Command; -pub use crate::builder::ValueHint; -pub use crate::builder::{Arg, ArgGroup}; -pub use crate::parser::ArgMatches; -pub use crate::util::color::ColorChoice; -pub use crate::util::Id; - -/// Command Line Argument Parser Error -/// -/// See [`Command::error`] to create an error. -/// -/// [`Command::error`]: crate::Command::error -pub type Error = crate::error::Error<crate::error::DefaultFormatter>; - -pub use crate::derive::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum}; - +pub use clap_builder::*; #[cfg(feature = "derive")] #[doc(hidden)] pub use clap_derive::{self, *}; @@ -130,25 +112,8 @@ pub mod _features; pub mod _tutorial; #[doc(hidden)] -pub mod __macro_refs { - #[cfg(any(feature = "derive", feature = "cargo"))] +#[cfg(feature = "derive")] +pub mod __derive_refs { #[doc(hidden)] pub use once_cell; } - -#[macro_use] -#[allow(missing_docs)] -mod macros; - -mod derive; - -pub mod builder; -pub mod error; -pub mod parser; - -mod mkeymap; -mod output; -mod util; - -const INTERNAL_ERROR_MSG: &str = "Fatal internal error. Please consider filing a bug \ - report at https://github.com/clap-rs/clap/issues"; diff --git a/vendor/clap/src/macros.rs b/vendor/clap/src/macros.rs deleted file mode 100644 index 9b4949a57..000000000 --- a/vendor/clap/src/macros.rs +++ /dev/null @@ -1,676 +0,0 @@ -/// Allows you to pull the version from your Cargo.toml at compile time as -/// `MAJOR.MINOR.PATCH_PKGVERSION_PRE` -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::Command; -/// # fn main() { -/// let m = Command::new("cmd") -/// .version(crate_version!()) -/// .get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! crate_version { - () => { - env!("CARGO_PKG_VERSION") - }; -} - -/// Allows you to pull the authors for the command from your Cargo.toml at -/// compile time in the form: -/// `"author1 lastname <author1@example.com>:author2 lastname <author2@example.com>"` -/// -/// You can replace the colons with a custom separator by supplying a -/// replacement string, so, for example, -/// `crate_authors!(",\n")` would become -/// `"author1 lastname <author1@example.com>,\nauthor2 lastname <author2@example.com>,\nauthor3 lastname <author3@example.com>"` -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::Command; -/// # fn main() { -/// let m = Command::new("cmd") -/// .author(crate_authors!("\n")) -/// .get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! crate_authors { - ($sep:expr) => {{ - static authors: &str = env!("CARGO_PKG_AUTHORS"); - if authors.contains(':') { - static CACHED: clap::__macro_refs::once_cell::sync::Lazy<String> = - clap::__macro_refs::once_cell::sync::Lazy::new(|| authors.replace(':', $sep)); - let s: &'static str = &*CACHED; - s - } else { - authors - } - }}; - () => { - env!("CARGO_PKG_AUTHORS") - }; -} - -/// Allows you to pull the description from your Cargo.toml at compile time. -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::Command; -/// # fn main() { -/// let m = Command::new("cmd") -/// .about(crate_description!()) -/// .get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! crate_description { - () => { - env!("CARGO_PKG_DESCRIPTION") - }; -} - -/// Allows you to pull the name from your Cargo.toml at compile time. -/// -/// **NOTE:** This macro extracts the name from an environment variable `CARGO_PKG_NAME`. -/// When the crate name is set to something different from the package name, -/// use environment variables `CARGO_CRATE_NAME` or `CARGO_BIN_NAME`. -/// See [the Cargo Book](https://doc.rust-lang.org/cargo/reference/environment-variables.html) -/// for more information. -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::Command; -/// # fn main() { -/// let m = Command::new(crate_name!()) -/// .get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! crate_name { - () => { - env!("CARGO_PKG_NAME") - }; -} - -/// Allows you to build the `Command` instance from your Cargo.toml at compile time. -/// -/// **NOTE:** Changing the values in your `Cargo.toml` does not trigger a re-build automatically, -/// and therefore won't change the generated output until you recompile. -/// -/// In some cases you can "trick" the compiler into triggering a rebuild when your -/// `Cargo.toml` is changed by including this in your `src/main.rs` file -/// `include_str!("../Cargo.toml");` -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # fn main() { -/// let m = command!().get_matches(); -/// # } -/// ``` -#[cfg(feature = "cargo")] -#[macro_export] -macro_rules! command { - () => {{ - $crate::command!($crate::crate_name!()) - }}; - ($name:expr) => {{ - let mut cmd = $crate::Command::new($name).version($crate::crate_version!()); - - let author = $crate::crate_authors!(); - if !author.is_empty() { - cmd = cmd.author(author) - } - - let about = $crate::crate_description!(); - if !about.is_empty() { - cmd = cmd.about(about) - } - - cmd - }}; -} - -/// Requires `cargo` feature flag to be enabled. -#[cfg(not(feature = "cargo"))] -#[macro_export] -macro_rules! command { - () => {{ - compile_error!("`cargo` feature flag is required"); - }}; - ($name:expr) => {{ - compile_error!("`cargo` feature flag is required"); - }}; -} - -#[doc(hidden)] -#[macro_export] -macro_rules! arg_impl { - ( @string $val:ident ) => { - stringify!($val) - }; - ( @string $val:literal ) => {{ - let ident_or_string_literal: &str = $val; - ident_or_string_literal - }}; - ( @string $val:tt ) => { - ::std::compile_error!("Only identifiers or string literals supported"); - }; - ( @string ) => { - None - }; - - ( @char $val:ident ) => {{ - let ident_or_char_literal = stringify!($val); - debug_assert_eq!( - ident_or_char_literal.len(), - 1, - "Single-letter identifier expected, got {}", - ident_or_char_literal - ); - ident_or_char_literal.chars().next().unwrap() - }}; - ( @char $val:literal ) => {{ - let ident_or_char_literal: char = $val; - ident_or_char_literal - }}; - ( @char ) => {{ - None - }}; - - ( - @arg - ($arg:expr) - --$long:ident - $($tail:tt)* - ) => {{ - debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); - debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`"); - - let mut arg = $arg; - let long = $crate::arg_impl! { @string $long }; - if arg.get_id() == "" { - arg = arg.id(long); - } - let action = $crate::ArgAction::SetTrue; - let arg = arg - .long(long) - .action(action); - let arg = $crate::arg_impl! { - @arg (arg) $($tail)* - }; - arg - }}; - ( - @arg - ($arg:expr) - --$long:literal - $($tail:tt)* - ) => {{ - debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); - debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`"); - - let mut arg = $arg; - let long = $crate::arg_impl! { @string $long }; - if arg.get_id() == "" { - arg = arg.id(long); - } - let action = $crate::ArgAction::SetTrue; - let arg = arg - .long(long) - .action(action); - let arg = $crate::arg_impl! { - @arg (arg) $($tail)* - }; - arg - }}; - ( - @arg - ($arg:expr) - -$short:ident - $($tail:tt)* - ) => {{ - debug_assert_eq!($arg.get_long(), None, "Short flags should precede long flags"); - debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); - debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`"); - - let action = $crate::ArgAction::SetTrue; - let arg = $arg - .short($crate::arg_impl! { @char $short }) - .action(action); - let arg = $crate::arg_impl! { - @arg (arg) $($tail)* - }; - arg - }}; - ( - @arg - ($arg:expr) - -$short:literal - $($tail:tt)* - ) => {{ - debug_assert_eq!($arg.get_long(), None, "Short flags should precede long flags"); - debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); - debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`"); - - let action = $crate::ArgAction::SetTrue; - let arg = $arg - .short($crate::arg_impl! { @char $short }) - .action(action); - let arg = $crate::arg_impl! { - @arg (arg) $($tail)* - }; - arg - }}; - ( - @arg - ($arg:expr) - <$value_name:ident> - $($tail:tt)* - ) => {{ - debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`"); - debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); - - let mut arg = $arg; - - if arg.get_long().is_none() && arg.get_short().is_none() { - arg = arg.required(true); - } - - let value_name = $crate::arg_impl! { @string $value_name }; - if arg.get_id() == "" { - arg = arg.id(value_name); - } - let arg = arg - .value_name(value_name) - .action($crate::ArgAction::Set); - let arg = $crate::arg_impl! { - @arg (arg) $($tail)* - }; - arg - }}; - ( - @arg - ($arg:expr) - <$value_name:literal> - $($tail:tt)* - ) => {{ - debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`"); - debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); - - let mut arg = $arg; - - if arg.get_long().is_none() && arg.get_short().is_none() { - arg = arg.required(true); - } - - let value_name = $crate::arg_impl! { @string $value_name }; - if arg.get_id() == "" { - arg = arg.id(value_name); - } - let arg = arg - .value_name(value_name) - .action($crate::ArgAction::Set); - let arg = $crate::arg_impl! { - @arg (arg) $($tail)* - }; - arg - }}; - ( - @arg - ($arg:expr) - [$value_name:ident] - $($tail:tt)* - ) => {{ - debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`"); - debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); - - let mut arg = $arg; - - if arg.get_long().is_none() && arg.get_short().is_none() { - arg = arg.required(false); - } else { - arg = arg.num_args(0..=1); - } - - let value_name = $crate::arg_impl! { @string $value_name }; - if arg.get_id() == "" { - arg = arg.id(value_name); - } - let arg = arg - .value_name(value_name) - .action($crate::ArgAction::Set); - let arg = $crate::arg_impl! { - @arg (arg) $($tail)* - }; - arg - }}; - ( - @arg - ($arg:expr) - [$value_name:literal] - $($tail:tt)* - ) => {{ - debug_assert!(!matches!($arg.get_action(), $crate::ArgAction::Append), "Flags should precede `...`"); - debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); - - let mut arg = $arg; - - if arg.get_long().is_none() && arg.get_short().is_none() { - arg = arg.required(false); - } else { - arg = arg.num_args(0..=1); - } - - let value_name = $crate::arg_impl! { @string $value_name }; - if arg.get_id() == "" { - arg = arg.id(value_name); - } - let arg = arg - .value_name(value_name) - .action($crate::ArgAction::Set); - let arg = $crate::arg_impl! { - @arg (arg) $($tail)* - }; - arg - }}; - ( - @arg - ($arg:expr) - ... - $($tail:tt)* - ) => {{ - let arg = match $arg.get_action() { - $crate::ArgAction::Set => { - if $arg.get_long().is_none() && $arg.get_short().is_none() { - $arg.num_args(1..) - // Allow collecting arguments interleaved with flags - .action($crate::ArgAction::Append) - } else { - $arg.action($crate::ArgAction::Append) - } - }, - $crate::ArgAction::SetTrue | $crate::ArgAction::Help | $crate::ArgAction::Version => { - $arg.action($crate::ArgAction::Count) - } - action => { - panic!("Unexpected action {:?}", action) - } - }; - let arg = $crate::arg_impl! { - @arg (arg) $($tail)* - }; - arg - }}; - ( - @arg - ($arg:expr) - $help:literal - ) => {{ - $arg.help($help) - }}; - ( - @arg - ($arg:expr) - ) => {{ - $arg - }}; -} - -/// Create an [`Arg`] from a usage string. -/// -/// Allows creation of basic settings for the [`Arg`]. -/// -/// **NOTE**: Not all settings may be set using the usage string method. Some properties are -/// only available via the builder pattern. -/// -/// # Syntax -/// -/// Usage strings typically following the form: -/// -/// ```notrust -/// [explicit name] [short] [long] [value names] [...] [help string] -/// ``` -/// -/// ### Explicit Name -/// -/// The name may be either a bare-word or a string, followed by a `:`, like `name:` or -/// `"name":`. -/// -/// *Note:* This is an optional field, if it's omitted the argument will use one of the additional -/// fields as the name using the following priority order: -/// -/// 1. Explicit Name -/// 2. Long -/// 3. Value Name -/// -/// See [`Arg::id`][crate::Arg::id]. -/// -/// ### Short -/// -/// A short flag is a `-` followed by either a bare-character or quoted character, like `-f` or -/// `-'f'`. -/// -/// See [`Arg::short`][crate::Arg::short]. -/// -/// ### Long -/// -/// A long flag is a `--` followed by either a bare-word or a string, like `--foo` or -/// `--"foo"`. -/// -/// **NOTE:** Dashes in the long name (e.g. `--foo-bar`) is not supported and quoting is required -/// (e.g. `--"foo-bar"`). -/// -/// See [`Arg::long`][crate::Arg::long]. -/// -/// ### Values (Value Notation) -/// -/// This is set by placing bare-word between: -/// - `[]` like `[FOO]` -/// - Positional argument: optional -/// - Named argument: optional value -/// - `<>` like `<FOO>`: required -/// -/// See [`Arg::value_name`][crate::Arg::value_name]. -/// -/// ### `...` -/// -/// `...` (three consecutive dots/periods) specifies that this argument may occur multiple -/// times (not to be confused with multiple values per occurrence). -/// -/// See [`ArgAction::Count`][crate::ArgAction::Count] and [`ArgAction::Append`][crate::ArgAction::Append]. -/// -/// ### Help String -/// -/// The help string is denoted between a pair of double quotes `""` and may contain any -/// characters. -/// -/// # Examples -/// -/// ```rust -/// # use clap::{Command, Arg, arg}; -/// let cmd = Command::new("prog") -/// .args(&[ -/// arg!(--config <FILE> "a required file for the configuration and no short"), -/// arg!(-d --debug ... "turns on debugging information and allows multiples"), -/// arg!([input] "an optional input file to use") -/// ]); -/// -/// let m = cmd.try_get_matches_from(["prog", "--config", "file.toml"]).unwrap(); -/// assert_eq!(m.get_one::<String>("config").unwrap(), "file.toml"); -/// assert_eq!(*m.get_one::<u8>("debug").unwrap(), 0); -/// assert_eq!(m.get_one::<String>("input"), None); -/// ``` -/// [`Arg`]: crate::Arg -#[macro_export] -macro_rules! arg { - ( $name:ident: $($tail:tt)+ ) => {{ - let arg = $crate::Arg::new($crate::arg_impl! { @string $name }); - let arg = $crate::arg_impl! { - @arg (arg) $($tail)+ - }; - arg - }}; - ( $($tail:tt)+ ) => {{ - let arg = $crate::Arg::default(); - let arg = $crate::arg_impl! { - @arg (arg) $($tail)+ - }; - debug_assert_ne!(arg.get_id(), "", "Without a value or long flag, the `name:` prefix is required"); - arg - }}; -} - -macro_rules! impl_settings { - ($settings:ident, $flags:ident, - $( - $(#[$inner:ident $($args:tt)*])* - $setting:ident => $flag:path - ),+ - ) => { - impl $flags { - #[allow(dead_code)] - pub(crate) fn empty() -> Self { - $flags(Flags::empty()) - } - - #[allow(dead_code)] - pub(crate) fn insert(&mut self, rhs: Self) { - self.0.insert(rhs.0); - } - - #[allow(dead_code)] - pub(crate) fn remove(&mut self, rhs: Self) { - self.0.remove(rhs.0); - } - - #[allow(dead_code)] - pub(crate) fn set(&mut self, s: $settings) { - match s { - $( - $(#[$inner $($args)*])* - $settings::$setting => self.0.insert($flag), - )* - } - } - - #[allow(dead_code)] - pub(crate) fn unset(&mut self, s: $settings) { - match s { - $( - $(#[$inner $($args)*])* - $settings::$setting => self.0.remove($flag), - )* - } - } - - #[allow(dead_code)] - pub(crate) fn is_set(&self, s: $settings) -> bool { - match s { - $( - $(#[$inner $($args)*])* - $settings::$setting => self.0.contains($flag), - )* - } - } - } - - impl BitOr for $flags { - type Output = Self; - - fn bitor(mut self, rhs: Self) -> Self::Output { - self.0.insert(rhs.0); - self - } - } - - impl From<$settings> for $flags { - fn from(setting: $settings) -> Self { - let mut flags = $flags::empty(); - flags.set(setting); - flags - } - } - - impl BitOr<$settings> for $flags { - type Output = Self; - - fn bitor(mut self, rhs: $settings) -> Self::Output { - self.set(rhs); - self - } - } - - impl BitOr for $settings { - type Output = $flags; - - fn bitor(self, rhs: Self) -> Self::Output { - let mut flags = $flags::empty(); - flags.set(self); - flags.set(rhs); - flags - } - } - } -} - -#[cfg(feature = "debug")] -macro_rules! debug { - ($($arg:tt)*) => ({ - let prefix = format!("[{:>w$}] \t", module_path!(), w = 28); - let body = format!($($arg)*); - let mut styled = $crate::builder::StyledStr::new(); - styled.hint(prefix); - styled.hint(body); - styled.none("\n"); - let color = $crate::output::fmt::Colorizer::new($crate::output::fmt::Stream::Stderr, $crate::ColorChoice::Auto).with_content(styled); - let _ = color.print(); - }) -} - -#[cfg(not(feature = "debug"))] -macro_rules! debug { - ($($arg:tt)*) => {}; -} - -macro_rules! ok { - ($expr:expr) => { - match $expr { - Ok(val) => val, - Err(err) => { - return Err(err); - } - } - }; -} - -macro_rules! some { - ($expr:expr) => { - match $expr { - Some(val) => val, - None => { - return None; - } - } - }; -} diff --git a/vendor/clap/src/mkeymap.rs b/vendor/clap/src/mkeymap.rs deleted file mode 100644 index a54fae455..000000000 --- a/vendor/clap/src/mkeymap.rs +++ /dev/null @@ -1,177 +0,0 @@ -use std::iter::Iterator; -use std::ops::Index; - -use crate::builder::OsStr; -use crate::Arg; -use crate::INTERNAL_ERROR_MSG; - -#[derive(PartialEq, Eq, Debug, Clone)] -pub(crate) struct Key { - key: KeyType, - index: usize, -} - -#[derive(Default, PartialEq, Eq, Debug, Clone)] -pub(crate) struct MKeyMap { - /// All of the arguments. - args: Vec<Arg>, - - // Cache part: - /// Will be set after `_build()`. - keys: Vec<Key>, -} - -#[derive(Debug, PartialEq, Eq, Hash, Clone)] -pub(crate) enum KeyType { - Short(char), - Long(OsStr), - Position(usize), -} - -impl KeyType { - pub(crate) fn is_position(&self) -> bool { - matches!(self, KeyType::Position(_)) - } -} - -impl PartialEq<usize> for KeyType { - fn eq(&self, rhs: &usize) -> bool { - match self { - KeyType::Position(x) => x == rhs, - _ => false, - } - } -} - -impl PartialEq<&str> for KeyType { - fn eq(&self, rhs: &&str) -> bool { - match self { - KeyType::Long(l) => l == rhs, - _ => false, - } - } -} - -impl PartialEq<str> for KeyType { - fn eq(&self, rhs: &str) -> bool { - match self { - KeyType::Long(l) => l == rhs, - _ => false, - } - } -} - -impl PartialEq<OsStr> for KeyType { - fn eq(&self, rhs: &OsStr) -> bool { - match self { - KeyType::Long(l) => l == rhs, - _ => false, - } - } -} - -impl PartialEq<char> for KeyType { - fn eq(&self, rhs: &char) -> bool { - match self { - KeyType::Short(c) => c == rhs, - _ => false, - } - } -} - -impl MKeyMap { - /// If any arg has corresponding key in this map, we can search the key with - /// u64(for positional argument), char(for short flag), &str and OsString - /// (for long flag) - pub(crate) fn contains<K>(&self, key: K) -> bool - where - KeyType: PartialEq<K>, - { - self.keys.iter().any(|x| x.key == key) - } - - /// Push an argument in the map. - pub(crate) fn push(&mut self, new_arg: Arg) { - self.args.push(new_arg); - } - - /// Find the arg have corresponding key in this map, we can search the key - /// with u64(for positional argument), char(for short flag), &str and - /// OsString (for long flag) - pub(crate) fn get<K: ?Sized>(&self, key: &K) -> Option<&Arg> - where - KeyType: PartialEq<K>, - { - self.keys - .iter() - .find(|k| &k.key == key) - .map(|k| &self.args[k.index]) - } - - /// Return iterators of all keys. - pub(crate) fn keys(&self) -> impl Iterator<Item = &KeyType> { - self.keys.iter().map(|x| &x.key) - } - - /// Return iterators of all args. - pub(crate) fn args(&self) -> impl Iterator<Item = &Arg> { - self.args.iter() - } - - /// Return mutable iterators of all args. - pub(crate) fn args_mut(&mut self) -> impl Iterator<Item = &mut Arg> { - self.args.iter_mut() - } - - /// We need a lazy build here since some we may change args after creating - /// the map, you can checkout who uses `args_mut`. - pub(crate) fn _build(&mut self) { - for (i, arg) in self.args.iter().enumerate() { - append_keys(&mut self.keys, arg, i); - } - } - - /// Remove an arg in the graph by Id, usually used by `mut_arg`. Return - /// `Some(arg)` if removed. - pub(crate) fn remove_by_name(&mut self, name: &str) -> Option<Arg> { - self.args - .iter() - .position(|arg| arg.id == name) - // since it's a cold function, using this wouldn't hurt much - .map(|i| self.args.remove(i)) - } -} - -impl Index<&'_ KeyType> for MKeyMap { - type Output = Arg; - - fn index(&self, key: &KeyType) -> &Self::Output { - self.get(key).expect(INTERNAL_ERROR_MSG) - } -} - -/// Generate key types for an specific Arg. -fn append_keys(keys: &mut Vec<Key>, arg: &Arg, index: usize) { - if let Some(pos_index) = arg.index { - let key = KeyType::Position(pos_index); - keys.push(Key { key, index }); - } else { - if let Some(short) = arg.short { - let key = KeyType::Short(short); - keys.push(Key { key, index }); - } - if let Some(long) = arg.long.clone() { - let key = KeyType::Long(long.into()); - keys.push(Key { key, index }); - } - - for (short, _) in arg.short_aliases.iter() { - let key = KeyType::Short(*short); - keys.push(Key { key, index }); - } - for (long, _) in arg.aliases.iter() { - let key = KeyType::Long(long.into()); - keys.push(Key { key, index }); - } - } -} diff --git a/vendor/clap/src/output/fmt.rs b/vendor/clap/src/output/fmt.rs deleted file mode 100644 index b5d0153f1..000000000 --- a/vendor/clap/src/output/fmt.rs +++ /dev/null @@ -1,90 +0,0 @@ -use crate::builder::StyledStr; -use crate::util::color::ColorChoice; - -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub(crate) enum Stream { - Stdout, - Stderr, -} - -#[derive(Clone, Debug)] -pub(crate) struct Colorizer { - stream: Stream, - #[allow(unused)] - color_when: ColorChoice, - content: StyledStr, -} - -impl Colorizer { - pub(crate) fn new(stream: Stream, color_when: ColorChoice) -> Self { - Colorizer { - stream, - color_when, - content: Default::default(), - } - } - - pub(crate) fn with_content(mut self, content: StyledStr) -> Self { - self.content = content; - self - } -} - -/// Printing methods. -impl Colorizer { - #[cfg(feature = "color")] - pub(crate) fn print(&self) -> std::io::Result<()> { - use termcolor::{BufferWriter, ColorChoice as DepColorChoice}; - - let color_when = match self.color_when { - ColorChoice::Always => DepColorChoice::Always, - ColorChoice::Auto if is_a_tty(self.stream) => DepColorChoice::Auto, - _ => DepColorChoice::Never, - }; - - let writer = match self.stream { - Stream::Stderr => BufferWriter::stderr(color_when), - Stream::Stdout => BufferWriter::stdout(color_when), - }; - - let mut buffer = writer.buffer(); - ok!(self.content.write_colored(&mut buffer)); - writer.print(&buffer) - } - - #[cfg(not(feature = "color"))] - pub(crate) fn print(&self) -> std::io::Result<()> { - use std::io::Write; - - // [e]println can't be used here because it panics - // if something went wrong. We don't want that. - match self.stream { - Stream::Stdout => { - let stdout = std::io::stdout(); - let mut stdout = stdout.lock(); - write!(stdout, "{}", self) - } - Stream::Stderr => { - let stderr = std::io::stderr(); - let mut stderr = stderr.lock(); - write!(stderr, "{}", self) - } - } - } -} - -/// Color-unaware printing. Never uses coloring. -impl std::fmt::Display for Colorizer { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.content.fmt(f) - } -} - -#[cfg(feature = "color")] -fn is_a_tty(stream: Stream) -> bool { - use is_terminal::IsTerminal; - match stream { - Stream::Stdout => std::io::stdout().is_terminal(), - Stream::Stderr => std::io::stderr().is_terminal(), - } -} diff --git a/vendor/clap/src/output/help.rs b/vendor/clap/src/output/help.rs deleted file mode 100644 index 4e4fdbfdc..000000000 --- a/vendor/clap/src/output/help.rs +++ /dev/null @@ -1,43 +0,0 @@ -#![cfg_attr(not(feature = "help"), allow(unused_variables))] - -// Internal -use crate::builder::Command; -use crate::builder::StyledStr; -use crate::output::Usage; - -/// Writes the parser help to the wrapped stream. -pub(crate) fn write_help(writer: &mut StyledStr, cmd: &Command, usage: &Usage<'_>, use_long: bool) { - debug!("write_help"); - - if let Some(h) = cmd.get_override_help() { - writer.extend(h.iter()); - } else { - #[cfg(feature = "help")] - { - use super::AutoHelp; - use super::HelpTemplate; - if let Some(tmpl) = cmd.get_help_template() { - for (style, content) in tmpl.iter() { - if style.is_none() { - HelpTemplate::new(writer, cmd, usage, use_long) - .write_templated_help(content); - } else { - writer.stylize(style, content); - } - } - } else { - AutoHelp::new(writer, cmd, usage, use_long).write_help(); - } - } - - #[cfg(not(feature = "help"))] - { - debug!("write_help: no help, `Command::override_help` and `help` is missing"); - } - } - - // Remove any extra lines caused by book keeping - writer.trim(); - // Ensure there is still a trailing newline - writer.none("\n"); -} diff --git a/vendor/clap/src/output/help_template.rs b/vendor/clap/src/output/help_template.rs deleted file mode 100644 index 6fe9db1b4..000000000 --- a/vendor/clap/src/output/help_template.rs +++ /dev/null @@ -1,1065 +0,0 @@ -// Std -use std::borrow::Cow; -use std::cmp; -use std::usize; - -// Internal -use crate::builder::PossibleValue; -use crate::builder::Str; -use crate::builder::StyledStr; -use crate::builder::{Arg, Command}; -use crate::output::display_width; -use crate::output::wrap; -use crate::output::Usage; -use crate::output::TAB; -use crate::output::TAB_WIDTH; -use crate::util::FlatSet; - -/// `clap` auto-generated help writer -pub(crate) struct AutoHelp<'cmd, 'writer> { - template: HelpTemplate<'cmd, 'writer>, -} - -// Public Functions -impl<'cmd, 'writer> AutoHelp<'cmd, 'writer> { - /// Create a new `HelpTemplate` instance. - pub(crate) fn new( - writer: &'writer mut StyledStr, - cmd: &'cmd Command, - usage: &'cmd Usage<'cmd>, - use_long: bool, - ) -> Self { - Self { - template: HelpTemplate::new(writer, cmd, usage, use_long), - } - } - - pub(crate) fn write_help(&mut self) { - let pos = self - .template - .cmd - .get_positionals() - .any(|arg| should_show_arg(self.template.use_long, arg)); - let non_pos = self - .template - .cmd - .get_non_positionals() - .any(|arg| should_show_arg(self.template.use_long, arg)); - let subcmds = self.template.cmd.has_visible_subcommands(); - - let template = if non_pos || pos || subcmds { - DEFAULT_TEMPLATE - } else { - DEFAULT_NO_ARGS_TEMPLATE - }; - self.template.write_templated_help(template); - } -} - -const DEFAULT_TEMPLATE: &str = "\ -{before-help}{about-with-newline} -{usage-heading} {usage} - -{all-args}{after-help}\ - "; - -const DEFAULT_NO_ARGS_TEMPLATE: &str = "\ -{before-help}{about-with-newline} -{usage-heading} {usage}{after-help}\ - "; - -/// `clap` HelpTemplate Writer. -/// -/// Wraps a writer stream providing different methods to generate help for `clap` objects. -pub(crate) struct HelpTemplate<'cmd, 'writer> { - writer: &'writer mut StyledStr, - cmd: &'cmd Command, - usage: &'cmd Usage<'cmd>, - next_line_help: bool, - term_w: usize, - use_long: bool, -} - -// Public Functions -impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> { - /// Create a new `HelpTemplate` instance. - pub(crate) fn new( - writer: &'writer mut StyledStr, - cmd: &'cmd Command, - usage: &'cmd Usage<'cmd>, - use_long: bool, - ) -> Self { - debug!( - "HelpTemplate::new cmd={}, use_long={}", - cmd.get_name(), - use_long - ); - let term_w = match cmd.get_term_width() { - Some(0) => usize::MAX, - Some(w) => w, - None => { - let (current_width, _h) = dimensions(); - let current_width = current_width.unwrap_or(100); - let max_width = match cmd.get_max_term_width() { - None | Some(0) => usize::MAX, - Some(mw) => mw, - }; - cmp::min(current_width, max_width) - } - }; - let next_line_help = cmd.is_next_line_help_set(); - - HelpTemplate { - writer, - cmd, - usage, - next_line_help, - term_w, - use_long, - } - } - - /// Write help to stream for the parser in the format defined by the template. - /// - /// For details about the template language see [`Command::help_template`]. - /// - /// [`Command::help_template`]: Command::help_template() - pub(crate) fn write_templated_help(&mut self, template: &str) { - debug!("HelpTemplate::write_templated_help"); - - let mut parts = template.split('{'); - if let Some(first) = parts.next() { - self.none(first); - } - for part in parts { - if let Some((tag, rest)) = part.split_once('}') { - match tag { - "name" => { - self.write_display_name(); - } - #[cfg(not(feature = "unstable-v5"))] - "bin" => { - self.write_bin_name(); - } - "version" => { - self.write_version(); - } - "author" => { - self.write_author(false, false); - } - "author-with-newline" => { - self.write_author(false, true); - } - "author-section" => { - self.write_author(true, true); - } - "about" => { - self.write_about(false, false); - } - "about-with-newline" => { - self.write_about(false, true); - } - "about-section" => { - self.write_about(true, true); - } - "usage-heading" => { - self.header("Usage:"); - } - "usage" => { - self.writer.extend( - self.usage - .create_usage_no_title(&[]) - .unwrap_or_default() - .into_iter(), - ); - } - "all-args" => { - self.write_all_args(); - } - "options" => { - // Include even those with a heading as we don't have a good way of - // handling help_heading in the template. - self.write_args( - &self.cmd.get_non_positionals().collect::<Vec<_>>(), - "options", - option_sort_key, - ); - } - "positionals" => { - self.write_args( - &self.cmd.get_positionals().collect::<Vec<_>>(), - "positionals", - positional_sort_key, - ); - } - "subcommands" => { - self.write_subcommands(self.cmd); - } - "tab" => { - self.none(TAB); - } - "after-help" => { - self.write_after_help(); - } - "before-help" => { - self.write_before_help(); - } - _ => { - self.none("{"); - self.none(tag); - self.none("}"); - } - } - self.none(rest); - } - } - } -} - -/// Basic template methods -impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> { - /// Writes binary name of a Parser Object to the wrapped stream. - fn write_display_name(&mut self) { - debug!("HelpTemplate::write_display_name"); - - let display_name = wrap( - &self - .cmd - .get_display_name() - .unwrap_or_else(|| self.cmd.get_name()) - .replace("{n}", "\n"), - self.term_w, - ); - self.none(&display_name); - } - - /// Writes binary name of a Parser Object to the wrapped stream. - fn write_bin_name(&mut self) { - debug!("HelpTemplate::write_bin_name"); - - let bin_name = if let Some(bn) = self.cmd.get_bin_name() { - if bn.contains(' ') { - // In case we're dealing with subcommands i.e. git mv is translated to git-mv - bn.replace(' ', "-") - } else { - wrap(&self.cmd.get_name().replace("{n}", "\n"), self.term_w) - } - } else { - wrap(&self.cmd.get_name().replace("{n}", "\n"), self.term_w) - }; - self.none(&bin_name); - } - - fn write_version(&mut self) { - let version = self - .cmd - .get_version() - .or_else(|| self.cmd.get_long_version()); - if let Some(output) = version { - self.none(wrap(output, self.term_w)); - } - } - - fn write_author(&mut self, before_new_line: bool, after_new_line: bool) { - if let Some(author) = self.cmd.get_author() { - if before_new_line { - self.none("\n"); - } - self.none(wrap(author, self.term_w)); - if after_new_line { - self.none("\n"); - } - } - } - - fn write_about(&mut self, before_new_line: bool, after_new_line: bool) { - let about = if self.use_long { - self.cmd.get_long_about().or_else(|| self.cmd.get_about()) - } else { - self.cmd.get_about() - }; - if let Some(output) = about { - if before_new_line { - self.none("\n"); - } - let mut output = output.clone(); - replace_newline_var(&mut output); - output.wrap(self.term_w); - self.writer.extend(output.into_iter()); - if after_new_line { - self.none("\n"); - } - } - } - - fn write_before_help(&mut self) { - debug!("HelpTemplate::write_before_help"); - let before_help = if self.use_long { - self.cmd - .get_before_long_help() - .or_else(|| self.cmd.get_before_help()) - } else { - self.cmd.get_before_help() - }; - if let Some(output) = before_help { - let mut output = output.clone(); - replace_newline_var(&mut output); - output.wrap(self.term_w); - self.writer.extend(output.into_iter()); - self.none("\n\n"); - } - } - - fn write_after_help(&mut self) { - debug!("HelpTemplate::write_after_help"); - let after_help = if self.use_long { - self.cmd - .get_after_long_help() - .or_else(|| self.cmd.get_after_help()) - } else { - self.cmd.get_after_help() - }; - if let Some(output) = after_help { - self.none("\n\n"); - let mut output = output.clone(); - replace_newline_var(&mut output); - output.wrap(self.term_w); - self.writer.extend(output.into_iter()); - } - } -} - -/// Arg handling -impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> { - /// Writes help for all arguments (options, flags, args, subcommands) - /// including titles of a Parser Object to the wrapped stream. - pub(crate) fn write_all_args(&mut self) { - debug!("HelpTemplate::write_all_args"); - let pos = self - .cmd - .get_positionals() - .filter(|a| a.get_help_heading().is_none()) - .filter(|arg| should_show_arg(self.use_long, arg)) - .collect::<Vec<_>>(); - let non_pos = self - .cmd - .get_non_positionals() - .filter(|a| a.get_help_heading().is_none()) - .filter(|arg| should_show_arg(self.use_long, arg)) - .collect::<Vec<_>>(); - let subcmds = self.cmd.has_visible_subcommands(); - - let custom_headings = self - .cmd - .get_arguments() - .filter_map(|arg| arg.get_help_heading()) - .collect::<FlatSet<_>>(); - - let mut first = true; - - if subcmds { - if !first { - self.none("\n\n"); - } - first = false; - let default_help_heading = Str::from("Commands"); - self.header( - self.cmd - .get_subcommand_help_heading() - .unwrap_or(&default_help_heading), - ); - self.header(":\n"); - - self.write_subcommands(self.cmd); - } - - if !pos.is_empty() { - if !first { - self.none("\n\n"); - } - first = false; - // Write positional args if any - self.header("Arguments:\n"); - self.write_args(&pos, "Arguments", positional_sort_key); - } - - if !non_pos.is_empty() { - if !first { - self.none("\n\n"); - } - first = false; - self.header("Options:\n"); - self.write_args(&non_pos, "Options", option_sort_key); - } - if !custom_headings.is_empty() { - for heading in custom_headings { - let args = self - .cmd - .get_arguments() - .filter(|a| { - if let Some(help_heading) = a.get_help_heading() { - return help_heading == heading; - } - false - }) - .filter(|arg| should_show_arg(self.use_long, arg)) - .collect::<Vec<_>>(); - - if !args.is_empty() { - if !first { - self.none("\n\n"); - } - first = false; - self.header(format!("{}:\n", heading)); - self.write_args(&args, heading, option_sort_key); - } - } - } - } - /// Sorts arguments by length and display order and write their help to the wrapped stream. - fn write_args(&mut self, args: &[&Arg], _category: &str, sort_key: ArgSortKey) { - debug!("HelpTemplate::write_args {}", _category); - // The shortest an arg can legally be is 2 (i.e. '-x') - let mut longest = 2; - let mut ord_v = Vec::new(); - - // Determine the longest - for &arg in args.iter().filter(|arg| { - // If it's NextLineHelp we don't care to compute how long it is because it may be - // NextLineHelp on purpose simply *because* it's so long and would throw off all other - // args alignment - should_show_arg(self.use_long, arg) - }) { - if longest_filter(arg) { - longest = longest.max(display_width(&arg.to_string())); - debug!( - "HelpTemplate::write_args: arg={:?} longest={}", - arg.get_id(), - longest - ); - } - - let key = (sort_key)(arg); - ord_v.push((key, arg)); - } - ord_v.sort_by(|a, b| a.0.cmp(&b.0)); - - let next_line_help = self.will_args_wrap(args, longest); - - for (i, (_, arg)) in ord_v.iter().enumerate() { - if i != 0 { - self.none("\n"); - if next_line_help && self.use_long { - self.none("\n"); - } - } - self.write_arg(arg, next_line_help, longest); - } - } - - /// Writes help for an argument to the wrapped stream. - fn write_arg(&mut self, arg: &Arg, next_line_help: bool, longest: usize) { - let spec_vals = &self.spec_vals(arg); - - self.none(TAB); - self.short(arg); - self.long(arg); - self.writer.extend(arg.stylize_arg_suffix(None).into_iter()); - self.align_to_about(arg, next_line_help, longest); - - let about = if self.use_long { - arg.get_long_help() - .or_else(|| arg.get_help()) - .unwrap_or_default() - } else { - arg.get_help() - .or_else(|| arg.get_long_help()) - .unwrap_or_default() - }; - - self.help(Some(arg), about, spec_vals, next_line_help, longest); - } - - /// Writes argument's short command to the wrapped stream. - fn short(&mut self, arg: &Arg) { - debug!("HelpTemplate::short"); - - if let Some(s) = arg.get_short() { - self.literal(format!("-{}", s)); - } else if arg.get_long().is_some() { - self.none(" "); - } - } - - /// Writes argument's long command to the wrapped stream. - fn long(&mut self, arg: &Arg) { - debug!("HelpTemplate::long"); - if let Some(long) = arg.get_long() { - if arg.get_short().is_some() { - self.none(", "); - } - self.literal(format!("--{}", long)); - } - } - - /// Write alignment padding between arg's switches/values and its about message. - fn align_to_about(&mut self, arg: &Arg, next_line_help: bool, longest: usize) { - debug!( - "HelpTemplate::align_to_about: arg={}, next_line_help={}, longest={}", - arg.get_id(), - next_line_help, - longest - ); - if self.use_long || next_line_help { - // long help prints messages on the next line so it doesn't need to align text - debug!("HelpTemplate::align_to_about: printing long help so skip alignment"); - } else if !arg.is_positional() { - let self_len = display_width(&arg.to_string()); - // Since we're writing spaces from the tab point we first need to know if we - // had a long and short, or just short - let padding = if arg.get_long().is_some() { - // Only account 4 after the val - TAB_WIDTH - } else { - // Only account for ', --' + 4 after the val - TAB_WIDTH + 4 - }; - let spcs = longest + padding - self_len; - debug!( - "HelpTemplate::align_to_about: positional=false arg_len={}, spaces={}", - self_len, spcs - ); - - self.spaces(spcs); - } else { - let self_len = display_width(&arg.to_string()); - let padding = TAB_WIDTH; - let spcs = longest + padding - self_len; - debug!( - "HelpTemplate::align_to_about: positional=true arg_len={}, spaces={}", - self_len, spcs - ); - - self.spaces(spcs); - } - } - - /// Writes argument's help to the wrapped stream. - fn help( - &mut self, - arg: Option<&Arg>, - about: &StyledStr, - spec_vals: &str, - next_line_help: bool, - longest: usize, - ) { - debug!("HelpTemplate::help"); - - // Is help on next line, if so then indent - if next_line_help { - debug!("HelpTemplate::help: Next Line...{:?}", next_line_help); - self.none("\n"); - self.none(TAB); - self.none(NEXT_LINE_INDENT); - } - - let spaces = if next_line_help { - TAB.len() + NEXT_LINE_INDENT.len() - } else if let Some(true) = arg.map(|a| a.is_positional()) { - longest + TAB_WIDTH * 2 - } else { - longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4 - }; - let trailing_indent = spaces; // Don't indent any further than the first line is indented - let trailing_indent = self.get_spaces(trailing_indent); - - let mut help = about.clone(); - replace_newline_var(&mut help); - if !spec_vals.is_empty() { - if !help.is_empty() { - let sep = if self.use_long && arg.is_some() { - "\n\n" - } else { - " " - }; - help.none(sep); - } - help.none(spec_vals); - } - let avail_chars = self.term_w.saturating_sub(spaces); - debug!( - "HelpTemplate::help: help_width={}, spaces={}, avail={}", - spaces, - help.display_width(), - avail_chars - ); - help.wrap(avail_chars); - help.indent("", &trailing_indent); - let help_is_empty = help.is_empty(); - self.writer.extend(help.into_iter()); - if let Some(arg) = arg { - const DASH_SPACE: usize = "- ".len(); - const COLON_SPACE: usize = ": ".len(); - let possible_vals = arg.get_possible_values(); - if self.use_long - && !arg.is_hide_possible_values_set() - && possible_vals.iter().any(PossibleValue::should_show_help) - { - debug!( - "HelpTemplate::help: Found possible vals...{:?}", - possible_vals - ); - if !help_is_empty { - self.none("\n\n"); - self.spaces(spaces); - } - self.none("Possible values:"); - let longest = possible_vals - .iter() - .filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name))) - .max() - .expect("Only called with possible value"); - let help_longest = possible_vals - .iter() - .filter_map(|f| f.get_visible_help().map(|h| h.display_width())) - .max() - .expect("Only called with possible value with help"); - // should new line - let taken = longest + spaces + DASH_SPACE; - - let possible_value_new_line = - self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest; - - let spaces = spaces + TAB_WIDTH - DASH_SPACE; - let trailing_indent = if possible_value_new_line { - spaces + DASH_SPACE - } else { - spaces + longest + DASH_SPACE + COLON_SPACE - }; - let trailing_indent = self.get_spaces(trailing_indent); - - for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) { - self.none("\n"); - self.spaces(spaces); - self.none("- "); - self.literal(pv.get_name()); - if let Some(help) = pv.get_help() { - debug!("HelpTemplate::help: Possible Value help"); - - if possible_value_new_line { - self.none(":\n"); - self.spaces(trailing_indent.len()); - } else { - self.none(": "); - // To align help messages - self.spaces(longest - display_width(pv.get_name())); - } - - let avail_chars = if self.term_w > trailing_indent.len() { - self.term_w - trailing_indent.len() - } else { - usize::MAX - }; - - let mut help = help.clone(); - replace_newline_var(&mut help); - help.wrap(avail_chars); - help.indent("", &trailing_indent); - self.writer.extend(help.into_iter()); - } - } - } - } - } - - /// Will use next line help on writing args. - fn will_args_wrap(&self, args: &[&Arg], longest: usize) -> bool { - args.iter() - .filter(|arg| should_show_arg(self.use_long, arg)) - .any(|arg| { - let spec_vals = &self.spec_vals(arg); - self.arg_next_line_help(arg, spec_vals, longest) - }) - } - - fn arg_next_line_help(&self, arg: &Arg, spec_vals: &str, longest: usize) -> bool { - if self.next_line_help || arg.is_next_line_help_set() || self.use_long { - // setting_next_line - true - } else { - // force_next_line - let h = arg.get_help().unwrap_or_default(); - let h_w = h.display_width() + display_width(spec_vals); - let taken = if arg.is_positional() { - longest + TAB_WIDTH * 2 - } else { - longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4 - }; - self.term_w >= taken - && (taken as f32 / self.term_w as f32) > 0.40 - && h_w > (self.term_w - taken) - } - } - - fn spec_vals(&self, a: &Arg) -> String { - debug!("HelpTemplate::spec_vals: a={}", a); - let mut spec_vals = Vec::new(); - #[cfg(feature = "env")] - if let Some(ref env) = a.env { - if !a.is_hide_env_set() { - debug!( - "HelpTemplate::spec_vals: Found environment variable...[{:?}:{:?}]", - env.0, env.1 - ); - let env_val = if !a.is_hide_env_values_set() { - format!( - "={}", - env.1 - .as_ref() - .map(|s| s.to_string_lossy()) - .unwrap_or_default() - ) - } else { - Default::default() - }; - let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val); - spec_vals.push(env_info); - } - } - if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() { - debug!( - "HelpTemplate::spec_vals: Found default value...[{:?}]", - a.default_vals - ); - - let pvs = a - .default_vals - .iter() - .map(|pvs| pvs.to_string_lossy()) - .map(|pvs| { - if pvs.contains(char::is_whitespace) { - Cow::from(format!("{:?}", pvs)) - } else { - pvs - } - }) - .collect::<Vec<_>>() - .join(" "); - - spec_vals.push(format!("[default: {}]", pvs)); - } - - let als = a - .aliases - .iter() - .filter(|&als| als.1) // visible - .map(|als| als.0.as_str()) // name - .collect::<Vec<_>>() - .join(", "); - if !als.is_empty() { - debug!("HelpTemplate::spec_vals: Found aliases...{:?}", a.aliases); - spec_vals.push(format!("[aliases: {}]", als)); - } - - let als = a - .short_aliases - .iter() - .filter(|&als| als.1) // visible - .map(|&als| als.0.to_string()) // name - .collect::<Vec<_>>() - .join(", "); - if !als.is_empty() { - debug!( - "HelpTemplate::spec_vals: Found short aliases...{:?}", - a.short_aliases - ); - spec_vals.push(format!("[short aliases: {}]", als)); - } - - let possible_vals = a.get_possible_values(); - if !(a.is_hide_possible_values_set() - || possible_vals.is_empty() - || self.use_long && possible_vals.iter().any(PossibleValue::should_show_help)) - { - debug!( - "HelpTemplate::spec_vals: Found possible vals...{:?}", - possible_vals - ); - - let pvs = possible_vals - .iter() - .filter_map(PossibleValue::get_visible_quoted_name) - .collect::<Vec<_>>() - .join(", "); - - spec_vals.push(format!("[possible values: {}]", pvs)); - } - let connector = if self.use_long { "\n" } else { " " }; - spec_vals.join(connector) - } - - fn header<T: Into<String>>(&mut self, msg: T) { - self.writer.header(msg); - } - - fn literal<T: Into<String>>(&mut self, msg: T) { - self.writer.literal(msg); - } - - fn none<T: Into<String>>(&mut self, msg: T) { - self.writer.none(msg); - } - - fn get_spaces(&self, n: usize) -> String { - " ".repeat(n) - } - - fn spaces(&mut self, n: usize) { - self.none(self.get_spaces(n)); - } -} - -/// Subcommand handling -impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> { - /// Writes help for subcommands of a Parser Object to the wrapped stream. - fn write_subcommands(&mut self, cmd: &Command) { - debug!("HelpTemplate::write_subcommands"); - // The shortest an arg can legally be is 2 (i.e. '-x') - let mut longest = 2; - let mut ord_v = Vec::new(); - for subcommand in cmd - .get_subcommands() - .filter(|subcommand| should_show_subcommand(subcommand)) - { - let mut styled = StyledStr::new(); - styled.literal(subcommand.get_name()); - if let Some(short) = subcommand.get_short_flag() { - styled.none(", "); - styled.literal(format!("-{}", short)); - } - if let Some(long) = subcommand.get_long_flag() { - styled.none(", "); - styled.literal(format!("--{}", long)); - } - longest = longest.max(styled.display_width()); - ord_v.push((subcommand.get_display_order(), styled, subcommand)); - } - ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1))); - - debug!("HelpTemplate::write_subcommands longest = {}", longest); - - let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest); - - let mut first = true; - for (_, sc_str, sc) in ord_v { - if first { - first = false; - } else { - self.none("\n"); - } - self.write_subcommand(sc_str, sc, next_line_help, longest); - } - } - - /// Will use next line help on writing subcommands. - fn will_subcommands_wrap<'a>( - &self, - subcommands: impl IntoIterator<Item = &'a Command>, - longest: usize, - ) -> bool { - subcommands - .into_iter() - .filter(|&subcommand| should_show_subcommand(subcommand)) - .any(|subcommand| { - let spec_vals = &self.sc_spec_vals(subcommand); - self.subcommand_next_line_help(subcommand, spec_vals, longest) - }) - } - - fn write_subcommand( - &mut self, - sc_str: StyledStr, - cmd: &Command, - next_line_help: bool, - longest: usize, - ) { - debug!("HelpTemplate::write_subcommand"); - - let spec_vals = &self.sc_spec_vals(cmd); - - let about = cmd - .get_about() - .or_else(|| cmd.get_long_about()) - .unwrap_or_default(); - - self.subcmd(sc_str, next_line_help, longest); - self.help(None, about, spec_vals, next_line_help, longest) - } - - fn sc_spec_vals(&self, a: &Command) -> String { - debug!("HelpTemplate::sc_spec_vals: a={}", a.get_name()); - let mut spec_vals = vec![]; - - let mut short_als = a - .get_visible_short_flag_aliases() - .map(|a| format!("-{}", a)) - .collect::<Vec<_>>(); - let als = a.get_visible_aliases().map(|s| s.to_string()); - short_als.extend(als); - let all_als = short_als.join(", "); - if !all_als.is_empty() { - debug!( - "HelpTemplate::spec_vals: Found aliases...{:?}", - a.get_all_aliases().collect::<Vec<_>>() - ); - debug!( - "HelpTemplate::spec_vals: Found short flag aliases...{:?}", - a.get_all_short_flag_aliases().collect::<Vec<_>>() - ); - spec_vals.push(format!("[aliases: {}]", all_als)); - } - - spec_vals.join(" ") - } - - fn subcommand_next_line_help(&self, cmd: &Command, spec_vals: &str, longest: usize) -> bool { - if self.next_line_help | self.use_long { - // setting_next_line - true - } else { - // force_next_line - let h = cmd.get_about().unwrap_or_default(); - let h_w = h.display_width() + display_width(spec_vals); - let taken = longest + TAB_WIDTH * 2; - self.term_w >= taken - && (taken as f32 / self.term_w as f32) > 0.40 - && h_w > (self.term_w - taken) - } - } - - /// Writes subcommand to the wrapped stream. - fn subcmd(&mut self, sc_str: StyledStr, next_line_help: bool, longest: usize) { - let width = sc_str.display_width(); - - self.none(TAB); - self.writer.extend(sc_str.into_iter()); - if !next_line_help { - self.spaces(longest + TAB_WIDTH - width); - } - } -} - -const NEXT_LINE_INDENT: &str = " "; - -type ArgSortKey = fn(arg: &Arg) -> (usize, String); - -fn positional_sort_key(arg: &Arg) -> (usize, String) { - (arg.get_index().unwrap_or(0), String::new()) -} - -fn option_sort_key(arg: &Arg) -> (usize, String) { - // Formatting key like this to ensure that: - // 1. Argument has long flags are printed just after short flags. - // 2. For two args both have short flags like `-c` and `-C`, the - // `-C` arg is printed just after the `-c` arg - // 3. For args without short or long flag, print them at last(sorted - // by arg name). - // Example order: -a, -b, -B, -s, --select-file, --select-folder, -x - - let key = if let Some(x) = arg.get_short() { - let mut s = x.to_ascii_lowercase().to_string(); - s.push(if x.is_ascii_lowercase() { '0' } else { '1' }); - s - } else if let Some(x) = arg.get_long() { - x.to_string() - } else { - let mut s = '{'.to_string(); - s.push_str(arg.get_id().as_str()); - s - }; - (arg.get_display_order(), key) -} - -pub(crate) fn dimensions() -> (Option<usize>, Option<usize>) { - #[cfg(not(feature = "wrap_help"))] - return (None, None); - - #[cfg(feature = "wrap_help")] - terminal_size::terminal_size() - .map(|(w, h)| (Some(w.0.into()), Some(h.0.into()))) - .unwrap_or_else(|| (parse_env("COLUMNS"), parse_env("LINES"))) -} - -#[cfg(feature = "wrap_help")] -fn parse_env(var: &str) -> Option<usize> { - some!(some!(std::env::var_os(var)).to_str()) - .parse::<usize>() - .ok() -} - -fn should_show_arg(use_long: bool, arg: &Arg) -> bool { - debug!( - "should_show_arg: use_long={:?}, arg={}", - use_long, - arg.get_id() - ); - if arg.is_hide_set() { - return false; - } - (!arg.is_hide_long_help_set() && use_long) - || (!arg.is_hide_short_help_set() && !use_long) - || arg.is_next_line_help_set() -} - -fn should_show_subcommand(subcommand: &Command) -> bool { - !subcommand.is_hide_set() -} - -fn replace_newline_var(styled: &mut StyledStr) { - for (_, content) in styled.iter_mut() { - *content = content.replace("{n}", "\n"); - } -} - -fn longest_filter(arg: &Arg) -> bool { - arg.is_takes_value_set() || arg.get_long().is_some() || arg.get_short().is_none() -} - -#[cfg(test)] -mod test { - #[test] - #[cfg(feature = "wrap_help")] - fn wrap_help_last_word() { - use super::*; - - let help = String::from("foo bar baz"); - assert_eq!(wrap(&help, 5), "foo\nbar\nbaz"); - } - - #[test] - #[cfg(feature = "unicode")] - fn display_width_handles_non_ascii() { - use super::*; - - // Popular Danish tongue-twister, the name of a fruit dessert. - let text = "rødgrød med fløde"; - assert_eq!(display_width(text), 17); - // Note that the string width is smaller than the string - // length. This is due to the precomposed non-ASCII letters: - assert_eq!(text.len(), 20); - } - - #[test] - #[cfg(feature = "unicode")] - fn display_width_handles_emojis() { - use super::*; - - let text = "😂"; - // There is a single `char`... - assert_eq!(text.chars().count(), 1); - // but it is double-width: - assert_eq!(display_width(text), 2); - // This is much less than the byte length: - assert_eq!(text.len(), 4); - } -} diff --git a/vendor/clap/src/output/mod.rs b/vendor/clap/src/output/mod.rs deleted file mode 100644 index b3587116f..000000000 --- a/vendor/clap/src/output/mod.rs +++ /dev/null @@ -1,23 +0,0 @@ -mod help; -#[cfg(feature = "help")] -mod help_template; -mod usage; - -pub(crate) mod fmt; -#[cfg(feature = "help")] -pub(crate) mod textwrap; - -pub(crate) use self::help::write_help; -#[cfg(feature = "help")] -pub(crate) use self::help_template::AutoHelp; -#[cfg(feature = "help")] -pub(crate) use self::help_template::HelpTemplate; -#[cfg(feature = "help")] -pub(crate) use self::textwrap::core::display_width; -#[cfg(feature = "help")] -pub(crate) use self::textwrap::wrap; -pub(crate) use self::usage::Usage; - -pub(crate) const TAB: &str = " "; -#[cfg(feature = "help")] -pub(crate) const TAB_WIDTH: usize = TAB.len(); diff --git a/vendor/clap/src/output/textwrap/core.rs b/vendor/clap/src/output/textwrap/core.rs deleted file mode 100644 index b890c6c7b..000000000 --- a/vendor/clap/src/output/textwrap/core.rs +++ /dev/null @@ -1,158 +0,0 @@ -/// Compute the display width of `text` -/// -/// # Examples -/// -/// **Note:** When the `unicode` Cargo feature is disabled, all characters are presumed to take up -/// 1 width. With the feature enabled, function will correctly deal with [combining characters] in -/// their decomposed form (see [Unicode equivalence]). -/// -/// An example of a decomposed character is “é”, which can be decomposed into: “e” followed by a -/// combining acute accent: “◌́”. Without the `unicode` Cargo feature, every `char` has a width of -/// 1. This includes the combining accent: -/// -/// ## Emojis and CJK Characters -/// -/// Characters such as emojis and [CJK characters] used in the -/// Chinese, Japanese, and Korean languages are seen as double-width, -/// even if the `unicode-width` feature is disabled: -/// -/// # Limitations -/// -/// The displayed width of a string cannot always be computed from the -/// string alone. This is because the width depends on the rendering -/// engine used. This is particularly visible with [emoji modifier -/// sequences] where a base emoji is modified with, e.g., skin tone or -/// hair color modifiers. It is up to the rendering engine to detect -/// this and to produce a suitable emoji. -/// -/// A simple example is “❤️”, which consists of “❤” (U+2764: Black -/// Heart Symbol) followed by U+FE0F (Variation Selector-16). By -/// itself, “❤” is a black heart, but if you follow it with the -/// variant selector, you may get a wider red heart. -/// -/// A more complex example would be “👨🦰” which should depict a man -/// with red hair. Here the computed width is too large — and the -/// width differs depending on the use of the `unicode-width` feature: -/// -/// This happens because the grapheme consists of three code points: -/// “👨” (U+1F468: Man), Zero Width Joiner (U+200D), and “🦰” -/// (U+1F9B0: Red Hair). You can see them above in the test. With -/// `unicode-width` enabled, the ZWJ is correctly seen as having zero -/// width, without it is counted as a double-width character. -/// -/// ## Terminal Support -/// -/// Modern browsers typically do a great job at combining characters -/// as shown above, but terminals often struggle more. As an example, -/// Gnome Terminal version 3.38.1, shows “❤️” as a big red heart, but -/// shows "👨🦰" as “👨🦰”. -/// -/// [combining characters]: https://en.wikipedia.org/wiki/Combining_character -/// [Unicode equivalence]: https://en.wikipedia.org/wiki/Unicode_equivalence -/// [CJK characters]: https://en.wikipedia.org/wiki/CJK_characters -/// [emoji modifier sequences]: https://unicode.org/emoji/charts/full-emoji-modifiers.html -#[inline(never)] -pub(crate) fn display_width(text: &str) -> usize { - let mut width = 0; - - let mut control_sequence = false; - let control_terminate: char = 'm'; - - for ch in text.chars() { - if ch.is_ascii_control() { - control_sequence = true; - } else if control_sequence && ch == control_terminate { - control_sequence = false; - continue; - } - - if !control_sequence { - width += ch_width(ch); - } - } - width -} - -#[cfg(feature = "unicode")] -fn ch_width(ch: char) -> usize { - unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0) -} - -#[cfg(not(feature = "unicode"))] -fn ch_width(_: char) -> usize { - 1 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[cfg(feature = "unicode")] - use unicode_width::UnicodeWidthChar; - - #[test] - fn emojis_have_correct_width() { - use unic_emoji_char::is_emoji; - - // Emojis in the Basic Latin (ASCII) and Latin-1 Supplement - // blocks all have a width of 1 column. This includes - // characters such as '#' and '©'. - for ch in '\u{1}'..'\u{FF}' { - if is_emoji(ch) { - let desc = format!("{:?} U+{:04X}", ch, ch as u32); - - #[cfg(feature = "unicode")] - assert_eq!(ch.width().unwrap(), 1, "char: {}", desc); - - #[cfg(not(feature = "unicode"))] - assert_eq!(ch_width(ch), 1, "char: {}", desc); - } - } - - // Emojis in the remaining blocks of the Basic Multilingual - // Plane (BMP), in the Supplementary Multilingual Plane (SMP), - // and in the Supplementary Ideographic Plane (SIP), are all 1 - // or 2 columns wide when unicode-width is used, and always 2 - // columns wide otherwise. This includes all of our favorite - // emojis such as 😊. - for ch in '\u{FF}'..'\u{2FFFF}' { - if is_emoji(ch) { - let desc = format!("{:?} U+{:04X}", ch, ch as u32); - - #[cfg(feature = "unicode")] - assert!(ch.width().unwrap() <= 2, "char: {}", desc); - - #[cfg(not(feature = "unicode"))] - assert_eq!(ch_width(ch), 1, "char: {}", desc); - } - } - - // The remaining planes contain almost no assigned code points - // and thus also no emojis. - } - - #[test] - #[cfg(feature = "unicode")] - fn display_width_works() { - assert_eq!("Café Plain".len(), 11); // “é” is two bytes - assert_eq!(display_width("Café Plain"), 10); - } - - #[test] - #[cfg(feature = "unicode")] - fn display_width_narrow_emojis() { - assert_eq!(display_width("⁉"), 1); - } - - #[test] - #[cfg(feature = "unicode")] - fn display_width_narrow_emojis_variant_selector() { - assert_eq!(display_width("⁉\u{fe0f}"), 1); - } - - #[test] - #[cfg(feature = "unicode")] - fn display_width_emojis() { - assert_eq!(display_width("😂😭🥺🤣✨😍🙏🥰😊🔥"), 20); - } -} diff --git a/vendor/clap/src/output/textwrap/mod.rs b/vendor/clap/src/output/textwrap/mod.rs deleted file mode 100644 index d14d3fe7f..000000000 --- a/vendor/clap/src/output/textwrap/mod.rs +++ /dev/null @@ -1,122 +0,0 @@ -//! Fork of `textwrap` crate -//! -//! Benefits of forking: -//! - Pull in only what we need rather than relying on the compiler to remove what we don't need -//! - `LineWrapper` is able to incrementally wrap which will help with `StyledStr - -pub(crate) mod core; -#[cfg(feature = "wrap_help")] -pub(crate) mod word_separators; -#[cfg(feature = "wrap_help")] -pub(crate) mod wrap_algorithms; - -#[cfg(feature = "wrap_help")] -pub(crate) fn wrap(content: &str, hard_width: usize) -> String { - let mut wrapper = wrap_algorithms::LineWrapper::new(hard_width); - let mut total = Vec::new(); - for line in content.split_inclusive('\n') { - wrapper.reset(); - let line = word_separators::find_words_ascii_space(line).collect::<Vec<_>>(); - total.extend(wrapper.wrap(line)); - } - total.join("") -} - -#[cfg(not(feature = "wrap_help"))] -pub(crate) fn wrap(content: &str, _hard_width: usize) -> String { - content.to_owned() -} - -#[cfg(test)] -#[cfg(feature = "wrap_help")] -mod test { - /// Compatibility shim to keep textwrap's tests - fn wrap(content: &str, hard_width: usize) -> Vec<String> { - super::wrap(content, hard_width) - .trim_end() - .split('\n') - .map(|s| s.to_owned()) - .collect::<Vec<_>>() - } - - #[test] - fn no_wrap() { - assert_eq!(wrap("foo", 10), vec!["foo"]); - } - - #[test] - fn wrap_simple() { - assert_eq!(wrap("foo bar baz", 5), vec!["foo", "bar", "baz"]); - } - - #[test] - fn to_be_or_not() { - assert_eq!( - wrap("To be, or not to be, that is the question.", 10), - vec!["To be, or", "not to be,", "that is", "the", "question."] - ); - } - - #[test] - fn multiple_words_on_first_line() { - assert_eq!(wrap("foo bar baz", 10), vec!["foo bar", "baz"]); - } - - #[test] - fn long_word() { - assert_eq!(wrap("foo", 0), vec!["foo"]); - } - - #[test] - fn long_words() { - assert_eq!(wrap("foo bar", 0), vec!["foo", "bar"]); - } - - #[test] - fn max_width() { - assert_eq!(wrap("foo bar", usize::MAX), vec!["foo bar"]); - - let text = "Hello there! This is some English text. \ - It should not be wrapped given the extents below."; - assert_eq!(wrap(text, usize::MAX), vec![text]); - } - - #[test] - fn leading_whitespace() { - assert_eq!(wrap(" foo bar", 6), vec![" foo", "bar"]); - } - - #[test] - fn leading_whitespace_empty_first_line() { - // If there is no space for the first word, the first line - // will be empty. This is because the string is split into - // words like [" ", "foobar ", "baz"], which puts "foobar " on - // the second line. We never output trailing whitespace - assert_eq!(wrap(" foobar baz", 6), vec!["", "foobar", "baz"]); - } - - #[test] - fn trailing_whitespace() { - // Whitespace is only significant inside a line. After a line - // gets too long and is broken, the first word starts in - // column zero and is not indented. - assert_eq!(wrap("foo bar baz ", 5), vec!["foo", "bar", "baz"]); - } - - #[test] - fn issue_99() { - // We did not reset the in_whitespace flag correctly and did - // not handle single-character words after a line break. - assert_eq!( - wrap("aaabbbccc x yyyzzzwww", 9), - vec!["aaabbbccc", "x", "yyyzzzwww"] - ); - } - - #[test] - fn issue_129() { - // The dash is an em-dash which takes up four bytes. We used - // to panic since we tried to index into the character. - assert_eq!(wrap("x – x", 1), vec!["x", "–", "x"]); - } -} diff --git a/vendor/clap/src/output/textwrap/word_separators.rs b/vendor/clap/src/output/textwrap/word_separators.rs deleted file mode 100644 index ac09231d5..000000000 --- a/vendor/clap/src/output/textwrap/word_separators.rs +++ /dev/null @@ -1,91 +0,0 @@ -pub(crate) fn find_words_ascii_space(line: &str) -> impl Iterator<Item = &'_ str> + '_ { - let mut start = 0; - let mut in_whitespace = false; - let mut char_indices = line.char_indices(); - - std::iter::from_fn(move || { - for (idx, ch) in char_indices.by_ref() { - if in_whitespace && ch != ' ' { - let word = &line[start..idx]; - start = idx; - in_whitespace = ch == ' '; - return Some(word); - } - - in_whitespace = ch == ' '; - } - - if start < line.len() { - let word = &line[start..]; - start = line.len(); - return Some(word); - } - - None - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - macro_rules! test_find_words { - ($ascii_name:ident, - $([ $line:expr, $ascii_words:expr ]),+) => { - #[test] - fn $ascii_name() { - $( - let expected_words: Vec<&str> = $ascii_words.to_vec(); - let actual_words = find_words_ascii_space($line) - .collect::<Vec<_>>(); - assert_eq!(actual_words, expected_words, "Line: {:?}", $line); - )+ - } - }; - } - - test_find_words!(ascii_space_empty, ["", []]); - - test_find_words!(ascii_single_word, ["foo", ["foo"]]); - - test_find_words!(ascii_two_words, ["foo bar", ["foo ", "bar"]]); - - test_find_words!( - ascii_multiple_words, - ["foo bar", ["foo ", "bar"]], - ["x y z", ["x ", "y ", "z"]] - ); - - test_find_words!(ascii_only_whitespace, [" ", [" "]], [" ", [" "]]); - - test_find_words!( - ascii_inter_word_whitespace, - ["foo bar", ["foo ", "bar"]] - ); - - test_find_words!(ascii_trailing_whitespace, ["foo ", ["foo "]]); - - test_find_words!(ascii_leading_whitespace, [" foo", [" ", "foo"]]); - - test_find_words!( - ascii_multi_column_char, - ["\u{1f920}", ["\u{1f920}"]] // cowboy emoji 🤠 - ); - - test_find_words!( - ascii_hyphens, - ["foo-bar", ["foo-bar"]], - ["foo- bar", ["foo- ", "bar"]], - ["foo - bar", ["foo ", "- ", "bar"]], - ["foo -bar", ["foo ", "-bar"]] - ); - - test_find_words!(ascii_newline, ["foo\nbar", ["foo\nbar"]]); - - test_find_words!(ascii_tab, ["foo\tbar", ["foo\tbar"]]); - - test_find_words!( - ascii_non_breaking_space, - ["foo\u{00A0}bar", ["foo\u{00A0}bar"]] - ); -} diff --git a/vendor/clap/src/output/textwrap/wrap_algorithms.rs b/vendor/clap/src/output/textwrap/wrap_algorithms.rs deleted file mode 100644 index 019cc04ff..000000000 --- a/vendor/clap/src/output/textwrap/wrap_algorithms.rs +++ /dev/null @@ -1,44 +0,0 @@ -use super::core::display_width; - -#[derive(Debug)] -pub(crate) struct LineWrapper { - line_width: usize, - hard_width: usize, -} - -impl LineWrapper { - pub(crate) fn new(hard_width: usize) -> Self { - Self { - line_width: 0, - hard_width, - } - } - - pub(crate) fn reset(&mut self) { - self.line_width = 0; - } - - pub(crate) fn wrap<'w>(&mut self, mut words: Vec<&'w str>) -> Vec<&'w str> { - let mut i = 0; - while i < words.len() { - let word = &words[i]; - let trimmed = word.trim_end(); - let word_width = display_width(trimmed); - let trimmed_delta = word.len() - trimmed.len(); - if i != 0 && self.hard_width < self.line_width + word_width { - if 0 < i { - let last = i - 1; - let trimmed = words[last].trim_end(); - words[last] = trimmed; - } - words.insert(i, "\n"); - i += 1; - self.reset(); - } - self.line_width += word_width + trimmed_delta; - - i += 1; - } - words - } -} diff --git a/vendor/clap/src/output/usage.rs b/vendor/clap/src/output/usage.rs deleted file mode 100644 index 145fce12d..000000000 --- a/vendor/clap/src/output/usage.rs +++ /dev/null @@ -1,441 +0,0 @@ -#![cfg_attr(not(feature = "usage"), allow(unused_imports))] -#![cfg_attr(not(feature = "usage"), allow(unused_variables))] -#![cfg_attr(not(feature = "usage"), allow(clippy::manual_map))] -#![cfg_attr(not(feature = "usage"), allow(dead_code))] - -// Internal -use crate::builder::StyledStr; -use crate::builder::{ArgPredicate, Command}; -use crate::parser::ArgMatcher; -use crate::util::ChildGraph; -use crate::util::FlatSet; -use crate::util::Id; - -static DEFAULT_SUB_VALUE_NAME: &str = "COMMAND"; - -pub(crate) struct Usage<'cmd> { - cmd: &'cmd Command, - required: Option<&'cmd ChildGraph<Id>>, -} - -impl<'cmd> Usage<'cmd> { - pub(crate) fn new(cmd: &'cmd Command) -> Self { - Usage { - cmd, - required: None, - } - } - - pub(crate) fn required(mut self, required: &'cmd ChildGraph<Id>) -> Self { - self.required = Some(required); - self - } - - // Creates a usage string for display. This happens just after all arguments were parsed, but before - // any subcommands have been parsed (so as to give subcommands their own usage recursively) - pub(crate) fn create_usage_with_title(&self, used: &[Id]) -> Option<StyledStr> { - debug!("Usage::create_usage_with_title"); - let usage = some!(self.create_usage_no_title(used)); - - let mut styled = StyledStr::new(); - styled.header("Usage:"); - styled.none(" "); - styled.extend(usage.into_iter()); - Some(styled) - } - - // Creates a usage string (*without title*) if one was not provided by the user manually. - pub(crate) fn create_usage_no_title(&self, used: &[Id]) -> Option<StyledStr> { - debug!("Usage::create_usage_no_title"); - if let Some(u) = self.cmd.get_override_usage() { - Some(u.clone()) - } else { - #[cfg(feature = "usage")] - { - if used.is_empty() { - Some(self.create_help_usage(true)) - } else { - Some(self.create_smart_usage(used)) - } - } - - #[cfg(not(feature = "usage"))] - { - None - } - } - } -} - -#[cfg(feature = "usage")] -impl<'cmd> Usage<'cmd> { - // Creates a usage string for display in help messages (i.e. not for errors) - fn create_help_usage(&self, incl_reqs: bool) -> StyledStr { - debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs); - let mut styled = StyledStr::new(); - let name = self - .cmd - .get_usage_name() - .or_else(|| self.cmd.get_bin_name()) - .unwrap_or_else(|| self.cmd.get_name()); - styled.literal(name); - - if self.needs_options_tag() { - styled.placeholder(" [OPTIONS]"); - } - - self.write_args(&[], !incl_reqs, &mut styled); - - // incl_reqs is only false when this function is called recursively - if self.cmd.has_visible_subcommands() && incl_reqs - || self.cmd.is_allow_external_subcommands_set() - { - let placeholder = self - .cmd - .get_subcommand_value_name() - .unwrap_or(DEFAULT_SUB_VALUE_NAME); - if self.cmd.is_subcommand_negates_reqs_set() - || self.cmd.is_args_conflicts_with_subcommands_set() - { - styled.none("\n"); - styled.none(" "); - if self.cmd.is_args_conflicts_with_subcommands_set() { - // Short-circuit full usage creation since no args will be relevant - styled.literal(name); - } else { - styled.extend(self.create_help_usage(false).into_iter()); - } - styled.placeholder(" <"); - styled.placeholder(placeholder); - styled.placeholder(">"); - } else if self.cmd.is_subcommand_required_set() { - styled.placeholder(" <"); - styled.placeholder(placeholder); - styled.placeholder(">"); - } else { - styled.placeholder(" ["); - styled.placeholder(placeholder); - styled.placeholder("]"); - } - } - styled.trim(); - debug!("Usage::create_help_usage: usage={}", styled); - styled - } - - // Creates a context aware usage string, or "smart usage" from currently used - // args, and requirements - fn create_smart_usage(&self, used: &[Id]) -> StyledStr { - debug!("Usage::create_smart_usage"); - let mut styled = StyledStr::new(); - - styled.literal( - self.cmd - .get_usage_name() - .or_else(|| self.cmd.get_bin_name()) - .unwrap_or_else(|| self.cmd.get_name()), - ); - - self.write_args(used, false, &mut styled); - - if self.cmd.is_subcommand_required_set() { - styled.placeholder(" <"); - styled.placeholder( - self.cmd - .get_subcommand_value_name() - .unwrap_or(DEFAULT_SUB_VALUE_NAME), - ); - styled.placeholder(">"); - } - styled - } - - // Determines if we need the `[OPTIONS]` tag in the usage string - fn needs_options_tag(&self) -> bool { - debug!("Usage::needs_options_tag"); - 'outer: for f in self.cmd.get_non_positionals() { - debug!("Usage::needs_options_tag:iter: f={}", f.get_id()); - - // Don't print `[OPTIONS]` just for help or version - if f.get_long() == Some("help") || f.get_long() == Some("version") { - debug!("Usage::needs_options_tag:iter Option is built-in"); - continue; - } - - if f.is_hide_set() { - debug!("Usage::needs_options_tag:iter Option is hidden"); - continue; - } - if f.is_required_set() { - debug!("Usage::needs_options_tag:iter Option is required"); - continue; - } - for grp_s in self.cmd.groups_for_arg(f.get_id()) { - debug!("Usage::needs_options_tag:iter:iter: grp_s={:?}", grp_s); - if self.cmd.get_groups().any(|g| g.id == grp_s && g.required) { - debug!("Usage::needs_options_tag:iter:iter: Group is required"); - continue 'outer; - } - } - - debug!("Usage::needs_options_tag:iter: [OPTIONS] required"); - return true; - } - - debug!("Usage::needs_options_tag: [OPTIONS] not required"); - false - } - - // Returns the required args in usage string form by fully unrolling all groups - pub(crate) fn write_args(&self, incls: &[Id], force_optional: bool, styled: &mut StyledStr) { - for required in self.get_args(incls, force_optional) { - styled.none(" "); - styled.extend(required.into_iter()); - } - } - - pub(crate) fn get_args(&self, incls: &[Id], force_optional: bool) -> Vec<StyledStr> { - debug!("Usage::get_args: incls={:?}", incls,); - - let required_owned; - let required = if let Some(required) = self.required { - required - } else { - required_owned = self.cmd.required_graph(); - &required_owned - }; - - let mut unrolled_reqs = Vec::new(); - for a in required.iter() { - let is_relevant = |(val, req_arg): &(ArgPredicate, Id)| -> Option<Id> { - let required = match val { - ArgPredicate::Equals(_) => false, - ArgPredicate::IsPresent => true, - }; - required.then(|| req_arg.clone()) - }; - - for aa in self.cmd.unroll_arg_requires(is_relevant, a) { - // if we don't check for duplicates here this causes duplicate error messages - // see https://github.com/clap-rs/clap/issues/2770 - unrolled_reqs.push(aa); - } - // always include the required arg itself. it will not be enumerated - // by unroll_requirements_for_arg. - unrolled_reqs.push(a.clone()); - } - debug!("Usage::get_args: unrolled_reqs={:?}", unrolled_reqs); - - let mut required_groups_members = FlatSet::new(); - let mut required_groups = FlatSet::new(); - for req in unrolled_reqs.iter().chain(incls.iter()) { - if self.cmd.find_group(req).is_some() { - let group_members = self.cmd.unroll_args_in_group(req); - let elem = self.cmd.format_group(req); - required_groups.insert(elem); - required_groups_members.extend(group_members); - } else { - debug_assert!(self.cmd.find(req).is_some()); - } - } - - let mut required_opts = FlatSet::new(); - let mut required_positionals = Vec::new(); - for req in unrolled_reqs.iter().chain(incls.iter()) { - if let Some(arg) = self.cmd.find(req) { - if required_groups_members.contains(arg.get_id()) { - continue; - } - - let stylized = arg.stylized(Some(!force_optional)); - if let Some(index) = arg.get_index() { - let new_len = index + 1; - if required_positionals.len() < new_len { - required_positionals.resize(new_len, None); - } - required_positionals[index] = Some(stylized); - } else { - required_opts.insert(stylized); - } - } else { - debug_assert!(self.cmd.find_group(req).is_some()); - } - } - - for pos in self.cmd.get_positionals() { - if pos.is_hide_set() { - continue; - } - if required_groups_members.contains(pos.get_id()) { - continue; - } - - let index = pos.get_index().unwrap(); - let new_len = index + 1; - if required_positionals.len() < new_len { - required_positionals.resize(new_len, None); - } - if required_positionals[index].is_some() { - if pos.is_last_set() { - let styled = required_positionals[index].take().unwrap(); - let mut new = StyledStr::new(); - new.literal("-- "); - new.extend(styled.into_iter()); - required_positionals[index] = Some(new); - } - } else { - let mut styled; - if pos.is_last_set() { - styled = StyledStr::new(); - styled.literal("[-- "); - styled.extend(pos.stylized(Some(true)).into_iter()); - styled.literal("]"); - } else { - styled = pos.stylized(Some(false)); - } - required_positionals[index] = Some(styled); - } - if pos.is_last_set() && force_optional { - required_positionals[index] = None; - } - } - - let mut ret_val = Vec::new(); - if !force_optional { - ret_val.extend(required_opts); - ret_val.extend(required_groups); - } - for pos in required_positionals.into_iter().flatten() { - ret_val.push(pos); - } - - debug!("Usage::get_args: ret_val={:?}", ret_val); - ret_val - } - - pub(crate) fn get_required_usage_from( - &self, - incls: &[Id], - matcher: Option<&ArgMatcher>, - incl_last: bool, - ) -> Vec<StyledStr> { - debug!( - "Usage::get_required_usage_from: incls={:?}, matcher={:?}, incl_last={:?}", - incls, - matcher.is_some(), - incl_last - ); - - let required_owned; - let required = if let Some(required) = self.required { - required - } else { - required_owned = self.cmd.required_graph(); - &required_owned - }; - - let mut unrolled_reqs = Vec::new(); - for a in required.iter() { - let is_relevant = |(val, req_arg): &(ArgPredicate, Id)| -> Option<Id> { - let required = match val { - ArgPredicate::Equals(_) => { - if let Some(matcher) = matcher { - matcher.check_explicit(a, val) - } else { - false - } - } - ArgPredicate::IsPresent => true, - }; - required.then(|| req_arg.clone()) - }; - - for aa in self.cmd.unroll_arg_requires(is_relevant, a) { - // if we don't check for duplicates here this causes duplicate error messages - // see https://github.com/clap-rs/clap/issues/2770 - unrolled_reqs.push(aa); - } - // always include the required arg itself. it will not be enumerated - // by unroll_requirements_for_arg. - unrolled_reqs.push(a.clone()); - } - debug!( - "Usage::get_required_usage_from: unrolled_reqs={:?}", - unrolled_reqs - ); - - let mut required_groups_members = FlatSet::new(); - let mut required_groups = FlatSet::new(); - for req in unrolled_reqs.iter().chain(incls.iter()) { - if self.cmd.find_group(req).is_some() { - let group_members = self.cmd.unroll_args_in_group(req); - let is_present = matcher - .map(|m| { - group_members - .iter() - .any(|arg| m.check_explicit(arg, &ArgPredicate::IsPresent)) - }) - .unwrap_or(false); - debug!( - "Usage::get_required_usage_from:iter:{:?} group is_present={}", - req, is_present - ); - if is_present { - continue; - } - - let elem = self.cmd.format_group(req); - required_groups.insert(elem); - required_groups_members.extend(group_members); - } else { - debug_assert!(self.cmd.find(req).is_some()); - } - } - - let mut required_opts = FlatSet::new(); - let mut required_positionals = Vec::new(); - for req in unrolled_reqs.iter().chain(incls.iter()) { - if let Some(arg) = self.cmd.find(req) { - if required_groups_members.contains(arg.get_id()) { - continue; - } - - let is_present = matcher - .map(|m| m.check_explicit(req, &ArgPredicate::IsPresent)) - .unwrap_or(false); - debug!( - "Usage::get_required_usage_from:iter:{:?} arg is_present={}", - req, is_present - ); - if is_present { - continue; - } - - let stylized = arg.stylized(Some(true)); - if let Some(index) = arg.get_index() { - if !arg.is_last_set() || incl_last { - let new_len = index + 1; - if required_positionals.len() < new_len { - required_positionals.resize(new_len, None); - } - required_positionals[index] = Some(stylized); - } - } else { - required_opts.insert(stylized); - } - } else { - debug_assert!(self.cmd.find_group(req).is_some()); - } - } - - let mut ret_val = Vec::new(); - ret_val.extend(required_opts); - ret_val.extend(required_groups); - for pos in required_positionals.into_iter().flatten() { - ret_val.push(pos); - } - - debug!("Usage::get_required_usage_from: ret_val={:?}", ret_val); - ret_val - } -} diff --git a/vendor/clap/src/parser/arg_matcher.rs b/vendor/clap/src/parser/arg_matcher.rs deleted file mode 100644 index c7e94e678..000000000 --- a/vendor/clap/src/parser/arg_matcher.rs +++ /dev/null @@ -1,248 +0,0 @@ -// Std -use std::ffi::OsString; -use std::mem; -use std::ops::Deref; - -// Internal -use crate::builder::{Arg, ArgPredicate, Command}; -use crate::parser::AnyValue; -use crate::parser::Identifier; -use crate::parser::PendingArg; -use crate::parser::{ArgMatches, MatchedArg, SubCommand, ValueSource}; -use crate::util::FlatMap; -use crate::util::Id; -use crate::INTERNAL_ERROR_MSG; - -#[derive(Debug, Default)] -pub(crate) struct ArgMatcher { - matches: ArgMatches, - pending: Option<PendingArg>, -} - -impl ArgMatcher { - pub(crate) fn new(_cmd: &Command) -> Self { - ArgMatcher { - matches: ArgMatches { - #[cfg(debug_assertions)] - valid_args: { - let args = _cmd.get_arguments().map(|a| a.get_id().clone()); - let groups = _cmd.get_groups().map(|g| g.get_id().clone()); - args.chain(groups).collect() - }, - #[cfg(debug_assertions)] - valid_subcommands: _cmd - .get_subcommands() - .map(|sc| sc.get_name_str().clone()) - .collect(), - ..Default::default() - }, - pending: None, - } - } - - pub(crate) fn into_inner(self) -> ArgMatches { - self.matches - } - - pub(crate) fn propagate_globals(&mut self, global_arg_vec: &[Id]) { - debug!( - "ArgMatcher::get_global_values: global_arg_vec={:?}", - global_arg_vec - ); - let mut vals_map = FlatMap::new(); - self.fill_in_global_values(global_arg_vec, &mut vals_map); - } - - fn fill_in_global_values( - &mut self, - global_arg_vec: &[Id], - vals_map: &mut FlatMap<Id, MatchedArg>, - ) { - for global_arg in global_arg_vec { - if let Some(ma) = self.get(global_arg) { - // We have to check if the parent's global arg wasn't used but still exists - // such as from a default value. - // - // For example, `myprog subcommand --global-arg=value` where `--global-arg` defines - // a default value of `other` myprog would have an existing MatchedArg for - // `--global-arg` where the value is `other` - let to_update = if let Some(parent_ma) = vals_map.get(global_arg) { - if parent_ma.source() > ma.source() { - parent_ma - } else { - ma - } - } else { - ma - } - .clone(); - vals_map.insert(global_arg.clone(), to_update); - } - } - if let Some(ref mut sc) = self.matches.subcommand { - let mut am = ArgMatcher { - matches: mem::take(&mut sc.matches), - pending: None, - }; - am.fill_in_global_values(global_arg_vec, vals_map); - mem::swap(&mut am.matches, &mut sc.matches); - } - - for (name, matched_arg) in vals_map.iter_mut() { - self.matches.args.insert(name.clone(), matched_arg.clone()); - } - } - - pub(crate) fn get(&self, arg: &Id) -> Option<&MatchedArg> { - self.matches.args.get(arg) - } - - pub(crate) fn get_mut(&mut self, arg: &Id) -> Option<&mut MatchedArg> { - self.matches.args.get_mut(arg) - } - - pub(crate) fn remove(&mut self, arg: &Id) -> bool { - self.matches.args.remove(arg).is_some() - } - - pub(crate) fn contains(&self, arg: &Id) -> bool { - self.matches.args.contains_key(arg) - } - - pub(crate) fn arg_ids(&self) -> std::slice::Iter<'_, Id> { - self.matches.args.keys() - } - - pub(crate) fn args(&self) -> crate::util::flat_map::Iter<'_, Id, MatchedArg> { - self.matches.args.iter() - } - - pub(crate) fn entry(&mut self, arg: Id) -> crate::util::Entry<Id, MatchedArg> { - self.matches.args.entry(arg) - } - - pub(crate) fn subcommand(&mut self, sc: SubCommand) { - self.matches.subcommand = Some(Box::new(sc)); - } - - pub(crate) fn subcommand_name(&self) -> Option<&str> { - self.matches.subcommand_name() - } - - pub(crate) fn check_explicit(&self, arg: &Id, predicate: &ArgPredicate) -> bool { - self.get(arg).map_or(false, |a| a.check_explicit(predicate)) - } - - pub(crate) fn start_custom_arg(&mut self, arg: &Arg, source: ValueSource) { - let id = arg.get_id().clone(); - debug!( - "ArgMatcher::start_custom_arg: id={:?}, source={:?}", - id, source - ); - let ma = self.entry(id).or_insert(MatchedArg::new_arg(arg)); - debug_assert_eq!(ma.type_id(), Some(arg.get_value_parser().type_id())); - ma.set_source(source); - ma.new_val_group(); - } - - pub(crate) fn start_custom_group(&mut self, id: Id, source: ValueSource) { - debug!( - "ArgMatcher::start_custom_arg: id={:?}, source={:?}", - id, source - ); - let ma = self.entry(id).or_insert(MatchedArg::new_group()); - debug_assert_eq!(ma.type_id(), None); - ma.set_source(source); - ma.new_val_group(); - } - - pub(crate) fn start_occurrence_of_external(&mut self, cmd: &crate::Command) { - let id = Id::from_static_ref(Id::EXTERNAL); - debug!("ArgMatcher::start_occurrence_of_external: id={:?}", id,); - let ma = self.entry(id).or_insert(MatchedArg::new_external(cmd)); - debug_assert_eq!( - ma.type_id(), - Some( - cmd.get_external_subcommand_value_parser() - .expect(INTERNAL_ERROR_MSG) - .type_id() - ) - ); - ma.set_source(ValueSource::CommandLine); - ma.new_val_group(); - } - - pub(crate) fn add_val_to(&mut self, arg: &Id, val: AnyValue, raw_val: OsString) { - let ma = self.get_mut(arg).expect(INTERNAL_ERROR_MSG); - ma.append_val(val, raw_val); - } - - pub(crate) fn add_index_to(&mut self, arg: &Id, idx: usize) { - let ma = self.get_mut(arg).expect(INTERNAL_ERROR_MSG); - ma.push_index(idx); - } - - pub(crate) fn needs_more_vals(&self, o: &Arg) -> bool { - let num_pending = self - .pending - .as_ref() - .and_then(|p| (p.id == *o.get_id()).then_some(p.raw_vals.len())) - .unwrap_or(0); - debug!( - "ArgMatcher::needs_more_vals: o={}, pending={}", - o.get_id(), - num_pending - ); - let expected = o.get_num_args().expect(INTERNAL_ERROR_MSG); - debug!( - "ArgMatcher::needs_more_vals: expected={}, actual={}", - expected, num_pending - ); - expected.accepts_more(num_pending) - } - - pub(crate) fn pending_arg_id(&self) -> Option<&Id> { - self.pending.as_ref().map(|p| &p.id) - } - - pub(crate) fn pending_values_mut( - &mut self, - id: &Id, - ident: Option<Identifier>, - trailing_values: bool, - ) -> &mut Vec<OsString> { - let pending = self.pending.get_or_insert_with(|| PendingArg { - id: id.clone(), - ident, - raw_vals: Default::default(), - trailing_idx: None, - }); - debug_assert_eq!(pending.id, *id, "{}", INTERNAL_ERROR_MSG); - if ident.is_some() { - debug_assert_eq!(pending.ident, ident, "{}", INTERNAL_ERROR_MSG); - } - if trailing_values { - pending.trailing_idx.get_or_insert(pending.raw_vals.len()); - } - &mut pending.raw_vals - } - - pub(crate) fn start_trailing(&mut self) { - if let Some(pending) = &mut self.pending { - // Allow asserting its started on subsequent calls - pending.trailing_idx.get_or_insert(pending.raw_vals.len()); - } - } - - pub(crate) fn take_pending(&mut self) -> Option<PendingArg> { - self.pending.take() - } -} - -impl Deref for ArgMatcher { - type Target = ArgMatches; - - fn deref(&self) -> &Self::Target { - &self.matches - } -} diff --git a/vendor/clap/src/parser/error.rs b/vendor/clap/src/parser/error.rs deleted file mode 100644 index 565233613..000000000 --- a/vendor/clap/src/parser/error.rs +++ /dev/null @@ -1,65 +0,0 @@ -/// Violation of [`ArgMatches`][crate::ArgMatches] assumptions -#[derive(Clone, Debug)] -#[allow(missing_copy_implementations)] // We might add non-Copy types in the future -#[non_exhaustive] -pub enum MatchesError { - /// Failed to downcast `AnyValue` to the specified type - #[non_exhaustive] - Downcast { - /// Type for value stored in [`ArgMatches`][crate::ArgMatches] - actual: super::AnyValueId, - /// The target type to downcast to - expected: super::AnyValueId, - }, - /// Argument not defined in [`Command`][crate::Command] - #[non_exhaustive] - UnknownArgument { - // Missing `id` but blocked on a public id type which will hopefully come with `unstable-v4` - }, -} - -impl MatchesError { - #[cfg_attr(debug_assertions, track_caller)] - pub(crate) fn unwrap<T>(id: &str, r: Result<T, MatchesError>) -> T { - let err = match r { - Ok(t) => { - return t; - } - Err(err) => err, - }; - panic!( - "Mismatch between definition and access of `{}`. {}", - id, err - ) - } -} - -impl std::error::Error for MatchesError {} - -impl std::fmt::Display for MatchesError { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - Self::Downcast { actual, expected } => { - writeln!( - f, - "Could not downcast to {:?}, need to downcast to {:?}", - expected, actual - ) - } - Self::UnknownArgument {} => { - writeln!(f, "Unknown argument or group id. Make sure you are using the argument id and not the short or long flags") - } - } - } -} - -#[test] -fn check_auto_traits() { - static_assertions::assert_impl_all!( - MatchesError: Send, - Sync, - std::panic::RefUnwindSafe, - std::panic::UnwindSafe, - Unpin - ); -} diff --git a/vendor/clap/src/parser/features/mod.rs b/vendor/clap/src/parser/features/mod.rs deleted file mode 100644 index bdeb766ec..000000000 --- a/vendor/clap/src/parser/features/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub(crate) mod suggestions; diff --git a/vendor/clap/src/parser/features/suggestions.rs b/vendor/clap/src/parser/features/suggestions.rs deleted file mode 100644 index b8bb7adfa..000000000 --- a/vendor/clap/src/parser/features/suggestions.rs +++ /dev/null @@ -1,167 +0,0 @@ -#[cfg(feature = "suggestions")] -use std::cmp::Ordering; - -// Internal -use crate::builder::Command; - -/// Find strings from an iterable of `possible_values` similar to a given value `v` -/// Returns a Vec of all possible values that exceed a similarity threshold -/// sorted by ascending similarity, most similar comes last -#[cfg(feature = "suggestions")] -pub(crate) fn did_you_mean<T, I>(v: &str, possible_values: I) -> Vec<String> -where - T: AsRef<str>, - I: IntoIterator<Item = T>, -{ - let mut candidates: Vec<(f64, String)> = possible_values - .into_iter() - // GH #4660: using `jaro` because `jaro_winkler` implementation in `strsim-rs` is wrong - // causing strings with common prefix >=10 to be considered perfectly similar - .map(|pv| (strsim::jaro(v, pv.as_ref()), pv.as_ref().to_owned())) - // Confidence of 0.7 so that bar -> baz is suggested - .filter(|(confidence, _)| *confidence > 0.7) - .collect(); - candidates.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal)); - candidates.into_iter().map(|(_, pv)| pv).collect() -} - -#[cfg(not(feature = "suggestions"))] -pub(crate) fn did_you_mean<T, I>(_: &str, _: I) -> Vec<String> -where - T: AsRef<str>, - I: IntoIterator<Item = T>, -{ - Vec::new() -} - -/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase -pub(crate) fn did_you_mean_flag<'a, 'help, I, T>( - arg: &str, - remaining_args: &[&std::ffi::OsStr], - longs: I, - subcommands: impl IntoIterator<Item = &'a mut Command>, -) -> Option<(String, Option<String>)> -where - 'help: 'a, - T: AsRef<str>, - I: IntoIterator<Item = T>, -{ - use crate::mkeymap::KeyType; - - match did_you_mean(arg, longs).pop() { - Some(candidate) => Some((candidate, None)), - None => subcommands - .into_iter() - .filter_map(|subcommand| { - subcommand._build_self(false); - - let longs = subcommand.get_keymap().keys().filter_map(|a| { - if let KeyType::Long(v) = a { - Some(v.to_string_lossy().into_owned()) - } else { - None - } - }); - - let subcommand_name = subcommand.get_name(); - - let candidate = some!(did_you_mean(arg, longs).pop()); - let score = some!(remaining_args.iter().position(|x| subcommand_name == *x)); - Some((score, (candidate, Some(subcommand_name.to_string())))) - }) - .min_by_key(|(x, _)| *x) - .map(|(_, suggestion)| suggestion), - } -} - -#[cfg(all(test, feature = "suggestions"))] -mod test { - use super::*; - - #[test] - fn missing_letter() { - let p_vals = ["test", "possible", "values"]; - assert_eq!(did_you_mean("tst", p_vals.iter()), vec!["test"]); - } - - #[test] - fn ambiguous() { - let p_vals = ["test", "temp", "possible", "values"]; - assert_eq!(did_you_mean("te", p_vals.iter()), vec!["test", "temp"]); - } - - #[test] - fn unrelated() { - let p_vals = ["test", "possible", "values"]; - assert_eq!( - did_you_mean("hahaahahah", p_vals.iter()), - Vec::<String>::new() - ); - } - - #[test] - fn best_fit() { - let p_vals = [ - "test", - "possible", - "values", - "alignmentStart", - "alignmentScore", - ]; - assert_eq!( - did_you_mean("alignmentScorr", p_vals.iter()), - vec!["alignmentStart", "alignmentScore"] - ); - } - - #[test] - fn best_fit_long_common_prefix_issue_4660() { - let p_vals = ["alignmentScore", "alignmentStart"]; - assert_eq!( - did_you_mean("alignmentScorr", p_vals.iter()), - vec!["alignmentStart", "alignmentScore"] - ); - } - - #[test] - fn flag_missing_letter() { - let p_vals = ["test", "possible", "values"]; - assert_eq!( - did_you_mean_flag("tst", &[], p_vals.iter(), []), - Some(("test".to_owned(), None)) - ); - } - - #[test] - fn flag_ambiguous() { - let p_vals = ["test", "temp", "possible", "values"]; - assert_eq!( - did_you_mean_flag("te", &[], p_vals.iter(), []), - Some(("temp".to_owned(), None)) - ); - } - - #[test] - fn flag_unrelated() { - let p_vals = ["test", "possible", "values"]; - assert_eq!( - did_you_mean_flag("hahaahahah", &[], p_vals.iter(), []), - None - ); - } - - #[test] - fn flag_best_fit() { - let p_vals = [ - "test", - "possible", - "values", - "alignmentStart", - "alignmentScore", - ]; - assert_eq!( - did_you_mean_flag("alignmentScorr", &[], p_vals.iter(), []), - Some(("alignmentScore".to_owned(), None)) - ); - } -} diff --git a/vendor/clap/src/parser/matches/any_value.rs b/vendor/clap/src/parser/matches/any_value.rs deleted file mode 100644 index dc7a3e953..000000000 --- a/vendor/clap/src/parser/matches/any_value.rs +++ /dev/null @@ -1,112 +0,0 @@ -#[derive(Clone)] -pub(crate) struct AnyValue { - inner: std::sync::Arc<dyn std::any::Any + Send + Sync + 'static>, - // While we can extract `TypeId` from `inner`, the debug repr is of a number, so let's track - // the type_name in debug builds. - id: AnyValueId, -} - -impl AnyValue { - pub(crate) fn new<V: std::any::Any + Clone + Send + Sync + 'static>(inner: V) -> Self { - let id = AnyValueId::of::<V>(); - let inner = std::sync::Arc::new(inner); - Self { inner, id } - } - - pub(crate) fn downcast_ref<T: std::any::Any + Clone + Send + Sync + 'static>( - &self, - ) -> Option<&T> { - self.inner.downcast_ref::<T>() - } - - pub(crate) fn downcast_into<T: std::any::Any + Clone + Send + Sync>(self) -> Result<T, Self> { - let id = self.id; - let value = - ok!(std::sync::Arc::downcast::<T>(self.inner).map_err(|inner| Self { inner, id })); - let value = std::sync::Arc::try_unwrap(value).unwrap_or_else(|arc| (*arc).clone()); - Ok(value) - } - - pub(crate) fn type_id(&self) -> AnyValueId { - self.id - } -} - -impl std::fmt::Debug for AnyValue { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { - f.debug_struct("AnyValue").field("inner", &self.id).finish() - } -} - -#[derive(Copy, Clone)] -pub struct AnyValueId { - type_id: std::any::TypeId, - #[cfg(debug_assertions)] - type_name: &'static str, -} - -impl AnyValueId { - pub(crate) fn of<A: ?Sized + 'static>() -> Self { - Self { - type_id: std::any::TypeId::of::<A>(), - #[cfg(debug_assertions)] - type_name: std::any::type_name::<A>(), - } - } -} - -impl PartialEq for AnyValueId { - fn eq(&self, other: &Self) -> bool { - self.type_id == other.type_id - } -} - -impl Eq for AnyValueId {} - -impl PartialOrd for AnyValueId { - fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { - self.type_id.partial_cmp(&other.type_id) - } -} - -impl Ord for AnyValueId { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.type_id.cmp(&other.type_id) - } -} - -impl std::hash::Hash for AnyValueId { - fn hash<H: std::hash::Hasher>(&self, state: &mut H) { - self.type_id.hash(state); - } -} - -impl std::fmt::Debug for AnyValueId { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { - #[cfg(not(debug_assertions))] - { - self.type_id.fmt(f) - } - #[cfg(debug_assertions)] - { - f.debug_struct(self.type_name).finish() - } - } -} - -impl<'a, A: ?Sized + 'static> From<&'a A> for AnyValueId { - fn from(_: &'a A) -> Self { - Self::of::<A>() - } -} - -#[cfg(test)] -mod test { - #[test] - #[cfg(debug_assertions)] - fn debug_impl() { - use super::*; - - assert_eq!(format!("{:?}", AnyValue::new(5)), "AnyValue { inner: i32 }"); - } -} diff --git a/vendor/clap/src/parser/matches/arg_matches.rs b/vendor/clap/src/parser/matches/arg_matches.rs deleted file mode 100644 index 23f53c02b..000000000 --- a/vendor/clap/src/parser/matches/arg_matches.rs +++ /dev/null @@ -1,1968 +0,0 @@ -// Std -use std::any::Any; -use std::ffi::{OsStr, OsString}; -use std::fmt::Debug; -use std::iter::{Cloned, Flatten, Map}; -use std::slice::Iter; - -// Internal -#[cfg(debug_assertions)] -use crate::builder::Str; -use crate::parser::AnyValue; -use crate::parser::AnyValueId; -use crate::parser::MatchedArg; -use crate::parser::MatchesError; -use crate::parser::ValueSource; -use crate::util::FlatMap; -use crate::util::Id; -use crate::INTERNAL_ERROR_MSG; - -/// Container for parse results. -/// -/// Used to get information about the arguments that were supplied to the program at runtime by -/// the user. New instances of this struct are obtained by using the [`Command::get_matches`] family of -/// methods. -/// -/// # Examples -/// -/// ```no_run -/// # use clap::{Command, Arg, ArgAction}; -/// # use clap::parser::ValueSource; -/// let matches = Command::new("MyApp") -/// .arg(Arg::new("out") -/// .long("output") -/// .required(true) -/// .action(ArgAction::Set) -/// .default_value("-")) -/// .arg(Arg::new("cfg") -/// .short('c') -/// .action(ArgAction::Set)) -/// .get_matches(); // builds the instance of ArgMatches -/// -/// // to get information about the "cfg" argument we created, such as the value supplied we use -/// // various ArgMatches methods, such as [ArgMatches::get_one] -/// if let Some(c) = matches.get_one::<String>("cfg") { -/// println!("Value for -c: {}", c); -/// } -/// -/// // The ArgMatches::get_one method returns an Option because the user may not have supplied -/// // that argument at runtime. But if we specified that the argument was "required" as we did -/// // with the "out" argument, we can safely unwrap because `clap` verifies that was actually -/// // used at runtime. -/// println!("Value for --output: {}", matches.get_one::<String>("out").unwrap()); -/// -/// // You can check the presence of an argument's values -/// if matches.contains_id("out") { -/// // However, if you want to know where the value came from -/// if matches.value_source("out").expect("checked contains_id") == ValueSource::CommandLine { -/// println!("`out` set by user"); -/// } else { -/// println!("`out` is defaulted"); -/// } -/// } -/// ``` -/// [`Command::get_matches`]: crate::Command::get_matches() -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct ArgMatches { - #[cfg(debug_assertions)] - pub(crate) valid_args: Vec<Id>, - #[cfg(debug_assertions)] - pub(crate) valid_subcommands: Vec<Str>, - pub(crate) args: FlatMap<Id, MatchedArg>, - pub(crate) subcommand: Option<Box<SubCommand>>, -} - -/// # Arguments -impl ArgMatches { - /// Gets the value of a specific option or positional argument. - /// - /// i.e. an argument that [takes an additional value][crate::Arg::num_args] at runtime. - /// - /// Returns an error if the wrong type was used. - /// - /// Returns `None` if the option wasn't present. - /// - /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set. - /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime. - /// - /// # Panic - /// - /// If the argument definition and access mismatch. To handle this case programmatically, see - /// [`ArgMatches::try_get_one`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, value_parser, ArgAction}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("port") - /// .value_parser(value_parser!(usize)) - /// .action(ArgAction::Set) - /// .required(true)) - /// .get_matches_from(vec!["myapp", "2020"]); - /// - /// let port: usize = *m - /// .get_one("port") - /// .expect("`port`is required"); - /// assert_eq!(port, 2020); - /// ``` - /// [positional]: crate::Arg::index() - /// [`default_value`]: crate::Arg::default_value() - #[cfg_attr(debug_assertions, track_caller)] - pub fn get_one<T: Any + Clone + Send + Sync + 'static>(&self, id: &str) -> Option<&T> { - MatchesError::unwrap(id, self.try_get_one(id)) - } - - /// Gets the value of a specific [`ArgAction::Count`][crate::ArgAction::Count] flag - /// - /// # Panic - /// - /// If the argument's action is not [`ArgAction::Count`][crate::ArgAction::Count] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::Count) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); - /// assert_eq!( - /// matches.get_count("flag"), - /// 2 - /// ); - /// ``` - #[cfg_attr(debug_assertions, track_caller)] - pub fn get_count(&self, id: &str) -> u8 { - *self - .get_one::<u8>(id) - .expect("ArgAction::Count is defaulted") - } - - /// Gets the value of a specific [`ArgAction::SetTrue`][crate::ArgAction::SetTrue] or [`ArgAction::SetFalse`][crate::ArgAction::SetFalse] flag - /// - /// # Panic - /// - /// If the argument's action is not [`ArgAction::SetTrue`][crate::ArgAction::SetTrue] or [`ArgAction::SetFalse`][crate::ArgAction::SetFalse] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Command; - /// # use clap::Arg; - /// let cmd = Command::new("mycmd") - /// .arg( - /// Arg::new("flag") - /// .long("flag") - /// .action(clap::ArgAction::SetTrue) - /// ); - /// - /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); - /// assert!(matches.contains_id("flag")); - /// assert_eq!( - /// matches.get_flag("flag"), - /// true - /// ); - /// ``` - #[cfg_attr(debug_assertions, track_caller)] - pub fn get_flag(&self, id: &str) -> bool { - *self - .get_one::<bool>(id) - .expect("ArgAction::SetTrue / ArgAction::SetFalse is defaulted") - } - - /// Iterate over values of a specific option or positional argument. - /// - /// i.e. an argument that takes multiple values at runtime. - /// - /// Returns an error if the wrong type was used. - /// - /// Returns `None` if the option wasn't present. - /// - /// # Panic - /// - /// If the argument definition and access mismatch. To handle this case programmatically, see - /// [`ArgMatches::try_get_many`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, value_parser, ArgAction}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("ports") - /// .action(ArgAction::Append) - /// .value_parser(value_parser!(usize)) - /// .short('p') - /// .required(true)) - /// .get_matches_from(vec![ - /// "myprog", "-p", "22", "-p", "80", "-p", "2020" - /// ]); - /// let vals: Vec<usize> = m.get_many("ports") - /// .expect("`port`is required") - /// .copied() - /// .collect(); - /// assert_eq!(vals, [22, 80, 2020]); - /// ``` - #[cfg_attr(debug_assertions, track_caller)] - pub fn get_many<T: Any + Clone + Send + Sync + 'static>( - &self, - id: &str, - ) -> Option<ValuesRef<T>> { - MatchesError::unwrap(id, self.try_get_many(id)) - } - - /// Iterate over the values passed to each occurrence of an option. - /// - /// Each item is itself an iterator containing the arguments passed to a single occurrence - /// of the option. - /// - /// If the option doesn't support multiple occurrences, or there was only a single occurrence, - /// the iterator will only contain a single item. - /// - /// Returns `None` if the option wasn't present. - /// - /// # Panics - /// - /// If the argument definition and access mismatch. To handle this case programmatically, see - /// [`ArgMatches::try_get_occurrences`]. - /// - /// # Examples - /// ```rust - /// # use clap::{Command,Arg, ArgAction, value_parser}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("x") - /// .short('x') - /// .num_args(2) - /// .action(ArgAction::Append) - /// .value_parser(value_parser!(String))) - /// .get_matches_from(vec![ - /// "myprog", "-x", "a", "b", "-x", "c", "d"]); - /// let vals: Vec<Vec<&String>> = m.get_occurrences("x").unwrap().map(Iterator::collect).collect(); - /// assert_eq!(vals, [["a", "b"], ["c", "d"]]); - /// ``` - #[cfg_attr(debug_assertions, track_caller)] - pub fn get_occurrences<T: Any + Clone + Send + Sync + 'static>( - &self, - id: &str, - ) -> Option<OccurrencesRef<T>> { - MatchesError::unwrap(id, self.try_get_occurrences(id)) - } - - /// Iterate over the original argument values. - /// - /// An `OsStr` on Unix-like systems is any series of bytes, regardless of whether or not they - /// contain valid UTF-8. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid - /// filename on a Unix system as an argument value may contain invalid UTF-8. - /// - /// Returns `None` if the option wasn't present. - /// - /// # Panic - /// - /// If the argument definition and access mismatch. To handle this case programmatically, see - /// [`ArgMatches::try_get_raw`]. - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{Command, arg, value_parser}; - /// # use std::ffi::{OsStr,OsString}; - /// # use std::os::unix::ffi::{OsStrExt,OsStringExt}; - /// use std::path::PathBuf; - /// - /// let m = Command::new("utf8") - /// .arg(arg!(<arg> ... "some arg").value_parser(value_parser!(PathBuf))) - /// .get_matches_from(vec![OsString::from("myprog"), - /// // "Hi" - /// OsString::from_vec(vec![b'H', b'i']), - /// // "{0xe9}!" - /// OsString::from_vec(vec![0xe9, b'!'])]); - /// - /// let mut itr = m.get_raw("arg") - /// .expect("`port`is required") - /// .into_iter(); - /// assert_eq!(itr.next(), Some(OsStr::new("Hi"))); - /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!']))); - /// assert_eq!(itr.next(), None); - /// ``` - /// [`Iterator`]: std::iter::Iterator - /// [`OsSt`]: std::ffi::OsStr - /// [values]: OsValues - /// [`String`]: std::string::String - #[cfg_attr(debug_assertions, track_caller)] - pub fn get_raw(&self, id: &str) -> Option<RawValues<'_>> { - MatchesError::unwrap(id, self.try_get_raw(id)) - } - - /// Iterate over the original values for each occurrence of an option. - /// - /// Similar to [`ArgMatches::get_occurrences`] but returns raw values. - /// - /// An `OsStr` on Unix-like systems is any series of bytes, regardless of whether or not they - /// contain valid UTF-8. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid - /// filename on a Unix system as an argument value may contain invalid UTF-8. - /// - /// Returns `None` if the option wasn't present. - /// - /// # Panic - /// - /// If the argument definition and access mismatch. To handle this case programmatically, see - /// [`ArgMatches::try_get_raw_occurrences`]. - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{Command, arg, value_parser, ArgAction, Arg}; - /// # use std::ffi::{OsStr,OsString}; - /// # use std::os::unix::ffi::{OsStrExt,OsStringExt}; - /// use std::path::PathBuf; - /// - /// let m = Command::new("myprog") - /// .arg(Arg::new("x") - /// .short('x') - /// .num_args(2) - /// .action(ArgAction::Append) - /// .value_parser(value_parser!(PathBuf))) - /// .get_matches_from(vec![OsString::from("myprog"), - /// OsString::from("-x"), - /// OsString::from("a"), OsString::from("b"), - /// OsString::from("-x"), - /// OsString::from("c"), - /// // "{0xe9}!" - /// OsString::from_vec(vec![0xe9, b'!'])]); - /// let mut itr = m.get_raw_occurrences("x") - /// .expect("`-x`is required") - /// .map(Iterator::collect::<Vec<_>>); - /// assert_eq!(itr.next(), Some(vec![OsStr::new("a"), OsStr::new("b")])); - /// assert_eq!(itr.next(), Some(vec![OsStr::new("c"), OsStr::from_bytes(&[0xe9, b'!'])])); - /// assert_eq!(itr.next(), None); - /// ``` - /// [`Iterator`]: std::iter::Iterator - /// [`OsStr`]: std::ffi::OsStr - /// [values]: OsValues - /// [`String`]: std::string::String - #[cfg_attr(debug_assertions, track_caller)] - pub fn get_raw_occurrences(&self, id: &str) -> Option<RawOccurrences<'_>> { - MatchesError::unwrap(id, self.try_get_raw_occurrences(id)) - } - - /// Returns the value of a specific option or positional argument. - /// - /// i.e. an argument that [takes an additional value][crate::Arg::num_args] at runtime. - /// - /// Returns an error if the wrong type was used. No item will have been removed. - /// - /// Returns `None` if the option wasn't present. - /// - /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set. - /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime. - /// - /// # Panic - /// - /// If the argument definition and access mismatch. To handle this case programmatically, see - /// [`ArgMatches::try_remove_one`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, value_parser, ArgAction}; - /// let mut m = Command::new("myprog") - /// .arg(Arg::new("file") - /// .required(true) - /// .action(ArgAction::Set)) - /// .get_matches_from(vec![ - /// "myprog", "file.txt", - /// ]); - /// let vals: String = m.remove_one("file") - /// .expect("`file`is required"); - /// assert_eq!(vals, "file.txt"); - /// ``` - /// [positional]: crate::Arg::index() - /// [`default_value`]: crate::Arg::default_value() - #[cfg_attr(debug_assertions, track_caller)] - pub fn remove_one<T: Any + Clone + Send + Sync + 'static>(&mut self, id: &str) -> Option<T> { - MatchesError::unwrap(id, self.try_remove_one(id)) - } - - /// Return values of a specific option or positional argument. - /// - /// i.e. an argument that takes multiple values at runtime. - /// - /// Returns an error if the wrong type was used. No item will have been removed. - /// - /// Returns `None` if the option wasn't present. - /// - /// # Panic - /// - /// If the argument definition and access mismatch. To handle this case programmatically, see - /// [`ArgMatches::try_remove_many`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, value_parser, ArgAction}; - /// let mut m = Command::new("myprog") - /// .arg(Arg::new("file") - /// .action(ArgAction::Append) - /// .num_args(1..) - /// .required(true)) - /// .get_matches_from(vec![ - /// "myprog", "file1.txt", "file2.txt", "file3.txt", "file4.txt", - /// ]); - /// let vals: Vec<String> = m.remove_many("file") - /// .expect("`file`is required") - /// .collect(); - /// assert_eq!(vals, ["file1.txt", "file2.txt", "file3.txt", "file4.txt"]); - /// ``` - #[cfg_attr(debug_assertions, track_caller)] - pub fn remove_many<T: Any + Clone + Send + Sync + 'static>( - &mut self, - id: &str, - ) -> Option<Values<T>> { - MatchesError::unwrap(id, self.try_remove_many(id)) - } - - /// Return values for each occurrence of an option. - /// - /// Each item is itself an iterator containing the arguments passed to a single occurrence of - /// the option. - /// - /// If the option doesn't support multiple occurrences, or there was only a single occurrence, - /// the iterator will only contain a single item. - /// - /// Returns `None` if the option wasn't present. - /// - /// # Panic - /// - /// If the argument definition and access mismatch. To handle this case programmatically, see - /// [`ArgMatches::try_remove_occurrences`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, value_parser, ArgAction}; - /// let mut m = Command::new("myprog") - /// .arg(Arg::new("x") - /// .short('x') - /// .num_args(2) - /// .action(ArgAction::Append) - /// .value_parser(value_parser!(String))) - /// .get_matches_from(vec![ - /// "myprog", "-x", "a", "b", "-x", "c", "d"]); - /// let vals: Vec<Vec<String>> = m.remove_occurrences("x").unwrap().map(Iterator::collect).collect(); - /// assert_eq!(vals, [["a", "b"], ["c", "d"]]); - /// ``` - #[cfg_attr(debug_assertions, track_caller)] - pub fn remove_occurrences<T: Any + Clone + Send + Sync + 'static>( - &mut self, - id: &str, - ) -> Option<Occurrences<T>> { - MatchesError::unwrap(id, self.try_remove_occurrences(id)) - } - - /// Check if values are present for the argument or group id - /// - /// *NOTE:* This will always return `true` if [`default_value`] has been set. - /// [`ArgMatches::value_source`] can be used to check if a value is present at runtime. - /// - /// # Panics - /// - /// If `id` is not a valid argument or group name. To handle this case programmatically, see - /// [`ArgMatches::try_contains_id`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("debug") - /// .short('d') - /// .action(ArgAction::SetTrue)) - /// .get_matches_from(vec![ - /// "myprog", "-d" - /// ]); - /// - /// assert!(m.contains_id("debug")); - /// ``` - /// - /// [`default_value`]: crate::Arg::default_value() - pub fn contains_id(&self, id: &str) -> bool { - MatchesError::unwrap(id, self.try_contains_id(id)) - } - - /// Iterate over [`Arg`][crate::Arg] and [`ArgGroup`][crate::ArgGroup] [`Id`][crate::Id]s via [`ArgMatches::ids`]. - /// - /// # Examples - /// - /// ``` - /// # use clap::{Command, arg, value_parser}; - /// - /// let m = Command::new("myprog") - /// .arg(arg!(--color <when>) - /// .value_parser(["auto", "always", "never"])) - /// .arg(arg!(--config <path>) - /// .value_parser(value_parser!(std::path::PathBuf))) - /// .get_matches_from(["myprog", "--config=config.toml", "--color=auto"]); - /// assert_eq!(m.ids().len(), 2); - /// assert_eq!( - /// m.ids() - /// .map(|id| id.as_str()) - /// .collect::<Vec<_>>(), - /// ["config", "color"] - /// ); - /// ``` - pub fn ids(&self) -> IdsRef<'_> { - IdsRef { - iter: self.args.keys(), - } - } - - /// Check if any args were present on the command line - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let mut cmd = Command::new("myapp") - /// .arg(Arg::new("output") - /// .action(ArgAction::Set)); - /// - /// let m = cmd - /// .try_get_matches_from_mut(vec!["myapp", "something"]) - /// .unwrap(); - /// assert!(m.args_present()); - /// - /// let m = cmd - /// .try_get_matches_from_mut(vec!["myapp"]) - /// .unwrap(); - /// assert!(! m.args_present()); - pub fn args_present(&self) -> bool { - !self.args.is_empty() - } - - /// Get an [`Iterator`] over groups of values of a specific option. - /// - /// specifically grouped by the occurrences of the options. - /// - /// Each group is a `Vec<&str>` containing the arguments passed to a single occurrence - /// of the option. - /// - /// If the option doesn't support multiple occurrences, or there was only a single occurrence, - /// the iterator will only contain a single item. - /// - /// Returns `None` if the option wasn't present. - /// - /// # Panics - /// - /// If the value is invalid UTF-8. - /// - /// If `id` is not a valid argument or group id. - /// - /// # Examples - /// ```rust - /// # use clap::{Command,Arg, ArgAction}; - /// let m = Command::new("myprog") - /// .arg(Arg::new("exec") - /// .short('x') - /// .num_args(1..) - /// .action(ArgAction::Append) - /// .value_terminator(";")) - /// .get_matches_from(vec![ - /// "myprog", "-x", "echo", "hi", ";", "-x", "echo", "bye"]); - /// let vals: Vec<Vec<&str>> = m.grouped_values_of("exec").unwrap().collect(); - /// assert_eq!(vals, [["echo", "hi"], ["echo", "bye"]]); - /// ``` - /// [`Iterator`]: std::iter::Iterator - #[cfg(feature = "unstable-grouped")] - #[cfg_attr(debug_assertions, track_caller)] - #[deprecated( - since = "4.1.0", - note = "Use get_occurrences or remove_occurrences instead" - )] - #[allow(deprecated)] - pub fn grouped_values_of(&self, id: &str) -> Option<GroupedValues> { - let arg = some!(self.get_arg(id)); - let v = GroupedValues { - iter: arg.vals().map(|g| g.iter().map(unwrap_string).collect()), - len: arg.vals().len(), - }; - Some(v) - } - - /// Report where argument value came from - /// - /// # Panics - /// - /// If `id` is not a valid argument or group id. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// # use clap::parser::ValueSource; - /// let m = Command::new("myprog") - /// .arg(Arg::new("debug") - /// .short('d') - /// .action(ArgAction::SetTrue)) - /// .get_matches_from(vec![ - /// "myprog", "-d" - /// ]); - /// - /// assert_eq!(m.value_source("debug"), Some(ValueSource::CommandLine)); - /// ``` - /// - /// [`default_value`]: crate::Arg::default_value() - #[cfg_attr(debug_assertions, track_caller)] - pub fn value_source(&self, id: &str) -> Option<ValueSource> { - let value = self.get_arg(id); - - value.and_then(MatchedArg::source) - } - - /// The first index of that an argument showed up. - /// - /// Indices are similar to argv indices, but are not exactly 1:1. - /// - /// For flags (i.e. those arguments which don't have an associated value), indices refer - /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices - /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the - /// index for `val` would be recorded. This is by design. - /// - /// Besides the flag/option discrepancy, the primary difference between an argv index and clap - /// index, is that clap continues counting once all arguments have properly separated, whereas - /// an argv index does not. - /// - /// The examples should clear this up. - /// - /// *NOTE:* If an argument is allowed multiple times, this method will only give the *first* - /// index. See [`ArgMatches::indices_of`]. - /// - /// # Panics - /// - /// If `id` is not a valid argument or group id. - /// - /// # Examples - /// - /// The argv indices are listed in the comments below. See how they correspond to the clap - /// indices. Note that if it's not listed in a clap index, this is because it's not saved in - /// in an `ArgMatches` struct for querying. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("option") - /// .short('o') - /// .action(ArgAction::Set)) - /// .get_matches_from(vec!["myapp", "-f", "-o", "val"]); - /// // ARGV indices: ^0 ^1 ^2 ^3 - /// // clap indices: ^1 ^3 - /// - /// assert_eq!(m.index_of("flag"), Some(1)); - /// assert_eq!(m.index_of("option"), Some(3)); - /// ``` - /// - /// Now notice, if we use one of the other styles of options: - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("option") - /// .short('o') - /// .action(ArgAction::Set)) - /// .get_matches_from(vec!["myapp", "-f", "-o=val"]); - /// // ARGV indices: ^0 ^1 ^2 - /// // clap indices: ^1 ^3 - /// - /// assert_eq!(m.index_of("flag"), Some(1)); - /// assert_eq!(m.index_of("option"), Some(3)); - /// ``` - /// - /// Things become much more complicated, or clear if we look at a more complex combination of - /// flags. Let's also throw in the final option style for good measure. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("flag2") - /// .short('F') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("flag3") - /// .short('z') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("option") - /// .short('o') - /// .action(ArgAction::Set)) - /// .get_matches_from(vec!["myapp", "-fzF", "-oval"]); - /// // ARGV indices: ^0 ^1 ^2 - /// // clap indices: ^1,2,3 ^5 - /// // - /// // clap sees the above as 'myapp -f -z -F -o val' - /// // ^0 ^1 ^2 ^3 ^4 ^5 - /// assert_eq!(m.index_of("flag"), Some(1)); - /// assert_eq!(m.index_of("flag2"), Some(3)); - /// assert_eq!(m.index_of("flag3"), Some(2)); - /// assert_eq!(m.index_of("option"), Some(5)); - /// ``` - /// - /// One final combination of flags/options to see how they combine: - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("flag2") - /// .short('F') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("flag3") - /// .short('z') - /// .action(ArgAction::SetTrue)) - /// .arg(Arg::new("option") - /// .short('o') - /// .action(ArgAction::Set)) - /// .get_matches_from(vec!["myapp", "-fzFoval"]); - /// // ARGV indices: ^0 ^1 - /// // clap indices: ^1,2,3^5 - /// // - /// // clap sees the above as 'myapp -f -z -F -o val' - /// // ^0 ^1 ^2 ^3 ^4 ^5 - /// assert_eq!(m.index_of("flag"), Some(1)); - /// assert_eq!(m.index_of("flag2"), Some(3)); - /// assert_eq!(m.index_of("flag3"), Some(2)); - /// assert_eq!(m.index_of("option"), Some(5)); - /// ``` - /// - /// The last part to mention is when values are sent in multiple groups with a [delimiter]. - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("option") - /// .short('o') - /// .value_delimiter(',') - /// .num_args(1..)) - /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); - /// // ARGV indices: ^0 ^1 - /// // clap indices: ^2 ^3 ^4 - /// // - /// // clap sees the above as 'myapp -o val1 val2 val3' - /// // ^0 ^1 ^2 ^3 ^4 - /// assert_eq!(m.index_of("option"), Some(2)); - /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]); - /// ``` - /// [delimiter]: crate::Arg::value_delimiter() - #[cfg_attr(debug_assertions, track_caller)] - pub fn index_of(&self, id: &str) -> Option<usize> { - let arg = some!(self.get_arg(id)); - let i = some!(arg.get_index(0)); - Some(i) - } - - /// All indices an argument appeared at when parsing. - /// - /// Indices are similar to argv indices, but are not exactly 1:1. - /// - /// For flags (i.e. those arguments which don't have an associated value), indices refer - /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices - /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the - /// index for `val` would be recorded. This is by design. - /// - /// *NOTE:* For more information about how clap indices compared to argv indices, see - /// [`ArgMatches::index_of`] - /// - /// # Panics - /// - /// If `id` is not a valid argument or group id. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("option") - /// .short('o') - /// .value_delimiter(',')) - /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); - /// // ARGV indices: ^0 ^1 - /// // clap indices: ^2 ^3 ^4 - /// // - /// // clap sees the above as 'myapp -o val1 val2 val3' - /// // ^0 ^1 ^2 ^3 ^4 - /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]); - /// ``` - /// - /// Another quick example is when flags and options are used together - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("option") - /// .short('o') - /// .action(ArgAction::Set) - /// .action(ArgAction::Append)) - /// .arg(Arg::new("flag") - /// .short('f') - /// .action(ArgAction::Count)) - /// .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]); - /// // ARGV indices: ^0 ^1 ^2 ^3 ^4 ^5 ^6 - /// // clap indices: ^2 ^3 ^5 ^6 - /// - /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 5]); - /// assert_eq!(m.indices_of("flag").unwrap().collect::<Vec<_>>(), &[6]); - /// ``` - /// - /// One final example, which is an odd case; if we *don't* use value delimiter as we did with - /// the first example above instead of `val1`, `val2` and `val3` all being distinc values, they - /// would all be a single value of `val1,val2,val3`, in which case they'd only receive a single - /// index. - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let m = Command::new("myapp") - /// .arg(Arg::new("option") - /// .short('o') - /// .action(ArgAction::Set) - /// .num_args(1..)) - /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); - /// // ARGV indices: ^0 ^1 - /// // clap indices: ^2 - /// // - /// // clap sees the above as 'myapp -o "val1,val2,val3"' - /// // ^0 ^1 ^2 - /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2]); - /// ``` - /// [`ArgMatches::index_of`]: ArgMatches::index_of() - /// [delimiter]: Arg::value_delimiter() - #[cfg_attr(debug_assertions, track_caller)] - pub fn indices_of(&self, id: &str) -> Option<Indices<'_>> { - let arg = some!(self.get_arg(id)); - let i = Indices { - iter: arg.indices(), - len: arg.num_vals(), - }; - Some(i) - } -} - -/// # Subcommands -impl ArgMatches { - /// The name and `ArgMatches` of the current [subcommand]. - /// - /// Subcommand values are put in a child [`ArgMatches`] - /// - /// Returns `None` if the subcommand wasn't present at runtime, - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let app_m = Command::new("git") - /// .subcommand(Command::new("clone")) - /// .subcommand(Command::new("push")) - /// .subcommand(Command::new("commit")) - /// .get_matches(); - /// - /// match app_m.subcommand() { - /// Some(("clone", sub_m)) => {}, // clone was used - /// Some(("push", sub_m)) => {}, // push was used - /// Some(("commit", sub_m)) => {}, // commit was used - /// _ => {}, // Either no subcommand or one not tested for... - /// } - /// ``` - /// - /// Another useful scenario is when you want to support third party, or external, subcommands. - /// In these cases you can't know the subcommand name ahead of time, so use a variable instead - /// with pattern matching! - /// - /// ```rust - /// # use std::ffi::OsString; - /// # use std::ffi::OsStr; - /// # use clap::Command; - /// // Assume there is an external subcommand named "subcmd" - /// let app_m = Command::new("myprog") - /// .allow_external_subcommands(true) - /// .get_matches_from(vec![ - /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" - /// ]); - /// - /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty - /// // string argument name - /// match app_m.subcommand() { - /// Some((external, sub_m)) => { - /// let ext_args: Vec<&OsStr> = sub_m.get_many::<OsString>("") - /// .unwrap().map(|s| s.as_os_str()).collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// [subcommand]: crate::Command::subcommand - #[inline] - pub fn subcommand(&self) -> Option<(&str, &ArgMatches)> { - self.subcommand.as_ref().map(|sc| (&*sc.name, &sc.matches)) - } - - /// Return the name and `ArgMatches` of the current [subcommand]. - /// - /// Subcommand values are put in a child [`ArgMatches`] - /// - /// Returns `None` if the subcommand wasn't present at runtime, - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let mut app_m = Command::new("git") - /// .subcommand(Command::new("clone")) - /// .subcommand(Command::new("push")) - /// .subcommand(Command::new("commit")) - /// .subcommand_required(true) - /// .get_matches(); - /// - /// let (name, sub_m) = app_m.remove_subcommand().expect("required"); - /// match (name.as_str(), sub_m) { - /// ("clone", sub_m) => {}, // clone was used - /// ("push", sub_m) => {}, // push was used - /// ("commit", sub_m) => {}, // commit was used - /// (name, _) => unimplemented!("{}", name), - /// } - /// ``` - /// - /// Another useful scenario is when you want to support third party, or external, subcommands. - /// In these cases you can't know the subcommand name ahead of time, so use a variable instead - /// with pattern matching! - /// - /// ```rust - /// # use std::ffi::OsString; - /// # use clap::Command; - /// // Assume there is an external subcommand named "subcmd" - /// let mut app_m = Command::new("myprog") - /// .allow_external_subcommands(true) - /// .get_matches_from(vec![ - /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" - /// ]); - /// - /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty - /// // string argument name - /// match app_m.remove_subcommand() { - /// Some((external, mut sub_m)) => { - /// let ext_args: Vec<OsString> = sub_m.remove_many("") - /// .expect("`file`is required") - /// .collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// [subcommand]: crate::Command::subcommand - pub fn remove_subcommand(&mut self) -> Option<(String, ArgMatches)> { - self.subcommand.take().map(|sc| (sc.name, sc.matches)) - } - - /// The `ArgMatches` for the current [subcommand]. - /// - /// Subcommand values are put in a child [`ArgMatches`] - /// - /// Returns `None` if the subcommand wasn't present at runtime, - /// - /// # Panics - /// - /// If `id` is not a valid subcommand. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{Command, Arg, ArgAction}; - /// let app_m = Command::new("myprog") - /// .arg(Arg::new("debug") - /// .short('d') - /// .action(ArgAction::SetTrue) - /// ) - /// .subcommand(Command::new("test") - /// .arg(Arg::new("opt") - /// .long("option") - /// .action(ArgAction::Set))) - /// .get_matches_from(vec![ - /// "myprog", "-d", "test", "--option", "val" - /// ]); - /// - /// // Both parent commands, and child subcommands can have arguments present at the same times - /// assert!(app_m.get_flag("debug")); - /// - /// // Get the subcommand's ArgMatches instance - /// if let Some(sub_m) = app_m.subcommand_matches("test") { - /// // Use the struct like normal - /// assert_eq!(sub_m.get_one::<String>("opt").map(|s| s.as_str()), Some("val")); - /// } - /// ``` - /// - /// [subcommand]: crate::Command::subcommand - /// [`Command`]: crate::Command - pub fn subcommand_matches(&self, name: &str) -> Option<&ArgMatches> { - self.get_subcommand(name).map(|sc| &sc.matches) - } - - /// The name of the current [subcommand]. - /// - /// Returns `None` if the subcommand wasn't present at runtime, - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{Command, Arg, }; - /// let app_m = Command::new("git") - /// .subcommand(Command::new("clone")) - /// .subcommand(Command::new("push")) - /// .subcommand(Command::new("commit")) - /// .get_matches(); - /// - /// match app_m.subcommand_name() { - /// Some("clone") => {}, // clone was used - /// Some("push") => {}, // push was used - /// Some("commit") => {}, // commit was used - /// _ => {}, // Either no subcommand or one not tested for... - /// } - /// ``` - /// [subcommand]: crate::Command::subcommand - /// [`Command`]: crate::Command - #[inline] - pub fn subcommand_name(&self) -> Option<&str> { - self.subcommand.as_ref().map(|sc| &*sc.name) - } - - /// Check if a subcommand can be queried - /// - /// By default, `ArgMatches` functions assert on undefined `Id`s to help catch programmer - /// mistakes. In some context, this doesn't work, so users can use this function to check - /// before they do a query on `ArgMatches`. - #[inline] - #[doc(hidden)] - pub fn is_valid_subcommand(&self, _name: &str) -> bool { - #[cfg(debug_assertions)] - { - _name.is_empty() || self.valid_subcommands.iter().any(|s| *s == _name) - } - #[cfg(not(debug_assertions))] - { - true - } - } -} - -/// # Advanced -impl ArgMatches { - /// Non-panicking version of [`ArgMatches::get_one`] - pub fn try_get_one<T: Any + Clone + Send + Sync + 'static>( - &self, - id: &str, - ) -> Result<Option<&T>, MatchesError> { - let arg = ok!(self.try_get_arg_t::<T>(id)); - let value = match arg.and_then(|a| a.first()) { - Some(value) => value, - None => { - return Ok(None); - } - }; - Ok(value - .downcast_ref::<T>() - .map(Some) - .expect(INTERNAL_ERROR_MSG)) // enforced by `try_get_arg_t` - } - - /// Non-panicking version of [`ArgMatches::get_many`] - pub fn try_get_many<T: Any + Clone + Send + Sync + 'static>( - &self, - id: &str, - ) -> Result<Option<ValuesRef<T>>, MatchesError> { - let arg = match ok!(self.try_get_arg_t::<T>(id)) { - Some(arg) => arg, - None => return Ok(None), - }; - let len = arg.num_vals(); - let values = arg.vals_flatten(); - let values = ValuesRef { - // enforced by `try_get_arg_t` - iter: values.map(unwrap_downcast_ref), - len, - }; - Ok(Some(values)) - } - - /// Non-panicking version of [`ArgMatches::get_occurrences`] - pub fn try_get_occurrences<T: Any + Clone + Send + Sync + 'static>( - &self, - id: &str, - ) -> Result<Option<OccurrencesRef<T>>, MatchesError> { - let arg = match ok!(self.try_get_arg_t::<T>(id)) { - Some(arg) => arg, - None => return Ok(None), - }; - let values = arg.vals(); - Ok(Some(OccurrencesRef { - iter: values.map(|g| OccurrenceValuesRef { - iter: g.iter().map(unwrap_downcast_ref), - }), - })) - } - - /// Non-panicking version of [`ArgMatches::get_raw`] - pub fn try_get_raw(&self, id: &str) -> Result<Option<RawValues<'_>>, MatchesError> { - let arg = match ok!(self.try_get_arg(id)) { - Some(arg) => arg, - None => return Ok(None), - }; - let len = arg.num_vals(); - let values = arg.raw_vals_flatten(); - let values = RawValues { - iter: values.map(OsString::as_os_str), - len, - }; - Ok(Some(values)) - } - - /// Non-panicking version of [`ArgMatches::get_raw_occurrences`] - pub fn try_get_raw_occurrences( - &self, - id: &str, - ) -> Result<Option<RawOccurrences<'_>>, MatchesError> { - let arg = match ok!(self.try_get_arg(id)) { - Some(arg) => arg, - None => return Ok(None), - }; - let values = arg.raw_vals(); - let occurrences = RawOccurrences { - iter: values.map(|g| RawOccurrenceValues { - iter: g.iter().map(OsString::as_os_str), - }), - }; - Ok(Some(occurrences)) - } - - /// Non-panicking version of [`ArgMatches::remove_one`] - pub fn try_remove_one<T: Any + Clone + Send + Sync + 'static>( - &mut self, - id: &str, - ) -> Result<Option<T>, MatchesError> { - match ok!(self.try_remove_arg_t::<T>(id)) { - Some(values) => Ok(values - .into_vals_flatten() - // enforced by `try_get_arg_t` - .map(unwrap_downcast_into) - .next()), - None => Ok(None), - } - } - - /// Non-panicking version of [`ArgMatches::remove_many`] - pub fn try_remove_many<T: Any + Clone + Send + Sync + 'static>( - &mut self, - id: &str, - ) -> Result<Option<Values<T>>, MatchesError> { - let arg = match ok!(self.try_remove_arg_t::<T>(id)) { - Some(arg) => arg, - None => return Ok(None), - }; - let len = arg.num_vals(); - let values = arg.into_vals_flatten(); - let values = Values { - // enforced by `try_get_arg_t` - iter: values.map(unwrap_downcast_into), - len, - }; - Ok(Some(values)) - } - - /// Non-panicking version of [`ArgMatches::remove_occurrences`] - pub fn try_remove_occurrences<T: Any + Clone + Send + Sync + 'static>( - &mut self, - id: &str, - ) -> Result<Option<Occurrences<T>>, MatchesError> { - let arg = match ok!(self.try_remove_arg_t::<T>(id)) { - Some(arg) => arg, - None => return Ok(None), - }; - let values = arg.into_vals(); - let occurrences = Occurrences { - iter: values.into_iter().map(|g| OccurrenceValues { - iter: g.into_iter().map(unwrap_downcast_into), - }), - }; - Ok(Some(occurrences)) - } - - /// Non-panicking version of [`ArgMatches::contains_id`] - pub fn try_contains_id(&self, id: &str) -> Result<bool, MatchesError> { - ok!(self.verify_arg(id)); - - let presence = self.args.contains_key(id); - Ok(presence) - } -} - -// Private methods -impl ArgMatches { - #[inline] - fn try_get_arg(&self, arg: &str) -> Result<Option<&MatchedArg>, MatchesError> { - ok!(self.verify_arg(arg)); - Ok(self.args.get(arg)) - } - - #[inline] - fn try_get_arg_t<T: Any + Send + Sync + 'static>( - &self, - arg: &str, - ) -> Result<Option<&MatchedArg>, MatchesError> { - let arg = match ok!(self.try_get_arg(arg)) { - Some(arg) => arg, - None => { - return Ok(None); - } - }; - ok!(self.verify_arg_t::<T>(arg)); - Ok(Some(arg)) - } - - #[inline] - fn try_remove_arg_t<T: Any + Send + Sync + 'static>( - &mut self, - arg: &str, - ) -> Result<Option<MatchedArg>, MatchesError> { - ok!(self.verify_arg(arg)); - let (id, matched) = match self.args.remove_entry(arg) { - Some((id, matched)) => (id, matched), - None => { - return Ok(None); - } - }; - - let expected = AnyValueId::of::<T>(); - let actual = matched.infer_type_id(expected); - if actual == expected { - Ok(Some(matched)) - } else { - self.args.insert(id, matched); - Err(MatchesError::Downcast { actual, expected }) - } - } - - fn verify_arg_t<T: Any + Send + Sync + 'static>( - &self, - arg: &MatchedArg, - ) -> Result<(), MatchesError> { - let expected = AnyValueId::of::<T>(); - let actual = arg.infer_type_id(expected); - if expected == actual { - Ok(()) - } else { - Err(MatchesError::Downcast { actual, expected }) - } - } - - #[inline] - fn verify_arg(&self, _arg: &str) -> Result<(), MatchesError> { - #[cfg(debug_assertions)] - { - if _arg == Id::EXTERNAL || self.valid_args.iter().any(|s| *s == _arg) { - } else { - debug!( - "`{:?}` is not an id of an argument or a group.\n\ - Make sure you're using the name of the argument itself \ - and not the name of short or long flags.", - _arg - ); - return Err(MatchesError::UnknownArgument {}); - } - } - Ok(()) - } - - #[inline] - #[cfg_attr(debug_assertions, track_caller)] - fn get_arg<'s>(&'s self, arg: &str) -> Option<&'s MatchedArg> { - #[cfg(debug_assertions)] - { - if arg == Id::EXTERNAL || self.valid_args.iter().any(|s| *s == arg) { - } else { - panic!( - "`{:?}` is not an id of an argument or a group.\n\ - Make sure you're using the name of the argument itself \ - and not the name of short or long flags.", - arg - ); - } - } - - self.args.get(arg) - } - - #[inline] - #[cfg_attr(debug_assertions, track_caller)] - fn get_subcommand(&self, name: &str) -> Option<&SubCommand> { - #[cfg(debug_assertions)] - { - if name.is_empty() || self.valid_subcommands.iter().any(|s| *s == name) { - } else { - panic!("`{}` is not a name of a subcommand.", name); - } - } - - if let Some(ref sc) = self.subcommand { - if sc.name == name { - return Some(sc); - } - } - - None - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct SubCommand { - pub(crate) name: String, - pub(crate) matches: ArgMatches, -} - -/// Iterate over [`Arg`][crate::Arg] and [`ArgGroup`][crate::ArgGroup] [`Id`][crate::Id]s via [`ArgMatches::ids`]. -/// -/// # Examples -/// -/// ``` -/// # use clap::{Command, arg, value_parser}; -/// -/// let m = Command::new("myprog") -/// .arg(arg!(--color <when>) -/// .value_parser(["auto", "always", "never"])) -/// .arg(arg!(--config <path>) -/// .value_parser(value_parser!(std::path::PathBuf))) -/// .get_matches_from(["myprog", "--config=config.toml", "--color=auto"]); -/// assert_eq!( -/// m.ids() -/// .map(|id| id.as_str()) -/// .collect::<Vec<_>>(), -/// ["config", "color"] -/// ); -/// ``` -#[derive(Clone, Debug)] -pub struct IdsRef<'a> { - iter: std::slice::Iter<'a, Id>, -} - -impl<'a> Iterator for IdsRef<'a> { - type Item = &'a Id; - - fn next(&mut self) -> Option<&'a Id> { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option<usize>) { - self.iter.size_hint() - } -} - -impl<'a> DoubleEndedIterator for IdsRef<'a> { - fn next_back(&mut self) -> Option<&'a Id> { - self.iter.next_back() - } -} - -impl<'a> ExactSizeIterator for IdsRef<'a> {} - -/// Iterate over multiple values for an argument via [`ArgMatches::remove_many`]. -/// -/// # Examples -/// -/// ```rust -/// # use clap::{Command, Arg, ArgAction}; -/// let mut m = Command::new("myapp") -/// .arg(Arg::new("output") -/// .short('o') -/// .action(ArgAction::Append)) -/// .get_matches_from(vec!["myapp", "-o", "val1", "-o", "val2"]); -/// -/// let mut values = m.remove_many::<String>("output") -/// .unwrap(); -/// -/// assert_eq!(values.next(), Some(String::from("val1"))); -/// assert_eq!(values.next(), Some(String::from("val2"))); -/// assert_eq!(values.next(), None); -/// ``` -#[derive(Clone, Debug)] -pub struct Values<T> { - #[allow(clippy::type_complexity)] - iter: Map<Flatten<std::vec::IntoIter<Vec<AnyValue>>>, fn(AnyValue) -> T>, - len: usize, -} - -impl<T> Iterator for Values<T> { - type Item = T; - - fn next(&mut self) -> Option<Self::Item> { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option<usize>) { - (self.len, Some(self.len)) - } -} - -impl<T> DoubleEndedIterator for Values<T> { - fn next_back(&mut self) -> Option<Self::Item> { - self.iter.next_back() - } -} - -impl<T> ExactSizeIterator for Values<T> {} - -/// Creates an empty iterator. -impl<T> Default for Values<T> { - fn default() -> Self { - let empty: Vec<Vec<AnyValue>> = Default::default(); - Values { - iter: empty.into_iter().flatten().map(|_| unreachable!()), - len: 0, - } - } -} - -/// Iterate over multiple values for an argument via [`ArgMatches::get_many`]. -/// -/// # Examples -/// -/// ```rust -/// # use clap::{Command, Arg, ArgAction}; -/// let m = Command::new("myapp") -/// .arg(Arg::new("output") -/// .short('o') -/// .action(ArgAction::Append)) -/// .get_matches_from(vec!["myapp", "-o", "val1", "-o", "val2"]); -/// -/// let mut values = m.get_many::<String>("output") -/// .unwrap() -/// .map(|s| s.as_str()); -/// -/// assert_eq!(values.next(), Some("val1")); -/// assert_eq!(values.next(), Some("val2")); -/// assert_eq!(values.next(), None); -/// ``` -#[derive(Clone, Debug)] -pub struct ValuesRef<'a, T> { - #[allow(clippy::type_complexity)] - iter: Map<Flatten<Iter<'a, Vec<AnyValue>>>, fn(&AnyValue) -> &T>, - len: usize, -} - -impl<'a, T: 'a> Iterator for ValuesRef<'a, T> { - type Item = &'a T; - - fn next(&mut self) -> Option<Self::Item> { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option<usize>) { - (self.len, Some(self.len)) - } -} - -impl<'a, T: 'a> DoubleEndedIterator for ValuesRef<'a, T> { - fn next_back(&mut self) -> Option<Self::Item> { - self.iter.next_back() - } -} - -impl<'a, T: 'a> ExactSizeIterator for ValuesRef<'a, T> {} - -/// Creates an empty iterator. -impl<'a, T: 'a> Default for ValuesRef<'a, T> { - fn default() -> Self { - static EMPTY: [Vec<AnyValue>; 0] = []; - ValuesRef { - iter: EMPTY[..].iter().flatten().map(|_| unreachable!()), - len: 0, - } - } -} - -/// Iterate over raw argument values via [`ArgMatches::get_raw`]. -/// -/// # Examples -/// -#[cfg_attr(not(unix), doc = " ```ignore")] -#[cfg_attr(unix, doc = " ```")] -/// # use clap::{Command, arg, value_parser}; -/// use std::ffi::OsString; -/// use std::os::unix::ffi::{OsStrExt,OsStringExt}; -/// -/// let m = Command::new("utf8") -/// .arg(arg!(<arg> "some arg") -/// .value_parser(value_parser!(OsString))) -/// .get_matches_from(vec![OsString::from("myprog"), -/// // "Hi {0xe9}!" -/// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); -/// assert_eq!( -/// &*m.get_raw("arg") -/// .unwrap() -/// .next().unwrap() -/// .as_bytes(), -/// [b'H', b'i', b' ', 0xe9, b'!'] -/// ); -/// ``` -#[derive(Clone, Debug)] -pub struct RawValues<'a> { - #[allow(clippy::type_complexity)] - iter: Map<Flatten<Iter<'a, Vec<OsString>>>, fn(&OsString) -> &OsStr>, - len: usize, -} - -impl<'a> Iterator for RawValues<'a> { - type Item = &'a OsStr; - - fn next(&mut self) -> Option<&'a OsStr> { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option<usize>) { - (self.len, Some(self.len)) - } -} - -impl<'a> DoubleEndedIterator for RawValues<'a> { - fn next_back(&mut self) -> Option<&'a OsStr> { - self.iter.next_back() - } -} - -impl<'a> ExactSizeIterator for RawValues<'a> {} - -/// Creates an empty iterator. -impl Default for RawValues<'_> { - fn default() -> Self { - static EMPTY: [Vec<OsString>; 0] = []; - RawValues { - iter: EMPTY[..].iter().flatten().map(|_| unreachable!()), - len: 0, - } - } -} - -// The following were taken and adapted from vec_map source -// repo: https://github.com/contain-rs/vec-map -// commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33 -// license: MIT - Copyright (c) 2015 The Rust Project Developers - -#[derive(Clone, Debug)] -#[deprecated(since = "4.1.0", note = "Use Occurrences instead")] -pub struct GroupedValues<'a> { - #[allow(clippy::type_complexity)] - iter: Map<Iter<'a, Vec<AnyValue>>, fn(&Vec<AnyValue>) -> Vec<&str>>, - len: usize, -} - -#[allow(deprecated)] -impl<'a> Iterator for GroupedValues<'a> { - type Item = Vec<&'a str>; - - fn next(&mut self) -> Option<Self::Item> { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option<usize>) { - (self.len, Some(self.len)) - } -} - -#[allow(deprecated)] -impl<'a> DoubleEndedIterator for GroupedValues<'a> { - fn next_back(&mut self) -> Option<Self::Item> { - self.iter.next_back() - } -} - -#[allow(deprecated)] -impl<'a> ExactSizeIterator for GroupedValues<'a> {} - -/// Creates an empty iterator. Used for `unwrap_or_default()`. -#[allow(deprecated)] -impl<'a> Default for GroupedValues<'a> { - fn default() -> Self { - static EMPTY: [Vec<AnyValue>; 0] = []; - GroupedValues { - iter: EMPTY[..].iter().map(|_| unreachable!()), - len: 0, - } - } -} - -#[derive(Clone, Debug)] -pub struct Occurrences<T> { - #[allow(clippy::type_complexity)] - iter: Map<std::vec::IntoIter<Vec<AnyValue>>, fn(Vec<AnyValue>) -> OccurrenceValues<T>>, -} - -impl<T> Iterator for Occurrences<T> { - type Item = OccurrenceValues<T>; - - fn next(&mut self) -> Option<Self::Item> { - self.iter.next() - } - - fn size_hint(&self) -> (usize, Option<usize>) { - self.iter.size_hint() - } -} - -impl<T> DoubleEndedIterator for Occurrences<T> { - fn next_back(&mut self) -> Option<Self::Item> { - self.iter.next_back() - } -} - -impl<T> ExactSizeIterator for Occurrences<T> {} - -impl<T> Default for Occurrences<T> { - fn default() -> Self { - let empty: Vec<Vec<AnyValue>> = Default::default(); - Occurrences { - iter: empty.into_iter().map(|_| unreachable!()), - } - } -} - -#[derive(Clone, Debug)] -pub struct OccurrenceValues<T> { - #[allow(clippy::type_complexity)] - iter: Map<std::vec::IntoIter<AnyValue>, fn(AnyValue) -> T>, -} - -impl<T> Iterator for OccurrenceValues<T> { - type Item = T; - - fn next(&mut self) -> Option<Self::Item> { - self.iter.next() - } - - fn size_hint(&self) -> (usize, Option<usize>) { - self.iter.size_hint() - } -} - -impl<T> DoubleEndedIterator for OccurrenceValues<T> { - fn next_back(&mut self) -> Option<Self::Item> { - self.iter.next_back() - } -} - -impl<T> ExactSizeIterator for OccurrenceValues<T> {} - -#[derive(Clone, Debug)] -pub struct OccurrencesRef<'a, T> { - #[allow(clippy::type_complexity)] - iter: Map<Iter<'a, Vec<AnyValue>>, fn(&Vec<AnyValue>) -> OccurrenceValuesRef<'_, T>>, -} - -impl<'a, T> Iterator for OccurrencesRef<'a, T> -where - Self: 'a, -{ - type Item = OccurrenceValuesRef<'a, T>; - - fn next(&mut self) -> Option<Self::Item> { - self.iter.next() - } - - fn size_hint(&self) -> (usize, Option<usize>) { - self.iter.size_hint() - } -} - -impl<'a, T> DoubleEndedIterator for OccurrencesRef<'a, T> -where - Self: 'a, -{ - fn next_back(&mut self) -> Option<Self::Item> { - self.iter.next_back() - } -} - -impl<'a, T> ExactSizeIterator for OccurrencesRef<'a, T> where Self: 'a {} -impl<'a, T> Default for OccurrencesRef<'a, T> { - fn default() -> Self { - static EMPTY: [Vec<AnyValue>; 0] = []; - OccurrencesRef { - iter: EMPTY[..].iter().map(|_| unreachable!()), - } - } -} - -#[derive(Clone, Debug)] -pub struct OccurrenceValuesRef<'a, T> { - #[allow(clippy::type_complexity)] - iter: Map<Iter<'a, AnyValue>, fn(&AnyValue) -> &T>, -} - -impl<'a, T> Iterator for OccurrenceValuesRef<'a, T> -where - Self: 'a, -{ - type Item = &'a T; - - fn next(&mut self) -> Option<Self::Item> { - self.iter.next() - } - - fn size_hint(&self) -> (usize, Option<usize>) { - self.iter.size_hint() - } -} - -impl<'a, T> DoubleEndedIterator for OccurrenceValuesRef<'a, T> -where - Self: 'a, -{ - fn next_back(&mut self) -> Option<Self::Item> { - self.iter.next_back() - } -} - -impl<'a, T> ExactSizeIterator for OccurrenceValuesRef<'a, T> where Self: 'a {} - -#[derive(Clone, Debug)] -pub struct RawOccurrences<'a> { - #[allow(clippy::type_complexity)] - iter: Map<Iter<'a, Vec<OsString>>, fn(&Vec<OsString>) -> RawOccurrenceValues<'_>>, -} - -impl<'a> Iterator for RawOccurrences<'a> { - type Item = RawOccurrenceValues<'a>; - - fn next(&mut self) -> Option<Self::Item> { - self.iter.next() - } - - fn size_hint(&self) -> (usize, Option<usize>) { - self.iter.size_hint() - } -} - -impl<'a> DoubleEndedIterator for RawOccurrences<'a> { - fn next_back(&mut self) -> Option<Self::Item> { - self.iter.next_back() - } -} - -impl<'a> ExactSizeIterator for RawOccurrences<'a> {} - -impl<'a> Default for RawOccurrences<'a> { - fn default() -> Self { - static EMPTY: [Vec<OsString>; 0] = []; - RawOccurrences { - iter: EMPTY[..].iter().map(|_| unreachable!()), - } - } -} - -#[derive(Clone, Debug)] -pub struct RawOccurrenceValues<'a> { - #[allow(clippy::type_complexity)] - iter: Map<Iter<'a, OsString>, fn(&OsString) -> &OsStr>, -} - -impl<'a> Iterator for RawOccurrenceValues<'a> -where - Self: 'a, -{ - type Item = &'a OsStr; - - fn next(&mut self) -> Option<Self::Item> { - self.iter.next() - } - - fn size_hint(&self) -> (usize, Option<usize>) { - self.iter.size_hint() - } -} - -impl<'a> DoubleEndedIterator for RawOccurrenceValues<'a> -where - Self: 'a, -{ - fn next_back(&mut self) -> Option<Self::Item> { - self.iter.next_back() - } -} - -impl<'a> ExactSizeIterator for RawOccurrenceValues<'a> {} - -/// Iterate over indices for where an argument appeared when parsing, via [`ArgMatches::indices_of`] -/// -/// # Examples -/// -/// ```rust -/// # use clap::{Command, Arg, ArgAction}; -/// let m = Command::new("myapp") -/// .arg(Arg::new("output") -/// .short('o') -/// .num_args(1..) -/// .action(ArgAction::Set)) -/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]); -/// -/// let mut indices = m.indices_of("output").unwrap(); -/// -/// assert_eq!(indices.next(), Some(2)); -/// assert_eq!(indices.next(), Some(3)); -/// assert_eq!(indices.next(), None); -/// ``` -/// [`ArgMatches::indices_of`]: ArgMatches::indices_of() -#[derive(Clone, Debug)] -pub struct Indices<'a> { - iter: Cloned<Iter<'a, usize>>, - len: usize, -} - -impl<'a> Iterator for Indices<'a> { - type Item = usize; - - fn next(&mut self) -> Option<usize> { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option<usize>) { - (self.len, Some(self.len)) - } -} - -impl<'a> DoubleEndedIterator for Indices<'a> { - fn next_back(&mut self) -> Option<usize> { - self.iter.next_back() - } -} - -impl<'a> ExactSizeIterator for Indices<'a> {} - -/// Creates an empty iterator. -impl<'a> Default for Indices<'a> { - fn default() -> Self { - static EMPTY: [usize; 0] = []; - // This is never called because the iterator is empty: - Indices { - iter: EMPTY[..].iter().cloned(), - len: 0, - } - } -} - -#[cfg_attr(debug_assertions, track_caller)] -#[inline] -#[cfg(feature = "unstable-grouped")] -fn unwrap_string(value: &AnyValue) -> &str { - match value.downcast_ref::<String>() { - Some(value) => value, - None => { - panic!("Must use `_os` lookups with `Arg::allow_invalid_utf8`",) - } - } -} - -#[track_caller] -fn unwrap_downcast_ref<T: Any + Clone + Send + Sync + 'static>(value: &AnyValue) -> &T { - value.downcast_ref().expect(INTERNAL_ERROR_MSG) -} - -#[track_caller] -fn unwrap_downcast_into<T: Any + Clone + Send + Sync + 'static>(value: AnyValue) -> T { - value.downcast_into().expect(INTERNAL_ERROR_MSG) -} - -#[cfg(test)] -mod tests { - use super::*; - - use crate::ArgAction; - - #[test] - fn check_auto_traits() { - static_assertions::assert_impl_all!(ArgMatches: Send, Sync, Unpin); - } - - #[test] - fn test_default_raw_values() { - let mut values: RawValues = Default::default(); - assert_eq!(values.next(), None); - } - - #[test] - fn test_default_indices() { - let mut indices: Indices = Indices::default(); - assert_eq!(indices.next(), None); - } - - #[test] - fn test_default_indices_with_shorter_lifetime() { - let matches = ArgMatches::default(); - let mut indices = matches.indices_of("").unwrap_or_default(); - assert_eq!(indices.next(), None); - } - - #[test] - fn values_exact_size() { - let l = crate::Command::new("test") - .arg( - crate::Arg::new("POTATO") - .action(ArgAction::Set) - .num_args(1..) - .required(true), - ) - .try_get_matches_from(["test", "one"]) - .unwrap() - .get_many::<String>("POTATO") - .expect("present") - .count(); - assert_eq!(l, 1); - } - - #[test] - fn os_values_exact_size() { - let l = crate::Command::new("test") - .arg( - crate::Arg::new("POTATO") - .action(ArgAction::Set) - .num_args(1..) - .value_parser(crate::builder::ValueParser::os_string()) - .required(true), - ) - .try_get_matches_from(["test", "one"]) - .unwrap() - .get_many::<std::ffi::OsString>("POTATO") - .expect("present") - .count(); - assert_eq!(l, 1); - } - - #[test] - fn indices_exact_size() { - let l = crate::Command::new("test") - .arg( - crate::Arg::new("POTATO") - .action(ArgAction::Set) - .num_args(1..) - .required(true), - ) - .try_get_matches_from(["test", "one"]) - .unwrap() - .indices_of("POTATO") - .expect("present") - .len(); - assert_eq!(l, 1); - } -} diff --git a/vendor/clap/src/parser/matches/matched_arg.rs b/vendor/clap/src/parser/matches/matched_arg.rs deleted file mode 100644 index 901990cfb..000000000 --- a/vendor/clap/src/parser/matches/matched_arg.rs +++ /dev/null @@ -1,225 +0,0 @@ -// Std -use std::{ - ffi::{OsStr, OsString}, - iter::{Cloned, Flatten}, - slice::Iter, -}; - -use crate::builder::ArgPredicate; -use crate::parser::AnyValue; -use crate::parser::AnyValueId; -use crate::parser::ValueSource; -use crate::util::eq_ignore_case; -use crate::INTERNAL_ERROR_MSG; - -#[derive(Debug, Clone)] -pub(crate) struct MatchedArg { - source: Option<ValueSource>, - indices: Vec<usize>, - type_id: Option<AnyValueId>, - vals: Vec<Vec<AnyValue>>, - raw_vals: Vec<Vec<OsString>>, - ignore_case: bool, -} - -impl MatchedArg { - pub(crate) fn new_arg(arg: &crate::Arg) -> Self { - let ignore_case = arg.is_ignore_case_set(); - Self { - source: None, - indices: Vec::new(), - type_id: Some(arg.get_value_parser().type_id()), - vals: Vec::new(), - raw_vals: Vec::new(), - ignore_case, - } - } - - pub(crate) fn new_group() -> Self { - let ignore_case = false; - Self { - source: None, - indices: Vec::new(), - type_id: None, - vals: Vec::new(), - raw_vals: Vec::new(), - ignore_case, - } - } - - pub(crate) fn new_external(cmd: &crate::Command) -> Self { - let ignore_case = false; - Self { - source: None, - indices: Vec::new(), - type_id: Some( - cmd.get_external_subcommand_value_parser() - .expect(INTERNAL_ERROR_MSG) - .type_id(), - ), - vals: Vec::new(), - raw_vals: Vec::new(), - ignore_case, - } - } - - pub(crate) fn indices(&self) -> Cloned<Iter<'_, usize>> { - self.indices.iter().cloned() - } - - pub(crate) fn get_index(&self, index: usize) -> Option<usize> { - self.indices.get(index).cloned() - } - - pub(crate) fn push_index(&mut self, index: usize) { - self.indices.push(index) - } - - pub(crate) fn vals(&self) -> Iter<Vec<AnyValue>> { - self.vals.iter() - } - - pub(crate) fn into_vals(self) -> Vec<Vec<AnyValue>> { - self.vals - } - - pub(crate) fn vals_flatten(&self) -> Flatten<Iter<Vec<AnyValue>>> { - self.vals.iter().flatten() - } - - pub(crate) fn into_vals_flatten(self) -> Flatten<std::vec::IntoIter<Vec<AnyValue>>> { - self.vals.into_iter().flatten() - } - - pub(crate) fn raw_vals(&self) -> Iter<Vec<OsString>> { - self.raw_vals.iter() - } - - pub(crate) fn raw_vals_flatten(&self) -> Flatten<Iter<Vec<OsString>>> { - self.raw_vals.iter().flatten() - } - - pub(crate) fn first(&self) -> Option<&AnyValue> { - self.vals_flatten().next() - } - - #[cfg(test)] - pub(crate) fn first_raw(&self) -> Option<&OsString> { - self.raw_vals_flatten().next() - } - - pub(crate) fn new_val_group(&mut self) { - self.vals.push(vec![]); - self.raw_vals.push(vec![]); - } - - pub(crate) fn append_val(&mut self, val: AnyValue, raw_val: OsString) { - // We assume there is always a group created before. - self.vals.last_mut().expect(INTERNAL_ERROR_MSG).push(val); - self.raw_vals - .last_mut() - .expect(INTERNAL_ERROR_MSG) - .push(raw_val); - } - - pub(crate) fn num_vals(&self) -> usize { - self.vals.iter().map(|v| v.len()).sum() - } - - // Will be used later - #[allow(dead_code)] - pub(crate) fn num_vals_last_group(&self) -> usize { - self.vals.last().map(|x| x.len()).unwrap_or(0) - } - - pub(crate) fn all_val_groups_empty(&self) -> bool { - self.vals.iter().flatten().count() == 0 - } - - pub(crate) fn check_explicit(&self, predicate: &ArgPredicate) -> bool { - if self.source.map(|s| !s.is_explicit()).unwrap_or(false) { - return false; - } - - match predicate { - ArgPredicate::Equals(val) => self.raw_vals_flatten().any(|v| { - if self.ignore_case { - // If `v` isn't utf8, it can't match `val`, so `OsStr::to_str` should be fine - eq_ignore_case(&v.to_string_lossy(), &val.to_string_lossy()) - } else { - OsString::as_os_str(v) == OsStr::new(val) - } - }), - ArgPredicate::IsPresent => true, - } - } - - pub(crate) fn source(&self) -> Option<ValueSource> { - self.source - } - - pub(crate) fn set_source(&mut self, source: ValueSource) { - if let Some(existing) = self.source { - self.source = Some(existing.max(source)); - } else { - self.source = Some(source) - } - } - - pub(crate) fn type_id(&self) -> Option<AnyValueId> { - self.type_id - } - - pub(crate) fn infer_type_id(&self, expected: AnyValueId) -> AnyValueId { - self.type_id() - .or_else(|| { - self.vals_flatten() - .map(|v| v.type_id()) - .find(|actual| *actual != expected) - }) - .unwrap_or(expected) - } -} - -impl PartialEq for MatchedArg { - fn eq(&self, other: &MatchedArg) -> bool { - let MatchedArg { - source: self_source, - indices: self_indices, - type_id: self_type_id, - vals: _, - raw_vals: self_raw_vals, - ignore_case: self_ignore_case, - } = self; - let MatchedArg { - source: other_source, - indices: other_indices, - type_id: other_type_id, - vals: _, - raw_vals: other_raw_vals, - ignore_case: other_ignore_case, - } = other; - self_source == other_source - && self_indices == other_indices - && self_type_id == other_type_id - && self_raw_vals == other_raw_vals - && self_ignore_case == other_ignore_case - } -} - -impl Eq for MatchedArg {} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_grouped_vals_first() { - let mut m = MatchedArg::new_group(); - m.new_val_group(); - m.new_val_group(); - m.append_val(AnyValue::new(String::from("bbb")), "bbb".into()); - m.append_val(AnyValue::new(String::from("ccc")), "ccc".into()); - assert_eq!(m.first_raw(), Some(&OsString::from("bbb"))); - } -} diff --git a/vendor/clap/src/parser/matches/mod.rs b/vendor/clap/src/parser/matches/mod.rs deleted file mode 100644 index 0e3474fb3..000000000 --- a/vendor/clap/src/parser/matches/mod.rs +++ /dev/null @@ -1,16 +0,0 @@ -mod any_value; -mod arg_matches; -mod matched_arg; -mod value_source; - -pub use any_value::AnyValueId; -pub use arg_matches::IdsRef; -pub use arg_matches::RawValues; -pub use arg_matches::Values; -pub use arg_matches::ValuesRef; -pub use arg_matches::{ArgMatches, Indices}; -pub use value_source::ValueSource; - -pub(crate) use any_value::AnyValue; -pub(crate) use arg_matches::SubCommand; -pub(crate) use matched_arg::MatchedArg; diff --git a/vendor/clap/src/parser/matches/value_source.rs b/vendor/clap/src/parser/matches/value_source.rs deleted file mode 100644 index db45d9c0f..000000000 --- a/vendor/clap/src/parser/matches/value_source.rs +++ /dev/null @@ -1,17 +0,0 @@ -/// Origin of the argument's value -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -#[non_exhaustive] -pub enum ValueSource { - /// Value came [`Arg::default_value`][crate::Arg::default_value] - DefaultValue, - /// Value came [`Arg::env`][crate::Arg::env] - EnvVariable, - /// Value was passed in on the command-line - CommandLine, -} - -impl ValueSource { - pub(crate) fn is_explicit(self) -> bool { - self != Self::DefaultValue - } -} diff --git a/vendor/clap/src/parser/mod.rs b/vendor/clap/src/parser/mod.rs deleted file mode 100644 index c99e74f95..000000000 --- a/vendor/clap/src/parser/mod.rs +++ /dev/null @@ -1,27 +0,0 @@ -//! [`Command`][crate::Command] line argument parser - -mod arg_matcher; -mod error; -mod matches; -#[allow(clippy::module_inception)] -mod parser; -mod validator; - -pub(crate) mod features; - -pub(crate) use self::arg_matcher::ArgMatcher; -pub(crate) use self::matches::AnyValue; -pub(crate) use self::matches::AnyValueId; -pub(crate) use self::matches::{MatchedArg, SubCommand}; -pub(crate) use self::parser::Identifier; -pub(crate) use self::parser::PendingArg; -pub(crate) use self::parser::{ParseState, Parser}; -pub(crate) use self::validator::get_possible_values_cli; -pub(crate) use self::validator::Validator; - -pub use self::matches::IdsRef; -pub use self::matches::RawValues; -pub use self::matches::Values; -pub use self::matches::ValuesRef; -pub use self::matches::{ArgMatches, Indices, ValueSource}; -pub use error::MatchesError; diff --git a/vendor/clap/src/parser/parser.rs b/vendor/clap/src/parser/parser.rs deleted file mode 100644 index dc99e32ec..000000000 --- a/vendor/clap/src/parser/parser.rs +++ /dev/null @@ -1,1643 +0,0 @@ -// Std -use std::{ - cell::Cell, - ffi::{OsStr, OsString}, -}; - -// Third Party -use clap_lex::RawOsStr; -use clap_lex::RawOsString; - -// Internal -use crate::builder::{Arg, Command}; -use crate::error::Error as ClapError; -use crate::error::Result as ClapResult; -use crate::mkeymap::KeyType; -use crate::output::Usage; -use crate::parser::features::suggestions; -use crate::parser::AnyValue; -use crate::parser::{ArgMatcher, SubCommand}; -use crate::parser::{Validator, ValueSource}; -use crate::util::Id; -use crate::ArgAction; -use crate::INTERNAL_ERROR_MSG; - -pub(crate) struct Parser<'cmd> { - cmd: &'cmd mut Command, - cur_idx: Cell<usize>, - /// Index of the previous flag subcommand in a group of flags. - flag_subcmd_at: Option<usize>, - /// Counter indicating the number of items to skip - /// when revisiting the group of flags which includes the flag subcommand. - flag_subcmd_skip: usize, -} - -// Initializing Methods -impl<'cmd> Parser<'cmd> { - pub(crate) fn new(cmd: &'cmd mut Command) -> Self { - Parser { - cmd, - cur_idx: Cell::new(0), - flag_subcmd_at: None, - flag_subcmd_skip: 0, - } - } -} - -// Parsing Methods -impl<'cmd> Parser<'cmd> { - // The actual parsing function - #[allow(clippy::cognitive_complexity)] - pub(crate) fn get_matches_with( - &mut self, - matcher: &mut ArgMatcher, - raw_args: &mut clap_lex::RawArgs, - mut args_cursor: clap_lex::ArgCursor, - ) -> ClapResult<()> { - debug!("Parser::get_matches_with"); - // Verify all positional assertions pass - - let mut subcmd_name: Option<String> = None; - let mut keep_state = false; - let mut parse_state = ParseState::ValuesDone; - let mut pos_counter = 1; - - // Already met any valid arg(then we shouldn't expect subcommands after it). - let mut valid_arg_found = false; - // If the user already passed '--'. Meaning only positional args follow. - let mut trailing_values = false; - - // Count of positional args - let positional_count = self - .cmd - .get_keymap() - .keys() - .filter(|x| x.is_position()) - .count(); - // If any arg sets .last(true) - let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set()); - - while let Some(arg_os) = raw_args.next(&mut args_cursor) { - // Recover the replaced items if any. - if let Some(replaced_items) = arg_os - .to_value() - .ok() - .and_then(|a| self.cmd.get_replacement(a)) - { - debug!( - "Parser::get_matches_with: found replacer: {:?}, target: {:?}", - arg_os, replaced_items - ); - raw_args.insert(&args_cursor, replaced_items); - continue; - } - - debug!( - "Parser::get_matches_with: Begin parsing '{:?}' ({:?})", - arg_os.to_value_os(), - arg_os.to_value_os().as_raw_bytes() - ); - - // Has the user already passed '--'? Meaning only positional args follow - if !trailing_values { - if self.cmd.is_subcommand_precedence_over_arg_set() - || !matches!(parse_state, ParseState::Opt(_) | ParseState::Pos(_)) - { - // Does the arg match a subcommand name, or any of its aliases (if defined) - let sc_name = self.possible_subcommand(arg_os.to_value(), valid_arg_found); - debug!("Parser::get_matches_with: sc={:?}", sc_name); - if let Some(sc_name) = sc_name { - if sc_name == "help" && !self.cmd.is_disable_help_subcommand_set() { - ok!(self.parse_help_subcommand(raw_args.remaining(&mut args_cursor))); - unreachable!("`parse_help_subcommand` always errors"); - } else { - subcmd_name = Some(sc_name.to_owned()); - } - break; - } - } - - if arg_os.is_escape() { - if matches!(&parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if - self.cmd[opt].is_allow_hyphen_values_set()) - { - // ParseResult::MaybeHyphenValue, do nothing - } else { - debug!("Parser::get_matches_with: setting TrailingVals=true"); - trailing_values = true; - matcher.start_trailing(); - continue; - } - } else if let Some((long_arg, long_value)) = arg_os.to_long() { - let parse_result = ok!(self.parse_long_arg( - matcher, - long_arg, - long_value, - &parse_state, - pos_counter, - &mut valid_arg_found, - )); - debug!( - "Parser::get_matches_with: After parse_long_arg {:?}", - parse_result - ); - match parse_result { - ParseResult::NoArg => { - unreachable!("`to_long` always has the flag specified") - } - ParseResult::ValuesDone => { - parse_state = ParseState::ValuesDone; - continue; - } - ParseResult::Opt(id) => { - parse_state = ParseState::Opt(id); - continue; - } - ParseResult::FlagSubCommand(name) => { - debug!( - "Parser::get_matches_with: FlagSubCommand found in long arg {:?}", - &name - ); - subcmd_name = Some(name); - break; - } - ParseResult::EqualsNotProvided { arg } => { - let _ = self.resolve_pending(matcher); - return Err(ClapError::no_equals( - self.cmd, - arg, - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - ParseResult::NoMatchingArg { arg } => { - let _ = self.resolve_pending(matcher); - let remaining_args: Vec<_> = - raw_args.remaining(&mut args_cursor).collect(); - return Err(self.did_you_mean_error( - &arg, - matcher, - &remaining_args, - trailing_values, - )); - } - ParseResult::UnneededAttachedValue { rest, used, arg } => { - let _ = self.resolve_pending(matcher); - return Err(ClapError::too_many_values( - self.cmd, - rest, - arg, - Usage::new(self.cmd).create_usage_with_title(&used), - )); - } - ParseResult::MaybeHyphenValue => { - // Maybe a hyphen value, do nothing. - } - ParseResult::AttachedValueNotConsumed => { - unreachable!() - } - } - } else if let Some(short_arg) = arg_os.to_short() { - // Arg looks like a short flag, and not a possible number - - // Try to parse short args like normal, if allow_hyphen_values or - // AllowNegativeNumbers is set, parse_short_arg will *not* throw - // an error, and instead return Ok(None) - let parse_result = ok!(self.parse_short_arg( - matcher, - short_arg, - &parse_state, - pos_counter, - &mut valid_arg_found, - )); - // If it's None, we then check if one of those two AppSettings was set - debug!( - "Parser::get_matches_with: After parse_short_arg {:?}", - parse_result - ); - match parse_result { - ParseResult::NoArg => { - // Is a single dash `-`, try positional. - } - ParseResult::ValuesDone => { - parse_state = ParseState::ValuesDone; - continue; - } - ParseResult::Opt(id) => { - parse_state = ParseState::Opt(id); - continue; - } - ParseResult::FlagSubCommand(name) => { - // If there are more short flags to be processed, we should keep the state, and later - // revisit the current group of short flags skipping the subcommand. - keep_state = self - .flag_subcmd_at - .map(|at| { - raw_args - .seek(&mut args_cursor, clap_lex::SeekFrom::Current(-1)); - // Since we are now saving the current state, the number of flags to skip during state recovery should - // be the current index (`cur_idx`) minus ONE UNIT TO THE LEFT of the starting position. - self.flag_subcmd_skip = self.cur_idx.get() - at + 1; - }) - .is_some(); - - debug!( - "Parser::get_matches_with:FlagSubCommandShort: subcmd_name={}, keep_state={}, flag_subcmd_skip={}", - name, - keep_state, - self.flag_subcmd_skip - ); - - subcmd_name = Some(name); - break; - } - ParseResult::EqualsNotProvided { arg } => { - let _ = self.resolve_pending(matcher); - return Err(ClapError::no_equals( - self.cmd, - arg, - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - ParseResult::NoMatchingArg { arg } => { - let _ = self.resolve_pending(matcher); - // We already know it looks like a flag - let suggested_trailing_arg = - !trailing_values && self.cmd.has_positionals(); - return Err(ClapError::unknown_argument( - self.cmd, - arg, - None, - suggested_trailing_arg, - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - ParseResult::MaybeHyphenValue => { - // Maybe a hyphen value, do nothing. - } - ParseResult::UnneededAttachedValue { .. } - | ParseResult::AttachedValueNotConsumed => unreachable!(), - } - } - - if let ParseState::Opt(id) = &parse_state { - // Assume this is a value of a previous arg. - - // get the option so we can check the settings - let arg = &self.cmd[id]; - let parse_result = if let Some(parse_result) = - self.check_terminator(arg, arg_os.to_value_os()) - { - parse_result - } else { - let trailing_values = false; - let arg_values = matcher.pending_values_mut(id, None, trailing_values); - arg_values.push(arg_os.to_value_os().to_os_str().into_owned()); - if matcher.needs_more_vals(arg) { - ParseResult::Opt(arg.get_id().clone()) - } else { - ParseResult::ValuesDone - } - }; - parse_state = match parse_result { - ParseResult::Opt(id) => ParseState::Opt(id), - ParseResult::ValuesDone => ParseState::ValuesDone, - _ => unreachable!(), - }; - // get the next value from the iterator - continue; - } - } - - // Correct pos_counter. - pos_counter = { - let is_second_to_last = pos_counter + 1 == positional_count; - - // The last positional argument, or second to last positional - // argument may be set to .multiple_values(true) or `.multiple_occurrences(true)` - let low_index_mults = is_second_to_last - && self.cmd.get_positionals().any(|a| { - a.is_multiple() && (positional_count != a.get_index().unwrap_or(0)) - }) - && self - .cmd - .get_positionals() - .last() - .map_or(false, |p_name| !p_name.is_last_set()); - - let missing_pos = self.cmd.is_allow_missing_positional_set() - && is_second_to_last - && !trailing_values; - - debug!( - "Parser::get_matches_with: Positional counter...{}", - pos_counter - ); - debug!( - "Parser::get_matches_with: Low index multiples...{:?}", - low_index_mults - ); - - if low_index_mults || missing_pos { - let skip_current = if let Some(n) = raw_args.peek(&args_cursor) { - if let Some(arg) = self - .cmd - .get_positionals() - .find(|a| a.get_index() == Some(pos_counter)) - { - // If next value looks like a new_arg or it's a - // subcommand, skip positional argument under current - // pos_counter(which means current value cannot be a - // positional argument with a value next to it), assume - // current value matches the next arg. - self.is_new_arg(&n, arg) - || self - .possible_subcommand(n.to_value(), valid_arg_found) - .is_some() - } else { - true - } - } else { - true - }; - - if skip_current { - debug!("Parser::get_matches_with: Bumping the positional counter..."); - pos_counter + 1 - } else { - pos_counter - } - } else if trailing_values - && (self.cmd.is_allow_missing_positional_set() || contains_last) - { - // Came to -- and one positional has .last(true) set, so we go immediately - // to the last (highest index) positional - debug!("Parser::get_matches_with: .last(true) and --, setting last pos"); - positional_count - } else { - pos_counter - } - }; - - if let Some(arg) = self.cmd.get_keymap().get(&pos_counter) { - if arg.is_last_set() && !trailing_values { - let _ = self.resolve_pending(matcher); - // Its already considered a positional, we don't need to suggest turning it - // into one - let suggested_trailing_arg = false; - return Err(ClapError::unknown_argument( - self.cmd, - arg_os.display().to_string(), - None, - suggested_trailing_arg, - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - - if arg.is_trailing_var_arg_set() { - trailing_values = true; - } - - if matcher.pending_arg_id() != Some(arg.get_id()) || !arg.is_multiple_values_set() { - ok!(self.resolve_pending(matcher)); - } - if let Some(_parse_result) = self.check_terminator(arg, arg_os.to_value_os()) { - debug!( - "Parser::get_matches_with: ignoring terminator result {:?}", - _parse_result - ); - } else { - let arg_values = matcher.pending_values_mut( - arg.get_id(), - Some(Identifier::Index), - trailing_values, - ); - arg_values.push(arg_os.to_value_os().to_os_str().into_owned()); - } - - // Only increment the positional counter if it doesn't allow multiples - if !arg.is_multiple() { - pos_counter += 1; - parse_state = ParseState::ValuesDone; - } else { - parse_state = ParseState::Pos(arg.get_id().clone()); - } - valid_arg_found = true; - } else if let Some(external_parser) = - self.cmd.get_external_subcommand_value_parser().cloned() - { - // Get external subcommand name - let sc_name = match arg_os.to_value() { - Ok(s) => s.to_owned(), - Err(_) => { - let _ = self.resolve_pending(matcher); - return Err(ClapError::invalid_utf8( - self.cmd, - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - }; - - // Collect the external subcommand args - let mut sc_m = ArgMatcher::new(self.cmd); - sc_m.start_occurrence_of_external(self.cmd); - - for raw_val in raw_args.remaining(&mut args_cursor) { - let val = ok!(external_parser.parse_ref(self.cmd, None, raw_val)); - let external_id = Id::from_static_ref(Id::EXTERNAL); - sc_m.add_val_to(&external_id, val, raw_val.to_os_string()); - } - - matcher.subcommand(SubCommand { - name: sc_name, - matches: sc_m.into_inner(), - }); - - ok!(self.resolve_pending(matcher)); - #[cfg(feature = "env")] - ok!(self.add_env(matcher)); - ok!(self.add_defaults(matcher)); - return Validator::new(self.cmd).validate(parse_state, matcher); - } else { - // Start error processing - let _ = self.resolve_pending(matcher); - return Err(self.match_arg_error(&arg_os, valid_arg_found, trailing_values)); - } - } - - if let Some(ref pos_sc_name) = subcmd_name { - let sc_name = self - .cmd - .find_subcommand(pos_sc_name) - .expect(INTERNAL_ERROR_MSG) - .get_name() - .to_owned(); - ok!(self.parse_subcommand(&sc_name, matcher, raw_args, args_cursor, keep_state)); - } - - ok!(self.resolve_pending(matcher)); - #[cfg(feature = "env")] - ok!(self.add_env(matcher)); - ok!(self.add_defaults(matcher)); - Validator::new(self.cmd).validate(parse_state, matcher) - } - - fn match_arg_error( - &self, - arg_os: &clap_lex::ParsedArg<'_>, - valid_arg_found: bool, - trailing_values: bool, - ) -> ClapError { - // If argument follows a `--` - if trailing_values { - // If the arg matches a subcommand name, or any of its aliases (if defined) - if self - .possible_subcommand(arg_os.to_value(), valid_arg_found) - .is_some() - { - return ClapError::unnecessary_double_dash( - self.cmd, - arg_os.display().to_string(), - Usage::new(self.cmd).create_usage_with_title(&[]), - ); - } - } - - if !(self.cmd.is_args_conflicts_with_subcommands_set() && valid_arg_found) { - let candidates = suggestions::did_you_mean( - &arg_os.display().to_string(), - self.cmd.all_subcommand_names(), - ); - // If the argument looks like a subcommand. - if !candidates.is_empty() { - return ClapError::invalid_subcommand( - self.cmd, - arg_os.display().to_string(), - candidates, - self.cmd - .get_bin_name() - .unwrap_or_else(|| self.cmd.get_name()) - .to_owned(), - Usage::new(self.cmd).create_usage_with_title(&[]), - ); - } - - // If the argument must be a subcommand. - if self.cmd.has_subcommands() - && (!self.cmd.has_positionals() || self.cmd.is_infer_subcommands_set()) - { - return ClapError::unrecognized_subcommand( - self.cmd, - arg_os.display().to_string(), - Usage::new(self.cmd).create_usage_with_title(&[]), - ); - } - } - - let suggested_trailing_arg = !trailing_values - && self.cmd.has_positionals() - && (arg_os.is_long() || arg_os.is_short()); - ClapError::unknown_argument( - self.cmd, - arg_os.display().to_string(), - None, - suggested_trailing_arg, - Usage::new(self.cmd).create_usage_with_title(&[]), - ) - } - - // Checks if the arg matches a subcommand name, or any of its aliases (if defined) - fn possible_subcommand( - &self, - arg: Result<&str, &RawOsStr>, - valid_arg_found: bool, - ) -> Option<&str> { - debug!("Parser::possible_subcommand: arg={:?}", arg); - let arg = some!(arg.ok()); - - if !(self.cmd.is_args_conflicts_with_subcommands_set() && valid_arg_found) { - if self.cmd.is_infer_subcommands_set() { - // For subcommand `test`, we accepts it's prefix: `t`, `te`, - // `tes` and `test`. - let v = self - .cmd - .all_subcommand_names() - .filter(|s| s.starts_with(arg)) - .collect::<Vec<_>>(); - - if v.len() == 1 { - return Some(v[0]); - } - - // If there is any ambiguity, fallback to non-infer subcommand - // search. - } - if let Some(sc) = self.cmd.find_subcommand(arg) { - return Some(sc.get_name()); - } - } - None - } - - // Checks if the arg matches a long flag subcommand name, or any of its aliases (if defined) - fn possible_long_flag_subcommand(&self, arg: &str) -> Option<&str> { - debug!("Parser::possible_long_flag_subcommand: arg={:?}", arg); - if self.cmd.is_infer_subcommands_set() { - let options = self - .cmd - .get_subcommands() - .fold(Vec::new(), |mut options, sc| { - if let Some(long) = sc.get_long_flag() { - if long.starts_with(arg) { - options.push(long); - } - options.extend(sc.get_all_aliases().filter(|alias| alias.starts_with(arg))) - } - options - }); - if options.len() == 1 { - return Some(options[0]); - } - - for sc in options { - if sc == arg { - return Some(sc); - } - } - } else if let Some(sc_name) = self.cmd.find_long_subcmd(arg) { - return Some(sc_name); - } - None - } - - fn parse_help_subcommand( - &self, - cmds: impl Iterator<Item = &'cmd OsStr>, - ) -> ClapResult<std::convert::Infallible> { - debug!("Parser::parse_help_subcommand"); - - let mut cmd = self.cmd.clone(); - let sc = { - let mut sc = &mut cmd; - - for cmd in cmds { - sc = if let Some(sc_name) = - sc.find_subcommand(cmd).map(|sc| sc.get_name().to_owned()) - { - sc._build_subcommand(&sc_name).unwrap() - } else { - return Err(ClapError::unrecognized_subcommand( - sc, - cmd.to_string_lossy().into_owned(), - Usage::new(sc).create_usage_with_title(&[]), - )); - }; - } - - sc - }; - let parser = Parser::new(sc); - - Err(parser.help_err(true)) - } - - fn is_new_arg(&self, next: &clap_lex::ParsedArg<'_>, current_positional: &Arg) -> bool { - #![allow(clippy::needless_bool)] // Prefer consistent if/else-if ladder - - debug!( - "Parser::is_new_arg: {:?}:{}", - next.to_value_os(), - current_positional.get_id() - ); - - if self.cmd[current_positional.get_id()].is_allow_hyphen_values_set() - || (self.cmd[current_positional.get_id()].is_allow_negative_numbers_set() - && next.is_number()) - { - // If allow hyphen, this isn't a new arg. - debug!("Parser::is_new_arg: Allow hyphen"); - false - } else if next.is_long() { - // If this is a long flag, this is a new arg. - debug!("Parser::is_new_arg: --<something> found"); - true - } else if next.is_short() { - // If this is a short flag, this is a new arg. But a singe '-' by - // itself is a value and typically means "stdin" on unix systems. - debug!("Parser::is_new_arg: -<something> found"); - true - } else { - // Nothing special, this is a value. - debug!("Parser::is_new_arg: value"); - false - } - } - - fn parse_subcommand( - &mut self, - sc_name: &str, - matcher: &mut ArgMatcher, - raw_args: &mut clap_lex::RawArgs, - args_cursor: clap_lex::ArgCursor, - keep_state: bool, - ) -> ClapResult<()> { - debug!("Parser::parse_subcommand"); - - let partial_parsing_enabled = self.cmd.is_ignore_errors_set(); - - if let Some(sc) = self.cmd._build_subcommand(sc_name) { - let mut sc_matcher = ArgMatcher::new(sc); - - debug!( - "Parser::parse_subcommand: About to parse sc={}", - sc.get_name() - ); - - { - let mut p = Parser::new(sc); - // HACK: maintain indexes between parsers - // FlagSubCommand short arg needs to revisit the current short args, but skip the subcommand itself - if keep_state { - p.cur_idx.set(self.cur_idx.get()); - p.flag_subcmd_at = self.flag_subcmd_at; - p.flag_subcmd_skip = self.flag_subcmd_skip; - } - if let Err(error) = p.get_matches_with(&mut sc_matcher, raw_args, args_cursor) { - if partial_parsing_enabled { - debug!( - "Parser::parse_subcommand: ignored error in subcommand {}: {:?}", - sc_name, error - ); - } else { - return Err(error); - } - } - } - matcher.subcommand(SubCommand { - name: sc.get_name().to_owned(), - matches: sc_matcher.into_inner(), - }); - } - Ok(()) - } - - fn parse_long_arg( - &mut self, - matcher: &mut ArgMatcher, - long_arg: Result<&str, &RawOsStr>, - long_value: Option<&RawOsStr>, - parse_state: &ParseState, - pos_counter: usize, - valid_arg_found: &mut bool, - ) -> ClapResult<ParseResult> { - // maybe here lifetime should be 'a - debug!("Parser::parse_long_arg"); - - #[allow(clippy::blocks_in_if_conditions)] - if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if - self.cmd[opt].is_allow_hyphen_values_set()) - { - debug!("Parser::parse_long_arg: prior arg accepts hyphenated values",); - return Ok(ParseResult::MaybeHyphenValue); - } - - debug!("Parser::parse_long_arg: Does it contain '='..."); - let long_arg = match long_arg { - Ok(long_arg) => long_arg, - Err(long_arg) => { - return Ok(ParseResult::NoMatchingArg { - arg: long_arg.to_str_lossy().into_owned(), - }); - } - }; - if long_arg.is_empty() { - debug_assert!( - long_value.is_some(), - "`--` should be filtered out before this point" - ); - } - - let arg = if let Some(arg) = self.cmd.get_keymap().get(long_arg) { - debug!("Parser::parse_long_arg: Found valid arg or flag '{}'", arg); - Some((long_arg, arg)) - } else if self.cmd.is_infer_long_args_set() { - self.cmd.get_arguments().find_map(|a| { - if let Some(long) = a.get_long() { - if long.starts_with(long_arg) { - return Some((long, a)); - } - } - a.aliases - .iter() - .find_map(|(alias, _)| alias.starts_with(long_arg).then(|| (alias.as_str(), a))) - }) - } else { - None - }; - - if let Some((_long_arg, arg)) = arg { - let ident = Identifier::Long; - *valid_arg_found = true; - if arg.is_takes_value_set() { - debug!( - "Parser::parse_long_arg({:?}): Found an arg with value '{:?}'", - long_arg, &long_value - ); - let has_eq = long_value.is_some(); - self.parse_opt_value(ident, long_value, arg, matcher, has_eq) - } else if let Some(rest) = long_value { - let required = self.cmd.required_graph(); - debug!( - "Parser::parse_long_arg({:?}): Got invalid literal `{:?}`", - long_arg, rest - ); - let mut used: Vec<Id> = matcher - .arg_ids() - .filter(|arg_id| { - matcher.check_explicit(arg_id, &crate::builder::ArgPredicate::IsPresent) - }) - .filter(|&n| { - self.cmd.find(n).map_or(true, |a| { - !(a.is_hide_set() || required.contains(a.get_id())) - }) - }) - .cloned() - .collect(); - used.push(arg.get_id().clone()); - - Ok(ParseResult::UnneededAttachedValue { - rest: rest.to_str_lossy().into_owned(), - used, - arg: arg.to_string(), - }) - } else { - debug!("Parser::parse_long_arg({:?}): Presence validated", long_arg); - let trailing_idx = None; - self.react( - Some(ident), - ValueSource::CommandLine, - arg, - vec![], - trailing_idx, - matcher, - ) - } - } else if let Some(sc_name) = self.possible_long_flag_subcommand(long_arg) { - Ok(ParseResult::FlagSubCommand(sc_name.to_string())) - } else if self - .cmd - .get_keymap() - .get(&pos_counter) - .map_or(false, |arg| { - arg.is_allow_hyphen_values_set() && !arg.is_last_set() - }) - { - debug!( - "Parser::parse_long_args: positional at {} allows hyphens", - pos_counter - ); - Ok(ParseResult::MaybeHyphenValue) - } else { - Ok(ParseResult::NoMatchingArg { - arg: long_arg.to_owned(), - }) - } - } - - fn parse_short_arg( - &mut self, - matcher: &mut ArgMatcher, - mut short_arg: clap_lex::ShortFlags<'_>, - parse_state: &ParseState, - // change this to possible pos_arg when removing the usage of &mut Parser. - pos_counter: usize, - valid_arg_found: &mut bool, - ) -> ClapResult<ParseResult> { - debug!("Parser::parse_short_arg: short_arg={:?}", short_arg); - - #[allow(clippy::blocks_in_if_conditions)] - if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) - if self.cmd[opt].is_allow_hyphen_values_set() || (self.cmd[opt].is_allow_negative_numbers_set() && short_arg.is_number())) - { - debug!("Parser::parse_short_args: prior arg accepts hyphenated values",); - return Ok(ParseResult::MaybeHyphenValue); - } else if self - .cmd - .get_keymap() - .get(&pos_counter) - .map_or(false, |arg| arg.is_allow_negative_numbers_set()) - && short_arg.is_number() - { - debug!("Parser::parse_short_arg: negative number"); - return Ok(ParseResult::MaybeHyphenValue); - } else if self - .cmd - .get_keymap() - .get(&pos_counter) - .map_or(false, |arg| { - arg.is_allow_hyphen_values_set() && !arg.is_last_set() - }) - && short_arg - .clone() - .any(|c| !c.map(|c| self.cmd.contains_short(c)).unwrap_or_default()) - { - debug!( - "Parser::parse_short_args: positional at {} allows hyphens", - pos_counter - ); - return Ok(ParseResult::MaybeHyphenValue); - } - - let mut ret = ParseResult::NoArg; - - let skip = self.flag_subcmd_skip; - self.flag_subcmd_skip = 0; - let res = short_arg.advance_by(skip); - debug_assert_eq!( - res, - Ok(()), - "tracking of `flag_subcmd_skip` is off for `{:?}`", - short_arg - ); - while let Some(c) = short_arg.next_flag() { - let c = match c { - Ok(c) => c, - Err(rest) => { - return Ok(ParseResult::NoMatchingArg { - arg: format!("-{}", rest.to_str_lossy()), - }); - } - }; - debug!("Parser::parse_short_arg:iter:{}", c); - - // Check for matching short options, and return the name if there is no trailing - // concatenated value: -oval - // Option: -o - // Value: val - if let Some(arg) = self.cmd.get_keymap().get(&c) { - let ident = Identifier::Short; - debug!( - "Parser::parse_short_arg:iter:{}: Found valid opt or flag", - c - ); - *valid_arg_found = true; - if !arg.is_takes_value_set() { - let arg_values = Vec::new(); - let trailing_idx = None; - ret = ok!(self.react( - Some(ident), - ValueSource::CommandLine, - arg, - arg_values, - trailing_idx, - matcher, - )); - continue; - } - - // Check for trailing concatenated value - // - // Cloning the iterator, so we rollback if it isn't there. - let val = short_arg.clone().next_value_os().unwrap_or_default(); - debug!( - "Parser::parse_short_arg:iter:{}: val={:?} (bytes), val={:?} (ascii), short_arg={:?}", - c, val, val.as_raw_bytes(), short_arg - ); - let val = Some(val).filter(|v| !v.is_empty()); - - // Default to "we're expecting a value later". - // - // If attached value is not consumed, we may have more short - // flags to parse, continue. - // - // e.g. `-xvf`, when require_equals && x.min_vals == 0, we don't - // consume the `vf`, even if it's provided as value. - let (val, has_eq) = if let Some(val) = val.and_then(|v| v.strip_prefix('=')) { - (Some(val), true) - } else { - (val, false) - }; - match ok!(self.parse_opt_value(ident, val, arg, matcher, has_eq)) { - ParseResult::AttachedValueNotConsumed => continue, - x => return Ok(x), - } - } - - return if let Some(sc_name) = self.cmd.find_short_subcmd(c) { - debug!("Parser::parse_short_arg:iter:{}: subcommand={}", c, sc_name); - // Make sure indices get updated before reading `self.cur_idx` - ok!(self.resolve_pending(matcher)); - self.cur_idx.set(self.cur_idx.get() + 1); - debug!("Parser::parse_short_arg: cur_idx:={}", self.cur_idx.get()); - - let name = sc_name.to_string(); - // Get the index of the previously saved flag subcommand in the group of flags (if exists). - // If it is a new flag subcommand, then the formentioned index should be the current one - // (ie. `cur_idx`), and should be registered. - let cur_idx = self.cur_idx.get(); - self.flag_subcmd_at.get_or_insert(cur_idx); - let done_short_args = short_arg.is_empty(); - if done_short_args { - self.flag_subcmd_at = None; - } - Ok(ParseResult::FlagSubCommand(name)) - } else { - Ok(ParseResult::NoMatchingArg { - arg: format!("-{}", c), - }) - }; - } - Ok(ret) - } - - fn parse_opt_value( - &self, - ident: Identifier, - attached_value: Option<&RawOsStr>, - arg: &Arg, - matcher: &mut ArgMatcher, - has_eq: bool, - ) -> ClapResult<ParseResult> { - debug!( - "Parser::parse_opt_value; arg={}, val={:?}, has_eq={:?}", - arg.get_id(), - attached_value, - has_eq - ); - debug!("Parser::parse_opt_value; arg.settings={:?}", arg.settings); - - debug!("Parser::parse_opt_value; Checking for val..."); - // require_equals is set, but no '=' is provided, try throwing error. - if arg.is_require_equals_set() && !has_eq { - if arg.get_min_vals() == 0 { - debug!("Requires equals, but min_vals == 0"); - let arg_values = Vec::new(); - let trailing_idx = None; - let react_result = ok!(self.react( - Some(ident), - ValueSource::CommandLine, - arg, - arg_values, - trailing_idx, - matcher, - )); - debug_assert_eq!(react_result, ParseResult::ValuesDone); - if attached_value.is_some() { - Ok(ParseResult::AttachedValueNotConsumed) - } else { - Ok(ParseResult::ValuesDone) - } - } else { - debug!("Requires equals but not provided. Error."); - Ok(ParseResult::EqualsNotProvided { - arg: arg.to_string(), - }) - } - } else if let Some(v) = attached_value { - let arg_values = vec![v.to_os_str().into_owned()]; - let trailing_idx = None; - let react_result = ok!(self.react( - Some(ident), - ValueSource::CommandLine, - arg, - arg_values, - trailing_idx, - matcher, - )); - debug_assert_eq!(react_result, ParseResult::ValuesDone); - // Attached are always done - Ok(ParseResult::ValuesDone) - } else { - debug!("Parser::parse_opt_value: More arg vals required..."); - ok!(self.resolve_pending(matcher)); - let trailing_values = false; - matcher.pending_values_mut(arg.get_id(), Some(ident), trailing_values); - Ok(ParseResult::Opt(arg.get_id().clone())) - } - } - - fn check_terminator(&self, arg: &Arg, val: &RawOsStr) -> Option<ParseResult> { - if Some(val) - == arg - .terminator - .as_ref() - .map(|s| RawOsStr::from_str(s.as_str())) - { - debug!("Parser::check_terminator: terminator={:?}", arg.terminator); - Some(ParseResult::ValuesDone) - } else { - None - } - } - - fn push_arg_values( - &self, - arg: &Arg, - raw_vals: Vec<OsString>, - matcher: &mut ArgMatcher, - ) -> ClapResult<()> { - debug!("Parser::push_arg_values: {:?}", raw_vals); - - for raw_val in raw_vals { - // update the current index because each value is a distinct index to clap - self.cur_idx.set(self.cur_idx.get() + 1); - debug!( - "Parser::add_single_val_to_arg: cur_idx:={}", - self.cur_idx.get() - ); - let value_parser = arg.get_value_parser(); - let val = ok!(value_parser.parse_ref(self.cmd, Some(arg), &raw_val)); - - matcher.add_val_to(arg.get_id(), val, raw_val); - matcher.add_index_to(arg.get_id(), self.cur_idx.get()); - } - - Ok(()) - } - - fn resolve_pending(&self, matcher: &mut ArgMatcher) -> ClapResult<()> { - let pending = match matcher.take_pending() { - Some(pending) => pending, - None => { - return Ok(()); - } - }; - - debug!("Parser::resolve_pending: id={:?}", pending.id); - let arg = self.cmd.find(&pending.id).expect(INTERNAL_ERROR_MSG); - let _ = ok!(self.react( - pending.ident, - ValueSource::CommandLine, - arg, - pending.raw_vals, - pending.trailing_idx, - matcher, - )); - - Ok(()) - } - - fn react( - &self, - ident: Option<Identifier>, - source: ValueSource, - arg: &Arg, - mut raw_vals: Vec<OsString>, - mut trailing_idx: Option<usize>, - matcher: &mut ArgMatcher, - ) -> ClapResult<ParseResult> { - ok!(self.resolve_pending(matcher)); - - debug!( - "Parser::react action={:?}, identifier={:?}, source={:?}", - arg.get_action(), - ident, - source - ); - - // Process before `default_missing_values` to avoid it counting as values from the command - // line - if source == ValueSource::CommandLine { - ok!(self.verify_num_args(arg, &raw_vals)); - } - - if raw_vals.is_empty() { - // We assume this case is valid: require equals, but min_vals == 0. - if !arg.default_missing_vals.is_empty() { - debug!("Parser::react: has default_missing_vals"); - trailing_idx = None; - raw_vals.extend( - arg.default_missing_vals - .iter() - .map(|s| s.as_os_str().to_owned()), - ); - } - } - - if let Some(val_delim) = arg.get_value_delimiter() { - if self.cmd.is_dont_delimit_trailing_values_set() && trailing_idx == Some(0) { - // Nothing to do - } else { - let mut split_raw_vals = Vec::with_capacity(raw_vals.len()); - for (i, raw_val) in raw_vals.into_iter().enumerate() { - let raw_val = RawOsString::new(raw_val); - if !raw_val.contains(val_delim) - || (self.cmd.is_dont_delimit_trailing_values_set() - && trailing_idx == Some(i)) - { - split_raw_vals.push(raw_val.into_os_string()); - } else { - split_raw_vals - .extend(raw_val.split(val_delim).map(|x| x.to_os_str().into_owned())); - } - } - raw_vals = split_raw_vals - } - } - - match arg.get_action() { - ArgAction::Set => { - if source == ValueSource::CommandLine - && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long)) - { - // Record flag's index - self.cur_idx.set(self.cur_idx.get() + 1); - debug!("Parser::react: cur_idx:={}", self.cur_idx.get()); - } - if matcher.remove(arg.get_id()) - && !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id())) - { - return Err(ClapError::argument_conflict( - self.cmd, - arg.to_string(), - vec![arg.to_string()], - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - self.start_custom_arg(matcher, arg, source); - ok!(self.push_arg_values(arg, raw_vals, matcher)); - if cfg!(debug_assertions) && matcher.needs_more_vals(arg) { - debug!( - "Parser::react not enough values passed in, leaving it to the validator to complain", - ); - } - Ok(ParseResult::ValuesDone) - } - ArgAction::Append => { - if source == ValueSource::CommandLine - && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long)) - { - // Record flag's index - self.cur_idx.set(self.cur_idx.get() + 1); - debug!("Parser::react: cur_idx:={}", self.cur_idx.get()); - } - self.start_custom_arg(matcher, arg, source); - ok!(self.push_arg_values(arg, raw_vals, matcher)); - if cfg!(debug_assertions) && matcher.needs_more_vals(arg) { - debug!( - "Parser::react not enough values passed in, leaving it to the validator to complain", - ); - } - Ok(ParseResult::ValuesDone) - } - ArgAction::SetTrue => { - let raw_vals = if raw_vals.is_empty() { - vec![OsString::from("true")] - } else { - raw_vals - }; - - if matcher.remove(arg.get_id()) - && !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id())) - { - return Err(ClapError::argument_conflict( - self.cmd, - arg.to_string(), - vec![arg.to_string()], - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - self.start_custom_arg(matcher, arg, source); - ok!(self.push_arg_values(arg, raw_vals, matcher)); - Ok(ParseResult::ValuesDone) - } - ArgAction::SetFalse => { - let raw_vals = if raw_vals.is_empty() { - vec![OsString::from("false")] - } else { - raw_vals - }; - - if matcher.remove(arg.get_id()) - && !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id())) - { - return Err(ClapError::argument_conflict( - self.cmd, - arg.to_string(), - vec![arg.to_string()], - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - self.start_custom_arg(matcher, arg, source); - ok!(self.push_arg_values(arg, raw_vals, matcher)); - Ok(ParseResult::ValuesDone) - } - ArgAction::Count => { - let raw_vals = if raw_vals.is_empty() { - let existing_value = *matcher - .get_one::<crate::builder::CountType>(arg.get_id().as_str()) - .unwrap_or(&0); - let next_value = existing_value.saturating_add(1); - vec![OsString::from(next_value.to_string())] - } else { - raw_vals - }; - - matcher.remove(arg.get_id()); - self.start_custom_arg(matcher, arg, source); - ok!(self.push_arg_values(arg, raw_vals, matcher)); - Ok(ParseResult::ValuesDone) - } - ArgAction::Help => { - let use_long = match ident { - Some(Identifier::Long) => true, - Some(Identifier::Short) => false, - Some(Identifier::Index) => true, - None => true, - }; - debug!("Help: use_long={}", use_long); - Err(self.help_err(use_long)) - } - ArgAction::Version => { - let use_long = match ident { - Some(Identifier::Long) => true, - Some(Identifier::Short) => false, - Some(Identifier::Index) => true, - None => true, - }; - debug!("Version: use_long={}", use_long); - Err(self.version_err(use_long)) - } - } - } - - fn verify_num_args(&self, arg: &Arg, raw_vals: &[OsString]) -> ClapResult<()> { - if self.cmd.is_ignore_errors_set() { - return Ok(()); - } - - let actual = raw_vals.len(); - let expected = arg.get_num_args().expect(INTERNAL_ERROR_MSG); - - if 0 < expected.min_values() && actual == 0 { - // Issue 665 (https://github.com/clap-rs/clap/issues/665) - // Issue 1105 (https://github.com/clap-rs/clap/issues/1105) - return Err(ClapError::empty_value( - self.cmd, - &super::get_possible_values_cli(arg) - .iter() - .filter(|pv| !pv.is_hide_set()) - .map(|n| n.get_name().to_owned()) - .collect::<Vec<_>>(), - arg.to_string(), - )); - } else if let Some(expected) = expected.num_values() { - if expected != actual { - debug!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues"); - return Err(ClapError::wrong_number_of_values( - self.cmd, - arg.to_string(), - expected, - actual, - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - } else if actual < expected.min_values() { - return Err(ClapError::too_few_values( - self.cmd, - arg.to_string(), - expected.min_values(), - actual, - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } else if expected.max_values() < actual { - debug!("Validator::validate_arg_num_vals: Sending error TooManyValues"); - return Err(ClapError::too_many_values( - self.cmd, - raw_vals - .last() - .expect(INTERNAL_ERROR_MSG) - .to_string_lossy() - .into_owned(), - arg.to_string(), - Usage::new(self.cmd).create_usage_with_title(&[]), - )); - } - - Ok(()) - } - - fn remove_overrides(&self, arg: &Arg, matcher: &mut ArgMatcher) { - debug!("Parser::remove_overrides: id={:?}", arg.id); - for override_id in &arg.overrides { - debug!("Parser::remove_overrides:iter:{:?}: removing", override_id); - matcher.remove(override_id); - } - - // Override anything that can override us - let mut transitive = Vec::new(); - for arg_id in matcher.arg_ids() { - if let Some(overrider) = self.cmd.find(arg_id) { - if overrider.overrides.contains(arg.get_id()) { - transitive.push(overrider.get_id()); - } - } - } - for overrider_id in transitive { - debug!("Parser::remove_overrides:iter:{:?}: removing", overrider_id); - matcher.remove(overrider_id); - } - } - - #[cfg(feature = "env")] - fn add_env(&mut self, matcher: &mut ArgMatcher) -> ClapResult<()> { - debug!("Parser::add_env"); - - for arg in self.cmd.get_arguments() { - // Use env only if the arg was absent among command line args, - // early return if this is not the case. - if matcher.contains(&arg.id) { - debug!("Parser::add_env: Skipping existing arg `{}`", arg); - continue; - } - - debug!("Parser::add_env: Checking arg `{}`", arg); - if let Some((_, Some(ref val))) = arg.env { - debug!("Parser::add_env: Found an opt with value={:?}", val); - let arg_values = vec![val.to_owned()]; - let trailing_idx = None; - let _ = ok!(self.react( - None, - ValueSource::EnvVariable, - arg, - arg_values, - trailing_idx, - matcher, - )); - } - } - - Ok(()) - } - - fn add_defaults(&self, matcher: &mut ArgMatcher) -> ClapResult<()> { - debug!("Parser::add_defaults"); - - for arg in self.cmd.get_arguments() { - debug!("Parser::add_defaults:iter:{}:", arg.get_id()); - ok!(self.add_default_value(arg, matcher)); - } - - Ok(()) - } - - fn add_default_value(&self, arg: &Arg, matcher: &mut ArgMatcher) -> ClapResult<()> { - if !arg.default_vals_ifs.is_empty() { - debug!("Parser::add_default_value: has conditional defaults"); - if !matcher.contains(arg.get_id()) { - for (id, val, default) in arg.default_vals_ifs.iter() { - let add = if let Some(a) = matcher.get(id) { - match val { - crate::builder::ArgPredicate::Equals(v) => { - a.raw_vals_flatten().any(|value| v == value) - } - crate::builder::ArgPredicate::IsPresent => true, - } - } else { - false - }; - - if add { - if let Some(default) = default { - let arg_values = vec![default.to_os_string()]; - let trailing_idx = None; - let _ = ok!(self.react( - None, - ValueSource::DefaultValue, - arg, - arg_values, - trailing_idx, - matcher, - )); - } - return Ok(()); - } - } - } - } else { - debug!("Parser::add_default_value: doesn't have conditional defaults"); - } - - if !arg.default_vals.is_empty() { - debug!( - "Parser::add_default_value:iter:{}: has default vals", - arg.get_id() - ); - if matcher.contains(arg.get_id()) { - debug!("Parser::add_default_value:iter:{}: was used", arg.get_id()); - // do nothing - } else { - debug!( - "Parser::add_default_value:iter:{}: wasn't used", - arg.get_id() - ); - let arg_values: Vec<_> = arg - .default_vals - .iter() - .map(crate::builder::OsStr::to_os_string) - .collect(); - let trailing_idx = None; - let _ = ok!(self.react( - None, - ValueSource::DefaultValue, - arg, - arg_values, - trailing_idx, - matcher, - )); - } - } else { - debug!( - "Parser::add_default_value:iter:{}: doesn't have default vals", - arg.get_id() - ); - - // do nothing - } - - Ok(()) - } - - fn start_custom_arg(&self, matcher: &mut ArgMatcher, arg: &Arg, source: ValueSource) { - if source == ValueSource::CommandLine { - // With each new occurrence, remove overrides from prior occurrences - self.remove_overrides(arg, matcher); - } - matcher.start_custom_arg(arg, source); - if source.is_explicit() { - for group in self.cmd.groups_for_arg(arg.get_id()) { - matcher.start_custom_group(group.clone(), source); - matcher.add_val_to( - &group, - AnyValue::new(arg.get_id().clone()), - OsString::from(arg.get_id().as_str()), - ); - } - } - } -} - -// Error, Help, and Version Methods -impl<'cmd> Parser<'cmd> { - /// Is only used for the long flag(which is the only one needs fuzzy searching) - fn did_you_mean_error( - &mut self, - arg: &str, - matcher: &mut ArgMatcher, - remaining_args: &[&OsStr], - trailing_values: bool, - ) -> ClapError { - debug!("Parser::did_you_mean_error: arg={}", arg); - // Didn't match a flag or option - let longs = self - .cmd - .get_keymap() - .keys() - .filter_map(|x| match x { - KeyType::Long(l) => Some(l.to_string_lossy().into_owned()), - _ => None, - }) - .collect::<Vec<_>>(); - debug!("Parser::did_you_mean_error: longs={:?}", longs); - - let did_you_mean = suggestions::did_you_mean_flag( - arg, - remaining_args, - longs.iter().map(|x| &x[..]), - self.cmd.get_subcommands_mut(), - ); - - // Add the arg to the matches to build a proper usage string - if let Some((name, _)) = did_you_mean.as_ref() { - if let Some(arg) = self.cmd.get_keymap().get(&name.as_ref()) { - self.start_custom_arg(matcher, arg, ValueSource::CommandLine); - } - } - - let required = self.cmd.required_graph(); - let used: Vec<Id> = matcher - .arg_ids() - .filter(|arg_id| { - matcher.check_explicit(arg_id, &crate::builder::ArgPredicate::IsPresent) - }) - .filter(|n| self.cmd.find(n).map_or(true, |a| !a.is_hide_set())) - .cloned() - .collect(); - - // `did_you_mean` is a lot more likely and should cause us to skip the `--` suggestion - // - // In theory, this is only called for `--long`s, so we don't need to check - let suggested_trailing_arg = - did_you_mean.is_none() && !trailing_values && self.cmd.has_positionals(); - ClapError::unknown_argument( - self.cmd, - format!("--{}", arg), - did_you_mean, - suggested_trailing_arg, - Usage::new(self.cmd) - .required(&required) - .create_usage_with_title(&used), - ) - } - - fn help_err(&self, use_long: bool) -> ClapError { - let styled = self.cmd.write_help_err(use_long); - ClapError::display_help(self.cmd, styled) - } - - fn version_err(&self, use_long: bool) -> ClapError { - let styled = self.cmd.write_version_err(use_long); - ClapError::display_version(self.cmd, styled) - } -} - -#[derive(Debug, PartialEq, Eq)] -pub(crate) enum ParseState { - ValuesDone, - Opt(Id), - Pos(Id), -} - -/// Recoverable Parsing results. -#[derive(Debug, PartialEq, Clone)] -#[must_use] -enum ParseResult { - FlagSubCommand(String), - Opt(Id), - ValuesDone, - /// Value attached to the short flag is not consumed(e.g. 'u' for `-cu` is - /// not consumed). - AttachedValueNotConsumed, - /// This long flag doesn't need a value but is provided one. - UnneededAttachedValue { - rest: String, - used: Vec<Id>, - arg: String, - }, - /// This flag might be an hyphen Value. - MaybeHyphenValue, - /// Equals required but not provided. - EqualsNotProvided { - arg: String, - }, - /// Failed to match a Arg. - NoMatchingArg { - arg: String, - }, - /// No argument found e.g. parser is given `-` when parsing a flag. - NoArg, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct PendingArg { - pub(crate) id: Id, - pub(crate) ident: Option<Identifier>, - pub(crate) raw_vals: Vec<OsString>, - pub(crate) trailing_idx: Option<usize>, -} - -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub(crate) enum Identifier { - Short, - Long, - Index, -} diff --git a/vendor/clap/src/parser/validator.rs b/vendor/clap/src/parser/validator.rs deleted file mode 100644 index 991dc513f..000000000 --- a/vendor/clap/src/parser/validator.rs +++ /dev/null @@ -1,565 +0,0 @@ -// Internal -use crate::builder::StyledStr; -use crate::builder::{Arg, ArgGroup, ArgPredicate, Command, PossibleValue}; -use crate::error::{Error, Result as ClapResult}; -use crate::output::Usage; -use crate::parser::{ArgMatcher, ParseState}; -use crate::util::ChildGraph; -use crate::util::FlatMap; -use crate::util::FlatSet; -use crate::util::Id; -use crate::INTERNAL_ERROR_MSG; - -pub(crate) struct Validator<'cmd> { - cmd: &'cmd Command, - required: ChildGraph<Id>, -} - -impl<'cmd> Validator<'cmd> { - pub(crate) fn new(cmd: &'cmd Command) -> Self { - let required = cmd.required_graph(); - Validator { cmd, required } - } - - pub(crate) fn validate( - &mut self, - parse_state: ParseState, - matcher: &mut ArgMatcher, - ) -> ClapResult<()> { - debug!("Validator::validate"); - let conflicts = Conflicts::with_args(self.cmd, matcher); - let has_subcmd = matcher.subcommand_name().is_some(); - - if let ParseState::Opt(a) = parse_state { - debug!("Validator::validate: needs_val_of={:?}", a); - - let o = &self.cmd[&a]; - let should_err = if let Some(v) = matcher.args.get(o.get_id()) { - v.all_val_groups_empty() && o.get_min_vals() != 0 - } else { - true - }; - if should_err { - return Err(Error::empty_value( - self.cmd, - &get_possible_values_cli(o) - .iter() - .filter(|pv| !pv.is_hide_set()) - .map(|n| n.get_name().to_owned()) - .collect::<Vec<_>>(), - o.to_string(), - )); - } - } - - if !has_subcmd && self.cmd.is_arg_required_else_help_set() { - let num_user_values = matcher - .args() - .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent)) - .count(); - if num_user_values == 0 { - let message = self.cmd.write_help_err(false); - return Err(Error::display_help_error(self.cmd, message)); - } - } - if !has_subcmd && self.cmd.is_subcommand_required_set() { - let bn = self - .cmd - .get_bin_name() - .unwrap_or_else(|| self.cmd.get_name()); - return Err(Error::missing_subcommand( - self.cmd, - bn.to_string(), - self.cmd - .all_subcommand_names() - .map(|s| s.to_owned()) - .collect::<Vec<_>>(), - Usage::new(self.cmd) - .required(&self.required) - .create_usage_with_title(&[]), - )); - } - - ok!(self.validate_conflicts(matcher, &conflicts)); - if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) { - ok!(self.validate_required(matcher, &conflicts)); - } - - Ok(()) - } - - fn validate_conflicts( - &mut self, - matcher: &ArgMatcher, - conflicts: &Conflicts, - ) -> ClapResult<()> { - debug!("Validator::validate_conflicts"); - - ok!(self.validate_exclusive(matcher)); - - for (arg_id, _) in matcher - .args() - .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent)) - .filter(|(arg_id, _)| self.cmd.find(arg_id).is_some()) - { - debug!("Validator::validate_conflicts::iter: id={:?}", arg_id); - let conflicts = conflicts.gather_conflicts(self.cmd, arg_id); - ok!(self.build_conflict_err(arg_id, &conflicts, matcher)); - } - - Ok(()) - } - - fn validate_exclusive(&self, matcher: &ArgMatcher) -> ClapResult<()> { - debug!("Validator::validate_exclusive"); - let args_count = matcher - .args() - .filter(|(arg_id, matched)| { - matched.check_explicit(&crate::builder::ArgPredicate::IsPresent) - // Avoid including our own groups by checking none of them. If a group is present, the - // args for the group will be. - && self.cmd.find(arg_id).is_some() - }) - .count(); - if args_count <= 1 { - // Nothing present to conflict with - return Ok(()); - } - - matcher - .args() - .filter(|(_, matched)| matched.check_explicit(&crate::builder::ArgPredicate::IsPresent)) - .filter_map(|(id, _)| { - debug!("Validator::validate_exclusive:iter:{:?}", id); - self.cmd - .find(id) - // Find `arg`s which are exclusive but also appear with other args. - .filter(|&arg| arg.is_exclusive_set() && args_count > 1) - }) - // Throw an error for the first conflict found. - .try_for_each(|arg| { - Err(Error::argument_conflict( - self.cmd, - arg.to_string(), - Vec::new(), - Usage::new(self.cmd) - .required(&self.required) - .create_usage_with_title(&[]), - )) - }) - } - - fn build_conflict_err( - &self, - name: &Id, - conflict_ids: &[Id], - matcher: &ArgMatcher, - ) -> ClapResult<()> { - if conflict_ids.is_empty() { - return Ok(()); - } - - debug!("Validator::build_conflict_err: name={:?}", name); - let mut seen = FlatSet::new(); - let conflicts = conflict_ids - .iter() - .flat_map(|c_id| { - if self.cmd.find_group(c_id).is_some() { - self.cmd.unroll_args_in_group(c_id) - } else { - vec![c_id.clone()] - } - }) - .filter_map(|c_id| { - seen.insert(c_id.clone()).then(|| { - let c_arg = self.cmd.find(&c_id).expect(INTERNAL_ERROR_MSG); - c_arg.to_string() - }) - }) - .collect(); - - let former_arg = self.cmd.find(name).expect(INTERNAL_ERROR_MSG); - let usg = self.build_conflict_err_usage(matcher, conflict_ids); - Err(Error::argument_conflict( - self.cmd, - former_arg.to_string(), - conflicts, - usg, - )) - } - - fn build_conflict_err_usage( - &self, - matcher: &ArgMatcher, - conflicting_keys: &[Id], - ) -> Option<StyledStr> { - let used_filtered: Vec<Id> = matcher - .args() - .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent)) - .map(|(n, _)| n) - .filter(|n| { - // Filter out the args we don't want to specify. - self.cmd.find(n).map_or(false, |a| !a.is_hide_set()) - }) - .filter(|key| !conflicting_keys.contains(key)) - .cloned() - .collect(); - let required: Vec<Id> = used_filtered - .iter() - .filter_map(|key| self.cmd.find(key)) - .flat_map(|arg| arg.requires.iter().map(|item| &item.1)) - .filter(|key| !used_filtered.contains(key) && !conflicting_keys.contains(key)) - .chain(used_filtered.iter()) - .cloned() - .collect(); - Usage::new(self.cmd) - .required(&self.required) - .create_usage_with_title(&required) - } - - fn gather_requires(&mut self, matcher: &ArgMatcher) { - debug!("Validator::gather_requires"); - for (name, matched) in matcher - .args() - .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent)) - { - debug!("Validator::gather_requires:iter:{:?}", name); - if let Some(arg) = self.cmd.find(name) { - let is_relevant = |(val, req_arg): &(ArgPredicate, Id)| -> Option<Id> { - let required = matched.check_explicit(val); - required.then(|| req_arg.clone()) - }; - - for req in self.cmd.unroll_arg_requires(is_relevant, arg.get_id()) { - self.required.insert(req); - } - } else if let Some(g) = self.cmd.find_group(name) { - debug!("Validator::gather_requires:iter:{:?}:group", name); - for r in &g.requires { - self.required.insert(r.clone()); - } - } - } - } - - fn validate_required(&mut self, matcher: &ArgMatcher, conflicts: &Conflicts) -> ClapResult<()> { - debug!("Validator::validate_required: required={:?}", self.required); - self.gather_requires(matcher); - - let mut missing_required = Vec::new(); - let mut highest_index = 0; - - let is_exclusive_present = matcher - .args() - .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent)) - .any(|(id, _)| { - self.cmd - .find(id) - .map(|arg| arg.is_exclusive_set()) - .unwrap_or_default() - }); - debug!( - "Validator::validate_required: is_exclusive_present={}", - is_exclusive_present - ); - - for arg_or_group in self - .required - .iter() - .filter(|r| !matcher.check_explicit(r, &ArgPredicate::IsPresent)) - { - debug!("Validator::validate_required:iter:aog={:?}", arg_or_group); - if let Some(arg) = self.cmd.find(arg_or_group) { - debug!("Validator::validate_required:iter: This is an arg"); - if !is_exclusive_present && !self.is_missing_required_ok(arg, conflicts) { - debug!( - "Validator::validate_required:iter: Missing {:?}", - arg.get_id() - ); - missing_required.push(arg.get_id().clone()); - if !arg.is_last_set() { - highest_index = highest_index.max(arg.get_index().unwrap_or(0)); - } - } - } else if let Some(group) = self.cmd.find_group(arg_or_group) { - debug!("Validator::validate_required:iter: This is a group"); - if !self - .cmd - .unroll_args_in_group(&group.id) - .iter() - .any(|a| matcher.check_explicit(a, &ArgPredicate::IsPresent)) - { - debug!( - "Validator::validate_required:iter: Missing {:?}", - group.get_id() - ); - missing_required.push(group.get_id().clone()); - } - } - } - - // Validate the conditionally required args - for a in self - .cmd - .get_arguments() - .filter(|a| !matcher.check_explicit(a.get_id(), &ArgPredicate::IsPresent)) - { - let mut required = false; - - for (other, val) in &a.r_ifs { - if matcher.check_explicit(other, &ArgPredicate::Equals(val.into())) { - debug!( - "Validator::validate_required:iter: Missing {:?}", - a.get_id() - ); - required = true; - } - } - - let match_all = a.r_ifs_all.iter().all(|(other, val)| { - matcher.check_explicit(other, &ArgPredicate::Equals(val.into())) - }); - if match_all && !a.r_ifs_all.is_empty() { - debug!( - "Validator::validate_required:iter: Missing {:?}", - a.get_id() - ); - required = true; - } - - if (!a.r_unless.is_empty() || !a.r_unless_all.is_empty()) - && self.fails_arg_required_unless(a, matcher) - { - debug!( - "Validator::validate_required:iter: Missing {:?}", - a.get_id() - ); - required = true; - } - - if required { - missing_required.push(a.get_id().clone()); - if !a.is_last_set() { - highest_index = highest_index.max(a.get_index().unwrap_or(0)); - } - } - } - - // For display purposes, include all of the preceding positional arguments - if !self.cmd.is_allow_missing_positional_set() { - for pos in self - .cmd - .get_positionals() - .filter(|a| !matcher.check_explicit(a.get_id(), &ArgPredicate::IsPresent)) - { - if pos.get_index() < Some(highest_index) { - debug!( - "Validator::validate_required:iter: Missing {:?}", - pos.get_id() - ); - missing_required.push(pos.get_id().clone()); - } - } - } - - if !missing_required.is_empty() { - ok!(self.missing_required_error(matcher, missing_required)); - } - - Ok(()) - } - - fn is_missing_required_ok(&self, a: &Arg, conflicts: &Conflicts) -> bool { - debug!("Validator::is_missing_required_ok: {}", a.get_id()); - if !conflicts.gather_conflicts(self.cmd, a.get_id()).is_empty() { - debug!("Validator::is_missing_required_ok: true (self)"); - return true; - } - for group_id in self.cmd.groups_for_arg(a.get_id()) { - if !conflicts.gather_conflicts(self.cmd, &group_id).is_empty() { - debug!("Validator::is_missing_required_ok: true ({})", group_id); - return true; - } - } - false - } - - // Failing a required unless means, the arg's "unless" wasn't present, and neither were they - fn fails_arg_required_unless(&self, a: &Arg, matcher: &ArgMatcher) -> bool { - debug!("Validator::fails_arg_required_unless: a={:?}", a.get_id()); - let exists = |id| matcher.check_explicit(id, &ArgPredicate::IsPresent); - - (a.r_unless_all.is_empty() || !a.r_unless_all.iter().all(exists)) - && !a.r_unless.iter().any(exists) - } - - // `req_args`: an arg to include in the error even if not used - fn missing_required_error( - &self, - matcher: &ArgMatcher, - raw_req_args: Vec<Id>, - ) -> ClapResult<()> { - debug!("Validator::missing_required_error; incl={:?}", raw_req_args); - debug!( - "Validator::missing_required_error: reqs={:?}", - self.required - ); - - let usg = Usage::new(self.cmd).required(&self.required); - - let req_args = { - #[cfg(feature = "usage")] - { - usg.get_required_usage_from(&raw_req_args, Some(matcher), true) - .into_iter() - .map(|s| s.to_string()) - .collect::<Vec<_>>() - } - - #[cfg(not(feature = "usage"))] - { - raw_req_args - .iter() - .map(|id| { - if let Some(arg) = self.cmd.find(id) { - arg.to_string() - } else if let Some(_group) = self.cmd.find_group(id) { - self.cmd.format_group(id).to_string() - } else { - debug_assert!(false, "id={:?} is unknown", id); - "".to_owned() - } - }) - .collect::<Vec<_>>() - } - }; - - debug!( - "Validator::missing_required_error: req_args={:#?}", - req_args - ); - - let used: Vec<Id> = matcher - .args() - .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent)) - .map(|(n, _)| n) - .filter(|n| { - // Filter out the args we don't want to specify. - self.cmd.find(n).map_or(false, |a| !a.is_hide_set()) - }) - .cloned() - .chain(raw_req_args) - .collect(); - - Err(Error::missing_required_argument( - self.cmd, - req_args, - usg.create_usage_with_title(&used), - )) - } -} - -#[derive(Default, Clone, Debug)] -struct Conflicts { - potential: FlatMap<Id, Vec<Id>>, -} - -impl Conflicts { - fn with_args(cmd: &Command, matcher: &ArgMatcher) -> Self { - let mut potential = FlatMap::new(); - potential.extend_unchecked( - matcher - .args() - .filter(|(_, matched)| matched.check_explicit(&ArgPredicate::IsPresent)) - .map(|(id, _)| { - let conf = gather_direct_conflicts(cmd, id); - (id.clone(), conf) - }), - ); - Self { potential } - } - - fn gather_conflicts(&self, cmd: &Command, arg_id: &Id) -> Vec<Id> { - debug!("Conflicts::gather_conflicts: arg={:?}", arg_id); - let mut conflicts = Vec::new(); - - let arg_id_conflicts_storage; - let arg_id_conflicts = if let Some(arg_id_conflicts) = self.get_direct_conflicts(arg_id) { - arg_id_conflicts - } else { - // `is_missing_required_ok` is a case where we check not-present args for conflicts - arg_id_conflicts_storage = gather_direct_conflicts(cmd, arg_id); - &arg_id_conflicts_storage - }; - for (other_arg_id, other_arg_id_conflicts) in self.potential.iter() { - if arg_id == other_arg_id { - continue; - } - - if arg_id_conflicts.contains(other_arg_id) { - conflicts.push(other_arg_id.clone()); - } - if other_arg_id_conflicts.contains(arg_id) { - conflicts.push(other_arg_id.clone()); - } - } - - debug!("Conflicts::gather_conflicts: conflicts={:?}", conflicts); - conflicts - } - - fn get_direct_conflicts(&self, arg_id: &Id) -> Option<&[Id]> { - self.potential.get(arg_id).map(Vec::as_slice) - } -} - -fn gather_direct_conflicts(cmd: &Command, id: &Id) -> Vec<Id> { - let conf = if let Some(arg) = cmd.find(id) { - gather_arg_direct_conflicts(cmd, arg) - } else if let Some(group) = cmd.find_group(id) { - gather_group_direct_conflicts(group) - } else { - debug_assert!(false, "id={:?} is unknown", id); - Vec::new() - }; - debug!( - "Conflicts::gather_direct_conflicts id={:?}, conflicts={:?}", - id, conf - ); - conf -} - -fn gather_arg_direct_conflicts(cmd: &Command, arg: &Arg) -> Vec<Id> { - let mut conf = arg.blacklist.clone(); - for group_id in cmd.groups_for_arg(arg.get_id()) { - let group = cmd.find_group(&group_id).expect(INTERNAL_ERROR_MSG); - conf.extend(group.conflicts.iter().cloned()); - if !group.multiple { - for member_id in &group.args { - if member_id != arg.get_id() { - conf.push(member_id.clone()); - } - } - } - } - - // Overrides are implicitly conflicts - conf.extend(arg.overrides.iter().cloned()); - - conf -} - -fn gather_group_direct_conflicts(group: &ArgGroup) -> Vec<Id> { - group.conflicts.clone() -} - -pub(crate) fn get_possible_values_cli(a: &Arg) -> Vec<PossibleValue> { - if !a.is_takes_value_set() { - vec![] - } else { - a.get_value_parser() - .possible_values() - .map(|pvs| pvs.collect()) - .unwrap_or_default() - } -} diff --git a/vendor/clap/src/util/color.rs b/vendor/clap/src/util/color.rs deleted file mode 100644 index 4d59b2eb2..000000000 --- a/vendor/clap/src/util/color.rs +++ /dev/null @@ -1,103 +0,0 @@ -use crate::builder::PossibleValue; -use crate::derive::ValueEnum; - -/// Represents the color preferences for program output -#[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub enum ColorChoice { - /// Enables colored output only when the output is going to a terminal or TTY. - /// - /// **NOTE:** This is the default behavior of `clap`. - /// - /// # Platform Specific - /// - /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). - /// - /// # Examples - /// - #[cfg_attr(not(feature = "color"), doc = " ```ignore")] - #[cfg_attr(feature = "color", doc = " ```no_run")] - /// # use clap::{Command, ColorChoice}; - /// Command::new("myprog") - /// .color(ColorChoice::Auto) - /// .get_matches(); - /// ``` - Auto, - - /// Enables colored output regardless of whether or not the output is going to a terminal/TTY. - /// - /// # Platform Specific - /// - /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). - /// - /// # Examples - /// - #[cfg_attr(not(feature = "color"), doc = " ```ignore")] - #[cfg_attr(feature = "color", doc = " ```no_run")] - /// # use clap::{Command, ColorChoice}; - /// Command::new("myprog") - /// .color(ColorChoice::Always) - /// .get_matches(); - /// ``` - Always, - - /// Disables colored output no matter if the output is going to a terminal/TTY, or not. - /// - /// # Platform Specific - /// - /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms) - /// - /// # Examples - /// - #[cfg_attr(not(feature = "color"), doc = " ```ignore")] - #[cfg_attr(feature = "color", doc = " ```no_run")] - /// # use clap::{Command, ColorChoice}; - /// Command::new("myprog") - /// .color(ColorChoice::Never) - /// .get_matches(); - /// ``` - Never, -} - -impl Default for ColorChoice { - fn default() -> Self { - Self::Auto - } -} - -impl std::fmt::Display for ColorChoice { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.to_possible_value() - .expect("no values are skipped") - .get_name() - .fmt(f) - } -} - -impl std::str::FromStr for ColorChoice { - type Err = String; - - fn from_str(s: &str) -> Result<Self, Self::Err> { - for variant in Self::value_variants() { - if variant.to_possible_value().unwrap().matches(s, false) { - return Ok(*variant); - } - } - Err(format!("invalid variant: {}", s)) - } -} - -impl ValueEnum for ColorChoice { - fn value_variants<'a>() -> &'a [Self] { - &[Self::Auto, Self::Always, Self::Never] - } - - fn to_possible_value(&self) -> Option<PossibleValue> { - Some(match self { - Self::Auto => { - PossibleValue::new("auto").help("Use colored output if writing to a terminal/TTY") - } - Self::Always => PossibleValue::new("always").help("Always use colored output"), - Self::Never => PossibleValue::new("never").help("Never use colored output"), - }) - } -} diff --git a/vendor/clap/src/util/flat_map.rs b/vendor/clap/src/util/flat_map.rs deleted file mode 100644 index 468f0a9d8..000000000 --- a/vendor/clap/src/util/flat_map.rs +++ /dev/null @@ -1,254 +0,0 @@ -#![allow(dead_code)] - -use std::borrow::Borrow; - -/// Flat (Vec) backed map -/// -/// This preserves insertion order -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct FlatMap<K, V> { - keys: Vec<K>, - values: Vec<V>, -} - -impl<K: PartialEq + Eq, V> FlatMap<K, V> { - pub(crate) fn new() -> Self { - Default::default() - } - - pub(crate) fn insert(&mut self, key: K, mut value: V) -> Option<V> { - for (index, existing) in self.keys.iter().enumerate() { - if *existing == key { - std::mem::swap(&mut self.values[index], &mut value); - return Some(value); - } - } - - self.insert_unchecked(key, value); - None - } - - pub(crate) fn insert_unchecked(&mut self, key: K, value: V) { - self.keys.push(key); - self.values.push(value); - } - - pub(crate) fn extend_unchecked(&mut self, iter: impl IntoIterator<Item = (K, V)>) { - for (key, value) in iter { - self.insert_unchecked(key, value); - } - } - - pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool - where - K: Borrow<Q>, - Q: Eq, - { - for existing in &self.keys { - if existing.borrow() == key { - return true; - } - } - false - } - - pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V> - where - K: Borrow<Q>, - Q: std::hash::Hash + Eq, - { - self.remove_entry(key).map(|(_, v)| v) - } - - pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)> - where - K: Borrow<Q>, - Q: std::hash::Hash + Eq, - { - let index = some!(self - .keys - .iter() - .enumerate() - .find_map(|(i, k)| (k.borrow() == key).then_some(i))); - let key = self.keys.remove(index); - let value = self.values.remove(index); - Some((key, value)) - } - - pub(crate) fn is_empty(&self) -> bool { - self.keys.is_empty() - } - - pub fn entry(&mut self, key: K) -> Entry<K, V> { - for (index, existing) in self.keys.iter().enumerate() { - if *existing == key { - return Entry::Occupied(OccupiedEntry { v: self, index }); - } - } - Entry::Vacant(VacantEntry { v: self, key }) - } - - pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> - where - K: Borrow<Q>, - Q: Eq, - { - for (index, existing) in self.keys.iter().enumerate() { - if existing.borrow() == k { - return Some(&self.values[index]); - } - } - None - } - - pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V> - where - K: Borrow<Q>, - Q: Eq, - { - for (index, existing) in self.keys.iter().enumerate() { - if existing.borrow() == k { - return Some(&mut self.values[index]); - } - } - None - } - - pub fn keys(&self) -> std::slice::Iter<'_, K> { - self.keys.iter() - } - - pub fn iter(&self) -> Iter<K, V> { - Iter { - keys: self.keys.iter(), - values: self.values.iter(), - } - } - - pub fn iter_mut(&mut self) -> IterMut<K, V> { - IterMut { - keys: self.keys.iter_mut(), - values: self.values.iter_mut(), - } - } -} - -impl<K: PartialEq + Eq, V> Default for FlatMap<K, V> { - fn default() -> Self { - Self { - keys: Default::default(), - values: Default::default(), - } - } -} - -pub enum Entry<'a, K: 'a, V: 'a> { - Vacant(VacantEntry<'a, K, V>), - Occupied(OccupiedEntry<'a, K, V>), -} - -impl<'a, K: 'a, V: 'a> Entry<'a, K, V> { - pub fn or_insert(self, default: V) -> &'a mut V { - match self { - Entry::Occupied(entry) => &mut entry.v.values[entry.index], - Entry::Vacant(entry) => { - entry.v.keys.push(entry.key); - entry.v.values.push(default); - entry.v.values.last_mut().unwrap() - } - } - } - - pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V { - match self { - Entry::Occupied(entry) => &mut entry.v.values[entry.index], - Entry::Vacant(entry) => { - entry.v.keys.push(entry.key); - entry.v.values.push(default()); - entry.v.values.last_mut().unwrap() - } - } - } -} - -pub struct VacantEntry<'a, K: 'a, V: 'a> { - v: &'a mut FlatMap<K, V>, - key: K, -} - -pub struct OccupiedEntry<'a, K: 'a, V: 'a> { - v: &'a mut FlatMap<K, V>, - index: usize, -} - -pub struct Iter<'a, K: 'a, V: 'a> { - keys: std::slice::Iter<'a, K>, - values: std::slice::Iter<'a, V>, -} - -impl<'a, K, V> Iterator for Iter<'a, K, V> { - type Item = (&'a K, &'a V); - - fn next(&mut self) -> Option<(&'a K, &'a V)> { - match self.keys.next() { - Some(k) => { - let v = self.values.next().unwrap(); - Some((k, v)) - } - None => None, - } - } - fn size_hint(&self) -> (usize, Option<usize>) { - self.keys.size_hint() - } -} - -impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> { - fn next_back(&mut self) -> Option<(&'a K, &'a V)> { - match self.keys.next_back() { - Some(k) => { - let v = self.values.next_back().unwrap(); - Some((k, v)) - } - None => None, - } - } -} - -impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {} - -pub struct IterMut<'a, K: 'a, V: 'a> { - keys: std::slice::IterMut<'a, K>, - values: std::slice::IterMut<'a, V>, -} - -impl<'a, K, V> Iterator for IterMut<'a, K, V> { - type Item = (&'a K, &'a mut V); - - fn next(&mut self) -> Option<(&'a K, &'a mut V)> { - match self.keys.next() { - Some(k) => { - let v = self.values.next().unwrap(); - Some((k, v)) - } - None => None, - } - } - fn size_hint(&self) -> (usize, Option<usize>) { - self.keys.size_hint() - } -} - -impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> { - fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { - match self.keys.next_back() { - Some(k) => { - let v = self.values.next_back().unwrap(); - Some((k, v)) - } - None => None, - } - } -} - -impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {} diff --git a/vendor/clap/src/util/flat_set.rs b/vendor/clap/src/util/flat_set.rs deleted file mode 100644 index 3e0b23dae..000000000 --- a/vendor/clap/src/util/flat_set.rs +++ /dev/null @@ -1,107 +0,0 @@ -#![allow(dead_code)] - -use std::borrow::Borrow; - -/// Flat (Vec) backed set -/// -/// This preserves insertion order -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct FlatSet<T> { - inner: Vec<T>, -} - -impl<T: PartialEq + Eq> FlatSet<T> { - pub(crate) fn new() -> Self { - Default::default() - } - - pub(crate) fn insert(&mut self, value: T) -> bool { - for existing in &self.inner { - if *existing == value { - return false; - } - } - self.inner.push(value); - true - } - - pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool - where - T: Borrow<Q>, - Q: Eq, - { - for existing in &self.inner { - if existing.borrow() == value { - return true; - } - } - false - } - - pub fn retain<F>(&mut self, f: F) - where - F: FnMut(&T) -> bool, - { - self.inner.retain(f); - } - - pub(crate) fn is_empty(&self) -> bool { - self.inner.is_empty() - } - - pub(crate) fn iter(&self) -> std::slice::Iter<'_, T> { - self.inner.iter() - } - - pub fn sort_by_key<K, F>(&mut self, f: F) - where - F: FnMut(&T) -> K, - K: Ord, - { - self.inner.sort_by_key(f); - } -} - -impl<T: PartialEq + Eq> Default for FlatSet<T> { - fn default() -> Self { - Self { - inner: Default::default(), - } - } -} - -impl<T: PartialEq + Eq> IntoIterator for FlatSet<T> { - type Item = T; - type IntoIter = std::vec::IntoIter<T>; - - fn into_iter(self) -> Self::IntoIter { - self.inner.into_iter() - } -} - -impl<'s, T: PartialEq + Eq> IntoIterator for &'s FlatSet<T> { - type Item = &'s T; - type IntoIter = std::slice::Iter<'s, T>; - - fn into_iter(self) -> Self::IntoIter { - self.inner.iter() - } -} - -impl<T: PartialEq + Eq> Extend<T> for FlatSet<T> { - fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { - for value in iter { - self.insert(value); - } - } -} - -impl<T: PartialEq + Eq> FromIterator<T> for FlatSet<T> { - fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { - let mut set = Self::new(); - for value in iter { - set.insert(value); - } - set - } -} diff --git a/vendor/clap/src/util/graph.rs b/vendor/clap/src/util/graph.rs deleted file mode 100644 index d646400b0..000000000 --- a/vendor/clap/src/util/graph.rs +++ /dev/null @@ -1,49 +0,0 @@ -#[derive(Debug)] -struct Child<T> { - id: T, - children: Vec<usize>, -} - -impl<T> Child<T> { - fn new(id: T) -> Self { - Child { - id, - children: vec![], - } - } -} - -#[derive(Debug)] -pub(crate) struct ChildGraph<T>(Vec<Child<T>>); - -impl<T> ChildGraph<T> -where - T: Sized + PartialEq + Clone, -{ - pub(crate) fn with_capacity(s: usize) -> Self { - ChildGraph(Vec::with_capacity(s)) - } - - pub(crate) fn insert(&mut self, req: T) -> usize { - self.0.iter().position(|e| e.id == req).unwrap_or_else(|| { - let idx = self.0.len(); - self.0.push(Child::new(req)); - idx - }) - } - - pub(crate) fn insert_child(&mut self, parent: usize, child: T) -> usize { - let c_idx = self.0.len(); - self.0.push(Child::new(child)); - self.0[parent].children.push(c_idx); - c_idx - } - - pub(crate) fn iter(&self) -> impl Iterator<Item = &T> { - self.0.iter().map(|r| &r.id) - } - - pub(crate) fn contains(&self, req: &T) -> bool { - self.0.iter().any(|r| r.id == *req) - } -} diff --git a/vendor/clap/src/util/id.rs b/vendor/clap/src/util/id.rs deleted file mode 100644 index 710d2ea7d..000000000 --- a/vendor/clap/src/util/id.rs +++ /dev/null @@ -1,164 +0,0 @@ -use crate::builder::Str; - -/// [`Arg`][crate::Arg] or [`ArgGroup`][crate::ArgGroup] identifier -/// -/// This is used for accessing the value in [`ArgMatches`][crate::ArgMatches] or defining -/// relationships between `Arg`s and `ArgGroup`s with functions like -/// [`Arg::conflicts_with`][crate::Arg::conflicts_with]. -#[derive(Default, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] -pub struct Id(Str); - -impl Id { - pub(crate) const HELP: &'static str = "help"; - pub(crate) const VERSION: &'static str = "version"; - pub(crate) const EXTERNAL: &'static str = ""; - - pub(crate) fn from_static_ref(name: &'static str) -> Self { - Self(Str::from_static_ref(name)) - } - - /// Get the raw string of the `Id` - pub fn as_str(&self) -> &str { - self.0.as_str() - } - - pub(crate) fn as_internal_str(&self) -> &Str { - &self.0 - } -} - -impl From<&'_ Id> for Id { - fn from(id: &'_ Id) -> Self { - id.clone() - } -} - -impl From<Str> for Id { - fn from(name: Str) -> Self { - Self(name) - } -} - -impl From<&'_ Str> for Id { - fn from(name: &'_ Str) -> Self { - Self(name.into()) - } -} - -#[cfg(feature = "string")] -impl From<std::string::String> for Id { - fn from(name: std::string::String) -> Self { - Self(name.into()) - } -} - -#[cfg(feature = "string")] -impl From<&'_ std::string::String> for Id { - fn from(name: &'_ std::string::String) -> Self { - Self(name.into()) - } -} - -impl From<&'static str> for Id { - fn from(name: &'static str) -> Self { - Self(name.into()) - } -} - -impl From<&'_ &'static str> for Id { - fn from(name: &'_ &'static str) -> Self { - Self(name.into()) - } -} - -impl From<Id> for Str { - fn from(name: Id) -> Self { - name.0 - } -} - -impl From<Id> for String { - fn from(name: Id) -> Self { - Str::from(name).into() - } -} - -impl std::fmt::Display for Id { - #[inline] - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Display::fmt(self.as_str(), f) - } -} - -impl std::fmt::Debug for Id { - #[inline] - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - std::fmt::Debug::fmt(self.as_str(), f) - } -} - -impl AsRef<str> for Id { - #[inline] - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::borrow::Borrow<str> for Id { - #[inline] - fn borrow(&self) -> &str { - self.as_str() - } -} - -impl PartialEq<str> for Id { - #[inline] - fn eq(&self, other: &str) -> bool { - PartialEq::eq(self.as_str(), other) - } -} -impl PartialEq<Id> for str { - #[inline] - fn eq(&self, other: &Id) -> bool { - PartialEq::eq(self, other.as_str()) - } -} - -impl PartialEq<&'_ str> for Id { - #[inline] - fn eq(&self, other: &&str) -> bool { - PartialEq::eq(self.as_str(), *other) - } -} -impl PartialEq<Id> for &'_ str { - #[inline] - fn eq(&self, other: &Id) -> bool { - PartialEq::eq(*self, other.as_str()) - } -} - -impl PartialEq<Str> for Id { - #[inline] - fn eq(&self, other: &Str) -> bool { - PartialEq::eq(self.as_str(), other.as_str()) - } -} -impl PartialEq<Id> for Str { - #[inline] - fn eq(&self, other: &Id) -> bool { - PartialEq::eq(self.as_str(), other.as_str()) - } -} - -impl PartialEq<std::string::String> for Id { - #[inline] - fn eq(&self, other: &std::string::String) -> bool { - PartialEq::eq(self.as_str(), other.as_str()) - } -} -impl PartialEq<Id> for std::string::String { - #[inline] - fn eq(&self, other: &Id) -> bool { - PartialEq::eq(other, self) - } -} diff --git a/vendor/clap/src/util/mod.rs b/vendor/clap/src/util/mod.rs deleted file mode 100644 index e6a8f70ed..000000000 --- a/vendor/clap/src/util/mod.rs +++ /dev/null @@ -1,44 +0,0 @@ -#![allow(clippy::single_component_path_imports)] - -pub(crate) mod flat_map; -pub(crate) mod flat_set; -mod graph; -mod id; -mod str_to_bool; - -pub use self::id::Id; - -pub(crate) use self::flat_map::Entry; -pub(crate) use self::flat_map::FlatMap; -pub(crate) use self::flat_set::FlatSet; -pub(crate) use self::graph::ChildGraph; -pub(crate) use self::str_to_bool::str_to_bool; -pub(crate) use self::str_to_bool::FALSE_LITERALS; -pub(crate) use self::str_to_bool::TRUE_LITERALS; - -pub(crate) mod color; - -pub(crate) const SUCCESS_CODE: i32 = 0; -// While sysexists.h defines EX_USAGE as 64, this doesn't seem to be used much in practice but -// instead 2 seems to be frequently used. -// Examples -// - GNU `ls` returns 2 -// - Python's `argparse` returns 2 -pub(crate) const USAGE_CODE: i32 = 2; - -pub(crate) fn safe_exit(code: i32) -> ! { - use std::io::Write; - - let _ = std::io::stdout().lock().flush(); - let _ = std::io::stderr().lock().flush(); - - std::process::exit(code) -} - -#[cfg(not(feature = "unicode"))] -pub(crate) fn eq_ignore_case(left: &str, right: &str) -> bool { - left.eq_ignore_ascii_case(right) -} - -#[cfg(feature = "unicode")] -pub(crate) use unicase::eq as eq_ignore_case; diff --git a/vendor/clap/src/util/str_to_bool.rs b/vendor/clap/src/util/str_to_bool.rs deleted file mode 100644 index 1fbdc7531..000000000 --- a/vendor/clap/src/util/str_to_bool.rs +++ /dev/null @@ -1,21 +0,0 @@ -/// True values are `y`, `yes`, `t`, `true`, `on`, and `1`. -pub(crate) const TRUE_LITERALS: [&str; 6] = ["y", "yes", "t", "true", "on", "1"]; - -/// False values are `n`, `no`, `f`, `false`, `off`, and `0`. -pub(crate) const FALSE_LITERALS: [&str; 6] = ["n", "no", "f", "false", "off", "0"]; - -/// Converts a string literal representation of truth to true or false. -/// -/// `false` values are `n`, `no`, `f`, `false`, `off`, and `0` (case insensitive). -/// -/// Any other value will be considered as `true`. -pub(crate) fn str_to_bool(val: impl AsRef<str>) -> Option<bool> { - let pat: &str = &val.as_ref().to_lowercase(); - if TRUE_LITERALS.contains(&pat) { - Some(true) - } else if FALSE_LITERALS.contains(&pat) { - Some(false) - } else { - None - } -} |