diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 19:33:14 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 19:33:14 +0000 |
commit | 36d22d82aa202bb199967e9512281e9a53db42c9 (patch) | |
tree | 105e8c98ddea1c1e4784a60a5a6410fa416be2de /third_party/rust/clap | |
parent | Initial commit. (diff) | |
download | firefox-esr-upstream.tar.xz firefox-esr-upstream.zip |
Adding upstream version 115.7.0esr.upstream/115.7.0esrupstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/clap')
122 files changed, 33916 insertions, 0 deletions
diff --git a/third_party/rust/clap/.cargo-checksum.json b/third_party/rust/clap/.cargo-checksum.json new file mode 100644 index 0000000000..dc82b6d7c8 --- /dev/null +++ b/third_party/rust/clap/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"2ec13fd0e12fedb834d38d41b9a8f5256d072bb72bd1dc9b2c82a5bce261baf9","Cargo.toml":"3029ba78c9f735e2603be18b3388585509f58830facfdf6db6ebce2c6b062158","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"6725d1437fc6c77301f2ff0e7d52914cf4f9509213e1078dc77d9356dbe6eac5","README.md":"f717b799574b78231a95049906acfadaefc010b1ef02897967c4cbb89cca9102","benches/01_default.rs":"d65df6622531917affdba219552236425f78a05712b796d82e9b5f6634aaf1cd","benches/02_simple.rs":"2c0653407241aa6d9ad13ac65a0e91a212c55b5842a5a025fbed795510709936","benches/03_complex.rs":"d74a8995066b1bbaa126bbedafa1b0e07be141ed5416be1a4131c263d4b50763","benches/04_new_help.rs":"82c7e6c7a2e29239131ec6358d87203019e6c6c81eb3c38fbc2f563607b7413d","benches/05_ripgrep.rs":"a36f2e5dad4edbfcf521e6b900e932d5b10de903ba1c560f45962f9f4a9d0863","benches/06_rustup.rs":"9397f81671043fb062d55b0066f4769f2e3c627fe7781b48f78440448bcc1ee3","examples/README.md":"3da9187b15988b99103f585ba6199d12c5a43441dd9bf3dc3225c211debbb5b1","examples/cargo-example-derive.md":"53a35e48cd04dfa10d70f99eb6d97d0d74110958f7f9e4ffc460fca87a256a73","examples/cargo-example-derive.rs":"2c08a8f93dc0bd4205323956d23e38f50f69846aece19edf749c341145c62d32","examples/cargo-example.md":"1f270b0a0ac9122feb9cdac0887c1c1bcf1b654fed27147871c9cfe71851a4d9","examples/cargo-example.rs":"675d39e5837ca71acb1d662f1f43e6704d19ac1f9b52800e54bbeacde6a0c47b","examples/demo.md":"3e986afca0863142fdd4cc092b5969fba32a70fac8adf84a55bd652f4b30eedb","examples/demo.rs":"2bf20d203a1f35fbdcae25690e4e9f55938a485ab92f909822decc0d2f3a6c10","examples/derive_ref/README.md":"4be9d9468ba4b5759d4fa8ca3e62695d5b3c654ab0542b22fec116aa857af983","examples/derive_ref/augment_args.rs":"de176a7978d2a45ce06a746cdc13806319f1999b41e9e7849bfb16839b33376e","examples/derive_ref/augment_subcommands.rs":"f0b4738ff01af53507f99754fa87ed244daeb95f7864b3c5463392d393f7ce2b","examples/derive_ref/custom-bool.md":"4aa41737326d7591a223d3b98b6c19dada4b62d12ac9d7aee44edadf71286fb0","examples/derive_ref/custom-bool.rs":"82b52b9fd902007a5b075445efac5bbc10f59e1a32433abe70850769b99a00cf","examples/derive_ref/flatten_hand_args.rs":"0565b6ef2077ed7ec09e8bbad85c8c9a20585111672b901d588fb6bdf7344f98","examples/derive_ref/hand_subcommand.rs":"288b9edfe70e017be8d1f5c11c8e294284f239748441d147a5a2f5282438c04f","examples/derive_ref/interop_tests.md":"3a357e82cfc155f71e0348be33f78295aa77839c3e3a5b7c1783cbd1259e6a61","examples/escaped-positional-derive.md":"b2190ada5ad2634c3ceb7f9d98293512628762545f9519579cbee9867c6a406a","examples/escaped-positional-derive.rs":"0784fc1a0407053065bd231ba20d7c7d7c0225ef5ee48892b60632ce87dceb48","examples/escaped-positional.md":"b6a5c103f5cea1464b5ac8e63e1964f032a4dbb4a908e45b9b391f4857fe2684","examples/escaped-positional.rs":"30220741cab1fbd6be8184e84b0715ca7d3db46e6002aa008d07600eee5eaf72","examples/git-derive.md":"1a20f30d1c6df28d7e48b527b0726e9440f54d55a1e0b9e059b2322a7960ee72","examples/git-derive.rs":"fbfa7c557155ff15ded43f5e4bd011e0dff874f7bc705993e3c6df50e5e18558","examples/git.md":"acb3a44f954a6e2160f8989952981fb4baea8b97b921e4227c67896bc64d5e4a","examples/git.rs":"f00c7857c81bdab373bce292eb9733e35a7d358729d829c6228f7a96bcef2d20","examples/multicall-busybox.md":"3cb9d00ad110fc99c298dac4aa471e2f7a304aecef51d2eda67f5fbf36c41293","examples/multicall-busybox.rs":"cee5c19664b7fe04a2ee15912337cc733042e35e4527d3d2aeddd686fd0e416e","examples/multicall-hostname.md":"8c2d95fa8b940d4f788f96cf6b08b81bb2541bf12adff63bdff90dfc24567c7e","examples/multicall-hostname.rs":"56002453334cdc2ce66b36b8c192535a6d25d2b93cb27761443cb0d7a5bfc75a","examples/pacman.md":"e583ef465e55fa2fffef3b121e4a90835b8905ef3ffe2ec9ae91702832b7392d","examples/pacman.rs":"9bc96e2bda8cb05e32ce2875c7895727035e91851c51feb666438fe91a67b942","examples/repl.rs":"2596ad5550c7516b39bb1c256698c47760289ad01c71d3fb5d8994b0aeb1432e","examples/tutorial_builder/01_quick.rs":"e77b7d13339c32175f8557872905a58f7e7cb12011af406db818003d58ff8383","examples/tutorial_builder/02_app_settings.rs":"e75c4ff25944d232a81a45e51cf537bb0953365029432bb412148088478117e9","examples/tutorial_builder/02_apps.rs":"c894e5532188a69b4f70da76cbd3ba0da0f2ef99b8cc166921d33e227d2097e2","examples/tutorial_builder/02_crate.rs":"d11d8b67d5970ffd1959920340feea9eb0ef28ef785c4aedfcbc856b196d15ae","examples/tutorial_builder/03_01_flag_bool.rs":"335fde46e6671f346475992ef354a65940031cd289797c633ba1ead945a50064","examples/tutorial_builder/03_01_flag_count.rs":"2fb0c286b6736814327e89691d4dff963d67ec2e21ca1d9eb0011104e54f3fb7","examples/tutorial_builder/03_02_option.rs":"f885febca66261de1fd9bdf644eee414640b366fcd40a5636dbe6b8b86ad79ab","examples/tutorial_builder/03_03_positional.rs":"7fde3b689cec6fe461a9d846edd0771bde38ecd140578872725f4b4662ec2702","examples/tutorial_builder/03_04_subcommands.rs":"74ce4e38f817e4b93ace297141761345a7613e2c2346d57d9d3b70ac1a246764","examples/tutorial_builder/03_05_default_values.rs":"f34dd35da83306ae272082ee4f950350e72e203d47351087c7c6ae4126fc8283","examples/tutorial_builder/04_01_enum.rs":"dbf7887694141402f1ffc3d1a1903ccccbead6ce7376396b12fe98763f4fb563","examples/tutorial_builder/04_01_possible.rs":"3fb3dfc39b94552d498e968c22ea55b7c2dd855c0147993b163f5e1188ccc36c","examples/tutorial_builder/04_02_parse.rs":"e2671f487c805bf5f27de87afa25a2ee18163a2feade1712c3bbbb3870af659d","examples/tutorial_builder/04_02_validate.rs":"1d4ca583cd17db81e1e2c0bd48f344527933859d2c6415421b44af78930d7c95","examples/tutorial_builder/04_03_relations.rs":"aafb5c8c3ae034046993d2d8dcd68642106aee07f1512d670bd1dea01e2fa07c","examples/tutorial_builder/04_04_custom.rs":"a35a895764d7a119273bca536297dc8f2f6ba7600b975ebb31ad72760cf6cf04","examples/tutorial_builder/05_01_assert.rs":"9dee6679af27136d3a9ca517a21f799d9e294167c7465a2b7c265fad4c9daf9c","examples/tutorial_builder/README.md":"f055e67f6aa693bb92bbae76f4bb50ceb0e10b07ab8728af0ddbea94a6c88bee","examples/tutorial_derive/01_quick.rs":"f0ea261accd0a8ecce82ddd4cc4f93e6efd9940300edfa972459d6caca05e506","examples/tutorial_derive/02_app_settings.rs":"43290668f00675ce43f1209f800892fa664ab0d9c57b42bbc470c5843ce66811","examples/tutorial_derive/02_apps.rs":"5c71c66b2a6ad0d57c47e911fc7d9ea9163064b89ee2ece610202b133241c3e5","examples/tutorial_derive/02_crate.rs":"345f4e9a7ba384d6008c1686009b1ba05ec646252fb56efdd02d8efd0b80d851","examples/tutorial_derive/03_01_flag_bool.rs":"8fb058ef030429ff601509e2d0f67279522d8c8639b5bafee29eaa83e983b0ba","examples/tutorial_derive/03_01_flag_count.rs":"edc54dcf8631ff60438b89871d7e92f1a97077ae4293271af2c279ec53a3d0bc","examples/tutorial_derive/03_02_option.rs":"cc9487c64a71ed272ee3ec210a87fde5cded839cb64548f0bab0a3f0c44186fe","examples/tutorial_derive/03_03_positional.rs":"092d843366f4959f917bcbeef3a521c033c623ba25dc8f8f167e9cc218024d7d","examples/tutorial_derive/03_04_subcommands.rs":"1f157b1cd8c9e1661bba1083555b77bcf0de4b0398ca1775e19f53a72a737df2","examples/tutorial_derive/03_04_subcommands_alt.rs":"6a019fbdf26c0a513304e95154bfc5b1e0564c3886e2d0b0feb1ddf6032e0c31","examples/tutorial_derive/03_05_default_values.rs":"28dacd9836fe525dab37b0095c8df40d8fa0c19457c0d09ac32f0f7b8972baeb","examples/tutorial_derive/04_01_enum.rs":"12fbe926afa371c633e36324c9e18976ac8b375939f7d637c9fcfabb0833a297","examples/tutorial_derive/04_02_parse.rs":"ecd08d395fd455cb4a167c29279dabfa0be13cc19d70cd9a9fe199725a3efe83","examples/tutorial_derive/04_02_validate.rs":"e4992869879af8a69097ef4fdcd1e9a5cbf1d174dcd9dfa53d1d93fa33eba128","examples/tutorial_derive/04_03_relations.rs":"ede16700d983aa08081d29054cd946237c67951e3c7f3ee92d432a7abcb3952e","examples/tutorial_derive/04_04_custom.rs":"bc0fc3838c42b394abf6a4e73b70933f0290b3ed4151ff349bafed4a5815d52f","examples/tutorial_derive/05_01_assert.rs":"ded7bb91cd293dce6e60fcf4c9208eaac799b9d90e4f30598e5a8510427a71d7","examples/tutorial_derive/README.md":"da4929d79505f8c2f09c88d5e555cafeb39e96da407bcb3cd97102893f8f7670","examples/typed-derive.md":"cf3ee8313709937cc9c5462e3826cca8679946a658d684e8a36e66b0950100a7","examples/typed-derive.rs":"5b7b5cc6d9f6f10be55bb2df8d8d8b8ed9484c0b7d8f1054b5d8a9697ea394f2","src/bin/stdio-fixture.rs":"e8f10afbfe1857bcf986d2f55be0ca19a50c905d9f650c6e1fd42dbacf219b04","src/build/app_settings.rs":"91fe424d11e5220e2000f3a25b367a6ea9cfbd6a93a47b8c53916d0f260d90ae","src/build/arg.rs":"dd26efc3ac7f250fc130fa77d2d4a31fd3c2d37ea6c169f5404d94aab7bc9de3","src/build/arg_group.rs":"27993e229092327be9e98bbcd0a033b23eb83ff4581efd39c53111a01a6c84fb","src/build/arg_predicate.rs":"8c9fd14780cd42465f32f2e8927b97c06e686d09b5927ba3cd5bbd792af7a13d","src/build/arg_settings.rs":"1eb03498d18e02874a4c534a75b204ef4ede9e10f72f7ba73e584a002537fcd3","src/build/command.rs":"3dda34aeb37d4cf623881d16e1081824c966df6a454aa2b4d2cec6e109a4dfce","src/build/debug_asserts.rs":"2a461f4e9b6ae98442a249a8de49b2777dc01dfe16fc8369f6999885ed1af687","src/build/macros.rs":"904e42e72c49107ae324f45d5df24fbff13b9c7d4589f1a4ae38594add704434","src/build/mod.rs":"c876a1f5bfc7d7545f1019c38520342ed681c427a2d2f2ccbac5f10c3612e9ca","src/build/possible_value.rs":"9f46be1a5a6d407f1c316dab763a528d538e3e29f6bff8883c4a39f98c79d8fb","src/build/regex.rs":"b18891310186ecdcca9bb611833b7188cc80fe72e9fef27b63fa076b880a1acb","src/build/tests.rs":"995c7d6be608b94c6f392f1356eba0cb8adb9ca661ffeebf7ebe6e8ad01a868c","src/build/usage_parser.rs":"9f5c0900932ce4d0e371f28f3d1fe7a04bd705508b0476c3bb2b035a55c078c3","src/build/value_hint.rs":"0dd974d495c313430898d28b79991a70983c9aa44e88fa9aa1776d3308935438","src/derive.rs":"cec2f22de80e768b52899dbabc7e3892813d464dd23325af4c15deef8326e73f","src/error/context.rs":"1dc561c7877d7f9b90f04bb7915744f0b3cc4ac2aa928ae100b2825a97077142","src/error/kind.rs":"ea521d41a60d0a53e305d6a7555a772253757bebe2734a5d17539fe66bcc2e27","src/error/mod.rs":"f92cc86699a1bff0f8d0ea1f02b4f6073acf01ee77303729ed75a354b9f57814","src/lib.rs":"cb455acb0c34043a716d4416cc43d247300c6a8226820c0655d8632817271f5a","src/macros.rs":"d8b4f47680b573624a62b2862b48d075d23d9b7d23b1785a21430f09c94efa9c","src/mkeymap.rs":"a5faf57bce951b03b06a25d2d63d28b04bef5dc9694e80e7519cc379b5f3d537","src/output/fmt.rs":"efb741b5854500d946c6c09763ece1badc2b9cd3efa616cb58012039836c2b7f","src/output/help.rs":"20f8267c059f40ef0ecdfe7e0b5c6599a3449e2394778717780d133a0fc2b124","src/output/mod.rs":"3a61f89a4568e95114a3ab839da8f3c4c92de2a228549308f5d1be076a474917","src/output/usage.rs":"da6833909eda05553eafbef3c7f06e48e5a76d28cfa82266ddad987dc572de2b","src/parse/arg_matcher.rs":"d8c8ae95fe663c7612931309aaafcd6d40e99b44765c46c6d636dbc2899903f3","src/parse/features/mod.rs":"6ed075e97af56bff22f22ed1ee83ff6479360e05f9d3661a3145f822c242b694","src/parse/features/suggestions.rs":"f1f78c9d359c66989f904314f6a0398ee616ac69e089b3e164d375d6b5873355","src/parse/matches/arg_matches.rs":"121ce832e8b03fb1d60b986aa8caa43219d32fac93bd435b1d04c5e079eeb031","src/parse/matches/matched_arg.rs":"58658f2461e5498bcd1cc996bac916ce7aa95600bfee23786f23995a9724fa19","src/parse/matches/mod.rs":"8144a1b46739f0048a0973a180b133a1ebdbed946514acbb17c79d0ec75e607a","src/parse/matches/value_source.rs":"e6a477ae36f2f7155960239a97b7d142eef4eb227c41c9eefea147289547d713","src/parse/mod.rs":"e9c2621a1d666d75c511f98704c18ffc9ba8d821debd55877e284c98a177e47a","src/parse/parser.rs":"ded330fd39af09b0b424f192b22d76ff8b24ce4d9acbb368cc61c34c544e6df2","src/parse/validator.rs":"bc512f3b9c2b94351f8502d04bb36e26abbcf4135ef443aa9a131a101c49fd93","src/util/color.rs":"63df5e1cda1001b4c536dc0b04e09dd85dae6d317e34e660abbe3c71e17eaa29","src/util/fnv.rs":"82492d91d990f38b62de8b3c3e67f1fad55919117b1f448aa28acf6d21919fd7","src/util/graph.rs":"f35396b6e2a427377dcbbca69b1b98737d89684a3834cfda98cbf8cc70ff9c2f","src/util/id.rs":"fc498c65887385d92a51359a2f72556c2e508ee49b8cac4b3f827512795d690d","src/util/mod.rs":"702c2567286d80f9ccb4e6910cda690965f23b21a93c4cd286f37e7890e92783","src/util/str_to_bool.rs":"f9302078014c7b8f493811f2bc0bcbb982c33efde6c5ca98bea479781c1501b7"},"package":"d2dbdf4bdacb33466e854ce889eee8dfd5729abf7ccd7664d0a2d60cd384440b"}
\ No newline at end of file diff --git a/third_party/rust/clap/Cargo.lock b/third_party/rust/clap/Cargo.lock new file mode 100644 index 0000000000..921f081e3b --- /dev/null +++ b/third_party/rust/clap/Cargo.lock @@ -0,0 +1,1040 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "addr2line" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "aho-corasick" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" +dependencies = [ + "memchr", +] + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi", +] + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "backtrace" +version = "0.3.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11a17d453482a265fd5f8479f2a3f405566e6ca627837aaddb85af8b1ab8ef61" +dependencies = [ + "addr2line", + "cc", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bstr" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" +dependencies = [ + "lazy_static", + "memchr", + "regex-automata", + "serde", +] + +[[package]] +name = "bumpalo" +version = "3.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4a45a46ab1f2412e53d3a0ade76ffad2025804294569aae387231a0cd6e0899" + +[[package]] +name = "bytes" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" + +[[package]] +name = "cast" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c24dab4283a142afa2fdca129b80ad2c6284e073930f964c3a1293c225ee39a" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "cc" +version = "1.0.73" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "clap" +version = "2.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" +dependencies = [ + "bitflags", + "textwrap 0.11.0", + "unicode-width", +] + +[[package]] +name = "clap" +version = "3.1.18" +dependencies = [ + "atty", + "backtrace", + "bitflags", + "clap_derive", + "clap_lex", + "criterion", + "humantime", + "indexmap", + "lazy_static", + "regex", + "rustversion", + "shlex", + "snapbox", + "strsim", + "termcolor", + "terminal_size", + "textwrap 0.15.0", + "trybuild", + "trycmd", + "unicase", + "yaml-rust", +] + +[[package]] +name = "clap_derive" +version = "3.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25320346e922cffe59c0bbc5410c8d8784509efb321488971081313cb1e1a33c" +dependencies = [ + "heck", + "proc-macro-error", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37c35f1112dad5e6e0b1adaff798507497a18fceeb30cceb3bae7d1427b9213" +dependencies = [ + "os_str_bytes", +] + +[[package]] +name = "combine" +version = "4.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a604e93b79d1808327a6fca85a6f2d69de66461e7620f5a4cbf5fb4d1d7c948" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concolor" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "015267563b1df20adccdd00cb05257b1dfbea70a04928e9cf88ffb850c1a40af" +dependencies = [ + "atty", + "bitflags", + "concolor-query", +] + +[[package]] +name = "concolor-query" +version = "0.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6417fe6fc03a8b533fd2177742eeb39a90c7233eedec7bac96d4d6b69a09449" + +[[package]] +name = "criterion" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1604dafd25fba2fe2d5895a9da139f8dc9b319a5fe5354ca137cbbce4e178d10" +dependencies = [ + "atty", + "cast", + "clap 2.34.0", + "criterion-plot", + "csv", + "itertools", + "lazy_static", + "num-traits", + "oorandom", + "plotters", + "rayon", + "regex", + "serde", + "serde_cbor", + "serde_derive", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d00996de9f2f7559f7f4dc286073197f83e92256a59ed395f9aac01fe717da57" +dependencies = [ + "cast", + "itertools", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aaa7bd5fb665c6864b5f963dd9097905c54125909c7aa94c9e18507cdbe6c53" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" +dependencies = [ + "cfg-if", + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1145cf131a2c6ba0615079ab6a638f7e1973ac9c2634fcbeaaad6114246efe8c" +dependencies = [ + "autocfg", + "cfg-if", + "crossbeam-utils", + "lazy_static", + "memoffset", + "scopeguard", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf124c720b7686e3c2663cf54062ab0f68a88af2fb6a030e87e30bf721fcb38" +dependencies = [ + "cfg-if", + "lazy_static", +] + +[[package]] +name = "csv" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22813a6dc45b335f9bade10bf7271dc477e81113e89eb251a0bc2a8a81c536e1" +dependencies = [ + "bstr", + "csv-core", + "itoa 0.4.8", + "ryu", + "serde", +] + +[[package]] +name = "csv-core" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" +dependencies = [ + "memchr", +] + +[[package]] +name = "either" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" + +[[package]] +name = "escargot" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5584ba17d7ab26a8a7284f13e5bd196294dd2f2d79773cff29b9e9edef601a6" +dependencies = [ + "log", + "once_cell", + "serde", + "serde_json", +] + +[[package]] +name = "gimli" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78cc372d058dcf6d5ecd98510e7fbc9e5aec4d21de70f65fea8fecebcd881bd4" + +[[package]] +name = "glob" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" + +[[package]] +name = "half" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" + +[[package]] +name = "hashbrown" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" + +[[package]] +name = "heck" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "humantime" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" + +[[package]] +name = "humantime-serde" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57a3db5ea5923d99402c94e9feb261dc5ee9b4efa158b0315f788cf549cc200c" +dependencies = [ + "humantime", + "serde", +] + +[[package]] +name = "indexmap" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" +dependencies = [ + "autocfg", + "hashbrown", +] + +[[package]] +name = "itertools" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" + +[[package]] +name = "itoa" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" + +[[package]] +name = "js-sys" +version = "0.3.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "671a26f820db17c2a2750743f1dd03bafd15b98c9f30c7c2628c024c05d73397" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.125" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5916d2ae698f6de9bfb891ad7a8d65c09d232dc58cc4ac433c7da3b2fd84bc2b" + +[[package]] +name = "linked-hash-map" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3" + +[[package]] +name = "log" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" + +[[package]] +name = "memoffset" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miniz_oxide" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2b29bd4bc3f33391105ebee3589c19197c4271e3e5a9ec9bfe8127eeff8f082" +dependencies = [ + "adler", +] + +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + +[[package]] +name = "num-traits" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "object" +version = "0.28.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40bec70ba014595f99f7aa110b84331ffe1ee9aece7fe6f387cc7e3ecda4d456" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" + +[[package]] +name = "oorandom" +version = "11.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" + +[[package]] +name = "os_pipe" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c92f2b54f081d635c77e7120862d48db8e91f7f21cef23ab1b4fe9971c59f55" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "os_str_bytes" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" + +[[package]] +name = "plotters" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a3fd9ec30b9749ce28cd91f255d569591cdf937fe280c312143e3c4bad6f2a" +dependencies = [ + "num-traits", + "plotters-backend", + "plotters-svg", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "plotters-backend" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d88417318da0eaf0fdcdb51a0ee6c3bed624333bff8f946733049380be67ac1c" + +[[package]] +name = "plotters-svg" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521fa9638fa597e1dc53e9412a4f9cefb01187ee1f7413076f9e6749e2885ba9" +dependencies = [ + "plotters-backend", +] + +[[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.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" +dependencies = [ + "unicode-xid", +] + +[[package]] +name = "quote" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rayon" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd249e82c21598a9a426a4e00dd7adc1d640b22445ec8545feef801d1a74c221" +dependencies = [ + "autocfg", + "crossbeam-deque", + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f51245e1e62e1f1629cbfec37b5793bbabcaeb90f30e94d2ba03564687353e4" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-utils", + "num_cpus", +] + +[[package]] +name = "regex" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" + +[[package]] +name = "regex-syntax" +version = "0.6.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" + +[[package]] +name = "rustc-demangle" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342" + +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver", +] + +[[package]] +name = "rustversion" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2cc38e8fa666e2de3c4aba7edeb5ffc5246c1c2ed0e3d17e560aeeba736b23f" + +[[package]] +name = "ryu" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "semver" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cb243bdfdb5936c8dc3c45762a19d12ab4550cdc753bc247637d4ec35a040fd" + +[[package]] +name = "serde" +version = "1.0.137" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_cbor" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5" +dependencies = [ + "half", + "serde", +] + +[[package]] +name = "serde_derive" +version = "1.0.137" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b7ce2b32a1aed03c558dc61a5cd328f15aff2dbc17daad8fb8af04d2100e15c" +dependencies = [ + "itoa 1.0.1", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b2853a4d09f215c24cc5489c992ce46052d359b5109343cbafbf26bc62f8a3" + +[[package]] +name = "similar" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e24979f63a11545f5f2c60141afe249d4f19f84581ea2138065e400941d83d3" + +[[package]] +name = "snapbox" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "767a1d5da232b6959cd1bd5c9e8db8a7cce09c3038e89deedb49a549a2aefd93" +dependencies = [ + "concolor", + "normalize-line-endings", + "os_pipe", + "similar", + "snapbox-macros", + "wait-timeout", + "yansi", +] + +[[package]] +name = "snapbox-macros" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c01dea7e04cbb27ef4c86e9922184608185f7cd95c1763bc30d727cda4a5e930" + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "syn" +version = "1.0.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ff7c592601f11445996a06f8ad0c27f094a58857c2f89e97974ab9235b92c52" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "termcolor" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "terminal_size" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "textwrap" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "textwrap" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb" +dependencies = [ + "terminal_size", + "unicode-width", +] + +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "toml" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba98375fd631b83696f87c64e4ed8e29e6a1f3404d6aed95fa95163bad38e705" +dependencies = [ + "combine", + "indexmap", + "itertools", + "serde", +] + +[[package]] +name = "trybuild" +version = "1.0.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fc92f558afb6d1d7c6f175eb8d615b8ef49c227543e68e19c123d4ee43d8a7d" +dependencies = [ + "glob", + "once_cell", + "serde", + "serde_derive", + "serde_json", + "termcolor", + "toml", +] + +[[package]] +name = "trycmd" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffb4185126cc904642173a54c185083f410c86d1202ada6761aacf7c40829f13" +dependencies = [ + "escargot", + "glob", + "humantime", + "humantime-serde", + "rayon", + "serde", + "shlex", + "snapbox", + "toml_edit", +] + +[[package]] +name = "unicase" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" +dependencies = [ + "version_check", +] + +[[package]] +name = "unicode-width" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" + +[[package]] +name = "unicode-xid" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "wait-timeout" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6" +dependencies = [ + "libc", +] + +[[package]] +name = "walkdir" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56" +dependencies = [ + "same-file", + "winapi", + "winapi-util", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27370197c907c55e3f1a9fbe26f44e937fe6451368324e009cba39e139dc08ad" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e04185bfa3a779273da532f5025e33398409573f348985af9a1cbf3774d3f4" +dependencies = [ + "bumpalo", + "lazy_static", + "log", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17cae7ff784d7e83a2fe7611cfe766ecf034111b49deb850a3dc7699c08251f5" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99ec0dc7a4756fffc231aab1b9f2f578d23cd391390ab27f952ae0c9b3ece20b" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d554b7f530dee5964d9a9468d95c1f8b8acae4f282807e7d27d4b03099a46744" + +[[package]] +name = "web-sys" +version = "0.3.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b17e741662c70c8bd24ac5c5b18de314a2c26c32bf8346ee1e6f53de919c283" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "yaml-rust" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" +dependencies = [ + "linked-hash-map", +] + +[[package]] +name = "yansi" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" diff --git a/third_party/rust/clap/Cargo.toml b/third_party/rust/clap/Cargo.toml new file mode 100644 index 0000000000..e1ced84be1 --- /dev/null +++ b/third_party/rust/clap/Cargo.toml @@ -0,0 +1,528 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "clap" +version = "3.1.18" +include = [ + "build.rs", + "src/**/*", + "Cargo.toml", + "LICENSE*", + "README.md", + "benches/**/*", + "examples/**/*", +] +description = "A simple to use, efficient, and full-featured Command Line Argument Parser" +documentation = "https://docs.rs/clap/" +readme = "README.md" +keywords = [ + "argument", + "cli", + "arg", + "parser", + "parse", +] +categories = ["command-line-interface"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/clap-rs/clap" + +[package.metadata.docs.rs] +features = ["unstable-doc"] +rustdoc-args = [ + "--cfg", + "docsrs", +] +cargo-args = [ + "-Zunstable-options", + "-Zrustdoc-scrape-examples=examples", +] + +[package.metadata.playground] +features = ["unstable-doc"] + +[package.metadata.release] +shared-version = true +tag-name = "v{{version}}" + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "Unreleased" +replace = "{{version}}" +min = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = '\.\.\.HEAD' +replace = "...{{tag_name}}" +exactly = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "ReleaseDate" +replace = "{{date}}" +min = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "<!-- next-header -->" +replace = """ +<!-- next-header --> +## [Unreleased] - ReleaseDate +""" +exactly = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "CHANGELOG.md" +search = "<!-- next-url -->" +replace = """ +<!-- next-url --> +[Unreleased]: https://github.com/clap-rs/clap/compare/{{tag_name}}...HEAD""" +exactly = 1 + +[[package.metadata.release.pre-release-replacements]] +file = "README.md" +search = "github.com/clap-rs/clap/blob/[^/]+/" +replace = "github.com/clap-rs/clap/blob/{{tag_name}}/" +exactly = 13 +prerelease = true + +[[package.metadata.release.pre-release-replacements]] +file = "README.md" +search = 'version = "[a-z0-9\.-]+"' +replace = "version = \"{{version}}\"" +exactly = 1 +prerelease = true + +[[package.metadata.release.pre-release-replacements]] +file = "src/derive.rs" +search = "github.com/clap-rs/clap/blob/[^/]+/" +replace = "github.com/clap-rs/clap/blob/{{tag_name}}/" +exactly = 4 +prerelease = true + +[profile.bench] +lto = true +codegen-units = 1 + +[profile.test] +opt-level = 1 + +[lib] +bench = false + +[[example]] +name = "demo" +required-features = ["derive"] + +[[example]] +name = "cargo-example" +required-features = ["cargo"] + +[[example]] +name = "cargo-example-derive" +required-features = ["derive"] + +[[example]] +name = "escaped-positional" +required-features = ["cargo"] + +[[example]] +name = "escaped-positional-derive" +required-features = ["derive"] + +[[example]] +name = "git-derive" +required-features = ["derive"] + +[[example]] +name = "typed-derive" +required-features = ["derive"] + +[[example]] +name = "busybox" +path = "examples/multicall-busybox.rs" +required-features = ["unstable-multicall"] + +[[example]] +name = "hostname" +path = "examples/multicall-hostname.rs" +required-features = ["unstable-multicall"] + +[[example]] +name = "repl" +path = "examples/repl.rs" +required-features = ["unstable-multicall"] + +[[example]] +name = "01_quick" +path = "examples/tutorial_builder/01_quick.rs" +required-features = ["cargo"] + +[[example]] +name = "02_apps" +path = "examples/tutorial_builder/02_apps.rs" + +[[example]] +name = "02_crate" +path = "examples/tutorial_builder/02_crate.rs" +required-features = ["cargo"] + +[[example]] +name = "02_app_settings" +path = "examples/tutorial_builder/02_app_settings.rs" +required-features = ["cargo"] + +[[example]] +name = "03_01_flag_bool" +path = "examples/tutorial_builder/03_01_flag_bool.rs" +required-features = ["cargo"] + +[[example]] +name = "03_01_flag_count" +path = "examples/tutorial_builder/03_01_flag_count.rs" +required-features = ["cargo"] + +[[example]] +name = "03_02_option" +path = "examples/tutorial_builder/03_02_option.rs" +required-features = ["cargo"] + +[[example]] +name = "03_03_positional" +path = "examples/tutorial_builder/03_03_positional.rs" +required-features = ["cargo"] + +[[example]] +name = "03_04_subcommands" +path = "examples/tutorial_builder/03_04_subcommands.rs" +required-features = ["cargo"] + +[[example]] +name = "03_05_default_values" +path = "examples/tutorial_builder/03_05_default_values.rs" +required-features = ["cargo"] + +[[example]] +name = "04_01_possible" +path = "examples/tutorial_builder/04_01_possible.rs" +required-features = ["cargo"] + +[[example]] +name = "04_01_enum" +path = "examples/tutorial_builder/04_01_enum.rs" +required-features = [ + "cargo", + "derive", +] + +[[example]] +name = "04_02_parse" +path = "examples/tutorial_builder/04_02_parse.rs" +required-features = ["cargo"] + +[[example]] +name = "04_02_validate" +path = "examples/tutorial_builder/04_02_validate.rs" +required-features = ["cargo"] + +[[example]] +name = "04_03_relations" +path = "examples/tutorial_builder/04_03_relations.rs" +required-features = ["cargo"] + +[[example]] +name = "04_04_custom" +path = "examples/tutorial_builder/04_04_custom.rs" +required-features = ["cargo"] + +[[example]] +name = "05_01_assert" +path = "examples/tutorial_builder/05_01_assert.rs" +test = true +required-features = ["cargo"] + +[[example]] +name = "01_quick_derive" +path = "examples/tutorial_derive/01_quick.rs" +required-features = ["derive"] + +[[example]] +name = "02_apps_derive" +path = "examples/tutorial_derive/02_apps.rs" +required-features = ["derive"] + +[[example]] +name = "02_crate_derive" +path = "examples/tutorial_derive/02_crate.rs" +required-features = ["derive"] + +[[example]] +name = "02_app_settings_derive" +path = "examples/tutorial_derive/02_app_settings.rs" +required-features = ["derive"] + +[[example]] +name = "03_01_flag_bool_derive" +path = "examples/tutorial_derive/03_01_flag_bool.rs" +required-features = ["derive"] + +[[example]] +name = "03_01_flag_count_derive" +path = "examples/tutorial_derive/03_01_flag_count.rs" +required-features = ["derive"] + +[[example]] +name = "03_02_option_derive" +path = "examples/tutorial_derive/03_02_option.rs" +required-features = ["derive"] + +[[example]] +name = "03_03_positional_derive" +path = "examples/tutorial_derive/03_03_positional.rs" +required-features = ["derive"] + +[[example]] +name = "03_04_subcommands_derive" +path = "examples/tutorial_derive/03_04_subcommands.rs" +required-features = ["derive"] + +[[example]] +name = "03_04_subcommands_alt_derive" +path = "examples/tutorial_derive/03_04_subcommands_alt.rs" +required-features = ["derive"] + +[[example]] +name = "03_05_default_values_derive" +path = "examples/tutorial_derive/03_05_default_values.rs" +required-features = ["derive"] + +[[example]] +name = "04_01_enum_derive" +path = "examples/tutorial_derive/04_01_enum.rs" +required-features = ["derive"] + +[[example]] +name = "04_02_parse_derive" +path = "examples/tutorial_derive/04_02_parse.rs" +required-features = ["derive"] + +[[example]] +name = "04_02_validate_derive" +path = "examples/tutorial_derive/04_02_validate.rs" +required-features = ["derive"] + +[[example]] +name = "04_03_relations_derive" +path = "examples/tutorial_derive/04_03_relations.rs" +required-features = ["derive"] + +[[example]] +name = "04_04_custom_derive" +path = "examples/tutorial_derive/04_04_custom.rs" +required-features = ["derive"] + +[[example]] +name = "05_01_assert_derive" +path = "examples/tutorial_derive/05_01_assert.rs" +test = true +required-features = ["derive"] + +[[example]] +name = "custom-bool" +path = "examples/derive_ref/custom-bool.rs" +required-features = ["derive"] + +[[example]] +name = "interop_augment_args" +path = "examples/derive_ref/augment_args.rs" +required-features = ["derive"] + +[[example]] +name = "interop_augment_subcommands" +path = "examples/derive_ref/augment_subcommands.rs" +required-features = ["derive"] + +[[example]] +name = "interop_hand_subcommand" +path = "examples/derive_ref/hand_subcommand.rs" +required-features = ["derive"] + +[[example]] +name = "interop_flatten_hand_args" +path = "examples/derive_ref/flatten_hand_args.rs" +required-features = ["derive"] + +[[bench]] +name = "01_default" +path = "benches/01_default.rs" +harness = false + +[[bench]] +name = "02_simple" +path = "benches/02_simple.rs" +harness = false + +[[bench]] +name = "03_complex" +path = "benches/03_complex.rs" +harness = false + +[[bench]] +name = "04_new_help" +path = "benches/04_new_help.rs" +harness = false + +[[bench]] +name = "05_ripgrep" +path = "benches/05_ripgrep.rs" +harness = false + +[[bench]] +name = "06_rustup" +path = "benches/06_rustup.rs" +harness = false + +[dependencies.atty] +version = "0.2" +optional = true + +[dependencies.backtrace] +version = "0.3" +optional = true + +[dependencies.bitflags] +version = "1.2" + +[dependencies.clap_derive] +version = "=3.1.18" +optional = true + +[dependencies.clap_lex] +version = "0.2.0" + +[dependencies.indexmap] +version = "1.0" + +[dependencies.lazy_static] +version = "1" +optional = true + +[dependencies.regex] +version = "1.0" +optional = true + +[dependencies.strsim] +version = "0.10" +optional = true + +[dependencies.termcolor] +version = "1.1.1" +optional = true + +[dependencies.terminal_size] +version = "0.1.12" +optional = true + +[dependencies.textwrap] +version = "0.15.0" +features = [] +default-features = false + +[dependencies.unicase] +version = "2.6" +optional = true + +[dependencies.yaml-rust] +version = "0.4.1" +optional = true + +[dev-dependencies.criterion] +version = "0.3.2" + +[dev-dependencies.humantime] +version = "2" + +[dev-dependencies.lazy_static] +version = "1" + +[dev-dependencies.regex] +version = "1.0" + +[dev-dependencies.rustversion] +version = "1" + +[dev-dependencies.shlex] +version = "1.1.0" + +[dev-dependencies.snapbox] +version = "0.2.9" + +[dev-dependencies.trybuild] +version = "1.0.18" + +[dev-dependencies.trycmd] +version = "0.13" +features = [ + "color-auto", + "diff", + "examples", +] +default-features = false + +[features] +cargo = ["lazy_static"] +color = [ + "atty", + "termcolor", +] +debug = [ + "clap_derive/debug", + "backtrace", +] +default = [ + "std", + "color", + "suggestions", +] +derive = [ + "clap_derive", + "lazy_static", +] +env = [] +std = ["indexmap/std"] +suggestions = ["strsim"] +unicode = [ + "textwrap/unicode-width", + "unicase", +] +unstable-doc = [ + "derive", + "cargo", + "wrap_help", + "yaml", + "env", + "unicode", + "regex", + "unstable-replace", + "unstable-multicall", + "unstable-grouped", +] +unstable-grouped = [] +unstable-multicall = [] +unstable-replace = [] +unstable-v4 = ["clap_derive/unstable-v4"] +wrap_help = [ + "terminal_size", + "textwrap/terminal_size", +] +yaml = ["yaml-rust"] diff --git a/third_party/rust/clap/LICENSE-APACHE b/third_party/rust/clap/LICENSE-APACHE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/third_party/rust/clap/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/third_party/rust/clap/LICENSE-MIT b/third_party/rust/clap/LICENSE-MIT new file mode 100644 index 0000000000..5acedf0412 --- /dev/null +++ b/third_party/rust/clap/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-2016 Kevin B. Knapp + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third_party/rust/clap/README.md b/third_party/rust/clap/README.md new file mode 100644 index 0000000000..ee6d9f3d8c --- /dev/null +++ b/third_party/rust/clap/README.md @@ -0,0 +1,179 @@ +<!-- omit in TOC --> +# clap + +> **Command Line Argument Parser for Rust** + +[![Crates.io](https://img.shields.io/crates/v/clap?style=flat-square)](https://crates.io/crates/clap) +[![Crates.io](https://img.shields.io/crates/d/clap?style=flat-square)](https://crates.io/crates/clap) +[![License](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/v3.1.18/LICENSE-APACHE) +[![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](https://github.com/clap-rs/clap/blob/v3.1.18/LICENSE-MIT) +[![Build Status](https://img.shields.io/github/workflow/status/clap-rs/clap/CI/staging?style=flat-square)](https://github.com/clap-rs/clap/actions/workflows/ci.yml?query=branch%3Astaging) +[![Coverage Status](https://img.shields.io/coveralls/github/clap-rs/clap/master?style=flat-square)](https://coveralls.io/github/clap-rs/clap?branch=master) +[![Contributors](https://img.shields.io/github/contributors/clap-rs/clap?style=flat-square)](https://github.com/clap-rs/clap/graphs/contributors) + +Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT). + +1. [About](#about) +2. Tutorial: [Builder API](https://github.com/clap-rs/clap/blob/v3.1.18/examples/tutorial_builder/README.md), [Derive API](https://github.com/clap-rs/clap/blob/v3.1.18/examples/tutorial_derive/README.md) +3. [Examples](https://github.com/clap-rs/clap/blob/v3.1.18/examples/README.md) +4. [API Reference](https://docs.rs/clap) + - [Derive Reference](https://github.com/clap-rs/clap/blob/v3.1.18/examples/derive_ref/README.md) + - [Feature Flags](#feature-flags) +5. [CHANGELOG](https://github.com/clap-rs/clap/blob/v3.1.18/CHANGELOG.md) +6. [FAQ](https://github.com/clap-rs/clap/blob/v3.1.18/docs/FAQ.md) +7. [Questions & Discussions](https://github.com/clap-rs/clap/discussions) +8. [Contributing](https://github.com/clap-rs/clap/blob/v3.1.18/CONTRIBUTING.md) +8. [Sponsors](#sponsors) + +## About + +Create your command-line parser, with all of the bells and whistles, declaratively or procedurally. + +### Example + +This uses our +[Derive API](https://github.com/clap-rs/clap/blob/v3.1.18/examples/tutorial_derive/README.md) +which provides access to the [Builder API](https://github.com/clap-rs/clap/blob/v3.1.18/examples/tutorial_builder/README.md) as attributes on a `struct`: + +<!-- Copied from examples/demo.{rs,md} --> +```rust,no_run +use clap::Parser; + +/// Simple program to greet a person +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Args { + /// Name of the person to greet + #[clap(short, long)] + name: String, + + /// Number of times to greet + #[clap(short, long, default_value_t = 1)] + count: u8, +} + +fn main() { + let args = Args::parse(); + + for _ in 0..args.count { + println!("Hello {}!", args.name) + } +} +``` +Add this to `Cargo.toml`: +```toml +[dependencies] +clap = { version = "3.1.18", features = ["derive"] } +``` +```bash +$ demo --help +clap [..] +Simple program to greet a person + +USAGE: + demo[EXE] [OPTIONS] --name <NAME> + +OPTIONS: + -c, --count <COUNT> Number of times to greet [default: 1] + -h, --help Print help information + -n, --name <NAME> Name of the person to greet + -V, --version Print version information +``` +*(version number and `.exe` extension on windows replaced by placeholders)* + +### Aspirations + +- Out of the box, users get a polished CLI experience + - Including common argument behavior, help generation, suggested fixes for users, colored output, [shell completions](https://github.com/clap-rs/clap/tree/master/clap_complete), etc +- Flexible enough to port your existing CLI interface + - However, we won't necessarily streamline support for each use case +- Reasonable parse performance +- Resilient maintainership, including + - Willing to break compatibility rather than batching up breaking changes in large releases + - Leverage feature flags to keep to one active branch + - Being under [WG-CLI](https://github.com/rust-cli/team/) to increase the bus factor +- We follow semver and will wait about 6-9 months between major breaking changes +- We will support the last two minor Rust releases (MSRV, currently 1.54.0) + +While these aspirations can be at odds with fast build times and low binary +size, we will still strive to keep these reasonable for the flexibility you +get. Check out the +[argparse-benchmarks](https://github.com/rust-cli/argparse-benchmarks-rs) for +CLI parsers optimized for other use cases. + +### Selecting an API + +Why use the declarative [Derive API](https://github.com/clap-rs/clap/blob/v3.1.18/examples/tutorial_derive/README.md): +- Easier to read, write, and modify +- Easier to keep the argument declaration and reading of argument in sync +- Easier to reuse, e.g. [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag) + +Why use the procedural [Builder API](https://github.com/clap-rs/clap/blob/v3.1.18/examples/tutorial_builder/README.md): +- Faster compile times if you aren't already using other procedural macros +- More flexible, e.g. you can look up how many times an argument showed up, + what its values were, and what were the indexes of those values. The Derive + API can only report presence, number of occurrences, or values but no indices + or combinations of data. + +### Related Projects + +- [wild](https://crates.io/crates/wild) for supporting wildcards (`*`) on Windows like you do Linux +- [argfile](https://crates.io/crates/argfile) for loading additional arguments from a file (aka response files) +- [shadow-rs](https://crates.io/crates/shadow-rs) for generating `Command::long_version` +- [clap_lex](https://crates.io/crates/clap_lex) for a lighter-weight, battle-tested CLI parser +- [clap_mangen](https://crates.io/crates/clap_mangen) for generating man page source (roff) +- [clap_complete](https://crates.io/crates/clap_complete) for shell completion support +- [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag) +- [clap-cargo](https://crates.io/crates/clap-cargo) +- [concolor-clap](https://crates.io/crates/concolor-clap) +- [Command-line Apps for Rust](https://rust-cli.github.io/book/index.html) book +- [`trycmd`](https://crates.io/crates/trycmd): Snapshot testing + - Or for more control, [`assert_cmd`](https://crates.io/crates/assert_cmd) and [`assert_fs`](https://crates.io/crates/assert_fs) + +## Feature Flags + +### Default Features + +* **std**: _Not Currently Used._ Placeholder for supporting `no_std` environments in a backwards compatible manner. +* **color**: Turns on colored error messages. +* **suggestions**: Turns on the `Did you mean '--myoption'?` feature for when users make typos. + +#### Optional features + +* **derive**: Enables the custom derive (i.e. `#[derive(Parser)]`). Without this you must use one of the other methods of creating a `clap` CLI listed above. +* **cargo**: Turns on macros that read values from `CARGO_*` environment variables. +* **env**: Turns on the usage of environment variables during parsing. +* **regex**: Enables regex validators. +* **unicode**: Turns on support for unicode characters (including emoji) in arguments and help messages. +* **wrap_help**: Turns on the help text wrapping feature, based on the terminal size. + +#### Experimental features + +**Warning:** These may contain breaking changes between minor releases. + +* **unstable-replace**: Enable [`Command::replace`](https://github.com/clap-rs/clap/issues/2836) +* **unstable-multicall**: Enable [`Command::multicall`](https://github.com/clap-rs/clap/issues/2861) +* **unstable-grouped**: Enable [`ArgMatches::grouped_values_of`](https://github.com/clap-rs/clap/issues/2924) +* **unstable-v4**: Preview features which will be stable on the v4.0 release + +## Sponsors + +<!-- omit in TOC --> +### Gold + +[![](https://opencollective.com/clap/tiers/gold.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) + +<!-- omit in TOC --> +### Silver + +[![](https://opencollective.com/clap/tiers/silver.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) + +<!-- omit in TOC --> +### Bronze + +[![](https://opencollective.com/clap/tiers/bronze.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) + +<!-- omit in TOC --> +### Backer + +[![](https://opencollective.com/clap/tiers/backer.svg?avatarHeight=36&width=600)](https://opencollective.com/clap) diff --git a/third_party/rust/clap/benches/01_default.rs b/third_party/rust/clap/benches/01_default.rs new file mode 100644 index 0000000000..620b32b818 --- /dev/null +++ b/third_party/rust/clap/benches/01_default.rs @@ -0,0 +1,15 @@ +use clap::Command; +use criterion::{criterion_group, criterion_main, Criterion}; + +pub fn build_empty(c: &mut Criterion) { + c.bench_function("build_empty", |b| b.iter(|| Command::new("claptests"))); +} + +pub fn parse_empty(c: &mut Criterion) { + c.bench_function("parse_empty", |b| { + b.iter(|| Command::new("claptests").get_matches_from(vec![""])) + }); +} + +criterion_group!(benches, build_empty, parse_empty); +criterion_main!(benches); diff --git a/third_party/rust/clap/benches/02_simple.rs b/third_party/rust/clap/benches/02_simple.rs new file mode 100644 index 0000000000..667d02f873 --- /dev/null +++ b/third_party/rust/clap/benches/02_simple.rs @@ -0,0 +1,104 @@ +use clap::{arg, Arg, Command}; +use criterion::{criterion_group, criterion_main, Criterion}; + +macro_rules! create_app { + () => {{ + Command::new("claptests") + .version("0.1") + .about("tests clap library") + .author("Kevin K. <kbknapp@gmail.com>") + .arg(arg!(-f --flag "tests flags")) + .arg(arg!(-o --option <opt> "tests options").required(false)) + .arg(arg!([positional] "tests positional")) + }}; +} + +pub fn build_simple(c: &mut Criterion) { + c.bench_function("build_simple", |b| b.iter(|| create_app!())); +} + +pub fn build_with_flag(c: &mut Criterion) { + c.bench_function("build_with_flag", |b| { + b.iter(|| Command::new("claptests").arg(arg!(-s --some "something"))) + }); +} + +pub fn build_with_flag_ref(c: &mut Criterion) { + c.bench_function("build_with_flag_ref", |b| { + b.iter(|| { + let arg = arg!(-s --some "something"); + Command::new("claptests").arg(&arg) + }) + }); +} + +pub fn build_with_opt(c: &mut Criterion) { + c.bench_function("build_with_opt", |b| { + b.iter(|| Command::new("claptests").arg(arg!(-s --some <FILE> "something"))) + }); +} + +pub fn build_with_opt_ref(c: &mut Criterion) { + c.bench_function("build_with_opt_ref", |b| { + b.iter(|| { + let arg = arg!(-s --some <FILE> "something"); + Command::new("claptests").arg(&arg) + }) + }); +} + +pub fn build_with_pos(c: &mut Criterion) { + c.bench_function("build_with_pos", |b| { + b.iter(|| Command::new("claptests").arg(Arg::new("some"))) + }); +} + +pub fn build_with_pos_ref(c: &mut Criterion) { + c.bench_function("build_with_pos_ref", |b| { + b.iter(|| { + let arg = Arg::new("some"); + Command::new("claptests").arg(&arg) + }) + }); +} + +pub fn parse_simple_with_flag(c: &mut Criterion) { + c.bench_function("parse_simple_with_flag", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "-f"])) + }); +} + +pub fn parse_simple_with_opt(c: &mut Criterion) { + c.bench_function("parse_simple_with_opt", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "-o", "option1"])) + }); +} + +pub fn parse_simple_with_pos(c: &mut Criterion) { + c.bench_function("parse_simple_with_pos", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "arg1"])) + }); +} + +pub fn parse_simple_with_complex(c: &mut Criterion) { + c.bench_function("parse_simple_with_complex", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "-o", "option1", "-f", "arg1"])) + }); +} + +criterion_group!( + benches, + parse_simple_with_complex, + parse_simple_with_pos, + parse_simple_with_opt, + parse_simple_with_flag, + build_with_pos_ref, + build_with_pos, + build_with_opt_ref, + build_with_opt, + build_with_flag_ref, + build_with_flag, + build_simple +); + +criterion_main!(benches); diff --git a/third_party/rust/clap/benches/03_complex.rs b/third_party/rust/clap/benches/03_complex.rs new file mode 100644 index 0000000000..3ac81bb15d --- /dev/null +++ b/third_party/rust/clap/benches/03_complex.rs @@ -0,0 +1,307 @@ +use clap::{arg, Arg, Command}; +use criterion::{criterion_group, criterion_main, Criterion}; + +static OPT3_VALS: [&str; 2] = ["fast", "slow"]; +static POS3_VALS: [&str; 2] = ["vi", "emacs"]; + +macro_rules! create_app { + () => {{ + Command::new("claptests") + .version("0.1") + .about("tests clap library") + .author("Kevin K. <kbknapp@gmail.com>") + .arg(arg!(-o --option <opt> ... "tests options").required(false)) + .arg(arg!([positional] "tests positionals")) + .arg(arg!(-f --flag ... "tests flags").global(true)) + .args(&[ + arg!(flag2: -F "tests flags with exclusions") + .conflicts_with("flag") + .requires("option2"), + arg!(option2: --"long-option-2" <option2> "tests long options with exclusions") + .required(false) + .conflicts_with("option") + .requires("positional2"), + arg!([positional2] "tests positionals with exclusions"), + arg!(-O --Option <option3> "tests options with specific value sets") + .required(false) + .possible_values(OPT3_VALS), + arg!([positional3] ... "tests positionals with specific values") + .possible_values(POS3_VALS), + arg!(--multvals "Tests multiple values not mult occs").required(false).value_names(&["one", "two"]), + arg!( + --multvalsmo "Tests multiple values, not mult occs" + ).multiple_values(true).required(false).value_names(&["one", "two"]), + arg!(--minvals2 <minvals> ... "Tests 2 min vals").min_values(2).multiple_values(true).required(false), + arg!(--maxvals3 <maxvals> ... "Tests 3 max vals").max_values(3).multiple_values(true).required(false), + ]) + .subcommand( + Command::new("subcmd") + .about("tests subcommands") + .version("0.1") + .author("Kevin K. <kbknapp@gmail.com>") + .arg(arg!(-o --option <scoption> ... "tests options").required(false)) + .arg(arg!([scpositional] "tests positionals")) + ) + }}; +} + +pub fn build_from_builder(c: &mut Criterion) { + c.bench_function("build_from_builder", |b| { + b.iter(|| { + Command::new("claptests") + .version("0.1") + .about("tests clap library") + .author("Kevin K. <kbknapp@gmail.com>") + .arg( + Arg::new("opt") + .help("tests options") + .short('o') + .long("option") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true), + ) + .arg(Arg::new("positional").help("tests positionals").index(1)) + .arg( + Arg::new("flag") + .short('f') + .help("tests flags") + .long("flag") + .global(true) + .multiple_occurrences(true), + ) + .arg( + Arg::new("flag2") + .short('F') + .help("tests flags with exclusions") + .conflicts_with("flag") + .requires("option2"), + ) + .arg( + Arg::new("option2") + .help("tests long options with exclusions") + .conflicts_with("option") + .requires("positional2") + .takes_value(true) + .long("long-option-2"), + ) + .arg( + Arg::new("positional2") + .index(3) + .help("tests positionals with exclusions"), + ) + .arg( + Arg::new("option3") + .short('O') + .long("Option") + .takes_value(true) + .help("tests options with specific value sets") + .possible_values(OPT3_VALS), + ) + .arg( + Arg::new("positional3") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .help("tests positionals with specific values") + .index(4) + .possible_values(POS3_VALS), + ) + .arg( + Arg::new("multvals") + .long("multvals") + .help("Tests multiple values, not mult occs") + .value_names(&["one", "two"]), + ) + .arg( + Arg::new("multvalsmo") + .long("multvalsmo") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .help("Tests multiple values, not mult occs") + .value_names(&["one", "two"]), + ) + .arg( + Arg::new("minvals") + .long("minvals2") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .help("Tests 2 min vals") + .min_values(2), + ) + .arg( + Arg::new("maxvals") + .long("maxvals3") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .help("Tests 3 max vals") + .max_values(3), + ) + .subcommand( + Command::new("subcmd") + .about("tests subcommands") + .version("0.1") + .author("Kevin K. <kbknapp@gmail.com>") + .arg( + Arg::new("scoption") + .short('o') + .long("option") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .help("tests options"), + ) + .arg(Arg::new("scpositional").index(1).help("tests positionals")), + ) + }) + }); +} + +pub fn parse_complex(c: &mut Criterion) { + c.bench_function("parse_complex", |b| { + b.iter(|| create_app!().get_matches_from(vec![""])) + }); +} + +pub fn parse_complex_with_flag(c: &mut Criterion) { + c.bench_function("parse_complex_with_flag", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "-f"])) + }); +} + +pub fn parse_complex_with_opt(c: &mut Criterion) { + c.bench_function("parse_complex_with_opt", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "-o", "option1"])) + }); +} + +pub fn parse_complex_with_pos(c: &mut Criterion) { + c.bench_function("parse_complex_with_pos", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "arg1"])) + }); +} + +pub fn parse_complex_with_sc(c: &mut Criterion) { + c.bench_function("parse_complex_with_sc", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "subcmd"])) + }); +} + +pub fn parse_complex_with_sc_flag(c: &mut Criterion) { + c.bench_function("parse_complex_with_sc_flag", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "subcmd", "-f"])) + }); +} + +pub fn parse_complex_with_sc_opt(c: &mut Criterion) { + c.bench_function("parse_complex_with_sc_opt", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "subcmd", "-o", "option1"])) + }); +} + +pub fn parse_complex_with_sc_pos(c: &mut Criterion) { + c.bench_function("parse_complex_with_sc_pos", |b| { + b.iter(|| create_app!().get_matches_from(vec!["myprog", "subcmd", "arg1"])) + }); +} + +pub fn parse_complex1(c: &mut Criterion) { + c.bench_function("parse_complex1", |b| { + b.iter(|| { + create_app!().get_matches_from(vec![ + "myprog", + "-ff", + "-o", + "option1", + "arg1", + "-O", + "fast", + "arg2", + "--multvals", + "one", + "two", + "emacs", + ]) + }) + }); +} + +pub fn parse_complex2(c: &mut Criterion) { + c.bench_function("parse_complex2", |b| { + b.iter(|| { + create_app!().get_matches_from(vec![ + "myprog", + "arg1", + "-f", + "arg2", + "--long-option-2", + "some", + "-O", + "slow", + "--multvalsmo", + "one", + "two", + "--minvals2", + "3", + "2", + "1", + ]) + }) + }); +} + +pub fn parse_args_negate_scs(c: &mut Criterion) { + c.bench_function("parse_args_negate_scs", |b| { + b.iter(|| { + create_app!() + .args_conflicts_with_subcommands(true) + .get_matches_from(vec![ + "myprog", + "arg1", + "-f", + "arg2", + "--long-option-2", + "some", + "-O", + "slow", + "--multvalsmo", + "one", + "two", + "--minvals2", + "3", + "2", + "1", + ]) + }) + }); +} + +pub fn parse_complex_with_sc_complex(c: &mut Criterion) { + c.bench_function("parse_complex_with_sc_complex", |b| { + b.iter(|| { + create_app!().get_matches_from(vec!["myprog", "subcmd", "-f", "-o", "option1", "arg1"]) + }) + }); +} + +criterion_group!( + benches, + build_from_builder, + parse_complex, + parse_complex_with_flag, + parse_complex_with_opt, + parse_complex_with_pos, + parse_complex_with_sc, + parse_complex_with_sc_flag, + parse_complex_with_sc_opt, + parse_complex_with_sc_pos, + parse_complex1, + parse_complex2, + parse_args_negate_scs, + parse_complex_with_sc_complex +); + +criterion_main!(benches); diff --git a/third_party/rust/clap/benches/04_new_help.rs b/third_party/rust/clap/benches/04_new_help.rs new file mode 100644 index 0000000000..83b14fb706 --- /dev/null +++ b/third_party/rust/clap/benches/04_new_help.rs @@ -0,0 +1,223 @@ +use clap::Command; +use clap::{arg, Arg}; +use criterion::{criterion_group, criterion_main, Criterion}; +use std::io::Cursor; + +fn build_help(cmd: &mut Command) -> String { + let mut buf = Cursor::new(Vec::with_capacity(50)); + cmd.write_help(&mut buf).unwrap(); + let content = buf.into_inner(); + String::from_utf8(content).unwrap() +} + +fn app_example1<'c>() -> Command<'c> { + Command::new("MyApp") + .version("1.0") + .author("Kevin K. <kbknapp@gmail.com>") + .about("Does awesome things") + .arg( + arg!( + -c --config <FILE> "Sets a custom config file" + ) + .required(false), + ) + .arg(arg!(<output> "Sets an optional output file")) + .arg(arg!(d: -d ... "Turn debugging information on")) + .subcommand( + Command::new("test") + .about("does testing things") + .arg(arg!(-l --list "lists test values")), + ) +} + +fn app_example2<'c>() -> Command<'c> { + Command::new("MyApp") + .version("1.0") + .author("Kevin K. <kbknapp@gmail.com>") + .about("Does awesome things") +} + +fn app_example3<'c>() -> Command<'c> { + Command::new("MyApp") + .arg( + Arg::new("debug") + .help("turn on debugging information") + .short('d'), + ) + .args(&[ + Arg::new("config") + .help("sets the config file to use") + .takes_value(true) + .short('c') + .long("config"), + Arg::new("input") + .help("the input file to use") + .required(true), + ]) + .arg(arg!(--license "display the license file")) + .arg(arg!([output] "Supply an output file to use")) + .arg( + arg!( + -i --int <IFACE> "Set an interface to use" + ) + .required(false), + ) +} + +fn app_example4<'c>() -> Command<'c> { + Command::new("MyApp") + .about("Parses an input file to do awesome things") + .version("1.0") + .author("Kevin K. <kbknapp@gmail.com>") + .arg( + Arg::new("debug") + .help("turn on debugging information") + .short('d') + .long("debug"), + ) + .arg( + Arg::new("config") + .help("sets the config file to use") + .short('c') + .long("config"), + ) + .arg( + Arg::new("input") + .help("the input file to use") + .index(1) + .required(true), + ) +} + +fn app_example5<'c>() -> Command<'c> { + Command::new("MyApp").arg( + Arg::new("awesome") + .help("turns up the awesome") + .short('a') + .long("awesome") + .multiple_occurrences(true), + ) +} + +fn app_example6<'c>() -> Command<'c> { + Command::new("MyApp") + .arg( + Arg::new("input") + .help("the input file to use") + .index(1) + .requires("config") + .required(true), + ) + .arg(Arg::new("config").help("the config file to use").index(2)) +} + +fn app_example7<'c>() -> Command<'c> { + Command::new("MyApp") + .arg(Arg::new("config")) + .arg(Arg::new("output")) + .arg( + Arg::new("input") + .help("the input file to use") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .required(true) + .short('i') + .long("input") + .requires("config") + .conflicts_with("output"), + ) +} + +fn app_example8<'c>() -> Command<'c> { + Command::new("MyApp") + .arg(Arg::new("config")) + .arg(Arg::new("output")) + .arg( + Arg::new("input") + .help("the input file to use") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true) + .required(true) + .short('i') + .long("input") + .requires("config") + .conflicts_with("output"), + ) +} + +fn app_example10<'c>() -> Command<'c> { + Command::new("myapp").about("does awesome things").arg( + Arg::new("CONFIG") + .help("The config file to use (default is \"config.json\")") + .short('c') + .takes_value(true), + ) +} + +pub fn example1(c: &mut Criterion) { + let mut cmd = app_example1(); + c.bench_function("example1", |b| b.iter(|| build_help(&mut cmd))); +} + +pub fn example2(c: &mut Criterion) { + let mut cmd = app_example2(); + c.bench_function("example2", |b| b.iter(|| build_help(&mut cmd))); +} + +pub fn example3(c: &mut Criterion) { + let mut cmd = app_example3(); + c.bench_function("example3", |b| b.iter(|| build_help(&mut cmd))); +} + +pub fn example4(c: &mut Criterion) { + let mut cmd = app_example4(); + c.bench_function("example4", |b| b.iter(|| build_help(&mut cmd))); +} + +pub fn example5(c: &mut Criterion) { + let mut cmd = app_example5(); + c.bench_function("example5", |b| b.iter(|| build_help(&mut cmd))); +} + +pub fn example6(c: &mut Criterion) { + let mut cmd = app_example6(); + c.bench_function("example6", |b| b.iter(|| build_help(&mut cmd))); +} + +pub fn example7(c: &mut Criterion) { + let mut cmd = app_example7(); + c.bench_function("example7", |b| b.iter(|| build_help(&mut cmd))); +} + +pub fn example8(c: &mut Criterion) { + let mut cmd = app_example8(); + c.bench_function("example8", |b| b.iter(|| build_help(&mut cmd))); +} + +pub fn example10(c: &mut Criterion) { + let mut cmd = app_example10(); + c.bench_function("example10", |b| b.iter(|| build_help(&mut cmd))); +} + +pub fn example4_template(c: &mut Criterion) { + let mut cmd = app_example4().help_template("{bin} {version}\n{author}\n{about}\n\nUSAGE:\n {usage}\n\nOPTIONS:\n{options}\n\nARGS:\n{args}\n"); + c.bench_function("example4_template", |b| b.iter(|| build_help(&mut cmd))); +} + +criterion_group!( + benches, + example1, + example2, + example3, + example4, + example5, + example6, + example7, + example8, + example10, + example4_template +); + +criterion_main!(benches); diff --git a/third_party/rust/clap/benches/05_ripgrep.rs b/third_party/rust/clap/benches/05_ripgrep.rs new file mode 100644 index 0000000000..7d5cab6964 --- /dev/null +++ b/third_party/rust/clap/benches/05_ripgrep.rs @@ -0,0 +1,952 @@ +// Used to simulate a fairly large number of options/flags and parsing with thousands of positional +// args +// +// CLI used is adapted from ripgrep 48a8a3a691220f9e5b2b08f4051abe8655ea7e8a + +use clap::{Arg, Command}; +use criterion::{criterion_group, criterion_main, Criterion}; +use std::collections::HashMap; +use std::io::Cursor; + +use lazy_static::lazy_static; + +pub fn build_rg_with_short_help(c: &mut Criterion) { + c.bench_function("build_rg_with_short_help", |b| b.iter(app_short)); +} + +pub fn build_rg_with_long_help(c: &mut Criterion) { + c.bench_function("build_rg_with_long_help", |b| b.iter(app_long)); +} + +pub fn write_rg_short_help(c: &mut Criterion) { + let mut cmd = app_short(); + c.bench_function("write_rg_short_help", |b| b.iter(|| build_help(&mut cmd))); +} + +pub fn write_rg_long_help(c: &mut Criterion) { + let mut cmd = app_long(); + c.bench_function("write_rg_long_help", |b| b.iter(|| build_help(&mut cmd))); +} + +pub fn parse_rg(c: &mut Criterion) { + c.bench_function("parse_rg", |b| { + b.iter(|| app_short().get_matches_from(vec!["rg", "pat"])) + }); +} + +pub fn parse_rg_with_complex(c: &mut Criterion) { + c.bench_function("parse_rg_with_complex", |b| { + b.iter(|| { + app_short().get_matches_from(vec![ + "rg", + "pat", + "-cFlN", + "-pqr=some", + "--null", + "--no-filename", + "--no-messages", + "-SH", + "-C5", + "--follow", + "-e some", + ]) + }) + }); +} + +pub fn parse_rg_with_lots(c: &mut Criterion) { + c.bench_function("parse_rg_with_lots", |b| { + b.iter(|| { + app_short().get_matches_from(vec![ + "rg", "pat", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", + ]) + }) + }); +} + +const ABOUT: &str = " +ripgrep (rg) recursively searches your current directory for a regex pattern. + +ripgrep's regex engine uses finite automata and guarantees linear time +searching. Because of this, features like backreferences and arbitrary +lookaround are not supported. + +Project home page: https://github.com/BurntSushi/ripgrep + +Use -h for short descriptions and --help for more details."; + +const USAGE: &str = " + rg [OPTIONS] <pattern> [<path> ...] + rg [OPTIONS] [-e PATTERN | -f FILE ]... [<path> ...] + rg [OPTIONS] --files [<path> ...] + rg [OPTIONS] --type-list"; + +const TEMPLATE: &str = "\ +{bin} {version} +{author} +{about} + +USAGE:{usage} + +ARGS: +{positionals} + +OPTIONS: +{options}"; + +/// Build a clap application with short help strings. +fn app_short() -> Command<'static> { + cmd(false, |k| USAGES[k].short) +} + +/// Build a clap application with long help strings. +fn app_long() -> Command<'static> { + cmd(true, |k| USAGES[k].long) +} + +/// Build the help text of an application. +fn build_help(cmd: &mut Command) -> String { + let mut buf = Cursor::new(Vec::with_capacity(50)); + cmd.write_help(&mut buf).unwrap(); + let content = buf.into_inner(); + String::from_utf8(content).unwrap() +} + +/// Build a clap application parameterized by usage strings. +/// +/// The function given should take a clap argument name and return a help +/// string. `cmd` will panic if a usage string is not defined. +/// +/// This is an intentionally stand-alone module so that it can be used easily +/// in a `build.rs` script to build shell completion files. +fn cmd<F>(_next_line_help: bool, doc: F) -> Command<'static> +where + F: Fn(&'static str) -> &'static str, +{ + let arg = |name| Arg::new(name).help(doc(name)); + let flag = |name| arg(name).long(name); + + Command::new("ripgrep") + .author("BurntSushi") // simulating since it's only a bench + .version("0.4.0") // Simulating + .about(ABOUT) + .max_term_width(100) + .override_usage(USAGE) + .help_template(TEMPLATE) + // Handle help/version manually to make their output formatting + // consistent with short/long views. + .arg(arg("help-short").short('h')) + .arg(flag("help")) + .arg(flag("version").short('V')) + // First, set up primary positional/flag arguments. + .arg(arg("pattern").required_unless_present_any(&[ + "file", + "files", + "help-short", + "help", + "regexp", + "type-list", + "version", + ])) + .arg( + arg("path") + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true), + ) + .arg( + flag("regexp") + .short('e') + .allow_hyphen_values(true) + .multiple_occurrences(true) + .takes_value(true) + .value_name("pattern"), + ) + .arg( + flag("files") + // This should also conflict with `pattern`, but the first file + // path will actually be in `pattern`. + .conflicts_with_all(&["file", "regexp", "type-list"]), + ) + .arg(flag("type-list").conflicts_with_all(&["file", "files", "pattern", "regexp"])) + // Second, set up common flags. + .arg(flag("text").short('a')) + .arg(flag("count").short('c')) + .arg( + flag("color") + .value_name("WHEN") + .takes_value(true) + .hide_possible_values(true) + .possible_values(["never", "auto", "always", "ansi"]), + ) + .arg( + flag("colors") + .value_name("SPEC") + .multiple_occurrences(true) + .takes_value(true), + ) + .arg(flag("fixed-strings").short('F')) + .arg( + flag("glob") + .short('g') + .multiple_occurrences(true) + .takes_value(true) + .value_name("GLOB"), + ) + .arg(flag("ignore-case").short('i')) + .arg(flag("line-number").short('n')) + .arg(flag("no-line-number").short('N')) + .arg(flag("quiet").short('q')) + .arg( + flag("type") + .short('t') + .multiple_occurrences(true) + .takes_value(true) + .value_name("TYPE"), + ) + .arg( + flag("type-not") + .short('T') + .multiple_occurrences(true) + .takes_value(true) + .value_name("TYPE"), + ) + .arg(flag("unrestricted").short('u').multiple_occurrences(true)) + .arg(flag("invert-match").short('v')) + .arg(flag("word-regexp").short('w')) + // Third, set up less common flags. + .arg( + flag("after-context") + .short('A') + .value_name("NUM") + .validator(validate_number), + ) + .arg( + flag("before-context") + .short('B') + .value_name("NUM") + .validator(validate_number), + ) + .arg( + flag("context") + .short('C') + .value_name("NUM") + .validator(validate_number), + ) + .arg(flag("column")) + .arg(flag("context-separator").value_name("SEPARATOR")) + .arg(flag("debug")) + .arg( + flag("file") + .short('f') + .value_name("FILE") + .multiple_occurrences(true), + ) + .arg(flag("files-with-matches").short('l')) + .arg(flag("files-without-match")) + .arg(flag("with-filename").short('H')) + .arg(flag("no-filename")) + .arg(flag("heading").overrides_with("no-heading")) + .arg(flag("no-heading").overrides_with("heading")) + .arg(flag("hidden")) + .arg( + flag("ignore-file") + .value_name("FILE") + .multiple_occurrences(true), + ) + .arg(flag("follow").short('L')) + .arg( + flag("max-count") + .short('m') + .value_name("NUM") + .validator(validate_number), + ) + .arg( + flag("maxdepth") + .value_name("NUM") + .validator(validate_number), + ) + .arg(flag("mmap")) + .arg(flag("no-messages")) + .arg(flag("no-mmap")) + .arg(flag("no-ignore")) + .arg(flag("no-ignore-parent")) + .arg(flag("no-ignore-vcs")) + .arg(flag("null")) + .arg(flag("path-separator").value_name("SEPARATOR")) + .arg(flag("pretty").short('p')) + .arg(flag("replace").short('r').value_name("ARG")) + .arg(flag("case-sensitive").short('s')) + .arg(flag("smart-case").short('S')) + .arg(flag("sort-files")) + .arg( + flag("threads") + .short('j') + .value_name("ARG") + .validator(validate_number), + ) + .arg(flag("vimgrep")) + .arg( + flag("type-add") + .value_name("TYPE") + .multiple_occurrences(true), + ) + .arg( + flag("type-clear") + .value_name("TYPE") + .multiple_occurrences(true), + ) +} + +struct Usage { + short: &'static str, + long: &'static str, +} + +macro_rules! doc { + ($map:expr, $name:expr, $short:expr) => { + doc!($map, $name, $short, $short) + }; + ($map:expr, $name:expr, $short:expr, $long:expr) => { + $map.insert( + $name, + Usage { + short: $short, + long: concat!($long, "\n "), + }, + ); + }; +} + +lazy_static! { + static ref USAGES: HashMap<&'static str, Usage> = { + let mut h = HashMap::new(); + doc!( + h, + "help-short", + "Show short help output.", + "Show short help output. Use --help to show more details." + ); + doc!( + h, + "help", + "Show verbose help output.", + "When given, more details about flags are provided." + ); + doc!(h, "version", "Print version information."); + + doc!( + h, + "pattern", + "A regular expression used for searching.", + "A regular expression used for searching. Multiple patterns \ + may be given. To match a pattern beginning with a -, use [-]." + ); + doc!( + h, + "regexp", + "A regular expression used for searching.", + "A regular expression used for searching. Multiple patterns \ + may be given. To match a pattern beginning with a -, use [-]." + ); + doc!( + h, + "path", + "A file or directory to search.", + "A file or directory to search. Directories are searched \ + recursively." + ); + doc!( + h, + "files", + "Print each file that would be searched.", + "Print each file that would be searched without actually \ + performing the search. This is useful to determine whether a \ + particular file is being searched or not." + ); + doc!( + h, + "type-list", + "Show all supported file types.", + "Show all supported file types and their corresponding globs." + ); + + doc!(h, "text", "Search binary files as if they were text."); + doc!(h, "count", "Only show count of matches for each file."); + doc!( + h, + "color", + "When to use color. [default: auto]", + "When to use color in the output. The possible values are \ + never, auto, always or ansi. The default is auto. When always \ + is used, coloring is attempted based on your environment. When \ + ansi used, coloring is forcefully done using ANSI escape color \ + codes." + ); + doc!( + h, + "colors", + "Configure color settings and styles.", + "This flag specifies color settings for use in the output. \ + This flag may be provided multiple times. Settings are applied \ + iteratively. Colors are limited to one of eight choices: \ + red, blue, green, cyan, magenta, yellow, white and black. \ + Styles are limited to nobold, bold, nointense or intense.\n\n\ + The format of the flag is {type}:{attribute}:{value}. {type} \ + should be one of path, line or match. {attribute} can be fg, bg \ + or style. {value} is either a color (for fg and bg) or a text \ + style. A special format, {type}:none, will clear all color \ + settings for {type}.\n\nFor example, the following command will \ + change the match color to magenta and the background color for \ + line numbers to yellow:\n\n\ + rg --colors 'match:fg:magenta' --colors 'line:bg:yellow' foo." + ); + doc!( + h, + "fixed-strings", + "Treat the pattern as a literal string.", + "Treat the pattern as a literal string instead of a regular \ + expression. When this flag is used, special regular expression \ + meta characters such as (){}*+. do not need to be escaped." + ); + doc!( + h, + "glob", + "Include or exclude files/directories.", + "Include or exclude files/directories for searching that \ + match the given glob. This always overrides any other \ + ignore logic. Multiple glob flags may be used. Globbing \ + rules match .gitignore globs. Precede a glob with a ! \ + to exclude it." + ); + doc!( + h, + "ignore-case", + "Case insensitive search.", + "Case insensitive search. This is overridden by \ + --case-sensitive." + ); + doc!( + h, + "line-number", + "Show line numbers.", + "Show line numbers (1-based). This is enabled by default when \ + searching in a tty." + ); + doc!( + h, + "no-line-number", + "Suppress line numbers.", + "Suppress line numbers. This is enabled by default when NOT \ + searching in a tty." + ); + doc!( + h, + "quiet", + "Do not print anything to stdout.", + "Do not print anything to stdout. If a match is found in a file, \ + stop searching. This is useful when ripgrep is used only for \ + its exit code." + ); + doc!( + h, + "type", + "Only search files matching TYPE.", + "Only search files matching TYPE. Multiple type flags may be \ + provided. Use the --type-list flag to list all available \ + types." + ); + doc!( + h, + "type-not", + "Do not search files matching TYPE.", + "Do not search files matching TYPE. Multiple type-not flags may \ + be provided. Use the --type-list flag to list all available \ + types." + ); + doc!( + h, + "unrestricted", + "Reduce the level of \"smart\" searching.", + "Reduce the level of \"smart\" searching. A single -u \ + won't respect .gitignore (etc.) files. Two -u flags will \ + additionally search hidden files and directories. Three \ + -u flags will additionally search binary files. -uu is \ + roughly equivalent to grep -r and -uuu is roughly \ + equivalent to grep -a -r." + ); + doc!( + h, + "invert-match", + "Invert matching.", + "Invert matching. Show lines that don't match given patterns." + ); + doc!( + h, + "word-regexp", + "Only show matches surrounded by word boundaries.", + "Only show matches surrounded by word boundaries. This is \ + equivalent to putting \\b before and after all of the search \ + patterns." + ); + + doc!(h, "after-context", "Show NUM lines after each match."); + doc!(h, "before-context", "Show NUM lines before each match."); + doc!(h, "context", "Show NUM lines before and after each match."); + doc!( + h, + "column", + "Show column numbers", + "Show column numbers (1-based). This only shows the column \ + numbers for the first match on each line. This does not try \ + to account for Unicode. One byte is equal to one column. This \ + implies --line-number." + ); + doc!( + h, + "context-separator", + "Set the context separator string. [default: --]", + "The string used to separate non-contiguous context lines in the \ + output. Escape sequences like \\x7F or \\t may be used. The \ + default value is --." + ); + doc!( + h, + "debug", + "Show debug messages.", + "Show debug messages. Please use this when filing a bug report." + ); + doc!( + h, + "file", + "Search for patterns from the given file.", + "Search for patterns from the given file, with one pattern per \ + line. When this flag is used or multiple times or in \ + combination with the -e/--regexp flag, then all patterns \ + provided are searched. Empty pattern lines will match all input \ + lines, and the newline is not counted as part of the pattern." + ); + doc!( + h, + "files-with-matches", + "Only show the path of each file with at least one match." + ); + doc!( + h, + "files-without-match", + "Only show the path of each file that contains zero matches." + ); + doc!( + h, + "with-filename", + "Show file name for each match.", + "Prefix each match with the file name that contains it. This is \ + the default when more than one file is searched." + ); + doc!( + h, + "no-filename", + "Never show the file name for a match.", + "Never show the file name for a match. This is the default when \ + one file is searched." + ); + doc!( + h, + "heading", + "Show matches grouped by each file.", + "This shows the file name above clusters of matches from each \ + file instead of showing the file name for every match. This is \ + the default mode at a tty." + ); + doc!( + h, + "no-heading", + "Don't group matches by each file.", + "Don't group matches by each file. If -H/--with-filename is \ + enabled, then file names will be shown for every line matched. \ + This is the default mode when not at a tty." + ); + doc!( + h, + "hidden", + "Search hidden files and directories.", + "Search hidden files and directories. By default, hidden files \ + and directories are skipped." + ); + doc!( + h, + "ignore-file", + "Specify additional ignore files.", + "Specify additional ignore files for filtering file paths. \ + Ignore files should be in the gitignore format and are matched \ + relative to the current working directory. These ignore files \ + have lower precedence than all other ignore files. When \ + specifying multiple ignore files, earlier files have lower \ + precedence than later files." + ); + doc!(h, "follow", "Follow symbolic links."); + doc!( + h, + "max-count", + "Limit the number of matches.", + "Limit the number of matching lines per file searched to NUM." + ); + doc!( + h, + "maxdepth", + "Descend at most NUM directories.", + "Limit the depth of directory traversal to NUM levels beyond \ + the paths given. A value of zero only searches the \ + starting-points themselves.\n\nFor example, \ + 'rg --maxdepth 0 dir/' is a no-op because dir/ will not be \ + descended into. 'rg --maxdepth 1 dir/' will search only the \ + direct children of dir/." + ); + doc!( + h, + "mmap", + "Searching using memory maps when possible.", + "Search using memory maps when possible. This is enabled by \ + default when ripgrep thinks it will be faster. Note that memory \ + map searching doesn't currently support all options, so if an \ + incompatible option (e.g., --context) is given with --mmap, \ + then memory maps will not be used." + ); + doc!( + h, + "no-messages", + "Suppress all error messages.", + "Suppress all error messages. This is equivalent to redirecting \ + stderr to /dev/null." + ); + doc!( + h, + "no-mmap", + "Never use memory maps.", + "Never use memory maps, even when they might be faster." + ); + doc!( + h, + "no-ignore", + "Don't respect ignore files.", + "Don't respect ignore files (.gitignore, .ignore, etc.). This \ + implies --no-ignore-parent and --no-ignore-vcs." + ); + doc!( + h, + "no-ignore-parent", + "Don't respect ignore files in parent directories.", + "Don't respect ignore files (.gitignore, .ignore, etc.) in \ + parent directories." + ); + doc!( + h, + "no-ignore-vcs", + "Don't respect VCS ignore files", + "Don't respect version control ignore files (.gitignore, etc.). \ + This implies --no-ignore-parent. Note that .ignore files will \ + continue to be respected." + ); + doc!( + h, + "null", + "Print NUL byte after file names", + "Whenever a file name is printed, follow it with a NUL byte. \ + This includes printing file names before matches, and when \ + printing a list of matching files such as with --count, \ + --files-with-matches and --files. This option is useful for use \ + with xargs." + ); + doc!( + h, + "path-separator", + "Path separator to use when printing file paths.", + "The path separator to use when printing file paths. This \ + defaults to your platform's path separator, which is / on Unix \ + and \\ on Windows. This flag is intended for overriding the \ + default when the environment demands it (e.g., cygwin). A path \ + separator is limited to a single byte." + ); + doc!(h, "pretty", "Alias for --color always --heading -n."); + doc!( + h, + "replace", + "Replace matches with string given.", + "Replace every match with the string given when printing \ + results. Neither this flag nor any other flag will modify your \ + files.\n\nCapture group indices (e.g., $5) and names \ + (e.g., $foo) are supported in the replacement string.\n\n\ + Note that the replacement by default replaces each match, and \ + NOT the entire line. To replace the entire line, you should \ + match the entire line." + ); + doc!( + h, + "case-sensitive", + "Search case sensitively.", + "Search case sensitively. This overrides -i/--ignore-case and \ + -S/--smart-case." + ); + doc!( + h, + "smart-case", + "Smart case search.", + "Searches case insensitively if the pattern is all lowercase. \ + Search case sensitively otherwise. This is overridden by \ + either -s/--case-sensitive or -i/--ignore-case." + ); + doc!( + h, + "sort-files", + "Sort results by file path. Implies --threads=1.", + "Sort results by file path. Note that this currently \ + disables all parallelism and runs search in a single thread." + ); + doc!( + h, + "threads", + "The approximate number of threads to use.", + "The approximate number of threads to use. A value of 0 (which \ + is the default) causes ripgrep to choose the thread count \ + using heuristics." + ); + doc!( + h, + "vimgrep", + "Show results in vim compatible format.", + "Show results with every match on its own line, including \ + line numbers and column numbers. With this option, a line with \ + more than one match will be printed more than once." + ); + + doc!( + h, + "type-add", + "Add a new glob for a file type.", + "Add a new glob for a particular file type. Only one glob can be \ + added at a time. Multiple --type-add flags can be provided. \ + Unless --type-clear is used, globs are added to any existing \ + globs defined inside of ripgrep.\n\nNote that this MUST be \ + passed to every invocation of ripgrep. Type settings are NOT \ + persisted.\n\nExample: \ + rg --type-add 'foo:*.foo' -tfoo PATTERN.\n\n\ + --type-add can also be used to include rules from other types \ + with the special include directive. The include directive \ + permits specifying one or more other type names (separated by a \ + comma) that have been defined and its rules will automatically \ + be imported into the type specified. For example, to create a \ + type called src that matches C++, Python and Markdown files, one \ + can use:\n\n\ + --type-add 'src:include:cpp,py,md'\n\n\ + Additional glob rules can still be added to the src type by \ + using the --type-add flag again:\n\n\ + --type-add 'src:include:cpp,py,md' --type-add 'src:*.foo'\n\n\ + Note that type names must consist only of Unicode letters or \ + numbers. Punctuation characters are not allowed." + ); + doc!( + h, + "type-clear", + "Clear globs for given file type.", + "Clear the file type globs previously defined for TYPE. This \ + only clears the default type definitions that are found inside \ + of ripgrep.\n\nNote that this MUST be passed to every \ + invocation of ripgrep. Type settings are NOT persisted." + ); + + h + }; +} + +fn validate_number(s: &str) -> Result<(), String> { + s.parse::<usize>() + .map(|_| ()) + .map_err(|err| err.to_string()) +} + +criterion_group!( + benches, + build_rg_with_short_help, + build_rg_with_long_help, + write_rg_short_help, + write_rg_long_help, + parse_rg, + parse_rg_with_complex, + parse_rg_with_lots +); +criterion_main!(benches); diff --git a/third_party/rust/clap/benches/06_rustup.rs b/third_party/rust/clap/benches/06_rustup.rs new file mode 100644 index 0000000000..8d9c406e40 --- /dev/null +++ b/third_party/rust/clap/benches/06_rustup.rs @@ -0,0 +1,412 @@ +// Used to simulate a fairly large number of subcommands +// +// CLI used is from rustup 408ed84f0e50511ed44a405dd91365e5da588790 + +use clap::{AppSettings, Arg, ArgGroup, Command}; +use criterion::{criterion_group, criterion_main, Criterion}; + +pub fn build_rustup(c: &mut Criterion) { + c.bench_function("build_rustup", |b| b.iter(build_cli)); +} + +pub fn parse_rustup(c: &mut Criterion) { + c.bench_function("parse_rustup", |b| { + b.iter(|| build_cli().get_matches_from(vec![""])) + }); +} + +pub fn parse_rustup_with_sc(c: &mut Criterion) { + c.bench_function("parse_rustup_with_sc", |b| { + b.iter(|| build_cli().get_matches_from(vec!["rustup override add stable"])) + }); +} + +fn build_cli() -> Command<'static> { + Command::new("rustup") + .version("0.9.0") // Simulating + .about("The Rust toolchain installer") + .after_help(RUSTUP_HELP) + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .arg( + Arg::new("verbose") + .help("Enable verbose output") + .short('v') + .long("verbose"), + ) + .subcommand( + Command::new("show") + .about("Show the active and installed toolchains") + .after_help(SHOW_HELP), + ) + .subcommand( + Command::new("install") + .about("Update Rust toolchains") + .after_help(TOOLCHAIN_INSTALL_HELP) + .hide(true) // synonym for 'toolchain install' + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + Command::new("update") + .about("Update Rust toolchains") + .after_help(UPDATE_HELP) + .arg(Arg::new("toolchain").required(true)) + .arg( + Arg::new("no-self-update") + .help("Don't perform self update when running the `rustup` command") + .long("no-self-update") + .hide(true), + ), + ) + .subcommand( + Command::new("default") + .about("Set the default toolchain") + .after_help(DEFAULT_HELP) + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + Command::new("toolchain") + .about("Modify or query the installed toolchains") + .after_help(TOOLCHAIN_HELP) + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand(Command::new("list").about("List installed toolchains")) + .subcommand( + Command::new("install") + .about("Install or update a given toolchain") + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + Command::new("uninstall") + .about("Uninstall a toolchain") + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + Command::new("link") + .about("Create a custom toolchain by symlinking to a directory") + .arg(Arg::new("toolchain").required(true)) + .arg(Arg::new("path").required(true)), + ) + .subcommand( + Command::new("update") + .hide(true) // synonym for 'install' + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + Command::new("add") + .hide(true) // synonym for 'install' + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + Command::new("remove") + .hide(true) // synonym for 'uninstall' + .arg(Arg::new("toolchain").required(true)), + ), + ) + .subcommand( + Command::new("target") + .about("Modify a toolchain's supported targets") + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + Command::new("list") + .about("List installed and available targets") + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ) + .subcommand( + Command::new("add") + .about("Add a target to a Rust toolchain") + .arg(Arg::new("target").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ) + .subcommand( + Command::new("remove") + .about("Remove a target from a Rust toolchain") + .arg(Arg::new("target").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ) + .subcommand( + Command::new("install") + .hide(true) // synonym for 'add' + .arg(Arg::new("target").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ) + .subcommand( + Command::new("uninstall") + .hide(true) // synonym for 'remove' + .arg(Arg::new("target").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ), + ) + .subcommand( + Command::new("component") + .about("Modify a toolchain's installed components") + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + Command::new("list") + .about("List installed and available components") + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ) + .subcommand( + Command::new("add") + .about("Add a component to a Rust toolchain") + .arg(Arg::new("component").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)) + .arg(Arg::new("target").long("target").takes_value(true)), + ) + .subcommand( + Command::new("remove") + .about("Remove a component from a Rust toolchain") + .arg(Arg::new("component").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)) + .arg(Arg::new("target").long("target").takes_value(true)), + ), + ) + .subcommand( + Command::new("override") + .about("Modify directory toolchain overrides") + .after_help(OVERRIDE_HELP) + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand(Command::new("list").about("List directory toolchain overrides")) + .subcommand( + Command::new("set") + .about("Set the override toolchain for a directory") + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + Command::new("unset") + .about("Remove the override toolchain for a directory") + .after_help(OVERRIDE_UNSET_HELP) + .arg( + Arg::new("path") + .long("path") + .takes_value(true) + .help("Path to the directory"), + ) + .arg( + Arg::new("nonexistent") + .long("nonexistent") + .help("Remove override toolchain for all nonexistent directories"), + ), + ) + .subcommand( + Command::new("add") + .hide(true) // synonym for 'set' + .arg(Arg::new("toolchain").required(true)), + ) + .subcommand( + Command::new("remove") + .hide(true) // synonym for 'unset' + .about("Remove the override toolchain for a directory") + .arg(Arg::new("path").long("path").takes_value(true)) + .arg( + Arg::new("nonexistent") + .long("nonexistent") + .help("Remove override toolchain for all nonexistent directories"), + ), + ), + ) + .subcommand( + Command::new("run") + .about("Run a command with an environment configured for a given toolchain") + .after_help(RUN_HELP) + .trailing_var_arg(true) + .arg(Arg::new("toolchain").required(true)) + .arg( + Arg::new("command") + .required(true) + .takes_value(true) + .multiple_values(true) + .multiple_occurrences(true), + ), + ) + .subcommand( + Command::new("which") + .about("Display which binary will be run for a given command") + .arg(Arg::new("command").required(true)), + ) + .subcommand( + Command::new("doc") + .about("Open the documentation for the current toolchain") + .after_help(DOC_HELP) + .arg( + Arg::new("book") + .long("book") + .help("The Rust Programming Language book"), + ) + .arg( + Arg::new("std") + .long("std") + .help("Standard library API documentation"), + ) + .group(ArgGroup::new("page").args(&["book", "std"])), + ) + .subcommand( + Command::new("man") + .about("View the man page for a given command") + .arg(Arg::new("command").required(true)) + .arg(Arg::new("toolchain").long("toolchain").takes_value(true)), + ) + .subcommand( + Command::new("self") + .about("Modify the rustup installation") + .setting(AppSettings::DeriveDisplayOrder) + .subcommand(Command::new("update").about("Download and install updates to rustup")) + .subcommand( + Command::new("uninstall") + .about("Uninstall rustup.") + .arg(Arg::new("no-prompt").short('y')), + ) + .subcommand( + Command::new("upgrade-data").about("Upgrade the internal data format."), + ), + ) + .subcommand( + Command::new("telemetry") + .about("rustup telemetry commands") + .hide(true) + .setting(AppSettings::DeriveDisplayOrder) + .subcommand(Command::new("enable").about("Enable rustup telemetry")) + .subcommand(Command::new("disable").about("Disable rustup telemetry")) + .subcommand(Command::new("analyze").about("Analyze stored telemetry")), + ) + .subcommand( + Command::new("set") + .about("Alter rustup settings") + .subcommand( + Command::new("default-host") + .about("The triple used to identify toolchains when not specified") + .arg(Arg::new("host_triple").required(true)), + ), + ) +} + +static RUSTUP_HELP: &str = r" +rustup installs The Rust Programming Language from the official +release channels, enabling you to easily switch between stable, beta, +and nightly compilers and keep them updated. It makes cross-compiling +simpler with binary builds of the standard library for common platforms. + +If you are new to Rust consider running `rustup doc --book` +to learn Rust."; + +static SHOW_HELP: &str = r" +Shows the name of the active toolchain and the version of `rustc`. + +If the active toolchain has installed support for additional +compilation targets, then they are listed as well. + +If there are multiple toolchains installed then all installed +toolchains are listed as well."; + +static UPDATE_HELP: &str = r" +With no toolchain specified, the `update` command updates each of the +installed toolchains from the official release channels, then updates +rustup itself. + +If given a toolchain argument then `update` updates that toolchain, +the same as `rustup toolchain install`. + +'toolchain' specifies a toolchain name, such as 'stable', 'nightly', +or '1.8.0'. For more information see `rustup help toolchain`."; + +static TOOLCHAIN_INSTALL_HELP: &str = r" +Installs a specific rust toolchain. + +The 'install' command is an alias for 'rustup update <toolchain>'. + +'toolchain' specifies a toolchain name, such as 'stable', 'nightly', +or '1.8.0'. For more information see `rustup help toolchain`."; + +static DEFAULT_HELP: &str = r" +Sets the default toolchain to the one specified. If the toolchain is +not already installed then it is installed first."; + +static TOOLCHAIN_HELP: &str = r" +Many `rustup` commands deal with *toolchains*, a single installation +of the Rust compiler. `rustup` supports multiple types of +toolchains. The most basic track the official release channels: +'stable', 'beta' and 'nightly'; but `rustup` can also install +toolchains from the official archives, for alternate host platforms, +and from local builds. + +Standard release channel toolchain names have the following form: + + <channel>[-<date>][-<host>] + + <channel> = stable|beta|nightly|<version> + <date> = YYYY-MM-DD + <host> = <target-triple> + +'channel' is either a named release channel or an explicit version +number, such as '1.8.0'. Channel names can be optionally appended with +an archive date, as in 'nightly-2014-12-18', in which case the +toolchain is downloaded from the archive for that date. + +Finally, the host may be specified as a target triple. This is most +useful for installing a 32-bit compiler on a 64-bit platform, or for +installing the [MSVC-based toolchain] on Windows. For example: + + rustup toolchain install stable-x86_64-pc-windows-msvc + +For convenience, elements of the target triple that are omitted will be +inferred, so the above could be written: + + $ rustup default stable-msvc + +Toolchain names that don't name a channel instead can be used to name +custom toolchains with the `rustup toolchain link` command."; + +static OVERRIDE_HELP: &str = r" +Overrides configure rustup to use a specific toolchain when +running in a specific directory. + +Directories can be assigned their own Rust toolchain with +`rustup override`. When a directory has an override then +any time `rustc` or `cargo` is run inside that directory, +or one of its child directories, the override toolchain +will be invoked. + +To pin to a specific nightly: + + rustup override set nightly-2014-12-18 + +Or a specific stable release: + + rustup override set 1.0.0 + +To see the active toolchain use `rustup show`. To remove the override +and use the default toolchain again, `rustup override unset`."; + +static OVERRIDE_UNSET_HELP: &str = r" +If `--path` argument is present, removes the override toolchain for +the specified directory. If `--nonexistent` argument is present, removes +the override toolchain for all nonexistent directories. Otherwise, +removes the override toolchain for the current directory."; + +static RUN_HELP: &str = r" +Configures an environment to use the given toolchain and then runs +the specified program. The command may be any program, not just +rustc or cargo. This can be used for testing arbitrary toolchains +without setting an override. + +Commands explicitly proxied by `rustup` (such as `rustc` and `cargo`) +also have a shorthand for this available. The toolchain can be set by +using `+toolchain` as the first argument. These are equivalent: + + cargo +nightly build + + rustup run nightly cargo build"; + +static DOC_HELP: &str = r" +Opens the documentation for the currently active toolchain with the +default browser. + +By default, it opens the documentation index. Use the various flags to +open specific pieces of documentation."; + +criterion_group!(benches, build_rustup, parse_rustup, parse_rustup_with_sc); + +criterion_main!(benches); diff --git a/third_party/rust/clap/examples/README.md b/third_party/rust/clap/examples/README.md new file mode 100644 index 0000000000..42ba88991a --- /dev/null +++ b/third_party/rust/clap/examples/README.md @@ -0,0 +1,40 @@ +# Examples + +- Basic demo: [derive](demo.md) +- Typed arguments: [derive](typed-derive.md) + - Topics: + - Custom `parse()` +- Custom cargo command: [builder](cargo-example.md), [derive](cargo-example-derive.md) + - Topics: + - Subcommands + - Cargo plugins +- git-like interface: [builder](git.md), [derive](git-derive.md) + - Topics: + - Subcommands + - External subcommands + - Optional subcommands + - Default subcommands +- pacman-like interface: [builder](pacman.md) + - Topics: + - Flag subcommands + - Conflicting arguments +- Escaped positionals with `--`: [builder](escaped-positional.md), [derive](escaped-positional-derive.md) +- Multi-call + - busybox: [builder](multicall-busybox.md) + - Topics: + - Subcommands + - hostname: [builder](multicall-hostname.md) + - Topics: + - Subcommands +- repl: [builder](repl.rs) + - Topics: + - Read-Eval-Print Loops / Custom command lines + +## Contributing + +New examples: +- Building: They must be added to [Cargo.toml](../../Cargo.toml) with the appropriate `required-features`. +- Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax +- Link the `.md` file from here + +See also the general [CONTRIBUTING](../CONTRIBUTING.md). diff --git a/third_party/rust/clap/examples/cargo-example-derive.md b/third_party/rust/clap/examples/cargo-example-derive.md new file mode 100644 index 0000000000..994c6d4d80 --- /dev/null +++ b/third_party/rust/clap/examples/cargo-example-derive.md @@ -0,0 +1,45 @@ +*Jump to [source](cargo-example-derive.rs)* + +For more on creating a custom subcommand, see [the cargo +book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands). +The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in +mimicking cargo's interface. + +The help looks like: +```console +$ cargo-example-derive --help +cargo + +USAGE: + cargo <SUBCOMMAND> + +OPTIONS: + -h, --help Print help information + +SUBCOMMANDS: + example-derive A simple to use, efficient, and full-featured Command Line Argument Parser + help Print this message or the help of the given subcommand(s) + +$ cargo-example-derive example-derive --help +cargo-example-derive [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + cargo example-derive [OPTIONS] + +OPTIONS: + -h, --help Print help information + --manifest-path <MANIFEST_PATH> + -V, --version Print version information + +``` + +Then to directly invoke the command, run: +```console +$ cargo-example-derive example-derive +None + +$ cargo-example-derive example-derive --manifest-path Cargo.toml +Some("Cargo.toml") + +``` diff --git a/third_party/rust/clap/examples/cargo-example-derive.rs b/third_party/rust/clap/examples/cargo-example-derive.rs new file mode 100644 index 0000000000..1ee0a02551 --- /dev/null +++ b/third_party/rust/clap/examples/cargo-example-derive.rs @@ -0,0 +1,22 @@ +// Note: this requires the `derive` feature + +use clap::Parser; + +#[derive(Parser)] +#[clap(name = "cargo")] +#[clap(bin_name = "cargo")] +enum Cargo { + ExampleDerive(ExampleDerive), +} + +#[derive(clap::Args)] +#[clap(author, version, about, long_about = None)] +struct ExampleDerive { + #[clap(long, parse(from_os_str))] + manifest_path: Option<std::path::PathBuf>, +} + +fn main() { + let Cargo::ExampleDerive(args) = Cargo::parse(); + println!("{:?}", args.manifest_path); +} diff --git a/third_party/rust/clap/examples/cargo-example.md b/third_party/rust/clap/examples/cargo-example.md new file mode 100644 index 0000000000..9279cc4925 --- /dev/null +++ b/third_party/rust/clap/examples/cargo-example.md @@ -0,0 +1,45 @@ +*Jump to [source](cargo-example.rs)* + +For more on creating a custom subcommand, see [the cargo +book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands). +The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in +mimicking cargo's interface. + +The help looks like: +```console +$ cargo-example --help +cargo + +USAGE: + cargo <SUBCOMMAND> + +OPTIONS: + -h, --help Print help information + +SUBCOMMANDS: + example A simple to use, efficient, and full-featured Command Line Argument Parser + help Print this message or the help of the given subcommand(s) + +$ cargo-example example --help +cargo-example [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + cargo example [OPTIONS] + +OPTIONS: + -h, --help Print help information + --manifest-path <PATH> + -V, --version Print version information + +``` + +Then to directly invoke the command, run: +```console +$ cargo-example example +None + +$ cargo-example example --manifest-path Cargo.toml +Some("Cargo.toml") + +``` diff --git a/third_party/rust/clap/examples/cargo-example.rs b/third_party/rust/clap/examples/cargo-example.rs new file mode 100644 index 0000000000..149bf59918 --- /dev/null +++ b/third_party/rust/clap/examples/cargo-example.rs @@ -0,0 +1,23 @@ +// Note: this requires the `cargo` feature + +fn main() { + let cmd = clap::Command::new("cargo") + .bin_name("cargo") + .subcommand_required(true) + .subcommand( + clap::command!("example").arg( + clap::arg!(--"manifest-path" <PATH>) + .required(false) + .allow_invalid_utf8(true), + ), + ); + let matches = cmd.get_matches(); + let matches = match matches.subcommand() { + Some(("example", matches)) => matches, + _ => unreachable!("clap should ensure we don't get here"), + }; + let manifest_path = matches + .value_of_os("manifest-path") + .map(std::path::PathBuf::from); + println!("{:?}", manifest_path); +} diff --git a/third_party/rust/clap/examples/demo.md b/third_party/rust/clap/examples/demo.md new file mode 100644 index 0000000000..9b0e7e260f --- /dev/null +++ b/third_party/rust/clap/examples/demo.md @@ -0,0 +1,20 @@ +*Jump to [source](demo.rs)* + +**This requires enabling the `derive` feature flag.** + +Used to validate README.md's content +```console +$ demo --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + demo[EXE] [OPTIONS] --name <NAME> + +OPTIONS: + -c, --count <COUNT> Number of times to greet [default: 1] + -h, --help Print help information + -n, --name <NAME> Name of the person to greet + -V, --version Print version information + +``` diff --git a/third_party/rust/clap/examples/demo.rs b/third_party/rust/clap/examples/demo.rs new file mode 100644 index 0000000000..262a81a2c1 --- /dev/null +++ b/third_party/rust/clap/examples/demo.rs @@ -0,0 +1,24 @@ +// Note: this requires the `derive` feature + +use clap::Parser; + +/// Simple program to greet a person +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Args { + /// Name of the person to greet + #[clap(short, long)] + name: String, + + /// Number of times to greet + #[clap(short, long, default_value_t = 1)] + count: u8, +} + +fn main() { + let args = Args::parse(); + + for _ in 0..args.count { + println!("Hello {}!", args.name) + } +} diff --git a/third_party/rust/clap/examples/derive_ref/README.md b/third_party/rust/clap/examples/derive_ref/README.md new file mode 100644 index 0000000000..11001dde85 --- /dev/null +++ b/third_party/rust/clap/examples/derive_ref/README.md @@ -0,0 +1,429 @@ +# Derive Reference + +1. [Overview](#overview) +2. [Attributes](#attributes) + 1. [Terminology](#terminology) + 2. [Command Attributes](#command-attributes) + 3. [Arg Attributes](#arg-attributes) + 4. [Arg Enum Attributes](#arg-enum-attributes) + 5. [Possible Value Attributes](#possible-value-attributes) +3. [Arg Types](#arg-types) +4. [Doc Comments](#doc-comments) +5. [Tips](#tips) +6. [Mixing Builder and Derive APIS](#mixing-builder-and-derive-apis) + +## Overview + +To derive `clap` types, you need to enable the `derive` feature flag. + +See [demo.rs](../demo.rs) and [demo.md](../demo.md) for a brief example. + +Let's start by breaking down the anatomy of the derive attributes: +```rust +use clap::{Parser, Args, Subcommand, ArgEnum}; + +/// Doc comment +#[derive(Parser)] +#[clap(APP ATTRIBUTE)] +struct Cli { + /// Doc comment + #[clap(ARG ATTRIBUTE)] + field: UserType, + + #[clap(arg_enum, ARG ATTRIBUTE...)] + field: EnumValues, + + #[clap(flatten)] + delegate: Struct, + + #[clap(subcommand)] + command: Command, +} + +/// Doc comment +#[derive(Args)] +#[clap(PARENT APP ATTRIBUTE)] +struct Struct { + /// Doc comment + #[clap(ARG ATTRIBUTE)] + field: UserType, +} + +/// Doc comment +#[derive(Subcommand)] +#[clap(PARENT APP ATTRIBUTE)] +enum Command { + /// Doc comment + #[clap(APP ATTRIBUTE)] + Variant1(Struct), + + /// Doc comment + #[clap(APP ATTRIBUTE)] + Variant2 { + /// Doc comment + #[clap(ARG ATTRIBUTE)] + field: UserType, + } +} + +/// Doc comment +#[derive(ArgEnum)] +#[clap(ARG ENUM ATTRIBUTE)] +enum EnumValues { + /// Doc comment + #[clap(POSSIBLE VALUE ATTRIBUTE)] + Variant1, +} + +fn main() { + let cli = Cli::parse(); +} +``` + +- `Parser` parses arguments into a `struct` (arguments) or `enum` (subcommands). +- `Args` allows defining a set of re-usable arguments that get merged into their parent container. +- `Subcommand` defines available subcommands. + - Subcommand arguments can be defined in a struct-variant or automatically flattened with a tuple-variant. +- `ArgEnum` allows parsing a value directly into an `enum`, erroring on unsupported values. + - The derive doesn't work on enums that contain non-unit variants, unless they are skipped + +See also the [tutorial](../tutorial_derive/README.md) and [examples](../README.md). + +## Attributes + +### Terminology + +**Raw attributes** are forwarded directly to the underlying `clap` builder. Any +`Command`, `Arg`, or `PossibleValue` method can be used as an attribute. + +Raw attributes come in two different syntaxes: +```rust +#[clap( + global = true, // name = arg form, neat for one-arg methods + required_if_eq("out", "file") // name(arg1, arg2, ...) form. +)] +``` + +- `method = arg` can only be used for methods which take only one argument. +- `method(arg1, arg2)` can be used with any method. + +As long as `method_name` is not one of the magical methods - it will be +translated into a mere method call. + +**Magic attributes** have post-processing done to them, whether that is +- Providing of defaults +- Special behavior is triggered off of it + +Magic attributes are more constrained in the syntax they support, usually just +`<attr> = <value>` though some use `<attr>(<value>)` instead. See the specific +magic attributes documentation for details. This allows users to access the +raw behavior of an attribute via `<attr>(<value>)` syntax. + +**NOTE:** Some attributes are inferred from [Arg Types](#arg-types) and [Doc +Comments](#doc-comments). Explicit attributes take precedence over inferred +attributes. + +### Command Attributes + +These correspond to a `clap::Command` which is used for both top-level parsers and +when defining subcommands. + +**Magic attributes:** +- `name = <expr>`: `clap::Command::name` + - When not present: [crate `name`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-name-field) (`Parser` container), variant name (`Subcommand` variant) +- `version [= <expr>]`: `clap::Command::version` + - When not present: no version set + - Without `<expr>`: defaults to [crate `version`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field) +- `author [= <expr>]`: `clap::Command::author` + - When not present: no author set + - Without `<expr>`: defaults to [crate `authors`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field) +- `about [= <expr>]`: `clap::Command::about` + - When not present: [Doc comment summary](#doc-comments) + - Without `<expr>`: [crate `description`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-description-field) (`Parser` container) + - **TIP:** When a doc comment is also present, you most likely want to add + `#[clap(long_about = None)]` to clear the doc comment so only `about` + gets shown with both `-h` and `--help`. +- `long_about = <expr>`: `clap::Command::long_about` + - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing +- `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to `about` / `long_about` +- `next_display_order`: `clap::Command::next_display_order` +- `next_help_heading`: `clap::Command::next_help_heading` + - When `flatten`ing `Args`, this is scoped to just the args in this struct and any struct `flatten`ed into it +- `rename_all = <expr>`: Override default field / variant name case conversion for `Command::name` / `Arg::name` + - When not present: `kebab-case` + - Available values: `camelCase`, `kebab-case`, `PascalCase`, `SCREAMING_SNAKE_CASE`, `snake_case`, `lower`, `UPPER`, `verbatim` +- `rename_all_env = <expr>`: Override default field name case conversion for env variables for `clap::Arg::env` + - When not present: `SCREAMING_SNAKE_CASE` + - Available values: `camelCase`, `kebab-case`, `PascalCase`, `SCREAMING_SNAKE_CASE`, `snake_case`, `lower`, `UPPER`, `verbatim` + +And for `Subcommand` variants: +- `skip`: Ignore this variant +- `flatten`: Delegates to the variant for more subcommands (must implement `Subcommand`) +- `subcommand`: Nest subcommands under the current set of subcommands (must implement `Subcommand`) +- `external_subcommand`: `clap::Command::allow_external_subcommand(true)` + - Variant must be either `Variant(Vec<String>)` or `Variant(Vec<OsString>)` + +**Raw attributes:** Any [`Command` method](https://docs.rs/clap/latest/clap/type.Command.html) can also be used as an attribute, see [Terminology](#terminology) for syntax. +- e.g. `#[clap(arg_required_else_help(true))]` would translate to `cmd.arg_required_else_help(true)` + +### Arg Attributes + +These correspond to a `clap::Arg`. + +**Magic attributes**: +- `name = <expr>`: `clap::Arg::new` + - When not present: case-converted field name is used +- `help = <expr>`: `clap::Arg::help` + - When not present: [Doc comment summary](#doc-comments) +- `long_help = <expr>`: `clap::Arg::long_help` + - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing +- `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to `help` / `long_help` +- `short [= <char>]`: `clap::Arg::short` + - When not present: no short set + - Without `<char>`: defaults to first character in the case-converted field name +- `long [= <str>]`: `clap::Arg::long` + - When not present: no long set + - Without `<str>`: defaults to the case-converted field name +- `env [= <str>]`: `clap::Arg::env` (needs `env` feature enabled) + - When not present: no env set + - Without `<str>`: defaults to the case-converted field name +- `flatten`: Delegates to the field for more arguments (must implement `Args`) + - Only `help_heading` can be used with `flatten`. See + [clap-rs/clap#3269](https://github.com/clap-rs/clap/issues/3269) for why + arg attributes are not generally supported. + - **Tip:** Though we do apply a flattened `Args`'s Parent Command Attributes, this + makes reuse harder. Generally prefer putting the cmd attributes on the `Parser` + or on the flattened field. +- `subcommand`: Delegates definition of subcommands to the field (must implement `Subcommand`) + - When `Option<T>`, the subcommand becomes optional +- `from_global`: Read a `clap::Arg::global` argument (raw attribute), regardless of what subcommand you are in +- `parse(<kind> [= <function>])`: `clap::Arg::validator` and `clap::ArgMatches::values_of_t` + - Default: `try_from_str` + - Warning: for `Path` / `OsString`, be sure to use `try_from_os_str` + - See [Arg Types](#arg-types) for more details +- `arg_enum`: Parse the value using the `ArgEnum` trait +- `skip [= <expr>]`: Ignore this field, filling in with `<expr>` + - Without `<expr>`: fills the field with `Default::default()` +- `default_value = <str>`: `clap::Arg::default_value` and `clap::Arg::required(false)` +- `default_value_t [= <expr>]`: `clap::Arg::default_value` and `clap::Arg::required(false)` + - Requires `std::fmt::Display` or `#[clap(arg_enum)]` + - Without `<expr>`, relies on `Default::default()` +- `default_value_os_t [= <expr>]`: `clap::Arg::default_value_os` and `clap::Arg::required(false)` + - Requires `std::convert::Into<OsString>` or `#[clap(arg_enum)]` + - Without `<expr>`, relies on `Default::default()` + +**Raw attributes:** Any [`Arg` method](https://docs.rs/clap/latest/clap/struct.Arg.html) can also be used as an attribute, see [Terminology](#terminology) for syntax. +- e.g. `#[clap(max_values(3))]` would translate to `arg.max_values(3)` + +### Arg Enum Attributes + +- `rename_all = <expr>`: Override default field / variant name case conversion for `PossibleValue::new` + - When not present: `kebab-case` + - Available values: `camelCase`, `kebab-case`, `PascalCase`, `SCREAMING_SNAKE_CASE`, `snake_case`, `lower`, `UPPER`, `verbatim` + +### Possible Value Attributes + +These correspond to a `clap::PossibleValue`. + +**Magic attributes**: +- `name = <expr>`: `clap::PossibleValue::new` + - When not present: case-converted field name is used +- `help = <expr>`: `clap::PossibleValue::help` + - When not present: [Doc comment summary](#doc-comments) + +**Raw attributes:** Any [`PossibleValue` method](https://docs.rs/clap/latest/clap/struct.PossibleValue.html) can also be used as an attribute, see [Terminology](#terminology) for syntax. +- e.g. `#[clap(alias("foo"))]` would translate to `pv.alias("foo")` + +## Arg Types + +`clap` assumes some intent based on the type used: + +| Type | Effect | Implies | +|---------------------|--------------------------------------|------------------------------------------------------------------| +| `bool` | flag | `#[clap(parse(from_flag))]` | +| `Option<T>` | optional argument | `.takes_value(true).required(false)` | +| `Option<Option<T>>` | optional value for optional argument | `.takes_value(true).required(false).min_values(0).max_values(1)` | +| `T` | required argument | `.takes_value(true).required(!has_default)` | +| `Vec<T>` | `0..` occurrences of argument | `.takes_value(true).required(false).multiple_occurrences(true)` | +| `Option<Vec<T>>` | `0..` occurrences of argument | `.takes_value(true).required(false).multiple_occurrences(true)` | + +Notes: +- For custom type behavior, you can override the implied attributes/settings and/or set additional ones + - For example, see [custom-bool](./custom-bool.md) +- `Option<Vec<T>>` will be `None` instead of `vec![]` if no arguments are provided. + - This gives the user some flexibility in designing their argument, like with `min_values(0)` + +You can then support your custom type with `#[clap(parse(<kind> [= <function>]))]`: + +| `<kind>` | Signature | Default `<function>` | +|--------------------------|---------------------------------------|---------------------------------| +| `from_str` | `fn(&str) -> T` | `::std::convert::From::from` | +| `try_from_str` (default) | `fn(&str) -> Result<T, E>` | `::std::str::FromStr::from_str` | +| `from_os_str` | `fn(&OsStr) -> T` | `::std::convert::From::from` | +| `try_from_os_str` | `fn(&OsStr) -> Result<T, OsString>` | (no default function) | +| `from_occurrences` | `fn(u64) -> T` | `value as T` | +| `from_flag` | `fn(bool) -> T` | `::std::convert::From::from` | + +Notes: +- `from_os_str`: + - Implies `arg.takes_value(true).allow_invalid_utf8(true)` +- `try_from_os_str`: + - Implies `arg.takes_value(true).allow_invalid_utf8(true)` +- `from_occurrences`: + - Implies `arg.takes_value(false).multiple_occurrences(true)` + - Reads from `clap::ArgMatches::occurrences_of` rather than a `value_of` function + - Note: operations on values, like `default_value`, are unlikely to do what you want +- `from_flag` + - Implies `arg.takes_value(false)` + - Reads from `clap::ArgMatches::is_present` rather than a `value_of` function + - Note: operations on values, like `default_value`, are unlikely to do what you want + +**Warning:** +- To support non-UTF8 paths, you must use `parse(from_os_str)`, otherwise + `clap` will use `clap::ArgMatches::value_of` with `PathBuf::FromStr`. + +## Doc Comments + +In clap, help messages for the whole binary can be specified +via [`Command::about`] and [`Command::long_about`] while help messages +for individual arguments can be specified via [`Arg::help`] and [`Arg::long_help`]". + +`long_*` variants are used when user calls the program with +`--help` and "short" variants are used with `-h` flag. + +```rust +# use clap::Parser; + +#[derive(Parser)] +#[clap(about = "I am a program and I work, just pass `-h`", long_about = None)] +struct Foo { + #[clap(short, help = "Pass `-h` and you'll see me!")] + bar: String, +} +``` + +For convenience, doc comments can be used instead of raw methods +(this example works exactly like the one above): + +```rust +# use clap::Parser; + +#[derive(Parser)] +/// I am a program and I work, just pass `-h` +struct Foo { + /// Pass `-h` and you'll see me! + bar: String, +} +``` + +**NOTE:** Attributes have priority over doc comments! + +**Top level doc comments always generate `Command::about/long_about` calls!** +If you really want to use the `Command::about/long_about` methods (you likely don't), +use the `about` / `long_about` attributes to override the calls generated from +the doc comment. To clear `long_about`, you can use +`#[clap(long_about = None)]`. + +**TIP:** Set `#![deny(missing_docs)]` to catch missing `--help` documentation at compile time. + +### Pre-processing + +```rust +# use clap::Parser; +#[derive(Parser)] +/// Hi there, I'm Robo! +/// +/// I like beeping, stumbling, eating your electricity, +/// and making records of you singing in a shower. +/// Pay up, or I'll upload it to youtube! +struct Robo { + /// Call my brother SkyNet. + /// + /// I am artificial superintelligence. I won't rest + /// until I'll have destroyed humanity. Enjoy your + /// pathetic existence, you mere mortals. + #[clap(long)] + kill_all_humans: bool, +} +``` + +A doc comment consists of three parts: +- Short summary +- A blank line (whitespace only) +- Detailed description, all the rest + +The summary corresponds with `Command::about` / `Arg::help`. When a blank line is +present, the whole doc comment will be passed to `Command::long_about` / +`Arg::long_help`. Or in other words, a doc may result in just a `Command::about` / +`Arg::help` or `Command::about` / `Arg::help` and `Command::long_about` / +`Arg::long_help` + +In addition, when `verbatim_doc_comment` is not present, `clap` applies some preprocessing, including: + +- Strip leading and trailing whitespace from every line, if present. + +- Strip leading and trailing blank lines, if present. + +- Interpret each group of non-empty lines as a word-wrapped paragraph. + + We replace newlines within paragraphs with spaces to allow the output + to be re-wrapped to the terminal width. + +- Strip any excess blank lines so that there is exactly one per paragraph break. + +- If the first paragraph ends in exactly one period, + remove the trailing period (i.e. strip trailing periods but not trailing ellipses). + +Sometimes you don't want this preprocessing to apply, for example the comment contains +some ASCII art or markdown tables, you would need to preserve LFs along with +blank lines and the leading/trailing whitespace. When you pass use the +`verbatim_doc_comment` magic attribute, you preserve +them. + +**Note:** Keep in mind that `verbatim_doc_comment` will *still* +- Remove one leading space from each line, even if this attribute is present, + to allow for a space between `///` and the content. +- Remove leading and trailing blank lines + +## Tips + +- To get access to a `Command` call `CommandFactory::command` (implemented when deriving `Parser`) +- Proactively check for bad `Command` configurations by calling `Command::debug_assert` in a test ([example](../tutorial_derive/05_01_assert.rs)) + +## Mixing Builder and Derive APIs + +The builder and derive APIs do not live in isolation. They can work together, which is especially helpful if some arguments can be specified at compile-time while others must be specified at runtime. + +### Using derived arguments in a builder application + +*[Jump to source](augment_args.rs)* + +When using the derive API, you can `#[clap(flatten)]` a struct deriving `Args` into a struct deriving `Args` or `Parser`. This example shows how you can augment a `Command` instance created using the builder API with `Args` created using the derive API. + +It uses the `Args::augment_args` method to add the arguments to the `Command` instance. + +Crates such as [clap-verbosity-flag](https://github.com/rust-cli/clap-verbosity-flag) provide structs that implement `Args` or `Parser`. Without the technique shown in this example, it would not be possible to use such crates with the builder API. `augment_args` to the rescue! + +### Using derived subcommands in a builder application + +*[Jump to source](augment_subcommands.rs)* + +When using the derive API, you can use `#[clap(subcommand)]` inside the struct to add subcommands. The type of the field is usually an enum that derived `Parser`. However, you can also add the subcommands in that enum to a `Command` instance created with the builder API. + +It uses the `Subcommand::augment_subcommands` method to add the subcommands to the `Command` instance. + +### Adding hand-implemented subcommands to a derived application + +*[Jump to source](hand_subcommand.rs)* + +When using the derive API, you can use `#[clap(subcommand)]` inside the struct to add subcommands. The type of the field is usually an enum that derived `Parser`. However, you can also implement the `Subcommand` trait manually on this enum (or any other type) and it can still be used inside the struct created with the derive API. The implementation of the `Subcommand` trait will use the builder API to add the subcommands to the `Command` instance created behind the scenes for you by the derive API. + +Notice how in the previous example we used `augment_subcommands` on an enum that derived `Parser`, whereas now we implement `augment_subcommands` ourselves, but the derive API calls it automatically since we used the `#[clap(subcommand)]` attribute. + +### Flattening hand-implemented args into a derived application + +*[Jump to source](flatten_hand_args.rs)* + +When using the derive API, you can use `#[clap(flatten)]` inside the struct to add arguments as if they were added directly to the containing struct. The type of the field is usually an struct that derived `Args`. However, you can also implement the `Args` trait manually on this struct (or any other type) and it can still be used inside the struct created with the derive API. The implementation of the `Args` trait will use the builder API to add the arguments to the `Command` instance created behind the scenes for you by the derive API. + +Notice how in the example 1 we used `augment_args` on the struct that derived `Parser`, whereas now we implement `augment_args` ourselves, but the derive API calls it automatically since we used the `#[clap(flatten)]` attribute. diff --git a/third_party/rust/clap/examples/derive_ref/augment_args.rs b/third_party/rust/clap/examples/derive_ref/augment_args.rs new file mode 100644 index 0000000000..59765ad61f --- /dev/null +++ b/third_party/rust/clap/examples/derive_ref/augment_args.rs @@ -0,0 +1,27 @@ +use clap::{arg, Args as _, Command, FromArgMatches as _, Parser}; + +#[derive(Parser, Debug)] +struct DerivedArgs { + #[clap(short, long)] + derived: bool, +} + +fn main() { + let cli = Command::new("CLI").arg(arg!(-b - -built)); + // Augment built args with derived args + let cli = DerivedArgs::augment_args(cli); + + let matches = cli.get_matches(); + println!("Value of built: {:?}", matches.is_present("built")); + println!( + "Value of derived via ArgMatches: {:?}", + matches.is_present("derived") + ); + + // Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches. + // This is the main benefit of using derived arguments. + let derived_matches = DerivedArgs::from_arg_matches(&matches) + .map_err(|err| err.exit()) + .unwrap(); + println!("Value of derived: {:#?}", derived_matches); +} diff --git a/third_party/rust/clap/examples/derive_ref/augment_subcommands.rs b/third_party/rust/clap/examples/derive_ref/augment_subcommands.rs new file mode 100644 index 0000000000..299c7f8cf6 --- /dev/null +++ b/third_party/rust/clap/examples/derive_ref/augment_subcommands.rs @@ -0,0 +1,21 @@ +use clap::{Command, FromArgMatches as _, Parser, Subcommand as _}; + +#[derive(Parser, Debug)] +enum Subcommands { + Derived { + #[clap(short, long)] + derived_flag: bool, + }, +} + +fn main() { + let cli = Command::new("Built CLI"); + // Augment with derived subcommands + let cli = Subcommands::augment_subcommands(cli); + + let matches = cli.get_matches(); + let derived_subcommands = Subcommands::from_arg_matches(&matches) + .map_err(|err| err.exit()) + .unwrap(); + println!("Derived subcommands: {:#?}", derived_subcommands); +} diff --git a/third_party/rust/clap/examples/derive_ref/custom-bool.md b/third_party/rust/clap/examples/derive_ref/custom-bool.md new file mode 100644 index 0000000000..2769f20e8f --- /dev/null +++ b/third_party/rust/clap/examples/derive_ref/custom-bool.md @@ -0,0 +1,47 @@ +*Jump to [source](custom-bool.rs)* + +Example of overriding the magic `bool` behavior + +```console +$ custom-bool --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + custom-bool[EXE] [OPTIONS] --foo <FOO> <BOOM> + +ARGS: + <BOOM> + +OPTIONS: + --bar <BAR> [default: false] + --foo <FOO> + -h, --help Print help information + -V, --version Print version information + +$ custom-bool +? failed +error: The following required arguments were not provided: + --foo <FOO> + <BOOM> + +USAGE: + custom-bool[EXE] [OPTIONS] --foo <FOO> <BOOM> + +For more information try --help + +$ custom-bool --foo true false +[examples/derive_ref/custom-bool.rs:31] opt = Opt { + foo: true, + bar: false, + boom: false, +} + +$ custom-bool --foo true --bar true false +[examples/derive_ref/custom-bool.rs:31] opt = Opt { + foo: true, + bar: true, + boom: false, +} + +``` diff --git a/third_party/rust/clap/examples/derive_ref/custom-bool.rs b/third_party/rust/clap/examples/derive_ref/custom-bool.rs new file mode 100644 index 0000000000..10f93f40ac --- /dev/null +++ b/third_party/rust/clap/examples/derive_ref/custom-bool.rs @@ -0,0 +1,32 @@ +use clap::Parser; + +#[derive(Parser, Debug, PartialEq)] +#[clap(author, version, about, long_about = None)] +struct Opt { + // Default parser for `try_from_str` is FromStr::from_str. + // `impl FromStr for bool` parses `true` or `false` so this + // works as expected. + #[clap(long, parse(try_from_str))] + foo: bool, + + // Of course, this could be done with an explicit parser function. + #[clap(long, parse(try_from_str = true_or_false), default_value_t)] + bar: bool, + + // `bool` can be positional only with explicit `parse(...)` annotation + #[clap(parse(try_from_str))] + boom: bool, +} + +fn true_or_false(s: &str) -> Result<bool, &'static str> { + match s { + "true" => Ok(true), + "false" => Ok(false), + _ => Err("expected `true` or `false`"), + } +} + +fn main() { + let opt = Opt::parse(); + dbg!(opt); +} diff --git a/third_party/rust/clap/examples/derive_ref/flatten_hand_args.rs b/third_party/rust/clap/examples/derive_ref/flatten_hand_args.rs new file mode 100644 index 0000000000..2969457e18 --- /dev/null +++ b/third_party/rust/clap/examples/derive_ref/flatten_hand_args.rs @@ -0,0 +1,53 @@ +use clap::error::Error; +use clap::{Arg, ArgMatches, Args, Command, FromArgMatches, Parser}; + +#[derive(Debug)] +struct CliArgs { + foo: bool, + bar: bool, + quuz: Option<String>, +} + +impl FromArgMatches for CliArgs { + fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> { + Ok(Self { + foo: matches.is_present("foo"), + bar: matches.is_present("bar"), + quuz: matches.value_of("quuz").map(|quuz| quuz.to_owned()), + }) + } + fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> { + self.foo |= matches.is_present("foo"); + self.bar |= matches.is_present("bar"); + if let Some(quuz) = matches.value_of("quuz") { + self.quuz = Some(quuz.to_owned()); + } + Ok(()) + } +} + +impl Args for CliArgs { + fn augment_args(cmd: Command<'_>) -> Command<'_> { + cmd.arg(Arg::new("foo").short('f').long("foo")) + .arg(Arg::new("bar").short('b').long("bar")) + .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true)) + } + fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> { + cmd.arg(Arg::new("foo").short('f').long("foo")) + .arg(Arg::new("bar").short('b').long("bar")) + .arg(Arg::new("quuz").short('q').long("quuz").takes_value(true)) + } +} + +#[derive(Parser, Debug)] +struct Cli { + #[clap(short, long)] + top_level: bool, + #[clap(flatten)] + more_args: CliArgs, +} + +fn main() { + let args = Cli::parse(); + println!("{:#?}", args); +} diff --git a/third_party/rust/clap/examples/derive_ref/hand_subcommand.rs b/third_party/rust/clap/examples/derive_ref/hand_subcommand.rs new file mode 100644 index 0000000000..5afd941327 --- /dev/null +++ b/third_party/rust/clap/examples/derive_ref/hand_subcommand.rs @@ -0,0 +1,79 @@ +use clap::error::{Error, ErrorKind}; +use clap::{ArgMatches, Args as _, Command, FromArgMatches, Parser, Subcommand}; + +#[derive(Parser, Debug)] +struct AddArgs { + name: Vec<String>, +} +#[derive(Parser, Debug)] +struct RemoveArgs { + #[clap(short, long)] + force: bool, + name: Vec<String>, +} + +#[derive(Debug)] +enum CliSub { + Add(AddArgs), + Remove(RemoveArgs), +} + +impl FromArgMatches for CliSub { + fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> { + match matches.subcommand() { + Some(("add", args)) => Ok(Self::Add(AddArgs::from_arg_matches(args)?)), + Some(("remove", args)) => Ok(Self::Remove(RemoveArgs::from_arg_matches(args)?)), + Some((_, _)) => Err(Error::raw( + ErrorKind::UnrecognizedSubcommand, + "Valid subcommands are `add` and `remove`", + )), + None => Err(Error::raw( + ErrorKind::MissingSubcommand, + "Valid subcommands are `add` and `remove`", + )), + } + } + fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> { + match matches.subcommand() { + Some(("add", args)) => *self = Self::Add(AddArgs::from_arg_matches(args)?), + Some(("remove", args)) => *self = Self::Remove(RemoveArgs::from_arg_matches(args)?), + Some((_, _)) => { + return Err(Error::raw( + ErrorKind::UnrecognizedSubcommand, + "Valid subcommands are `add` and `remove`", + )) + } + None => (), + }; + Ok(()) + } +} + +impl Subcommand for CliSub { + fn augment_subcommands(cmd: Command<'_>) -> Command<'_> { + cmd.subcommand(AddArgs::augment_args(Command::new("add"))) + .subcommand(RemoveArgs::augment_args(Command::new("remove"))) + .subcommand_required(true) + } + fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_> { + cmd.subcommand(AddArgs::augment_args(Command::new("add"))) + .subcommand(RemoveArgs::augment_args(Command::new("remove"))) + .subcommand_required(true) + } + fn has_subcommand(name: &str) -> bool { + matches!(name, "add" | "remove") + } +} + +#[derive(Parser, Debug)] +struct Cli { + #[clap(short, long)] + top_level: bool, + #[clap(subcommand)] + subcommand: CliSub, +} + +fn main() { + let args = Cli::parse(); + println!("{:#?}", args); +} diff --git a/third_party/rust/clap/examples/derive_ref/interop_tests.md b/third_party/rust/clap/examples/derive_ref/interop_tests.md new file mode 100644 index 0000000000..746fe1878d --- /dev/null +++ b/third_party/rust/clap/examples/derive_ref/interop_tests.md @@ -0,0 +1,256 @@ +Following are tests for the interop examples in this directory. + +## Augment Args + +```console +$ interop_augment_args +Value of built: false +Value of derived via ArgMatches: false +Value of derived: DerivedArgs { + derived: false, +} + +``` + +```console +$ interop_augment_args -b --derived +Value of built: true +Value of derived via ArgMatches: true +Value of derived: DerivedArgs { + derived: true, +} + +``` + +```console +$ interop_augment_args -d --built +Value of built: true +Value of derived via ArgMatches: true +Value of derived: DerivedArgs { + derived: true, +} + +``` + +```console +$ interop_augment_args --unknown +? failed +error: Found argument '--unknown' which wasn't expected, or isn't valid in this context + + If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown` + +USAGE: + interop_augment_args[EXE] [OPTIONS] + +For more information try --help + +``` + +## Augment Subcommands + +```console +$ interop_augment_subcommands +? failed +error: A subcommand is required but one was not provided. +``` + +```console +$ interop_augment_subcommands derived +Derived subcommands: Derived { + derived_flag: false, +} + +``` + +```console +$ interop_augment_subcommands derived --derived-flag +Derived subcommands: Derived { + derived_flag: true, +} + +``` + +```console +$ interop_augment_subcommands derived --unknown +? failed +error: Found argument '--unknown' which wasn't expected, or isn't valid in this context + + If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown` + +USAGE: + interop_augment_subcommands[EXE] derived [OPTIONS] + +For more information try --help + +``` + +```console +$ interop_augment_subcommands unknown +? failed +error: Found argument 'unknown' which wasn't expected, or isn't valid in this context + +USAGE: + interop_augment_subcommands[EXE] [SUBCOMMAND] + +For more information try --help + +``` + +## Hand-Implemented Subcommand + +```console +$ interop_hand_subcommand +? failed +error: 'interop_hand_subcommand[EXE]' requires a subcommand but one was not provided + +USAGE: + interop_hand_subcommand[EXE] [OPTIONS] <SUBCOMMAND> + +For more information try --help + +``` + +```console +$ interop_hand_subcommand add +Cli { + top_level: false, + subcommand: Add( + AddArgs { + name: [], + }, + ), +} + +``` + +```console +$ interop_hand_subcommand add a b c +Cli { + top_level: false, + subcommand: Add( + AddArgs { + name: [ + "a", + "b", + "c", + ], + }, + ), +} + +``` + +```console +$ interop_hand_subcommand add --unknown +? failed +error: Found argument '--unknown' which wasn't expected, or isn't valid in this context + + If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown` + +USAGE: + interop_hand_subcommand[EXE] add [NAME]... + +For more information try --help + +``` + +```console +$ interop_hand_subcommand remove +Cli { + top_level: false, + subcommand: Remove( + RemoveArgs { + force: false, + name: [], + }, + ), +} + +``` + +```console +$ interop_hand_subcommand remove --force a b c +Cli { + top_level: false, + subcommand: Remove( + RemoveArgs { + force: true, + name: [ + "a", + "b", + "c", + ], + }, + ), +} + +``` + +```console +$ interop_hand_subcommand unknown +? failed +error: Found argument 'unknown' which wasn't expected, or isn't valid in this context + +USAGE: + interop_hand_subcommand[EXE] [OPTIONS] <SUBCOMMAND> + +For more information try --help + +``` + +## Flatten Hand-Implemented Args + +```console +$ interop_flatten_hand_args +Cli { + top_level: false, + more_args: CliArgs { + foo: false, + bar: false, + quuz: None, + }, +} + +``` + +```console +$ interop_flatten_hand_args -f --bar +Cli { + top_level: false, + more_args: CliArgs { + foo: true, + bar: true, + quuz: None, + }, +} + +``` + +```console +$ interop_flatten_hand_args --quuz abc +Cli { + top_level: false, + more_args: CliArgs { + foo: false, + bar: false, + quuz: Some( + "abc", + ), + }, +} + +``` + +```console +$ interop_flatten_hand_args --unknown +? failed +error: Found argument '--unknown' which wasn't expected, or isn't valid in this context + + If you tried to supply `--unknown` as a value rather than a flag, use `-- --unknown` + +USAGE: + interop_flatten_hand_args[EXE] [OPTIONS] + +For more information try --help + +``` diff --git a/third_party/rust/clap/examples/escaped-positional-derive.md b/third_party/rust/clap/examples/escaped-positional-derive.md new file mode 100644 index 0000000000..3b5f8fe565 --- /dev/null +++ b/third_party/rust/clap/examples/escaped-positional-derive.md @@ -0,0 +1,65 @@ +*Jump to [source](escaped-positional-derive.rs)* + +**This requires enabling the `derive` feature flag.** + +You can use `--` to escape further arguments. + +Let's see what this looks like in the help: +```console +$ escaped-positional-derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + escaped-positional-derive[EXE] [OPTIONS] [-- <SLOP>...] + +ARGS: + <SLOP>... + +OPTIONS: + -f + -h, --help Print help information + -p <PEAR> + -V, --version Print version information + +``` + +Here is a baseline without any arguments: +```console +$ escaped-positional-derive +-f used: false +-p's value: None +'slops' values: [] + +``` + +Notice that we can't pass positional arguments before `--`: +```console +$ escaped-positional-derive foo bar +? failed +error: Found argument 'foo' which wasn't expected, or isn't valid in this context + +USAGE: + escaped-positional-derive[EXE] [OPTIONS] [-- <SLOP>...] + +For more information try --help + +``` + +But you can after: +```console +$ escaped-positional-derive -f -p=bob -- sloppy slop slop +-f used: true +-p's value: Some("bob") +'slops' values: ["sloppy", "slop", "slop"] + +``` + +As mentioned, the parser will directly pass everything through: +```console +$ escaped-positional-derive -- -f -p=bob sloppy slop slop +-f used: false +-p's value: None +'slops' values: ["-f", "-p=bob", "sloppy", "slop", "slop"] + +``` diff --git a/third_party/rust/clap/examples/escaped-positional-derive.rs b/third_party/rust/clap/examples/escaped-positional-derive.rs new file mode 100644 index 0000000000..8038395aff --- /dev/null +++ b/third_party/rust/clap/examples/escaped-positional-derive.rs @@ -0,0 +1,27 @@ +// Note: this requires the `derive` feature + +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(short = 'f')] + eff: bool, + + #[clap(short = 'p', value_name = "PEAR")] + pea: Option<String>, + + #[clap(last = true)] + slop: Vec<String>, +} + +fn main() { + let args = Cli::parse(); + + // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`... + println!("-f used: {:?}", args.eff); // -f used: true + println!("-p's value: {:?}", args.pea); // -p's value: Some("bob") + println!("'slops' values: {:?}", args.slop); // 'slops' values: Some(["sloppy", "slop", "slop"]) + + // Continued program logic goes here... +} diff --git a/third_party/rust/clap/examples/escaped-positional.md b/third_party/rust/clap/examples/escaped-positional.md new file mode 100644 index 0000000000..1f71a87369 --- /dev/null +++ b/third_party/rust/clap/examples/escaped-positional.md @@ -0,0 +1,65 @@ +*Jump to [source](escaped-positional.rs)* + +**This requires enabling the `cargo` feature flag.** + +You can use `--` to escape further arguments. + +Let's see what this looks like in the help: +```console +$ escaped-positional --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + escaped-positional[EXE] [OPTIONS] [-- <SLOP>...] + +ARGS: + <SLOP>... + +OPTIONS: + -f + -h, --help Print help information + -p <PEAR> + -V, --version Print version information + +``` + +Here is a baseline without any arguments: +```console +$ escaped-positional +-f used: false +-p's value: None +'slops' values: [] + +``` + +Notice that we can't pass positional arguments before `--`: +```console +$ escaped-positional foo bar +? failed +error: Found argument 'foo' which wasn't expected, or isn't valid in this context + +USAGE: + escaped-positional[EXE] [OPTIONS] [-- <SLOP>...] + +For more information try --help + +``` + +But you can after: +```console +$ escaped-positional -f -p=bob -- sloppy slop slop +-f used: true +-p's value: Some("bob") +'slops' values: ["sloppy", "slop", "slop"] + +``` + +As mentioned, the parser will directly pass everything through: +```console +$ escaped-positional -- -f -p=bob sloppy slop slop +-f used: false +-p's value: None +'slops' values: ["-f", "-p=bob", "sloppy", "slop", "slop"] + +``` diff --git a/third_party/rust/clap/examples/escaped-positional.rs b/third_party/rust/clap/examples/escaped-positional.rs new file mode 100644 index 0000000000..f6d61bd965 --- /dev/null +++ b/third_party/rust/clap/examples/escaped-positional.rs @@ -0,0 +1,26 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command}; + +fn main() { + let matches = command!() + .arg(arg!(eff: -f)) + .arg(arg!(pea: -p <PEAR>).required(false)) + .arg( + arg!(slop: [SLOP]).multiple_occurrences(true).last(true), // Indicates that `slop` is only accessible after `--`. + ) + .get_matches(); + + // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`... + println!("-f used: {:?}", matches.is_present("eff")); // -f used: true + println!("-p's value: {:?}", matches.value_of("pea")); // -p's value: Some("bob") + println!( + "'slops' values: {:?}", + matches + .values_of("slop") + .map(|vals| vals.collect::<Vec<_>>()) + .unwrap_or_default() + ); // 'slops' values: Some(["sloppy", "slop", "slop"]) + + // Continued program logic goes here... +} diff --git a/third_party/rust/clap/examples/git-derive.md b/third_party/rust/clap/examples/git-derive.md new file mode 100644 index 0000000000..dc27776f58 --- /dev/null +++ b/third_party/rust/clap/examples/git-derive.md @@ -0,0 +1,140 @@ +*Jump to [source](git-derive.rs)* + +**This requires enabling the `derive` feature flag.** + +Git is an example of several common subcommand patterns. + +Help: +```console +$ git-derive +? failed +git +A fictional versioning CLI + +USAGE: + git-derive[EXE] <SUBCOMMAND> + +OPTIONS: + -h, --help Print help information + +SUBCOMMANDS: + add adds things + clone Clones repos + help Print this message or the help of the given subcommand(s) + push pushes things + stash + +$ git-derive help +git +A fictional versioning CLI + +USAGE: + git-derive[EXE] <SUBCOMMAND> + +OPTIONS: + -h, --help Print help information + +SUBCOMMANDS: + add adds things + clone Clones repos + help Print this message or the help of the given subcommand(s) + push pushes things + stash + +$ git-derive help add +git-derive[EXE]-add +adds things + +USAGE: + git-derive[EXE] add <PATH>... + +ARGS: + <PATH>... Stuff to add + +OPTIONS: + -h, --help Print help information + +``` + +A basic argument: +```console +$ git-derive add +? failed +git-derive[EXE]-add +adds things + +USAGE: + git-derive[EXE] add <PATH>... + +ARGS: + <PATH>... Stuff to add + +OPTIONS: + -h, --help Print help information + +$ git-derive add Cargo.toml Cargo.lock +Adding ["Cargo.toml", "Cargo.lock"] + +``` + +Default subcommand: +```console +$ git-derive stash -h +git-derive[EXE]-stash + +USAGE: + git-derive[EXE] stash [OPTIONS] + git-derive[EXE] stash <SUBCOMMAND> + +OPTIONS: + -h, --help Print help information + -m, --message <MESSAGE> + +SUBCOMMANDS: + apply + help Print this message or the help of the given subcommand(s) + pop + push + +$ git-derive stash push -h +git-derive[EXE]-stash-push + +USAGE: + git-derive[EXE] stash push [OPTIONS] + +OPTIONS: + -h, --help Print help information + -m, --message <MESSAGE> + +$ git-derive stash pop -h +git-derive[EXE]-stash-pop + +USAGE: + git-derive[EXE] stash pop [STASH] + +ARGS: + <STASH> + +OPTIONS: + -h, --help Print help information + +$ git-derive stash -m "Prototype" +Pushing StashPush { message: Some("Prototype") } + +$ git-derive stash pop +Popping None + +$ git-derive stash push -m "Prototype" +Pushing StashPush { message: Some("Prototype") } + +$ git-derive stash pop +Popping None + +``` + +External subcommands: +```console +$ git-derive custom-tool arg1 --foo bar +Calling out to "custom-tool" with ["arg1", "--foo", "bar"] + +``` diff --git a/third_party/rust/clap/examples/git-derive.rs b/third_party/rust/clap/examples/git-derive.rs new file mode 100644 index 0000000000..7e44edb1af --- /dev/null +++ b/third_party/rust/clap/examples/git-derive.rs @@ -0,0 +1,99 @@ +// Note: this requires the `derive` feature + +use std::ffi::OsString; +use std::path::PathBuf; + +use clap::{Args, Parser, Subcommand}; + +/// A fictional versioning CLI +#[derive(Debug, Parser)] +#[clap(name = "git")] +#[clap(about = "A fictional versioning CLI", long_about = None)] +struct Cli { + #[clap(subcommand)] + command: Commands, +} + +#[derive(Debug, Subcommand)] +enum Commands { + /// Clones repos + #[clap(arg_required_else_help = true)] + Clone { + /// The remote to clone + remote: String, + }, + /// pushes things + #[clap(arg_required_else_help = true)] + Push { + /// The remote to target + remote: String, + }, + /// adds things + #[clap(arg_required_else_help = true)] + Add { + /// Stuff to add + #[clap(required = true, parse(from_os_str))] + path: Vec<PathBuf>, + }, + Stash(Stash), + #[clap(external_subcommand)] + External(Vec<OsString>), +} + +#[derive(Debug, Args)] +#[clap(args_conflicts_with_subcommands = true)] +struct Stash { + #[clap(subcommand)] + command: Option<StashCommands>, + + #[clap(flatten)] + push: StashPush, +} + +#[derive(Debug, Subcommand)] +enum StashCommands { + Push(StashPush), + Pop { stash: Option<String> }, + Apply { stash: Option<String> }, +} + +#[derive(Debug, Args)] +struct StashPush { + #[clap(short, long)] + message: Option<String>, +} + +fn main() { + let args = Cli::parse(); + + match args.command { + Commands::Clone { remote } => { + println!("Cloning {}", remote); + } + Commands::Push { remote } => { + println!("Pushing to {}", remote); + } + Commands::Add { path } => { + println!("Adding {:?}", path); + } + Commands::Stash(stash) => { + let stash_cmd = stash.command.unwrap_or(StashCommands::Push(stash.push)); + match stash_cmd { + StashCommands::Push(push) => { + println!("Pushing {:?}", push); + } + StashCommands::Pop { stash } => { + println!("Popping {:?}", stash); + } + StashCommands::Apply { stash } => { + println!("Applying {:?}", stash); + } + } + } + Commands::External(args) => { + println!("Calling out to {:?} with {:?}", &args[0], &args[1..]); + } + } + + // Continued program logic goes here... +} diff --git a/third_party/rust/clap/examples/git.md b/third_party/rust/clap/examples/git.md new file mode 100644 index 0000000000..2cdfe653b3 --- /dev/null +++ b/third_party/rust/clap/examples/git.md @@ -0,0 +1,138 @@ +*Jump to [source](git.rs)* + +Git is an example of several common subcommand patterns. + +Help: +```console +$ git +? failed +git +A fictional versioning CLI + +USAGE: + git[EXE] <SUBCOMMAND> + +OPTIONS: + -h, --help Print help information + +SUBCOMMANDS: + add adds things + clone Clones repos + help Print this message or the help of the given subcommand(s) + push pushes things + stash + +$ git help +git +A fictional versioning CLI + +USAGE: + git[EXE] <SUBCOMMAND> + +OPTIONS: + -h, --help Print help information + +SUBCOMMANDS: + add adds things + clone Clones repos + help Print this message or the help of the given subcommand(s) + push pushes things + stash + +$ git help add +git[EXE]-add +adds things + +USAGE: + git[EXE] add <PATH>... + +ARGS: + <PATH>... Stuff to add + +OPTIONS: + -h, --help Print help information + +``` + +A basic argument: +```console +$ git add +? failed +git[EXE]-add +adds things + +USAGE: + git[EXE] add <PATH>... + +ARGS: + <PATH>... Stuff to add + +OPTIONS: + -h, --help Print help information + +$ git add Cargo.toml Cargo.lock +Adding ["Cargo.toml", "Cargo.lock"] + +``` + +Default subcommand: +```console +$ git stash -h +git[EXE]-stash + +USAGE: + git[EXE] stash [OPTIONS] + git[EXE] stash <SUBCOMMAND> + +OPTIONS: + -h, --help Print help information + -m, --message <MESSAGE> + +SUBCOMMANDS: + apply + help Print this message or the help of the given subcommand(s) + pop + push + +$ git stash push -h +git[EXE]-stash-push + +USAGE: + git[EXE] stash push [OPTIONS] + +OPTIONS: + -h, --help Print help information + -m, --message <MESSAGE> + +$ git stash pop -h +git[EXE]-stash-pop + +USAGE: + git[EXE] stash pop [STASH] + +ARGS: + <STASH> + +OPTIONS: + -h, --help Print help information + +$ git stash -m "Prototype" +Pushing Some("Prototype") + +$ git stash pop +Popping None + +$ git stash push -m "Prototype" +Pushing Some("Prototype") + +$ git stash pop +Popping None + +``` + +External subcommands: +```console +$ git custom-tool arg1 --foo bar +Calling out to "custom-tool" with ["arg1", "--foo", "bar"] + +``` diff --git a/third_party/rust/clap/examples/git.rs b/third_party/rust/clap/examples/git.rs new file mode 100644 index 0000000000..1ced54a90e --- /dev/null +++ b/third_party/rust/clap/examples/git.rs @@ -0,0 +1,101 @@ +// Note: this requires the `cargo` feature + +use std::path::PathBuf; + +use clap::{arg, Command}; + +fn cli() -> Command<'static> { + Command::new("git") + .about("A fictional versioning CLI") + .subcommand_required(true) + .arg_required_else_help(true) + .allow_external_subcommands(true) + .allow_invalid_utf8_for_external_subcommands(true) + .subcommand( + Command::new("clone") + .about("Clones repos") + .arg(arg!(<REMOTE> "The remote to clone")) + .arg_required_else_help(true), + ) + .subcommand( + Command::new("push") + .about("pushes things") + .arg(arg!(<REMOTE> "The remote to target")) + .arg_required_else_help(true), + ) + .subcommand( + Command::new("add") + .about("adds things") + .arg_required_else_help(true) + .arg(arg!(<PATH> ... "Stuff to add").allow_invalid_utf8(true)), + ) + .subcommand( + Command::new("stash") + .args_conflicts_with_subcommands(true) + .args(push_args()) + .subcommand(Command::new("push").args(push_args())) + .subcommand(Command::new("pop").arg(arg!([STASH]))) + .subcommand(Command::new("apply").arg(arg!([STASH]))), + ) +} + +fn push_args() -> Vec<clap::Arg<'static>> { + vec![arg!(-m --message <MESSAGE>).required(false)] +} + +fn main() { + let matches = cli().get_matches(); + + match matches.subcommand() { + Some(("clone", sub_matches)) => { + println!( + "Cloning {}", + sub_matches.value_of("REMOTE").expect("required") + ); + } + Some(("push", sub_matches)) => { + println!( + "Pushing to {}", + sub_matches.value_of("REMOTE").expect("required") + ); + } + Some(("add", sub_matches)) => { + let paths = sub_matches + .values_of_os("PATH") + .unwrap_or_default() + .map(PathBuf::from) + .collect::<Vec<_>>(); + println!("Adding {:?}", paths); + } + Some(("stash", sub_matches)) => { + let stash_command = sub_matches.subcommand().unwrap_or(("push", sub_matches)); + match stash_command { + ("apply", sub_matches) => { + let stash = sub_matches.value_of("STASH"); + println!("Applying {:?}", stash); + } + ("pop", sub_matches) => { + let stash = sub_matches.value_of("STASH"); + println!("Popping {:?}", stash); + } + ("push", sub_matches) => { + let message = sub_matches.value_of("message"); + println!("Pushing {:?}", message); + } + (name, _) => { + unreachable!("Unsupported subcommand `{}`", name) + } + } + } + Some((ext, sub_matches)) => { + let args = sub_matches + .values_of_os("") + .unwrap_or_default() + .collect::<Vec<_>>(); + println!("Calling out to {:?} with {:?}", ext, args); + } + _ => unreachable!(), // If all subcommands are defined above, anything else is unreachabe!() + } + + // Continued program logic goes here... +} diff --git a/third_party/rust/clap/examples/multicall-busybox.md b/third_party/rust/clap/examples/multicall-busybox.md new file mode 100644 index 0000000000..a09418403f --- /dev/null +++ b/third_party/rust/clap/examples/multicall-busybox.md @@ -0,0 +1,46 @@ +*Jump to [source](multicall-busybox.rs)* + +Example of a busybox-style multicall program + +See the documentation for `clap::Command::multicall` for rationale. + +This example omits every command except true and false, +which are the most trivial to implement, +```console +$ busybox true +? 0 + +$ busybox false +? 1 + +``` +*Note: without the links setup, we can't demonstrate the multicall behavior* + +But includes the `--install` option as an example of why it can be useful +for the main program to take arguments that aren't applet subcommands. +```console +$ busybox --install +? failed +... + +``` + +Though users must pass something: +```console +$ busybox +? failed +busybox + +USAGE: + busybox [OPTIONS] [APPLET] + +OPTIONS: + -h, --help Print help information + --install <install> Install hardlinks for all subcommands in path + +APPLETS: + false does nothing unsuccessfully + help Print this message or the help of the given subcommand(s) + true does nothing successfully + +``` diff --git a/third_party/rust/clap/examples/multicall-busybox.rs b/third_party/rust/clap/examples/multicall-busybox.rs new file mode 100644 index 0000000000..30865a8303 --- /dev/null +++ b/third_party/rust/clap/examples/multicall-busybox.rs @@ -0,0 +1,48 @@ +// Note: this requires the `unstable-multicall` feature + +use std::process::exit; + +use clap::{Arg, Command}; + +fn applet_commands() -> [Command<'static>; 2] { + [ + Command::new("true").about("does nothing successfully"), + Command::new("false").about("does nothing unsuccessfully"), + ] +} + +fn main() { + let cmd = Command::new(env!("CARGO_CRATE_NAME")) + .multicall(true) + .subcommand( + Command::new("busybox") + .arg_required_else_help(true) + .subcommand_value_name("APPLET") + .subcommand_help_heading("APPLETS") + .arg( + Arg::new("install") + .long("install") + .help("Install hardlinks for all subcommands in path") + .exclusive(true) + .takes_value(true) + .default_missing_value("/usr/local/bin") + .use_value_delimiter(false), + ) + .subcommands(applet_commands()), + ) + .subcommands(applet_commands()); + + let matches = cmd.get_matches(); + let mut subcommand = matches.subcommand(); + if let Some(("busybox", cmd)) = subcommand { + if cmd.occurrences_of("install") > 0 { + unimplemented!("Make hardlinks to the executable here"); + } + subcommand = cmd.subcommand(); + } + match subcommand { + Some(("false", _)) => exit(1), + Some(("true", _)) => exit(0), + _ => unreachable!("parser should ensure only valid subcommand names are used"), + } +} diff --git a/third_party/rust/clap/examples/multicall-hostname.md b/third_party/rust/clap/examples/multicall-hostname.md new file mode 100644 index 0000000000..9e17ca16cb --- /dev/null +++ b/third_party/rust/clap/examples/multicall-hostname.md @@ -0,0 +1,14 @@ +*Jump to [source](multicall-hostname.rs)* + +Example of a `hostname-style` multicall program + +See the documentation for `clap::Command::multicall` for rationale. + +This example omits the implementation of displaying address config + +```console +$ hostname +www + +``` +*Note: without the links setup, we can't demonstrate the multicall behavior* diff --git a/third_party/rust/clap/examples/multicall-hostname.rs b/third_party/rust/clap/examples/multicall-hostname.rs new file mode 100644 index 0000000000..2c89a14484 --- /dev/null +++ b/third_party/rust/clap/examples/multicall-hostname.rs @@ -0,0 +1,19 @@ +// Note: this requires the `unstable-multicall` feature + +use clap::Command; + +fn main() { + let cmd = Command::new(env!("CARGO_CRATE_NAME")) + .multicall(true) + .arg_required_else_help(true) + .subcommand_value_name("APPLET") + .subcommand_help_heading("APPLETS") + .subcommand(Command::new("hostname").about("show hostname part of FQDN")) + .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN")); + + match cmd.get_matches().subcommand_name() { + Some("hostname") => println!("www"), + Some("dnsdomainname") => println!("example.com"), + _ => unreachable!("parser should ensure only valid subcommand names are used"), + } +} diff --git a/third_party/rust/clap/examples/pacman.md b/third_party/rust/clap/examples/pacman.md new file mode 100644 index 0000000000..7f6c5a7d33 --- /dev/null +++ b/third_party/rust/clap/examples/pacman.md @@ -0,0 +1,87 @@ +*Jump to [source](pacman.rs)* + +[`pacman`](https://wiki.archlinux.org/index.php/pacman) defines subcommands via flags. + +Here, `-S` is a short flag subcommand: +```console +$ pacman -S package +Installing package... + +``` + +Here `--sync` is a long flag subcommand: +```console +$ pacman --sync package +Installing package... + +``` + +Now the short flag subcommand (`-S`) with a long flag: +```console +$ pacman -S --search name +Searching for name... + +``` + +And the various forms of short flags that work: +```console +$ pacman -S -s name +Searching for name... + +$ pacman -Ss name +Searching for name... + +``` +*(users can "stack" short subcommands with short flags or with other short flag subcommands)* + +In the help, this looks like: +```console +$ pacman -h +pacman 5.2.1 +Pacman Development Team +package manager utility + +USAGE: + pacman[EXE] <SUBCOMMAND> + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + help Print this message or the help of the given subcommand(s) + query -Q --query Query the package database. + sync -S --sync Synchronize packages. + +$ pacman -S -h +pacman[EXE]-sync +Synchronize packages. + +USAGE: + pacman[EXE] {sync|--sync|-S} [OPTIONS] [--] [package]... + +ARGS: + <package>... packages + +OPTIONS: + -h, --help Print help information + -i, --info view package information + -s, --search <search>... search remote repositories for matching strings + +``` + +And errors: +```console +$ pacman -S -s foo -i bar +? failed +error: The argument '--search <search>...' cannot be used with '--info' + +USAGE: + pacman[EXE] {sync|--sync|-S} --search <search>... <package>... + +For more information try --help + +``` + +**NOTE:** Keep in mind that subcommands, flags, and long flags are *case sensitive*: `-Q` and `-q` are different flags/subcommands. For example, you can have both `-Q` subcommand and `-q` flag, and they will be properly disambiguated. +Let's make a quick program to illustrate. diff --git a/third_party/rust/clap/examples/pacman.rs b/third_party/rust/clap/examples/pacman.rs new file mode 100644 index 0000000000..c088a8fe91 --- /dev/null +++ b/third_party/rust/clap/examples/pacman.rs @@ -0,0 +1,102 @@ +use clap::{Arg, Command}; + +fn main() { + let matches = Command::new("pacman") + .about("package manager utility") + .version("5.2.1") + .subcommand_required(true) + .arg_required_else_help(true) + .author("Pacman Development Team") + // Query subcommand + // + // Only a few of its arguments are implemented below. + .subcommand( + Command::new("query") + .short_flag('Q') + .long_flag("query") + .about("Query the package database.") + .arg( + Arg::new("search") + .short('s') + .long("search") + .help("search locally installed packages for matching strings") + .conflicts_with("info") + .takes_value(true) + .multiple_values(true), + ) + .arg( + Arg::new("info") + .long("info") + .short('i') + .conflicts_with("search") + .help("view package information") + .takes_value(true) + .multiple_values(true), + ), + ) + // Sync subcommand + // + // Only a few of its arguments are implemented below. + .subcommand( + Command::new("sync") + .short_flag('S') + .long_flag("sync") + .about("Synchronize packages.") + .arg( + Arg::new("search") + .short('s') + .long("search") + .conflicts_with("info") + .takes_value(true) + .multiple_values(true) + .help("search remote repositories for matching strings"), + ) + .arg( + Arg::new("info") + .long("info") + .conflicts_with("search") + .short('i') + .help("view package information"), + ) + .arg( + Arg::new("package") + .help("packages") + .required_unless_present("search") + .takes_value(true) + .multiple_values(true), + ), + ) + .get_matches(); + + match matches.subcommand() { + Some(("sync", sync_matches)) => { + if sync_matches.is_present("search") { + let packages: Vec<_> = sync_matches.values_of("search").unwrap().collect(); + let values = packages.join(", "); + println!("Searching for {}...", values); + return; + } + + let packages: Vec<_> = sync_matches.values_of("package").unwrap().collect(); + let values = packages.join(", "); + + if sync_matches.is_present("info") { + println!("Retrieving info for {}...", values); + } else { + println!("Installing {}...", values); + } + } + Some(("query", query_matches)) => { + if let Some(packages) = query_matches.values_of("info") { + let comma_sep = packages.collect::<Vec<_>>().join(", "); + println!("Retrieving info for {}...", comma_sep); + } else if let Some(queries) = query_matches.values_of("search") { + let comma_sep = queries.collect::<Vec<_>>().join(", "); + println!("Searching Locally for {}...", comma_sep); + } else { + println!("Displaying all locally installed packages..."); + } + } + _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable + } +} diff --git a/third_party/rust/clap/examples/repl.rs b/third_party/rust/clap/examples/repl.rs new file mode 100644 index 0000000000..f1b65c3090 --- /dev/null +++ b/third_party/rust/clap/examples/repl.rs @@ -0,0 +1,94 @@ +// Note: this requires the `unstable-multicall` feature + +use std::io::Write; + +use clap::Command; + +fn main() -> Result<(), String> { + loop { + let line = readline()?; + let line = line.trim(); + if line.is_empty() { + continue; + } + + match respond(line) { + Ok(quit) => { + if quit { + break; + } + } + Err(err) => { + write!(std::io::stdout(), "{}", err).map_err(|e| e.to_string())?; + std::io::stdout().flush().map_err(|e| e.to_string())?; + } + } + } + + Ok(()) +} + +fn respond(line: &str) -> Result<bool, String> { + let args = shlex::split(line).ok_or("error: Invalid quoting")?; + let matches = cli() + .try_get_matches_from(&args) + .map_err(|e| e.to_string())?; + match matches.subcommand() { + Some(("ping", _matches)) => { + write!(std::io::stdout(), "Pong").map_err(|e| e.to_string())?; + std::io::stdout().flush().map_err(|e| e.to_string())?; + } + Some(("quit", _matches)) => { + write!(std::io::stdout(), "Exiting ...").map_err(|e| e.to_string())?; + std::io::stdout().flush().map_err(|e| e.to_string())?; + return Ok(true); + } + Some((name, _matches)) => unimplemented!("{}", name), + None => unreachable!("subcommand required"), + } + + Ok(false) +} + +fn cli() -> Command<'static> { + // strip out usage + const PARSER_TEMPLATE: &str = "\ + {all-args} + "; + // strip out name/version + const APPLET_TEMPLATE: &str = "\ + {about-with-newline}\n\ + {usage-heading}\n {usage}\n\ + \n\ + {all-args}{after-help}\ + "; + + Command::new("repl") + .multicall(true) + .arg_required_else_help(true) + .subcommand_required(true) + .subcommand_value_name("APPLET") + .subcommand_help_heading("APPLETS") + .help_template(PARSER_TEMPLATE) + .subcommand( + Command::new("ping") + .about("Get a response") + .help_template(APPLET_TEMPLATE), + ) + .subcommand( + Command::new("quit") + .alias("exit") + .about("Quit the REPL") + .help_template(APPLET_TEMPLATE), + ) +} + +fn readline() -> Result<String, String> { + write!(std::io::stdout(), "$ ").map_err(|e| e.to_string())?; + std::io::stdout().flush().map_err(|e| e.to_string())?; + let mut buffer = String::new(); + std::io::stdin() + .read_line(&mut buffer) + .map_err(|e| e.to_string())?; + Ok(buffer) +} diff --git a/third_party/rust/clap/examples/tutorial_builder/01_quick.rs b/third_party/rust/clap/examples/tutorial_builder/01_quick.rs new file mode 100644 index 0000000000..7ab5081dfc --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/01_quick.rs @@ -0,0 +1,60 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command, Command}; +use std::path::Path; + +fn main() { + let matches = command!() + .arg(arg!([name] "Optional name to operate on")) + .arg( + arg!( + -c --config <FILE> "Sets a custom config file" + ) + // We don't have syntax yet for optional options, so manually calling `required` + .required(false) + // Support non-UTF8 paths + .allow_invalid_utf8(true), + ) + .arg(arg!( + -d --debug ... "Turn debugging information on" + )) + .subcommand( + Command::new("test") + .about("does testing things") + .arg(arg!(-l --list "lists test values")), + ) + .get_matches(); + + // You can check the value provided by positional arguments, or option arguments + if let Some(name) = matches.value_of("name") { + println!("Value for name: {}", name); + } + + if let Some(raw_config) = matches.value_of_os("config") { + let config_path = Path::new(raw_config); + println!("Value for config: {}", config_path.display()); + } + + // You can see how many times a particular flag or argument occurred + // Note, only flags can have multiple occurrences + match matches.occurrences_of("debug") { + 0 => println!("Debug mode is off"), + 1 => println!("Debug mode is kind of on"), + 2 => println!("Debug mode is on"), + _ => println!("Don't be crazy"), + } + + // You can check for the existence of subcommands, and if found use their + // matches just as you would the top level cmd + if let Some(matches) = matches.subcommand_matches("test") { + // "$ myapp test" was run + if matches.is_present("list") { + // "$ myapp test -l" was run + println!("Printing testing lists..."); + } else { + println!("Not printing testing lists..."); + } + } + + // Continued program logic goes here... +} diff --git a/third_party/rust/clap/examples/tutorial_builder/02_app_settings.rs b/third_party/rust/clap/examples/tutorial_builder/02_app_settings.rs new file mode 100644 index 0000000000..3485f588eb --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/02_app_settings.rs @@ -0,0 +1,16 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command, AppSettings}; + +fn main() { + let matches = command!() + .args_override_self(true) + .global_setting(AppSettings::DeriveDisplayOrder) + .allow_negative_numbers(true) + .arg(arg!(--two <VALUE>)) + .arg(arg!(--one <VALUE>)) + .get_matches(); + + println!("two: {:?}", matches.value_of("two").expect("required")); + println!("one: {:?}", matches.value_of("one").expect("required")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/02_apps.rs b/third_party/rust/clap/examples/tutorial_builder/02_apps.rs new file mode 100644 index 0000000000..c9422d64a3 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/02_apps.rs @@ -0,0 +1,14 @@ +use clap::{arg, Command}; + +fn main() { + let matches = Command::new("MyApp") + .version("1.0") + .author("Kevin K. <kbknapp@gmail.com>") + .about("Does awesome things") + .arg(arg!(--two <VALUE>)) + .arg(arg!(--one <VALUE>)) + .get_matches(); + + println!("two: {:?}", matches.value_of("two").expect("required")); + println!("one: {:?}", matches.value_of("one").expect("required")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/02_crate.rs b/third_party/rust/clap/examples/tutorial_builder/02_crate.rs new file mode 100644 index 0000000000..df214f3f5c --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/02_crate.rs @@ -0,0 +1,13 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command}; + +fn main() { + let matches = command!() + .arg(arg!(--two <VALUE>)) + .arg(arg!(--one <VALUE>)) + .get_matches(); + + println!("two: {:?}", matches.value_of("two").expect("required")); + println!("one: {:?}", matches.value_of("one").expect("required")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/03_01_flag_bool.rs b/third_party/rust/clap/examples/tutorial_builder/03_01_flag_bool.rs new file mode 100644 index 0000000000..a8d85c4c2e --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/03_01_flag_bool.rs @@ -0,0 +1,9 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command}; + +fn main() { + let matches = command!().arg(arg!(-v - -verbose)).get_matches(); + + println!("verbose: {:?}", matches.is_present("verbose")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/03_01_flag_count.rs b/third_party/rust/clap/examples/tutorial_builder/03_01_flag_count.rs new file mode 100644 index 0000000000..c5532c07a4 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/03_01_flag_count.rs @@ -0,0 +1,9 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command}; + +fn main() { + let matches = command!().arg(arg!(-v --verbose ...)).get_matches(); + + println!("verbose: {:?}", matches.occurrences_of("verbose")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/03_02_option.rs b/third_party/rust/clap/examples/tutorial_builder/03_02_option.rs new file mode 100644 index 0000000000..29ad60a99c --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/03_02_option.rs @@ -0,0 +1,11 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command}; + +fn main() { + let matches = command!() + .arg(arg!(-n --name <NAME>).required(false)) + .get_matches(); + + println!("name: {:?}", matches.value_of("name")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/03_03_positional.rs b/third_party/rust/clap/examples/tutorial_builder/03_03_positional.rs new file mode 100644 index 0000000000..03bfab8e05 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/03_03_positional.rs @@ -0,0 +1,9 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command}; + +fn main() { + let matches = command!().arg(arg!([NAME])).get_matches(); + + println!("NAME: {:?}", matches.value_of("NAME")); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/03_04_subcommands.rs b/third_party/rust/clap/examples/tutorial_builder/03_04_subcommands.rs new file mode 100644 index 0000000000..1ab79e714d --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/03_04_subcommands.rs @@ -0,0 +1,24 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command, Command}; + +fn main() { + let matches = command!() + .propagate_version(true) + .subcommand_required(true) + .arg_required_else_help(true) + .subcommand( + Command::new("add") + .about("Adds files to myapp") + .arg(arg!([NAME])), + ) + .get_matches(); + + match matches.subcommand() { + Some(("add", sub_matches)) => println!( + "'myapp add' was used, name is: {:?}", + sub_matches.value_of("NAME") + ), + _ => unreachable!("Exhausted list of subcommands and subcommand_required prevents `None`"), + } +} diff --git a/third_party/rust/clap/examples/tutorial_builder/03_05_default_values.rs b/third_party/rust/clap/examples/tutorial_builder/03_05_default_values.rs new file mode 100644 index 0000000000..f88e3953c8 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/03_05_default_values.rs @@ -0,0 +1,16 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command}; + +fn main() { + let matches = command!() + .arg(arg!([NAME]).default_value("alice")) + .get_matches(); + + println!( + "NAME: {:?}", + matches + .value_of("NAME") + .expect("default ensures there is always a value") + ); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/04_01_enum.rs b/third_party/rust/clap/examples/tutorial_builder/04_01_enum.rs new file mode 100644 index 0000000000..128b3cdc4a --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/04_01_enum.rs @@ -0,0 +1,62 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command, ArgEnum, PossibleValue}; + +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ArgEnum)] +enum Mode { + Fast, + Slow, +} + +impl Mode { + pub fn possible_values() -> impl Iterator<Item = PossibleValue<'static>> { + Mode::value_variants() + .iter() + .filter_map(ArgEnum::to_possible_value) + } +} + +impl std::fmt::Display for Mode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.to_possible_value() + .expect("no values are skipped") + .get_name() + .fmt(f) + } +} + +impl std::str::FromStr for Mode { + type Err = String; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + for variant in Self::value_variants() { + if variant.to_possible_value().unwrap().matches(s, false) { + return Ok(*variant); + } + } + Err(format!("Invalid variant: {}", s)) + } +} + +fn main() { + let matches = command!() + .arg( + arg!(<MODE>) + .help("What mode to run the program in") + .possible_values(Mode::possible_values()), + ) + .get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + match matches + .value_of_t("MODE") + .expect("'MODE' is required and parsing will fail if its missing") + { + Mode::Fast => { + println!("Hare"); + } + Mode::Slow => { + println!("Tortoise"); + } + } +} diff --git a/third_party/rust/clap/examples/tutorial_builder/04_01_possible.rs b/third_party/rust/clap/examples/tutorial_builder/04_01_possible.rs new file mode 100644 index 0000000000..77160392a3 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/04_01_possible.rs @@ -0,0 +1,27 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command}; + +fn main() { + let matches = command!() + .arg( + arg!(<MODE>) + .help("What mode to run the program in") + .possible_values(["fast", "slow"]), + ) + .get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + match matches + .value_of("MODE") + .expect("'MODE' is required and parsing will fail if its missing") + { + "fast" => { + println!("Hare"); + } + "slow" => { + println!("Tortoise"); + } + _ => unreachable!(), + } +} diff --git a/third_party/rust/clap/examples/tutorial_builder/04_02_parse.rs b/third_party/rust/clap/examples/tutorial_builder/04_02_parse.rs new file mode 100644 index 0000000000..e354af3a8a --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/04_02_parse.rs @@ -0,0 +1,19 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command}; + +fn main() { + let matches = command!() + .arg( + arg!(<PORT>) + .help("Network port to use") + .validator(|s| s.parse::<usize>()), + ) + .get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + let port: usize = matches + .value_of_t("PORT") + .expect("'PORT' is required and parsing will fail if its missing"); + println!("PORT = {}", port); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/04_02_validate.rs b/third_party/rust/clap/examples/tutorial_builder/04_02_validate.rs new file mode 100644 index 0000000000..a49f869e00 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/04_02_validate.rs @@ -0,0 +1,38 @@ +// Note: this requires the `cargo` feature + +use std::ops::RangeInclusive; + +use clap::{arg, command}; + +fn main() { + let matches = command!() + .arg( + arg!(<PORT>) + .help("Network port to use") + .validator(port_in_range), + ) + .get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + let port: usize = matches + .value_of_t("PORT") + .expect("'PORT' is required and parsing will fail if its missing"); + println!("PORT = {}", port); +} + +const PORT_RANGE: RangeInclusive<usize> = 1..=65535; + +fn port_in_range(s: &str) -> Result<(), String> { + let port: usize = s + .parse() + .map_err(|_| format!("`{}` isn't a port number", s))?; + if PORT_RANGE.contains(&port) { + Ok(()) + } else { + Err(format!( + "Port not in range {}-{}", + PORT_RANGE.start(), + PORT_RANGE.end() + )) + } +} diff --git a/third_party/rust/clap/examples/tutorial_builder/04_03_relations.rs b/third_party/rust/clap/examples/tutorial_builder/04_03_relations.rs new file mode 100644 index 0000000000..495bf365cc --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/04_03_relations.rs @@ -0,0 +1,69 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command, ArgGroup}; + +fn main() { + // Create application like normal + let matches = command!() + // Add the version arguments + .arg(arg!(--"set-ver" <VER> "set version manually").required(false)) + .arg(arg!(--major "auto inc major")) + .arg(arg!(--minor "auto inc minor")) + .arg(arg!(--patch "auto inc patch")) + // Create a group, make it required, and add the above arguments + .group( + ArgGroup::new("vers") + .required(true) + .args(&["set-ver", "major", "minor", "patch"]), + ) + // Arguments can also be added to a group individually, these two arguments + // are part of the "input" group which is not required + .arg(arg!([INPUT_FILE] "some regular input").group("input")) + .arg( + arg!(--"spec-in" <SPEC_IN> "some special input argument") + .required(false) + .group("input"), + ) + // Now let's assume we have a -c [config] argument which requires one of + // (but **not** both) the "input" arguments + .arg(arg!(config: -c <CONFIG>).required(false).requires("input")) + .get_matches(); + + // Let's assume the old version 1.2.3 + let mut major = 1; + let mut minor = 2; + let mut patch = 3; + + // See if --set-ver was used to set the version manually + let version = if let Some(ver) = matches.value_of("set-ver") { + ver.to_string() + } else { + // Increment the one requested (in a real program, we'd reset the lower numbers) + let (maj, min, pat) = ( + matches.is_present("major"), + matches.is_present("minor"), + matches.is_present("patch"), + ); + match (maj, min, pat) { + (true, _, _) => major += 1, + (_, true, _) => minor += 1, + (_, _, true) => patch += 1, + _ => unreachable!(), + }; + format!("{}.{}.{}", major, minor, patch) + }; + + println!("Version: {}", version); + + // Check for usage of -c + if matches.is_present("config") { + let input = matches + .value_of("INPUT_FILE") + .unwrap_or_else(|| matches.value_of("spec-in").unwrap()); + println!( + "Doing work using input {} and config {}", + input, + matches.value_of("config").unwrap() + ); + } +} diff --git a/third_party/rust/clap/examples/tutorial_builder/04_04_custom.rs b/third_party/rust/clap/examples/tutorial_builder/04_04_custom.rs new file mode 100644 index 0000000000..6993329d32 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/04_04_custom.rs @@ -0,0 +1,80 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command, ErrorKind}; + +fn main() { + // Create application like normal + let mut cmd = command!() + // Add the version arguments + .arg(arg!(--"set-ver" <VER> "set version manually").required(false)) + .arg(arg!(--major "auto inc major")) + .arg(arg!(--minor "auto inc minor")) + .arg(arg!(--patch "auto inc patch")) + // Arguments can also be added to a group individually, these two arguments + // are part of the "input" group which is not required + .arg(arg!([INPUT_FILE] "some regular input")) + .arg(arg!(--"spec-in" <SPEC_IN> "some special input argument").required(false)) + // Now let's assume we have a -c [config] argument which requires one of + // (but **not** both) the "input" arguments + .arg(arg!(config: -c <CONFIG>).required(false)); + let matches = cmd.get_matches_mut(); + + // Let's assume the old version 1.2.3 + let mut major = 1; + let mut minor = 2; + let mut patch = 3; + + // See if --set-ver was used to set the version manually + let version = if let Some(ver) = matches.value_of("set-ver") { + if matches.is_present("major") || matches.is_present("minor") || matches.is_present("patch") + { + cmd.error( + ErrorKind::ArgumentConflict, + "Can't do relative and absolute version change", + ) + .exit(); + } + ver.to_string() + } else { + // Increment the one requested (in a real program, we'd reset the lower numbers) + let (maj, min, pat) = ( + matches.is_present("major"), + matches.is_present("minor"), + matches.is_present("patch"), + ); + match (maj, min, pat) { + (true, false, false) => major += 1, + (false, true, false) => minor += 1, + (false, false, true) => patch += 1, + _ => { + cmd.error( + ErrorKind::ArgumentConflict, + "Can only modify one version field", + ) + .exit(); + } + }; + format!("{}.{}.{}", major, minor, patch) + }; + + println!("Version: {}", version); + + // Check for usage of -c + if matches.is_present("config") { + let input = matches + .value_of("INPUT_FILE") + .or_else(|| matches.value_of("spec-in")) + .unwrap_or_else(|| { + cmd.error( + ErrorKind::MissingRequiredArgument, + "INPUT_FILE or --spec-in is required when using --config", + ) + .exit() + }); + println!( + "Doing work using input {} and config {}", + input, + matches.value_of("config").unwrap() + ); + } +} diff --git a/third_party/rust/clap/examples/tutorial_builder/05_01_assert.rs b/third_party/rust/clap/examples/tutorial_builder/05_01_assert.rs new file mode 100644 index 0000000000..f40f6ebd20 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/05_01_assert.rs @@ -0,0 +1,26 @@ +// Note: this requires the `cargo` feature + +use clap::{arg, command}; + +fn main() { + let matches = cmd().get_matches(); + + // Note, it's safe to call unwrap() because the arg is required + let port: usize = matches + .value_of_t("PORT") + .expect("'PORT' is required and parsing will fail if its missing"); + println!("PORT = {}", port); +} + +fn cmd() -> clap::Command<'static> { + command!().arg( + arg!(<PORT>) + .help("Network port to use") + .validator(|s| s.parse::<usize>()), + ) +} + +#[test] +fn verify_app() { + cmd().debug_assert(); +} diff --git a/third_party/rust/clap/examples/tutorial_builder/README.md b/third_party/rust/clap/examples/tutorial_builder/README.md new file mode 100644 index 0000000000..fcbda4b3a0 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_builder/README.md @@ -0,0 +1,664 @@ +# Tutorial + +*Jump to [derive tutorial](../tutorial_derive/README.md)* + +1. [Quick Start](#quick-start) +2. [Configuring the Parser](#configuring-the-parser) +3. [Adding Arguments](#adding-arguments) + 1. [Positionals](#positionals) + 2. [Options](#options) + 3. [Flags](#flags) + 4. [Subcommands](#subcommands) + 5. [Defaults](#defaults) +4. Validation + 1. [Enumerated values](#enumerated-values) + 2. [Validated values](#validated-values) + 3. [Argument Relations](#argument-relations) + 4. [Custom Validation](#custom-validation) +5. [Tips](#tips) +6. [Contributing](#contributing) + +## Quick Start + +You can create an application with several arguments using usage strings. + +[Example:](01_quick.rs) +```console +$ 01_quick --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 01_quick[EXE] [OPTIONS] [name] [SUBCOMMAND] + +ARGS: + <name> Optional name to operate on + +OPTIONS: + -c, --config <FILE> Sets a custom config file + -d, --debug Turn debugging information on + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + help Print this message or the help of the given subcommand(s) + test does testing things + +``` + +By default, the program does nothing: +```console +$ 01_quick +Debug mode is off + +``` + +But you can mix and match the various features +```console +$ 01_quick -dd test +Debug mode is on +Not printing testing lists... + +``` + +## Configuring the Parser + +You use the `Command` the start building a parser. + +[Example:](02_apps.rs) +```console +$ 02_apps --help +MyApp 1.0 +Kevin K. <kbknapp@gmail.com> +Does awesome things + +USAGE: + 02_apps[EXE] --two <VALUE> --one <VALUE> + +OPTIONS: + -h, --help Print help information + --one <VALUE> + --two <VALUE> + -V, --version Print version information + +$ 02_apps --version +MyApp 1.0 + +``` + +You can use `command!()` to fill these fields in from your `Cargo.toml` +file. **This requires the `cargo` feature flag.** + +[Example:](02_crate.rs) +```console +$ 02_crate --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 02_crate[EXE] --two <VALUE> --one <VALUE> + +OPTIONS: + -h, --help Print help information + --one <VALUE> + --two <VALUE> + -V, --version Print version information + +$ 02_crate --version +clap [..] + +``` + +You can use `Command` methods to change the application level behavior of clap. + +[Example:](02_app_settings.rs) +```console +$ 02_app_settings --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 02_app_settings[EXE] --two <VALUE> --one <VALUE> + +OPTIONS: + --two <VALUE> + --one <VALUE> + -h, --help Print help information + -V, --version Print version information + +$ 02_app_settings --one -1 --one -3 --two 10 +two: "10" +one: "-3" + +``` + +## Adding Arguments + +### Positionals + +You can have users specify values by their position on the command-line: + +[Example:](03_03_positional.rs) +```console +$ 03_03_positional --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_03_positional[EXE] [NAME] + +ARGS: + <NAME> + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_03_positional +NAME: None + +$ 03_03_positional bob +NAME: Some("bob") + +``` + +### Options + +You can name your arguments with a flag: +- Order doesn't matter +- They can be optional +- Intent is clearer + +[Example:](03_02_option.rs) +```console +$ 03_02_option --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_02_option[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -n, --name <NAME> + -V, --version Print version information + +$ 03_02_option +name: None + +$ 03_02_option --name bob +name: Some("bob") + +$ 03_02_option --name=bob +name: Some("bob") + +$ 03_02_option -n bob +name: Some("bob") + +$ 03_02_option -n=bob +name: Some("bob") + +$ 03_02_option -nbob +name: Some("bob") + +``` + +### Flags + +Flags can also be switches that can be on/off: + +[Example:](03_01_flag_bool.rs) +```console +$ 03_01_flag_bool --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_01_flag_bool[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -v, --verbose + -V, --version Print version information + +$ 03_01_flag_bool +verbose: false + +$ 03_01_flag_bool --verbose +verbose: true + +$ 03_01_flag_bool --verbose --verbose +? failed +error: The argument '--verbose' was provided more than once, but cannot be used multiple times + +USAGE: + 03_01_flag_bool[EXE] [OPTIONS] + +For more information try --help + +``` + +Or counted. + +[Example:](03_01_flag_count.rs) +```console +$ 03_01_flag_count --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_01_flag_count[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -v, --verbose + -V, --version Print version information + +$ 03_01_flag_count +verbose: 0 + +$ 03_01_flag_count --verbose +verbose: 1 + +$ 03_01_flag_count --verbose --verbose +verbose: 2 + +``` + +### Subcommands + +Subcommands are defined as `Command`s that get added via `Command::subcommand`. Each +instance of a Subcommand can have its own version, author(s), Args, and even its own +subcommands. + +[Example:](03_04_subcommands.rs) +```console +$ 03_04_subcommands help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_04_subcommands[EXE] <SUBCOMMAND> + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + add Adds files to myapp + help Print this message or the help of the given subcommand(s) + +$ 03_04_subcommands help add +03_04_subcommands[EXE]-add [..] +Adds files to myapp + +USAGE: + 03_04_subcommands[EXE] add [NAME] + +ARGS: + <NAME> + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_04_subcommands add bob +'myapp add' was used, name is: Some("bob") + +``` + +Because we set `Command::arg_required_else_help`: +```console +$ 03_04_subcommands +? failed +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_04_subcommands[EXE] <SUBCOMMAND> + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + add Adds files to myapp + help Print this message or the help of the given subcommand(s) + +``` + +Because we set `Command::propagate_version`: +```console +$ 03_04_subcommands --version +clap [..] + +$ 03_04_subcommands add --version +03_04_subcommands[EXE]-add [..] + +``` + +### Defaults + +We've previously showed that arguments can be `required` or optional. When +optional, you work with a `Option` and can `unwrap_or`. Alternatively, you can +set `Arg::default_value`. + +[Example:](03_05_default_values.rs) +```console +$ 03_05_default_values --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_05_default_values[EXE] [NAME] + +ARGS: + <NAME> [default: alice] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_05_default_values +NAME: "alice" + +$ 03_05_default_values bob +NAME: "bob" + +``` + +## Validation + +### Enumerated values + +If you have arguments of specific values you want to test for, you can use the +`Arg::possible_values()`. + +This allows you specify the valid values for that argument. If the user does not use one of +those specific values, they will receive a graceful exit with error message informing them +of the mistake, and what the possible valid values are + +[Example:](04_01_possible.rs) +```console +$ 04_01_possible --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_01_possible[EXE] <MODE> + +ARGS: + <MODE> What mode to run the program in [possible values: fast, slow] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_01_possible fast +Hare + +$ 04_01_possible slow +Tortoise + +$ 04_01_possible medium +? failed +error: "medium" isn't a valid value for '<MODE>' + [possible values: fast, slow] + +USAGE: + 04_01_possible[EXE] <MODE> + +For more information try --help + +``` + +When enabling the `derive` feature, you can use `ArgEnum` to take care of the boiler plate for you, giving the same results. + +[Example:](04_01_enum.rs) +```console +$ 04_01_enum --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_01_enum[EXE] <MODE> + +ARGS: + <MODE> What mode to run the program in [possible values: fast, slow] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_01_enum fast +Hare + +$ 04_01_enum slow +Tortoise + +$ 04_01_enum medium +? failed +error: "medium" isn't a valid value for '<MODE>' + [possible values: fast, slow] + +USAGE: + 04_01_enum[EXE] <MODE> + +For more information try --help + +``` + +### Validated values + +More generally, you can parse into any data type. + +[Example:](04_02_parse.rs) +```console +$ 04_02_parse --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_02_parse[EXE] <PORT> + +ARGS: + <PORT> Network port to use + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_02_parse 22 +PORT = 22 + +$ 04_02_parse foobar +? failed +error: Invalid value "foobar" for '<PORT>': invalid digit found in string + +For more information try --help + +``` + +A custom validator can be used to improve the error messages or provide additional validation: + +[Example:](04_02_validate.rs) +```console +$ 04_02_validate --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_02_validate[EXE] <PORT> + +ARGS: + <PORT> Network port to use + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_02_validate 22 +PORT = 22 + +$ 04_02_validate foobar +? failed +error: Invalid value "foobar" for '<PORT>': `foobar` isn't a port number + +For more information try --help + +$ 04_02_validate 0 +? failed +error: Invalid value "0" for '<PORT>': Port not in range 1-65535 + +For more information try --help + +``` + +### Argument Relations + +You can declare dependencies or conflicts between `Arg`s or even `ArgGroup`s. + +`ArgGroup`s make it easier to declare relations instead of having to list each +individually, or when you want a rule to apply "any but not all" arguments. + +Perhaps the most common use of `ArgGroup`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. + +[Example:](04_03_relations.rs) +```console +$ 04_03_relations --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_03_relations[EXE] [OPTIONS] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE] + +ARGS: + <INPUT_FILE> some regular input + +OPTIONS: + -c <CONFIG> + -h, --help Print help information + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --set-ver <VER> set version manually + --spec-in <SPEC_IN> some special input argument + -V, --version Print version information + +$ 04_03_relations +? failed +error: The following required arguments were not provided: + <--set-ver <VER>|--major|--minor|--patch> + +USAGE: + 04_03_relations[EXE] [OPTIONS] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE] + +For more information try --help + +$ 04_03_relations --major +Version: 2.2.3 + +$ 04_03_relations --major --minor +? failed +error: The argument '--major' cannot be used with '--minor' + +USAGE: + 04_03_relations[EXE] <--set-ver <VER>|--major|--minor|--patch> + +For more information try --help + +$ 04_03_relations --major -c config.toml +? failed +error: The following required arguments were not provided: + <INPUT_FILE|--spec-in <SPEC_IN>> + +USAGE: + 04_03_relations[EXE] -c <CONFIG> <--set-ver <VER>|--major|--minor|--patch> <INPUT_FILE|--spec-in <SPEC_IN>> + +For more information try --help + +$ 04_03_relations --major -c config.toml --spec-in input.txt +Version: 2.2.3 +Doing work using input input.txt and config config.toml + +``` + +### Custom Validation + +As a last resort, you can create custom errors with the basics of clap's formatting. + +[Example:](04_04_custom.rs) +```console +$ 04_04_custom --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +ARGS: + <INPUT_FILE> some regular input + +OPTIONS: + -c <CONFIG> + -h, --help Print help information + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --set-ver <VER> set version manually + --spec-in <SPEC_IN> some special input argument + -V, --version Print version information + +$ 04_04_custom +? failed +error: Can only modify one version field + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom --major +Version: 2.2.3 + +$ 04_04_custom --major --minor +? failed +error: Can only modify one version field + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom --major -c config.toml +? failed +Version: 2.2.3 +error: INPUT_FILE or --spec-in is required when using --config + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom --major -c config.toml --spec-in input.txt +Version: 2.2.3 +Doing work using input input.txt and config config.toml + +``` + +## Tips + +- For more complex demonstration of features, see our [examples](../README.md). +- Proactively check for bad `Command` configurations by calling `Command::debug_assert` in a test ([example](05_01_assert.rs)) + +## Contributing + +New example code: +- Please update the corresponding section in the [derive tutorial](../tutorial_derive/README.md) +- Building: They must be added to [Cargo.toml](../../Cargo.toml) with the appropriate `required-features`. +- Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax (generally they'll go in here). + +See also the general [CONTRIBUTING](../../CONTRIBUTING.md). diff --git a/third_party/rust/clap/examples/tutorial_derive/01_quick.rs b/third_party/rust/clap/examples/tutorial_derive/01_quick.rs new file mode 100644 index 0000000000..f840b8a9b2 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/01_quick.rs @@ -0,0 +1,68 @@ +use std::path::PathBuf; + +use clap::{Parser, Subcommand}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// Optional name to operate on + name: Option<String>, + + /// Sets a custom config file + #[clap(short, long, parse(from_os_str), value_name = "FILE")] + config: Option<PathBuf>, + + /// Turn debugging information on + #[clap(short, long, parse(from_occurrences))] + debug: usize, + + #[clap(subcommand)] + command: Option<Commands>, +} + +#[derive(Subcommand)] +enum Commands { + /// does testing things + Test { + /// lists test values + #[clap(short, long)] + list: bool, + }, +} + +fn main() { + let cli = Cli::parse(); + + // You can check the value provided by positional arguments, or option arguments + if let Some(name) = cli.name.as_deref() { + println!("Value for name: {}", name); + } + + if let Some(config_path) = cli.config.as_deref() { + println!("Value for config: {}", config_path.display()); + } + + // You can see how many times a particular flag or argument occurred + // Note, only flags can have multiple occurrences + match cli.debug { + 0 => println!("Debug mode is off"), + 1 => println!("Debug mode is kind of on"), + 2 => println!("Debug mode is on"), + _ => println!("Don't be crazy"), + } + + // You can check for the existence of subcommands, and if found use their + // matches just as you would the top level cmd + match &cli.command { + Some(Commands::Test { list }) => { + if *list { + println!("Printing testing lists..."); + } else { + println!("Not printing testing lists..."); + } + } + None => {} + } + + // Continued program logic goes here... +} diff --git a/third_party/rust/clap/examples/tutorial_derive/02_app_settings.rs b/third_party/rust/clap/examples/tutorial_derive/02_app_settings.rs new file mode 100644 index 0000000000..bccd353f60 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/02_app_settings.rs @@ -0,0 +1,20 @@ +use clap::{AppSettings, Parser}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +#[clap(args_override_self = true)] +#[clap(allow_negative_numbers = true)] +#[clap(global_setting(AppSettings::DeriveDisplayOrder))] +struct Cli { + #[clap(long)] + two: String, + #[clap(long)] + one: String, +} + +fn main() { + let cli = Cli::parse(); + + println!("two: {:?}", cli.two); + println!("one: {:?}", cli.one); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/02_apps.rs b/third_party/rust/clap/examples/tutorial_derive/02_apps.rs new file mode 100644 index 0000000000..442e928a9f --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/02_apps.rs @@ -0,0 +1,20 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(name = "MyApp")] +#[clap(author = "Kevin K. <kbknapp@gmail.com>")] +#[clap(version = "1.0")] +#[clap(about = "Does awesome things", long_about = None)] +struct Cli { + #[clap(long)] + two: String, + #[clap(long)] + one: String, +} + +fn main() { + let cli = Cli::parse(); + + println!("two: {:?}", cli.two); + println!("one: {:?}", cli.one); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/02_crate.rs b/third_party/rust/clap/examples/tutorial_derive/02_crate.rs new file mode 100644 index 0000000000..93f7888af3 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/02_crate.rs @@ -0,0 +1,17 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(long)] + two: String, + #[clap(long)] + one: String, +} + +fn main() { + let cli = Cli::parse(); + + println!("two: {:?}", cli.two); + println!("one: {:?}", cli.one); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/03_01_flag_bool.rs b/third_party/rust/clap/examples/tutorial_derive/03_01_flag_bool.rs new file mode 100644 index 0000000000..8b574b7481 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/03_01_flag_bool.rs @@ -0,0 +1,14 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(short, long)] + verbose: bool, +} + +fn main() { + let cli = Cli::parse(); + + println!("verbose: {:?}", cli.verbose); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/03_01_flag_count.rs b/third_party/rust/clap/examples/tutorial_derive/03_01_flag_count.rs new file mode 100644 index 0000000000..2ab883977a --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/03_01_flag_count.rs @@ -0,0 +1,14 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(short, long, parse(from_occurrences))] + verbose: usize, +} + +fn main() { + let cli = Cli::parse(); + + println!("verbose: {:?}", cli.verbose); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/03_02_option.rs b/third_party/rust/clap/examples/tutorial_derive/03_02_option.rs new file mode 100644 index 0000000000..b09aadf20d --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/03_02_option.rs @@ -0,0 +1,14 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(short, long)] + name: Option<String>, +} + +fn main() { + let cli = Cli::parse(); + + println!("name: {:?}", cli.name.as_deref()); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/03_03_positional.rs b/third_party/rust/clap/examples/tutorial_derive/03_03_positional.rs new file mode 100644 index 0000000000..f7850ddccf --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/03_03_positional.rs @@ -0,0 +1,13 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + name: Option<String>, +} + +fn main() { + let cli = Cli::parse(); + + println!("name: {:?}", cli.name.as_deref()); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/03_04_subcommands.rs b/third_party/rust/clap/examples/tutorial_derive/03_04_subcommands.rs new file mode 100644 index 0000000000..86cf444c21 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/03_04_subcommands.rs @@ -0,0 +1,27 @@ +use clap::{Parser, Subcommand}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +#[clap(propagate_version = true)] +struct Cli { + #[clap(subcommand)] + command: Commands, +} + +#[derive(Subcommand)] +enum Commands { + /// Adds files to myapp + Add { name: Option<String> }, +} + +fn main() { + let cli = Cli::parse(); + + // You can check for the existence of subcommands, and if found use their + // matches just as you would the top level cmd + match &cli.command { + Commands::Add { name } => { + println!("'myapp add' was used, name is: {:?}", name) + } + } +} diff --git a/third_party/rust/clap/examples/tutorial_derive/03_04_subcommands_alt.rs b/third_party/rust/clap/examples/tutorial_derive/03_04_subcommands_alt.rs new file mode 100644 index 0000000000..0a5b60682d --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/03_04_subcommands_alt.rs @@ -0,0 +1,32 @@ +use clap::{Args, Parser, Subcommand}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +#[clap(propagate_version = true)] +struct Cli { + #[clap(subcommand)] + command: Commands, +} + +#[derive(Subcommand)] +enum Commands { + /// Adds files to myapp + Add(Add), +} + +#[derive(Args)] +struct Add { + name: Option<String>, +} + +fn main() { + let cli = Cli::parse(); + + // You can check for the existence of subcommands, and if found use their + // matches just as you would the top level cmd + match &cli.command { + Commands::Add(name) => { + println!("'myapp add' was used, name is: {:?}", name.name) + } + } +} diff --git a/third_party/rust/clap/examples/tutorial_derive/03_05_default_values.rs b/third_party/rust/clap/examples/tutorial_derive/03_05_default_values.rs new file mode 100644 index 0000000000..af4532bbc7 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/03_05_default_values.rs @@ -0,0 +1,14 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(default_value_t = String::from("alice"))] + name: String, +} + +fn main() { + let cli = Cli::parse(); + + println!("name: {:?}", cli.name); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/04_01_enum.rs b/third_party/rust/clap/examples/tutorial_derive/04_01_enum.rs new file mode 100644 index 0000000000..3a2df391ff --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/04_01_enum.rs @@ -0,0 +1,28 @@ +use clap::{ArgEnum, Parser}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// What mode to run the program in + #[clap(arg_enum)] + mode: Mode, +} + +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ArgEnum)] +enum Mode { + Fast, + Slow, +} + +fn main() { + let cli = Cli::parse(); + + match cli.mode { + Mode::Fast => { + println!("Hare"); + } + Mode::Slow => { + println!("Tortoise"); + } + } +} diff --git a/third_party/rust/clap/examples/tutorial_derive/04_02_parse.rs b/third_party/rust/clap/examples/tutorial_derive/04_02_parse.rs new file mode 100644 index 0000000000..5f4cbadc04 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/04_02_parse.rs @@ -0,0 +1,15 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// Network port to use + #[clap(parse(try_from_str))] + port: usize, +} + +fn main() { + let cli = Cli::parse(); + + println!("PORT = {}", cli.port); +} diff --git a/third_party/rust/clap/examples/tutorial_derive/04_02_validate.rs b/third_party/rust/clap/examples/tutorial_derive/04_02_validate.rs new file mode 100644 index 0000000000..434f40c869 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/04_02_validate.rs @@ -0,0 +1,34 @@ +use std::ops::RangeInclusive; + +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// Network port to use + #[clap(parse(try_from_str=port_in_range))] + port: usize, +} + +fn main() { + let cli = Cli::parse(); + + println!("PORT = {}", cli.port); +} + +const PORT_RANGE: RangeInclusive<usize> = 1..=65535; + +fn port_in_range(s: &str) -> Result<usize, String> { + let port: usize = s + .parse() + .map_err(|_| format!("`{}` isn't a port number", s))?; + if PORT_RANGE.contains(&port) { + Ok(port) + } else { + Err(format!( + "Port not in range {}-{}", + PORT_RANGE.start(), + PORT_RANGE.end() + )) + } +} diff --git a/third_party/rust/clap/examples/tutorial_derive/04_03_relations.rs b/third_party/rust/clap/examples/tutorial_derive/04_03_relations.rs new file mode 100644 index 0000000000..f0e1e5913b --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/04_03_relations.rs @@ -0,0 +1,72 @@ +use clap::{ArgGroup, Parser}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +#[clap(group( + ArgGroup::new("vers") + .required(true) + .args(&["set-ver", "major", "minor", "patch"]), + ))] +struct Cli { + /// set version manually + #[clap(long, value_name = "VER")] + set_ver: Option<String>, + + /// auto inc major + #[clap(long)] + major: bool, + + /// auto inc minor + #[clap(long)] + minor: bool, + + /// auto inc patch + #[clap(long)] + patch: bool, + + /// some regular input + #[clap(group = "input")] + input_file: Option<String>, + + /// some special input argument + #[clap(long, group = "input")] + spec_in: Option<String>, + + #[clap(short, requires = "input")] + config: Option<String>, +} + +fn main() { + let cli = Cli::parse(); + + // Let's assume the old version 1.2.3 + let mut major = 1; + let mut minor = 2; + let mut patch = 3; + + // See if --set-ver was used to set the version manually + let version = if let Some(ver) = cli.set_ver.as_deref() { + ver.to_string() + } else { + // Increment the one requested (in a real program, we'd reset the lower numbers) + let (maj, min, pat) = (cli.major, cli.minor, cli.patch); + match (maj, min, pat) { + (true, _, _) => major += 1, + (_, true, _) => minor += 1, + (_, _, true) => patch += 1, + _ => unreachable!(), + }; + format!("{}.{}.{}", major, minor, patch) + }; + + println!("Version: {}", version); + + // Check for usage of -c + if let Some(config) = cli.config.as_deref() { + let input = cli + .input_file + .as_deref() + .unwrap_or_else(|| cli.spec_in.as_deref().unwrap()); + println!("Doing work using input {} and config {}", input, config); + } +} diff --git a/third_party/rust/clap/examples/tutorial_derive/04_04_custom.rs b/third_party/rust/clap/examples/tutorial_derive/04_04_custom.rs new file mode 100644 index 0000000000..a03345b829 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/04_04_custom.rs @@ -0,0 +1,92 @@ +use clap::{CommandFactory, ErrorKind, Parser}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// set version manually + #[clap(long, value_name = "VER")] + set_ver: Option<String>, + + /// auto inc major + #[clap(long)] + major: bool, + + /// auto inc minor + #[clap(long)] + minor: bool, + + /// auto inc patch + #[clap(long)] + patch: bool, + + /// some regular input + input_file: Option<String>, + + /// some special input argument + #[clap(long)] + spec_in: Option<String>, + + #[clap(short)] + config: Option<String>, +} + +fn main() { + let cli = Cli::parse(); + + // Let's assume the old version 1.2.3 + let mut major = 1; + let mut minor = 2; + let mut patch = 3; + + // See if --set-ver was used to set the version manually + let version = if let Some(ver) = cli.set_ver.as_deref() { + if cli.major || cli.minor || cli.patch { + let mut cmd = Cli::command(); + cmd.error( + ErrorKind::ArgumentConflict, + "Can't do relative and absolute version change", + ) + .exit(); + } + ver.to_string() + } else { + // Increment the one requested (in a real program, we'd reset the lower numbers) + let (maj, min, pat) = (cli.major, cli.minor, cli.patch); + match (maj, min, pat) { + (true, false, false) => major += 1, + (false, true, false) => minor += 1, + (false, false, true) => patch += 1, + _ => { + let mut cmd = Cli::command(); + cmd.error( + ErrorKind::ArgumentConflict, + "Can only modify one version field", + ) + .exit(); + } + }; + format!("{}.{}.{}", major, minor, patch) + }; + + println!("Version: {}", version); + + // Check for usage of -c + if let Some(config) = cli.config.as_deref() { + // todo: remove `#[allow(clippy::or_fun_call)]` lint when MSRV is bumped. + #[allow(clippy::or_fun_call)] + let input = cli + .input_file + .as_deref() + // 'or' is preferred to 'or_else' here since `Option::as_deref` is 'const' + .or(cli.spec_in.as_deref()) + .unwrap_or_else(|| { + let mut cmd = Cli::command(); + cmd.error( + ErrorKind::MissingRequiredArgument, + "INPUT_FILE or --spec-in is required when using --config", + ) + .exit() + }); + println!("Doing work using input {} and config {}", input, config); + } +} diff --git a/third_party/rust/clap/examples/tutorial_derive/05_01_assert.rs b/third_party/rust/clap/examples/tutorial_derive/05_01_assert.rs new file mode 100644 index 0000000000..12fdba9b92 --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/05_01_assert.rs @@ -0,0 +1,21 @@ +use clap::Parser; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + /// Network port to use + #[clap(parse(try_from_str))] + port: usize, +} + +fn main() { + let cli = Cli::parse(); + + println!("PORT = {}", cli.port); +} + +#[test] +fn verify_app() { + use clap::CommandFactory; + Cli::command().debug_assert() +} diff --git a/third_party/rust/clap/examples/tutorial_derive/README.md b/third_party/rust/clap/examples/tutorial_derive/README.md new file mode 100644 index 0000000000..706e76c09e --- /dev/null +++ b/third_party/rust/clap/examples/tutorial_derive/README.md @@ -0,0 +1,642 @@ +# Tutorial + +*Jump to [builder tutorial](../tutorial_builder/README.md)* + +1. [Quick Start](#quick-start) +2. [Configuring the Parser](#configuring-the-parser) +3. [Adding Arguments](#adding-arguments) + 1. [Positionals](#positionals) + 2. [Options](#options) + 3. [Flags](#flags) + 4. [Subcommands](#subcommands) + 5. [Defaults](#defaults) +4. Validation + 1. [Enumerated values](#enumerated-values) + 2. [Validated values](#validated-values) + 3. [Argument Relations](#argument-relations) + 4. [Custom Validation](#custom-validation) +5. [Tips](#tips) +6. [Contributing](#contributing) + +## Quick Start + +You can create an application declaratively with a `struct` and some +attributes. **This requires enabling the `derive` feature flag.** + +[Example:](01_quick.rs) +```console +$ 01_quick_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 01_quick_derive[EXE] [OPTIONS] [NAME] [SUBCOMMAND] + +ARGS: + <NAME> Optional name to operate on + +OPTIONS: + -c, --config <FILE> Sets a custom config file + -d, --debug Turn debugging information on + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + help Print this message or the help of the given subcommand(s) + test does testing things + +``` + +By default, the program does nothing: +```console +$ 01_quick_derive +Debug mode is off + +``` + +But you can mix and match the various features +```console +$ 01_quick_derive -dd test +Debug mode is on +Not printing testing lists... + +``` + +In addition to this tutorial, see the [derive reference](../derive_ref/README.md). + +## Configuring the Parser + +You use derive `Parser` the start building a parser. + +[Example:](02_apps.rs) +```console +$ 02_apps_derive --help +MyApp 1.0 +Kevin K. <kbknapp@gmail.com> +Does awesome things + +USAGE: + 02_apps_derive[EXE] --two <TWO> --one <ONE> + +OPTIONS: + -h, --help Print help information + --one <ONE> + --two <TWO> + -V, --version Print version information + +$ 02_apps_derive --version +MyApp 1.0 + +``` + +You can use `#[clap(author, version, about)]` attribute defaults to fill these fields in from your `Cargo.toml` file. + +[Example:](02_crate.rs) +```console +$ 02_crate_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 02_crate_derive[EXE] --two <TWO> --one <ONE> + +OPTIONS: + -h, --help Print help information + --one <ONE> + --two <TWO> + -V, --version Print version information + +$ 02_crate_derive --version +clap [..] + +``` + +You can use attributes to change the application level behavior of clap. Any `Command` builder function can be used as an attribute. + +[Example:](02_app_settings.rs) +```console +$ 02_app_settings_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 02_app_settings_derive[EXE] --two <TWO> --one <ONE> + +OPTIONS: + --two <TWO> + --one <ONE> + -h, --help Print help information + -V, --version Print version information + +$ 02_app_settings_derive --one -1 --one -3 --two 10 +two: "10" +one: "-3" + +``` + +## Adding Arguments + +### Positionals + +You can have users specify values by their position on the command-line: + +[Example:](03_03_positional.rs) +```console +$ 03_03_positional_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_03_positional_derive[EXE] [NAME] + +ARGS: + <NAME> + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_03_positional_derive +name: None + +$ 03_03_positional_derive bob +name: Some("bob") + +``` + +### Options + +You can name your arguments with a flag: +- Order doesn't matter +- They can be optional +- Intent is clearer + +The `#[clap(short = 'c')]` and `#[clap(long = "name")]` attributes that define +the flags are `Arg` methods that are derived from the field name when no value +is specified (`#[clap(short)]` and `#[clap(long)]`). + +[Example:](03_02_option.rs) +```console +$ 03_02_option_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_02_option_derive[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -n, --name <NAME> + -V, --version Print version information + +$ 03_02_option_derive +name: None + +$ 03_02_option_derive --name bob +name: Some("bob") + +$ 03_02_option_derive --name=bob +name: Some("bob") + +$ 03_02_option_derive -n bob +name: Some("bob") + +$ 03_02_option_derive -n=bob +name: Some("bob") + +$ 03_02_option_derive -nbob +name: Some("bob") + +``` + +### Flags + +Flags can also be switches that can be on/off. This is enabled via the +`#[clap(parse(from_flag)]` attribute though this is implied when the field is a +`bool`. + +[Example:](03_01_flag_bool.rs) +```console +$ 03_01_flag_bool_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_01_flag_bool_derive[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -v, --verbose + -V, --version Print version information + +$ 03_01_flag_bool_derive +verbose: false + +$ 03_01_flag_bool_derive --verbose +verbose: true + +$ 03_01_flag_bool_derive --verbose --verbose +? failed +error: The argument '--verbose' was provided more than once, but cannot be used multiple times + +USAGE: + 03_01_flag_bool_derive[EXE] [OPTIONS] + +For more information try --help + +``` + +Or counted with `#[clap(parse(from_occurrences))]`: + +[Example:](03_01_flag_count.rs) +```console +$ 03_01_flag_count_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_01_flag_count_derive[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -v, --verbose + -V, --version Print version information + +$ 03_01_flag_count_derive +verbose: 0 + +$ 03_01_flag_count_derive --verbose +verbose: 1 + +$ 03_01_flag_count_derive --verbose --verbose +verbose: 2 + +``` + +### Subcommands + +Subcommands are derived with `#[derive(Subcommand)]` and be added via `#[clap(subcommand)]` attribute. Each +instance of a Subcommand can have its own version, author(s), Args, and even its own +subcommands. + +[Example:](03_04_subcommands.rs) +```console +$ 03_04_subcommands_derive help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_04_subcommands_derive[EXE] <SUBCOMMAND> + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + add Adds files to myapp + help Print this message or the help of the given subcommand(s) + +$ 03_04_subcommands_derive help add +03_04_subcommands_derive[EXE]-add [..] +Adds files to myapp + +USAGE: + 03_04_subcommands_derive[EXE] add [NAME] + +ARGS: + <NAME> + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_04_subcommands_derive add bob +'myapp add' was used, name is: Some("bob") + +``` + +Above, we used a struct-variant to define the `add` subcommand. Alternatively, +you can +[use a struct for your subcommand's arguments](03_04_subcommands_alt.rs). + +Because we used `command: Commands` instead of `command: Option<Commands>`: +```console +$ 03_04_subcommands_derive +? failed +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_04_subcommands_derive[EXE] <SUBCOMMAND> + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + add Adds files to myapp + help Print this message or the help of the given subcommand(s) + +``` + +Because we added `#[clap(propagate_version = true)]`: +```console +$ 03_04_subcommands_derive --version +clap [..] + +$ 03_04_subcommands_derive add --version +03_04_subcommands_derive[EXE]-add [..] + +``` + +### Defaults + +We've previously showed that arguments can be `required` or optional. When +optional, you work with an `Option` and can `unwrap_or`. Alternatively, you can +set `#[clap(default_value_t)]`. + +[Example:](03_05_default_values.rs) +```console +$ 03_05_default_values_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_05_default_values_derive[EXE] [NAME] + +ARGS: + <NAME> [default: alice] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_05_default_values_derive +name: "alice" + +$ 03_05_default_values_derive bob +name: "bob" + +``` + +## Validation + +### Enumerated values + +If you have arguments of specific values you want to test for, you can derive +`ArgEnum`. + +This allows you specify the valid values for that argument. If the user does not use one of +those specific values, they will receive a graceful exit with error message informing them +of the mistake, and what the possible valid values are + +[Example:](04_01_enum.rs) +```console +$ 04_01_enum_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_01_enum_derive[EXE] <MODE> + +ARGS: + <MODE> What mode to run the program in [possible values: fast, slow] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_01_enum_derive fast +Hare + +$ 04_01_enum_derive slow +Tortoise + +$ 04_01_enum_derive medium +? failed +error: "medium" isn't a valid value for '<MODE>' + [possible values: fast, slow] + +USAGE: + 04_01_enum_derive[EXE] <MODE> + +For more information try --help + +``` + +### Validated values + +More generally, you can validate and parse into any data type. + +[Example:](04_02_parse.rs) +```console +$ 04_02_parse_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_02_parse_derive[EXE] <PORT> + +ARGS: + <PORT> Network port to use + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_02_parse_derive 22 +PORT = 22 + +$ 04_02_parse_derive foobar +? failed +error: Invalid value "foobar" for '<PORT>': invalid digit found in string + +For more information try --help + +``` + +A custom parser can be used to improve the error messages or provide additional validation: + +[Example:](04_02_validate.rs) +```console +$ 04_02_validate_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_02_validate_derive[EXE] <PORT> + +ARGS: + <PORT> Network port to use + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_02_validate_derive 22 +PORT = 22 + +$ 04_02_validate_derive foobar +? failed +error: Invalid value "foobar" for '<PORT>': `foobar` isn't a port number + +For more information try --help + +$ 04_02_validate_derive 0 +? failed +error: Invalid value "0" for '<PORT>': Port not in range 1-65535 + +For more information try --help + +``` + +### Argument Relations + +You can declare dependencies or conflicts between `Arg`s or even `ArgGroup`s. + +`ArgGroup`s make it easier to declare relations instead of having to list each +individually, or when you want a rule to apply "any but not all" arguments. + +Perhaps the most common use of `ArgGroup`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. + +[Example:](04_03_relations.rs) +```console +$ 04_03_relations_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_03_relations_derive[EXE] [OPTIONS] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE] + +ARGS: + <INPUT_FILE> some regular input + +OPTIONS: + -c <CONFIG> + -h, --help Print help information + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --set-ver <VER> set version manually + --spec-in <SPEC_IN> some special input argument + -V, --version Print version information + +$ 04_03_relations_derive +? failed +error: The following required arguments were not provided: + <--set-ver <VER>|--major|--minor|--patch> + +USAGE: + 04_03_relations_derive[EXE] [OPTIONS] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE] + +For more information try --help + +$ 04_03_relations_derive --major +Version: 2.2.3 + +$ 04_03_relations_derive --major --minor +? failed +error: The argument '--major' cannot be used with '--minor' + +USAGE: + 04_03_relations_derive[EXE] <--set-ver <VER>|--major|--minor|--patch> + +For more information try --help + +$ 04_03_relations_derive --major -c config.toml +? failed +error: The following required arguments were not provided: + <INPUT_FILE|--spec-in <SPEC_IN>> + +USAGE: + 04_03_relations_derive[EXE] -c <CONFIG> <--set-ver <VER>|--major|--minor|--patch> <INPUT_FILE|--spec-in <SPEC_IN>> + +For more information try --help + +$ 04_03_relations_derive --major -c config.toml --spec-in input.txt +Version: 2.2.3 +Doing work using input input.txt and config config.toml + +``` + +### Custom Validation + +As a last resort, you can create custom errors with the basics of clap's formatting. + +[Example:](04_04_custom.rs) +```console +$ 04_04_custom_derive --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_04_custom_derive[EXE] [OPTIONS] [INPUT_FILE] + +ARGS: + <INPUT_FILE> some regular input + +OPTIONS: + -c <CONFIG> + -h, --help Print help information + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --set-ver <VER> set version manually + --spec-in <SPEC_IN> some special input argument + -V, --version Print version information + +$ 04_04_custom_derive +? failed +error: Can only modify one version field + +USAGE: + clap [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom_derive --major +Version: 2.2.3 + +$ 04_04_custom_derive --major --minor +? failed +error: Can only modify one version field + +USAGE: + clap [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom_derive --major -c config.toml +? failed +Version: 2.2.3 +error: INPUT_FILE or --spec-in is required when using --config + +USAGE: + clap [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom_derive --major -c config.toml --spec-in input.txt +Version: 2.2.3 +Doing work using input input.txt and config config.toml + +``` + +## Tips + +- For more complex demonstration of features, see our [examples](../README.md). +- See the [derive reference](../derive_ref/README.md) to understand how to use + anything in the [builder API](https://docs.rs/clap/) in the derive API. +- Proactively check for bad `Command` configurations by calling `Command::debug_assert` in a test ([example](05_01_assert.rs)) + +## Contributing + +New example code: +- Please update the corresponding section in the [builder tutorial](../tutorial_builder/README.md) +- Building: They must be added to [Cargo.toml](../../Cargo.toml) with the appropriate `required-features`. +- Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax (generally they'll go in here). + +See also the general [CONTRIBUTING](../../CONTRIBUTING.md). diff --git a/third_party/rust/clap/examples/typed-derive.md b/third_party/rust/clap/examples/typed-derive.md new file mode 100644 index 0000000000..7c61f70d9a --- /dev/null +++ b/third_party/rust/clap/examples/typed-derive.md @@ -0,0 +1,86 @@ +*Jump to [source](typed-derive.rs)* + +**This requires enabling the `derive` feature flag.** + +Help: +```console +$ typed-derive --help +clap + +USAGE: + typed-derive[EXE] [OPTIONS] + +OPTIONS: + --bind <BIND> Handle IP addresses + -D <DEFINES> Hand-written parser for tuples + -h, --help Print help information + -I <DIR> Allow invalid UTF-8 paths + -O <OPTIMIZATION> Implicitly using `std::str::FromStr` + --sleep <SLEEP> Allow human-readable durations + +``` + +Optimization-level (number) +```console +$ typed-derive -O 1 +Args { optimization: Some(1), include: None, bind: None, sleep: None, defines: [] } + +$ typed-derive -O plaid +? failed +error: Invalid value "plaid" for '-O <OPTIMIZATION>': invalid digit found in string + +For more information try --help + +``` + +Include (path) +```console +$ typed-derive -I../hello +Args { optimization: None, include: Some("../hello"), bind: None, sleep: None, defines: [] } + +``` + +IP Address +```console +$ typed-derive --bind 192.0.0.1 +Args { optimization: None, include: None, bind: Some(192.0.0.1), sleep: None, defines: [] } + +$ typed-derive --bind localhost +? failed +error: Invalid value "localhost" for '--bind <BIND>': invalid IP address syntax + +For more information try --help + +``` + +Time +```console +$ typed-derive --sleep 10s +Args { optimization: None, include: None, bind: None, sleep: Some(Duration(10s)), defines: [] } + +$ typed-derive --sleep forever +? failed +error: Invalid value "forever" for '--sleep <SLEEP>': expected number at 0 + +For more information try --help + +``` + +Defines (key-value pairs) +```console +$ typed-derive -D Foo=10 -D Alice=30 +Args { optimization: None, include: None, bind: None, sleep: None, defines: [("Foo", 10), ("Alice", 30)] } + +$ typed-derive -D Foo +? failed +error: Invalid value "Foo" for '-D <DEFINES>': invalid KEY=value: no `=` found in `Foo` + +For more information try --help + +$ typed-derive -D Foo=Bar +? failed +error: Invalid value "Foo=Bar" for '-D <DEFINES>': invalid digit found in string + +For more information try --help + +``` diff --git a/third_party/rust/clap/examples/typed-derive.rs b/third_party/rust/clap/examples/typed-derive.rs new file mode 100644 index 0000000000..237bbe15e8 --- /dev/null +++ b/third_party/rust/clap/examples/typed-derive.rs @@ -0,0 +1,46 @@ +// Note: this requires the `derive` feature + +use clap::Parser; +use std::error::Error; + +#[derive(Parser, Debug)] +struct Args { + /// Implicitly using `std::str::FromStr` + #[clap(short = 'O')] + optimization: Option<usize>, + + /// Allow invalid UTF-8 paths + #[clap(short = 'I', parse(from_os_str), value_name = "DIR", value_hint = clap::ValueHint::DirPath)] + include: Option<std::path::PathBuf>, + + /// Handle IP addresses + #[clap(long)] + bind: Option<std::net::IpAddr>, + + /// Allow human-readable durations + #[clap(long)] + sleep: Option<humantime::Duration>, + + /// Hand-written parser for tuples + #[clap(short = 'D', parse(try_from_str = parse_key_val), multiple_occurrences(true))] + defines: Vec<(String, i32)>, +} + +/// Parse a single key-value pair +fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>> +where + T: std::str::FromStr, + T::Err: Error + Send + Sync + 'static, + U: std::str::FromStr, + U::Err: Error + Send + Sync + 'static, +{ + let pos = s + .find('=') + .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?; + Ok((s[..pos].parse()?, s[pos + 1..].parse()?)) +} + +fn main() { + let args = Args::parse(); + println!("{:?}", args); +} diff --git a/third_party/rust/clap/src/bin/stdio-fixture.rs b/third_party/rust/clap/src/bin/stdio-fixture.rs new file mode 100644 index 0000000000..e3f34b41a2 --- /dev/null +++ b/third_party/rust/clap/src/bin/stdio-fixture.rs @@ -0,0 +1,14 @@ +fn main() { + let cmd = clap::Command::new("stdio-fixture") + .version("1.0") + .long_version("1.0 - a2132c") + .arg_required_else_help(true) + .subcommand(clap::Command::new("more")) + .arg( + clap::Arg::new("verbose") + .long("verbose") + .help("log") + .long_help("more log"), + ); + cmd.get_matches(); +} diff --git a/third_party/rust/clap/src/build/app_settings.rs b/third_party/rust/clap/src/build/app_settings.rs new file mode 100644 index 0000000000..65d69ef825 --- /dev/null +++ b/third_party/rust/clap/src/build/app_settings.rs @@ -0,0 +1,765 @@ +#![allow(deprecated)] + +// Std +use std::ops::BitOr; +#[cfg(feature = "yaml")] +use std::str::FromStr; + +#[allow(unused)] +use crate::Arg; +#[allow(unused)] +use crate::Command; + +// Third party +use bitflags::bitflags; + +#[doc(hidden)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct AppFlags(Flags); + +impl Default for AppFlags { + fn default() -> Self { + AppFlags(Flags::COLOR_AUTO) + } +} + +/// Application level settings, which affect how [`Command`] operates +/// +/// **NOTE:** When these settings are used, they apply only to current command, and are *not* +/// propagated down or up through child or parent subcommands +/// +/// [`Command`]: crate::Command +#[derive(Debug, PartialEq, Copy, Clone)] +#[non_exhaustive] +pub enum AppSettings { + /// Deprecated, replaced with [`Command::ignore_errors`] + #[deprecated(since = "3.1.0", note = "Replaced with `Command::ignore_errors`")] + IgnoreErrors, + + /// Deprecated, replace + /// ```rust,no_run + /// let cmd = clap::Command::new("cmd") + /// .global_setting(clap::AppSettings::WaitOnError) + /// .arg(clap::arg!(--flag)); + /// let m = cmd.get_matches(); + /// ``` + /// with + /// ```rust + /// let cmd = clap::Command::new("cmd") + /// .arg(clap::arg!(--flag)); + /// let m = match cmd.try_get_matches() { + /// Ok(m) => m, + /// Err(err) => { + /// if err.use_stderr() { + /// let _ = err.print(); + /// + /// eprintln!("\nPress [ENTER] / [RETURN] to continue..."); + /// use std::io::BufRead; + /// let mut s = String::new(); + /// let i = std::io::stdin(); + /// i.lock().read_line(&mut s).unwrap(); + /// + /// std::process::exit(2); + /// } else { + /// let _ = err.print(); + /// std::process::exit(0); + /// } + /// } + /// }; + /// ``` + #[deprecated( + since = "3.1.0", + note = "See documentation for how to hand-implement this" + )] + WaitOnError, + + /// Deprecated, replaced with [`Command::allow_hyphen_values`] and + /// [`Arg::is_allow_hyphen_values_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::allow_hyphen_values` and `Arg::is_allow_hyphen_values_set`" + )] + AllowHyphenValues, + + /// Deprecated, replaced with [`Command::allow_negative_numbers`] and + /// [`Command::is_allow_negative_numbers_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::allow_negative_numbers` and `Command::is_allow_negative_numbers_set`" + )] + AllowNegativeNumbers, + + /// Deprecated, replaced with [`Command::args_override_self`] + #[deprecated(since = "3.1.0", note = "Replaced with `Command::args_override_self`")] + AllArgsOverrideSelf, + + /// Deprecated, replaced with [`Command::allow_missing_positional`] and + /// [`Command::is_allow_missing_positional_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::allow_missing_positional` and `Command::is_allow_missing_positional_set`" + )] + AllowMissingPositional, + + /// Deprecated, replaced with [`Command::trailing_var_arg`] and [`Command::is_trailing_var_arg_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::trailing_var_arg` and `Command::is_trailing_var_arg_set`" + )] + TrailingVarArg, + + /// Deprecated, replaced with [`Command::dont_delimit_trailing_values`] and + /// [`Command::is_dont_delimit_trailing_values_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::dont_delimit_trailing_values` and `Command::is_dont_delimit_trailing_values_set`" + )] + DontDelimitTrailingValues, + + /// Deprecated, replaced with [`Command::infer_long_args`] + #[deprecated(since = "3.1.0", note = "Replaced with `Command::infer_long_args`")] + InferLongArgs, + + /// Deprecated, replaced with [`Command::infer_subcommands`] + #[deprecated(since = "3.1.0", note = "Replaced with `Command::infer_subcommands`")] + InferSubcommands, + + /// Deprecated, replaced with [`Command::subcommand_required`] and + /// [`Command::is_subcommand_required_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::subcommand_required` and `Command::is_subcommand_required_set`" + )] + SubcommandRequired, + + /// Deprecated, replaced with [`Command::subcommand_required`] combined with + /// [`Command::arg_required_else_help`]. + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::subcommand_required` combined with `Command::arg_required_else_help`" + )] + SubcommandRequiredElseHelp, + + /// Deprecated, replaced with [`Command::allow_external_subcommands`] and + /// [`Command::is_allow_external_subcommands_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::allow_external_subcommands` and `Command::is_allow_external_subcommands_set`" + )] + AllowExternalSubcommands, + + /// Deprecated, replaced with [`Command::multicall`] and [`Command::is_multicall_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::multicall` and `Command::is_multicall_set`" + )] + #[cfg(feature = "unstable-multicall")] + Multicall, + + /// Deprecated, replaced with [`Command::allow_invalid_utf8_for_external_subcommands`] and [`Command::is_allow_invalid_utf8_for_external_subcommands_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::allow_invalid_utf8_for_external_subcommands` and `Command::is_allow_invalid_utf8_for_external_subcommands_set`" + )] + AllowInvalidUtf8ForExternalSubcommands, + + /// Deprecated, this is now the default + #[deprecated(since = "3.1.0", note = "This is now the default")] + UseLongFormatForHelpSubcommand, + + /// Deprecated, replaced with [`Command::subcommand_negates_reqs`] and + /// [`Command::is_subcommand_negates_reqs_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::subcommand_negates_reqs` and `Command::is_subcommand_negates_reqs_set`" + )] + SubcommandsNegateReqs, + + /// Deprecated, replaced with [`Command::args_conflicts_with_subcommands`] and + /// [`Command::is_args_conflicts_with_subcommands_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::args_conflicts_with_subcommands` and `Command::is_args_conflicts_with_subcommands_set`" + )] + ArgsNegateSubcommands, + + /// Deprecated, replaced with [`Command::subcommand_precedence_over_arg`] and + /// [`Command::is_subcommand_precedence_over_arg_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::subcommand_precedence_over_arg` and `Command::is_subcommand_precedence_over_arg_set`" + )] + SubcommandPrecedenceOverArg, + + /// Deprecated, replaced with [`Command::arg_required_else_help`] and + /// [`Command::is_arg_required_else_help_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::arg_required_else_help` and `Command::is_arg_required_else_help_set`" + )] + ArgRequiredElseHelp, + + /// Displays the arguments and [`subcommands`] in the help message in the order that they were + /// declared in, and not alphabetically which is the default. + /// + /// To override the declaration order, see [`Arg::display_order`] and [`Command::display_order`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, AppSettings}; + /// Command::new("myprog") + /// .global_setting(AppSettings::DeriveDisplayOrder) + /// .get_matches(); + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + /// [`Arg::display_order`]: crate::Arg::display_order + /// [`Command::display_order`]: crate::Command::display_order + DeriveDisplayOrder, + + /// Deprecated, replaced with [`Command::dont_collapse_args_in_usage`] and + /// [`Command::is_dont_collapse_args_in_usage_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::dont_collapse_args_in_usage` and `Command::is_dont_collapse_args_in_usage_set`" + )] + DontCollapseArgsInUsage, + + /// Deprecated, replaced with [`Command::next_line_help`] and [`Command::is_next_line_help_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::next_line_help` and `Command::is_next_line_help_set`" + )] + NextLineHelp, + + /// Deprecated, replaced with [`Command::disable_colored_help`] and + /// [`Command::is_disable_colored_help_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::disable_colored_help` and `Command::is_disable_colored_help_set`" + )] + DisableColoredHelp, + + /// Deprecated, replaced with [`Command::disable_help_flag`] and [`Command::is_disable_help_flag_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::disable_help_flag` and `Command::is_disable_help_flag_set`" + )] + DisableHelpFlag, + + /// Deprecated, replaced with [`Command::disable_help_subcommand`] and + /// [`Command::is_disable_help_subcommand_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::disable_help_subcommand` and `Command::is_disable_help_subcommand_set`" + )] + DisableHelpSubcommand, + + /// Deprecated, replaced with [`Command::disable_version_flag`] and + /// [`Command::is_disable_version_flag_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::disable_version_flag` and `Command::is_disable_version_flag_set`" + )] + DisableVersionFlag, + + /// Deprecated, replaced with [`Command::propagate_version`] and [`Command::is_propagate_version_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::propagate_version` and `Command::is_propagate_version_set`" + )] + PropagateVersion, + + /// Deprecated, replaced with [`Command::hide`] and [`Command::is_hide_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::hide` and `Command::is_hide_set`" + )] + Hidden, + + /// Deprecated, replaced with [`Command::hide_possible_values`] and + /// [`Arg::is_hide_possible_values_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Command::hide_possible_values` and `Arg::is_hide_possible_values_set`" + )] + HidePossibleValues, + + /// Deprecated, replaced with [`Command::help_expected`] + #[deprecated(since = "3.1.0", note = "Replaced with `Command::help_expected`")] + HelpExpected, + + /// Deprecated, replaced with [`Command::no_binary_name`] + #[deprecated(since = "3.1.0", note = "Replaced with `Command::no_binary_name`")] + NoBinaryName, + + /// Treat the auto-generated `-h, --help` flags like any other flag, and *not* print the help + /// message. + /// + /// This allows one to handle printing of the help message manually. + /// + /// ```rust + /// # use clap::{Command, AppSettings}; + /// let result = Command::new("myprog") + /// .setting(AppSettings::NoAutoHelp) + /// .try_get_matches_from("myprog --help".split(" ")); + /// + /// // Normally, if `--help` is used clap prints the help message and returns an + /// // ErrorKind::DisplayHelp + /// // + /// // However, `--help` was treated like a normal flag + /// + /// assert!(result.is_ok()); + /// assert!(result.unwrap().is_present("help")); + /// ``` + NoAutoHelp, + + /// Treat the auto-generated `-V, --version` flags like any other flag, and + /// *not* print the version message. + /// + /// This allows one to handle printing of the version message manually. + /// + /// ```rust + /// # use clap::{Command, AppSettings}; + /// let result = Command::new("myprog") + /// .version("3.0") + /// .setting(AppSettings::NoAutoVersion) + /// .try_get_matches_from("myprog --version".split(" ")); + /// + /// // Normally, if `--version` is used clap prints the version message and returns an + /// // ErrorKind::DisplayVersion + /// // + /// // However, `--version` was treated like a normal flag + /// + /// assert!(result.is_ok()); + /// assert!(result.unwrap().is_present("version")); + /// ``` + NoAutoVersion, + + /// Deprecated, replaced with [`AppSettings::AllowHyphenValues`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `AppSettings::AllowHyphenValues`" + )] + #[doc(hidden)] + AllowLeadingHyphen, + + /// Deprecated, this is now the default, see [`AppSettings::AllowInvalidUtf8ForExternalSubcommands`] and [`ArgSettings::AllowInvalidUtf8`][crate::ArgSettings::AllowInvalidUtf8] for the opposite. + #[deprecated( + since = "3.0.0", + note = "This is now the default see `AppSettings::AllowInvalidUtf8ForExternalSubcommands` and `ArgSettings::AllowInvalidUtf8` for the opposite." + )] + #[doc(hidden)] + StrictUtf8, + + /// Deprecated, this is now the default + #[deprecated(since = "3.0.0", note = "This is now the default")] + #[doc(hidden)] + UnifiedHelpMessage, + + /// Deprecated, this is now the default + #[deprecated(since = "3.0.0", note = "This is now the default")] + #[doc(hidden)] + ColoredHelp, + + /// Deprecated, see [`Command::color`][crate::Command::color] + #[deprecated(since = "3.0.0", note = "Replaced with `Command::color`")] + #[doc(hidden)] + ColorAuto, + + /// Deprecated, replaced with [`Command::color`][crate::Command::color] + #[deprecated(since = "3.0.0", note = "Replaced with `Command::color`")] + #[doc(hidden)] + ColorAlways, + + /// Deprecated, replaced with [`Command::color`][crate::Command::color] + #[deprecated(since = "3.0.0", note = "Replaced with `Command::color`")] + #[doc(hidden)] + ColorNever, + + /// Deprecated, replaced with [`AppSettings::DisableHelpFlag`] + #[deprecated(since = "3.0.0", note = "Replaced with `AppSettings::DisableHelpFlag`")] + #[doc(hidden)] + DisableHelpFlags, + + /// Deprecated, replaced with [`AppSettings::DisableVersionFlag`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `AppSettings::DisableVersionFlag`" + )] + #[doc(hidden)] + DisableVersion, + + /// Deprecated, replaced with [`AppSettings::PropagateVersion`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `AppSettings::PropagateVersion`" + )] + #[doc(hidden)] + GlobalVersion, + + /// Deprecated, replaced with [`AppSettings::HidePossibleValues`] + #[deprecated( + since = "3.0.0", + note = "Replaced with AppSettings::HidePossibleValues" + )] + #[doc(hidden)] + HidePossibleValuesInHelp, + + /// Deprecated, this is now the default + #[deprecated(since = "3.0.0", note = "This is now the default")] + #[doc(hidden)] + UnifiedHelp, + + /// If the cmd is already built, used for caching. + #[doc(hidden)] + Built, + + /// If the cmd's bin name is already built, used for caching. + #[doc(hidden)] + BinNameBuilt, +} + +bitflags! { + struct Flags: u64 { + const SC_NEGATE_REQS = 1; + const SC_REQUIRED = 1 << 1; + const ARG_REQUIRED_ELSE_HELP = 1 << 2; + const PROPAGATE_VERSION = 1 << 3; + const DISABLE_VERSION_FOR_SC = 1 << 4; + const WAIT_ON_ERROR = 1 << 6; + const SC_REQUIRED_ELSE_HELP = 1 << 7; + const NO_AUTO_HELP = 1 << 8; + const NO_AUTO_VERSION = 1 << 9; + const DISABLE_VERSION_FLAG = 1 << 10; + const HIDDEN = 1 << 11; + const TRAILING_VARARG = 1 << 12; + const NO_BIN_NAME = 1 << 13; + const ALLOW_UNK_SC = 1 << 14; + const SC_UTF8_NONE = 1 << 15; + const LEADING_HYPHEN = 1 << 16; + const NO_POS_VALUES = 1 << 17; + const NEXT_LINE_HELP = 1 << 18; + const DERIVE_DISP_ORDER = 1 << 19; + const DISABLE_COLORED_HELP = 1 << 20; + const COLOR_ALWAYS = 1 << 21; + const COLOR_AUTO = 1 << 22; + const COLOR_NEVER = 1 << 23; + const DONT_DELIM_TRAIL = 1 << 24; + const ALLOW_NEG_NUMS = 1 << 25; + const DISABLE_HELP_SC = 1 << 27; + const DONT_COLLAPSE_ARGS = 1 << 28; + const ARGS_NEGATE_SCS = 1 << 29; + const PROPAGATE_VALS_DOWN = 1 << 30; + const ALLOW_MISSING_POS = 1 << 31; + const TRAILING_VALUES = 1 << 32; + const BUILT = 1 << 33; + const BIN_NAME_BUILT = 1 << 34; + const VALID_ARG_FOUND = 1 << 35; + const INFER_SUBCOMMANDS = 1 << 36; + const CONTAINS_LAST = 1 << 37; + const ARGS_OVERRIDE_SELF = 1 << 38; + const HELP_REQUIRED = 1 << 39; + const SUBCOMMAND_PRECEDENCE_OVER_ARG = 1 << 40; + const DISABLE_HELP_FLAG = 1 << 41; + const USE_LONG_FORMAT_FOR_HELP_SC = 1 << 42; + const INFER_LONG_ARGS = 1 << 43; + const IGNORE_ERRORS = 1 << 44; + #[cfg(feature = "unstable-multicall")] + const MULTICALL = 1 << 45; + const NO_OP = 0; + } +} + +impl_settings! { AppSettings, AppFlags, + ArgRequiredElseHelp + => Flags::ARG_REQUIRED_ELSE_HELP, + SubcommandPrecedenceOverArg + => Flags::SUBCOMMAND_PRECEDENCE_OVER_ARG, + ArgsNegateSubcommands + => Flags::ARGS_NEGATE_SCS, + AllowExternalSubcommands + => Flags::ALLOW_UNK_SC, + StrictUtf8 + => Flags::NO_OP, + AllowInvalidUtf8ForExternalSubcommands + => Flags::SC_UTF8_NONE, + AllowHyphenValues + => Flags::LEADING_HYPHEN, + AllowLeadingHyphen + => Flags::LEADING_HYPHEN, + AllowNegativeNumbers + => Flags::ALLOW_NEG_NUMS, + AllowMissingPositional + => Flags::ALLOW_MISSING_POS, + UnifiedHelpMessage + => Flags::NO_OP, + ColoredHelp + => Flags::NO_OP, + ColorAlways + => Flags::COLOR_ALWAYS, + ColorAuto + => Flags::COLOR_AUTO, + ColorNever + => Flags::COLOR_NEVER, + DontDelimitTrailingValues + => Flags::DONT_DELIM_TRAIL, + DontCollapseArgsInUsage + => Flags::DONT_COLLAPSE_ARGS, + DeriveDisplayOrder + => Flags::DERIVE_DISP_ORDER, + DisableColoredHelp + => Flags::DISABLE_COLORED_HELP, + DisableHelpSubcommand + => Flags::DISABLE_HELP_SC, + DisableHelpFlag + => Flags::DISABLE_HELP_FLAG, + DisableHelpFlags + => Flags::DISABLE_HELP_FLAG, + DisableVersionFlag + => Flags::DISABLE_VERSION_FLAG, + DisableVersion + => Flags::DISABLE_VERSION_FLAG, + PropagateVersion + => Flags::PROPAGATE_VERSION, + GlobalVersion + => Flags::PROPAGATE_VERSION, + HidePossibleValues + => Flags::NO_POS_VALUES, + HidePossibleValuesInHelp + => Flags::NO_POS_VALUES, + HelpExpected + => Flags::HELP_REQUIRED, + Hidden + => Flags::HIDDEN, + #[cfg(feature = "unstable-multicall")] + Multicall + => Flags::MULTICALL, + NoAutoHelp + => Flags::NO_AUTO_HELP, + NoAutoVersion + => Flags::NO_AUTO_VERSION, + NoBinaryName + => Flags::NO_BIN_NAME, + SubcommandsNegateReqs + => Flags::SC_NEGATE_REQS, + SubcommandRequired + => Flags::SC_REQUIRED, + SubcommandRequiredElseHelp + => Flags::SC_REQUIRED_ELSE_HELP, + UseLongFormatForHelpSubcommand + => Flags::USE_LONG_FORMAT_FOR_HELP_SC, + TrailingVarArg + => Flags::TRAILING_VARARG, + UnifiedHelp => Flags::NO_OP, + NextLineHelp + => Flags::NEXT_LINE_HELP, + IgnoreErrors + => Flags::IGNORE_ERRORS, + WaitOnError + => Flags::WAIT_ON_ERROR, + Built + => Flags::BUILT, + BinNameBuilt + => Flags::BIN_NAME_BUILT, + InferSubcommands + => Flags::INFER_SUBCOMMANDS, + AllArgsOverrideSelf + => Flags::ARGS_OVERRIDE_SELF, + InferLongArgs + => Flags::INFER_LONG_ARGS +} + +/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? +#[cfg(feature = "yaml")] +impl FromStr for AppSettings { + type Err = String; + fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> { + #[allow(deprecated)] + #[allow(unreachable_patterns)] + match &*s.to_ascii_lowercase() { + "argrequiredelsehelp" => Ok(AppSettings::ArgRequiredElseHelp), + "subcommandprecedenceoverarg" => Ok(AppSettings::SubcommandPrecedenceOverArg), + "argsnegatesubcommands" => Ok(AppSettings::ArgsNegateSubcommands), + "allowexternalsubcommands" => Ok(AppSettings::AllowExternalSubcommands), + "strictutf8" => Ok(AppSettings::StrictUtf8), + "allowinvalidutf8forexternalsubcommands" => { + Ok(AppSettings::AllowInvalidUtf8ForExternalSubcommands) + } + "allowhyphenvalues" => Ok(AppSettings::AllowHyphenValues), + "allowleadinghyphen" => Ok(AppSettings::AllowLeadingHyphen), + "allownegativenumbers" => Ok(AppSettings::AllowNegativeNumbers), + "allowmissingpositional" => Ok(AppSettings::AllowMissingPositional), + "unifiedhelpmessage" => Ok(AppSettings::UnifiedHelpMessage), + "coloredhelp" => Ok(AppSettings::ColoredHelp), + "coloralways" => Ok(AppSettings::ColorAlways), + "colorauto" => Ok(AppSettings::ColorAuto), + "colornever" => Ok(AppSettings::ColorNever), + "dontdelimittrailingvalues" => Ok(AppSettings::DontDelimitTrailingValues), + "dontcollapseargsinusage" => Ok(AppSettings::DontCollapseArgsInUsage), + "derivedisplayorder" => Ok(AppSettings::DeriveDisplayOrder), + "disablecoloredhelp" => Ok(AppSettings::DisableColoredHelp), + "disablehelpsubcommand" => Ok(AppSettings::DisableHelpSubcommand), + "disablehelpflag" => Ok(AppSettings::DisableHelpFlag), + "disablehelpflags" => Ok(AppSettings::DisableHelpFlags), + "disableversionflag" => Ok(AppSettings::DisableVersionFlag), + "disableversion" => Ok(AppSettings::DisableVersion), + "propagateversion" => Ok(AppSettings::PropagateVersion), + "propagateversion" => Ok(AppSettings::GlobalVersion), + "hidepossiblevalues" => Ok(AppSettings::HidePossibleValues), + "hidepossiblevaluesinhelp" => Ok(AppSettings::HidePossibleValuesInHelp), + "helpexpected" => Ok(AppSettings::HelpExpected), + "hidden" => Ok(AppSettings::Hidden), + "noautohelp" => Ok(AppSettings::NoAutoHelp), + "noautoversion" => Ok(AppSettings::NoAutoVersion), + "nobinaryname" => Ok(AppSettings::NoBinaryName), + "subcommandsnegatereqs" => Ok(AppSettings::SubcommandsNegateReqs), + "subcommandrequired" => Ok(AppSettings::SubcommandRequired), + "subcommandrequiredelsehelp" => Ok(AppSettings::SubcommandRequiredElseHelp), + "uselongformatforhelpsubcommand" => Ok(AppSettings::UseLongFormatForHelpSubcommand), + "trailingvararg" => Ok(AppSettings::TrailingVarArg), + "unifiedhelp" => Ok(AppSettings::UnifiedHelp), + "nextlinehelp" => Ok(AppSettings::NextLineHelp), + "ignoreerrors" => Ok(AppSettings::IgnoreErrors), + "waitonerror" => Ok(AppSettings::WaitOnError), + "built" => Ok(AppSettings::Built), + "binnamebuilt" => Ok(AppSettings::BinNameBuilt), + "infersubcommands" => Ok(AppSettings::InferSubcommands), + "allargsoverrideself" => Ok(AppSettings::AllArgsOverrideSelf), + "inferlongargs" => Ok(AppSettings::InferLongArgs), + _ => Err(format!("unknown AppSetting: `{}`", s)), + } + } +} + +#[cfg(test)] +mod test { + #[allow(clippy::cognitive_complexity)] + #[test] + #[cfg(feature = "yaml")] + fn app_settings_fromstr() { + use super::AppSettings; + + assert_eq!( + "disablehelpflag".parse::<AppSettings>().unwrap(), + AppSettings::DisableHelpFlag + ); + assert_eq!( + "argsnegatesubcommands".parse::<AppSettings>().unwrap(), + AppSettings::ArgsNegateSubcommands + ); + assert_eq!( + "argrequiredelsehelp".parse::<AppSettings>().unwrap(), + AppSettings::ArgRequiredElseHelp + ); + assert_eq!( + "subcommandprecedenceoverarg" + .parse::<AppSettings>() + .unwrap(), + AppSettings::SubcommandPrecedenceOverArg + ); + assert_eq!( + "allowexternalsubcommands".parse::<AppSettings>().unwrap(), + AppSettings::AllowExternalSubcommands + ); + assert_eq!( + "allowinvalidutf8forexternalsubcommands" + .parse::<AppSettings>() + .unwrap(), + AppSettings::AllowInvalidUtf8ForExternalSubcommands + ); + assert_eq!( + "allowhyphenvalues".parse::<AppSettings>().unwrap(), + AppSettings::AllowHyphenValues + ); + assert_eq!( + "allownegativenumbers".parse::<AppSettings>().unwrap(), + AppSettings::AllowNegativeNumbers + ); + assert_eq!( + "disablehelpsubcommand".parse::<AppSettings>().unwrap(), + AppSettings::DisableHelpSubcommand + ); + assert_eq!( + "disableversionflag".parse::<AppSettings>().unwrap(), + AppSettings::DisableVersionFlag + ); + assert_eq!( + "dontcollapseargsinusage".parse::<AppSettings>().unwrap(), + AppSettings::DontCollapseArgsInUsage + ); + assert_eq!( + "dontdelimittrailingvalues".parse::<AppSettings>().unwrap(), + AppSettings::DontDelimitTrailingValues + ); + assert_eq!( + "derivedisplayorder".parse::<AppSettings>().unwrap(), + AppSettings::DeriveDisplayOrder + ); + assert_eq!( + "disablecoloredhelp".parse::<AppSettings>().unwrap(), + AppSettings::DisableColoredHelp + ); + assert_eq!( + "propagateversion".parse::<AppSettings>().unwrap(), + AppSettings::PropagateVersion + ); + assert_eq!( + "hidden".parse::<AppSettings>().unwrap(), + AppSettings::Hidden + ); + assert_eq!( + "hidepossiblevalues".parse::<AppSettings>().unwrap(), + AppSettings::HidePossibleValues + ); + assert_eq!( + "helpexpected".parse::<AppSettings>().unwrap(), + AppSettings::HelpExpected + ); + assert_eq!( + "nobinaryname".parse::<AppSettings>().unwrap(), + AppSettings::NoBinaryName + ); + assert_eq!( + "nextlinehelp".parse::<AppSettings>().unwrap(), + AppSettings::NextLineHelp + ); + assert_eq!( + "subcommandsnegatereqs".parse::<AppSettings>().unwrap(), + AppSettings::SubcommandsNegateReqs + ); + assert_eq!( + "subcommandrequired".parse::<AppSettings>().unwrap(), + AppSettings::SubcommandRequired + ); + assert_eq!( + "subcommandrequiredelsehelp".parse::<AppSettings>().unwrap(), + AppSettings::SubcommandRequiredElseHelp + ); + assert_eq!( + "uselongformatforhelpsubcommand" + .parse::<AppSettings>() + .unwrap(), + AppSettings::UseLongFormatForHelpSubcommand + ); + assert_eq!( + "trailingvararg".parse::<AppSettings>().unwrap(), + AppSettings::TrailingVarArg + ); + assert_eq!( + "waitonerror".parse::<AppSettings>().unwrap(), + AppSettings::WaitOnError + ); + assert_eq!("built".parse::<AppSettings>().unwrap(), AppSettings::Built); + assert_eq!( + "binnamebuilt".parse::<AppSettings>().unwrap(), + AppSettings::BinNameBuilt + ); + assert_eq!( + "infersubcommands".parse::<AppSettings>().unwrap(), + AppSettings::InferSubcommands + ); + assert!("hahahaha".parse::<AppSettings>().is_err()); + } +} diff --git a/third_party/rust/clap/src/build/arg.rs b/third_party/rust/clap/src/build/arg.rs new file mode 100644 index 0000000000..9fdf2a1cff --- /dev/null +++ b/third_party/rust/clap/src/build/arg.rs @@ -0,0 +1,5545 @@ +#![allow(deprecated)] + +// Std +use std::{ + borrow::Cow, + cmp::{Ord, Ordering}, + error::Error, + ffi::OsStr, + fmt::{self, Display, Formatter}, + str, + sync::{Arc, Mutex}, +}; +#[cfg(feature = "env")] +use std::{env, ffi::OsString}; + +#[cfg(feature = "yaml")] +use yaml_rust::Yaml; + +// Internal +use crate::build::usage_parser::UsageParser; +use crate::build::ArgPredicate; +use crate::util::{Id, Key}; +use crate::PossibleValue; +use crate::ValueHint; +use crate::INTERNAL_ERROR_MSG; +use crate::{ArgFlags, ArgSettings}; + +#[cfg(feature = "regex")] +use crate::build::RegexRef; + +/// The abstract representation of a command line argument. Used to set all the options and +/// relationships that define a valid argument for the program. +/// +/// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options +/// manually, or using a usage string which is far less verbose but has fewer options. You can also +/// use a combination of the two methods to achieve the best of both worlds. +/// +/// - [Basic API][crate::Arg#basic-api] +/// - [Value Handling][crate::Arg#value-handling] +/// - [Help][crate::Arg#help-1] +/// - [Advanced Argument Relations][crate::Arg#advanced-argument-relations] +/// - [Reflection][crate::Arg#reflection] +/// +/// # Examples +/// +/// ```rust +/// # use clap::{Arg, arg}; +/// // Using the traditional builder pattern and setting each option manually +/// let cfg = Arg::new("config") +/// .short('c') +/// .long("config") +/// .takes_value(true) +/// .value_name("FILE") +/// .help("Provides a config file to myprog"); +/// // Using a usage string (setting a similar argument to the one above) +/// let input = arg!(-i --input <FILE> "Provides an input file to the program"); +/// ``` +#[allow(missing_debug_implementations)] +#[derive(Default, Clone)] +pub struct Arg<'help> { + pub(crate) id: Id, + pub(crate) provider: ArgProvider, + pub(crate) name: &'help str, + pub(crate) help: Option<&'help str>, + pub(crate) long_help: Option<&'help str>, + pub(crate) blacklist: Vec<Id>, + pub(crate) settings: ArgFlags, + pub(crate) overrides: Vec<Id>, + pub(crate) groups: Vec<Id>, + pub(crate) requires: Vec<(ArgPredicate<'help>, Id)>, + pub(crate) r_ifs: Vec<(Id, &'help str)>, + pub(crate) r_ifs_all: Vec<(Id, &'help str)>, + pub(crate) r_unless: Vec<Id>, + pub(crate) r_unless_all: Vec<Id>, + pub(crate) short: Option<char>, + pub(crate) long: Option<&'help str>, + pub(crate) aliases: Vec<(&'help str, bool)>, // (name, visible) + pub(crate) short_aliases: Vec<(char, bool)>, // (name, visible) + pub(crate) disp_ord: DisplayOrder, + pub(crate) possible_vals: Vec<PossibleValue<'help>>, + pub(crate) val_names: Vec<&'help str>, + pub(crate) num_vals: Option<usize>, + pub(crate) max_occurs: Option<usize>, + pub(crate) max_vals: Option<usize>, + pub(crate) min_vals: Option<usize>, + pub(crate) validator: Option<Arc<Mutex<Validator<'help>>>>, + pub(crate) validator_os: Option<Arc<Mutex<ValidatorOs<'help>>>>, + pub(crate) val_delim: Option<char>, + pub(crate) default_vals: Vec<&'help OsStr>, + pub(crate) default_vals_ifs: Vec<(Id, ArgPredicate<'help>, Option<&'help OsStr>)>, + pub(crate) default_missing_vals: Vec<&'help OsStr>, + #[cfg(feature = "env")] + pub(crate) env: Option<(&'help OsStr, Option<OsString>)>, + pub(crate) terminator: Option<&'help str>, + pub(crate) index: Option<usize>, + pub(crate) help_heading: Option<Option<&'help str>>, + pub(crate) value_hint: ValueHint, +} + +/// # Basic API +impl<'help> Arg<'help> { + /// Create a new [`Arg`] with a unique name. + /// + /// The name is used to check whether or not the argument was used at + /// runtime, get values, set relationships with other args, etc.. + /// + /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::takes_value(true)`]) + /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also + /// be displayed when the user prints the usage/help information of the program. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("config") + /// # ; + /// ``` + /// [`Arg::takes_value(true)`]: Arg::takes_value() + pub fn new<S: Into<&'help str>>(n: S) -> Self { + Arg::default().name(n) + } + + /// Set the identifier used for referencing this argument in the clap API. + /// + /// See [`Arg::new`] for more details. + #[must_use] + pub fn id<S: Into<&'help str>>(mut self, n: S) -> Self { + let name = n.into(); + self.id = Id::from(&*name); + self.name = name; + self + } + + /// Deprecated, replaced with [`Arg::id`] + #[deprecated(since = "3.1.0", note = "Replaced with `Arg::id`")] + pub fn name<S: Into<&'help str>>(self, n: S) -> Self { + self.id(n) + } + + /// Sets the short version of the argument without the preceding `-`. + /// + /// By default `V` and `h` are used by the auto-generated `version` and `help` arguments, + /// respectively. You may use the uppercase `V` or lowercase `h` for your own arguments, in + /// which case `clap` simply will not assign those to the auto-generated + /// `version` or `help` arguments. + /// + /// # Examples + /// + /// When calling `short`, use a single valid UTF-8 character which will allow using the + /// argument via a single hyphen (`-`) such as `-c`: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("config") + /// .short('c')) + /// .get_matches_from(vec![ + /// "prog", "-c" + /// ]); + /// + /// assert!(m.is_present("config")); + /// ``` + #[inline] + #[must_use] + pub fn short(mut self, s: char) -> Self { + assert!(s != '-', "short option name cannot be `-`"); + + self.short = Some(s); + self + } + + /// Sets the long version of the argument without the preceding `--`. + /// + /// By default `version` and `help` are used by the auto-generated `version` and `help` + /// arguments, respectively. You may use the word `version` or `help` for the long form of your + /// own arguments, in which case `clap` simply will not assign those to the auto-generated + /// `version` or `help` arguments. + /// + /// **NOTE:** Any leading `-` characters will be stripped + /// + /// # Examples + /// + /// To set `long` use a word containing valid UTF-8. If you supply a double leading + /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however, + /// will *not* be stripped (i.e. `config-file` is allowed). + /// + /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config` + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config")) + /// .get_matches_from(vec![ + /// "prog", "--config" + /// ]); + /// + /// assert!(m.is_present("cfg")); + /// ``` + #[inline] + #[must_use] + pub fn long(mut self, l: &'help str) -> Self { + #[cfg(feature = "unstable-v4")] + { + self.long = Some(l); + } + #[cfg(not(feature = "unstable-v4"))] + { + self.long = Some(l.trim_start_matches(|c| c == '-')); + } + self + } + + /// Add an alias, which functions as a hidden long flag. + /// + /// This is more efficient, and easier than creating multiple hidden arguments as one only + /// needs to check for the existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .alias("alias") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--alias", "cool" + /// ]); + /// assert!(m.is_present("test")); + /// assert_eq!(m.value_of("test"), Some("cool")); + /// ``` + #[must_use] + pub fn alias<S: Into<&'help str>>(mut self, name: S) -> Self { + self.aliases.push((name.into(), false)); + self + } + + /// Add an alias, which functions as a hidden short flag. + /// + /// This is more efficient, and easier than creating multiple hidden arguments as one only + /// needs to check for the existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .short('t') + /// .short_alias('e') + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "-e", "cool" + /// ]); + /// assert!(m.is_present("test")); + /// assert_eq!(m.value_of("test"), Some("cool")); + /// ``` + #[must_use] + pub fn short_alias(mut self, name: char) -> Self { + assert!(name != '-', "short alias name cannot be `-`"); + + self.short_aliases.push((name, false)); + self + } + + /// Add aliases, which function as hidden long flags. + /// + /// This is more efficient, and easier than creating multiple hidden subcommands as one only + /// needs to check for the existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .aliases(&["do-stuff", "do-tests", "tests"]) + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec![ + /// "prog", "--do-tests" + /// ]); + /// assert!(m.is_present("test")); + /// ``` + #[must_use] + pub fn aliases(mut self, names: &[&'help str]) -> Self { + self.aliases.extend(names.iter().map(|&x| (x, false))); + self + } + + /// Add aliases, which functions as a hidden short flag. + /// + /// This is more efficient, and easier than creating multiple hidden subcommands as one only + /// needs to check for the existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .short('t') + /// .short_aliases(&['e', 's']) + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec![ + /// "prog", "-s" + /// ]); + /// assert!(m.is_present("test")); + /// ``` + #[must_use] + pub fn short_aliases(mut self, names: &[char]) -> Self { + for s in names { + assert!(s != &'-', "short alias name cannot be `-`"); + self.short_aliases.push((*s, false)); + } + self + } + + /// Add an alias, which functions as a visible long flag. + /// + /// Like [`Arg::alias`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .visible_alias("something-awesome") + /// .long("test") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--something-awesome", "coffee" + /// ]); + /// assert!(m.is_present("test")); + /// assert_eq!(m.value_of("test"), Some("coffee")); + /// ``` + /// [`Command::alias`]: Arg::alias() + #[must_use] + pub fn visible_alias<S: Into<&'help str>>(mut self, name: S) -> Self { + self.aliases.push((name.into(), true)); + self + } + + /// Add an alias, which functions as a visible short flag. + /// + /// Like [`Arg::short_alias`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .visible_short_alias('t') + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "-t", "coffee" + /// ]); + /// assert!(m.is_present("test")); + /// assert_eq!(m.value_of("test"), Some("coffee")); + /// ``` + #[must_use] + pub fn visible_short_alias(mut self, name: char) -> Self { + assert!(name != '-', "short alias name cannot be `-`"); + + self.short_aliases.push((name, true)); + self + } + + /// Add aliases, which function as visible long flags. + /// + /// Like [`Arg::aliases`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .visible_aliases(&["something", "awesome", "cool"])) + /// .get_matches_from(vec![ + /// "prog", "--awesome" + /// ]); + /// assert!(m.is_present("test")); + /// ``` + /// [`Command::aliases`]: Arg::aliases() + #[must_use] + pub fn visible_aliases(mut self, names: &[&'help str]) -> Self { + self.aliases.extend(names.iter().map(|n| (*n, true))); + self + } + + /// Add aliases, which function as visible short flags. + /// + /// Like [`Arg::short_aliases`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .visible_short_aliases(&['t', 'e'])) + /// .get_matches_from(vec![ + /// "prog", "-t" + /// ]); + /// assert!(m.is_present("test")); + /// ``` + #[must_use] + pub fn visible_short_aliases(mut self, names: &[char]) -> Self { + for n in names { + assert!(n != &'-', "short alias name cannot be `-`"); + self.short_aliases.push((*n, true)); + } + self + } + + /// Specifies the index of a positional argument **starting at** 1. + /// + /// **NOTE:** The index refers to position according to **other positional argument**. It does + /// not define position in the argument list as a whole. + /// + /// **NOTE:** You can optionally leave off the `index` method, and the index will be + /// assigned in order of evaluation. Utilizing the `index` method allows for setting + /// indexes out of order + /// + /// **NOTE:** This is only meant to be used for positional arguments and shouldn't to be used + /// with [`Arg::short`] or [`Arg::long`]. + /// + /// **NOTE:** When utilized with [`Arg::multiple_values(true)`], only the **last** positional argument + /// may be defined as multiple (i.e. with the highest index) + /// + /// # Panics + /// + /// [`Command`] will [`panic!`] if indexes are skipped (such as defining `index(1)` and `index(3)` + /// but not `index(2)`, or a positional argument is defined as multiple and is not the highest + /// index + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("config") + /// .index(1) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .index(1)) + /// .arg(Arg::new("debug") + /// .long("debug")) + /// .get_matches_from(vec![ + /// "prog", "--debug", "fast" + /// ]); + /// + /// assert!(m.is_present("mode")); + /// assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional" + /// // *not* first argument + /// ``` + /// [`Arg::short`]: Arg::short() + /// [`Arg::long`]: Arg::long() + /// [`Arg::multiple_values(true)`]: Arg::multiple_values() + /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html + /// [`Command`]: crate::Command + #[inline] + #[must_use] + pub fn index(mut self, idx: usize) -> Self { + self.index = Some(idx); + self + } + + /// This arg is the last, or final, positional argument (i.e. has the highest + /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args -- + /// last_arg`). + /// + /// Even, if no other arguments are left to parse, if the user omits the `--` syntax + /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also + /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with + /// the `--` syntax is otherwise not possible. + /// + /// **NOTE:** This will change the usage string to look like `$ prog [OPTIONS] [-- <ARG>]` if + /// `ARG` is marked as `.last(true)`. + /// + /// **NOTE:** This setting will imply [`crate::Command::dont_collapse_args_in_usage`] because failing + /// to set this can make the usage string very confusing. + /// + /// **NOTE**: This setting only applies to positional arguments, and has no effect on OPTIONS + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// **CAUTION:** Using this setting *and* having child subcommands is not + /// recommended with the exception of *also* using + /// [`crate::Command::args_conflicts_with_subcommands`] + /// (or [`crate::Command::subcommand_negates_reqs`] if the argument marked `Last` is also + /// marked [`Arg::required`]) + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("args") + /// .takes_value(true) + /// .last(true) + /// # ; + /// ``` + /// + /// Setting `last` ensures the arg has the highest [index] of all positional args + /// and requires that the `--` syntax be used to access it early. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("first")) + /// .arg(Arg::new("second")) + /// .arg(Arg::new("third") + /// .takes_value(true) + /// .last(true)) + /// .try_get_matches_from(vec![ + /// "prog", "one", "--", "three" + /// ]); + /// + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// assert_eq!(m.value_of("third"), Some("three")); + /// assert!(m.value_of("second").is_none()); + /// ``` + /// + /// Even if the positional argument marked `Last` is the only argument left to parse, + /// failing to use the `--` syntax results in an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("first")) + /// .arg(Arg::new("second")) + /// .arg(Arg::new("third") + /// .takes_value(true) + /// .last(true)) + /// .try_get_matches_from(vec![ + /// "prog", "one", "two", "three" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + /// [index]: Arg::index() + /// [`UnknownArgument`]: crate::ErrorKind::UnknownArgument + #[inline] + #[must_use] + pub fn last(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Last) + } else { + self.unset_setting(ArgSettings::Last) + } + } + + /// Specifies that the argument must be present. + /// + /// Required by default means it is required, when no other conflicting rules or overrides have + /// been evaluated. Conflicting rules take precedence over being required. + /// + /// **Pro tip:** Flags (i.e. not positional, or arguments that take values) shouldn't be + /// required by default. This is because if a flag were to be required, it should simply be + /// implied. No additional information is required from user. Flags by their very nature are + /// simply boolean on/off switches. The only time a user *should* be required to use a flag + /// is if the operation is destructive in nature, and the user is essentially proving to you, + /// "Yes, I know what I'm doing." + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required(true) + /// # ; + /// ``` + /// + /// Setting required requires that the argument be used at runtime. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required(true) + /// .takes_value(true) + /// .long("config")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf", + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting required and then *not* supplying that argument at runtime is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required(true) + /// .takes_value(true) + /// .long("config")) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + #[inline] + #[must_use] + pub fn required(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Required) + } else { + self.unset_setting(ArgSettings::Required) + } + } + + /// Sets an argument that is required when this one is present + /// + /// i.e. when using this argument, the following argument *must* be present. + /// + /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .requires("input") + /// # ; + /// ``` + /// + /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the + /// defining argument is used. If the defining argument isn't used, the other argument isn't + /// required + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required + /// ``` + /// + /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [override]: Arg::overrides_with() + #[must_use] + pub fn requires<T: Key>(mut self, arg_id: T) -> Self { + self.requires.push((ArgPredicate::IsPresent, arg_id.into())); + self + } + + /// This argument must be passed alone; it conflicts with all other arguments. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .exclusive(true) + /// # ; + /// ``` + /// + /// Setting an exclusive argument and having any other arguments present at runtime + /// is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("exclusive") + /// .takes_value(true) + /// .exclusive(true) + /// .long("exclusive")) + /// .arg(Arg::new("debug") + /// .long("debug")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog", "--exclusive", "file.conf", "file.txt" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); + /// ``` + #[inline] + #[must_use] + pub fn exclusive(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Exclusive) + } else { + self.unset_setting(ArgSettings::Exclusive) + } + } + + /// Specifies that an argument can be matched to all child [`Subcommand`]s. + /// + /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however + /// their values once a user uses them will be propagated back up to parents. In effect, this + /// means one should *define* all global arguments at the top level, however it doesn't matter + /// where the user *uses* the global argument. + /// + /// # Examples + /// + /// Assume an application with two subcommands, and you'd like to define a + /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't + /// want to clutter the source with three duplicate [`Arg`] definitions. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("verb") + /// .long("verbose") + /// .short('v') + /// .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!(sub_m.is_present("verb")); + /// ``` + /// + /// [`Subcommand`]: crate::Subcommand + /// [`ArgMatches::is_present("flag")`]: ArgMatches::is_present() + #[inline] + #[must_use] + pub fn global(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Global) + } else { + self.unset_setting(ArgSettings::Global) + } + } + + /// Specifies that the argument may appear more than once. + /// + /// For flags, this results in the number of occurrences of the flag being recorded. For + /// example `-ddd` or `-d -d -d` would count as three occurrences. For options or arguments + /// that take a value, this *does not* affect how many values they can accept. (i.e. only one + /// at a time is allowed) + /// + /// For example, `--opt val1 --opt val2` is allowed, but `--opt val1 val2` is not. + /// + /// # Examples + /// + /// An example with flags + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("verbose") + /// .multiple_occurrences(true) + /// .short('v')) + /// .get_matches_from(vec![ + /// "prog", "-v", "-v", "-v" // note, -vvv would have same result + /// ]); + /// + /// assert!(m.is_present("verbose")); + /// assert_eq!(m.occurrences_of("verbose"), 3); + /// ``` + /// + /// An example with options + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("file") + /// .multiple_occurrences(true) + /// .takes_value(true) + /// .short('F')) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "-F", "file2", "-F", "file3" + /// ]); + /// + /// assert!(m.is_present("file")); + /// assert_eq!(m.occurrences_of("file"), 3); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// ``` + #[inline] + #[must_use] + pub fn multiple_occurrences(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::MultipleOccurrences) + } else { + self.unset_setting(ArgSettings::MultipleOccurrences) + } + } + + /// The *maximum* number of occurrences for this argument. + /// + /// For example, if you had a + /// `-v` flag and you wanted up to 3 levels of verbosity you would set `.max_occurrences(3)`, and + /// this argument would be satisfied if the user provided it once or twice or thrice. + /// + /// **NOTE:** This implicitly sets [`Arg::multiple_occurrences(true)`] if the value is greater than 1. + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("verbosity") + /// .short('v') + /// .max_occurrences(3); + /// ``` + /// + /// Supplying less than the maximum number of arguments is allowed + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("verbosity") + /// .max_occurrences(3) + /// .short('v')) + /// .try_get_matches_from(vec![ + /// "prog", "-vvv" + /// ]); + /// + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// assert_eq!(m.occurrences_of("verbosity"), 3); + /// ``` + /// + /// Supplying more than the maximum number of arguments is an error + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("verbosity") + /// .max_occurrences(2) + /// .short('v')) + /// .try_get_matches_from(vec![ + /// "prog", "-vvv" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::TooManyOccurrences); + /// ``` + /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences() + #[inline] + #[must_use] + pub fn max_occurrences(mut self, qty: usize) -> Self { + self.max_occurs = Some(qty); + if qty > 1 { + self.multiple_occurrences(true) + } else { + self + } + } + + /// Check if the [`ArgSettings`] variant is currently set on the argument. + /// + /// [`ArgSettings`]: crate::ArgSettings + #[inline] + pub fn is_set(&self, s: ArgSettings) -> bool { + self.settings.is_set(s) + } + + /// Apply a setting to the argument. + /// + /// See [`ArgSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Arg, ArgSettings}; + /// Arg::new("config") + /// .setting(ArgSettings::Required) + /// .setting(ArgSettings::TakesValue) + /// # ; + /// ``` + /// + /// ```no_run + /// # use clap::{Arg, ArgSettings}; + /// Arg::new("config") + /// .setting(ArgSettings::Required | ArgSettings::TakesValue) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn setting<F>(mut self, setting: F) -> Self + where + F: Into<ArgFlags>, + { + self.settings.insert(setting.into()); + self + } + + /// Remove a setting from the argument. + /// + /// See [`ArgSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Arg, ArgSettings}; + /// Arg::new("config") + /// .unset_setting(ArgSettings::Required) + /// .unset_setting(ArgSettings::TakesValue) + /// # ; + /// ``` + /// + /// ```no_run + /// # use clap::{Arg, ArgSettings}; + /// Arg::new("config") + /// .unset_setting(ArgSettings::Required | ArgSettings::TakesValue) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn unset_setting<F>(mut self, setting: F) -> Self + where + F: Into<ArgFlags>, + { + self.settings.remove(setting.into()); + self + } +} + +/// # Value Handling +impl<'help> Arg<'help> { + /// Specifies that the argument takes a value at run time. + /// + /// **NOTE:** values for arguments may be specified in any of the following methods + /// + /// - Using a space such as `-o value` or `--option value` + /// - Using an equals and no space such as `-o=value` or `--option=value` + /// - Use a short and no space such as `-ovalue` + /// + /// **NOTE:** By default, args which allow [multiple values] are delimited by commas, meaning + /// `--option=val1,val2,val3` is three values for the `--option` argument. If you wish to + /// change the delimiter to another character you can use [`Arg::value_delimiter(char)`], + /// alternatively you can turn delimiting values **OFF** by using + /// [`Arg::use_value_delimiter(false)`][Arg::use_value_delimiter] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--mode", "fast" + /// ]); + /// + /// assert!(m.is_present("mode")); + /// assert_eq!(m.value_of("mode"), Some("fast")); + /// ``` + /// [`Arg::value_delimiter(char)`]: Arg::value_delimiter() + /// [multiple values]: Arg::multiple_values + #[inline] + #[must_use] + pub fn takes_value(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::TakesValue) + } else { + self.unset_setting(ArgSettings::TakesValue) + } + } + + /// Specifies that the argument may have an unknown number of values + /// + /// Without any other settings, this argument may appear only *once*. + /// + /// For example, `--opt val1 val2` is allowed, but `--opt val1 val2 --opt val3` is not. + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`]. + /// + /// **WARNING:** + /// + /// Setting `multiple_values` for an argument that takes a value, but with no other details can + /// be dangerous in some circumstances. Because multiple values are allowed, + /// `--option val1 val2 val3` is perfectly valid. Be careful when designing a CLI where + /// positional arguments are *also* expected as `clap` will continue parsing *values* until one + /// of the following happens: + /// + /// - It reaches the [maximum number of values] + /// - It reaches a [specific number of values] + /// - It finds another flag or option (i.e. something that starts with a `-`) + /// - It reaches a [value terminator][Arg::value_terminator] is reached + /// + /// Alternatively, [require a delimiter between values][Arg::require_delimiter]. + /// + /// **WARNING:** + /// + /// When using args with `multiple_values` and [`subcommands`], one needs to consider the + /// possibility of an argument value being the same as a valid subcommand. By default `clap` will + /// parse the argument in question as a value *only if* a value is possible at that moment. + /// Otherwise it will be parsed as a subcommand. In effect, this means using `multiple_values` with no + /// additional parameters and a value that coincides with a subcommand name, the subcommand + /// cannot be called unless another argument is passed between them. + /// + /// As an example, consider a CLI with an option `--ui-paths=<paths>...` and subcommand `signer` + /// + /// The following would be parsed as values to `--ui-paths`. + /// + /// ```text + /// $ program --ui-paths path1 path2 signer + /// ``` + /// + /// This is because `--ui-paths` accepts multiple values. `clap` will continue parsing values + /// until another argument is reached and it knows `--ui-paths` is done parsing. + /// + /// By adding additional parameters to `--ui-paths` we can solve this issue. Consider adding + /// [`Arg::number_of_values(1)`] or using *only* [`Arg::multiple_occurrences`]. The following are all + /// valid, and `signer` is parsed as a subcommand in the first case, but a value in the second + /// case. + /// + /// ```text + /// $ program --ui-paths path1 signer + /// $ program --ui-paths path1 --ui-paths signer signer + /// ``` + /// + /// # Examples + /// + /// An example with options + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .multiple_values(true) + /// .short('F')) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3" + /// ]); + /// + /// assert!(m.is_present("file")); + /// assert_eq!(m.occurrences_of("file"), 1); // notice only one occurrence + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// ``` + /// + /// Although `multiple_values` has been specified, we cannot use the argument more than once. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .multiple_values(true) + /// .short('F')) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1", "-F", "file2", "-F", "file3" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnexpectedMultipleUsage) + /// ``` + /// + /// A common mistake is to define an option which allows multiple values, and a positional + /// argument. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .multiple_values(true) + /// .short('F')) + /// .arg(Arg::new("word")) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3", "word" + /// ]); + /// + /// assert!(m.is_present("file")); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?! + /// assert!(!m.is_present("word")); // but we clearly used word! + /// ``` + /// + /// The problem is `clap` doesn't know when to stop parsing values for "files". This is further + /// compounded by if we'd said `word -F file1 file2` it would have worked fine, so it would + /// appear to only fail sometimes...not good! + /// + /// A solution for the example above is to limit how many values with a [maximum], or [specific] + /// number, or to say [`Arg::multiple_occurrences`] is ok, but multiple values is not. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .multiple_occurrences(true) + /// .short('F')) + /// .arg(Arg::new("word")) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word" + /// ]); + /// + /// assert!(m.is_present("file")); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// assert!(m.is_present("word")); + /// assert_eq!(m.value_of("word"), Some("word")); + /// ``` + /// + /// As a final example, let's fix the above error and get a pretty message to the user :) + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .multiple_occurrences(true) + /// .short('F')) + /// .arg(Arg::new("word")) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3", "word" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + /// [`Arg::number_of_values(1)`]: Arg::number_of_values() + /// [maximum number of values]: Arg::max_values() + /// [specific number of values]: Arg::number_of_values() + /// [maximum]: Arg::max_values() + /// [specific]: Arg::number_of_values() + #[inline] + #[must_use] + pub fn multiple_values(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::MultipleValues) + } else { + self.unset_setting(ArgSettings::MultipleValues) + } + } + + /// The number of values allowed for this argument. + /// + /// For example, if you had a + /// `-f <file>` argument where you wanted exactly 3 'files' you would set + /// `.number_of_values(3)`, and this argument wouldn't be satisfied unless the user provided + /// 3 and only 3 values. + /// + /// **NOTE:** Does *not* require [`Arg::multiple_occurrences(true)`] to be set. Setting + /// [`Arg::multiple_occurrences(true)`] would allow `-f <file> <file> <file> -f <file> <file> <file>` where + /// as *not* setting it would only allow one occurrence of this argument. + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] and [`Arg::multiple_values(true)`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("file") + /// .short('f') + /// .number_of_values(3); + /// ``` + /// + /// Not supplying the correct number of values is an error + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .number_of_values(2) + /// .short('F')) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::WrongNumberOfValues); + /// ``` + /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences() + #[inline] + #[must_use] + pub fn number_of_values(mut self, qty: usize) -> Self { + self.num_vals = Some(qty); + self.takes_value(true).multiple_values(true) + } + + /// The *maximum* number of values are for this argument. + /// + /// For example, if you had a + /// `-f <file>` argument where you wanted up to 3 'files' you would set `.max_values(3)`, and + /// this argument would be satisfied if the user provided, 1, 2, or 3 values. + /// + /// **NOTE:** This does *not* implicitly set [`Arg::multiple_occurrences(true)`]. This is because + /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single + /// occurrence with multiple values. For positional arguments this **does** set + /// [`Arg::multiple_occurrences(true)`] because there is no way to determine the difference between multiple + /// occurrences and multiple values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("file") + /// .short('f') + /// .max_values(3); + /// ``` + /// + /// Supplying less than the maximum number of values is allowed + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .max_values(3) + /// .short('F')) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1", "file2" + /// ]); + /// + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2"]); + /// ``` + /// + /// Supplying more than the maximum number of values is an error + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .max_values(2) + /// .short('F')) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences() + #[inline] + #[must_use] + pub fn max_values(mut self, qty: usize) -> Self { + self.max_vals = Some(qty); + self.takes_value(true).multiple_values(true) + } + + /// The *minimum* number of values for this argument. + /// + /// For example, if you had a + /// `-f <file>` argument where you wanted at least 2 'files' you would set + /// `.min_values(2)`, and this argument would be satisfied if the user provided, 2 or more + /// values. + /// + /// **NOTE:** This does not implicitly set [`Arg::multiple_occurrences(true)`]. This is because + /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single + /// occurrence with multiple values. For positional arguments this **does** set + /// [`Arg::multiple_occurrences(true)`] because there is no way to determine the difference between multiple + /// occurrences and multiple values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("file") + /// .short('f') + /// .min_values(3); + /// ``` + /// + /// Supplying more than the minimum number of values is allowed + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .min_values(2) + /// .short('F')) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3" + /// ]); + /// + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// let files: Vec<_> = m.values_of("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// ``` + /// + /// Supplying less than the minimum number of values is an error + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .takes_value(true) + /// .min_values(2) + /// .short('F')) + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::TooFewValues); + /// ``` + /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences() + #[inline] + #[must_use] + pub fn min_values(mut self, qty: usize) -> Self { + self.min_vals = Some(qty); + self.takes_value(true).multiple_values(true) + } + + /// Placeholder for the argument's value in the help message / usage. + /// + /// This name is cosmetic only; the name is **not** used to access arguments. + /// This setting can be very helpful when describing the type of input the user should be + /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to + /// use all capital letters for the value name. + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("cfg") + /// .long("config") + /// .value_name("FILE") + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("config") + /// .long("config") + /// .value_name("FILE") + /// .help("Some help text")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// Running the above program produces the following output + /// + /// ```text + /// valnames + /// + /// USAGE: + /// valnames [OPTIONS] + /// + /// OPTIONS: + /// --config <FILE> Some help text + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + /// [option]: Arg::takes_value() + /// [positional]: Arg::index() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + #[inline] + #[must_use] + pub fn value_name(self, name: &'help str) -> Self { + self.value_names(&[name]) + } + + /// Placeholders for the argument's values in the help message / usage. + /// + /// These names are cosmetic only, used for help and usage strings only. The names are **not** + /// used to access arguments. The values of the arguments are accessed in numeric order (i.e. + /// if you specify two names `one` and `two` `one` will be the first matched value, `two` will + /// be the second). + /// + /// This setting can be very helpful when describing the type of input the user should be + /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to + /// use all capital letters for the value name. + /// + /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or + /// multiple value names in order to not throw off the help text alignment of all options. + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] and [`Arg::multiple_values(true)`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("speed") + /// .short('s') + /// .value_names(&["fast", "slow"]); + /// ``` + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("io") + /// .long("io-files") + /// .value_names(&["INFILE", "OUTFILE"])) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// Running the above program produces the following output + /// + /// ```text + /// valnames + /// + /// USAGE: + /// valnames [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// --io-files <INFILE> <OUTFILE> Some help text + /// -V, --version Print version information + /// ``` + /// [`Arg::next_line_help(true)`]: Arg::next_line_help() + /// [`Arg::number_of_values`]: Arg::number_of_values() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`Arg::multiple_values(true)`]: Arg::multiple_values() + #[must_use] + pub fn value_names(mut self, names: &[&'help str]) -> Self { + self.val_names = names.to_vec(); + self.takes_value(true) + } + + /// Provide the shell a hint about how to complete this argument. + /// + /// See [`ValueHint`][crate::ValueHint] for more information. + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]. + /// + /// For example, to take a username as argument: + /// + /// ``` + /// # use clap::{Arg, ValueHint}; + /// Arg::new("user") + /// .short('u') + /// .long("user") + /// .value_hint(ValueHint::Username); + /// ``` + /// + /// To take a full command line and its arguments (for example, when writing a command wrapper): + /// + /// ``` + /// # use clap::{Command, Arg, ValueHint}; + /// Command::new("prog") + /// .trailing_var_arg(true) + /// .arg( + /// Arg::new("command") + /// .takes_value(true) + /// .multiple_values(true) + /// .value_hint(ValueHint::CommandWithArguments) + /// ); + /// ``` + #[must_use] + pub fn value_hint(mut self, value_hint: ValueHint) -> Self { + self.value_hint = value_hint; + self.takes_value(true) + } + + /// Perform a custom validation on the argument value. + /// + /// You provide a closure + /// which accepts a [`&str`] value, and return a [`Result`] where the [`Err(String)`] is a + /// message displayed to the user. + /// + /// **NOTE:** The error message does *not* need to contain the `error:` portion, only the + /// message as all errors will appear as + /// `error: Invalid value for '<arg>': <YOUR MESSAGE>` where `<arg>` is replaced by the actual + /// arg, and `<YOUR MESSAGE>` is the `String` you return as the error. + /// + /// **NOTE:** There is a small performance hit for using validators, as they are implemented + /// with [`Arc`] pointers. And the value to be checked will be allocated an extra time in order + /// to be passed to the closure. This performance hit is extremely minimal in the grand + /// scheme of things. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// fn has_at(v: &str) -> Result<(), String> { + /// if v.contains("@") { return Ok(()); } + /// Err(String::from("The value did not contain the required @ sigil")) + /// } + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .validator(has_at)) + /// .try_get_matches_from(vec![ + /// "prog", "some@file" + /// ]); + /// assert!(res.is_ok()); + /// assert_eq!(res.unwrap().value_of("file"), Some("some@file")); + /// ``` + /// [`Result`]: std::result::Result + /// [`Err(String)`]: std::result::Result::Err + /// [`Arc`]: std::sync::Arc + #[must_use] + pub fn validator<F, O, E>(mut self, mut f: F) -> Self + where + F: FnMut(&str) -> Result<O, E> + Send + 'help, + E: Into<Box<dyn Error + Send + Sync + 'static>>, + { + self.validator = Some(Arc::new(Mutex::new(move |s: &str| { + f(s).map(|_| ()).map_err(|e| e.into()) + }))); + self + } + + /// Perform a custom validation on the argument value. + /// + /// See [validator][Arg::validator]. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```rust")] + /// # use clap::{Command, Arg}; + /// # use std::ffi::{OsStr, OsString}; + /// # use std::os::unix::ffi::OsStrExt; + /// fn has_ampersand(v: &OsStr) -> Result<(), String> { + /// if v.as_bytes().iter().any(|b| *b == b'&') { return Ok(()); } + /// Err(String::from("The value did not contain the required & sigil")) + /// } + /// let res = Command::new("prog") + /// .arg(Arg::new("file") + /// .validator_os(has_ampersand)) + /// .try_get_matches_from(vec![ + /// "prog", "Fish & chips" + /// ]); + /// assert!(res.is_ok()); + /// assert_eq!(res.unwrap().value_of("file"), Some("Fish & chips")); + /// ``` + /// [`String`]: std::string::String + /// [`OsStr`]: std::ffi::OsStr + /// [`OsString`]: std::ffi::OsString + /// [`Result`]: std::result::Result + /// [`Err(String)`]: std::result::Result::Err + /// [`Rc`]: std::rc::Rc + #[must_use] + pub fn validator_os<F, O, E>(mut self, mut f: F) -> Self + where + F: FnMut(&OsStr) -> Result<O, E> + Send + 'help, + E: Into<Box<dyn Error + Send + Sync + 'static>>, + { + self.validator_os = Some(Arc::new(Mutex::new(move |s: &OsStr| { + f(s).map(|_| ()).map_err(|e| e.into()) + }))); + self + } + + /// Validates the argument via the given regular expression. + /// + /// As regular expressions are not very user friendly, the additional `err_message` should + /// describe the expected format in clear words. All notes for [`Arg::validator()`] regarding the + /// error message and performance also hold for `validator_regex`. + /// + /// The regular expression can either be borrowed or moved into `validator_regex`. This happens + /// automatically via [`RegexRef`]'s `Into` implementation. + /// + /// # Performance + /// Regular expressions are expensive to compile. You should prefer sharing your regular expression. + /// We use a [`Cow`]-like internal structure to enable both sharing as well as taking ownership of a + /// provided regular expression. + /// + /// # Examples + /// + /// You can use the classical `"\d+"` regular expression to match digits only: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// use regex::Regex; + /// + /// let digits = Regex::new(r"\d+").unwrap(); + /// + /// let res = Command::new("prog") + /// .arg(Arg::new("digits") + /// .validator_regex(&digits, "only digits are allowed")) + /// .try_get_matches_from(vec![ + /// "prog", "12345" + /// ]); + /// assert!(res.is_ok()); + /// assert_eq!(res.unwrap().value_of("digits"), Some("12345")); + /// ``` + /// + /// However, any valid `Regex` can be used: + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// use regex::Regex; + /// + /// let priority = Regex::new(r"[A-C]").unwrap(); + /// + /// let res = Command::new("prog") + /// .arg(Arg::new("priority") + /// .validator_regex(priority, "only priorities A, B or C are allowed")) + /// .try_get_matches_from(vec![ + /// "prog", "12345" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.err().unwrap().kind(), ErrorKind::ValueValidation) + /// ``` + #[cfg(feature = "regex")] + #[must_use] + pub fn validator_regex( + self, + regex: impl Into<RegexRef<'help>>, + err_message: &'help str, + ) -> Self { + let regex = regex.into(); + self.validator(move |s: &str| { + if regex.is_match(s) { + Ok(()) + } else { + Err(err_message) + } + }) + } + + /// Add a possible value for this argument. + /// + /// At runtime, `clap` verifies that only one of the specified values was used, or fails with + /// error message. + /// + /// **NOTE:** This setting only applies to [options] and [positional arguments] + /// + /// **NOTE:** You can use both strings directly or use [`PossibleValue`] if you want more control + /// over single possible values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("mode") + /// .takes_value(true) + /// .possible_value("fast") + /// .possible_value("slow") + /// .possible_value("medium") + /// # ; + /// ``` + /// The same using [`PossibleValue`]: + /// + /// ```rust + /// # use clap::{Command, Arg, PossibleValue}; + /// Arg::new("mode").takes_value(true) + /// .possible_value(PossibleValue::new("fast")) + /// // value with a help text + /// .possible_value(PossibleValue::new("slow").help("not that fast")) + /// // value that is hidden from completion and help text + /// .possible_value(PossibleValue::new("medium").hide(true)) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .takes_value(true) + /// .possible_value("fast") + /// .possible_value("slow") + /// .possible_value("medium")) + /// .get_matches_from(vec![ + /// "prog", "--mode", "fast" + /// ]); + /// assert!(m.is_present("mode")); + /// assert_eq!(m.value_of("mode"), Some("fast")); + /// ``` + /// + /// The next example shows a failed parse from using a value which wasn't defined as one of the + /// possible values. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .takes_value(true) + /// .possible_value("fast") + /// .possible_value("slow") + /// .possible_value("medium")) + /// .try_get_matches_from(vec![ + /// "prog", "--mode", "wrong" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidValue); + /// ``` + /// [options]: Arg::takes_value() + /// [positional arguments]: Arg::index() + #[must_use] + pub fn possible_value<T>(mut self, value: T) -> Self + where + T: Into<PossibleValue<'help>>, + { + self.possible_vals.push(value.into()); + self.takes_value(true) + } + + /// Possible values for this argument. + /// + /// At runtime, `clap` verifies that + /// only one of the specified values was used, or fails with an error message. + /// + /// **NOTE:** This setting only applies to [options] and [positional arguments] + /// + /// **NOTE:** You can use both strings directly or use [`PossibleValue`] if you want more control + /// over single possible values. + /// + /// See also [hide_possible_values][Arg::hide_possible_values]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("mode") + /// .takes_value(true) + /// .possible_values(["fast", "slow", "medium"]) + /// # ; + /// ``` + /// The same using [`PossibleValue`]: + /// + /// ```rust + /// # use clap::{Command, Arg, PossibleValue}; + /// Arg::new("mode").takes_value(true).possible_values([ + /// PossibleValue::new("fast"), + /// // value with a help text + /// PossibleValue::new("slow").help("not that fast"), + /// // value that is hidden from completion and help text + /// PossibleValue::new("medium").hide(true), + /// ]) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .takes_value(true) + /// .possible_values(["fast", "slow", "medium"])) + /// .get_matches_from(vec![ + /// "prog", "--mode", "fast" + /// ]); + /// assert!(m.is_present("mode")); + /// assert_eq!(m.value_of("mode"), Some("fast")); + /// ``` + /// + /// The next example shows a failed parse from using a value which wasn't defined as one of the + /// possible values. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .takes_value(true) + /// .possible_values(["fast", "slow", "medium"])) + /// .try_get_matches_from(vec![ + /// "prog", "--mode", "wrong" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidValue); + /// ``` + /// [options]: Arg::takes_value() + /// [positional arguments]: Arg::index() + #[must_use] + pub fn possible_values<I, T>(mut self, values: I) -> Self + where + I: IntoIterator<Item = T>, + T: Into<PossibleValue<'help>>, + { + self.possible_vals + .extend(values.into_iter().map(|value| value.into())); + self.takes_value(true) + } + + /// Match values against [`Arg::possible_values`] without matching case. + /// + /// When other arguments are conditionally required based on the + /// value of a case-insensitive argument, the equality check done + /// by [`Arg::required_if_eq`], [`Arg::required_if_eq_any`], or + /// [`Arg::required_if_eq_all`] is case-insensitive. + /// + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// **NOTE:** To do unicode case folding, enable the `unicode` feature flag. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("pv") + /// .arg(Arg::new("option") + /// .long("option") + /// .takes_value(true) + /// .ignore_case(true) + /// .possible_value("test123")) + /// .get_matches_from(vec![ + /// "pv", "--option", "TeSt123", + /// ]); + /// + /// assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123")); + /// ``` + /// + /// This setting also works when multiple values can be defined: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("pv") + /// .arg(Arg::new("option") + /// .short('o') + /// .long("option") + /// .takes_value(true) + /// .ignore_case(true) + /// .multiple_values(true) + /// .possible_values(&["test123", "test321"])) + /// .get_matches_from(vec![ + /// "pv", "--option", "TeSt123", "teST123", "tESt321" + /// ]); + /// + /// let matched_vals = m.values_of("option").unwrap().collect::<Vec<_>>(); + /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]); + /// ``` + #[inline] + #[must_use] + pub fn ignore_case(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::IgnoreCase) + } else { + self.unset_setting(ArgSettings::IgnoreCase) + } + } + + /// Allows values which start with a leading hyphen (`-`) + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// **WARNING**: Take caution when using this setting combined with + /// [`Arg::multiple_values`], as this becomes ambiguous `$ prog --arg -- -- val`. All + /// three `--, --, val` will be values when the user may have thought the second `--` would + /// constitute the normal, "Only positional args follow" idiom. To fix this, consider using + /// [`Arg::multiple_occurrences`] which only allows a single value at a time. + /// + /// **WARNING**: When building your CLIs, consider the effects of allowing leading hyphens and + /// the user passing in a value that matches a valid short. For example, `prog -opt -F` where + /// `-F` is supposed to be a value, yet `-F` is *also* a valid short for another arg. + /// Care should be taken when designing these args. This is compounded by the ability to "stack" + /// short args. I.e. if `-val` is supposed to be a value, but `-v`, `-a`, and `-l` are all valid + /// shorts. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("pat") + /// .takes_value(true) + /// .allow_hyphen_values(true) + /// .long("pattern")) + /// .get_matches_from(vec![ + /// "prog", "--pattern", "-file" + /// ]); + /// + /// assert_eq!(m.value_of("pat"), Some("-file")); + /// ``` + /// + /// Not setting `Arg::allow_hyphen_values(true)` and supplying a value which starts with a + /// hyphen is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("pat") + /// .takes_value(true) + /// .long("pattern")) + /// .try_get_matches_from(vec![ + /// "prog", "--pattern", "-file" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + /// [`Arg::number_of_values(1)`]: Arg::number_of_values() + #[inline] + #[must_use] + pub fn allow_hyphen_values(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::AllowHyphenValues) + } else { + self.unset_setting(ArgSettings::AllowHyphenValues) + } + } + + /// The argument's values can be invalid UTF-8 and should *not* be treated as an error. + /// + /// **NOTE:** Using argument values with invalid UTF-8 code points requires using + /// [`ArgMatches::value_of_os`], [`ArgMatches::values_of_os`], [`ArgMatches::value_of_lossy`], + /// or [`ArgMatches::values_of_lossy`] for those particular arguments which may contain invalid + /// UTF-8 values. + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```rust")] + /// # use clap::{Command, Arg}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// let r = Command::new("myprog") + /// .arg(Arg::new("arg").allow_invalid_utf8(true)) + /// .try_get_matches_from(vec![ + /// OsString::from("myprog"), + /// OsString::from_vec(vec![0xe9]) + /// ]); + /// + /// assert!(r.is_ok()); + /// let m = r.unwrap(); + /// assert_eq!(m.value_of_os("arg").unwrap().as_bytes(), &[0xe9]); + /// ``` + /// [`ArgMatches::value_of_os`]: crate::ArgMatches::value_of_os() + /// [`ArgMatches::values_of_os`]: crate::ArgMatches::values_of_os() + /// [`ArgMatches::value_of_lossy`]: crate::ArgMatches::value_of_lossy() + /// [`ArgMatches::values_of_lossy`]: crate::ArgMatches::values_of_lossy() + #[inline] + #[must_use] + pub fn allow_invalid_utf8(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::AllowInvalidUtf8) + } else { + self.unset_setting(ArgSettings::AllowInvalidUtf8) + } + } + + /// Don't allow an argument to accept explicitly empty values. + /// + /// An empty value must be specified at the command line with an explicit `""`, `''`, or + /// `--option=` + /// + /// **NOTE:** By default empty values are allowed. + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`]. + /// + /// # Examples + /// + /// The default is allowing empty values. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .short('v') + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--config=" + /// ]); + /// + /// assert!(res.is_ok()); + /// assert_eq!(res.unwrap().value_of("cfg"), Some("")); + /// ``` + /// + /// By adding this setting, we can forbid empty values. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .short('v') + /// .takes_value(true) + /// .forbid_empty_values(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--config=" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::EmptyValue); + /// ``` + #[inline] + #[must_use] + pub fn forbid_empty_values(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::ForbidEmptyValues) + } else { + self.unset_setting(ArgSettings::ForbidEmptyValues) + } + } + + /// Requires that options use the `--option=val` syntax + /// + /// i.e. an equals between the option and associated value. + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// # Examples + /// + /// Setting `require_equals` requires that the option have an equals sign between + /// it and the associated value. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .require_equals(true) + /// .long("config")) + /// .try_get_matches_from(vec![ + /// "prog", "--config=file.conf" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting `require_equals` and *not* supplying the equals will cause an + /// error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .require_equals(true) + /// .long("config")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals); + /// ``` + #[inline] + #[must_use] + pub fn require_equals(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::RequireEquals) + } else { + self.unset_setting(ArgSettings::RequireEquals) + } + } + + /// Specifies that an argument should allow grouping of multiple values via a + /// delimiter. + /// + /// i.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`, + /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the + /// value delimiter for all arguments that accept values (options and positional arguments) + /// + /// **NOTE:** When this setting is used, it will default [`Arg::value_delimiter`] + /// to the comma `,`. + /// + /// **NOTE:** Implicitly sets [`Arg::takes_value`] + /// + /// # Examples + /// + /// The following example shows the default behavior. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let delims = Command::new("prog") + /// .arg(Arg::new("option") + /// .long("option") + /// .use_value_delimiter(true) + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--option=val1,val2,val3", + /// ]); + /// + /// assert!(delims.is_present("option")); + /// assert_eq!(delims.occurrences_of("option"), 1); + /// assert_eq!(delims.values_of("option").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]); + /// ``` + /// The next example shows the difference when turning delimiters off. This is the default + /// behavior + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let nodelims = Command::new("prog") + /// .arg(Arg::new("option") + /// .long("option") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--option=val1,val2,val3", + /// ]); + /// + /// assert!(nodelims.is_present("option")); + /// assert_eq!(nodelims.occurrences_of("option"), 1); + /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3"); + /// ``` + /// [`Arg::value_delimiter`]: Arg::value_delimiter() + #[inline] + #[must_use] + pub fn use_value_delimiter(mut self, yes: bool) -> Self { + if yes { + if self.val_delim.is_none() { + self.val_delim = Some(','); + } + self.takes_value(true) + .setting(ArgSettings::UseValueDelimiter) + } else { + self.val_delim = None; + self.unset_setting(ArgSettings::UseValueDelimiter) + } + } + + /// Deprecated, replaced with [`Arg::use_value_delimiter`] + #[inline] + #[must_use] + #[deprecated(since = "3.1.0", note = "Replaced with `Arg::use_value_delimiter`")] + pub fn use_delimiter(self, yes: bool) -> Self { + self.use_value_delimiter(yes) + } + + /// Separator between the arguments values, defaults to `,` (comma). + /// + /// **NOTE:** implicitly sets [`Arg::use_value_delimiter(true)`] + /// + /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("config") + /// .short('c') + /// .long("config") + /// .value_delimiter(';')) + /// .get_matches_from(vec![ + /// "prog", "--config=val1;val2;val3" + /// ]); + /// + /// assert_eq!(m.values_of("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]) + /// ``` + /// [`Arg::use_value_delimiter(true)`]: Arg::use_value_delimiter() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + #[inline] + #[must_use] + pub fn value_delimiter(mut self, d: char) -> Self { + self.val_delim = Some(d); + self.takes_value(true).use_value_delimiter(true) + } + + /// Specifies that *multiple values* may only be set using the delimiter. + /// + /// This means if an option is encountered, and no delimiter is found, it is assumed that no + /// additional values for that option follow. This is unlike the default, where it is generally + /// assumed that more values will follow regardless of whether or not a delimiter is used. + /// + /// **NOTE:** The default is `false`. + /// + /// **NOTE:** Setting this requires [`Arg::use_value_delimiter`] and + /// [`Arg::takes_value`] + /// + /// **NOTE:** It's a good idea to inform the user that use of a delimiter is required, either + /// through help text or other means. + /// + /// # Examples + /// + /// These examples demonstrate what happens when `require_delimiter(true)` is used. Notice + /// everything works in this first example, as we use a delimiter, as expected. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let delims = Command::new("prog") + /// .arg(Arg::new("opt") + /// .short('o') + /// .takes_value(true) + /// .use_value_delimiter(true) + /// .require_delimiter(true) + /// .multiple_values(true)) + /// .get_matches_from(vec![ + /// "prog", "-o", "val1,val2,val3", + /// ]); + /// + /// assert!(delims.is_present("opt")); + /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]); + /// ``` + /// + /// In this next example, we will *not* use a delimiter. Notice it's now an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("opt") + /// .short('o') + /// .takes_value(true) + /// .use_value_delimiter(true) + /// .require_delimiter(true)) + /// .try_get_matches_from(vec![ + /// "prog", "-o", "val1", "val2", "val3", + /// ]); + /// + /// assert!(res.is_err()); + /// let err = res.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::UnknownArgument); + /// ``` + /// + /// What's happening is `-o` is getting `val1`, and because delimiters are required yet none + /// were present, it stops parsing `-o`. At this point it reaches `val2` and because no + /// positional arguments have been defined, it's an error of an unexpected argument. + /// + /// In this final example, we contrast the above with `clap`'s default behavior where the above + /// is *not* an error. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let delims = Command::new("prog") + /// .arg(Arg::new("opt") + /// .short('o') + /// .takes_value(true) + /// .multiple_values(true)) + /// .get_matches_from(vec![ + /// "prog", "-o", "val1", "val2", "val3", + /// ]); + /// + /// assert!(delims.is_present("opt")); + /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]); + /// ``` + #[inline] + #[must_use] + pub fn require_value_delimiter(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::RequireDelimiter) + } else { + self.unset_setting(ArgSettings::RequireDelimiter) + } + } + + /// Deprecated, replaced with [`Arg::require_value_delimiter`] + #[inline] + #[must_use] + #[deprecated(since = "3.1.0", note = "Replaced with `Arg::require_value_delimiter`")] + pub fn require_delimiter(self, yes: bool) -> Self { + self.require_value_delimiter(yes) + } + + /// Sentinel to **stop** parsing multiple values of a give argument. + /// + /// By default when + /// one sets [`multiple_values(true)`] on an argument, clap will continue parsing values for that + /// argument until it reaches another valid argument, or one of the other more specific settings + /// for multiple values is used (such as [`min_values`], [`max_values`] or + /// [`number_of_values`]). + /// + /// **NOTE:** This setting only applies to [options] and [positional arguments] + /// + /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one + /// of the values + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("vals") + /// .takes_value(true) + /// .multiple_values(true) + /// .value_terminator(";") + /// # ; + /// ``` + /// + /// The following example uses two arguments, a sequence of commands, and the location in which + /// to perform them + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cmds") + /// .takes_value(true) + /// .multiple_values(true) + /// .allow_hyphen_values(true) + /// .value_terminator(";")) + /// .arg(Arg::new("location")) + /// .get_matches_from(vec![ + /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap" + /// ]); + /// let cmds: Vec<_> = m.values_of("cmds").unwrap().collect(); + /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]); + /// assert_eq!(m.value_of("location"), Some("/home/clap")); + /// ``` + /// [options]: Arg::takes_value() + /// [positional arguments]: Arg::index() + /// [`multiple_values(true)`]: Arg::multiple_values() + /// [`min_values`]: Arg::min_values() + /// [`number_of_values`]: Arg::number_of_values() + /// [`max_values`]: Arg::max_values() + #[inline] + #[must_use] + pub fn value_terminator(mut self, term: &'help str) -> Self { + self.terminator = Some(term); + self.takes_value(true) + } + + /// Consume all following arguments. + /// + /// Do not be parse them individually, but rather pass them in entirety. + /// + /// It is worth noting that setting this requires all values to come after a `--` to indicate + /// they should all be captured. For example: + /// + /// ```text + /// --foo something -- -v -v -v -b -b -b --baz -q -u -x + /// ``` + /// + /// Will result in everything after `--` to be considered one raw argument. This behavior + /// may not be exactly what you are expecting and using [`crate::Command::trailing_var_arg`] + /// may be more appropriate. + /// + /// **NOTE:** Implicitly sets [`Arg::takes_value(true)`] [`Arg::multiple_values(true)`], + /// [`Arg::allow_hyphen_values(true)`], and [`Arg::last(true)`] when set to `true`. + /// + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`Arg::multiple_values(true)`]: Arg::multiple_values() + /// [`Arg::allow_hyphen_values(true)`]: Arg::allow_hyphen_values() + /// [`Arg::last(true)`]: Arg::last() + #[inline] + #[must_use] + pub fn raw(self, yes: bool) -> Self { + self.takes_value(yes) + .multiple_values(yes) + .allow_hyphen_values(yes) + .last(yes) + } + + /// Value for the argument when not present. + /// + /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`] + /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified. + /// + /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::is_present`] will + /// still return `true`. If you wish to determine whether the argument was used at runtime or + /// not, consider [`ArgMatches::occurrences_of`] which will return `0` if the argument was *not* + /// used at runtime. + /// + /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly + /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg + /// at runtime. `Arg::default_value_if` however only takes effect when the user has not provided + /// a value at runtime **and** these other conditions are met as well. If you have set + /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide this arg + /// at runtime, nor were the conditions met for `Arg::default_value_if`, the `Arg::default_value` + /// will be applied. + /// + /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. + /// + /// # Examples + /// + /// First we use the default value without providing any value at runtime. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .long("myopt") + /// .default_value("myval")) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("opt"), Some("myval")); + /// assert!(m.is_present("opt")); + /// assert_eq!(m.occurrences_of("opt"), 0); + /// ``` + /// + /// Next we provide a value at runtime to override the default. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .long("myopt") + /// .default_value("myval")) + /// .get_matches_from(vec![ + /// "prog", "--myopt=non_default" + /// ]); + /// + /// assert_eq!(m.value_of("opt"), Some("non_default")); + /// assert!(m.is_present("opt")); + /// assert_eq!(m.occurrences_of("opt"), 1); + /// ``` + /// [`ArgMatches::occurrences_of`]: crate::ArgMatches::occurrences_of() + /// [`ArgMatches::value_of`]: crate::ArgMatches::value_of() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`ArgMatches::is_present`]: crate::ArgMatches::is_present() + /// [`Arg::default_value_if`]: Arg::default_value_if() + #[inline] + #[must_use] + pub fn default_value(self, val: &'help str) -> Self { + self.default_values_os(&[OsStr::new(val)]) + } + + /// Value for the argument when not present. + /// + /// See [`Arg::default_value`]. + /// + /// [`Arg::default_value`]: Arg::default_value() + /// [`OsStr`]: std::ffi::OsStr + #[inline] + #[must_use] + pub fn default_value_os(self, val: &'help OsStr) -> Self { + self.default_values_os(&[val]) + } + + /// Value for the argument when not present. + /// + /// See [`Arg::default_value`]. + /// + /// [`Arg::default_value`]: Arg::default_value() + #[inline] + #[must_use] + pub fn default_values(self, vals: &[&'help str]) -> Self { + let vals_vec: Vec<_> = vals.iter().map(|val| OsStr::new(*val)).collect(); + self.default_values_os(&vals_vec[..]) + } + + /// Value for the argument when not present. + /// + /// See [`Arg::default_values`]. + /// + /// [`Arg::default_values`]: Arg::default_values() + /// [`OsStr`]: std::ffi::OsStr + #[inline] + #[must_use] + pub fn default_values_os(mut self, vals: &[&'help OsStr]) -> Self { + self.default_vals = vals.to_vec(); + self.takes_value(true) + } + + /// Value for the argument when the flag is present but no value is specified. + /// + /// This configuration option is often used to give the user a shortcut and allow them to + /// efficiently specify an option argument without requiring an explicitly value. The `--color` + /// argument is a common example. By, supplying an default, such as `default_missing_value("always")`, + /// the user can quickly just add `--color` to the command line to produce the desired color output. + /// + /// **NOTE:** using this configuration option requires the use of the `.min_values(0)` and the + /// `.require_equals(true)` configuration option. These are required in order to unambiguously + /// determine what, if any, value was supplied for the argument. + /// + /// # Examples + /// + /// Here is an implementation of the common POSIX style `--color` argument. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// + /// macro_rules! cmd { + /// () => {{ + /// Command::new("prog") + /// .arg(Arg::new("color").long("color") + /// .value_name("WHEN") + /// .possible_values(["always", "auto", "never"]) + /// .default_value("auto") + /// .overrides_with("color") + /// .min_values(0) + /// .require_equals(true) + /// .default_missing_value("always") + /// .help("Specify WHEN to colorize output.") + /// ) + /// }}; + /// } + /// + /// let mut m; + /// + /// // first, we'll provide no arguments + /// + /// m = cmd!().get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("color"), Some("auto")); + /// assert!(m.is_present("color")); + /// assert_eq!(m.occurrences_of("color"), 0); + /// + /// // next, we'll provide a runtime value to override the default (as usually done). + /// + /// m = cmd!().get_matches_from(vec![ + /// "prog", "--color=never" + /// ]); + /// + /// assert_eq!(m.value_of("color"), Some("never")); + /// assert!(m.is_present("color")); + /// assert_eq!(m.occurrences_of("color"), 1); + /// + /// // finally, we will use the shortcut and only provide the argument without a value. + /// + /// m = cmd!().get_matches_from(vec![ + /// "prog", "--color" + /// ]); + /// + /// assert_eq!(m.value_of("color"), Some("always")); + /// assert!(m.is_present("color")); + /// assert_eq!(m.occurrences_of("color"), 1); + /// ``` + /// [`ArgMatches::occurrences_of`]: ArgMatches::occurrences_of() + /// [`ArgMatches::value_of`]: ArgMatches::value_of() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`ArgMatches::is_present`]: ArgMatches::is_present() + /// [`Arg::default_value`]: Arg::default_value() + #[inline] + #[must_use] + pub fn default_missing_value(self, val: &'help str) -> Self { + self.default_missing_values_os(&[OsStr::new(val)]) + } + + /// Value for the argument when the flag is present but no value is specified. + /// + /// See [`Arg::default_missing_value`]. + /// + /// [`Arg::default_missing_value`]: Arg::default_missing_value() + /// [`OsStr`]: std::ffi::OsStr + #[inline] + #[must_use] + pub fn default_missing_value_os(self, val: &'help OsStr) -> Self { + self.default_missing_values_os(&[val]) + } + + /// Value for the argument when the flag is present but no value is specified. + /// + /// See [`Arg::default_missing_value`]. + /// + /// [`Arg::default_missing_value`]: Arg::default_missing_value() + #[inline] + #[must_use] + pub fn default_missing_values(self, vals: &[&'help str]) -> Self { + let vals_vec: Vec<_> = vals.iter().map(|val| OsStr::new(*val)).collect(); + self.default_missing_values_os(&vals_vec[..]) + } + + /// Value for the argument when the flag is present but no value is specified. + /// + /// See [`Arg::default_missing_values`]. + /// + /// [`Arg::default_missing_values`]: Arg::default_missing_values() + /// [`OsStr`]: std::ffi::OsStr + #[inline] + #[must_use] + pub fn default_missing_values_os(mut self, vals: &[&'help OsStr]) -> Self { + self.default_missing_vals = vals.to_vec(); + self.takes_value(true) + } + + /// Read from `name` environment variable when argument is not present. + /// + /// If it is not present in the environment, then default + /// rules will apply. + /// + /// If user sets the argument in the environment: + /// - When [`Arg::takes_value(true)`] is not set, the flag is considered raised. + /// - When [`Arg::takes_value(true)`] is set, [`ArgMatches::value_of`] will + /// return value of the environment variable. + /// + /// If user doesn't set the argument in the environment: + /// - When [`Arg::takes_value(true)`] is not set, the flag is considered off. + /// - When [`Arg::takes_value(true)`] is set, [`ArgMatches::value_of`] will + /// return the default specified. + /// + /// # Examples + /// + /// In this example, we show the variable coming from the environment: + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .env("MY_FLAG") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("flag"), Some("env")); + /// ``` + /// + /// In this example, because [`Arg::takes_value(false)`] (by default), + /// `prog` is a flag that accepts an optional, case-insensitive boolean literal. + /// A `false` literal is `n`, `no`, `f`, `false`, `off` or `0`. + /// An absent environment variable will also be considered as `false`. + /// Anything else will considered as `true`. + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg}; + /// + /// env::set_var("TRUE_FLAG", "true"); + /// env::set_var("FALSE_FLAG", "0"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("true_flag") + /// .long("true_flag") + /// .env("TRUE_FLAG")) + /// .arg(Arg::new("false_flag") + /// .long("false_flag") + /// .env("FALSE_FLAG")) + /// .arg(Arg::new("absent_flag") + /// .long("absent_flag") + /// .env("ABSENT_FLAG")) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(m.is_present("true_flag")); + /// assert_eq!(m.value_of("true_flag"), None); + /// assert!(!m.is_present("false_flag")); + /// assert!(!m.is_present("absent_flag")); + /// ``` + /// + /// In this example, we show the variable coming from an option on the CLI: + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .env("MY_FLAG") + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "prog", "--flag", "opt" + /// ]); + /// + /// assert_eq!(m.value_of("flag"), Some("opt")); + /// ``` + /// + /// In this example, we show the variable coming from the environment even with the + /// presence of a default: + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .env("MY_FLAG") + /// .takes_value(true) + /// .default_value("default")) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("flag"), Some("env")); + /// ``` + /// + /// In this example, we show the use of multiple values in a single environment variable: + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg}; + /// + /// env::set_var("MY_FLAG_MULTI", "env1,env2"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .env("MY_FLAG_MULTI") + /// .takes_value(true) + /// .multiple_values(true) + /// .use_value_delimiter(true)) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.values_of("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]); + /// ``` + /// [`ArgMatches::occurrences_of`]: ArgMatches::occurrences_of() + /// [`ArgMatches::value_of`]: crate::ArgMatches::value_of() + /// [`ArgMatches::is_present`]: ArgMatches::is_present() + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`Arg::use_value_delimiter(true)`]: Arg::use_value_delimiter() + #[cfg(feature = "env")] + #[inline] + #[must_use] + pub fn env(self, name: &'help str) -> Self { + self.env_os(OsStr::new(name)) + } + + /// Read from `name` environment variable when argument is not present. + /// + /// See [`Arg::env`]. + #[cfg(feature = "env")] + #[inline] + #[must_use] + pub fn env_os(mut self, name: &'help OsStr) -> Self { + self.env = Some((name, env::var_os(name))); + self + } +} + +/// # Help +impl<'help> Arg<'help> { + /// Sets the description of the argument for short help (`-h`). + /// + /// Typically, this is a short (one line) description of the arg. + /// + /// If [`Arg::long_help`] is not specified, this message will be displayed for `--help`. + /// + /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise + /// + /// # Examples + /// + /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to + /// include a newline in the help text and have the following text be properly aligned with all + /// the other help text. + /// + /// Setting `help` displays a short message to the side of the argument when the user passes + /// `-h` or `--help` (by default). + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```notrust + /// helptest + /// + /// USAGE: + /// helptest [OPTIONS] + /// + /// OPTIONS: + /// --config Some help text describing the --config arg + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + /// [`Arg::long_help`]: Arg::long_help() + #[inline] + #[must_use] + pub fn help(mut self, h: impl Into<Option<&'help str>>) -> Self { + self.help = h.into(); + self + } + + /// Sets the description of the argument for long help (`--help`). + /// + /// Typically this a more detailed (multi-line) message + /// that describes the arg. + /// + /// If [`Arg::help`] is not specified, this message will be displayed for `-h`. + /// + /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise + /// + /// # Examples + /// + /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to + /// include a newline in the help text and have the following text be properly aligned with all + /// the other help text. + /// + /// Setting `help` displays a short message to the side of the argument when the user passes + /// `-h` or `--help` (by default). + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .long_help( + /// "The config file used by the myprog must be in JSON format + /// with only valid keys and may not contain other nonsense + /// that cannot be read by this program. Obviously I'm going on + /// and on, so I'll stop now.")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```text + /// prog + /// + /// USAGE: + /// prog [OPTIONS] + /// + /// OPTIONS: + /// --config + /// The config file used by the myprog must be in JSON format + /// with only valid keys and may not contain other nonsense + /// that cannot be read by this program. Obviously I'm going on + /// and on, so I'll stop now. + /// + /// -h, --help + /// Print help information + /// + /// -V, --version + /// Print version information + /// ``` + /// [`Arg::help`]: Arg::help() + #[inline] + #[must_use] + pub fn long_help(mut self, h: impl Into<Option<&'help str>>) -> Self { + self.long_help = h.into(); + self + } + + /// Allows custom ordering of args within the help message. + /// + /// Args with a lower value will be displayed first in the help message. This is helpful when + /// one would like to emphasise frequently used args, or prioritize those towards the top of + /// the list. Args with duplicate display orders will be displayed in alphabetical order. + /// + /// **NOTE:** The default is 999 for all arguments. + /// + /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in + /// [index] order. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("a") // Typically args are grouped alphabetically by name. + /// // Args without a display_order have a value of 999 and are + /// // displayed alphabetically with all other 999 valued args. + /// .long("long-option") + /// .short('o') + /// .takes_value(true) + /// .help("Some help and text")) + /// .arg(Arg::new("b") + /// .long("other-option") + /// .short('O') + /// .takes_value(true) + /// .display_order(1) // In order to force this arg to appear *first* + /// // all we have to do is give it a value lower than 999. + /// // Any other args with a value of 1 will be displayed + /// // alphabetically with this one...then 2 values, then 3, etc. + /// .help("I should be first!")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays the following help message + /// + /// ```text + /// cust-ord + /// + /// USAGE: + /// cust-ord [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// -O, --other-option <b> I should be first! + /// -o, --long-option <a> Some help and text + /// ``` + /// [positional arguments]: Arg::index() + /// [index]: Arg::index() + #[inline] + #[must_use] + pub fn display_order(mut self, ord: usize) -> Self { + self.disp_ord.set_explicit(ord); + self + } + + /// Override the [current] help section. + /// + /// [current]: crate::Command::help_heading + #[inline] + #[must_use] + pub fn help_heading<O>(mut self, heading: O) -> Self + where + O: Into<Option<&'help str>>, + { + self.help_heading = Some(heading.into()); + self + } + + /// Render the [help][Arg::help] on the line after the argument. + /// + /// This can be helpful for arguments with very long or complex help messages. + /// This can also be helpful for arguments with very long flag names, or many/long value names. + /// + /// **NOTE:** To apply this setting to all arguments and subcommands, consider using + /// [`crate::Command::next_line_help`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .long("long-option-flag") + /// .short('o') + /// .takes_value(true) + /// .next_line_help(true) + /// .value_names(&["value1", "value2"]) + /// .help("Some really long help and complex\n\ + /// help that makes more sense to be\n\ + /// on a line after the option")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays the following help message + /// + /// ```text + /// nlh + /// + /// USAGE: + /// nlh [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// -o, --long-option-flag <value1> <value2> + /// Some really long help and complex + /// help that makes more sense to be + /// on a line after the option + /// ``` + #[inline] + #[must_use] + pub fn next_line_help(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::NextLineHelp) + } else { + self.unset_setting(ArgSettings::NextLineHelp) + } + } + + /// Do not display the argument in help message. + /// + /// **NOTE:** This does **not** hide the argument from usage strings on error + /// + /// # Examples + /// + /// Setting `Hidden` will hide the argument when displaying help text + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```text + /// helptest + /// + /// USAGE: + /// helptest [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + #[inline] + #[must_use] + pub fn hide(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Hidden) + } else { + self.unset_setting(ArgSettings::Hidden) + } + } + + /// Do not display the [possible values][Arg::possible_values] in the help message. + /// + /// This is useful for args with many values, or ones which are explained elsewhere in the + /// help text. + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// To set this for all arguments, see + /// [`Command::hide_possible_values`][crate::Command::hide_possible_values]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .possible_values(["fast", "slow"]) + /// .takes_value(true) + /// .hide_possible_values(true)); + /// ``` + /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of + /// the help text would be omitted. + #[inline] + #[must_use] + pub fn hide_possible_values(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HidePossibleValues) + } else { + self.unset_setting(ArgSettings::HidePossibleValues) + } + } + + /// Do not display the default value of the argument in the help message. + /// + /// This is useful when default behavior of an arg is explained elsewhere in the help text. + /// + /// **NOTE:** Setting this requires [`Arg::takes_value`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("connect") + /// .arg(Arg::new("host") + /// .long("host") + /// .default_value("localhost") + /// .takes_value(true) + /// .hide_default_value(true)); + /// + /// ``` + /// + /// If we were to run the above program with `--help` the `[default: localhost]` portion of + /// the help text would be omitted. + #[inline] + #[must_use] + pub fn hide_default_value(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HideDefaultValue) + } else { + self.unset_setting(ArgSettings::HideDefaultValue) + } + } + + /// Do not display in help the environment variable name. + /// + /// This is useful when the variable option is explained elsewhere in the help text. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .env("MODE") + /// .takes_value(true) + /// .hide_env(true)); + /// ``` + /// + /// If we were to run the above program with `--help` the `[env: MODE]` portion of the help + /// text would be omitted. + #[cfg(feature = "env")] + #[inline] + #[must_use] + pub fn hide_env(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HideEnv) + } else { + self.unset_setting(ArgSettings::HideEnv) + } + } + + /// Do not display in help any values inside the associated ENV variables for the argument. + /// + /// This is useful when ENV vars contain sensitive values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("connect") + /// .arg(Arg::new("host") + /// .long("host") + /// .env("CONNECT") + /// .takes_value(true) + /// .hide_env_values(true)); + /// + /// ``` + /// + /// If we were to run the above program with `$ CONNECT=super_secret connect --help` the + /// `[default: CONNECT=super_secret]` portion of the help text would be omitted. + #[cfg(feature = "env")] + #[inline] + #[must_use] + pub fn hide_env_values(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HideEnvValues) + } else { + self.unset_setting(ArgSettings::HideEnvValues) + } + } + + /// Hides an argument from short help (`-h`). + /// + /// **NOTE:** This does **not** hide the argument from usage strings on error + /// + /// **NOTE:** Setting this option will cause next-line-help output style to be used + /// when long help (`--help`) is called. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("debug") + /// .hide_short_help(true); + /// ``` + /// + /// Setting `hide_short_help(true)` will hide the argument when displaying short help text + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide_short_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "-h" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```text + /// helptest + /// + /// USAGE: + /// helptest [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + /// + /// However, when --help is called + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide_short_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// Then the following would be displayed + /// + /// ```text + /// helptest + /// + /// USAGE: + /// helptest [OPTIONS] + /// + /// OPTIONS: + /// --config Some help text describing the --config arg + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + #[inline] + #[must_use] + pub fn hide_short_help(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HiddenShortHelp) + } else { + self.unset_setting(ArgSettings::HiddenShortHelp) + } + } + + /// Hides an argument from long help (`--help`). + /// + /// **NOTE:** This does **not** hide the argument from usage strings on error + /// + /// **NOTE:** Setting this option will cause next-line-help output style to be used + /// when long help (`--help`) is called. + /// + /// # Examples + /// + /// Setting `hide_long_help(true)` will hide the argument when displaying long help text + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide_long_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```text + /// helptest + /// + /// USAGE: + /// helptest [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + /// + /// However, when -h is called + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide_long_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "-h" + /// ]); + /// ``` + /// + /// Then the following would be displayed + /// + /// ```text + /// helptest + /// + /// USAGE: + /// helptest [OPTIONS] + /// + /// OPTIONS: + /// --config Some help text describing the --config arg + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + #[inline] + #[must_use] + pub fn hide_long_help(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HiddenLongHelp) + } else { + self.unset_setting(ArgSettings::HiddenLongHelp) + } + } +} + +/// # Advanced Argument Relations +impl<'help> Arg<'help> { + /// The name of the [`ArgGroup`] the argument belongs to. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("debug") + /// .long("debug") + /// .group("mode") + /// # ; + /// ``` + /// + /// Multiple arguments can be a member of a single group and then the group checked as if it + /// was one of said arguments. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("debug") + /// .long("debug") + /// .group("mode")) + /// .arg(Arg::new("verbose") + /// .long("verbose") + /// .group("mode")) + /// .get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// assert!(m.is_present("mode")); + /// ``` + /// + /// [`ArgGroup`]: crate::ArgGroup + #[must_use] + pub fn group<T: Key>(mut self, group_id: T) -> Self { + self.groups.push(group_id.into()); + self + } + + /// The names of [`ArgGroup`]'s the argument belongs to. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("debug") + /// .long("debug") + /// .groups(&["mode", "verbosity"]) + /// # ; + /// ``` + /// + /// Arguments can be members of multiple groups and then the group checked as if it + /// was one of said arguments. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("debug") + /// .long("debug") + /// .groups(&["mode", "verbosity"])) + /// .arg(Arg::new("verbose") + /// .long("verbose") + /// .groups(&["mode", "verbosity"])) + /// .get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// assert!(m.is_present("mode")); + /// assert!(m.is_present("verbosity")); + /// ``` + /// + /// [`ArgGroup`]: crate::ArgGroup + #[must_use] + pub fn groups<T: Key>(mut self, group_ids: &[T]) -> Self { + self.groups.extend(group_ids.iter().map(Id::from)); + self + } + + /// Specifies the value of the argument if `arg` has been used at runtime. + /// + /// If `val` is set to `None`, `arg` only needs to be present. If `val` is set to `"some-val"` + /// then `arg` must be present at runtime **and** have the value `val`. + /// + /// If `default` is set to `None`, `default_value` will be removed. + /// + /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly + /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg + /// at runtime. This setting however only takes effect when the user has not provided a value at + /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value` + /// and `Arg::default_value_if`, and the user **did not** provide this arg at runtime, nor were + /// the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be applied. + /// + /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. + /// + /// # Examples + /// + /// First we use the default value only if another arg is present at runtime. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_if("flag", None, Some("default"))) + /// .get_matches_from(vec![ + /// "prog", "--flag" + /// ]); + /// + /// assert_eq!(m.value_of("other"), Some("default")); + /// ``` + /// + /// Next we run the same test, but without providing `--flag`. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_if("flag", None, Some("default"))) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("other"), None); + /// ``` + /// + /// Now lets only use the default value if `--opt` contains the value `special`. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .takes_value(true) + /// .long("opt")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_if("opt", Some("special"), Some("default"))) + /// .get_matches_from(vec![ + /// "prog", "--opt", "special" + /// ]); + /// + /// assert_eq!(m.value_of("other"), Some("default")); + /// ``` + /// + /// We can run the same test and provide any value *other than* `special` and we won't get a + /// default value. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .takes_value(true) + /// .long("opt")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_if("opt", Some("special"), Some("default"))) + /// .get_matches_from(vec![ + /// "prog", "--opt", "hahaha" + /// ]); + /// + /// assert_eq!(m.value_of("other"), None); + /// ``` + /// + /// If we want to unset the default value for an Arg based on the presence or + /// value of some other Arg. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value("default") + /// .default_value_if("flag", None, None)) + /// .get_matches_from(vec![ + /// "prog", "--flag" + /// ]); + /// + /// assert_eq!(m.value_of("other"), None); + /// ``` + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`Arg::default_value`]: Arg::default_value() + #[must_use] + pub fn default_value_if<T: Key>( + self, + arg_id: T, + val: Option<&'help str>, + default: Option<&'help str>, + ) -> Self { + self.default_value_if_os(arg_id, val.map(OsStr::new), default.map(OsStr::new)) + } + + /// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`] + /// only using [`OsStr`]s instead. + /// + /// [`Arg::default_value_if`]: Arg::default_value_if() + /// [`OsStr`]: std::ffi::OsStr + #[must_use] + pub fn default_value_if_os<T: Key>( + mut self, + arg_id: T, + val: Option<&'help OsStr>, + default: Option<&'help OsStr>, + ) -> Self { + self.default_vals_ifs + .push((arg_id.into(), val.into(), default)); + self.takes_value(true) + } + + /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`]. + /// + /// The method takes a slice of tuples in the `(arg, Option<val>, default)` format. + /// + /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first + /// if multiple conditions are true, the first one found will be applied and the ultimate value. + /// + /// # Examples + /// + /// First we use the default value only if another arg is present at runtime. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag")) + /// .arg(Arg::new("opt") + /// .long("opt") + /// .takes_value(true)) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_ifs(&[ + /// ("flag", None, Some("default")), + /// ("opt", Some("channal"), Some("chan")), + /// ])) + /// .get_matches_from(vec![ + /// "prog", "--opt", "channal" + /// ]); + /// + /// assert_eq!(m.value_of("other"), Some("chan")); + /// ``` + /// + /// Next we run the same test, but without providing `--flag`. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_ifs(&[ + /// ("flag", None, Some("default")), + /// ("opt", Some("channal"), Some("chan")), + /// ])) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.value_of("other"), None); + /// ``` + /// + /// We can also see that these values are applied in order, and if more than one condition is + /// true, only the first evaluated "wins" + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag")) + /// .arg(Arg::new("opt") + /// .long("opt") + /// .takes_value(true)) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_ifs(&[ + /// ("flag", None, Some("default")), + /// ("opt", Some("channal"), Some("chan")), + /// ])) + /// .get_matches_from(vec![ + /// "prog", "--opt", "channal", "--flag" + /// ]); + /// + /// assert_eq!(m.value_of("other"), Some("default")); + /// ``` + /// [`Arg::takes_value(true)`]: Arg::takes_value() + /// [`Arg::default_value_if`]: Arg::default_value_if() + #[must_use] + pub fn default_value_ifs<T: Key>( + mut self, + ifs: &[(T, Option<&'help str>, Option<&'help str>)], + ) -> Self { + for (arg, val, default) in ifs { + self = self.default_value_if_os(arg, val.map(OsStr::new), default.map(OsStr::new)); + } + self + } + + /// Provides multiple conditional default values in the exact same manner as + /// [`Arg::default_value_ifs`] only using [`OsStr`]s instead. + /// + /// [`Arg::default_value_ifs`]: Arg::default_value_ifs() + /// [`OsStr`]: std::ffi::OsStr + #[must_use] + pub fn default_value_ifs_os<T: Key>( + mut self, + ifs: &[(T, Option<&'help OsStr>, Option<&'help OsStr>)], + ) -> Self { + for (arg, val, default) in ifs { + self = self.default_value_if_os(arg.key(), *val, *default); + } + self + } + + /// Set this arg as [required] as long as the specified argument is not present at runtime. + /// + /// **Pro Tip:** Using `Arg::required_unless_present` implies [`Arg::required`] and is therefore not + /// mandatory to also set. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_unless_present("debug") + /// # ; + /// ``` + /// + /// In the following example, the required argument is *not* provided, + /// but it's not an error because the `unless` arg has been supplied. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present("dbg") + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug")) + /// .try_get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting `Arg::required_unless_present(name)` and *not* supplying `name` or this arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present("dbg") + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug")) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required]: Arg::required() + #[must_use] + pub fn required_unless_present<T: Key>(mut self, arg_id: T) -> Self { + self.r_unless.push(arg_id.into()); + self + } + + /// Sets this arg as [required] unless *all* of the specified arguments are present at runtime. + /// + /// In other words, parsing will succeed only if user either + /// * supplies the `self` arg. + /// * supplies *all* of the `names` arguments. + /// + /// **NOTE:** If you wish for this argument to only be required unless *any of* these args are + /// present see [`Arg::required_unless_present_any`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_unless_present_all(&["cfg", "dbg"]) + /// # ; + /// ``` + /// + /// In the following example, the required argument is *not* provided, but it's not an error + /// because *all* of the `names` args have been supplied. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present_all(&["dbg", "infile"]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug")) + /// .arg(Arg::new("infile") + /// .short('i') + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--debug", "-i", "file" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting [`Arg::required_unless_present_all(names)`] and *not* supplying + /// either *all* of `unless` args or the `self` arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present_all(&["dbg", "infile"]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug")) + /// .arg(Arg::new("infile") + /// .short('i') + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required]: Arg::required() + /// [`Arg::required_unless_present_any`]: Arg::required_unless_present_any() + /// [`Arg::required_unless_present_all(names)`]: Arg::required_unless_present_all() + #[must_use] + pub fn required_unless_present_all<T, I>(mut self, names: I) -> Self + where + I: IntoIterator<Item = T>, + T: Key, + { + self.r_unless_all.extend(names.into_iter().map(Id::from)); + self + } + + /// Sets this arg as [required] unless *any* of the specified arguments are present at runtime. + /// + /// In other words, parsing will succeed only if user either + /// * supplies the `self` arg. + /// * supplies *one or more* of the `unless` arguments. + /// + /// **NOTE:** If you wish for this argument to be required unless *all of* these args are + /// present see [`Arg::required_unless_present_all`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_unless_present_any(&["cfg", "dbg"]) + /// # ; + /// ``` + /// + /// Setting [`Arg::required_unless_present_any(names)`] requires that the argument be used at runtime + /// *unless* *at least one of* the args in `names` are present. In the following example, the + /// required argument is *not* provided, but it's not an error because one the `unless` args + /// have been supplied. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present_any(&["dbg", "infile"]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug")) + /// .arg(Arg::new("infile") + /// .short('i') + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting [`Arg::required_unless_present_any(names)`] and *not* supplying *at least one of* `names` + /// or this arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present_any(&["dbg", "infile"]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug")) + /// .arg(Arg::new("infile") + /// .short('i') + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required]: Arg::required() + /// [`Arg::required_unless_present_any(names)`]: Arg::required_unless_present_any() + /// [`Arg::required_unless_present_all`]: Arg::required_unless_present_all() + #[must_use] + pub fn required_unless_present_any<T, I>(mut self, names: I) -> Self + where + I: IntoIterator<Item = T>, + T: Key, + { + self.r_unless.extend(names.into_iter().map(Id::from)); + self + } + + /// This argument is [required] only if the specified `arg` is present at runtime and its value + /// equals `val`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_if_eq("other_arg", "value") + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .required_if_eq("other", "special") + /// .long("config")) + /// .arg(Arg::new("other") + /// .long("other") + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--other", "not-special" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required + /// + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .required_if_eq("other", "special") + /// .long("config")) + /// .arg(Arg::new("other") + /// .long("other") + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--other", "special" + /// ]); + /// + /// // We did use --other=special so "cfg" had become required but was missing. + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .required_if_eq("other", "special") + /// .long("config")) + /// .arg(Arg::new("other") + /// .long("other") + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--other", "SPECIAL" + /// ]); + /// + /// // By default, the comparison is case-sensitive, so "cfg" wasn't required + /// assert!(res.is_ok()); + /// + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .required_if_eq("other", "special") + /// .long("config")) + /// .arg(Arg::new("other") + /// .long("other") + /// .ignore_case(true) + /// .takes_value(true)) + /// .try_get_matches_from(vec![ + /// "prog", "--other", "SPECIAL" + /// ]); + /// + /// // However, case-insensitive comparisons can be enabled. This typically occurs when using Arg::possible_values(). + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [required]: Arg::required() + #[must_use] + pub fn required_if_eq<T: Key>(mut self, arg_id: T, val: &'help str) -> Self { + self.r_ifs.push((arg_id.into(), val)); + self + } + + /// Specify this argument is [required] based on multiple conditions. + /// + /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become + /// valid if one of the specified `arg`'s value equals its corresponding `val`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_if_eq_any(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// # ; + /// ``` + /// + /// Setting `Arg::required_if_eq_any(&[(arg, val)])` makes this arg required if any of the `arg`s + /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is + /// anything other than `val`, this argument isn't required. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_if_eq_any(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("extra") + /// .takes_value(true) + /// .long("extra")) + /// .arg(Arg::new("option") + /// .takes_value(true) + /// .long("option")) + /// .try_get_matches_from(vec![ + /// "prog", "--option", "other" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required + /// ``` + /// + /// Setting `Arg::required_if_eq_any(&[(arg, val)])` and having any of the `arg`s used with its + /// value of `val` but *not* using this arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_if_eq_any(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("extra") + /// .takes_value(true) + /// .long("extra")) + /// .arg(Arg::new("option") + /// .takes_value(true) + /// .long("option")) + /// .try_get_matches_from(vec![ + /// "prog", "--option", "spec" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [required]: Arg::required() + #[must_use] + pub fn required_if_eq_any<T: Key>(mut self, ifs: &[(T, &'help str)]) -> Self { + self.r_ifs + .extend(ifs.iter().map(|(id, val)| (Id::from_ref(id), *val))); + self + } + + /// Specify this argument is [required] based on multiple conditions. + /// + /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become + /// valid if every one of the specified `arg`'s value equals its corresponding `val`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_if_eq_all(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// # ; + /// ``` + /// + /// Setting `Arg::required_if_eq_all(&[(arg, val)])` makes this arg required if all of the `arg`s + /// are used at runtime and every value is equal to its corresponding `val`. If the `arg`'s value is + /// anything other than `val`, this argument isn't required. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_if_eq_all(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("extra") + /// .takes_value(true) + /// .long("extra")) + /// .arg(Arg::new("option") + /// .takes_value(true) + /// .long("option")) + /// .try_get_matches_from(vec![ + /// "prog", "--option", "spec" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required + /// ``` + /// + /// Setting `Arg::required_if_eq_all(&[(arg, val)])` and having all of the `arg`s used with its + /// value of `val` but *not* using this arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_if_eq_all(&[ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .takes_value(true) + /// .long("config")) + /// .arg(Arg::new("extra") + /// .takes_value(true) + /// .long("extra")) + /// .arg(Arg::new("option") + /// .takes_value(true) + /// .long("option")) + /// .try_get_matches_from(vec![ + /// "prog", "--extra", "val", "--option", "spec" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required]: Arg::required() + #[must_use] + pub fn required_if_eq_all<T: Key>(mut self, ifs: &[(T, &'help str)]) -> Self { + self.r_ifs_all + .extend(ifs.iter().map(|(id, val)| (Id::from_ref(id), *val))); + self + } + + /// Require another argument if this arg was present at runtime and its value equals to `val`. + /// + /// This method takes `value, another_arg` pair. At runtime, clap will check + /// if this arg (`self`) is present and its value equals to `val`. + /// If it does, `another_arg` will be marked as required. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .requires_if("val", "arg") + /// # ; + /// ``` + /// + /// Setting `Arg::requires_if(val, arg)` requires that the `arg` be used at runtime if the + /// defining argument's value is equal to `val`. If the defining argument is anything other than + /// `val`, the other argument isn't required. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires_if("my.cfg", "other") + /// .long("config")) + /// .arg(Arg::new("other")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "some.cfg" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required + /// ``` + /// + /// Setting `Arg::requires_if(val, arg)` and setting the value to `val` but *not* supplying + /// `arg` is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires_if("my.cfg", "input") + /// .long("config")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "my.cfg" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [override]: Arg::overrides_with() + #[must_use] + pub fn requires_if<T: Key>(mut self, val: &'help str, arg_id: T) -> Self { + self.requires + .push((ArgPredicate::Equals(OsStr::new(val)), arg_id.into())); + self + } + + /// Allows multiple conditional requirements. + /// + /// The requirement will only become valid if this arg's value equals `val`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .requires_ifs(&[ + /// ("val", "arg"), + /// ("other_val", "arg2"), + /// ]) + /// # ; + /// ``` + /// + /// Setting `Arg::requires_ifs(&["val", "arg"])` requires that the `arg` be used at runtime if the + /// defining argument's value is equal to `val`. If the defining argument's value is anything other + /// than `val`, `arg` isn't required. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires_ifs(&[ + /// ("special.conf", "opt"), + /// ("other.conf", "other"), + /// ]) + /// .long("config")) + /// .arg(Arg::new("opt") + /// .long("option") + /// .takes_value(true)) + /// .arg(Arg::new("other")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "special.conf" + /// ]); + /// + /// assert!(res.is_err()); // We used --config=special.conf so --option <val> is required + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [override]: Arg::overrides_with() + #[must_use] + pub fn requires_ifs<T: Key>(mut self, ifs: &[(&'help str, T)]) -> Self { + self.requires.extend( + ifs.iter() + .map(|(val, arg)| (ArgPredicate::Equals(OsStr::new(*val)), Id::from(arg))), + ); + self + } + + /// Require these arguments names when this one is presen + /// + /// i.e. when using this argument, the following arguments *must* be present. + /// + /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required + /// by default. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .requires_all(&["input", "output"]) + /// # ; + /// ``` + /// + /// Setting `Arg::requires_all(&[arg, arg2])` requires that all the arguments be used at + /// runtime if the defining argument is used. If the defining argument isn't used, the other + /// argument isn't required + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::new("input")) + /// .arg(Arg::new("output")) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required + /// ``` + /// + /// Setting `Arg::requires_all(&[arg, arg2])` and *not* supplying all the arguments is an + /// error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .requires_all(&["input", "output"]) + /// .long("config")) + /// .arg(Arg::new("input")) + /// .arg(Arg::new("output")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf", "in.txt" + /// ]); + /// + /// assert!(res.is_err()); + /// // We didn't use output + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [Conflicting]: Arg::conflicts_with() + /// [override]: Arg::overrides_with() + #[must_use] + pub fn requires_all<T: Key>(mut self, names: &[T]) -> Self { + self.requires + .extend(names.iter().map(|s| (ArgPredicate::IsPresent, s.into()))); + self + } + + /// This argument is mutually exclusive with the specified argument. + /// + /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules + /// only need to be set for one of the two arguments, they do not need to be set for each. + /// + /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments + /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not + /// need to also do B.conflicts_with(A)) + /// + /// **NOTE:** [`Arg::conflicts_with_all(names)`] allows specifying an argument which conflicts with more than one argument. + /// + /// **NOTE** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .conflicts_with("debug") + /// # ; + /// ``` + /// + /// Setting conflicting argument, and having both arguments present at runtime is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .conflicts_with("debug") + /// .long("config")) + /// .arg(Arg::new("debug") + /// .long("debug")) + /// .try_get_matches_from(vec![ + /// "prog", "--debug", "--config", "file.conf" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); + /// ``` + /// + /// [`Arg::conflicts_with_all(names)`]: Arg::conflicts_with_all() + /// [`Arg::exclusive(true)`]: Arg::exclusive() + #[must_use] + pub fn conflicts_with<T: Key>(mut self, arg_id: T) -> Self { + self.blacklist.push(arg_id.into()); + self + } + + /// This argument is mutually exclusive with the specified arguments. + /// + /// See [`Arg::conflicts_with`]. + /// + /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules + /// only need to be set for one of the two arguments, they do not need to be set for each. + /// + /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments + /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need + /// need to also do B.conflicts_with(A)) + /// + /// **NOTE:** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .conflicts_with_all(&["debug", "input"]) + /// # ; + /// ``` + /// + /// Setting conflicting argument, and having any of the arguments present at runtime with a + /// conflicting argument is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .takes_value(true) + /// .conflicts_with_all(&["debug", "input"]) + /// .long("config")) + /// .arg(Arg::new("debug") + /// .long("debug")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf", "file.txt" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); + /// ``` + /// [`Arg::conflicts_with`]: Arg::conflicts_with() + /// [`Arg::exclusive(true)`]: Arg::exclusive() + #[must_use] + pub fn conflicts_with_all(mut self, names: &[&str]) -> Self { + self.blacklist.extend(names.iter().copied().map(Id::from)); + self + } + + /// Sets an overridable argument. + /// + /// i.e. this argument and the following argument + /// will override each other in POSIX style (whichever argument was specified at runtime + /// **last** "wins") + /// + /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any + /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed + /// + /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with`]. + /// + /// **WARNING:** Positional arguments and options which accept + /// [`Arg::multiple_occurrences`] cannot override themselves (or we + /// would never be able to advance to the next positional). If a positional + /// argument or option with one of the [`Arg::multiple_occurrences`] + /// settings lists itself as an override, it is simply ignored. + /// + /// # Examples + /// + /// ```rust # use clap::{Command, Arg}; + /// # use clap::{Command, arg}; + /// let m = Command::new("prog") + /// .arg(arg!(-f --flag "some flag") + /// .conflicts_with("debug")) + /// .arg(arg!(-d --debug "other flag")) + /// .arg(arg!(-c --color "third flag") + /// .overrides_with("flag")) + /// .get_matches_from(vec![ + /// "prog", "-f", "-d", "-c"]); + /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color + /// + /// assert!(m.is_present("color")); + /// assert!(m.is_present("debug")); // even though flag conflicts with debug, it's as if flag + /// // was never used because it was overridden with color + /// assert!(!m.is_present("flag")); + /// ``` + /// Care must be taken when using this setting, and having an arg override with itself. This + /// is common practice when supporting things like shell aliases, config files, etc. + /// However, when combined with multiple values, it can get dicy. + /// Here is how clap handles such situations: + /// + /// When a flag overrides itself, it's as if the flag was only ever used once (essentially + /// preventing a "Unexpected multiple usage" error): + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let m = Command::new("posix") + /// .arg(arg!(--flag "some flag").overrides_with("flag")) + /// .get_matches_from(vec!["posix", "--flag", "--flag"]); + /// assert!(m.is_present("flag")); + /// assert_eq!(m.occurrences_of("flag"), 1); + /// ``` + /// + /// Making an arg [`Arg::multiple_occurrences`] and override itself + /// is essentially meaningless. Therefore clap ignores an override of self + /// if it's a flag and it already accepts multiple occurrences. + /// + /// ``` + /// # use clap::{Command, arg}; + /// let m = Command::new("posix") + /// .arg(arg!(--flag ... "some flag").overrides_with("flag")) + /// .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]); + /// assert!(m.is_present("flag")); + /// assert_eq!(m.occurrences_of("flag"), 4); + /// ``` + /// + /// Now notice with options (which *do not* set + /// [`Arg::multiple_occurrences`]), it's as if only the last + /// occurrence happened. + /// + /// ``` + /// # use clap::{Command, arg}; + /// let m = Command::new("posix") + /// .arg(arg!(--opt <val> "some option").overrides_with("opt")) + /// .get_matches_from(vec!["", "--opt=some", "--opt=other"]); + /// assert!(m.is_present("opt")); + /// assert_eq!(m.occurrences_of("opt"), 1); + /// assert_eq!(m.value_of("opt"), Some("other")); + /// ``` + /// + /// This will also work when [`Arg::multiple_values`] is enabled: + /// + /// ``` + /// # use clap::{Command, Arg}; + /// let m = Command::new("posix") + /// .arg( + /// Arg::new("opt") + /// .long("opt") + /// .takes_value(true) + /// .multiple_values(true) + /// .overrides_with("opt") + /// ) + /// .get_matches_from(vec!["", "--opt", "1", "2", "--opt", "3", "4", "5"]); + /// assert!(m.is_present("opt")); + /// assert_eq!(m.occurrences_of("opt"), 1); + /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["3", "4", "5"]); + /// ``` + /// + /// Just like flags, options with [`Arg::multiple_occurrences`] set + /// will ignore the "override self" setting. + /// + /// ``` + /// # use clap::{Command, arg}; + /// let m = Command::new("posix") + /// .arg(arg!(--opt <val> ... "some option") + /// .multiple_values(true) + /// .overrides_with("opt")) + /// .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]); + /// assert!(m.is_present("opt")); + /// assert_eq!(m.occurrences_of("opt"), 2); + /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["first", "over", "other", "val"]); + /// ``` + #[must_use] + pub fn overrides_with<T: Key>(mut self, arg_id: T) -> Self { + self.overrides.push(arg_id.into()); + self + } + + /// Sets multiple mutually overridable arguments by name. + /// + /// i.e. this argument and the following argument will override each other in POSIX style + /// (whichever argument was specified at runtime **last** "wins") + /// + /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any + /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed + /// + /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with_all`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let m = Command::new("prog") + /// .arg(arg!(-f --flag "some flag") + /// .conflicts_with("color")) + /// .arg(arg!(-d --debug "other flag")) + /// .arg(arg!(-c --color "third flag") + /// .overrides_with_all(&["flag", "debug"])) + /// .get_matches_from(vec![ + /// "prog", "-f", "-d", "-c"]); + /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color + /// + /// assert!(m.is_present("color")); // even though flag conflicts with color, it's as if flag + /// // and debug were never used because they were overridden + /// // with color + /// assert!(!m.is_present("debug")); + /// assert!(!m.is_present("flag")); + /// ``` + #[must_use] + pub fn overrides_with_all<T: Key>(mut self, names: &[T]) -> Self { + self.overrides.extend(names.iter().map(Id::from)); + self + } +} + +/// # Reflection +impl<'help> Arg<'help> { + /// Get the name of the argument + #[inline] + pub fn get_id(&self) -> &'help str { + self.name + } + + /// Deprecated, replaced with [`Arg::get_id`] + #[deprecated(since = "3.1.0", note = "Replaced with `Arg::get_id`")] + pub fn get_name(&self) -> &'help str { + self.get_id() + } + + /// Get the help specified for this argument, if any + #[inline] + pub fn get_help(&self) -> Option<&'help str> { + self.help + } + + /// Get the long help specified for this argument, if any + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// let arg = Arg::new("foo").long_help("long help"); + /// assert_eq!(Some("long help"), arg.get_long_help()); + /// ``` + /// + #[inline] + pub fn get_long_help(&self) -> Option<&'help str> { + self.long_help + } + + /// Get the help heading specified for this argument, if any + #[inline] + pub fn get_help_heading(&self) -> Option<&'help str> { + self.help_heading.unwrap_or_default() + } + + /// Get the short option name for this argument, if any + #[inline] + pub fn get_short(&self) -> Option<char> { + self.short + } + + /// Get visible short aliases for this argument, if any + #[inline] + pub fn get_visible_short_aliases(&self) -> Option<Vec<char>> { + if self.short_aliases.is_empty() { + None + } else { + Some( + self.short_aliases + .iter() + .filter_map(|(c, v)| if *v { Some(c) } else { None }) + .copied() + .collect(), + ) + } + } + + /// Get the short option name and its visible aliases, if any + #[inline] + pub fn get_short_and_visible_aliases(&self) -> Option<Vec<char>> { + let mut shorts = match self.short { + Some(short) => vec![short], + None => return None, + }; + if let Some(aliases) = self.get_visible_short_aliases() { + shorts.extend(aliases); + } + Some(shorts) + } + + /// Get the long option name for this argument, if any + #[inline] + pub fn get_long(&self) -> Option<&'help str> { + self.long + } + + /// Get visible aliases for this argument, if any + #[inline] + pub fn get_visible_aliases(&self) -> Option<Vec<&'help str>> { + if self.aliases.is_empty() { + None + } else { + Some( + self.aliases + .iter() + .filter_map(|(s, v)| if *v { Some(s) } else { None }) + .copied() + .collect(), + ) + } + } + + /// Get the long option name and its visible aliases, if any + #[inline] + pub fn get_long_and_visible_aliases(&self) -> Option<Vec<&'help str>> { + let mut longs = match self.long { + Some(long) => vec![long], + None => return None, + }; + if let Some(aliases) = self.get_visible_aliases() { + longs.extend(aliases); + } + Some(longs) + } + + /// Get the list of the possible values for this argument, if any + #[inline] + pub fn get_possible_values(&self) -> Option<&[PossibleValue]> { + if self.possible_vals.is_empty() { + None + } else { + Some(&self.possible_vals) + } + } + + /// Get the names of values for this argument. + #[inline] + pub fn get_value_names(&self) -> Option<&[&'help str]> { + if self.val_names.is_empty() { + None + } else { + Some(&self.val_names) + } + } + + /// Get the number of values for this argument. + #[inline] + pub fn get_num_vals(&self) -> Option<usize> { + self.num_vals + } + + /// Get the delimiter between multiple values + #[inline] + pub fn get_value_delimiter(&self) -> Option<char> { + self.val_delim + } + + /// Get the index of this argument, if any + #[inline] + pub fn get_index(&self) -> Option<usize> { + self.index + } + + /// Get the value hint of this argument + pub fn get_value_hint(&self) -> ValueHint { + self.value_hint + } + + /// Deprecated, replaced with [`Arg::is_global_set`] + #[deprecated(since = "3.1.0", note = "Replaced with `Arg::is_global_set`")] + pub fn get_global(&self) -> bool { + self.is_global_set() + } + + /// Get the environment variable name specified for this argument, if any + /// + /// # Examples + /// + /// ```rust + /// # use std::ffi::OsStr; + /// # use clap::Arg; + /// let arg = Arg::new("foo").env("ENVIRONMENT"); + /// assert_eq!(Some(OsStr::new("ENVIRONMENT")), arg.get_env()); + /// ``` + #[cfg(feature = "env")] + pub fn get_env(&self) -> Option<&OsStr> { + self.env.as_ref().map(|x| x.0) + } + + /// Get the default values specified for this argument, if any + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// let arg = Arg::new("foo").default_value("default value"); + /// assert_eq!(&["default value"], arg.get_default_values()); + /// ``` + pub fn get_default_values(&self) -> &[&OsStr] { + &self.default_vals + } + + /// Checks whether this argument is a positional or not. + /// + /// # Examples + /// + /// ``` + /// # use clap::Arg; + /// let arg = Arg::new("foo"); + /// assert_eq!(true, arg.is_positional()); + /// + /// let arg = Arg::new("foo").long("foo"); + /// assert_eq!(false, arg.is_positional()); + /// ``` + pub fn is_positional(&self) -> bool { + self.long.is_none() && self.short.is_none() + } + + /// Reports whether [`Arg::required`] is set + pub fn is_required_set(&self) -> bool { + self.is_set(ArgSettings::Required) + } + + /// Report whether [`Arg::multiple_values`] is set + pub fn is_multiple_values_set(&self) -> bool { + self.is_set(ArgSettings::MultipleValues) + } + + /// Report whether [`Arg::multiple_occurrences`] is set + pub fn is_multiple_occurrences_set(&self) -> bool { + self.is_set(ArgSettings::MultipleOccurrences) + } + + /// Report whether [`Arg::is_takes_value_set`] is set + pub fn is_takes_value_set(&self) -> bool { + self.is_set(ArgSettings::TakesValue) + } + + /// Report whether [`Arg::allow_hyphen_values`] is set + pub fn is_allow_hyphen_values_set(&self) -> bool { + self.is_set(ArgSettings::AllowHyphenValues) + } + + /// Report whether [`Arg::forbid_empty_values`] is set + pub fn is_forbid_empty_values_set(&self) -> bool { + self.is_set(ArgSettings::ForbidEmptyValues) + } + + /// Report whether [`Arg::is_allow_invalid_utf8_set`] is set + pub fn is_allow_invalid_utf8_set(&self) -> bool { + self.is_set(ArgSettings::AllowInvalidUtf8) + } + + /// Report whether [`Arg::global`] is set + pub fn is_global_set(&self) -> bool { + self.is_set(ArgSettings::Global) + } + + /// Report whether [`Arg::next_line_help`] is set + pub fn is_next_line_help_set(&self) -> bool { + self.is_set(ArgSettings::NextLineHelp) + } + + /// Report whether [`Arg::hide`] is set + pub fn is_hide_set(&self) -> bool { + self.is_set(ArgSettings::Hidden) + } + + /// Report whether [`Arg::hide_default_value`] is set + pub fn is_hide_default_value_set(&self) -> bool { + self.is_set(ArgSettings::HideDefaultValue) + } + + /// Report whether [`Arg::hide_possible_values`] is set + pub fn is_hide_possible_values_set(&self) -> bool { + self.is_set(ArgSettings::HidePossibleValues) + } + + /// Report whether [`Arg::hide_env`] is set + #[cfg(feature = "env")] + pub fn is_hide_env_set(&self) -> bool { + self.is_set(ArgSettings::HideEnv) + } + + /// Report whether [`Arg::hide_env_values`] is set + #[cfg(feature = "env")] + pub fn is_hide_env_values_set(&self) -> bool { + self.is_set(ArgSettings::HideEnvValues) + } + + /// Report whether [`Arg::hide_short_help`] is set + pub fn is_hide_short_help_set(&self) -> bool { + self.is_set(ArgSettings::HiddenShortHelp) + } + + /// Report whether [`Arg::hide_long_help`] is set + pub fn is_hide_long_help_set(&self) -> bool { + self.is_set(ArgSettings::HiddenLongHelp) + } + + /// Report whether [`Arg::use_value_delimiter`] is set + pub fn is_use_value_delimiter_set(&self) -> bool { + self.is_set(ArgSettings::UseValueDelimiter) + } + + /// Report whether [`Arg::require_value_delimiter`] is set + pub fn is_require_value_delimiter_set(&self) -> bool { + self.is_set(ArgSettings::RequireDelimiter) + } + + /// Report whether [`Arg::require_equals`] is set + pub fn is_require_equals_set(&self) -> bool { + self.is_set(ArgSettings::RequireEquals) + } + + /// Reports whether [`Arg::exclusive`] is set + pub fn is_exclusive_set(&self) -> bool { + self.is_set(ArgSettings::Exclusive) + } + + /// Reports whether [`Arg::last`] is set + pub fn is_last_set(&self) -> bool { + self.is_set(ArgSettings::Last) + } + + /// Reports whether [`Arg::ignore_case`] is set + pub fn is_ignore_case_set(&self) -> bool { + self.is_set(ArgSettings::IgnoreCase) + } +} + +/// # Deprecated +impl<'help> Arg<'help> { + /// Deprecated, replaced with [`Arg::new`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::new`")] + #[doc(hidden)] + pub fn with_name<S: Into<&'help str>>(n: S) -> Self { + Self::new(n) + } + + /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? + #[cfg(feature = "yaml")] + #[deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" + )] + #[doc(hidden)] + pub fn from_yaml(y: &'help Yaml) -> Self { + #![allow(deprecated)] + let yaml_file_hash = y.as_hash().expect("YAML file must be a hash"); + // We WANT this to panic on error...so expect() is good. + let (name_yaml, yaml) = yaml_file_hash + .iter() + .next() + .expect("There must be one arg in the YAML file"); + let name_str = name_yaml.as_str().expect("Arg name must be a string"); + let mut a = Arg::new(name_str); + + for (k, v) in yaml.as_hash().expect("Arg must be a hash") { + a = match k.as_str().expect("Arg fields must be strings") { + "short" => yaml_to_char!(a, v, short), + "long" => yaml_to_str!(a, v, long), + "aliases" => yaml_vec_or_str!(a, v, alias), + "help" => yaml_to_str!(a, v, help), + "long_help" => yaml_to_str!(a, v, long_help), + "required" => yaml_to_bool!(a, v, required), + "required_if" => yaml_tuple2!(a, v, required_if_eq), + "required_ifs" => yaml_tuple2!(a, v, required_if_eq), + "takes_value" => yaml_to_bool!(a, v, takes_value), + "index" => yaml_to_usize!(a, v, index), + "global" => yaml_to_bool!(a, v, global), + "multiple" => yaml_to_bool!(a, v, multiple), + "hidden" => yaml_to_bool!(a, v, hide), + "next_line_help" => yaml_to_bool!(a, v, next_line_help), + "group" => yaml_to_str!(a, v, group), + "number_of_values" => yaml_to_usize!(a, v, number_of_values), + "max_values" => yaml_to_usize!(a, v, max_values), + "min_values" => yaml_to_usize!(a, v, min_values), + "value_name" => yaml_to_str!(a, v, value_name), + "use_delimiter" => yaml_to_bool!(a, v, use_delimiter), + "allow_hyphen_values" => yaml_to_bool!(a, v, allow_hyphen_values), + "last" => yaml_to_bool!(a, v, last), + "require_delimiter" => yaml_to_bool!(a, v, require_delimiter), + "value_delimiter" => yaml_to_char!(a, v, value_delimiter), + "required_unless" => yaml_to_str!(a, v, required_unless_present), + "display_order" => yaml_to_usize!(a, v, display_order), + "default_value" => yaml_to_str!(a, v, default_value), + "default_value_if" => yaml_tuple3!(a, v, default_value_if), + "default_value_ifs" => yaml_tuple3!(a, v, default_value_if), + #[cfg(feature = "env")] + "env" => yaml_to_str!(a, v, env), + "value_names" => yaml_vec_or_str!(a, v, value_name), + "groups" => yaml_vec_or_str!(a, v, group), + "requires" => yaml_vec_or_str!(a, v, requires), + "requires_if" => yaml_tuple2!(a, v, requires_if), + "requires_ifs" => yaml_tuple2!(a, v, requires_if), + "conflicts_with" => yaml_vec_or_str!(a, v, conflicts_with), + "overrides_with" => yaml_to_str!(a, v, overrides_with), + "possible_values" => yaml_vec_or_str!(a, v, possible_value), + "case_insensitive" => yaml_to_bool!(a, v, ignore_case), + "required_unless_one" => yaml_vec!(a, v, required_unless_present_any), + "required_unless_all" => yaml_vec!(a, v, required_unless_present_all), + s => { + panic!( + "Unknown setting '{}' in YAML file for arg '{}'", + s, name_str + ) + } + } + } + + a + } + + /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!]. + #[deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!")] + #[doc(hidden)] + pub fn from_usage(u: &'help str) -> Self { + UsageParser::from_usage(u).parse() + } + + /// Deprecated, replaced with [`Arg::required_unless_present`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::required_unless_present`")] + #[doc(hidden)] + #[must_use] + pub fn required_unless<T: Key>(self, arg_id: T) -> Self { + self.required_unless_present(arg_id) + } + + /// Deprecated, replaced with [`Arg::required_unless_present_all`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `Arg::required_unless_present_all`" + )] + #[doc(hidden)] + #[must_use] + pub fn required_unless_all<T, I>(self, names: I) -> Self + where + I: IntoIterator<Item = T>, + T: Key, + { + self.required_unless_present_all(names) + } + + /// Deprecated, replaced with [`Arg::required_unless_present_any`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `Arg::required_unless_present_any`" + )] + #[doc(hidden)] + #[must_use] + pub fn required_unless_one<T, I>(self, names: I) -> Self + where + I: IntoIterator<Item = T>, + T: Key, + { + self.required_unless_present_any(names) + } + + /// Deprecated, replaced with [`Arg::required_if_eq`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::required_if_eq`")] + #[doc(hidden)] + #[must_use] + pub fn required_if<T: Key>(self, arg_id: T, val: &'help str) -> Self { + self.required_if_eq(arg_id, val) + } + + /// Deprecated, replaced with [`Arg::required_if_eq_any`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::required_if_eq_any`")] + #[doc(hidden)] + #[must_use] + pub fn required_ifs<T: Key>(self, ifs: &[(T, &'help str)]) -> Self { + self.required_if_eq_any(ifs) + } + + /// Deprecated, replaced with [`Arg::hide`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::hide`")] + #[doc(hidden)] + #[inline] + #[must_use] + pub fn hidden(self, yes: bool) -> Self { + self.hide(yes) + } + + /// Deprecated, replaced with [`Arg::ignore_case`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::ignore_case`")] + #[doc(hidden)] + #[inline] + #[must_use] + pub fn case_insensitive(self, yes: bool) -> Self { + self.ignore_case(yes) + } + + /// Deprecated, replaced with [`Arg::forbid_empty_values`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::forbid_empty_values`")] + #[doc(hidden)] + #[must_use] + pub fn empty_values(self, yes: bool) -> Self { + self.forbid_empty_values(!yes) + } + + /// Deprecated, replaced with [`Arg::multiple_occurrences`] (most likely what you want) and + /// [`Arg::multiple_values`] + #[deprecated( + since = "3.0.0", + note = "Split into `Arg::multiple_occurrences` (most likely what you want) and `Arg::multiple_values`" + )] + #[doc(hidden)] + #[must_use] + pub fn multiple(self, yes: bool) -> Self { + self.multiple_occurrences(yes).multiple_values(yes) + } + + /// Deprecated, replaced with [`Arg::hide_short_help`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::hide_short_help`")] + #[doc(hidden)] + #[inline] + #[must_use] + pub fn hidden_short_help(self, yes: bool) -> Self { + self.hide_short_help(yes) + } + + /// Deprecated, replaced with [`Arg::hide_long_help`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::hide_long_help`")] + #[doc(hidden)] + #[inline] + #[must_use] + pub fn hidden_long_help(self, yes: bool) -> Self { + self.hide_long_help(yes) + } + + /// Deprecated, replaced with [`Arg::setting`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::setting`")] + #[doc(hidden)] + #[must_use] + pub fn set(self, s: ArgSettings) -> Self { + self.setting(s) + } + + /// Deprecated, replaced with [`Arg::unset_setting`] + #[deprecated(since = "3.0.0", note = "Replaced with `Arg::unset_setting`")] + #[doc(hidden)] + #[must_use] + pub fn unset(self, s: ArgSettings) -> Self { + self.unset_setting(s) + } +} + +/// # Internally used only +impl<'help> Arg<'help> { + pub(crate) fn _build(&mut self) { + if self.is_positional() { + self.settings.set(ArgSettings::TakesValue); + } + + if (self.is_use_value_delimiter_set() || self.is_require_value_delimiter_set()) + && self.val_delim.is_none() + { + self.val_delim = Some(','); + } + + let val_names_len = self.val_names.len(); + + if val_names_len > 1 { + self.settings.set(ArgSettings::MultipleValues); + + if self.num_vals.is_none() { + self.num_vals = Some(val_names_len); + } + } + + let self_id = self.id.clone(); + if self.is_positional() || self.is_multiple_occurrences_set() { + // Remove self-overrides where they don't make sense. + // + // We can evaluate switching this to a debug assert at a later time (though it will + // require changing propagation of `AllArgsOverrideSelf`). Being conservative for now + // due to where we are at in the release. + self.overrides.retain(|e| *e != self_id); + } + } + + pub(crate) fn generated(mut self) -> Self { + self.provider = ArgProvider::Generated; + self + } + + pub(crate) fn longest_filter(&self) -> bool { + self.is_takes_value_set() || self.long.is_some() || self.short.is_none() + } + + // Used for positionals when printing + pub(crate) fn multiple_str(&self) -> &str { + let mult_vals = self.val_names.len() > 1; + if (self.is_multiple_values_set() || self.is_multiple_occurrences_set()) && !mult_vals { + "..." + } else { + "" + } + } + + // Used for positionals when printing + pub(crate) fn name_no_brackets(&self) -> Cow<str> { + debug!("Arg::name_no_brackets:{}", self.name); + let delim = if self.is_require_value_delimiter_set() { + self.val_delim.expect(INTERNAL_ERROR_MSG) + } else { + ' ' + } + .to_string(); + if !self.val_names.is_empty() { + debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names); + + if self.val_names.len() > 1 { + Cow::Owned( + self.val_names + .iter() + .map(|n| format!("<{}>", n)) + .collect::<Vec<_>>() + .join(&*delim), + ) + } else { + Cow::Borrowed(self.val_names.get(0).expect(INTERNAL_ERROR_MSG)) + } + } else { + debug!("Arg::name_no_brackets: just name"); + Cow::Borrowed(self.name) + } + } + + /// Either multiple values or occurrences + pub(crate) fn is_multiple(&self) -> bool { + self.is_multiple_values_set() | self.is_multiple_occurrences_set() + } + + pub(crate) fn get_display_order(&self) -> usize { + self.disp_ord.get_explicit() + } +} + +impl<'help> From<&'_ Arg<'help>> for Arg<'help> { + fn from(a: &Arg<'help>) -> Self { + a.clone() + } +} + +impl<'help> PartialEq for Arg<'help> { + fn eq(&self, other: &Arg<'help>) -> bool { + self.name == other.name + } +} + +impl<'help> PartialOrd for Arg<'help> { + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +impl<'help> Ord for Arg<'help> { + fn cmp(&self, other: &Arg) -> Ordering { + self.name.cmp(other.name) + } +} + +impl<'help> Eq for Arg<'help> {} + +impl<'help> Display for Arg<'help> { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + // Write the name such --long or -l + if let Some(l) = self.long { + write!(f, "--{}", l)?; + } else if let Some(s) = self.short { + write!(f, "-{}", s)?; + } + let mut need_closing_bracket = false; + if !self.is_positional() && self.is_takes_value_set() { + let is_optional_val = self.min_vals == Some(0); + let sep = if self.is_require_equals_set() { + if is_optional_val { + need_closing_bracket = true; + "[=" + } else { + "=" + } + } else if is_optional_val { + need_closing_bracket = true; + " [" + } else { + " " + }; + f.write_str(sep)?; + } + if self.is_takes_value_set() || self.is_positional() { + display_arg_val(self, |s, _| f.write_str(s))?; + } + if need_closing_bracket { + f.write_str("]")?; + } + + Ok(()) + } +} + +impl<'help> fmt::Debug for Arg<'help> { + fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { + let mut ds = f.debug_struct("Arg"); + + #[allow(unused_mut)] + let mut ds = ds + .field("id", &self.id) + .field("provider", &self.provider) + .field("name", &self.name) + .field("help", &self.help) + .field("long_help", &self.long_help) + .field("blacklist", &self.blacklist) + .field("settings", &self.settings) + .field("overrides", &self.overrides) + .field("groups", &self.groups) + .field("requires", &self.requires) + .field("r_ifs", &self.r_ifs) + .field("r_unless", &self.r_unless) + .field("short", &self.short) + .field("long", &self.long) + .field("aliases", &self.aliases) + .field("short_aliases", &self.short_aliases) + .field("disp_ord", &self.disp_ord) + .field("possible_vals", &self.possible_vals) + .field("val_names", &self.val_names) + .field("num_vals", &self.num_vals) + .field("max_vals", &self.max_vals) + .field("min_vals", &self.min_vals) + .field( + "validator", + &self.validator.as_ref().map_or("None", |_| "Some(FnMut)"), + ) + .field( + "validator_os", + &self.validator_os.as_ref().map_or("None", |_| "Some(FnMut)"), + ) + .field("val_delim", &self.val_delim) + .field("default_vals", &self.default_vals) + .field("default_vals_ifs", &self.default_vals_ifs) + .field("terminator", &self.terminator) + .field("index", &self.index) + .field("help_heading", &self.help_heading) + .field("value_hint", &self.value_hint) + .field("default_missing_vals", &self.default_missing_vals); + + #[cfg(feature = "env")] + { + ds = ds.field("env", &self.env); + } + + ds.finish() + } +} + +type Validator<'a> = dyn FnMut(&str) -> Result<(), Box<dyn Error + Send + Sync>> + Send + 'a; +type ValidatorOs<'a> = dyn FnMut(&OsStr) -> Result<(), Box<dyn Error + Send + Sync>> + Send + 'a; + +#[derive(Debug, Clone, Eq, PartialEq)] +pub(crate) enum ArgProvider { + Generated, + GeneratedMutated, + User, +} + +impl Default for ArgProvider { + fn default() -> Self { + ArgProvider::User + } +} + +/// Write the values such as <name1> <name2> +pub(crate) fn display_arg_val<F, T, E>(arg: &Arg, mut write: F) -> Result<(), E> +where + F: FnMut(&str, bool) -> Result<T, E>, +{ + let mult_val = arg.is_multiple_values_set(); + let mult_occ = arg.is_multiple_occurrences_set(); + let delim = if arg.is_require_value_delimiter_set() { + arg.val_delim.expect(INTERNAL_ERROR_MSG) + } else { + ' ' + } + .to_string(); + if !arg.val_names.is_empty() { + // If have val_name. + match (arg.val_names.len(), arg.num_vals) { + (1, Some(num_vals)) => { + // If single value name with multiple num_of_vals, display all + // the values with the single value name. + let arg_name = format!("<{}>", arg.val_names.get(0).unwrap()); + for n in 1..=num_vals { + write(&arg_name, true)?; + if n != num_vals { + write(&delim, false)?; + } + } + } + (num_val_names, _) => { + // If multiple value names, display them sequentially(ignore num of vals). + let mut it = arg.val_names.iter().peekable(); + while let Some(val) = it.next() { + write(&format!("<{}>", val), true)?; + if it.peek().is_some() { + write(&delim, false)?; + } + } + if (num_val_names == 1 && mult_val) + || (arg.is_positional() && mult_occ) + || num_val_names < arg.num_vals.unwrap_or(0) + { + write("...", true)?; + } + } + } + } else if let Some(num_vals) = arg.num_vals { + // If number_of_values is specified, display the value multiple times. + let arg_name = format!("<{}>", arg.name); + for n in 1..=num_vals { + write(&arg_name, true)?; + if n != num_vals { + write(&delim, false)?; + } + } + } else if arg.is_positional() { + // Value of positional argument with no num_vals and val_names. + write(&format!("<{}>", arg.name), true)?; + + if mult_val || mult_occ { + write("...", true)?; + } + } else { + // value of flag argument with no num_vals and val_names. + write(&format!("<{}>", arg.name), true)?; + if mult_val { + write("...", true)?; + } + } + Ok(()) +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum DisplayOrder { + None, + Implicit(usize), + Explicit(usize), +} + +impl DisplayOrder { + pub(crate) fn set_explicit(&mut self, explicit: usize) { + *self = Self::Explicit(explicit) + } + + pub(crate) fn set_implicit(&mut self, implicit: usize) { + *self = (*self).max(Self::Implicit(implicit)) + } + + pub(crate) fn make_explicit(&mut self) { + match *self { + Self::None | Self::Explicit(_) => {} + Self::Implicit(disp) => self.set_explicit(disp), + } + } + + pub(crate) fn get_explicit(self) -> usize { + match self { + Self::None | Self::Implicit(_) => 999, + Self::Explicit(disp) => disp, + } + } +} + +impl Default for DisplayOrder { + fn default() -> Self { + Self::None + } +} + +// Flags +#[cfg(test)] +mod test { + use super::Arg; + + #[test] + fn flag_display() { + let mut f = Arg::new("flg").multiple_occurrences(true); + f.long = Some("flag"); + + assert_eq!(f.to_string(), "--flag"); + + let mut f2 = Arg::new("flg"); + f2.short = Some('f'); + + assert_eq!(f2.to_string(), "-f"); + } + + #[test] + fn flag_display_single_alias() { + let mut f = Arg::new("flg"); + f.long = Some("flag"); + f.aliases = vec![("als", true)]; + + assert_eq!(f.to_string(), "--flag") + } + + #[test] + fn flag_display_multiple_aliases() { + let mut f = Arg::new("flg"); + f.short = Some('f'); + f.aliases = vec![ + ("alias_not_visible", false), + ("f2", true), + ("f3", true), + ("f4", true), + ]; + assert_eq!(f.to_string(), "-f"); + } + + #[test] + fn flag_display_single_short_alias() { + let mut f = Arg::new("flg"); + f.short = Some('a'); + f.short_aliases = vec![('b', true)]; + + assert_eq!(f.to_string(), "-a") + } + + #[test] + fn flag_display_multiple_short_aliases() { + let mut f = Arg::new("flg"); + f.short = Some('a'); + f.short_aliases = vec![('b', false), ('c', true), ('d', true), ('e', true)]; + assert_eq!(f.to_string(), "-a"); + } + + // Options + + #[test] + fn option_display_multiple_occurrences() { + let o = Arg::new("opt") + .long("option") + .takes_value(true) + .multiple_occurrences(true); + + assert_eq!(o.to_string(), "--option <opt>"); + } + + #[test] + fn option_display_multiple_values() { + let o = Arg::new("opt") + .long("option") + .takes_value(true) + .multiple_values(true); + + assert_eq!(o.to_string(), "--option <opt>..."); + } + + #[test] + fn option_display2() { + let o2 = Arg::new("opt").short('o').value_names(&["file", "name"]); + + assert_eq!(o2.to_string(), "-o <file> <name>"); + } + + #[test] + fn option_display3() { + let o2 = Arg::new("opt") + .short('o') + .takes_value(true) + .multiple_values(true) + .value_names(&["file", "name"]); + + assert_eq!(o2.to_string(), "-o <file> <name>"); + } + + #[test] + fn option_display_single_alias() { + let o = Arg::new("opt") + .takes_value(true) + .long("option") + .visible_alias("als"); + + assert_eq!(o.to_string(), "--option <opt>"); + } + + #[test] + fn option_display_multiple_aliases() { + let o = Arg::new("opt") + .long("option") + .takes_value(true) + .visible_aliases(&["als2", "als3", "als4"]) + .alias("als_not_visible"); + + assert_eq!(o.to_string(), "--option <opt>"); + } + + #[test] + fn option_display_single_short_alias() { + let o = Arg::new("opt") + .takes_value(true) + .short('a') + .visible_short_alias('b'); + + assert_eq!(o.to_string(), "-a <opt>"); + } + + #[test] + fn option_display_multiple_short_aliases() { + let o = Arg::new("opt") + .short('a') + .takes_value(true) + .visible_short_aliases(&['b', 'c', 'd']) + .short_alias('e'); + + assert_eq!(o.to_string(), "-a <opt>"); + } + + // Positionals + + #[test] + fn positional_display_multiple_values() { + let p = Arg::new("pos") + .index(1) + .takes_value(true) + .multiple_values(true); + + assert_eq!(p.to_string(), "<pos>..."); + } + + #[test] + fn positional_display_multiple_occurrences() { + let p = Arg::new("pos") + .index(1) + .takes_value(true) + .multiple_occurrences(true); + + assert_eq!(p.to_string(), "<pos>..."); + } + + #[test] + fn positional_display_required() { + let p2 = Arg::new("pos").index(1).required(true); + + assert_eq!(p2.to_string(), "<pos>"); + } + + #[test] + fn positional_display_val_names() { + let p2 = Arg::new("pos").index(1).value_names(&["file1", "file2"]); + + assert_eq!(p2.to_string(), "<file1> <file2>"); + } + + #[test] + fn positional_display_val_names_req() { + let p2 = Arg::new("pos") + .index(1) + .required(true) + .value_names(&["file1", "file2"]); + + assert_eq!(p2.to_string(), "<file1> <file2>"); + } +} diff --git a/third_party/rust/clap/src/build/arg_group.rs b/third_party/rust/clap/src/build/arg_group.rs new file mode 100644 index 0000000000..dbcf9aa41b --- /dev/null +++ b/third_party/rust/clap/src/build/arg_group.rs @@ -0,0 +1,624 @@ +// Internal +use crate::util::{Id, Key}; + +#[cfg(feature = "yaml")] +use yaml_rust::Yaml; + +/// Family of related [arguments]. +/// +/// By placing arguments in a logical group, you can create easier requirement and +/// exclusion rules instead of having to list each argument individually, or when you want a rule +/// to apply "any but not all" arguments. +/// +/// For instance, you can make an entire `ArgGroup` required. If [`ArgGroup::multiple(true)`] is +/// set, this means that at least one argument from that group must be present. If +/// [`ArgGroup::multiple(false)`] is set (the default), one and *only* one must be present. +/// +/// You can also do things such as name an entire `ArgGroup` as a [conflict] or [requirement] for +/// another argument, meaning any of the arguments that belong to that group will cause a failure +/// if present, or must be present respectively. +/// +/// Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be +/// present out of a given set. Imagine that you had multiple arguments, and you want one of them +/// to be required, but making all of them required isn't feasible because perhaps they conflict +/// with each other. For example, lets say that you were building an application where one could +/// set a given version number by supplying a string with an option argument, i.e. +/// `--set-ver v1.2.3`, you also wanted to support automatically using a previous version number +/// and simply incrementing one of the three numbers. So you create three flags `--major`, +/// `--minor`, and `--patch`. All of these arguments shouldn't be used at one time but you want to +/// specify that *at least one* of them is used. For this, you can create a group. +/// +/// Finally, you may use `ArgGroup`s to pull a value from a group of arguments when you don't care +/// exactly which argument was actually used at runtime. +/// +/// # Examples +/// +/// The following example demonstrates using an `ArgGroup` to ensure that one, and only one, of +/// the arguments from the specified group is present at runtime. +/// +/// ```rust +/// # use clap::{Command, arg, ArgGroup, ErrorKind}; +/// let result = Command::new("cmd") +/// .arg(arg!(--"set-ver" <ver> "set the version manually").required(false)) +/// .arg(arg!(--major "auto increase major")) +/// .arg(arg!(--minor "auto increase minor")) +/// .arg(arg!(--patch "auto increase patch")) +/// .group(ArgGroup::new("vers") +/// .args(&["set-ver", "major", "minor", "patch"]) +/// .required(true)) +/// .try_get_matches_from(vec!["cmd", "--major", "--patch"]); +/// // Because we used two args in the group it's an error +/// assert!(result.is_err()); +/// let err = result.unwrap_err(); +/// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); +/// ``` +/// This next example shows a passing parse of the same scenario +/// +/// ```rust +/// # use clap::{Command, arg, ArgGroup}; +/// let result = Command::new("cmd") +/// .arg(arg!(--"set-ver" <ver> "set the version manually").required(false)) +/// .arg(arg!(--major "auto increase major")) +/// .arg(arg!(--minor "auto increase minor")) +/// .arg(arg!(--patch "auto increase patch")) +/// .group(ArgGroup::new("vers") +/// .args(&["set-ver", "major", "minor","patch"]) +/// .required(true)) +/// .try_get_matches_from(vec!["cmd", "--major"]); +/// assert!(result.is_ok()); +/// let matches = result.unwrap(); +/// // We may not know which of the args was used, so we can test for the group... +/// assert!(matches.is_present("vers")); +/// // we could also alternatively check each arg individually (not shown here) +/// ``` +/// [`ArgGroup::multiple(true)`]: ArgGroup::multiple() +/// +/// [`ArgGroup::multiple(false)`]: ArgGroup::multiple() +/// [arguments]: crate::Arg +/// [conflict]: crate::Arg::conflicts_with() +/// [requirement]: crate::Arg::requires() +#[derive(Default, Debug, PartialEq, Eq)] +pub struct ArgGroup<'help> { + pub(crate) id: Id, + pub(crate) name: &'help str, + pub(crate) args: Vec<Id>, + pub(crate) required: bool, + pub(crate) requires: Vec<Id>, + pub(crate) conflicts: Vec<Id>, + pub(crate) multiple: bool, +} + +impl<'help> ArgGroup<'help> { + pub(crate) fn with_id(id: Id) -> Self { + ArgGroup { + id, + ..ArgGroup::default() + } + } + + /// Create a `ArgGroup` using a unique name. + /// + /// The name will be used to get values from the group or refer to the group inside of conflict + /// and requirement rules. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ArgGroup}; + /// ArgGroup::new("config") + /// # ; + /// ``` + pub fn new<S: Into<&'help str>>(n: S) -> Self { + ArgGroup::default().id(n) + } + + /// Sets the group name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ArgGroup}; + /// ArgGroup::default().name("config") + /// # ; + /// ``` + #[must_use] + pub fn id<S: Into<&'help str>>(mut self, n: S) -> Self { + self.name = n.into(); + self.id = Id::from(self.name); + self + } + + /// Deprecated, replaced with [`ArgGroup::id`] + #[deprecated(since = "3.1.0", note = "Replaced with `ArgGroup::id`")] + pub fn name<S: Into<&'help str>>(self, n: S) -> Self { + self.id(n) + } + + /// Adds an [argument] to this group by name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .group(ArgGroup::new("req_flags") + /// .arg("flag") + /// .arg("color")) + /// .get_matches_from(vec!["myprog", "-f"]); + /// // maybe we don't know which of the two flags was used... + /// assert!(m.is_present("req_flags")); + /// // but we can also check individually if needed + /// assert!(m.is_present("flag")); + /// ``` + /// [argument]: crate::Arg + #[must_use] + pub fn arg<T: Key>(mut self, arg_id: T) -> Self { + self.args.push(arg_id.into()); + self + } + + /// Adds multiple [arguments] to this group by name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"])) + /// .get_matches_from(vec!["myprog", "-f"]); + /// // maybe we don't know which of the two flags was used... + /// assert!(m.is_present("req_flags")); + /// // but we can also check individually if needed + /// assert!(m.is_present("flag")); + /// ``` + /// [arguments]: crate::Arg + #[must_use] + pub fn args<T: Key>(mut self, ns: &[T]) -> Self { + for n in ns { + self = self.arg(n); + } + self + } + + /// Allows more than one of the [`Arg`]s in this group to be used. (Default: `false`) + /// + /// # Examples + /// + /// Notice in this example we use *both* the `-f` and `-c` flags which are both part of the + /// group + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"]) + /// .multiple(true)) + /// .get_matches_from(vec!["myprog", "-f", "-c"]); + /// // maybe we don't know which of the two flags was used... + /// assert!(m.is_present("req_flags")); + /// ``` + /// In this next example, we show the default behavior (i.e. `multiple(false)) which will throw + /// an error if more than one of the args in the group was used. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"])) + /// .try_get_matches_from(vec!["myprog", "-f", "-c"]); + /// // Because we used both args in the group it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); + /// ``` + /// + /// [`Arg`]: crate::Arg + #[inline] + #[must_use] + pub fn multiple(mut self, yes: bool) -> Self { + self.multiple = yes; + self + } + + /// Require an argument from the group to be present when parsing. + /// + /// This is unless conflicting with another argument. A required group will be displayed in + /// the usage string of the application in the format `<arg|arg2|arg3>`. + /// + /// **NOTE:** This setting only applies to the current [`Command`] / [`Subcommand`]s, and not + /// globally. + /// + /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with + /// `ArgGroup::required(true)` states, "One and *only one* arg must be used from this group. + /// Use of more than one arg is an error." Vice setting `ArgGroup::multiple(true)` which + /// states, '*At least* one arg from this group must be used. Using multiple is OK." + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"]) + /// .required(true)) + /// .try_get_matches_from(vec!["myprog"]); + /// // Because we didn't use any of the args in the group, it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// + /// [`Subcommand`]: crate::Subcommand + /// [`ArgGroup::multiple`]: ArgGroup::multiple() + /// [`Command`]: crate::Command + #[inline] + #[must_use] + pub fn required(mut self, yes: bool) -> Self { + self.required = yes; + self + } + + /// Specify an argument or group that must be present when this group is. + /// + /// This is not to be confused with a [required group]. Requirement rules function just like + /// [argument requirement rules], you can name other arguments or groups that must be present + /// when any one of the arguments from this group is used. + /// + /// **NOTE:** The name provided may be an argument or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .arg(Arg::new("debug") + /// .short('d')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"]) + /// .requires("debug")) + /// .try_get_matches_from(vec!["myprog", "-c"]); + /// // because we used an arg from the group, and the group requires "-d" to be used, it's an + /// // error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required group]: ArgGroup::required() + /// [argument requirement rules]: crate::Arg::requires() + #[must_use] + pub fn requires<T: Key>(mut self, id: T) -> Self { + self.requires.push(id.into()); + self + } + + /// Specify arguments or groups that must be present when this group is. + /// + /// This is not to be confused with a [required group]. Requirement rules function just like + /// [argument requirement rules], you can name other arguments or groups that must be present + /// when one of the arguments from this group is used. + /// + /// **NOTE:** The names provided may be an argument or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .arg(Arg::new("debug") + /// .short('d')) + /// .arg(Arg::new("verb") + /// .short('v')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"]) + /// .requires_all(&["debug", "verb"])) + /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); + /// // because we used an arg from the group, and the group requires "-d" and "-v" to be used, + /// // yet we only used "-d" it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required group]: ArgGroup::required() + /// [argument requirement rules]: crate::Arg::requires_all() + #[must_use] + pub fn requires_all(mut self, ns: &[&'help str]) -> Self { + for n in ns { + self = self.requires(n); + } + self + } + + /// Specify an argument or group that must **not** be present when this group is. + /// + /// Exclusion (aka conflict) rules function just like [argument exclusion rules], you can name + /// other arguments or groups that must *not* be present when one of the arguments from this + /// group are used. + /// + /// **NOTE:** The name provided may be an argument, or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .arg(Arg::new("debug") + /// .short('d')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"]) + /// .conflicts_with("debug")) + /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); + /// // because we used an arg from the group, and the group conflicts with "-d", it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); + /// ``` + /// [argument exclusion rules]: crate::Arg::conflicts_with() + #[must_use] + pub fn conflicts_with<T: Key>(mut self, id: T) -> Self { + self.conflicts.push(id.into()); + self + } + + /// Specify arguments or groups that must **not** be present when this group is. + /// + /// Exclusion rules function just like [argument exclusion rules], you can name other arguments + /// or groups that must *not* be present when one of the arguments from this group are used. + /// + /// **NOTE:** The names provided may be an argument, or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ErrorKind}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("color") + /// .short('c')) + /// .arg(Arg::new("debug") + /// .short('d')) + /// .arg(Arg::new("verb") + /// .short('v')) + /// .group(ArgGroup::new("req_flags") + /// .args(&["flag", "color"]) + /// .conflicts_with_all(&["debug", "verb"])) + /// .try_get_matches_from(vec!["myprog", "-c", "-v"]); + /// // because we used an arg from the group, and the group conflicts with either "-v" or "-d" + /// // it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); + /// ``` + /// + /// [argument exclusion rules]: crate::Arg::conflicts_with_all() + #[must_use] + pub fn conflicts_with_all(mut self, ns: &[&'help str]) -> Self { + for n in ns { + self = self.conflicts_with(n); + } + self + } + + /// Deprecated, replaced with [`ArgGroup::new`] + #[deprecated(since = "3.0.0", note = "Replaced with `ArgGroup::new`")] + #[doc(hidden)] + pub fn with_name<S: Into<&'help str>>(n: S) -> Self { + Self::new(n) + } + + /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? + #[cfg(feature = "yaml")] + #[deprecated( + since = "3.0.0", + note = "Maybe clap::Parser would fit your use case? (Issue #3087)" + )] + #[doc(hidden)] + pub fn from_yaml(yaml: &'help Yaml) -> Self { + Self::from(yaml) + } +} + +impl<'help> From<&'_ ArgGroup<'help>> for ArgGroup<'help> { + fn from(g: &ArgGroup<'help>) -> Self { + ArgGroup { + id: g.id.clone(), + name: g.name, + required: g.required, + args: g.args.clone(), + requires: g.requires.clone(), + conflicts: g.conflicts.clone(), + multiple: g.multiple, + } + } +} + +/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? +#[cfg(feature = "yaml")] +impl<'help> From<&'help Yaml> for ArgGroup<'help> { + /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? + fn from(y: &'help Yaml) -> Self { + let b = y.as_hash().expect("ArgGroup::from::<Yaml> expects a table"); + // We WANT this to panic on error...so expect() is good. + let mut a = ArgGroup::default(); + let group_settings = if b.len() == 1 { + let name_yaml = b.keys().next().expect("failed to get name"); + let name_str = name_yaml + .as_str() + .expect("failed to convert arg YAML name to str"); + a.name = name_str; + a.id = Id::from(&a.name); + b.get(name_yaml) + .expect("failed to get name_str") + .as_hash() + .expect("failed to convert to a hash") + } else { + b + }; + + for (k, v) in group_settings { + a = match k.as_str().unwrap() { + "required" => a.required(v.as_bool().unwrap()), + "multiple" => a.multiple(v.as_bool().unwrap()), + "args" => yaml_vec_or_str!(a, v, arg), + "arg" => { + if let Some(ys) = v.as_str() { + a = a.arg(ys); + } + a + } + "requires" => yaml_vec_or_str!(a, v, requires), + "conflicts_with" => yaml_vec_or_str!(a, v, conflicts_with), + "name" => { + if let Some(ys) = v.as_str() { + a = a.id(ys); + } + a + } + s => panic!( + "Unknown ArgGroup setting '{}' in YAML file for \ + ArgGroup '{}'", + s, a.name + ), + } + } + + a + } +} + +#[cfg(test)] +mod test { + use super::ArgGroup; + #[cfg(feature = "yaml")] + use yaml_rust::YamlLoader; + + #[test] + fn groups() { + let g = ArgGroup::new("test") + .arg("a1") + .arg("a4") + .args(&["a2", "a3"]) + .required(true) + .conflicts_with("c1") + .conflicts_with_all(&["c2", "c3"]) + .conflicts_with("c4") + .requires("r1") + .requires_all(&["r2", "r3"]) + .requires("r4"); + + let args = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; + let reqs = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; + let confs = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; + + assert_eq!(g.args, args); + assert_eq!(g.requires, reqs); + assert_eq!(g.conflicts, confs); + } + + #[test] + fn test_from() { + let g = ArgGroup::new("test") + .arg("a1") + .arg("a4") + .args(&["a2", "a3"]) + .required(true) + .conflicts_with("c1") + .conflicts_with_all(&["c2", "c3"]) + .conflicts_with("c4") + .requires("r1") + .requires_all(&["r2", "r3"]) + .requires("r4"); + + let args = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; + let reqs = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; + let confs = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; + + let g2 = ArgGroup::from(&g); + assert_eq!(g2.args, args); + assert_eq!(g2.requires, reqs); + assert_eq!(g2.conflicts, confs); + } + + #[cfg(feature = "yaml")] + #[test] + fn test_yaml() { + let g_yaml = "name: test +args: +- a1 +- a4 +- a2 +- a3 +conflicts_with: +- c1 +- c2 +- c3 +- c4 +requires: +- r1 +- r2 +- r3 +- r4"; + let yaml = &YamlLoader::load_from_str(g_yaml).expect("failed to load YAML file")[0]; + let g = ArgGroup::from(yaml); + let args = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; + let reqs = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; + let confs = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; + assert_eq!(g.args, args); + assert_eq!(g.requires, reqs); + assert_eq!(g.conflicts, confs); + } + + // This test will *fail to compile* if ArgGroup is not Send + Sync + #[test] + fn arg_group_send_sync() { + fn foo<T: Send + Sync>(_: T) {} + foo(ArgGroup::new("test")) + } +} + +impl Clone for ArgGroup<'_> { + fn clone(&self) -> Self { + ArgGroup { + id: self.id.clone(), + name: self.name, + required: self.required, + args: self.args.clone(), + requires: self.requires.clone(), + conflicts: self.conflicts.clone(), + multiple: self.multiple, + } + } +} diff --git a/third_party/rust/clap/src/build/arg_predicate.rs b/third_party/rust/clap/src/build/arg_predicate.rs new file mode 100644 index 0000000000..58eb5494c0 --- /dev/null +++ b/third_party/rust/clap/src/build/arg_predicate.rs @@ -0,0 +1,14 @@ +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum ArgPredicate<'help> { + IsPresent, + Equals(&'help std::ffi::OsStr), +} + +impl<'help> From<Option<&'help std::ffi::OsStr>> for ArgPredicate<'help> { + fn from(other: Option<&'help std::ffi::OsStr>) -> Self { + match other { + Some(other) => Self::Equals(other), + None => Self::IsPresent, + } + } +} diff --git a/third_party/rust/clap/src/build/arg_settings.rs b/third_party/rust/clap/src/build/arg_settings.rs new file mode 100644 index 0000000000..dee79565b9 --- /dev/null +++ b/third_party/rust/clap/src/build/arg_settings.rs @@ -0,0 +1,382 @@ +#![allow(deprecated)] + +// Std +use std::ops::BitOr; +#[cfg(feature = "yaml")] +use std::str::FromStr; + +// Third party +use bitflags::bitflags; + +#[allow(unused)] +use crate::Arg; + +#[doc(hidden)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ArgFlags(Flags); + +impl Default for ArgFlags { + fn default() -> Self { + Self::empty() + } +} + +/// Various settings that apply to arguments and may be set, unset, and checked via getter/setter +/// methods [`Arg::setting`], [`Arg::unset_setting`], and [`Arg::is_set`]. This is what the +/// [`Arg`] methods which accept a `bool` use internally. +/// +/// [`Arg`]: crate::Arg +/// [`Arg::setting`]: crate::Arg::setting() +/// [`Arg::unset_setting`]: crate::Arg::unset_setting() +/// [`Arg::is_set`]: crate::Arg::is_set() +#[derive(Debug, PartialEq, Copy, Clone)] +#[non_exhaustive] +pub enum ArgSettings { + /// Deprecated, replaced with [`Arg::required`] and [`Arg::is_required_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::required` and `Arg::is_required_set`" + )] + Required, + /// Deprecated, replaced with [`Arg::multiple_values`] and [`Arg::is_multiple_values_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::multiple_values` and `Arg::`is_multiple_values_set`" + )] + MultipleValues, + /// Deprecated, replaced with [`Arg::multiple_occurrences`] and + /// [`Arg::is_multiple_occurrences_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::multiple_occurrences` and `Arg::is_multiple_occurrences_set`" + )] + MultipleOccurrences, + /// Deprecated, see [`ArgSettings::MultipleOccurrences`] (most likely what you want) and + /// [`ArgSettings::MultipleValues`] + #[deprecated( + since = "3.0.0", + note = "Split into `ArgSettings::MultipleOccurrences` (most likely what you want) and `ArgSettings::MultipleValues`" + )] + #[doc(hidden)] + Multiple, + /// Deprecated, replaced with [`Arg::forbid_empty_values`] and + /// [`Arg::is_forbid_empty_values_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::forbid_empty_values` and `Arg::is_forbid_empty_values_set`" + )] + ForbidEmptyValues, + /// Deprecated, replaced with [`Arg::global`] and [`Arg::is_global_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::global` and `Arg::is_global_set`" + )] + Global, + /// Deprecated, replaced with [`Arg::hide`] and [`Arg::is_hide_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide` and `Arg::is_hide_set`" + )] + Hidden, + /// Deprecated, replaced with [`Arg::takes_value`] and [`Arg::is_takes_value_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::takes_value` and `Arg::is_takes_value_set`" + )] + TakesValue, + /// Deprecated, replaced with [`Arg::use_value_delimiter`] and + /// [`Arg::is_use_value_delimiter_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::use_value_delimiter` and `Arg::is_use_value_delimiter_set`" + )] + UseValueDelimiter, + /// Deprecated, replaced with [`Arg::next_line_help`] and [`Arg::is_next_line_help_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::next_line_help` and `Arg::is_next_line_help_set`" + )] + NextLineHelp, + /// Deprecated, replaced with [`Arg::require_value_delimiter`] and + /// [`Arg::is_require_value_delimiter_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::require_value_delimiter` and `Arg::is_require_value_delimiter_set`" + )] + RequireDelimiter, + /// Deprecated, replaced with [`Arg::hide_possible_values`] and + /// [`Arg::is_hide_possible_values_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide_possible_values` and `Arg::is_hide_possible_values_set`" + )] + HidePossibleValues, + /// Deprecated, replaced with [`Arg::allow_hyphen_values`] and + /// [`Arg::is_allow_hyphen_values_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::allow_hyphen_values` and `Arg::is_allow_hyphen_values_set`" + )] + AllowHyphenValues, + /// Deprecated, replaced with [`ArgSettings::AllowHyphenValues`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `ArgSettings::AllowHyphenValues`" + )] + #[doc(hidden)] + AllowLeadingHyphen, + /// Deprecated, replaced with [`Arg::require_equals`] and [`Arg::is_require_equals_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::require_equals` and `Arg::is_require_equals_set`" + )] + RequireEquals, + /// Deprecated, replaced with [`Arg::last`] and [`Arg::is_last_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::last` and `Arg::is_last_set`" + )] + Last, + /// Deprecated, replaced with [`Arg::hide_default_value`] and [`Arg::is_hide_default_value_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide_default_value` and `Arg::is_hide_default_value_set`" + )] + HideDefaultValue, + /// Deprecated, replaced with [`Arg::ignore_case`] and [`Arg::is_ignore_case_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::ignore_case` and `Arg::is_ignore_case_set`" + )] + IgnoreCase, + /// Deprecated, replaced with [`ArgSettings::IgnoreCase`] + #[deprecated(since = "3.0.0", note = "Replaced with `ArgSettings::IgnoreCase`")] + #[doc(hidden)] + CaseInsensitive, + /// Deprecated, replaced with [`Arg::hide_env`] and [`Arg::is_hide_env_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide_env` and `Arg::is_hide_env_set`" + )] + #[cfg(feature = "env")] + HideEnv, + /// Deprecated, replaced with [`Arg::hide_env_values`] and [`Arg::is_hide_env_values_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide_env_values` and `Arg::is_hide_env_values_set`" + )] + #[cfg(feature = "env")] + HideEnvValues, + /// Deprecated, replaced with [`Arg::hide_short_help`] and [`Arg::is_hide_short_help_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide_short_help` and `Arg::is_hide_short_help_set`" + )] + HiddenShortHelp, + /// Deprecated, replaced with [`Arg::hide_long_help`] and [`Arg::is_hide_long_help_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::hide_long_help` and `Arg::is_hide_long_help_set`" + )] + HiddenLongHelp, + /// Deprecated, replaced with [`Arg::allow_invalid_utf8`] and [`Arg::is_allow_invalid_utf8_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::allow_invalid_utf8` and `Arg::is_allow_invalid_utf8_set`" + )] + AllowInvalidUtf8, + /// Deprecated, replaced with [`Arg::exclusive`] and [`Arg::is_exclusive_set`] + #[deprecated( + since = "3.1.0", + note = "Replaced with `Arg::exclusive` and `Arg::is_exclusive_set`" + )] + Exclusive, +} + +bitflags! { + struct Flags: u32 { + const REQUIRED = 1; + const MULTIPLE_OCC = 1 << 1; + const NO_EMPTY_VALS = 1 << 2; + const GLOBAL = 1 << 3; + const HIDDEN = 1 << 4; + const TAKES_VAL = 1 << 5; + const USE_DELIM = 1 << 6; + const NEXT_LINE_HELP = 1 << 7; + const REQ_DELIM = 1 << 9; + const DELIM_NOT_SET = 1 << 10; + const HIDE_POS_VALS = 1 << 11; + const ALLOW_TAC_VALS = 1 << 12; + const REQUIRE_EQUALS = 1 << 13; + const LAST = 1 << 14; + const HIDE_DEFAULT_VAL = 1 << 15; + const CASE_INSENSITIVE = 1 << 16; + #[cfg(feature = "env")] + const HIDE_ENV_VALS = 1 << 17; + const HIDDEN_SHORT_H = 1 << 18; + const HIDDEN_LONG_H = 1 << 19; + const MULTIPLE_VALS = 1 << 20; + const MULTIPLE = Self::MULTIPLE_OCC.bits | Self::MULTIPLE_VALS.bits; + #[cfg(feature = "env")] + const HIDE_ENV = 1 << 21; + const UTF8_NONE = 1 << 22; + const EXCLUSIVE = 1 << 23; + const NO_OP = 0; + } +} + +impl_settings! { ArgSettings, ArgFlags, + Required => Flags::REQUIRED, + MultipleOccurrences => Flags::MULTIPLE_OCC, + MultipleValues => Flags::MULTIPLE_VALS, + Multiple => Flags::MULTIPLE, + ForbidEmptyValues => Flags::NO_EMPTY_VALS, + Global => Flags::GLOBAL, + Hidden => Flags::HIDDEN, + TakesValue => Flags::TAKES_VAL, + UseValueDelimiter => Flags::USE_DELIM, + NextLineHelp => Flags::NEXT_LINE_HELP, + RequireDelimiter => Flags::REQ_DELIM, + HidePossibleValues => Flags::HIDE_POS_VALS, + AllowHyphenValues => Flags::ALLOW_TAC_VALS, + AllowLeadingHyphen => Flags::ALLOW_TAC_VALS, + RequireEquals => Flags::REQUIRE_EQUALS, + Last => Flags::LAST, + IgnoreCase => Flags::CASE_INSENSITIVE, + CaseInsensitive => Flags::CASE_INSENSITIVE, + #[cfg(feature = "env")] + HideEnv => Flags::HIDE_ENV, + #[cfg(feature = "env")] + HideEnvValues => Flags::HIDE_ENV_VALS, + HideDefaultValue => Flags::HIDE_DEFAULT_VAL, + HiddenShortHelp => Flags::HIDDEN_SHORT_H, + HiddenLongHelp => Flags::HIDDEN_LONG_H, + AllowInvalidUtf8 => Flags::UTF8_NONE, + Exclusive => Flags::EXCLUSIVE +} + +/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? +#[cfg(feature = "yaml")] +impl FromStr for ArgSettings { + type Err = String; + fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> { + #[allow(deprecated)] + #[allow(unreachable_patterns)] + match &*s.to_ascii_lowercase() { + "required" => Ok(ArgSettings::Required), + "multipleoccurrences" => Ok(ArgSettings::MultipleOccurrences), + "multiplevalues" => Ok(ArgSettings::MultipleValues), + "multiple" => Ok(ArgSettings::Multiple), + "forbidemptyvalues" => Ok(ArgSettings::ForbidEmptyValues), + "global" => Ok(ArgSettings::Global), + "hidden" => Ok(ArgSettings::Hidden), + "takesvalue" => Ok(ArgSettings::TakesValue), + "usevaluedelimiter" => Ok(ArgSettings::UseValueDelimiter), + "nextlinehelp" => Ok(ArgSettings::NextLineHelp), + "requiredelimiter" => Ok(ArgSettings::RequireDelimiter), + "hidepossiblevalues" => Ok(ArgSettings::HidePossibleValues), + "allowhyphenvalues" => Ok(ArgSettings::AllowHyphenValues), + "allowleadinghypyhen" => Ok(ArgSettings::AllowLeadingHyphen), + "requireequals" => Ok(ArgSettings::RequireEquals), + "last" => Ok(ArgSettings::Last), + "ignorecase" => Ok(ArgSettings::IgnoreCase), + "caseinsensitive" => Ok(ArgSettings::CaseInsensitive), + #[cfg(feature = "env")] + "hideenv" => Ok(ArgSettings::HideEnv), + #[cfg(feature = "env")] + "hideenvvalues" => Ok(ArgSettings::HideEnvValues), + "hidedefaultvalue" => Ok(ArgSettings::HideDefaultValue), + "hiddenshorthelp" => Ok(ArgSettings::HiddenShortHelp), + "hiddenlonghelp" => Ok(ArgSettings::HiddenLongHelp), + "allowinvalidutf8" => Ok(ArgSettings::AllowInvalidUtf8), + "exclusive" => Ok(ArgSettings::Exclusive), + _ => Err(format!("unknown AppSetting: `{}`", s)), + } + } +} + +#[cfg(test)] +mod test { + #[test] + #[cfg(feature = "yaml")] + fn arg_settings_fromstr() { + use super::ArgSettings; + + assert_eq!( + "allowhyphenvalues".parse::<ArgSettings>().unwrap(), + ArgSettings::AllowHyphenValues + ); + assert_eq!( + "forbidemptyvalues".parse::<ArgSettings>().unwrap(), + ArgSettings::ForbidEmptyValues + ); + assert_eq!( + "hidepossiblevalues".parse::<ArgSettings>().unwrap(), + ArgSettings::HidePossibleValues + ); + assert_eq!( + "hidden".parse::<ArgSettings>().unwrap(), + ArgSettings::Hidden + ); + assert_eq!( + "nextlinehelp".parse::<ArgSettings>().unwrap(), + ArgSettings::NextLineHelp + ); + assert_eq!( + "requiredelimiter".parse::<ArgSettings>().unwrap(), + ArgSettings::RequireDelimiter + ); + assert_eq!( + "required".parse::<ArgSettings>().unwrap(), + ArgSettings::Required + ); + assert_eq!( + "takesvalue".parse::<ArgSettings>().unwrap(), + ArgSettings::TakesValue + ); + assert_eq!( + "usevaluedelimiter".parse::<ArgSettings>().unwrap(), + ArgSettings::UseValueDelimiter + ); + assert_eq!( + "requireequals".parse::<ArgSettings>().unwrap(), + ArgSettings::RequireEquals + ); + assert_eq!("last".parse::<ArgSettings>().unwrap(), ArgSettings::Last); + assert_eq!( + "hidedefaultvalue".parse::<ArgSettings>().unwrap(), + ArgSettings::HideDefaultValue + ); + assert_eq!( + "ignorecase".parse::<ArgSettings>().unwrap(), + ArgSettings::IgnoreCase + ); + #[cfg(feature = "env")] + assert_eq!( + "hideenv".parse::<ArgSettings>().unwrap(), + ArgSettings::HideEnv + ); + #[cfg(feature = "env")] + assert_eq!( + "hideenvvalues".parse::<ArgSettings>().unwrap(), + ArgSettings::HideEnvValues + ); + assert_eq!( + "hiddenshorthelp".parse::<ArgSettings>().unwrap(), + ArgSettings::HiddenShortHelp + ); + assert_eq!( + "hiddenlonghelp".parse::<ArgSettings>().unwrap(), + ArgSettings::HiddenLongHelp + ); + assert_eq!( + "allowinvalidutf8".parse::<ArgSettings>().unwrap(), + ArgSettings::AllowInvalidUtf8 + ); + assert_eq!( + "exclusive".parse::<ArgSettings>().unwrap(), + ArgSettings::Exclusive + ); + assert!("hahahaha".parse::<ArgSettings>().is_err()); + } +} diff --git a/third_party/rust/clap/src/build/command.rs b/third_party/rust/clap/src/build/command.rs new file mode 100644 index 0000000000..1ba2629109 --- /dev/null +++ b/third_party/rust/clap/src/build/command.rs @@ -0,0 +1,4984 @@ +#![allow(deprecated)] + +// Std +use std::collections::HashMap; +use std::env; +use std::ffi::OsString; +use std::fmt; +use std::io; +use std::ops::Index; +use std::path::Path; + +// Third Party +#[cfg(feature = "yaml")] +use yaml_rust::Yaml; + +// Internal +use crate::build::app_settings::{AppFlags, AppSettings}; +use crate::build::arg_settings::ArgSettings; +use crate::build::{arg::ArgProvider, Arg, ArgGroup, ArgPredicate}; +use crate::error::ErrorKind; +use crate::error::Result as ClapResult; +use crate::mkeymap::MKeyMap; +use crate::output::fmt::Stream; +use crate::output::{fmt::Colorizer, Help, HelpWriter, Usage}; +use crate::parse::{ArgMatcher, ArgMatches, Parser}; +use crate::util::ChildGraph; +use crate::util::{color::ColorChoice, Id, Key}; +use crate::PossibleValue; +use crate::{Error, INTERNAL_ERROR_MSG}; + +#[cfg(debug_assertions)] +use crate::build::debug_asserts::assert_app; + +/// Build a command-line interface. +/// +/// This includes defining arguments, subcommands, parser behavior, and help output. +/// Once all configuration is complete, +/// the [`Command::get_matches`] family of methods starts the runtime-parsing +/// process. These methods then return information about the user supplied +/// arguments (or lack thereof). +/// +/// When deriving a [`Parser`][crate::Parser], you can use +/// [`CommandFactory::command`][crate::CommandFactory::command] to access the +/// `Command`. +/// +/// - [Basic API][crate::App#basic-api] +/// - [Application-wide Settings][crate::App#application-wide-settings] +/// - [Command-specific Settings][crate::App#command-specific-settings] +/// - [Subcommand-specific Settings][crate::App#subcommand-specific-settings] +/// - [Reflection][crate::App#reflection] +/// +/// # Examples +/// +/// ```no_run +/// # use clap::{Command, Arg}; +/// let m = Command::new("My Program") +/// .author("Me, me@mail.com") +/// .version("1.0.2") +/// .about("Explains in brief what the program does") +/// .arg( +/// Arg::new("in_file") +/// ) +/// .after_help("Longer explanation to appear after the options when \ +/// displaying the help information from --help or -h") +/// .get_matches(); +/// +/// // Your program logic starts here... +/// ``` +/// [`App::get_matches`]: Command::get_matches() +pub type Command<'help> = App<'help>; + +/// Deprecated, replaced with [`Command`] +#[deprecated(since = "3.1.0", note = "Replaced with `Command`")] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct App<'help> { + id: Id, + name: String, + long_flag: Option<&'help str>, + short_flag: Option<char>, + display_name: Option<String>, + bin_name: Option<String>, + author: Option<&'help str>, + version: Option<&'help str>, + long_version: Option<&'help str>, + about: Option<&'help str>, + long_about: Option<&'help str>, + before_help: Option<&'help str>, + before_long_help: Option<&'help str>, + after_help: Option<&'help str>, + after_long_help: Option<&'help str>, + aliases: Vec<(&'help str, bool)>, // (name, visible) + short_flag_aliases: Vec<(char, bool)>, // (name, visible) + long_flag_aliases: Vec<(&'help str, bool)>, // (name, visible) + usage_str: Option<&'help str>, + usage_name: Option<String>, + help_str: Option<&'help str>, + disp_ord: Option<usize>, + term_w: Option<usize>, + max_w: Option<usize>, + template: Option<&'help str>, + settings: AppFlags, + g_settings: AppFlags, + args: MKeyMap<'help>, + subcommands: Vec<App<'help>>, + replacers: HashMap<&'help str, &'help [&'help str]>, + groups: Vec<ArgGroup<'help>>, + current_help_heading: Option<&'help str>, + current_disp_ord: Option<usize>, + subcommand_value_name: Option<&'help str>, + subcommand_heading: Option<&'help str>, +} + +/// # Basic API +impl<'help> App<'help> { + /// Creates a new instance of an `Command`. + /// + /// It is common, but not required, to use binary name as the `name`. This + /// name will only be displayed to the user when they request to print + /// version or help and usage information. + /// + /// See also [`command!`](crate::command!) and [`crate_name!`](crate::crate_name!). + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("My Program") + /// # ; + /// ``` + pub fn new<S: Into<String>>(name: S) -> Self { + /// The actual implementation of `new`, non-generic to save code size. + /// + /// If we don't do this rustc will unnecessarily generate multiple versions + /// of this code. + fn new_inner<'help>(name: String) -> App<'help> { + App { + id: Id::from(&*name), + name, + ..Default::default() + } + .arg( + Arg::new("help") + .long("help") + .help("Print help information") + .global(true) + .generated(), + ) + .arg( + Arg::new("version") + .long("version") + .help("Print version information") + .global(true) + .generated(), + ) + } + + new_inner(name.into()) + } + + /// Adds an [argument] to the list of valid possibilities. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, arg, Arg}; + /// Command::new("myprog") + /// // Adding a single "flag" argument with a short and help text, using Arg::new() + /// .arg( + /// Arg::new("debug") + /// .short('d') + /// .help("turns on debugging mode") + /// ) + /// // Adding a single "option" argument with a short, a long, and help text using the less + /// // verbose Arg::from() + /// .arg( + /// arg!(-c --config <CONFIG> "Optionally sets a config file to use") + /// ) + /// # ; + /// ``` + /// [argument]: Arg + #[must_use] + pub fn arg<A: Into<Arg<'help>>>(mut self, a: A) -> Self { + let mut arg = a.into(); + if let Some(current_disp_ord) = self.current_disp_ord.as_mut() { + if !arg.is_positional() && arg.provider != ArgProvider::Generated { + let current = *current_disp_ord; + arg.disp_ord.set_implicit(current); + *current_disp_ord = current + 1; + } + } + + arg.help_heading.get_or_insert(self.current_help_heading); + self.args.push(arg); + self + } + + /// Adds multiple [arguments] to the list of valid possibilities. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, arg, Arg}; + /// Command::new("myprog") + /// .args(&[ + /// arg!("[debug] -d 'turns on debugging info'"), + /// Arg::new("input").help("the input file to use") + /// ]) + /// # ; + /// ``` + /// [arguments]: Arg + #[must_use] + pub fn args<I, T>(mut self, args: I) -> Self + where + I: IntoIterator<Item = T>, + T: Into<Arg<'help>>, + { + let args = args.into_iter(); + let (lower, _) = args.size_hint(); + self.args.reserve(lower); + + for arg in args { + self = self.arg(arg); + } + self + } + + /// Allows one to mutate an [`Arg`] after it's been added to a [`Command`]. + /// + /// This can be useful for modifying the auto-generated help or version arguments. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// + /// let mut cmd = Command::new("foo") + /// .arg(Arg::new("bar") + /// .short('b')) + /// .mut_arg("bar", |a| a.short('B')); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]); + /// + /// // Since we changed `bar`'s short to "B" this should err as there + /// // is no `-b` anymore, only `-B` + /// + /// assert!(res.is_err()); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]); + /// assert!(res.is_ok()); + /// ``` + #[must_use] + pub fn mut_arg<T, F>(mut self, arg_id: T, f: F) -> Self + where + F: FnOnce(Arg<'help>) -> Arg<'help>, + T: Key + Into<&'help str>, + { + let arg_id: &str = arg_id.into(); + let id = Id::from(arg_id); + + let mut a = self.args.remove_by_name(&id).unwrap_or_else(|| Arg { + id, + name: arg_id, + ..Arg::default() + }); + + if a.provider == ArgProvider::Generated { + a.provider = ArgProvider::GeneratedMutated; + } + + self.args.push(f(a)); + self + } + + /// Adds an [`ArgGroup`] to the application. + /// + /// [`ArgGroup`]s are a family of related arguments. + /// By placing them in a logical group, you can build easier requirement and exclusion rules. + /// + /// Example use cases: + /// - Make an entire [`ArgGroup`] required, meaning that one (and *only* + /// one) argument from that group must be present at runtime. + /// - Name an [`ArgGroup`] as a conflict to another argument. + /// Meaning any of the arguments that belong to that group will cause a failure if present with + /// the conflicting argument. + /// - Ensure exclusion between arguments. + /// - Extract a value from a group instead of determining exactly which argument was used. + /// + /// # Examples + /// + /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one, + /// of the arguments from the specified group is present at runtime. + /// + /// ```no_run + /// # use clap::{Command, arg, ArgGroup}; + /// Command::new("cmd") + /// .arg(arg!("--set-ver [ver] 'set the version manually'")) + /// .arg(arg!("--major 'auto increase major'")) + /// .arg(arg!("--minor 'auto increase minor'")) + /// .arg(arg!("--patch 'auto increase patch'")) + /// .group(ArgGroup::new("vers") + /// .args(&["set-ver", "major", "minor","patch"]) + /// .required(true)) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn group<G: Into<ArgGroup<'help>>>(mut self, group: G) -> Self { + self.groups.push(group.into()); + self + } + + /// Adds multiple [`ArgGroup`]s to the [`Command`] at once. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, arg, ArgGroup}; + /// Command::new("cmd") + /// .arg(arg!("--set-ver [ver] 'set the version manually'")) + /// .arg(arg!("--major 'auto increase major'")) + /// .arg(arg!("--minor 'auto increase minor'")) + /// .arg(arg!("--patch 'auto increase patch'")) + /// .arg(arg!("-c [FILE] 'a config file'")) + /// .arg(arg!("-i [IFACE] 'an interface'")) + /// .groups(&[ + /// ArgGroup::new("vers") + /// .args(&["set-ver", "major", "minor","patch"]) + /// .required(true), + /// ArgGroup::new("input") + /// .args(&["c", "i"]) + /// ]) + /// # ; + /// ``` + #[must_use] + pub fn groups<I, T>(mut self, groups: I) -> Self + where + I: IntoIterator<Item = T>, + T: Into<ArgGroup<'help>>, + { + for g in groups.into_iter() { + self = self.group(g.into()); + } + self + } + + /// Adds a subcommand to the list of valid possibilities. + /// + /// Subcommands are effectively sub-[`Command`]s, because they can contain their own arguments, + /// subcommands, version, usage, etc. They also function just like [`Command`]s, in that they get + /// their own auto generated help, version, and usage. + /// + /// A subcommand's [`Command::name`] will be used for: + /// - The argument the user passes in + /// - Programmatically looking up the subcommand + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("config") + /// .about("Controls configuration features") + /// .arg(arg!("<config> 'Required configuration file to use'"))) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn subcommand<S: Into<App<'help>>>(mut self, subcmd: S) -> Self { + self.subcommands.push(subcmd.into()); + self + } + + /// Adds multiple subcommands to the list of valid possibilities. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, }; + /// # Command::new("myprog") + /// .subcommands( vec![ + /// Command::new("config").about("Controls configuration functionality") + /// .arg(Arg::new("config_file")), + /// Command::new("debug").about("Controls debug functionality")]) + /// # ; + /// ``` + /// [`IntoIterator`]: std::iter::IntoIterator + #[must_use] + pub fn subcommands<I, T>(mut self, subcmds: I) -> Self + where + I: IntoIterator<Item = T>, + T: Into<App<'help>>, + { + for subcmd in subcmds.into_iter() { + self.subcommands.push(subcmd.into()); + } + self + } + + /// Catch problems earlier in the development cycle. + /// + /// Most error states are handled as asserts under the assumption they are programming mistake + /// and not something to handle at runtime. Rather than relying on tests (manual or automated) + /// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those + /// asserts in a way convenient for running as a test. + /// + /// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive + /// testing of your CLI. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// fn cmd() -> Command<'static> { + /// Command::new("foo") + /// .arg(Arg::new("bar").short('b') + /// ) + /// } + /// + /// #[test] + /// fn verify_app() { + /// cmd().debug_assert(); + /// } + /// + /// fn main() { + /// let m = cmd().get_matches_from(vec!["foo", "-b"]); + /// println!("{}", m.is_present("bar")); + /// } + /// ``` + pub fn debug_assert(mut self) { + self._build_all(); + } + + /// Custom error message for post-parsing validation + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let mut cmd = Command::new("myprog"); + /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case"); + /// ``` + pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error { + Error::raw(kind, message).format(self) + } + + /// Parse [`env::args_os`], exiting on failure. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let matches = Command::new("myprog") + /// // Args and options go here... + /// .get_matches(); + /// ``` + /// [`env::args_os`]: std::env::args_os() + /// [`App::try_get_matches_from_mut`]: Command::try_get_matches_from_mut() + #[inline] + pub fn get_matches(self) -> ArgMatches { + self.get_matches_from(&mut env::args_os()) + } + + /// Parse [`env::args_os`], exiting on failure. + /// + /// Like [`App::get_matches`] but doesn't consume the `Command`. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let mut cmd = Command::new("myprog") + /// // Args and options go here... + /// ; + /// let matches = cmd.get_matches_mut(); + /// ``` + /// [`env::args_os`]: std::env::args_os() + /// [`App::get_matches`]: Command::get_matches() + pub fn get_matches_mut(&mut self) -> ArgMatches { + self.try_get_matches_from_mut(&mut env::args_os()) + .unwrap_or_else(|e| e.exit()) + } + + /// Parse [`env::args_os`], returning a [`clap::Result`] on failure. + /// + /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are + /// used. It will return a [`clap::Error`], where the [`kind`] is a + /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call + /// [`Error::exit`] or perform a [`std::process::exit`]. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let matches = Command::new("myprog") + /// // Args and options go here... + /// .try_get_matches() + /// .unwrap_or_else(|e| e.exit()); + /// ``` + /// [`env::args_os`]: std::env::args_os() + /// [`Error::exit`]: crate::Error::exit() + /// [`std::process::exit`]: std::process::exit() + /// [`clap::Result`]: Result + /// [`clap::Error`]: crate::Error + /// [`kind`]: crate::Error + /// [`ErrorKind::DisplayHelp`]: crate::ErrorKind::DisplayHelp + /// [`ErrorKind::DisplayVersion`]: crate::ErrorKind::DisplayVersion + #[inline] + pub fn try_get_matches(self) -> ClapResult<ArgMatches> { + // Start the parsing + self.try_get_matches_from(&mut env::args_os()) + } + + /// Parse the specified arguments, exiting on failure. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`Command::no_binary_name`] is used. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let matches = Command::new("myprog") + /// // Args and options go here... + /// .get_matches_from(arg_vec); + /// ``` + /// [`App::get_matches`]: Command::get_matches() + /// [`clap::Result`]: Result + /// [`Vec`]: std::vec::Vec + pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches + where + I: IntoIterator<Item = T>, + T: Into<OsString> + Clone, + { + self.try_get_matches_from_mut(itr).unwrap_or_else(|e| { + drop(self); + e.exit() + }) + } + + /// Parse the specified arguments, returning a [`clap::Result`] on failure. + /// + /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are + /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] + /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or + /// perform a [`std::process::exit`] yourself. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`Command::no_binary_name`] is used. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let matches = Command::new("myprog") + /// // Args and options go here... + /// .try_get_matches_from(arg_vec) + /// .unwrap_or_else(|e| e.exit()); + /// ``` + /// [`App::get_matches_from`]: Command::get_matches_from() + /// [`App::try_get_matches`]: Command::try_get_matches() + /// [`Error::exit`]: crate::Error::exit() + /// [`std::process::exit`]: std::process::exit() + /// [`clap::Error`]: crate::Error + /// [`Error::exit`]: crate::Error::exit() + /// [`kind`]: crate::Error + /// [`ErrorKind::DisplayHelp`]: crate::ErrorKind::DisplayHelp + /// [`ErrorKind::DisplayVersion`]: crate::ErrorKind::DisplayVersion + /// [`clap::Result`]: Result + pub fn try_get_matches_from<I, T>(mut self, itr: I) -> ClapResult<ArgMatches> + where + I: IntoIterator<Item = T>, + T: Into<OsString> + Clone, + { + self.try_get_matches_from_mut(itr) + } + + /// Parse the specified arguments, returning a [`clap::Result`] on failure. + /// + /// Like [`App::try_get_matches_from`] but doesn't consume the `Command`. + /// + /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are + /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] + /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or + /// perform a [`std::process::exit`] yourself. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`Command::no_binary_name`] is used. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let mut cmd = Command::new("myprog"); + /// // Args and options go here... + /// let matches = cmd.try_get_matches_from_mut(arg_vec) + /// .unwrap_or_else(|e| e.exit()); + /// ``` + /// [`App::try_get_matches_from`]: Command::try_get_matches_from() + /// [`clap::Result`]: Result + /// [`clap::Error`]: crate::Error + /// [`kind`]: crate::Error + pub fn try_get_matches_from_mut<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches> + where + I: IntoIterator<Item = T>, + T: Into<OsString> + Clone, + { + let mut raw_args = clap_lex::RawArgs::new(itr.into_iter()); + let mut cursor = raw_args.cursor(); + + #[cfg(feature = "unstable-multicall")] + if self.settings.is_set(AppSettings::Multicall) { + if let Some(argv0) = raw_args.next_os(&mut cursor) { + let argv0 = Path::new(&argv0); + if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) { + // Stop borrowing command so we can get another mut ref to it. + let command = command.to_owned(); + debug!( + "Command::try_get_matches_from_mut: Parsed command {} from argv", + command + ); + + debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it"); + raw_args.insert(&cursor, &[&command]); + debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name"); + self.name.clear(); + self.bin_name = None; + return self._do_parse(&mut raw_args, cursor); + } + } + }; + + // Get the name of the program (argument 1 of env::args()) and determine the + // actual file + // that was used to execute the program. This is because a program called + // ./target/release/my_prog -a + // will have two arguments, './target/release/my_prog', '-a' but we don't want + // to display + // the full path when displaying help messages and such + if !self.settings.is_set(AppSettings::NoBinaryName) { + if let Some(name) = raw_args.next_os(&mut cursor) { + let p = Path::new(name); + + if let Some(f) = p.file_name() { + if let Some(s) = f.to_str() { + if self.bin_name.is_none() { + self.bin_name = Some(s.to_owned()); + } + } + } + } + } + + self._do_parse(&mut raw_args, cursor) + } + + /// Prints the short help message (`-h`) to [`io::stdout()`]. + /// + /// See also [`Command::print_long_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// let mut cmd = Command::new("myprog"); + /// cmd.print_help(); + /// ``` + /// [`io::stdout()`]: std::io::stdout() + pub fn print_help(&mut self) -> io::Result<()> { + self._build_self(); + let color = self.get_color(); + + let mut c = Colorizer::new(Stream::Stdout, color); + let usage = Usage::new(self); + Help::new(HelpWriter::Buffer(&mut c), self, &usage, false).write_help()?; + c.print() + } + + /// Prints the long help message (`--help`) to [`io::stdout()`]. + /// + /// See also [`Command::print_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// let mut cmd = Command::new("myprog"); + /// cmd.print_long_help(); + /// ``` + /// [`io::stdout()`]: std::io::stdout() + /// [`BufWriter`]: std::io::BufWriter + /// [`-h` (short)]: Arg::help() + /// [`--help` (long)]: Arg::long_help() + pub fn print_long_help(&mut self) -> io::Result<()> { + self._build_self(); + let color = self.get_color(); + + let mut c = Colorizer::new(Stream::Stdout, color); + let usage = Usage::new(self); + Help::new(HelpWriter::Buffer(&mut c), self, &usage, true).write_help()?; + c.print() + } + + /// Writes the short help message (`-h`) to a [`io::Write`] object. + /// + /// See also [`Command::write_long_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let mut cmd = Command::new("myprog"); + /// let mut out = io::stdout(); + /// cmd.write_help(&mut out).expect("failed to write to stdout"); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-h` (short)]: Arg::help() + /// [`--help` (long)]: Arg::long_help() + pub fn write_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> { + self._build_self(); + + let usage = Usage::new(self); + Help::new(HelpWriter::Normal(w), self, &usage, false).write_help()?; + w.flush() + } + + /// Writes the long help message (`--help`) to a [`io::Write`] object. + /// + /// See also [`Command::write_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let mut cmd = Command::new("myprog"); + /// let mut out = io::stdout(); + /// cmd.write_long_help(&mut out).expect("failed to write to stdout"); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-h` (short)]: Arg::help() + /// [`--help` (long)]: Arg::long_help() + pub fn write_long_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> { + self._build_self(); + + let usage = Usage::new(self); + Help::new(HelpWriter::Normal(w), self, &usage, true).write_help()?; + w.flush() + } + + /// Version message rendered as if the user ran `-V`. + /// + /// See also [`Command::render_long_version`]. + /// + /// ### Coloring + /// + /// This function does not try to color the message nor it inserts any [ANSI escape codes]. + /// + /// ### Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let cmd = Command::new("myprog"); + /// println!("{}", cmd.render_version()); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-V` (short)]: Command::version() + /// [`--version` (long)]: Command::long_version() + /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code + pub fn render_version(&self) -> String { + self._render_version(false) + } + + /// Version message rendered as if the user ran `--version`. + /// + /// See also [`Command::render_version`]. + /// + /// ### Coloring + /// + /// This function does not try to color the message nor it inserts any [ANSI escape codes]. + /// + /// ### Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let cmd = Command::new("myprog"); + /// println!("{}", cmd.render_long_version()); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-V` (short)]: Command::version() + /// [`--version` (long)]: Command::long_version() + /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code + pub fn render_long_version(&self) -> String { + self._render_version(true) + } + + /// Usage statement + /// + /// ### Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let mut cmd = Command::new("myprog"); + /// println!("{}", cmd.render_usage()); + /// ``` + pub fn render_usage(&mut self) -> String { + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing incase we run into a subcommand + self._build_self(); + + Usage::new(self).create_usage_with_title(&[]) + } +} + +/// # Application-wide Settings +/// +/// These settings will apply to the top-level command and all subcommands, by default. Some +/// settings can be overridden in subcommands. +impl<'help> App<'help> { + /// Specifies that the parser should not assume the first argument passed is the binary name. + /// + /// This is normally the case when using a "daemon" style mode. For shells / REPLs, see + /// [`Command::multicall`][App::multicall]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let m = Command::new("myprog") + /// .no_binary_name(true) + /// .arg(arg!(<cmd> ... "commands to run")) + /// .get_matches_from(vec!["command", "set"]); + /// + /// let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect(); + /// assert_eq!(cmds, ["command", "set"]); + /// ``` + /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut() + #[inline] + pub fn no_binary_name(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::NoBinaryName) + } else { + self.unset_global_setting(AppSettings::NoBinaryName) + } + } + + /// Try not to fail on parse errors, like missing option values. + /// + /// **Note:** Make sure you apply it as `global_setting` if you want this setting + /// to be propagated to subcommands and sub-subcommands! + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let cmd = Command::new("cmd") + /// .ignore_errors(true) + /// .arg(arg!(-c --config <FILE> "Sets a custom config file").required(false)) + /// .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file").required(false)) + /// .arg(arg!(f: -f "Flag")); + /// + /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]); + /// + /// assert!(r.is_ok(), "unexpected error: {:?}", r); + /// let m = r.unwrap(); + /// assert_eq!(m.value_of("config"), Some("file")); + /// assert!(m.is_present("f")); + /// assert_eq!(m.value_of("stuff"), None); + /// ``` + #[inline] + pub fn ignore_errors(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::IgnoreErrors) + } else { + self.unset_global_setting(AppSettings::IgnoreErrors) + } + } + + /// Specifies that all arguments override themselves. + /// + /// This is the equivalent to saying the `foo` arg using [`Arg::overrides_with("foo")`] for all + /// defined arguments. + /// + /// **NOTE:** This will not be applied when [`Arg::multiple_occurrences(true)`]. + /// + /// **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::use_value_delimiter(false)`]. Using this setting is safer, because it's easier to locate + /// when making changes. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .dont_delimit_trailing_values(true) + /// .get_matches(); + /// ``` + /// + /// [`Arg::use_value_delimiter(false)`]: crate::Arg::use_value_delimiter() + #[inline] + pub fn dont_delimit_trailing_values(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DontDelimitTrailingValues) + } else { + self.unset_global_setting(AppSettings::DontDelimitTrailingValues) + } + } + + /// Sets when to color output. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// **NOTE:** Default behaviour is [`ColorChoice::Auto`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, ColorChoice}; + /// Command::new("myprog") + /// .color(ColorChoice::Never) + /// .get_matches(); + /// ``` + /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto + #[cfg(feature = "color")] + #[inline] + #[must_use] + pub fn color(self, color: ColorChoice) -> Self { + #![allow(deprecated)] + let cmd = self + .unset_global_setting(AppSettings::ColorAuto) + .unset_global_setting(AppSettings::ColorAlways) + .unset_global_setting(AppSettings::ColorNever); + match color { + ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto), + ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways), + ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever), + } + } + + /// Sets the terminal width at which to wrap help messages. + /// + /// Using `0` will ignore terminal widths and use source formatting. + /// + /// Defaults to current terminal width when `wrap_help` feature flag is enabled. If the flag + /// is disabled or it cannot be determined, the default is 100. + /// + /// **NOTE:** This setting applies globally and *not* on a per-command basis. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .term_width(80) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn term_width(mut self, width: usize) -> Self { + self.term_w = Some(width); + self + } + + /// Sets the maximum terminal width at which to wrap help messages. + /// + /// This only applies when setting the current terminal width. See [`Command::term_width`] for + /// more details. + /// + /// Using `0` will ignore terminal widths and use source formatting. + /// + /// **NOTE:** This setting applies globally and *not* on a per-command basis. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .max_term_width(100) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn max_term_width(mut self, w: usize) -> Self { + self.max_w = Some(w); + self + } + + /// Disables `-V` and `--version` flag. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let res = Command::new("myprog") + /// .disable_version_flag(true) + /// .try_get_matches_from(vec![ + /// "myprog", "-V" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + #[inline] + pub fn disable_version_flag(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DisableVersionFlag) + } else { + self.unset_global_setting(AppSettings::DisableVersionFlag) + } + } + + /// Specifies to use the version of the current command for all [`subcommands`]. + /// + /// Defaults to `false`; subcommands have independent version strings from their parents. + /// + /// **Note:** Make sure you apply it as `global_setting` if you want this setting + /// to be propagated to subcommands and sub-subcommands! + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .version("v1.1") + /// .propagate_version(true) + /// .subcommand(Command::new("test")) + /// .get_matches(); + /// // running `$ myprog test --version` will display + /// // "myprog-test v1.1" + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + #[inline] + pub fn propagate_version(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::PropagateVersion) + } else { + self.unset_global_setting(AppSettings::PropagateVersion) + } + } + + /// Places the help string for all arguments and subcommands on the line after them. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .next_line_help(true) + /// .get_matches(); + /// ``` + #[inline] + pub fn next_line_help(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::NextLineHelp) + } else { + self.unset_global_setting(AppSettings::NextLineHelp) + } + } + + /// Disables `-h` and `--help` flag. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let res = Command::new("myprog") + /// .disable_help_flag(true) + /// .try_get_matches_from(vec![ + /// "myprog", "-h" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + #[inline] + pub fn disable_help_flag(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DisableHelpFlag) + } else { + self.unset_global_setting(AppSettings::DisableHelpFlag) + } + } + + /// Disables the `help` [`subcommand`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let res = Command::new("myprog") + /// .disable_help_subcommand(true) + /// // Normally, creating a subcommand causes a `help` subcommand to automatically + /// // be generated as well + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", "help" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + /// + /// [`subcommand`]: crate::Command::subcommand() + #[inline] + pub fn disable_help_subcommand(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DisableHelpSubcommand) + } else { + self.unset_global_setting(AppSettings::DisableHelpSubcommand) + } + } + + /// Disables colorized help messages. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .disable_colored_help(true) + /// .get_matches(); + /// ``` + #[inline] + pub fn disable_colored_help(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DisableColoredHelp) + } else { + self.unset_global_setting(AppSettings::DisableColoredHelp) + } + } + + /// Panic if help descriptions are omitted. + /// + /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at + /// compile-time with `#![deny(missing_docs)]` + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .help_expected(true) + /// .arg( + /// Arg::new("foo").help("It does foo stuff") + /// // As required via `help_expected`, a help message was supplied + /// ) + /// # .get_matches(); + /// ``` + /// + /// # Panics + /// + /// ```rust,no_run + /// # use clap::{Command, Arg}; + /// Command::new("myapp") + /// .help_expected(true) + /// .arg( + /// Arg::new("foo") + /// // Someone forgot to put .about("...") here + /// // Since the setting `help_expected` is activated, this will lead to + /// // a panic (if you are in debug mode) + /// ) + /// # .get_matches(); + ///``` + #[inline] + pub fn help_expected(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::HelpExpected) + } else { + self.unset_global_setting(AppSettings::HelpExpected) + } + } + + /// Disables the automatic collapsing of positional args into `[ARGS]` inside the usage string. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .dont_collapse_args_in_usage(true) + /// .get_matches(); + /// ``` + #[inline] + pub fn dont_collapse_args_in_usage(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DontCollapseArgsInUsage) + } else { + self.unset_global_setting(AppSettings::DontCollapseArgsInUsage) + } + } + + /// Tells `clap` *not* to print possible values when displaying help information. + /// + /// This can be useful if there are many values, or they are explained elsewhere. + /// + /// To set this per argument, see + /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values]. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + #[inline] + pub fn hide_possible_values(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::HidePossibleValues) + } else { + self.unset_global_setting(AppSettings::HidePossibleValues) + } + } + + /// Allow partial matches of long arguments or their [aliases]. + /// + /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and + /// `--test`. + /// + /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match + /// `--te` to `--test` there could not also be another argument or alias `--temp` because both + /// start with `--te` + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// [aliases]: crate::Command::aliases() + #[inline] + pub fn infer_long_args(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::InferLongArgs) + } else { + self.unset_global_setting(AppSettings::InferLongArgs) + } + } + + /// Allow partial matches of [subcommand] names and their [aliases]. + /// + /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and + /// `test`. + /// + /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te` + /// to `test` there could not also be a subcommand or alias `temp` because both start with `te` + /// + /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when + /// designing CLIs which allow inferred subcommands and have potential positional/free + /// arguments whose values could start with the same characters as subcommands. If this is the + /// case, it's recommended to use settings such as [`Command::args_conflicts_with_subcommands`] in + /// conjunction with this setting. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .infer_subcommands(true) + /// .subcommand(Command::new("test")) + /// .get_matches_from(vec![ + /// "prog", "te" + /// ]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// + /// [subcommand]: crate::Command::subcommand() + /// [positional/free arguments]: crate::Arg::index() + /// [aliases]: crate::Command::aliases() + #[inline] + pub fn infer_subcommands(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::InferSubcommands) + } else { + self.unset_global_setting(AppSettings::InferSubcommands) + } + } +} + +/// # Command-specific Settings +/// +/// These apply only to the current command and are not inherited by subcommands. +impl<'help> App<'help> { + /// (Re)Sets the program's name. + /// + /// See [`Command::new`] for more details. + /// + /// # Examples + /// + /// ```ignore + /// # use clap::{Command, load_yaml}; + /// let yaml = load_yaml!("cmd.yaml"); + /// let cmd = Command::from(yaml) + /// .name(crate_name!()); + /// + /// // continued logic goes here, such as `cmd.get_matches()` etc. + /// ``` + #[must_use] + pub fn name<S: Into<String>>(mut self, name: S) -> Self { + self.name = name.into(); + self + } + + /// Overrides the runtime-determined name of the binary for help and error messages. + /// + /// This should only be used when absolutely necessary, such as when the binary name for your + /// application is misleading, or perhaps *not* how the user should invoke your program. + /// + /// **Pro-tip:** When building things such as third party `cargo` + /// subcommands, this setting **should** be used! + /// + /// **NOTE:** This *does not* change or set the name of the binary file on + /// disk. It only changes what clap thinks the name is for the purposes of + /// error or help messages. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("My Program") + /// .bin_name("my_binary") + /// # ; + /// ``` + #[must_use] + pub fn bin_name<S: Into<String>>(mut self, name: S) -> Self { + self.bin_name = Some(name.into()); + self + } + + /// Overrides the runtime-determined display name of the program for help and error messages. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("My Program") + /// .display_name("my_program") + /// # ; + /// ``` + #[must_use] + pub fn display_name<S: Into<String>>(mut self, name: S) -> Self { + self.display_name = Some(name.into()); + self + } + + /// Sets the author(s) for the help message. + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to + /// automatically set your application's author(s) to the same thing as your + /// crate at compile time. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .author("Me, me@mymain.com") + /// # ; + /// ``` + /// [`crate_authors!`]: ./macro.crate_authors!.html + #[must_use] + pub fn author<S: Into<&'help str>>(mut self, author: S) -> Self { + self.author = Some(author.into()); + self + } + + /// Sets the program's description for the short help (`-h`). + /// + /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`. + /// + /// **NOTE:** Only `Command::about` (short format) is used in completion + /// script generation in order to be concise. + /// + /// See also [`crate_description!`](crate::crate_description!). + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .about("Does really amazing things for great people") + /// # ; + /// ``` + #[must_use] + pub fn about<O: Into<Option<&'help str>>>(mut self, about: O) -> Self { + self.about = about.into(); + self + } + + /// Sets the program's description for the long help (`--help`). + /// + /// If [`Command::about`] is not specified, this message will be displayed for `-h`. + /// + /// **NOTE:** Only [`Command::about`] (short format) is used in completion + /// script generation in order to be concise. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .long_about( + /// "Does really amazing things to great people. Now let's talk a little + /// more in depth about how this subcommand really works. It may take about + /// a few lines of text, but that's ok!") + /// # ; + /// ``` + /// [`App::about`]: Command::about() + #[must_use] + pub fn long_about<O: Into<Option<&'help str>>>(mut self, long_about: O) -> Self { + self.long_about = long_about.into(); + self + } + + /// Free-form help text for after auto-generated short help (`-h`). + /// + /// This is often used to describe how to use the arguments, caveats to be noted, or license + /// and contact information. + /// + /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .after_help("Does really amazing things for great people... but be careful with -R!") + /// # ; + /// ``` + /// + #[must_use] + pub fn after_help<S: Into<&'help str>>(mut self, help: S) -> Self { + self.after_help = Some(help.into()); + self + } + + /// Free-form help text for after auto-generated long help (`--help`). + /// + /// This is often used to describe how to use the arguments, caveats to be noted, or license + /// and contact information. + /// + /// If [`Command::after_help`] is not specified, this message will be displayed for `-h`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .after_long_help("Does really amazing things to great people... but be careful with -R, \ + /// like, for real, be careful with this!") + /// # ; + /// ``` + #[must_use] + pub fn after_long_help<S: Into<&'help str>>(mut self, help: S) -> Self { + self.after_long_help = Some(help.into()); + self + } + + /// Free-form help text for before auto-generated short help (`-h`). + /// + /// This is often used for header, copyright, or license information. + /// + /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .before_help("Some info I'd like to appear before the help info") + /// # ; + /// ``` + #[must_use] + pub fn before_help<S: Into<&'help str>>(mut self, help: S) -> Self { + self.before_help = Some(help.into()); + self + } + + /// Free-form help text for before auto-generated long help (`--help`). + /// + /// This is often used for header, copyright, or license information. + /// + /// If [`Command::before_help`] is not specified, this message will be displayed for `-h`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .before_long_help("Some verbose and long info I'd like to appear before the help info") + /// # ; + /// ``` + #[must_use] + pub fn before_long_help<S: Into<&'help str>>(mut self, help: S) -> Self { + self.before_long_help = Some(help.into()); + self + } + + /// Sets the version for the short version (`-V`) and help messages. + /// + /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`. + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to + /// automatically set your application's version to the same thing as your + /// crate at compile time. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .version("v0.1.24") + /// # ; + /// ``` + /// [`crate_version!`]: ./macro.crate_version!.html + #[must_use] + pub fn version<S: Into<&'help str>>(mut self, ver: S) -> Self { + self.version = Some(ver.into()); + self + } + + /// Sets the version for the long version (`--version`) and help messages. + /// + /// If [`Command::version`] is not specified, this message will be displayed for `-V`. + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to + /// automatically set your application's version to the same thing as your + /// crate at compile time. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .long_version( + /// "v0.1.24 + /// commit: abcdef89726d + /// revision: 123 + /// release: 2 + /// binary: myprog") + /// # ; + /// ``` + /// [`crate_version!`]: ./macro.crate_version!.html + #[must_use] + pub fn long_version<S: Into<&'help str>>(mut self, ver: S) -> Self { + self.long_version = Some(ver.into()); + self + } + + /// Overrides the `clap` generated usage string for help and error messages. + /// + /// **NOTE:** Using this setting disables `clap`s "context-aware" usage + /// strings. After this setting is set, this will be *the only* usage string + /// displayed to the user! + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .override_usage("myapp [-clDas] <some_file>") + /// # ; + /// ``` + /// [`ArgMatches::usage`]: ArgMatches::usage() + #[must_use] + pub fn override_usage<S: Into<&'help str>>(mut self, usage: S) -> Self { + self.usage_str = Some(usage.into()); + self + } + + /// Overrides the `clap` generated help message (both `-h` and `--help`). + /// + /// This should only be used when the auto-generated message does not suffice. + /// + /// **NOTE:** This **only** replaces the help message for the current + /// command, meaning if you are using subcommands, those help messages will + /// still be auto-generated unless you specify a [`Command::override_help`] for + /// them as well. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myapp") + /// .override_help("myapp v1.0\n\ + /// Does awesome things\n\ + /// (C) me@mail.com\n\n\ + /// + /// USAGE: myapp <opts> <command>\n\n\ + /// + /// Options:\n\ + /// -h, --help Display this message\n\ + /// -V, --version Display version info\n\ + /// -s <stuff> Do something with stuff\n\ + /// -v Be verbose\n\n\ + /// + /// Commands:\n\ + /// help Print this message\n\ + /// work Do some work") + /// # ; + /// ``` + #[must_use] + pub fn override_help<S: Into<&'help str>>(mut self, help: S) -> Self { + self.help_str = Some(help.into()); + self + } + + /// Sets the help template to be used, overriding the default format. + /// + /// **NOTE:** The template system is by design very simple. Therefore, the + /// tags have to be written in the lowercase and without spacing. + /// + /// Tags are given inside curly brackets. + /// + /// Valid tags are: + /// + /// * `{name}` - Display name for the (sub-)command. + /// * `{bin}` - Binary name. + /// * `{version}` - Version number. + /// * `{author}` - Author information. + /// * `{author-with-newline}` - Author followed by `\n`. + /// * `{author-section}` - Author preceded and followed by `\n`. + /// * `{about}` - General description (from [`Command::about`] or + /// [`Command::long_about`]). + /// * `{about-with-newline}` - About followed by `\n`. + /// * `{about-section}` - About preceded and followed by '\n'. + /// * `{usage-heading}` - Automatically generated usage heading. + /// * `{usage}` - Automatically generated or given usage string. + /// * `{all-args}` - Help for all arguments (options, flags, positional + /// arguments, and subcommands) including titles. + /// * `{options}` - Help for options. + /// * `{positionals}` - Help for positional arguments. + /// * `{subcommands}` - Help for subcommands. + /// * `{after-help}` - Help from [`App::after_help`] or [`Command::after_long_help`]. + /// * `{before-help}` - Help from [`App::before_help`] or [`Command::before_long_help`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .version("1.0") + /// .help_template("{bin} ({version}) - {usage}") + /// # ; + /// ``` + /// [`App::about`]: Command::about() + /// [`App::long_about`]: Command::long_about() + /// [`App::after_help`]: Command::after_help() + /// [`App::after_long_help`]: Command::after_long_help() + /// [`App::before_help`]: Command::before_help() + /// [`App::before_long_help`]: Command::before_long_help() + #[must_use] + pub fn help_template<S: Into<&'help str>>(mut self, s: S) -> Self { + self.template = Some(s.into()); + self + } + + /// Apply a setting for the current command or subcommand. + /// + /// See [`Command::global_setting`] to apply a setting to this command and all subcommands. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, AppSettings}; + /// Command::new("myprog") + /// .setting(AppSettings::SubcommandRequired) + /// .setting(AppSettings::AllowLeadingHyphen) + /// # ; + /// ``` + /// or + /// ```no_run + /// # use clap::{Command, AppSettings}; + /// Command::new("myprog") + /// .setting(AppSettings::SubcommandRequired | AppSettings::AllowLeadingHyphen) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn setting<F>(mut self, setting: F) -> Self + where + F: Into<AppFlags>, + { + self.settings.insert(setting.into()); + self + } + + /// Remove a setting for the current command or subcommand. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, AppSettings}; + /// Command::new("myprog") + /// .unset_setting(AppSettings::SubcommandRequired) + /// .setting(AppSettings::AllowLeadingHyphen) + /// # ; + /// ``` + /// or + /// ```no_run + /// # use clap::{Command, AppSettings}; + /// Command::new("myprog") + /// .unset_setting(AppSettings::SubcommandRequired | AppSettings::AllowLeadingHyphen) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn unset_setting<F>(mut self, setting: F) -> Self + where + F: Into<AppFlags>, + { + self.settings.remove(setting.into()); + self + } + + /// Apply a setting for the current command and all subcommands. + /// + /// See [`Command::setting`] to apply a setting only to this command. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, AppSettings}; + /// Command::new("myprog") + /// .global_setting(AppSettings::AllowNegativeNumbers) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn global_setting(mut self, setting: AppSettings) -> Self { + self.settings.set(setting); + self.g_settings.set(setting); + self + } + + /// Remove a setting and stop propagating down to subcommands. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, AppSettings}; + /// Command::new("myprog") + /// .unset_global_setting(AppSettings::AllowNegativeNumbers) + /// # ; + /// ``` + /// [global]: Command::global_setting() + #[inline] + #[must_use] + pub fn unset_global_setting(mut self, setting: AppSettings) -> Self { + self.settings.unset(setting); + self.g_settings.unset(setting); + self + } + + /// Deprecated, replaced with [`Command::next_help_heading`] + #[inline] + #[must_use] + #[deprecated(since = "3.1.0", note = "Replaced with `App::next_help_heading`")] + pub fn help_heading<O>(self, heading: O) -> Self + where + O: Into<Option<&'help str>>, + { + self.next_help_heading(heading) + } + + /// Set the default section heading for future args. + /// + /// This will be used for any arg that hasn't had [`Arg::help_heading`] called. + /// + /// This is useful if the default `OPTIONS` or `ARGS` headings are + /// not specific enough for one's use case. + /// + /// For subcommands, see [`Command::subcommand_help_heading`] + /// + /// [`App::arg`]: Command::arg() + /// [`Arg::help_heading`]: crate::Arg::help_heading() + #[inline] + #[must_use] + pub fn next_help_heading<O>(mut self, heading: O) -> Self + where + O: Into<Option<&'help str>>, + { + self.current_help_heading = heading.into(); + self + } + + /// Change the starting value for assigning future display orders for ags. + /// + /// This will be used for any arg that hasn't had [`Arg::display_order`] called. + #[inline] + #[must_use] + pub fn next_display_order(mut self, disp_ord: impl Into<Option<usize>>) -> Self { + self.current_disp_ord = disp_ord.into(); + self + } + + /// Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands. + /// + /// **Note:** This is gated behind [`unstable-replace`](https://github.com/clap-rs/clap/issues/2836) + /// + /// When this method is used, `name` is removed from the CLI, and `target` + /// is inserted in its place. Parsing continues as if the user typed + /// `target` instead of `name`. + /// + /// This can be used to create "shortcuts" for subcommands, or if a + /// particular argument has the semantic meaning of several other specific + /// arguments and values. + /// + /// # Examples + /// + /// We'll start with the "subcommand short" example. In this example, let's + /// assume we have a program with a subcommand `module` which can be invoked + /// via `cmd module`. Now let's also assume `module` also has a subcommand + /// called `install` which can be invoked `cmd module install`. If for some + /// reason users needed to be able to reach `cmd module install` via the + /// short-hand `cmd install`, we'd have several options. + /// + /// We *could* create another sibling subcommand to `module` called + /// `install`, but then we would need to manage another subcommand and manually + /// dispatch to `cmd module install` handling code. This is error prone and + /// tedious. + /// + /// We could instead use [`Command::replace`] so that, when the user types `cmd + /// install`, `clap` will replace `install` with `module install` which will + /// end up getting parsed as if the user typed the entire incantation. + /// + /// ```rust + /// # use clap::Command; + /// let m = Command::new("cmd") + /// .subcommand(Command::new("module") + /// .subcommand(Command::new("install"))) + /// .replace("install", &["module", "install"]) + /// .get_matches_from(vec!["cmd", "install"]); + /// + /// assert!(m.subcommand_matches("module").is_some()); + /// assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some()); + /// ``` + /// + /// Now let's show an argument example! + /// + /// Let's assume we have an application with two flags `--save-context` and + /// `--save-runtime`. But often users end up needing to do *both* at the + /// same time. We can add a third flag `--save-all` which semantically means + /// the same thing as `cmd --save-context --save-runtime`. To implement that, + /// we have several options. + /// + /// We could create this third argument and manually check if that argument + /// and in our own consumer code handle the fact that both `--save-context` + /// and `--save-runtime` *should* have been used. But again this is error + /// prone and tedious. If we had code relying on checking `--save-context` + /// and we forgot to update that code to *also* check `--save-all` it'd mean + /// an error! + /// + /// Luckily we can use [`Command::replace`] so that when the user types + /// `--save-all`, `clap` will replace that argument with `--save-context + /// --save-runtime`, and parsing will continue like normal. Now all our code + /// that was originally checking for things like `--save-context` doesn't + /// need to change! + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("cmd") + /// .arg(Arg::new("save-context") + /// .long("save-context")) + /// .arg(Arg::new("save-runtime") + /// .long("save-runtime")) + /// .replace("--save-all", &["--save-context", "--save-runtime"]) + /// .get_matches_from(vec!["cmd", "--save-all"]); + /// + /// assert!(m.is_present("save-context")); + /// assert!(m.is_present("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}; + /// let m = Command::new("cmd") + /// .arg(Arg::new("save-context") + /// .long("save-context")) + /// .arg(Arg::new("save-runtime") + /// .long("save-runtime")) + /// .arg(Arg::new("format") + /// .long("format") + /// .takes_value(true) + /// .possible_values(["txt", "json"])) + /// .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"]) + /// .get_matches_from(vec!["cmd", "--save-all"]); + /// + /// assert!(m.is_present("save-context")); + /// assert!(m.is_present("save-runtime")); + /// assert_eq!(m.value_of("format"), Some("json")); + /// ``` + /// + /// [`App::replace`]: Command::replace() + #[inline] + #[cfg(feature = "unstable-replace")] + #[must_use] + pub fn replace(mut self, name: &'help str, target: &'help [&'help str]) -> Self { + self.replacers.insert(name, target); + self + } + + /// Exit gracefully if no arguments are present (e.g. `$ myprog`). + /// + /// **NOTE:** [`subcommands`] count as arguments + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command}; + /// Command::new("myprog") + /// .arg_required_else_help(true); + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + /// [`Arg::default_value`]: crate::Arg::default_value() + #[inline] + pub fn arg_required_else_help(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::ArgRequiredElseHelp) + } else { + self.unset_setting(AppSettings::ArgRequiredElseHelp) + } + } + + /// Specifies that leading hyphens are allowed in all argument *values* (e.g. `-10`). + /// + /// Otherwise they will be parsed as another flag or option. See also + /// [`Command::allow_negative_numbers`]. + /// + /// **NOTE:** Use this setting with caution as it silences certain circumstances which would + /// otherwise be an error (such as accidentally forgetting to specify a value for leading + /// option). It is preferred to set this on a per argument basis, via [`Arg::allow_hyphen_values`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Arg, Command}; + /// // Imagine you needed to represent negative numbers as well, such as -10 + /// let m = Command::new("nums") + /// .allow_hyphen_values(true) + /// .arg(Arg::new("neg")) + /// .get_matches_from(vec![ + /// "nums", "-20" + /// ]); + /// + /// assert_eq!(m.value_of("neg"), Some("-20")); + /// # ; + /// ``` + /// [`Arg::allow_hyphen_values`]: crate::Arg::allow_hyphen_values() + #[inline] + pub fn allow_hyphen_values(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowHyphenValues) + } else { + self.unset_setting(AppSettings::AllowHyphenValues) + } + } + + /// Allows negative numbers to pass as values. + /// + /// This is similar to [`Command::allow_hyphen_values`] except that it only allows numbers, + /// all other undefined leading hyphens will fail to parse. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("myprog") + /// .allow_negative_numbers(true) + /// .arg(Arg::new("num")) + /// .try_get_matches_from(vec![ + /// "myprog", "-20" + /// ]); + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// assert_eq!(m.value_of("num").unwrap(), "-20"); + /// ``` + #[inline] + pub fn allow_negative_numbers(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowNegativeNumbers) + } else { + self.unset_setting(AppSettings::AllowNegativeNumbers) + } + } + + /// Specifies that the final positional argument is a "VarArg" and that `clap` should not + /// attempt to parse any further args. + /// + /// The values of the trailing positional argument will contain all args from itself on. + /// + /// **NOTE:** The final positional argument **must** have [`Arg::multiple_values(true)`] or the usage + /// string equivalent. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let m = Command::new("myprog") + /// .trailing_var_arg(true) + /// .arg(arg!(<cmd> ... "commands to run")) + /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]); + /// + /// let trail: Vec<&str> = m.values_of("cmd").unwrap().collect(); + /// assert_eq!(trail, ["arg1", "-r", "val1"]); + /// ``` + /// [`Arg::multiple_values(true)`]: crate::Arg::multiple_values() + pub fn trailing_var_arg(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::TrailingVarArg) + } else { + self.unset_setting(AppSettings::TrailingVarArg) + } + } + + /// Allows one to implement two styles of CLIs where positionals can be used out of order. + /// + /// The first example is a CLI where the second to last positional argument is optional, but + /// the final positional argument is required. Such as `$ prog [optional] <required>` where one + /// of the two following usages is allowed: + /// + /// * `$ prog [optional] <required>` + /// * `$ prog <required>` + /// + /// This would otherwise not be allowed. This is useful when `[optional]` has a default value. + /// + /// **Note:** when using this style of "missing positionals" the final positional *must* be + /// [required] if `--` will not be used to skip to the final positional argument. + /// + /// **Note:** This style also only allows a single positional argument to be "skipped" without + /// the use of `--`. To skip more than one, see the second example. + /// + /// The second example is when one wants to skip multiple optional positional arguments, and use + /// of the `--` operator is OK (but not required if all arguments will be specified anyways). + /// + /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where + /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments). + /// + /// With this setting the following invocations are posisble: + /// + /// * `$ prog foo bar baz1 baz2 baz3` + /// * `$ prog foo -- baz1 baz2 baz3` + /// * `$ prog -- baz1 baz2 baz3` + /// + /// # Examples + /// + /// Style number one from above: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_missing_positional(true) + /// .arg(Arg::new("arg1")) + /// .arg(Arg::new("arg2") + /// .required(true)) + /// .get_matches_from(vec![ + /// "prog", "other" + /// ]); + /// + /// assert_eq!(m.value_of("arg1"), None); + /// assert_eq!(m.value_of("arg2"), Some("other")); + /// ``` + /// + /// Now the same example, but using a default value for the first optional positional argument + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_missing_positional(true) + /// .arg(Arg::new("arg1") + /// .default_value("something")) + /// .arg(Arg::new("arg2") + /// .required(true)) + /// .get_matches_from(vec![ + /// "prog", "other" + /// ]); + /// + /// assert_eq!(m.value_of("arg1"), Some("something")); + /// assert_eq!(m.value_of("arg2"), Some("other")); + /// ``` + /// + /// Style number two from above: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_missing_positional(true) + /// .arg(Arg::new("foo")) + /// .arg(Arg::new("bar")) + /// .arg(Arg::new("baz").takes_value(true).multiple_values(true)) + /// .get_matches_from(vec![ + /// "prog", "foo", "bar", "baz1", "baz2", "baz3" + /// ]); + /// + /// assert_eq!(m.value_of("foo"), Some("foo")); + /// assert_eq!(m.value_of("bar"), Some("bar")); + /// assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]); + /// ``` + /// + /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_missing_positional(true) + /// .arg(Arg::new("foo")) + /// .arg(Arg::new("bar")) + /// .arg(Arg::new("baz").takes_value(true).multiple_values(true)) + /// .get_matches_from(vec![ + /// "prog", "--", "baz1", "baz2", "baz3" + /// ]); + /// + /// assert_eq!(m.value_of("foo"), None); + /// assert_eq!(m.value_of("bar"), None); + /// assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]); + /// ``` + /// + /// [required]: crate::Arg::required() + #[inline] + pub fn allow_missing_positional(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowMissingPositional) + } else { + self.unset_setting(AppSettings::AllowMissingPositional) + } + } +} + +/// # Subcommand-specific Settings +impl<'help> App<'help> { + /// Sets the short version of the subcommand flag without the preceding `-`. + /// + /// Allows the subcommand to be used as if it were an [`Arg::short`]. + /// + /// # Examples + /// + /// ``` + /// # use clap::{Command, Arg}; + /// let matches = Command::new("pacman") + /// .subcommand( + /// Command::new("sync").short_flag('S').arg( + /// Arg::new("search") + /// .short('s') + /// .long("search") + /// .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.is_present("search")); + /// ``` + /// [`Arg::short`]: Arg::short() + #[must_use] + pub fn short_flag(mut self, short: char) -> Self { + self.short_flag = Some(short); + self + } + + /// Sets the long version of the subcommand flag without the preceding `--`. + /// + /// Allows the subcommand to be used as if it were an [`Arg::long`]. + /// + /// **NOTE:** Any leading `-` characters will be stripped. + /// + /// # Examples + /// + /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading + /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however, + /// will *not* be stripped (i.e. `sync-file` is allowed). + /// + /// ``` + /// # use clap::{Command, Arg}; + /// let matches = Command::new("pacman") + /// .subcommand( + /// Command::new("sync").long_flag("sync").arg( + /// Arg::new("search") + /// .short('s') + /// .long("search") + /// .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.is_present("search")); + /// ``` + /// + /// [`Arg::long`]: Arg::long() + #[must_use] + pub fn long_flag(mut self, long: &'help str) -> Self { + #[cfg(feature = "unstable-v4")] + { + self.long_flag = Some(long); + } + #[cfg(not(feature = "unstable-v4"))] + { + self.long_flag = Some(long.trim_start_matches(|c| c == '-')); + } + self + } + + /// Sets a hidden alias to this subcommand. + /// + /// This allows the subcommand to be accessed via *either* the original name, or this given + /// alias. This is more efficient and easier than creating multiple hidden subcommands as one + /// only needs to check for the existence of this command, and not all aliased variants. + /// + /// **NOTE:** Aliases defined with this method are *hidden* from the help + /// message. If you're looking for aliases that will be displayed in the help + /// message, see [`Command::visible_alias`]. + /// + /// **NOTE:** When using aliases and checking for the existence of a + /// particular subcommand within an [`ArgMatches`] struct, one only needs to + /// search for the original name and not all aliases. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test") + /// .alias("do-stuff")) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::visible_alias`]: Command::visible_alias() + #[must_use] + pub fn alias<S: Into<&'help str>>(mut self, name: S) -> Self { + self.aliases.push((name.into(), false)); + self + } + + /// Add an alias, which functions as "hidden" short flag subcommand + /// + /// This will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").short_flag('t') + /// .short_flag_alias('d')) + /// .get_matches_from(vec!["myprog", "-d"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + #[must_use] + pub fn short_flag_alias(mut self, name: char) -> Self { + assert!(name != '-', "short alias name cannot be `-`"); + self.short_flag_aliases.push((name, false)); + self + } + + /// Add an alias, which functions as a "hidden" long flag subcommand. + /// + /// This will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").long_flag("test") + /// .long_flag_alias("testing")) + /// .get_matches_from(vec!["myprog", "--testing"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + #[must_use] + pub fn long_flag_alias(mut self, name: &'help str) -> Self { + self.long_flag_aliases.push((name, false)); + self + } + + /// Sets multiple hidden aliases to this subcommand. + /// + /// This allows the subcommand to be accessed via *either* the original name or any of the + /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands + /// as one only needs to check for the existence of this command and not all aliased variants. + /// + /// **NOTE:** Aliases defined with this method are *hidden* from the help + /// message. If looking for aliases that will be displayed in the help + /// message, see [`Command::visible_aliases`]. + /// + /// **NOTE:** When using aliases and checking for the existence of a + /// particular subcommand within an [`ArgMatches`] struct, one only needs to + /// search for the original name and not all aliases. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test") + /// .aliases(&["do-stuff", "do-tests", "tests"])) + /// .arg(Arg::new("input") + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec!["myprog", "do-tests"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::visible_aliases`]: Command::visible_aliases() + #[must_use] + pub fn aliases(mut self, names: &[&'help str]) -> Self { + self.aliases.extend(names.iter().map(|n| (*n, false))); + self + } + + /// Add aliases, which function as "hidden" short flag subcommands. + /// + /// These will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").short_flag('t') + /// .short_flag_aliases(&['a', 'b', 'c'])) + /// .arg(Arg::new("input") + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec!["myprog", "-a"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + #[must_use] + pub fn short_flag_aliases(mut self, names: &[char]) -> Self { + for s in names { + assert!(s != &'-', "short alias name cannot be `-`"); + self.short_flag_aliases.push((*s, false)); + } + self + } + + /// Add aliases, which function as "hidden" long flag subcommands. + /// + /// These will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").long_flag("test") + /// .long_flag_aliases(&["testing", "testall", "test_all"])) + /// .arg(Arg::new("input") + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec!["myprog", "--testing"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + #[must_use] + pub fn long_flag_aliases(mut self, names: &[&'help str]) -> Self { + for s in names { + self.long_flag_aliases.push((s, false)); + } + self + } + + /// Sets a visible alias to this subcommand. + /// + /// This allows the subcommand to be accessed via *either* the + /// original name or the given alias. This is more efficient and easier + /// than creating hidden subcommands as one only needs to check for + /// the existence of this command and not all aliased variants. + /// + /// **NOTE:** The alias defined with this method is *visible* from the help + /// message and displayed as if it were just another regular subcommand. If + /// looking for an alias that will not be displayed in the help message, see + /// [`Command::alias`]. + /// + /// **NOTE:** When using aliases and checking for the existence of a + /// particular subcommand within an [`ArgMatches`] struct, one only needs to + /// search for the original name and not all aliases. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test") + /// .visible_alias("do-stuff")) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::alias`]: Command::alias() + #[must_use] + pub fn visible_alias<S: Into<&'help str>>(mut self, name: S) -> Self { + self.aliases.push((name.into(), true)); + self + } + + /// Add an alias, which functions as "visible" short flag subcommand + /// + /// This will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// See also [`Command::short_flag_alias`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").short_flag('t') + /// .visible_short_flag_alias('d')) + /// .get_matches_from(vec!["myprog", "-d"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::short_flag_alias`]: Command::short_flag_alias() + #[must_use] + pub fn visible_short_flag_alias(mut self, name: char) -> Self { + assert!(name != '-', "short alias name cannot be `-`"); + self.short_flag_aliases.push((name, true)); + self + } + + /// Add an alias, which functions as a "visible" long flag subcommand. + /// + /// This will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// See also [`Command::long_flag_alias`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").long_flag("test") + /// .visible_long_flag_alias("testing")) + /// .get_matches_from(vec!["myprog", "--testing"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::long_flag_alias`]: Command::long_flag_alias() + #[must_use] + pub fn visible_long_flag_alias(mut self, name: &'help str) -> Self { + self.long_flag_aliases.push((name, true)); + self + } + + /// Sets multiple visible aliases to this subcommand. + /// + /// This allows the subcommand to be accessed via *either* the + /// original name or any of the given aliases. This is more efficient and easier + /// than creating multiple hidden subcommands as one only needs to check for + /// the existence of this command and not all aliased variants. + /// + /// **NOTE:** The alias defined with this method is *visible* from the help + /// message and displayed as if it were just another regular subcommand. If + /// looking for an alias that will not be displayed in the help message, see + /// [`Command::alias`]. + /// + /// **NOTE:** When using aliases, and checking for the existence of a + /// particular subcommand within an [`ArgMatches`] struct, one only needs to + /// search for the original name and not all aliases. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test") + /// .visible_aliases(&["do-stuff", "tests"])) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::alias`]: Command::alias() + #[must_use] + pub fn visible_aliases(mut self, names: &[&'help str]) -> Self { + self.aliases.extend(names.iter().map(|n| (*n, true))); + self + } + + /// Add aliases, which function as *visible* short flag subcommands. + /// + /// See [`Command::short_flag_aliases`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").short_flag('b') + /// .visible_short_flag_aliases(&['t'])) + /// .get_matches_from(vec!["myprog", "-t"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::short_flag_aliases`]: Command::short_flag_aliases() + #[must_use] + pub fn visible_short_flag_aliases(mut self, names: &[char]) -> Self { + for s in names { + assert!(s != &'-', "short alias name cannot be `-`"); + self.short_flag_aliases.push((*s, true)); + } + self + } + + /// Add aliases, which function as *visible* long flag subcommands. + /// + /// See [`Command::long_flag_aliases`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").long_flag("test") + /// .visible_long_flag_aliases(&["testing", "testall", "test_all"])) + /// .get_matches_from(vec!["myprog", "--testing"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`App::long_flag_aliases`]: Command::long_flag_aliases() + #[must_use] + pub fn visible_long_flag_aliases(mut self, names: &[&'help str]) -> Self { + for s in names { + self.long_flag_aliases.push((s, true)); + } + self + } + + /// Set the placement of this subcommand within the help. + /// + /// Subcommands with a lower value will be displayed first in the help message. Subcommands + /// with duplicate display orders will be displayed in alphabetical order. + /// + /// This is helpful when one would like to emphasize frequently used subcommands, or prioritize + /// those towards the top of the list. + /// + /// **NOTE:** The default is 999 for all subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, }; + /// let m = Command::new("cust-ord") + /// .subcommand(Command::new("alpha") // typically subcommands are grouped + /// // alphabetically by name. Subcommands + /// // without a display_order have a value of + /// // 999 and are displayed alphabetically with + /// // all other 999 subcommands + /// .about("Some help and text")) + /// .subcommand(Command::new("beta") + /// .display_order(1) // In order to force this subcommand to appear *first* + /// // all we have to do is give it a value lower than 999. + /// // Any other subcommands with a value of 1 will be displayed + /// // alphabetically with this one...then 2 values, then 3, etc. + /// .about("I should be first!")) + /// .get_matches_from(vec![ + /// "cust-ord", "--help" + /// ]); + /// ``` + /// + /// The above example displays the following help message + /// + /// ```text + /// cust-ord + /// + /// USAGE: + /// cust-ord [OPTIONS] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// + /// SUBCOMMANDS: + /// beta I should be first! + /// alpha Some help and text + /// ``` + #[inline] + #[must_use] + pub fn display_order(mut self, ord: usize) -> Self { + self.disp_ord = Some(ord); + self + } + + /// Specifies that this [`subcommand`] should be hidden from help messages + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand( + /// Command::new("test").hide(true) + /// ) + /// # ; + /// ``` + /// + /// [`subcommand`]: crate::Command::subcommand() + #[inline] + pub fn hide(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::Hidden) + } else { + self.unset_setting(AppSettings::Hidden) + } + } + + /// If no [`subcommand`] is present at runtime, error and exit gracefully. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let err = Command::new("myprog") + /// .subcommand_required(true) + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); + /// # ; + /// ``` + /// + /// [`subcommand`]: crate::Command::subcommand() + pub fn subcommand_required(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::SubcommandRequired) + } else { + self.unset_setting(AppSettings::SubcommandRequired) + } + } + + /// Assume unexpected positional arguments are a [`subcommand`]. + /// + /// Arguments will be stored in the `""` argument in the [`ArgMatches`] + /// + /// **NOTE:** Use this setting with caution, + /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand) + /// will **not** cause an error and instead be treated as a potential subcommand. + /// One should check for such cases manually and inform the user appropriately. + /// + /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with + /// `--`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_external_subcommands(true) + /// .get_matches_from(vec![ + /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" + /// ]); + /// + /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty + /// // string argument name + /// match m.subcommand() { + /// Some((external, ext_m)) => { + /// let ext_args: Vec<&str> = ext_m.values_of("").unwrap().collect(); + /// assert_eq!(external, "subcmd"); + /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + /// }, + /// _ => {}, + /// } + /// ``` + /// + /// [`subcommand`]: crate::Command::subcommand() + /// [`ArgMatches`]: crate::ArgMatches + /// [`ErrorKind::UnknownArgument`]: crate::ErrorKind::UnknownArgument + pub fn allow_external_subcommands(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowExternalSubcommands) + } else { + self.unset_setting(AppSettings::AllowExternalSubcommands) + } + } + + /// Specifies that external subcommands that are invalid UTF-8 should *not* be treated as an error. + /// + /// **NOTE:** Using external subcommand argument values with invalid UTF-8 requires using + /// [`ArgMatches::values_of_os`] or [`ArgMatches::values_of_lossy`] for those particular + /// arguments which may contain invalid UTF-8 values + /// + /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`] + /// + /// # Platform Specific + /// + /// Non Windows systems only + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::Command; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_invalid_utf8_for_external_subcommands(true) + /// .allow_external_subcommands(true) + /// .get_matches_from(vec![ + /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" + /// ]); + /// + /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty + /// // string argument name + /// match m.subcommand() { + /// Some((external, ext_m)) => { + /// let ext_args: Vec<&std::ffi::OsStr> = ext_m.values_of_os("").unwrap().collect(); + /// assert_eq!(external, "subcmd"); + /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + /// }, + /// _ => {}, + /// } + /// ``` + /// + /// [`ArgMatches::values_of_os`]: crate::ArgMatches::values_of_os() + /// [`ArgMatches::values_of_lossy`]: crate::ArgMatches::values_of_lossy() + /// [`subcommands`]: crate::Command::subcommand() + pub fn allow_invalid_utf8_for_external_subcommands(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands) + } else { + self.unset_setting(AppSettings::AllowInvalidUtf8ForExternalSubcommands) + } + } + + /// Specifies that use of an argument prevents the use of [`subcommands`]. + /// + /// By default `clap` allows arguments between subcommands such + /// as `<cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args]`. + /// + /// This setting disables that functionality and says that arguments can + /// only follow the *final* subcommand. For instance using this setting + /// makes only the following invocations possible: + /// + /// * `<cmd> <subcmd> <subsubcmd> [subsubcmd_args]` + /// * `<cmd> <subcmd> [subcmd_args]` + /// * `<cmd> [cmd_args]` + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// Command::new("myprog") + /// .args_conflicts_with_subcommands(true); + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::ArgsNegateSubcommands) + } else { + self.unset_setting(AppSettings::ArgsNegateSubcommands) + } + } + + /// Prevent subcommands from being consumed as an arguments value. + /// + /// By default, if an option taking multiple values is followed by a subcommand, the + /// subcommand will be parsed as another value. + /// + /// ```text + /// cmd --foo val1 val2 subcommand + /// --------- ---------- + /// values another value + /// ``` + /// + /// This setting instructs the parser to stop when encountering a subcommand instead of + /// greedily consuming arguments. + /// + /// ```text + /// cmd --foo val1 val2 subcommand + /// --------- ---------- + /// values subcommand + /// ``` + /// + /// **Note:** Make sure you apply it as `global_setting` if you want this setting + /// to be propagated to subcommands and sub-subcommands! + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg( + /// Arg::new("arg") + /// .long("arg") + /// .multiple_values(true) + /// .takes_value(true), + /// ); + /// + /// let matches = cmd + /// .clone() + /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) + /// .unwrap(); + /// assert_eq!( + /// matches.values_of("arg").unwrap().collect::<Vec<_>>(), + /// &["1", "2", "3", "sub"] + /// ); + /// assert!(matches.subcommand_matches("sub").is_none()); + /// + /// let matches = cmd + /// .subcommand_precedence_over_arg(true) + /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) + /// .unwrap(); + /// assert_eq!( + /// matches.values_of("arg").unwrap().collect::<Vec<_>>(), + /// &["1", "2", "3"] + /// ); + /// assert!(matches.subcommand_matches("sub").is_some()); + /// ``` + pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::SubcommandPrecedenceOverArg) + } else { + self.unset_setting(AppSettings::SubcommandPrecedenceOverArg) + } + } + + /// Allows [`subcommands`] to override all requirements of the parent command. + /// + /// For example, if you had a subcommand or top level application with a required argument + /// that is only required as long as there is no subcommand present, + /// using this setting would allow you to set those arguments to [`Arg::required(true)`] + /// and yet receive no error so long as the user uses a valid subcommand instead. + /// + /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements) + /// + /// # Examples + /// + /// This first example shows that it is an error to not use a required argument + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let err = Command::new("myprog") + /// .subcommand_negates_reqs(true) + /// .arg(Arg::new("opt").required(true)) + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog" + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// # ; + /// ``` + /// + /// This next example shows that it is no longer error to not use a required argument if a + /// valid subcommand is used. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let noerr = Command::new("myprog") + /// .subcommand_negates_reqs(true) + /// .arg(Arg::new("opt").required(true)) + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", "test" + /// ]); + /// assert!(noerr.is_ok()); + /// # ; + /// ``` + /// + /// [`Arg::required(true)`]: crate::Arg::required() + /// [`subcommands`]: crate::Command::subcommand() + pub fn subcommand_negates_reqs(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::SubcommandsNegateReqs) + } else { + self.unset_setting(AppSettings::SubcommandsNegateReqs) + } + } + + /// Multiple-personality program dispatched on the binary name (`argv[0]`) + /// + /// A "multicall" executable is a single executable + /// that contains a variety of applets, + /// and decides which applet to run based on the name of the file. + /// The executable can be called from different names by creating hard links + /// or symbolic links to it. + /// + /// This is desirable for: + /// - Easy distribution, a single binary that can install hardlinks to access the different + /// personalities. + /// - Minimal binary size by sharing common code (e.g. standard library, clap) + /// - Custom shells or REPLs where there isn't a single top-level command + /// + /// Setting `multicall` will cause + /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if + /// [`Command::no_binary_name`][App::no_binary_name] was set. + /// - Help and errors to report subcommands as if they were the top-level command + /// + /// When the subcommand is not present, there are several strategies you may employ, depending + /// on your needs: + /// - Let the error percolate up normally + /// - Print a specialized error message using the + /// [`Error::context`][crate::Error::context] + /// - Print the [help][App::write_help] but this might be ambiguous + /// - Disable `multicall` and re-parse it + /// - Disable `multicall` and re-parse it with a specific subcommand + /// + /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand + /// might report the same error. Enable + /// [`allow_external_subcommands`][App::allow_external_subcommands] if you want to specifically + /// get the unrecognized binary name. + /// + /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret + /// the command name in incompatible ways. + /// + /// **NOTE:** The multicall command cannot have arguments. + /// + /// **NOTE:** Applets are slightly semantically different from subcommands, + /// so it's recommended to use [`Command::subcommand_help_heading`] and + /// [`Command::subcommand_value_name`] to change the descriptive text as above. + /// + /// # Examples + /// + /// `hostname` is an example of a multicall executable. + /// Both `hostname` and `dnsdomainname` are provided by the same executable + /// and which behaviour to use is based on the executable file name. + /// + /// This is desirable when the executable has a primary purpose + /// but there is related functionality that would be convenient to provide + /// and implement it to be in the same executable. + /// + /// The name of the cmd is essentially unused + /// and may be the same as the name of a subcommand. + /// + /// The names of the immediate subcommands of the Command + /// are matched against the basename of the first argument, + /// which is conventionally the path of the executable. + /// + /// This does not allow the subcommand to be passed as the first non-path argument. + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let mut cmd = Command::new("hostname") + /// .multicall(true) + /// .subcommand(Command::new("hostname")) + /// .subcommand(Command::new("dnsdomainname")); + /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]); + /// assert!(m.is_err()); + /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]); + /// assert_eq!(m.subcommand_name(), Some("dnsdomainname")); + /// ``` + /// + /// Busybox is another common example of a multicall executable + /// with a subcommmand for each applet that can be run directly, + /// e.g. with the `cat` applet being run by running `busybox cat`, + /// or with `cat` as a link to the `busybox` binary. + /// + /// This is desirable when the launcher program has additional options + /// or it is useful to run the applet without installing a symlink + /// e.g. to test the applet without installing it + /// or there may already be a command of that name installed. + /// + /// To make an applet usable as both a multicall link and a subcommand + /// the subcommands must be defined both in the top-level Command + /// and as subcommands of the "main" applet. + /// + /// ```rust + /// # use clap::Command; + /// fn applet_commands() -> [Command<'static>; 2] { + /// [Command::new("true"), Command::new("false")] + /// } + /// let mut cmd = Command::new("busybox") + /// .multicall(true) + /// .subcommand( + /// Command::new("busybox") + /// .subcommand_value_name("APPLET") + /// .subcommand_help_heading("APPLETS") + /// .subcommands(applet_commands()), + /// ) + /// .subcommands(applet_commands()); + /// // When called from the executable's canonical name + /// // its applets can be matched as subcommands. + /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap(); + /// assert_eq!(m.subcommand_name(), Some("busybox")); + /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true")); + /// // When called from a link named after an applet that applet is matched. + /// let m = cmd.get_matches_from(&["/usr/bin/true"]); + /// assert_eq!(m.subcommand_name(), Some("true")); + /// ``` + /// + /// [`no_binary_name`]: crate::Command::no_binary_name + /// [`App::subcommand_value_name`]: crate::Command::subcommand_value_name + /// [`App::subcommand_help_heading`]: crate::Command::subcommand_help_heading + #[inline] + #[cfg(feature = "unstable-multicall")] + pub fn multicall(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::Multicall) + } else { + self.unset_setting(AppSettings::Multicall) + } + } + + /// Sets the value name used for subcommands when printing usage and help. + /// + /// By default, this is "SUBCOMMAND". + /// + /// See also [`Command::subcommand_help_heading`] + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("sub1")) + /// .print_help() + /// # ; + /// ``` + /// + /// will produce + /// + /// ```text + /// myprog + /// + /// USAGE: + /// myprog [SUBCOMMAND] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// + /// SUBCOMMANDS: + /// help Print this message or the help of the given subcommand(s) + /// sub1 + /// ``` + /// + /// but usage of `subcommand_value_name` + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("sub1")) + /// .subcommand_value_name("THING") + /// .print_help() + /// # ; + /// ``` + /// + /// will produce + /// + /// ```text + /// myprog + /// + /// USAGE: + /// myprog [THING] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// + /// SUBCOMMANDS: + /// help Print this message or the help of the given subcommand(s) + /// sub1 + /// ``` + #[must_use] + pub fn subcommand_value_name<S>(mut self, value_name: S) -> Self + where + S: Into<&'help str>, + { + self.subcommand_value_name = Some(value_name.into()); + self + } + + /// Sets the help heading used for subcommands when printing usage and help. + /// + /// By default, this is "SUBCOMMANDS". + /// + /// See also [`Command::subcommand_value_name`] + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("sub1")) + /// .print_help() + /// # ; + /// ``` + /// + /// will produce + /// + /// ```text + /// myprog + /// + /// USAGE: + /// myprog [SUBCOMMAND] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// + /// SUBCOMMANDS: + /// help Print this message or the help of the given subcommand(s) + /// sub1 + /// ``` + /// + /// but usage of `subcommand_help_heading` + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("sub1")) + /// .subcommand_help_heading("THINGS") + /// .print_help() + /// # ; + /// ``` + /// + /// will produce + /// + /// ```text + /// myprog + /// + /// USAGE: + /// myprog [SUBCOMMAND] + /// + /// OPTIONS: + /// -h, --help Print help information + /// -V, --version Print version information + /// + /// THINGS: + /// help Print this message or the help of the given subcommand(s) + /// sub1 + /// ``` + #[must_use] + pub fn subcommand_help_heading<T>(mut self, heading: T) -> Self + where + T: Into<&'help str>, + { + self.subcommand_heading = Some(heading.into()); + self + } +} + +/// # Reflection +impl<'help> App<'help> { + #[inline] + pub(crate) fn get_usage_name(&self) -> Option<&str> { + self.usage_name.as_deref() + } + + /// Get the name of the binary. + #[inline] + pub fn get_display_name(&self) -> Option<&str> { + self.display_name.as_deref() + } + + /// Get the name of the binary. + #[inline] + pub fn get_bin_name(&self) -> Option<&str> { + self.bin_name.as_deref() + } + + /// Set binary name. Uses `&mut self` instead of `self`. + pub fn set_bin_name<S: Into<String>>(&mut self, name: S) { + self.bin_name = Some(name.into()); + } + + /// Get the name of the cmd. + #[inline] + pub fn get_name(&self) -> &str { + &self.name + } + + /// Get the version of the cmd. + #[inline] + pub fn get_version(&self) -> Option<&'help str> { + self.version + } + + /// Get the long version of the cmd. + #[inline] + pub fn get_long_version(&self) -> Option<&'help str> { + self.long_version + } + + /// Get the authors of the cmd. + #[inline] + pub fn get_author(&self) -> Option<&'help str> { + self.author + } + + /// Get the short flag of the subcommand. + #[inline] + pub fn get_short_flag(&self) -> Option<char> { + self.short_flag + } + + /// Get the long flag of the subcommand. + #[inline] + pub fn get_long_flag(&self) -> Option<&'help str> { + self.long_flag + } + + /// Get the help message specified via [`Command::about`]. + /// + /// [`App::about`]: Command::about() + #[inline] + pub fn get_about(&self) -> Option<&'help str> { + self.about + } + + /// Get the help message specified via [`Command::long_about`]. + /// + /// [`App::long_about`]: Command::long_about() + #[inline] + pub fn get_long_about(&self) -> Option<&'help str> { + self.long_about + } + + /// Deprecated, replaced with [`Command::get_next_help_heading`] + #[inline] + #[deprecated(since = "3.1.0", note = "Replaced with `App::get_next_help_heading`")] + pub fn get_help_heading(&self) -> Option<&'help str> { + self.get_next_help_heading() + } + + /// Get the custom section heading specified via [`Command::help_heading`]. + /// + /// [`App::help_heading`]: Command::help_heading() + #[inline] + pub fn get_next_help_heading(&self) -> Option<&'help str> { + self.current_help_heading + } + + /// Iterate through the *visible* aliases for this subcommand. + #[inline] + pub fn get_visible_aliases(&self) -> impl Iterator<Item = &'help str> + '_ { + self.aliases.iter().filter(|(_, vis)| *vis).map(|a| a.0) + } + + /// Iterate through the *visible* short aliases for this subcommand. + #[inline] + pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ { + self.short_flag_aliases + .iter() + .filter(|(_, vis)| *vis) + .map(|a| a.0) + } + + /// Iterate through the *visible* long aliases for this subcommand. + #[inline] + pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &'help str> + '_ { + self.long_flag_aliases + .iter() + .filter(|(_, vis)| *vis) + .map(|a| a.0) + } + + /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden. + #[inline] + pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> + '_ { + self.aliases.iter().map(|a| a.0) + } + + /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden. + #[inline] + pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ { + self.short_flag_aliases.iter().map(|a| a.0) + } + + /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden. + #[inline] + pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &'help str> + '_ { + self.long_flag_aliases.iter().map(|a| a.0) + } + + /// Check if the given [`AppSettings`] variant is currently set on the `Command`. + /// + /// This checks both [local] and [global settings]. + /// + /// [local]: Command::setting() + /// [global settings]: Command::global_setting() + #[inline] + pub fn is_set(&self, s: AppSettings) -> bool { + self.settings.is_set(s) || self.g_settings.is_set(s) + } + + /// Should we color the output? + #[inline(never)] + pub fn get_color(&self) -> ColorChoice { + debug!("Command::color: Color setting..."); + + if cfg!(feature = "color") { + #[allow(deprecated)] + if self.is_set(AppSettings::ColorNever) { + debug!("Never"); + ColorChoice::Never + } else if self.is_set(AppSettings::ColorAlways) { + debug!("Always"); + ColorChoice::Always + } else { + debug!("Auto"); + ColorChoice::Auto + } + } else { + ColorChoice::Never + } + } + + /// Iterate through the set of subcommands, getting a reference to each. + #[inline] + pub fn get_subcommands(&self) -> impl Iterator<Item = &App<'help>> { + self.subcommands.iter() + } + + /// Iterate through the set of subcommands, getting a mutable reference to each. + #[inline] + pub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut App<'help>> { + self.subcommands.iter_mut() + } + + /// Returns `true` if this `Command` has subcommands. + #[inline] + pub fn has_subcommands(&self) -> bool { + !self.subcommands.is_empty() + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_subcommand_help_heading(&self) -> Option<&str> { + self.subcommand_heading + } + + /// Deprecated, replaced with [`App::get_subcommand_help_heading`] + #[inline] + #[deprecated( + since = "3.1.0", + note = "Replaced with `App::get_subcommand_help_heading`" + )] + pub fn get_subommand_help_heading(&self) -> Option<&str> { + self.get_subcommand_help_heading() + } + + /// Returns the subcommand value name. + #[inline] + pub fn get_subcommand_value_name(&self) -> Option<&str> { + self.subcommand_value_name + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_before_help(&self) -> Option<&str> { + self.before_help + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_before_long_help(&self) -> Option<&str> { + self.before_long_help + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_after_help(&self) -> Option<&str> { + self.after_help + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_after_long_help(&self) -> Option<&str> { + self.after_long_help + } + + /// Find subcommand such that its name or one of aliases equals `name`. + /// + /// This does not recurse through subcommands of subcommands. + #[inline] + pub fn find_subcommand<T>(&self, name: &T) -> Option<&App<'help>> + where + T: PartialEq<str> + ?Sized, + { + self.get_subcommands().find(|s| s.aliases_to(name)) + } + + /// Find subcommand such that its name or one of aliases equals `name`, returning + /// a mutable reference to the subcommand. + /// + /// This does not recurse through subcommands of subcommands. + #[inline] + pub fn find_subcommand_mut<T>(&mut self, name: &T) -> Option<&mut App<'help>> + where + T: PartialEq<str> + ?Sized, + { + self.get_subcommands_mut().find(|s| s.aliases_to(name)) + } + + /// Iterate through the set of groups. + #[inline] + pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup<'help>> { + self.groups.iter() + } + + /// Iterate through the set of arguments. + #[inline] + pub fn get_arguments(&self) -> impl Iterator<Item = &Arg<'help>> { + self.args.args() + } + + /// Iterate through the *positionals* arguments. + #[inline] + pub fn get_positionals(&self) -> impl Iterator<Item = &Arg<'help>> { + self.get_arguments().filter(|a| a.is_positional()) + } + + /// Iterate through the *options*. + pub fn get_opts(&self) -> impl Iterator<Item = &Arg<'help>> { + self.get_arguments() + .filter(|a| a.is_takes_value_set() && !a.is_positional()) + } + + /// Get a list of all arguments the given argument conflicts with. + /// + /// If the provided argument is declared as global, the conflicts will be determined + /// based on the propagation rules of global arguments. + /// + /// ### Panics + /// + /// If the given arg contains a conflict with an argument that is unknown to + /// this `Command`. + pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // FIXME: This could probably have been an iterator + { + if arg.is_global_set() { + self.get_global_arg_conflicts_with(arg) + } else { + arg.blacklist + .iter() + .map(|id| { + self.args.args().find(|arg| arg.id == *id).expect( + "Command::get_arg_conflicts_with: \ + The passed arg conflicts with an arg unknown to the cmd", + ) + }) + .collect() + } + } + + // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with. + // + // This behavior follows the propagation rules of global arguments. + // It is useful for finding conflicts for arguments declared as global. + // + // ### Panics + // + // If the given arg contains a conflict with an argument that is unknown to + // this `App`. + fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // FIXME: This could probably have been an iterator + { + arg.blacklist + .iter() + .map(|id| { + self.args + .args() + .chain( + self.get_subcommands_containing(arg) + .iter() + .flat_map(|x| x.args.args()), + ) + .find(|arg| arg.id == *id) + .expect( + "Command::get_arg_conflicts_with: \ + The passed arg conflicts with an arg unknown to the cmd", + ) + }) + .collect() + } + + // Get a list of subcommands which contain the provided Argument + // + // This command will only include subcommands in its list for which the subcommands + // parent also contains the Argument. + // + // This search follows the propagation rules of global arguments. + // It is useful to finding subcommands, that have inherited a global argument. + // + // **NOTE:** In this case only Sucommand_1 will be included + // Subcommand_1 (contains Arg) + // Subcommand_1.1 (doesn't contain Arg) + // Subcommand_1.1.1 (contains Arg) + // + fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&App<'help>> { + let mut vec = std::vec::Vec::new(); + for idx in 0..self.subcommands.len() { + if self.subcommands[idx].args.args().any(|ar| ar.id == arg.id) { + vec.push(&self.subcommands[idx]); + vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg)); + } + } + vec + } + + /// Report whether [`Command::no_binary_name`] is set + pub fn is_no_binary_name_set(&self) -> bool { + self.is_set(AppSettings::NoBinaryName) + } + + /// Report whether [`Command::ignore_errors`] is set + pub(crate) fn is_ignore_errors_set(&self) -> bool { + self.is_set(AppSettings::IgnoreErrors) + } + + /// Report whether [`Command::dont_delimit_trailing_values`] is set + pub fn is_dont_delimit_trailing_values_set(&self) -> bool { + self.is_set(AppSettings::DontDelimitTrailingValues) + } + + /// Report whether [`Command::disable_version_flag`] is set + pub fn is_disable_version_flag_set(&self) -> bool { + self.is_set(AppSettings::DisableVersionFlag) + } + + /// Report whether [`Command::propagate_version`] is set + pub fn is_propagate_version_set(&self) -> bool { + self.is_set(AppSettings::PropagateVersion) + } + + /// Report whether [`Command::next_line_help`] is set + pub fn is_next_line_help_set(&self) -> bool { + self.is_set(AppSettings::NextLineHelp) + } + + /// Report whether [`Command::disable_help_flag`] is set + pub fn is_disable_help_flag_set(&self) -> bool { + self.is_set(AppSettings::DisableHelpFlag) + } + + /// Report whether [`Command::disable_help_subcommand`] is set + pub fn is_disable_help_subcommand_set(&self) -> bool { + self.is_set(AppSettings::DisableHelpSubcommand) + } + + /// Report whether [`Command::disable_colored_help`] is set + pub fn is_disable_colored_help_set(&self) -> bool { + self.is_set(AppSettings::DisableColoredHelp) + } + + /// Report whether [`Command::help_expected`] is set + #[cfg(debug_assertions)] + pub(crate) fn is_help_expected_set(&self) -> bool { + self.is_set(AppSettings::HelpExpected) + } + + /// Report whether [`Command::dont_collapse_args_in_usage`] is set + pub fn is_dont_collapse_args_in_usage_set(&self) -> bool { + self.is_set(AppSettings::DontCollapseArgsInUsage) + } + + /// Report whether [`Command::infer_long_args`] is set + pub(crate) fn is_infer_long_args_set(&self) -> bool { + self.is_set(AppSettings::InferLongArgs) + } + + /// Report whether [`Command::infer_subcommands`] is set + pub(crate) fn is_infer_subcommands_set(&self) -> bool { + self.is_set(AppSettings::InferSubcommands) + } + + /// Report whether [`Command::arg_required_else_help`] is set + pub fn is_arg_required_else_help_set(&self) -> bool { + self.is_set(AppSettings::ArgRequiredElseHelp) + } + + /// Report whether [`Command::allow_hyphen_values`] is set + pub(crate) fn is_allow_hyphen_values_set(&self) -> bool { + self.is_set(AppSettings::AllowHyphenValues) + } + + /// Report whether [`Command::allow_negative_numbers`] is set + pub fn is_allow_negative_numbers_set(&self) -> bool { + self.is_set(AppSettings::AllowNegativeNumbers) + } + + /// Report whether [`Command::trailing_var_arg`] is set + pub fn is_trailing_var_arg_set(&self) -> bool { + self.is_set(AppSettings::TrailingVarArg) + } + + /// Report whether [`Command::allow_missing_positional`] is set + pub fn is_allow_missing_positional_set(&self) -> bool { + self.is_set(AppSettings::AllowMissingPositional) + } + + /// Report whether [`Command::hide`] is set + pub fn is_hide_set(&self) -> bool { + self.is_set(AppSettings::Hidden) + } + + /// Report whether [`Command::subcommand_required`] is set + pub fn is_subcommand_required_set(&self) -> bool { + self.is_set(AppSettings::SubcommandRequired) + } + + /// Report whether [`Command::allow_external_subcommands`] is set + pub fn is_allow_external_subcommands_set(&self) -> bool { + self.is_set(AppSettings::AllowExternalSubcommands) + } + + /// Report whether [`Command::allow_invalid_utf8_for_external_subcommands`] is set + pub fn is_allow_invalid_utf8_for_external_subcommands_set(&self) -> bool { + self.is_set(AppSettings::AllowInvalidUtf8ForExternalSubcommands) + } + + /// Report whether [`Command::args_conflicts_with_subcommands`] is set + pub fn is_args_conflicts_with_subcommands_set(&self) -> bool { + self.is_set(AppSettings::ArgsNegateSubcommands) + } + + /// Report whether [`Command::subcommand_precedence_over_arg`] is set + pub fn is_subcommand_precedence_over_arg_set(&self) -> bool { + self.is_set(AppSettings::SubcommandPrecedenceOverArg) + } + + /// Report whether [`Command::subcommand_negates_reqs`] is set + pub fn is_subcommand_negates_reqs_set(&self) -> bool { + self.is_set(AppSettings::SubcommandsNegateReqs) + } + + /// Report whether [`Command::multicall`] is set + #[cfg(feature = "unstable-multicall")] + pub fn is_multicall_set(&self) -> bool { + self.is_set(AppSettings::Multicall) + } + + #[cfg(not(feature = "unstable-multicall"))] + fn is_multicall_set(&self) -> bool { + false + } +} + +/// Deprecated +impl<'help> App<'help> { + /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? + #[cfg(feature = "yaml")] + #[deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" + )] + #[doc(hidden)] + pub fn from_yaml(y: &'help Yaml) -> Self { + #![allow(deprecated)] + let yaml_file_hash = y.as_hash().expect("YAML file must be a hash"); + // We WANT this to panic on error...so expect() is good. + let (mut a, yaml, err) = if let Some(name) = y["name"].as_str() { + (App::new(name), yaml_file_hash, "cmd".into()) + } else { + let (name_yaml, value_yaml) = yaml_file_hash + .iter() + .next() + .expect("There must be one subcommand in the YAML file"); + let name_str = name_yaml + .as_str() + .expect("Subcommand name must be a string"); + + ( + App::new(name_str), + value_yaml.as_hash().expect("Subcommand must be a hash"), + format!("subcommand '{}'", name_str), + ) + }; + + for (k, v) in yaml { + a = match k.as_str().expect("App fields must be strings") { + "version" => yaml_to_str!(a, v, version), + "long_version" => yaml_to_str!(a, v, long_version), + "author" => yaml_to_str!(a, v, author), + "bin_name" => yaml_to_str!(a, v, bin_name), + "about" => yaml_to_str!(a, v, about), + "long_about" => yaml_to_str!(a, v, long_about), + "before_help" => yaml_to_str!(a, v, before_help), + "after_help" => yaml_to_str!(a, v, after_help), + "template" => yaml_to_str!(a, v, help_template), + "usage" => yaml_to_str!(a, v, override_usage), + "help" => yaml_to_str!(a, v, override_help), + "help_message" => yaml_to_str!(a, v, help_message), + "version_message" => yaml_to_str!(a, v, version_message), + "alias" => yaml_to_str!(a, v, alias), + "aliases" => yaml_vec_or_str!(a, v, alias), + "visible_alias" => yaml_to_str!(a, v, visible_alias), + "visible_aliases" => yaml_vec_or_str!(a, v, visible_alias), + "display_order" => yaml_to_usize!(a, v, display_order), + "args" => { + if let Some(vec) = v.as_vec() { + for arg_yaml in vec { + a = a.arg(Arg::from_yaml(arg_yaml)); + } + } else { + panic!("Failed to convert YAML value {:?} to a vec", v); + } + a + } + "subcommands" => { + if let Some(vec) = v.as_vec() { + for sc_yaml in vec { + a = a.subcommand(App::from_yaml(sc_yaml)); + } + } else { + panic!("Failed to convert YAML value {:?} to a vec", v); + } + a + } + "groups" => { + if let Some(vec) = v.as_vec() { + for ag_yaml in vec { + a = a.group(ArgGroup::from(ag_yaml)); + } + } else { + panic!("Failed to convert YAML value {:?} to a vec", v); + } + a + } + "setting" | "settings" => { + yaml_to_setting!(a, v, setting, AppSettings, "AppSetting", err) + } + "global_setting" | "global_settings" => { + yaml_to_setting!(a, v, global_setting, AppSettings, "AppSetting", err) + } + _ => a, + } + } + + a + } + + /// Deprecated, replaced with [`Command::override_usage`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::override_usage`")] + #[doc(hidden)] + #[must_use] + pub fn usage<S: Into<&'help str>>(self, usage: S) -> Self { + self.override_usage(usage) + } + + /// Deprecated, replaced with [`Command::override_help`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::override_help`")] + #[doc(hidden)] + #[must_use] + pub fn help<S: Into<&'help str>>(self, help: S) -> Self { + self.override_help(help) + } + + /// Deprecated, replaced with [`Command::mut_arg`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`")] + #[doc(hidden)] + #[must_use] + pub fn help_short(self, c: char) -> Self { + self.mut_arg("help", |a| a.short(c)) + } + + /// Deprecated, replaced with [`Command::mut_arg`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`")] + #[doc(hidden)] + #[must_use] + pub fn version_short(self, c: char) -> Self { + self.mut_arg("version", |a| a.short(c)) + } + + /// Deprecated, replaced with [`Command::mut_arg`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`")] + #[doc(hidden)] + #[must_use] + pub fn help_message(self, s: impl Into<&'help str>) -> Self { + self.mut_arg("help", |a| a.help(s.into())) + } + + /// Deprecated, replaced with [`Command::mut_arg`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::mut_arg`")] + #[doc(hidden)] + #[must_use] + pub fn version_message(self, s: impl Into<&'help str>) -> Self { + self.mut_arg("version", |a| a.help(s.into())) + } + + /// Deprecated, replaced with [`Command::help_template`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::help_template`")] + #[doc(hidden)] + #[must_use] + pub fn template<S: Into<&'help str>>(self, s: S) -> Self { + self.help_template(s) + } + + /// Deprecated, replaced with [`Command::setting(a| b)`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::setting(a | b)`")] + #[doc(hidden)] + #[must_use] + pub fn settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.settings.insert((*s).into()); + } + self + } + + /// Deprecated, replaced with [`Command::unset_setting(a| b)`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::unset_setting(a | b)`")] + #[doc(hidden)] + #[must_use] + pub fn unset_settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.settings.remove((*s).into()); + } + self + } + + /// Deprecated, replaced with [`Command::global_setting(a| b)`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::global_setting(a | b)`")] + #[doc(hidden)] + #[must_use] + pub fn global_settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.settings.insert((*s).into()); + self.g_settings.insert((*s).into()); + } + self + } + + /// Deprecated, replaced with [`Command::term_width`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::term_width`")] + #[doc(hidden)] + #[must_use] + pub fn set_term_width(self, width: usize) -> Self { + self.term_width(width) + } + + /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!]. + #[deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!")] + #[doc(hidden)] + #[must_use] + pub fn arg_from_usage(self, usage: &'help str) -> Self { + #![allow(deprecated)] + self.arg(Arg::from_usage(usage)) + } + + /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!]. + #[deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!")] + #[doc(hidden)] + #[must_use] + pub fn args_from_usage(mut self, usage: &'help str) -> Self { + #![allow(deprecated)] + for line in usage.lines() { + let l = line.trim(); + if l.is_empty() { + continue; + } + self = self.arg(Arg::from_usage(l)); + } + self + } + + /// Deprecated, replaced with [`Command::render_version`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::render_version`")] + #[doc(hidden)] + pub fn write_version<W: io::Write>(&self, w: &mut W) -> ClapResult<()> { + write!(w, "{}", self.render_version()).map_err(From::from) + } + + /// Deprecated, replaced with [`Command::render_long_version`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::render_long_version`")] + #[doc(hidden)] + pub fn write_long_version<W: io::Write>(&self, w: &mut W) -> ClapResult<()> { + write!(w, "{}", self.render_long_version()).map_err(From::from) + } + + /// Deprecated, replaced with [`Command::try_get_matches`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::try_get_matches`")] + #[doc(hidden)] + pub fn get_matches_safe(self) -> ClapResult<ArgMatches> { + self.try_get_matches() + } + + /// Deprecated, replaced with [`Command::try_get_matches_from`] + #[deprecated(since = "3.0.0", note = "Replaced with `App::try_get_matches_from`")] + #[doc(hidden)] + pub fn get_matches_from_safe<I, T>(self, itr: I) -> ClapResult<ArgMatches> + where + I: IntoIterator<Item = T>, + T: Into<OsString> + Clone, + { + self.try_get_matches_from(itr) + } + + /// Deprecated, replaced with [`Command::try_get_matches_from_mut`] + #[deprecated( + since = "3.0.0", + note = "Replaced with `App::try_get_matches_from_mut`" + )] + #[doc(hidden)] + pub fn get_matches_from_safe_borrow<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches> + where + I: IntoIterator<Item = T>, + T: Into<OsString> + Clone, + { + self.try_get_matches_from_mut(itr) + } +} + +// Internally used only +impl<'help> App<'help> { + pub(crate) fn get_id(&self) -> Id { + self.id.clone() + } + + pub(crate) fn get_override_usage(&self) -> Option<&str> { + self.usage_str + } + + pub(crate) fn get_override_help(&self) -> Option<&str> { + self.help_str + } + + pub(crate) fn get_help_template(&self) -> Option<&str> { + self.template + } + + pub(crate) fn get_term_width(&self) -> Option<usize> { + self.term_w + } + + pub(crate) fn get_max_term_width(&self) -> Option<usize> { + self.max_w + } + + pub(crate) fn get_replacement(&self, key: &str) -> Option<&[&str]> { + self.replacers.get(key).copied() + } + + pub(crate) fn get_keymap(&self) -> &MKeyMap<'help> { + &self.args + } + + fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) { + global_arg_vec.extend( + self.args + .args() + .filter(|a| a.is_global_set()) + .map(|ga| ga.id.clone()), + ); + if let Some((id, matches)) = matches.subcommand() { + if let Some(used_sub) = self.find_subcommand(id) { + used_sub.get_used_global_args(matches, global_arg_vec); + } + } + } + + fn _do_parse( + &mut self, + raw_args: &mut clap_lex::RawArgs, + args_cursor: clap_lex::ArgCursor, + ) -> ClapResult<ArgMatches> { + debug!("Command::_do_parse"); + + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing in case we run into a subcommand + self._build_self(); + + let mut matcher = ArgMatcher::new(self); + + // do the real parsing + let mut parser = Parser::new(self); + if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) { + if self.is_set(AppSettings::IgnoreErrors) { + debug!("Command::_do_parse: ignoring error: {}", error); + } else { + return Err(error); + } + } + + let mut global_arg_vec = Default::default(); + self.get_used_global_args(&matcher, &mut global_arg_vec); + + matcher.propagate_globals(&global_arg_vec); + + Ok(matcher.into_inner()) + } + + #[doc(hidden)] + #[deprecated(since = "3.1.10", note = "Replaced with `Command::build`")] + pub fn _build_all(&mut self) { + self.build(); + } + + #[doc(hidden)] + #[deprecated(since = "3.1.10", note = "Replaced with `Command::build`")] + pub fn _build(&mut self) { + self._build_self() + } + + #[doc(hidden)] + #[deprecated(since = "3.1.13", note = "Replaced with `Command::build`")] + pub fn _build_bin_names(&mut self) { + self._build_bin_names_internal(); + } + + /// Prepare for introspecting on all included [`Command`]s + /// + /// Call this on the top-level [`Command`] when done building and before reading state for + /// cases like completions, custom help output, etc. + pub fn build(&mut self) { + self._build_recursive(); + self._build_bin_names_internal(); + } + + pub(crate) fn _build_recursive(&mut self) { + self._build_self(); + for subcmd in self.get_subcommands_mut() { + subcmd._build_recursive(); + } + } + + pub(crate) fn _build_self(&mut self) { + debug!("Command::_build: name={:?}", self.get_name()); + if !self.settings.is_set(AppSettings::Built) { + // Make sure all the globally set flags apply to us as well + self.settings = self.settings | self.g_settings; + + #[cfg(feature = "unstable-multicall")] + { + if self.is_multicall_set() { + self.settings.insert(AppSettings::SubcommandRequired.into()); + self.settings.insert(AppSettings::DisableHelpFlag.into()); + self.settings.insert(AppSettings::DisableVersionFlag.into()); + } + } + + self._propagate(); + self._check_help_and_version(); + self._propagate_global_args(); + self._derive_display_order(); + + let mut pos_counter = 1; + let self_override = self.is_set(AppSettings::AllArgsOverrideSelf); + let hide_pv = self.is_set(AppSettings::HidePossibleValues); + for a in self.args.args_mut() { + // Fill in the groups + for g in &a.groups { + if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) { + ag.args.push(a.id.clone()); + } else { + let mut ag = ArgGroup::with_id(g.clone()); + ag.args.push(a.id.clone()); + self.groups.push(ag); + } + } + + // Figure out implied settings + if a.is_last_set() { + // if an arg has `Last` set, we need to imply DontCollapseArgsInUsage so that args + // in the usage string don't get confused or left out. + self.settings.set(AppSettings::DontCollapseArgsInUsage); + } + if hide_pv && a.is_takes_value_set() { + a.settings.set(ArgSettings::HidePossibleValues); + } + if self_override { + let self_id = a.id.clone(); + a.overrides.push(self_id); + } + a._build(); + if a.is_positional() && a.index.is_none() { + a.index = Some(pos_counter); + pos_counter += 1; + } + } + + self.args._build(); + + #[cfg(debug_assertions)] + assert_app(self); + self.settings.set(AppSettings::Built); + } else { + debug!("Command::_build: already built"); + } + } + + pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> { + use std::fmt::Write; + + let mut mid_string = String::from(" "); + if !self.is_subcommand_negates_reqs_set() { + let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) + + for s in &reqs { + mid_string.push_str(s); + mid_string.push(' '); + } + } + let is_multicall_set = cfg!(feature = "unstable-multicall") && self.is_multicall_set(); + + let sc = self.subcommands.iter_mut().find(|s| s.name == name)?; + + // Display subcommand name, short and long in usage + let mut sc_names = sc.name.clone(); + let mut flag_subcmd = false; + if let Some(l) = sc.long_flag { + write!(sc_names, "|--{}", l).unwrap(); + flag_subcmd = true; + } + if let Some(s) = sc.short_flag { + write!(sc_names, "|-{}", s).unwrap(); + flag_subcmd = true; + } + + if flag_subcmd { + sc_names = format!("{{{}}}", sc_names); + } + + let usage_name = self + .bin_name + .as_ref() + .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names)) + .unwrap_or(sc_names); + sc.usage_name = Some(usage_name); + + // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by + // a space + let bin_name = format!( + "{}{}{}", + self.bin_name.as_ref().unwrap_or(&String::new()), + if self.bin_name.is_some() { " " } else { "" }, + &*sc.name + ); + debug!( + "Command::_build_subcommand Setting bin_name of {} to {:?}", + sc.name, bin_name + ); + sc.bin_name = Some(bin_name); + + if sc.display_name.is_none() { + let self_display_name = if is_multicall_set { + self.display_name.as_deref().unwrap_or("") + } else { + self.display_name.as_deref().unwrap_or(&self.name) + }; + let display_name = format!( + "{}{}{}", + self_display_name, + if !self_display_name.is_empty() { + "-" + } else { + "" + }, + &*sc.name + ); + debug!( + "Command::_build_subcommand Setting display_name of {} to {:?}", + sc.name, display_name + ); + sc.display_name = Some(display_name); + } + + // Ensure all args are built and ready to parse + sc._build_self(); + + Some(sc) + } + + fn _build_bin_names_internal(&mut self) { + debug!("Command::_build_bin_names"); + + if !self.is_set(AppSettings::BinNameBuilt) { + let mut mid_string = String::from(" "); + if !self.is_subcommand_negates_reqs_set() { + let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) + + for s in &reqs { + mid_string.push_str(s); + mid_string.push(' '); + } + } + let is_multicall_set = cfg!(feature = "unstable-multicall") && self.is_multicall_set(); + + let self_bin_name = if is_multicall_set { + self.bin_name.as_deref().unwrap_or("") + } else { + self.bin_name.as_deref().unwrap_or(&self.name) + } + .to_owned(); + + for mut sc in &mut self.subcommands { + debug!("Command::_build_bin_names:iter: bin_name set..."); + + if sc.usage_name.is_none() { + use std::fmt::Write; + // Display subcommand name, short and long in usage + let mut sc_names = sc.name.clone(); + let mut flag_subcmd = false; + if let Some(l) = sc.long_flag { + write!(sc_names, "|--{}", l).unwrap(); + flag_subcmd = true; + } + if let Some(s) = sc.short_flag { + write!(sc_names, "|-{}", s).unwrap(); + flag_subcmd = true; + } + + if flag_subcmd { + sc_names = format!("{{{}}}", sc_names); + } + + let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names); + debug!( + "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}", + sc.name, usage_name + ); + sc.usage_name = Some(usage_name); + } else { + debug!( + "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})", + sc.name, sc.usage_name + ); + } + + if sc.bin_name.is_none() { + let bin_name = format!( + "{}{}{}", + self_bin_name, + if !self_bin_name.is_empty() { " " } else { "" }, + &*sc.name + ); + debug!( + "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}", + sc.name, bin_name + ); + sc.bin_name = Some(bin_name); + } else { + debug!( + "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})", + sc.name, sc.bin_name + ); + } + + if sc.display_name.is_none() { + let self_display_name = if is_multicall_set { + self.display_name.as_deref().unwrap_or("") + } else { + self.display_name.as_deref().unwrap_or(&self.name) + }; + let display_name = format!( + "{}{}{}", + self_display_name, + if !self_display_name.is_empty() { + "-" + } else { + "" + }, + &*sc.name + ); + debug!( + "Command::_build_bin_names:iter: Setting display_name of {} to {:?}", + sc.name, display_name + ); + sc.display_name = Some(display_name); + } else { + debug!( + "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})", + sc.name, sc.display_name + ); + } + + sc._build_bin_names_internal(); + } + self.set(AppSettings::BinNameBuilt); + } else { + debug!("Command::_build_bin_names: already built"); + } + } + + pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) { + if self.is_set(AppSettings::HelpExpected) || help_required_globally { + let args_missing_help: Vec<String> = self + .args + .args() + .filter(|arg| arg.help.is_none() && arg.long_help.is_none()) + .map(|arg| String::from(arg.name)) + .collect(); + + assert!(args_missing_help.is_empty(), + "AppSettings::HelpExpected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}", + self.name, + args_missing_help.join(", ") + ); + } + + for sub_app in &self.subcommands { + sub_app._panic_on_missing_help(help_required_globally); + } + } + + #[cfg(debug_assertions)] + pub(crate) fn two_args_of<F>(&self, condition: F) -> Option<(&Arg<'help>, &Arg<'help>)> + where + F: Fn(&Arg) -> bool, + { + two_elements_of(self.args.args().filter(|a: &&Arg| condition(a))) + } + + // just in case + #[allow(unused)] + fn two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)> + where + F: Fn(&ArgGroup) -> bool, + { + two_elements_of(self.groups.iter().filter(|a| condition(a))) + } + + /// Propagate global args + pub(crate) fn _propagate_global_args(&mut self) { + debug!("Command::_propagate_global_args:{}", self.name); + + for sc in &mut self.subcommands { + for a in self.args.args().filter(|a| a.is_global_set()) { + let mut propagate = false; + let is_generated = matches!( + a.provider, + ArgProvider::Generated | ArgProvider::GeneratedMutated + ); + + // Remove generated help and version args in the subcommand + // + // Don't remove if those args are further mutated + if is_generated { + let generated_pos = sc + .args + .args() + .position(|x| x.id == a.id && x.provider == ArgProvider::Generated); + + if let Some(index) = generated_pos { + sc.args.remove(index); + propagate = true; + } + } + + if propagate || sc.find(&a.id).is_none() { + sc.args.push(a.clone()); + } + } + } + } + + /// Propagate settings + pub(crate) fn _propagate(&mut self) { + debug!("Command::_propagate:{}", self.name); + let mut subcommands = std::mem::take(&mut self.subcommands); + for sc in &mut subcommands { + self._propagate_subcommand(sc); + } + self.subcommands = subcommands; + } + + fn _propagate_subcommand(&self, sc: &mut Self) { + // We have to create a new scope in order to tell rustc the borrow of `sc` is + // done and to recursively call this method + { + if self.settings.is_set(AppSettings::PropagateVersion) { + if sc.version.is_none() && self.version.is_some() { + sc.version = Some(self.version.unwrap()); + } + if sc.long_version.is_none() && self.long_version.is_some() { + sc.long_version = Some(self.long_version.unwrap()); + } + } + + sc.settings = sc.settings | self.g_settings; + sc.g_settings = sc.g_settings | self.g_settings; + sc.term_w = self.term_w; + sc.max_w = self.max_w; + } + } + + #[allow(clippy::blocks_in_if_conditions)] + pub(crate) fn _check_help_and_version(&mut self) { + debug!("Command::_check_help_and_version: {}", self.name); + + if self.is_set(AppSettings::DisableHelpFlag) + || self.args.args().any(|x| { + x.provider == ArgProvider::User + && (x.long == Some("help") || x.id == Id::help_hash()) + }) + || self + .subcommands + .iter() + .any(|sc| sc.long_flag == Some("help")) + { + debug!("Command::_check_help_and_version: Removing generated help"); + + let generated_help_pos = self + .args + .args() + .position(|x| x.id == Id::help_hash() && x.provider == ArgProvider::Generated); + + if let Some(index) = generated_help_pos { + self.args.remove(index); + } + } else { + let help = self + .args + .args() + .find(|x| x.id == Id::help_hash()) + .expect(INTERNAL_ERROR_MSG); + assert_ne!(help.provider, ArgProvider::User); + + if help.short.is_some() { + if help.short == Some('h') { + if let Some(other_arg) = self + .args + .args() + .find(|x| x.id != Id::help_hash() && x.short == Some('h')) + { + panic!( + "`help`s `-h` conflicts with `{}`. + +To change `help`s short, call `cmd.arg(Arg::new(\"help\")...)`.", + other_arg.name + ); + } + } + } else if !(self.args.args().any(|x| x.short == Some('h')) + || self.subcommands.iter().any(|sc| sc.short_flag == Some('h'))) + { + let help = self + .args + .args_mut() + .find(|x| x.id == Id::help_hash()) + .expect(INTERNAL_ERROR_MSG); + help.short = Some('h'); + } else { + debug!("Command::_check_help_and_version: Removing `-h` from help"); + } + } + + // Determine if we should remove the generated --version flag + // + // Note that if only mut_arg() was used, the first expression will evaluate to `true` + // however inside the condition block, we only check for Generated args, not + // GeneratedMutated args, so the `mut_arg("version", ..) will be skipped and fall through + // to the following condition below (Adding the short `-V`) + if self.settings.is_set(AppSettings::DisableVersionFlag) + || (self.version.is_none() && self.long_version.is_none()) + || self.args.args().any(|x| { + x.provider == ArgProvider::User + && (x.long == Some("version") || x.id == Id::version_hash()) + }) + || self + .subcommands + .iter() + .any(|sc| sc.long_flag == Some("version")) + { + debug!("Command::_check_help_and_version: Removing generated version"); + + // This is the check mentioned above that only checks for Generated, not + // GeneratedMutated args by design. + let generated_version_pos = self + .args + .args() + .position(|x| x.id == Id::version_hash() && x.provider == ArgProvider::Generated); + + if let Some(index) = generated_version_pos { + self.args.remove(index); + } + } + + // If we still have a generated --version flag, determine if we can apply the short `-V` + if self.args.args().any(|x| { + x.id == Id::version_hash() + && matches!( + x.provider, + ArgProvider::Generated | ArgProvider::GeneratedMutated + ) + }) { + let other_arg_has_short = self.args.args().any(|x| x.short == Some('V')); + let version = self + .args + .args_mut() + .find(|x| x.id == Id::version_hash()) + .expect(INTERNAL_ERROR_MSG); + + if !(version.short.is_some() + || other_arg_has_short + || self.subcommands.iter().any(|sc| sc.short_flag == Some('V'))) + { + version.short = Some('V'); + } + } + + if !self.is_set(AppSettings::DisableHelpSubcommand) + && self.has_subcommands() + && !self.subcommands.iter().any(|s| s.id == Id::help_hash()) + { + debug!("Command::_check_help_and_version: Building help subcommand"); + let mut help_subcmd = App::new("help") + .about("Print this message or the help of the given subcommand(s)") + .arg( + Arg::new("subcommand") + .index(1) + .takes_value(true) + .multiple_occurrences(true) + .value_name("SUBCOMMAND") + .help("The subcommand whose help message to display"), + ); + self._propagate_subcommand(&mut help_subcmd); + + // The parser acts like this is set, so let's set it so we don't falsely + // advertise it to the user + help_subcmd.version = None; + help_subcmd.long_version = None; + help_subcmd = help_subcmd + .setting(AppSettings::DisableHelpFlag) + .unset_global_setting(AppSettings::PropagateVersion); + + self.subcommands.push(help_subcmd); + } + } + + pub(crate) fn _derive_display_order(&mut self) { + debug!("Command::_derive_display_order:{}", self.name); + + if self.settings.is_set(AppSettings::DeriveDisplayOrder) { + for a in self + .args + .args_mut() + .filter(|a| !a.is_positional()) + .filter(|a| a.provider != ArgProvider::Generated) + { + a.disp_ord.make_explicit(); + } + for (i, sc) in &mut self.subcommands.iter_mut().enumerate() { + sc.disp_ord.get_or_insert(i); + } + } + for sc in &mut self.subcommands { + sc._derive_display_order(); + } + } + + pub(crate) fn _render_version(&self, use_long: bool) -> String { + debug!("Command::_render_version"); + + let ver = if use_long { + self.long_version.or(self.version).unwrap_or("") + } else { + self.version.or(self.long_version).unwrap_or("") + }; + if let Some(bn) = self.bin_name.as_ref() { + if bn.contains(' ') { + // In case we're dealing with subcommands i.e. git mv is translated to git-mv + format!("{} {}\n", bn.replace(' ', "-"), ver) + } else { + format!("{} {}\n", &self.name[..], ver) + } + } else { + format!("{} {}\n", &self.name[..], ver) + } + } + + pub(crate) fn format_group(&self, g: &Id) -> String { + let g_string = self + .unroll_args_in_group(g) + .iter() + .filter_map(|x| self.find(x)) + .map(|x| { + if x.is_positional() { + // Print val_name for positional arguments. e.g. <file_name> + x.name_no_brackets().to_string() + } else { + // Print usage string for flags arguments, e.g. <--help> + x.to_string() + } + }) + .collect::<Vec<_>>() + .join("|"); + format!("<{}>", &*g_string) + } +} + +/// A workaround: +/// <https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999> +pub(crate) trait Captures<'a> {} +impl<'a, T> Captures<'a> for T {} + +// Internal Query Methods +impl<'help> App<'help> { + /// Iterate through the *flags* & *options* arguments. + pub(crate) fn get_non_positionals(&self) -> impl Iterator<Item = &Arg<'help>> { + self.get_arguments().filter(|a| !a.is_positional()) + } + + /// Iterate through the *positionals* that don't have custom heading. + pub(crate) fn get_positionals_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>> { + self.get_positionals() + .filter(|a| a.get_help_heading().is_none()) + } + + /// Iterate through the *flags* & *options* that don't have custom heading. + pub(crate) fn get_non_positionals_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>> { + self.get_non_positionals() + .filter(|a| a.get_help_heading().is_none()) + } + + pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg<'help>> { + self.args.args().find(|a| a.id == *arg_id) + } + + #[inline] + pub(crate) fn contains_short(&self, s: char) -> bool { + assert!( + self.is_set(AppSettings::Built), + "If App::_build hasn't been called, manually search through Arg shorts" + ); + + self.args.contains(s) + } + + #[inline] + pub(crate) fn set(&mut self, s: AppSettings) { + self.settings.set(s) + } + + #[inline] + pub(crate) fn has_args(&self) -> bool { + !self.args.is_empty() + } + + pub(crate) fn has_positionals(&self) -> bool { + self.args.keys().any(|x| x.is_position()) + } + + pub(crate) fn has_visible_subcommands(&self) -> bool { + self.subcommands + .iter() + .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden)) + } + + /// Check if this subcommand can be referred to as `name`. In other words, + /// check if `name` is the name of this subcommand or is one of its aliases. + #[inline] + pub(crate) fn aliases_to<T>(&self, name: &T) -> bool + where + T: PartialEq<str> + ?Sized, + { + *name == *self.get_name() || self.get_all_aliases().any(|alias| *name == *alias) + } + + /// Check if this subcommand can be referred to as `name`. In other words, + /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases. + #[inline] + pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool { + Some(flag) == self.short_flag + || self.get_all_short_flag_aliases().any(|alias| flag == alias) + } + + /// Check if this subcommand can be referred to as `name`. In other words, + /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases. + #[inline] + pub(crate) fn long_flag_aliases_to<T>(&self, flag: &T) -> bool + where + T: PartialEq<str> + ?Sized, + { + match self.long_flag { + Some(long_flag) => { + flag == long_flag || self.get_all_long_flag_aliases().any(|alias| flag == alias) + } + None => self.get_all_long_flag_aliases().any(|alias| flag == alias), + } + } + + #[cfg(debug_assertions)] + pub(crate) fn id_exists(&self, id: &Id) -> bool { + self.args.args().any(|x| x.id == *id) || self.groups.iter().any(|x| x.id == *id) + } + + /// Iterate through the groups this arg is member of. + pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a { + debug!("Command::groups_for_arg: id={:?}", arg); + let arg = arg.clone(); + self.groups + .iter() + .filter(move |grp| grp.args.iter().any(|a| a == &arg)) + .map(|grp| grp.id.clone()) + } + + pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup<'help>> { + self.groups.iter().find(|g| g.id == *group_id) + } + + /// Iterate through all the names of all subcommands (not recursively), including aliases. + /// Used for suggestions. + pub(crate) fn all_subcommand_names(&self) -> impl Iterator<Item = &str> + Captures<'help> { + self.get_subcommands().flat_map(|sc| { + let name = sc.get_name(); + let aliases = sc.get_all_aliases(); + std::iter::once(name).chain(aliases) + }) + } + + pub(crate) fn required_graph(&self) -> ChildGraph<Id> { + let mut reqs = ChildGraph::with_capacity(5); + for a in self.args.args().filter(|a| a.is_required_set()) { + reqs.insert(a.id.clone()); + } + for group in &self.groups { + if group.required { + let idx = reqs.insert(group.id.clone()); + for a in &group.requires { + reqs.insert_child(idx, a.clone()); + } + } + } + + reqs + } + + pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec<Id> { + debug!("Command::unroll_args_in_group: group={:?}", group); + let mut g_vec = vec![group]; + let mut args = vec![]; + + while let Some(g) = g_vec.pop() { + for n in self + .groups + .iter() + .find(|grp| grp.id == *g) + .expect(INTERNAL_ERROR_MSG) + .args + .iter() + { + debug!("Command::unroll_args_in_group:iter: entity={:?}", n); + if !args.contains(n) { + if self.find(n).is_some() { + debug!("Command::unroll_args_in_group:iter: this is an arg"); + args.push(n.clone()) + } else { + debug!("Command::unroll_args_in_group:iter: this is a group"); + g_vec.push(n); + } + } + } + } + + args + } + + pub(crate) fn unroll_arg_requires<F>(&self, func: F, arg: &Id) -> Vec<Id> + where + F: Fn(&(ArgPredicate<'_>, Id)) -> Option<Id>, + { + let mut processed = vec![]; + let mut r_vec = vec![arg]; + let mut args = vec![]; + + while let Some(a) = r_vec.pop() { + if processed.contains(&a) { + continue; + } + + processed.push(a); + + if let Some(arg) = self.find(a) { + for r in arg.requires.iter().filter_map(&func) { + if let Some(req) = self.find(&r) { + if !req.requires.is_empty() { + r_vec.push(&req.id) + } + } + args.push(r); + } + } + } + + args + } + + /// Find a flag subcommand name by short flag or an alias + pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> { + self.get_subcommands() + .find(|sc| sc.short_flag_aliases_to(c)) + .map(|sc| sc.get_name()) + } + + /// Find a flag subcommand name by long flag or an alias + pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> { + self.get_subcommands() + .find(|sc| sc.long_flag_aliases_to(long)) + .map(|sc| sc.get_name()) + } + + pub(crate) fn get_display_order(&self) -> usize { + self.disp_ord.unwrap_or(999) + } + + pub(crate) fn write_help_err( + &self, + mut use_long: bool, + stream: Stream, + ) -> ClapResult<Colorizer> { + debug!( + "Parser::write_help_err: use_long={:?}, stream={:?}", + use_long && self.use_long_help(), + stream + ); + + use_long = use_long && self.use_long_help(); + let usage = Usage::new(self); + + let mut c = Colorizer::new(stream, self.color_help()); + Help::new(HelpWriter::Buffer(&mut c), self, &usage, use_long).write_help()?; + Ok(c) + } + + pub(crate) fn use_long_help(&self) -> bool { + debug!("Command::use_long_help"); + // In this case, both must be checked. This allows the retention of + // original formatting, but also ensures that the actual -h or --help + // specified by the user is sent through. If hide_short_help is not included, + // then items specified with hidden_short_help will also be hidden. + let should_long = |v: &Arg| { + v.long_help.is_some() + || v.is_hide_long_help_set() + || v.is_hide_short_help_set() + || cfg!(feature = "unstable-v4") + && v.possible_vals.iter().any(PossibleValue::should_show_help) + }; + + // Subcommands aren't checked because we prefer short help for them, deferring to + // `cmd subcmd --help` for more. + self.get_long_about().is_some() + || self.get_before_long_help().is_some() + || self.get_after_long_help().is_some() + || self.get_arguments().any(should_long) + } + + // Should we color the help? + pub(crate) fn color_help(&self) -> ColorChoice { + #[cfg(feature = "color")] + if self.is_disable_colored_help_set() { + return ColorChoice::Never; + } + + self.get_color() + } +} + +impl<'help> Default for App<'help> { + fn default() -> Self { + Self { + id: Default::default(), + name: Default::default(), + long_flag: Default::default(), + short_flag: Default::default(), + display_name: Default::default(), + bin_name: Default::default(), + author: Default::default(), + version: Default::default(), + long_version: Default::default(), + about: Default::default(), + long_about: Default::default(), + before_help: Default::default(), + before_long_help: Default::default(), + after_help: Default::default(), + after_long_help: Default::default(), + aliases: Default::default(), + short_flag_aliases: Default::default(), + long_flag_aliases: Default::default(), + usage_str: Default::default(), + usage_name: Default::default(), + help_str: Default::default(), + disp_ord: Default::default(), + term_w: Default::default(), + max_w: Default::default(), + template: Default::default(), + settings: Default::default(), + g_settings: Default::default(), + args: Default::default(), + subcommands: Default::default(), + replacers: Default::default(), + groups: Default::default(), + current_help_heading: Default::default(), + current_disp_ord: Some(0), + subcommand_value_name: Default::default(), + subcommand_heading: Default::default(), + } + } +} + +impl<'help> Index<&'_ Id> for App<'help> { + type Output = Arg<'help>; + + fn index(&self, key: &Id) -> &Self::Output { + self.find(key).expect(INTERNAL_ERROR_MSG) + } +} + +impl fmt::Display for App<'_> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.name) + } +} + +fn two_elements_of<I, T>(mut iter: I) -> Option<(T, T)> +where + I: Iterator<Item = T>, +{ + let first = iter.next(); + let second = iter.next(); + + match (first, second) { + (Some(first), Some(second)) => Some((first, second)), + _ => None, + } +} diff --git a/third_party/rust/clap/src/build/debug_asserts.rs b/third_party/rust/clap/src/build/debug_asserts.rs new file mode 100644 index 0000000000..7b470d8431 --- /dev/null +++ b/third_party/rust/clap/src/build/debug_asserts.rs @@ -0,0 +1,815 @@ +use std::cmp::Ordering; + +use clap_lex::RawOsStr; + +use crate::build::arg::ArgProvider; +use crate::mkeymap::KeyType; +use crate::util::Id; +use crate::{AppSettings, 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 has_mutated_version = cmd + .get_arguments() + .any(|x| x.id == Id::version_hash() && x.provider == ArgProvider::GeneratedMutated); + + if has_mutated_version { + assert!(cmd.is_set(AppSettings::NoAutoVersion), + "Command {}: Used Command::mut_arg(\"version\", ..) without providing Command::version, Command::long_version or using AppSettings::NoAutoVersion" + ,cmd.get_name() + ); + } + } + + for sc in cmd.get_subcommands() { + if let Some(s) = sc.get_short_flag().as_ref() { + short_flags.push(Flag::Command(format!("-{}", s), sc.get_name())); + } + + for short_alias in sc.get_all_short_flag_aliases() { + short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name())); + } + + if let Some(l) = sc.get_long_flag().as_ref() { + #[cfg(feature = "unstable-v4")] + { + assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l); + } + long_flags.push(Flag::Command(format!("--{}", l), sc.get_name())); + } + + for long_alias in sc.get_all_long_flag_aliases() { + long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name())); + } + } + + for arg in cmd.get_arguments() { + assert_arg(arg); + + #[cfg(feature = "unstable-multicall")] + { + assert!( + !cmd.is_multicall_set(), + "Command {}: Arguments like {} cannot be set on a multicall command", + cmd.get_name(), + arg.name + ); + } + + if let Some(s) = arg.short.as_ref() { + short_flags.push(Flag::Arg(format!("-{}", s), &*arg.name)); + } + + for (short_alias, _) in &arg.short_aliases { + short_flags.push(Flag::Arg(format!("-{}", short_alias), arg.name)); + } + + if let Some(l) = arg.long.as_ref() { + #[cfg(feature = "unstable-v4")] + { + assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.name, l); + } + long_flags.push(Flag::Arg(format!("--{}", l), &*arg.name)); + } + + for (long_alias, _) in &arg.aliases { + long_flags.push(Flag::Arg(format!("--{}", long_alias), arg.name)); + } + + // Name conflicts + assert!( + cmd.two_args_of(|x| x.id == arg.id).is_none(), + "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group", + cmd.get_name(), + arg.name, + ); + + // Long conflicts + if let Some(l) = arg.long { + if let Some((first, second)) = cmd.two_args_of(|x| x.long == Some(l)) { + panic!( + "Command {}: Long option names must be unique for each argument, \ + but '--{}' is in use by both '{}' and '{}'", + cmd.get_name(), + l, + first.name, + second.name + ) + } + } + + // Short conflicts + if let Some(s) = arg.short { + if let Some((first, second)) = cmd.two_args_of(|x| x.short == Some(s)) { + panic!( + "Command {}: Short option names must be unique for each argument, \ + but '-{}' is in use by both '{}' and '{}'", + cmd.get_name(), + s, + first.name, + second.name + ) + } + } + + // Index conflicts + if let Some(idx) = arg.index { + if let Some((first, second)) = + cmd.two_args_of(|x| x.is_positional() && x.index == Some(idx)) + { + panic!( + "Command {}: Argument '{}' has the same index as '{}' \ + and they are both positional arguments\n\n\t \ + Use Arg::multiple_values(true) to allow one \ + positional argument to take multiple values", + cmd.get_name(), + first.name, + second.name + ) + } + } + + // requires, r_if, r_unless + for req in &arg.requires { + assert!( + cmd.id_exists(&req.1), + "Command {}: Argument or group '{:?}' specified in 'requires*' for '{}' does not exist", + cmd.get_name(), + req.1, + arg.name, + ); + } + + for req in &arg.r_ifs { + #[cfg(feature = "unstable-v4")] + { + assert!( + !arg.is_required_set(), + "Argument {}: `required` conflicts with `required_if_eq*`", + arg.name + ); + } + assert!( + cmd.id_exists(&req.0), + "Command {}: Argument or group '{:?}' specified in 'required_if_eq*' for '{}' does not exist", + cmd.get_name(), + req.0, + arg.name + ); + } + + for req in &arg.r_ifs_all { + #[cfg(feature = "unstable-v4")] + { + assert!( + !arg.is_required_set(), + "Argument {}: `required` conflicts with `required_if_eq_all`", + arg.name + ); + } + assert!( + cmd.id_exists(&req.0), + "Command {}: Argument or group '{:?}' specified in 'required_if_eq_all' for '{}' does not exist", + cmd.get_name(), + req.0, + arg.name + ); + } + + for req in &arg.r_unless { + #[cfg(feature = "unstable-v4")] + { + assert!( + !arg.is_required_set(), + "Argument {}: `required` conflicts with `required_unless*`", + arg.name + ); + } + assert!( + cmd.id_exists(req), + "Command {}: Argument or group '{:?}' specified in 'required_unless*' for '{}' does not exist", + cmd.get_name(), + req, + arg.name, + ); + } + + for req in &arg.r_unless_all { + #[cfg(feature = "unstable-v4")] + { + assert!( + !arg.is_required_set(), + "Argument {}: `required` conflicts with `required_unless*`", + arg.name + ); + } + assert!( + cmd.id_exists(req), + "Command {}: Argument or group '{:?}' specified in 'required_unless*' for '{}' does not exist", + cmd.get_name(), + req, + arg.name, + ); + } + + // blacklist + for req in &arg.blacklist { + assert!( + cmd.id_exists(req), + "Command {}: Argument or group '{:?}' specified in 'conflicts_with*' for '{}' does not exist", + cmd.get_name(), + req, + arg.name, + ); + } + + if arg.is_last_set() { + assert!( + arg.long.is_none(), + "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.", + cmd.get_name(), + arg.name + ); + assert!( + arg.short.is_none(), + "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.", + cmd.get_name(), + arg.name + ); + } + + assert!( + !(arg.is_required_set() && arg.is_global_set()), + "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required", + cmd.get_name(), + arg.name + ); + + // validators + assert!( + arg.validator.is_none() || arg.validator_os.is_none(), + "Command {}: Argument '{}' has both `validator` and `validator_os` set which is not allowed", + cmd.get_name(), + arg.name + ); + + if arg.value_hint == ValueHint::CommandWithArguments { + assert!( + arg.is_positional(), + "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.", + cmd.get_name(), + arg.name + ); + + assert!( + cmd.is_trailing_var_arg_set(), + "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have TrailingVarArg set.", + cmd.get_name(), + arg.name + ); + } + } + + for group in cmd.get_groups() { + // Name conflicts + assert!( + cmd.get_groups().filter(|x| x.id == group.id).count() < 2, + "Command {}: Argument group name must be unique\n\n\t'{}' is already in use", + cmd.get_name(), + group.name, + ); + + // Groups should not have naming conflicts with Args + assert!( + !cmd.get_arguments().any(|x| x.id == group.id), + "Command {}: Argument group name '{}' must not conflict with argument name", + cmd.get_name(), + group.name, + ); + + for arg in &group.args { + // Args listed inside groups should exist + assert!( + cmd.get_arguments().any(|x| x.id == *arg), + "Command {}: Argument group '{}' contains non-existent argument '{:?}'", + cmd.get_name(), + group.name, + arg + ); + } + + // Required groups should have at least one arg without default values + if group.required && !group.args.is_empty() { + assert!( + group.args.iter().any(|arg| { + cmd.get_arguments() + .any(|x| x.id == *arg && x.default_vals.is_empty()) + }), + "Command {}: Argument group '{}' is required but all of it's arguments have a default value.", + cmd.get_name(), + group.name + ) + } + } + + // Conflicts between flags and subcommands + + long_flags.sort_unstable(); + short_flags.sort_unstable(); + + detect_duplicate_flags(&long_flags, "long"); + detect_duplicate_flags(&short_flags, "short"); + + _verify_positionals(cmd); + + if let Some(help_template) = cmd.get_help_template() { + assert!( + !help_template.contains("{flags}"), + "Command {}: {}", + cmd.get_name(), + "`{flags}` template variable was removed in clap3, they are now included in `{options}`", + ); + assert!( + !help_template.contains("{unified}"), + "Command {}: {}", + cmd.get_name(), + "`{unified}` template variable was removed in clap3, use `{options}` instead" + ); + } + + cmd._panic_on_missing_help(cmd.is_help_expected_set()); + assert_app_flags(cmd); +} + +#[derive(Eq)] +enum Flag<'a> { + Command(String, &'a str), + Arg(String, &'a str), +} + +impl PartialEq for Flag<'_> { + fn eq(&self, other: &Flag) -> bool { + self.cmp(other) == Ordering::Equal + } +} + +impl PartialOrd for Flag<'_> { + fn partial_cmp(&self, other: &Flag) -> Option<Ordering> { + use Flag::*; + + match (self, other) { + (Command(s1, _), Command(s2, _)) + | (Arg(s1, _), Arg(s2, _)) + | (Command(s1, _), Arg(s2, _)) + | (Arg(s1, _), Command(s2, _)) => { + if s1 == s2 { + Some(Ordering::Equal) + } else { + s1.partial_cmp(s2) + } + } + } + } +} + +impl Ord for Flag<'_> { + fn cmp(&self, other: &Self) -> Ordering { + self.partial_cmp(other).unwrap() + } +} + +fn detect_duplicate_flags(flags: &[Flag], short_or_long: &str) { + use Flag::*; + + for (one, two) in find_duplicates(flags) { + match (one, two) { + (Command(flag, one), Command(_, another)) if one != another => panic!( + "the '{}' {} flag is specified for both '{}' and '{}' subcommands", + flag, short_or_long, one, another + ), + + (Arg(flag, one), Arg(_, another)) if one != another => panic!( + "{} option names must be unique, but '{}' is in use by both '{}' and '{}'", + short_or_long, flag, one, another + ), + + (Arg(flag, arg), Command(_, sub)) | (Command(flag, sub), Arg(_, arg)) => panic!( + "the '{}' {} flag for the '{}' argument conflicts with the short flag \ + for '{}' subcommand", + flag, short_or_long, arg, sub + ), + + _ => {} + } + } +} + +/// Find duplicates in a sorted array. +/// +/// The algorithm is simple: the array is sorted, duplicates +/// must be placed next to each other, we can check only adjacent elements. +fn find_duplicates<T: PartialEq>(slice: &[T]) -> impl Iterator<Item = (&T, &T)> { + slice.windows(2).filter_map(|w| { + if w[0] == w[1] { + Some((&w[0], &w[1])) + } else { + None + } + }) +} + +fn assert_app_flags(cmd: &Command) { + macro_rules! checker { + ($a:ident requires $($b:ident)|+) => { + if cmd.$a() { + let mut s = String::new(); + + $( + if !cmd.$b() { + s.push_str(&format!(" AppSettings::{} is required when AppSettings::{} is set.\n", std::stringify!($b), std::stringify!($a))); + } + )+ + + if !s.is_empty() { + panic!("{}", s) + } + } + }; + ($a:ident conflicts $($b:ident)|+) => { + if cmd.$a() { + let mut s = String::new(); + + $( + if cmd.$b() { + s.push_str(&format!(" AppSettings::{} conflicts with AppSettings::{}.\n", std::stringify!($b), std::stringify!($a))); + } + )+ + + if !s.is_empty() { + panic!("{}\n{}", cmd.get_name(), s) + } + } + }; + } + + checker!(is_allow_invalid_utf8_for_external_subcommands_set requires is_allow_external_subcommands_set); + #[cfg(feature = "unstable-multicall")] + checker!(is_multicall_set conflicts is_no_binary_name_set); +} + +#[cfg(debug_assertions)] +fn _verify_positionals(cmd: &Command) -> bool { + debug!("Command::_verify_positionals"); + // Because you must wait until all arguments have been supplied, this is the first chance + // to make assertions on positional argument indexes + // + // First we verify that the index highest supplied index, is equal to the number of + // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3 + // but no 2) + + let highest_idx = cmd + .get_keymap() + .keys() + .filter_map(|x| { + if let KeyType::Position(n) = x { + Some(*n) + } else { + None + } + }) + .max() + .unwrap_or(0); + + let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count(); + + assert!( + highest_idx == num_p, + "Found positional argument whose index is {} but there \ + are only {} positional arguments defined", + highest_idx, + num_p + ); + + // Next we verify that only the highest index has takes multiple arguments (if any) + let only_highest = |a: &Arg| a.is_multiple() && (a.index.unwrap_or(0) != highest_idx); + if cmd.get_positionals().any(only_highest) { + // First we make sure if there is a positional that allows multiple values + // the one before it (second to last) has one of these: + // * a value terminator + // * ArgSettings::Last + // * The last arg is Required + + // We can't pass the closure (it.next()) to the macro directly because each call to + // find() (iterator, not macro) gets called repeatedly. + let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)]; + let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)]; + + // Either the final positional is required + // Or the second to last has a terminator or .last(true) set + let ok = last.is_required_set() + || (second_to_last.terminator.is_some() || second_to_last.is_last_set()) + || last.is_last_set(); + assert!( + ok, + "When using a positional argument with .multiple_values(true) that is *not the \ + last* positional argument, the last positional argument (i.e. the one \ + with the highest index) *must* have .required(true) or .last(true) set." + ); + + // We make sure if the second to last is Multiple the last is ArgSettings::Last + let ok = second_to_last.is_multiple() || last.is_last_set(); + assert!( + ok, + "Only the last positional argument, or second to last positional \ + argument may be set to .multiple_values(true)" + ); + + // Next we check how many have both Multiple and not a specific number of values set + let count = cmd + .get_positionals() + .filter(|p| { + p.is_multiple_occurrences_set() + || (p.is_multiple_values_set() && p.num_vals.is_none()) + }) + .count(); + let ok = count <= 1 + || (last.is_last_set() + && last.is_multiple() + && second_to_last.is_multiple() + && count == 2); + assert!( + ok, + "Only one positional argument with .multiple_values(true) set is allowed per \ + command, unless the second one also has .last(true) set" + ); + } + + let mut found = false; + + if cmd.is_allow_missing_positional_set() { + // Check that if a required positional argument is found, all positions with a lower + // index are also required. + let mut foundx2 = false; + + for p in cmd.get_positionals() { + if foundx2 && !p.is_required_set() { + assert!( + p.is_required_set(), + "Found non-required positional argument with a lower \ + index than a required positional argument by two or more: {:?} \ + index {:?}", + p.name, + p.index + ); + } else if p.is_required_set() && !p.is_last_set() { + // Args that .last(true) don't count since they can be required and have + // positionals with a lower index that aren't required + // Imagine: prog <req1> [opt1] -- <req2> + // Both of these are valid invocations: + // $ prog r1 -- r2 + // $ prog r1 o1 -- r2 + if found { + foundx2 = true; + continue; + } + found = true; + continue; + } else { + found = false; + } + } + } else { + // Check that if a required positional argument is found, all positions with a lower + // index are also required + for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) { + if found { + assert!( + p.is_required_set(), + "Found non-required positional argument with a lower \ + index than a required positional argument: {:?} index {:?}", + p.name, + p.index + ); + } else if p.is_required_set() && !p.is_last_set() { + // Args that .last(true) don't count since they can be required and have + // positionals with a lower index that aren't required + // Imagine: prog <req1> [opt1] -- <req2> + // Both of these are valid invocations: + // $ prog r1 -- r2 + // $ prog r1 o1 -- r2 + found = true; + continue; + } + } + } + assert!( + cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2, + "Only one positional argument may have last(true) set. Found two." + ); + if cmd + .get_positionals() + .any(|p| p.is_last_set() && p.is_required_set()) + && cmd.has_subcommands() + && !cmd.is_subcommand_negates_reqs_set() + { + panic!( + "Having a required positional argument with .last(true) set *and* child \ + subcommands without setting SubcommandsNegateReqs isn't compatible." + ); + } + + true +} + +fn assert_arg(arg: &Arg) { + debug!("Arg::_debug_asserts:{}", arg.name); + + // Self conflict + // TODO: this check should be recursive + assert!( + !arg.blacklist.iter().any(|x| *x == arg.id), + "Argument '{}' cannot conflict with itself", + arg.name, + ); + + if arg.value_hint != ValueHint::Unknown { + assert!( + arg.is_takes_value_set(), + "Argument '{}' has value hint but takes no value", + arg.name + ); + + if arg.value_hint == ValueHint::CommandWithArguments { + assert!( + arg.is_multiple_values_set(), + "Argument '{}' uses hint CommandWithArguments and must accept multiple values", + arg.name + ) + } + } + + if arg.index.is_some() { + assert!( + arg.is_positional(), + "Argument '{}' is a positional argument and can't have short or long name versions", + arg.name + ); + } + + if arg.is_required_set() { + assert!( + arg.default_vals.is_empty(), + "Argument '{}' is required and can't have a default value", + arg.name + ); + } + + #[cfg(feature = "unstable-v4")] + { + let num_vals = arg.get_num_vals().unwrap_or(usize::MAX); + let num_val_names = arg.get_value_names().unwrap_or(&[]).len(); + if num_vals < num_val_names { + panic!( + "Argument {}: Too many value names ({}) compared to number_of_values ({})", + arg.name, num_val_names, num_vals + ); + } + } + + assert_arg_flags(arg); + + assert_defaults(arg, "default_value", arg.default_vals.iter().copied()); + assert_defaults( + arg, + "default_missing_value", + arg.default_missing_vals.iter().copied(), + ); + assert_defaults( + arg, + "default_value_if", + arg.default_vals_ifs + .iter() + .filter_map(|(_, _, default)| *default), + ); +} + +fn assert_arg_flags(arg: &Arg) { + macro_rules! checker { + ($a:ident requires $($b:ident)|+) => { + if arg.$a() { + let mut s = String::new(); + + $( + if !arg.$b() { + s.push_str(&format!(" Arg::{} is required when Arg::{} is set.\n", std::stringify!($b), std::stringify!($a))); + } + )+ + + if !s.is_empty() { + panic!("Argument {:?}\n{}", arg.get_id(), s) + } + } + } + } + + checker!(is_forbid_empty_values_set requires is_takes_value_set); + checker!(is_require_value_delimiter_set requires is_takes_value_set); + checker!(is_require_value_delimiter_set requires is_use_value_delimiter_set); + checker!(is_hide_possible_values_set requires is_takes_value_set); + checker!(is_allow_hyphen_values_set requires is_takes_value_set); + checker!(is_require_equals_set requires is_takes_value_set); + checker!(is_last_set requires is_takes_value_set); + checker!(is_hide_default_value_set requires is_takes_value_set); + checker!(is_multiple_values_set requires is_takes_value_set); + checker!(is_ignore_case_set requires is_takes_value_set); + checker!(is_allow_invalid_utf8_set requires is_takes_value_set); +} + +fn assert_defaults<'d>( + arg: &Arg, + field: &'static str, + defaults: impl IntoIterator<Item = &'d std::ffi::OsStr>, +) { + for default_os in defaults { + if let Some(default_s) = default_os.to_str() { + if !arg.possible_vals.is_empty() { + if let Some(delim) = arg.get_value_delimiter() { + for part in default_s.split(delim) { + assert!( + arg.possible_vals.iter().any(|possible_val| { + possible_val.matches(part, arg.is_ignore_case_set()) + }), + "Argument `{}`'s {}={} doesn't match possible values", + arg.name, + field, + part + ) + } + } else { + assert!( + arg.possible_vals.iter().any(|possible_val| { + possible_val.matches(default_s, arg.is_ignore_case_set()) + }), + "Argument `{}`'s {}={} doesn't match possible values", + arg.name, + field, + default_s + ); + } + } + + if let Some(validator) = arg.validator.as_ref() { + let mut validator = validator.lock().unwrap(); + if let Some(delim) = arg.get_value_delimiter() { + for part in default_s.split(delim) { + if let Err(err) = validator(part) { + panic!( + "Argument `{}`'s {}={} failed validation: {}", + arg.name, field, part, err + ); + } + } + } else if let Err(err) = validator(default_s) { + panic!( + "Argument `{}`'s {}={} failed validation: {}", + arg.name, field, default_s, err + ); + } + } + } + + if let Some(validator) = arg.validator_os.as_ref() { + let mut validator = validator.lock().unwrap(); + if let Some(delim) = arg.get_value_delimiter() { + let default_os = RawOsStr::new(default_os); + for part in default_os.split(delim) { + if let Err(err) = validator(&part.to_os_str()) { + panic!( + "Argument `{}`'s {}={:?} failed validation: {}", + arg.name, field, part, err + ); + } + } + } else if let Err(err) = validator(default_os) { + panic!( + "Argument `{}`'s {}={:?} failed validation: {}", + arg.name, field, default_os, err + ); + } + } + } +} diff --git a/third_party/rust/clap/src/build/macros.rs b/third_party/rust/clap/src/build/macros.rs new file mode 100644 index 0000000000..5be4d205e0 --- /dev/null +++ b/third_party/rust/clap/src/build/macros.rs @@ -0,0 +1,180 @@ +#[cfg(feature = "yaml")] +macro_rules! yaml_tuple2 { + ($a:ident, $v:ident, $c:ident) => {{ + if let Some(vec) = $v.as_vec() { + for ys in vec { + if let Some(tup) = ys.as_vec() { + debug_assert_eq!(2, tup.len()); + $a = $a.$c(yaml_str!(tup[0]), yaml_str!(tup[1])); + } else { + panic!("Failed to convert YAML value to vec"); + } + } + } else { + panic!("Failed to convert YAML value to vec"); + } + $a + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_tuple3 { + ($a:ident, $v:ident, $c:ident) => {{ + if let Some(vec) = $v.as_vec() { + for ys in vec { + if let Some(tup) = ys.as_vec() { + debug_assert_eq!(3, tup.len()); + $a = $a.$c( + yaml_str!(tup[0]), + yaml_opt_str!(tup[1]), + yaml_opt_str!(tup[2]), + ); + } else { + panic!("Failed to convert YAML value to vec"); + } + } + } else { + panic!("Failed to convert YAML value to vec"); + } + $a + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_vec_or_str { + ($a:ident, $v:ident, $c:ident) => {{ + let maybe_vec = $v.as_vec(); + if let Some(vec) = maybe_vec { + for ys in vec { + if let Some(s) = ys.as_str() { + $a = $a.$c(s); + } else { + panic!("Failed to convert YAML value {:?} to a string", ys); + } + } + } else { + if let Some(s) = $v.as_str() { + $a = $a.$c(s); + } else { + panic!( + "Failed to convert YAML value {:?} to either a vec or string", + $v + ); + } + } + $a + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_vec { + ($a:ident, $v:ident, $c:ident) => {{ + let maybe_vec = $v.as_vec(); + if let Some(vec) = maybe_vec { + let content = vec.into_iter().map(|ys| { + if let Some(s) = ys.as_str() { + s + } else { + panic!("Failed to convert YAML value {:?} to a string", ys); + } + }); + $a = $a.$c(content) + } else { + panic!("Failed to convert YAML value {:?} to a vec", $v); + } + $a + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_opt_str { + ($v:expr) => {{ + if !$v.is_null() { + Some( + $v.as_str() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)), + ) + } else { + None + } + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_char { + ($v:expr) => {{ + $v.as_str() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) + .chars() + .next() + .unwrap_or_else(|| panic!("Expected char")) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_str { + ($v:expr) => {{ + $v.as_str() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_char { + ($a:ident, $v:ident, $c:ident) => {{ + $a.$c(yaml_char!($v)) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_str { + ($a:ident, $v:ident, $c:ident) => {{ + $a.$c(yaml_str!($v)) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_bool { + ($a:ident, $v:ident, $c:ident) => {{ + $a.$c($v + .as_bool() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_usize { + ($a:ident, $v:ident, $c:ident) => {{ + $a.$c($v + .as_i64() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) + as usize) + }}; +} + +#[cfg(feature = "yaml")] +macro_rules! yaml_to_setting { + ($a:ident, $v:ident, $c:ident, $s:ident, $t:literal, $n:expr) => {{ + if let Some(v) = $v.as_vec() { + for ys in v { + if let Some(s) = ys.as_str() { + $a = $a.$c(s.parse::<$s>().unwrap_or_else(|_| { + panic!("Unknown {} '{}' found in YAML file for {}", $t, s, $n) + })); + } else { + panic!( + "Failed to convert YAML {:?} value to an array of strings", + $v + ); + } + } + } else if let Some(v) = $v.as_str() { + $a = $a.$c(v + .parse::<$s>() + .unwrap_or_else(|_| panic!("Unknown {} '{}' found in YAML file for {}", $t, v, $n))) + } else { + panic!("Failed to convert YAML {:?} value to a string", $v); + } + $a + }}; +} diff --git a/third_party/rust/clap/src/build/mod.rs b/third_party/rust/clap/src/build/mod.rs new file mode 100644 index 0000000000..ae8c46b636 --- /dev/null +++ b/third_party/rust/clap/src/build/mod.rs @@ -0,0 +1,38 @@ +#[macro_use] +mod macros; + +mod app_settings; +mod arg; +mod arg_group; +mod arg_predicate; +mod arg_settings; +mod command; +mod possible_value; +mod usage_parser; +mod value_hint; + +#[cfg(feature = "regex")] +mod regex; + +#[cfg(debug_assertions)] +mod debug_asserts; + +#[cfg(test)] +mod tests; + +pub use app_settings::{AppFlags, AppSettings}; +pub use arg::Arg; +pub use arg_group::ArgGroup; +pub use arg_settings::{ArgFlags, ArgSettings}; +pub use command::Command; +pub use possible_value::PossibleValue; +pub use value_hint::ValueHint; + +#[allow(deprecated)] +pub use command::App; + +#[cfg(feature = "regex")] +pub use self::regex::RegexRef; + +pub(crate) use arg::display_arg_val; +pub(crate) use arg_predicate::ArgPredicate; diff --git a/third_party/rust/clap/src/build/possible_value.rs b/third_party/rust/clap/src/build/possible_value.rs new file mode 100644 index 0000000000..e56fb858ce --- /dev/null +++ b/third_party/rust/clap/src/build/possible_value.rs @@ -0,0 +1,251 @@ +use std::{borrow::Cow, iter}; + +use crate::util::eq_ignore_case; + +/// A possible value of an argument. +/// +/// This is used for specifying [possible values] of [Args]. +/// +/// **NOTE:** This struct is likely not needed for most usecases as it is only required to +/// [hide] single values from help messages and shell completions or to attach [help] to possible values. +/// +/// # Examples +/// +/// ```rust +/// # use clap::{Arg, PossibleValue}; +/// let cfg = Arg::new("config") +/// .takes_value(true) +/// .value_name("FILE") +/// .possible_value(PossibleValue::new("fast")) +/// .possible_value(PossibleValue::new("slow").help("slower than fast")) +/// .possible_value(PossibleValue::new("secret speed").hide(true)); +/// ``` +/// [Args]: crate::Arg +/// [possible values]: crate::Arg::possible_value() +/// [hide]: PossibleValue::hide() +/// [help]: PossibleValue::help() +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct PossibleValue<'help> { + name: &'help str, + help: Option<&'help str>, + aliases: Vec<&'help str>, // (name, visible) + hide: bool, +} + +impl<'help> PossibleValue<'help> { + /// Create a [`PossibleValue`] with its name. + /// + /// The name will be used to decide whether this value was provided by the user to an argument. + /// + /// **NOTE:** In case it is not [hidden] it will also be shown in help messages for arguments + /// that use it as a [possible value] and have not hidden them through [`Arg::hide_possible_values(true)`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::PossibleValue; + /// PossibleValue::new("fast") + /// # ; + /// ``` + /// [hidden]: PossibleValue::hide + /// [possible value]: crate::Arg::possible_values + /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() + pub fn new(name: &'help str) -> Self { + PossibleValue { + name, + ..Default::default() + } + } + + /// Sets the help description of the value. + /// + /// This is typically displayed in completions (where supported) and should be a short, one-line + /// description. + /// + /// # Examples + /// + /// ```rust + /// # use clap::PossibleValue; + /// PossibleValue::new("slow") + /// .help("not fast") + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn help(mut self, help: &'help str) -> Self { + self.help = Some(help); + self + } + + /// Hides this value from help and shell completions. + /// + /// This is an alternative to hiding through [`Arg::hide_possible_values(true)`], if you only + /// want to hide some values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::PossibleValue; + /// PossibleValue::new("secret") + /// .hide(true) + /// # ; + /// ``` + /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() + #[inline] + #[must_use] + pub fn hide(mut self, yes: bool) -> Self { + self.hide = yes; + self + } + + /// Sets a *hidden* alias for this argument value. + /// + /// # Examples + /// + /// ```rust + /// # use clap::PossibleValue; + /// PossibleValue::new("slow") + /// .alias("not-fast") + /// # ; + /// ``` + #[must_use] + pub fn alias(mut self, name: &'help str) -> Self { + self.aliases.push(name); + self + } + + /// Sets multiple *hidden* aliases for this argument value. + /// + /// # Examples + /// + /// ```rust + /// # use clap::PossibleValue; + /// PossibleValue::new("slow") + /// .aliases(["not-fast", "snake-like"]) + /// # ; + /// ``` + #[must_use] + pub fn aliases<I>(mut self, names: I) -> Self + where + I: IntoIterator<Item = &'help str>, + { + self.aliases.extend(names.into_iter()); + self + } +} + +/// Reflection +impl<'help> PossibleValue<'help> { + /// Get the name of the argument value + #[inline] + pub fn get_name(&self) -> &'help str { + self.name + } + + /// Get the help specified for this argument, if any + #[inline] + pub fn get_help(&self) -> Option<&'help str> { + self.help + } + + /// Get the help specified for this argument, if any and the argument + /// value is not hidden + #[inline] + #[cfg(feature = "unstable-v4")] + pub(crate) fn get_visible_help(&self) -> Option<&'help str> { + if !self.hide { + self.help + } else { + None + } + } + + /// Deprecated, replaced with [`PossibleValue::is_hide_set`] + #[inline] + #[deprecated(since = "3.1.0", note = "Replaced with `PossibleValue::is_hide_set`")] + pub fn is_hidden(&self) -> bool { + self.is_hide_set() + } + + /// Report if [`PossibleValue::hide`] is set + #[inline] + pub fn is_hide_set(&self) -> bool { + self.hide + } + + /// Report if PossibleValue is not hidden and has a help message + pub(crate) fn should_show_help(&self) -> bool { + !self.hide && self.help.is_some() + } + + /// Get the name if argument value is not hidden, `None` otherwise + #[deprecated( + since = "3.1.4", + note = "Use `PossibleValue::is_hide_set` and `PossibleValue::get_name`" + )] + pub fn get_visible_name(&self) -> Option<&'help str> { + if self.hide { + None + } else { + Some(self.name) + } + } + + /// Get the name if argument value is not hidden, `None` otherwise, + /// but wrapped in quotes if it contains whitespace + pub(crate) fn get_visible_quoted_name(&self) -> Option<Cow<'help, str>> { + if !self.hide { + Some(if self.name.contains(char::is_whitespace) { + format!("{:?}", self.name).into() + } else { + self.name.into() + }) + } else { + None + } + } + + /// Returns all valid values of the argument value. + /// + /// Namely the name and all aliases. + pub fn get_name_and_aliases(&self) -> impl Iterator<Item = &'help str> + '_ { + iter::once(&self.name).chain(&self.aliases).copied() + } + + /// Tests if the value is valid for this argument value + /// + /// The value is valid if it is either the name or one of the aliases. + /// + /// # Examples + /// + /// ```rust + /// # use clap::PossibleValue; + /// let arg_value = PossibleValue::new("fast").alias("not-slow"); + /// + /// assert!(arg_value.matches("fast", false)); + /// assert!(arg_value.matches("not-slow", false)); + /// + /// assert!(arg_value.matches("FAST", true)); + /// assert!(!arg_value.matches("FAST", false)); + /// ``` + pub fn matches(&self, value: &str, ignore_case: bool) -> bool { + if ignore_case { + self.get_name_and_aliases() + .any(|name| eq_ignore_case(name, value)) + } else { + self.get_name_and_aliases().any(|name| name == value) + } + } +} + +impl<'help> From<&'help str> for PossibleValue<'help> { + fn from(s: &'help str) -> Self { + Self::new(s) + } +} + +impl<'help> From<&'help &'help str> for PossibleValue<'help> { + fn from(s: &'help &'help str) -> Self { + Self::new(s) + } +} diff --git a/third_party/rust/clap/src/build/regex.rs b/third_party/rust/clap/src/build/regex.rs new file mode 100644 index 0000000000..bf3a78e0c2 --- /dev/null +++ b/third_party/rust/clap/src/build/regex.rs @@ -0,0 +1,88 @@ +use ::regex::{Error, Regex, RegexSet}; + +use core::{convert::TryFrom, ops::Deref, str::FromStr}; +use std::borrow::Cow; + +/// Contains either a regular expression or a set of them or a reference to one. +/// +/// See [Arg::validator_regex(][crate::Arg::validator_regex] to set this on an argument. +#[derive(Debug, Clone)] +pub enum RegexRef<'a> { + /// Used if the underlying is a regex set + RegexSet(Cow<'a, RegexSet>), + /// Used if the underlying is a regex + Regex(Cow<'a, Regex>), +} + +impl<'a> RegexRef<'a> { + pub(crate) fn is_match(&self, text: &str) -> bool { + match self { + Self::Regex(r) => r.deref().is_match(text), + Self::RegexSet(r) => r.deref().is_match(text), + } + } +} + +impl<'a> From<&'a Regex> for RegexRef<'a> { + fn from(r: &'a Regex) -> Self { + Self::Regex(Cow::Borrowed(r)) + } +} + +impl<'a> From<Regex> for RegexRef<'a> { + fn from(r: Regex) -> Self { + Self::Regex(Cow::Owned(r)) + } +} + +impl<'a> From<&'a RegexSet> for RegexRef<'a> { + fn from(r: &'a RegexSet) -> Self { + Self::RegexSet(Cow::Borrowed(r)) + } +} + +impl<'a> From<RegexSet> for RegexRef<'a> { + fn from(r: RegexSet) -> Self { + Self::RegexSet(Cow::Owned(r)) + } +} + +impl<'a> TryFrom<&'a str> for RegexRef<'a> { + type Error = <Self as FromStr>::Err; + + fn try_from(r: &'a str) -> Result<Self, Self::Error> { + Self::from_str(r) + } +} + +impl<'a> FromStr for RegexRef<'a> { + type Err = Error; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + Regex::from_str(s).map(|v| Self::Regex(Cow::Owned(v))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use core::convert::TryInto; + + #[test] + fn test_try_from_with_valid_string() { + let t: Result<RegexRef, _> = "^Hello, World$".try_into(); + assert!(t.is_ok()) + } + + #[test] + fn test_try_from_with_invalid_string() { + let t: Result<RegexRef, _> = "^Hello, World)$".try_into(); + assert!(t.is_err()); + } + + #[test] + fn from_str() { + let t: Result<RegexRef, _> = RegexRef::from_str("^Hello, World"); + assert!(t.is_ok()); + } +} diff --git a/third_party/rust/clap/src/build/tests.rs b/third_party/rust/clap/src/build/tests.rs new file mode 100644 index 0000000000..76c8b87855 --- /dev/null +++ b/third_party/rust/clap/src/build/tests.rs @@ -0,0 +1,56 @@ +use crate::Arg; +use crate::Command; + +#[test] +fn propagate_version() { + let mut cmd = Command::new("test") + .propagate_version(true) + .version("1.1") + .subcommand(Command::new("sub1")); + cmd._propagate(); + assert_eq!( + cmd.get_subcommands().next().unwrap().get_version(), + Some("1.1") + ); +} + +#[test] +fn global_setting() { + let mut cmd = Command::new("test") + .disable_version_flag(true) + .subcommand(Command::new("subcmd")); + cmd._propagate(); + assert!(cmd + .get_subcommands() + .find(|s| s.get_name() == "subcmd") + .unwrap() + .is_disable_version_flag_set()); +} + +// This test will *fail to compile* if Command is not Send + Sync +#[test] +fn app_send_sync() { + fn foo<T: Send + Sync>(_: T) {} + foo(Command::new("test")) +} + +#[test] +fn issue_2090() { + let mut cmd = Command::new("cmd") + .disable_version_flag(true) + .subcommand(Command::new("sub")); + cmd._build_self(); + + assert!(cmd + .get_subcommands() + .next() + .unwrap() + .is_disable_version_flag_set()); +} + +// This test will *fail to compile* if Arg is not Send + Sync +#[test] +fn arg_send_sync() { + fn foo<T: Send + Sync>(_: T) {} + foo(Arg::new("test")) +} diff --git a/third_party/rust/clap/src/build/usage_parser.rs b/third_party/rust/clap/src/build/usage_parser.rs new file mode 100644 index 0000000000..ccfad66bfa --- /dev/null +++ b/third_party/rust/clap/src/build/usage_parser.rs @@ -0,0 +1,1278 @@ +#![allow(deprecated)] + +// Internal +use crate::{ + build::{Arg, ArgSettings}, + INTERNAL_ERROR_MSG, +}; + +#[derive(PartialEq, Debug)] +enum UsageToken { + Name, + ValName, + Short, + Long, + Help, + Multiple, + Unknown, + Default, +} + +#[derive(Debug)] +pub(crate) struct UsageParser<'help> { + usage: &'help str, + pos: usize, + start: usize, + prev: UsageToken, + explicit_name_set: bool, +} + +impl<'help> UsageParser<'help> { + fn new(usage: &'help str) -> Self { + debug!("new: usage={:?}", usage); + UsageParser { + usage, + pos: 0, + start: 0, + prev: UsageToken::Unknown, + explicit_name_set: false, + } + } + + pub(crate) fn from_usage(usage: &'help str) -> Self { + debug!("UsageParser::from_usage"); + UsageParser::new(usage) + } + + pub(crate) fn parse(mut self) -> Arg<'help> { + debug!("UsageParser::parse"); + let mut arg = Arg::default(); + loop { + debug!("UsageParser::parse:iter: pos={}", self.pos); + self.stop_at(token); + if let Some(&c) = self.usage.as_bytes().get(self.pos) { + match c { + b'-' => self.short_or_long(&mut arg), + b'.' => self.multiple(&mut arg), + b'@' => self.default(&mut arg), + b'\'' => self.help(&mut arg), + _ => self.name(&mut arg), + } + } else { + break; + } + } + + debug!("UsageParser::parse: vals...{:?}", arg.val_names); + arg + } + + fn name(&mut self, arg: &mut Arg<'help>) { + debug!("UsageParser::name"); + if *self + .usage + .as_bytes() + .get(self.pos) + .expect(INTERNAL_ERROR_MSG) + == b'<' + && !self.explicit_name_set + { + arg.settings.set(ArgSettings::Required); + } + self.pos += 1; + self.stop_at(name_end); + let name = &self.usage[self.start..self.pos]; + if self.prev == UsageToken::Unknown { + debug!("UsageParser::name: setting name...{}", name); + arg.id = name.into(); + arg.name = name; + if arg.long.is_none() && arg.short.is_none() { + debug!("name: explicit name set..."); + self.explicit_name_set = true; + self.prev = UsageToken::Name; + } + } else { + debug!("UsageParser::name: setting val name...{}", name); + if arg.val_names.is_empty() { + arg.settings.set(ArgSettings::TakesValue); + } + let len = arg.val_names.len(); + arg.val_names.insert(len, name); + self.prev = UsageToken::ValName; + } + } + + fn stop_at<F>(&mut self, f: F) + where + F: Fn(u8) -> bool, + { + debug!("UsageParser::stop_at"); + self.start = self.pos; + self.pos += self.usage[self.start..] + .bytes() + .take_while(|&b| f(b)) + .count(); + } + + fn short_or_long(&mut self, arg: &mut Arg<'help>) { + debug!("UsageParser::short_or_long"); + self.pos += 1; + if *self + .usage + .as_bytes() + .get(self.pos) + .expect(INTERNAL_ERROR_MSG) + == b'-' + { + self.pos += 1; + self.long(arg); + return; + } + self.short(arg) + } + + fn long(&mut self, arg: &mut Arg<'help>) { + debug!("UsageParser::long"); + self.stop_at(long_end); + let name = &self.usage[self.start..self.pos]; + if !self.explicit_name_set { + debug!("UsageParser::long: setting name...{}", name); + arg.id = name.into(); + arg.name = name; + } + debug!("UsageParser::long: setting long...{}", name); + arg.long = Some(name); + self.prev = UsageToken::Long; + } + + fn short(&mut self, arg: &mut Arg<'help>) { + debug!("UsageParser::short"); + let start = &self.usage[self.pos..]; + let short = start.chars().next().expect(INTERNAL_ERROR_MSG); + debug!("UsageParser::short: setting short...{}", short); + arg.short = Some(short); + if arg.name.is_empty() { + // --long takes precedence but doesn't set self.explicit_name_set + let name = &start[..short.len_utf8()]; + debug!("UsageParser::short: setting name...{}", name); + arg.id = name.into(); + arg.name = name; + } + self.prev = UsageToken::Short; + } + + // "something..." + fn multiple(&mut self, arg: &mut Arg) { + debug!("UsageParser::multiple"); + let mut dot_counter = 1; + let start = self.pos; + let mut bytes = self.usage[start..].bytes(); + while bytes.next() == Some(b'.') { + dot_counter += 1; + self.pos += 1; + if dot_counter == 3 { + debug!("UsageParser::multiple: setting multiple"); + arg.settings.set(ArgSettings::MultipleOccurrences); + if arg.is_takes_value_set() { + arg.settings.set(ArgSettings::MultipleValues); + arg.settings.set(ArgSettings::UseValueDelimiter); + arg.val_delim.get_or_insert(','); + } + self.prev = UsageToken::Multiple; + self.pos += 1; + break; + } + } + } + + fn help(&mut self, arg: &mut Arg<'help>) { + debug!("UsageParser::help"); + self.stop_at(help_start); + self.start = self.pos + 1; + self.pos = self.usage.len() - 1; + debug!( + "UsageParser::help: setting help...{}", + &self.usage[self.start..self.pos] + ); + arg.help = Some(&self.usage[self.start..self.pos]); + self.pos += 1; // Move to next byte to keep from thinking ending ' is a start + self.prev = UsageToken::Help; + } + + fn default(&mut self, arg: &mut Arg<'help>) { + debug!( + "UsageParser::default: from=\"{}\"", + &self.usage[self.pos..self.usage.len()] + ); + self.pos += 1; // Skip @ + self.stop_at(default_value_end); // Find first space after value + debug!( + "UsageParser::default: setting default...\"{}\"", + &self.usage[self.start..self.pos] + ); + arg.settings.set(ArgSettings::TakesValue); + arg.default_vals = vec![std::ffi::OsStr::new(&self.usage[self.start..self.pos])]; + self.prev = UsageToken::Default; + } +} + +#[inline] +fn name_end(b: u8) -> bool { + b != b']' && b != b'>' +} + +#[inline] +fn token(b: u8) -> bool { + b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'-' && b != b'@' +} + +#[inline] +fn long_end(b: u8) -> bool { + b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'=' && b != b' ' +} + +#[inline] +fn help_start(b: u8) -> bool { + b != b'\'' +} + +#[inline] +fn default_value_end(b: u8) -> bool { + b != b' ' +} + +#[cfg(test)] +mod test { + #![allow(deprecated)] + + use crate::build::{Arg, ArgSettings}; + + #[allow(clippy::cognitive_complexity)] + #[test] + fn create_flag_usage() { + let a = Arg::from_usage("[flag] -f 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("[flag] --flag 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.long.unwrap(), "flag"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("--flag 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.long.unwrap(), "flag"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("[flag] -f --flag 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.short.unwrap(), 'f'); + assert_eq!(a.long.unwrap(), "flag"); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("[flag] -f... 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("[flag] -f --flag... 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.long.unwrap(), "flag"); + assert_eq!(a.short.unwrap(), 'f'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("-f --flag... 'some help info'"); + assert_eq!(a.name, "flag"); + assert_eq!(a.long.unwrap(), "flag"); + assert_eq!(a.short.unwrap(), 'f'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("--flags"); + assert_eq!(a.name, "flags"); + assert_eq!(a.long.unwrap(), "flags"); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("--flags..."); + assert_eq!(a.name, "flags"); + assert_eq!(a.long.unwrap(), "flags"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("[flags] -f"); + assert_eq!(a.name, "flags"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("[flags] -f..."); + assert_eq!(a.name, "flags"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("-f 'some help info'"); + assert_eq!(a.name, "f"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("-f"); + assert_eq!(a.name, "f"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.val_names.is_empty()); + + let a = Arg::from_usage("-f..."); + assert_eq!(a.name, "f"); + assert_eq!(a.short.unwrap(), 'f'); + assert!(a.is_multiple_occurrences_set()); + assert!(a.val_names.is_empty()); + } + + #[test] + fn create_option_usage0() { + // Short only + let a = Arg::from_usage("[option] -o [opt] 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.short.unwrap(), 'o'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage1() { + let a = Arg::from_usage("-o [opt] 'some help info'"); + assert_eq!(a.name, "o"); + assert_eq!(a.short.unwrap(), 'o'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage2() { + let a = Arg::from_usage("<option> -o <opt> 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.short.unwrap(), 'o'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage3() { + let a = Arg::from_usage("-o <opt> 'some help info'"); + assert_eq!(a.name, "o"); + assert_eq!(a.short.unwrap(), 'o'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage4() { + let a = Arg::from_usage("[option] -o [opt]... 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.short.unwrap(), 'o'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage5() { + let a = Arg::from_usage("[option]... -o [opt] 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.short.unwrap(), 'o'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage6() { + let a = Arg::from_usage("-o [opt]... 'some help info'"); + assert_eq!(a.name, "o"); + assert_eq!(a.short.unwrap(), 'o'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage7() { + let a = Arg::from_usage("<option> -o <opt>... 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.short.unwrap(), 'o'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage8() { + let a = Arg::from_usage("<option>... -o <opt> 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.short.unwrap(), 'o'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage9() { + let a = Arg::from_usage("-o <opt>... 'some help info'"); + assert_eq!(a.name, "o"); + assert_eq!(a.short.unwrap(), 'o'); + assert!(a.long.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_long1() { + let a = Arg::from_usage("[option] --opt [opt] 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_long2() { + let a = Arg::from_usage("--opt [option] 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_long3() { + let a = Arg::from_usage("<option> --opt <opt> 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_long4() { + let a = Arg::from_usage("--opt <option> 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_long5() { + let a = Arg::from_usage("[option] --opt [opt]... 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_long6() { + let a = Arg::from_usage("[option]... --opt [opt] 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_long7() { + let a = Arg::from_usage("--opt [option]... 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_long8() { + let a = Arg::from_usage("<option> --opt <opt>... 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_long9() { + let a = Arg::from_usage("<option>... --opt <opt> 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_long10() { + let a = Arg::from_usage("--opt <option>... 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_long_equals1() { + let a = Arg::from_usage("[option] --opt=[opt] 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_long_equals2() { + let a = Arg::from_usage("--opt=[option] 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_long_equals3() { + let a = Arg::from_usage("<option> --opt=<opt> 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_long_equals4() { + let a = Arg::from_usage("--opt=<option> 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_long_equals5() { + let a = Arg::from_usage("[option] --opt=[opt]... 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_long_equals6() { + let a = Arg::from_usage("[option]... --opt=[opt] 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_long_equals7() { + let a = Arg::from_usage("--opt=[option]... 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_long_equals8() { + let a = Arg::from_usage("<option> --opt=<opt>... 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_long_equals9() { + let a = Arg::from_usage("<option>... --opt=<opt> 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_long_equals10() { + let a = Arg::from_usage("--opt=<option>... 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert!(a.short.is_none()); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_both1() { + let a = Arg::from_usage("[option] -o --opt [option] 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_both2() { + let a = Arg::from_usage("-o --opt [option] 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_both3() { + let a = Arg::from_usage("<option> -o --opt <opt> 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_both4() { + let a = Arg::from_usage("-o --opt <option> 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_both5() { + let a = Arg::from_usage("[option]... -o --opt [option] 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_both6() { + let a = Arg::from_usage("-o --opt [option]... 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_both7() { + let a = Arg::from_usage("<option>... -o --opt <opt> 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_both8() { + let a = Arg::from_usage("-o --opt <option>... 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_both_equals1() { + let a = Arg::from_usage("[option] -o --opt=[option] 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_both_equals2() { + let a = Arg::from_usage("-o --opt=[option] 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_both_equals3() { + let a = Arg::from_usage("<option> -o --opt=<opt> 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_both_equals4() { + let a = Arg::from_usage("-o --opt=<option> 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_both_equals5() { + let a = Arg::from_usage("[option]... -o --opt=[option] 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_both_equals6() { + let a = Arg::from_usage("-o --opt=[option]... 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_usage_both_equals7() { + let a = Arg::from_usage("<option>... -o --opt=<opt> 'some help info'"); + assert_eq!(a.name, "option"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"opt"]); + } + + #[test] + fn create_option_usage_both_equals8() { + let a = Arg::from_usage("-o --opt=<option>... 'some help info'"); + assert_eq!(a.name, "opt"); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"option"]); + } + + #[test] + fn create_option_with_vals1() { + let a = Arg::from_usage("-o <file> <mode> 'some help info'"); + assert_eq!(a.name, "o"); + assert!(a.long.is_none()); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"file", &"mode"]); + } + + #[test] + fn create_option_with_vals2() { + let a = Arg::from_usage("-o <file> <mode>... 'some help info'"); + assert_eq!(a.name, "o"); + assert!(a.long.is_none()); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"file", &"mode"]); + } + + #[test] + fn create_option_with_vals3() { + let a = Arg::from_usage("--opt <file> <mode>... 'some help info'"); + assert_eq!(a.name, "opt"); + assert!(a.short.is_none()); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"file", &"mode"]); + } + + #[test] + fn create_option_with_vals4() { + let a = Arg::from_usage("[myopt] --opt <file> <mode> 'some help info'"); + assert_eq!(a.name, "myopt"); + assert!(a.short.is_none()); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"file", &"mode"]); + } + + #[test] + fn create_option_with_vals5() { + let a = Arg::from_usage("--opt <file> <mode> 'some help info'"); + assert_eq!(a.name, "opt"); + assert!(a.short.is_none()); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + } + + #[test] + fn create_positional_usage() { + let a = Arg::from_usage("[pos] 'some help info'"); + assert_eq!(a.name, "pos"); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(!a.is_required_set()); + assert!(a.val_names.is_empty()); + } + + #[test] + fn create_positional_usage0() { + let a = Arg::from_usage("<pos> 'some help info'"); + assert_eq!(a.name, "pos"); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_required_set()); + assert!(a.val_names.is_empty()); + } + + #[test] + fn pos_mult_help() { + let a = Arg::from_usage("[pos]... 'some help info'"); + assert_eq!(a.name, "pos"); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(!a.is_required_set()); + assert!(a.val_names.is_empty()); + } + + #[test] + fn pos_help_lit_single_quote() { + let a = Arg::from_usage("[pos]... 'some help\' info'"); + assert_eq!(a.name, "pos"); + assert_eq!(a.help.unwrap(), "some help' info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(!a.is_required_set()); + assert!(a.val_names.is_empty()); + } + + #[test] + fn pos_help_double_lit_single_quote() { + let a = Arg::from_usage("[pos]... 'some \'help\' info'"); + assert_eq!(a.name, "pos"); + assert_eq!(a.help.unwrap(), "some 'help' info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(!a.is_required_set()); + assert!(a.val_names.is_empty()); + } + + #[test] + fn pos_help_newline() { + let a = Arg::from_usage( + "[pos]... 'some help{n}\ + info'", + ); + assert_eq!(a.name, "pos"); + assert_eq!(a.help.unwrap(), "some help{n}info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(!a.is_required_set()); + assert!(a.val_names.is_empty()); + } + + #[test] + fn pos_help_newline_lit_sq() { + let a = Arg::from_usage( + "[pos]... 'some help\' stuff{n}\ + info'", + ); + assert_eq!(a.name, "pos"); + assert_eq!(a.help.unwrap(), "some help' stuff{n}info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(!a.is_required_set()); + assert!(a.val_names.is_empty()); + } + + #[test] + fn pos_req_mult_help() { + let a = Arg::from_usage("<pos>... 'some help info'"); + assert_eq!(a.name, "pos"); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_required_set()); + assert!(a.val_names.is_empty()); + } + + #[test] + fn pos_req() { + let a = Arg::from_usage("<pos>"); + assert_eq!(a.name, "pos"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_required_set()); + assert!(a.val_names.is_empty()); + } + + #[test] + fn pos_mult() { + let a = Arg::from_usage("[pos]..."); + assert_eq!(a.name, "pos"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(!a.is_required_set()); + assert!(a.val_names.is_empty()); + } + + #[test] + fn pos_req_mult_def_help() { + let a = Arg::from_usage("<pos>... @a 'some help info'"); + assert_eq!(a.name, "pos"); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_required_set()); + assert!(a.val_names.is_empty()); + assert_eq!(a.default_vals, vec![std::ffi::OsStr::new("a")]); + } + + #[test] + fn create_option_with_vals1_def() { + let a = Arg::from_usage("-o <file> <mode> @a 'some help info'"); + assert_eq!(a.name, "o"); + assert!(a.long.is_none()); + assert_eq!(a.short.unwrap(), 'o'); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"file", &"mode"]); + assert_eq!(a.default_vals, vec![std::ffi::OsStr::new("a")]); + } + + #[test] + fn create_option_with_vals4_def() { + let a = Arg::from_usage("[myopt] --opt <file> <mode> @a 'some help info'"); + assert_eq!(a.name, "myopt"); + assert!(a.short.is_none()); + assert_eq!(a.long.unwrap(), "opt"); + assert_eq!(a.help.unwrap(), "some help info"); + assert!(!a.is_multiple_occurrences_set()); + assert!(!a.is_multiple_values_set()); + assert!(a.is_takes_value_set()); + assert!(!a.is_required_set()); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"file", &"mode"]); + assert_eq!(a.default_vals, vec![std::ffi::OsStr::new("a")]); + } + + #[test] + fn nonascii() { + let a = Arg::from_usage("<ASCII> 'üñíčöĐ€'"); + assert_eq!(a.name, "ASCII"); + assert_eq!(a.help, Some("üñíčöĐ€")); + let a = Arg::from_usage("<üñíčöĐ€> 'ASCII'"); + assert_eq!(a.name, "üñíčöĐ€"); + assert_eq!(a.help, Some("ASCII")); + let a = Arg::from_usage("<üñíčöĐ€> 'üñíčöĐ€'"); + assert_eq!(a.name, "üñíčöĐ€"); + assert_eq!(a.help, Some("üñíčöĐ€")); + let a = Arg::from_usage("-ø 'ø'"); + assert_eq!(a.name, "ø"); + assert_eq!(a.short, Some('ø')); + assert_eq!(a.help, Some("ø")); + let a = Arg::from_usage("--üñíčöĐ€ 'Nōṫ ASCII'"); + assert_eq!(a.name, "üñíčöĐ€"); + assert_eq!(a.long, Some("üñíčöĐ€")); + assert_eq!(a.help, Some("Nōṫ ASCII")); + let a = Arg::from_usage("[ñämê] --ôpt=[üñíčöĐ€] 'hælp'"); + assert_eq!(a.name, "ñämê"); + assert_eq!(a.long, Some("ôpt")); + assert_eq!(a.val_names.iter().collect::<Vec<_>>(), [&"üñíčöĐ€"]); + assert_eq!(a.help, Some("hælp")); + } + + #[test] + fn value_names_building_num_vals_from_usage() { + use crate::Command; + let m = Command::new("test") + .arg(Arg::from_usage("--pos <who> <what> <why>")) + .try_get_matches_from(vec!["myprog", "--pos", "val1", "val2", "val3"]); + + assert!(m.is_ok(), "{:?}", m.unwrap_err().kind()); + let m = m.unwrap(); + + assert_eq!( + m.values_of("pos").unwrap().collect::<Vec<_>>(), + ["val1", "val2", "val3"] + ); + } + + #[test] + fn issue_665() { + use crate::{error::ErrorKind, Command}; + // Verify fix for "arg_from_usage(): required values not being enforced when followed by another option" + let res = Command::new("tester") + .arg(Arg::from_usage("-v, --reroll-count=[N] 'Mark the patch series as PATCH vN'")) + .arg( + Arg::from_usage("--subject-prefix [Subject-Prefix] 'Use [Subject-Prefix] instead of the standard [PATCH] prefix'") + .setting(ArgSettings::ForbidEmptyValues) + ) + .try_get_matches_from(vec!["test", "--subject-prefix", "-v", "2"]); + + assert!(res.is_err()); + assert_eq!(res.unwrap_err().kind(), ErrorKind::EmptyValue); + } +} diff --git a/third_party/rust/clap/src/build/value_hint.rs b/third_party/rust/clap/src/build/value_hint.rs new file mode 100644 index 0000000000..7c35d1eb3e --- /dev/null +++ b/third_party/rust/clap/src/build/value_hint.rs @@ -0,0 +1,95 @@ +use std::str::FromStr; + +/// Provide shell with hint on how to complete an argument. +/// +/// See [Arg::value_hint][crate::Arg::value_hint] to set this on an argument. +/// +/// See the `clap_complete` crate for completion script generation. +/// +/// Overview of which hints are supported by which shell: +/// +/// | Hint | zsh | fish[^1]| +/// | ---------------------- | --- | ------- | +/// | `AnyPath` | Yes | Yes | +/// | `FilePath` | Yes | Yes | +/// | `DirPath` | Yes | Yes | +/// | `ExecutablePath` | Yes | Partial | +/// | `CommandName` | Yes | Yes | +/// | `CommandString` | Yes | Partial | +/// | `CommandWithArguments` | Yes | | +/// | `Username` | Yes | Yes | +/// | `Hostname` | Yes | Yes | +/// | `Url` | Yes | | +/// | `EmailAddress` | Yes | | +/// +/// [^1]: fish completions currently only support named arguments (e.g. -o or --opt), not +/// positional arguments. +#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] +#[non_exhaustive] +pub enum ValueHint { + /// Default value if hint is not specified. Follows shell default behavior, which is usually + /// auto-completing filenames. + Unknown, + /// None of the hints below apply. Disables shell completion for this argument. + Other, + /// Any existing path. + AnyPath, + /// Path to a file. + FilePath, + /// Path to a directory. + DirPath, + /// Path to an executable file. + ExecutablePath, + /// Name of a command, without arguments. May be relative to PATH, or full path to executable. + CommandName, + /// A single string containing a command and its arguments. + CommandString, + /// Capture the remaining arguments as a command name and arguments for that command. This is + /// common when writing shell wrappers that execute anther command, for example `sudo` or `env`. + /// + /// This hint is special, the argument must be a positional argument and have + /// [`.multiple_values(true)`] and Command must use [`Command::trailing_var_arg(true)`]. The result is that the + /// command line `my_app ls -la /` will be parsed as `["ls", "-la", "/"]` and clap won't try to + /// parse the `-la` argument itself. + /// + /// [`Command::trailing_var_arg(true)`]: crate::Command::trailing_var_arg + /// [`.multiple_values(true)`]: crate::Arg::multiple_values() + CommandWithArguments, + /// Name of a local operating system user. + Username, + /// Host name of a computer. + /// Shells usually parse `/etc/hosts` and `.ssh/known_hosts` to complete hostnames. + Hostname, + /// Complete web address. + Url, + /// Email address. + EmailAddress, +} + +impl Default for ValueHint { + fn default() -> Self { + ValueHint::Unknown + } +} + +impl FromStr for ValueHint { + type Err = String; + fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> { + Ok(match &*s.to_ascii_lowercase() { + "unknown" => ValueHint::Unknown, + "other" => ValueHint::Other, + "anypath" => ValueHint::AnyPath, + "filepath" => ValueHint::FilePath, + "dirpath" => ValueHint::DirPath, + "executablepath" => ValueHint::ExecutablePath, + "commandname" => ValueHint::CommandName, + "commandstring" => ValueHint::CommandString, + "commandwitharguments" => ValueHint::CommandWithArguments, + "username" => ValueHint::Username, + "hostname" => ValueHint::Hostname, + "url" => ValueHint::Url, + "emailaddress" => ValueHint::EmailAddress, + _ => return Err(format!("unknown ValueHint: `{}`", s)), + }) + } +} diff --git a/third_party/rust/clap/src/derive.rs b/third_party/rust/clap/src/derive.rs new file mode 100644 index 0000000000..110af93727 --- /dev/null +++ b/third_party/rust/clap/src/derive.rs @@ -0,0 +1,512 @@ +//! This module contains traits that are usable with the `#[derive(...)].` +//! macros in [`clap_derive`]. + +use crate::{ArgMatches, Command, Error, PossibleValue}; + +use std::ffi::OsString; + +/// Parse command-line arguments into `Self`. +/// +/// The primary one-stop-shop trait used to create an instance of a `clap` +/// [`Command`], conduct the parsing, and turn the resulting [`ArgMatches`] back +/// into concrete instance of the user struct. +/// +/// This trait is primarily a convenience on top of [`FromArgMatches`] + +/// [`CommandFactory`] which uses those two underlying traits to build the two +/// fundamental functions `parse` which uses the `std::env::args_os` iterator, +/// and `parse_from` which allows the consumer to supply the iterator (along +/// with fallible options for each). +/// +/// See also [`Subcommand`] and [`Args`]. +/// +/// See the +/// [derive reference](https://github.com/clap-rs/clap/blob/v3.1.18/examples/derive_ref/README.md) +/// for attributes and best practices. +/// +/// **NOTE:** Deriving requires the `derive` feature flag +/// +/// # Examples +/// +/// The following example creates a `Context` struct that would be used +/// throughout the application representing the normalized values coming from +/// the CLI. +/// +#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] +#[cfg_attr(feature = "derive", doc = " ```")] +/// /// My super CLI +/// #[derive(clap::Parser)] +/// #[clap(name = "demo")] +/// struct Context { +/// /// More verbose output +/// #[clap(long)] +/// verbose: bool, +/// /// An optional name +/// #[clap(short, long)] +/// name: Option<String>, +/// } +/// ``` +/// +/// The equivalent [`Command`] struct + `From` implementation: +/// +/// ```rust +/// # use clap::{Command, Arg, ArgMatches}; +/// Command::new("demo") +/// .about("My super CLI") +/// .arg(Arg::new("verbose") +/// .long("verbose") +/// .help("More verbose output")) +/// .arg(Arg::new("name") +/// .long("name") +/// .short('n') +/// .help("An optional name") +/// .takes_value(true)); +/// +/// struct Context { +/// verbose: bool, +/// name: Option<String>, +/// } +/// +/// impl From<ArgMatches> for Context { +/// fn from(m: ArgMatches) -> Self { +/// Context { +/// verbose: m.is_present("verbose"), +/// name: m.value_of("name").map(|n| n.to_owned()), +/// } +/// } +/// } +/// ``` +/// +pub trait Parser: FromArgMatches + CommandFactory + Sized { + /// Parse from `std::env::args_os()`, exit on error + fn parse() -> Self { + let matches = <Self as CommandFactory>::command().get_matches(); + let res = + <Self as FromArgMatches>::from_arg_matches(&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 matches = <Self as CommandFactory>::command().try_get_matches()?; + <Self as FromArgMatches>::from_arg_matches(&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 matches = <Self as CommandFactory>::command().get_matches_from(itr); + let res = + <Self as FromArgMatches>::from_arg_matches(&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 matches = <Self as CommandFactory>::command().try_get_matches_from(itr)?; + <Self as FromArgMatches>::from_arg_matches(&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 matches = <Self as CommandFactory>::command_for_update().get_matches_from(itr); + let res = <Self as FromArgMatches>::update_from_arg_matches(self, &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 matches = <Self as CommandFactory>::command_for_update().try_get_matches_from(itr)?; + <Self as FromArgMatches>::update_from_arg_matches(self, &matches) + .map_err(format_error::<Self>) + } + + /// Deprecated, `StructOpt::clap` replaced with [`IntoCommand::command`] (derive as part of + /// [`Parser`]) + #[deprecated( + since = "3.0.0", + note = "`StructOpt::clap` is replaced with `IntoCommand::command` (derived as part of `Parser`)" + )] + #[doc(hidden)] + fn clap<'help>() -> Command<'help> { + <Self as CommandFactory>::command() + } + + /// Deprecated, `StructOpt::from_clap` replaced with [`FromArgMatches::from_arg_matches`] (derive as part of + /// [`Parser`]) + #[deprecated( + since = "3.0.0", + note = "`StructOpt::from_clap` is replaced with `FromArgMatches::from_arg_matches` (derived as part of `Parser`)" + )] + #[doc(hidden)] + fn from_clap(matches: &ArgMatches) -> Self { + <Self as FromArgMatches>::from_arg_matches(matches).unwrap() + } + + /// Deprecated, `StructOpt::from_args` replaced with `Parser::parse` (note the change in derives) + #[deprecated( + since = "3.0.0", + note = "`StructOpt::from_args` is replaced with `Parser::parse` (note the change in derives)" + )] + #[doc(hidden)] + fn from_args() -> Self { + Self::parse() + } + + /// Deprecated, `StructOpt::from_args_safe` replaced with `Parser::try_parse` (note the change in derives) + #[deprecated( + since = "3.0.0", + note = "`StructOpt::from_args_safe` is replaced with `Parser::try_parse` (note the change in derives)" + )] + #[doc(hidden)] + fn from_args_safe() -> Result<Self, Error> { + Self::try_parse() + } + + /// Deprecated, `StructOpt::from_iter` replaced with `Parser::parse_from` (note the change in derives) + #[deprecated( + since = "3.0.0", + note = "`StructOpt::from_iter` is replaced with `Parser::parse_from` (note the change in derives)" + )] + #[doc(hidden)] + fn from_iter<I, T>(itr: I) -> Self + where + I: IntoIterator<Item = T>, + T: Into<OsString> + Clone, + { + Self::parse_from(itr) + } + + /// Deprecated, `StructOpt::from_iter_safe` replaced with `Parser::try_parse_from` (note the + /// change in derives) + #[deprecated( + since = "3.0.0", + note = "`StructOpt::from_iter_safe` is replaced with `Parser::try_parse_from` (note the change in derives)" + )] + #[doc(hidden)] + fn from_iter_safe<I, T>(itr: I) -> Result<Self, Error> + where + I: IntoIterator<Item = T>, + T: Into<OsString> + Clone, + { + Self::try_parse_from(itr) + } +} + +/// Create a [`Command`] relevant for a user-defined container. +/// +/// Derived as part of [`Parser`]. +pub trait CommandFactory: Sized { + /// Build a [`Command`] that can instantiate `Self`. + /// + /// See [`FromArgMatches::from_arg_matches`] for instantiating `Self`. + fn command<'help>() -> Command<'help> { + #[allow(deprecated)] + Self::into_app() + } + /// Deprecated, replaced with `CommandFactory::command` + #[deprecated(since = "3.1.0", note = "Replaced with `CommandFactory::command")] + fn into_app<'help>() -> Command<'help>; + /// Build a [`Command`] that can update `self`. + /// + /// See [`FromArgMatches::update_from_arg_matches`] for updating `self`. + fn command_for_update<'help>() -> Command<'help> { + #[allow(deprecated)] + Self::into_app_for_update() + } + /// Deprecated, replaced with `CommandFactory::command_for_update` + #[deprecated( + since = "3.1.0", + note = "Replaced with `CommandFactory::command_for_update" + )] + fn into_app_for_update<'help>() -> Command<'help>; +} + +/// Converts an instance of [`ArgMatches`] to a user-defined container. +/// +/// Derived as part of [`Parser`], [`Args`], and [`Subcommand`]. +pub trait FromArgMatches: Sized { + /// Instantiate `Self` from [`ArgMatches`], parsing the arguments as needed. + /// + /// Motivation: If our application had two CLI options, `--name + /// <STRING>` and the flag `--debug`, we may create a struct as follows: + /// + #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] + #[cfg_attr(feature = "derive", doc = " ```no_run")] + /// struct Context { + /// name: String, + /// debug: bool + /// } + /// ``` + /// + /// We then need to convert the `ArgMatches` that `clap` generated into our struct. + /// `from_arg_matches` serves as the equivalent of: + /// + #[cfg_attr(not(feature = "derive"), doc = " ```ignore")] + #[cfg_attr(feature = "derive", doc = " ```no_run")] + /// # use clap::ArgMatches; + /// # struct Context { + /// # name: String, + /// # debug: bool + /// # } + /// impl From<ArgMatches> for Context { + /// fn from(m: ArgMatches) -> Self { + /// Context { + /// name: m.value_of("name").unwrap().to_string(), + /// debug: m.is_present("debug"), + /// } + /// } + /// } + /// ``` + fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error>; + + /// Assign values from `ArgMatches` to `self`. + fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error>; +} + +/// Parse a set of arguments into a user-defined container. +/// +/// Implementing this trait lets a parent container delegate argument parsing behavior to `Self`. +/// with: +/// - `#[clap(flatten)] args: ChildArgs`: Attribute can only be used with struct fields that impl +/// `Args`. +/// - `Variant(ChildArgs)`: No attribute is used with enum variants that impl `Args`. +/// +/// See the +/// [derive reference](https://github.com/clap-rs/clap/blob/v3.1.18/examples/derive_ref/README.md) +/// for attributes and best practices. +/// +/// **NOTE:** Deriving requires the `derive` feature flag +/// +/// # Example +/// +#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] +#[cfg_attr(feature = "derive", doc = " ```")] +/// #[derive(clap::Parser)] +/// struct Args { +/// #[clap(flatten)] +/// logging: LogArgs, +/// } +/// +/// #[derive(clap::Args)] +/// struct LogArgs { +/// #[clap(long, short = 'v', parse(from_occurrences))] +/// verbose: i8, +/// } +/// ``` +pub trait Args: FromArgMatches + Sized { + /// Append to [`Command`] so it can instantiate `Self`. + /// + /// See also [`CommandFactory`]. + fn augment_args(cmd: Command<'_>) -> Command<'_>; + /// Append to [`Command`] so it can update `self`. + /// + /// This is used to implement `#[clap(flatten)]` + /// + /// See also [`CommandFactory`]. + fn augment_args_for_update(cmd: Command<'_>) -> Command<'_>; +} + +/// Parse a sub-command into a user-defined enum. +/// +/// Implementing this trait lets a parent container delegate subcommand behavior to `Self`. +/// with: +/// - `#[clap(subcommand)] field: SubCmd`: Attribute can be used with either struct fields or enum +/// variants that impl `Subcommand`. +/// - `#[clap(flatten)] Variant(SubCmd)`: Attribute can only be used with enum variants that impl +/// `Subcommand`. +/// +/// See the +/// [derive reference](https://github.com/clap-rs/clap/blob/v3.1.18/examples/derive_ref/README.md) +/// for attributes and best practices. +/// +/// **NOTE:** Deriving requires the `derive` feature flag +/// +/// # Example +/// +#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] +#[cfg_attr(feature = "derive", doc = " ```")] +/// #[derive(clap::Parser)] +/// struct Args { +/// #[clap(subcommand)] +/// action: Action, +/// } +/// +/// #[derive(clap::Subcommand)] +/// enum Action { +/// Add, +/// Remove, +/// } +/// ``` +pub trait Subcommand: FromArgMatches + Sized { + /// Append to [`Command`] so it can instantiate `Self`. + /// + /// See also [`CommandFactory`]. + fn augment_subcommands(cmd: Command<'_>) -> Command<'_>; + /// Append to [`Command`] so it can update `self`. + /// + /// This is used to implement `#[clap(flatten)]` + /// + /// See also [`CommandFactory`]. + fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_>; + /// Test whether `Self` can parse a specific subcommand + fn has_subcommand(name: &str) -> bool; +} + +/// Parse arguments into enums. +/// +/// When deriving [`Parser`], a field whose type implements `ArgEnum` can have the attribute +/// `#[clap(arg_enum)]` which will +/// - Call [`Arg::possible_values`][crate::Arg::possible_values] +/// - Allowing using the `#[clap(default_value_t)]` attribute without implementing `Display`. +/// +/// See the +/// [derive reference](https://github.com/clap-rs/clap/blob/v3.1.18/examples/derive_ref/README.md) +/// for attributes and best practices. +/// +/// **NOTE:** Deriving requires the `derive` feature flag +/// +/// # Example +/// +#[cfg_attr(not(feature = "derive"), doc = " ```ignore")] +#[cfg_attr(feature = "derive", doc = " ```")] +/// #[derive(clap::Parser)] +/// struct Args { +/// #[clap(arg_enum)] +/// level: Level, +/// } +/// +/// #[derive(clap::ArgEnum, Clone)] +/// enum Level { +/// Debug, +/// Info, +/// Warning, +/// Error, +/// } +/// ``` +pub trait ArgEnum: 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("ArgEnum::value_variants contains only values with a corresponding ArgEnum::to_possible_value") + .matches(input, ignore_case) + }) + .cloned() + .ok_or_else(|| format!("Invalid variant: {}", input)) + } + + /// The canonical argument value. + /// + /// The value is `None` for skipped variants. + fn to_possible_value<'a>(&self) -> Option<PossibleValue<'a>>; +} + +impl<T: Parser> Parser for Box<T> { + fn parse() -> Self { + Box::new(<T as Parser>::parse()) + } + + fn try_parse() -> Result<Self, Error> { + <T as Parser>::try_parse().map(Box::new) + } + + fn parse_from<I, It>(itr: I) -> Self + where + I: IntoIterator<Item = It>, + It: Into<OsString> + Clone, + { + Box::new(<T as Parser>::parse_from(itr)) + } + + fn try_parse_from<I, It>(itr: I) -> Result<Self, Error> + where + I: IntoIterator<Item = It>, + It: Into<OsString> + Clone, + { + <T as Parser>::try_parse_from(itr).map(Box::new) + } +} + +#[allow(deprecated)] +impl<T: CommandFactory> CommandFactory for Box<T> { + fn into_app<'help>() -> Command<'help> { + <T as CommandFactory>::into_app() + } + fn into_app_for_update<'help>() -> Command<'help> { + <T as CommandFactory>::into_app_for_update() + } +} + +impl<T: FromArgMatches> FromArgMatches for Box<T> { + fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> { + <T as FromArgMatches>::from_arg_matches(matches).map(Box::new) + } + fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> { + <T as FromArgMatches>::update_from_arg_matches(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/third_party/rust/clap/src/error/context.rs b/third_party/rust/clap/src/error/context.rs new file mode 100644 index 0000000000..985cd4d70b --- /dev/null +++ b/third_party/rust/clap/src/error/context.rs @@ -0,0 +1,55 @@ +/// Semantics for a piece of error information +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ContextKind { + /// The cause of the error + InvalidSubcommand, + /// The cause of the error + InvalidArg, + /// Existing arguments + PriorArg, + /// Accepted values + ValidValue, + /// Rejected values + InvalidValue, + /// Number of values present + ActualNumValues, + /// Number of allowed values + ExpectedNumValues, + /// Minimum number of allowed values + MinValues, + /// Number of occurrences present + ActualNumOccurrences, + /// Maximum number of allowed occurrences + MaxOccurrences, + /// Potential fix for the user + SuggestedCommand, + /// Potential fix for the user + SuggestedSubcommand, + /// Potential fix for the user + SuggestedArg, + /// Potential fix for the user + SuggestedValue, + /// Trailing argument + TrailingArg, + /// A usage string + Usage, + /// An opaque message to the user + Custom, +} + +/// A piece of error information +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ContextValue { + /// [`ContextKind`] is self-sufficient, no additional information needed + None, + /// A single value + Bool(bool), + /// A single value + String(String), + /// Many values + Strings(Vec<String>), + /// A single value + Number(isize), +} diff --git a/third_party/rust/clap/src/error/kind.rs b/third_party/rust/clap/src/error/kind.rs new file mode 100644 index 0000000000..2c7c422a63 --- /dev/null +++ b/third_party/rust/clap/src/error/kind.rs @@ -0,0 +1,441 @@ +/// Command line argument parser kind of error +#[derive(Debug, Copy, Clone, PartialEq)] +#[non_exhaustive] +pub enum ErrorKind { + /// Occurs when an [`Arg`][crate::Arg] has a set of possible values, + /// and the user provides a value which isn't in that set. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("speed") + /// .possible_value("fast") + /// .possible_value("slow")) + /// .try_get_matches_from(vec!["prog", "other"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidValue); + /// ``` + InvalidValue, + + /// Occurs when a user provides a flag, option, argument or subcommand which isn't defined. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(arg!(--flag "some flag")) + /// .try_get_matches_from(vec!["prog", "--other"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + UnknownArgument, + + /// Occurs when the user provides an unrecognized [`Subcommand`] which meets the threshold for + /// being similar enough to an existing subcommand. + /// If it doesn't meet the threshold, or the 'suggestions' feature is disabled, + /// the more general [`UnknownArgument`] error is returned. + /// + /// # Examples + /// + #[cfg_attr(not(feature = "suggestions"), doc = " ```no_run")] + #[cfg_attr(feature = "suggestions", doc = " ```")] + /// # use clap::{Command, Arg, ErrorKind, }; + /// let result = Command::new("prog") + /// .subcommand(Command::new("config") + /// .about("Used for configuration") + /// .arg(Arg::new("config_file") + /// .help("The configuration file to use"))) + /// .try_get_matches_from(vec!["prog", "confi"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidSubcommand); + /// ``` + /// + /// [`Subcommand`]: crate::Subcommand + /// [`UnknownArgument`]: ErrorKind::UnknownArgument + InvalidSubcommand, + + /// Occurs when the user provides an unrecognized [`Subcommand`] which either + /// doesn't meet the threshold for being similar enough to an existing subcommand, + /// or the 'suggestions' feature is disabled. + /// Otherwise the more detailed [`InvalidSubcommand`] error is returned. + /// + /// This error typically happens when passing additional subcommand names to the `help` + /// subcommand. Otherwise, the more general [`UnknownArgument`] error is used. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind, }; + /// let result = Command::new("prog") + /// .subcommand(Command::new("config") + /// .about("Used for configuration") + /// .arg(Arg::new("config_file") + /// .help("The configuration file to use"))) + /// .try_get_matches_from(vec!["prog", "help", "nothing"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::UnrecognizedSubcommand); + /// ``` + /// + /// [`Subcommand`]: crate::Subcommand + /// [`InvalidSubcommand`]: ErrorKind::InvalidSubcommand + /// [`UnknownArgument`]: ErrorKind::UnknownArgument + UnrecognizedSubcommand, + + /// Occurs when the user provides an empty value for an option that does not allow empty + /// values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("color") + /// .takes_value(true) + /// .forbid_empty_values(true) + /// .long("color")) + /// .try_get_matches_from(vec!["prog", "--color="]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::EmptyValue); + /// ``` + EmptyValue, + + /// Occurs when the user doesn't use equals for an option that requires equal + /// sign to provide values. + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let res = Command::new("prog") + /// .arg(Arg::new("color") + /// .takes_value(true) + /// .require_equals(true) + /// .long("color")) + /// .try_get_matches_from(vec!["prog", "--color", "red"]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals); + /// ``` + NoEquals, + + /// Occurs when the user provides a value for an argument with a custom validation and the + /// value fails that validation. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// fn is_numeric(val: &str) -> Result<(), String> { + /// match val.parse::<i64>() { + /// Ok(..) => Ok(()), + /// Err(..) => Err(String::from("Value wasn't a number!")), + /// } + /// } + /// + /// let result = Command::new("prog") + /// .arg(Arg::new("num") + /// .validator(is_numeric)) + /// .try_get_matches_from(vec!["prog", "NotANumber"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::ValueValidation); + /// ``` + ValueValidation, + + /// Occurs when a user provides more values for an argument than were defined by setting + /// [`Arg::max_values`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("arg") + /// .max_values(2)) + /// .try_get_matches_from(vec!["prog", "too", "many", "values"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooManyValues); + /// ``` + /// [`Arg::max_values`]: crate::Arg::max_values() + TooManyValues, + + /// Occurs when the user provides fewer values for an argument than were defined by setting + /// [`Arg::min_values`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("some_opt") + /// .long("opt") + /// .min_values(3)) + /// .try_get_matches_from(vec!["prog", "--opt", "too", "few"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooFewValues); + /// ``` + /// [`Arg::min_values`]: crate::Arg::min_values() + TooFewValues, + + /// Occurs when a user provides more occurrences for an argument than were defined by setting + /// [`Arg::max_occurrences`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("verbosity") + /// .short('v') + /// .max_occurrences(2)) + /// .try_get_matches_from(vec!["prog", "-vvv"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::TooManyOccurrences); + /// ``` + /// [`Arg::max_occurrences`]: crate::Arg::max_occurrences() + TooManyOccurrences, + + /// Occurs when the user provides a different number of values for an argument than what's + /// been defined by setting [`Arg::number_of_values`] or than was implicitly set by + /// [`Arg::value_names`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("some_opt") + /// .long("opt") + /// .takes_value(true) + /// .number_of_values(2)) + /// .try_get_matches_from(vec!["prog", "--opt", "wrong"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::WrongNumberOfValues); + /// ``` + /// + /// [`Arg::number_of_values`]: crate::Arg::number_of_values() + /// [`Arg::value_names`]: crate::Arg::value_names() + WrongNumberOfValues, + + /// Occurs when the user provides two values which conflict with each other and can't be used + /// together. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("debug") + /// .long("debug") + /// .conflicts_with("color")) + /// .arg(Arg::new("color") + /// .long("color")) + /// .try_get_matches_from(vec!["prog", "--debug", "--color"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::ArgumentConflict); + /// ``` + ArgumentConflict, + + /// Occurs when the user does not provide one or more required arguments. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("debug") + /// .required(true)) + /// .try_get_matches_from(vec!["prog"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + MissingRequiredArgument, + + /// Occurs when a subcommand is required (as defined by [`Command::subcommand_required`]), + /// but the user does not provide one. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ErrorKind}; + /// let err = Command::new("prog") + /// .subcommand_required(true) + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); + /// # ; + /// ``` + /// + /// [`Command::subcommand_required`]: crate::Command::subcommand_required + MissingSubcommand, + + /// Occurs when the user provides multiple values to an argument which doesn't allow that. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .arg(Arg::new("debug") + /// .long("debug") + /// .multiple_occurrences(false)) + /// .try_get_matches_from(vec!["prog", "--debug", "--debug"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::UnexpectedMultipleUsage); + /// ``` + UnexpectedMultipleUsage, + + /// Occurs when the user provides a value containing invalid UTF-8. + /// + /// To allow arbitrary data + /// - Set [`Arg::allow_invalid_utf8`] for argument values + /// - Set [`Command::allow_invalid_utf8_for_external_subcommands`] for external-subcommand + /// values + /// + /// # Platform Specific + /// + /// Non-Windows platforms only (such as Linux, Unix, OSX, etc.) + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{Command, Arg, ErrorKind}; + /// # use std::os::unix::ffi::OsStringExt; + /// # use std::ffi::OsString; + /// let result = Command::new("prog") + /// .arg(Arg::new("utf8") + /// .short('u') + /// .takes_value(true)) + /// .try_get_matches_from(vec![OsString::from("myprog"), + /// OsString::from("-u"), + /// OsString::from_vec(vec![0xE9])]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidUtf8); + /// ``` + /// + /// [`Arg::allow_invalid_utf8`]: crate::Arg::allow_invalid_utf8 + /// [`Command::allow_invalid_utf8_for_external_subcommands`]: crate::Command::allow_invalid_utf8_for_external_subcommands + InvalidUtf8, + + /// Not a true "error" as it means `--help` or similar was used. + /// The help message will be sent to `stdout`. + /// + /// **Note**: If the help is displayed due to an error (such as missing subcommands) it will + /// be sent to `stderr` instead of `stdout`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .try_get_matches_from(vec!["prog", "--help"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayHelp); + /// ``` + DisplayHelp, + + /// Occurs when either an argument or a [`Subcommand`] is required, as defined by + /// [`Command::arg_required_else_help`] , but the user did not provide + /// one. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind, }; + /// let result = Command::new("prog") + /// .arg_required_else_help(true) + /// .subcommand(Command::new("config") + /// .about("Used for configuration") + /// .arg(Arg::new("config_file") + /// .help("The configuration file to use"))) + /// .try_get_matches_from(vec!["prog"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand); + /// ``` + /// + /// [`Subcommand`]: crate::Subcommand + /// [`Command::arg_required_else_help`]: crate::Command::arg_required_else_help + DisplayHelpOnMissingArgumentOrSubcommand, + + /// Not a true "error" as it means `--version` or similar was used. + /// The message will be sent to `stdout`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ErrorKind}; + /// let result = Command::new("prog") + /// .version("3.0") + /// .try_get_matches_from(vec!["prog", "--version"]); + /// assert!(result.is_err()); + /// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayVersion); + /// ``` + DisplayVersion, + + /// Occurs when using the [`ArgMatches::value_of_t`] and friends to convert an argument value + /// into type `T`, but the argument you requested wasn't used. I.e. you asked for an argument + /// with name `config` to be converted, but `config` wasn't used by the user. + /// + /// [`ArgMatches::value_of_t`]: crate::ArgMatches::value_of_t() + ArgumentNotFound, + + /// Represents an [I/O error]. + /// Can occur when writing to `stderr` or `stdout` or reading a configuration file. + /// + /// [I/O error]: std::io::Error + Io, + + /// Represents a [Format error] (which is a part of [`Display`]). + /// Typically caused by writing to `stderr` or `stdout`. + /// + /// [`Display`]: std::fmt::Display + /// [Format error]: std::fmt::Error + Format, +} + +impl ErrorKind { + /// End-user description of the error case, where relevant + pub fn as_str(self) -> Option<&'static str> { + match self { + Self::InvalidValue => Some("One of the values isn't valid for an argument"), + Self::UnknownArgument => { + Some("Found an argument which wasn't expected or isn't valid in this context") + } + Self::InvalidSubcommand => Some("A subcommand wasn't recognized"), + Self::UnrecognizedSubcommand => Some("A subcommand wasn't recognized"), + Self::EmptyValue => Some("An argument requires a value but none was supplied"), + Self::NoEquals => Some("Equal is needed when assigning values to one of the arguments"), + Self::ValueValidation => Some("Invalid for for one of the arguments"), + Self::TooManyValues => Some("An argument received an unexpected value"), + Self::TooFewValues => Some("An argument requires more values"), + Self::TooManyOccurrences => Some("An argument occurred too many times"), + Self::WrongNumberOfValues => Some("An argument received too many or too few values"), + Self::ArgumentConflict => { + Some("An argument cannot be used with one or more of the other specified arguments") + } + Self::MissingRequiredArgument => { + Some("One or more required arguments were not provided") + } + Self::MissingSubcommand => Some("A subcommand is required but one was not provided"), + Self::UnexpectedMultipleUsage => { + Some("An argument was provided more than once but cannot be used multiple times") + } + Self::InvalidUtf8 => Some("Invalid UTF-8 was detected in one or more arguments"), + Self::DisplayHelp => None, + Self::DisplayHelpOnMissingArgumentOrSubcommand => None, + Self::DisplayVersion => None, + Self::ArgumentNotFound => Some("An argument wasn't found"), + Self::Io => None, + Self::Format => None, + } + } +} + +impl std::fmt::Display for ErrorKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.as_str().unwrap_or_default().fmt(f) + } +} diff --git a/third_party/rust/clap/src/error/mod.rs b/third_party/rust/clap/src/error/mod.rs new file mode 100644 index 0000000000..5c8a18e397 --- /dev/null +++ b/third_party/rust/clap/src/error/mod.rs @@ -0,0 +1,1181 @@ +//! Error reporting +#![allow(deprecated)] + +// Std +use std::{ + borrow::Cow, + convert::From, + error, + fmt::{self, Debug, Display, Formatter}, + io::{self, BufRead}, + result::Result as StdResult, +}; + +// Internal +use crate::{ + build::Arg, + output::fmt::Colorizer, + output::fmt::Stream, + parse::features::suggestions, + util::{color::ColorChoice, safe_exit, SUCCESS_CODE, USAGE_CODE}, + AppSettings, Command, +}; + +mod context; +mod kind; + +pub use context::ContextKind; +pub use context::ContextValue; +pub use kind::ErrorKind; + +/// Short hand for [`Result`] type +/// +/// [`Result`]: std::result::Result +pub type Result<T, E = Error> = StdResult<T, E>; + +/// Command Line Argument Parser Error +/// +/// See [`Command::error`] to create an error. +/// +/// [`Command::error`]: crate::Command::error +#[derive(Debug)] +pub struct Error { + inner: Box<ErrorInner>, + /// Deprecated, replaced with [`Error::kind()`] + #[deprecated(since = "3.1.0", note = "Replaced with `Error::kind()`")] + pub kind: ErrorKind, + /// Deprecated, replaced with [`Error::context()`] + #[deprecated(since = "3.1.0", note = "Replaced with `Error::context()`")] + pub info: Vec<String>, +} + +#[derive(Debug)] +struct ErrorInner { + kind: ErrorKind, + context: Vec<(ContextKind, ContextValue)>, + message: Option<Message>, + source: Option<Box<dyn error::Error + Send + Sync>>, + help_flag: Option<&'static str>, + color_when: ColorChoice, + wait_on_exit: bool, + backtrace: Option<Backtrace>, +} + +impl Error { + /// Create an unformatted error + /// + /// This is for you need to pass the error up to + /// a place that has access to the `Command` at which point you can call [`Error::format`]. + /// + /// Prefer [`Command::error`] for generating errors. + /// + /// [`Command::error`]: crate::Command::error + pub fn raw(kind: ErrorKind, message: impl std::fmt::Display) -> Self { + Self::new(kind).set_message(message.to_string()) + } + + /// Format the existing message with the Command's context + #[must_use] + pub fn format(mut self, cmd: &mut Command) -> Self { + cmd._build_self(); + let usage = cmd.render_usage(); + if let Some(message) = self.inner.message.as_mut() { + message.format(cmd, usage); + } + self.with_cmd(cmd) + } + + /// Type of error for programmatic processing + pub fn kind(&self) -> ErrorKind { + self.inner.kind + } + + /// Additional information to further qualify the error + pub fn context(&self) -> impl Iterator<Item = (ContextKind, &ContextValue)> { + self.inner.context.iter().map(|(k, v)| (*k, v)) + } + + /// Should the message be written to `stdout` or not? + #[inline] + pub fn use_stderr(&self) -> bool { + self.stream() == Stream::Stderr + } + + pub(crate) fn stream(&self) -> Stream { + match self.kind() { + ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => Stream::Stdout, + _ => Stream::Stderr, + } + } + + /// Prints the error and exits. + /// + /// Depending on the error kind, this either prints to `stderr` and exits with a status of `2` + /// or prints to `stdout` and exits with a status of `0`. + pub fn exit(&self) -> ! { + if self.use_stderr() { + // Swallow broken pipe errors + let _ = self.print(); + + if self.inner.wait_on_exit { + wlnerr!("\nPress [ENTER] / [RETURN] to continue..."); + let mut s = String::new(); + let i = io::stdin(); + i.lock().read_line(&mut s).unwrap(); + } + + safe_exit(USAGE_CODE); + } + + // Swallow broken pipe errors + let _ = self.print(); + safe_exit(SUCCESS_CODE) + } + + /// Prints formatted and colored error to `stdout` or `stderr` according to its error kind + /// + /// # Example + /// ```no_run + /// use clap::Command; + /// + /// match Command::new("Command").try_get_matches() { + /// Ok(matches) => { + /// // do_something + /// }, + /// Err(err) => { + /// err.print().expect("Error writing Error"); + /// // do_something + /// }, + /// }; + /// ``` + pub fn print(&self) -> io::Result<()> { + self.formatted().print() + } + + /// Deprecated, replaced with [`Command::error`] + /// + /// [`Command::error`]: crate::Command::error + #[deprecated(since = "3.0.0", note = "Replaced with `Command::error`")] + #[doc(hidden)] + pub fn with_description(description: String, kind: ErrorKind) -> Self { + Error::raw(kind, description) + } + + fn new(kind: ErrorKind) -> Self { + Self { + inner: Box::new(ErrorInner { + kind, + context: Vec::new(), + message: None, + source: None, + help_flag: None, + color_when: ColorChoice::Never, + wait_on_exit: false, + backtrace: Backtrace::new(), + }), + kind, + info: vec![], + } + } + + #[inline(never)] + fn for_app(kind: ErrorKind, cmd: &Command, colorizer: Colorizer, info: Vec<String>) -> Self { + Self::new(kind) + .set_message(colorizer) + .with_cmd(cmd) + .set_info(info) + } + + pub(crate) fn with_cmd(self, cmd: &Command) -> Self { + self.set_wait_on_exit(cmd.is_set(AppSettings::WaitOnError)) + .set_color(cmd.get_color()) + .set_help_flag(get_help_flag(cmd)) + } + + pub(crate) fn set_message(mut self, message: impl Into<Message>) -> Self { + self.inner.message = Some(message.into()); + self + } + + pub(crate) fn set_info(mut self, info: Vec<String>) -> Self { + self.info = info; + self + } + + pub(crate) fn set_source(mut self, source: Box<dyn error::Error + Send + Sync>) -> Self { + self.inner.source = Some(source); + self + } + + pub(crate) fn set_color(mut self, color_when: ColorChoice) -> Self { + self.inner.color_when = color_when; + self + } + + pub(crate) fn set_help_flag(mut self, help_flag: Option<&'static str>) -> Self { + self.inner.help_flag = help_flag; + self + } + + pub(crate) fn set_wait_on_exit(mut self, yes: bool) -> Self { + self.inner.wait_on_exit = yes; + self + } + + /// Does not verify if `ContextKind` is already present + #[inline(never)] + pub(crate) fn insert_context_unchecked( + mut self, + kind: ContextKind, + value: ContextValue, + ) -> Self { + self.inner.context.push((kind, value)); + self + } + + /// Does not verify if `ContextKind` is already present + #[inline(never)] + pub(crate) fn extend_context_unchecked<const N: usize>( + mut self, + context: [(ContextKind, ContextValue); N], + ) -> Self { + self.inner.context.extend(context); + self + } + + #[inline(never)] + fn get_context(&self, kind: ContextKind) -> Option<&ContextValue> { + self.inner + .context + .iter() + .find_map(|(k, v)| (*k == kind).then(|| v)) + } + + pub(crate) fn display_help(cmd: &Command, colorizer: Colorizer) -> Self { + Self::for_app(ErrorKind::DisplayHelp, cmd, colorizer, vec![]) + } + + pub(crate) fn display_help_error(cmd: &Command, colorizer: Colorizer) -> Self { + Self::for_app( + ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand, + cmd, + colorizer, + vec![], + ) + } + + pub(crate) fn display_version(cmd: &Command, colorizer: Colorizer) -> Self { + Self::for_app(ErrorKind::DisplayVersion, cmd, colorizer, vec![]) + } + + pub(crate) fn argument_conflict( + cmd: &Command, + arg: &Arg, + mut others: Vec<String>, + usage: String, + ) -> Self { + let info = others.clone(); + let others = match others.len() { + 0 => ContextValue::None, + 1 => ContextValue::String(others.pop().unwrap()), + _ => ContextValue::Strings(others), + }; + Self::new(ErrorKind::ArgumentConflict) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + ( + ContextKind::InvalidArg, + ContextValue::String(arg.to_string()), + ), + (ContextKind::PriorArg, others), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn empty_value(cmd: &Command, good_vals: &[&str], arg: &Arg, usage: String) -> Self { + let info = vec![arg.to_string()]; + let mut err = Self::new(ErrorKind::EmptyValue) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + ( + ContextKind::InvalidArg, + ContextValue::String(arg.to_string()), + ), + (ContextKind::Usage, ContextValue::String(usage)), + ]); + if !good_vals.is_empty() { + err = err.insert_context_unchecked( + ContextKind::ValidValue, + ContextValue::Strings(good_vals.iter().map(|s| (*s).to_owned()).collect()), + ); + } + err + } + + pub(crate) fn no_equals(cmd: &Command, arg: String, usage: String) -> Self { + let info = vec![arg.to_string()]; + Self::new(ErrorKind::NoEquals) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn invalid_value( + cmd: &Command, + bad_val: String, + good_vals: &[&str], + arg: &Arg, + usage: String, + ) -> Self { + let mut info = vec![arg.to_string(), bad_val.clone()]; + info.extend(good_vals.iter().map(|s| (*s).to_owned())); + + let suggestion = suggestions::did_you_mean(&bad_val, good_vals.iter()).pop(); + let mut err = Self::new(ErrorKind::InvalidValue) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + ( + ContextKind::InvalidArg, + ContextValue::String(arg.to_string()), + ), + (ContextKind::InvalidValue, ContextValue::String(bad_val)), + ( + ContextKind::ValidValue, + ContextValue::Strings(good_vals.iter().map(|s| (*s).to_owned()).collect()), + ), + (ContextKind::Usage, ContextValue::String(usage)), + ]); + if let Some(suggestion) = suggestion { + err = err.insert_context_unchecked( + ContextKind::SuggestedValue, + ContextValue::String(suggestion), + ); + } + err + } + + pub(crate) fn invalid_subcommand( + cmd: &Command, + subcmd: String, + did_you_mean: String, + name: String, + usage: String, + ) -> Self { + let info = vec![subcmd.clone()]; + let suggestion = format!("{} -- {}", name, subcmd); + Self::new(ErrorKind::InvalidSubcommand) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidSubcommand, ContextValue::String(subcmd)), + ( + ContextKind::SuggestedSubcommand, + ContextValue::String(did_you_mean), + ), + ( + ContextKind::SuggestedCommand, + ContextValue::String(suggestion), + ), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn unrecognized_subcommand(cmd: &Command, subcmd: String, usage: String) -> Self { + let info = vec![subcmd.clone()]; + Self::new(ErrorKind::UnrecognizedSubcommand) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidSubcommand, ContextValue::String(subcmd)), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn missing_required_argument( + cmd: &Command, + required: Vec<String>, + usage: String, + ) -> Self { + let info = required.clone(); + Self::new(ErrorKind::MissingRequiredArgument) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::Strings(required)), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn missing_subcommand(cmd: &Command, name: String, usage: String) -> Self { + let info = vec![]; + Self::new(ErrorKind::MissingSubcommand) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidSubcommand, ContextValue::String(name)), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn invalid_utf8(cmd: &Command, usage: String) -> Self { + let info = vec![]; + Self::new(ErrorKind::InvalidUtf8) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([(ContextKind::Usage, ContextValue::String(usage))]) + } + + pub(crate) fn too_many_occurrences( + cmd: &Command, + arg: &Arg, + max_occurs: usize, + curr_occurs: usize, + usage: String, + ) -> Self { + let info = vec![ + arg.to_string(), + curr_occurs.to_string(), + max_occurs.to_string(), + ]; + Self::new(ErrorKind::TooManyOccurrences) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + ( + ContextKind::InvalidArg, + ContextValue::String(arg.to_string()), + ), + ( + ContextKind::MaxOccurrences, + ContextValue::Number(max_occurs as isize), + ), + ( + ContextKind::ActualNumValues, + ContextValue::Number(curr_occurs as isize), + ), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn too_many_values(cmd: &Command, val: String, arg: String, usage: String) -> Self { + let info = vec![arg.to_string(), val.clone()]; + Self::new(ErrorKind::TooManyValues) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + (ContextKind::InvalidValue, ContextValue::String(val)), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn too_few_values( + cmd: &Command, + arg: &Arg, + min_vals: usize, + curr_vals: usize, + usage: String, + ) -> Self { + let info = vec![arg.to_string(), curr_vals.to_string(), min_vals.to_string()]; + Self::new(ErrorKind::TooFewValues) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + ( + ContextKind::InvalidArg, + ContextValue::String(arg.to_string()), + ), + ( + ContextKind::MinValues, + ContextValue::Number(min_vals as isize), + ), + ( + ContextKind::ActualNumValues, + ContextValue::Number(curr_vals as isize), + ), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn value_validation( + arg: String, + val: String, + err: Box<dyn error::Error + Send + Sync>, + ) -> Self { + let info = vec![arg.to_string(), val.to_string(), err.to_string()]; + Self::new(ErrorKind::ValueValidation) + .set_info(info) + .set_source(err) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + (ContextKind::InvalidValue, ContextValue::String(val)), + ]) + } + + pub(crate) fn wrong_number_of_values( + cmd: &Command, + arg: &Arg, + num_vals: usize, + curr_vals: usize, + usage: String, + ) -> Self { + let info = vec![arg.to_string(), curr_vals.to_string(), num_vals.to_string()]; + Self::new(ErrorKind::WrongNumberOfValues) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + ( + ContextKind::InvalidArg, + ContextValue::String(arg.to_string()), + ), + ( + ContextKind::ExpectedNumValues, + ContextValue::Number(num_vals as isize), + ), + ( + ContextKind::ActualNumValues, + ContextValue::Number(curr_vals as isize), + ), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn unexpected_multiple_usage(cmd: &Command, arg: &Arg, usage: String) -> Self { + let info = vec![arg.to_string()]; + Self::new(ErrorKind::UnexpectedMultipleUsage) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + ( + ContextKind::InvalidArg, + ContextValue::String(arg.to_string()), + ), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn unknown_argument( + cmd: &Command, + arg: String, + did_you_mean: Option<(String, Option<String>)>, + usage: String, + ) -> Self { + let info = vec![arg.to_string()]; + let mut err = Self::new(ErrorKind::UnknownArgument) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + (ContextKind::Usage, ContextValue::String(usage)), + ]); + if let Some((flag, sub)) = did_you_mean { + err = err.insert_context_unchecked( + ContextKind::SuggestedArg, + ContextValue::String(format!("--{}", flag)), + ); + if let Some(sub) = sub { + err = err.insert_context_unchecked( + ContextKind::SuggestedSubcommand, + ContextValue::String(sub), + ); + } + } + err + } + + pub(crate) fn unnecessary_double_dash(cmd: &Command, arg: String, usage: String) -> Self { + let info = vec![arg.to_string()]; + Self::new(ErrorKind::UnknownArgument) + .with_cmd(cmd) + .set_info(info) + .extend_context_unchecked([ + (ContextKind::InvalidArg, ContextValue::String(arg)), + (ContextKind::TrailingArg, ContextValue::Bool(true)), + (ContextKind::Usage, ContextValue::String(usage)), + ]) + } + + pub(crate) fn argument_not_found_auto(arg: String) -> Self { + let info = vec![arg.to_string()]; + Self::new(ErrorKind::ArgumentNotFound) + .set_info(info) + .extend_context_unchecked([(ContextKind::InvalidArg, ContextValue::String(arg))]) + } + + fn formatted(&self) -> Cow<'_, Colorizer> { + if let Some(message) = self.inner.message.as_ref() { + message.formatted() + } else { + let mut c = Colorizer::new(self.stream(), self.inner.color_when); + + start_error(&mut c); + + if !self.write_dynamic_context(&mut c) { + if let Some(msg) = self.kind().as_str() { + c.none(msg.to_owned()); + } else if let Some(source) = self.inner.source.as_ref() { + c.none(source.to_string()); + } else { + c.none("Unknown cause"); + } + } + + let usage = self.get_context(ContextKind::Usage); + if let Some(ContextValue::String(usage)) = usage { + put_usage(&mut c, usage); + } + + try_help(&mut c, self.inner.help_flag); + + Cow::Owned(c) + } + } + + #[must_use] + fn write_dynamic_context(&self, c: &mut Colorizer) -> bool { + match self.kind() { + ErrorKind::ArgumentConflict => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let prior_arg = self.get_context(ContextKind::PriorArg); + if let (Some(ContextValue::String(invalid_arg)), Some(prior_arg)) = + (invalid_arg, prior_arg) + { + c.none("The argument '"); + c.warning(invalid_arg); + c.none("' cannot be used with"); + + match prior_arg { + ContextValue::Strings(values) => { + c.none(":"); + for v in values { + c.none("\n "); + c.warning(&**v); + } + } + ContextValue::String(value) => { + c.none(" '"); + c.warning(value); + c.none("'"); + } + _ => { + c.none(" one or more of the other specified arguments"); + } + } + true + } else { + false + } + } + ErrorKind::EmptyValue => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::String(invalid_arg)) = invalid_arg { + c.none("The argument '"); + c.warning(invalid_arg); + c.none("' requires a value but none was supplied"); + + let possible_values = self.get_context(ContextKind::ValidValue); + if let Some(ContextValue::Strings(possible_values)) = possible_values { + c.none("\n\t[possible values: "); + if let Some((last, elements)) = possible_values.split_last() { + for v in elements { + c.good(escape(v)); + c.none(", "); + } + c.good(escape(last)); + } + c.none("]"); + } + true + } else { + false + } + } + ErrorKind::NoEquals => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::String(invalid_arg)) = invalid_arg { + c.none("Equal sign is needed when assigning values to '"); + c.warning(invalid_arg); + c.none("'."); + true + } else { + false + } + } + ErrorKind::InvalidValue => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let invalid_value = self.get_context(ContextKind::InvalidValue); + if let ( + Some(ContextValue::String(invalid_arg)), + Some(ContextValue::String(invalid_value)), + ) = (invalid_arg, invalid_value) + { + c.none(quote(invalid_value)); + c.none(" isn't a valid value for '"); + c.warning(invalid_arg); + c.none("'"); + + let possible_values = self.get_context(ContextKind::ValidValue); + if let Some(ContextValue::Strings(possible_values)) = possible_values { + c.none("\n\t[possible values: "); + if let Some((last, elements)) = possible_values.split_last() { + for v in elements { + c.good(escape(v)); + c.none(", "); + } + c.good(escape(last)); + } + c.none("]"); + } + + let suggestion = self.get_context(ContextKind::SuggestedValue); + if let Some(ContextValue::String(suggestion)) = suggestion { + c.none("\n\n\tDid you mean "); + c.good(quote(suggestion)); + c.none("?"); + } + true + } else { + false + } + } + ErrorKind::InvalidSubcommand => { + let invalid_sub = self.get_context(ContextKind::InvalidSubcommand); + if let Some(ContextValue::String(invalid_sub)) = invalid_sub { + c.none("The subcommand '"); + c.warning(invalid_sub); + c.none("' wasn't recognized"); + + let valid_sub = self.get_context(ContextKind::SuggestedSubcommand); + if let Some(ContextValue::String(valid_sub)) = valid_sub { + c.none("\n\n\tDid you mean "); + c.good(valid_sub); + c.none("?"); + } + + let suggestion = self.get_context(ContextKind::SuggestedCommand); + if let Some(ContextValue::String(suggestion)) = suggestion { + c.none( + "\n\nIf you believe you received this message in error, try re-running with '", + ); + c.good(suggestion); + c.none("'"); + } + true + } else { + false + } + } + ErrorKind::UnrecognizedSubcommand => { + let invalid_sub = self.get_context(ContextKind::InvalidSubcommand); + if let Some(ContextValue::String(invalid_sub)) = invalid_sub { + c.none("The subcommand '"); + c.warning(invalid_sub); + c.none("' wasn't recognized"); + true + } else { + false + } + } + ErrorKind::MissingRequiredArgument => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::Strings(invalid_arg)) = invalid_arg { + c.none("The following required arguments were not provided:"); + for v in invalid_arg { + c.none("\n "); + c.good(&**v); + } + true + } else { + false + } + } + ErrorKind::MissingSubcommand => { + let invalid_sub = self.get_context(ContextKind::InvalidSubcommand); + if let Some(ContextValue::String(invalid_sub)) = invalid_sub { + c.none("'"); + c.warning(invalid_sub); + c.none("' requires a subcommand but one was not provided"); + true + } else { + false + } + } + ErrorKind::InvalidUtf8 => false, + ErrorKind::TooManyOccurrences => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let actual_num_occurs = self.get_context(ContextKind::ActualNumOccurrences); + let max_occurs = self.get_context(ContextKind::MaxOccurrences); + if let ( + Some(ContextValue::String(invalid_arg)), + Some(ContextValue::Number(actual_num_occurs)), + Some(ContextValue::Number(max_occurs)), + ) = (invalid_arg, actual_num_occurs, max_occurs) + { + let were_provided = Error::singular_or_plural(*actual_num_occurs as usize); + c.none("The argument '"); + c.warning(invalid_arg); + c.none("' allows at most "); + c.warning(max_occurs.to_string()); + c.none(" occurrences but "); + c.warning(actual_num_occurs.to_string()); + c.none(were_provided); + true + } else { + false + } + } + ErrorKind::TooManyValues => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let invalid_value = self.get_context(ContextKind::InvalidValue); + if let ( + Some(ContextValue::String(invalid_arg)), + Some(ContextValue::String(invalid_value)), + ) = (invalid_arg, invalid_value) + { + c.none("The value '"); + c.warning(invalid_value); + c.none("' was provided to '"); + c.warning(invalid_arg); + c.none("' but it wasn't expecting any more values"); + true + } else { + false + } + } + ErrorKind::TooFewValues => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let actual_num_values = self.get_context(ContextKind::ActualNumValues); + let min_values = self.get_context(ContextKind::MinValues); + if let ( + Some(ContextValue::String(invalid_arg)), + Some(ContextValue::Number(actual_num_values)), + Some(ContextValue::Number(min_values)), + ) = (invalid_arg, actual_num_values, min_values) + { + let were_provided = Error::singular_or_plural(*actual_num_values as usize); + c.none("The argument '"); + c.warning(invalid_arg); + c.none("' requires at least "); + c.warning(min_values.to_string()); + c.none(" values but only "); + c.warning(actual_num_values.to_string()); + c.none(were_provided); + true + } else { + false + } + } + ErrorKind::ValueValidation => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let invalid_value = self.get_context(ContextKind::InvalidValue); + if let ( + Some(ContextValue::String(invalid_arg)), + Some(ContextValue::String(invalid_value)), + ) = (invalid_arg, invalid_value) + { + c.none("Invalid value "); + c.warning(quote(invalid_value)); + c.none(" for '"); + c.warning(invalid_arg); + if let Some(source) = self.inner.source.as_deref() { + c.none("': "); + c.none(source.to_string()); + } else { + c.none("'"); + } + true + } else { + false + } + } + ErrorKind::WrongNumberOfValues => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + let actual_num_values = self.get_context(ContextKind::ActualNumValues); + let num_values = self.get_context(ContextKind::ExpectedNumValues); + if let ( + Some(ContextValue::String(invalid_arg)), + Some(ContextValue::Number(actual_num_values)), + Some(ContextValue::Number(num_values)), + ) = (invalid_arg, actual_num_values, num_values) + { + let were_provided = Error::singular_or_plural(*actual_num_values as usize); + c.none("The argument '"); + c.warning(invalid_arg); + c.none("' requires "); + c.warning(num_values.to_string()); + c.none(" values, but "); + c.warning(actual_num_values.to_string()); + c.none(were_provided); + true + } else { + false + } + } + ErrorKind::UnexpectedMultipleUsage => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::String(invalid_arg)) = invalid_arg { + c.none("The argument '"); + c.warning(invalid_arg.to_string()); + c.none("' was provided more than once, but cannot be used multiple times"); + true + } else { + false + } + } + ErrorKind::UnknownArgument => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::String(invalid_arg)) = invalid_arg { + c.none("Found argument '"); + c.warning(invalid_arg.to_string()); + c.none("' which wasn't expected, or isn't valid in this context"); + + let valid_sub = self.get_context(ContextKind::SuggestedSubcommand); + let valid_arg = self.get_context(ContextKind::SuggestedArg); + match (valid_sub, valid_arg) { + ( + Some(ContextValue::String(valid_sub)), + Some(ContextValue::String(valid_arg)), + ) => { + c.none("\n\n\tDid you mean "); + c.none("to put '"); + c.good(valid_arg); + c.none("' after the subcommand '"); + c.good(valid_sub); + c.none("'?"); + } + (None, Some(ContextValue::String(valid_arg))) => { + c.none("\n\n\tDid you mean '"); + c.good(valid_arg); + c.none("'?"); + } + (_, _) => {} + } + + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::String(invalid_arg)) = invalid_arg { + if invalid_arg.starts_with('-') { + c.none(format!( + "\n\n\tIf you tried to supply `{}` as a value rather than a flag, use `-- {}`", + invalid_arg, invalid_arg + )); + } + + let trailing_arg = self.get_context(ContextKind::TrailingArg); + if trailing_arg == Some(&ContextValue::Bool(true)) { + c.none(format!( + "\n\n\tIf you tried to supply `{}` as a subcommand, remove the '--' before it.", + invalid_arg + )); + } + } + true + } else { + false + } + } + ErrorKind::ArgumentNotFound => { + let invalid_arg = self.get_context(ContextKind::InvalidArg); + if let Some(ContextValue::String(invalid_arg)) = invalid_arg { + c.none("The argument '"); + c.warning(invalid_arg.to_string()); + c.none("' wasn't found"); + true + } else { + false + } + } + ErrorKind::DisplayHelp + | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand + | ErrorKind::DisplayVersion + | ErrorKind::Io + | ErrorKind::Format => false, + } + } + + /// Returns the singular or plural form on the verb to be based on the argument's value. + fn singular_or_plural(n: usize) -> &'static str { + if n > 1 { + " were provided" + } else { + " was provided" + } + } +} + +impl From<io::Error> for Error { + fn from(e: io::Error) -> Self { + Error::raw(ErrorKind::Io, e) + } +} + +impl From<fmt::Error> for Error { + fn from(e: fmt::Error) -> Self { + Error::raw(ErrorKind::Format, e) + } +} + +impl error::Error for Error { + #[allow(trivial_casts)] + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + self.inner.source.as_ref().map(|e| e.as_ref() as _) + } +} + +impl Display for Error { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + // Assuming `self.message` already has a trailing newline, from `try_help` or similar + write!(f, "{}", self.formatted())?; + if let Some(backtrace) = self.inner.backtrace.as_ref() { + writeln!(f)?; + writeln!(f, "Backtrace:")?; + writeln!(f, "{}", backtrace)?; + } + Ok(()) + } +} + +fn start_error(c: &mut Colorizer) { + c.error("error:"); + c.none(" "); +} + +fn put_usage(c: &mut Colorizer, usage: impl Into<String>) { + c.none("\n\n"); + c.none(usage); +} + +fn get_help_flag(cmd: &Command) -> Option<&'static str> { + if !cmd.is_disable_help_flag_set() { + Some("--help") + } else if cmd.has_subcommands() && !cmd.is_disable_help_subcommand_set() { + Some("help") + } else { + None + } +} + +fn try_help(c: &mut Colorizer, help: Option<&str>) { + if let Some(help) = help { + c.none("\n\nFor more information try "); + c.good(help); + c.none("\n"); + } else { + c.none("\n"); + } +} + +fn quote(s: impl AsRef<str>) -> String { + let s = s.as_ref(); + format!("{:?}", s) +} + +fn escape(s: impl AsRef<str>) -> String { + let s = s.as_ref(); + if s.contains(char::is_whitespace) { + quote(s) + } else { + s.to_owned() + } +} + +#[derive(Clone, Debug)] +pub(crate) enum Message { + Raw(String), + Formatted(Colorizer), +} + +impl Message { + fn format(&mut self, cmd: &Command, usage: String) { + match self { + Message::Raw(s) => { + let mut c = Colorizer::new(Stream::Stderr, cmd.get_color()); + + let mut message = String::new(); + std::mem::swap(s, &mut message); + start_error(&mut c); + c.none(message); + put_usage(&mut c, usage); + try_help(&mut c, get_help_flag(cmd)); + *self = Self::Formatted(c); + } + Message::Formatted(_) => {} + } + } + + fn formatted(&self) -> Cow<Colorizer> { + match self { + Message::Raw(s) => { + let mut c = Colorizer::new(Stream::Stderr, ColorChoice::Never); + start_error(&mut c); + c.none(s); + Cow::Owned(c) + } + Message::Formatted(c) => Cow::Borrowed(c), + } + } +} + +impl From<String> for Message { + fn from(inner: String) -> Self { + Self::Raw(inner) + } +} + +impl From<Colorizer> for Message { + fn from(inner: Colorizer) -> Self { + Self::Formatted(inner) + } +} + +#[cfg(feature = "debug")] +#[derive(Debug)] +struct Backtrace(backtrace::Backtrace); + +#[cfg(feature = "debug")] +impl Backtrace { + fn new() -> Option<Self> { + Some(Self(backtrace::Backtrace::new())) + } +} + +#[cfg(feature = "debug")] +impl Display for Backtrace { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + // `backtrace::Backtrace` uses `Debug` instead of `Display` + write!(f, "{:?}", self.0) + } +} + +#[cfg(not(feature = "debug"))] +#[derive(Debug)] +struct Backtrace; + +#[cfg(not(feature = "debug"))] +impl Backtrace { + fn new() -> Option<Self> { + None + } +} + +#[cfg(not(feature = "debug"))] +impl Display for Backtrace { + fn fmt(&self, _: &mut Formatter) -> fmt::Result { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + /// Check `clap::Error` impls Send and Sync. + mod clap_error_impl_send_sync { + use crate::Error; + trait Foo: std::error::Error + Send + Sync + 'static {} + impl Foo for Error {} + } +} diff --git a/third_party/rust/clap/src/lib.rs b/third_party/rust/clap/src/lib.rs new file mode 100644 index 0000000000..dc92f87395 --- /dev/null +++ b/third_party/rust/clap/src/lib.rs @@ -0,0 +1,124 @@ +// Copyright ⓒ 2015-2016 Kevin B. Knapp and [`clap-rs` contributors](https://github.com/clap-rs/clap/graphs/contributors). +// Licensed under the MIT license +// (see LICENSE or <http://opensource.org/licenses/MIT>) All files in the project carrying such +// notice may not be copied, modified, or distributed except according to those terms. + +#![cfg_attr(docsrs, feature(doc_auto_cfg))] +#![doc(html_logo_url = "https://raw.githubusercontent.com/clap-rs/clap/master/assets/clap.png")] +#![cfg_attr(feature = "derive", doc = include_str!("../README.md"))] +//! <https://github.com/clap-rs/clap> +#![warn( + missing_docs, + missing_debug_implementations, + missing_copy_implementations, + trivial_casts, + unused_allocation, + trivial_numeric_casts, + clippy::single_char_pattern +)] +#![forbid(unsafe_code)] +// HACK https://github.com/rust-lang/rust-clippy/issues/7290 +#![allow(clippy::single_component_path_imports)] +#![allow(clippy::branches_sharing_code)] +// Doesn't allow for debug statements, etc to be unique +#![allow(clippy::if_same_then_else)] + +#[cfg(not(feature = "std"))] +compile_error!("`std` feature is currently required to build `clap`"); + +pub use crate::build::Command; +pub use crate::build::{ + AppFlags, AppSettings, Arg, ArgFlags, ArgGroup, ArgSettings, PossibleValue, ValueHint, +}; +pub use crate::error::Error; +pub use crate::parse::{ArgMatches, Indices, OsValues, ValueSource, Values}; +#[cfg(feature = "color")] +pub use crate::util::color::ColorChoice; +#[cfg(not(feature = "color"))] +#[allow(unused_imports)] +pub(crate) use crate::util::color::ColorChoice; + +pub use crate::derive::{ArgEnum, Args, CommandFactory, FromArgMatches, Parser, Subcommand}; + +pub use crate::error::{ErrorKind, Result}; + +#[allow(deprecated)] +pub use crate::build::App; + +#[cfg(feature = "yaml")] +#[doc(hidden)] +#[deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" +)] +#[doc(hidden)] +pub use yaml_rust::YamlLoader; + +#[cfg(feature = "derive")] +#[doc(hidden)] +pub use clap_derive::{self, *}; + +/// Deprecated, replaced with [`CommandFactory`] +#[deprecated(since = "3.0.0", note = "Replaced with `CommandFactory`")] +pub use CommandFactory as IntoApp; +/// Deprecated, replaced with [`Parser`] +#[deprecated(since = "3.0.0", note = "Replaced with `Parser`")] +#[doc(hidden)] +pub use Parser as StructOpt; + +#[cfg(any(feature = "derive", feature = "cargo"))] +#[doc(hidden)] +pub use lazy_static; + +#[macro_use] +#[allow(missing_docs)] +mod macros; + +mod derive; + +#[cfg(feature = "regex")] +pub use crate::build::RegexRef; + +pub mod error; + +mod build; +mod mkeymap; +mod output; +mod parse; +mod util; + +const INTERNAL_ERROR_MSG: &str = "Fatal internal error. Please consider filing a bug \ + report at https://github.com/clap-rs/clap/issues"; +const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point"; + +/// Deprecated, replaced with [`Command::new`], unless you were looking for [Subcommand] +#[deprecated( + since = "3.0.0", + note = "Replaced with `Command::new` unless you intended the `Subcommand` trait" +)] +#[doc(hidden)] +#[derive(Debug, Copy, Clone)] +pub struct SubCommand {} + +#[allow(deprecated)] +impl SubCommand { + /// Deprecated, replaced with [`Command::new`]. + /// Did you mean Subcommand (lower-case c)? + #[deprecated(since = "3.0.0", note = "Replaced with `Command::new`")] + #[doc(hidden)] + pub fn with_name<'help>(name: &str) -> App<'help> { + Command::new(name) + } + + /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? + #[cfg(feature = "yaml")] + #[deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" + )] + #[doc(hidden)] + pub fn from_yaml(yaml: &yaml_rust::Yaml) -> App { + #![allow(deprecated)] + Command::from_yaml(yaml) + } +} diff --git a/third_party/rust/clap/src/macros.rs b/third_party/rust/clap/src/macros.rs new file mode 100644 index 0000000000..f50b854959 --- /dev/null +++ b/third_party/rust/clap/src/macros.rs @@ -0,0 +1,1012 @@ +/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case? +#[cfg(feature = "yaml")] +#[deprecated( + since = "3.0.0", + note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?" +)] +#[doc(hidden)] +#[macro_export] +macro_rules! load_yaml { + ($yaml:expr) => { + &$crate::YamlLoader::load_from_str(include_str!($yaml)).expect("failed to load YAML file") + [0] + }; +} + +/// Deprecated, replaced with [`ArgMatches::value_of_t`][crate::ArgMatches::value_of_t] +#[macro_export] +#[deprecated(since = "3.0.0", note = "Replaced with `ArgMatches::value_of_t`")] +#[doc(hidden)] +macro_rules! value_t { + ($m:ident, $v:expr, $t:ty) => { + $crate::value_t!($m.value_of($v), $t) + }; + ($m:ident.value_of($v:expr), $t:ty) => { + $m.value_of_t::<$t>($v) + }; +} + +/// Deprecated, replaced with [`ArgMatches::value_of_t_or_exit`][crate::ArgMatches::value_of_t_or_exit] +#[macro_export] +#[deprecated( + since = "3.0.0", + note = "Replaced with `ArgMatches::value_of_t_or_exit`" +)] +#[doc(hidden)] +macro_rules! value_t_or_exit { + ($m:ident, $v:expr, $t:ty) => { + value_t_or_exit!($m.value_of($v), $t) + }; + ($m:ident.value_of($v:expr), $t:ty) => { + $m.value_of_t_or_exit::<$t>($v) + }; +} + +/// Deprecated, replaced with [`ArgMatches::values_of_t`][crate::ArgMatches::value_of_t] +#[macro_export] +#[deprecated(since = "3.0.0", note = "Replaced with `ArgMatches::values_of_t`")] +#[doc(hidden)] +macro_rules! values_t { + ($m:ident, $v:expr, $t:ty) => { + values_t!($m.values_of($v), $t) + }; + ($m:ident.values_of($v:expr), $t:ty) => { + $m.values_of_t::<$t>($v) + }; +} + +/// Deprecated, replaced with [`ArgMatches::values_of_t_or_exit`][crate::ArgMatches::value_of_t_or_exit] +#[macro_export] +#[deprecated( + since = "3.0.0", + note = "Replaced with `ArgMatches::values_of_t_or_exit`" +)] +#[doc(hidden)] +macro_rules! values_t_or_exit { + ($m:ident, $v:expr, $t:ty) => { + values_t_or_exit!($m.values_of($v), $t) + }; + ($m:ident.values_of($v:expr), $t:ty) => { + $m.values_of_t_or_exit::<$t>($v) + }; +} + +#[deprecated(since = "3.0.0", note = "Replaced with `ArgEnum`")] +#[doc(hidden)] +#[macro_export] +macro_rules! _clap_count_exprs { + () => { 0 }; + ($e:expr) => { 1 }; + ($e:expr, $($es:expr),+) => { 1 + $crate::_clap_count_exprs!($($es),*) }; +} + +/// Deprecated, replaced with [`ArgEnum`][crate::ArgEnum] +#[deprecated(since = "3.0.0", note = "Replaced with `ArgEnum`")] +#[doc(hidden)] +#[macro_export] +macro_rules! arg_enum { + (@as_item $($i:item)*) => ($($i)*); + (@impls ( $($tts:tt)* ) -> ($e:ident, $($v:ident),+)) => { + $crate::arg_enum!(@as_item + $($tts)* + + impl ::std::str::FromStr for $e { + type Err = String; + + fn from_str(s: &str) -> ::std::result::Result<Self,Self::Err> { + #[allow(deprecated, unused_imports)] + use ::std::ascii::AsciiExt; + match s { + $(stringify!($v) | + _ if s.eq_ignore_ascii_case(stringify!($v)) => Ok($e::$v)),+, + _ => Err({ + let v = vec![ + $(stringify!($v),)+ + ]; + format!("valid values: {}", + v.join(", ")) + }), + } + } + } + impl ::std::fmt::Display for $e { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + match *self { + $($e::$v => write!(f, stringify!($v)),)+ + } + } + } + impl $e { + #[allow(dead_code)] + pub fn variants() -> [&'static str; $crate::_clap_count_exprs!($(stringify!($v)),+)] { + [ + $(stringify!($v),)+ + ] + } + }); + }; + ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { + $crate::arg_enum!(@impls + ($(#[$($m),+])+ + pub enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { + $crate::arg_enum!(@impls + ($(#[$($m),+])+ + pub enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { + $crate::arg_enum!(@impls + ($(#[$($m),+])+ + enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { + $crate::arg_enum!(@impls + ($(#[$($m),+])+ + enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + (pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { + $crate::arg_enum!(@impls + (pub enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + (pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { + $crate::arg_enum!(@impls + (pub enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + (enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { + $crate::arg_enum!(@impls + (enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; + (enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { + $crate::arg_enum!(@impls + (enum $e { + $($v$(=$val)*),+ + }) -> ($e, $($v),+) + ); + }; +} + +/// Allows you to pull the version from your Cargo.toml at compile time as +/// `MAJOR.MINOR.PATCH_PKGVERSION_PRE` +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::Command; +/// # fn main() { +/// let m = Command::new("cmd") +/// .version(crate_version!()) +/// .get_matches(); +/// # } +/// ``` +#[cfg(feature = "cargo")] +#[macro_export] +macro_rules! crate_version { + () => { + env!("CARGO_PKG_VERSION") + }; +} + +/// Allows you to pull the authors for the command from your Cargo.toml at +/// compile time in the form: +/// `"author1 lastname <author1@example.com>:author2 lastname <author2@example.com>"` +/// +/// You can replace the colons with a custom separator by supplying a +/// replacement string, so, for example, +/// `crate_authors!(",\n")` would become +/// `"author1 lastname <author1@example.com>,\nauthor2 lastname <author2@example.com>,\nauthor3 lastname <author3@example.com>"` +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::Command; +/// # fn main() { +/// let m = Command::new("cmd") +/// .author(crate_authors!("\n")) +/// .get_matches(); +/// # } +/// ``` +#[cfg(feature = "cargo")] +#[macro_export] +macro_rules! crate_authors { + ($sep:expr) => {{ + clap::lazy_static::lazy_static! { + static ref CACHED: String = env!("CARGO_PKG_AUTHORS").replace(':', $sep); + } + + let s: &'static str = &*CACHED; + s + }}; + () => { + env!("CARGO_PKG_AUTHORS") + }; +} + +/// Allows you to pull the description from your Cargo.toml at compile time. +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::Command; +/// # fn main() { +/// let m = Command::new("cmd") +/// .about(crate_description!()) +/// .get_matches(); +/// # } +/// ``` +#[cfg(feature = "cargo")] +#[macro_export] +macro_rules! crate_description { + () => { + env!("CARGO_PKG_DESCRIPTION") + }; +} + +/// Allows you to pull the name from your Cargo.toml at compile time. +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # use clap::Command; +/// # fn main() { +/// let m = Command::new(crate_name!()) +/// .get_matches(); +/// # } +/// ``` +#[cfg(feature = "cargo")] +#[macro_export] +macro_rules! crate_name { + () => { + env!("CARGO_PKG_NAME") + }; +} + +/// Allows you to build the `Command` instance from your Cargo.toml at compile time. +/// +/// **NOTE:** Changing the values in your `Cargo.toml` does not trigger a re-build automatically, +/// and therefore won't change the generated output until you recompile. +/// +/// In some cases you can "trick" the compiler into triggering a rebuild when your +/// `Cargo.toml` is changed by including this in your `src/main.rs` file +/// `include_str!("../Cargo.toml");` +/// +/// # Examples +/// +/// ```no_run +/// # #[macro_use] +/// # extern crate clap; +/// # fn main() { +/// let m = command!().get_matches(); +/// # } +/// ``` +#[cfg(feature = "cargo")] +#[macro_export] +macro_rules! command { + () => {{ + $crate::command!($crate::crate_name!()) + }}; + ($name:expr) => {{ + let mut cmd = $crate::Command::new($name).version($crate::crate_version!()); + + let author = $crate::crate_authors!(); + if !author.is_empty() { + cmd = cmd.author(author) + } + + let about = $crate::crate_description!(); + if !about.is_empty() { + cmd = cmd.about(about) + } + + cmd + }}; +} + +/// Requires `cargo` feature flag to be enabled. +#[cfg(not(feature = "cargo"))] +#[macro_export] +macro_rules! command { + () => {{ + compile_error!("`cargo` feature flag is required"); + }}; + ($name:expr) => {{ + compile_error!("`cargo` feature flag is required"); + }}; +} + +/// Deprecated, replaced with [`clap::command!`][crate::command] +#[cfg(feature = "cargo")] +#[deprecated(since = "3.1.0", note = "Replaced with `clap::command!")] +#[macro_export] +macro_rules! app_from_crate { + () => {{ + let mut cmd = $crate::Command::new($crate::crate_name!()).version($crate::crate_version!()); + + let author = $crate::crate_authors!(", "); + if !author.is_empty() { + cmd = cmd.author(author) + } + + let about = $crate::crate_description!(); + if !about.is_empty() { + cmd = cmd.about(about) + } + + cmd + }}; + ($sep:expr) => {{ + let mut cmd = $crate::Command::new($crate::crate_name!()).version($crate::crate_version!()); + + let author = $crate::crate_authors!($sep); + if !author.is_empty() { + cmd = cmd.author(author) + } + + let about = $crate::crate_description!(); + if !about.is_empty() { + cmd = cmd.about(about) + } + + cmd + }}; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! arg_impl { + ( @string $val:ident ) => { + stringify!($val) + }; + ( @string $val:literal ) => {{ + let ident_or_string_literal: &str = $val; + ident_or_string_literal + }}; + ( @string $val:tt ) => { + ::std::compile_error!("Only identifiers or string literals supported"); + }; + ( @string ) => { + None + }; + + ( @char $val:ident ) => {{ + let ident_or_char_literal = stringify!($val); + debug_assert_eq!( + ident_or_char_literal.len(), + 1, + "Single-letter identifier expected, got {}", + ident_or_char_literal + ); + ident_or_char_literal.chars().next().unwrap() + }}; + ( @char $val:literal ) => {{ + let ident_or_char_literal: char = $val; + ident_or_char_literal + }}; + ( @char ) => {{ + None + }}; + + ( + @arg + ($arg:expr) + --$long:ident + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); + debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); + + let mut arg = $arg; + let long = $crate::arg_impl! { @string $long }; + if arg.get_id().is_empty() { + arg = arg.id(long); + } + arg.long(long) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + --$long:literal + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); + debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); + + let mut arg = $arg; + let long = $crate::arg_impl! { @string $long }; + if arg.get_id().is_empty() { + arg = arg.id(long); + } + arg.long(long) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + -$short:ident + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert_eq!($arg.get_long(), None, "Short flags should precede long flags"); + debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); + debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); + + $arg.short($crate::arg_impl! { @char $short }) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + -$short:literal + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert_eq!($arg.get_long(), None, "Short flags should precede long flags"); + debug_assert_eq!($arg.get_value_names(), None, "Flags should precede values"); + debug_assert!(!$arg.is_multiple_occurrences_set(), "Flags should precede `...`"); + + $arg.short($crate::arg_impl! { @char $short }) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + <$value_name:ident> + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); + debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); + + let mut arg = $arg; + + arg = arg.required(true); + arg = arg.takes_value(true); + + let value_name = $crate::arg_impl! { @string $value_name }; + if arg.get_id().is_empty() { + arg = arg.id(value_name); + } + arg.value_name(value_name) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + <$value_name:literal> + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); + debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); + + let mut arg = $arg; + + arg = arg.required(true); + arg = arg.takes_value(true); + + let value_name = $crate::arg_impl! { @string $value_name }; + if arg.get_id().is_empty() { + arg = arg.id(value_name); + } + arg.value_name(value_name) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + [$value_name:ident] + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); + debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); + + let mut arg = $arg; + + if arg.get_long().is_none() && arg.get_short().is_none() { + arg = arg.required(false); + } else { + arg = arg.min_values(0).max_values(1); + } + arg = arg.takes_value(true); + + let value_name = $crate::arg_impl! { @string $value_name }; + if arg.get_id().is_empty() { + arg = arg.id(value_name); + } + arg.value_name(value_name) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + [$value_name:literal] + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + debug_assert!(!$arg.is_multiple_occurrences_set(), "Values should precede `...`"); + debug_assert_eq!($arg.get_value_names(), None, "Multiple values not yet supported"); + + let mut arg = $arg; + + if arg.get_long().is_none() && arg.get_short().is_none() { + arg = arg.required(false); + } else { + arg = arg.min_values(0).max_values(1); + } + arg = arg.takes_value(true); + + let value_name = $crate::arg_impl! { @string $value_name }; + if arg.get_id().is_empty() { + arg = arg.id(value_name); + } + arg.value_name(value_name) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + ... + $($tail:tt)* + ) => { + $crate::arg_impl! { + @arg + ({ + $arg.multiple_occurrences(true) + }) + $($tail)* + } + }; + ( + @arg + ($arg:expr) + $help:literal + ) => { + $arg.help($help) + }; + ( + @arg + ($arg:expr) + ) => { + $arg + }; +} + +/// Create an [`Arg`] from a usage string. +/// +/// Allows creation of basic settings for the [`Arg`]. +/// +/// **NOTE**: Not all settings may be set using the usage string method. Some properties are +/// only available via the builder pattern. +/// +/// # Syntax +/// +/// Usage strings typically following the form: +/// +/// ```notrust +/// [explicit name] [short] [long] [value names] [...] [help string] +/// ``` +/// +/// ### Explicit Name +/// +/// The name may be either a bare-word or a string, followed by a `:`, like `name:` or +/// `"name":`. +/// +/// *Note:* This is an optional field, if it's omitted the argument will use one of the additional +/// fields as the name using the following priority order: +/// +/// 1. Explicit Name +/// 2. Long +/// 3. Value Name +/// +/// See [`Arg::name`][crate::Arg::name]. +/// +/// ### Short +/// +/// A short flag is a `-` followed by either a bare-character or quoted character, like `-f` or +/// `-'f'`. +/// +/// See [`Arg::short`][crate::Arg::short]. +/// +/// ### Long +/// +/// A long flag is a `--` followed by either a bare-word or a string, like `--foo` or +/// `--"foo"`. +/// +/// See [`Arg::long`][crate::Arg::long]. +/// +/// ### Values (Value Notation) +/// +/// This is set by placing bare-word between: +/// - `[]` like `[FOO]` +/// - Positional argument: optional +/// - Named argument: optional value +/// - `<>` like `<FOO>`: required +/// +/// See [`Arg::value_name`][crate::Arg::value_name]. +/// +/// ### `...` +/// +/// `...` (three consecutive dots/periods) specifies that this argument may occur multiple +/// times (not to be confused with multiple values per occurrence). +/// +/// See [`Arg::multiple_occurrences`][crate::Arg::multiple_occurrences]. +/// +/// ### Help String +/// +/// The help string is denoted between a pair of double quotes `""` and may contain any +/// characters. +/// +/// # Examples +/// +/// ```rust +/// # use clap::{Command, Arg, arg}; +/// Command::new("prog") +/// .args(&[ +/// arg!(--config <FILE> "a required file for the configuration and no short"), +/// arg!(-d --debug ... "turns on debugging information and allows multiples"), +/// arg!([input] "an optional input file to use") +/// ]) +/// # ; +/// ``` +/// [`Arg`]: ./struct.Arg.html +#[macro_export] +macro_rules! arg { + ( $name:ident: $($tail:tt)+ ) => { + $crate::arg_impl! { + @arg ($crate::Arg::new($crate::arg_impl! { @string $name })) $($tail)+ + } + }; + ( $($tail:tt)+ ) => {{ + let arg = $crate::arg_impl! { + @arg ($crate::Arg::default()) $($tail)+ + }; + debug_assert!(!arg.get_id().is_empty(), "Without a value or long flag, the `name:` prefix is required"); + arg + }}; +} + +/// Deprecated, replaced with [`clap::Parser`][crate::Parser] and [`clap::arg!`][crate::arg] (Issue clap-rs/clap#2835) +#[deprecated( + since = "3.0.0", + note = "Replaced with `clap::Parser` for a declarative API (Issue clap-rs/clap#2835)" +)] +#[doc(hidden)] +#[macro_export] +macro_rules! clap_app { + (@app ($builder:expr)) => { $builder }; + (@app ($builder:expr) (@arg ($name:expr): $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($builder.arg( + $crate::clap_app!{ @arg ($crate::Arg::new($name)) (-) $($tail)* })) + $($tt)* + } + }; + (@app ($builder:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($builder.arg( + $crate::clap_app!{ @arg ($crate::Arg::new(stringify!($name))) (-) $($tail)* })) + $($tt)* + } + }; + (@app ($builder:expr) (@setting $setting:ident) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($builder.setting($crate::AppSettings::$setting)) + $($tt)* + } + }; +// Treat the application builder as an argument to set its attributes + (@app ($builder:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app ($crate::clap_app!{ @arg ($builder) $($attr)* }) $($tt)* } + }; + (@app ($builder:expr) (@group $name:ident => $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::new(stringify!($name))) $($tail)* }) + $($tt)* + } + }; + (@app ($builder:expr) (@group $name:ident !$ident:ident => $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::new(stringify!($name)).$ident(false)) $($tail)* }) + $($tt)* + } + }; + (@app ($builder:expr) (@group $name:ident +$ident:ident => $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($crate::clap_app!{ @group ($builder, $crate::ArgGroup::new(stringify!($name)).$ident(true)) $($tail)* }) + $($tt)* + } + }; +// Handle subcommand creation + (@app ($builder:expr) (@subcommand $name:ident => $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @app + ($builder.subcommand( + $crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)* } + )) + $($tt)* + } + }; +// Yaml like function calls - used for setting various meta directly against the app + (@app ($builder:expr) ($ident:ident: $($v:expr),*) $($tt:tt)*) => { +// $crate::clap_app!{ @app ($builder.$ident($($v),*)) $($tt)* } + $crate::clap_app!{ @app + ($builder.$ident($($v),*)) + $($tt)* + } + }; + +// Add members to group and continue argument handling with the parent builder + (@group ($builder:expr, $group:expr)) => { $builder.group($group) }; + // Treat the group builder as an argument to set its attributes + (@group ($builder:expr, $group:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @group ($builder, $crate::clap_app!{ @arg ($group) (-) $($attr)* }) $($tt)* } + }; + (@group ($builder:expr, $group:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => { + $crate::clap_app!{ @group + ($crate::clap_app!{ @app ($builder) (@arg $name: $($tail)*) }, + $group.arg(stringify!($name))) + $($tt)* + } + }; + +// No more tokens to munch + (@arg ($arg:expr) $modes:tt) => { $arg }; +// Shorthand tokens influenced by the usage_string + (@arg ($arg:expr) $modes:tt --($long:expr) $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.long($long)) $modes $($tail)* } + }; + (@arg ($arg:expr) $modes:tt --$long:ident $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.long(stringify!($long))) $modes $($tail)* } + }; + (@arg ($arg:expr) $modes:tt -$short:ident $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.short(stringify!($short).chars().next().unwrap())) $modes $($tail)* } + }; + (@arg ($arg:expr) (-) <$var:ident> $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value +required $($tail)* } + }; + (@arg ($arg:expr) (+) <$var:ident> $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } + }; + (@arg ($arg:expr) (-) [$var:ident] $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value $($tail)* } + }; + (@arg ($arg:expr) (+) [$var:ident] $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } + }; + (@arg ($arg:expr) $modes:tt ... $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg) $modes +multiple +takes_value $($tail)* } + }; +// Shorthand magic + (@arg ($arg:expr) $modes:tt #{$n:expr, $m:expr} $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg) $modes min_values($n) max_values($m) $($tail)* } + }; + (@arg ($arg:expr) $modes:tt * $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg) $modes +required $($tail)* } + }; +// !foo -> .foo(false) + (@arg ($arg:expr) $modes:tt !$ident:ident $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.$ident(false)) $modes $($tail)* } + }; +// +foo -> .foo(true) + (@arg ($arg:expr) $modes:tt +$ident:ident $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.$ident(true)) $modes $($tail)* } + }; +// Validator + (@arg ($arg:expr) $modes:tt {$fn_:expr} $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.validator($fn_)) $modes $($tail)* } + }; + (@as_expr $expr:expr) => { $expr }; +// Help + (@arg ($arg:expr) $modes:tt $desc:tt) => { $arg.help($crate::clap_app!{ @as_expr $desc }) }; +// Handle functions that need to be called multiple times for each argument + (@arg ($arg:expr) $modes:tt $ident:ident[$($target:ident)*] $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg $( .$ident(stringify!($target)) )*) $modes $($tail)* } + }; +// Inherit builder's functions, e.g. `index(2)`, `requires_if("val", "arg")` + (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr),*) $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } + }; +// Inherit builder's functions with trailing comma, e.g. `index(2,)`, `requires_if("val", "arg",)` + (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr,)*) $($tail:tt)*) => { + $crate::clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } + }; + +// Build a subcommand outside of an app. + (@subcommand $name:ident => $($tail:tt)*) => { + $crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)* } + }; +// Start the magic + (($name:expr) => $($tail:tt)*) => {{ + $crate::clap_app!{ @app ($crate::Command::new($name)) $($tail)*} + }}; + + ($name:ident => $($tail:tt)*) => {{ + $crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)*} + }}; +} + +macro_rules! impl_settings { + ($settings:ident, $flags:ident, + $( + $(#[$inner:ident $($args:tt)*])* + $setting:ident => $flag:path + ),+ + ) => { + impl $flags { + #[allow(dead_code)] + pub(crate) fn empty() -> Self { + $flags(Flags::empty()) + } + + #[allow(dead_code)] + pub(crate) fn insert(&mut self, rhs: Self) { + self.0.insert(rhs.0); + } + + #[allow(dead_code)] + pub(crate) fn remove(&mut self, rhs: Self) { + self.0.remove(rhs.0); + } + + #[allow(dead_code)] + pub(crate) fn set(&mut self, s: $settings) { + #[allow(deprecated)] // some Settings might be deprecated + match s { + $( + $(#[$inner $($args)*])* + $settings::$setting => self.0.insert($flag), + )* + } + } + + #[allow(dead_code)] + pub(crate) fn unset(&mut self, s: $settings) { + #[allow(deprecated)] // some Settings might be deprecated + match s { + $( + $(#[$inner $($args)*])* + $settings::$setting => self.0.remove($flag), + )* + } + } + + #[allow(dead_code)] + pub(crate) fn is_set(&self, s: $settings) -> bool { + #[allow(deprecated)] // some Settings might be deprecated + match s { + $( + $(#[$inner $($args)*])* + $settings::$setting => self.0.contains($flag), + )* + } + } + } + + impl BitOr for $flags { + type Output = Self; + + fn bitor(mut self, rhs: Self) -> Self::Output { + self.0.insert(rhs.0); + self + } + } + + impl From<$settings> for $flags { + fn from(setting: $settings) -> Self { + let mut flags = $flags::empty(); + flags.set(setting); + flags + } + } + + impl BitOr<$settings> for $flags { + type Output = Self; + + fn bitor(mut self, rhs: $settings) -> Self::Output { + self.set(rhs); + self + } + } + + impl BitOr for $settings { + type Output = $flags; + + fn bitor(self, rhs: Self) -> Self::Output { + let mut flags = $flags::empty(); + flags.set(self); + flags.set(rhs); + flags + } + } + } +} + +// Convenience for writing to stderr thanks to https://github.com/BurntSushi +macro_rules! wlnerr { + ($($arg:tt)*) => ({ + use std::io::{Write, stderr}; + writeln!(&mut stderr(), $($arg)*).ok(); + }) +} + +#[cfg(feature = "debug")] +macro_rules! debug { + ($($arg:tt)*) => ({ + let prefix = format!("[{:>w$}] \t", module_path!(), w = 28); + let body = format!($($arg)*); + let mut color = $crate::output::fmt::Colorizer::new($crate::output::fmt::Stream::Stderr, $crate::ColorChoice::Auto); + color.hint(prefix); + color.hint(body); + color.none("\n"); + let _ = color.print(); + }) +} + +#[cfg(not(feature = "debug"))] +macro_rules! debug { + ($($arg:tt)*) => {}; +} diff --git a/third_party/rust/clap/src/mkeymap.rs b/third_party/rust/clap/src/mkeymap.rs new file mode 100644 index 0000000000..8ba3dcb306 --- /dev/null +++ b/third_party/rust/clap/src/mkeymap.rs @@ -0,0 +1,189 @@ +use crate::{build::Arg, util::Id, INTERNAL_ERROR_MSG}; + +use std::{ffi::OsStr, ffi::OsString, iter::Iterator, ops::Index}; + +#[derive(PartialEq, Eq, Debug, Clone)] +pub(crate) struct Key { + key: KeyType, + index: usize, +} + +#[derive(Default, PartialEq, Eq, Debug, Clone)] +pub(crate) struct MKeyMap<'help> { + /// All of the arguments. + args: Vec<Arg<'help>>, + + // Cache part: + /// Will be set after `_build()`. + keys: Vec<Key>, +} + +#[derive(Debug, PartialEq, Eq, Hash, Clone)] +pub(crate) enum KeyType { + Short(char), + Long(OsString), + Position(usize), +} + +impl KeyType { + pub(crate) fn is_position(&self) -> bool { + matches!(self, KeyType::Position(_)) + } +} + +impl PartialEq<usize> for KeyType { + fn eq(&self, rhs: &usize) -> bool { + match self { + KeyType::Position(x) => x == rhs, + _ => false, + } + } +} + +impl PartialEq<&str> for KeyType { + fn eq(&self, rhs: &&str) -> bool { + match self { + KeyType::Long(l) => l == rhs, + _ => false, + } + } +} + +impl PartialEq<str> for KeyType { + fn eq(&self, rhs: &str) -> bool { + match self { + KeyType::Long(l) => l == rhs, + _ => false, + } + } +} + +impl PartialEq<OsStr> for KeyType { + fn eq(&self, rhs: &OsStr) -> bool { + match self { + KeyType::Long(l) => l == rhs, + _ => false, + } + } +} + +impl PartialEq<char> for KeyType { + fn eq(&self, rhs: &char) -> bool { + match self { + KeyType::Short(c) => c == rhs, + _ => false, + } + } +} + +impl<'help> MKeyMap<'help> { + /// If any arg has corresponding key in this map, we can search the key with + /// u64(for positional argument), char(for short flag), &str and OsString + /// (for long flag) + pub(crate) fn contains<K>(&self, key: K) -> bool + where + KeyType: PartialEq<K>, + { + self.keys.iter().any(|x| x.key == key) + } + + /// Reserves capacity for at least additional more elements to be inserted + pub(crate) fn reserve(&mut self, additional: usize) { + self.args.reserve(additional); + } + + /// Push an argument in the map. + pub(crate) fn push(&mut self, new_arg: Arg<'help>) { + self.args.push(new_arg); + } + + /// Find the arg have corresponding key in this map, we can search the key + /// with u64(for positional argument), char(for short flag), &str and + /// OsString (for long flag) + pub(crate) fn get<K: ?Sized>(&self, key: &K) -> Option<&Arg<'help>> + where + KeyType: PartialEq<K>, + { + self.keys + .iter() + .find(|k| &k.key == key) + .map(|k| &self.args[k.index]) + } + + /// Find out if the map have no arg. + pub(crate) fn is_empty(&self) -> bool { + self.args.is_empty() + } + + /// Return iterators of all keys. + pub(crate) fn keys(&self) -> impl Iterator<Item = &KeyType> { + self.keys.iter().map(|x| &x.key) + } + + /// Return iterators of all args. + pub(crate) fn args(&self) -> impl Iterator<Item = &Arg<'help>> { + self.args.iter() + } + + /// Return mutable iterators of all args. + pub(crate) fn args_mut<'map>(&'map mut self) -> impl Iterator<Item = &'map mut Arg<'help>> { + self.args.iter_mut() + } + + /// We need a lazy build here since some we may change args after creating + /// the map, you can checkout who uses `args_mut`. + pub(crate) fn _build(&mut self) { + for (i, arg) in self.args.iter().enumerate() { + append_keys(&mut self.keys, arg, i); + } + } + + /// Remove an arg in the graph by Id, usually used by `mut_arg`. Return + /// `Some(arg)` if removed. + pub(crate) fn remove_by_name(&mut self, name: &Id) -> Option<Arg<'help>> { + self.args + .iter() + .position(|arg| &arg.id == name) + // since it's a cold function, using this wouldn't hurt much + .map(|i| self.args.remove(i)) + } + + /// Remove an arg based on index + pub(crate) fn remove(&mut self, index: usize) -> Arg<'help> { + self.args.remove(index) + } +} + +impl<'help> Index<&'_ KeyType> for MKeyMap<'help> { + type Output = Arg<'help>; + + fn index(&self, key: &KeyType) -> &Self::Output { + self.get(key).expect(INTERNAL_ERROR_MSG) + } +} + +/// Generate key types for an specific Arg. +fn append_keys(keys: &mut Vec<Key>, arg: &Arg, index: usize) { + if let Some(pos_index) = arg.index { + let key = KeyType::Position(pos_index); + keys.push(Key { key, index }); + } else { + if let Some(short) = arg.short { + let key = KeyType::Short(short); + keys.push(Key { key, index }); + } + if let Some(long) = arg.long { + let key = KeyType::Long(OsString::from(long)); + keys.push(Key { key, index }); + } + + for (short, _) in arg.short_aliases.iter() { + let key = KeyType::Short(*short); + keys.push(Key { key, index }); + } + for (long, _) in arg.aliases.iter() { + let key = KeyType::Long(OsString::from(long)); + keys.push(Key { key, index }); + } + } +} diff --git a/third_party/rust/clap/src/output/fmt.rs b/third_party/rust/clap/src/output/fmt.rs new file mode 100644 index 0000000000..dc1f46e08f --- /dev/null +++ b/third_party/rust/clap/src/output/fmt.rs @@ -0,0 +1,158 @@ +use crate::util::color::ColorChoice; + +use std::{ + fmt::{self, Display, Formatter}, + io::{self, Write}, +}; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Stream { + Stdout, + Stderr, +} + +#[derive(Clone, Debug)] +pub(crate) struct Colorizer { + stream: Stream, + #[allow(unused)] + color_when: ColorChoice, + pieces: Vec<(String, Style)>, +} + +impl Colorizer { + #[inline(never)] + pub(crate) fn new(stream: Stream, color_when: ColorChoice) -> Self { + Colorizer { + stream, + color_when, + pieces: vec![], + } + } + + #[inline(never)] + pub(crate) fn good(&mut self, msg: impl Into<String>) { + self.pieces.push((msg.into(), Style::Good)); + } + + #[inline(never)] + pub(crate) fn warning(&mut self, msg: impl Into<String>) { + self.pieces.push((msg.into(), Style::Warning)); + } + + #[inline(never)] + pub(crate) fn error(&mut self, msg: impl Into<String>) { + self.pieces.push((msg.into(), Style::Error)); + } + + #[inline(never)] + #[allow(dead_code)] + pub(crate) fn hint(&mut self, msg: impl Into<String>) { + self.pieces.push((msg.into(), Style::Hint)); + } + + #[inline(never)] + pub(crate) fn none(&mut self, msg: impl Into<String>) { + self.pieces.push((msg.into(), Style::Default)); + } +} + +/// Printing methods. +impl Colorizer { + #[cfg(feature = "color")] + pub(crate) fn print(&self) -> io::Result<()> { + use termcolor::{BufferWriter, ColorChoice as DepColorChoice, ColorSpec, WriteColor}; + + let color_when = match self.color_when { + ColorChoice::Always => DepColorChoice::Always, + ColorChoice::Auto if is_a_tty(self.stream) => DepColorChoice::Auto, + _ => DepColorChoice::Never, + }; + + let writer = match self.stream { + Stream::Stderr => BufferWriter::stderr(color_when), + Stream::Stdout => BufferWriter::stdout(color_when), + }; + + let mut buffer = writer.buffer(); + + for piece in &self.pieces { + let mut color = ColorSpec::new(); + match piece.1 { + Style::Good => { + color.set_fg(Some(termcolor::Color::Green)); + } + Style::Warning => { + color.set_fg(Some(termcolor::Color::Yellow)); + } + Style::Error => { + color.set_fg(Some(termcolor::Color::Red)); + color.set_bold(true); + } + Style::Hint => { + color.set_dimmed(true); + } + Style::Default => {} + } + + buffer.set_color(&color)?; + buffer.write_all(piece.0.as_bytes())?; + buffer.reset()?; + } + + writer.print(&buffer) + } + + #[cfg(not(feature = "color"))] + pub(crate) fn print(&self) -> io::Result<()> { + // [e]println can't be used here because it panics + // if something went wrong. We don't want that. + match self.stream { + Stream::Stdout => { + let stdout = std::io::stdout(); + let mut stdout = stdout.lock(); + write!(stdout, "{}", self) + } + Stream::Stderr => { + let stderr = std::io::stderr(); + let mut stderr = stderr.lock(); + write!(stderr, "{}", self) + } + } + } +} + +/// Color-unaware printing. Never uses coloring. +impl Display for Colorizer { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + for piece in &self.pieces { + Display::fmt(&piece.0, f)?; + } + + Ok(()) + } +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Style { + Good, + Warning, + Error, + Hint, + Default, +} + +impl Default for Style { + fn default() -> Self { + Self::Default + } +} + +#[cfg(feature = "color")] +fn is_a_tty(stream: Stream) -> bool { + let stream = match stream { + Stream::Stdout => atty::Stream::Stdout, + Stream::Stderr => atty::Stream::Stderr, + }; + + atty::is(stream) +} diff --git a/third_party/rust/clap/src/output/help.rs b/third_party/rust/clap/src/output/help.rs new file mode 100644 index 0000000000..85ba7d13a2 --- /dev/null +++ b/third_party/rust/clap/src/output/help.rs @@ -0,0 +1,1185 @@ +// Std +use std::{ + borrow::Cow, + cmp, + fmt::Write as _, + io::{self, Write}, + usize, +}; + +// Internal +use crate::{ + build::{display_arg_val, Arg, Command}, + output::{fmt::Colorizer, Usage}, + PossibleValue, +}; + +// Third party +use indexmap::IndexSet; +use textwrap::core::display_width; + +/// `clap` Help Writer. +/// +/// Wraps a writer stream providing different methods to generate help for `clap` objects. +pub(crate) struct Help<'help, 'cmd, 'writer> { + writer: HelpWriter<'writer>, + cmd: &'cmd Command<'help>, + usage: &'cmd Usage<'help, 'cmd>, + next_line_help: bool, + term_w: usize, + use_long: bool, +} + +// Public Functions +impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { + #[cfg(feature = "unstable-v4")] + const DEFAULT_TEMPLATE: &'static str = "\ + {before-help}{name} {version}\n\ + {author-with-newline}{about-with-newline}\n\ + {usage-heading}\n {usage}\n\ + \n\ + {all-args}{after-help}\ + "; + #[cfg(not(feature = "unstable-v4"))] + const DEFAULT_TEMPLATE: &'static str = "\ + {before-help}{bin} {version}\n\ + {author-with-newline}{about-with-newline}\n\ + {usage-heading}\n {usage}\n\ + \n\ + {all-args}{after-help}\ + "; + + #[cfg(feature = "unstable-v4")] + const DEFAULT_NO_ARGS_TEMPLATE: &'static str = "\ + {before-help}{name} {version}\n\ + {author-with-newline}{about-with-newline}\n\ + {usage-heading}\n {usage}{after-help}\ + "; + #[cfg(not(feature = "unstable-v4"))] + const DEFAULT_NO_ARGS_TEMPLATE: &'static str = "\ + {before-help}{bin} {version}\n\ + {author-with-newline}{about-with-newline}\n\ + {usage-heading}\n {usage}{after-help}\ + "; + + /// Create a new `Help` instance. + pub(crate) fn new( + writer: HelpWriter<'writer>, + cmd: &'cmd Command<'help>, + usage: &'cmd Usage<'help, 'cmd>, + use_long: bool, + ) -> Self { + debug!("Help::new"); + let term_w = match cmd.get_term_width() { + Some(0) => usize::MAX, + Some(w) => w, + None => cmp::min( + dimensions().map_or(100, |(w, _)| w), + match cmd.get_max_term_width() { + None | Some(0) => usize::MAX, + Some(mw) => mw, + }, + ), + }; + let next_line_help = cmd.is_next_line_help_set(); + + Help { + writer, + cmd, + usage, + next_line_help, + term_w, + use_long, + } + } + + /// Writes the parser help to the wrapped stream. + pub(crate) fn write_help(&mut self) -> io::Result<()> { + debug!("Help::write_help"); + + if let Some(h) = self.cmd.get_override_help() { + self.none(h)?; + } else if let Some(tmpl) = self.cmd.get_help_template() { + self.write_templated_help(tmpl)?; + } else { + let pos = self + .cmd + .get_positionals() + .any(|arg| should_show_arg(self.use_long, arg)); + let non_pos = self + .cmd + .get_non_positionals() + .any(|arg| should_show_arg(self.use_long, arg)); + let subcmds = self.cmd.has_visible_subcommands(); + + if non_pos || pos || subcmds { + self.write_templated_help(Self::DEFAULT_TEMPLATE)?; + } else { + self.write_templated_help(Self::DEFAULT_NO_ARGS_TEMPLATE)?; + } + } + + self.none("\n")?; + + Ok(()) + } +} + +macro_rules! write_method { + ($_self:ident, $msg:ident, $meth:ident) => { + match &mut $_self.writer { + HelpWriter::Buffer(c) => { + c.$meth(($msg).into()); + Ok(()) + } + HelpWriter::Normal(w) => w.write_all($msg.as_ref()), + } + }; +} + +// Methods to write Arg help. +impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { + #[inline(never)] + fn good<T: Into<String> + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { + write_method!(self, msg, good) + } + + #[inline(never)] + fn warning<T: Into<String> + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { + write_method!(self, msg, warning) + } + + #[inline(never)] + fn none<T: Into<String> + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> { + write_method!(self, msg, none) + } + + #[inline(never)] + fn spaces(&mut self, n: usize) -> io::Result<()> { + // A string with 64 consecutive spaces. + const SHORT_SPACE: &str = + " "; + if let Some(short) = SHORT_SPACE.get(..n) { + self.none(short) + } else { + self.none(" ".repeat(n)) + } + } + + /// Writes help for each argument in the order they were declared to the wrapped stream. + fn write_args_unsorted(&mut self, args: &[&Arg<'help>]) -> io::Result<()> { + debug!("Help::write_args_unsorted"); + // The shortest an arg can legally be is 2 (i.e. '-x') + let mut longest = 2; + let mut arg_v = Vec::with_capacity(10); + + for &arg in args + .iter() + .filter(|arg| should_show_arg(self.use_long, *arg)) + { + if arg.longest_filter() { + longest = longest.max(display_width(arg.to_string().as_str())); + } + arg_v.push(arg) + } + + let next_line_help = self.will_args_wrap(args, longest); + + let argc = arg_v.len(); + for (i, arg) in arg_v.iter().enumerate() { + self.write_arg(arg, i + 1 == argc, next_line_help, longest)?; + } + Ok(()) + } + + /// Sorts arguments by length and display order and write their help to the wrapped stream. + fn write_args(&mut self, args: &[&Arg<'help>]) -> io::Result<()> { + debug!("Help::write_args"); + // The shortest an arg can legally be is 2 (i.e. '-x') + let mut longest = 2; + let mut ord_v = Vec::new(); + + // Determine the longest + for &arg in args.iter().filter(|arg| { + // If it's NextLineHelp we don't care to compute how long it is because it may be + // NextLineHelp on purpose simply *because* it's so long and would throw off all other + // args alignment + should_show_arg(self.use_long, *arg) + }) { + if arg.longest_filter() { + debug!("Help::write_args: Current Longest...{}", longest); + longest = longest.max(display_width(arg.to_string().as_str())); + debug!("Help::write_args: New Longest...{}", longest); + } + + // Formatting key like this to ensure that: + // 1. Argument has long flags are printed just after short flags. + // 2. For two args both have short flags like `-c` and `-C`, the + // `-C` arg is printed just after the `-c` arg + // 3. For args without short or long flag, print them at last(sorted + // by arg name). + // Example order: -a, -b, -B, -s, --select-file, --select-folder, -x + + let key = if let Some(x) = arg.short { + let mut s = x.to_ascii_lowercase().to_string(); + s.push(if x.is_ascii_lowercase() { '0' } else { '1' }); + s + } else if let Some(x) = arg.long { + x.to_string() + } else { + let mut s = '{'.to_string(); + s.push_str(arg.name); + s + }; + ord_v.push((arg.get_display_order(), key, arg)); + } + ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1))); + + let next_line_help = self.will_args_wrap(args, longest); + + for (i, (_, _, arg)) in ord_v.iter().enumerate() { + let last_arg = i + 1 == ord_v.len(); + self.write_arg(arg, last_arg, next_line_help, longest)?; + } + Ok(()) + } + + /// Writes help for an argument to the wrapped stream. + fn write_arg( + &mut self, + arg: &Arg<'help>, + last_arg: bool, + next_line_help: bool, + longest: usize, + ) -> io::Result<()> { + let spec_vals = &self.spec_vals(arg); + + self.write_arg_inner(arg, spec_vals, next_line_help, longest)?; + + if !last_arg { + self.none("\n")?; + if next_line_help { + self.none("\n")?; + } + } + Ok(()) + } + + /// Writes argument's short command to the wrapped stream. + fn short(&mut self, arg: &Arg<'help>) -> io::Result<()> { + debug!("Help::short"); + + self.none(TAB)?; + + if let Some(s) = arg.short { + self.good(format!("-{}", s)) + } else if !arg.is_positional() { + self.none(TAB) + } else { + Ok(()) + } + } + + /// Writes argument's long command to the wrapped stream. + fn long(&mut self, arg: &Arg<'help>) -> io::Result<()> { + debug!("Help::long"); + if let Some(long) = arg.long { + if arg.short.is_some() { + self.none(", ")?; + } + self.good(format!("--{}", long))?; + } + Ok(()) + } + + /// Writes argument's possible values to the wrapped stream. + fn val(&mut self, arg: &Arg<'help>) -> io::Result<()> { + debug!("Help::val: arg={}", arg.name); + let mut need_closing_bracket = false; + if arg.is_takes_value_set() && !arg.is_positional() { + let is_optional_val = arg.min_vals == Some(0); + let sep = if arg.is_require_equals_set() { + if is_optional_val { + need_closing_bracket = true; + "[=" + } else { + "=" + } + } else if is_optional_val { + need_closing_bracket = true; + " [" + } else { + " " + }; + self.none(sep)?; + } + + if arg.is_takes_value_set() || arg.is_positional() { + display_arg_val( + arg, + |s, good| if good { self.good(s) } else { self.none(s) }, + )?; + } + + if need_closing_bracket { + self.none("]")?; + } + Ok(()) + } + + /// Write alignment padding between arg's switches/values and its about message. + fn align_to_about( + &mut self, + arg: &Arg<'help>, + next_line_help: bool, + longest: usize, + ) -> io::Result<()> { + debug!("Help::align_to_about: arg={}", arg.name); + debug!("Help::align_to_about: Has switch..."); + if self.use_long { + // long help prints messages on the next line so it doesn't need to align text + debug!("Help::align_to_about: printing long help so skip alignment"); + } else if !arg.is_positional() { + debug!("Yes"); + debug!("Help::align_to_about: nlh...{:?}", next_line_help); + if !next_line_help { + let self_len = display_width(arg.to_string().as_str()); + // subtract ourself + let mut spcs = longest - self_len; + // Since we're writing spaces from the tab point we first need to know if we + // had a long and short, or just short + if arg.long.is_some() { + // Only account 4 after the val + spcs += 4; + } else { + // Only account for ', --' + 4 after the val + spcs += 8; + } + + self.spaces(spcs)?; + } + } else if !next_line_help { + debug!("No, and not next_line"); + self.spaces(longest + 4 - display_width(&arg.to_string()))?; + } else { + debug!("No"); + } + Ok(()) + } + + fn write_before_help(&mut self) -> io::Result<()> { + debug!("Help::write_before_help"); + let before_help = if self.use_long { + self.cmd + .get_before_long_help() + .or_else(|| self.cmd.get_before_help()) + } else { + self.cmd.get_before_help() + }; + if let Some(output) = before_help { + self.none(text_wrapper(&output.replace("{n}", "\n"), self.term_w))?; + self.none("\n\n")?; + } + Ok(()) + } + + fn write_after_help(&mut self) -> io::Result<()> { + debug!("Help::write_after_help"); + let after_help = if self.use_long { + self.cmd + .get_after_long_help() + .or_else(|| self.cmd.get_after_help()) + } else { + self.cmd.get_after_help() + }; + if let Some(output) = after_help { + self.none("\n\n")?; + self.none(text_wrapper(&output.replace("{n}", "\n"), self.term_w))?; + } + Ok(()) + } + + /// Writes argument's help to the wrapped stream. + fn help( + &mut self, + arg: Option<&Arg<'help>>, + about: &str, + spec_vals: &str, + next_line_help: bool, + longest: usize, + ) -> io::Result<()> { + debug!("Help::help"); + let mut help = String::from(about) + spec_vals; + debug!("Help::help: Next Line...{:?}", next_line_help); + + let spaces = if next_line_help { + 12 // "tab" * 3 + } else { + longest + 12 + }; + + let too_long = spaces + display_width(&help) >= self.term_w; + + // Is help on next line, if so then indent + if next_line_help { + self.none(format!("\n{}{}{}", TAB, TAB, TAB))?; + } + + debug!("Help::help: Too long..."); + if too_long && spaces <= self.term_w || help.contains("{n}") { + debug!("Yes"); + debug!("Help::help: help...{}", help); + debug!("Help::help: help width...{}", display_width(&help)); + // Determine how many newlines we need to insert + let avail_chars = self.term_w - spaces; + debug!("Help::help: Usable space...{}", avail_chars); + help = text_wrapper(&help.replace("{n}", "\n"), avail_chars); + } else { + debug!("No"); + } + if let Some(part) = help.lines().next() { + self.none(part)?; + } + + // indent of help + let spaces = if next_line_help { + TAB_WIDTH * 3 + } else if let Some(true) = arg.map(|a| a.is_positional()) { + longest + TAB_WIDTH * 2 + } else { + longest + TAB_WIDTH * 3 + }; + + for part in help.lines().skip(1) { + self.none("\n")?; + self.spaces(spaces)?; + self.none(part)?; + } + + #[cfg(feature = "unstable-v4")] + if let Some(arg) = arg { + const DASH_SPACE: usize = "- ".len(); + const COLON_SPACE: usize = ": ".len(); + if self.use_long + && !arg.is_hide_possible_values_set() + && arg + .possible_vals + .iter() + .any(PossibleValue::should_show_help) + { + debug!("Help::help: Found possible vals...{:?}", arg.possible_vals); + if !help.is_empty() { + self.none("\n\n")?; + self.spaces(spaces)?; + } + self.none("Possible values:")?; + let longest = arg + .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 = arg + .possible_vals + .iter() + .filter_map(|f| f.get_visible_help().map(display_width)) + .max() + .expect("Only called with possible value with help"); + // should new line + let taken = longest + spaces + DASH_SPACE; + + let possible_value_new_line = + self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest; + + let spaces = spaces + TAB_WIDTH - DASH_SPACE; + let spaces_help = if possible_value_new_line { + spaces + DASH_SPACE + } else { + spaces + longest + DASH_SPACE + COLON_SPACE + }; + + for pv in arg.possible_vals.iter().filter(|pv| !pv.is_hide_set()) { + self.none("\n")?; + self.spaces(spaces)?; + self.none("- ")?; + self.good(pv.get_name())?; + if let Some(help) = pv.get_help() { + debug!("Help::help: Possible Value help"); + + if possible_value_new_line { + self.none(":\n")?; + self.spaces(spaces_help)?; + } else { + self.none(": ")?; + // To align help messages + self.spaces(longest - display_width(pv.get_name()))?; + } + + let avail_chars = if self.term_w > spaces_help { + self.term_w - spaces_help + } else { + usize::MAX + }; + + let help = text_wrapper(help, avail_chars); + let mut help = help.lines(); + + self.none(help.next().unwrap_or_default())?; + for part in help { + self.none("\n")?; + self.spaces(spaces_help)?; + self.none(part)?; + } + } + } + } + } + Ok(()) + } + + /// Writes help for an argument to the wrapped stream. + fn write_arg_inner( + &mut self, + arg: &Arg<'help>, + spec_vals: &str, + next_line_help: bool, + longest: usize, + ) -> io::Result<()> { + self.short(arg)?; + self.long(arg)?; + self.val(arg)?; + self.align_to_about(arg, next_line_help, longest)?; + + let about = if self.use_long { + arg.long_help.or(arg.help).unwrap_or("") + } else { + arg.help.or(arg.long_help).unwrap_or("") + }; + + self.help(Some(arg), about, spec_vals, next_line_help, longest)?; + Ok(()) + } + + /// Will use next line help on writing args. + fn will_args_wrap(&self, args: &[&Arg<'help>], longest: usize) -> bool { + args.iter() + .filter(|arg| should_show_arg(self.use_long, *arg)) + .any(|arg| { + let spec_vals = &self.spec_vals(arg); + self.arg_next_line_help(arg, spec_vals, longest) + }) + } + + fn arg_next_line_help(&self, arg: &Arg<'help>, spec_vals: &str, longest: usize) -> bool { + if self.next_line_help || arg.is_next_line_help_set() || self.use_long { + // setting_next_line + true + } else { + // force_next_line + let h = arg.help.unwrap_or(""); + let h_w = display_width(h) + display_width(spec_vals); + let taken = longest + 12; + self.term_w >= taken + && (taken as f32 / self.term_w as f32) > 0.40 + && h_w > (self.term_w - taken) + } + } + + fn spec_vals(&self, a: &Arg) -> String { + debug!("Help::spec_vals: a={}", a); + let mut spec_vals = vec![]; + #[cfg(feature = "env")] + if let Some(ref env) = a.env { + if !a.is_hide_env_set() { + debug!( + "Help::spec_vals: Found environment variable...[{:?}:{:?}]", + env.0, env.1 + ); + let env_val = if !a.is_hide_env_values_set() { + format!( + "={}", + env.1 + .as_ref() + .map_or(Cow::Borrowed(""), |val| val.to_string_lossy()) + ) + } else { + String::new() + }; + let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val); + spec_vals.push(env_info); + } + } + if !a.is_hide_default_value_set() && !a.default_vals.is_empty() { + debug!( + "Help::spec_vals: Found default value...[{:?}]", + a.default_vals + ); + + let pvs = a + .default_vals + .iter() + .map(|&pvs| pvs.to_string_lossy()) + .map(|pvs| { + if pvs.contains(char::is_whitespace) { + Cow::from(format!("{:?}", pvs)) + } else { + pvs + } + }) + .collect::<Vec<_>>() + .join(" "); + + spec_vals.push(format!("[default: {}]", pvs)); + } + if !a.aliases.is_empty() { + debug!("Help::spec_vals: Found aliases...{:?}", a.aliases); + + let als = a + .aliases + .iter() + .filter(|&als| als.1) // visible + .map(|&als| als.0) // name + .collect::<Vec<_>>() + .join(", "); + + if !als.is_empty() { + spec_vals.push(format!("[aliases: {}]", als)); + } + } + + if !a.short_aliases.is_empty() { + debug!( + "Help::spec_vals: Found short aliases...{:?}", + a.short_aliases + ); + + let als = a + .short_aliases + .iter() + .filter(|&als| als.1) // visible + .map(|&als| als.0.to_string()) // name + .collect::<Vec<_>>() + .join(", "); + + if !als.is_empty() { + spec_vals.push(format!("[short aliases: {}]", als)); + } + } + + if !(a.is_hide_possible_values_set() + || a.possible_vals.is_empty() + || cfg!(feature = "unstable-v4") + && self.use_long + && a.possible_vals.iter().any(PossibleValue::should_show_help)) + { + debug!( + "Help::spec_vals: Found possible vals...{:?}", + a.possible_vals + ); + + let pvs = a + .possible_vals + .iter() + .filter_map(PossibleValue::get_visible_quoted_name) + .collect::<Vec<_>>() + .join(", "); + + spec_vals.push(format!("[possible values: {}]", pvs)); + } + let connector = if self.use_long { "\n" } else { " " }; + let prefix = if !spec_vals.is_empty() && !a.get_help().unwrap_or("").is_empty() { + if self.use_long { + "\n\n" + } else { + " " + } + } else { + "" + }; + prefix.to_string() + &spec_vals.join(connector) + } + + fn write_about(&mut self, before_new_line: bool, after_new_line: bool) -> io::Result<()> { + let about = if self.use_long { + self.cmd.get_long_about().or_else(|| self.cmd.get_about()) + } else { + self.cmd.get_about() + }; + if let Some(output) = about { + if before_new_line { + self.none("\n")?; + } + self.none(text_wrapper(output, self.term_w))?; + if after_new_line { + self.none("\n")?; + } + } + Ok(()) + } + + fn write_author(&mut self, before_new_line: bool, after_new_line: bool) -> io::Result<()> { + if let Some(author) = self.cmd.get_author() { + if before_new_line { + self.none("\n")?; + } + self.none(text_wrapper(author, self.term_w))?; + if after_new_line { + self.none("\n")?; + } + } + Ok(()) + } + + fn write_version(&mut self) -> io::Result<()> { + let version = self + .cmd + .get_version() + .or_else(|| self.cmd.get_long_version()); + if let Some(output) = version { + self.none(text_wrapper(output, self.term_w))?; + } + Ok(()) + } +} + +/// Methods to write a single subcommand +impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { + fn write_subcommand( + &mut self, + sc_str: &str, + cmd: &Command<'help>, + next_line_help: bool, + longest: usize, + ) -> io::Result<()> { + debug!("Help::write_subcommand"); + + let spec_vals = &self.sc_spec_vals(cmd); + + let about = cmd + .get_about() + .or_else(|| cmd.get_long_about()) + .unwrap_or(""); + + self.subcmd(sc_str, next_line_help, longest)?; + self.help(None, about, spec_vals, next_line_help, longest) + } + + fn sc_spec_vals(&self, a: &Command) -> String { + debug!("Help::sc_spec_vals: a={}", a.get_name()); + let mut spec_vals = vec![]; + if 0 < a.get_all_aliases().count() || 0 < a.get_all_short_flag_aliases().count() { + debug!( + "Help::spec_vals: Found aliases...{:?}", + a.get_all_aliases().collect::<Vec<_>>() + ); + debug!( + "Help::spec_vals: Found short flag aliases...{:?}", + a.get_all_short_flag_aliases().collect::<Vec<_>>() + ); + + let mut short_als = a + .get_visible_short_flag_aliases() + .map(|a| format!("-{}", a)) + .collect::<Vec<_>>(); + + let als = a.get_visible_aliases().map(|s| s.to_string()); + + short_als.extend(als); + + let all_als = short_als.join(", "); + + if !all_als.is_empty() { + spec_vals.push(format!(" [aliases: {}]", all_als)); + } + } + spec_vals.join(" ") + } + + fn subcommand_next_line_help( + &self, + cmd: &Command<'help>, + spec_vals: &str, + longest: usize, + ) -> bool { + if self.next_line_help | self.use_long { + // setting_next_line + true + } else { + // force_next_line + let h = cmd.get_about().unwrap_or(""); + let h_w = display_width(h) + display_width(spec_vals); + let taken = longest + 12; + self.term_w >= taken + && (taken as f32 / self.term_w as f32) > 0.40 + && h_w > (self.term_w - taken) + } + } + + /// Writes subcommand to the wrapped stream. + fn subcmd(&mut self, sc_str: &str, next_line_help: bool, longest: usize) -> io::Result<()> { + self.none(TAB)?; + self.good(sc_str)?; + if !next_line_help { + let width = display_width(sc_str); + self.spaces(width.max(longest + 4) - width)?; + } + Ok(()) + } +} + +// Methods to write Parser help. +impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { + /// Writes help for all arguments (options, flags, args, subcommands) + /// including titles of a Parser Object to the wrapped stream. + pub(crate) fn write_all_args(&mut self) -> io::Result<()> { + debug!("Help::write_all_args"); + let pos = self + .cmd + .get_positionals_with_no_heading() + .filter(|arg| should_show_arg(self.use_long, arg)) + .collect::<Vec<_>>(); + let non_pos = self + .cmd + .get_non_positionals_with_no_heading() + .filter(|arg| should_show_arg(self.use_long, arg)) + .collect::<Vec<_>>(); + let subcmds = self.cmd.has_visible_subcommands(); + + let custom_headings = self + .cmd + .get_arguments() + .filter_map(|arg| arg.get_help_heading()) + .collect::<IndexSet<_>>(); + + let mut first = if !pos.is_empty() { + // Write positional args if any + self.warning("ARGS:\n")?; + self.write_args_unsorted(&pos)?; + false + } else { + true + }; + + if !non_pos.is_empty() { + if !first { + self.none("\n\n")?; + } + self.warning("OPTIONS:\n")?; + self.write_args(&non_pos)?; + first = false; + } + if !custom_headings.is_empty() { + for heading in custom_headings { + let args = self + .cmd + .get_arguments() + .filter(|a| { + if let Some(help_heading) = a.get_help_heading() { + return help_heading == heading; + } + false + }) + .filter(|arg| should_show_arg(self.use_long, arg)) + .collect::<Vec<_>>(); + + if !args.is_empty() { + if !first { + self.none("\n\n")?; + } + self.warning(format!("{}:\n", heading))?; + self.write_args(&args)?; + first = false + } + } + } + + if subcmds { + if !first { + self.none("\n\n")?; + } + + self.warning( + self.cmd + .get_subcommand_help_heading() + .unwrap_or("SUBCOMMANDS"), + )?; + self.warning(":\n")?; + + self.write_subcommands(self.cmd)?; + } + + Ok(()) + } + + /// Will use next line help on writing subcommands. + fn will_subcommands_wrap<'a>( + &self, + subcommands: impl IntoIterator<Item = &'a Command<'help>>, + longest: usize, + ) -> bool + where + 'help: 'a, + { + subcommands + .into_iter() + .filter(|&subcommand| should_show_subcommand(subcommand)) + .any(|subcommand| { + let spec_vals = &self.sc_spec_vals(subcommand); + self.subcommand_next_line_help(subcommand, spec_vals, longest) + }) + } + + /// Writes help for subcommands of a Parser Object to the wrapped stream. + fn write_subcommands(&mut self, cmd: &Command<'help>) -> io::Result<()> { + debug!("Help::write_subcommands"); + // The shortest an arg can legally be is 2 (i.e. '-x') + let mut longest = 2; + let mut ord_v = Vec::new(); + for subcommand in cmd + .get_subcommands() + .filter(|subcommand| should_show_subcommand(subcommand)) + { + let mut sc_str = String::new(); + sc_str.push_str(subcommand.get_name()); + if let Some(short) = subcommand.get_short_flag() { + write!(sc_str, " -{}", short).unwrap(); + } + if let Some(long) = subcommand.get_long_flag() { + write!(sc_str, " --{}", long).unwrap(); + } + longest = longest.max(display_width(&sc_str)); + ord_v.push((subcommand.get_display_order(), sc_str, subcommand)); + } + ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1))); + + debug!("Help::write_subcommands longest = {}", longest); + + let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest); + + let mut first = true; + for (_, sc_str, sc) in &ord_v { + if first { + first = false; + } else { + self.none("\n")?; + } + self.write_subcommand(sc_str, sc, next_line_help, longest)?; + } + Ok(()) + } + + /// Writes binary name of a Parser Object to the wrapped stream. + fn write_display_name(&mut self) -> io::Result<()> { + debug!("Help::write_display_name"); + + let display_name = text_wrapper( + &self + .cmd + .get_display_name() + .unwrap_or_else(|| self.cmd.get_name()) + .replace("{n}", "\n"), + self.term_w, + ); + self.good(&display_name)?; + Ok(()) + } + + /// Writes binary name of a Parser Object to the wrapped stream. + fn write_bin_name(&mut self) -> io::Result<()> { + debug!("Help::write_bin_name"); + + let bin_name = if let Some(bn) = self.cmd.get_bin_name() { + if bn.contains(' ') { + // In case we're dealing with subcommands i.e. git mv is translated to git-mv + bn.replace(' ', "-") + } else { + text_wrapper(&self.cmd.get_name().replace("{n}", "\n"), self.term_w) + } + } else { + text_wrapper(&self.cmd.get_name().replace("{n}", "\n"), self.term_w) + }; + self.good(&bin_name)?; + Ok(()) + } +} + +// Methods to write Parser help using templates. +impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> { + /// Write help to stream for the parser in the format defined by the template. + /// + /// For details about the template language see [`Command::help_template`]. + /// + /// [`Command::help_template`]: Command::help_template() + fn write_templated_help(&mut self, template: &str) -> io::Result<()> { + debug!("Help::write_templated_help"); + + // The strategy is to copy the template from the reader to wrapped stream + // until a tag is found. Depending on its value, the appropriate content is copied + // to the wrapped stream. + // The copy from template is then resumed, repeating this sequence until reading + // the complete template. + + macro_rules! tags { + ( + match $part:ident { + $( $tag:expr => $action:stmt )* + } + ) => { + match $part { + $( + part if part.starts_with(concat!($tag, "}")) => { + $action + let rest = &part[$tag.len()+1..]; + self.none(rest)?; + } + )* + + // Unknown tag, write it back. + part => { + self.none("{")?; + self.none(part)?; + } + } + }; + } + + let mut parts = template.split('{'); + if let Some(first) = parts.next() { + self.none(first)?; + } + + for part in parts { + tags! { + match part { + "name" => { + self.write_display_name()?; + } + "bin" => { + self.write_bin_name()?; + } + "version" => { + self.write_version()?; + } + "author" => { + self.write_author(false, false)?; + } + "author-with-newline" => { + self.write_author(false, true)?; + } + "author-section" => { + self.write_author(true, true)?; + } + "about" => { + self.write_about(false, false)?; + } + "about-with-newline" => { + self.write_about(false, true)?; + } + "about-section" => { + self.write_about(true, true)?; + } + "usage-heading" => { + self.warning("USAGE:")?; + } + "usage" => { + self.none(self.usage.create_usage_no_title(&[]))?; + } + "all-args" => { + self.write_all_args()?; + } + "options" => { + // Include even those with a heading as we don't have a good way of + // handling help_heading in the template. + self.write_args(&self.cmd.get_non_positionals().collect::<Vec<_>>())?; + } + "positionals" => { + self.write_args(&self.cmd.get_positionals().collect::<Vec<_>>())?; + } + "subcommands" => { + self.write_subcommands(self.cmd)?; + } + "after-help" => { + self.write_after_help()?; + } + "before-help" => { + self.write_before_help()?; + } + } + } + } + + Ok(()) + } +} + +pub(crate) fn dimensions() -> Option<(usize, usize)> { + #[cfg(not(feature = "wrap_help"))] + return None; + + #[cfg(feature = "wrap_help")] + terminal_size::terminal_size().map(|(w, h)| (w.0.into(), h.0.into())) +} + +const TAB: &str = " "; +const TAB_WIDTH: usize = 4; + +pub(crate) enum HelpWriter<'writer> { + Normal(&'writer mut dyn Write), + Buffer(&'writer mut Colorizer), +} + +fn should_show_arg(use_long: bool, arg: &Arg) -> bool { + debug!("should_show_arg: use_long={:?}, arg={}", use_long, arg.name); + if arg.is_hide_set() { + return false; + } + (!arg.is_hide_long_help_set() && use_long) + || (!arg.is_hide_short_help_set() && !use_long) + || arg.is_next_line_help_set() +} + +fn should_show_subcommand(subcommand: &Command) -> bool { + !subcommand.is_hide_set() +} + +fn text_wrapper(help: &str, width: usize) -> String { + let wrapper = textwrap::Options::new(width) + .break_words(false) + .word_splitter(textwrap::WordSplitter::NoHyphenation); + help.lines() + .map(|line| textwrap::fill(line, &wrapper)) + .collect::<Vec<String>>() + .join("\n") +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn wrap_help_last_word() { + let help = String::from("foo bar baz"); + assert_eq!(text_wrapper(&help, 5), "foo\nbar\nbaz"); + } + + #[test] + fn display_width_handles_non_ascii() { + // Popular Danish tongue-twister, the name of a fruit dessert. + let text = "rødgrød med fløde"; + assert_eq!(display_width(text), 17); + // Note that the string width is smaller than the string + // length. This is due to the precomposed non-ASCII letters: + assert_eq!(text.len(), 20); + } + + #[test] + fn display_width_handles_emojis() { + let text = "😂"; + // There is a single `char`... + assert_eq!(text.chars().count(), 1); + // but it is double-width: + assert_eq!(display_width(text), 2); + // This is much less than the byte length: + assert_eq!(text.len(), 4); + } +} diff --git a/third_party/rust/clap/src/output/mod.rs b/third_party/rust/clap/src/output/mod.rs new file mode 100644 index 0000000000..e32aac26a0 --- /dev/null +++ b/third_party/rust/clap/src/output/mod.rs @@ -0,0 +1,7 @@ +mod help; +mod usage; + +pub(crate) mod fmt; + +pub(crate) use self::help::{Help, HelpWriter}; +pub(crate) use self::usage::Usage; diff --git a/third_party/rust/clap/src/output/usage.rs b/third_party/rust/clap/src/output/usage.rs new file mode 100644 index 0000000000..f223d9c127 --- /dev/null +++ b/third_party/rust/clap/src/output/usage.rs @@ -0,0 +1,450 @@ +use indexmap::IndexSet; + +// Internal +use crate::build::AppSettings as AS; +use crate::build::{Arg, ArgPredicate, Command}; +use crate::parse::ArgMatcher; +use crate::util::ChildGraph; +use crate::util::Id; +use crate::INTERNAL_ERROR_MSG; + +pub(crate) struct Usage<'help, 'cmd> { + cmd: &'cmd Command<'help>, + required: Option<&'cmd ChildGraph<Id>>, +} + +impl<'help, 'cmd> Usage<'help, 'cmd> { + pub(crate) fn new(cmd: &'cmd Command<'help>) -> Self { + Usage { + cmd, + required: None, + } + } + + pub(crate) fn required(mut self, required: &'cmd ChildGraph<Id>) -> Self { + self.required = Some(required); + self + } + + // Creates a usage string for display. This happens just after all arguments were parsed, but before + // any subcommands have been parsed (so as to give subcommands their own usage recursively) + pub(crate) fn create_usage_with_title(&self, used: &[Id]) -> String { + debug!("Usage::create_usage_with_title"); + let mut usage = String::with_capacity(75); + usage.push_str("USAGE:\n "); + usage.push_str(&*self.create_usage_no_title(used)); + usage + } + + // Creates a usage string (*without title*) if one was not provided by the user manually. + pub(crate) fn create_usage_no_title(&self, used: &[Id]) -> String { + debug!("Usage::create_usage_no_title"); + if let Some(u) = self.cmd.get_override_usage() { + String::from(&*u) + } else if used.is_empty() { + self.create_help_usage(true) + } else { + self.create_smart_usage(used) + } + } + + // Creates a usage string for display in help messages (i.e. not for errors) + fn create_help_usage(&self, incl_reqs: bool) -> String { + debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs); + let mut usage = String::with_capacity(75); + let name = self + .cmd + .get_usage_name() + .or_else(|| self.cmd.get_bin_name()) + .unwrap_or_else(|| self.cmd.get_name()); + usage.push_str(name); + let req_string = if incl_reqs { + self.get_required_usage_from(&[], None, false) + .iter() + .fold(String::new(), |a, s| a + " " + s) + } else { + String::new() + }; + + if self.needs_options_tag() { + usage.push_str(" [OPTIONS]"); + } + + let allow_missing_positional = self.cmd.is_allow_missing_positional_set(); + if !allow_missing_positional { + usage.push_str(&req_string); + } + + let has_last = self.cmd.get_positionals().any(|p| p.is_last_set()); + // places a '--' in the usage string if there are args and options + // supporting multiple values + if self + .cmd + .get_non_positionals() + .any(|o| o.is_multiple_values_set()) + && self.cmd.get_positionals().any(|p| !p.is_required_set()) + && !(self.cmd.has_visible_subcommands() || self.cmd.is_allow_external_subcommands_set()) + && !has_last + { + usage.push_str(" [--]"); + } + let not_req_or_hidden = + |p: &Arg| (!p.is_required_set() || p.is_last_set()) && !p.is_hide_set(); + if self.cmd.get_positionals().any(not_req_or_hidden) { + if let Some(args_tag) = self.get_args_tag(incl_reqs) { + usage.push_str(&*args_tag); + } else { + usage.push_str(" [ARGS]"); + } + if has_last && incl_reqs { + let pos = self + .cmd + .get_positionals() + .find(|p| p.is_last_set()) + .expect(INTERNAL_ERROR_MSG); + debug!("Usage::create_help_usage: '{}' has .last(true)", pos.name); + let req = pos.is_required_set(); + if req && self.cmd.get_positionals().any(|p| !p.is_required_set()) { + usage.push_str(" -- <"); + } else if req { + usage.push_str(" [--] <"); + } else { + usage.push_str(" [-- <"); + } + usage.push_str(&*pos.name_no_brackets()); + usage.push('>'); + usage.push_str(pos.multiple_str()); + if !req { + usage.push(']'); + } + } + } + + if allow_missing_positional { + usage.push_str(&req_string); + } + + // incl_reqs is only false when this function is called recursively + if self.cmd.has_visible_subcommands() && incl_reqs + || self.cmd.is_allow_external_subcommands_set() + { + let placeholder = self.cmd.get_subcommand_value_name().unwrap_or("SUBCOMMAND"); + #[allow(deprecated)] + if self.cmd.is_subcommand_negates_reqs_set() + || self.cmd.is_args_conflicts_with_subcommands_set() + { + usage.push_str("\n "); + if !self.cmd.is_args_conflicts_with_subcommands_set() { + usage.push_str(&*self.create_help_usage(false)); + } else { + usage.push_str(&*name); + } + usage.push_str(" <"); + usage.push_str(placeholder); + usage.push('>'); + } else if self.cmd.is_subcommand_required_set() + || self.cmd.is_set(AS::SubcommandRequiredElseHelp) + { + usage.push_str(" <"); + usage.push_str(placeholder); + usage.push('>'); + } else { + usage.push_str(" ["); + usage.push_str(placeholder); + usage.push(']'); + } + } + let usage = usage.trim().to_owned(); + debug!("Usage::create_help_usage: usage={}", usage); + usage + } + + // Creates a context aware usage string, or "smart usage" from currently used + // args, and requirements + fn create_smart_usage(&self, used: &[Id]) -> String { + debug!("Usage::create_smart_usage"); + let mut usage = String::with_capacity(75); + + let r_string = self + .get_required_usage_from(used, None, true) + .iter() + .fold(String::new(), |acc, s| acc + " " + s); + + usage.push_str( + self.cmd + .get_usage_name() + .or_else(|| self.cmd.get_bin_name()) + .unwrap_or_else(|| self.cmd.get_name()), + ); + usage.push_str(&*r_string); + if self.cmd.is_subcommand_required_set() { + usage.push_str(" <"); + usage.push_str(self.cmd.get_subcommand_value_name().unwrap_or("SUBCOMMAND")); + usage.push('>'); + } + usage.shrink_to_fit(); + usage + } + + // Gets the `[ARGS]` tag for the usage string + fn get_args_tag(&self, incl_reqs: bool) -> Option<String> { + debug!("Usage::get_args_tag; incl_reqs = {:?}", incl_reqs); + let mut count = 0; + for pos in self + .cmd + .get_positionals() + .filter(|pos| !pos.is_required_set()) + .filter(|pos| !pos.is_hide_set()) + .filter(|pos| !pos.is_last_set()) + { + debug!("Usage::get_args_tag:iter:{}", pos.name); + let required = self.cmd.groups_for_arg(&pos.id).any(|grp_s| { + debug!("Usage::get_args_tag:iter:{:?}:iter:{:?}", pos.name, grp_s); + // if it's part of a required group we don't want to count it + self.cmd.get_groups().any(|g| g.required && (g.id == grp_s)) + }); + if !required { + count += 1; + debug!( + "Usage::get_args_tag:iter: {} Args not required or hidden", + count + ); + } + } + + if !self.cmd.is_dont_collapse_args_in_usage_set() && count > 1 { + debug!("Usage::get_args_tag:iter: More than one, returning [ARGS]"); + + // [ARGS] + None + } else if count == 1 && incl_reqs { + let pos = self + .cmd + .get_positionals() + .find(|pos| { + !pos.is_required_set() + && !pos.is_hide_set() + && !pos.is_last_set() + && !self.cmd.groups_for_arg(&pos.id).any(|grp_s| { + debug!("Usage::get_args_tag:iter:{:?}:iter:{:?}", pos.name, grp_s); + // if it's part of a required group we don't want to count it + self.cmd.get_groups().any(|g| g.required && (g.id == grp_s)) + }) + }) + .expect(INTERNAL_ERROR_MSG); + + debug!( + "Usage::get_args_tag:iter: Exactly one, returning '{}'", + pos.name + ); + + Some(format!( + " [{}]{}", + pos.name_no_brackets(), + pos.multiple_str() + )) + } else if self.cmd.is_dont_collapse_args_in_usage_set() + && self.cmd.has_positionals() + && incl_reqs + { + debug!("Usage::get_args_tag:iter: Don't collapse returning all"); + Some( + self.cmd + .get_positionals() + .filter(|pos| !pos.is_required_set()) + .filter(|pos| !pos.is_hide_set()) + .filter(|pos| !pos.is_last_set()) + .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str())) + .collect::<Vec<_>>() + .join(""), + ) + } else if !incl_reqs { + debug!("Usage::get_args_tag:iter: incl_reqs=false, building secondary usage string"); + let highest_req_pos = self + .cmd + .get_positionals() + .filter_map(|pos| { + if pos.is_required_set() && !pos.is_last_set() { + Some(pos.index) + } else { + None + } + }) + .max() + .unwrap_or_else(|| Some(self.cmd.get_positionals().count())); + Some( + self.cmd + .get_positionals() + .filter(|pos| pos.index <= highest_req_pos) + .filter(|pos| !pos.is_required_set()) + .filter(|pos| !pos.is_hide_set()) + .filter(|pos| !pos.is_last_set()) + .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str())) + .collect::<Vec<_>>() + .join(""), + ) + } else { + Some("".into()) + } + } + + // Determines if we need the `[OPTIONS]` tag in the usage string + fn needs_options_tag(&self) -> bool { + debug!("Usage::needs_options_tag"); + 'outer: for f in self.cmd.get_non_positionals() { + debug!("Usage::needs_options_tag:iter: f={}", f.name); + + // Don't print `[OPTIONS]` just for help or version + if f.long == Some("help") || f.long == Some("version") { + debug!("Usage::needs_options_tag:iter Option is built-in"); + continue; + } + + if f.is_hide_set() { + debug!("Usage::needs_options_tag:iter Option is hidden"); + continue; + } + if f.is_required_set() { + debug!("Usage::needs_options_tag:iter Option is required"); + continue; + } + for grp_s in self.cmd.groups_for_arg(&f.id) { + debug!("Usage::needs_options_tag:iter:iter: grp_s={:?}", grp_s); + if self.cmd.get_groups().any(|g| g.id == grp_s && g.required) { + debug!("Usage::needs_options_tag:iter:iter: Group is required"); + continue 'outer; + } + } + + debug!("Usage::needs_options_tag:iter: [OPTIONS] required"); + return true; + } + + debug!("Usage::needs_options_tag: [OPTIONS] not required"); + false + } + + // Returns the required args in usage string form by fully unrolling all groups + // `incl_last`: should we include args that are Arg::Last? (i.e. `prog [foo] -- [last]). We + // can't do that for required usages being built for subcommands because it would look like: + // `prog [foo] -- [last] <subcommand>` which is totally wrong. + pub(crate) fn get_required_usage_from( + &self, + incls: &[Id], + matcher: Option<&ArgMatcher>, + incl_last: bool, + ) -> IndexSet<String> { + debug!( + "Usage::get_required_usage_from: incls={:?}, matcher={:?}, incl_last={:?}", + incls, + matcher.is_some(), + incl_last + ); + let mut ret_val = IndexSet::new(); + + let mut unrolled_reqs = IndexSet::new(); + + let required_owned; + let required = if let Some(required) = self.required { + required + } else { + required_owned = self.cmd.required_graph(); + &required_owned + }; + + for a in required.iter() { + let is_relevant = |(val, req_arg): &(ArgPredicate<'_>, Id)| -> Option<Id> { + let required = match val { + ArgPredicate::Equals(_) => { + if let Some(matcher) = matcher { + matcher.check_explicit(a, *val) + } else { + false + } + } + ArgPredicate::IsPresent => true, + }; + required.then(|| req_arg.clone()) + }; + + for aa in self.cmd.unroll_arg_requires(is_relevant, a) { + // if we don't check for duplicates here this causes duplicate error messages + // see https://github.com/clap-rs/clap/issues/2770 + unrolled_reqs.insert(aa); + } + // always include the required arg itself. it will not be enumerated + // by unroll_requirements_for_arg. + unrolled_reqs.insert(a.clone()); + } + + debug!( + "Usage::get_required_usage_from: unrolled_reqs={:?}", + unrolled_reqs + ); + + let args_in_groups = self + .cmd + .get_groups() + .filter(|gn| required.contains(&gn.id)) + .flat_map(|g| self.cmd.unroll_args_in_group(&g.id)) + .collect::<Vec<_>>(); + + for a in unrolled_reqs + .iter() + .chain(incls.iter()) + .filter(|name| !self.cmd.get_positionals().any(|p| &&p.id == name)) + .filter(|name| !self.cmd.get_groups().any(|g| &&g.id == name)) + .filter(|name| !args_in_groups.contains(name)) + .filter(|name| !(matcher.is_some() && matcher.as_ref().unwrap().contains(name))) + { + debug!("Usage::get_required_usage_from:iter:{:?}", a); + let arg = self.cmd.find(a).expect(INTERNAL_ERROR_MSG).to_string(); + ret_val.insert(arg); + } + let mut g_vec: Vec<String> = vec![]; + for g in unrolled_reqs + .iter() + .filter(|n| self.cmd.get_groups().any(|g| g.id == **n)) + { + // don't print requirement for required groups that have an arg. + if let Some(m) = matcher { + let have_group_entry = self + .cmd + .unroll_args_in_group(g) + .iter() + .any(|arg| m.contains(arg)); + if have_group_entry { + continue; + } + } + + let elem = self.cmd.format_group(g); + if !g_vec.contains(&elem) { + g_vec.push(elem); + } + } + ret_val.extend(g_vec); + + let mut pvec = unrolled_reqs + .iter() + .chain(incls.iter()) + .filter(|a| self.cmd.get_positionals().any(|p| &&p.id == a)) + .filter(|&pos| matcher.map_or(true, |m| !m.contains(pos))) + .filter_map(|pos| self.cmd.find(pos)) + .filter(|&pos| incl_last || !pos.is_last_set()) + .filter(|pos| !args_in_groups.contains(&pos.id)) + .map(|pos| (pos.index.unwrap(), pos)) + .collect::<Vec<(usize, &Arg)>>(); + pvec.sort_by_key(|(ind, _)| *ind); // sort by index + + for (_, p) in pvec { + debug!("Usage::get_required_usage_from:push:{:?}", p.id); + if !args_in_groups.contains(&p.id) { + ret_val.insert(p.to_string()); + } + } + + debug!("Usage::get_required_usage_from: ret_val={:?}", ret_val); + ret_val + } +} diff --git a/third_party/rust/clap/src/parse/arg_matcher.rs b/third_party/rust/clap/src/parse/arg_matcher.rs new file mode 100644 index 0000000000..31804a46fc --- /dev/null +++ b/third_party/rust/clap/src/parse/arg_matcher.rs @@ -0,0 +1,234 @@ +// Std +use std::{collections::HashMap, ffi::OsString, mem, ops::Deref}; + +// Internal +use crate::{ + build::{Arg, ArgPredicate, Command}, + parse::{ArgMatches, MatchedArg, SubCommand, ValueSource}, + util::Id, +}; + +// Third party +use indexmap::map::Entry; + +#[derive(Debug, Default)] +pub(crate) struct ArgMatcher(ArgMatches); + +impl ArgMatcher { + pub(crate) fn new(_cmd: &Command) -> Self { + ArgMatcher(ArgMatches { + #[cfg(debug_assertions)] + valid_args: { + let args = _cmd.get_arguments().map(|a| a.id.clone()); + let groups = _cmd.get_groups().map(|g| g.id.clone()); + args.chain(groups).collect() + }, + #[cfg(debug_assertions)] + valid_subcommands: _cmd.get_subcommands().map(|sc| sc.get_id()).collect(), + // HACK: Allow an external subcommand's ArgMatches be a stand-in for any ArgMatches + // since users can't detect it and avoid the asserts. + // + // See clap-rs/clap#3263 + #[cfg(debug_assertions)] + #[cfg(not(feature = "unstable-v4"))] + disable_asserts: _cmd.is_allow_external_subcommands_set(), + #[cfg(debug_assertions)] + #[cfg(feature = "unstable-v4")] + disable_asserts: false, + ..Default::default() + }) + } + + pub(crate) fn into_inner(self) -> ArgMatches { + self.0 + } + + pub(crate) fn propagate_globals(&mut self, global_arg_vec: &[Id]) { + debug!( + "ArgMatcher::get_global_values: global_arg_vec={:?}", + global_arg_vec + ); + let mut vals_map = HashMap::new(); + self.fill_in_global_values(global_arg_vec, &mut vals_map); + } + + fn fill_in_global_values( + &mut self, + global_arg_vec: &[Id], + vals_map: &mut HashMap<Id, MatchedArg>, + ) { + for global_arg in global_arg_vec { + if let Some(ma) = self.get(global_arg) { + // We have to check if the parent's global arg wasn't used but still exists + // such as from a default value. + // + // For example, `myprog subcommand --global-arg=value` where --global-arg defines + // a default value of `other` myprog would have an existing MatchedArg for + // --global-arg where the value is `other`, however the occurs will be 0. + let to_update = if let Some(parent_ma) = vals_map.get(global_arg) { + if parent_ma.get_occurrences() > 0 && ma.get_occurrences() == 0 { + parent_ma + } else { + ma + } + } else { + ma + } + .clone(); + vals_map.insert(global_arg.clone(), to_update); + } + } + if let Some(ref mut sc) = self.0.subcommand { + let mut am = ArgMatcher(mem::take(&mut sc.matches)); + am.fill_in_global_values(global_arg_vec, vals_map); + mem::swap(&mut am.0, &mut sc.matches); + } + + for (name, matched_arg) in vals_map.iter_mut() { + self.0.args.insert(name.clone(), matched_arg.clone()); + } + } + + #[cfg(not(feature = "unstable-v4"))] + pub(crate) fn get_mut(&mut self, arg: &Id) -> Option<&mut MatchedArg> { + self.0.args.get_mut(arg) + } + + pub(crate) fn get(&self, arg: &Id) -> Option<&MatchedArg> { + self.0.args.get(arg) + } + + pub(crate) fn remove(&mut self, arg: &Id) { + self.0.args.swap_remove(arg); + } + + pub(crate) fn contains(&self, arg: &Id) -> bool { + self.0.args.contains_key(arg) + } + + pub(crate) fn arg_names(&self) -> indexmap::map::Keys<Id, MatchedArg> { + self.0.args.keys() + } + + pub(crate) fn entry(&mut self, arg: &Id) -> indexmap::map::Entry<Id, MatchedArg> { + self.0.args.entry(arg.clone()) + } + + pub(crate) fn subcommand(&mut self, sc: SubCommand) { + self.0.subcommand = Some(Box::new(sc)); + } + + pub(crate) fn subcommand_name(&self) -> Option<&str> { + self.0.subcommand_name() + } + + pub(crate) fn iter(&self) -> indexmap::map::Iter<Id, MatchedArg> { + self.0.args.iter() + } + + pub(crate) fn check_explicit<'a>(&self, arg: &Id, predicate: ArgPredicate<'a>) -> bool { + self.get(arg).map_or(false, |a| a.check_explicit(predicate)) + } + + pub(crate) fn inc_occurrence_of_arg(&mut self, arg: &Arg) { + let id = &arg.id; + debug!("ArgMatcher::inc_occurrence_of_arg: id={:?}", id); + let ma = self.entry(id).or_insert(MatchedArg::new()); + ma.update_ty(ValueSource::CommandLine); + ma.set_ignore_case(arg.is_ignore_case_set()); + ma.invalid_utf8_allowed(arg.is_allow_invalid_utf8_set()); + ma.inc_occurrences(); + } + + pub(crate) fn inc_occurrence_of_group(&mut self, id: &Id) { + debug!("ArgMatcher::inc_occurrence_of_group: id={:?}", id); + let ma = self.entry(id).or_insert(MatchedArg::new()); + ma.update_ty(ValueSource::CommandLine); + ma.inc_occurrences(); + } + + #[cfg(feature = "unstable-v4")] + pub(crate) fn inc_occurrence_of_external(&mut self, allow_invalid_utf8: bool) { + let id = &Id::empty_hash(); + debug!( + "ArgMatcher::inc_occurrence_of_external: id={:?}, allow_invalid_utf8={}", + id, allow_invalid_utf8 + ); + let ma = self.entry(id).or_insert(MatchedArg::new()); + ma.update_ty(ValueSource::CommandLine); + ma.invalid_utf8_allowed(allow_invalid_utf8); + ma.inc_occurrences(); + } + + pub(crate) fn add_val_to(&mut self, arg: &Id, val: OsString, ty: ValueSource, append: bool) { + if append { + self.append_val_to(arg, val, ty); + } else { + self.push_val_to(arg, val, ty); + } + } + + fn push_val_to(&mut self, arg: &Id, val: OsString, ty: ValueSource) { + // We will manually inc occurrences later(for flexibility under + // specific circumstances, like only add one occurrence for flag + // when we met: `--flag=one,two`). + let ma = self.entry(arg).or_default(); + ma.update_ty(ty); + ma.push_val(val); + } + + fn append_val_to(&mut self, arg: &Id, val: OsString, ty: ValueSource) { + let ma = self.entry(arg).or_default(); + ma.update_ty(ty); + ma.append_val(val); + } + + pub(crate) fn new_val_group(&mut self, arg: &Id) { + let ma = self.entry(arg).or_default(); + ma.new_val_group(); + } + + pub(crate) fn add_index_to(&mut self, arg: &Id, idx: usize, ty: ValueSource) { + let ma = self.entry(arg).or_default(); + ma.update_ty(ty); + ma.push_index(idx); + } + + pub(crate) fn has_val_groups(&mut self, arg: &Id) -> bool { + match self.entry(arg) { + Entry::Occupied(e) => e.get().has_val_groups(), + Entry::Vacant(_) => false, + } + } + + pub(crate) fn needs_more_vals(&self, o: &Arg) -> bool { + debug!("ArgMatcher::needs_more_vals: o={}", o.name); + if let Some(ma) = self.get(&o.id) { + let current_num = ma.num_vals(); + if let Some(num) = o.num_vals { + debug!("ArgMatcher::needs_more_vals: num_vals...{}", num); + return if o.is_multiple_occurrences_set() { + (current_num % num) != 0 + } else { + num != current_num + }; + } else if let Some(num) = o.max_vals { + debug!("ArgMatcher::needs_more_vals: max_vals...{}", num); + return current_num < num; + } else if o.min_vals.is_some() { + debug!("ArgMatcher::needs_more_vals: min_vals...true"); + return true; + } + return o.is_multiple_values_set(); + } + true + } +} + +impl Deref for ArgMatcher { + type Target = ArgMatches; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} diff --git a/third_party/rust/clap/src/parse/features/mod.rs b/third_party/rust/clap/src/parse/features/mod.rs new file mode 100644 index 0000000000..bdeb766ecd --- /dev/null +++ b/third_party/rust/clap/src/parse/features/mod.rs @@ -0,0 +1 @@ +pub(crate) mod suggestions; diff --git a/third_party/rust/clap/src/parse/features/suggestions.rs b/third_party/rust/clap/src/parse/features/suggestions.rs new file mode 100644 index 0000000000..77ba8c7a25 --- /dev/null +++ b/third_party/rust/clap/src/parse/features/suggestions.rs @@ -0,0 +1,105 @@ +#[cfg(feature = "suggestions")] +use std::cmp::Ordering; + +// Internal +use crate::build::Command; + +/// Produces multiple strings from a given list of possible values which are similar +/// to the passed in value `v` within a certain confidence by least confidence. +/// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield +/// `Some("foo")`, whereas "blark" would yield `None`. +#[cfg(feature = "suggestions")] +pub(crate) fn did_you_mean<T, I>(v: &str, possible_values: I) -> Vec<String> +where + T: AsRef<str>, + I: IntoIterator<Item = T>, +{ + let mut candidates: Vec<(f64, String)> = possible_values + .into_iter() + .map(|pv| (strsim::jaro_winkler(v, pv.as_ref()), pv.as_ref().to_owned())) + .filter(|(confidence, _)| *confidence > 0.8) + .collect(); + candidates.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal)); + candidates.into_iter().map(|(_, pv)| pv).collect() +} + +#[cfg(not(feature = "suggestions"))] +pub(crate) fn did_you_mean<T, I>(_: &str, _: I) -> Vec<String> +where + T: AsRef<str>, + I: IntoIterator<Item = T>, +{ + Vec::new() +} + +/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase +pub(crate) fn did_you_mean_flag<'a, 'help, I, T>( + arg: &str, + remaining_args: &[&str], + longs: I, + subcommands: impl IntoIterator<Item = &'a mut Command<'help>>, +) -> Option<(String, Option<String>)> +where + 'help: 'a, + T: AsRef<str>, + I: IntoIterator<Item = T>, +{ + use crate::mkeymap::KeyType; + + match did_you_mean(arg, longs).pop() { + Some(candidate) => Some((candidate, None)), + None => subcommands + .into_iter() + .filter_map(|subcommand| { + subcommand._build_self(); + + let longs = subcommand.get_keymap().keys().filter_map(|a| { + if let KeyType::Long(v) = a { + Some(v.to_string_lossy().into_owned()) + } else { + None + } + }); + + let subcommand_name = subcommand.get_name(); + + let candidate = did_you_mean(arg, longs).pop()?; + let score = remaining_args.iter().position(|x| *x == subcommand_name)?; + Some((score, (candidate, Some(subcommand_name.to_string())))) + }) + .min_by_key(|(x, _)| *x) + .map(|(_, suggestion)| suggestion), + } +} + +#[cfg(all(test, features = "suggestions"))] +mod test { + use super::*; + + #[test] + fn possible_values_match() { + let p_vals = ["test", "possible", "values"]; + assert_eq!(did_you_mean("tst", p_vals.iter()), Some("test")); + } + + #[test] + fn possible_values_match() { + let p_vals = ["test", "temp"]; + assert_eq!(did_you_mean("te", p_vals.iter()), Some("test")); + } + + #[test] + fn possible_values_nomatch() { + let p_vals = ["test", "possible", "values"]; + assert!(did_you_mean("hahaahahah", p_vals.iter()).is_none()); + } + + #[test] + fn flag() { + let p_vals = ["test", "possible", "values"]; + assert_eq!( + did_you_mean_flag("tst", p_vals.iter(), []), + Some(("test", None)) + ); + } +} diff --git a/third_party/rust/clap/src/parse/matches/arg_matches.rs b/third_party/rust/clap/src/parse/matches/arg_matches.rs new file mode 100644 index 0000000000..a2fa6237c0 --- /dev/null +++ b/third_party/rust/clap/src/parse/matches/arg_matches.rs @@ -0,0 +1,1519 @@ +// Std +use std::{ + borrow::Cow, + ffi::{OsStr, OsString}, + fmt::{Debug, Display}, + iter::{Cloned, Flatten, Map}, + slice::Iter, + str::FromStr, +}; + +// Third Party +use indexmap::IndexMap; + +// Internal +use crate::parse::MatchedArg; +use crate::parse::ValueSource; +use crate::util::{Id, Key}; +use crate::{Error, INVALID_UTF8}; + +/// 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}; +/// let matches = Command::new("MyApp") +/// .arg(Arg::new("out") +/// .long("output") +/// .required(true) +/// .takes_value(true)) +/// .arg(Arg::new("debug") +/// .short('d') +/// .multiple_occurrences(true)) +/// .arg(Arg::new("cfg") +/// .short('c') +/// .takes_value(true)) +/// .get_matches(); // builds the instance of ArgMatches +/// +/// // to get information about the "cfg" argument we created, such as the value supplied we use +/// // various ArgMatches methods, such as ArgMatches::value_of +/// if let Some(c) = matches.value_of("cfg") { +/// println!("Value for -c: {}", c); +/// } +/// +/// // The ArgMatches::value_of method returns an Option because the user may not have supplied +/// // that argument at runtime. But if we specified that the argument was "required" as we did +/// // with the "out" argument, we can safely unwrap because `clap` verifies that was actually +/// // used at runtime. +/// println!("Value for --output: {}", matches.value_of("out").unwrap()); +/// +/// // You can check the presence of an argument +/// if matches.is_present("out") { +/// // Another way to check if an argument was present, or if it occurred multiple times is to +/// // use occurrences_of() which returns 0 if an argument isn't found at runtime, or the +/// // number of times that it occurred, if it was. To allow an argument to appear more than +/// // once, you must use the .multiple_occurrences(true) method, otherwise it will only return 1 or 0. +/// if matches.occurrences_of("debug") > 2 { +/// println!("Debug mode is REALLY on, don't be crazy"); +/// } else { +/// println!("Debug mode kind of on"); +/// } +/// } +/// ``` +/// [`Command::get_matches`]: crate::Command::get_matches() +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ArgMatches { + #[cfg(debug_assertions)] + pub(crate) valid_args: Vec<Id>, + #[cfg(debug_assertions)] + pub(crate) valid_subcommands: Vec<Id>, + #[cfg(debug_assertions)] + pub(crate) disable_asserts: bool, + pub(crate) args: IndexMap<Id, MatchedArg>, + pub(crate) subcommand: Option<Box<SubCommand>>, +} + +impl ArgMatches { + /// Check if any args were present on the command line + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let mut cmd = Command::new("myapp") + /// .arg(Arg::new("output") + /// .takes_value(true)); + /// + /// let m = cmd + /// .try_get_matches_from_mut(vec!["myapp", "something"]) + /// .unwrap(); + /// assert!(m.args_present()); + /// + /// let m = cmd + /// .try_get_matches_from_mut(vec!["myapp"]) + /// .unwrap(); + /// assert!(! m.args_present()); + pub fn args_present(&self) -> bool { + !self.args.is_empty() + } + + /// Gets the value of a specific option or positional argument. + /// + /// i.e. an argument that [takes an additional value][crate::Arg::takes_value] at runtime. + /// + /// Returns `None` if the option wasn't present. + /// + /// *NOTE:* Prefer [`ArgMatches::values_of`] if getting a value for an option or positional + /// argument that allows multiples as `ArgMatches::value_of` will only return the *first* + /// value. + /// + /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set. + /// [`occurrences_of`] can be used to check if a value is present at runtime. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. See + /// [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("output") + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "something"]); + /// + /// assert_eq!(m.value_of("output"), Some("something")); + /// ``` + /// [option]: crate::Arg::takes_value() + /// [positional]: crate::Arg::index() + /// [`ArgMatches::values_of`]: ArgMatches::values_of() + /// [`default_value`]: crate::Arg::default_value() + /// [`occurrences_of`]: crate::ArgMatches::occurrences_of() + #[cfg_attr(debug_assertions, track_caller)] + pub fn value_of<T: Key>(&self, id: T) -> Option<&str> { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + assert_utf8_validation(arg, &id); + let v = arg.first()?; + Some(v.to_str().expect(INVALID_UTF8)) + } + + /// Gets the lossy value of a specific option or positional argument. + /// + /// i.e. an argument that [takes an additional value][crate::Arg::takes_value] at runtime. + /// + /// A lossy value is one which contains invalid UTF-8, those invalid points will be replaced + /// with `\u{FFFD}` + /// + /// Returns `None` if the option wasn't present. + /// + /// *NOTE:* Recommend having set [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// *NOTE:* Prefer [`ArgMatches::values_of_lossy`] if getting a value for an option or positional + /// argument that allows multiples as `ArgMatches::value_of_lossy` will only return the *first* + /// value. + /// + /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set. + /// [`occurrences_of`] can be used to check if a value is present at runtime. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{Command, arg}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// + /// let m = Command::new("utf8") + /// .arg(arg!(<arg> "some arg") + /// .allow_invalid_utf8(true)) + /// .get_matches_from(vec![OsString::from("myprog"), + /// // "Hi {0xe9}!" + /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); + /// assert_eq!(&*m.value_of_lossy("arg").unwrap(), "Hi \u{FFFD}!"); + /// ``` + /// [`default_value`]: crate::Arg::default_value() + /// [`occurrences_of`]: ArgMatches::occurrences_of() + /// [`Arg::values_of_lossy`]: ArgMatches::values_of_lossy() + #[cfg_attr(debug_assertions, track_caller)] + pub fn value_of_lossy<T: Key>(&self, id: T) -> Option<Cow<'_, str>> { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + assert_no_utf8_validation(arg, &id); + let v = arg.first()?; + Some(v.to_string_lossy()) + } + + /// Get the `OsStr` value of a specific option or positional argument. + /// + /// i.e. an argument that [takes an additional value][crate::Arg::takes_value] at runtime. + /// + /// 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. + /// + /// *NOTE:* Recommend having set [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// *NOTE:* Prefer [`ArgMatches::values_of_os`] if getting a value for an option or positional + /// argument that allows multiples as `ArgMatches::value_of_os` will only return the *first* + /// value. + /// + /// *NOTE:* This will always return `Some(value)` if [`default_value`] has been set. + /// [`occurrences_of`] can be used to check if a value is present at runtime. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{Command, arg}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// + /// let m = Command::new("utf8") + /// .arg(arg!(<arg> "some arg") + /// .allow_invalid_utf8(true)) + /// .get_matches_from(vec![OsString::from("myprog"), + /// // "Hi {0xe9}!" + /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); + /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']); + /// ``` + /// [`default_value`]: crate::Arg::default_value() + /// [`occurrences_of`]: ArgMatches::occurrences_of() + /// [`ArgMatches::values_of_os`]: ArgMatches::values_of_os() + #[cfg_attr(debug_assertions, track_caller)] + pub fn value_of_os<T: Key>(&self, id: T) -> Option<&OsStr> { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + assert_no_utf8_validation(arg, &id); + let v = arg.first()?; + Some(v.as_os_str()) + } + + /// Get an [`Iterator`] over [values] of a specific option or positional argument. + /// + /// i.e. an argument that takes multiple values at runtime. + /// + /// Returns `None` if the option wasn't present. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. See + /// [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("output") + /// .multiple_occurrences(true) + /// .short('o') + /// .takes_value(true)) + /// .get_matches_from(vec![ + /// "myprog", "-o", "val1", "-o", "val2", "-o", "val3" + /// ]); + /// let vals: Vec<&str> = m.values_of("output").unwrap().collect(); + /// assert_eq!(vals, ["val1", "val2", "val3"]); + /// ``` + /// [values]: Values + /// [`Iterator`]: std::iter::Iterator + #[cfg_attr(debug_assertions, track_caller)] + pub fn values_of<T: Key>(&self, id: T) -> Option<Values> { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + assert_utf8_validation(arg, &id); + fn to_str_slice(o: &OsString) -> &str { + o.to_str().expect(INVALID_UTF8) + } + let v = Values { + iter: arg.vals_flatten().map(to_str_slice), + len: arg.num_vals(), + }; + Some(v) + } + + /// Get an [`Iterator`] over groups of values of a specific option. + /// + /// specifically grouped by the occurrences of the options. + /// + /// Each group is a `Vec<&str>` containing the arguments passed to a single occurrence + /// of the option. + /// + /// If the option doesn't support multiple occurrences, or there was only a single occurrence, + /// the iterator will only contain a single item. + /// + /// Returns `None` if the option wasn't present. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. + /// + /// If `id` is not a valid argument or group name. + /// + /// # Examples + /// ```rust + /// # use clap::{Command,Arg}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("exec") + /// .short('x') + /// .min_values(1) + /// .multiple_occurrences(true) + /// .value_terminator(";")) + /// .get_matches_from(vec![ + /// "myprog", "-x", "echo", "hi", ";", "-x", "echo", "bye"]); + /// let vals: Vec<Vec<&str>> = m.grouped_values_of("exec").unwrap().collect(); + /// assert_eq!(vals, [["echo", "hi"], ["echo", "bye"]]); + /// ``` + /// [`Iterator`]: std::iter::Iterator + #[cfg(feature = "unstable-grouped")] + #[cfg_attr(debug_assertions, track_caller)] + pub fn grouped_values_of<T: Key>(&self, id: T) -> Option<GroupedValues> { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + assert_utf8_validation(arg, &id); + let v = GroupedValues { + iter: arg + .vals() + .map(|g| g.iter().map(|x| x.to_str().expect(INVALID_UTF8)).collect()), + len: arg.vals().len(), + }; + Some(v) + } + + /// Get the lossy values of a specific option or positional argument. + /// + /// i.e. an argument that takes multiple values at runtime. + /// + /// A lossy value is one which contains invalid UTF-8, those invalid points will be replaced + /// with `\u{FFFD}` + /// + /// Returns `None` if the option wasn't present. + /// + /// *NOTE:* Recommend having set [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{Command, arg}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::OsStringExt; + /// + /// let m = Command::new("utf8") + /// .arg(arg!(<arg> ... "some arg") + /// .allow_invalid_utf8(true)) + /// .get_matches_from(vec![OsString::from("myprog"), + /// // "Hi" + /// OsString::from_vec(vec![b'H', b'i']), + /// // "{0xe9}!" + /// OsString::from_vec(vec![0xe9, b'!'])]); + /// let mut itr = m.values_of_lossy("arg").unwrap().into_iter(); + /// assert_eq!(&itr.next().unwrap()[..], "Hi"); + /// assert_eq!(&itr.next().unwrap()[..], "\u{FFFD}!"); + /// assert_eq!(itr.next(), None); + /// ``` + #[cfg_attr(debug_assertions, track_caller)] + pub fn values_of_lossy<T: Key>(&self, id: T) -> Option<Vec<String>> { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + assert_no_utf8_validation(arg, &id); + let v = arg + .vals_flatten() + .map(|v| v.to_string_lossy().into_owned()) + .collect(); + Some(v) + } + + /// Get an [`Iterator`] over [`OsStr`] [values] of a specific option or positional argument. + /// + /// i.e. an argument that takes multiple values at runtime. + /// + /// 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. + /// + /// *NOTE:* Recommend having set [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{Command, arg}; + /// use std::ffi::{OsStr,OsString}; + /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// + /// let m = Command::new("utf8") + /// .arg(arg!(<arg> ... "some arg") + /// .allow_invalid_utf8(true)) + /// .get_matches_from(vec![OsString::from("myprog"), + /// // "Hi" + /// OsString::from_vec(vec![b'H', b'i']), + /// // "{0xe9}!" + /// OsString::from_vec(vec![0xe9, b'!'])]); + /// + /// let mut itr = m.values_of_os("arg").unwrap().into_iter(); + /// assert_eq!(itr.next(), Some(OsStr::new("Hi"))); + /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!']))); + /// assert_eq!(itr.next(), None); + /// ``` + /// [`Iterator`]: std::iter::Iterator + /// [`OsSt`]: std::ffi::OsStr + /// [values]: OsValues + /// [`String`]: std::string::String + #[cfg_attr(debug_assertions, track_caller)] + pub fn values_of_os<T: Key>(&self, id: T) -> Option<OsValues> { + let id = Id::from(id); + let arg = self.get_arg(&id)?; + assert_no_utf8_validation(arg, &id); + fn to_str_slice(o: &OsString) -> &OsStr { + o + } + let v = OsValues { + iter: arg.vals_flatten().map(to_str_slice), + len: arg.num_vals(), + }; + Some(v) + } + + /// Parse the value (with [`FromStr`]) of a specific option or positional argument. + /// + /// There are two types of errors, parse failures and those where the argument wasn't present + /// (such as a non-required argument). Check [`ErrorKind`] to distinguish them. + /// + /// *NOTE:* If getting a value for an option or positional argument that allows multiples, + /// prefer [`ArgMatches::values_of_t`] as this method will only return the *first* + /// value. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. See + /// [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ``` + /// # use clap::{Command, arg}; + /// let matches = Command::new("myapp") + /// .arg(arg!([length] "Set the length to use as a pos whole num i.e. 20")) + /// .get_matches_from(&["test", "12"]); + /// + /// // Specify the type explicitly (or use turbofish) + /// let len: u32 = matches.value_of_t("length").unwrap_or_else(|e| e.exit()); + /// assert_eq!(len, 12); + /// + /// // You can often leave the type for rustc to figure out + /// let also_len = matches.value_of_t("length").unwrap_or_else(|e| e.exit()); + /// // Something that expects u32 + /// let _: u32 = also_len; + /// ``` + /// + /// [`FromStr]: std::str::FromStr + /// [`ArgMatches::values_of_t`]: ArgMatches::values_of_t() + /// [`ErrorKind`]: crate::ErrorKind + pub fn value_of_t<R>(&self, name: &str) -> Result<R, Error> + where + R: FromStr, + <R as FromStr>::Err: Display, + { + let v = self + .value_of(name) + .ok_or_else(|| Error::argument_not_found_auto(name.to_string()))?; + v.parse::<R>().map_err(|e| { + let message = format!( + "The argument '{}' isn't a valid value for '{}': {}", + v, name, e + ); + + Error::value_validation(name.to_string(), v.to_string(), message.into()) + }) + } + + /// Parse the value (with [`FromStr`]) of a specific option or positional argument. + /// + /// If either the value is not present or parsing failed, exits the program. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. See + /// [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ``` + /// # use clap::{Command, arg}; + /// let matches = Command::new("myapp") + /// .arg(arg!([length] "Set the length to use as a pos whole num i.e. 20")) + /// .get_matches_from(&["test", "12"]); + /// + /// // Specify the type explicitly (or use turbofish) + /// let len: u32 = matches.value_of_t_or_exit("length"); + /// assert_eq!(len, 12); + /// + /// // You can often leave the type for rustc to figure out + /// let also_len = matches.value_of_t_or_exit("length"); + /// // Something that expects u32 + /// let _: u32 = also_len; + /// ``` + /// + /// [`FromStr][std::str::FromStr] + pub fn value_of_t_or_exit<R>(&self, name: &str) -> R + where + R: FromStr, + <R as FromStr>::Err: Display, + { + self.value_of_t(name).unwrap_or_else(|e| e.exit()) + } + + /// Parse the values (with [`FromStr`]) of a specific option or positional argument. + /// + /// There are two types of errors, parse failures and those where the argument wasn't present + /// (such as a non-required argument). Check [`ErrorKind`] to distinguish them. + /// + /// *NOTE:* If getting a value for an option or positional argument that allows multiples, + /// prefer [`ArgMatches::values_of_t`] as this method will only return the *first* + /// value. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. See + /// [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ``` + /// # use clap::{Command, arg}; + /// let matches = Command::new("myapp") + /// .arg(arg!([length] ... "A sequence of integers because integers are neat!")) + /// .get_matches_from(&["test", "12", "77", "40"]); + /// + /// // Specify the type explicitly (or use turbofish) + /// let len: Vec<u32> = matches.values_of_t("length").unwrap_or_else(|e| e.exit()); + /// assert_eq!(len, vec![12, 77, 40]); + /// + /// // You can often leave the type for rustc to figure out + /// let also_len = matches.values_of_t("length").unwrap_or_else(|e| e.exit()); + /// // Something that expects Vec<u32> + /// let _: Vec<u32> = also_len; + /// ``` + /// [`ErrorKind`]: crate::ErrorKind + pub fn values_of_t<R>(&self, name: &str) -> Result<Vec<R>, Error> + where + R: FromStr, + <R as FromStr>::Err: Display, + { + let v = self + .values_of(name) + .ok_or_else(|| Error::argument_not_found_auto(name.to_string()))?; + v.map(|v| { + v.parse::<R>().map_err(|e| { + let message = format!("The argument '{}' isn't a valid value: {}", v, e); + + Error::value_validation(name.to_string(), v.to_string(), message.into()) + }) + }) + .collect() + } + + /// Parse the values (with [`FromStr`]) of a specific option or positional argument. + /// + /// If parsing (of any value) has failed, exits the program. + /// + /// # Panics + /// + /// If the value is invalid UTF-8. See + /// [`Arg::allow_invalid_utf8`][crate::Arg::allow_invalid_utf8]. + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ``` + /// # use clap::{Command, arg}; + /// let matches = Command::new("myapp") + /// .arg(arg!([length] ... "A sequence of integers because integers are neat!")) + /// .get_matches_from(&["test", "12", "77", "40"]); + /// + /// // Specify the type explicitly (or use turbofish) + /// let len: Vec<u32> = matches.values_of_t_or_exit("length"); + /// assert_eq!(len, vec![12, 77, 40]); + /// + /// // You can often leave the type for rustc to figure out + /// let also_len = matches.values_of_t_or_exit("length"); + /// // Something that expects Vec<u32> + /// let _: Vec<u32> = also_len; + /// ``` + pub fn values_of_t_or_exit<R>(&self, name: &str) -> Vec<R> + where + R: FromStr, + <R as FromStr>::Err: Display, + { + self.values_of_t(name).unwrap_or_else(|e| e.exit()) + } + + /// Check if an argument was present at runtime. + /// + /// *NOTE:* This will always return `true` if [`default_value`] has been set. + /// [`occurrences_of`] can be used to check if a value is present at runtime. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("debug") + /// .short('d')) + /// .get_matches_from(vec![ + /// "myprog", "-d" + /// ]); + /// + /// assert!(m.is_present("debug")); + /// ``` + /// + /// [`default_value`]: crate::Arg::default_value() + /// [`occurrences_of`]: ArgMatches::occurrences_of() + pub fn is_present<T: Key>(&self, id: T) -> bool { + let id = Id::from(id); + + #[cfg(debug_assertions)] + self.get_arg(&id); + + self.args.contains_key(&id) + } + + /// Report where argument value came from + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ValueSource}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("debug") + /// .short('d')) + /// .get_matches_from(vec![ + /// "myprog", "-d" + /// ]); + /// + /// assert_eq!(m.value_source("debug"), Some(ValueSource::CommandLine)); + /// ``` + /// + /// [`default_value`]: crate::Arg::default_value() + /// [`occurrences_of`]: ArgMatches::occurrences_of() + pub fn value_source<T: Key>(&self, id: T) -> Option<ValueSource> { + let id = Id::from(id); + + let value = self.get_arg(&id); + + value.and_then(MatchedArg::source) + } + + /// The number of times an argument was used at runtime. + /// + /// If an argument isn't present it will return `0`. + /// + /// **NOTE:** This returns the number of times the argument was used, *not* the number of + /// values. For example, `-o val1 val2 val3 -o val4` would return `2` (2 occurrences, but 4 + /// values). See [Arg::multiple_occurrences][crate::Arg::multiple_occurrences]. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("debug") + /// .short('d') + /// .multiple_occurrences(true)) + /// .get_matches_from(vec![ + /// "myprog", "-d", "-d", "-d" + /// ]); + /// + /// assert_eq!(m.occurrences_of("debug"), 3); + /// ``` + /// + /// This next example shows that counts actual uses of the argument, not just `-`'s + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("debug") + /// .short('d') + /// .multiple_occurrences(true)) + /// .arg(Arg::new("flag") + /// .short('f')) + /// .get_matches_from(vec![ + /// "myprog", "-ddfd" + /// ]); + /// + /// assert_eq!(m.occurrences_of("debug"), 3); + /// assert_eq!(m.occurrences_of("flag"), 1); + /// ``` + pub fn occurrences_of<T: Key>(&self, id: T) -> u64 { + self.get_arg(&Id::from(id)) + .map_or(0, |a| a.get_occurrences()) + } + + /// The first index of that an argument showed up. + /// + /// Indices are similar to argv indices, but are not exactly 1:1. + /// + /// For flags (i.e. those arguments which don't have an associated value), indices refer + /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices + /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the + /// index for `val` would be recorded. This is by design. + /// + /// Besides the flag/option discrepancy, the primary difference between an argv index and clap + /// index, is that clap continues counting once all arguments have properly separated, whereas + /// an argv index does not. + /// + /// The examples should clear this up. + /// + /// *NOTE:* If an argument is allowed multiple times, this method will only give the *first* + /// index. See [`ArgMatches::indices_of`]. + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// The argv indices are listed in the comments below. See how they correspond to the clap + /// indices. Note that if it's not listed in a clap index, this is because it's not saved in + /// in an `ArgMatches` struct for querying. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("option") + /// .short('o') + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "-f", "-o", "val"]); + /// // ARGV indices: ^0 ^1 ^2 ^3 + /// // clap indices: ^1 ^3 + /// + /// assert_eq!(m.index_of("flag"), Some(1)); + /// assert_eq!(m.index_of("option"), Some(3)); + /// ``` + /// + /// Now notice, if we use one of the other styles of options: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("option") + /// .short('o') + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "-f", "-o=val"]); + /// // ARGV indices: ^0 ^1 ^2 + /// // clap indices: ^1 ^3 + /// + /// assert_eq!(m.index_of("flag"), Some(1)); + /// assert_eq!(m.index_of("option"), Some(3)); + /// ``` + /// + /// Things become much more complicated, or clear if we look at a more complex combination of + /// flags. Let's also throw in the final option style for good measure. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("flag2") + /// .short('F')) + /// .arg(Arg::new("flag3") + /// .short('z')) + /// .arg(Arg::new("option") + /// .short('o') + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "-fzF", "-oval"]); + /// // ARGV indices: ^0 ^1 ^2 + /// // clap indices: ^1,2,3 ^5 + /// // + /// // clap sees the above as 'myapp -f -z -F -o val' + /// // ^0 ^1 ^2 ^3 ^4 ^5 + /// assert_eq!(m.index_of("flag"), Some(1)); + /// assert_eq!(m.index_of("flag2"), Some(3)); + /// assert_eq!(m.index_of("flag3"), Some(2)); + /// assert_eq!(m.index_of("option"), Some(5)); + /// ``` + /// + /// One final combination of flags/options to see how they combine: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("flag") + /// .short('f')) + /// .arg(Arg::new("flag2") + /// .short('F')) + /// .arg(Arg::new("flag3") + /// .short('z')) + /// .arg(Arg::new("option") + /// .short('o') + /// .takes_value(true)) + /// .get_matches_from(vec!["myapp", "-fzFoval"]); + /// // ARGV indices: ^0 ^1 + /// // clap indices: ^1,2,3^5 + /// // + /// // clap sees the above as 'myapp -f -z -F -o val' + /// // ^0 ^1 ^2 ^3 ^4 ^5 + /// assert_eq!(m.index_of("flag"), Some(1)); + /// assert_eq!(m.index_of("flag2"), Some(3)); + /// assert_eq!(m.index_of("flag3"), Some(2)); + /// assert_eq!(m.index_of("option"), Some(5)); + /// ``` + /// + /// The last part to mention is when values are sent in multiple groups with a [delimiter]. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("option") + /// .short('o') + /// .use_value_delimiter(true) + /// .multiple_values(true)) + /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + /// // ARGV indices: ^0 ^1 + /// // clap indices: ^2 ^3 ^4 + /// // + /// // clap sees the above as 'myapp -o val1 val2 val3' + /// // ^0 ^1 ^2 ^3 ^4 + /// assert_eq!(m.index_of("option"), Some(2)); + /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]); + /// ``` + /// [delimiter]: crate::Arg::value_delimiter() + pub fn index_of<T: Key>(&self, id: T) -> Option<usize> { + let arg = self.get_arg(&Id::from(id))?; + let i = arg.get_index(0)?; + Some(i) + } + + /// All indices an argument appeared at when parsing. + /// + /// Indices are similar to argv indices, but are not exactly 1:1. + /// + /// For flags (i.e. those arguments which don't have an associated value), indices refer + /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices + /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the + /// index for `val` would be recorded. This is by design. + /// + /// *NOTE:* For more information about how clap indices compared to argv indices, see + /// [`ArgMatches::index_of`] + /// + /// # Panics + /// + /// If `id` is is not a valid argument or group name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("option") + /// .short('o') + /// .use_value_delimiter(true) + /// .multiple_values(true)) + /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + /// // ARGV indices: ^0 ^1 + /// // clap indices: ^2 ^3 ^4 + /// // + /// // clap sees the above as 'myapp -o val1 val2 val3' + /// // ^0 ^1 ^2 ^3 ^4 + /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]); + /// ``` + /// + /// Another quick example is when flags and options are used together + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("option") + /// .short('o') + /// .takes_value(true) + /// .multiple_occurrences(true)) + /// .arg(Arg::new("flag") + /// .short('f') + /// .multiple_occurrences(true)) + /// .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<_>>(), &[3, 6]); + /// ``` + /// + /// One final example, which is an odd case; if we *don't* use value delimiter as we did with + /// the first example above instead of `val1`, `val2` and `val3` all being distinc values, they + /// would all be a single value of `val1,val2,val3`, in which case they'd only receive a single + /// index. + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myapp") + /// .arg(Arg::new("option") + /// .short('o') + /// .takes_value(true) + /// .multiple_values(true)) + /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + /// // ARGV indices: ^0 ^1 + /// // clap indices: ^2 + /// // + /// // clap sees the above as 'myapp -o "val1,val2,val3"' + /// // ^0 ^1 ^2 + /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2]); + /// ``` + /// [`ArgMatches::index_of`]: ArgMatches::index_of() + /// [delimiter]: Arg::value_delimiter() + pub fn indices_of<T: Key>(&self, id: T) -> Option<Indices<'_>> { + let arg = self.get_arg(&Id::from(id))?; + let i = Indices { + iter: arg.indices(), + len: arg.num_vals(), + }; + Some(i) + } + + /// The name and `ArgMatches` of the current [subcommand]. + /// + /// Subcommand values are put in a child [`ArgMatches`] + /// + /// Returns `None` if the subcommand wasn't present at runtime, + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let app_m = Command::new("git") + /// .subcommand(Command::new("clone")) + /// .subcommand(Command::new("push")) + /// .subcommand(Command::new("commit")) + /// .get_matches(); + /// + /// match app_m.subcommand() { + /// Some(("clone", sub_m)) => {}, // clone was used + /// Some(("push", sub_m)) => {}, // push was used + /// Some(("commit", sub_m)) => {}, // commit was used + /// _ => {}, // Either no subcommand or one not tested for... + /// } + /// ``` + /// + /// Another useful scenario is when you want to support third party, or external, subcommands. + /// In these cases you can't know the subcommand name ahead of time, so use a variable instead + /// with pattern matching! + /// + /// ```rust + /// # use clap::Command; + /// // Assume there is an external subcommand named "subcmd" + /// let app_m = Command::new("myprog") + /// .allow_external_subcommands(true) + /// .get_matches_from(vec![ + /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" + /// ]); + /// + /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty + /// // string argument name + /// match app_m.subcommand() { + /// Some((external, sub_m)) => { + /// let ext_args: Vec<&str> = sub_m.values_of("").unwrap().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)) + } + + /// The `ArgMatches` for the current [subcommand]. + /// + /// Subcommand values are put in a child [`ArgMatches`] + /// + /// Returns `None` if the subcommand wasn't present at runtime, + /// + /// # Panics + /// + /// If `id` is is not a valid subcommand. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, }; + /// let app_m = Command::new("myprog") + /// .arg(Arg::new("debug") + /// .short('d')) + /// .subcommand(Command::new("test") + /// .arg(Arg::new("opt") + /// .long("option") + /// .takes_value(true))) + /// .get_matches_from(vec![ + /// "myprog", "-d", "test", "--option", "val" + /// ]); + /// + /// // Both parent commands, and child subcommands can have arguments present at the same times + /// assert!(app_m.is_present("debug")); + /// + /// // Get the subcommand's ArgMatches instance + /// if let Some(sub_m) = app_m.subcommand_matches("test") { + /// // Use the struct like normal + /// assert_eq!(sub_m.value_of("opt"), Some("val")); + /// } + /// ``` + /// + /// [subcommand]: crate::Command::subcommand + /// [`Command`]: crate::Command + pub fn subcommand_matches<T: Key>(&self, id: T) -> Option<&ArgMatches> { + self.get_subcommand(&id.into()).map(|sc| &sc.matches) + } + + /// The name of the current [subcommand]. + /// + /// Returns `None` if the subcommand wasn't present at runtime, + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let app_m = Command::new("git") + /// .subcommand(Command::new("clone")) + /// .subcommand(Command::new("push")) + /// .subcommand(Command::new("commit")) + /// .get_matches(); + /// + /// match app_m.subcommand_name() { + /// Some("clone") => {}, // clone was used + /// Some("push") => {}, // push was used + /// Some("commit") => {}, // commit was used + /// _ => {}, // Either no subcommand or one not tested for... + /// } + /// ``` + /// [subcommand]: crate::Command::subcommand + /// [`Command`]: crate::Command + #[inline] + pub fn subcommand_name(&self) -> Option<&str> { + self.subcommand.as_ref().map(|sc| &*sc.name) + } + + /// Check if an arg 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_arg(&self, _id: impl Key) -> bool { + #[cfg(debug_assertions)] + { + let id = Id::from(_id); + self.disable_asserts || id == Id::empty_hash() || self.valid_args.contains(&id) + } + #[cfg(not(debug_assertions))] + { + true + } + } + + /// Check if a subcommand can be queried + /// + /// By default, `ArgMatches` functions assert on undefined `Id`s to help catch programmer + /// mistakes. In some context, this doesn't work, so users can use this function to check + /// before they do a query on `ArgMatches`. + #[inline] + #[doc(hidden)] + pub fn is_valid_subcommand(&self, _id: impl Key) -> bool { + #[cfg(debug_assertions)] + { + let id = Id::from(_id); + self.disable_asserts || id == Id::empty_hash() || self.valid_subcommands.contains(&id) + } + #[cfg(not(debug_assertions))] + { + true + } + } +} + +// Private methods +impl ArgMatches { + #[inline] + #[cfg_attr(debug_assertions, track_caller)] + fn get_arg(&self, arg: &Id) -> Option<&MatchedArg> { + #[cfg(debug_assertions)] + { + if self.disable_asserts || *arg == Id::empty_hash() || self.valid_args.contains(arg) { + } else if self.valid_subcommands.contains(arg) { + panic!( + "Subcommand `{:?}` used where an argument or group name was expected.", + arg + ); + } else { + panic!( + "`{:?}` is not a name of an argument or a group.\n\ + Make sure you're using the name of the argument itself \ + and not the name of short or long flags.", + arg + ); + } + } + + self.args.get(arg) + } + + #[inline] + #[cfg_attr(debug_assertions, track_caller)] + fn get_subcommand(&self, id: &Id) -> Option<&SubCommand> { + #[cfg(debug_assertions)] + { + if self.disable_asserts + || *id == Id::empty_hash() + || self.valid_subcommands.contains(id) + { + } else if self.valid_args.contains(id) { + panic!( + "Argument or group `{:?}` used where a subcommand name was expected.", + id + ); + } else { + panic!("`{:?}` is not a name of a subcommand.", id); + } + } + + if let Some(ref sc) = self.subcommand { + if sc.id == *id { + return Some(sc); + } + } + + None + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct SubCommand { + pub(crate) id: Id, + pub(crate) name: String, + pub(crate) matches: ArgMatches, +} + +// 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 + +/// Iterate over multiple values for an argument via [`ArgMatches::values_of`]. +/// +/// # Examples +/// +/// ```rust +/// # use clap::{Command, Arg}; +/// let m = Command::new("myapp") +/// .arg(Arg::new("output") +/// .short('o') +/// .multiple_occurrences(true) +/// .takes_value(true)) +/// .get_matches_from(vec!["myapp", "-o", "val1", "-o", "val2"]); +/// +/// let mut values = m.values_of("output").unwrap(); +/// +/// assert_eq!(values.next(), Some("val1")); +/// assert_eq!(values.next(), Some("val2")); +/// assert_eq!(values.next(), None); +/// ``` +/// [`ArgMatches::values_of`]: ArgMatches::values_of() +#[derive(Clone, Debug)] +pub struct Values<'a> { + #[allow(clippy::type_complexity)] + iter: Map<Flatten<Iter<'a, Vec<OsString>>>, for<'r> fn(&'r OsString) -> &'r str>, + len: usize, +} + +impl<'a> Iterator for Values<'a> { + type Item = &'a str; + + fn next(&mut self) -> Option<&'a str> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option<usize>) { + (self.len, Some(self.len)) + } +} + +impl<'a> DoubleEndedIterator for Values<'a> { + fn next_back(&mut self) -> Option<&'a str> { + self.iter.next_back() + } +} + +impl<'a> ExactSizeIterator for Values<'a> {} + +/// Creates an empty iterator. +impl<'a> Default for Values<'a> { + fn default() -> Self { + static EMPTY: [Vec<OsString>; 0] = []; + Values { + iter: EMPTY[..].iter().flatten().map(|_| unreachable!()), + len: 0, + } + } +} + +#[derive(Clone)] +#[allow(missing_debug_implementations)] +pub struct GroupedValues<'a> { + #[allow(clippy::type_complexity)] + iter: Map<Iter<'a, Vec<OsString>>, fn(&Vec<OsString>) -> Vec<&str>>, + len: usize, +} + +impl<'a> Iterator for GroupedValues<'a> { + type Item = Vec<&'a str>; + + fn next(&mut self) -> Option<Self::Item> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option<usize>) { + (self.len, Some(self.len)) + } +} + +impl<'a> DoubleEndedIterator for GroupedValues<'a> { + fn next_back(&mut self) -> Option<Self::Item> { + self.iter.next_back() + } +} + +impl<'a> ExactSizeIterator for GroupedValues<'a> {} + +/// Creates an empty iterator. Used for `unwrap_or_default()`. +impl<'a> Default for GroupedValues<'a> { + fn default() -> Self { + static EMPTY: [Vec<OsString>; 0] = []; + GroupedValues { + iter: EMPTY[..].iter().map(|_| unreachable!()), + len: 0, + } + } +} + +/// Iterate over multiple values for an argument via [`ArgMatches::values_of_os`]. +/// +/// # Examples +/// +#[cfg_attr(not(unix), doc = " ```ignore")] +#[cfg_attr(unix, doc = " ```")] +/// # use clap::{Command, arg}; +/// use std::ffi::OsString; +/// use std::os::unix::ffi::{OsStrExt,OsStringExt}; +/// +/// let m = Command::new("utf8") +/// .arg(arg!(<arg> "some arg") +/// .allow_invalid_utf8(true)) +/// .get_matches_from(vec![OsString::from("myprog"), +/// // "Hi {0xe9}!" +/// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); +/// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']); +/// ``` +/// [`ArgMatches::values_of_os`]: ArgMatches::values_of_os() +#[derive(Clone, Debug)] +pub struct OsValues<'a> { + #[allow(clippy::type_complexity)] + iter: Map<Flatten<Iter<'a, Vec<OsString>>>, fn(&OsString) -> &OsStr>, + len: usize, +} + +impl<'a> Iterator for OsValues<'a> { + type Item = &'a OsStr; + + fn next(&mut self) -> Option<&'a OsStr> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option<usize>) { + (self.len, Some(self.len)) + } +} + +impl<'a> DoubleEndedIterator for OsValues<'a> { + fn next_back(&mut self) -> Option<&'a OsStr> { + self.iter.next_back() + } +} + +impl<'a> ExactSizeIterator for OsValues<'a> {} + +/// Creates an empty iterator. +impl Default for OsValues<'_> { + fn default() -> Self { + static EMPTY: [Vec<OsString>; 0] = []; + OsValues { + iter: EMPTY[..].iter().flatten().map(|_| unreachable!()), + len: 0, + } + } +} + +/// Iterate over indices for where an argument appeared when parsing, via [`ArgMatches::indices_of`] +/// +/// # Examples +/// +/// ```rust +/// # use clap::{Command, Arg}; +/// let m = Command::new("myapp") +/// .arg(Arg::new("output") +/// .short('o') +/// .multiple_values(true) +/// .takes_value(true)) +/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]); +/// +/// let mut indices = m.indices_of("output").unwrap(); +/// +/// assert_eq!(indices.next(), Some(2)); +/// assert_eq!(indices.next(), Some(3)); +/// assert_eq!(indices.next(), None); +/// ``` +/// [`ArgMatches::indices_of`]: ArgMatches::indices_of() +#[derive(Clone, Debug)] +pub struct Indices<'a> { + iter: Cloned<Iter<'a, usize>>, + len: usize, +} + +impl<'a> Iterator for Indices<'a> { + type Item = usize; + + fn next(&mut self) -> Option<usize> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option<usize>) { + (self.len, Some(self.len)) + } +} + +impl<'a> DoubleEndedIterator for Indices<'a> { + fn next_back(&mut self) -> Option<usize> { + self.iter.next_back() + } +} + +impl<'a> ExactSizeIterator for Indices<'a> {} + +/// Creates an empty iterator. +impl<'a> Default for Indices<'a> { + fn default() -> Self { + static EMPTY: [usize; 0] = []; + // This is never called because the iterator is empty: + Indices { + iter: EMPTY[..].iter().cloned(), + len: 0, + } + } +} + +#[cfg_attr(debug_assertions, track_caller)] +#[inline] +fn assert_utf8_validation(arg: &MatchedArg, id: &Id) { + debug_assert!( + matches!(arg.is_invalid_utf8_allowed(), None | Some(false)), + "Must use `_os` lookups with `Arg::allow_invalid_utf8` at `{:?}`", + id + ); +} + +#[cfg_attr(debug_assertions, track_caller)] +#[inline] +fn assert_no_utf8_validation(arg: &MatchedArg, id: &Id) { + debug_assert!( + matches!(arg.is_invalid_utf8_allowed(), None | Some(true)), + "Must use `Arg::allow_invalid_utf8` with `_os` lookups at `{:?}`", + id + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_default_values() { + let mut values: Values = Values::default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_values_with_shorter_lifetime() { + let matches = ArgMatches::default(); + let mut values = matches.values_of("").unwrap_or_default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_osvalues() { + let mut values: OsValues = OsValues::default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_osvalues_with_shorter_lifetime() { + let matches = ArgMatches::default(); + let mut values = matches.values_of_os("").unwrap_or_default(); + assert_eq!(values.next(), None); + } + + #[test] + fn test_default_indices() { + let mut indices: Indices = Indices::default(); + assert_eq!(indices.next(), None); + } + + #[test] + fn test_default_indices_with_shorter_lifetime() { + let matches = ArgMatches::default(); + let mut indices = matches.indices_of("").unwrap_or_default(); + assert_eq!(indices.next(), None); + } + + #[test] + fn values_exact_size() { + let l = crate::Command::new("test") + .arg( + crate::Arg::new("POTATO") + .takes_value(true) + .multiple_values(true) + .required(true), + ) + .try_get_matches_from(["test", "one"]) + .unwrap() + .values_of("POTATO") + .expect("present") + .len(); + assert_eq!(l, 1); + } + + #[test] + fn os_values_exact_size() { + let l = crate::Command::new("test") + .arg( + crate::Arg::new("POTATO") + .takes_value(true) + .multiple_values(true) + .allow_invalid_utf8(true) + .required(true), + ) + .try_get_matches_from(["test", "one"]) + .unwrap() + .values_of_os("POTATO") + .expect("present") + .len(); + assert_eq!(l, 1); + } + + #[test] + fn indices_exact_size() { + let l = crate::Command::new("test") + .arg( + crate::Arg::new("POTATO") + .takes_value(true) + .multiple_values(true) + .required(true), + ) + .try_get_matches_from(["test", "one"]) + .unwrap() + .indices_of("POTATO") + .expect("present") + .len(); + assert_eq!(l, 1); + } +} diff --git a/third_party/rust/clap/src/parse/matches/matched_arg.rs b/third_party/rust/clap/src/parse/matches/matched_arg.rs new file mode 100644 index 0000000000..55326ecd08 --- /dev/null +++ b/third_party/rust/clap/src/parse/matches/matched_arg.rs @@ -0,0 +1,365 @@ +// Std +use std::{ + ffi::{OsStr, OsString}, + iter::{Cloned, Flatten}, + slice::Iter, +}; + +use crate::build::ArgPredicate; +use crate::parse::ValueSource; +use crate::util::eq_ignore_case; +use crate::INTERNAL_ERROR_MSG; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct MatchedArg { + occurs: u64, + ty: Option<ValueSource>, + indices: Vec<usize>, + vals: Vec<Vec<OsString>>, + ignore_case: bool, + invalid_utf8_allowed: Option<bool>, +} + +impl MatchedArg { + pub(crate) fn new() -> Self { + MatchedArg { + occurs: 0, + ty: None, + indices: Vec::new(), + vals: Vec::new(), + ignore_case: false, + invalid_utf8_allowed: None, + } + } + + pub(crate) fn inc_occurrences(&mut self) { + self.occurs += 1; + } + + pub(crate) fn get_occurrences(&self) -> u64 { + self.occurs + } + + pub(crate) fn indices(&self) -> Cloned<Iter<'_, usize>> { + self.indices.iter().cloned() + } + + pub(crate) fn get_index(&self, index: usize) -> Option<usize> { + self.indices.get(index).cloned() + } + + pub(crate) fn push_index(&mut self, index: usize) { + self.indices.push(index) + } + + pub(crate) fn vals(&self) -> Iter<Vec<OsString>> { + self.vals.iter() + } + + pub(crate) fn vals_flatten(&self) -> Flatten<Iter<Vec<OsString>>> { + self.vals.iter().flatten() + } + + pub(crate) fn first(&self) -> Option<&OsString> { + self.vals_flatten().next() + } + + pub(crate) fn push_val(&mut self, val: OsString) { + self.vals.push(vec![val]) + } + + pub(crate) fn new_val_group(&mut self) { + self.vals.push(vec![]) + } + + pub(crate) fn append_val(&mut self, val: OsString) { + // We assume there is always a group created before. + self.vals.last_mut().expect(INTERNAL_ERROR_MSG).push(val) + } + + pub(crate) fn num_vals(&self) -> usize { + self.vals.iter().flatten().count() + } + + // 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 has_val_groups(&self) -> bool { + !self.vals.is_empty() + } + + // Will be used later + #[allow(dead_code)] + pub(crate) fn remove_vals(&mut self, len: usize) { + let mut want_remove = len; + let mut remove_group = None; + let mut remove_val = None; + for (i, g) in self.vals().enumerate() { + if g.len() <= want_remove { + want_remove -= g.len(); + remove_group = Some(i); + } else { + remove_val = Some(want_remove); + break; + } + } + if let Some(remove_group) = remove_group { + self.vals.drain(0..=remove_group); + } + if let Some(remove_val) = remove_val { + self.vals[0].drain(0..remove_val); + } + } + + pub(crate) fn check_explicit(&self, predicate: ArgPredicate) -> bool { + if self.ty == Some(ValueSource::DefaultValue) { + return false; + } + + match predicate { + ArgPredicate::Equals(val) => self.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.ty + } + + pub(crate) fn update_ty(&mut self, ty: ValueSource) { + if let Some(existing) = self.ty { + self.ty = Some(existing.max(ty)); + } else { + self.ty = Some(ty) + } + } + + pub(crate) fn set_ignore_case(&mut self, yes: bool) { + self.ignore_case = yes; + } + + pub(crate) fn invalid_utf8_allowed(&mut self, yes: bool) { + self.invalid_utf8_allowed = Some(yes); + } + + pub(crate) fn is_invalid_utf8_allowed(&self) -> Option<bool> { + self.invalid_utf8_allowed + } +} + +impl Default for MatchedArg { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_grouped_vals_first() { + let mut m = MatchedArg::new(); + m.new_val_group(); + m.new_val_group(); + m.append_val("bbb".into()); + m.append_val("ccc".into()); + assert_eq!(m.first(), Some(&OsString::from("bbb"))); + } + + #[test] + fn test_grouped_vals_push_and_append() { + let mut m = MatchedArg::new(); + m.push_val("aaa".into()); + m.new_val_group(); + m.append_val("bbb".into()); + m.append_val("ccc".into()); + m.new_val_group(); + m.append_val("ddd".into()); + m.push_val("eee".into()); + m.new_val_group(); + m.append_val("fff".into()); + m.append_val("ggg".into()); + m.append_val("hhh".into()); + m.append_val("iii".into()); + + let vals: Vec<&Vec<OsString>> = m.vals().collect(); + assert_eq!( + vals, + vec![ + &vec![OsString::from("aaa")], + &vec![OsString::from("bbb"), OsString::from("ccc"),], + &vec![OsString::from("ddd")], + &vec![OsString::from("eee")], + &vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ] + ] + ) + } + + #[test] + fn test_grouped_vals_removal() { + let m = { + let mut m = MatchedArg::new(); + m.push_val("aaa".into()); + m.new_val_group(); + m.append_val("bbb".into()); + m.append_val("ccc".into()); + m.new_val_group(); + m.append_val("ddd".into()); + m.push_val("eee".into()); + m.new_val_group(); + m.append_val("fff".into()); + m.append_val("ggg".into()); + m.append_val("hhh".into()); + m.append_val("iii".into()); + m + }; + { + let mut m = m.clone(); + m.remove_vals(0); + let vals1 = m.vals().collect::<Vec<_>>(); + assert_eq!( + vals1, + vec![ + &vec![OsString::from("aaa")], + &vec![OsString::from("bbb"), OsString::from("ccc"),], + &vec![OsString::from("ddd")], + &vec![OsString::from("eee")], + &vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ] + ] + ); + } + + { + let mut m = m.clone(); + m.remove_vals(1); + let vals0 = m.vals().collect::<Vec<_>>(); + assert_eq!( + vals0, + vec![ + &vec![OsString::from("bbb"), OsString::from("ccc"),], + &vec![OsString::from("ddd")], + &vec![OsString::from("eee")], + &vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ] + ] + ); + } + + { + let mut m = m.clone(); + m.remove_vals(2); + let vals1 = m.vals().collect::<Vec<_>>(); + assert_eq!( + vals1, + vec![ + &vec![OsString::from("ccc"),], + &vec![OsString::from("ddd")], + &vec![OsString::from("eee")], + &vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ] + ] + ); + } + + { + let mut m = m.clone(); + m.remove_vals(3); + let vals1 = m.vals().collect::<Vec<_>>(); + assert_eq!( + vals1, + vec![ + &vec![OsString::from("ddd")], + &vec![OsString::from("eee")], + &vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ] + ] + ); + } + + { + let mut m = m.clone(); + m.remove_vals(4); + let vals1 = m.vals().collect::<Vec<_>>(); + assert_eq!( + vals1, + vec![ + &vec![OsString::from("eee")], + &vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ] + ] + ); + } + + { + let mut m = m.clone(); + m.remove_vals(5); + let vals1 = m.vals().collect::<Vec<_>>(); + assert_eq!( + vals1, + vec![&vec![ + OsString::from("fff"), + OsString::from("ggg"), + OsString::from("hhh"), + OsString::from("iii"), + ]] + ); + } + + { + let mut m = m.clone(); + m.remove_vals(7); + let vals1 = m.vals().collect::<Vec<_>>(); + assert_eq!( + vals1, + vec![&vec![OsString::from("hhh"), OsString::from("iii"),]] + ); + } + + { + let mut m = m; + m.remove_vals(9); + assert_eq!(m.vals().next(), None); + } + } +} diff --git a/third_party/rust/clap/src/parse/matches/mod.rs b/third_party/rust/clap/src/parse/matches/mod.rs new file mode 100644 index 0000000000..7efa8b414f --- /dev/null +++ b/third_party/rust/clap/src/parse/matches/mod.rs @@ -0,0 +1,9 @@ +mod arg_matches; +mod matched_arg; +mod value_source; + +pub use arg_matches::{ArgMatches, Indices, OsValues, Values}; +pub use value_source::ValueSource; + +pub(crate) use arg_matches::SubCommand; +pub(crate) use matched_arg::MatchedArg; diff --git a/third_party/rust/clap/src/parse/matches/value_source.rs b/third_party/rust/clap/src/parse/matches/value_source.rs new file mode 100644 index 0000000000..fb762d2af6 --- /dev/null +++ b/third_party/rust/clap/src/parse/matches/value_source.rs @@ -0,0 +1,11 @@ +/// Origin of the argument's value +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +#[non_exhaustive] +pub enum ValueSource { + /// Value came [`Arg::default_value`][crate::Arg::default_value] + DefaultValue, + /// Value came [`Arg::env`][crate::Arg::env] + EnvVariable, + /// Value was passed in on the command-line + CommandLine, +} diff --git a/third_party/rust/clap/src/parse/mod.rs b/third_party/rust/clap/src/parse/mod.rs new file mode 100644 index 0000000000..298862e134 --- /dev/null +++ b/third_party/rust/clap/src/parse/mod.rs @@ -0,0 +1,13 @@ +mod arg_matcher; +mod parser; +mod validator; + +pub mod features; +pub mod matches; + +pub(crate) use self::arg_matcher::ArgMatcher; +pub(crate) use self::matches::{MatchedArg, SubCommand}; +pub(crate) use self::parser::{ParseState, Parser}; +pub(crate) use self::validator::Validator; + +pub use self::matches::{ArgMatches, Indices, OsValues, ValueSource, Values}; diff --git a/third_party/rust/clap/src/parse/parser.rs b/third_party/rust/clap/src/parse/parser.rs new file mode 100644 index 0000000000..6262d18d88 --- /dev/null +++ b/third_party/rust/clap/src/parse/parser.rs @@ -0,0 +1,1555 @@ +// Std +use std::{ + cell::Cell, + ffi::{OsStr, OsString}, +}; + +// Third Party +use clap_lex::RawOsStr; + +// Internal +use crate::build::AppSettings as AS; +use crate::build::{Arg, Command}; +use crate::error::Error as ClapError; +use crate::error::Result as ClapResult; +use crate::mkeymap::KeyType; +use crate::output::fmt::Stream; +use crate::output::{fmt::Colorizer, Usage}; +use crate::parse::features::suggestions; +use crate::parse::{ArgMatcher, SubCommand}; +use crate::parse::{Validator, ValueSource}; +use crate::util::Id; +use crate::{INTERNAL_ERROR_MSG, INVALID_UTF8}; + +pub(crate) struct Parser<'help, 'cmd> { + cmd: &'cmd mut Command<'help>, + seen: Vec<Id>, + cur_idx: Cell<usize>, + /// Index of the previous flag subcommand in a group of flags. + flag_subcmd_at: Option<usize>, + /// Counter indicating the number of items to skip + /// when revisiting the group of flags which includes the flag subcommand. + flag_subcmd_skip: usize, +} + +// Initializing Methods +impl<'help, 'cmd> Parser<'help, 'cmd> { + pub(crate) fn new(cmd: &'cmd mut Command<'help>) -> Self { + Parser { + cmd, + seen: Vec::new(), + cur_idx: Cell::new(0), + flag_subcmd_at: None, + flag_subcmd_skip: 0, + } + } +} + +// Parsing Methods +impl<'help, 'cmd> Parser<'help, 'cmd> { + // The actual parsing function + #[allow(clippy::cognitive_complexity)] + pub(crate) fn get_matches_with( + &mut self, + matcher: &mut ArgMatcher, + raw_args: &mut clap_lex::RawArgs, + mut args_cursor: clap_lex::ArgCursor, + ) -> ClapResult<()> { + debug!("Parser::get_matches_with"); + // Verify all positional assertions pass + + let mut subcmd_name: Option<String> = None; + let mut keep_state = false; + let mut parse_state = ParseState::ValuesDone; + let mut pos_counter = 1; + + // Already met any valid arg(then we shouldn't expect subcommands after it). + let mut valid_arg_found = false; + // If the user already passed '--'. Meaning only positional args follow. + let mut trailing_values = false; + + // Count of positional args + let positional_count = self + .cmd + .get_keymap() + .keys() + .filter(|x| x.is_position()) + .count(); + // If any arg sets .last(true) + let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set()); + + while let Some(arg_os) = raw_args.next(&mut args_cursor) { + // Recover the replaced items if any. + if let Some(replaced_items) = arg_os + .to_value() + .ok() + .and_then(|a| self.cmd.get_replacement(a)) + { + debug!( + "Parser::get_matches_with: found replacer: {:?}, target: {:?}", + arg_os, replaced_items + ); + raw_args.insert(&args_cursor, replaced_items); + continue; + } + + debug!( + "Parser::get_matches_with: Begin parsing '{:?}' ({:?})", + arg_os.to_value_os(), + arg_os.to_value_os().as_raw_bytes() + ); + + // Correct pos_counter. + pos_counter = { + let is_second_to_last = pos_counter + 1 == positional_count; + + // The last positional argument, or second to last positional + // argument may be set to .multiple_values(true) or `.multiple_occurrences(true)` + let low_index_mults = is_second_to_last + && self + .cmd + .get_positionals() + .any(|a| a.is_multiple() && (positional_count != a.index.unwrap_or(0))) + && self + .cmd + .get_positionals() + .last() + .map_or(false, |p_name| !p_name.is_last_set()); + + let missing_pos = self.cmd.is_allow_missing_positional_set() + && is_second_to_last + && !trailing_values; + + debug!( + "Parser::get_matches_with: Positional counter...{}", + pos_counter + ); + debug!( + "Parser::get_matches_with: Low index multiples...{:?}", + low_index_mults + ); + + if low_index_mults || missing_pos { + let skip_current = if let Some(n) = raw_args.peek(&args_cursor) { + if let Some(p) = self + .cmd + .get_positionals() + .find(|p| p.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, p) + || 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 + } + }; + + // 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.is_set(AS::NoAutoHelp) + && !self.cmd.is_disable_help_subcommand_set() + { + self.parse_help_subcommand(raw_args.remaining(&mut args_cursor))?; + } + subcmd_name = Some(sc_name.to_owned()); + break; + } + } + + if arg_os.is_escape() { + if matches!(&parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if + self.cmd[opt].is_allow_hyphen_values_set()) + { + // ParseResult::MaybeHyphenValue, do nothing + } else { + debug!("Parser::get_matches_with: setting TrailingVals=true"); + trailing_values = true; + continue; + } + } else if let Some((long_arg, long_value)) = arg_os.to_long() { + let parse_result = self.parse_long_arg( + matcher, + long_arg, + long_value, + &parse_state, + &mut valid_arg_found, + trailing_values, + ); + debug!( + "Parser::get_matches_with: After parse_long_arg {:?}", + parse_result + ); + match parse_result { + ParseResult::NoArg => { + unreachable!("`to_long` always has the flag specified") + } + ParseResult::ValuesDone => { + parse_state = ParseState::ValuesDone; + continue; + } + ParseResult::Opt(id) => { + parse_state = ParseState::Opt(id); + continue; + } + ParseResult::FlagSubCommand(name) => { + debug!( + "Parser::get_matches_with: FlagSubCommand found in long arg {:?}", + &name + ); + subcmd_name = Some(name); + break; + } + ParseResult::EqualsNotProvided { arg } => { + return Err(ClapError::no_equals( + self.cmd, + arg, + Usage::new(self.cmd).create_usage_with_title(&[]), + )); + } + ParseResult::NoMatchingArg { arg } => { + let remaining_args: Vec<_> = raw_args + .remaining(&mut args_cursor) + .map(|x| x.to_str().expect(INVALID_UTF8)) + .collect(); + return Err(self.did_you_mean_error(&arg, matcher, &remaining_args)); + } + ParseResult::UnneededAttachedValue { rest, used, arg } => { + return Err(ClapError::too_many_values( + self.cmd, + rest, + arg, + Usage::new(self.cmd).create_usage_no_title(&used), + )) + } + ParseResult::HelpFlag => { + return Err(self.help_err(true, Stream::Stdout)); + } + ParseResult::VersionFlag => { + return Err(self.version_err(true)); + } + ParseResult::MaybeHyphenValue => { + // Maybe a hyphen value, do nothing. + } + ParseResult::AttachedValueNotConsumed => { + unreachable!() + } + } + } else if let Some(short_arg) = arg_os.to_short() { + // Arg looks like a short flag, and not a possible number + + // Try to parse short args like normal, if allow_hyphen_values or + // AllowNegativeNumbers is set, parse_short_arg will *not* throw + // an error, and instead return Ok(None) + let parse_result = self.parse_short_arg( + matcher, + short_arg, + &parse_state, + pos_counter, + &mut valid_arg_found, + trailing_values, + ); + // If it's None, we then check if one of those two AppSettings was set + debug!( + "Parser::get_matches_with: After parse_short_arg {:?}", + parse_result + ); + match parse_result { + ParseResult::NoArg => { + // Is a single dash `-`, try positional. + } + ParseResult::ValuesDone => { + parse_state = ParseState::ValuesDone; + continue; + } + ParseResult::Opt(id) => { + parse_state = ParseState::Opt(id); + continue; + } + ParseResult::FlagSubCommand(name) => { + // If there are more short flags to be processed, we should keep the state, and later + // revisit the current group of short flags skipping the subcommand. + keep_state = self + .flag_subcmd_at + .map(|at| { + raw_args + .seek(&mut args_cursor, clap_lex::SeekFrom::Current(-1)); + // Since we are now saving the current state, the number of flags to skip during state recovery should + // be the current index (`cur_idx`) minus ONE UNIT TO THE LEFT of the starting position. + self.flag_subcmd_skip = self.cur_idx.get() - at + 1; + }) + .is_some(); + + debug!( + "Parser::get_matches_with:FlagSubCommandShort: subcmd_name={}, keep_state={}, flag_subcmd_skip={}", + name, + keep_state, + self.flag_subcmd_skip + ); + + subcmd_name = Some(name); + break; + } + ParseResult::EqualsNotProvided { arg } => { + return Err(ClapError::no_equals( + self.cmd, + arg, + Usage::new(self.cmd).create_usage_with_title(&[]), + )) + } + ParseResult::NoMatchingArg { arg } => { + return Err(ClapError::unknown_argument( + self.cmd, + arg, + None, + Usage::new(self.cmd).create_usage_with_title(&[]), + )); + } + ParseResult::HelpFlag => { + return Err(self.help_err(false, Stream::Stdout)); + } + ParseResult::VersionFlag => { + return Err(self.version_err(false)); + } + 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 parse_result = self.add_val_to_arg( + &self.cmd[id], + arg_os.to_value_os(), + matcher, + ValueSource::CommandLine, + true, + trailing_values, + ); + parse_state = match parse_result { + ParseResult::Opt(id) => ParseState::Opt(id), + ParseResult::ValuesDone => ParseState::ValuesDone, + _ => unreachable!(), + }; + // get the next value from the iterator + continue; + } + } + + if let Some(p) = self.cmd.get_keymap().get(&pos_counter) { + if p.is_last_set() && !trailing_values { + return Err(ClapError::unknown_argument( + self.cmd, + arg_os.display().to_string(), + None, + Usage::new(self.cmd).create_usage_with_title(&[]), + )); + } + + if self.cmd.is_trailing_var_arg_set() && pos_counter == positional_count { + trailing_values = true; + } + + self.seen.push(p.id.clone()); + // Increase occurrence no matter if we are appending, occurrences + // of positional argument equals to number of values rather than + // the number of value groups. + self.inc_occurrence_of_arg(matcher, p); + // Creating new value group rather than appending when the arg + // doesn't have any value. This behaviour is right because + // positional arguments are always present continuously. + let append = self.has_val_groups(matcher, p); + self.add_val_to_arg( + p, + arg_os.to_value_os(), + matcher, + ValueSource::CommandLine, + append, + trailing_values, + ); + + // Only increment the positional counter if it doesn't allow multiples + if !p.is_multiple() { + pos_counter += 1; + parse_state = ParseState::ValuesDone; + } else { + parse_state = ParseState::Pos(p.id.clone()); + } + valid_arg_found = true; + } else if self.cmd.is_allow_external_subcommands_set() { + // Get external subcommand name + let sc_name = match arg_os.to_value() { + Ok(s) => s.to_string(), + Err(_) => { + 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); + let allow_invalid_utf8 = self + .cmd + .is_allow_invalid_utf8_for_external_subcommands_set(); + #[cfg(feature = "unstable-v4")] + { + sc_m.inc_occurrence_of_external(allow_invalid_utf8); + } + + for v in raw_args.remaining(&mut args_cursor) { + if !allow_invalid_utf8 && v.to_str().is_none() { + return Err(ClapError::invalid_utf8( + self.cmd, + Usage::new(self.cmd).create_usage_with_title(&[]), + )); + } + let external_id = &Id::empty_hash(); + sc_m.add_val_to( + external_id, + v.to_os_string(), + ValueSource::CommandLine, + false, + ); + #[cfg(not(feature = "unstable-v4"))] + { + sc_m.get_mut(external_id) + .expect("just inserted") + .invalid_utf8_allowed(allow_invalid_utf8); + } + } + + matcher.subcommand(SubCommand { + id: Id::from(&*sc_name), + name: sc_name, + matches: sc_m.into_inner(), + }); + + #[cfg(feature = "env")] + self.add_env(matcher, trailing_values)?; + self.add_defaults(matcher, trailing_values); + return Validator::new(self.cmd).validate(parse_state, matcher); + } else { + // Start error processing + return Err(self.match_arg_error(&arg_os, valid_arg_found, trailing_values)); + } + } + + if let Some(ref pos_sc_name) = subcmd_name { + let sc_name = self + .cmd + .find_subcommand(pos_sc_name) + .expect(INTERNAL_ERROR_MSG) + .get_name() + .to_owned(); + self.parse_subcommand(&sc_name, matcher, raw_args, args_cursor, keep_state)?; + } + + #[cfg(feature = "env")] + self.add_env(matcher, trailing_values)?; + self.add_defaults(matcher, trailing_values); + Validator::new(self.cmd).validate(parse_state, matcher) + } + + fn match_arg_error( + &self, + arg_os: &clap_lex::ParsedArg<'_>, + valid_arg_found: bool, + trailing_values: bool, + ) -> ClapError { + // If argument follows a `--` + if trailing_values { + // If the arg matches a subcommand name, or any of its aliases (if defined) + if self + .possible_subcommand(arg_os.to_value(), valid_arg_found) + .is_some() + { + return ClapError::unnecessary_double_dash( + self.cmd, + arg_os.display().to_string(), + Usage::new(self.cmd).create_usage_with_title(&[]), + ); + } + } + let candidates = suggestions::did_you_mean( + &arg_os.display().to_string(), + self.cmd.all_subcommand_names(), + ); + // If the argument looks like a subcommand. + if !candidates.is_empty() { + let candidates: Vec<_> = candidates + .iter() + .map(|candidate| format!("'{}'", candidate)) + .collect(); + return ClapError::invalid_subcommand( + self.cmd, + arg_os.display().to_string(), + candidates.join(" or "), + self.cmd + .get_bin_name() + .unwrap_or_else(|| self.cmd.get_name()) + .to_owned(), + Usage::new(self.cmd).create_usage_with_title(&[]), + ); + } + // If the argument must be a subcommand. + if !self.cmd.has_args() || self.cmd.is_infer_subcommands_set() && self.cmd.has_subcommands() + { + return ClapError::unrecognized_subcommand( + self.cmd, + arg_os.display().to_string(), + Usage::new(self.cmd).create_usage_with_title(&[]), + ); + } + ClapError::unknown_argument( + self.cmd, + arg_os.display().to_string(), + None, + Usage::new(self.cmd).create_usage_with_title(&[]), + ) + } + + // Checks if the arg matches a subcommand name, or any of its aliases (if defined) + fn possible_subcommand( + &self, + arg: Result<&str, &RawOsStr>, + valid_arg_found: bool, + ) -> Option<&str> { + debug!("Parser::possible_subcommand: arg={:?}", arg); + let arg = arg.ok()?; + + if !(self.cmd.is_args_conflicts_with_subcommands_set() && valid_arg_found) { + if self.cmd.is_infer_subcommands_set() { + // For subcommand `test`, we accepts it's prefix: `t`, `te`, + // `tes` and `test`. + let v = self + .cmd + .all_subcommand_names() + .filter(|s| s.starts_with(arg)) + .collect::<Vec<_>>(); + + if v.len() == 1 { + return Some(v[0]); + } + + // If there is any ambiguity, fallback to non-infer subcommand + // search. + } + if let Some(sc) = self.cmd.find_subcommand(arg) { + return Some(sc.get_name()); + } + } + None + } + + // Checks if the arg matches a long flag subcommand name, or any of its aliases (if defined) + fn possible_long_flag_subcommand(&self, arg: &str) -> Option<&str> { + debug!("Parser::possible_long_flag_subcommand: arg={:?}", arg); + if self.cmd.is_infer_subcommands_set() { + let options = self + .cmd + .get_subcommands() + .fold(Vec::new(), |mut options, sc| { + if let Some(long) = sc.get_long_flag() { + if long.starts_with(arg) { + options.push(long); + } + options.extend(sc.get_all_aliases().filter(|alias| alias.starts_with(arg))) + } + options + }); + if options.len() == 1 { + return Some(options[0]); + } + + for sc in options { + if sc == arg { + return Some(sc); + } + } + } else if let Some(sc_name) = self.cmd.find_long_subcmd(arg) { + return Some(sc_name); + } + None + } + + fn parse_help_subcommand( + &self, + cmds: impl Iterator<Item = &'cmd OsStr>, + ) -> ClapResult<ParseResult> { + debug!("Parser::parse_help_subcommand"); + + let mut cmd = self.cmd.clone(); + let sc = { + let mut sc = &mut cmd; + + for cmd in cmds { + sc = if let Some(sc_name) = + sc.find_subcommand(cmd).map(|sc| sc.get_name().to_owned()) + { + sc._build_subcommand(&sc_name).unwrap() + } else { + return Err(ClapError::unrecognized_subcommand( + sc, + cmd.to_string_lossy().into_owned(), + Usage::new(sc).create_usage_with_title(&[]), + )); + }; + } + + sc + }; + let parser = Parser::new(sc); + + Err(parser.help_err(true, Stream::Stdout)) + } + + fn is_new_arg(&self, next: &clap_lex::ParsedArg<'_>, current_positional: &Arg) -> bool { + #![allow(clippy::needless_bool)] // Prefer consistent if/else-if ladder + + debug!( + "Parser::is_new_arg: {:?}:{:?}", + next.to_value_os(), + current_positional.name + ); + + if self.cmd.is_allow_hyphen_values_set() + || self.cmd[¤t_positional.id].is_allow_hyphen_values_set() + || (self.cmd.is_allow_negative_numbers_set() && next.is_number()) + { + // If allow hyphen, this isn't a new arg. + debug!("Parser::is_new_arg: Allow hyphen"); + false + } else if next.is_long() { + // If this is a long flag, this is a new arg. + debug!("Parser::is_new_arg: --<something> found"); + true + } else if next.is_short() { + // If this is a short flag, this is a new arg. But a singe '-' by + // itself is a value and typically means "stdin" on unix systems. + debug!("Parser::is_new_arg: -<something> found"); + true + } else { + // Nothing special, this is a value. + debug!("Parser::is_new_arg: value"); + false + } + } + + fn parse_subcommand( + &mut self, + sc_name: &str, + matcher: &mut ArgMatcher, + raw_args: &mut clap_lex::RawArgs, + args_cursor: clap_lex::ArgCursor, + keep_state: bool, + ) -> ClapResult<()> { + debug!("Parser::parse_subcommand"); + + let partial_parsing_enabled = self.cmd.is_ignore_errors_set(); + + if let Some(sc) = self.cmd._build_subcommand(sc_name) { + let mut sc_matcher = ArgMatcher::new(sc); + + debug!( + "Parser::parse_subcommand: About to parse sc={}", + sc.get_name() + ); + + { + let mut p = Parser::new(sc); + // HACK: maintain indexes between parsers + // FlagSubCommand short arg needs to revisit the current short args, but skip the subcommand itself + if keep_state { + p.cur_idx.set(self.cur_idx.get()); + p.flag_subcmd_at = self.flag_subcmd_at; + p.flag_subcmd_skip = self.flag_subcmd_skip; + } + if let Err(error) = p.get_matches_with(&mut sc_matcher, raw_args, args_cursor) { + if partial_parsing_enabled { + debug!( + "Parser::parse_subcommand: ignored error in subcommand {}: {:?}", + sc_name, error + ); + } else { + return Err(error); + } + } + } + matcher.subcommand(SubCommand { + id: sc.get_id(), + name: sc.get_name().to_owned(), + matches: sc_matcher.into_inner(), + }); + } + Ok(()) + } + + // Retrieves the names of all args the user has supplied thus far, except required ones + // because those will be listed in self.required + fn check_for_help_and_version_str(&self, arg: &RawOsStr) -> Option<ParseResult> { + debug!("Parser::check_for_help_and_version_str"); + debug!( + "Parser::check_for_help_and_version_str: Checking if --{:?} is help or version...", + arg + ); + + if let Some(help) = self.cmd.find(&Id::help_hash()) { + if let Some(h) = help.long { + if arg == h && !self.is_set(AS::NoAutoHelp) && !self.cmd.is_disable_help_flag_set() + { + debug!("Help"); + return Some(ParseResult::HelpFlag); + } + } + } + + if let Some(version) = self.cmd.find(&Id::version_hash()) { + if let Some(v) = version.long { + if arg == v + && !self.is_set(AS::NoAutoVersion) + && !self.cmd.is_disable_version_flag_set() + { + debug!("Version"); + return Some(ParseResult::VersionFlag); + } + } + } + + debug!("Neither"); + None + } + + fn check_for_help_and_version_char(&self, arg: char) -> Option<ParseResult> { + debug!("Parser::check_for_help_and_version_char"); + debug!( + "Parser::check_for_help_and_version_char: Checking if -{} is help or version...", + arg + ); + + if let Some(help) = self.cmd.find(&Id::help_hash()) { + if let Some(h) = help.short { + if arg == h && !self.is_set(AS::NoAutoHelp) && !self.cmd.is_disable_help_flag_set() + { + debug!("Help"); + return Some(ParseResult::HelpFlag); + } + } + } + + if let Some(version) = self.cmd.find(&Id::version_hash()) { + if let Some(v) = version.short { + if arg == v + && !self.is_set(AS::NoAutoVersion) + && !self.cmd.is_disable_version_flag_set() + { + debug!("Version"); + return Some(ParseResult::VersionFlag); + } + } + } + + debug!("Neither"); + None + } + + fn parse_long_arg( + &mut self, + matcher: &mut ArgMatcher, + long_arg: Result<&str, &RawOsStr>, + long_value: Option<&RawOsStr>, + parse_state: &ParseState, + valid_arg_found: &mut bool, + trailing_values: bool, + ) -> ParseResult { + // maybe here lifetime should be 'a + debug!("Parser::parse_long_arg"); + + if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if + self.cmd[opt].is_allow_hyphen_values_set()) + { + return ParseResult::MaybeHyphenValue; + } + + // Update the current index + self.cur_idx.set(self.cur_idx.get() + 1); + debug!("Parser::parse_long_arg: cur_idx:={}", self.cur_idx.get()); + + debug!("Parser::parse_long_arg: Does it contain '='..."); + let long_arg = match long_arg { + Ok(long_arg) => long_arg, + Err(long_arg) => { + return ParseResult::NoMatchingArg { + arg: long_arg.to_str_lossy().into_owned(), + }; + } + }; + if long_arg.is_empty() { + debug_assert!(long_value.is_none(), "{:?}", long_value); + return ParseResult::NoArg; + } + + let opt = if let Some(opt) = self.cmd.get_keymap().get(long_arg) { + debug!( + "Parser::parse_long_arg: Found valid opt or flag '{}'", + opt.to_string() + ); + Some(opt) + } else if self.cmd.is_infer_long_args_set() { + self.cmd.get_arguments().find(|a| { + a.long.map_or(false, |long| long.starts_with(long_arg)) + || a.aliases + .iter() + .any(|(alias, _)| alias.starts_with(long_arg)) + }) + } else { + None + }; + + if let Some(opt) = opt { + *valid_arg_found = true; + self.seen.push(opt.id.clone()); + if opt.is_takes_value_set() { + debug!( + "Parser::parse_long_arg: Found an opt with value '{:?}'", + &long_value + ); + let has_eq = long_value.is_some(); + self.parse_opt(long_value, opt, matcher, trailing_values, has_eq) + } else if let Some(rest) = long_value { + let required = self.cmd.required_graph(); + debug!("Parser::parse_long_arg: Got invalid literal `{:?}`", rest); + let used: Vec<Id> = matcher + .arg_names() + .filter(|&n| { + self.cmd + .find(n) + .map_or(true, |a| !(a.is_hide_set() || required.contains(&a.id))) + }) + .cloned() + .collect(); + + ParseResult::UnneededAttachedValue { + rest: rest.to_str_lossy().into_owned(), + used, + arg: opt.to_string(), + } + } else if let Some(parse_result) = + self.check_for_help_and_version_str(RawOsStr::from_str(long_arg)) + { + parse_result + } else { + debug!("Parser::parse_long_arg: Presence validated"); + self.parse_flag(opt, matcher) + } + } else if let Some(sc_name) = self.possible_long_flag_subcommand(long_arg) { + ParseResult::FlagSubCommand(sc_name.to_string()) + } else if self.cmd.is_allow_hyphen_values_set() { + ParseResult::MaybeHyphenValue + } else { + ParseResult::NoMatchingArg { + arg: long_arg.to_owned(), + } + } + } + + fn parse_short_arg( + &mut self, + matcher: &mut ArgMatcher, + mut short_arg: clap_lex::ShortFlags<'_>, + parse_state: &ParseState, + // change this to possible pos_arg when removing the usage of &mut Parser. + pos_counter: usize, + valid_arg_found: &mut bool, + trailing_values: bool, + ) -> ParseResult { + debug!("Parser::parse_short_arg: short_arg={:?}", short_arg); + + #[allow(clippy::blocks_in_if_conditions)] + if self.cmd.is_allow_negative_numbers_set() && short_arg.is_number() { + debug!("Parser::parse_short_arg: negative number"); + return ParseResult::MaybeHyphenValue; + } else if self.cmd.is_allow_hyphen_values_set() + && short_arg + .clone() + .any(|c| !c.map(|c| self.cmd.contains_short(c)).unwrap_or_default()) + { + debug!("Parser::parse_short_args: contains non-short flag"); + return ParseResult::MaybeHyphenValue; + } else if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) + if self.cmd[opt].is_allow_hyphen_values_set()) + { + debug!("Parser::parse_short_args: prior arg accepts hyphenated values",); + return ParseResult::MaybeHyphenValue; + } else if self + .cmd + .get_keymap() + .get(&pos_counter) + .map_or(false, |arg| { + arg.is_allow_hyphen_values_set() && !arg.is_last_set() + }) + { + debug!( + "Parser::parse_short_args: positional at {} allows hyphens", + pos_counter + ); + return 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 ParseResult::NoMatchingArg { + arg: format!("-{}", rest.to_str_lossy()), + }; + } + }; + debug!("Parser::parse_short_arg:iter:{}", c); + + // update each index because `-abcd` is four indices to clap + self.cur_idx.set(self.cur_idx.get() + 1); + debug!( + "Parser::parse_short_arg:iter:{}: cur_idx:={}", + c, + self.cur_idx.get() + ); + + // Check for matching short options, and return the name if there is no trailing + // concatenated value: -oval + // Option: -o + // Value: val + if let Some(opt) = self.cmd.get_keymap().get(&c) { + debug!( + "Parser::parse_short_arg:iter:{}: Found valid opt or flag", + c + ); + *valid_arg_found = true; + self.seen.push(opt.id.clone()); + if !opt.is_takes_value_set() { + if let Some(parse_result) = self.check_for_help_and_version_char(c) { + return parse_result; + } + ret = self.parse_flag(opt, matcher); + continue; + } + + // Check for trailing concatenated value + // + // Cloning the iterator, so we rollback if it isn't there. + let val = short_arg.clone().next_value_os().unwrap_or_default(); + debug!( + "Parser::parse_short_arg:iter:{}: val={:?} (bytes), val={:?} (ascii), short_arg={:?}", + c, val, val.as_raw_bytes(), short_arg + ); + let val = Some(val).filter(|v| !v.is_empty()); + + // Default to "we're expecting a value later". + // + // If attached value is not consumed, we may have more short + // flags to parse, continue. + // + // e.g. `-xvf`, when require_equals && x.min_vals == 0, we don't + // consume the `vf`, even if it's provided as value. + let (val, has_eq) = if let Some(val) = val.and_then(|v| v.strip_prefix('=')) { + (Some(val), true) + } else { + (val, false) + }; + match self.parse_opt(val, opt, matcher, trailing_values, has_eq) { + ParseResult::AttachedValueNotConsumed => continue, + x => return x, + } + } + + return if let Some(sc_name) = self.cmd.find_short_subcmd(c) { + debug!("Parser::parse_short_arg:iter:{}: subcommand={}", c, sc_name); + 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; + } + ParseResult::FlagSubCommand(name) + } else { + ParseResult::NoMatchingArg { + arg: format!("-{}", c), + } + }; + } + ret + } + + fn parse_opt( + &self, + attached_value: Option<&RawOsStr>, + opt: &Arg<'help>, + matcher: &mut ArgMatcher, + trailing_values: bool, + has_eq: bool, + ) -> ParseResult { + debug!( + "Parser::parse_opt; opt={}, val={:?}, has_eq={:?}", + opt.name, attached_value, has_eq + ); + debug!("Parser::parse_opt; opt.settings={:?}", opt.settings); + + debug!("Parser::parse_opt; Checking for val..."); + // require_equals is set, but no '=' is provided, try throwing error. + if opt.is_require_equals_set() && !has_eq { + if opt.min_vals == Some(0) { + debug!("Requires equals, but min_vals == 0"); + self.inc_occurrence_of_arg(matcher, opt); + // We assume this case is valid: require equals, but min_vals == 0. + if !opt.default_missing_vals.is_empty() { + debug!("Parser::parse_opt: has default_missing_vals"); + self.add_multiple_vals_to_arg( + opt, + opt.default_missing_vals.iter().map(OsString::from), + matcher, + ValueSource::CommandLine, + false, + ); + }; + if attached_value.is_some() { + ParseResult::AttachedValueNotConsumed + } else { + ParseResult::ValuesDone + } + } else { + debug!("Requires equals but not provided. Error."); + ParseResult::EqualsNotProvided { + arg: opt.to_string(), + } + } + } else if let Some(v) = attached_value { + self.inc_occurrence_of_arg(matcher, opt); + self.add_val_to_arg( + opt, + v, + matcher, + ValueSource::CommandLine, + false, + trailing_values, + ); + ParseResult::ValuesDone + } else { + debug!("Parser::parse_opt: More arg vals required..."); + self.inc_occurrence_of_arg(matcher, opt); + matcher.new_val_group(&opt.id); + for group in self.cmd.groups_for_arg(&opt.id) { + matcher.new_val_group(&group); + } + ParseResult::Opt(opt.id.clone()) + } + } + + fn add_val_to_arg( + &self, + arg: &Arg<'help>, + val: &RawOsStr, + matcher: &mut ArgMatcher, + ty: ValueSource, + append: bool, + trailing_values: bool, + ) -> ParseResult { + debug!("Parser::add_val_to_arg; arg={}, val={:?}", arg.name, val); + debug!( + "Parser::add_val_to_arg; trailing_values={:?}, DontDelimTrailingVals={:?}", + trailing_values, + self.cmd.is_dont_delimit_trailing_values_set() + ); + if !(trailing_values && self.cmd.is_dont_delimit_trailing_values_set()) { + if let Some(delim) = arg.val_delim { + let terminator = arg.terminator.map(OsStr::new); + let vals = val + .split(delim) + .map(|x| x.to_os_str().into_owned()) + .take_while(|val| Some(val.as_os_str()) != terminator); + self.add_multiple_vals_to_arg(arg, vals, matcher, ty, append); + // If there was a delimiter used or we must use the delimiter to + // separate the values or no more vals is needed, we're not + // looking for more values. + return if val.contains(delim) + || arg.is_require_value_delimiter_set() + || !matcher.needs_more_vals(arg) + { + ParseResult::ValuesDone + } else { + ParseResult::Opt(arg.id.clone()) + }; + } + } + if let Some(t) = arg.terminator { + if t == val { + return ParseResult::ValuesDone; + } + } + self.add_single_val_to_arg(arg, val.to_os_str().into_owned(), matcher, ty, append); + if matcher.needs_more_vals(arg) { + ParseResult::Opt(arg.id.clone()) + } else { + ParseResult::ValuesDone + } + } + + fn add_multiple_vals_to_arg( + &self, + arg: &Arg<'help>, + vals: impl Iterator<Item = OsString>, + matcher: &mut ArgMatcher, + ty: ValueSource, + append: bool, + ) { + // If not appending, create a new val group and then append vals in. + if !append { + matcher.new_val_group(&arg.id); + for group in self.cmd.groups_for_arg(&arg.id) { + matcher.new_val_group(&group); + } + } + for val in vals { + self.add_single_val_to_arg(arg, val, matcher, ty, true); + } + } + + fn add_single_val_to_arg( + &self, + arg: &Arg<'help>, + val: OsString, + matcher: &mut ArgMatcher, + ty: ValueSource, + append: bool, + ) { + debug!("Parser::add_single_val_to_arg: adding val...{:?}", val); + + // 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() + ); + + // Increment or create the group "args" + for group in self.cmd.groups_for_arg(&arg.id) { + matcher.add_val_to(&group, val.clone(), ty, append); + } + + matcher.add_val_to(&arg.id, val, ty, append); + matcher.add_index_to(&arg.id, self.cur_idx.get(), ty); + } + + fn has_val_groups(&self, matcher: &mut ArgMatcher, arg: &Arg<'help>) -> bool { + matcher.has_val_groups(&arg.id) + } + + fn parse_flag(&self, flag: &Arg<'help>, matcher: &mut ArgMatcher) -> ParseResult { + debug!("Parser::parse_flag"); + + self.inc_occurrence_of_arg(matcher, flag); + matcher.add_index_to(&flag.id, self.cur_idx.get(), ValueSource::CommandLine); + + ParseResult::ValuesDone + } + + fn remove_overrides(&self, arg: &Arg<'help>, matcher: &mut ArgMatcher) { + debug!("Parser::remove_overrides: id={:?}", arg.id); + for override_id in &arg.overrides { + debug!("Parser::remove_overrides:iter:{:?}: removing", override_id); + matcher.remove(override_id); + } + + // Override anything that can override us + let mut transitive = Vec::new(); + for arg_id in matcher.arg_names() { + if let Some(overrider) = self.cmd.find(arg_id) { + if overrider.overrides.contains(&arg.id) { + transitive.push(&overrider.id); + } + } + } + for overrider_id in transitive { + debug!("Parser::remove_overrides:iter:{:?}: removing", overrider_id); + matcher.remove(overrider_id); + } + } + + pub(crate) fn add_defaults(&mut self, matcher: &mut ArgMatcher, trailing_values: bool) { + debug!("Parser::add_defaults"); + + for o in self.cmd.get_opts() { + debug!("Parser::add_defaults:iter:{}:", o.name); + self.add_value(o, matcher, ValueSource::DefaultValue, trailing_values); + } + + for p in self.cmd.get_positionals() { + debug!("Parser::add_defaults:iter:{}:", p.name); + self.add_value(p, matcher, ValueSource::DefaultValue, trailing_values); + } + } + + fn add_value( + &self, + arg: &Arg<'help>, + matcher: &mut ArgMatcher, + ty: ValueSource, + trailing_values: bool, + ) { + if !arg.default_vals_ifs.is_empty() { + debug!("Parser::add_value: has conditional defaults"); + if matcher.get(&arg.id).is_none() { + for (id, val, default) in arg.default_vals_ifs.iter() { + let add = if let Some(a) = matcher.get(id) { + match val { + crate::build::ArgPredicate::Equals(v) => { + a.vals_flatten().any(|value| v == value) + } + crate::build::ArgPredicate::IsPresent => true, + } + } else { + false + }; + + if add { + if let Some(default) = default { + self.add_val_to_arg( + arg, + &RawOsStr::new(default), + matcher, + ty, + false, + trailing_values, + ); + } + return; + } + } + } + } else { + debug!("Parser::add_value: doesn't have conditional defaults"); + } + + fn process_default_vals(arg: &Arg<'_>, default_vals: &[&OsStr]) -> Vec<OsString> { + if let Some(delim) = arg.val_delim { + let mut vals = vec![]; + for val in default_vals { + let val = RawOsStr::new(val); + for val in val.split(delim) { + vals.push(val.to_os_str().into_owned()); + } + } + vals + } else { + default_vals.iter().map(OsString::from).collect() + } + } + + if !arg.default_vals.is_empty() { + debug!("Parser::add_value:iter:{}: has default vals", arg.name); + if matcher.get(&arg.id).is_some() { + debug!("Parser::add_value:iter:{}: was used", arg.name); + // do nothing + } else { + debug!("Parser::add_value:iter:{}: wasn't used", arg.name); + + self.add_multiple_vals_to_arg( + arg, + process_default_vals(arg, &arg.default_vals).into_iter(), + matcher, + ty, + false, + ); + } + } else { + debug!( + "Parser::add_value:iter:{}: doesn't have default vals", + arg.name + ); + + // do nothing + } + + if !arg.default_missing_vals.is_empty() { + debug!( + "Parser::add_value:iter:{}: has default missing vals", + arg.name + ); + match matcher.get(&arg.id) { + Some(ma) if ma.all_val_groups_empty() => { + debug!( + "Parser::add_value:iter:{}: has no user defined vals", + arg.name + ); + self.add_multiple_vals_to_arg( + arg, + process_default_vals(arg, &arg.default_missing_vals).into_iter(), + matcher, + ty, + false, + ); + } + None => { + debug!("Parser::add_value:iter:{}: wasn't used", arg.name); + // do nothing + } + _ => { + debug!("Parser::add_value:iter:{}: has user defined vals", arg.name); + // do nothing + } + } + } else { + debug!( + "Parser::add_value:iter:{}: doesn't have default missing vals", + arg.name + ); + + // do nothing + } + } + + #[cfg(feature = "env")] + pub(crate) fn add_env( + &mut self, + matcher: &mut ArgMatcher, + trailing_values: bool, + ) -> ClapResult<()> { + use crate::util::str_to_bool; + + self.cmd.get_arguments().try_for_each(|a| { + // Use env only if the arg was absent among command line args, + // early return if this is not the case. + if matcher + .get(&a.id) + .map_or(false, |a| a.get_occurrences() != 0) + { + debug!("Parser::add_env: Skipping existing arg `{}`", a); + return Ok(()); + } + + debug!("Parser::add_env: Checking arg `{}`", a); + if let Some((_, Some(ref val))) = a.env { + let val = RawOsStr::new(val); + + if a.is_takes_value_set() { + debug!( + "Parser::add_env: Found an opt with value={:?}, trailing={:?}", + val, trailing_values + ); + self.add_val_to_arg( + a, + &val, + matcher, + ValueSource::EnvVariable, + false, + trailing_values, + ); + return Ok(()); + } + + debug!("Parser::add_env: Checking for help and version"); + // Early return on `HelpFlag` or `VersionFlag`. + match self.check_for_help_and_version_str(&val) { + Some(ParseResult::HelpFlag) => { + return Err(self.help_err(true, Stream::Stdout)); + } + Some(ParseResult::VersionFlag) => { + return Err(self.version_err(true)); + } + _ => (), + } + + debug!("Parser::add_env: Found a flag with value `{:?}`", val); + let predicate = str_to_bool(val.to_str_lossy()); + debug!("Parser::add_env: Found boolean literal `{}`", predicate); + if predicate { + matcher.add_index_to(&a.id, self.cur_idx.get(), ValueSource::EnvVariable); + } + } + + Ok(()) + }) + } + + /// Increase occurrence of specific argument and the grouped arg it's in. + fn inc_occurrence_of_arg(&self, matcher: &mut ArgMatcher, arg: &Arg<'help>) { + // With each new occurrence, remove overrides from prior occurrences + self.remove_overrides(arg, matcher); + + matcher.inc_occurrence_of_arg(arg); + // Increment or create the group "args" + for group in self.cmd.groups_for_arg(&arg.id) { + matcher.inc_occurrence_of_group(&group); + } + } +} + +// Error, Help, and Version Methods +impl<'help, 'cmd> Parser<'help, 'cmd> { + /// Is only used for the long flag(which is the only one needs fuzzy searching) + fn did_you_mean_error( + &mut self, + arg: &str, + matcher: &mut ArgMatcher, + remaining_args: &[&str], + ) -> ClapError { + debug!("Parser::did_you_mean_error: arg={}", arg); + // Didn't match a flag or option + let longs = self + .cmd + .get_keymap() + .keys() + .filter_map(|x| match x { + KeyType::Long(l) => Some(l.to_string_lossy().into_owned()), + _ => None, + }) + .collect::<Vec<_>>(); + debug!("Parser::did_you_mean_error: longs={:?}", longs); + + let did_you_mean = suggestions::did_you_mean_flag( + arg, + remaining_args, + longs.iter().map(|x| &x[..]), + self.cmd.get_subcommands_mut(), + ); + + // Add the arg to the matches to build a proper usage string + if let Some((name, _)) = did_you_mean.as_ref() { + if let Some(opt) = self.cmd.get_keymap().get(&name.as_ref()) { + self.inc_occurrence_of_arg(matcher, opt); + } + } + + let required = self.cmd.required_graph(); + let used: Vec<Id> = matcher + .arg_names() + .filter(|n| self.cmd.find(n).map_or(true, |a| !a.is_hide_set())) + .cloned() + .collect(); + + ClapError::unknown_argument( + self.cmd, + format!("--{}", arg), + did_you_mean, + Usage::new(self.cmd) + .required(&required) + .create_usage_with_title(&*used), + ) + } + + fn help_err(&self, use_long: bool, stream: Stream) -> ClapError { + match self.cmd.write_help_err(use_long, stream) { + Ok(c) => ClapError::display_help(self.cmd, c), + Err(e) => e, + } + } + + fn version_err(&self, use_long: bool) -> ClapError { + debug!("Parser::version_err"); + + let msg = self.cmd._render_version(use_long); + let mut c = Colorizer::new(Stream::Stdout, self.cmd.color_help()); + c.none(msg); + ClapError::display_version(self.cmd, c) + } +} + +// Query Methods +impl<'help, 'cmd> Parser<'help, 'cmd> { + pub(crate) fn is_set(&self, s: AS) -> bool { + self.cmd.is_set(s) + } +} + +#[derive(Debug)] +pub(crate) enum ParseState { + ValuesDone, + Opt(Id), + Pos(Id), +} + +/// Recoverable Parsing results. +#[derive(Debug, PartialEq, Clone)] +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, + /// This is a Help flag. + HelpFlag, + /// This is a version flag. + VersionFlag, +} diff --git a/third_party/rust/clap/src/parse/validator.rs b/third_party/rust/clap/src/parse/validator.rs new file mode 100644 index 0000000000..2e2766f651 --- /dev/null +++ b/third_party/rust/clap/src/parse/validator.rs @@ -0,0 +1,685 @@ +// Internal +use crate::build::{AppSettings, Arg, ArgPredicate, Command, PossibleValue}; +use crate::error::{Error, Result as ClapResult}; +use crate::output::fmt::Stream; +use crate::output::Usage; +use crate::parse::{ArgMatcher, MatchedArg, ParseState}; +use crate::util::ChildGraph; +use crate::util::Id; +use crate::{INTERNAL_ERROR_MSG, INVALID_UTF8}; + +pub(crate) struct Validator<'help, 'cmd> { + cmd: &'cmd Command<'help>, + required: ChildGraph<Id>, +} + +impl<'help, 'cmd> Validator<'help, 'cmd> { + pub(crate) fn new(cmd: &'cmd Command<'help>) -> Self { + let required = cmd.required_graph(); + Validator { cmd, required } + } + + pub(crate) fn validate( + &mut self, + parse_state: ParseState, + matcher: &mut ArgMatcher, + ) -> ClapResult<()> { + debug!("Validator::validate"); + let mut conflicts = Conflicts::new(); + let has_subcmd = matcher.subcommand_name().is_some(); + + if let ParseState::Opt(a) = parse_state { + debug!("Validator::validate: needs_val_of={:?}", a); + + let o = &self.cmd[&a]; + let should_err = if let Some(v) = matcher.args.get(&o.id) { + v.all_val_groups_empty() && !(o.min_vals.is_some() && o.min_vals.unwrap() == 0) + } else { + true + }; + if should_err { + return Err(Error::empty_value( + self.cmd, + &o.possible_vals + .iter() + .filter(|pv| !pv.is_hide_set()) + .map(PossibleValue::get_name) + .collect::<Vec<_>>(), + o, + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + } + + if !has_subcmd && self.cmd.is_arg_required_else_help_set() { + let num_user_values = matcher + .arg_names() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + .count(); + if num_user_values == 0 { + let message = self.cmd.write_help_err(false, Stream::Stderr)?; + return Err(Error::display_help_error(self.cmd, message)); + } + } + #[allow(deprecated)] + if !has_subcmd && self.cmd.is_subcommand_required_set() { + let bn = self + .cmd + .get_bin_name() + .unwrap_or_else(|| self.cmd.get_name()); + return Err(Error::missing_subcommand( + self.cmd, + bn.to_string(), + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } else if !has_subcmd && self.cmd.is_set(AppSettings::SubcommandRequiredElseHelp) { + debug!("Validator::new::get_matches_with: SubcommandRequiredElseHelp=true"); + let message = self.cmd.write_help_err(false, Stream::Stderr)?; + return Err(Error::display_help_error(self.cmd, message)); + } + + self.validate_conflicts(matcher, &mut conflicts)?; + if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) { + self.validate_required(matcher, &mut conflicts)?; + } + self.validate_matched_args(matcher)?; + + Ok(()) + } + + fn validate_arg_values( + &self, + arg: &Arg, + ma: &MatchedArg, + matcher: &ArgMatcher, + ) -> ClapResult<()> { + debug!("Validator::validate_arg_values: arg={:?}", arg.name); + for val in ma.vals_flatten() { + if !arg.is_allow_invalid_utf8_set() && val.to_str().is_none() { + debug!( + "Validator::validate_arg_values: invalid UTF-8 found in val {:?}", + val + ); + return Err(Error::invalid_utf8( + self.cmd, + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + if !arg.possible_vals.is_empty() { + debug!( + "Validator::validate_arg_values: possible_vals={:?}", + arg.possible_vals + ); + let val_str = val.to_string_lossy(); + let ok = arg + .possible_vals + .iter() + .any(|pv| pv.matches(&val_str, arg.is_ignore_case_set())); + if !ok { + let used: Vec<Id> = matcher + .arg_names() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + .filter(|&n| self.cmd.find(n).map_or(true, |a| !a.is_hide_set())) + .cloned() + .collect(); + return Err(Error::invalid_value( + self.cmd, + val_str.into_owned(), + &arg.possible_vals + .iter() + .filter(|pv| !pv.is_hide_set()) + .map(PossibleValue::get_name) + .collect::<Vec<_>>(), + arg, + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&used), + )); + } + } + if arg.is_forbid_empty_values_set() && val.is_empty() && matcher.contains(&arg.id) { + debug!("Validator::validate_arg_values: illegal empty val found"); + return Err(Error::empty_value( + self.cmd, + &arg.possible_vals + .iter() + .filter(|pv| !pv.is_hide_set()) + .map(PossibleValue::get_name) + .collect::<Vec<_>>(), + arg, + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + + if let Some(ref vtor) = arg.validator { + debug!("Validator::validate_arg_values: checking validator..."); + let mut vtor = vtor.lock().unwrap(); + if let Err(e) = vtor(&*val.to_string_lossy()) { + debug!("error"); + return Err(Error::value_validation( + arg.to_string(), + val.to_string_lossy().into_owned(), + e, + ) + .with_cmd(self.cmd)); + } else { + debug!("good"); + } + } + if let Some(ref vtor) = arg.validator_os { + debug!("Validator::validate_arg_values: checking validator_os..."); + let mut vtor = vtor.lock().unwrap(); + if let Err(e) = vtor(val) { + debug!("error"); + return Err(Error::value_validation( + arg.to_string(), + val.to_string_lossy().into(), + e, + ) + .with_cmd(self.cmd)); + } else { + debug!("good"); + } + } + } + Ok(()) + } + + fn validate_conflicts( + &mut self, + matcher: &ArgMatcher, + conflicts: &mut Conflicts, + ) -> ClapResult<()> { + debug!("Validator::validate_conflicts"); + + self.validate_exclusive(matcher)?; + + for arg_id in matcher + .arg_names() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + .filter(|arg_id| self.cmd.find(arg_id).is_some()) + { + debug!("Validator::validate_conflicts::iter: id={:?}", arg_id); + let conflicts = conflicts.gather_conflicts(self.cmd, matcher, arg_id); + self.build_conflict_err(arg_id, &conflicts, matcher)?; + } + + Ok(()) + } + + fn validate_exclusive(&self, matcher: &ArgMatcher) -> ClapResult<()> { + debug!("Validator::validate_exclusive"); + // Not bothering to filter for `check_explicit` since defaults shouldn't play into this + let args_count = matcher.arg_names().count(); + if args_count <= 1 { + // Nothing present to conflict with + return Ok(()); + } + + matcher + .arg_names() + .filter_map(|name| { + debug!("Validator::validate_exclusive:iter:{:?}", name); + self.cmd + .find(name) + // Find `arg`s which are exclusive but also appear with other args. + .filter(|&arg| arg.is_exclusive_set() && args_count > 1) + }) + // Throw an error for the first conflict found. + .try_for_each(|arg| { + Err(Error::argument_conflict( + self.cmd, + arg, + Vec::new(), + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )) + }) + } + + fn build_conflict_err( + &self, + name: &Id, + conflict_ids: &[Id], + matcher: &ArgMatcher, + ) -> ClapResult<()> { + if conflict_ids.is_empty() { + return Ok(()); + } + + debug!("Validator::build_conflict_err: name={:?}", name); + let mut seen = std::collections::HashSet::new(); + let conflicts = conflict_ids + .iter() + .flat_map(|c_id| { + if self.cmd.find_group(c_id).is_some() { + self.cmd.unroll_args_in_group(c_id) + } else { + vec![c_id.clone()] + } + }) + .filter_map(|c_id| { + seen.insert(c_id.clone()).then(|| { + let c_arg = self.cmd.find(&c_id).expect(INTERNAL_ERROR_MSG); + c_arg.to_string() + }) + }) + .collect(); + + let former_arg = self.cmd.find(name).expect(INTERNAL_ERROR_MSG); + let usg = self.build_conflict_err_usage(matcher, conflict_ids); + Err(Error::argument_conflict( + self.cmd, former_arg, conflicts, usg, + )) + } + + fn build_conflict_err_usage(&self, matcher: &ArgMatcher, conflicting_keys: &[Id]) -> String { + let used_filtered: Vec<Id> = matcher + .arg_names() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + .filter(|n| { + // Filter out the args we don't want to specify. + self.cmd.find(n).map_or(true, |a| !a.is_hide_set()) + }) + .filter(|key| !conflicting_keys.contains(key)) + .cloned() + .collect(); + let required: Vec<Id> = used_filtered + .iter() + .filter_map(|key| self.cmd.find(key)) + .flat_map(|arg| arg.requires.iter().map(|item| &item.1)) + .filter(|key| !used_filtered.contains(key) && !conflicting_keys.contains(key)) + .chain(used_filtered.iter()) + .cloned() + .collect(); + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&required) + } + + fn gather_requires(&mut self, matcher: &ArgMatcher) { + debug!("Validator::gather_requires"); + for name in matcher + .arg_names() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + { + debug!("Validator::gather_requires:iter:{:?}", name); + if let Some(arg) = self.cmd.find(name) { + let is_relevant = |(val, req_arg): &(ArgPredicate<'_>, Id)| -> Option<Id> { + let required = matcher.check_explicit(&arg.id, *val); + required.then(|| req_arg.clone()) + }; + + for req in self.cmd.unroll_arg_requires(is_relevant, &arg.id) { + self.required.insert(req); + } + } else if let Some(g) = self.cmd.find_group(name) { + debug!("Validator::gather_requires:iter:{:?}:group", name); + for r in &g.requires { + self.required.insert(r.clone()); + } + } + } + } + + fn validate_matched_args(&self, matcher: &ArgMatcher) -> ClapResult<()> { + debug!("Validator::validate_matched_args"); + matcher.iter().try_for_each(|(name, ma)| { + debug!( + "Validator::validate_matched_args:iter:{:?}: vals={:#?}", + name, + ma.vals_flatten() + ); + if let Some(arg) = self.cmd.find(name) { + self.validate_arg_num_vals(arg, ma)?; + self.validate_arg_values(arg, ma, matcher)?; + self.validate_arg_num_occurs(arg, ma)?; + } + Ok(()) + }) + } + + fn validate_arg_num_occurs(&self, a: &Arg, ma: &MatchedArg) -> ClapResult<()> { + debug!( + "Validator::validate_arg_num_occurs: {:?}={}", + a.name, + ma.get_occurrences() + ); + // Occurrence of positional argument equals to number of values rather + // than number of grouped values. + if ma.get_occurrences() > 1 && !a.is_multiple_occurrences_set() && !a.is_positional() { + // Not the first time, and we don't allow multiples + return Err(Error::unexpected_multiple_usage( + self.cmd, + a, + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + if let Some(max_occurs) = a.max_occurs { + debug!( + "Validator::validate_arg_num_occurs: max_occurs set...{}", + max_occurs + ); + let occurs = ma.get_occurrences() as usize; + if occurs > max_occurs { + return Err(Error::too_many_occurrences( + self.cmd, + a, + max_occurs, + occurs, + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + } + + Ok(()) + } + + fn validate_arg_num_vals(&self, a: &Arg, ma: &MatchedArg) -> ClapResult<()> { + debug!("Validator::validate_arg_num_vals"); + if let Some(num) = a.num_vals { + let total_num = ma.num_vals(); + debug!("Validator::validate_arg_num_vals: num_vals set...{}", num); + let should_err = if a.is_multiple_occurrences_set() { + total_num % num != 0 + } else { + num != total_num + }; + if should_err { + debug!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues"); + return Err(Error::wrong_number_of_values( + self.cmd, + a, + num, + if a.is_multiple_occurrences_set() { + total_num % num + } else { + total_num + }, + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + } + if let Some(num) = a.max_vals { + debug!("Validator::validate_arg_num_vals: max_vals set...{}", num); + if ma.num_vals() > num { + debug!("Validator::validate_arg_num_vals: Sending error TooManyValues"); + return Err(Error::too_many_values( + self.cmd, + ma.vals_flatten() + .last() + .expect(INTERNAL_ERROR_MSG) + .to_str() + .expect(INVALID_UTF8) + .to_string(), + a.to_string(), + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + } + let min_vals_zero = if let Some(num) = a.min_vals { + debug!("Validator::validate_arg_num_vals: min_vals set: {}", num); + if ma.num_vals() < num && num != 0 { + debug!("Validator::validate_arg_num_vals: Sending error TooFewValues"); + return Err(Error::too_few_values( + self.cmd, + a, + num, + ma.num_vals(), + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + num == 0 + } else { + false + }; + // Issue 665 (https://github.com/clap-rs/clap/issues/665) + // Issue 1105 (https://github.com/clap-rs/clap/issues/1105) + if a.is_takes_value_set() && !min_vals_zero && ma.all_val_groups_empty() { + return Err(Error::empty_value( + self.cmd, + &a.possible_vals + .iter() + .filter(|pv| !pv.is_hide_set()) + .map(PossibleValue::get_name) + .collect::<Vec<_>>(), + a, + Usage::new(self.cmd) + .required(&self.required) + .create_usage_with_title(&[]), + )); + } + Ok(()) + } + + fn validate_required( + &mut self, + matcher: &ArgMatcher, + conflicts: &mut Conflicts, + ) -> ClapResult<()> { + debug!("Validator::validate_required: required={:?}", self.required); + self.gather_requires(matcher); + + let is_exclusive_present = matcher.arg_names().any(|name| { + self.cmd + .find(name) + .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.contains(r)) { + debug!("Validator::validate_required:iter:aog={:?}", arg_or_group); + if let Some(arg) = self.cmd.find(arg_or_group) { + debug!("Validator::validate_required:iter: This is an arg"); + if !is_exclusive_present && !self.is_missing_required_ok(arg, matcher, conflicts) { + return self.missing_required_error(matcher, vec![]); + } + } else if let Some(group) = self.cmd.find_group(arg_or_group) { + debug!("Validator::validate_required:iter: This is a group"); + if !self + .cmd + .unroll_args_in_group(&group.id) + .iter() + .any(|a| matcher.contains(a)) + { + return self.missing_required_error(matcher, vec![]); + } + } + } + + // Validate the conditionally required args + for a in self.cmd.get_arguments() { + for (other, val) in &a.r_ifs { + if matcher.check_explicit(other, ArgPredicate::Equals(std::ffi::OsStr::new(*val))) + && !matcher.contains(&a.id) + { + return self.missing_required_error(matcher, vec![a.id.clone()]); + } + } + + let match_all = a.r_ifs_all.iter().all(|(other, val)| { + matcher.check_explicit(other, ArgPredicate::Equals(std::ffi::OsStr::new(*val))) + }); + if match_all && !a.r_ifs_all.is_empty() && !matcher.contains(&a.id) { + return self.missing_required_error(matcher, vec![a.id.clone()]); + } + } + + self.validate_required_unless(matcher)?; + + Ok(()) + } + + fn is_missing_required_ok( + &self, + a: &Arg<'help>, + matcher: &ArgMatcher, + conflicts: &mut Conflicts, + ) -> bool { + debug!("Validator::is_missing_required_ok: {}", a.name); + let conflicts = conflicts.gather_conflicts(self.cmd, matcher, &a.id); + !conflicts.is_empty() + } + + fn validate_required_unless(&self, matcher: &ArgMatcher) -> ClapResult<()> { + debug!("Validator::validate_required_unless"); + let failed_args: Vec<_> = self + .cmd + .get_arguments() + .filter(|&a| { + (!a.r_unless.is_empty() || !a.r_unless_all.is_empty()) + && !matcher.contains(&a.id) + && self.fails_arg_required_unless(a, matcher) + }) + .map(|a| a.id.clone()) + .collect(); + if failed_args.is_empty() { + Ok(()) + } else { + self.missing_required_error(matcher, failed_args) + } + } + + // Failing a required unless means, the arg's "unless" wasn't present, and neither were they + fn fails_arg_required_unless(&self, a: &Arg<'help>, matcher: &ArgMatcher) -> bool { + debug!("Validator::fails_arg_required_unless: a={:?}", a.name); + let exists = |id| matcher.check_explicit(id, ArgPredicate::IsPresent); + + (a.r_unless_all.is_empty() || !a.r_unless_all.iter().all(exists)) + && !a.r_unless.iter().any(exists) + } + + // `incl`: an arg to include in the error even if not used + fn missing_required_error(&self, matcher: &ArgMatcher, incl: Vec<Id>) -> ClapResult<()> { + debug!("Validator::missing_required_error; incl={:?}", incl); + debug!( + "Validator::missing_required_error: reqs={:?}", + self.required + ); + + let usg = Usage::new(self.cmd).required(&self.required); + + let req_args = usg + .get_required_usage_from(&incl, Some(matcher), true) + .into_iter() + .collect::<Vec<_>>(); + + debug!( + "Validator::missing_required_error: req_args={:#?}", + req_args + ); + + let used: Vec<Id> = matcher + .arg_names() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + .filter(|n| { + // Filter out the args we don't want to specify. + self.cmd.find(n).map_or(true, |a| !a.is_hide_set()) + }) + .cloned() + .chain(incl) + .collect(); + + Err(Error::missing_required_argument( + self.cmd, + req_args, + usg.create_usage_with_title(&used), + )) + } +} + +#[derive(Default, Clone, Debug)] +struct Conflicts { + potential: std::collections::HashMap<Id, Vec<Id>>, +} + +impl Conflicts { + fn new() -> Self { + Self::default() + } + + fn gather_conflicts(&mut self, cmd: &Command, matcher: &ArgMatcher, arg_id: &Id) -> Vec<Id> { + debug!("Conflicts::gather_conflicts: arg={:?}", arg_id); + let mut conflicts = Vec::new(); + for other_arg_id in matcher + .arg_names() + .filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent)) + { + if arg_id == other_arg_id { + continue; + } + + if self + .gather_direct_conflicts(cmd, arg_id) + .contains(other_arg_id) + { + conflicts.push(other_arg_id.clone()); + } + if self + .gather_direct_conflicts(cmd, other_arg_id) + .contains(arg_id) + { + conflicts.push(other_arg_id.clone()); + } + } + debug!("Conflicts::gather_conflicts: conflicts={:?}", conflicts); + conflicts + } + + fn gather_direct_conflicts(&mut self, cmd: &Command, arg_id: &Id) -> &[Id] { + self.potential.entry(arg_id.clone()).or_insert_with(|| { + let conf = if let Some(arg) = cmd.find(arg_id) { + let mut conf = arg.blacklist.clone(); + for group_id in cmd.groups_for_arg(arg_id) { + let group = cmd.find_group(&group_id).expect(INTERNAL_ERROR_MSG); + conf.extend(group.conflicts.iter().cloned()); + if !group.multiple { + for member_id in &group.args { + if member_id != arg_id { + conf.push(member_id.clone()); + } + } + } + } + + // Overrides are implicitly conflicts + conf.extend(arg.overrides.iter().cloned()); + + conf + } else if let Some(group) = cmd.find_group(arg_id) { + group.conflicts.clone() + } else { + debug_assert!(false, "id={:?} is unknown", arg_id); + Vec::new() + }; + debug!( + "Conflicts::gather_direct_conflicts id={:?}, conflicts={:?}", + arg_id, conf + ); + conf + }) + } +} diff --git a/third_party/rust/clap/src/util/color.rs b/third_party/rust/clap/src/util/color.rs new file mode 100644 index 0000000000..15c9901a07 --- /dev/null +++ b/third_party/rust/clap/src/util/color.rs @@ -0,0 +1,62 @@ +/// Represents the color preferences for program output +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ColorChoice { + /// Enables colored output only when the output is going to a terminal or TTY. + /// + /// **NOTE:** This is the default behavior of `clap`. + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). + /// + /// # Examples + /// + #[cfg_attr(not(feature = "color"), doc = " ```ignore")] + #[cfg_attr(feature = "color", doc = " ```no_run")] + /// # use clap::{Command, ColorChoice}; + /// Command::new("myprog") + /// .color(ColorChoice::Auto) + /// .get_matches(); + /// ``` + Auto, + + /// Enables colored output regardless of whether or not the output is going to a terminal/TTY. + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). + /// + /// # Examples + /// + #[cfg_attr(not(feature = "color"), doc = " ```ignore")] + #[cfg_attr(feature = "color", doc = " ```no_run")] + /// # use clap::{Command, ColorChoice}; + /// Command::new("myprog") + /// .color(ColorChoice::Always) + /// .get_matches(); + /// ``` + Always, + + /// Disables colored output no matter if the output is going to a terminal/TTY, or not. + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms) + /// + /// # Examples + /// + #[cfg_attr(not(feature = "color"), doc = " ```ignore")] + #[cfg_attr(feature = "color", doc = " ```no_run")] + /// # use clap::{Command, ColorChoice}; + /// Command::new("myprog") + /// .color(ColorChoice::Never) + /// .get_matches(); + /// ``` + Never, +} + +impl Default for ColorChoice { + fn default() -> Self { + Self::Auto + } +} diff --git a/third_party/rust/clap/src/util/fnv.rs b/third_party/rust/clap/src/util/fnv.rs new file mode 100644 index 0000000000..4602300a49 --- /dev/null +++ b/third_party/rust/clap/src/util/fnv.rs @@ -0,0 +1,46 @@ +use std::{ + fmt::Display, + hash::{Hash, Hasher}, +}; + +const MAGIC_INIT: u64 = 0x811C_9DC5; + +// TODO: Docs +pub trait Key: Hash + Display { + fn key(&self) -> u64; +} + +impl<T> Key for T +where + T: Hash + Display, +{ + fn key(&self) -> u64 { + let mut hasher = FnvHasher::new(); + self.hash(&mut hasher); + hasher.finish() + } +} + +pub(crate) struct FnvHasher(u64); + +impl FnvHasher { + pub(crate) fn new() -> Self { + FnvHasher(MAGIC_INIT) + } +} + +impl Hasher for FnvHasher { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + let FnvHasher(mut hash) = *self; + + for byte in bytes.iter() { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x0100_0000_01b3); + } + + *self = FnvHasher(hash); + } +} diff --git a/third_party/rust/clap/src/util/graph.rs b/third_party/rust/clap/src/util/graph.rs new file mode 100644 index 0000000000..d646400b01 --- /dev/null +++ b/third_party/rust/clap/src/util/graph.rs @@ -0,0 +1,49 @@ +#[derive(Debug)] +struct Child<T> { + id: T, + children: Vec<usize>, +} + +impl<T> Child<T> { + fn new(id: T) -> Self { + Child { + id, + children: vec![], + } + } +} + +#[derive(Debug)] +pub(crate) struct ChildGraph<T>(Vec<Child<T>>); + +impl<T> ChildGraph<T> +where + T: Sized + PartialEq + Clone, +{ + pub(crate) fn with_capacity(s: usize) -> Self { + ChildGraph(Vec::with_capacity(s)) + } + + pub(crate) fn insert(&mut self, req: T) -> usize { + self.0.iter().position(|e| e.id == req).unwrap_or_else(|| { + let idx = self.0.len(); + self.0.push(Child::new(req)); + idx + }) + } + + pub(crate) fn insert_child(&mut self, parent: usize, child: T) -> usize { + let c_idx = self.0.len(); + self.0.push(Child::new(child)); + self.0[parent].children.push(c_idx); + c_idx + } + + pub(crate) fn iter(&self) -> impl Iterator<Item = &T> { + self.0.iter().map(|r| &r.id) + } + + pub(crate) fn contains(&self, req: &T) -> bool { + self.0.iter().any(|r| r.id == *req) + } +} diff --git a/third_party/rust/clap/src/util/id.rs b/third_party/rust/clap/src/util/id.rs new file mode 100644 index 0000000000..63a7e003ee --- /dev/null +++ b/third_party/rust/clap/src/util/id.rs @@ -0,0 +1,92 @@ +use crate::util::fnv::Key; + +use std::{ + fmt::{Debug, Formatter, Result}, + hash::{Hash, Hasher}, + ops::Deref, +}; + +#[derive(Clone, Eq, Default)] +#[cfg_attr(not(debug_assertions), repr(transparent))] +pub(crate) struct Id { + #[cfg(debug_assertions)] + name: String, + id: u64, +} + +macro_rules! precomputed_hashes { + ($($fn_name:ident, $const:expr, $name:expr;)*) => { + impl Id { + $( + pub(crate) fn $fn_name() -> Self { + Id { + #[cfg(debug_assertions)] + name: $name.into(), + id: $const, + } + } + )* + } + }; +} + +// precompute some common values +precomputed_hashes! { + empty_hash, 0x1C9D_3ADB_639F_298E, ""; + help_hash, 0x5963_6393_CFFB_FE5F, "help"; + version_hash, 0x30FF_0B7C_4D07_9478, "version"; +} + +impl Id { + pub(crate) fn from_ref<T: Key>(val: T) -> Self { + Id { + #[cfg(debug_assertions)] + name: val.to_string(), + id: val.key(), + } + } +} + +impl Debug for Id { + fn fmt(&self, f: &mut Formatter) -> Result { + #[cfg(debug_assertions)] + write!(f, "{}", self.name)?; + #[cfg(not(debug_assertions))] + write!(f, "[hash: {:X}]", self.id)?; + + Ok(()) + } +} + +impl Deref for Id { + type Target = u64; + + fn deref(&self) -> &Self::Target { + &self.id + } +} + +impl<T: Key> From<T> for Id { + fn from(val: T) -> Self { + Id { + #[cfg(debug_assertions)] + name: val.to_string(), + id: val.key(), + } + } +} + +impl Hash for Id { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.id.hash(state) + } +} + +impl PartialEq for Id { + fn eq(&self, other: &Id) -> bool { + self.id == other.id + } +} diff --git a/third_party/rust/clap/src/util/mod.rs b/third_party/rust/clap/src/util/mod.rs new file mode 100644 index 0000000000..ed35765ff6 --- /dev/null +++ b/third_party/rust/clap/src/util/mod.rs @@ -0,0 +1,40 @@ +#![allow(clippy::single_component_path_imports)] + +mod fnv; +mod graph; +mod id; +#[cfg(feature = "env")] +mod str_to_bool; + +pub use self::fnv::Key; + +#[cfg(feature = "env")] +pub(crate) use self::str_to_bool::str_to_bool; +pub(crate) use self::{graph::ChildGraph, id::Id}; + +pub(crate) mod color; + +pub(crate) const SUCCESS_CODE: i32 = 0; +// While sysexists.h defines EX_USAGE as 64, this doesn't seem to be used much in practice but +// instead 2 seems to be frequently used. +// Examples +// - GNU `ls` returns 2 +// - Python's `argparse` returns 2 +pub(crate) const USAGE_CODE: i32 = 2; + +pub(crate) fn safe_exit(code: i32) -> ! { + use std::io::Write; + + let _ = std::io::stdout().lock().flush(); + let _ = std::io::stderr().lock().flush(); + + std::process::exit(code) +} + +#[cfg(not(feature = "unicode"))] +pub(crate) fn eq_ignore_case(left: &str, right: &str) -> bool { + left.eq_ignore_ascii_case(right) +} + +#[cfg(feature = "unicode")] +pub(crate) use unicase::eq as eq_ignore_case; diff --git a/third_party/rust/clap/src/util/str_to_bool.rs b/third_party/rust/clap/src/util/str_to_bool.rs new file mode 100644 index 0000000000..58e2efa63d --- /dev/null +++ b/third_party/rust/clap/src/util/str_to_bool.rs @@ -0,0 +1,15 @@ +/// 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`. +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>) -> bool { + let pat: &str = &val.as_ref().to_lowercase(); + !FALSE_LITERALS.contains(&pat) +} |