clap_builder-4.5.48/.cargo_vcs_info.json0000644000000001520000000000100135610ustar { "git": { "sha1": "8e3d03639756241aa2b7dd624a7f5852bef76f31" }, "path_in_vcs": "clap_builder" }clap_builder-4.5.48/Cargo.lock0000644000000301330000000000100115360ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "addr2line" version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" dependencies = [ "gimli", ] [[package]] name = "adler" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "anstream" version = "0.6.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", "is_terminal_polyfill", "utf8parse", ] [[package]] name = "anstyle" version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" [[package]] name = "anstyle-parse" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad186efb764318d35165f1758e7dcef3b10628e26d41a44bc5550652e6804391" dependencies = [ "windows-sys 0.52.0", ] [[package]] name = "anstyle-wincon" version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19" dependencies = [ "anstyle", "windows-sys 0.52.0", ] [[package]] name = "backtrace" version = "0.3.73" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a" dependencies = [ "addr2line", "cc", "cfg-if", "libc", "miniz_oxide", "object", "rustc-demangle", ] [[package]] name = "bitflags" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" [[package]] name = "cc" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaff6f8ce506b9773fa786672d63fc7a191ffea1be33f72bbd4aeacefca9ffc8" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "clap_builder" version = "4.5.48" dependencies = [ "anstream", "anstyle", "backtrace", "clap_lex", "color-print", "static_assertions", "strsim", "terminal_size", "unic-emoji-char", "unicase", "unicode-width", ] [[package]] name = "clap_lex" version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" [[package]] name = "color-print" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3aa954171903797d5623e047d9ab69d91b493657917bdfb8c2c80ecaf9cdb6f4" dependencies = [ "color-print-proc-macro", ] [[package]] name = "color-print-proc-macro" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "692186b5ebe54007e45a59aea47ece9eb4108e141326c304cdc91699a7118a22" dependencies = [ "nom", "proc-macro2", "quote", "syn", ] [[package]] name = "colorchoice" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" [[package]] name = "errno" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" dependencies = [ "libc", "windows-sys 0.52.0", ] [[package]] name = "gimli" version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" [[package]] name = "is_terminal_polyfill" version = "1.70.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800" [[package]] name = "libc" version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "linux-raw-sys" version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "minimal-lexical" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" dependencies = [ "adler", ] [[package]] name = "nom" version = "7.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" dependencies = [ "memchr", "minimal-lexical", ] [[package]] name = "object" version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "081b846d1d56ddfc18fdf1a922e4f6e07a11768ea1b92dec44e42b72712ccfce" dependencies = [ "memchr", ] [[package]] name = "proc-macro2" version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.39" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1f1914ce909e1658d9907913b4b91947430c7d9be598b15a1912935b8c04801" dependencies = [ "proc-macro2", ] [[package]] name = "rustc-demangle" version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" [[package]] name = "rustix" version = "0.38.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys 0.52.0", ] [[package]] name = "static_assertions" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "syn" version = "2.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e02e925281e18ffd9d640e234264753c43edc62d64b2d4cf898f1bc5e75f3fc2" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "terminal_size" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f599bd7ca042cfdf8f4512b277c02ba102247820f9d9d4a9f521f496751a6ef" dependencies = [ "rustix", "windows-sys 0.59.0", ] [[package]] name = "unic-char-property" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" dependencies = [ "unic-char-range", ] [[package]] name = "unic-char-range" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" [[package]] name = "unic-common" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" [[package]] name = "unic-emoji-char" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b07221e68897210270a38bde4babb655869637af0f69407f96053a34f76494d" dependencies = [ "unic-char-property", "unic-char-range", "unic-ucd-version", ] [[package]] name = "unic-ucd-version" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" dependencies = [ "unic-common", ] [[package]] name = "unicase" version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89" dependencies = [ "version_check", ] [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-width" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" [[package]] name = "utf8parse" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "version_check" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets", ] [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" clap_builder-4.5.48/Cargo.toml0000644000000110640000000000100115630ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.74" name = "clap_builder" version = "4.5.48" build = false include = [ "build.rs", "src/**/*", "Cargo.toml", "LICENSE*", "README.md", "examples/**/*", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "A simple to use, efficient, and full-featured Command Line Argument Parser" readme = "README.md" keywords = [ "argument", "cli", "arg", "parser", "parse", ] categories = ["command-line-interface"] license = "MIT OR Apache-2.0" repository = "https://github.com/clap-rs/clap" [package.metadata.docs.rs] features = ["unstable-doc"] rustdoc-args = [ "--cfg", "docsrs", ] cargo-args = [ "-Zunstable-options", "-Zrustdoc-scrape-examples", ] [package.metadata.playground] features = ["unstable-doc"] [package.metadata.release] shared-version = true dependent-version = "upgrade" tag-name = "v{{version}}" [features] cargo = [] color = ["dep:anstream"] debug = ["dep:backtrace"] default = [ "std", "color", "help", "usage", "error-context", "suggestions", ] deprecated = [] env = [] error-context = [] help = [] std = ["anstyle/std"] string = [] suggestions = [ "dep:strsim", "error-context", ] unicode = [ "dep:unicode-width", "dep:unicase", ] unstable-doc = [ "cargo", "wrap_help", "env", "unicode", "string", "unstable-ext", ] unstable-ext = [] unstable-styles = ["color"] unstable-v5 = ["deprecated"] usage = [] wrap_help = [ "help", "dep:terminal_size", ] [lib] name = "clap_builder" path = "src/lib.rs" bench = false [dependencies.anstream] version = "0.6.7" optional = true [dependencies.anstyle] version = "1.0.8" [dependencies.backtrace] version = "0.3.73" optional = true [dependencies.clap_lex] version = "0.7.4" [dependencies.strsim] version = "0.11.0" optional = true [dependencies.terminal_size] version = "0.4.0" optional = true [dependencies.unicase] version = "2.6.0" optional = true [dependencies.unicode-width] version = "0.2.0" optional = true [dev-dependencies.color-print] version = "0.3.6" [dev-dependencies.static_assertions] version = "1.1.0" [dev-dependencies.unic-emoji-char] version = "0.9.0" [lints.clippy] assigning_clones = "allow" blocks_in_conditions = "allow" bool_assert_comparison = "allow" branches_sharing_code = "allow" checked_conversions = "warn" collapsible_else_if = "allow" create_dir = "warn" dbg_macro = "warn" debug_assert_with_mut_call = "warn" doc_markdown = "warn" empty_enum = "warn" enum_glob_use = "warn" expl_impl_clone_on_copy = "warn" explicit_deref_methods = "warn" explicit_into_iter_loop = "warn" fallible_impl_from = "warn" filter_map_next = "warn" flat_map_option = "warn" float_cmp_const = "warn" fn_params_excessive_bools = "warn" from_iter_instead_of_collect = "warn" if_same_then_else = "allow" implicit_clone = "warn" imprecise_flops = "warn" inconsistent_struct_constructor = "warn" inefficient_to_string = "warn" infinite_loop = "warn" invalid_upcast_comparisons = "warn" large_digit_groups = "warn" large_stack_arrays = "warn" large_types_passed_by_value = "warn" let_and_return = "allow" linkedlist = "warn" lossy_float_literal = "warn" macro_use_imports = "warn" mem_forget = "warn" multiple_bound_locations = "allow" mutex_integer = "warn" needless_continue = "allow" needless_for_each = "warn" negative_feature_names = "warn" path_buf_push_overwrite = "warn" ptr_as_ptr = "warn" rc_mutex = "warn" redundant_feature_names = "warn" ref_option_ref = "warn" rest_pat_in_fully_bound_structs = "warn" result_large_err = "allow" same_functions_in_if_condition = "warn" self_named_module_files = "warn" semicolon_if_nothing_returned = "warn" string_add_assign = "warn" string_lit_as_bytes = "warn" todo = "warn" trait_duplication_in_bounds = "warn" uninlined_format_args = "warn" verbose_file_reads = "warn" zero_sized_map_values = "warn" [lints.rust] unnameable_types = "allow" unreachable_pub = "warn" unsafe_op_in_unsafe_fn = "warn" unused_lifetimes = "warn" unused_macro_rules = "warn" unused_qualifications = "warn" [lints.rust.rust_2018_idioms] level = "warn" priority = -1 clap_builder-4.5.48/Cargo.toml.orig000064400000000000000000000043561046102023000152520ustar 00000000000000[package] name = "clap_builder" version = "4.5.48" description = "A simple to use, efficient, and full-featured Command Line Argument Parser" categories = ["command-line-interface"] keywords = [ "argument", "cli", "arg", "parser", "parse" ] repository.workspace = true license.workspace = true edition.workspace = true rust-version.workspace = true include.workspace = true [package.metadata.docs.rs] features = ["unstable-doc"] rustdoc-args = ["--cfg", "docsrs"] cargo-args = ["-Zunstable-options", "-Zrustdoc-scrape-examples"] [package.metadata.playground] features = ["unstable-doc"] [package.metadata.release] shared-version = true dependent-version = "upgrade" tag-name = "v{{version}}" [features] default = ["std", "color", "help", "usage", "error-context", "suggestions"] debug = ["dep:backtrace"] # Enables debug messages unstable-doc = ["cargo", "wrap_help", "env", "unicode", "string", "unstable-ext"] # for docs.rs # Used in default std = ["anstyle/std"] # support for no_std in a backwards-compatible way color = ["dep:anstream"] help = [] usage = [] error-context = [] suggestions = ["dep:strsim", "error-context"] # Optional deprecated = [] # Guided experience to prepare for next breaking release (at different stages of development, this may become default) cargo = [] # Disable if you're not using Cargo, enables Cargo-env-var-dependent macros wrap_help = ["help", "dep:terminal_size"] env = [] # Use environment variables during arg parsing unicode = ["dep:unicode-width", "dep:unicase"] # Support for unicode characters in arguments and help messages string = [] # Allow runtime generated strings # In-work features unstable-v5 = ["deprecated"] unstable-ext = [] unstable-styles = ["color"] # deprecated [lib] bench = false [dependencies] clap_lex = { path = "../clap_lex", version = "0.7.4" } unicase = { version = "2.6.0", optional = true } strsim = { version = "0.11.0", optional = true } anstream = { version = "0.6.7", optional = true } anstyle = "1.0.8" terminal_size = { version = "0.4.0", optional = true } backtrace = { version = "0.3.73", optional = true } unicode-width = { version = "0.2.0", optional = true } [dev-dependencies] static_assertions = "1.1.0" unic-emoji-char = "0.9.0" color-print = "0.3.6" [lints] workspace = true clap_builder-4.5.48/LICENSE-APACHE000064400000000000000000000261361046102023000143070ustar 00000000000000 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. clap_builder-4.5.48/LICENSE-MIT000064400000000000000000000020461046102023000140110ustar 00000000000000Copyright (c) Individual contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. clap_builder-4.5.48/README.md000064400000000000000000000014351046102023000136350ustar 00000000000000# `clap_builder` Builder implementation for clap. [docs.rs](https://docs.rs/clap) - [Derive Tutorial](https://docs.rs/clap/latest/clap/_derive/_tutorial/index.html) - [Derive Reference](https://docs.rs/clap/latest/clap/_derive/index.html) ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or ) * MIT license ([LICENSE-MIT](LICENSE-MIT) or ) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual-licensed as above, without any additional terms or conditions. See [CONTRIBUTING](CONTRIBUTING.md) for more details. clap_builder-4.5.48/src/builder/action.rs000064400000000000000000000363201046102023000164170ustar 00000000000000#[cfg(debug_assertions)] use crate::util::AnyValueId; use crate::builder::ValueRange; /// Behavior of arguments when they are encountered while parsing /// /// # Examples /// /// ```rust /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::Arg; /// let cmd = Command::new("mycmd") /// .arg( /// Arg::new("special-help") /// .short('?') /// .action(clap::ArgAction::Help) /// ); /// /// // Existing help still exists /// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); /// /// // New help available /// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); /// # } /// ``` #[derive(Clone, Debug)] #[non_exhaustive] #[allow(missing_copy_implementations)] // In the future, we may accept `Box` pub enum ArgAction { /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches] /// ///
/// /// **NOTE:** If the argument has previously been seen, it will result in a /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::Arg; /// let cmd = Command::new("mycmd") /// .arg( /// Arg::new("flag") /// .long("flag") /// .action(clap::ArgAction::Set) /// ); /// /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap(); /// assert!(matches.contains_id("flag")); /// assert_eq!( /// matches.get_many::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), /// vec!["value"] /// ); /// ``` Set, /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches] /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::Arg; /// let cmd = Command::new("mycmd") /// .arg( /// Arg::new("flag") /// .long("flag") /// .action(clap::ArgAction::Append) /// ); /// /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value1", "--flag", "value2"]).unwrap(); /// assert!(matches.contains_id("flag")); /// assert_eq!( /// matches.get_many::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), /// vec!["value1", "value2"] /// ); /// ``` Append, /// When encountered, act as if `"true"` was encountered on the command-line /// /// If no [`default_value`][super::Arg::default_value] is set, it will be `false`. /// /// No value is allowed. To optionally accept a value, see /// [`Arg::default_missing_value`][super::Arg::default_missing_value] /// ///
/// /// **NOTE:** If the argument has previously been seen, it will result in a /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::Arg; /// let cmd = Command::new("mycmd") /// .arg( /// Arg::new("flag") /// .long("flag") /// .action(clap::ArgAction::SetTrue) /// ); /// /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); /// assert!(matches.contains_id("flag")); /// assert_eq!( /// matches.get_flag("flag"), /// true /// ); /// /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); /// assert!(matches.contains_id("flag")); /// assert_eq!( /// matches.get_flag("flag"), /// false /// ); /// ``` /// /// You can use [`TypedValueParser::map`][crate::builder::TypedValueParser::map] to have the /// flag control an application-specific type: /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::Arg; /// # use clap::builder::TypedValueParser as _; /// # use clap::builder::BoolishValueParser; /// let cmd = Command::new("mycmd") /// .arg( /// Arg::new("flag") /// .long("flag") /// .action(clap::ArgAction::SetTrue) /// .value_parser( /// BoolishValueParser::new() /// .map(|b| -> usize { /// if b { 10 } else { 5 } /// }) /// ) /// ); /// /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); /// assert!(matches.contains_id("flag")); /// assert_eq!( /// matches.get_one::("flag").copied(), /// Some(10) /// ); /// /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); /// assert!(matches.contains_id("flag")); /// assert_eq!( /// matches.get_one::("flag").copied(), /// Some(5) /// ); /// ``` SetTrue, /// When encountered, act as if `"false"` was encountered on the command-line /// /// If no [`default_value`][super::Arg::default_value] is set, it will be `true`. /// /// No value is allowed. To optionally accept a value, see /// [`Arg::default_missing_value`][super::Arg::default_missing_value] /// ///
/// /// **NOTE:** If the argument has previously been seen, it will result in a /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::Arg; /// let cmd = Command::new("mycmd") /// .arg( /// Arg::new("flag") /// .long("flag") /// .action(clap::ArgAction::SetFalse) /// ); /// /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); /// assert!(matches.contains_id("flag")); /// assert_eq!( /// matches.get_flag("flag"), /// false /// ); /// /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); /// assert!(matches.contains_id("flag")); /// assert_eq!( /// matches.get_flag("flag"), /// true /// ); /// ``` SetFalse, /// When encountered, increment a `u8` counter starting from `0`. /// /// If no [`default_value`][super::Arg::default_value] is set, it will be `0`. /// /// No value is allowed. To optionally accept a value, see /// [`Arg::default_missing_value`][super::Arg::default_missing_value] /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::Arg; /// let cmd = Command::new("mycmd") /// .arg( /// Arg::new("flag") /// .long("flag") /// .action(clap::ArgAction::Count) /// ); /// /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); /// assert!(matches.contains_id("flag")); /// assert_eq!( /// matches.get_count("flag"), /// 2 /// ); /// /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); /// assert!(matches.contains_id("flag")); /// assert_eq!( /// matches.get_count("flag"), /// 0 /// ); /// ``` Count, /// When encountered, display [`Command::print_help`][super::Command::print_help] /// /// Depending on the flag, [`Command::print_long_help`][super::Command::print_long_help] may be shown /// /// # Examples /// /// ```rust /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::Arg; /// let cmd = Command::new("mycmd") /// .arg( /// Arg::new("special-help") /// .short('?') /// .action(clap::ArgAction::Help) /// ); /// /// // Existing help still exists /// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); /// /// // New help available /// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); /// # } /// ``` Help, /// When encountered, display [`Command::print_help`][super::Command::print_help] /// /// # Examples /// /// ```rust /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::Arg; /// let cmd = Command::new("mycmd") /// .arg( /// Arg::new("special-help") /// .short('?') /// .action(clap::ArgAction::HelpShort) /// ); /// /// // Existing help still exists /// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); /// /// // New help available /// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); /// # } /// ``` HelpShort, /// When encountered, display [`Command::print_long_help`][super::Command::print_long_help] /// /// # Examples /// /// ```rust /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::Arg; /// let cmd = Command::new("mycmd") /// .arg( /// Arg::new("special-help") /// .short('?') /// .action(clap::ArgAction::HelpLong) /// ); /// /// // Existing help still exists /// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); /// /// // New help available /// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); /// # } /// ``` HelpLong, /// When encountered, display [`Command::version`][super::Command::version] /// /// Depending on the flag, [`Command::long_version`][super::Command::long_version] may be shown /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::Arg; /// let cmd = Command::new("mycmd") /// .version("1.0.0") /// .arg( /// Arg::new("special-version") /// .long("special-version") /// .action(clap::ArgAction::Version) /// ); /// /// // Existing version still exists /// let err = cmd.clone().try_get_matches_from(["mycmd", "--version"]).unwrap_err(); /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion); /// /// // New version available /// let err = cmd.try_get_matches_from(["mycmd", "--special-version"]).unwrap_err(); /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion); /// ``` Version, } impl ArgAction { /// Returns whether this action accepts values on the command-line /// /// [`default_values`][super::Arg::default_values] and [`env`][super::Arg::env] may still be /// processed. pub fn takes_values(&self) -> bool { match self { Self::Set => true, Self::Append => true, Self::SetTrue => false, Self::SetFalse => false, Self::Count => false, Self::Help => false, Self::HelpShort => false, Self::HelpLong => false, Self::Version => false, } } #[cfg(debug_assertions)] pub(crate) fn max_num_args(&self) -> ValueRange { match self { Self::Set => ValueRange::FULL, Self::Append => ValueRange::FULL, Self::SetTrue => ValueRange::OPTIONAL, Self::SetFalse => ValueRange::OPTIONAL, Self::Count => ValueRange::EMPTY, Self::Help => ValueRange::EMPTY, Self::HelpShort => ValueRange::EMPTY, Self::HelpLong => ValueRange::EMPTY, Self::Version => ValueRange::EMPTY, } } pub(crate) fn default_num_args(&self) -> ValueRange { match self { Self::Set => ValueRange::SINGLE, Self::Append => ValueRange::SINGLE, Self::SetTrue => ValueRange::EMPTY, Self::SetFalse => ValueRange::EMPTY, Self::Count => ValueRange::EMPTY, Self::Help => ValueRange::EMPTY, Self::HelpShort => ValueRange::EMPTY, Self::HelpLong => ValueRange::EMPTY, Self::Version => ValueRange::EMPTY, } } pub(crate) fn default_value(&self) -> Option<&'static std::ffi::OsStr> { match self { Self::Set => None, Self::Append => None, Self::SetTrue => Some(std::ffi::OsStr::new("false")), Self::SetFalse => Some(std::ffi::OsStr::new("true")), Self::Count => Some(std::ffi::OsStr::new("0")), Self::Help => None, Self::HelpShort => None, Self::HelpLong => None, Self::Version => None, } } pub(crate) fn default_missing_value(&self) -> Option<&'static std::ffi::OsStr> { match self { Self::Set => None, Self::Append => None, Self::SetTrue => Some(std::ffi::OsStr::new("true")), Self::SetFalse => Some(std::ffi::OsStr::new("false")), Self::Count => None, Self::Help => None, Self::HelpShort => None, Self::HelpLong => None, Self::Version => None, } } pub(crate) fn default_value_parser(&self) -> Option { match self { Self::Set => None, Self::Append => None, Self::SetTrue => Some(super::ValueParser::bool()), Self::SetFalse => Some(super::ValueParser::bool()), Self::Count => Some(crate::value_parser!(u8).into()), Self::Help => None, Self::HelpShort => None, Self::HelpLong => None, Self::Version => None, } } #[cfg(debug_assertions)] pub(crate) fn value_type_id(&self) -> Option { match self { Self::Set => None, Self::Append => None, Self::SetTrue => None, Self::SetFalse => None, Self::Count => Some(AnyValueId::of::()), Self::Help => None, Self::HelpShort => None, Self::HelpLong => None, Self::Version => None, } } } pub(crate) type CountType = u8; clap_builder-4.5.48/src/builder/app_settings.rs000064400000000000000000000036021046102023000176370ustar 00000000000000#[allow(unused)] use crate::Arg; #[allow(unused)] use crate::Command; #[derive(Default, Copy, Clone, Debug, PartialEq, Eq)] pub(crate) struct AppFlags(u32); impl AppFlags { pub(crate) fn set(&mut self, setting: AppSettings) { self.0 |= setting.bit(); } pub(crate) fn unset(&mut self, setting: AppSettings) { self.0 &= !setting.bit(); } pub(crate) fn is_set(&self, setting: AppSettings) -> bool { self.0 & setting.bit() != 0 } pub(crate) fn insert(&mut self, other: Self) { self.0 |= other.0; } } impl std::ops::BitOr for AppFlags { type Output = Self; fn bitor(mut self, rhs: Self) -> Self::Output { self.insert(rhs); self } } /// 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)] #[repr(u8)] pub(crate) enum AppSettings { IgnoreErrors, AllowHyphenValues, AllowNegativeNumbers, AllArgsOverrideSelf, AllowMissingPositional, TrailingVarArg, DontDelimitTrailingValues, InferLongArgs, InferSubcommands, SubcommandRequired, AllowExternalSubcommands, Multicall, SubcommandsNegateReqs, ArgsNegateSubcommands, SubcommandPrecedenceOverArg, FlattenHelp, ArgRequiredElseHelp, NextLineHelp, DisableColoredHelp, DisableHelpFlag, DisableHelpSubcommand, DisableVersionFlag, PropagateVersion, Hidden, HidePossibleValues, HelpExpected, NoBinaryName, #[allow(dead_code)] ColorAuto, ColorAlways, ColorNever, Built, BinNameBuilt, } impl AppSettings { fn bit(self) -> u32 { 1 << (self as u8) } } clap_builder-4.5.48/src/builder/arg.rs000064400000000000000000005122161046102023000157160ustar 00000000000000// Std #[cfg(feature = "env")] use std::env; #[cfg(feature = "env")] use std::ffi::OsString; use std::{ cmp::{Ord, Ordering}, fmt::{self, Display, Formatter}, str, }; // Internal use super::{ArgFlags, ArgSettings}; #[cfg(feature = "unstable-ext")] use crate::builder::ext::Extension; use crate::builder::ext::Extensions; use crate::builder::ArgPredicate; use crate::builder::IntoResettable; use crate::builder::OsStr; use crate::builder::PossibleValue; use crate::builder::Str; use crate::builder::StyledStr; use crate::builder::Styles; use crate::builder::ValueRange; use crate::util::AnyValueId; use crate::ArgAction; use crate::Id; use crate::ValueHint; use crate::INTERNAL_ERROR_MSG; /// The abstract representation of a command line argument. Used to set all the options and /// relationships that define a valid argument for the program. /// /// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options /// manually, or using a usage string which is far less verbose but has fewer options. You can also /// use a combination of the two methods to achieve the best of both worlds. /// /// - [Basic API][crate::Arg#basic-api] /// - [Value Handling][crate::Arg#value-handling] /// - [Help][crate::Arg#help-1] /// - [Advanced Argument Relations][crate::Arg#advanced-argument-relations] /// - [Reflection][crate::Arg#reflection] /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Arg, arg, ArgAction}; /// // Using the traditional builder pattern and setting each option manually /// let cfg = Arg::new("config") /// .short('c') /// .long("config") /// .action(ArgAction::Set) /// .value_name("FILE") /// .help("Provides a config file to myprog"); /// // Using a usage string (setting a similar argument to the one above) /// let input = arg!(-i --input "Provides an input file to the program"); /// ``` #[derive(Default, Clone)] pub struct Arg { pub(crate) id: Id, pub(crate) help: Option, pub(crate) long_help: Option, pub(crate) action: Option, pub(crate) value_parser: Option, pub(crate) blacklist: Vec, pub(crate) settings: ArgFlags, pub(crate) overrides: Vec, pub(crate) groups: Vec, pub(crate) requires: Vec<(ArgPredicate, Id)>, pub(crate) r_ifs: Vec<(Id, OsStr)>, pub(crate) r_ifs_all: Vec<(Id, OsStr)>, pub(crate) r_unless: Vec, pub(crate) r_unless_all: Vec, pub(crate) short: Option, pub(crate) long: Option, pub(crate) aliases: Vec<(Str, bool)>, // (name, visible) pub(crate) short_aliases: Vec<(char, bool)>, // (name, visible) pub(crate) disp_ord: Option, pub(crate) val_names: Vec, pub(crate) num_vals: Option, pub(crate) val_delim: Option, pub(crate) default_vals: Vec, pub(crate) default_vals_ifs: Vec<(Id, ArgPredicate, Option)>, pub(crate) default_missing_vals: Vec, #[cfg(feature = "env")] pub(crate) env: Option<(OsStr, Option)>, pub(crate) terminator: Option, pub(crate) index: Option, pub(crate) help_heading: Option>, pub(crate) ext: Extensions, } /// # Basic API impl Arg { /// Create a new [`Arg`] with a unique name. /// /// The name is used to check whether or not the argument was used at /// runtime, get values, set relationships with other args, etc.. /// /// By default, an `Arg` is /// - Positional, see [`Arg::short`] or [`Arg::long`] turn it into an option /// - Accept a single value, see [`Arg::action`] to override this /// ///
/// /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::action(ArgAction::Set)`]) /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also /// be displayed when the user prints the usage/help information of the program. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// Arg::new("config") /// # ; /// ``` /// [`Arg::action(ArgAction::Set)`]: Arg::action() pub fn new(id: impl Into) -> Self { Arg::default().id(id) } /// Set the identifier used for referencing this argument in the clap API. /// /// See [`Arg::new`] for more details. #[must_use] pub fn id(mut self, id: impl Into) -> Self { self.id = id.into(); self } /// Sets the short version of the argument without the preceding `-`. /// /// By default `V` and `h` are used by the auto-generated `version` and `help` arguments, /// respectively. You will need to disable the auto-generated flags /// ([`disable_help_flag`][crate::Command::disable_help_flag], /// [`disable_version_flag`][crate::Command::disable_version_flag]) and define your own. /// /// # Examples /// /// When calling `short`, use a single valid UTF-8 character which will allow using the /// argument via a single hyphen (`-`) such as `-c`: /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("config") /// .short('c') /// .action(ArgAction::Set)) /// .get_matches_from(vec![ /// "prog", "-c", "file.toml" /// ]); /// /// assert_eq!(m.get_one::("config").map(String::as_str), Some("file.toml")); /// ``` /// /// To use `-h` for your own flag and still have help: /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .disable_help_flag(true) /// .arg(Arg::new("host") /// .short('h') /// .long("host")) /// .arg(Arg::new("help") /// .long("help") /// .global(true) /// .action(ArgAction::Help)) /// .get_matches_from(vec![ /// "prog", "-h", "wikipedia.org" /// ]); /// /// assert_eq!(m.get_one::("host").map(String::as_str), Some("wikipedia.org")); /// ``` #[inline] #[must_use] pub fn short(mut self, s: impl IntoResettable) -> Self { if let Some(s) = s.into_resettable().into_option() { debug_assert!(s != '-', "short option name cannot be `-`"); self.short = Some(s); } else { self.short = None; } self } /// Sets the long version of the argument without the preceding `--`. /// /// By default `version` and `help` are used by the auto-generated `version` and `help` /// arguments, respectively. You may use the word `version` or `help` for the long form of your /// own arguments, in which case `clap` simply will not assign those to the auto-generated /// `version` or `help` arguments. /// ///
/// /// **NOTE:** Any leading `-` characters will be stripped /// ///
/// /// # Examples /// /// To set `long` use a word containing valid UTF-8. If you supply a double leading /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however, /// will *not* be stripped (i.e. `config-file` is allowed). /// /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config` /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("cfg") /// .long("config") /// .action(ArgAction::Set)) /// .get_matches_from(vec![ /// "prog", "--config", "file.toml" /// ]); /// /// assert_eq!(m.get_one::("cfg").map(String::as_str), Some("file.toml")); /// ``` #[inline] #[must_use] pub fn long(mut self, l: impl IntoResettable) -> Self { self.long = l.into_resettable().into_option(); self } /// Add an alias, which functions as a hidden long flag. /// /// This is more efficient, and easier than creating multiple hidden arguments as one only /// needs to check for the existence of this command, and not all variants. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("test") /// .long("test") /// .alias("alias") /// .action(ArgAction::Set)) /// .get_matches_from(vec![ /// "prog", "--alias", "cool" /// ]); /// assert_eq!(m.get_one::("test").unwrap(), "cool"); /// ``` #[must_use] pub fn alias(mut self, name: impl IntoResettable) -> Self { if let Some(name) = name.into_resettable().into_option() { self.aliases.push((name, false)); } else { self.aliases.clear(); } self } /// Add an alias, which functions as a hidden short flag. /// /// This is more efficient, and easier than creating multiple hidden arguments as one only /// needs to check for the existence of this command, and not all variants. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("test") /// .short('t') /// .short_alias('e') /// .action(ArgAction::Set)) /// .get_matches_from(vec![ /// "prog", "-e", "cool" /// ]); /// assert_eq!(m.get_one::("test").unwrap(), "cool"); /// ``` #[must_use] pub fn short_alias(mut self, name: impl IntoResettable) -> Self { if let Some(name) = name.into_resettable().into_option() { debug_assert!(name != '-', "short alias name cannot be `-`"); self.short_aliases.push((name, false)); } else { self.short_aliases.clear(); } self } /// Add aliases, which function as hidden long flags. /// /// This is more efficient, and easier than creating multiple hidden subcommands as one only /// needs to check for the existence of this command, and not all variants. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("test") /// .long("test") /// .aliases(["do-stuff", "do-tests", "tests"]) /// .action(ArgAction::SetTrue) /// .help("the file to add") /// .required(false)) /// .get_matches_from(vec![ /// "prog", "--do-tests" /// ]); /// assert_eq!(m.get_flag("test"), true); /// ``` #[must_use] pub fn aliases(mut self, names: impl IntoIterator>) -> Self { self.aliases .extend(names.into_iter().map(|x| (x.into(), false))); self } /// Add aliases, which functions as a hidden short flag. /// /// This is more efficient, and easier than creating multiple hidden subcommands as one only /// needs to check for the existence of this command, and not all variants. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("test") /// .short('t') /// .short_aliases(['e', 's']) /// .action(ArgAction::SetTrue) /// .help("the file to add") /// .required(false)) /// .get_matches_from(vec![ /// "prog", "-s" /// ]); /// assert_eq!(m.get_flag("test"), true); /// ``` #[must_use] pub fn short_aliases(mut self, names: impl IntoIterator) -> Self { for s in names { debug_assert!(s != '-', "short alias name cannot be `-`"); self.short_aliases.push((s, false)); } self } /// Add an alias, which functions as a visible long flag. /// /// Like [`Arg::alias`], except that they are visible inside the help message. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("test") /// .visible_alias("something-awesome") /// .long("test") /// .action(ArgAction::Set)) /// .get_matches_from(vec![ /// "prog", "--something-awesome", "coffee" /// ]); /// assert_eq!(m.get_one::("test").unwrap(), "coffee"); /// ``` /// [`Command::alias`]: Arg::alias() #[must_use] pub fn visible_alias(mut self, name: impl IntoResettable) -> Self { if let Some(name) = name.into_resettable().into_option() { self.aliases.push((name, true)); } else { self.aliases.clear(); } self } /// Add an alias, which functions as a visible short flag. /// /// Like [`Arg::short_alias`], except that they are visible inside the help message. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("test") /// .long("test") /// .visible_short_alias('t') /// .action(ArgAction::Set)) /// .get_matches_from(vec![ /// "prog", "-t", "coffee" /// ]); /// assert_eq!(m.get_one::("test").unwrap(), "coffee"); /// ``` #[must_use] pub fn visible_short_alias(mut self, name: impl IntoResettable) -> Self { if let Some(name) = name.into_resettable().into_option() { debug_assert!(name != '-', "short alias name cannot be `-`"); self.short_aliases.push((name, true)); } else { self.short_aliases.clear(); } self } /// Add aliases, which function as visible long flags. /// /// Like [`Arg::aliases`], except that they are visible inside the help message. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("test") /// .long("test") /// .action(ArgAction::SetTrue) /// .visible_aliases(["something", "awesome", "cool"])) /// .get_matches_from(vec![ /// "prog", "--awesome" /// ]); /// assert_eq!(m.get_flag("test"), true); /// ``` /// [`Command::aliases`]: Arg::aliases() #[must_use] pub fn visible_aliases(mut self, names: impl IntoIterator>) -> Self { self.aliases .extend(names.into_iter().map(|n| (n.into(), true))); self } /// Add aliases, which function as visible short flags. /// /// Like [`Arg::short_aliases`], except that they are visible inside the help message. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("test") /// .long("test") /// .action(ArgAction::SetTrue) /// .visible_short_aliases(['t', 'e'])) /// .get_matches_from(vec![ /// "prog", "-t" /// ]); /// assert_eq!(m.get_flag("test"), true); /// ``` #[must_use] pub fn visible_short_aliases(mut self, names: impl IntoIterator) -> Self { for n in names { debug_assert!(n != '-', "short alias name cannot be `-`"); self.short_aliases.push((n, true)); } self } /// Specifies the index of a positional argument **starting at** 1. /// ///
/// /// **NOTE:** The index refers to position according to **other positional argument**. It does /// not define position in the argument list as a whole. /// ///
/// ///
/// /// **NOTE:** You can optionally leave off the `index` method, and the index will be /// assigned in order of evaluation. Utilizing the `index` method allows for setting /// indexes out of order /// ///
/// ///
/// /// **NOTE:** This is only meant to be used for positional arguments and shouldn't to be used /// with [`Arg::short`] or [`Arg::long`]. /// ///
/// ///
/// /// **NOTE:** When utilized with [`Arg::num_args(1..)`], only the **last** positional argument /// may be defined as having a variable number of arguments (i.e. with the highest index) /// ///
/// /// # Panics /// /// [`Command`] will [`panic!`] if indexes are skipped (such as defining `index(1)` and `index(3)` /// but not `index(2)`, or a positional argument is defined as multiple and is not the highest /// index (debug builds) /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// Arg::new("config") /// .index(1) /// # ; /// ``` /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("mode") /// .index(1)) /// .arg(Arg::new("debug") /// .long("debug") /// .action(ArgAction::SetTrue)) /// .get_matches_from(vec![ /// "prog", "--debug", "fast" /// ]); /// /// assert!(m.contains_id("mode")); /// assert_eq!(m.get_one::("mode").unwrap(), "fast"); // notice index(1) means "first positional" /// // *not* first argument /// ``` /// [`Arg::short`]: Arg::short() /// [`Arg::long`]: Arg::long() /// [`Arg::num_args(true)`]: Arg::num_args() /// [`Command`]: crate::Command #[inline] #[must_use] pub fn index(mut self, idx: impl IntoResettable) -> Self { self.index = idx.into_resettable().into_option(); self } /// This is a "var arg" and everything that follows should be captured by it, as if the user had /// used a `--`. /// ///
/// /// **NOTE:** To start the trailing "var arg" on unknown flags (and not just a positional /// value), set [`allow_hyphen_values`][Arg::allow_hyphen_values]. Either way, users still /// have the option to explicitly escape ambiguous arguments with `--`. /// ///
/// ///
/// /// **NOTE:** [`Arg::value_delimiter`] still applies if set. /// ///
/// ///
/// /// **NOTE:** Setting this requires [`Arg::num_args(..)`]. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg}; /// let m = Command::new("myprog") /// .arg(arg!( ... "commands to run").trailing_var_arg(true)) /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]); /// /// let trail: Vec<_> = m.get_many::("cmd").unwrap().collect(); /// assert_eq!(trail, ["arg1", "-r", "val1"]); /// ``` /// [`Arg::num_args(..)`]: crate::Arg::num_args() pub fn trailing_var_arg(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::TrailingVarArg) } else { self.unset_setting(ArgSettings::TrailingVarArg) } } /// This arg is the last, or final, positional argument (i.e. has the highest /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args -- /// last_arg`). /// /// Even, if no other arguments are left to parse, if the user omits the `--` syntax /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with /// the `--` syntax is otherwise not possible. /// ///
/// /// **NOTE:** This will change the usage string to look like `$ prog [OPTIONS] [-- ]` if /// `ARG` is marked as `.last(true)`. /// ///
/// ///
/// /// **NOTE:** This setting will imply [`crate::Command::dont_collapse_args_in_usage`] because failing /// to set this can make the usage string very confusing. /// ///
/// ///
/// /// **NOTE**: This setting only applies to positional arguments, and has no effect on OPTIONS /// ///
/// ///
/// /// **NOTE:** Setting this requires [taking values][Arg::num_args] /// ///
/// ///
/// /// **WARNING:** 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_builder as clap; /// # use clap::{Arg, ArgAction}; /// Arg::new("args") /// .action(ArgAction::Set) /// .last(true) /// # ; /// ``` /// /// Setting `last` ensures the arg has the highest [index] of all positional args /// and requires that the `--` syntax be used to access it early. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("first")) /// .arg(Arg::new("second")) /// .arg(Arg::new("third") /// .action(ArgAction::Set) /// .last(true)) /// .try_get_matches_from(vec![ /// "prog", "one", "--", "three" /// ]); /// /// assert!(res.is_ok()); /// let m = res.unwrap(); /// assert_eq!(m.get_one::("third").unwrap(), "three"); /// assert_eq!(m.get_one::("second"), None); /// ``` /// /// Even if the positional argument marked `Last` is the only argument left to parse, /// failing to use the `--` syntax results in an error. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("first")) /// .arg(Arg::new("second")) /// .arg(Arg::new("third") /// .action(ArgAction::Set) /// .last(true)) /// .try_get_matches_from(vec![ /// "prog", "one", "two", "three" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); /// ``` /// [index]: Arg::index() /// [`UnknownArgument`]: crate::error::ErrorKind::UnknownArgument #[inline] #[must_use] pub fn last(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::Last) } else { self.unset_setting(ArgSettings::Last) } } /// Specifies that the argument must be present. /// /// Required by default means it is required, when no other conflicting rules or overrides have /// been evaluated. Conflicting rules take precedence over being required. /// /// **Pro tip:** Flags (i.e. not positional, or arguments that take values) shouldn't be /// required by default. This is because if a flag were to be required, it should simply be /// implied. No additional information is required from user. Flags by their very nature are /// simply boolean on/off switches. The only time a user *should* be required to use a flag /// is if the operation is destructive in nature, and the user is essentially proving to you, /// "Yes, I know what I'm doing." /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Arg; /// Arg::new("config") /// .required(true) /// # ; /// ``` /// /// Setting required requires that the argument be used at runtime. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .required(true) /// .action(ArgAction::Set) /// .long("config")) /// .try_get_matches_from(vec![ /// "prog", "--config", "file.conf", /// ]); /// /// assert!(res.is_ok()); /// ``` /// /// Setting required and then *not* supplying that argument at runtime is an error. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .required(true) /// .action(ArgAction::Set) /// .long("config")) /// .try_get_matches_from(vec![ /// "prog" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); /// ``` #[inline] #[must_use] pub fn required(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::Required) } else { self.unset_setting(ArgSettings::Required) } } /// Sets an argument that is required when this one is present /// /// i.e. when using this argument, the following argument *must* be present. /// ///
/// /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # 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_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .requires("input") /// .long("config")) /// .arg(Arg::new("input")) /// .try_get_matches_from(vec![ /// "prog" /// ]); /// /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required /// ``` /// /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .requires("input") /// .long("config")) /// .arg(Arg::new("input")) /// .try_get_matches_from(vec![ /// "prog", "--config", "file.conf" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); /// ``` /// [`Arg::requires(name)`]: Arg::requires() /// [Conflicting]: Arg::conflicts_with() /// [override]: Arg::overrides_with() #[must_use] pub fn requires(mut self, arg_id: impl IntoResettable) -> Self { if let Some(arg_id) = arg_id.into_resettable().into_option() { self.requires.push((ArgPredicate::IsPresent, arg_id)); } else { self.requires.clear(); } self } /// This argument must be passed alone; it conflicts with all other arguments. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # 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_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("exclusive") /// .action(ArgAction::Set) /// .exclusive(true) /// .long("exclusive")) /// .arg(Arg::new("debug") /// .long("debug")) /// .arg(Arg::new("input")) /// .try_get_matches_from(vec![ /// "prog", "--exclusive", "file.conf", "file.txt" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); /// ``` #[inline] #[must_use] pub fn exclusive(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::Exclusive) } else { self.unset_setting(ArgSettings::Exclusive) } } /// Specifies that an argument can be matched to all child [`Subcommand`]s. /// ///
/// /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however /// their values once a user uses them will be propagated back up to parents. In effect, this /// means one should *define* all global arguments at the top level, however it doesn't matter /// where the user *uses* the global argument. /// ///
/// /// # Examples /// /// Assume an application with two subcommands, and you'd like to define a /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't /// want to clutter the source with three duplicate [`Arg`] definitions. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("verb") /// .long("verbose") /// .short('v') /// .action(ArgAction::SetTrue) /// .global(true)) /// .subcommand(Command::new("test")) /// .subcommand(Command::new("do-stuff")) /// .get_matches_from(vec![ /// "prog", "do-stuff", "--verbose" /// ]); /// /// assert_eq!(m.subcommand_name(), Some("do-stuff")); /// let sub_m = m.subcommand_matches("do-stuff").unwrap(); /// assert_eq!(sub_m.get_flag("verb"), true); /// ``` /// /// [`Subcommand`]: crate::Subcommand #[inline] #[must_use] pub fn global(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::Global) } else { self.unset_setting(ArgSettings::Global) } } #[inline] pub(crate) fn is_set(&self, s: ArgSettings) -> bool { self.settings.is_set(s) } #[inline] #[must_use] pub(crate) fn setting(mut self, setting: ArgSettings) -> Self { self.settings.set(setting); self } #[inline] #[must_use] pub(crate) fn unset_setting(mut self, setting: ArgSettings) -> Self { self.settings.unset(setting); self } /// Extend [`Arg`] with [`ArgExt`] data #[cfg(feature = "unstable-ext")] #[allow(clippy::should_implement_trait)] pub fn add(mut self, tagged: T) -> Self { self.ext.set(tagged); self } } /// # Value Handling impl Arg { /// Specify how to react to an argument when parsing it. /// /// [`ArgAction`] controls things like /// - Overwriting previous values with new ones /// - Appending new values to all previous ones /// - Counting how many times a flag occurs /// /// The default action is `ArgAction::Set` /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::Arg; /// let cmd = Command::new("mycmd") /// .arg( /// Arg::new("flag") /// .long("flag") /// .action(clap::ArgAction::Append) /// ); /// /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap(); /// assert!(matches.contains_id("flag")); /// assert_eq!( /// matches.get_many::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), /// vec!["value"] /// ); /// ``` #[inline] #[must_use] pub fn action(mut self, action: impl IntoResettable) -> Self { self.action = action.into_resettable().into_option(); self } /// Specify the typed behavior of the argument. /// /// This allows parsing and validating a value before storing it into /// [`ArgMatches`][crate::ArgMatches] as the given type. /// /// Possible value parsers include: /// - [`value_parser!(T)`][crate::value_parser!] for auto-selecting a value parser for a given type /// - Or [range expressions like `0..=1`][std::ops::RangeBounds] as a shorthand for [`RangedI64ValueParser`][crate::builder::RangedI64ValueParser] /// - `Fn(&str) -> Result` /// - `[&str]` and [`PossibleValuesParser`][crate::builder::PossibleValuesParser] for static enumerated values /// - [`BoolishValueParser`][crate::builder::BoolishValueParser], and [`FalseyValueParser`][crate::builder::FalseyValueParser] for alternative `bool` implementations /// - [`NonEmptyStringValueParser`][crate::builder::NonEmptyStringValueParser] for basic validation for strings /// - or any other [`TypedValueParser`][crate::builder::TypedValueParser] implementation /// /// The default value is [`ValueParser::string`][crate::builder::ValueParser::string]. /// /// ```rust /// # use clap_builder as clap; /// # use clap::ArgAction; /// let mut cmd = clap::Command::new("raw") /// .arg( /// clap::Arg::new("color") /// .long("color") /// .value_parser(["always", "auto", "never"]) /// .default_value("auto") /// ) /// .arg( /// clap::Arg::new("hostname") /// .long("hostname") /// .value_parser(clap::builder::NonEmptyStringValueParser::new()) /// .action(ArgAction::Set) /// .required(true) /// ) /// .arg( /// clap::Arg::new("port") /// .long("port") /// .value_parser(clap::value_parser!(u16).range(3000..)) /// .action(ArgAction::Set) /// .required(true) /// ); /// /// let m = cmd.try_get_matches_from_mut( /// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"] /// ).unwrap(); /// /// let color: &String = m.get_one("color") /// .expect("default"); /// assert_eq!(color, "auto"); /// /// let hostname: &String = m.get_one("hostname") /// .expect("required"); /// assert_eq!(hostname, "rust-lang.org"); /// /// let port: u16 = *m.get_one("port") /// .expect("required"); /// assert_eq!(port, 3001); /// ``` pub fn value_parser(mut self, parser: impl IntoResettable) -> Self { self.value_parser = parser.into_resettable().into_option(); self } /// Specifies the number of arguments parsed per occurrence /// /// For example, if you had a `-f ` argument where you wanted exactly 3 'files' you would /// set `.num_args(3)`, and this argument wouldn't be satisfied unless the user /// provided 3 and only 3 values. /// /// Users may specify values for arguments in any of the following methods /// /// - Using a space such as `-o value` or `--option value` /// - Using an equals and no space such as `-o=value` or `--option=value` /// - Use a short and no space such as `-ovalue` /// ///
/// /// **WARNING:** /// /// Setting a variable number of values (e.g. `1..=10`) for an argument without /// other details can be dangerous in some circumstances. Because multiple values are /// allowed, `--option val1 val2 val3` is perfectly valid. Be careful when designing a CLI /// where **positional arguments** or **subcommands** are *also* expected as `clap` will continue /// parsing *values* until one of the following happens: /// /// - It reaches the maximum number of values /// - It reaches a specific number of values /// - It finds another flag or option (i.e. something that starts with a `-`) /// - It reaches the [`Arg::value_terminator`] if set /// /// Alternatively, /// - Use a delimiter between values with [`Arg::value_delimiter`] /// - Require a flag occurrence per value with [`ArgAction::Append`] /// - Require positional arguments to appear after `--` with [`Arg::last`] /// ///
/// /// # Examples /// /// Option: /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let m = Command::new("prog") /// .arg(Arg::new("mode") /// .long("mode") /// .num_args(1)) /// .get_matches_from(vec![ /// "prog", "--mode", "fast" /// ]); /// /// assert_eq!(m.get_one::("mode").unwrap(), "fast"); /// ``` /// /// Flag/option hybrid (see also [`default_missing_value`][Arg::default_missing_value]) /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let cmd = Command::new("prog") /// .arg(Arg::new("mode") /// .long("mode") /// .default_missing_value("slow") /// .default_value("plaid") /// .num_args(0..=1)); /// /// let m = cmd.clone() /// .get_matches_from(vec![ /// "prog", "--mode", "fast" /// ]); /// assert_eq!(m.get_one::("mode").unwrap(), "fast"); /// /// let m = cmd.clone() /// .get_matches_from(vec![ /// "prog", "--mode", /// ]); /// assert_eq!(m.get_one::("mode").unwrap(), "slow"); /// /// let m = cmd.clone() /// .get_matches_from(vec![ /// "prog", /// ]); /// assert_eq!(m.get_one::("mode").unwrap(), "plaid"); /// ``` /// /// Tuples /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let cmd = Command::new("prog") /// .arg(Arg::new("file") /// .action(ArgAction::Set) /// .num_args(2) /// .short('F')); /// /// let m = cmd.clone() /// .get_matches_from(vec![ /// "prog", "-F", "in-file", "out-file" /// ]); /// assert_eq!( /// m.get_many::("file").unwrap_or_default().map(|v| v.as_str()).collect::>(), /// vec!["in-file", "out-file"] /// ); /// /// let res = cmd.clone() /// .try_get_matches_from(vec![ /// "prog", "-F", "file1" /// ]); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::WrongNumberOfValues); /// ``` /// /// A common mistake is to define an option which allows multiple values and a positional /// argument. /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let cmd = Command::new("prog") /// .arg(Arg::new("file") /// .action(ArgAction::Set) /// .num_args(0..) /// .short('F')) /// .arg(Arg::new("word")); /// /// let m = cmd.clone().get_matches_from(vec![ /// "prog", "-F", "file1", "file2", "file3", "word" /// ]); /// let files: Vec<_> = m.get_many::("file").unwrap().collect(); /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?! /// assert!(!m.contains_id("word")); // but we clearly used word! /// /// // but this works /// let m = cmd.clone().get_matches_from(vec![ /// "prog", "word", "-F", "file1", "file2", "file3", /// ]); /// let files: Vec<_> = m.get_many::("file").unwrap().collect(); /// assert_eq!(files, ["file1", "file2", "file3"]); /// assert_eq!(m.get_one::("word").unwrap(), "word"); /// ``` /// The problem is `clap` doesn't know when to stop parsing values for "file". /// /// A solution for the example above is to limit how many values with a maximum, or specific /// number, or to say [`ArgAction::Append`] is ok, but multiple values are not. /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("file") /// .action(ArgAction::Append) /// .short('F')) /// .arg(Arg::new("word")) /// .get_matches_from(vec![ /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word" /// ]); /// /// let files: Vec<_> = m.get_many::("file").unwrap().collect(); /// assert_eq!(files, ["file1", "file2", "file3"]); /// assert_eq!(m.get_one::("word").unwrap(), "word"); /// ``` #[inline] #[must_use] pub fn num_args(mut self, qty: impl IntoResettable) -> Self { self.num_vals = qty.into_resettable().into_option(); self } #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Arg::num_args`") )] pub fn number_of_values(self, qty: usize) -> Self { self.num_args(qty) } /// Placeholder for the argument's value in the help message / usage. /// /// This name is cosmetic only; the name is **not** used to access arguments. /// This setting can be very helpful when describing the type of input the user should be /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to /// use all capital letters for the value name. /// ///
/// /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`] /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// Arg::new("cfg") /// .long("config") /// .value_name("FILE") /// # ; /// ``` /// /// ```rust /// # use clap_builder as clap; /// # #[cfg(feature = "help")] { /// # use clap::{Command, Arg}; /// let m = Command::new("prog") /// .arg(Arg::new("config") /// .long("config") /// .value_name("FILE") /// .help("Some help text")) /// .get_matches_from(vec![ /// "prog", "--help" /// ]); /// # } /// ``` /// Running the above program produces the following output /// /// ```text /// valnames /// /// Usage: valnames [OPTIONS] /// /// Options: /// --config Some help text /// -h, --help Print help information /// -V, --version Print version information /// ``` /// [positional]: Arg::index() /// [`Arg::action(ArgAction::Set)`]: Arg::action() #[inline] #[must_use] pub fn value_name(mut self, name: impl IntoResettable) -> Self { if let Some(name) = name.into_resettable().into_option() { self.value_names([name]) } else { self.val_names.clear(); self } } /// Placeholders for the argument's values in the help message / usage. /// /// These names are cosmetic only, used for help and usage strings only. The names are **not** /// used to access arguments. The values of the arguments are accessed in numeric order (i.e. /// if you specify two names `one` and `two` `one` will be the first matched value, `two` will /// be the second). /// /// This setting can be very helpful when describing the type of input the user should be /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to /// use all capital letters for the value name. /// ///
/// /// **TIP:** It may help to use [`Arg::next_line_help(true)`] if there are long, or /// multiple value names in order to not throw off the help text alignment of all options. /// ///
/// ///
/// /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`] and [`Arg::num_args(1..)`]. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// Arg::new("speed") /// .short('s') /// .value_names(["fast", "slow"]); /// ``` /// /// ```rust /// # use clap_builder as clap; /// # #[cfg(feature = "help")] { /// # use clap::{Command, Arg}; /// let m = Command::new("prog") /// .arg(Arg::new("io") /// .long("io-files") /// .value_names(["INFILE", "OUTFILE"])) /// .get_matches_from(vec![ /// "prog", "--help" /// ]); /// # } /// ``` /// /// Running the above program produces the following output /// /// ```text /// valnames /// /// Usage: valnames [OPTIONS] /// /// Options: /// -h, --help Print help information /// --io-files Some help text /// -V, --version Print version information /// ``` /// [`Arg::next_line_help(true)`]: Arg::next_line_help() /// [`Arg::num_args`]: Arg::num_args() /// [`Arg::action(ArgAction::Set)`]: Arg::action() /// [`Arg::num_args(1..)`]: Arg::num_args() #[must_use] pub fn value_names(mut self, names: impl IntoIterator>) -> Self { self.val_names = names.into_iter().map(|s| s.into()).collect(); self } /// Provide the shell a hint about how to complete this argument. /// /// See [`ValueHint`] for more information. /// ///
/// /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`]. /// ///
/// /// For example, to take a username as argument: /// /// ```rust /// # use clap_builder as clap; /// # 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): /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ValueHint, ArgAction}; /// Command::new("prog") /// .trailing_var_arg(true) /// .arg( /// Arg::new("command") /// .action(ArgAction::Set) /// .num_args(1..) /// .value_hint(ValueHint::CommandWithArguments) /// ); /// ``` #[must_use] pub fn value_hint(mut self, value_hint: impl IntoResettable) -> Self { // HACK: we should use `Self::add` and `Self::remove` to type-check that `ArgExt` is used match value_hint.into_resettable().into_option() { Some(value_hint) => { self.ext.set(value_hint); } None => { self.ext.remove::(); } } self } /// Match values against [`PossibleValuesParser`][crate::builder::PossibleValuesParser] without matching case. /// /// When other arguments are conditionally required based on the /// value of a case-insensitive argument, the equality check done /// by [`Arg::required_if_eq`], [`Arg::required_if_eq_any`], or /// [`Arg::required_if_eq_all`] is case-insensitive. /// /// ///
/// /// **NOTE:** Setting this requires [taking values][Arg::num_args] /// ///
/// ///
/// /// **NOTE:** To do unicode case folding, enable the `unicode` feature flag. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("pv") /// .arg(Arg::new("option") /// .long("option") /// .action(ArgAction::Set) /// .ignore_case(true) /// .value_parser(["test123"])) /// .get_matches_from(vec![ /// "pv", "--option", "TeSt123", /// ]); /// /// assert!(m.get_one::("option").unwrap().eq_ignore_ascii_case("test123")); /// ``` /// /// This setting also works when multiple values can be defined: /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("pv") /// .arg(Arg::new("option") /// .short('o') /// .long("option") /// .action(ArgAction::Set) /// .ignore_case(true) /// .num_args(1..) /// .value_parser(["test123", "test321"])) /// .get_matches_from(vec![ /// "pv", "--option", "TeSt123", "teST123", "tESt321" /// ]); /// /// let matched_vals = m.get_many::("option").unwrap().collect::>(); /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]); /// ``` #[inline] #[must_use] pub fn ignore_case(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::IgnoreCase) } else { self.unset_setting(ArgSettings::IgnoreCase) } } /// Allows values which start with a leading hyphen (`-`) /// /// To limit values to just numbers, see /// [`allow_negative_numbers`][Arg::allow_negative_numbers]. /// /// See also [`trailing_var_arg`][Arg::trailing_var_arg]. /// ///
/// /// **NOTE:** Setting this requires [taking values][Arg::num_args] /// ///
/// ///
/// /// **WARNING:** Prior arguments with `allow_hyphen_values(true)` get precedence over known /// flags but known flags get precedence over the next possible positional argument with /// `allow_hyphen_values(true)`. When combined with [`Arg::num_args(..)`], /// [`Arg::value_terminator`] is one way to ensure processing stops. /// ///
/// ///
/// /// **WARNING**: Take caution when using this setting combined with another argument using /// [`Arg::num_args`], as this becomes ambiguous `$ prog --arg -- -- val`. All /// three `--, --, val` will be values when the user may have thought the second `--` would /// constitute the normal, "Only positional args follow" idiom. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("pat") /// .action(ArgAction::Set) /// .allow_hyphen_values(true) /// .long("pattern")) /// .get_matches_from(vec![ /// "prog", "--pattern", "-file" /// ]); /// /// assert_eq!(m.get_one::("pat").unwrap(), "-file"); /// ``` /// /// Not setting `Arg::allow_hyphen_values(true)` and supplying a value which starts with a /// hyphen is an error. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("pat") /// .action(ArgAction::Set) /// .long("pattern")) /// .try_get_matches_from(vec![ /// "prog", "--pattern", "-file" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); /// ``` /// [`Arg::num_args(1)`]: Arg::num_args() #[inline] #[must_use] pub fn allow_hyphen_values(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::AllowHyphenValues) } else { self.unset_setting(ArgSettings::AllowHyphenValues) } } /// Allows negative numbers to pass as values. /// /// This is similar to [`Arg::allow_hyphen_values`] except that it only allows numbers, /// all other undefined leading hyphens will fail to parse. /// ///
/// /// **NOTE:** Setting this requires [taking values][Arg::num_args] /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let res = Command::new("myprog") /// .arg(Arg::new("num").allow_negative_numbers(true)) /// .try_get_matches_from(vec![ /// "myprog", "-20" /// ]); /// assert!(res.is_ok()); /// let m = res.unwrap(); /// assert_eq!(m.get_one::("num").unwrap(), "-20"); /// ``` #[inline] pub fn allow_negative_numbers(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::AllowNegativeNumbers) } else { self.unset_setting(ArgSettings::AllowNegativeNumbers) } } /// Requires that options use the `--option=val` syntax /// /// i.e. an equals between the option and associated value. /// ///
/// /// **NOTE:** Setting this requires [taking values][Arg::num_args] /// ///
/// /// # Examples /// /// Setting `require_equals` requires that the option have an equals sign between /// it and the associated value. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .require_equals(true) /// .long("config")) /// .try_get_matches_from(vec![ /// "prog", "--config=file.conf" /// ]); /// /// assert!(res.is_ok()); /// ``` /// /// Setting `require_equals` and *not* supplying the equals will cause an /// error. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .require_equals(true) /// .long("config")) /// .try_get_matches_from(vec![ /// "prog", "--config", "file.conf" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals); /// ``` #[inline] #[must_use] pub fn require_equals(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::RequireEquals) } else { self.unset_setting(ArgSettings::RequireEquals) } } #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Arg::value_delimiter`") )] pub fn use_value_delimiter(mut self, yes: bool) -> Self { if yes { self.val_delim.get_or_insert(','); } else { self.val_delim = None; } self } /// Allow grouping of multiple values via a delimiter. /// /// i.e. allow values (`val1,val2,val3`) to be parsed as three values (`val1`, `val2`, /// and `val3`) instead of one value (`val1,val2,val3`). /// /// See also [`Command::dont_delimit_trailing_values`][crate::Command::dont_delimit_trailing_values]. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let m = Command::new("prog") /// .arg(Arg::new("config") /// .short('c') /// .long("config") /// .value_delimiter(',')) /// .get_matches_from(vec![ /// "prog", "--config=val1,val2,val3" /// ]); /// /// assert_eq!(m.get_many::("config").unwrap().collect::>(), ["val1", "val2", "val3"]) /// ``` /// [`Arg::value_delimiter(',')`]: Arg::value_delimiter() /// [`Arg::action(ArgAction::Set)`]: Arg::action() #[inline] #[must_use] pub fn value_delimiter(mut self, d: impl IntoResettable) -> Self { self.val_delim = d.into_resettable().into_option(); self } /// Sentinel to **stop** parsing multiple values of a given argument. /// /// By default when /// one sets [`num_args(1..)`] on an argument, clap will continue parsing values for that /// argument until it reaches another valid argument, or one of the other more specific settings /// for multiple values is used (such as [`num_args`]). /// ///
/// /// **NOTE:** This setting only applies to [options] and [positional arguments] /// ///
/// ///
/// /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one /// of the values /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// Arg::new("vals") /// .action(ArgAction::Set) /// .num_args(1..) /// .value_terminator(";") /// # ; /// ``` /// /// The following example uses two arguments, a sequence of commands, and the location in which /// to perform them /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("cmds") /// .action(ArgAction::Set) /// .num_args(1..) /// .allow_hyphen_values(true) /// .value_terminator(";")) /// .arg(Arg::new("location")) /// .get_matches_from(vec![ /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap" /// ]); /// let cmds: Vec<_> = m.get_many::("cmds").unwrap().collect(); /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]); /// assert_eq!(m.get_one::("location").unwrap(), "/home/clap"); /// ``` /// [options]: Arg::action /// [positional arguments]: Arg::index() /// [`num_args(1..)`]: Arg::num_args() /// [`num_args`]: Arg::num_args() #[inline] #[must_use] pub fn value_terminator(mut self, term: impl IntoResettable) -> Self { self.terminator = term.into_resettable().into_option(); self } /// Consume all following arguments. /// /// Do not 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 [`Arg::trailing_var_arg`] /// may be more appropriate. /// ///
/// /// **NOTE:** Implicitly sets [`Arg::action(ArgAction::Set)`], [`Arg::num_args(1..)`], /// [`Arg::allow_hyphen_values(true)`], and [`Arg::last(true)`] when set to `true`. /// ///
/// /// [`Arg::action(ArgAction::Set)`]: Arg::action() /// [`Arg::num_args(1..)`]: Arg::num_args() /// [`Arg::allow_hyphen_values(true)`]: Arg::allow_hyphen_values() /// [`Arg::last(true)`]: Arg::last() #[inline] #[must_use] pub fn raw(mut self, yes: bool) -> Self { if yes { self.num_vals.get_or_insert_with(|| (1..).into()); } self.allow_hyphen_values(yes).last(yes) } /// Value for the argument when not present. /// /// Like with command-line values, this will be split by [`Arg::value_delimiter`]. /// ///
/// /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::contains_id`] will /// still return `true`. If you wish to determine whether the argument was used at runtime or /// not, consider [`ArgMatches::value_source`][crate::ArgMatches::value_source]. /// ///
/// ///
/// /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg /// at runtime. `Arg::default_value_if` however only takes effect when the user has not provided /// a value at runtime **and** these other conditions are met as well. If you have set /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide this arg /// at runtime, nor were the conditions met for `Arg::default_value_if`, the `Arg::default_value` /// will be applied. /// ///
/// /// # Examples /// /// First we use the default value without providing any value at runtime. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, parser::ValueSource}; /// let m = Command::new("prog") /// .arg(Arg::new("opt") /// .long("myopt") /// .default_value("myval")) /// .get_matches_from(vec![ /// "prog" /// ]); /// /// assert_eq!(m.get_one::("opt").unwrap(), "myval"); /// assert!(m.contains_id("opt")); /// assert_eq!(m.value_source("opt"), Some(ValueSource::DefaultValue)); /// ``` /// /// Next we provide a value at runtime to override the default. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, parser::ValueSource}; /// let m = Command::new("prog") /// .arg(Arg::new("opt") /// .long("myopt") /// .default_value("myval")) /// .get_matches_from(vec![ /// "prog", "--myopt=non_default" /// ]); /// /// assert_eq!(m.get_one::("opt").unwrap(), "non_default"); /// assert!(m.contains_id("opt")); /// assert_eq!(m.value_source("opt"), Some(ValueSource::CommandLine)); /// ``` /// [`Arg::action(ArgAction::Set)`]: Arg::action() /// [`ArgMatches::contains_id`]: crate::ArgMatches::contains_id() /// [`Arg::default_value_if`]: Arg::default_value_if() #[inline] #[must_use] pub fn default_value(mut self, val: impl IntoResettable) -> Self { if let Some(val) = val.into_resettable().into_option() { self.default_values([val]) } else { self.default_vals.clear(); self } } #[inline] #[must_use] #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value`") )] pub fn default_value_os(self, val: impl Into) -> Self { self.default_values([val]) } /// Value for the argument when not present. /// /// See [`Arg::default_value`]. /// /// [`Arg::default_value`]: Arg::default_value() #[inline] #[must_use] pub fn default_values(mut self, vals: impl IntoIterator>) -> Self { self.default_vals = vals.into_iter().map(|s| s.into()).collect(); self } #[inline] #[must_use] #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Arg::default_values`") )] pub fn default_values_os(self, vals: impl IntoIterator>) -> Self { self.default_values(vals) } /// Value for the argument when the flag is present but no value is specified. /// /// This configuration option is often used to give the user a shortcut and allow them to /// efficiently specify an option argument without requiring an explicitly value. The `--color` /// argument is a common example. By supplying a default, such as `default_missing_value("always")`, /// the user can quickly just add `--color` to the command line to produce the desired color output. /// /// Like with command-line values, this will be split by [`Arg::value_delimiter`]. /// ///
/// /// **NOTE:** using this configuration option requires the use of the /// [`.num_args(0..N)`][Arg::num_args] and the /// [`.require_equals(true)`][Arg::require_equals] configuration option. These are required in /// order to unambiguously determine what, if any, value was supplied for the argument. /// ///
/// /// # Examples /// /// For POSIX style `--color`: /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, parser::ValueSource}; /// fn cli() -> Command { /// Command::new("prog") /// .arg(Arg::new("color").long("color") /// .value_name("WHEN") /// .value_parser(["always", "auto", "never"]) /// .default_value("auto") /// .num_args(0..=1) /// .require_equals(true) /// .default_missing_value("always") /// .help("Specify WHEN to colorize output.") /// ) /// } /// /// // first, we'll provide no arguments /// let m = cli().get_matches_from(vec![ /// "prog" /// ]); /// assert_eq!(m.get_one::("color").unwrap(), "auto"); /// assert_eq!(m.value_source("color"), Some(ValueSource::DefaultValue)); /// /// // next, we'll provide a runtime value to override the default (as usually done). /// let m = cli().get_matches_from(vec![ /// "prog", "--color=never" /// ]); /// assert_eq!(m.get_one::("color").unwrap(), "never"); /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine)); /// /// // finally, we will use the shortcut and only provide the argument without a value. /// let m = cli().get_matches_from(vec![ /// "prog", "--color" /// ]); /// assert_eq!(m.get_one::("color").unwrap(), "always"); /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine)); /// ``` /// /// For bool literals: /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, parser::ValueSource, value_parser}; /// fn cli() -> Command { /// Command::new("prog") /// .arg(Arg::new("create").long("create") /// .value_name("BOOL") /// .value_parser(value_parser!(bool)) /// .num_args(0..=1) /// .require_equals(true) /// .default_missing_value("true") /// ) /// } /// /// // first, we'll provide no arguments /// let m = cli().get_matches_from(vec![ /// "prog" /// ]); /// assert_eq!(m.get_one::("create").copied(), None); /// /// // next, we'll provide a runtime value to override the default (as usually done). /// let m = cli().get_matches_from(vec![ /// "prog", "--create=false" /// ]); /// assert_eq!(m.get_one::("create").copied(), Some(false)); /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine)); /// /// // finally, we will use the shortcut and only provide the argument without a value. /// let m = cli().get_matches_from(vec![ /// "prog", "--create" /// ]); /// assert_eq!(m.get_one::("create").copied(), Some(true)); /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine)); /// ``` /// /// [`Arg::action(ArgAction::Set)`]: Arg::action() /// [`Arg::default_value`]: Arg::default_value() #[inline] #[must_use] pub fn default_missing_value(mut self, val: impl IntoResettable) -> Self { if let Some(val) = val.into_resettable().into_option() { self.default_missing_values_os([val]) } else { self.default_missing_vals.clear(); self } } /// Value for the argument when the flag is present but no value is specified. /// /// See [`Arg::default_missing_value`]. /// /// [`Arg::default_missing_value`]: Arg::default_missing_value() /// [`OsStr`]: std::ffi::OsStr #[inline] #[must_use] pub fn default_missing_value_os(self, val: impl Into) -> Self { self.default_missing_values_os([val]) } /// Value for the argument when the flag is present but no value is specified. /// /// See [`Arg::default_missing_value`]. /// /// [`Arg::default_missing_value`]: Arg::default_missing_value() #[inline] #[must_use] pub fn default_missing_values(self, vals: impl IntoIterator>) -> Self { self.default_missing_values_os(vals) } /// Value for the argument when the flag is present but no value is specified. /// /// See [`Arg::default_missing_values`]. /// /// [`Arg::default_missing_values`]: Arg::default_missing_values() /// [`OsStr`]: std::ffi::OsStr #[inline] #[must_use] pub fn default_missing_values_os( mut self, vals: impl IntoIterator>, ) -> Self { self.default_missing_vals = vals.into_iter().map(|s| s.into()).collect(); self } /// Read from `name` environment variable when argument is not present. /// /// If it is not present in the environment, then default /// rules will apply. /// /// If user sets the argument in the environment: /// - When [`Arg::action(ArgAction::Set)`] is not set, the flag is considered raised. /// - When [`Arg::action(ArgAction::Set)`] is set, /// [`ArgMatches::get_one`][crate::ArgMatches::get_one] will /// return value of the environment variable. /// /// If user doesn't set the argument in the environment: /// - When [`Arg::action(ArgAction::Set)`] is not set, the flag is considered off. /// - When [`Arg::action(ArgAction::Set)`] is set, /// [`ArgMatches::get_one`][crate::ArgMatches::get_one] will /// return the default specified. /// /// Like with command-line values, this will be split by [`Arg::value_delimiter`]. /// /// # Examples /// /// In this example, we show the variable coming from the environment: /// /// ```rust /// # use clap_builder as clap; /// # use std::env; /// # use clap::{Command, Arg, ArgAction}; /// /// env::set_var("MY_FLAG", "env"); /// /// let m = Command::new("prog") /// .arg(Arg::new("flag") /// .long("flag") /// .env("MY_FLAG") /// .action(ArgAction::Set)) /// .get_matches_from(vec![ /// "prog" /// ]); /// /// assert_eq!(m.get_one::("flag").unwrap(), "env"); /// ``` /// /// In this example, because `prog` is a flag that accepts an optional, case-insensitive /// boolean literal. /// /// Note that the value parser controls how flags are parsed. In this case we've selected /// [`FalseyValueParser`][crate::builder::FalseyValueParser]. A `false` literal is `n`, `no`, /// `f`, `false`, `off` or `0`. An absent environment variable will also be considered as /// `false`. Anything else will considered as `true`. /// /// ```rust /// # use clap_builder as clap; /// # use std::env; /// # use clap::{Command, Arg, ArgAction}; /// # use clap::builder::FalseyValueParser; /// /// env::set_var("TRUE_FLAG", "true"); /// env::set_var("FALSE_FLAG", "0"); /// /// let m = Command::new("prog") /// .arg(Arg::new("true_flag") /// .long("true_flag") /// .action(ArgAction::SetTrue) /// .value_parser(FalseyValueParser::new()) /// .env("TRUE_FLAG")) /// .arg(Arg::new("false_flag") /// .long("false_flag") /// .action(ArgAction::SetTrue) /// .value_parser(FalseyValueParser::new()) /// .env("FALSE_FLAG")) /// .arg(Arg::new("absent_flag") /// .long("absent_flag") /// .action(ArgAction::SetTrue) /// .value_parser(FalseyValueParser::new()) /// .env("ABSENT_FLAG")) /// .get_matches_from(vec![ /// "prog" /// ]); /// /// assert!(m.get_flag("true_flag")); /// assert!(!m.get_flag("false_flag")); /// assert!(!m.get_flag("absent_flag")); /// ``` /// /// In this example, we show the variable coming from an option on the CLI: /// /// ```rust /// # use clap_builder as clap; /// # use std::env; /// # use clap::{Command, Arg, ArgAction}; /// /// env::set_var("MY_FLAG", "env"); /// /// let m = Command::new("prog") /// .arg(Arg::new("flag") /// .long("flag") /// .env("MY_FLAG") /// .action(ArgAction::Set)) /// .get_matches_from(vec![ /// "prog", "--flag", "opt" /// ]); /// /// assert_eq!(m.get_one::("flag").unwrap(), "opt"); /// ``` /// /// In this example, we show the variable coming from the environment even with the /// presence of a default: /// /// ```rust /// # use clap_builder as clap; /// # use std::env; /// # use clap::{Command, Arg, ArgAction}; /// /// env::set_var("MY_FLAG", "env"); /// /// let m = Command::new("prog") /// .arg(Arg::new("flag") /// .long("flag") /// .env("MY_FLAG") /// .action(ArgAction::Set) /// .default_value("default")) /// .get_matches_from(vec![ /// "prog" /// ]); /// /// assert_eq!(m.get_one::("flag").unwrap(), "env"); /// ``` /// /// In this example, we show the use of multiple values in a single environment variable: /// /// ```rust /// # use clap_builder as clap; /// # use std::env; /// # use clap::{Command, Arg, ArgAction}; /// /// env::set_var("MY_FLAG_MULTI", "env1,env2"); /// /// let m = Command::new("prog") /// .arg(Arg::new("flag") /// .long("flag") /// .env("MY_FLAG_MULTI") /// .action(ArgAction::Set) /// .num_args(1..) /// .value_delimiter(',')) /// .get_matches_from(vec![ /// "prog" /// ]); /// /// assert_eq!(m.get_many::("flag").unwrap().collect::>(), vec!["env1", "env2"]); /// ``` /// [`Arg::action(ArgAction::Set)`]: Arg::action() /// [`Arg::value_delimiter(',')`]: Arg::value_delimiter() #[cfg(feature = "env")] #[inline] #[must_use] pub fn env(mut self, name: impl IntoResettable) -> Self { if let Some(name) = name.into_resettable().into_option() { let value = env::var_os(&name); self.env = Some((name, value)); } else { self.env = None; } self } #[cfg(feature = "env")] #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Arg::env`") )] pub fn env_os(self, name: impl Into) -> Self { self.env(name) } } /// # Help impl Arg { /// Sets the description of the argument for short help (`-h`). /// /// Typically, this is a short (one line) description of the arg. /// /// If [`Arg::long_help`] is not specified, this message will be displayed for `--help`. /// ///
/// /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise /// ///
/// /// # Examples /// /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to /// include a newline in the help text and have the following text be properly aligned with all /// the other help text. /// /// Setting `help` displays a short message to the side of the argument when the user passes /// `-h` or `--help` (by default). /// /// ```rust /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let m = Command::new("prog") /// .arg(Arg::new("cfg") /// .long("config") /// .help("Some help text describing the --config arg")) /// .get_matches_from(vec![ /// "prog", "--help" /// ]); /// # } /// ``` /// /// The above example displays /// /// ```notrust /// helptest /// /// Usage: helptest [OPTIONS] /// /// Options: /// --config Some help text describing the --config arg /// -h, --help Print help information /// -V, --version Print version information /// ``` /// [`Arg::long_help`]: Arg::long_help() #[inline] #[must_use] pub fn help(mut self, h: impl IntoResettable) -> Self { self.help = h.into_resettable().into_option(); self } /// Sets the description of the argument for long help (`--help`). /// /// Typically this a more detailed (multi-line) message /// that describes the arg. /// /// If [`Arg::help`] is not specified, this message will be displayed for `-h`. /// ///
/// /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise /// ///
/// /// # Examples /// /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to /// include a newline in the help text and have the following text be properly aligned with all /// the other help text. /// /// Setting `help` displays a short message to the side of the argument when the user passes /// `-h` or `--help` (by default). /// /// ```rust /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let m = Command::new("prog") /// .arg(Arg::new("cfg") /// .long("config") /// .long_help( /// "The config file used by the myprog must be in JSON format /// with only valid keys and may not contain other nonsense /// that cannot be read by this program. Obviously I'm going on /// and on, so I'll stop now.")) /// .get_matches_from(vec![ /// "prog", "--help" /// ]); /// # } /// ``` /// /// The above example displays /// /// ```text /// prog /// /// Usage: prog [OPTIONS] /// /// Options: /// --config /// The config file used by the myprog must be in JSON format /// with only valid keys and may not contain other nonsense /// that cannot be read by this program. Obviously I'm going on /// and on, so I'll stop now. /// /// -h, --help /// Print help information /// /// -V, --version /// Print version information /// ``` /// [`Arg::help`]: Arg::help() #[inline] #[must_use] pub fn long_help(mut self, h: impl IntoResettable) -> Self { self.long_help = h.into_resettable().into_option(); self } /// Allows custom ordering of args within the help message. /// /// `Arg`s with a lower value will be displayed first in the help message. /// Those with the same display order will be sorted. /// /// `Arg`s are automatically assigned a display order based on the order they are added to the /// [`Command`][crate::Command]. /// Overriding this is helpful when the order arguments are added in isn't the same as the /// display order, whether in one-off cases or to automatically sort arguments. /// /// To change, see [`Command::next_display_order`][crate::Command::next_display_order]. /// ///
/// /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in /// [index] order. /// ///
/// /// # Examples /// /// ```rust /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("boat") /// .short('b') /// .long("boat") /// .action(ArgAction::Set) /// .display_order(0) // Sort /// .help("Some help and text")) /// .arg(Arg::new("airplane") /// .short('a') /// .long("airplane") /// .action(ArgAction::Set) /// .display_order(0) // Sort /// .help("I should be first!")) /// .arg(Arg::new("custom-help") /// .short('?') /// .action(ArgAction::Help) /// .display_order(100) // Don't sort /// .help("Alt help")) /// .get_matches_from(vec![ /// "prog", "--help" /// ]); /// # } /// ``` /// /// The above example displays the following help message /// /// ```text /// cust-ord /// /// Usage: cust-ord [OPTIONS] /// /// Options: /// -a, --airplane I should be first! /// -b, --boat Some help and text /// -h, --help Print help information /// -? Alt help /// ``` /// [positional arguments]: Arg::index() /// [index]: Arg::index() #[inline] #[must_use] pub fn display_order(mut self, ord: impl IntoResettable) -> Self { self.disp_ord = ord.into_resettable().into_option(); self } /// Override the [current] help section. /// /// [current]: crate::Command::next_help_heading #[inline] #[must_use] pub fn help_heading(mut self, heading: impl IntoResettable) -> Self { self.help_heading = Some(heading.into_resettable().into_option()); self } /// Render the [help][Arg::help] on the line after the argument. /// /// This can be helpful for arguments with very long or complex help messages. /// This can also be helpful for arguments with very long flag names, or many/long value names. /// ///
/// /// **NOTE:** To apply this setting to all arguments and subcommands, consider using /// [`crate::Command::next_line_help`] /// ///
/// /// # Examples /// /// ```rust /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("opt") /// .long("long-option-flag") /// .short('o') /// .action(ArgAction::Set) /// .next_line_help(true) /// .value_names(["value1", "value2"]) /// .help("Some really long help and complex\n\ /// help that makes more sense to be\n\ /// on a line after the option")) /// .get_matches_from(vec![ /// "prog", "--help" /// ]); /// # } /// ``` /// /// The above example displays the following help message /// /// ```text /// nlh /// /// Usage: nlh [OPTIONS] /// /// Options: /// -h, --help Print help information /// -V, --version Print version information /// -o, --long-option-flag /// Some really long help and complex /// help that makes more sense to be /// on a line after the option /// ``` #[inline] #[must_use] pub fn next_line_help(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::NextLineHelp) } else { self.unset_setting(ArgSettings::NextLineHelp) } } /// Do not display the argument in help message. /// ///
/// /// **NOTE:** This does **not** hide the argument from usage strings on error /// ///
/// /// # Examples /// /// Setting `Hidden` will hide the argument when displaying help text /// /// ```rust /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let m = Command::new("prog") /// .arg(Arg::new("cfg") /// .long("config") /// .hide(true) /// .help("Some help text describing the --config arg")) /// .get_matches_from(vec![ /// "prog", "--help" /// ]); /// # } /// ``` /// /// The above example displays /// /// ```text /// helptest /// /// Usage: helptest [OPTIONS] /// /// Options: /// -h, --help Print help information /// -V, --version Print version information /// ``` #[inline] #[must_use] pub fn hide(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::Hidden) } else { self.unset_setting(ArgSettings::Hidden) } } /// Do not display the [possible values][crate::builder::ValueParser::possible_values] in the help message. /// /// This is useful for args with many values, or ones which are explained elsewhere in the /// help text. /// /// To set this for all arguments, see /// [`Command::hide_possible_values`][crate::Command::hide_possible_values]. /// ///
/// /// **NOTE:** Setting this requires [taking values][Arg::num_args] /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("mode") /// .long("mode") /// .value_parser(["fast", "slow"]) /// .action(ArgAction::Set) /// .hide_possible_values(true)); /// ``` /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of /// the help text would be omitted. #[inline] #[must_use] pub fn hide_possible_values(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::HidePossibleValues) } else { self.unset_setting(ArgSettings::HidePossibleValues) } } /// Do not display the default value of the argument in the help message. /// /// This is useful when default behavior of an arg is explained elsewhere in the help text. /// ///
/// /// **NOTE:** Setting this requires [taking values][Arg::num_args] /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("connect") /// .arg(Arg::new("host") /// .long("host") /// .default_value("localhost") /// .action(ArgAction::Set) /// .hide_default_value(true)); /// /// ``` /// /// If we were to run the above program with `--help` the `[default: localhost]` portion of /// the help text would be omitted. #[inline] #[must_use] pub fn hide_default_value(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::HideDefaultValue) } else { self.unset_setting(ArgSettings::HideDefaultValue) } } /// Do not display in help the environment variable name. /// /// This is useful when the variable option is explained elsewhere in the help text. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("mode") /// .long("mode") /// .env("MODE") /// .action(ArgAction::Set) /// .hide_env(true)); /// ``` /// /// If we were to run the above program with `--help` the `[env: MODE]` portion of the help /// text would be omitted. #[cfg(feature = "env")] #[inline] #[must_use] pub fn hide_env(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::HideEnv) } else { self.unset_setting(ArgSettings::HideEnv) } } /// Do not display in help any values inside the associated ENV variables for the argument. /// /// This is useful when ENV vars contain sensitive values. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("connect") /// .arg(Arg::new("host") /// .long("host") /// .env("CONNECT") /// .action(ArgAction::Set) /// .hide_env_values(true)); /// /// ``` /// /// If we were to run the above program with `$ CONNECT=super_secret connect --help` the /// `[default: CONNECT=super_secret]` portion of the help text would be omitted. #[cfg(feature = "env")] #[inline] #[must_use] pub fn hide_env_values(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::HideEnvValues) } else { self.unset_setting(ArgSettings::HideEnvValues) } } /// Hides an argument from short help (`-h`). /// ///
/// /// **NOTE:** This does **not** hide the argument from usage strings on error /// ///
/// ///
/// /// **NOTE:** Setting this option will cause next-line-help output style to be used /// when long help (`--help`) is called. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # 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 /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # 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 /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # 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 /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # 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 /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let m = Command::new("prog") /// .arg(Arg::new("cfg") /// .long("config") /// .hide_long_help(true) /// .help("Some help text describing the --config arg")) /// .get_matches_from(vec![ /// "prog", "-h" /// ]); /// # } /// ``` /// /// Then the following would be displayed /// /// ```text /// helptest /// /// Usage: helptest [OPTIONS] /// /// OPTIONS: /// --config Some help text describing the --config arg /// -h, --help Print help information /// -V, --version Print version information /// ``` #[inline] #[must_use] pub fn hide_long_help(self, yes: bool) -> Self { if yes { self.setting(ArgSettings::HiddenLongHelp) } else { self.unset_setting(ArgSettings::HiddenLongHelp) } } } /// # Advanced Argument Relations impl Arg { /// The name of the [`ArgGroup`] the argument belongs to. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// Arg::new("debug") /// .long("debug") /// .action(ArgAction::SetTrue) /// .group("mode") /// # ; /// ``` /// /// Multiple arguments can be a member of a single group and then the group checked as if it /// was one of said arguments. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("debug") /// .long("debug") /// .action(ArgAction::SetTrue) /// .group("mode")) /// .arg(Arg::new("verbose") /// .long("verbose") /// .action(ArgAction::SetTrue) /// .group("mode")) /// .get_matches_from(vec![ /// "prog", "--debug" /// ]); /// assert!(m.contains_id("mode")); /// ``` /// /// [`ArgGroup`]: crate::ArgGroup #[must_use] pub fn group(mut self, group_id: impl IntoResettable) -> Self { if let Some(group_id) = group_id.into_resettable().into_option() { self.groups.push(group_id); } else { self.groups.clear(); } self } /// The names of [`ArgGroup`]'s the argument belongs to. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// Arg::new("debug") /// .long("debug") /// .action(ArgAction::SetTrue) /// .groups(["mode", "verbosity"]) /// # ; /// ``` /// /// Arguments can be members of multiple groups and then the group checked as if it /// was one of said arguments. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("debug") /// .long("debug") /// .action(ArgAction::SetTrue) /// .groups(["mode", "verbosity"])) /// .arg(Arg::new("verbose") /// .long("verbose") /// .action(ArgAction::SetTrue) /// .groups(["mode", "verbosity"])) /// .get_matches_from(vec![ /// "prog", "--debug" /// ]); /// assert!(m.contains_id("mode")); /// assert!(m.contains_id("verbosity")); /// ``` /// /// [`ArgGroup`]: crate::ArgGroup #[must_use] pub fn groups(mut self, group_ids: impl IntoIterator>) -> Self { self.groups.extend(group_ids.into_iter().map(Into::into)); self } /// Specifies the value of the argument if `arg` has been used at runtime. /// /// If `default` is set to `None`, `default_value` will be removed. /// /// Like with command-line values, this will be split by [`Arg::value_delimiter`]. /// ///
/// /// **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. /// ///
/// /// # Examples /// /// First we use the default value only if another arg is present at runtime. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// # use clap::builder::{ArgPredicate}; /// let m = Command::new("prog") /// .arg(Arg::new("flag") /// .long("flag") /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("other") /// .long("other") /// .default_value_if("flag", ArgPredicate::IsPresent, Some("default"))) /// .get_matches_from(vec![ /// "prog", "--flag" /// ]); /// /// assert_eq!(m.get_one::("other").unwrap(), "default"); /// ``` /// /// Next we run the same test, but without providing `--flag`. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("flag") /// .long("flag") /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("other") /// .long("other") /// .default_value_if("flag", "true", Some("default"))) /// .get_matches_from(vec![ /// "prog" /// ]); /// /// assert_eq!(m.get_one::("other"), None); /// ``` /// /// Now lets only use the default value if `--opt` contains the value `special`. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("opt") /// .action(ArgAction::Set) /// .long("opt")) /// .arg(Arg::new("other") /// .long("other") /// .default_value_if("opt", "special", Some("default"))) /// .get_matches_from(vec![ /// "prog", "--opt", "special" /// ]); /// /// assert_eq!(m.get_one::("other").unwrap(), "default"); /// ``` /// /// We can run the same test and provide any value *other than* `special` and we won't get a /// default value. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("opt") /// .action(ArgAction::Set) /// .long("opt")) /// .arg(Arg::new("other") /// .long("other") /// .default_value_if("opt", "special", Some("default"))) /// .get_matches_from(vec![ /// "prog", "--opt", "hahaha" /// ]); /// /// assert_eq!(m.get_one::("other"), None); /// ``` /// /// If we want to unset the default value for an Arg based on the presence or /// value of some other Arg. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("flag") /// .long("flag") /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("other") /// .long("other") /// .default_value("default") /// .default_value_if("flag", "true", None)) /// .get_matches_from(vec![ /// "prog", "--flag" /// ]); /// /// assert_eq!(m.get_one::("other"), None); /// ``` /// [`Arg::action(ArgAction::Set)`]: Arg::action() /// [`Arg::default_value`]: Arg::default_value() #[must_use] pub fn default_value_if( mut self, arg_id: impl Into, predicate: impl Into, default: impl IntoResettable, ) -> Self { self.default_vals_ifs.push(( arg_id.into(), predicate.into(), default.into_resettable().into_option(), )); self } #[must_use] #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_if`") )] pub fn default_value_if_os( self, arg_id: impl Into, predicate: impl Into, default: impl IntoResettable, ) -> Self { self.default_value_if(arg_id, predicate, default) } /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`]. /// /// The method takes a slice of tuples in the `(arg, predicate, default)` format. /// /// Like with command-line values, this will be split by [`Arg::value_delimiter`]. /// ///
/// /// **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_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("flag") /// .long("flag") /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("opt") /// .long("opt") /// .action(ArgAction::Set)) /// .arg(Arg::new("other") /// .long("other") /// .default_value_ifs([ /// ("flag", "true", Some("default")), /// ("opt", "channal", Some("chan")), /// ])) /// .get_matches_from(vec![ /// "prog", "--opt", "channal" /// ]); /// /// assert_eq!(m.get_one::("other").unwrap(), "chan"); /// ``` /// /// Next we run the same test, but without providing `--flag`. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let m = Command::new("prog") /// .arg(Arg::new("flag") /// .long("flag") /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("other") /// .long("other") /// .default_value_ifs([ /// ("flag", "true", Some("default")), /// ("opt", "channal", Some("chan")), /// ])) /// .get_matches_from(vec![ /// "prog" /// ]); /// /// assert_eq!(m.get_one::("other"), None); /// ``` /// /// We can also see that these values are applied in order, and if more than one condition is /// true, only the first evaluated "wins" /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// # use clap::builder::ArgPredicate; /// let m = Command::new("prog") /// .arg(Arg::new("flag") /// .long("flag") /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("opt") /// .long("opt") /// .action(ArgAction::Set)) /// .arg(Arg::new("other") /// .long("other") /// .default_value_ifs([ /// ("flag", ArgPredicate::IsPresent, Some("default")), /// ("opt", ArgPredicate::Equals("channal".into()), Some("chan")), /// ])) /// .get_matches_from(vec![ /// "prog", "--opt", "channal", "--flag" /// ]); /// /// assert_eq!(m.get_one::("other").unwrap(), "default"); /// ``` /// [`Arg::action(ArgAction::Set)`]: Arg::action() /// [`Arg::default_value_if`]: Arg::default_value_if() #[must_use] pub fn default_value_ifs( mut self, ifs: impl IntoIterator< Item = ( impl Into, impl Into, impl IntoResettable, ), >, ) -> Self { for (arg, predicate, default) in ifs { self = self.default_value_if(arg, predicate, default); } self } #[must_use] #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_ifs`") )] pub fn default_value_ifs_os( self, ifs: impl IntoIterator< Item = ( impl Into, impl Into, impl IntoResettable, ), >, ) -> Self { self.default_value_ifs(ifs) } /// Set this arg as [required] as long as the specified argument is not present at runtime. /// ///
/// /// **TIP:** Using `Arg::required_unless_present` implies [`Arg::required`] and is therefore not /// mandatory to also set. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # 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_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .required_unless_present("dbg") /// .action(ArgAction::Set) /// .long("config")) /// .arg(Arg::new("dbg") /// .long("debug") /// .action(ArgAction::SetTrue)) /// .try_get_matches_from(vec![ /// "prog", "--debug" /// ]); /// /// assert!(res.is_ok()); /// ``` /// /// Setting `Arg::required_unless_present(name)` and *not* supplying `name` or this arg is an error. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .required_unless_present("dbg") /// .action(ArgAction::Set) /// .long("config")) /// .arg(Arg::new("dbg") /// .long("debug")) /// .try_get_matches_from(vec![ /// "prog" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); /// ``` /// [required]: Arg::required() #[must_use] pub fn required_unless_present(mut self, arg_id: impl IntoResettable) -> Self { if let Some(arg_id) = arg_id.into_resettable().into_option() { self.r_unless.push(arg_id); } else { self.r_unless.clear(); } self } /// Sets this arg as [required] unless *all* of the specified arguments are present at runtime. /// /// In other words, parsing will succeed only if user either /// * supplies the `self` arg. /// * supplies *all* of the `names` arguments. /// ///
/// /// **NOTE:** If you wish for this argument to only be required unless *any of* these args are /// present see [`Arg::required_unless_present_any`] /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # 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_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .required_unless_present_all(["dbg", "infile"]) /// .action(ArgAction::Set) /// .long("config")) /// .arg(Arg::new("dbg") /// .long("debug") /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("infile") /// .short('i') /// .action(ArgAction::Set)) /// .try_get_matches_from(vec![ /// "prog", "--debug", "-i", "file" /// ]); /// /// assert!(res.is_ok()); /// ``` /// /// Setting [`Arg::required_unless_present_all(names)`] and *not* supplying /// either *all* of `unless` args or the `self` arg is an error. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .required_unless_present_all(["dbg", "infile"]) /// .action(ArgAction::Set) /// .long("config")) /// .arg(Arg::new("dbg") /// .long("debug") /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("infile") /// .short('i') /// .action(ArgAction::Set)) /// .try_get_matches_from(vec![ /// "prog" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); /// ``` /// [required]: Arg::required() /// [`Arg::required_unless_present_any`]: Arg::required_unless_present_any() /// [`Arg::required_unless_present_all(names)`]: Arg::required_unless_present_all() #[must_use] pub fn required_unless_present_all( mut self, names: impl IntoIterator>, ) -> Self { self.r_unless_all.extend(names.into_iter().map(Into::into)); self } /// Sets this arg as [required] unless *any* of the specified arguments are present at runtime. /// /// In other words, parsing will succeed only if user either /// * supplies the `self` arg. /// * supplies *one or more* of the `unless` arguments. /// ///
/// /// **NOTE:** If you wish for this argument to be required unless *all of* these args are /// present see [`Arg::required_unless_present_all`] /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # 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_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .required_unless_present_any(["dbg", "infile"]) /// .action(ArgAction::Set) /// .long("config")) /// .arg(Arg::new("dbg") /// .long("debug") /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("infile") /// .short('i') /// .action(ArgAction::Set)) /// .try_get_matches_from(vec![ /// "prog", "--debug" /// ]); /// /// assert!(res.is_ok()); /// ``` /// /// Setting [`Arg::required_unless_present_any(names)`] and *not* supplying *at least one of* `names` /// or this arg is an error. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .required_unless_present_any(["dbg", "infile"]) /// .action(ArgAction::Set) /// .long("config")) /// .arg(Arg::new("dbg") /// .long("debug") /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("infile") /// .short('i') /// .action(ArgAction::Set)) /// .try_get_matches_from(vec![ /// "prog" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); /// ``` /// [required]: Arg::required() /// [`Arg::required_unless_present_any(names)`]: Arg::required_unless_present_any() /// [`Arg::required_unless_present_all`]: Arg::required_unless_present_all() #[must_use] pub fn required_unless_present_any( mut self, names: impl IntoIterator>, ) -> Self { self.r_unless.extend(names.into_iter().map(Into::into)); self } /// This argument is [required] only if the specified `arg` is present at runtime and its value /// equals `val`. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Arg; /// Arg::new("config") /// .required_if_eq("other_arg", "value") /// # ; /// ``` /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .required_if_eq("other", "special") /// .long("config")) /// .arg(Arg::new("other") /// .long("other") /// .action(ArgAction::Set)) /// .try_get_matches_from(vec![ /// "prog", "--other", "not-special" /// ]); /// /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required /// /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .required_if_eq("other", "special") /// .long("config")) /// .arg(Arg::new("other") /// .long("other") /// .action(ArgAction::Set)) /// .try_get_matches_from(vec![ /// "prog", "--other", "special" /// ]); /// /// // We did use --other=special so "cfg" had become required but was missing. /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); /// /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .required_if_eq("other", "special") /// .long("config")) /// .arg(Arg::new("other") /// .long("other") /// .action(ArgAction::Set)) /// .try_get_matches_from(vec![ /// "prog", "--other", "SPECIAL" /// ]); /// /// // By default, the comparison is case-sensitive, so "cfg" wasn't required /// assert!(res.is_ok()); /// /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .required_if_eq("other", "special") /// .long("config")) /// .arg(Arg::new("other") /// .long("other") /// .ignore_case(true) /// .action(ArgAction::Set)) /// .try_get_matches_from(vec![ /// "prog", "--other", "SPECIAL" /// ]); /// /// // However, case-insensitive comparisons can be enabled. This typically occurs when using Arg::possible_values(). /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); /// ``` /// [`Arg::requires(name)`]: Arg::requires() /// [Conflicting]: Arg::conflicts_with() /// [required]: Arg::required() #[must_use] pub fn required_if_eq(mut self, arg_id: impl Into, val: impl Into) -> Self { self.r_ifs.push((arg_id.into(), val.into())); self } /// Specify this argument is [required] based on multiple conditions. /// /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become /// valid if one of the specified `arg`'s value equals its corresponding `val`. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # 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_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .required_if_eq_any([ /// ("extra", "val"), /// ("option", "spec") /// ]) /// .action(ArgAction::Set) /// .long("config")) /// .arg(Arg::new("extra") /// .action(ArgAction::Set) /// .long("extra")) /// .arg(Arg::new("option") /// .action(ArgAction::Set) /// .long("option")) /// .try_get_matches_from(vec![ /// "prog", "--option", "other" /// ]); /// /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required /// ``` /// /// Setting `Arg::required_if_eq_any([(arg, val)])` and having any of the `arg`s used with its /// value of `val` but *not* using this arg is an error. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .required_if_eq_any([ /// ("extra", "val"), /// ("option", "spec") /// ]) /// .action(ArgAction::Set) /// .long("config")) /// .arg(Arg::new("extra") /// .action(ArgAction::Set) /// .long("extra")) /// .arg(Arg::new("option") /// .action(ArgAction::Set) /// .long("option")) /// .try_get_matches_from(vec![ /// "prog", "--option", "spec" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); /// ``` /// [`Arg::requires(name)`]: Arg::requires() /// [Conflicting]: Arg::conflicts_with() /// [required]: Arg::required() #[must_use] pub fn required_if_eq_any( mut self, ifs: impl IntoIterator, impl Into)>, ) -> Self { self.r_ifs .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into()))); self } /// Specify this argument is [required] based on multiple conditions. /// /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become /// valid if every one of the specified `arg`'s value equals its corresponding `val`. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # 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_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .required_if_eq_all([ /// ("extra", "val"), /// ("option", "spec") /// ]) /// .action(ArgAction::Set) /// .long("config")) /// .arg(Arg::new("extra") /// .action(ArgAction::Set) /// .long("extra")) /// .arg(Arg::new("option") /// .action(ArgAction::Set) /// .long("option")) /// .try_get_matches_from(vec![ /// "prog", "--option", "spec" /// ]); /// /// assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required /// ``` /// /// Setting `Arg::required_if_eq_all([(arg, val)])` and having all of the `arg`s used with its /// value of `val` but *not* using this arg is an error. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .required_if_eq_all([ /// ("extra", "val"), /// ("option", "spec") /// ]) /// .action(ArgAction::Set) /// .long("config")) /// .arg(Arg::new("extra") /// .action(ArgAction::Set) /// .long("extra")) /// .arg(Arg::new("option") /// .action(ArgAction::Set) /// .long("option")) /// .try_get_matches_from(vec![ /// "prog", "--extra", "val", "--option", "spec" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); /// ``` /// [required]: Arg::required() #[must_use] pub fn required_if_eq_all( mut self, ifs: impl IntoIterator, impl Into)>, ) -> Self { self.r_ifs_all .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into()))); self } /// Require another argument if this arg matches the [`ArgPredicate`] /// /// This method takes `value, another_arg` pair. At runtime, clap will check /// if this arg (`self`) matches the [`ArgPredicate`]. /// If it does, `another_arg` will be marked as required. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # 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_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .requires_if("my.cfg", "other") /// .long("config")) /// .arg(Arg::new("other")) /// .try_get_matches_from(vec![ /// "prog", "--config", "some.cfg" /// ]); /// /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required /// ``` /// /// Setting `Arg::requires_if(val, arg)` and setting the value to `val` but *not* supplying /// `arg` is an error. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .requires_if("my.cfg", "input") /// .long("config")) /// .arg(Arg::new("input")) /// .try_get_matches_from(vec![ /// "prog", "--config", "my.cfg" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); /// ``` /// [`Arg::requires(name)`]: Arg::requires() /// [Conflicting]: Arg::conflicts_with() /// [override]: Arg::overrides_with() #[must_use] pub fn requires_if(mut self, val: impl Into, arg_id: impl Into) -> Self { self.requires.push((val.into(), arg_id.into())); self } /// Allows multiple conditional requirements. /// /// The requirement will only become valid if this arg's value matches the /// [`ArgPredicate`]. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # 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_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .requires_ifs([ /// ("special.conf", "opt"), /// ("other.conf", "other"), /// ]) /// .long("config")) /// .arg(Arg::new("opt") /// .long("option") /// .action(ArgAction::Set)) /// .arg(Arg::new("other")) /// .try_get_matches_from(vec![ /// "prog", "--config", "special.conf" /// ]); /// /// assert!(res.is_err()); // We used --config=special.conf so --option is required /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); /// ``` /// /// Setting `Arg::requires_ifs` with [`ArgPredicate::IsPresent`] and *not* supplying all the /// arguments is an error. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction, builder::ArgPredicate}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .requires_ifs([ /// (ArgPredicate::IsPresent, "input"), /// (ArgPredicate::IsPresent, "output"), /// ]) /// .long("config")) /// .arg(Arg::new("input")) /// .arg(Arg::new("output")) /// .try_get_matches_from(vec![ /// "prog", "--config", "file.conf", "in.txt" /// ]); /// /// assert!(res.is_err()); /// // We didn't use output /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); /// ``` /// /// [`Arg::requires(name)`]: Arg::requires() /// [Conflicting]: Arg::conflicts_with() /// [override]: Arg::overrides_with() #[must_use] pub fn requires_ifs( mut self, ifs: impl IntoIterator, impl Into)>, ) -> Self { self.requires .extend(ifs.into_iter().map(|(val, arg)| (val.into(), arg.into()))); self } #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Arg::requires_ifs`") )] pub fn requires_all(self, ids: impl IntoIterator>) -> Self { self.requires_ifs(ids.into_iter().map(|id| (ArgPredicate::IsPresent, id))) } /// This argument is mutually exclusive with the specified argument. /// ///
/// /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules /// only need to be set for one of the two arguments, they do not need to be set for each. /// ///
/// ///
/// /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments /// (i.e. if A conflicts with B, defining `A.conflicts_with(B)` is sufficient. You do not /// need to also do `B.conflicts_with(A)`) /// ///
/// ///
/// /// **NOTE:** [`Arg::conflicts_with_all(names)`] allows specifying an argument which conflicts with more than one argument. /// ///
/// ///
/// /// **NOTE** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. /// ///
/// ///
/// /// **NOTE:** All arguments implicitly conflict with themselves. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # 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_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .conflicts_with("debug") /// .long("config")) /// .arg(Arg::new("debug") /// .long("debug") /// .action(ArgAction::SetTrue)) /// .try_get_matches_from(vec![ /// "prog", "--debug", "--config", "file.conf" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); /// ``` /// /// [`Arg::conflicts_with_all(names)`]: Arg::conflicts_with_all() /// [`Arg::exclusive(true)`]: Arg::exclusive() #[must_use] pub fn conflicts_with(mut self, arg_id: impl IntoResettable) -> Self { if let Some(arg_id) = arg_id.into_resettable().into_option() { self.blacklist.push(arg_id); } else { self.blacklist.clear(); } self } /// This argument is mutually exclusive with the specified arguments. /// /// See [`Arg::conflicts_with`]. /// ///
/// /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules /// only need to be set for one of the two arguments, they do not need to be set for each. /// ///
/// ///
/// /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments /// (i.e. if A conflicts with B, defining `A.conflicts_with(B)` is sufficient. You do not need /// need to also do `B.conflicts_with(A)`) /// ///
/// ///
/// /// **NOTE:** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # 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_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; /// let res = Command::new("prog") /// .arg(Arg::new("cfg") /// .action(ArgAction::Set) /// .conflicts_with_all(["debug", "input"]) /// .long("config")) /// .arg(Arg::new("debug") /// .long("debug")) /// .arg(Arg::new("input")) /// .try_get_matches_from(vec![ /// "prog", "--config", "file.conf", "file.txt" /// ]); /// /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); /// ``` /// [`Arg::conflicts_with`]: Arg::conflicts_with() /// [`Arg::exclusive(true)`]: Arg::exclusive() #[must_use] pub fn conflicts_with_all(mut self, names: impl IntoIterator>) -> Self { self.blacklist.extend(names.into_iter().map(Into::into)); self } /// Sets an overridable argument. /// /// i.e. this argument and the following argument /// will override each other in POSIX style (whichever argument was specified at runtime /// **last** "wins") /// ///
/// /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed /// ///
/// ///
/// /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with`]. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg}; /// let m = Command::new("prog") /// .arg(arg!(-f --flag "some flag") /// .conflicts_with("debug")) /// .arg(arg!(-d --debug "other flag")) /// .arg(arg!(-c --color "third flag") /// .overrides_with("flag")) /// .get_matches_from(vec![ /// "prog", "-f", "-d", "-c"]); /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color /// /// assert!(m.get_flag("color")); /// assert!(m.get_flag("debug")); // even though flag conflicts with debug, it's as if flag /// // was never used because it was overridden with color /// assert!(!m.get_flag("flag")); /// ``` #[must_use] pub fn overrides_with(mut self, arg_id: impl IntoResettable) -> Self { if let Some(arg_id) = arg_id.into_resettable().into_option() { self.overrides.push(arg_id); } else { self.overrides.clear(); } self } /// Sets multiple mutually overridable arguments by name. /// /// i.e. this argument and the following argument will override each other in POSIX style /// (whichever argument was specified at runtime **last** "wins") /// ///
/// /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed /// ///
/// ///
/// /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with_all`]. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg}; /// let m = Command::new("prog") /// .arg(arg!(-f --flag "some flag") /// .conflicts_with("color")) /// .arg(arg!(-d --debug "other flag")) /// .arg(arg!(-c --color "third flag") /// .overrides_with_all(["flag", "debug"])) /// .get_matches_from(vec![ /// "prog", "-f", "-d", "-c"]); /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color /// /// assert!(m.get_flag("color")); // even though flag conflicts with color, it's as if flag /// // and debug were never used because they were overridden /// // with color /// assert!(!m.get_flag("debug")); /// assert!(!m.get_flag("flag")); /// ``` #[must_use] pub fn overrides_with_all(mut self, names: impl IntoIterator>) -> Self { self.overrides.extend(names.into_iter().map(Into::into)); self } } /// # Reflection impl Arg { /// Get the name of the argument #[inline] pub fn get_id(&self) -> &Id { &self.id } /// Get the help specified for this argument, if any #[inline] pub fn get_help(&self) -> Option<&StyledStr> { self.help.as_ref() } /// Get the long help specified for this argument, if any /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Arg; /// let arg = Arg::new("foo").long_help("long help"); /// assert_eq!(Some("long help".to_owned()), arg.get_long_help().map(|s| s.to_string())); /// ``` /// #[inline] pub fn get_long_help(&self) -> Option<&StyledStr> { self.long_help.as_ref() } /// Get the placement within help #[inline] pub fn get_display_order(&self) -> usize { self.disp_ord.unwrap_or(999) } /// Get the help heading specified for this argument, if any #[inline] pub fn get_help_heading(&self) -> Option<&str> { self.help_heading .as_ref() .map(|s| s.as_deref()) .unwrap_or_default() } /// Get the short option name for this argument, if any #[inline] pub fn get_short(&self) -> Option { self.short } /// Get visible short aliases for this argument, if any #[inline] pub fn get_visible_short_aliases(&self) -> Option> { if self.short_aliases.is_empty() { None } else { Some( self.short_aliases .iter() .filter_map(|(c, v)| if *v { Some(c) } else { None }) .copied() .collect(), ) } } /// Get *all* short aliases for this argument, if any, both visible and hidden. #[inline] pub fn get_all_short_aliases(&self) -> Option> { if self.short_aliases.is_empty() { None } else { Some(self.short_aliases.iter().map(|(s, _)| s).copied().collect()) } } /// Get the short option name and its visible aliases, if any #[inline] pub fn get_short_and_visible_aliases(&self) -> Option> { let mut shorts = match self.short { Some(short) => vec![short], None => return None, }; if let Some(aliases) = self.get_visible_short_aliases() { shorts.extend(aliases); } Some(shorts) } /// Get the long option name for this argument, if any #[inline] pub fn get_long(&self) -> Option<&str> { self.long.as_deref() } /// Get visible aliases for this argument, if any #[inline] pub fn get_visible_aliases(&self) -> Option> { if self.aliases.is_empty() { None } else { Some( self.aliases .iter() .filter_map(|(s, v)| if *v { Some(s.as_str()) } else { None }) .collect(), ) } } /// Get *all* aliases for this argument, if any, both visible and hidden. #[inline] pub fn get_all_aliases(&self) -> Option> { if self.aliases.is_empty() { None } else { Some(self.aliases.iter().map(|(s, _)| s.as_str()).collect()) } } /// Get the long option name and its visible aliases, if any #[inline] pub fn get_long_and_visible_aliases(&self) -> Option> { let mut longs = match self.get_long() { Some(long) => vec![long], None => return None, }; if let Some(aliases) = self.get_visible_aliases() { longs.extend(aliases); } Some(longs) } /// Get hidden aliases for this argument, if any #[inline] pub fn get_aliases(&self) -> Option> { if self.aliases.is_empty() { None } else { Some( self.aliases .iter() .filter_map(|(s, v)| if !*v { Some(s.as_str()) } else { None }) .collect(), ) } } /// Get the names of possible values for this argument. Only useful for user /// facing applications, such as building help messages or man files pub fn get_possible_values(&self) -> Vec { if !self.is_takes_value_set() { vec![] } else { self.get_value_parser() .possible_values() .map(|pvs| pvs.collect()) .unwrap_or_default() } } /// Get the names of values for this argument. #[inline] pub fn get_value_names(&self) -> Option<&[Str]> { if self.val_names.is_empty() { None } else { Some(&self.val_names) } } /// Get the number of values for this argument. #[inline] pub fn get_num_args(&self) -> Option { self.num_vals } #[inline] pub(crate) fn get_min_vals(&self) -> usize { self.get_num_args().expect(INTERNAL_ERROR_MSG).min_values() } /// Get the delimiter between multiple values #[inline] pub fn get_value_delimiter(&self) -> Option { self.val_delim } /// Get the value terminator for this argument. The `value_terminator` is a value /// that terminates parsing of multi-valued arguments. #[inline] pub fn get_value_terminator(&self) -> Option<&Str> { self.terminator.as_ref() } /// Get the index of this argument, if any #[inline] pub fn get_index(&self) -> Option { self.index } /// Get the value hint of this argument pub fn get_value_hint(&self) -> ValueHint { // HACK: we should use `Self::add` and `Self::remove` to type-check that `ArgExt` is used self.ext.get::().copied().unwrap_or_else(|| { if self.is_takes_value_set() { let type_id = self.get_value_parser().type_id(); if type_id == AnyValueId::of::() { ValueHint::AnyPath } else { ValueHint::default() } } else { ValueHint::default() } }) } /// Get the environment variable name specified for this argument, if any /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use std::ffi::OsStr; /// # use clap::Arg; /// let arg = Arg::new("foo").env("ENVIRONMENT"); /// assert_eq!(arg.get_env(), Some(OsStr::new("ENVIRONMENT"))); /// ``` #[cfg(feature = "env")] pub fn get_env(&self) -> Option<&std::ffi::OsStr> { self.env.as_ref().map(|x| x.0.as_os_str()) } /// Get the default values specified for this argument, if any /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Arg; /// let arg = Arg::new("foo").default_value("default value"); /// assert_eq!(arg.get_default_values(), &["default value"]); /// ``` pub fn get_default_values(&self) -> &[OsStr] { &self.default_vals } /// Checks whether this argument is a positional or not. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Arg; /// let arg = Arg::new("foo"); /// assert_eq!(arg.is_positional(), true); /// /// let arg = Arg::new("foo").long("foo"); /// assert_eq!(arg.is_positional(), false); /// ``` pub fn is_positional(&self) -> bool { self.get_long().is_none() && self.get_short().is_none() } /// Reports whether [`Arg::required`] is set pub fn is_required_set(&self) -> bool { self.is_set(ArgSettings::Required) } pub(crate) fn is_multiple_values_set(&self) -> bool { self.get_num_args().unwrap_or_default().is_multiple() } pub(crate) fn is_takes_value_set(&self) -> bool { self.get_num_args() .unwrap_or_else(|| 1.into()) .takes_values() } /// Report whether [`Arg::allow_hyphen_values`] is set pub fn is_allow_hyphen_values_set(&self) -> bool { self.is_set(ArgSettings::AllowHyphenValues) } /// Report whether [`Arg::allow_negative_numbers`] is set pub fn is_allow_negative_numbers_set(&self) -> bool { self.is_set(ArgSettings::AllowNegativeNumbers) } /// Behavior when parsing the argument pub fn get_action(&self) -> &ArgAction { const DEFAULT: ArgAction = ArgAction::Set; self.action.as_ref().unwrap_or(&DEFAULT) } /// Configured parser for argument values /// /// # Example /// /// ```rust /// # use clap_builder as clap; /// let cmd = clap::Command::new("raw") /// .arg( /// clap::Arg::new("port") /// .value_parser(clap::value_parser!(usize)) /// ); /// let value_parser = cmd.get_arguments() /// .find(|a| a.get_id() == "port").unwrap() /// .get_value_parser(); /// println!("{value_parser:?}"); /// ``` pub fn get_value_parser(&self) -> &super::ValueParser { if let Some(value_parser) = self.value_parser.as_ref() { value_parser } else { static DEFAULT: super::ValueParser = super::ValueParser::string(); &DEFAULT } } /// Report whether [`Arg::global`] is set pub fn is_global_set(&self) -> bool { self.is_set(ArgSettings::Global) } /// Report whether [`Arg::next_line_help`] is set pub fn is_next_line_help_set(&self) -> bool { self.is_set(ArgSettings::NextLineHelp) } /// Report whether [`Arg::hide`] is set pub fn is_hide_set(&self) -> bool { self.is_set(ArgSettings::Hidden) } /// Report whether [`Arg::hide_default_value`] is set pub fn is_hide_default_value_set(&self) -> bool { self.is_set(ArgSettings::HideDefaultValue) } /// Report whether [`Arg::hide_possible_values`] is set pub fn is_hide_possible_values_set(&self) -> bool { self.is_set(ArgSettings::HidePossibleValues) } /// Report whether [`Arg::hide_env`] is set #[cfg(feature = "env")] pub fn is_hide_env_set(&self) -> bool { self.is_set(ArgSettings::HideEnv) } /// Report whether [`Arg::hide_env_values`] is set #[cfg(feature = "env")] pub fn is_hide_env_values_set(&self) -> bool { self.is_set(ArgSettings::HideEnvValues) } /// Report whether [`Arg::hide_short_help`] is set pub fn is_hide_short_help_set(&self) -> bool { self.is_set(ArgSettings::HiddenShortHelp) } /// Report whether [`Arg::hide_long_help`] is set pub fn is_hide_long_help_set(&self) -> bool { self.is_set(ArgSettings::HiddenLongHelp) } /// Report whether [`Arg::require_equals`] is set pub fn is_require_equals_set(&self) -> bool { self.is_set(ArgSettings::RequireEquals) } /// Reports whether [`Arg::exclusive`] is set pub fn is_exclusive_set(&self) -> bool { self.is_set(ArgSettings::Exclusive) } /// Report whether [`Arg::trailing_var_arg`] is set pub fn is_trailing_var_arg_set(&self) -> bool { self.is_set(ArgSettings::TrailingVarArg) } /// Reports whether [`Arg::last`] is set pub fn is_last_set(&self) -> bool { self.is_set(ArgSettings::Last) } /// Reports whether [`Arg::ignore_case`] is set pub fn is_ignore_case_set(&self) -> bool { self.is_set(ArgSettings::IgnoreCase) } /// Access an [`ArgExt`] #[cfg(feature = "unstable-ext")] pub fn get(&self) -> Option<&T> { self.ext.get::() } /// Remove an [`ArgExt`] #[cfg(feature = "unstable-ext")] pub fn remove(mut self) -> Option { self.ext.remove::() } } /// # Internally used only impl Arg { pub(crate) fn _build(&mut self) { if self.action.is_none() { if self.num_vals == Some(ValueRange::EMPTY) { let action = ArgAction::SetTrue; self.action = Some(action); } else { let action = if self.is_positional() && self.num_vals.unwrap_or_default().is_unbounded() { // Allow collecting arguments interleaved with flags // // Bounded values are probably a group and the user should explicitly opt-in to // Append ArgAction::Append } else { ArgAction::Set }; self.action = Some(action); } } if let Some(action) = self.action.as_ref() { if let Some(default_value) = action.default_value() { if self.default_vals.is_empty() { self.default_vals = vec![default_value.into()]; } } if let Some(default_value) = action.default_missing_value() { if self.default_missing_vals.is_empty() { self.default_missing_vals = vec![default_value.into()]; } } } if self.value_parser.is_none() { if let Some(default) = self.action.as_ref().and_then(|a| a.default_value_parser()) { self.value_parser = Some(default); } else { self.value_parser = Some(super::ValueParser::string()); } } let val_names_len = self.val_names.len(); if val_names_len > 1 { self.num_vals.get_or_insert(val_names_len.into()); } else { let nargs = self.get_action().default_num_args(); self.num_vals.get_or_insert(nargs); } } // Used for positionals when printing pub(crate) fn name_no_brackets(&self) -> String { debug!("Arg::name_no_brackets:{}", self.get_id()); let delim = " "; if !self.val_names.is_empty() { debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names); if self.val_names.len() > 1 { self.val_names .iter() .map(|n| format!("<{n}>")) .collect::>() .join(delim) } else { self.val_names .first() .expect(INTERNAL_ERROR_MSG) .as_str() .to_owned() } } else { debug!("Arg::name_no_brackets: just name"); self.get_id().as_str().to_owned() } } pub(crate) fn stylized(&self, styles: &Styles, required: Option) -> StyledStr { use std::fmt::Write as _; let literal = styles.get_literal(); let mut styled = StyledStr::new(); // Write the name such --long or -l if let Some(l) = self.get_long() { let _ = write!(styled, "{literal}--{l}{literal:#}",); } else if let Some(s) = self.get_short() { let _ = write!(styled, "{literal}-{s}{literal:#}"); } styled.push_styled(&self.stylize_arg_suffix(styles, required)); styled } pub(crate) fn stylize_arg_suffix(&self, styles: &Styles, required: Option) -> StyledStr { use std::fmt::Write as _; let literal = styles.get_literal(); let placeholder = styles.get_placeholder(); let mut styled = StyledStr::new(); let mut need_closing_bracket = false; if self.is_takes_value_set() && !self.is_positional() { let is_optional_val = self.get_min_vals() == 0; let (style, start) = if self.is_require_equals_set() { if is_optional_val { need_closing_bracket = true; (placeholder, "[=") } else { (literal, "=") } } else if is_optional_val { need_closing_bracket = true; (placeholder, " [") } else { (placeholder, " ") }; let _ = write!(styled, "{style}{start}{style:#}"); } if self.is_takes_value_set() || self.is_positional() { let required = required.unwrap_or_else(|| self.is_required_set()); let arg_val = self.render_arg_val(required); let _ = write!(styled, "{placeholder}{arg_val}{placeholder:#}",); } else if matches!(*self.get_action(), ArgAction::Count) { let _ = write!(styled, "{placeholder}...{placeholder:#}",); } if need_closing_bracket { let _ = write!(styled, "{placeholder}]{placeholder:#}",); } styled } /// Write the values such as ` ` fn render_arg_val(&self, required: bool) -> String { let mut rendered = String::new(); let num_vals = self.get_num_args().unwrap_or_else(|| 1.into()); let mut val_names = if self.val_names.is_empty() { vec![self.id.as_internal_str().to_owned()] } else { self.val_names.clone() }; if val_names.len() == 1 { let min = num_vals.min_values().max(1); let val_name = val_names.pop().unwrap(); val_names = vec![val_name; min]; } debug_assert!(self.is_takes_value_set()); for (n, val_name) in val_names.iter().enumerate() { let arg_name = if self.is_positional() && (num_vals.min_values() == 0 || !required) { format!("[{val_name}]") } else { format!("<{val_name}>") }; if n != 0 { rendered.push(' '); } rendered.push_str(&arg_name); } let mut extra_values = false; extra_values |= val_names.len() < num_vals.max_values(); if self.is_positional() && matches!(*self.get_action(), ArgAction::Append) { extra_values = true; } if extra_values { rendered.push_str("..."); } rendered } /// Either multiple values or occurrences pub(crate) fn is_multiple(&self) -> bool { self.is_multiple_values_set() || matches!(*self.get_action(), ArgAction::Append) } } impl From<&'_ Arg> for Arg { fn from(a: &Arg) -> Self { a.clone() } } impl PartialEq for Arg { fn eq(&self, other: &Arg) -> bool { self.get_id() == other.get_id() } } impl PartialOrd for Arg { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for Arg { fn cmp(&self, other: &Arg) -> Ordering { self.get_id().cmp(other.get_id()) } } impl Eq for Arg {} impl Display for Arg { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let plain = Styles::plain(); self.stylized(&plain, None).fmt(f) } } impl fmt::Debug for Arg { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { let mut ds = f.debug_struct("Arg"); #[allow(unused_mut)] let mut ds = ds .field("id", &self.id) .field("help", &self.help) .field("long_help", &self.long_help) .field("action", &self.action) .field("value_parser", &self.value_parser) .field("blacklist", &self.blacklist) .field("settings", &self.settings) .field("overrides", &self.overrides) .field("groups", &self.groups) .field("requires", &self.requires) .field("r_ifs", &self.r_ifs) .field("r_unless", &self.r_unless) .field("short", &self.short) .field("long", &self.long) .field("aliases", &self.aliases) .field("short_aliases", &self.short_aliases) .field("disp_ord", &self.disp_ord) .field("val_names", &self.val_names) .field("num_vals", &self.num_vals) .field("val_delim", &self.val_delim) .field("default_vals", &self.default_vals) .field("default_vals_ifs", &self.default_vals_ifs) .field("terminator", &self.terminator) .field("index", &self.index) .field("help_heading", &self.help_heading) .field("default_missing_vals", &self.default_missing_vals) .field("ext", &self.ext); #[cfg(feature = "env")] { ds = ds.field("env", &self.env); } ds.finish() } } /// User-provided data that can be attached to an [`Arg`] #[cfg(feature = "unstable-ext")] pub trait ArgExt: Extension {} // Flags #[cfg(test)] mod test { use super::Arg; use super::ArgAction; #[test] fn flag_display_long() { let mut f = Arg::new("flg").long("flag").action(ArgAction::SetTrue); f._build(); assert_eq!(f.to_string(), "--flag"); } #[test] fn flag_display_short() { let mut f2 = Arg::new("flg").short('f').action(ArgAction::SetTrue); f2._build(); assert_eq!(f2.to_string(), "-f"); } #[test] fn flag_display_count() { let mut f2 = Arg::new("flg").long("flag").action(ArgAction::Count); f2._build(); assert_eq!(f2.to_string(), "--flag..."); } #[test] fn flag_display_single_alias() { let mut f = Arg::new("flg") .long("flag") .visible_alias("als") .action(ArgAction::SetTrue); f._build(); assert_eq!(f.to_string(), "--flag"); } #[test] fn flag_display_multiple_aliases() { let mut f = Arg::new("flg").short('f').action(ArgAction::SetTrue); f.aliases = vec![ ("alias_not_visible".into(), false), ("f2".into(), true), ("f3".into(), true), ("f4".into(), true), ]; f._build(); assert_eq!(f.to_string(), "-f"); } #[test] fn flag_display_single_short_alias() { let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue); f.short_aliases = vec![('b', true)]; f._build(); assert_eq!(f.to_string(), "-a"); } #[test] fn flag_display_multiple_short_aliases() { let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue); f.short_aliases = vec![('b', false), ('c', true), ('d', true), ('e', true)]; f._build(); assert_eq!(f.to_string(), "-a"); } // Options #[test] fn option_display_multiple_occurrences() { let mut o = Arg::new("opt").long("option").action(ArgAction::Append); o._build(); assert_eq!(o.to_string(), "--option "); } #[test] fn option_display_multiple_values() { let mut o = Arg::new("opt") .long("option") .action(ArgAction::Set) .num_args(1..); o._build(); assert_eq!(o.to_string(), "--option ..."); } #[test] fn option_display_zero_or_more_values() { let mut o = Arg::new("opt") .long("option") .action(ArgAction::Set) .num_args(0..); o._build(); assert_eq!(o.to_string(), "--option [...]"); } #[test] fn option_display_one_or_more_values() { let mut o = Arg::new("opt") .long("option") .action(ArgAction::Set) .num_args(1..); o._build(); assert_eq!(o.to_string(), "--option ..."); } #[test] fn option_display_zero_or_more_values_with_value_name() { let mut o = Arg::new("opt") .short('o') .action(ArgAction::Set) .num_args(0..) .value_names(["file"]); o._build(); assert_eq!(o.to_string(), "-o [...]"); } #[test] fn option_display_one_or_more_values_with_value_name() { let mut o = Arg::new("opt") .short('o') .action(ArgAction::Set) .num_args(1..) .value_names(["file"]); o._build(); assert_eq!(o.to_string(), "-o ..."); } #[test] fn option_display_optional_value() { let mut o = Arg::new("opt") .long("option") .action(ArgAction::Set) .num_args(0..=1); o._build(); assert_eq!(o.to_string(), "--option []"); } #[test] fn option_display_value_names() { let mut o = Arg::new("opt") .short('o') .action(ArgAction::Set) .value_names(["file", "name"]); o._build(); assert_eq!(o.to_string(), "-o "); } #[test] fn option_display3() { let mut o = Arg::new("opt") .short('o') .num_args(1..) .action(ArgAction::Set) .value_names(["file", "name"]); o._build(); assert_eq!(o.to_string(), "-o ..."); } #[test] fn option_display_single_alias() { let mut o = Arg::new("opt") .long("option") .action(ArgAction::Set) .visible_alias("als"); o._build(); assert_eq!(o.to_string(), "--option "); } #[test] fn option_display_multiple_aliases() { let mut o = Arg::new("opt") .long("option") .action(ArgAction::Set) .visible_aliases(["als2", "als3", "als4"]) .alias("als_not_visible"); o._build(); assert_eq!(o.to_string(), "--option "); } #[test] fn option_display_single_short_alias() { let mut o = Arg::new("opt") .short('a') .action(ArgAction::Set) .visible_short_alias('b'); o._build(); assert_eq!(o.to_string(), "-a "); } #[test] fn option_display_multiple_short_aliases() { let mut o = Arg::new("opt") .short('a') .action(ArgAction::Set) .visible_short_aliases(['b', 'c', 'd']) .short_alias('e'); o._build(); assert_eq!(o.to_string(), "-a "); } // Positionals #[test] fn positional_display_multiple_values() { let mut p = Arg::new("pos").index(1).num_args(1..); p._build(); assert_eq!(p.to_string(), "[pos]..."); } #[test] fn positional_display_multiple_values_required() { let mut p = Arg::new("pos").index(1).num_args(1..).required(true); p._build(); assert_eq!(p.to_string(), "..."); } #[test] fn positional_display_zero_or_more_values() { let mut p = Arg::new("pos").index(1).num_args(0..); p._build(); assert_eq!(p.to_string(), "[pos]..."); } #[test] fn positional_display_one_or_more_values() { let mut p = Arg::new("pos").index(1).num_args(1..); p._build(); assert_eq!(p.to_string(), "[pos]..."); } #[test] fn positional_display_one_or_more_values_required() { let mut p = Arg::new("pos").index(1).num_args(1..).required(true); p._build(); assert_eq!(p.to_string(), "..."); } #[test] fn positional_display_optional_value() { let mut p = Arg::new("pos") .index(1) .num_args(0..=1) .action(ArgAction::Set); p._build(); assert_eq!(p.to_string(), "[pos]"); } #[test] fn positional_display_multiple_occurrences() { let mut p = Arg::new("pos").index(1).action(ArgAction::Append); p._build(); assert_eq!(p.to_string(), "[pos]..."); } #[test] fn positional_display_multiple_occurrences_required() { let mut p = Arg::new("pos") .index(1) .action(ArgAction::Append) .required(true); p._build(); assert_eq!(p.to_string(), "..."); } #[test] fn positional_display_required() { let mut p = Arg::new("pos").index(1).required(true); p._build(); assert_eq!(p.to_string(), ""); } #[test] fn positional_display_val_names() { let mut p = Arg::new("pos").index(1).value_names(["file1", "file2"]); p._build(); assert_eq!(p.to_string(), "[file1] [file2]"); } #[test] fn positional_display_val_names_required() { let mut p = Arg::new("pos") .index(1) .value_names(["file1", "file2"]) .required(true); p._build(); assert_eq!(p.to_string(), " "); } } clap_builder-4.5.48/src/builder/arg_group.rs000064400000000000000000000540431046102023000171310ustar 00000000000000// Internal use crate::builder::IntoResettable; use crate::util::Id; /// Family of related [arguments]. /// /// By placing arguments in a logical group, you can create easier requirement and /// exclusion rules instead of having to list each argument individually, or when you want a rule /// to apply "any but not all" arguments. /// /// For instance, you can make an entire `ArgGroup` required. If [`ArgGroup::multiple(true)`] is /// set, this means that at least one argument from that group must be present. If /// [`ArgGroup::multiple(false)`] is set (the default), one and *only* one must be present. /// /// You can also do things such as name an entire `ArgGroup` as a [conflict] or [requirement] for /// another argument, meaning any of the arguments that belong to that group will cause a failure /// if present, or must be present respectively. /// /// Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be /// present out of a given set. Imagine that you had multiple arguments, and you want one of them /// to be required, but making all of them required isn't feasible because perhaps they conflict /// with each other. For example, lets say that you were building an application where one could /// set a given version number by supplying a string with an option argument, i.e. /// `--set-ver v1.2.3`, you also wanted to support automatically using a previous version number /// and simply incrementing one of the three numbers. So you create three flags `--major`, /// `--minor`, and `--patch`. All of these arguments shouldn't be used at one time but you want to /// specify that *at least one* of them is used. For this, you can create a group. /// /// Finally, you may use `ArgGroup`s to pull a value from a group of arguments when you don't care /// exactly which argument was actually used at runtime. /// /// # Examples /// /// The following example demonstrates using an `ArgGroup` to ensure that one, and only one, of /// the arguments from the specified group is present at runtime. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg, ArgGroup, error::ErrorKind}; /// let result = Command::new("cmd") /// .arg(arg!(--"set-ver" "set the version manually")) /// .arg(arg!(--major "auto increase major")) /// .arg(arg!(--minor "auto increase minor")) /// .arg(arg!(--patch "auto increase patch")) /// .group(ArgGroup::new("vers") /// .args(["set-ver", "major", "minor", "patch"]) /// .required(true)) /// .try_get_matches_from(vec!["cmd", "--major", "--patch"]); /// // Because we used two args in the group it's an error /// assert!(result.is_err()); /// let err = result.unwrap_err(); /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); /// ``` /// /// This next example shows a passing parse of the same scenario /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg, ArgGroup, Id}; /// let result = Command::new("cmd") /// .arg(arg!(--"set-ver" "set the version manually")) /// .arg(arg!(--major "auto increase major")) /// .arg(arg!(--minor "auto increase minor")) /// .arg(arg!(--patch "auto increase patch")) /// .group(ArgGroup::new("vers") /// .args(["set-ver", "major", "minor","patch"]) /// .required(true)) /// .try_get_matches_from(vec!["cmd", "--major"]); /// assert!(result.is_ok()); /// let matches = result.unwrap(); /// // We may not know which of the args was used, so we can test for the group... /// assert!(matches.contains_id("vers")); /// // We can also ask the group which arg was used /// assert_eq!(matches /// .get_one::("vers") /// .expect("`vers` is required") /// .as_str(), /// "major" /// ); /// // we could also alternatively check each arg individually (not shown here) /// ``` /// [`ArgGroup::multiple(true)`]: ArgGroup::multiple() /// /// [`ArgGroup::multiple(false)`]: ArgGroup::multiple() /// [arguments]: crate::Arg /// [conflict]: crate::Arg::conflicts_with() /// [requirement]: crate::Arg::requires() #[derive(Default, Clone, Debug, PartialEq, Eq)] pub struct ArgGroup { pub(crate) id: Id, pub(crate) args: Vec, pub(crate) required: bool, pub(crate) requires: Vec, pub(crate) conflicts: Vec, pub(crate) multiple: bool, } /// # Builder impl ArgGroup { /// Create a `ArgGroup` using a unique name. /// /// The name will be used to get values from the group or refer to the group inside of conflict /// and requirement rules. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, ArgGroup}; /// ArgGroup::new("config") /// # ; /// ``` pub fn new(id: impl Into) -> Self { ArgGroup::default().id(id) } /// Sets the group name. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, ArgGroup}; /// ArgGroup::default().id("config") /// # ; /// ``` #[must_use] pub fn id(mut self, id: impl Into) -> Self { self.id = id.into(); self } /// Adds an [argument] to this group by name /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgGroup, ArgAction}; /// let m = Command::new("myprog") /// .arg(Arg::new("flag") /// .short('f') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("color") /// .short('c') /// .action(ArgAction::SetTrue)) /// .group(ArgGroup::new("req_flags") /// .arg("flag") /// .arg("color")) /// .get_matches_from(vec!["myprog", "-f"]); /// // maybe we don't know which of the two flags was used... /// assert!(m.contains_id("req_flags")); /// // but we can also check individually if needed /// assert!(m.contains_id("flag")); /// ``` /// [argument]: crate::Arg #[must_use] pub fn arg(mut self, arg_id: impl IntoResettable) -> Self { if let Some(arg_id) = arg_id.into_resettable().into_option() { self.args.push(arg_id); } else { self.args.clear(); } self } /// Adds multiple [arguments] to this group by name /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgGroup, ArgAction}; /// let m = Command::new("myprog") /// .arg(Arg::new("flag") /// .short('f') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("color") /// .short('c') /// .action(ArgAction::SetTrue)) /// .group(ArgGroup::new("req_flags") /// .args(["flag", "color"])) /// .get_matches_from(vec!["myprog", "-f"]); /// // maybe we don't know which of the two flags was used... /// assert!(m.contains_id("req_flags")); /// // but we can also check individually if needed /// assert!(m.contains_id("flag")); /// ``` /// [arguments]: crate::Arg #[must_use] pub fn args(mut self, ns: impl IntoIterator>) -> Self { for n in ns { self = self.arg(n); } self } /// Getters for all args. It will return a vector of `Id` /// /// # Example /// /// ```rust /// # use clap_builder as clap; /// # use clap::{ArgGroup}; /// let args: Vec<&str> = vec!["a1".into(), "a4".into()]; /// let grp = ArgGroup::new("program").args(&args); /// /// for (pos, arg) in grp.get_args().enumerate() { /// assert_eq!(*arg, args[pos]); /// } /// ``` pub fn get_args(&self) -> impl Iterator { self.args.iter() } /// Allows more than one of the [`Arg`]s in this group to be used. (Default: `false`) /// /// # Examples /// /// Notice in this example we use *both* the `-f` and `-c` flags which are both part of the /// group /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgGroup, ArgAction}; /// let m = Command::new("myprog") /// .arg(Arg::new("flag") /// .short('f') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("color") /// .short('c') /// .action(ArgAction::SetTrue)) /// .group(ArgGroup::new("req_flags") /// .args(["flag", "color"]) /// .multiple(true)) /// .get_matches_from(vec!["myprog", "-f", "-c"]); /// // maybe we don't know which of the two flags was used... /// assert!(m.contains_id("req_flags")); /// ``` /// In this next example, we show the default behavior (i.e. `multiple(false)`) which will throw /// an error if more than one of the args in the group was used. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; /// let result = Command::new("myprog") /// .arg(Arg::new("flag") /// .short('f') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("color") /// .short('c') /// .action(ArgAction::SetTrue)) /// .group(ArgGroup::new("req_flags") /// .args(["flag", "color"])) /// .try_get_matches_from(vec!["myprog", "-f", "-c"]); /// // Because we used both args in the group it's an error /// assert!(result.is_err()); /// let err = result.unwrap_err(); /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); /// ``` /// /// [`Arg`]: crate::Arg #[inline] #[must_use] pub fn multiple(mut self, yes: bool) -> Self { self.multiple = yes; self } /// Return true if the group allows more than one of the arguments /// in this group to be used. (Default: `false`) /// /// # Example /// /// ```rust /// # use clap_builder as clap; /// # use clap::{ArgGroup}; /// let mut group = ArgGroup::new("myprog") /// .args(["f", "c"]) /// .multiple(true); /// /// assert!(group.is_multiple()); /// ``` pub fn is_multiple(&mut self) -> bool { self.multiple } /// Require an argument from the group to be present when parsing. /// /// This is unless conflicting with another argument. A required group will be displayed in /// the usage string of the application in the format ``. /// ///
/// /// **NOTE:** This setting only applies to the current [`Command`] / [`Subcommand`]s, and not /// globally. /// ///
/// ///
/// /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with /// `ArgGroup::required(true)` states, "One and *only one* arg must be used from this group. /// Use of more than one arg is an error." Vice setting `ArgGroup::multiple(true)` which /// states, '*At least* one arg from this group must be used. Using multiple is OK." /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; /// let result = Command::new("myprog") /// .arg(Arg::new("flag") /// .short('f') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("color") /// .short('c') /// .action(ArgAction::SetTrue)) /// .group(ArgGroup::new("req_flags") /// .args(["flag", "color"]) /// .required(true)) /// .try_get_matches_from(vec!["myprog"]); /// // Because we didn't use any of the args in the group, it's an error /// assert!(result.is_err()); /// let err = result.unwrap_err(); /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); /// ``` /// /// [`Subcommand`]: crate::Subcommand /// [`ArgGroup::multiple`]: ArgGroup::multiple() /// [`Command`]: crate::Command #[inline] #[must_use] pub fn required(mut self, yes: bool) -> Self { self.required = yes; self } /// Specify an argument or group that must be present when this group is. /// /// This is not to be confused with a [required group]. Requirement rules function just like /// [argument requirement rules], you can name other arguments or groups that must be present /// when any one of the arguments from this group is used. /// ///
/// /// **NOTE:** The name provided may be an argument or group name /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; /// let result = Command::new("myprog") /// .arg(Arg::new("flag") /// .short('f') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("color") /// .short('c') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("debug") /// .short('d') /// .action(ArgAction::SetTrue)) /// .group(ArgGroup::new("req_flags") /// .args(["flag", "color"]) /// .requires("debug")) /// .try_get_matches_from(vec!["myprog", "-c"]); /// // because we used an arg from the group, and the group requires "-d" to be used, it's an /// // error /// assert!(result.is_err()); /// let err = result.unwrap_err(); /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); /// ``` /// [required group]: ArgGroup::required() /// [argument requirement rules]: crate::Arg::requires() #[must_use] pub fn requires(mut self, id: impl IntoResettable) -> Self { if let Some(id) = id.into_resettable().into_option() { self.requires.push(id); } else { self.requires.clear(); } self } /// Specify arguments or groups that must be present when this group is. /// /// This is not to be confused with a [required group]. Requirement rules function just like /// [argument requirement rules], you can name other arguments or groups that must be present /// when one of the arguments from this group is used. /// ///
/// /// **NOTE:** The names provided may be an argument or group name /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; /// let result = Command::new("myprog") /// .arg(Arg::new("flag") /// .short('f') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("color") /// .short('c') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("debug") /// .short('d') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("verb") /// .short('v') /// .action(ArgAction::SetTrue)) /// .group(ArgGroup::new("req_flags") /// .args(["flag", "color"]) /// .requires_all(["debug", "verb"])) /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); /// // because we used an arg from the group, and the group requires "-d" and "-v" to be used, /// // yet we only used "-d" it's an error /// assert!(result.is_err()); /// let err = result.unwrap_err(); /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); /// ``` /// [required group]: ArgGroup::required() /// [argument requirement rules]: crate::Arg::requires_ifs() #[must_use] pub fn requires_all(mut self, ns: impl IntoIterator>) -> Self { for n in ns { self = self.requires(n); } self } /// Specify an argument or group that must **not** be present when this group is. /// /// Exclusion (aka conflict) rules function just like [argument exclusion rules], you can name /// other arguments or groups that must *not* be present when one of the arguments from this /// group are used. /// ///
/// /// **NOTE:** The name provided may be an argument, or group name /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; /// let result = Command::new("myprog") /// .arg(Arg::new("flag") /// .short('f') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("color") /// .short('c') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("debug") /// .short('d') /// .action(ArgAction::SetTrue)) /// .group(ArgGroup::new("req_flags") /// .args(["flag", "color"]) /// .conflicts_with("debug")) /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); /// // because we used an arg from the group, and the group conflicts with "-d", it's an error /// assert!(result.is_err()); /// let err = result.unwrap_err(); /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); /// ``` /// [argument exclusion rules]: crate::Arg::conflicts_with() #[must_use] pub fn conflicts_with(mut self, id: impl IntoResettable) -> Self { if let Some(id) = id.into_resettable().into_option() { self.conflicts.push(id); } else { self.conflicts.clear(); } self } /// Specify arguments or groups that must **not** be present when this group is. /// /// Exclusion rules function just like [argument exclusion rules], you can name other arguments /// or groups that must *not* be present when one of the arguments from this group are used. /// ///
/// /// **NOTE:** The names provided may be an argument, or group name /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; /// let result = Command::new("myprog") /// .arg(Arg::new("flag") /// .short('f') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("color") /// .short('c') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("debug") /// .short('d') /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("verb") /// .short('v') /// .action(ArgAction::SetTrue)) /// .group(ArgGroup::new("req_flags") /// .args(["flag", "color"]) /// .conflicts_with_all(["debug", "verb"])) /// .try_get_matches_from(vec!["myprog", "-c", "-v"]); /// // because we used an arg from the group, and the group conflicts with either "-v" or "-d" /// // it's an error /// assert!(result.is_err()); /// let err = result.unwrap_err(); /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); /// ``` /// /// [argument exclusion rules]: crate::Arg::conflicts_with_all() #[must_use] pub fn conflicts_with_all(mut self, ns: impl IntoIterator>) -> Self { for n in ns { self = self.conflicts_with(n); } self } } /// # Reflection impl ArgGroup { /// Get the name of the group #[inline] pub fn get_id(&self) -> &Id { &self.id } /// Reports whether [`ArgGroup::required`] is set #[inline] pub fn is_required_set(&self) -> bool { self.required } } impl From<&'_ ArgGroup> for ArgGroup { fn from(g: &ArgGroup) -> Self { g.clone() } } #[cfg(test)] mod test { use super::*; #[test] fn groups() { let g = ArgGroup::new("test") .arg("a1") .arg("a4") .args(["a2", "a3"]) .required(true) .conflicts_with("c1") .conflicts_with_all(["c2", "c3"]) .conflicts_with("c4") .requires("r1") .requires_all(["r2", "r3"]) .requires("r4"); let args: Vec = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; let reqs: Vec = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; let confs: Vec = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; assert_eq!(g.args, args); assert_eq!(g.requires, reqs); assert_eq!(g.conflicts, confs); } #[test] fn test_from() { let g = ArgGroup::new("test") .arg("a1") .arg("a4") .args(["a2", "a3"]) .required(true) .conflicts_with("c1") .conflicts_with_all(["c2", "c3"]) .conflicts_with("c4") .requires("r1") .requires_all(["r2", "r3"]) .requires("r4"); let args: Vec = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; let reqs: Vec = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; let confs: Vec = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; let g2 = ArgGroup::from(&g); assert_eq!(g2.args, args); assert_eq!(g2.requires, reqs); assert_eq!(g2.conflicts, confs); } // This test will *fail to compile* if ArgGroup is not Send + Sync #[test] fn arg_group_send_sync() { fn foo(_: T) {} foo(ArgGroup::new("test")); } #[test] fn arg_group_expose_is_multiple_helper() { let args: Vec = vec!["a1".into(), "a4".into()]; let mut grp_multiple = ArgGroup::new("test_multiple").args(&args).multiple(true); assert!(grp_multiple.is_multiple()); let mut grp_not_multiple = ArgGroup::new("test_multiple").args(&args).multiple(false); assert!(!grp_not_multiple.is_multiple()); } #[test] fn arg_group_expose_get_args_helper() { let args: Vec = vec!["a1".into(), "a4".into()]; let grp = ArgGroup::new("program").args(&args); for (pos, arg) in grp.get_args().enumerate() { assert_eq!(*arg, args[pos]); } } } clap_builder-4.5.48/src/builder/arg_predicate.rs000064400000000000000000000010311046102023000177220ustar 00000000000000use crate::builder::OsStr; /// Operations to perform on argument values /// /// These do not apply to [`ValueSource::DefaultValue`][crate::parser::ValueSource::DefaultValue] #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "unstable-v5", non_exhaustive)] pub enum ArgPredicate { /// Is the argument present? IsPresent, /// Does the argument match the specified value? Equals(OsStr), } impl> From for ArgPredicate { fn from(other: S) -> Self { Self::Equals(other.into()) } } clap_builder-4.5.48/src/builder/arg_settings.rs000064400000000000000000000040701046102023000176300ustar 00000000000000#[allow(unused)] use crate::Arg; #[derive(Default, Copy, Clone, Debug, PartialEq, Eq)] pub(crate) struct ArgFlags(u32); impl ArgFlags { pub(crate) fn set(&mut self, setting: ArgSettings) { self.0 |= setting.bit(); } pub(crate) fn unset(&mut self, setting: ArgSettings) { self.0 &= !setting.bit(); } pub(crate) fn is_set(&self, setting: ArgSettings) -> bool { self.0 & setting.bit() != 0 } pub(crate) fn insert(&mut self, other: Self) { self.0 |= other.0; } } impl std::ops::BitOr for ArgFlags { type Output = Self; fn bitor(mut self, rhs: Self) -> Self::Output { self.insert(rhs); self } } /// 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)] #[repr(u8)] pub(crate) enum ArgSettings { Required, Global, Hidden, NextLineHelp, HidePossibleValues, AllowHyphenValues, AllowNegativeNumbers, RequireEquals, Last, TrailingVarArg, HideDefaultValue, IgnoreCase, #[cfg(feature = "env")] HideEnv, #[cfg(feature = "env")] HideEnvValues, HiddenShortHelp, HiddenLongHelp, Exclusive, } impl ArgSettings { fn bit(self) -> u32 { 1 << (self as u8) } } #[cfg(test)] mod test { use super::*; use crate::Arg; #[test] fn setting() { let m = Arg::new("setting").setting(ArgSettings::Required); assert!(m.is_required_set()); } #[test] fn unset_setting() { let m = Arg::new("unset_setting").setting(ArgSettings::Required); assert!(m.is_required_set()); let m = m.unset_setting(ArgSettings::Required); assert!(!m.is_required_set(), "{m:#?}"); } } clap_builder-4.5.48/src/builder/command.rs000064400000000000000000005404411046102023000165640ustar 00000000000000#![cfg_attr(not(feature = "usage"), allow(unused_mut))] // Std use std::env; use std::ffi::OsString; use std::fmt; use std::io; use std::ops::Index; use std::path::Path; // Internal use crate::builder::app_settings::{AppFlags, AppSettings}; use crate::builder::arg_settings::ArgSettings; use crate::builder::ext::Extension; use crate::builder::ext::Extensions; use crate::builder::ArgAction; use crate::builder::IntoResettable; use crate::builder::PossibleValue; use crate::builder::Str; use crate::builder::StyledStr; use crate::builder::Styles; use crate::builder::{Arg, ArgGroup, ArgPredicate}; use crate::error::ErrorKind; use crate::error::Result as ClapResult; use crate::mkeymap::MKeyMap; use crate::output::fmt::Stream; use crate::output::{fmt::Colorizer, write_help, Usage}; use crate::parser::{ArgMatcher, ArgMatches, Parser}; use crate::util::ChildGraph; use crate::util::{color::ColorChoice, Id}; use crate::{Error, INTERNAL_ERROR_MSG}; #[cfg(debug_assertions)] use crate::builder::debug_asserts::assert_app; /// Build a command-line interface. /// /// This includes defining arguments, subcommands, parser behavior, and help output. /// Once all configuration is complete, /// the [`Command::get_matches`] family of methods starts the runtime-parsing /// process. These methods then return information about the user supplied /// arguments (or lack thereof). /// /// When deriving a [`Parser`][crate::Parser], you can use /// [`CommandFactory::command`][crate::CommandFactory::command] to access the /// `Command`. /// /// - [Basic API][crate::Command#basic-api] /// - [Application-wide Settings][crate::Command#application-wide-settings] /// - [Command-specific Settings][crate::Command#command-specific-settings] /// - [Subcommand-specific Settings][crate::Command#subcommand-specific-settings] /// - [Reflection][crate::Command#reflection] /// /// # Examples /// /// ```no_run /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let m = Command::new("My Program") /// .author("Me, me@mail.com") /// .version("1.0.2") /// .about("Explains in brief what the program does") /// .arg( /// Arg::new("in_file") /// ) /// .after_help("Longer explanation to appear after the options when \ /// displaying the help information from --help or -h") /// .get_matches(); /// /// // Your program logic starts here... /// ``` /// [`Command::get_matches`]: Command::get_matches() #[derive(Debug, Clone)] pub struct Command { name: Str, long_flag: Option, short_flag: Option, display_name: Option, bin_name: Option, author: Option, version: Option, long_version: Option, about: Option, long_about: Option, before_help: Option, before_long_help: Option, after_help: Option, after_long_help: Option, aliases: Vec<(Str, bool)>, // (name, visible) short_flag_aliases: Vec<(char, bool)>, // (name, visible) long_flag_aliases: Vec<(Str, bool)>, // (name, visible) usage_str: Option, usage_name: Option, help_str: Option, disp_ord: Option, #[cfg(feature = "help")] template: Option, settings: AppFlags, g_settings: AppFlags, args: MKeyMap, subcommands: Vec, groups: Vec, current_help_heading: Option, current_disp_ord: Option, subcommand_value_name: Option, subcommand_heading: Option, external_value_parser: Option, long_help_exists: bool, deferred: Option Command>, #[cfg(feature = "unstable-ext")] ext: Extensions, app_ext: Extensions, } /// # Basic API impl Command { /// Creates a new instance of an `Command`. /// /// It is common, but not required, to use binary name as the `name`. This /// name will only be displayed to the user when they request to print /// version or help and usage information. /// /// See also [`command!`](crate::command!) and [`crate_name!`](crate::crate_name!). /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("My Program") /// # ; /// ``` pub fn new(name: impl Into) -> Self { /// The actual implementation of `new`, non-generic to save code size. /// /// If we don't do this rustc will unnecessarily generate multiple versions /// of this code. fn new_inner(name: Str) -> Command { Command { name, ..Default::default() } } new_inner(name.into()) } /// Adds an [argument] to the list of valid possibilities. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg, Arg}; /// Command::new("myprog") /// // Adding a single "flag" argument with a short and help text, using Arg::new() /// .arg( /// Arg::new("debug") /// .short('d') /// .help("turns on debugging mode") /// ) /// // Adding a single "option" argument with a short, a long, and help text using the less /// // verbose Arg::from() /// .arg( /// arg!(-c --config "Optionally sets a config file to use") /// ) /// # ; /// ``` /// [argument]: Arg #[must_use] pub fn arg(mut self, a: impl Into) -> Self { let arg = a.into(); self.arg_internal(arg); self } fn arg_internal(&mut self, mut arg: Arg) { if let Some(current_disp_ord) = self.current_disp_ord.as_mut() { if !arg.is_positional() { let current = *current_disp_ord; arg.disp_ord.get_or_insert(current); *current_disp_ord = current + 1; } } arg.help_heading .get_or_insert_with(|| self.current_help_heading.clone()); self.args.push(arg); } /// Adds multiple [arguments] to the list of valid possibilities. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg, Arg}; /// Command::new("myprog") /// .args([ /// arg!(-d --debug "turns on debugging info"), /// Arg::new("input").help("the input file to use") /// ]) /// # ; /// ``` /// [arguments]: Arg #[must_use] pub fn args(mut self, args: impl IntoIterator>) -> Self { for arg in args { self = self.arg(arg); } self } /// Allows one to mutate an [`Arg`] after it's been added to a [`Command`]. /// /// # Panics /// /// If the argument is undefined /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// /// let mut cmd = Command::new("foo") /// .arg(Arg::new("bar") /// .short('b') /// .action(ArgAction::SetTrue)) /// .mut_arg("bar", |a| a.short('B')); /// /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]); /// /// // Since we changed `bar`'s short to "B" this should err as there /// // is no `-b` anymore, only `-B` /// /// assert!(res.is_err()); /// /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]); /// assert!(res.is_ok()); /// ``` #[must_use] #[cfg_attr(debug_assertions, track_caller)] pub fn mut_arg(mut self, arg_id: impl AsRef, f: F) -> Self where F: FnOnce(Arg) -> Arg, { let id = arg_id.as_ref(); let a = self .args .remove_by_name(id) .unwrap_or_else(|| panic!("Argument `{id}` is undefined")); self.args.push(f(a)); self } /// Allows one to mutate all [`Arg`]s after they've been added to a [`Command`]. /// /// This does not affect the built-in `--help` or `--version` arguments. /// /// # Examples /// #[cfg_attr(feature = "string", doc = "```")] #[cfg_attr(not(feature = "string"), doc = "```ignore")] /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// /// let mut cmd = Command::new("foo") /// .arg(Arg::new("bar") /// .long("bar") /// .action(ArgAction::SetTrue)) /// .arg(Arg::new("baz") /// .long("baz") /// .action(ArgAction::SetTrue)) /// .mut_args(|a| { /// if let Some(l) = a.get_long().map(|l| format!("prefix-{l}")) { /// a.long(l) /// } else { /// a /// } /// }); /// /// let res = cmd.try_get_matches_from_mut(vec!["foo", "--bar"]); /// /// // Since we changed `bar`'s long to "prefix-bar" this should err as there /// // is no `--bar` anymore, only `--prefix-bar`. /// /// assert!(res.is_err()); /// /// let res = cmd.try_get_matches_from_mut(vec!["foo", "--prefix-bar"]); /// assert!(res.is_ok()); /// ``` #[must_use] #[cfg_attr(debug_assertions, track_caller)] pub fn mut_args(mut self, f: F) -> Self where F: FnMut(Arg) -> Arg, { self.args.mut_args(f); self } /// Allows one to mutate an [`ArgGroup`] after it's been added to a [`Command`]. /// /// # Panics /// /// If the argument is undefined /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg, ArgGroup}; /// /// Command::new("foo") /// .arg(arg!(--"set-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)) /// .mut_group("vers", |a| a.required(false)); /// ``` #[must_use] #[cfg_attr(debug_assertions, track_caller)] pub fn mut_group(mut self, arg_id: impl AsRef, f: F) -> Self where F: FnOnce(ArgGroup) -> ArgGroup, { let id = arg_id.as_ref(); let index = self .groups .iter() .position(|g| g.get_id() == id) .unwrap_or_else(|| panic!("Group `{id}` is undefined")); let a = self.groups.remove(index); self.groups.push(f(a)); self } /// Allows one to mutate a [`Command`] after it's been added as a subcommand. /// /// This can be useful for modifying auto-generated arguments of nested subcommands with /// [`Command::mut_arg`]. /// /// # Panics /// /// If the subcommand is undefined /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// /// let mut cmd = Command::new("foo") /// .subcommand(Command::new("bar")) /// .mut_subcommand("bar", |subcmd| subcmd.disable_help_flag(true)); /// /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar", "--help"]); /// /// // Since we disabled the help flag on the "bar" subcommand, this should err. /// /// assert!(res.is_err()); /// /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar"]); /// assert!(res.is_ok()); /// ``` #[must_use] pub fn mut_subcommand(mut self, name: impl AsRef, f: F) -> Self where F: FnOnce(Self) -> Self, { let name = name.as_ref(); let pos = self.subcommands.iter().position(|s| s.name == name); let subcmd = if let Some(idx) = pos { self.subcommands.remove(idx) } else { panic!("Command `{name}` is undefined") }; self.subcommands.push(f(subcmd)); self } /// Allows one to mutate all [`Command`]s after they've been added as subcommands. /// /// This does not affect the built-in `--help` or `--version` arguments. /// /// # Examples /// #[cfg_attr(feature = "string", doc = "```")] #[cfg_attr(not(feature = "string"), doc = "```ignore")] /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// /// let mut cmd = Command::new("foo") /// .subcommands([ /// Command::new("fetch"), /// Command::new("push"), /// ]) /// // Allow title-case subcommands /// .mut_subcommands(|sub| { /// let name = sub.get_name(); /// let alias = name.chars().enumerate().map(|(i, c)| { /// if i == 0 { /// c.to_ascii_uppercase() /// } else { /// c /// } /// }).collect::(); /// sub.alias(alias) /// }); /// /// let res = cmd.try_get_matches_from_mut(vec!["foo", "fetch"]); /// assert!(res.is_ok()); /// /// let res = cmd.try_get_matches_from_mut(vec!["foo", "Fetch"]); /// assert!(res.is_ok()); /// ``` #[must_use] #[cfg_attr(debug_assertions, track_caller)] pub fn mut_subcommands(mut self, f: F) -> Self where F: FnMut(Command) -> Command, { self.subcommands = self.subcommands.into_iter().map(f).collect(); 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. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg, ArgGroup}; /// Command::new("cmd") /// .arg(arg!(--"set-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)) /// # ; /// ``` #[inline] #[must_use] pub fn group(mut self, group: impl Into) -> Self { self.groups.push(group.into()); self } /// Adds multiple [`ArgGroup`]s to the [`Command`] at once. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg, ArgGroup}; /// Command::new("cmd") /// .arg(arg!(--"set-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")) /// .arg(arg!(-c "a config file").required(false)) /// .arg(arg!(-i "an interface").required(false)) /// .groups([ /// ArgGroup::new("vers") /// .args(["set-ver", "major", "minor","patch"]) /// .required(true), /// ArgGroup::new("input") /// .args(["c", "i"]) /// ]) /// # ; /// ``` #[must_use] pub fn groups(mut self, groups: impl IntoIterator>) -> Self { for g in groups { 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 /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg}; /// Command::new("myprog") /// .subcommand(Command::new("config") /// .about("Controls configuration features") /// .arg(arg!( "Required configuration file to use"))) /// # ; /// ``` #[inline] #[must_use] pub fn subcommand(self, subcmd: impl Into) -> Self { let subcmd = subcmd.into(); self.subcommand_internal(subcmd) } fn subcommand_internal(mut self, mut subcmd: Self) -> Self { if let Some(current_disp_ord) = self.current_disp_ord.as_mut() { let current = *current_disp_ord; subcmd.disp_ord.get_or_insert(current); *current_disp_ord = current + 1; } self.subcommands.push(subcmd); self } /// Adds multiple subcommands to the list of valid possibilities. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, }; /// # Command::new("myprog") /// .subcommands( [ /// Command::new("config").about("Controls configuration functionality") /// .arg(Arg::new("config_file")), /// Command::new("debug").about("Controls debug functionality")]) /// # ; /// ``` /// [`IntoIterator`]: std::iter::IntoIterator #[must_use] pub fn subcommands(mut self, subcmds: impl IntoIterator>) -> Self { for subcmd in subcmds { self = self.subcommand(subcmd); } self } /// Delay initialization for parts of the `Command` /// /// This is useful for large applications to delay definitions of subcommands until they are /// being invoked. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg}; /// Command::new("myprog") /// .subcommand(Command::new("config") /// .about("Controls configuration features") /// .defer(|cmd| { /// cmd.arg(arg!( "Required configuration file to use")) /// }) /// ) /// # ; /// ``` pub fn defer(mut self, deferred: fn(Command) -> Command) -> Self { self.deferred = Some(deferred); 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_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// fn cmd() -> Command { /// Command::new("foo") /// .arg( /// Arg::new("bar").short('b').action(ArgAction::SetTrue) /// ) /// } /// /// #[test] /// fn verify_app() { /// cmd().debug_assert(); /// } /// /// fn main() { /// let m = cmd().get_matches_from(vec!["foo", "-b"]); /// println!("{}", m.get_flag("bar")); /// } /// ``` pub fn debug_assert(mut self) { self.build(); } /// Custom error message for post-parsing validation /// /// **Note:** this will ensure the `Command` has been sufficiently [built][Command::build] for any /// relevant context, including usage. /// /// # Panics /// /// If contradictory arguments or settings exist (debug builds). /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, error::ErrorKind}; /// let mut cmd = Command::new("myprog"); /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case"); /// ``` pub fn error(&mut self, kind: ErrorKind, message: impl fmt::Display) -> Error { Error::raw(kind, message).format(self) } /// Parse [`env::args_os`], [exiting][Error::exit] on failure. /// /// # Panics /// /// If contradictory arguments or settings exist (debug builds). /// /// # Examples /// /// ```no_run /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let matches = Command::new("myprog") /// // Args and options go here... /// .get_matches(); /// ``` /// [`env::args_os`]: std::env::args_os() /// [`Command::try_get_matches_from_mut`]: Command::try_get_matches_from_mut() #[inline] pub fn get_matches(self) -> ArgMatches { self.get_matches_from(env::args_os()) } /// Parse [`env::args_os`], [exiting][Error::exit] on failure. /// /// Like [`Command::get_matches`] but doesn't consume the `Command`. /// /// # Panics /// /// If contradictory arguments or settings exist (debug builds). /// /// # Examples /// /// ```no_run /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let mut cmd = Command::new("myprog") /// // Args and options go here... /// ; /// let matches = cmd.get_matches_mut(); /// ``` /// [`env::args_os`]: std::env::args_os() /// [`Command::get_matches`]: Command::get_matches() pub fn get_matches_mut(&mut self) -> ArgMatches { self.try_get_matches_from_mut(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 (debug builds). /// /// # Examples /// /// ```no_run /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let matches = Command::new("myprog") /// // Args and options go here... /// .try_get_matches() /// .unwrap_or_else(|e| e.exit()); /// ``` /// [`env::args_os`]: std::env::args_os() /// [`Error::exit`]: crate::Error::exit() /// [`std::process::exit`]: std::process::exit() /// [`clap::Result`]: Result /// [`clap::Error`]: crate::Error /// [`kind`]: crate::Error /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion #[inline] pub fn try_get_matches(self) -> ClapResult { // Start the parsing self.try_get_matches_from(env::args_os()) } /// Parse the specified arguments, [exiting][Error::exit] 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 (debug builds). /// /// # Examples /// /// ```no_run /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; /// /// let matches = Command::new("myprog") /// // Args and options go here... /// .get_matches_from(arg_vec); /// ``` /// [`Command::get_matches`]: Command::get_matches() /// [`clap::Result`]: Result /// [`Vec`]: std::vec::Vec pub fn get_matches_from(mut self, itr: I) -> ArgMatches where I: IntoIterator, T: Into + Clone, { self.try_get_matches_from_mut(itr).unwrap_or_else(|e| { drop(self); e.exit() }) } /// Parse the specified arguments, returning a [`clap::Result`] on failure. /// ///
/// /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or /// perform a [`std::process::exit`] yourself. /// ///
/// ///
/// /// **NOTE:** The first argument will be parsed as the binary name unless /// [`Command::no_binary_name`] is used. /// ///
/// /// # Panics /// /// If contradictory arguments or settings exist (debug builds). /// /// # Examples /// /// ```no_run /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; /// /// let matches = Command::new("myprog") /// // Args and options go here... /// .try_get_matches_from(arg_vec) /// .unwrap_or_else(|e| e.exit()); /// ``` /// [`Command::get_matches_from`]: Command::get_matches_from() /// [`Command::try_get_matches`]: Command::try_get_matches() /// [`Error::exit`]: crate::Error::exit() /// [`std::process::exit`]: std::process::exit() /// [`clap::Error`]: crate::Error /// [`Error::exit`]: crate::Error::exit() /// [`kind`]: crate::Error /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion /// [`clap::Result`]: Result pub fn try_get_matches_from(mut self, itr: I) -> ClapResult where I: IntoIterator, T: Into + Clone, { self.try_get_matches_from_mut(itr) } /// Parse the specified arguments, returning a [`clap::Result`] on failure. /// /// Like [`Command::try_get_matches_from`] but doesn't consume the `Command`. /// ///
/// /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or /// perform a [`std::process::exit`] yourself. /// ///
/// ///
/// /// **NOTE:** The first argument will be parsed as the binary name unless /// [`Command::no_binary_name`] is used. /// ///
/// /// # Panics /// /// If contradictory arguments or settings exist (debug builds). /// /// # Examples /// /// ```no_run /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; /// /// let mut cmd = Command::new("myprog"); /// // Args and options go here... /// let matches = cmd.try_get_matches_from_mut(arg_vec) /// .unwrap_or_else(|e| e.exit()); /// ``` /// [`Command::try_get_matches_from`]: Command::try_get_matches_from() /// [`clap::Result`]: Result /// [`clap::Error`]: crate::Error /// [`kind`]: crate::Error pub fn try_get_matches_from_mut(&mut self, itr: I) -> ClapResult where I: IntoIterator, T: Into + Clone, { let mut raw_args = clap_lex::RawArgs::new(itr); let mut cursor = raw_args.cursor(); if self.settings.is_set(AppSettings::Multicall) { if let Some(argv0) = raw_args.next_os(&mut cursor) { let argv0 = Path::new(&argv0); if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) { // Stop borrowing command so we can get another mut ref to it. let command = command.to_owned(); debug!("Command::try_get_matches_from_mut: Parsed command {command} from argv"); debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it"); raw_args.insert(&cursor, [&command]); debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name"); self.name = "".into(); self.bin_name = None; return self._do_parse(&mut raw_args, cursor); } } }; // Get the name of the program (argument 1 of env::args()) and determine the // actual file // that was used to execute the program. This is because a program called // ./target/release/my_prog -a // will have two arguments, './target/release/my_prog', '-a' but we don't want // to display // the full path when displaying help messages and such if !self.settings.is_set(AppSettings::NoBinaryName) { if let Some(name) = raw_args.next_os(&mut cursor) { let p = Path::new(name); if let Some(f) = p.file_name() { if let Some(s) = f.to_str() { if self.bin_name.is_none() { self.bin_name = Some(s.to_owned()); } } } } } self._do_parse(&mut raw_args, cursor) } /// Prints the short help message (`-h`) to [`io::stdout()`]. /// /// See also [`Command::print_long_help`]. /// /// **Note:** this will ensure the `Command` has been sufficiently [built][Command::build]. /// /// # Panics /// /// If contradictory arguments or settings exist (debug builds). /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// let mut cmd = Command::new("myprog"); /// cmd.print_help(); /// ``` /// [`io::stdout()`]: std::io::stdout() pub fn print_help(&mut self) -> io::Result<()> { self._build_self(false); let color = self.color_help(); let mut styled = StyledStr::new(); let usage = Usage::new(self); write_help(&mut styled, self, &usage, false); let c = Colorizer::new(Stream::Stdout, color).with_content(styled); c.print() } /// Prints the long help message (`--help`) to [`io::stdout()`]. /// /// See also [`Command::print_help`]. /// /// **Note:** this will ensure the `Command` has been sufficiently [built][Command::build]. /// /// # Panics /// /// If contradictory arguments or settings exist (debug builds). /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// let mut cmd = Command::new("myprog"); /// cmd.print_long_help(); /// ``` /// [`io::stdout()`]: std::io::stdout() /// [`BufWriter`]: std::io::BufWriter /// [`-h` (short)]: Arg::help() /// [`--help` (long)]: Arg::long_help() pub fn print_long_help(&mut self) -> io::Result<()> { self._build_self(false); let color = self.color_help(); let mut styled = StyledStr::new(); let usage = Usage::new(self); write_help(&mut styled, self, &usage, true); let c = Colorizer::new(Stream::Stdout, color).with_content(styled); c.print() } /// Render the short help message (`-h`) to a [`StyledStr`] /// /// See also [`Command::render_long_help`]. /// /// **Note:** this will ensure the `Command` has been sufficiently [built][Command::build]. /// /// # Panics /// /// If contradictory arguments or settings exist (debug builds). /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// use std::io; /// let mut cmd = Command::new("myprog"); /// let mut out = io::stdout(); /// let help = cmd.render_help(); /// println!("{help}"); /// ``` /// [`io::Write`]: std::io::Write /// [`-h` (short)]: Arg::help() /// [`--help` (long)]: Arg::long_help() pub fn render_help(&mut self) -> StyledStr { self._build_self(false); let mut styled = StyledStr::new(); let usage = Usage::new(self); write_help(&mut styled, self, &usage, false); styled } /// Render the long help message (`--help`) to a [`StyledStr`]. /// /// See also [`Command::render_help`]. /// /// **Note:** this will ensure the `Command` has been sufficiently [built][Command::build]. /// /// # Panics /// /// If contradictory arguments or settings exist (debug builds). /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// use std::io; /// let mut cmd = Command::new("myprog"); /// let mut out = io::stdout(); /// let help = cmd.render_long_help(); /// println!("{help}"); /// ``` /// [`io::Write`]: std::io::Write /// [`-h` (short)]: Arg::help() /// [`--help` (long)]: Arg::long_help() pub fn render_long_help(&mut self) -> StyledStr { self._build_self(false); let mut styled = StyledStr::new(); let usage = Usage::new(self); write_help(&mut styled, self, &usage, true); styled } #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Command::render_help`") )] pub fn write_help(&mut self, w: &mut W) -> io::Result<()> { self._build_self(false); let mut styled = StyledStr::new(); let usage = Usage::new(self); write_help(&mut styled, self, &usage, false); ok!(write!(w, "{styled}")); w.flush() } #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Command::render_long_help`") )] pub fn write_long_help(&mut self, w: &mut W) -> io::Result<()> { self._build_self(false); let mut styled = StyledStr::new(); let usage = Usage::new(self); write_help(&mut styled, self, &usage, true); ok!(write!(w, "{styled}")); w.flush() } /// Version message rendered as if the user ran `-V`. /// /// See also [`Command::render_long_version`]. /// /// ### Coloring /// /// This function does not try to color the message nor it inserts any [ANSI escape codes]. /// /// ### Examples /// /// ```rust /// # use clap_builder as clap; /// # 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_builder as clap; /// # 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 /// /// **Note:** this will ensure the `Command` has been sufficiently [built][Command::build]. /// /// # Panics /// /// If contradictory arguments or settings exist (debug builds). /// /// ### Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// use std::io; /// let mut cmd = Command::new("myprog"); /// println!("{}", cmd.render_usage()); /// ``` pub fn render_usage(&mut self) -> StyledStr { self.render_usage_().unwrap_or_default() } pub(crate) fn render_usage_(&mut self) -> Option { // If there are global arguments, or settings we need to propagate them down to subcommands // before parsing incase we run into a subcommand self._build_self(false); Usage::new(self).create_usage_with_title(&[]) } /// Extend [`Command`] with [`CommandExt`] data #[cfg(feature = "unstable-ext")] #[allow(clippy::should_implement_trait)] pub fn add(mut self, tagged: T) -> Self { self.ext.set(tagged); self } } /// # Application-wide Settings /// /// These settings will apply to the top-level command and all subcommands, by default. Some /// settings can be overridden in subcommands. impl Command { /// Specifies that the parser should not assume the first argument passed is the binary name. /// /// This is normally the case when using a "daemon" style mode. For shells / REPLs, see /// [`Command::multicall`][Command::multicall]. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg}; /// let m = Command::new("myprog") /// .no_binary_name(true) /// .arg(arg!( ... "commands to run")) /// .get_matches_from(vec!["command", "set"]); /// /// let cmds: Vec<_> = m.get_many::("cmd").unwrap().collect(); /// assert_eq!(cmds, ["command", "set"]); /// ``` /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut() #[inline] pub fn no_binary_name(self, yes: bool) -> Self { if yes { self.global_setting(AppSettings::NoBinaryName) } else { self.unset_global_setting(AppSettings::NoBinaryName) } } /// Try not to fail on parse errors, like missing option values. /// ///
/// /// **NOTE:** This choice is propagated to all child subcommands. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, arg}; /// let cmd = Command::new("cmd") /// .ignore_errors(true) /// .arg(arg!(-c --config "Sets a custom config file")) /// .arg(arg!(-x --stuff "Sets a custom stuff file")) /// .arg(arg!(f: -f "Flag")); /// /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]); /// /// assert!(r.is_ok(), "unexpected error: {r:?}"); /// let m = r.unwrap(); /// assert_eq!(m.get_one::("config").unwrap(), "file"); /// assert!(m.get_flag("f")); /// assert_eq!(m.get_one::("stuff"), None); /// ``` #[inline] pub fn ignore_errors(self, yes: bool) -> Self { if yes { self.global_setting(AppSettings::IgnoreErrors) } else { self.unset_global_setting(AppSettings::IgnoreErrors) } } /// Replace prior occurrences of arguments rather than error /// /// For any argument that would conflict with itself by default (e.g. /// [`ArgAction::Set`], it will now override itself. /// /// This is the equivalent to saying the `foo` arg using [`Arg::overrides_with("foo")`] for all /// defined arguments. /// ///
/// /// **NOTE:** This choice is propagated to all child subcommands. /// ///
/// /// [`Arg::overrides_with("foo")`]: crate::Arg::overrides_with() #[inline] pub fn args_override_self(self, yes: bool) -> Self { if yes { self.global_setting(AppSettings::AllArgsOverrideSelf) } else { self.unset_global_setting(AppSettings::AllArgsOverrideSelf) } } /// Disables the automatic [delimiting of values][Arg::value_delimiter] after `--` or when [`Arg::trailing_var_arg`] /// was used. /// ///
/// /// **NOTE:** The same thing can be done manually by setting the final positional argument to /// [`Arg::value_delimiter(None)`]. Using this setting is safer, because it's easier to locate /// when making changes. /// ///
/// ///
/// /// **NOTE:** This choice is propagated to all child subcommands. /// ///
/// /// # Examples /// /// ```no_run /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// Command::new("myprog") /// .dont_delimit_trailing_values(true) /// .get_matches(); /// ``` /// /// [`Arg::value_delimiter(None)`]: crate::Arg::value_delimiter() #[inline] pub fn dont_delimit_trailing_values(self, yes: bool) -> Self { if yes { self.global_setting(AppSettings::DontDelimitTrailingValues) } else { self.unset_global_setting(AppSettings::DontDelimitTrailingValues) } } /// Sets when to color output. /// /// To customize how the output is styled, see [`Command::styles`]. /// ///
/// /// **NOTE:** This choice is propagated to all child subcommands. /// ///
/// ///
/// /// **NOTE:** Default behaviour is [`ColorChoice::Auto`]. /// ///
/// /// # Examples /// /// ```no_run /// # use clap_builder as clap; /// # use clap::{Command, ColorChoice}; /// Command::new("myprog") /// .color(ColorChoice::Never) /// .get_matches(); /// ``` /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto #[cfg(feature = "color")] #[inline] #[must_use] pub fn color(self, color: ColorChoice) -> Self { let cmd = self .unset_global_setting(AppSettings::ColorAuto) .unset_global_setting(AppSettings::ColorAlways) .unset_global_setting(AppSettings::ColorNever); match color { ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto), ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways), ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever), } } /// Sets the [`Styles`] for terminal output /// ///
/// /// **NOTE:** This choice is propagated to all child subcommands. /// ///
/// ///
/// /// **NOTE:** Default behaviour is [`Styles::default`]. /// ///
/// /// # Examples /// /// ```no_run /// # use clap_builder as clap; /// # use clap::{Command, ColorChoice, builder::styling}; /// const STYLES: styling::Styles = styling::Styles::styled() /// .header(styling::AnsiColor::Green.on_default().bold()) /// .usage(styling::AnsiColor::Green.on_default().bold()) /// .literal(styling::AnsiColor::Blue.on_default().bold()) /// .placeholder(styling::AnsiColor::Cyan.on_default()); /// Command::new("myprog") /// .styles(STYLES) /// .get_matches(); /// ``` #[cfg(feature = "color")] #[inline] #[must_use] pub fn styles(mut self, styles: Styles) -> Self { self.app_ext.set(styles); self } /// 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 current /// width cannot be determined, the default is 100. /// /// **`unstable-v5` feature**: Defaults to unbound, being subject to /// [`Command::max_term_width`]. /// ///
/// /// **NOTE:** This setting applies globally and *not* on a per-command basis. /// ///
/// ///
/// /// **NOTE:** This requires the `wrap_help` feature /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .term_width(80) /// # ; /// ``` #[inline] #[must_use] #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))] pub fn term_width(mut self, width: usize) -> Self { self.app_ext.set(TermWidth(width)); self } /// Limit the line length for wrapping help when using the current terminal's width. /// /// This only applies when [`term_width`][Command::term_width] is unset so that the current /// terminal's width will be used. See [`Command::term_width`] for more details. /// /// Using `0` will ignore this, always respecting [`Command::term_width`] (default). /// /// **`unstable-v5` feature**: Defaults to 100. /// ///
/// /// **NOTE:** This setting applies globally and *not* on a per-command basis. /// ///
/// ///
/// /// **NOTE:** This requires the `wrap_help` feature /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .max_term_width(100) /// # ; /// ``` #[inline] #[must_use] #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))] pub fn max_term_width(mut self, width: usize) -> Self { self.app_ext.set(MaxTermWidth(width)); self } /// Disables `-V` and `--version` flag. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, error::ErrorKind}; /// let res = Command::new("myprog") /// .version("1.0.0") /// .disable_version_flag(true) /// .try_get_matches_from(vec![ /// "myprog", "--version" /// ]); /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); /// ``` /// /// You can create a custom version flag with [`ArgAction::Version`] /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction, error::ErrorKind}; /// let mut cmd = Command::new("myprog") /// .version("1.0.0") /// // Remove the `-V` short flag /// .disable_version_flag(true) /// .arg( /// Arg::new("version") /// .long("version") /// .action(ArgAction::Version) /// .help("Print version") /// ); /// /// let res = cmd.try_get_matches_from_mut(vec![ /// "myprog", "-V" /// ]); /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); /// /// let res = cmd.try_get_matches_from_mut(vec![ /// "myprog", "--version" /// ]); /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::DisplayVersion); /// ``` #[inline] pub fn disable_version_flag(self, yes: bool) -> Self { if yes { self.global_setting(AppSettings::DisableVersionFlag) } else { self.unset_global_setting(AppSettings::DisableVersionFlag) } } /// Specifies to use the version of the current command for all [`subcommands`]. /// /// Defaults to `false`; subcommands have independent version strings from their parents. /// ///
/// /// **NOTE:** This choice is propagated to all child subcommands. /// ///
/// /// # Examples /// /// ```no_run /// # use clap_builder as clap; /// # 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_builder as clap; /// # 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_builder as clap; /// # use clap::{Command, error::ErrorKind}; /// let res = Command::new("myprog") /// .disable_help_flag(true) /// .try_get_matches_from(vec![ /// "myprog", "-h" /// ]); /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); /// ``` /// /// You can create a custom help flag with [`ArgAction::Help`], [`ArgAction::HelpShort`], or /// [`ArgAction::HelpLong`] /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction, error::ErrorKind}; /// let mut cmd = Command::new("myprog") /// // Change help short flag to `?` /// .disable_help_flag(true) /// .arg( /// Arg::new("help") /// .short('?') /// .long("help") /// .action(ArgAction::Help) /// .help("Print help") /// ); /// /// let res = cmd.try_get_matches_from_mut(vec![ /// "myprog", "-h" /// ]); /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); /// /// let res = cmd.try_get_matches_from_mut(vec![ /// "myprog", "-?" /// ]); /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::DisplayHelp); /// ``` #[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`]. /// ///
/// /// **NOTE:** This choice is propagated to all child subcommands. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, error::ErrorKind}; /// let res = Command::new("myprog") /// .disable_help_subcommand(true) /// // Normally, creating a subcommand causes a `help` subcommand to automatically /// // be generated as well /// .subcommand(Command::new("test")) /// .try_get_matches_from(vec![ /// "myprog", "help" /// ]); /// assert!(res.is_err()); /// assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidSubcommand); /// ``` /// /// [`subcommand`]: crate::Command::subcommand() #[inline] pub fn disable_help_subcommand(self, yes: bool) -> Self { if yes { self.global_setting(AppSettings::DisableHelpSubcommand) } else { self.unset_global_setting(AppSettings::DisableHelpSubcommand) } } /// Disables colorized help messages. /// ///
/// /// **NOTE:** This choice is propagated to all child subcommands. /// ///
/// /// # Examples /// /// ```no_run /// # use clap_builder as clap; /// # 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_builder as clap; /// # 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 /// /// On debug builds: /// ```rust,no_run /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// Command::new("myapp") /// .help_expected(true) /// .arg( /// Arg::new("foo") /// // Someone forgot to put .about("...") here /// // Since the setting `help_expected` is activated, this will lead to /// // a panic (if you are in debug mode) /// ) /// # .get_matches(); ///``` #[inline] pub fn help_expected(self, yes: bool) -> Self { if yes { self.global_setting(AppSettings::HelpExpected) } else { self.unset_global_setting(AppSettings::HelpExpected) } } #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "This is now the default") )] pub fn dont_collapse_args_in_usage(self, _yes: bool) -> Self { self } /// Tells `clap` *not* to print possible values when displaying help information. /// /// This can be useful if there are many values, or they are explained elsewhere. /// /// To set this per argument, see /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values]. /// ///
/// /// **NOTE:** This choice is propagated to all child subcommands. /// ///
#[inline] pub fn hide_possible_values(self, yes: bool) -> Self { if yes { self.global_setting(AppSettings::HidePossibleValues) } else { self.unset_global_setting(AppSettings::HidePossibleValues) } } /// Allow partial matches of long arguments or their [aliases]. /// /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and /// `--test`. /// ///
/// /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match /// `--te` to `--test` there could not also be another argument or alias `--temp` because both /// start with `--te` /// ///
/// ///
/// /// **NOTE:** This choice is propagated to all child subcommands. /// ///
/// /// [aliases]: crate::Command::aliases() #[inline] pub fn infer_long_args(self, yes: bool) -> Self { if yes { self.global_setting(AppSettings::InferLongArgs) } else { self.unset_global_setting(AppSettings::InferLongArgs) } } /// Allow partial matches of [subcommand] names and their [aliases]. /// /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and /// `test`. /// ///
/// /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te` /// to `test` there could not also be a subcommand or alias `temp` because both start with `te` /// ///
/// ///
/// /// **WARNING:** 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_builder as clap; /// # use clap::{Command, Arg}; /// let m = Command::new("prog") /// .infer_subcommands(true) /// .subcommand(Command::new("test")) /// .get_matches_from(vec![ /// "prog", "te" /// ]); /// assert_eq!(m.subcommand_name(), Some("test")); /// ``` /// /// [subcommand]: crate::Command::subcommand() /// [positional/free arguments]: crate::Arg::index() /// [aliases]: crate::Command::aliases() #[inline] pub fn infer_subcommands(self, yes: bool) -> Self { if yes { self.global_setting(AppSettings::InferSubcommands) } else { self.unset_global_setting(AppSettings::InferSubcommands) } } } /// # Command-specific Settings /// /// These apply only to the current command and are not inherited by subcommands. impl Command { /// (Re)Sets the program's name. /// /// See [`Command::new`] for more details. /// /// # Examples /// /// ```ignore /// let cmd = clap::command!() /// .name("foo"); /// /// // continued logic goes here, such as `cmd.get_matches()` etc. /// ``` #[must_use] pub fn name(mut self, name: impl Into) -> Self { self.name = name.into(); self } /// Overrides the runtime-determined name of the binary for help and error messages. /// /// This should only be used when absolutely necessary, such as when the binary name for your /// application is misleading, or perhaps *not* how the user should invoke your program. /// ///
/// /// **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 /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("My Program") /// .bin_name("my_binary") /// # ; /// ``` #[must_use] pub fn bin_name(mut self, name: impl IntoResettable) -> Self { self.bin_name = name.into_resettable().into_option(); self } /// Overrides the runtime-determined display name of the program for help and error messages. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("My Program") /// .display_name("my_program") /// # ; /// ``` #[must_use] pub fn display_name(mut self, name: impl IntoResettable) -> Self { self.display_name = name.into_resettable().into_option(); self } /// Sets the author(s) for the help message. /// ///
/// /// **TIP:** Use `clap`s convenience macro [`crate_authors!`] to /// automatically set your application's author(s) to the same thing as your /// crate at compile time. /// ///
/// ///
/// /// **NOTE:** A custom [`help_template`][Command::help_template] is needed for author to show /// up. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .author("Me, me@mymain.com") /// # ; /// ``` #[must_use] pub fn author(mut self, author: impl IntoResettable) -> Self { self.author = author.into_resettable().into_option(); self } /// Sets the program's description for the short help (`-h`). /// /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`. /// /// See also [`crate_description!`](crate::crate_description!). /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .about("Does really amazing things for great people") /// # ; /// ``` #[must_use] pub fn about(mut self, about: impl IntoResettable) -> Self { self.about = about.into_resettable().into_option(); self } /// Sets the program's description for the long help (`--help`). /// /// If not set, [`Command::about`] will be used for long help in addition to short help /// (`-h`). /// ///
/// /// **NOTE:** Only [`Command::about`] (short format) is used in completion /// script generation in order to be concise. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .long_about( /// "Does really amazing things to great people. Now let's talk a little /// more in depth about how this subcommand really works. It may take about /// a few lines of text, but that's ok!") /// # ; /// ``` /// [`Command::about`]: Command::about() #[must_use] pub fn long_about(mut self, long_about: impl IntoResettable) -> Self { self.long_about = long_about.into_resettable().into_option(); self } /// Free-form help text for after auto-generated short help (`-h`). /// /// This is often used to describe how to use the arguments, caveats to be noted, or license /// and contact information. /// /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .after_help("Does really amazing things for great people... but be careful with -R!") /// # ; /// ``` /// #[must_use] pub fn after_help(mut self, help: impl IntoResettable) -> Self { self.after_help = help.into_resettable().into_option(); self } /// Free-form help text for after auto-generated long help (`--help`). /// /// This is often used to describe how to use the arguments, caveats to be noted, or license /// and contact information. /// /// If not set, [`Command::after_help`] will be used for long help in addition to short help /// (`-h`). /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .after_long_help("Does really amazing things to great people... but be careful with -R, \ /// like, for real, be careful with this!") /// # ; /// ``` #[must_use] pub fn after_long_help(mut self, help: impl IntoResettable) -> Self { self.after_long_help = help.into_resettable().into_option(); self } /// Free-form help text for before auto-generated short help (`-h`). /// /// This is often used for header, copyright, or license information. /// /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .before_help("Some info I'd like to appear before the help info") /// # ; /// ``` #[must_use] pub fn before_help(mut self, help: impl IntoResettable) -> Self { self.before_help = help.into_resettable().into_option(); self } /// Free-form help text for before auto-generated long help (`--help`). /// /// This is often used for header, copyright, or license information. /// /// If not set, [`Command::before_help`] will be used for long help in addition to short help /// (`-h`). /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .before_long_help("Some verbose and long info I'd like to appear before the help info") /// # ; /// ``` #[must_use] pub fn before_long_help(mut self, help: impl IntoResettable) -> Self { self.before_long_help = help.into_resettable().into_option(); self } /// Sets the version for the short version (`-V`) and help messages. /// /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`. /// ///
/// /// **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 /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .version("v0.1.24") /// # ; /// ``` #[must_use] pub fn version(mut self, ver: impl IntoResettable) -> Self { self.version = ver.into_resettable().into_option(); self } /// Sets the version for the long version (`--version`) and help messages. /// /// If [`Command::version`] is not specified, this message will be displayed for `-V`. /// ///
/// /// **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 /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .long_version( /// "v0.1.24 /// commit: abcdef89726d /// revision: 123 /// release: 2 /// binary: myprog") /// # ; /// ``` #[must_use] pub fn long_version(mut self, ver: impl IntoResettable) -> Self { self.long_version = ver.into_resettable().into_option(); self } /// Overrides the `clap` generated usage string for help and error messages. /// ///
/// /// **NOTE:** Using this setting disables `clap`s "context-aware" usage /// strings. After this setting is set, this will be *the only* usage string /// displayed to the user! /// ///
/// ///
/// /// **NOTE:** Multiple usage lines may be present in the usage argument, but /// some rules need to be followed to ensure the usage lines are formatted /// correctly by the default help formatter: /// /// - Do not indent the first usage line. /// - Indent all subsequent usage lines with seven spaces. /// - The last line must not end with a newline. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// Command::new("myprog") /// .override_usage("myapp [-clDas] ") /// # ; /// ``` /// /// Or for multiple usage lines: /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// Command::new("myprog") /// .override_usage( /// "myapp -X [-a] [-b] \n \ /// myapp -Y [-c] \n \ /// myapp -Z [-d|-e]" /// ) /// # ; /// ``` #[must_use] pub fn override_usage(mut self, usage: impl IntoResettable) -> Self { self.usage_str = usage.into_resettable().into_option(); self } /// Overrides the `clap` generated help message (both `-h` and `--help`). /// /// This should only be used when the auto-generated message does not suffice. /// ///
/// /// **NOTE:** This **only** replaces the help message for the current /// command, meaning if you are using subcommands, those help messages will /// still be auto-generated unless you specify a [`Command::override_help`] for /// them as well. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// Command::new("myapp") /// .override_help("myapp v1.0\n\ /// Does awesome things\n\ /// (C) me@mail.com\n\n\ /// /// Usage: myapp \n\n\ /// /// Options:\n\ /// -h, --help Display this message\n\ /// -V, --version Display version info\n\ /// -s Do something with stuff\n\ /// -v Be verbose\n\n\ /// /// Commands:\n\ /// help Print this message\n\ /// work Do some work") /// # ; /// ``` #[must_use] pub fn override_help(mut self, help: impl IntoResettable) -> Self { self.help_str = help.into_resettable().into_option(); self } /// Sets the help template to be used, overriding the default format. /// /// Tags are given inside curly brackets. /// /// Valid tags are: /// /// * `{name}` - Display name for the (sub-)command. /// * `{bin}` - Binary name.(deprecated) /// * `{version}` - Version number. /// * `{author}` - Author information. /// * `{author-with-newline}` - Author followed by `\n`. /// * `{author-section}` - Author preceded and followed by `\n`. /// * `{about}` - General description (from [`Command::about`] or /// [`Command::long_about`]). /// * `{about-with-newline}` - About followed by `\n`. /// * `{about-section}` - About preceded and followed by '\n'. /// * `{usage-heading}` - Automatically generated usage heading. /// * `{usage}` - Automatically generated or given usage string. /// * `{all-args}` - Help for all arguments (options, flags, positional /// arguments, and subcommands) including titles. /// * `{options}` - Help for options. /// * `{positionals}` - Help for positional arguments. /// * `{subcommands}` - Help for subcommands. /// * `{tab}` - Standard tab sized used within clap /// * `{after-help}` - Help from [`Command::after_help`] or [`Command::after_long_help`]. /// * `{before-help}` - Help from [`Command::before_help`] or [`Command::before_long_help`]. /// /// # Examples /// /// For a very brief help: /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .version("1.0") /// .help_template("{name} ({version}) - {usage}") /// # ; /// ``` /// /// For showing more application context: /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .version("1.0") /// .help_template("\ /// {before-help}{name} {version} /// {author-with-newline}{about-with-newline} /// {usage-heading} {usage} /// /// {all-args}{after-help} /// ") /// # ; /// ``` /// [`Command::about`]: Command::about() /// [`Command::long_about`]: Command::long_about() /// [`Command::after_help`]: Command::after_help() /// [`Command::after_long_help`]: Command::after_long_help() /// [`Command::before_help`]: Command::before_help() /// [`Command::before_long_help`]: Command::before_long_help() #[must_use] #[cfg(feature = "help")] pub fn help_template(mut self, s: impl IntoResettable) -> Self { self.template = s.into_resettable().into_option(); self } #[inline] #[must_use] pub(crate) fn setting(mut self, setting: AppSettings) -> Self { self.settings.set(setting); self } #[inline] #[must_use] pub(crate) fn unset_setting(mut self, setting: AppSettings) -> Self { self.settings.unset(setting); self } #[inline] #[must_use] pub(crate) fn global_setting(mut self, setting: AppSettings) -> Self { self.settings.set(setting); self.g_settings.set(setting); self } #[inline] #[must_use] pub(crate) fn unset_global_setting(mut self, setting: AppSettings) -> Self { self.settings.unset(setting); self.g_settings.unset(setting); self } /// Flatten subcommand help into the current command's help /// /// This shows a summary of subcommands within the usage and help for the current command, similar to /// `git stash --help` showing information on `push`, `pop`, etc. /// To see more information, a user can still pass `--help` to the individual subcommands. #[inline] #[must_use] pub fn flatten_help(self, yes: bool) -> Self { if yes { self.setting(AppSettings::FlattenHelp) } else { self.unset_setting(AppSettings::FlattenHelp) } } /// Set the default section heading for future args. /// /// This will be used for any arg that hasn't had [`Arg::help_heading`] called. /// /// This is useful if the default `Options` or `Arguments` headings are /// not specific enough for one's use case. /// /// For subcommands, see [`Command::subcommand_help_heading`] /// /// [`Command::arg`]: Command::arg() /// [`Arg::help_heading`]: crate::Arg::help_heading() #[inline] #[must_use] pub fn next_help_heading(mut self, heading: impl IntoResettable) -> Self { self.current_help_heading = heading.into_resettable().into_option(); self } /// Change the starting value for assigning future display orders for args. /// /// This will be used for any arg that hasn't had [`Arg::display_order`] called. #[inline] #[must_use] pub fn next_display_order(mut self, disp_ord: impl IntoResettable) -> Self { self.current_disp_ord = disp_ord.into_resettable().into_option(); self } /// Exit gracefully if no arguments are present (e.g. `$ myprog`). /// ///
/// /// **NOTE:** [`subcommands`] count as arguments /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command}; /// Command::new("myprog") /// .arg_required_else_help(true); /// ``` /// /// [`subcommands`]: crate::Command::subcommand() /// [`Arg::default_value`]: crate::Arg::default_value() #[inline] pub fn arg_required_else_help(self, yes: bool) -> Self { if yes { self.setting(AppSettings::ArgRequiredElseHelp) } else { self.unset_setting(AppSettings::ArgRequiredElseHelp) } } #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_hyphen_values`") )] pub fn allow_hyphen_values(self, yes: bool) -> Self { if yes { self.setting(AppSettings::AllowHyphenValues) } else { self.unset_setting(AppSettings::AllowHyphenValues) } } #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_negative_numbers`") )] pub fn allow_negative_numbers(self, yes: bool) -> Self { if yes { self.setting(AppSettings::AllowNegativeNumbers) } else { self.unset_setting(AppSettings::AllowNegativeNumbers) } } #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Arg::trailing_var_arg`") )] pub fn trailing_var_arg(self, yes: bool) -> Self { if yes { self.setting(AppSettings::TrailingVarArg) } else { self.unset_setting(AppSettings::TrailingVarArg) } } /// Allows one to implement two styles of CLIs where positionals can be used out of order. /// /// The first example is a CLI where the second to last positional argument is optional, but /// the final positional argument is required. Such as `$ prog [optional] ` where one /// of the two following usages is allowed: /// /// * `$ prog [optional] ` /// * `$ prog ` /// /// This would otherwise not be allowed. This is useful when `[optional]` has a default value. /// /// **Note:** when using this style of "missing positionals" the final positional *must* be /// [required] if `--` will not be used to skip to the final positional argument. /// /// **Note:** This style also only allows a single positional argument to be "skipped" without /// the use of `--`. To skip more than one, see the second example. /// /// The second example is when one wants to skip multiple optional positional arguments, and use /// of the `--` operator is OK (but not required if all arguments will be specified anyways). /// /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments). /// /// With this setting the following invocations are possible: /// /// * `$ prog foo bar baz1 baz2 baz3` /// * `$ prog foo -- baz1 baz2 baz3` /// * `$ prog -- baz1 baz2 baz3` /// /// # Examples /// /// Style number one from above: /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// // Assume there is an external subcommand named "subcmd" /// let m = Command::new("myprog") /// .allow_missing_positional(true) /// .arg(Arg::new("arg1")) /// .arg(Arg::new("arg2") /// .required(true)) /// .get_matches_from(vec![ /// "prog", "other" /// ]); /// /// assert_eq!(m.get_one::("arg1"), None); /// assert_eq!(m.get_one::("arg2").unwrap(), "other"); /// ``` /// /// Now the same example, but using a default value for the first optional positional argument /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// // Assume there is an external subcommand named "subcmd" /// let m = Command::new("myprog") /// .allow_missing_positional(true) /// .arg(Arg::new("arg1") /// .default_value("something")) /// .arg(Arg::new("arg2") /// .required(true)) /// .get_matches_from(vec![ /// "prog", "other" /// ]); /// /// assert_eq!(m.get_one::("arg1").unwrap(), "something"); /// assert_eq!(m.get_one::("arg2").unwrap(), "other"); /// ``` /// /// Style number two from above: /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// // Assume there is an external subcommand named "subcmd" /// let m = Command::new("myprog") /// .allow_missing_positional(true) /// .arg(Arg::new("foo")) /// .arg(Arg::new("bar")) /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..)) /// .get_matches_from(vec![ /// "prog", "foo", "bar", "baz1", "baz2", "baz3" /// ]); /// /// assert_eq!(m.get_one::("foo").unwrap(), "foo"); /// assert_eq!(m.get_one::("bar").unwrap(), "bar"); /// assert_eq!(m.get_many::("baz").unwrap().collect::>(), &["baz1", "baz2", "baz3"]); /// ``` /// /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// // Assume there is an external subcommand named "subcmd" /// let m = Command::new("myprog") /// .allow_missing_positional(true) /// .arg(Arg::new("foo")) /// .arg(Arg::new("bar")) /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..)) /// .get_matches_from(vec![ /// "prog", "--", "baz1", "baz2", "baz3" /// ]); /// /// assert_eq!(m.get_one::("foo"), None); /// assert_eq!(m.get_one::("bar"), None); /// assert_eq!(m.get_many::("baz").unwrap().collect::>(), &["baz1", "baz2", "baz3"]); /// ``` /// /// [required]: crate::Arg::required() #[inline] pub fn allow_missing_positional(self, yes: bool) -> Self { if yes { self.setting(AppSettings::AllowMissingPositional) } else { self.unset_setting(AppSettings::AllowMissingPositional) } } } /// # Subcommand-specific Settings impl Command { /// Sets the short version of the subcommand flag without the preceding `-`. /// /// Allows the subcommand to be used as if it were an [`Arg::short`]. /// /// # Examples /// /// ``` /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let matches = Command::new("pacman") /// .subcommand( /// Command::new("sync").short_flag('S').arg( /// Arg::new("search") /// .short('s') /// .long("search") /// .action(ArgAction::SetTrue) /// .help("search remote repositories for matching strings"), /// ), /// ) /// .get_matches_from(vec!["pacman", "-Ss"]); /// /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); /// let sync_matches = matches.subcommand_matches("sync").unwrap(); /// assert!(sync_matches.get_flag("search")); /// ``` /// [`Arg::short`]: Arg::short() #[must_use] pub fn short_flag(mut self, short: impl IntoResettable) -> Self { self.short_flag = short.into_resettable().into_option(); self } /// Sets the long version of the subcommand flag without the preceding `--`. /// /// Allows the subcommand to be used as if it were an [`Arg::long`]. /// ///
/// /// **NOTE:** Any leading `-` characters will be stripped. /// ///
/// /// # Examples /// /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however, /// will *not* be stripped (i.e. `sync-file` is allowed). /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let matches = Command::new("pacman") /// .subcommand( /// Command::new("sync").long_flag("sync").arg( /// Arg::new("search") /// .short('s') /// .long("search") /// .action(ArgAction::SetTrue) /// .help("search remote repositories for matching strings"), /// ), /// ) /// .get_matches_from(vec!["pacman", "--sync", "--search"]); /// /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); /// let sync_matches = matches.subcommand_matches("sync").unwrap(); /// assert!(sync_matches.get_flag("search")); /// ``` /// /// [`Arg::long`]: Arg::long() #[must_use] pub fn long_flag(mut self, long: impl Into) -> Self { self.long_flag = Some(long.into()); self } /// Sets a hidden alias to this subcommand. /// /// This allows the subcommand to be accessed via *either* the original name, or this given /// alias. This is more efficient and easier than creating multiple hidden subcommands as one /// only needs to check for the existence of this command, and not all aliased variants. /// ///
/// /// **NOTE:** Aliases defined with this method are *hidden* from the help /// message. If you're looking for aliases that will be displayed in the help /// message, see [`Command::visible_alias`]. /// ///
/// ///
/// /// **NOTE:** When using aliases and checking for the existence of a /// particular subcommand within an [`ArgMatches`] struct, one only needs to /// search for the original name and not all aliases. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, }; /// let m = Command::new("myprog") /// .subcommand(Command::new("test") /// .alias("do-stuff")) /// .get_matches_from(vec!["myprog", "do-stuff"]); /// assert_eq!(m.subcommand_name(), Some("test")); /// ``` /// [`Command::visible_alias`]: Command::visible_alias() #[must_use] pub fn alias(mut self, name: impl IntoResettable) -> Self { if let Some(name) = name.into_resettable().into_option() { self.aliases.push((name, false)); } else { self.aliases.clear(); } self } /// Add an alias, which functions as "hidden" short flag subcommand /// /// This will automatically dispatch as if this subcommand was used. This is more efficient, /// and easier than creating multiple hidden subcommands as one only needs to check for the /// existence of this command, and not all variants. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, }; /// let m = Command::new("myprog") /// .subcommand(Command::new("test").short_flag('t') /// .short_flag_alias('d')) /// .get_matches_from(vec!["myprog", "-d"]); /// assert_eq!(m.subcommand_name(), Some("test")); /// ``` #[must_use] pub fn short_flag_alias(mut self, name: impl IntoResettable) -> Self { if let Some(name) = name.into_resettable().into_option() { debug_assert!(name != '-', "short alias name cannot be `-`"); self.short_flag_aliases.push((name, false)); } else { self.short_flag_aliases.clear(); } self } /// Add an alias, which functions as a "hidden" long flag subcommand. /// /// This will automatically dispatch as if this subcommand was used. This is more efficient, /// and easier than creating multiple hidden subcommands as one only needs to check for the /// existence of this command, and not all variants. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, }; /// let m = Command::new("myprog") /// .subcommand(Command::new("test").long_flag("test") /// .long_flag_alias("testing")) /// .get_matches_from(vec!["myprog", "--testing"]); /// assert_eq!(m.subcommand_name(), Some("test")); /// ``` #[must_use] pub fn long_flag_alias(mut self, name: impl IntoResettable) -> Self { if let Some(name) = name.into_resettable().into_option() { self.long_flag_aliases.push((name, false)); } else { self.long_flag_aliases.clear(); } self } /// Sets multiple hidden aliases to this subcommand. /// /// This allows the subcommand to be accessed via *either* the original name or any of the /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands /// as one only needs to check for the existence of this command and not all aliased variants. /// ///
/// /// **NOTE:** Aliases defined with this method are *hidden* from the help /// message. If looking for aliases that will be displayed in the help /// message, see [`Command::visible_aliases`]. /// ///
/// ///
/// /// **NOTE:** When using aliases and checking for the existence of a /// particular subcommand within an [`ArgMatches`] struct, one only needs to /// search for the original name and not all aliases. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let m = Command::new("myprog") /// .subcommand(Command::new("test") /// .aliases(["do-stuff", "do-tests", "tests"])) /// .arg(Arg::new("input") /// .help("the file to add") /// .required(false)) /// .get_matches_from(vec!["myprog", "do-tests"]); /// assert_eq!(m.subcommand_name(), Some("test")); /// ``` /// [`Command::visible_aliases`]: Command::visible_aliases() #[must_use] pub fn aliases(mut self, names: impl IntoIterator>) -> Self { self.aliases .extend(names.into_iter().map(|n| (n.into(), false))); self } /// Add aliases, which function as "hidden" short flag subcommands. /// /// These will automatically dispatch as if this subcommand was used. This is more efficient, /// and easier than creating multiple hidden subcommands as one only needs to check for the /// existence of this command, and not all variants. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, }; /// let m = Command::new("myprog") /// .subcommand(Command::new("test").short_flag('t') /// .short_flag_aliases(['a', 'b', 'c'])) /// .arg(Arg::new("input") /// .help("the file to add") /// .required(false)) /// .get_matches_from(vec!["myprog", "-a"]); /// assert_eq!(m.subcommand_name(), Some("test")); /// ``` #[must_use] pub fn short_flag_aliases(mut self, names: impl IntoIterator) -> Self { for s in names { debug_assert!(s != '-', "short alias name cannot be `-`"); self.short_flag_aliases.push((s, false)); } self } /// Add aliases, which function as "hidden" long flag subcommands. /// /// These will automatically dispatch as if this subcommand was used. This is more efficient, /// and easier than creating multiple hidden subcommands as one only needs to check for the /// existence of this command, and not all variants. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, }; /// let m = Command::new("myprog") /// .subcommand(Command::new("test").long_flag("test") /// .long_flag_aliases(["testing", "testall", "test_all"])) /// .arg(Arg::new("input") /// .help("the file to add") /// .required(false)) /// .get_matches_from(vec!["myprog", "--testing"]); /// assert_eq!(m.subcommand_name(), Some("test")); /// ``` #[must_use] pub fn long_flag_aliases(mut self, names: impl IntoIterator>) -> Self { for s in names { self = self.long_flag_alias(s); } self } /// Sets a visible alias to this subcommand. /// /// This allows the subcommand to be accessed via *either* the /// original name or the given alias. This is more efficient and easier /// than creating hidden subcommands as one only needs to check for /// the existence of this command and not all aliased variants. /// ///
/// /// **NOTE:** The alias defined with this method is *visible* from the help /// message and displayed as if it were just another regular subcommand. If /// looking for an alias that will not be displayed in the help message, see /// [`Command::alias`]. /// ///
/// ///
/// /// **NOTE:** When using aliases and checking for the existence of a /// particular subcommand within an [`ArgMatches`] struct, one only needs to /// search for the original name and not all aliases. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// let m = Command::new("myprog") /// .subcommand(Command::new("test") /// .visible_alias("do-stuff")) /// .get_matches_from(vec!["myprog", "do-stuff"]); /// assert_eq!(m.subcommand_name(), Some("test")); /// ``` /// [`Command::alias`]: Command::alias() #[must_use] pub fn visible_alias(mut self, name: impl IntoResettable) -> Self { if let Some(name) = name.into_resettable().into_option() { self.aliases.push((name, true)); } else { self.aliases.clear(); } self } /// Add an alias, which functions as "visible" short flag subcommand /// /// This will automatically dispatch as if this subcommand was used. This is more efficient, /// and easier than creating multiple hidden subcommands as one only needs to check for the /// existence of this command, and not all variants. /// /// See also [`Command::short_flag_alias`]. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, }; /// let m = Command::new("myprog") /// .subcommand(Command::new("test").short_flag('t') /// .visible_short_flag_alias('d')) /// .get_matches_from(vec!["myprog", "-d"]); /// assert_eq!(m.subcommand_name(), Some("test")); /// ``` /// [`Command::short_flag_alias`]: Command::short_flag_alias() #[must_use] pub fn visible_short_flag_alias(mut self, name: impl IntoResettable) -> Self { if let Some(name) = name.into_resettable().into_option() { debug_assert!(name != '-', "short alias name cannot be `-`"); self.short_flag_aliases.push((name, true)); } else { self.short_flag_aliases.clear(); } self } /// Add an alias, which functions as a "visible" long flag subcommand. /// /// This will automatically dispatch as if this subcommand was used. This is more efficient, /// and easier than creating multiple hidden subcommands as one only needs to check for the /// existence of this command, and not all variants. /// /// See also [`Command::long_flag_alias`]. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, }; /// let m = Command::new("myprog") /// .subcommand(Command::new("test").long_flag("test") /// .visible_long_flag_alias("testing")) /// .get_matches_from(vec!["myprog", "--testing"]); /// assert_eq!(m.subcommand_name(), Some("test")); /// ``` /// [`Command::long_flag_alias`]: Command::long_flag_alias() #[must_use] pub fn visible_long_flag_alias(mut self, name: impl IntoResettable) -> Self { if let Some(name) = name.into_resettable().into_option() { self.long_flag_aliases.push((name, true)); } else { self.long_flag_aliases.clear(); } self } /// Sets multiple visible aliases to this subcommand. /// /// This allows the subcommand to be accessed via *either* the /// original name or any of the given aliases. This is more efficient and easier /// than creating multiple hidden subcommands as one only needs to check for /// the existence of this command and not all aliased variants. /// ///
/// /// **NOTE:** The alias defined with this method is *visible* from the help /// message and displayed as if it were just another regular subcommand. If /// looking for an alias that will not be displayed in the help message, see /// [`Command::alias`]. /// ///
/// ///
/// /// **NOTE:** When using aliases, and checking for the existence of a /// particular subcommand within an [`ArgMatches`] struct, one only needs to /// search for the original name and not all aliases. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, }; /// let m = Command::new("myprog") /// .subcommand(Command::new("test") /// .visible_aliases(["do-stuff", "tests"])) /// .get_matches_from(vec!["myprog", "do-stuff"]); /// assert_eq!(m.subcommand_name(), Some("test")); /// ``` /// [`Command::alias`]: Command::alias() #[must_use] pub fn visible_aliases(mut self, names: impl IntoIterator>) -> Self { self.aliases .extend(names.into_iter().map(|n| (n.into(), true))); self } /// Add aliases, which function as *visible* short flag subcommands. /// /// See [`Command::short_flag_aliases`]. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, }; /// let m = Command::new("myprog") /// .subcommand(Command::new("test").short_flag('b') /// .visible_short_flag_aliases(['t'])) /// .get_matches_from(vec!["myprog", "-t"]); /// assert_eq!(m.subcommand_name(), Some("test")); /// ``` /// [`Command::short_flag_aliases`]: Command::short_flag_aliases() #[must_use] pub fn visible_short_flag_aliases(mut self, names: impl IntoIterator) -> Self { for s in names { debug_assert!(s != '-', "short alias name cannot be `-`"); self.short_flag_aliases.push((s, true)); } self } /// Add aliases, which function as *visible* long flag subcommands. /// /// See [`Command::long_flag_aliases`]. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, }; /// let m = Command::new("myprog") /// .subcommand(Command::new("test").long_flag("test") /// .visible_long_flag_aliases(["testing", "testall", "test_all"])) /// .get_matches_from(vec!["myprog", "--testing"]); /// assert_eq!(m.subcommand_name(), Some("test")); /// ``` /// [`Command::long_flag_aliases`]: Command::long_flag_aliases() #[must_use] pub fn visible_long_flag_aliases( mut self, names: impl IntoIterator>, ) -> Self { for s in names { self = self.visible_long_flag_alias(s); } self } /// Set the placement of this subcommand within the help. /// /// Subcommands with a lower value will be displayed first in the help message. /// Those with the same display order will be sorted. /// /// `Command`s are automatically assigned a display order based on the order they are added to /// their parent [`Command`]. /// Overriding this is helpful when the order commands are added in isn't the same as the /// display order, whether in one-off cases or to automatically sort commands. /// /// # Examples /// /// ```rust /// # #[cfg(feature = "help")] { /// # use clap_builder as clap; /// # use clap::{Command, }; /// let m = Command::new("cust-ord") /// .subcommand(Command::new("beta") /// .display_order(0) // Sort /// .about("Some help and text")) /// .subcommand(Command::new("alpha") /// .display_order(0) // Sort /// .about("I should be first!")) /// .get_matches_from(vec![ /// "cust-ord", "--help" /// ]); /// # } /// ``` /// /// The above example displays the following help message /// /// ```text /// cust-ord /// /// Usage: cust-ord [OPTIONS] /// /// Commands: /// alpha I should be first! /// beta Some help and text /// help Print help for the subcommand(s) /// /// Options: /// -h, --help Print help /// -V, --version Print version /// ``` #[inline] #[must_use] pub fn display_order(mut self, ord: impl IntoResettable) -> Self { self.disp_ord = ord.into_resettable().into_option(); self } /// Specifies that this [`subcommand`] should be hidden from help messages /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # 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_builder as clap; /// # use clap::{Command, error::ErrorKind}; /// let err = Command::new("myprog") /// .subcommand_required(true) /// .subcommand(Command::new("test")) /// .try_get_matches_from(vec![ /// "myprog", /// ]); /// assert!(err.is_err()); /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); /// # ; /// ``` /// /// [`subcommand`]: crate::Command::subcommand() pub fn subcommand_required(self, yes: bool) -> Self { if yes { self.setting(AppSettings::SubcommandRequired) } else { self.unset_setting(AppSettings::SubcommandRequired) } } /// Assume unexpected positional arguments are a [`subcommand`]. /// /// Arguments will be stored in the `""` argument in the [`ArgMatches`] /// ///
/// /// **NOTE:** Use this setting with caution, /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand) /// will **not** cause an error and instead be treated as a potential subcommand. /// One should check for such cases manually and inform the user appropriately. /// ///
/// ///
/// /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with /// `--`. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use std::ffi::OsString; /// # use clap::Command; /// // Assume there is an external subcommand named "subcmd" /// let m = Command::new("myprog") /// .allow_external_subcommands(true) /// .get_matches_from(vec![ /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" /// ]); /// /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty /// // string argument name /// match m.subcommand() { /// Some((external, ext_m)) => { /// let ext_args: Vec<_> = ext_m.get_many::("").unwrap().collect(); /// assert_eq!(external, "subcmd"); /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); /// }, /// _ => {}, /// } /// ``` /// /// [`subcommand`]: crate::Command::subcommand() /// [`ArgMatches`]: crate::ArgMatches /// [`ErrorKind::UnknownArgument`]: crate::error::ErrorKind::UnknownArgument pub fn allow_external_subcommands(self, yes: bool) -> Self { if yes { self.setting(AppSettings::AllowExternalSubcommands) } else { self.unset_setting(AppSettings::AllowExternalSubcommands) } } /// Specifies how to parse external subcommand arguments. /// /// The default parser is for `OsString`. This can be used to switch it to `String` or another /// type. /// ///
/// /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`] /// ///
/// /// # Examples /// /// ```rust /// # #[cfg(unix)] { /// # use clap_builder as clap; /// # use std::ffi::OsString; /// # use clap::Command; /// # use clap::value_parser; /// // Assume there is an external subcommand named "subcmd" /// let m = Command::new("myprog") /// .allow_external_subcommands(true) /// .get_matches_from(vec![ /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" /// ]); /// /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty /// // string argument name /// match m.subcommand() { /// Some((external, ext_m)) => { /// let ext_args: Vec<_> = ext_m.get_many::("").unwrap().collect(); /// assert_eq!(external, "subcmd"); /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); /// }, /// _ => {}, /// } /// # } /// ``` /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::value_parser; /// // Assume there is an external subcommand named "subcmd" /// let m = Command::new("myprog") /// .external_subcommand_value_parser(value_parser!(String)) /// .get_matches_from(vec![ /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" /// ]); /// /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty /// // string argument name /// match m.subcommand() { /// Some((external, ext_m)) => { /// let ext_args: Vec<_> = ext_m.get_many::("").unwrap().collect(); /// assert_eq!(external, "subcmd"); /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); /// }, /// _ => {}, /// } /// ``` /// /// [`subcommands`]: crate::Command::subcommand() pub fn external_subcommand_value_parser( mut self, parser: impl IntoResettable, ) -> Self { self.external_value_parser = parser.into_resettable().into_option(); self } /// Specifies that use of an argument prevents the use of [`subcommands`]. /// /// By default `clap` allows arguments between subcommands such /// as ` [cmd_args] [subcmd_args] [subsubcmd_args]`. /// /// This setting disables that functionality and says that arguments can /// only follow the *final* subcommand. For instance using this setting /// makes only the following invocations possible: /// /// * ` [subsubcmd_args]` /// * ` [subcmd_args]` /// * ` [cmd_args]` /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// Command::new("myprog") /// .args_conflicts_with_subcommands(true); /// ``` /// /// [`subcommands`]: crate::Command::subcommand() pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self { if yes { self.setting(AppSettings::ArgsNegateSubcommands) } else { self.unset_setting(AppSettings::ArgsNegateSubcommands) } } /// Prevent subcommands from being consumed as an arguments value. /// /// By default, if an option taking multiple values is followed by a subcommand, the /// subcommand will be parsed as another value. /// /// ```text /// cmd --foo val1 val2 subcommand /// --------- ---------- /// values another value /// ``` /// /// This setting instructs the parser to stop when encountering a subcommand instead of /// greedily consuming arguments. /// /// ```text /// cmd --foo val1 val2 subcommand /// --------- ---------- /// values subcommand /// ``` /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, ArgAction}; /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg( /// Arg::new("arg") /// .long("arg") /// .num_args(1..) /// .action(ArgAction::Set), /// ); /// /// let matches = cmd /// .clone() /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) /// .unwrap(); /// assert_eq!( /// matches.get_many::("arg").unwrap().collect::>(), /// &["1", "2", "3", "sub"] /// ); /// assert!(matches.subcommand_matches("sub").is_none()); /// /// let matches = cmd /// .subcommand_precedence_over_arg(true) /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) /// .unwrap(); /// assert_eq!( /// matches.get_many::("arg").unwrap().collect::>(), /// &["1", "2", "3"] /// ); /// assert!(matches.subcommand_matches("sub").is_some()); /// ``` pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self { if yes { self.setting(AppSettings::SubcommandPrecedenceOverArg) } else { self.unset_setting(AppSettings::SubcommandPrecedenceOverArg) } } /// Allows [`subcommands`] to override all requirements of the parent command. /// /// For example, if you had a subcommand or top level application with a required argument /// that is only required as long as there is no subcommand present, /// using this setting would allow you to set those arguments to [`Arg::required(true)`] /// and yet receive no error so long as the user uses a valid subcommand instead. /// ///
/// /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements) /// ///
/// /// # Examples /// /// This first example shows that it is an error to not use a required argument /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind}; /// let err = Command::new("myprog") /// .subcommand_negates_reqs(true) /// .arg(Arg::new("opt").required(true)) /// .subcommand(Command::new("test")) /// .try_get_matches_from(vec![ /// "myprog" /// ]); /// assert!(err.is_err()); /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); /// # ; /// ``` /// /// This next example shows that it is no longer error to not use a required argument if a /// valid subcommand is used. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg, error::ErrorKind}; /// let noerr = Command::new("myprog") /// .subcommand_negates_reqs(true) /// .arg(Arg::new("opt").required(true)) /// .subcommand(Command::new("test")) /// .try_get_matches_from(vec![ /// "myprog", "test" /// ]); /// assert!(noerr.is_ok()); /// # ; /// ``` /// /// [`Arg::required(true)`]: crate::Arg::required() /// [`subcommands`]: crate::Command::subcommand() pub fn subcommand_negates_reqs(self, yes: bool) -> Self { if yes { self.setting(AppSettings::SubcommandsNegateReqs) } else { self.unset_setting(AppSettings::SubcommandsNegateReqs) } } /// Multiple-personality program dispatched on the binary name (`argv[0]`) /// /// A "multicall" executable is a single executable /// that contains a variety of applets, /// and decides which applet to run based on the name of the file. /// The executable can be called from different names by creating hard links /// or symbolic links to it. /// /// This is desirable for: /// - Easy distribution, a single binary that can install hardlinks to access the different /// personalities. /// - Minimal binary size by sharing common code (e.g. standard library, clap) /// - Custom shells or REPLs where there isn't a single top-level command /// /// Setting `multicall` will cause /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if /// [`Command::no_binary_name`][Command::no_binary_name] was set. /// - Help and errors to report subcommands as if they were the top-level command /// /// When the subcommand is not present, there are several strategies you may employ, depending /// on your needs: /// - Let the error percolate up normally /// - Print a specialized error message using the /// [`Error::context`][crate::Error::context] /// - Print the [help][Command::write_help] but this might be ambiguous /// - Disable `multicall` and re-parse it /// - Disable `multicall` and re-parse it with a specific subcommand /// /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand /// might report the same error. Enable /// [`allow_external_subcommands`][Command::allow_external_subcommands] if you want to specifically /// get the unrecognized binary name. /// ///
/// /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret /// the command name in incompatible ways. /// ///
/// ///
/// /// **NOTE:** The multicall command cannot have arguments. /// ///
/// ///
/// /// **NOTE:** Applets are slightly semantically different from subcommands, /// so it's recommended to use [`Command::subcommand_help_heading`] and /// [`Command::subcommand_value_name`] to change the descriptive text as above. /// ///
/// /// # Examples /// /// `hostname` is an example of a multicall executable. /// Both `hostname` and `dnsdomainname` are provided by the same executable /// and which behaviour to use is based on the executable file name. /// /// This is desirable when the executable has a primary purpose /// but there is related functionality that would be convenient to provide /// and implement it to be in the same executable. /// /// The name of the cmd is essentially unused /// and may be the same as the name of a subcommand. /// /// The names of the immediate subcommands of the Command /// are matched against the basename of the first argument, /// which is conventionally the path of the executable. /// /// This does not allow the subcommand to be passed as the first non-path argument. /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, error::ErrorKind}; /// let mut cmd = Command::new("hostname") /// .multicall(true) /// .subcommand(Command::new("hostname")) /// .subcommand(Command::new("dnsdomainname")); /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]); /// assert!(m.is_err()); /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument); /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]); /// assert_eq!(m.subcommand_name(), Some("dnsdomainname")); /// ``` /// /// Busybox is another common example of a multicall executable /// with a subcommmand for each applet that can be run directly, /// e.g. with the `cat` applet being run by running `busybox cat`, /// or with `cat` as a link to the `busybox` binary. /// /// This is desirable when the launcher program has additional options /// or it is useful to run the applet without installing a symlink /// e.g. to test the applet without installing it /// or there may already be a command of that name installed. /// /// To make an applet usable as both a multicall link and a subcommand /// the subcommands must be defined both in the top-level Command /// and as subcommands of the "main" applet. /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// fn applet_commands() -> [Command; 2] { /// [Command::new("true"), Command::new("false")] /// } /// let mut cmd = Command::new("busybox") /// .multicall(true) /// .subcommand( /// Command::new("busybox") /// .subcommand_value_name("APPLET") /// .subcommand_help_heading("APPLETS") /// .subcommands(applet_commands()), /// ) /// .subcommands(applet_commands()); /// // When called from the executable's canonical name /// // its applets can be matched as subcommands. /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap(); /// assert_eq!(m.subcommand_name(), Some("busybox")); /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true")); /// // When called from a link named after an applet that applet is matched. /// let m = cmd.get_matches_from(&["/usr/bin/true"]); /// assert_eq!(m.subcommand_name(), Some("true")); /// ``` /// /// [`no_binary_name`]: crate::Command::no_binary_name /// [`Command::subcommand_value_name`]: crate::Command::subcommand_value_name /// [`Command::subcommand_help_heading`]: crate::Command::subcommand_help_heading #[inline] pub fn multicall(self, yes: bool) -> Self { if yes { self.setting(AppSettings::Multicall) } else { self.unset_setting(AppSettings::Multicall) } } /// Sets the value name used for subcommands when printing usage and help. /// /// By default, this is "COMMAND". /// /// See also [`Command::subcommand_help_heading`] /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// Command::new("myprog") /// .subcommand(Command::new("sub1")) /// .print_help() /// # ; /// ``` /// /// will produce /// /// ```text /// myprog /// /// Usage: myprog [COMMAND] /// /// Commands: /// help Print this message or the help of the given subcommand(s) /// sub1 /// /// Options: /// -h, --help Print help /// -V, --version Print version /// ``` /// /// but usage of `subcommand_value_name` /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// Command::new("myprog") /// .subcommand(Command::new("sub1")) /// .subcommand_value_name("THING") /// .print_help() /// # ; /// ``` /// /// will produce /// /// ```text /// myprog /// /// Usage: myprog [THING] /// /// Commands: /// help Print this message or the help of the given subcommand(s) /// sub1 /// /// Options: /// -h, --help Print help /// -V, --version Print version /// ``` #[must_use] pub fn subcommand_value_name(mut self, value_name: impl IntoResettable) -> Self { self.subcommand_value_name = value_name.into_resettable().into_option(); self } /// Sets the help heading used for subcommands when printing usage and help. /// /// By default, this is "Commands". /// /// See also [`Command::subcommand_value_name`] /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// Command::new("myprog") /// .subcommand(Command::new("sub1")) /// .print_help() /// # ; /// ``` /// /// will produce /// /// ```text /// myprog /// /// Usage: myprog [COMMAND] /// /// Commands: /// help Print this message or the help of the given subcommand(s) /// sub1 /// /// Options: /// -h, --help Print help /// -V, --version Print version /// ``` /// /// but usage of `subcommand_help_heading` /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Command, Arg}; /// Command::new("myprog") /// .subcommand(Command::new("sub1")) /// .subcommand_help_heading("Things") /// .print_help() /// # ; /// ``` /// /// will produce /// /// ```text /// myprog /// /// Usage: myprog [COMMAND] /// /// Things: /// help Print this message or the help of the given subcommand(s) /// sub1 /// /// Options: /// -h, --help Print help /// -V, --version Print version /// ``` #[must_use] pub fn subcommand_help_heading(mut self, heading: impl IntoResettable) -> Self { self.subcommand_heading = heading.into_resettable().into_option(); self } } /// # Reflection impl Command { #[inline] #[cfg(feature = "usage")] pub(crate) fn get_usage_name(&self) -> Option<&str> { self.usage_name.as_deref() } #[inline] #[cfg(feature = "usage")] pub(crate) fn get_usage_name_fallback(&self) -> &str { self.get_usage_name() .unwrap_or_else(|| self.get_bin_name_fallback()) } #[inline] #[cfg(not(feature = "usage"))] #[allow(dead_code)] pub(crate) fn get_usage_name_fallback(&self) -> &str { self.get_bin_name_fallback() } /// 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() } /// Get the name of the binary. #[inline] pub(crate) fn get_bin_name_fallback(&self) -> &str { self.bin_name.as_deref().unwrap_or_else(|| self.get_name()) } /// Set binary name. Uses `&mut self` instead of `self`. pub fn set_bin_name(&mut self, name: impl Into) { self.bin_name = Some(name.into()); } /// Get the name of the cmd. #[inline] pub fn get_name(&self) -> &str { self.name.as_str() } #[inline] #[cfg(debug_assertions)] pub(crate) fn get_name_str(&self) -> &Str { &self.name } /// Get all known names of the cmd (i.e. primary name and visible aliases). pub fn get_name_and_visible_aliases(&self) -> Vec<&str> { let mut names = vec![self.name.as_str()]; names.extend(self.get_visible_aliases()); names } /// Get the version of the cmd. #[inline] pub fn get_version(&self) -> Option<&str> { self.version.as_deref() } /// Get the long version of the cmd. #[inline] pub fn get_long_version(&self) -> Option<&str> { self.long_version.as_deref() } /// Get the placement within help #[inline] pub fn get_display_order(&self) -> usize { self.disp_ord.unwrap_or(999) } /// Get the authors of the cmd. #[inline] pub fn get_author(&self) -> Option<&str> { self.author.as_deref() } /// Get the short flag of the subcommand. #[inline] pub fn get_short_flag(&self) -> Option { self.short_flag } /// Get the long flag of the subcommand. #[inline] pub fn get_long_flag(&self) -> Option<&str> { self.long_flag.as_deref() } /// Get the help message specified via [`Command::about`]. /// /// [`Command::about`]: Command::about() #[inline] pub fn get_about(&self) -> Option<&StyledStr> { self.about.as_ref() } /// Get the help message specified via [`Command::long_about`]. /// /// [`Command::long_about`]: Command::long_about() #[inline] pub fn get_long_about(&self) -> Option<&StyledStr> { self.long_about.as_ref() } /// Get the custom section heading specified via [`Command::flatten_help`]. #[inline] pub fn is_flatten_help_set(&self) -> bool { self.is_set(AppSettings::FlattenHelp) } /// Get the custom section heading specified via [`Command::next_help_heading`]. #[inline] pub fn get_next_help_heading(&self) -> Option<&str> { self.current_help_heading.as_deref() } /// Iterate through the *visible* aliases for this subcommand. #[inline] pub fn get_visible_aliases(&self) -> impl Iterator + '_ { self.aliases .iter() .filter(|(_, vis)| *vis) .map(|a| a.0.as_str()) } /// Iterate through the *visible* short aliases for this subcommand. #[inline] pub fn get_visible_short_flag_aliases(&self) -> impl Iterator + '_ { self.short_flag_aliases .iter() .filter(|(_, vis)| *vis) .map(|a| a.0) } /// Iterate through the *visible* long aliases for this subcommand. #[inline] pub fn get_visible_long_flag_aliases(&self) -> impl Iterator + '_ { self.long_flag_aliases .iter() .filter(|(_, vis)| *vis) .map(|a| a.0.as_str()) } /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden. #[inline] pub fn get_all_aliases(&self) -> impl Iterator + '_ { self.aliases.iter().map(|a| a.0.as_str()) } /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden. #[inline] pub fn get_all_short_flag_aliases(&self) -> impl Iterator + '_ { self.short_flag_aliases.iter().map(|a| a.0) } /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden. #[inline] pub fn get_all_long_flag_aliases(&self) -> impl Iterator + '_ { self.long_flag_aliases.iter().map(|a| a.0.as_str()) } /// Iterate through the *hidden* aliases for this subcommand. #[inline] pub fn get_aliases(&self) -> impl Iterator + '_ { self.aliases .iter() .filter(|(_, vis)| !*vis) .map(|a| a.0.as_str()) } #[inline] pub(crate) fn is_set(&self, s: AppSettings) -> bool { self.settings.is_set(s) || self.g_settings.is_set(s) } /// Should we color the output? pub fn get_color(&self) -> ColorChoice { debug!("Command::color: Color setting..."); if cfg!(feature = "color") { if self.is_set(AppSettings::ColorNever) { debug!("Never"); ColorChoice::Never } else if self.is_set(AppSettings::ColorAlways) { debug!("Always"); ColorChoice::Always } else { debug!("Auto"); ColorChoice::Auto } } else { ColorChoice::Never } } /// Return the current `Styles` for the `Command` #[inline] pub fn get_styles(&self) -> &Styles { self.app_ext.get().unwrap_or_default() } /// Iterate through the set of subcommands, getting a reference to each. #[inline] pub fn get_subcommands(&self) -> impl Iterator { self.subcommands.iter() } /// Iterate through the set of subcommands, getting a mutable reference to each. #[inline] pub fn get_subcommands_mut(&mut self) -> impl Iterator { self.subcommands.iter_mut() } /// Returns `true` if this `Command` has subcommands. #[inline] pub fn has_subcommands(&self) -> bool { !self.subcommands.is_empty() } /// Returns the help heading for listing subcommands. #[inline] pub fn get_subcommand_help_heading(&self) -> Option<&str> { self.subcommand_heading.as_deref() } /// Returns the subcommand value name. #[inline] pub fn get_subcommand_value_name(&self) -> Option<&str> { self.subcommand_value_name.as_deref() } /// Returns the help heading for listing subcommands. #[inline] pub fn get_before_help(&self) -> Option<&StyledStr> { self.before_help.as_ref() } /// Returns the help heading for listing subcommands. #[inline] pub fn get_before_long_help(&self) -> Option<&StyledStr> { self.before_long_help.as_ref() } /// Returns the help heading for listing subcommands. #[inline] pub fn get_after_help(&self) -> Option<&StyledStr> { self.after_help.as_ref() } /// Returns the help heading for listing subcommands. #[inline] pub fn get_after_long_help(&self) -> Option<&StyledStr> { self.after_long_help.as_ref() } /// Find subcommand such that its name or one of aliases equals `name`. /// /// This does not recurse through subcommands of subcommands. #[inline] pub fn find_subcommand(&self, name: impl AsRef) -> Option<&Command> { let name = name.as_ref(); self.get_subcommands().find(|s| s.aliases_to(name)) } /// Find subcommand such that its name or one of aliases equals `name`, returning /// a mutable reference to the subcommand. /// /// This does not recurse through subcommands of subcommands. #[inline] pub fn find_subcommand_mut( &mut self, name: impl AsRef, ) -> Option<&mut Command> { let name = name.as_ref(); self.get_subcommands_mut().find(|s| s.aliases_to(name)) } /// Iterate through the set of groups. #[inline] pub fn get_groups(&self) -> impl Iterator { self.groups.iter() } /// Iterate through the set of arguments. #[inline] pub fn get_arguments(&self) -> impl Iterator { self.args.args() } /// Iterate through the *positionals* arguments. #[inline] pub fn get_positionals(&self) -> impl Iterator { self.get_arguments().filter(|a| a.is_positional()) } /// Iterate through the *options*. pub fn get_opts(&self) -> impl Iterator { self.get_arguments() .filter(|a| a.is_takes_value_set() && !a.is_positional()) } /// Get a list of all arguments the given argument conflicts with. /// /// If the provided argument is declared as global, the conflicts will be determined /// based on the propagation rules of global arguments. /// /// ### Panics /// /// If the given arg contains a conflict with an argument that is unknown to /// this `Command`. pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator { if arg.is_global_set() { self.get_global_arg_conflicts_with(arg) } else { let mut result = Vec::new(); for id in arg.blacklist.iter() { if let Some(arg) = self.find(id) { result.push(arg); } else if let Some(group) = self.find_group(id) { result.extend( self.unroll_args_in_group(&group.id) .iter() .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)), ); } else { panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd"); } } result } } /// Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with. /// /// This behavior follows the propagation rules of global arguments. /// It is useful for finding conflicts for arguments declared as global. /// /// ### Panics /// /// If the given arg contains a conflict with an argument that is unknown to /// this `Command`. fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator { arg.blacklist .iter() .map(|id| { self.args .args() .chain( self.get_subcommands_containing(arg) .iter() .flat_map(|x| x.args.args()), ) .find(|arg| arg.get_id() == id) .expect( "Command::get_arg_conflicts_with: \ The passed arg conflicts with an arg unknown to the cmd", ) }) .collect() } /// Get a list of subcommands which contain the provided Argument /// /// This command will only include subcommands in its list for which the subcommands /// parent also contains the Argument. /// /// This search follows the propagation rules of global arguments. /// It is useful to finding subcommands, that have inherited a global argument. /// ///
/// /// **NOTE:** In this case only `Sucommand_1` will be included /// ```text /// Subcommand_1 (contains Arg) /// Subcommand_1.1 (doesn't contain Arg) /// Subcommand_1.1.1 (contains Arg) /// ``` /// ///
fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> { let mut vec = Vec::new(); for idx in 0..self.subcommands.len() { if self.subcommands[idx] .args .args() .any(|ar| ar.get_id() == arg.get_id()) { vec.push(&self.subcommands[idx]); vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg)); } } vec } /// Report whether [`Command::no_binary_name`] is set pub fn is_no_binary_name_set(&self) -> bool { self.is_set(AppSettings::NoBinaryName) } /// Report whether [`Command::ignore_errors`] is set pub(crate) fn is_ignore_errors_set(&self) -> bool { self.is_set(AppSettings::IgnoreErrors) } /// Report whether [`Command::dont_delimit_trailing_values`] is set pub fn is_dont_delimit_trailing_values_set(&self) -> bool { self.is_set(AppSettings::DontDelimitTrailingValues) } /// Report whether [`Command::disable_version_flag`] is set pub fn is_disable_version_flag_set(&self) -> bool { self.is_set(AppSettings::DisableVersionFlag) || (self.version.is_none() && self.long_version.is_none()) } /// Report whether [`Command::propagate_version`] is set pub fn is_propagate_version_set(&self) -> bool { self.is_set(AppSettings::PropagateVersion) } /// Report whether [`Command::next_line_help`] is set pub fn is_next_line_help_set(&self) -> bool { self.is_set(AppSettings::NextLineHelp) } /// Report whether [`Command::disable_help_flag`] is set pub fn is_disable_help_flag_set(&self) -> bool { self.is_set(AppSettings::DisableHelpFlag) } /// Report whether [`Command::disable_help_subcommand`] is set pub fn is_disable_help_subcommand_set(&self) -> bool { self.is_set(AppSettings::DisableHelpSubcommand) } /// Report whether [`Command::disable_colored_help`] is set pub fn is_disable_colored_help_set(&self) -> bool { self.is_set(AppSettings::DisableColoredHelp) } /// Report whether [`Command::help_expected`] is set #[cfg(debug_assertions)] pub(crate) fn is_help_expected_set(&self) -> bool { self.is_set(AppSettings::HelpExpected) } #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "This is now the default") )] pub fn is_dont_collapse_args_in_usage_set(&self) -> bool { true } /// Report whether [`Command::infer_long_args`] is set pub(crate) fn is_infer_long_args_set(&self) -> bool { self.is_set(AppSettings::InferLongArgs) } /// Report whether [`Command::infer_subcommands`] is set pub(crate) fn is_infer_subcommands_set(&self) -> bool { self.is_set(AppSettings::InferSubcommands) } /// Report whether [`Command::arg_required_else_help`] is set pub fn is_arg_required_else_help_set(&self) -> bool { self.is_set(AppSettings::ArgRequiredElseHelp) } #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated( since = "4.0.0", note = "Replaced with `Arg::is_allow_hyphen_values_set`" ) )] pub(crate) fn is_allow_hyphen_values_set(&self) -> bool { self.is_set(AppSettings::AllowHyphenValues) } #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated( since = "4.0.0", note = "Replaced with `Arg::is_allow_negative_numbers_set`" ) )] pub fn is_allow_negative_numbers_set(&self) -> bool { self.is_set(AppSettings::AllowNegativeNumbers) } #[doc(hidden)] #[cfg_attr( feature = "deprecated", deprecated(since = "4.0.0", note = "Replaced with `Arg::is_trailing_var_arg_set`") )] pub fn is_trailing_var_arg_set(&self) -> bool { self.is_set(AppSettings::TrailingVarArg) } /// Report whether [`Command::allow_missing_positional`] is set pub fn is_allow_missing_positional_set(&self) -> bool { self.is_set(AppSettings::AllowMissingPositional) } /// Report whether [`Command::hide`] is set pub fn is_hide_set(&self) -> bool { self.is_set(AppSettings::Hidden) } /// Report whether [`Command::subcommand_required`] is set pub fn is_subcommand_required_set(&self) -> bool { self.is_set(AppSettings::SubcommandRequired) } /// Report whether [`Command::allow_external_subcommands`] is set pub fn is_allow_external_subcommands_set(&self) -> bool { self.is_set(AppSettings::AllowExternalSubcommands) } /// Configured parser for values passed to an external subcommand /// /// # Example /// /// ```rust /// # use clap_builder as clap; /// let cmd = clap::Command::new("raw") /// .external_subcommand_value_parser(clap::value_parser!(String)); /// let value_parser = cmd.get_external_subcommand_value_parser(); /// println!("{value_parser:?}"); /// ``` pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> { if !self.is_allow_external_subcommands_set() { None } else { static DEFAULT: super::ValueParser = super::ValueParser::os_string(); Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT)) } } /// Report whether [`Command::args_conflicts_with_subcommands`] is set pub fn is_args_conflicts_with_subcommands_set(&self) -> bool { self.is_set(AppSettings::ArgsNegateSubcommands) } #[doc(hidden)] pub fn is_args_override_self(&self) -> bool { self.is_set(AppSettings::AllArgsOverrideSelf) } /// Report whether [`Command::subcommand_precedence_over_arg`] is set pub fn is_subcommand_precedence_over_arg_set(&self) -> bool { self.is_set(AppSettings::SubcommandPrecedenceOverArg) } /// Report whether [`Command::subcommand_negates_reqs`] is set pub fn is_subcommand_negates_reqs_set(&self) -> bool { self.is_set(AppSettings::SubcommandsNegateReqs) } /// Report whether [`Command::multicall`] is set pub fn is_multicall_set(&self) -> bool { self.is_set(AppSettings::Multicall) } /// Access an [`CommandExt`] #[cfg(feature = "unstable-ext")] pub fn get(&self) -> Option<&T> { self.ext.get::() } /// Remove an [`CommandExt`] #[cfg(feature = "unstable-ext")] pub fn remove(mut self) -> Option { self.ext.remove::() } } // Internally used only impl Command { pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> { self.usage_str.as_ref() } pub(crate) fn get_override_help(&self) -> Option<&StyledStr> { self.help_str.as_ref() } #[cfg(feature = "help")] pub(crate) fn get_help_template(&self) -> Option<&StyledStr> { self.template.as_ref() } #[cfg(feature = "help")] pub(crate) fn get_term_width(&self) -> Option { self.app_ext.get::().map(|e| e.0) } #[cfg(feature = "help")] pub(crate) fn get_max_term_width(&self) -> Option { self.app_ext.get::().map(|e| e.0) } pub(crate) fn get_keymap(&self) -> &MKeyMap { &self.args } fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec) { global_arg_vec.extend( self.args .args() .filter(|a| a.is_global_set()) .map(|ga| ga.id.clone()), ); if let Some((id, matches)) = matches.subcommand() { if let Some(used_sub) = self.find_subcommand(id) { used_sub.get_used_global_args(matches, global_arg_vec); } } } fn _do_parse( &mut self, raw_args: &mut clap_lex::RawArgs, args_cursor: clap_lex::ArgCursor, ) -> ClapResult { debug!("Command::_do_parse"); // If there are global arguments, or settings we need to propagate them down to subcommands // before parsing in case we run into a subcommand self._build_self(false); let mut matcher = ArgMatcher::new(self); // do the real parsing let mut parser = Parser::new(self); if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) { if self.is_set(AppSettings::IgnoreErrors) && error.use_stderr() { debug!("Command::_do_parse: ignoring error: {error}"); } else { return Err(error); } } let mut global_arg_vec = Default::default(); self.get_used_global_args(&matcher, &mut global_arg_vec); matcher.propagate_globals(&global_arg_vec); Ok(matcher.into_inner()) } /// Prepare for introspecting on all included [`Command`]s /// /// Call this on the top-level [`Command`] when done building and before reading state for /// cases like completions, custom help output, etc. pub fn build(&mut self) { self._build_recursive(true); self._build_bin_names_internal(); } pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) { self._build_self(expand_help_tree); for subcmd in self.get_subcommands_mut() { subcmd._build_recursive(expand_help_tree); } } pub(crate) fn _build_self(&mut self, expand_help_tree: bool) { debug!("Command::_build: name={:?}", self.get_name()); if !self.settings.is_set(AppSettings::Built) { if let Some(deferred) = self.deferred.take() { *self = (deferred)(std::mem::take(self)); } // Make sure all the globally set flags apply to us as well self.settings = self.settings | self.g_settings; if self.is_multicall_set() { self.settings.set(AppSettings::SubcommandRequired); self.settings.set(AppSettings::DisableHelpFlag); self.settings.set(AppSettings::DisableVersionFlag); } if !cfg!(feature = "help") && self.get_override_help().is_none() { self.settings.set(AppSettings::DisableHelpFlag); self.settings.set(AppSettings::DisableHelpSubcommand); } if self.is_set(AppSettings::ArgsNegateSubcommands) { self.settings.set(AppSettings::SubcommandsNegateReqs); } if self.external_value_parser.is_some() { self.settings.set(AppSettings::AllowExternalSubcommands); } if !self.has_subcommands() { self.settings.set(AppSettings::DisableHelpSubcommand); } self._propagate(); self._check_help_and_version(expand_help_tree); self._propagate_global_args(); let mut pos_counter = 1; let hide_pv = self.is_set(AppSettings::HidePossibleValues); for a in self.args.args_mut() { // Fill in the groups for g in &a.groups { if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) { ag.args.push(a.get_id().clone()); } else { let mut ag = ArgGroup::new(g); ag.args.push(a.get_id().clone()); self.groups.push(ag); } } // Figure out implied settings a._build(); if hide_pv && a.is_takes_value_set() { a.settings.set(ArgSettings::HidePossibleValues); } if a.is_positional() && a.index.is_none() { a.index = Some(pos_counter); pos_counter += 1; } } self.args._build(); #[allow(deprecated)] { let highest_idx = self .get_keymap() .keys() .filter_map(|x| { if let crate::mkeymap::KeyType::Position(n) = x { Some(*n) } else { None } }) .max() .unwrap_or(0); let is_trailing_var_arg_set = self.is_trailing_var_arg_set(); let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set(); let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set(); for arg in self.args.args_mut() { if is_allow_hyphen_values_set && arg.is_takes_value_set() { arg.settings.set(ArgSettings::AllowHyphenValues); } if is_allow_negative_numbers_set && arg.is_takes_value_set() { arg.settings.set(ArgSettings::AllowNegativeNumbers); } if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) { arg.settings.set(ArgSettings::TrailingVarArg); } } } #[cfg(debug_assertions)] assert_app(self); self.settings.set(AppSettings::Built); } else { debug!("Command::_build: already built"); } } pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> { use std::fmt::Write; let mut mid_string = String::from(" "); #[cfg(feature = "usage")] if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set() { let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) for s in &reqs { mid_string.push_str(&s.to_string()); mid_string.push(' '); } } let is_multicall_set = self.is_multicall_set(); let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name)); // Display subcommand name, short and long in usage let mut sc_names = String::new(); sc_names.push_str(sc.name.as_str()); let mut flag_subcmd = false; if let Some(l) = sc.get_long_flag() { write!(sc_names, "|--{l}").unwrap(); flag_subcmd = true; } if let Some(s) = sc.get_short_flag() { write!(sc_names, "|-{s}").unwrap(); flag_subcmd = true; } if flag_subcmd { sc_names = format!("{{{sc_names}}}"); } let usage_name = self .bin_name .as_ref() .map(|bin_name| format!("{bin_name}{mid_string}{sc_names}")) .unwrap_or(sc_names); sc.usage_name = Some(usage_name); // bin_name should be parent's bin_name + [] + the sc's name separated by // a space let bin_name = format!( "{}{}{}", self.bin_name.as_deref().unwrap_or_default(), if self.bin_name.is_some() { " " } else { "" }, &*sc.name ); debug!( "Command::_build_subcommand Setting bin_name of {} to {:?}", sc.name, bin_name ); sc.bin_name = Some(bin_name); if sc.display_name.is_none() { let self_display_name = if is_multicall_set { self.display_name.as_deref().unwrap_or("") } else { self.display_name.as_deref().unwrap_or(&self.name) }; let display_name = format!( "{}{}{}", self_display_name, if !self_display_name.is_empty() { "-" } else { "" }, &*sc.name ); debug!( "Command::_build_subcommand Setting display_name of {} to {:?}", sc.name, display_name ); sc.display_name = Some(display_name); } // Ensure all args are built and ready to parse sc._build_self(false); Some(sc) } fn _build_bin_names_internal(&mut self) { debug!("Command::_build_bin_names"); if !self.is_set(AppSettings::BinNameBuilt) { let mut mid_string = String::from(" "); #[cfg(feature = "usage")] if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set() { let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) for s in &reqs { mid_string.push_str(&s.to_string()); mid_string.push(' '); } } let is_multicall_set = self.is_multicall_set(); let self_bin_name = if is_multicall_set { self.bin_name.as_deref().unwrap_or("") } else { self.bin_name.as_deref().unwrap_or(&self.name) } .to_owned(); for sc in &mut self.subcommands { debug!("Command::_build_bin_names:iter: bin_name set..."); if sc.usage_name.is_none() { use std::fmt::Write; // Display subcommand name, short and long in usage let mut sc_names = String::new(); sc_names.push_str(sc.name.as_str()); let mut flag_subcmd = false; if let Some(l) = sc.get_long_flag() { write!(sc_names, "|--{l}").unwrap(); flag_subcmd = true; } if let Some(s) = sc.get_short_flag() { write!(sc_names, "|-{s}").unwrap(); flag_subcmd = true; } if flag_subcmd { sc_names = format!("{{{sc_names}}}"); } let usage_name = format!("{self_bin_name}{mid_string}{sc_names}"); debug!( "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}", sc.name, usage_name ); sc.usage_name = Some(usage_name); } else { debug!( "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})", sc.name, sc.usage_name ); } if sc.bin_name.is_none() { let bin_name = format!( "{}{}{}", self_bin_name, if !self_bin_name.is_empty() { " " } else { "" }, &*sc.name ); debug!( "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}", sc.name, bin_name ); sc.bin_name = Some(bin_name); } else { debug!( "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})", sc.name, sc.bin_name ); } if sc.display_name.is_none() { let self_display_name = if is_multicall_set { self.display_name.as_deref().unwrap_or("") } else { self.display_name.as_deref().unwrap_or(&self.name) }; let display_name = format!( "{}{}{}", self_display_name, if !self_display_name.is_empty() { "-" } else { "" }, &*sc.name ); debug!( "Command::_build_bin_names:iter: Setting display_name of {} to {:?}", sc.name, display_name ); sc.display_name = Some(display_name); } else { debug!( "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})", sc.name, sc.display_name ); } sc._build_bin_names_internal(); } self.set(AppSettings::BinNameBuilt); } else { debug!("Command::_build_bin_names: already built"); } } pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) { if self.is_set(AppSettings::HelpExpected) || help_required_globally { let args_missing_help: Vec = self .args .args() .filter(|arg| arg.get_help().is_none() && arg.get_long_help().is_none()) .map(|arg| arg.get_id().clone()) .collect(); debug_assert!(args_missing_help.is_empty(), "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}", self.name, args_missing_help.join(", ") ); } for sub_app in &self.subcommands { sub_app._panic_on_missing_help(help_required_globally); } } /// Returns the first two arguments that match the condition. /// /// If fewer than two arguments that match the condition, `None` is returned. #[cfg(debug_assertions)] pub(crate) fn two_args_of(&self, condition: F) -> Option<(&Arg, &Arg)> where F: Fn(&Arg) -> bool, { two_elements_of(self.args.args().filter(|a: &&Arg| condition(a))) } /// Returns the first two groups that match the condition. /// /// If fewer than two groups that match the condition, `None` is returned. #[allow(unused)] fn two_groups_of(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)> where F: Fn(&ArgGroup) -> bool, { two_elements_of(self.groups.iter().filter(|a| condition(a))) } /// Propagate global args pub(crate) fn _propagate_global_args(&mut self) { debug!("Command::_propagate_global_args:{}", self.name); let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set(); for sc in &mut self.subcommands { if sc.get_name() == "help" && autogenerated_help_subcommand { // Avoid propagating args to the autogenerated help subtrees used in completion. // This prevents args from showing up during help completions like // `myapp help subcmd `, which should only suggest subcommands and not args, // while still allowing args to show up properly on the generated help message. continue; } for a in self.args.args().filter(|a| a.is_global_set()) { if sc.find(&a.id).is_some() { debug!( "Command::_propagate skipping {:?} to {}, already exists", a.id, sc.get_name(), ); continue; } debug!( "Command::_propagate pushing {:?} to {}", a.id, sc.get_name(), ); sc.args.push(a.clone()); } } } /// Propagate settings pub(crate) fn _propagate(&mut self) { debug!("Command::_propagate:{}", self.name); let mut subcommands = std::mem::take(&mut self.subcommands); for sc in &mut subcommands { self._propagate_subcommand(sc); } self.subcommands = subcommands; } fn _propagate_subcommand(&self, sc: &mut Self) { // We have to create a new scope in order to tell rustc the borrow of `sc` is // done and to recursively call this method { if self.settings.is_set(AppSettings::PropagateVersion) { if let Some(version) = self.version.as_ref() { sc.version.get_or_insert_with(|| version.clone()); } if let Some(long_version) = self.long_version.as_ref() { sc.long_version.get_or_insert_with(|| long_version.clone()); } } sc.settings = sc.settings | self.g_settings; sc.g_settings = sc.g_settings | self.g_settings; sc.app_ext.update(&self.app_ext); } } pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) { debug!( "Command::_check_help_and_version:{} expand_help_tree={}", self.name, expand_help_tree ); self.long_help_exists = self.long_help_exists_(); if !self.is_disable_help_flag_set() { debug!("Command::_check_help_and_version: Building default --help"); let mut arg = Arg::new(Id::HELP) .short('h') .long("help") .action(ArgAction::Help); if self.long_help_exists { arg = arg .help("Print help (see more with '--help')") .long_help("Print help (see a summary with '-h')"); } else { arg = arg.help("Print help"); } // Avoiding `arg_internal` to not be sensitive to `next_help_heading` / // `next_display_order` self.args.push(arg); } if !self.is_disable_version_flag_set() { debug!("Command::_check_help_and_version: Building default --version"); let arg = Arg::new(Id::VERSION) .short('V') .long("version") .action(ArgAction::Version) .help("Print version"); // Avoiding `arg_internal` to not be sensitive to `next_help_heading` / // `next_display_order` self.args.push(arg); } if !self.is_set(AppSettings::DisableHelpSubcommand) { debug!("Command::_check_help_and_version: Building help subcommand"); let help_about = "Print this message or the help of the given subcommand(s)"; let mut help_subcmd = if expand_help_tree { // Slow code path to recursively clone all other subcommand subtrees under help let help_subcmd = Command::new("help") .about(help_about) .global_setting(AppSettings::DisableHelpSubcommand) .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); let mut help_help_subcmd = Command::new("help").about(help_about); help_help_subcmd.version = None; help_help_subcmd.long_version = None; help_help_subcmd = help_help_subcmd .setting(AppSettings::DisableHelpFlag) .setting(AppSettings::DisableVersionFlag); help_subcmd.subcommand(help_help_subcmd) } else { Command::new("help").about(help_about).arg( Arg::new("subcommand") .action(ArgAction::Append) .num_args(..) .value_name("COMMAND") .help("Print help for the subcommand(s)"), ) }; self._propagate_subcommand(&mut help_subcmd); // The parser acts like this is set, so let's set it so we don't falsely // advertise it to the user help_subcmd.version = None; help_subcmd.long_version = None; help_subcmd = help_subcmd .setting(AppSettings::DisableHelpFlag) .setting(AppSettings::DisableVersionFlag) .unset_global_setting(AppSettings::PropagateVersion); self.subcommands.push(help_subcmd); } } fn _copy_subtree_for_help(&self) -> Command { let mut cmd = Command::new(self.name.clone()) .hide(self.is_hide_set()) .global_setting(AppSettings::DisableHelpFlag) .global_setting(AppSettings::DisableVersionFlag) .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); if self.get_about().is_some() { cmd = cmd.about(self.get_about().unwrap().clone()); } cmd } pub(crate) fn _render_version(&self, use_long: bool) -> String { debug!("Command::_render_version"); let ver = if use_long { self.long_version .as_deref() .or(self.version.as_deref()) .unwrap_or_default() } else { self.version .as_deref() .or(self.long_version.as_deref()) .unwrap_or_default() }; let display_name = self.get_display_name().unwrap_or_else(|| self.get_name()); format!("{display_name} {ver}\n") } pub(crate) fn format_group(&self, g: &Id) -> StyledStr { use std::fmt::Write as _; let g_string = self .unroll_args_in_group(g) .iter() .filter_map(|x| self.find(x)) .map(|x| { if x.is_positional() { // Print val_name for positional arguments. e.g. x.name_no_brackets() } else { // Print usage string for flags arguments, e.g. <--help> x.to_string() } }) .collect::>() .join("|"); let placeholder = self.get_styles().get_placeholder(); let mut styled = StyledStr::new(); write!(&mut styled, "{placeholder}<{g_string}>{placeholder:#}").unwrap(); styled } } /// A workaround: /// pub(crate) trait Captures<'a> {} impl Captures<'_> for T {} // Internal Query Methods impl Command { /// Iterate through the *flags* & *options* arguments. #[cfg(any(feature = "usage", feature = "help"))] pub(crate) fn get_non_positionals(&self) -> impl Iterator { self.get_arguments().filter(|a| !a.is_positional()) } pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg> { self.args.args().find(|a| a.get_id() == arg_id) } #[inline] pub(crate) fn contains_short(&self, s: char) -> bool { debug_assert!( self.is_set(AppSettings::Built), "If Command::_build hasn't been called, manually search through Arg shorts" ); self.args.contains(s) } #[inline] pub(crate) fn set(&mut self, s: AppSettings) { self.settings.set(s); } #[inline] pub(crate) fn has_positionals(&self) -> bool { self.get_positionals().next().is_some() } #[cfg(any(feature = "usage", feature = "help"))] pub(crate) fn has_visible_subcommands(&self) -> bool { self.subcommands .iter() .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden)) } /// Check if this subcommand can be referred to as `name`. In other words, /// check if `name` is the name of this subcommand or is one of its aliases. #[inline] pub(crate) fn aliases_to(&self, name: impl AsRef) -> bool { let name = name.as_ref(); self.get_name() == name || self.get_all_aliases().any(|alias| alias == name) } /// Check if this subcommand can be referred to as `name`. In other words, /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases. #[inline] pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool { Some(flag) == self.short_flag || self.get_all_short_flag_aliases().any(|alias| flag == alias) } /// Check if this subcommand can be referred to as `name`. In other words, /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases. #[inline] pub(crate) fn long_flag_aliases_to(&self, flag: &str) -> bool { match self.long_flag.as_ref() { Some(long_flag) => { long_flag == flag || self.get_all_long_flag_aliases().any(|alias| alias == flag) } None => self.get_all_long_flag_aliases().any(|alias| alias == flag), } } /// Checks if there is an argument or group with the given id. #[cfg(debug_assertions)] pub(crate) fn id_exists(&self, id: &Id) -> bool { self.args.args().any(|x| x.get_id() == id) || self.groups.iter().any(|x| x.id == *id) } /// Iterate through the groups this arg is member of. pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator + 'a { debug!("Command::groups_for_arg: id={arg:?}"); let arg = arg.clone(); self.groups .iter() .filter(move |grp| grp.args.iter().any(|a| a == &arg)) .map(|grp| grp.id.clone()) } pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup> { self.groups.iter().find(|g| g.id == *group_id) } /// Iterate through all the names of all subcommands (not recursively), including aliases. /// Used for suggestions. pub(crate) fn all_subcommand_names(&self) -> impl Iterator + Captures<'_> { self.get_subcommands().flat_map(|sc| { let name = sc.get_name(); let aliases = sc.get_all_aliases(); std::iter::once(name).chain(aliases) }) } pub(crate) fn required_graph(&self) -> ChildGraph { let mut reqs = ChildGraph::with_capacity(5); for a in self.args.args().filter(|a| a.is_required_set()) { reqs.insert(a.get_id().clone()); } for group in &self.groups { if group.required { let idx = reqs.insert(group.id.clone()); for a in &group.requires { reqs.insert_child(idx, a.clone()); } } } reqs } pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec { debug!("Command::unroll_args_in_group: group={group:?}"); let mut g_vec = vec![group]; let mut args = vec![]; while let Some(g) = g_vec.pop() { for n in self .groups .iter() .find(|grp| grp.id == *g) .expect(INTERNAL_ERROR_MSG) .args .iter() { debug!("Command::unroll_args_in_group:iter: entity={n:?}"); if !args.contains(n) { if self.find(n).is_some() { debug!("Command::unroll_args_in_group:iter: this is an arg"); args.push(n.clone()); } else { debug!("Command::unroll_args_in_group:iter: this is a group"); g_vec.push(n); } } } } args } pub(crate) fn unroll_arg_requires(&self, func: F, arg: &Id) -> Vec where F: Fn(&(ArgPredicate, Id)) -> Option, { let mut processed = vec![]; let mut r_vec = vec![arg]; let mut args = vec![]; while let Some(a) = r_vec.pop() { if processed.contains(&a) { continue; } processed.push(a); if let Some(arg) = self.find(a) { for r in arg.requires.iter().filter_map(&func) { if let Some(req) = self.find(&r) { if !req.requires.is_empty() { r_vec.push(req.get_id()); } } args.push(r); } } } args } /// Find a flag subcommand name by short flag or an alias pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> { self.get_subcommands() .find(|sc| sc.short_flag_aliases_to(c)) .map(|sc| sc.get_name()) } /// Find a flag subcommand name by long flag or an alias pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> { self.get_subcommands() .find(|sc| sc.long_flag_aliases_to(long)) .map(|sc| sc.get_name()) } pub(crate) fn write_help_err(&self, mut use_long: bool) -> StyledStr { debug!( "Command::write_help_err: {}, use_long={:?}", self.get_display_name().unwrap_or_else(|| self.get_name()), use_long && self.long_help_exists(), ); use_long = use_long && self.long_help_exists(); let usage = Usage::new(self); let mut styled = StyledStr::new(); write_help(&mut styled, self, &usage, use_long); styled } pub(crate) fn write_version_err(&self, use_long: bool) -> StyledStr { let msg = self._render_version(use_long); StyledStr::from(msg) } pub(crate) fn long_help_exists(&self) -> bool { debug!("Command::long_help_exists: {}", self.long_help_exists); self.long_help_exists } fn long_help_exists_(&self) -> bool { debug!("Command::long_help_exists"); // In this case, both must be checked. This allows the retention of // original formatting, but also ensures that the actual -h or --help // specified by the user is sent through. If hide_short_help is not included, // then items specified with hidden_short_help will also be hidden. let should_long = |v: &Arg| { !v.is_hide_set() && (v.get_long_help().is_some() || v.is_hide_long_help_set() || v.is_hide_short_help_set() || (!v.is_hide_possible_values_set() && v.get_possible_values() .iter() .any(PossibleValue::should_show_help))) }; // Subcommands aren't checked because we prefer short help for them, deferring to // `cmd subcmd --help` for more. self.get_long_about().is_some() || self.get_before_long_help().is_some() || self.get_after_long_help().is_some() || self.get_arguments().any(should_long) } // Should we color the help? pub(crate) fn color_help(&self) -> ColorChoice { #[cfg(feature = "color")] if self.is_disable_colored_help_set() { return ColorChoice::Never; } self.get_color() } } impl Default for Command { fn default() -> Self { Self { name: Default::default(), long_flag: Default::default(), short_flag: Default::default(), display_name: Default::default(), bin_name: Default::default(), author: Default::default(), version: Default::default(), long_version: Default::default(), about: Default::default(), long_about: Default::default(), before_help: Default::default(), before_long_help: Default::default(), after_help: Default::default(), after_long_help: Default::default(), aliases: Default::default(), short_flag_aliases: Default::default(), long_flag_aliases: Default::default(), usage_str: Default::default(), usage_name: Default::default(), help_str: Default::default(), disp_ord: Default::default(), #[cfg(feature = "help")] template: Default::default(), settings: Default::default(), g_settings: Default::default(), args: Default::default(), subcommands: Default::default(), groups: Default::default(), current_help_heading: Default::default(), current_disp_ord: Some(0), subcommand_value_name: Default::default(), subcommand_heading: Default::default(), external_value_parser: Default::default(), long_help_exists: false, deferred: None, #[cfg(feature = "unstable-ext")] ext: Default::default(), app_ext: Default::default(), } } } impl Index<&'_ Id> for Command { type Output = Arg; fn index(&self, key: &Id) -> &Self::Output { self.find(key).expect(INTERNAL_ERROR_MSG) } } impl From<&'_ Command> for Command { fn from(cmd: &'_ Command) -> Self { cmd.clone() } } impl fmt::Display for Command { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.name) } } /// User-provided data that can be attached to an [`Arg`] #[cfg(feature = "unstable-ext")] pub trait CommandExt: Extension {} #[allow(dead_code)] // atm dependent on features enabled pub(crate) trait AppExt: Extension {} #[allow(dead_code)] // atm dependent on features enabled #[derive(Default, Copy, Clone, Debug)] struct TermWidth(usize); impl AppExt for TermWidth {} #[allow(dead_code)] // atm dependent on features enabled #[derive(Default, Copy, Clone, Debug)] struct MaxTermWidth(usize); impl AppExt for MaxTermWidth {} /// Returns the first two elements of an iterator as an `Option<(T, T)>`. /// /// If the iterator has fewer than two elements, it returns `None`. fn two_elements_of(mut iter: I) -> Option<(T, T)> where I: Iterator, { let first = iter.next(); let second = iter.next(); match (first, second) { (Some(first), Some(second)) => Some((first, second)), _ => None, } } #[test] fn check_auto_traits() { static_assertions::assert_impl_all!(Command: Send, Sync, Unpin); } clap_builder-4.5.48/src/builder/debug_asserts.rs000064400000000000000000000676141046102023000200060ustar 00000000000000use std::cmp::Ordering; use crate::builder::ValueRange; use crate::mkeymap::KeyType; use crate::util::FlatSet; use crate::util::Id; use crate::ArgAction; use crate::INTERNAL_ERROR_MSG; use crate::{Arg, Command, ValueHint}; pub(crate) fn assert_app(cmd: &Command) { debug!("Command::_debug_asserts"); let mut short_flags = vec![]; let mut long_flags = vec![]; // Invalid version flag settings if cmd.get_version().is_none() && cmd.get_long_version().is_none() { // PropagateVersion is meaningless if there is no version assert!( !cmd.is_propagate_version_set(), "Command {}: No version information via Command::version or Command::long_version to propagate", cmd.get_name(), ); // Used `Command::mut_arg("version", ..) but did not provide any version information to display let version_needed = cmd .get_arguments() .filter(|x| matches!(x.get_action(), ArgAction::Version)) .map(|x| x.get_id()) .collect::>(); assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version" ,cmd.get_name() ); } for sc in cmd.get_subcommands() { if let Some(s) = sc.get_short_flag().as_ref() { short_flags.push(Flag::Command(format!("-{s}"), sc.get_name())); } for short_alias in sc.get_all_short_flag_aliases() { short_flags.push(Flag::Command(format!("-{short_alias}"), sc.get_name())); } if let Some(l) = sc.get_long_flag().as_ref() { assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l); long_flags.push(Flag::Command(format!("--{l}"), sc.get_name())); } for long_alias in sc.get_all_long_flag_aliases() { long_flags.push(Flag::Command(format!("--{long_alias}"), sc.get_name())); } } for arg in cmd.get_arguments() { assert_arg(arg); assert!( !cmd.is_multicall_set(), "Command {}: Arguments like {} cannot be set on a multicall command", cmd.get_name(), arg.get_id() ); if let Some(s) = arg.get_short() { short_flags.push(Flag::Arg(format!("-{s}"), arg.get_id().as_str())); } for (short_alias, _) in &arg.short_aliases { short_flags.push(Flag::Arg(format!("-{short_alias}"), arg.get_id().as_str())); } if let Some(l) = arg.get_long() { assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l); long_flags.push(Flag::Arg(format!("--{l}"), arg.get_id().as_str())); } for (long_alias, _) in &arg.aliases { long_flags.push(Flag::Arg(format!("--{long_alias}"), arg.get_id().as_str())); } // Name conflicts if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) { panic!( "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}", cmd.get_name(), arg.get_id(), duplicate_tip(cmd, first, second), ); } // Long conflicts if let Some(l) = arg.get_long() { if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) { panic!( "Command {}: Long option names must be unique for each argument, \ but '--{}' is in use by both '{}' and '{}'{}", cmd.get_name(), l, first.get_id(), second.get_id(), duplicate_tip(cmd, first, second) ) } } // Short conflicts if let Some(s) = arg.get_short() { if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) { panic!( "Command {}: Short option names must be unique for each argument, \ but '-{}' is in use by both '{}' and '{}'{}", cmd.get_name(), s, first.get_id(), second.get_id(), duplicate_tip(cmd, first, second), ) } } // Index conflicts if let Some(idx) = arg.index { if let Some((first, second)) = cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx)) { panic!( "Command {}: Argument '{}' has the same index as '{}' \ and they are both positional arguments\n\n\t \ Use `Arg::num_args(1..)` to allow one \ positional argument to take multiple values", cmd.get_name(), first.get_id(), second.get_id() ) } } // requires, r_if, r_unless for (_predicate, req_id) in &arg.requires { assert!( &arg.id != req_id, "Argument {} cannot require itself", arg.get_id() ); assert!( cmd.id_exists(req_id), "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist", cmd.get_name(), req_id, arg.get_id(), ); } for req in &arg.r_ifs { assert!( !arg.is_required_set(), "Argument {}: `required` conflicts with `required_if_eq*`", arg.get_id() ); assert!( cmd.id_exists(&req.0), "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist", cmd.get_name(), req.0, arg.get_id() ); } for req in &arg.r_ifs_all { assert!( !arg.is_required_set(), "Argument {}: `required` conflicts with `required_if_eq_all`", arg.get_id() ); assert!( cmd.id_exists(&req.0), "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist", cmd.get_name(), req.0, arg.get_id() ); } for req in &arg.r_unless { assert!( !arg.is_required_set(), "Argument {}: `required` conflicts with `required_unless*`", arg.get_id() ); assert!( cmd.id_exists(req), "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist", cmd.get_name(), req, arg.get_id(), ); } for req in &arg.r_unless_all { assert!( !arg.is_required_set(), "Argument {}: `required` conflicts with `required_unless*`", arg.get_id() ); assert!( cmd.id_exists(req), "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist", cmd.get_name(), req, arg.get_id(), ); } // blacklist for req in &arg.blacklist { assert!( cmd.id_exists(req), "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist", cmd.get_name(), req, arg.get_id(), ); } // overrides for req in &arg.overrides { assert!( cmd.id_exists(req), "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist", cmd.get_name(), req, arg.get_id(), ); } if arg.is_last_set() { assert!( arg.get_long().is_none(), "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.", cmd.get_name(), arg.get_id() ); assert!( arg.get_short().is_none(), "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.", cmd.get_name(), arg.get_id() ); } assert!( !(arg.is_required_set() && arg.is_global_set()), "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required", cmd.get_name(), arg.get_id() ); if arg.get_value_hint() == ValueHint::CommandWithArguments { assert!( arg.is_positional(), "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.", cmd.get_name(), arg.get_id() ); assert!( arg.is_trailing_var_arg_set() || arg.is_last_set(), "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.", cmd.get_name(), arg.get_id() ); } } for group in cmd.get_groups() { // Name conflicts assert!( cmd.get_groups().filter(|x| x.id == group.id).count() < 2, "Command {}: Argument group name must be unique\n\n\t'{}' is already in use", cmd.get_name(), group.get_id(), ); // Groups should not have naming conflicts with Args assert!( !cmd.get_arguments().any(|x| x.get_id() == group.get_id()), "Command {}: Argument group name '{}' must not conflict with argument name", cmd.get_name(), group.get_id(), ); for arg in &group.args { // Args listed inside groups should exist assert!( cmd.get_arguments().any(|x| x.get_id() == arg), "Command {}: Argument group '{}' contains non-existent argument '{}'", cmd.get_name(), group.get_id(), arg ); } for arg in &group.requires { // Args listed inside groups should exist assert!( cmd.id_exists(arg), "Command {}: Argument group '{}' requires non-existent '{}' id", cmd.get_name(), group.get_id(), arg ); } for arg in &group.conflicts { // Args listed inside groups should exist assert!( cmd.id_exists(arg), "Command {}: Argument group '{}' conflicts with non-existent '{}' id", cmd.get_name(), group.get_id(), arg ); } } // Conflicts between flags and subcommands long_flags.sort_unstable(); short_flags.sort_unstable(); detect_duplicate_flags(&long_flags, "long"); detect_duplicate_flags(&short_flags, "short"); let mut subs = FlatSet::new(); for sc in cmd.get_subcommands() { assert!( subs.insert(sc.get_name()), "Command {}: command name `{}` is duplicated", cmd.get_name(), sc.get_name() ); for alias in sc.get_all_aliases() { assert!( subs.insert(alias), "Command {}: command `{}` alias `{}` is duplicated", cmd.get_name(), sc.get_name(), alias ); } } _verify_positionals(cmd); #[cfg(feature = "help")] if let Some(help_template) = cmd.get_help_template() { assert!( !help_template.to_string().contains("{flags}"), "Command {}: {}", cmd.get_name(), "`{flags}` template variable was removed in clap3, they are now included in `{options}`", ); assert!( !help_template.to_string().contains("{unified}"), "Command {}: {}", cmd.get_name(), "`{unified}` template variable was removed in clap3, use `{options}` instead" ); #[cfg(feature = "unstable-v5")] assert!( !help_template.to_string().contains("{bin}"), "Command {}: {}", cmd.get_name(), "`{bin}` template variable was removed in clap5, use `{name}` instead" ); } cmd._panic_on_missing_help(cmd.is_help_expected_set()); assert_app_flags(cmd); } fn duplicate_tip(cmd: &Command, first: &Arg, second: &Arg) -> &'static str { if !cmd.is_disable_help_flag_set() && (first.get_id() == Id::HELP || second.get_id() == Id::HELP) { " (call `cmd.disable_help_flag(true)` to remove the auto-generated `--help`)" } else if !cmd.is_disable_version_flag_set() && (first.get_id() == Id::VERSION || second.get_id() == Id::VERSION) { " (call `cmd.disable_version_flag(true)` to remove the auto-generated `--version`)" } else { "" } } #[derive(Eq)] enum Flag<'a> { Command(String, &'a str), Arg(String, &'a str), } impl PartialEq for Flag<'_> { fn eq(&self, other: &Flag<'_>) -> bool { self.cmp(other) == Ordering::Equal } } impl PartialOrd for Flag<'_> { fn partial_cmp(&self, other: &Flag<'_>) -> Option { Some(self.cmp(other)) } } impl Ord for Flag<'_> { fn cmp(&self, other: &Self) -> Ordering { match (self, other) { (Flag::Command(s1, _), Flag::Command(s2, _)) | (Flag::Arg(s1, _), Flag::Arg(s2, _)) | (Flag::Command(s1, _), Flag::Arg(s2, _)) | (Flag::Arg(s1, _), Flag::Command(s2, _)) => { if s1 == s2 { Ordering::Equal } else { s1.cmp(s2) } } } } } fn detect_duplicate_flags(flags: &[Flag<'_>], short_or_long: &str) { for (one, two) in find_duplicates(flags) { match (one, two) { (Flag::Command(flag, one), Flag::Command(_, another)) if one != another => panic!( "the '{flag}' {short_or_long} flag is specified for both '{one}' and '{another}' subcommands" ), (Flag::Arg(flag, one), Flag::Arg(_, another)) if one != another => panic!( "{short_or_long} option names must be unique, but '{flag}' is in use by both '{one}' and '{another}'" ), (Flag::Arg(flag, arg), Flag::Command(_, sub)) | (Flag::Command(flag, sub), Flag::Arg(_, arg)) => panic!( "the '{flag}' {short_or_long} flag for the '{arg}' argument conflicts with the short flag \ for '{sub}' subcommand" ), _ => {} } } } /// Find duplicates in a sorted array. /// /// The algorithm is simple: the array is sorted, duplicates /// must be placed next to each other, we can check only adjacent elements. fn find_duplicates(slice: &[T]) -> impl Iterator { slice.windows(2).filter_map(|w| { if w[0] == w[1] { Some((&w[0], &w[1])) } else { None } }) } fn assert_app_flags(cmd: &Command) { macro_rules! checker { ($a:ident conflicts $($b:ident)|+) => { if cmd.$a() { let mut s = String::new(); $( if cmd.$b() { use std::fmt::Write; write!(&mut s, " AppSettings::{} conflicts with AppSettings::{}.\n", std::stringify!($b), std::stringify!($a)).unwrap(); } )+ if !s.is_empty() { panic!("{}\n{}", cmd.get_name(), s) } } }; } checker!(is_multicall_set conflicts is_no_binary_name_set); } #[cfg(debug_assertions)] fn _verify_positionals(cmd: &Command) -> bool { debug!("Command::_verify_positionals"); // Because you must wait until all arguments have been supplied, this is the first chance // to make assertions on positional argument indexes // // First we verify that the index highest supplied index, is equal to the number of // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3 // but no 2) let highest_idx = cmd .get_keymap() .keys() .filter_map(|x| { if let KeyType::Position(n) = x { Some(*n) } else { None } }) .max() .unwrap_or(0); let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count(); assert!( highest_idx == num_p, "Found positional argument whose index is {highest_idx} but there \ are only {num_p} positional arguments defined", ); for arg in cmd.get_arguments() { if arg.index.unwrap_or(0) == highest_idx { assert!( !arg.is_trailing_var_arg_set() || !arg.is_last_set(), "{}:{}: `Arg::trailing_var_arg` and `Arg::last` cannot be used together", cmd.get_name(), arg.get_id() ); if arg.is_trailing_var_arg_set() { assert!( arg.is_multiple(), "{}:{}: `Arg::trailing_var_arg` must accept multiple values", cmd.get_name(), arg.get_id() ); } } else { assert!( !arg.is_trailing_var_arg_set(), "{}:{}: `Arg::trailing_var_arg` can only apply to last positional", cmd.get_name(), arg.get_id() ); } } // Next we verify that only the highest index has takes multiple arguments (if any) let only_highest = |a: &Arg| a.is_multiple() && (a.get_index().unwrap_or(0) != highest_idx); if cmd.get_positionals().any(only_highest) { // First we make sure if there is a positional that allows multiple values // the one before it (second to last) has one of these: // * a value terminator // * ArgSettings::Last // * The last arg is Required // We can't pass the closure (it.next()) to the macro directly because each call to // find() (iterator, not macro) gets called repeatedly. let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)]; let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)]; // Either the final positional is required // Or the second to last has a terminator or .last(true) set let ok = last.is_required_set() || (second_to_last.terminator.is_some() || second_to_last.is_last_set()) || last.is_last_set(); assert!( ok, "Positional argument `{last}` *must* have `required(true)` or `last(true)` set \ because a prior positional argument (`{second_to_last}`) has `num_args(1..)`" ); // We make sure if the second to last is Multiple the last is ArgSettings::Last let ok = second_to_last.is_multiple() || last.is_last_set(); assert!( ok, "Only the last positional argument, or second to last positional \ argument may be set to `.num_args(1..)`" ); // Next we check how many have both Multiple and not a specific number of values set let count = cmd .get_positionals() .filter(|p| { p.is_multiple_values_set() && p.get_value_terminator().is_none() && !p.get_num_args().expect(INTERNAL_ERROR_MSG).is_fixed() }) .count(); let ok = count <= 1 || (last.is_last_set() && last.is_multiple() && second_to_last.is_multiple() && count == 2); assert!( ok, "Only one positional argument with `.num_args(1..)` set is allowed per \ command, unless the second one also has .last(true) set" ); } let mut found = false; if cmd.is_allow_missing_positional_set() { // Check that if a required positional argument is found, all positions with a lower // index are also required. let mut foundx2 = false; for p in cmd.get_positionals() { if foundx2 && !p.is_required_set() { assert!( p.is_required_set(), "Found non-required positional argument with a lower \ index than a required positional argument by two or more: {:?} \ index {:?}", p.get_id(), p.get_index() ); } else if p.is_required_set() && !p.is_last_set() { // Args that .last(true) don't count since they can be required and have // positionals with a lower index that aren't required // Imagine: prog [opt1] -- // Both of these are valid invocations: // $ prog r1 -- r2 // $ prog r1 o1 -- r2 if found { foundx2 = true; continue; } found = true; } else { found = false; } } } else { // Check that if a required positional argument is found, all positions with a lower // index are also required for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) { if found { assert!( p.is_required_set(), "Found non-required positional argument with a lower \ index than a required positional argument: {:?} index {:?}", p.get_id(), p.get_index() ); } else if p.is_required_set() && !p.is_last_set() { // Args that .last(true) don't count since they can be required and have // positionals with a lower index that aren't required // Imagine: prog [opt1] -- // Both of these are valid invocations: // $ prog r1 -- r2 // $ prog r1 o1 -- r2 found = true; } } } assert!( cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2, "Only one positional argument may have last(true) set. Found two." ); if cmd .get_positionals() .any(|p| p.is_last_set() && p.is_required_set()) && cmd.has_subcommands() && !cmd.is_subcommand_negates_reqs_set() { panic!( "Having a required positional argument with .last(true) set *and* child \ subcommands without setting SubcommandsNegateReqs isn't compatible." ); } true } fn assert_arg(arg: &Arg) { debug!("Arg::_debug_asserts:{}", arg.get_id()); // Self conflict // TODO: this check should be recursive assert!( !arg.blacklist.iter().any(|x| x == arg.get_id()), "Argument '{}' cannot conflict with itself", arg.get_id(), ); assert!( arg.get_num_args().unwrap_or(1.into()).max_values() <= arg.get_action().max_num_args().max_values(), "Argument `{}`'s action {:?} is incompatible with `num_args({:?})`", arg.get_id(), arg.get_action(), arg.get_num_args().unwrap_or(1.into()) ); if let Some(action_type_id) = arg.get_action().value_type_id() { assert_eq!( action_type_id, arg.get_value_parser().type_id(), "Argument `{}`'s selected action {:?} contradicts `value_parser` ({:?})", arg.get_id(), arg.get_action(), arg.get_value_parser() ); } if arg.get_value_hint() != ValueHint::Unknown { assert!( arg.is_takes_value_set(), "Argument '{}' has value hint but takes no value", arg.get_id() ); if arg.get_value_hint() == ValueHint::CommandWithArguments { assert!( arg.is_multiple_values_set(), "Argument '{}' uses hint CommandWithArguments and must accept multiple values", arg.get_id() ); } } if arg.index.is_some() { assert!( arg.is_positional(), "Argument '{}' is a positional argument and can't have short or long name versions", arg.get_id() ); assert!( arg.is_takes_value_set(), "Argument '{}' is positional and it must take a value but action is {:?}{}", arg.get_id(), arg.get_action(), if arg.get_id() == Id::HELP { " (`mut_arg` no longer works with implicit `--help`)" } else if arg.get_id() == Id::VERSION { " (`mut_arg` no longer works with implicit `--version`)" } else { "" } ); } let num_vals = arg.get_num_args().expect(INTERNAL_ERROR_MSG); // This can be the cause of later asserts, so put this first if num_vals != ValueRange::EMPTY { // HACK: Don't check for flags to make the derive easier let num_val_names = arg.get_value_names().unwrap_or(&[]).len(); if num_vals.max_values() < num_val_names { panic!( "Argument {}: Too many value names ({}) compared to `num_args` ({})", arg.get_id(), num_val_names, num_vals ); } } assert_eq!( num_vals.is_multiple(), arg.is_multiple_values_set(), "Argument {}: mismatch between `num_args` ({}) and `multiple_values`", arg.get_id(), num_vals, ); if 1 < num_vals.min_values() { assert!( !arg.is_require_equals_set(), "Argument {}: cannot accept more than 1 arg (num_args={}) with require_equals", arg.get_id(), num_vals ); } if num_vals == ValueRange::SINGLE { assert!( !arg.is_multiple_values_set(), "Argument {}: mismatch between `num_args` and `multiple_values`", arg.get_id() ); } assert_arg_flags(arg); } fn assert_arg_flags(arg: &Arg) { macro_rules! checker { ($a:ident requires $($b:ident)|+) => { if arg.$a() { let mut s = String::new(); $( if !arg.$b() { use std::fmt::Write; write!(&mut s, " Arg::{} is required when Arg::{} is set.\n", std::stringify!($b), std::stringify!($a)).unwrap(); } )+ if !s.is_empty() { panic!("Argument {:?}\n{}", arg.get_id(), s) } } } } checker!(is_hide_possible_values_set requires is_takes_value_set); checker!(is_allow_hyphen_values_set requires is_takes_value_set); checker!(is_allow_negative_numbers_set requires is_takes_value_set); checker!(is_require_equals_set requires is_takes_value_set); checker!(is_last_set requires is_takes_value_set); checker!(is_hide_default_value_set requires is_takes_value_set); checker!(is_multiple_values_set requires is_takes_value_set); checker!(is_ignore_case_set requires is_takes_value_set); } clap_builder-4.5.48/src/builder/ext.rs000064400000000000000000000026021046102023000157360ustar 00000000000000use crate::util::AnyValue; use crate::util::AnyValueId; use crate::util::FlatMap; #[derive(Default, Clone, Debug)] pub(crate) struct Extensions { extensions: FlatMap, } impl Extensions { #[allow(dead_code)] pub(crate) fn get(&self) -> Option<&T> { let id = AnyValueId::of::(); self.extensions.get(&id).map(|e| { e.downcast_ref::() .expect("`Extensions` tracks values by type") }) } #[allow(dead_code)] pub(crate) fn set(&mut self, tagged: T) -> bool { let value = AnyValue::new(tagged); let id = value.type_id(); self.extensions.insert(id, value).is_some() } #[allow(dead_code)] pub(crate) fn remove(&mut self) -> Option { let id = AnyValueId::of::(); self.extensions.remove(&id).map(|e| { e.downcast_into::() .expect("`Extensions` tracks values by type") }) } pub(crate) fn update(&mut self, other: &Self) { for (key, value) in other.extensions.iter() { self.extensions.insert(*key, value.clone()); } } } #[allow(unreachable_pub)] pub trait Extension: std::fmt::Debug + Clone + std::any::Any + Send + Sync + 'static {} impl Extension for T where T: std::fmt::Debug + Clone + std::any::Any + Send + Sync + 'static {} clap_builder-4.5.48/src/builder/mod.rs000064400000000000000000000036011046102023000157150ustar 00000000000000//! Define [`Command`] line [arguments][`Arg`] mod action; mod app_settings; mod arg; mod arg_group; mod arg_predicate; mod arg_settings; mod command; mod ext; mod os_str; mod possible_value; mod range; mod resettable; mod str; mod styled_str; mod value_hint; mod value_parser; #[cfg(debug_assertions)] mod debug_asserts; #[cfg(test)] mod tests; pub mod styling; pub use self::str::Str; pub use action::ArgAction; pub use arg::Arg; #[cfg(feature = "unstable-ext")] pub use arg::ArgExt; pub use arg_group::ArgGroup; pub use arg_predicate::ArgPredicate; pub use command::Command; #[cfg(feature = "unstable-ext")] pub use command::CommandExt; pub use os_str::OsStr; pub use possible_value::PossibleValue; pub use range::ValueRange; pub use resettable::IntoResettable; pub use resettable::Resettable; pub use styled_str::StyledStr; pub use styling::Styles; pub use value_hint::ValueHint; pub use value_parser::BoolValueParser; pub use value_parser::_infer_ValueParser_for; pub use value_parser::impl_prelude; pub use value_parser::BoolishValueParser; pub use value_parser::EnumValueParser; pub use value_parser::FalseyValueParser; pub use value_parser::MapValueParser; pub use value_parser::NonEmptyStringValueParser; pub use value_parser::OsStringValueParser; pub use value_parser::PathBufValueParser; pub use value_parser::PossibleValuesParser; pub use value_parser::RangedI64ValueParser; pub use value_parser::RangedU64ValueParser; pub use value_parser::StringValueParser; pub use value_parser::TryMapValueParser; pub use value_parser::TypedValueParser; pub use value_parser::UnknownArgumentValueParser; pub use value_parser::ValueParser; pub use value_parser::ValueParserFactory; pub use value_parser::_AnonymousValueParser; #[allow(unused_imports)] pub(crate) use self::str::Inner as StrInner; pub(crate) use action::CountType; pub(crate) use arg_settings::{ArgFlags, ArgSettings}; pub(crate) use command::AppExt; clap_builder-4.5.48/src/builder/os_str.rs000064400000000000000000000170011046102023000164460ustar 00000000000000use crate::builder::Str; /// A UTF-8-encoded fixed string /// ///
/// /// **NOTE:** To support dynamic values (i.e. `OsString`), enable the `string` /// feature /// ///
#[derive(Default, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] pub struct OsStr { name: Inner, } impl OsStr { #[cfg(feature = "string")] pub(crate) fn from_string(name: std::ffi::OsString) -> Self { Self { name: Inner::from_string(name), } } #[cfg(feature = "string")] pub(crate) fn from_ref(name: &std::ffi::OsStr) -> Self { Self { name: Inner::from_ref(name), } } pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self { Self { name: Inner::from_static_ref(name), } } /// Get the raw string as an `std::ffi::OsStr` pub fn as_os_str(&self) -> &std::ffi::OsStr { self.name.as_os_str() } /// Get the raw string as an `OsString` pub fn to_os_string(&self) -> std::ffi::OsString { self.as_os_str().to_owned() } } impl From<&'_ OsStr> for OsStr { fn from(id: &'_ OsStr) -> Self { id.clone() } } #[cfg(feature = "string")] impl From for OsStr { fn from(id: Str) -> Self { match id.into_inner() { crate::builder::StrInner::Static(s) => Self::from_static_ref(std::ffi::OsStr::new(s)), crate::builder::StrInner::Owned(s) => Self::from_ref(std::ffi::OsStr::new(s.as_ref())), } } } #[cfg(not(feature = "string"))] impl From for OsStr { fn from(id: Str) -> Self { Self::from_static_ref(std::ffi::OsStr::new(id.into_inner().0)) } } impl From<&'_ Str> for OsStr { fn from(id: &'_ Str) -> Self { id.clone().into() } } #[cfg(feature = "string")] impl From for OsStr { fn from(name: std::ffi::OsString) -> Self { Self::from_string(name) } } #[cfg(feature = "string")] impl From<&'_ std::ffi::OsString> for OsStr { fn from(name: &'_ std::ffi::OsString) -> Self { Self::from_ref(name.as_os_str()) } } #[cfg(feature = "string")] impl From for OsStr { fn from(name: String) -> Self { Self::from_string(name.into()) } } #[cfg(feature = "string")] impl From<&'_ String> for OsStr { fn from(name: &'_ String) -> Self { Self::from_ref(name.as_str().as_ref()) } } impl From<&'static std::ffi::OsStr> for OsStr { fn from(name: &'static std::ffi::OsStr) -> Self { Self::from_static_ref(name) } } impl From<&'_ &'static std::ffi::OsStr> for OsStr { fn from(name: &'_ &'static std::ffi::OsStr) -> Self { Self::from_static_ref(name) } } impl From<&'static str> for OsStr { fn from(name: &'static str) -> Self { Self::from_static_ref(name.as_ref()) } } impl From<&'_ &'static str> for OsStr { fn from(name: &'_ &'static str) -> Self { Self::from_static_ref((*name).as_ref()) } } impl From for std::ffi::OsString { fn from(name: OsStr) -> Self { name.name.into_os_string() } } impl From for std::path::PathBuf { fn from(name: OsStr) -> Self { std::ffi::OsString::from(name).into() } } impl std::fmt::Debug for OsStr { #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Debug::fmt(self.as_os_str(), f) } } impl std::ops::Deref for OsStr { type Target = std::ffi::OsStr; #[inline] fn deref(&self) -> &std::ffi::OsStr { self.as_os_str() } } impl AsRef for OsStr { #[inline] fn as_ref(&self) -> &std::ffi::OsStr { self.as_os_str() } } impl AsRef for OsStr { #[inline] fn as_ref(&self) -> &std::path::Path { std::path::Path::new(self) } } impl std::borrow::Borrow for OsStr { #[inline] fn borrow(&self) -> &std::ffi::OsStr { self.as_os_str() } } impl PartialEq for OsStr { #[inline] fn eq(&self, other: &str) -> bool { PartialEq::eq(self.as_os_str(), other) } } impl PartialEq for str { #[inline] fn eq(&self, other: &OsStr) -> bool { PartialEq::eq(self, other.as_os_str()) } } impl PartialEq<&'_ str> for OsStr { #[inline] fn eq(&self, other: &&str) -> bool { PartialEq::eq(self.as_os_str(), *other) } } impl PartialEq for &'_ str { #[inline] fn eq(&self, other: &OsStr) -> bool { PartialEq::eq(*self, other.as_os_str()) } } impl PartialEq<&'_ std::ffi::OsStr> for OsStr { #[inline] fn eq(&self, other: &&std::ffi::OsStr) -> bool { PartialEq::eq(self.as_os_str(), *other) } } impl PartialEq for &'_ std::ffi::OsStr { #[inline] fn eq(&self, other: &OsStr) -> bool { PartialEq::eq(*self, other.as_os_str()) } } impl PartialEq for OsStr { #[inline] fn eq(&self, other: &String) -> bool { PartialEq::eq(self.as_os_str(), other.as_str()) } } impl PartialEq for String { #[inline] fn eq(&self, other: &OsStr) -> bool { PartialEq::eq(self.as_str(), other.as_os_str()) } } impl PartialEq for OsStr { #[inline] fn eq(&self, other: &std::ffi::OsString) -> bool { PartialEq::eq(self.as_os_str(), other.as_os_str()) } } impl PartialEq for std::ffi::OsString { #[inline] fn eq(&self, other: &OsStr) -> bool { PartialEq::eq(self.as_os_str(), other.as_os_str()) } } #[cfg(feature = "string")] pub(crate) mod inner { #[derive(Clone)] pub(crate) enum Inner { Static(&'static std::ffi::OsStr), Owned(Box), } impl Inner { pub(crate) fn from_string(name: std::ffi::OsString) -> Self { Self::Owned(name.into_boxed_os_str()) } pub(crate) fn from_ref(name: &std::ffi::OsStr) -> Self { Self::Owned(Box::from(name)) } pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self { Self::Static(name) } pub(crate) fn as_os_str(&self) -> &std::ffi::OsStr { match self { Self::Static(s) => s, Self::Owned(s) => s.as_ref(), } } pub(crate) fn into_os_string(self) -> std::ffi::OsString { self.as_os_str().to_owned() } } } #[cfg(not(feature = "string"))] pub(crate) mod inner { #[derive(Clone)] pub(crate) struct Inner(&'static std::ffi::OsStr); impl Inner { pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self { Self(name) } pub(crate) fn as_os_str(&self) -> &std::ffi::OsStr { self.0 } pub(crate) fn into_os_string(self) -> std::ffi::OsString { self.as_os_str().to_owned() } } } pub(crate) use inner::Inner; impl Default for Inner { fn default() -> Self { Self::from_static_ref(std::ffi::OsStr::new("")) } } impl PartialEq for Inner { fn eq(&self, other: &Inner) -> bool { self.as_os_str() == other.as_os_str() } } impl PartialOrd for Inner { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for Inner { fn cmp(&self, other: &Inner) -> std::cmp::Ordering { self.as_os_str().cmp(other.as_os_str()) } } impl Eq for Inner {} impl std::hash::Hash for Inner { #[inline] fn hash(&self, state: &mut H) { self.as_os_str().hash(state); } } clap_builder-4.5.48/src/builder/possible_value.rs000064400000000000000000000154301046102023000201550ustar 00000000000000use crate::builder::IntoResettable; use crate::builder::Str; use crate::builder::StyledStr; use crate::util::eq_ignore_case; /// A possible value of an argument. /// /// This is used for specifying [possible values] of [Args]. /// /// See also [`PossibleValuesParser`][crate::builder::PossibleValuesParser] /// ///
/// /// **NOTE:** Most likely you can use strings, rather than `PossibleValue` as it is only required /// to [hide] single values from help messages and shell completions or to attach [help] to /// possible values. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::{Arg, builder::PossibleValue, ArgAction}; /// let cfg = Arg::new("config") /// .action(ArgAction::Set) /// .value_name("FILE") /// .value_parser([ /// PossibleValue::new("fast"), /// PossibleValue::new("slow").help("slower than fast"), /// PossibleValue::new("secret speed").hide(true) /// ]); /// ``` /// /// [Args]: crate::Arg /// [possible values]: crate::builder::ValueParser::possible_values /// [hide]: PossibleValue::hide() /// [help]: PossibleValue::help() #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct PossibleValue { name: Str, help: Option, aliases: Vec, // (name, visible) hide: bool, } impl PossibleValue { /// Create a [`PossibleValue`] with its name. /// /// The name will be used to decide whether this value was provided by the user to an argument. /// ///
/// /// **NOTE:** In case it is not [hidden] it will also be shown in help messages for arguments /// that use it as a [possible value] and have not hidden them through [`Arg::hide_possible_values(true)`]. /// ///
/// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::builder::PossibleValue; /// PossibleValue::new("fast") /// # ; /// ``` /// [hidden]: PossibleValue::hide /// [possible value]: crate::builder::PossibleValuesParser /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() pub fn new(name: impl Into) -> Self { PossibleValue { name: name.into(), ..Default::default() } } /// Sets the help description of the value. /// /// This is typically displayed in completions (where supported) and should be a short, one-line /// description. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::builder::PossibleValue; /// PossibleValue::new("slow") /// .help("not fast") /// # ; /// ``` #[inline] #[must_use] pub fn help(mut self, help: impl IntoResettable) -> Self { self.help = help.into_resettable().into_option(); self } /// Hides this value from help and shell completions. /// /// This is an alternative to hiding through [`Arg::hide_possible_values(true)`], if you only /// want to hide some values. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::builder::PossibleValue; /// PossibleValue::new("secret") /// .hide(true) /// # ; /// ``` /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() #[inline] #[must_use] pub fn hide(mut self, yes: bool) -> Self { self.hide = yes; self } /// Sets a *hidden* alias for this argument value. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::builder::PossibleValue; /// PossibleValue::new("slow") /// .alias("not-fast") /// # ; /// ``` #[must_use] pub fn alias(mut self, name: impl IntoResettable) -> Self { if let Some(name) = name.into_resettable().into_option() { self.aliases.push(name); } else { self.aliases.clear(); } self } /// Sets multiple *hidden* aliases for this argument value. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::builder::PossibleValue; /// PossibleValue::new("slow") /// .aliases(["not-fast", "snake-like"]) /// # ; /// ``` #[must_use] pub fn aliases(mut self, names: impl IntoIterator>) -> Self { self.aliases.extend(names.into_iter().map(|a| a.into())); self } } /// Reflection impl PossibleValue { /// Get the name of the argument value #[inline] pub fn get_name(&self) -> &str { self.name.as_str() } /// Get the help specified for this argument, if any #[inline] pub fn get_help(&self) -> Option<&StyledStr> { self.help.as_ref() } /// Report if [`PossibleValue::hide`] is set #[inline] pub fn is_hide_set(&self) -> bool { self.hide } /// Report if `PossibleValue` is not hidden and has a help message pub(crate) fn should_show_help(&self) -> bool { !self.hide && self.help.is_some() } /// Get the name if argument value is not hidden, `None` otherwise, /// but wrapped in quotes if it contains whitespace #[cfg(feature = "help")] pub(crate) fn get_visible_quoted_name(&self) -> Option> { if !self.hide { Some(if self.name.contains(char::is_whitespace) { format!("{:?}", self.name).into() } else { self.name.as_str().into() }) } else { None } } /// Returns all valid values of the argument value. /// /// Namely the name and all aliases. pub fn get_name_and_aliases(&self) -> impl Iterator + '_ { std::iter::once(self.get_name()).chain(self.aliases.iter().map(|s| s.as_str())) } /// Tests if the value is valid for this argument value /// /// The value is valid if it is either the name or one of the aliases. /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::builder::PossibleValue; /// let arg_value = PossibleValue::new("fast").alias("not-slow"); /// /// assert!(arg_value.matches("fast", false)); /// assert!(arg_value.matches("not-slow", false)); /// /// assert!(arg_value.matches("FAST", true)); /// assert!(!arg_value.matches("FAST", false)); /// ``` pub fn matches(&self, value: &str, ignore_case: bool) -> bool { if ignore_case { self.get_name_and_aliases() .any(|name| eq_ignore_case(name, value)) } else { self.get_name_and_aliases().any(|name| name == value) } } } impl> From for PossibleValue { fn from(s: S) -> Self { Self::new(s) } } clap_builder-4.5.48/src/builder/range.rs000064400000000000000000000210121046102023000162260ustar 00000000000000/// Values per occurrence for an argument #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct ValueRange { start_inclusive: usize, end_inclusive: usize, } impl ValueRange { /// Nor argument values, or a flag pub const EMPTY: Self = Self { start_inclusive: 0, end_inclusive: 0, }; /// A single argument value, the most common case for options pub const SINGLE: Self = Self { start_inclusive: 1, end_inclusive: 1, }; #[cfg(debug_assertions)] pub(crate) const OPTIONAL: Self = Self { start_inclusive: 0, end_inclusive: 1, }; pub(crate) const FULL: Self = Self { start_inclusive: 0, end_inclusive: usize::MAX, }; /// Create a range /// /// # Panics /// /// If the end is less than the start (debug builds) /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::builder::ValueRange; /// let range = ValueRange::new(5); /// let range = ValueRange::new(5..10); /// let range = ValueRange::new(5..=10); /// let range = ValueRange::new(5..); /// let range = ValueRange::new(..10); /// let range = ValueRange::new(..=10); /// ``` /// /// While this will panic: /// ```should_panic /// # use clap_builder as clap; /// # use clap::builder::ValueRange; /// let range = ValueRange::new(10..5); // Panics! /// ``` pub fn new(range: impl Into) -> Self { range.into() } pub(crate) fn raw(start_inclusive: usize, end_inclusive: usize) -> Self { debug_assert!(start_inclusive <= end_inclusive); Self { start_inclusive, end_inclusive, } } /// Fewest number of values the argument accepts pub fn min_values(&self) -> usize { self.start_inclusive } /// Most number of values the argument accepts pub fn max_values(&self) -> usize { self.end_inclusive } /// Report whether the argument takes any values (ie is a flag) /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// # use clap::builder::ValueRange; /// let range = ValueRange::new(5); /// assert!(range.takes_values()); /// /// let range = ValueRange::new(0); /// assert!(!range.takes_values()); /// ``` pub fn takes_values(&self) -> bool { self.end_inclusive != 0 } pub(crate) fn is_unbounded(&self) -> bool { self.end_inclusive == usize::MAX } pub(crate) fn is_fixed(&self) -> bool { self.start_inclusive == self.end_inclusive } pub(crate) fn is_multiple(&self) -> bool { self.start_inclusive != self.end_inclusive || 1 < self.start_inclusive } pub(crate) fn num_values(&self) -> Option { self.is_fixed().then_some(self.start_inclusive) } pub(crate) fn accepts_more(&self, current: usize) -> bool { current < self.end_inclusive } } impl std::ops::RangeBounds for ValueRange { fn start_bound(&self) -> std::ops::Bound<&usize> { std::ops::Bound::Included(&self.start_inclusive) } fn end_bound(&self) -> std::ops::Bound<&usize> { std::ops::Bound::Included(&self.end_inclusive) } } impl Default for ValueRange { fn default() -> Self { Self::SINGLE } } impl From for ValueRange { fn from(fixed: usize) -> Self { (fixed..=fixed).into() } } impl From> for ValueRange { fn from(range: std::ops::Range) -> Self { let start_inclusive = range.start; let end_inclusive = range.end.saturating_sub(1); Self::raw(start_inclusive, end_inclusive) } } impl From for ValueRange { fn from(_: std::ops::RangeFull) -> Self { Self::FULL } } impl From> for ValueRange { fn from(range: std::ops::RangeFrom) -> Self { let start_inclusive = range.start; let end_inclusive = usize::MAX; Self::raw(start_inclusive, end_inclusive) } } impl From> for ValueRange { fn from(range: std::ops::RangeTo) -> Self { let start_inclusive = 0; let end_inclusive = range.end.saturating_sub(1); Self::raw(start_inclusive, end_inclusive) } } impl From> for ValueRange { fn from(range: std::ops::RangeInclusive) -> Self { let start_inclusive = *range.start(); let end_inclusive = *range.end(); Self::raw(start_inclusive, end_inclusive) } } impl From> for ValueRange { fn from(range: std::ops::RangeToInclusive) -> Self { let start_inclusive = 0; let end_inclusive = range.end; Self::raw(start_inclusive, end_inclusive) } } impl std::fmt::Display for ValueRange { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { ok!(self.start_inclusive.fmt(f)); if self.is_fixed() { } else if self.end_inclusive == usize::MAX { ok!("..".fmt(f)); } else { ok!("..=".fmt(f)); ok!(self.end_inclusive.fmt(f)); } Ok(()) } } impl std::fmt::Debug for ValueRange { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{self}") } } #[cfg(test)] mod test { use super::*; use std::ops::RangeBounds; #[test] fn from_fixed() { let range: ValueRange = 5.into(); assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); assert_eq!(range.end_bound(), std::ops::Bound::Included(&5)); assert!(range.is_fixed()); assert!(range.is_multiple()); assert_eq!(range.num_values(), Some(5)); assert!(range.takes_values()); } #[test] fn from_fixed_empty() { let range: ValueRange = 0.into(); assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); assert_eq!(range.end_bound(), std::ops::Bound::Included(&0)); assert!(range.is_fixed()); assert!(!range.is_multiple()); assert_eq!(range.num_values(), Some(0)); assert!(!range.takes_values()); } #[test] fn from_range() { let range: ValueRange = (5..10).into(); assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); assert_eq!(range.end_bound(), std::ops::Bound::Included(&9)); assert!(!range.is_fixed()); assert!(range.is_multiple()); assert_eq!(range.num_values(), None); assert!(range.takes_values()); } #[test] fn from_range_inclusive() { let range: ValueRange = (5..=10).into(); assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); assert_eq!(range.end_bound(), std::ops::Bound::Included(&10)); assert!(!range.is_fixed()); assert!(range.is_multiple()); assert_eq!(range.num_values(), None); assert!(range.takes_values()); } #[test] fn from_range_full() { let range: ValueRange = (..).into(); assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); assert_eq!(range.end_bound(), std::ops::Bound::Included(&usize::MAX)); assert!(!range.is_fixed()); assert!(range.is_multiple()); assert_eq!(range.num_values(), None); assert!(range.takes_values()); } #[test] fn from_range_from() { let range: ValueRange = (5..).into(); assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); assert_eq!(range.end_bound(), std::ops::Bound::Included(&usize::MAX)); assert!(!range.is_fixed()); assert!(range.is_multiple()); assert_eq!(range.num_values(), None); assert!(range.takes_values()); } #[test] fn from_range_to() { let range: ValueRange = (..10).into(); assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); assert_eq!(range.end_bound(), std::ops::Bound::Included(&9)); assert!(!range.is_fixed()); assert!(range.is_multiple()); assert_eq!(range.num_values(), None); assert!(range.takes_values()); } #[test] fn from_range_to_inclusive() { let range: ValueRange = (..=10).into(); assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); assert_eq!(range.end_bound(), std::ops::Bound::Included(&10)); assert!(!range.is_fixed()); assert!(range.is_multiple()); assert_eq!(range.num_values(), None); assert!(range.takes_values()); } } clap_builder-4.5.48/src/builder/resettable.rs000064400000000000000000000126271046102023000173000ustar 00000000000000// Unlike `impl Into>` or `Option>`, this isn't ambiguous for the `None` // case. use crate::builder::ArgAction; use crate::builder::OsStr; use crate::builder::Str; use crate::builder::StyledStr; use crate::builder::ValueHint; use crate::builder::ValueParser; use crate::builder::ValueRange; /// Clearable builder value /// /// This allows a builder function to both accept any value that can [`Into::into`] `T` (like /// `&str` into `OsStr`) as well as `None` to reset it to the default. This is needed to /// workaround a limitation where you can't have a function argument that is `impl Into>` /// where `T` is `impl Into` accept `None` as its type is ambiguous. /// /// # Example /// /// ```rust /// # use clap_builder as clap; /// # use clap::Command; /// # use clap::Arg; /// fn common() -> Command { /// Command::new("cli") /// .arg(Arg::new("input").short('i').long("input")) /// } /// let mut command = common(); /// command.mut_arg("input", |arg| arg.short(None)); /// ``` #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Resettable { /// Overwrite builder value Value(T), /// Reset builder value Reset, } impl Resettable { pub(crate) fn into_option(self) -> Option { match self { Self::Value(t) => Some(t), Self::Reset => None, } } } impl From for Resettable { fn from(other: T) -> Self { Self::Value(other) } } impl From> for Resettable { fn from(other: Option) -> Self { match other { Some(inner) => Self::Value(inner), None => Self::Reset, } } } /// Convert to the intended resettable type pub trait IntoResettable { /// Convert to the intended resettable type fn into_resettable(self) -> Resettable; } impl IntoResettable for Option { fn into_resettable(self) -> Resettable { match self { Some(s) => Resettable::Value(s), None => Resettable::Reset, } } } impl IntoResettable for Option { fn into_resettable(self) -> Resettable { match self { Some(s) => Resettable::Value(s), None => Resettable::Reset, } } } impl IntoResettable for Option { fn into_resettable(self) -> Resettable { match self { Some(s) => Resettable::Value(s), None => Resettable::Reset, } } } impl IntoResettable for Option { fn into_resettable(self) -> Resettable { match self { Some(s) => Resettable::Value(s), None => Resettable::Reset, } } } impl IntoResettable for Option { fn into_resettable(self) -> Resettable { match self { Some(s) => Resettable::Value(s), None => Resettable::Reset, } } } impl IntoResettable for Option<&'static str> { fn into_resettable(self) -> Resettable { match self { Some(s) => Resettable::Value(s.into()), None => Resettable::Reset, } } } impl IntoResettable for Option<&'static str> { fn into_resettable(self) -> Resettable { match self { Some(s) => Resettable::Value(s.into()), None => Resettable::Reset, } } } impl IntoResettable for Option<&'static str> { fn into_resettable(self) -> Resettable { match self { Some(s) => Resettable::Value(s.into()), None => Resettable::Reset, } } } impl IntoResettable for Resettable { fn into_resettable(self) -> Resettable { self } } impl IntoResettable for char { fn into_resettable(self) -> Resettable { Resettable::Value(self) } } impl IntoResettable for usize { fn into_resettable(self) -> Resettable { Resettable::Value(self) } } impl IntoResettable for ArgAction { fn into_resettable(self) -> Resettable { Resettable::Value(self) } } impl IntoResettable for ValueHint { fn into_resettable(self) -> Resettable { Resettable::Value(self) } } impl> IntoResettable for I { fn into_resettable(self) -> Resettable { Resettable::Value(self.into()) } } impl> IntoResettable for I { fn into_resettable(self) -> Resettable { Resettable::Value(self.into()) } } impl> IntoResettable for I { fn into_resettable(self) -> Resettable { Resettable::Value(self.into()) } } impl> IntoResettable for I { fn into_resettable(self) -> Resettable { Resettable::Value(self.into()) } } impl> IntoResettable for I { fn into_resettable(self) -> Resettable { Resettable::Value(self.into()) } } impl> IntoResettable for I { fn into_resettable(self) -> Resettable { Resettable::Value(self.into()) } } impl> IntoResettable for I { fn into_resettable(self) -> Resettable { Resettable::Value(self.into()) } } clap_builder-4.5.48/src/builder/str.rs000064400000000000000000000146261046102023000157570ustar 00000000000000/// A UTF-8-encoded fixed string /// ///
/// /// **NOTE:** To support dynamic values (i.e. `String`), enable the `string` /// feature /// ///
#[derive(Default, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] pub struct Str { name: Inner, } impl Str { #[cfg(feature = "string")] pub(crate) fn from_string(name: String) -> Self { Self { name: Inner::from_string(name), } } #[cfg(feature = "string")] pub(crate) fn from_ref(name: &str) -> Self { Self { name: Inner::from_ref(name), } } pub(crate) fn from_static_ref(name: &'static str) -> Self { Self { name: Inner::from_static_ref(name), } } pub(crate) fn into_inner(self) -> Inner { self.name } /// Get the raw string of the `Str` pub fn as_str(&self) -> &str { self.name.as_str() } } impl From<&'_ Str> for Str { fn from(id: &'_ Str) -> Self { id.clone() } } #[cfg(feature = "string")] impl From for Str { fn from(name: String) -> Self { Self::from_string(name) } } #[cfg(feature = "string")] impl From<&'_ String> for Str { fn from(name: &'_ String) -> Self { Self::from_ref(name.as_str()) } } impl From<&'static str> for Str { fn from(name: &'static str) -> Self { Self::from_static_ref(name) } } impl From<&'_ &'static str> for Str { fn from(name: &'_ &'static str) -> Self { Self::from_static_ref(name) } } impl From for String { fn from(name: Str) -> Self { name.name.into_string() } } impl From for Vec { fn from(name: Str) -> Self { String::from(name).into() } } impl From for std::ffi::OsString { fn from(name: Str) -> Self { String::from(name).into() } } impl From for std::path::PathBuf { fn from(name: Str) -> Self { String::from(name).into() } } impl std::fmt::Display for Str { #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(self.as_str(), f) } } impl std::fmt::Debug for Str { #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Debug::fmt(self.as_str(), f) } } impl std::ops::Deref for Str { type Target = str; #[inline] fn deref(&self) -> &str { self.as_str() } } impl AsRef for Str { #[inline] fn as_ref(&self) -> &str { self.as_str() } } impl AsRef<[u8]> for Str { #[inline] fn as_ref(&self) -> &[u8] { self.as_bytes() } } impl AsRef for Str { #[inline] fn as_ref(&self) -> &std::ffi::OsStr { (**self).as_ref() } } impl AsRef for Str { #[inline] fn as_ref(&self) -> &std::path::Path { std::path::Path::new(self) } } impl std::borrow::Borrow for Str { #[inline] fn borrow(&self) -> &str { self.as_str() } } impl PartialEq for Str { #[inline] fn eq(&self, other: &str) -> bool { PartialEq::eq(self.as_str(), other) } } impl PartialEq for str { #[inline] fn eq(&self, other: &Str) -> bool { PartialEq::eq(self, other.as_str()) } } impl PartialEq<&'_ str> for Str { #[inline] fn eq(&self, other: &&str) -> bool { PartialEq::eq(self.as_str(), *other) } } impl PartialEq for &'_ str { #[inline] fn eq(&self, other: &Str) -> bool { PartialEq::eq(*self, other.as_str()) } } impl PartialEq for Str { #[inline] fn eq(&self, other: &std::ffi::OsStr) -> bool { PartialEq::eq(self.as_str(), other) } } impl PartialEq for std::ffi::OsStr { #[inline] fn eq(&self, other: &Str) -> bool { PartialEq::eq(self, other.as_str()) } } impl PartialEq<&'_ std::ffi::OsStr> for Str { #[inline] fn eq(&self, other: &&std::ffi::OsStr) -> bool { PartialEq::eq(self.as_str(), *other) } } impl PartialEq for &'_ std::ffi::OsStr { #[inline] fn eq(&self, other: &Str) -> bool { PartialEq::eq(*self, other.as_str()) } } impl PartialEq for Str { #[inline] fn eq(&self, other: &String) -> bool { PartialEq::eq(self.as_str(), other.as_str()) } } impl PartialEq for String { #[inline] fn eq(&self, other: &Str) -> bool { PartialEq::eq(self.as_str(), other.as_str()) } } #[cfg(feature = "string")] pub(crate) mod inner { #[derive(Clone)] pub(crate) enum Inner { Static(&'static str), Owned(Box), } impl Inner { pub(crate) fn from_string(name: String) -> Self { Self::Owned(name.into_boxed_str()) } pub(crate) fn from_ref(name: &str) -> Self { Self::Owned(Box::from(name)) } pub(crate) fn from_static_ref(name: &'static str) -> Self { Self::Static(name) } pub(crate) fn as_str(&self) -> &str { match self { Self::Static(s) => s, Self::Owned(s) => s.as_ref(), } } pub(crate) fn into_string(self) -> String { match self { Self::Static(s) => s.to_owned(), Self::Owned(s) => s.into(), } } } } #[cfg(not(feature = "string"))] pub(crate) mod inner { #[derive(Clone)] pub(crate) struct Inner(pub(crate) &'static str); impl Inner { pub(crate) fn from_static_ref(name: &'static str) -> Self { Self(name) } pub(crate) fn as_str(&self) -> &str { self.0 } pub(crate) fn into_string(self) -> String { self.as_str().to_owned() } } } pub(crate) use inner::Inner; impl Default for Inner { fn default() -> Self { Self::from_static_ref("") } } impl PartialEq for Inner { fn eq(&self, other: &Inner) -> bool { self.as_str() == other.as_str() } } impl PartialOrd for Inner { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for Inner { fn cmp(&self, other: &Inner) -> std::cmp::Ordering { self.as_str().cmp(other.as_str()) } } impl Eq for Inner {} impl std::hash::Hash for Inner { #[inline] fn hash(&self, state: &mut H) { self.as_str().hash(state); } } clap_builder-4.5.48/src/builder/styled_str.rs000064400000000000000000000134461046102023000173420ustar 00000000000000#![cfg_attr(not(feature = "usage"), allow(dead_code))] /// Terminal-styling container /// /// Styling may be encoded as [ANSI Escape Code](https://en.wikipedia.org/wiki/ANSI_escape_code) /// /// # Examples /// /// ```rust /// # use clap_builder as clap; /// // `cstr!` converts tags to ANSI codes /// let after_help: &'static str = color_print::cstr!( /// r#"Examples /// /// $ mybin --input file.toml /// "#); /// /// let cmd = clap::Command::new("mybin") /// .after_help(after_help) // The `&str` gets converted into a `StyledStr` /// // ... /// # ; /// ``` #[derive(Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct StyledStr(String); impl StyledStr { /// Create an empty buffer pub const fn new() -> Self { Self(String::new()) } /// Display using [ANSI Escape Code](https://en.wikipedia.org/wiki/ANSI_escape_code) styling #[cfg(feature = "color")] pub fn ansi(&self) -> impl std::fmt::Display + '_ { self.0.as_str() } /// May allow the compiler to consolidate the `Drop`s for `msg`, reducing code size compared to /// `styled.push_str(&msg)` pub(crate) fn push_string(&mut self, msg: String) { self.0.push_str(&msg); } /// Appends a given string slice onto the end of this `StyledStr`. pub fn push_str(&mut self, msg: &str) { self.0.push_str(msg); } pub(crate) fn trim_start_lines(&mut self) { if let Some(pos) = self.0.find('\n') { let (leading, help) = self.0.split_at(pos + 1); if leading.trim().is_empty() { self.0 = help.to_owned(); } } } pub(crate) fn trim_end(&mut self) { self.0 = self.0.trim_end().to_owned(); } #[cfg(feature = "help")] pub(crate) fn replace_newline_var(&mut self) { self.0 = self.0.replace("{n}", "\n"); } #[cfg(feature = "help")] pub(crate) fn indent(&mut self, initial: &str, trailing: &str) { self.0.insert_str(0, initial); let mut line_sep = "\n".to_owned(); line_sep.push_str(trailing); self.0 = self.0.replace('\n', &line_sep); } #[cfg(all(not(feature = "wrap_help"), feature = "help"))] pub(crate) fn wrap(&mut self, _hard_width: usize) {} #[cfg(feature = "wrap_help")] pub(crate) fn wrap(&mut self, hard_width: usize) { let mut new = String::with_capacity(self.0.len()); let mut last = 0; let mut wrapper = crate::output::textwrap::wrap_algorithms::LineWrapper::new(hard_width); for content in self.iter_text() { // Preserve styling let current = content.as_ptr() as usize - self.0.as_str().as_ptr() as usize; if last != current { new.push_str(&self.0.as_str()[last..current]); } last = current + content.len(); for (i, line) in content.split_inclusive('\n').enumerate() { if 0 < i { // reset char count on newline, skipping the start as we might have carried // over from a prior block of styled text wrapper.reset(); } let line = crate::output::textwrap::word_separators::find_words_ascii_space(line) .collect::>(); new.extend(wrapper.wrap(line)); } } if last != self.0.len() { new.push_str(&self.0.as_str()[last..]); } new = new.trim_end().to_owned(); self.0 = new; } #[inline(never)] #[cfg(feature = "help")] pub(crate) fn display_width(&self) -> usize { let mut width = 0; for c in self.iter_text() { width += crate::output::display_width(c); } width } #[cfg(feature = "help")] pub(crate) fn is_empty(&self) -> bool { self.0.is_empty() } #[cfg(feature = "help")] pub(crate) fn as_styled_str(&self) -> &str { &self.0 } #[cfg(feature = "color")] pub(crate) fn iter_text(&self) -> impl Iterator { anstream::adapter::strip_str(&self.0) } #[cfg(not(feature = "color"))] pub(crate) fn iter_text(&self) -> impl Iterator { [self.0.as_str()].into_iter() } pub(crate) fn push_styled(&mut self, other: &Self) { self.0.push_str(&other.0); } pub(crate) fn write_to(&self, buffer: &mut dyn std::io::Write) -> std::io::Result<()> { ok!(buffer.write_all(self.0.as_bytes())); Ok(()) } } impl Default for &'_ StyledStr { fn default() -> Self { static DEFAULT: StyledStr = StyledStr::new(); &DEFAULT } } impl From for StyledStr { fn from(name: String) -> Self { StyledStr(name) } } impl From<&'_ String> for StyledStr { fn from(name: &'_ String) -> Self { let mut styled = StyledStr::new(); styled.push_str(name); styled } } impl From<&'static str> for StyledStr { fn from(name: &'static str) -> Self { let mut styled = StyledStr::new(); styled.push_str(name); styled } } impl From<&'_ &'static str> for StyledStr { fn from(name: &'_ &'static str) -> Self { StyledStr::from(*name) } } impl std::fmt::Write for StyledStr { #[inline] fn write_str(&mut self, s: &str) -> Result<(), std::fmt::Error> { self.0.push_str(s); Ok(()) } #[inline] fn write_char(&mut self, c: char) -> Result<(), std::fmt::Error> { self.0.push(c); Ok(()) } } /// Color-unaware printing. Never uses coloring. impl std::fmt::Display for StyledStr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for part in self.iter_text() { part.fmt(f)?; } Ok(()) } } clap_builder-4.5.48/src/builder/styling.rs000064400000000000000000000132721046102023000166340ustar 00000000000000//! Terminal [`Styles`] for help and error output pub use anstyle::*; /// Terminal styling definitions /// /// See also [`Command::styles`][crate::Command::styles]. /// /// # Example /// /// clap v3 styling /// ```rust /// # use clap_builder as clap; /// # use clap::builder::styling::*; /// let styles = Styles::styled() /// .header(AnsiColor::Yellow.on_default()) /// .usage(AnsiColor::Green.on_default()) /// .literal(AnsiColor::Green.on_default()) /// .placeholder(AnsiColor::Green.on_default()); /// ``` #[derive(Clone, Debug)] #[allow(missing_copy_implementations)] // Large enough type that I want an explicit `clone()` for now pub struct Styles { header: Style, error: Style, usage: Style, literal: Style, placeholder: Style, valid: Style, invalid: Style, context: Style, context_value: Option