From 218caa410aa38c29984be31a5229b9fa717560ee Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 17 Apr 2024 14:19:13 +0200 Subject: Merging upstream version 1.68.2+dfsg1. Signed-off-by: Daniel Baumann --- vendor/clap/src/_cookbook/cargo_example.rs | 7 + vendor/clap/src/_cookbook/cargo_example_derive.rs | 7 + vendor/clap/src/_cookbook/escaped_positional.rs | 7 + .../src/_cookbook/escaped_positional_derive.rs | 7 + vendor/clap/src/_cookbook/find.rs | 7 + vendor/clap/src/_cookbook/git.rs | 7 + vendor/clap/src/_cookbook/git_derive.rs | 7 + vendor/clap/src/_cookbook/mod.rs | 61 + vendor/clap/src/_cookbook/multicall_busybox.rs | 7 + vendor/clap/src/_cookbook/multicall_hostname.rs | 7 + vendor/clap/src/_cookbook/pacman.rs | 7 + vendor/clap/src/_cookbook/repl.rs | 5 + vendor/clap/src/_cookbook/typed_derive.rs | 7 + vendor/clap/src/_derive/_tutorial.rs | 226 + vendor/clap/src/_derive/mod.rs | 480 ++ vendor/clap/src/_faq.rs | 95 + vendor/clap/src/_features.rs | 29 + vendor/clap/src/_tutorial.rs | 222 + vendor/clap/src/bin/stdio-fixture.rs | 15 + vendor/clap/src/builder/action.rs | 344 ++ vendor/clap/src/builder/app_settings.rs | 172 + vendor/clap/src/builder/arg.rs | 4647 +++++++++++++++++++ vendor/clap/src/builder/arg_group.rs | 596 +++ vendor/clap/src/builder/arg_predicate.rs | 19 + vendor/clap/src/builder/arg_settings.rs | 145 + vendor/clap/src/builder/command.rs | 4703 ++++++++++++++++++++ vendor/clap/src/builder/debug_asserts.rs | 887 ++++ vendor/clap/src/builder/mod.rs | 60 + vendor/clap/src/builder/os_str.rs | 336 ++ vendor/clap/src/builder/possible_value.rs | 234 + vendor/clap/src/builder/range.rs | 283 ++ vendor/clap/src/builder/resettable.rs | 211 + vendor/clap/src/builder/str.rs | 307 ++ vendor/clap/src/builder/styled_str.rs | 349 ++ vendor/clap/src/builder/tests.rs | 56 + vendor/clap/src/builder/value_hint.rs | 95 + vendor/clap/src/builder/value_parser.rs | 2435 ++++++++++ vendor/clap/src/derive.rs | 471 ++ vendor/clap/src/error/context.rs | 114 + vendor/clap/src/error/format.rs | 468 ++ vendor/clap/src/error/kind.rs | 348 ++ vendor/clap/src/error/mod.rs | 876 ++++ vendor/clap/src/lib.rs | 154 + vendor/clap/src/macros.rs | 676 +++ vendor/clap/src/mkeymap.rs | 177 + vendor/clap/src/output/fmt.rs | 90 + vendor/clap/src/output/help.rs | 43 + vendor/clap/src/output/help_template.rs | 1065 +++++ vendor/clap/src/output/mod.rs | 23 + vendor/clap/src/output/textwrap/core.rs | 158 + vendor/clap/src/output/textwrap/mod.rs | 122 + vendor/clap/src/output/textwrap/word_separators.rs | 91 + vendor/clap/src/output/textwrap/wrap_algorithms.rs | 44 + vendor/clap/src/output/usage.rs | 441 ++ vendor/clap/src/parser/arg_matcher.rs | 248 ++ vendor/clap/src/parser/error.rs | 65 + vendor/clap/src/parser/features/mod.rs | 1 + vendor/clap/src/parser/features/suggestions.rs | 167 + vendor/clap/src/parser/matches/any_value.rs | 112 + vendor/clap/src/parser/matches/arg_matches.rs | 1968 ++++++++ vendor/clap/src/parser/matches/matched_arg.rs | 225 + vendor/clap/src/parser/matches/mod.rs | 16 + vendor/clap/src/parser/matches/value_source.rs | 17 + vendor/clap/src/parser/mod.rs | 27 + vendor/clap/src/parser/parser.rs | 1643 +++++++ vendor/clap/src/parser/validator.rs | 565 +++ vendor/clap/src/util/color.rs | 103 + vendor/clap/src/util/flat_map.rs | 254 ++ vendor/clap/src/util/flat_set.rs | 107 + vendor/clap/src/util/graph.rs | 49 + vendor/clap/src/util/id.rs | 164 + vendor/clap/src/util/mod.rs | 44 + vendor/clap/src/util/str_to_bool.rs | 21 + 73 files changed, 28246 insertions(+) create mode 100644 vendor/clap/src/_cookbook/cargo_example.rs create mode 100644 vendor/clap/src/_cookbook/cargo_example_derive.rs create mode 100644 vendor/clap/src/_cookbook/escaped_positional.rs create mode 100644 vendor/clap/src/_cookbook/escaped_positional_derive.rs create mode 100644 vendor/clap/src/_cookbook/find.rs create mode 100644 vendor/clap/src/_cookbook/git.rs create mode 100644 vendor/clap/src/_cookbook/git_derive.rs create mode 100644 vendor/clap/src/_cookbook/mod.rs create mode 100644 vendor/clap/src/_cookbook/multicall_busybox.rs create mode 100644 vendor/clap/src/_cookbook/multicall_hostname.rs create mode 100644 vendor/clap/src/_cookbook/pacman.rs create mode 100644 vendor/clap/src/_cookbook/repl.rs create mode 100644 vendor/clap/src/_cookbook/typed_derive.rs create mode 100644 vendor/clap/src/_derive/_tutorial.rs create mode 100644 vendor/clap/src/_derive/mod.rs create mode 100644 vendor/clap/src/_faq.rs create mode 100644 vendor/clap/src/_features.rs create mode 100644 vendor/clap/src/_tutorial.rs create mode 100644 vendor/clap/src/bin/stdio-fixture.rs create mode 100644 vendor/clap/src/builder/action.rs create mode 100644 vendor/clap/src/builder/app_settings.rs create mode 100644 vendor/clap/src/builder/arg.rs create mode 100644 vendor/clap/src/builder/arg_group.rs create mode 100644 vendor/clap/src/builder/arg_predicate.rs create mode 100644 vendor/clap/src/builder/arg_settings.rs create mode 100644 vendor/clap/src/builder/command.rs create mode 100644 vendor/clap/src/builder/debug_asserts.rs create mode 100644 vendor/clap/src/builder/mod.rs create mode 100644 vendor/clap/src/builder/os_str.rs create mode 100644 vendor/clap/src/builder/possible_value.rs create mode 100644 vendor/clap/src/builder/range.rs create mode 100644 vendor/clap/src/builder/resettable.rs create mode 100644 vendor/clap/src/builder/str.rs create mode 100644 vendor/clap/src/builder/styled_str.rs create mode 100644 vendor/clap/src/builder/tests.rs create mode 100644 vendor/clap/src/builder/value_hint.rs create mode 100644 vendor/clap/src/builder/value_parser.rs create mode 100644 vendor/clap/src/derive.rs create mode 100644 vendor/clap/src/error/context.rs create mode 100644 vendor/clap/src/error/format.rs create mode 100644 vendor/clap/src/error/kind.rs create mode 100644 vendor/clap/src/error/mod.rs create mode 100644 vendor/clap/src/lib.rs create mode 100644 vendor/clap/src/macros.rs create mode 100644 vendor/clap/src/mkeymap.rs create mode 100644 vendor/clap/src/output/fmt.rs create mode 100644 vendor/clap/src/output/help.rs create mode 100644 vendor/clap/src/output/help_template.rs create mode 100644 vendor/clap/src/output/mod.rs create mode 100644 vendor/clap/src/output/textwrap/core.rs create mode 100644 vendor/clap/src/output/textwrap/mod.rs create mode 100644 vendor/clap/src/output/textwrap/word_separators.rs create mode 100644 vendor/clap/src/output/textwrap/wrap_algorithms.rs create mode 100644 vendor/clap/src/output/usage.rs create mode 100644 vendor/clap/src/parser/arg_matcher.rs create mode 100644 vendor/clap/src/parser/error.rs create mode 100644 vendor/clap/src/parser/features/mod.rs create mode 100644 vendor/clap/src/parser/features/suggestions.rs create mode 100644 vendor/clap/src/parser/matches/any_value.rs create mode 100644 vendor/clap/src/parser/matches/arg_matches.rs create mode 100644 vendor/clap/src/parser/matches/matched_arg.rs create mode 100644 vendor/clap/src/parser/matches/mod.rs create mode 100644 vendor/clap/src/parser/matches/value_source.rs create mode 100644 vendor/clap/src/parser/mod.rs create mode 100644 vendor/clap/src/parser/parser.rs create mode 100644 vendor/clap/src/parser/validator.rs create mode 100644 vendor/clap/src/util/color.rs create mode 100644 vendor/clap/src/util/flat_map.rs create mode 100644 vendor/clap/src/util/flat_set.rs create mode 100644 vendor/clap/src/util/graph.rs create mode 100644 vendor/clap/src/util/id.rs create mode 100644 vendor/clap/src/util/mod.rs create mode 100644 vendor/clap/src/util/str_to_bool.rs (limited to 'vendor/clap/src') diff --git a/vendor/clap/src/_cookbook/cargo_example.rs b/vendor/clap/src/_cookbook/cargo_example.rs new file mode 100644 index 000000000..ec5d582db --- /dev/null +++ b/vendor/clap/src/_cookbook/cargo_example.rs @@ -0,0 +1,7 @@ +//! # Example: cargo subcommand (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/cargo-example.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/cargo-example.md")] diff --git a/vendor/clap/src/_cookbook/cargo_example_derive.rs b/vendor/clap/src/_cookbook/cargo_example_derive.rs new file mode 100644 index 000000000..d49f956f9 --- /dev/null +++ b/vendor/clap/src/_cookbook/cargo_example_derive.rs @@ -0,0 +1,7 @@ +//! # Example: cargo subcommand (Derive API) +//! +//! ```rust +#![doc = include_str!("../../examples/cargo-example-derive.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/cargo-example-derive.md")] diff --git a/vendor/clap/src/_cookbook/escaped_positional.rs b/vendor/clap/src/_cookbook/escaped_positional.rs new file mode 100644 index 000000000..99a3f83f3 --- /dev/null +++ b/vendor/clap/src/_cookbook/escaped_positional.rs @@ -0,0 +1,7 @@ +//! # Example (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/escaped-positional.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/escaped-positional.md")] diff --git a/vendor/clap/src/_cookbook/escaped_positional_derive.rs b/vendor/clap/src/_cookbook/escaped_positional_derive.rs new file mode 100644 index 000000000..e6f99ad17 --- /dev/null +++ b/vendor/clap/src/_cookbook/escaped_positional_derive.rs @@ -0,0 +1,7 @@ +//! # Example (Derive API) +//! +//! ```rust +#![doc = include_str!("../../examples/escaped-positional-derive.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/escaped-positional-derive.md")] diff --git a/vendor/clap/src/_cookbook/find.rs b/vendor/clap/src/_cookbook/find.rs new file mode 100644 index 000000000..2ca11c665 --- /dev/null +++ b/vendor/clap/src/_cookbook/find.rs @@ -0,0 +1,7 @@ +//! # Example: find-like CLI (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/find.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/find.md")] diff --git a/vendor/clap/src/_cookbook/git.rs b/vendor/clap/src/_cookbook/git.rs new file mode 100644 index 000000000..03a926ca8 --- /dev/null +++ b/vendor/clap/src/_cookbook/git.rs @@ -0,0 +1,7 @@ +//! # Example: git-like CLI (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/git.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/git.md")] diff --git a/vendor/clap/src/_cookbook/git_derive.rs b/vendor/clap/src/_cookbook/git_derive.rs new file mode 100644 index 000000000..d3119736d --- /dev/null +++ b/vendor/clap/src/_cookbook/git_derive.rs @@ -0,0 +1,7 @@ +//! # Example: git-like CLI (Derive API) +//! +//! ```rust +#![doc = include_str!("../../examples/git-derive.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/git-derive.md")] diff --git a/vendor/clap/src/_cookbook/mod.rs b/vendor/clap/src/_cookbook/mod.rs new file mode 100644 index 000000000..dacb1219a --- /dev/null +++ b/vendor/clap/src/_cookbook/mod.rs @@ -0,0 +1,61 @@ +// Contributing +// +// New examples: +// - Building: They must be added to `Cargo.toml` with the appropriate `required-features`. +// - Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax +// - Link the `.md` file from here + +//! # Documentation: Cookbook +//! +//! Typed arguments: [derive][typed_derive] +//! - Topics: +//! - Custom `parse()` +//! +//! Custom cargo command: [builder][cargo_example], [derive][cargo_example_derive] +//! - Topics: +//! - Subcommands +//! - Cargo plugins +//! +//! find-like interface: [builder][find] +//! - Topics: +//! - Position-sensitive flags +//! +//! git-like interface: [builder][git], [derive][git_derive] +//! - Topics: +//! - Subcommands +//! - External subcommands +//! - Optional subcommands +//! - Default subcommands +//! - [`last`][crate::Arg::last] +//! +//! pacman-like interface: [builder][pacman] +//! - Topics: +//! - Flag subcommands +//! - Conflicting arguments +//! +//! Escaped positionals with `--`: [builder][escaped_positional], [derive][escaped_positional_derive] +//! +//! Multi-call +//! - busybox: [builder][multicall_busybox] +//! - Topics: +//! - Subcommands +//! - hostname: [builder][multicall_hostname] +//! - Topics: +//! - Subcommands +//! +//! repl: [builder][repl] +//! - Topics: +//! - Read-Eval-Print Loops / Custom command lines + +pub mod cargo_example; +pub mod cargo_example_derive; +pub mod escaped_positional; +pub mod escaped_positional_derive; +pub mod find; +pub mod git; +pub mod git_derive; +pub mod multicall_busybox; +pub mod multicall_hostname; +pub mod pacman; +pub mod repl; +pub mod typed_derive; diff --git a/vendor/clap/src/_cookbook/multicall_busybox.rs b/vendor/clap/src/_cookbook/multicall_busybox.rs new file mode 100644 index 000000000..e3384d682 --- /dev/null +++ b/vendor/clap/src/_cookbook/multicall_busybox.rs @@ -0,0 +1,7 @@ +//! # Example: busybox-like CLI (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/multicall-busybox.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/multicall-busybox.md")] diff --git a/vendor/clap/src/_cookbook/multicall_hostname.rs b/vendor/clap/src/_cookbook/multicall_hostname.rs new file mode 100644 index 000000000..9777654dc --- /dev/null +++ b/vendor/clap/src/_cookbook/multicall_hostname.rs @@ -0,0 +1,7 @@ +//! # Example: hostname-like CLI (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/multicall-hostname.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/multicall-hostname.md")] diff --git a/vendor/clap/src/_cookbook/pacman.rs b/vendor/clap/src/_cookbook/pacman.rs new file mode 100644 index 000000000..880c58158 --- /dev/null +++ b/vendor/clap/src/_cookbook/pacman.rs @@ -0,0 +1,7 @@ +//! # Example: pacman-like CLI (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/pacman.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/pacman.md")] diff --git a/vendor/clap/src/_cookbook/repl.rs b/vendor/clap/src/_cookbook/repl.rs new file mode 100644 index 000000000..549ec8259 --- /dev/null +++ b/vendor/clap/src/_cookbook/repl.rs @@ -0,0 +1,5 @@ +//! # Example: Command REPL (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/repl.rs")] +//! ``` diff --git a/vendor/clap/src/_cookbook/typed_derive.rs b/vendor/clap/src/_cookbook/typed_derive.rs new file mode 100644 index 000000000..a5fd15ff8 --- /dev/null +++ b/vendor/clap/src/_cookbook/typed_derive.rs @@ -0,0 +1,7 @@ +//! # Example: Custom Types (Derive API) +//! +//! ```rust +#![doc = include_str!("../../examples/typed-derive.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/typed-derive.md")] diff --git a/vendor/clap/src/_derive/_tutorial.rs b/vendor/clap/src/_derive/_tutorial.rs new file mode 100644 index 000000000..eb95c8754 --- /dev/null +++ b/vendor/clap/src/_derive/_tutorial.rs @@ -0,0 +1,226 @@ +// Contributing +// +// New example code: +// - Please update the corresponding section in the derive tutorial +// - Building: They must be added to `Cargo.toml` with the appropriate `required-features`. +// - Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax +// +// See also the general CONTRIBUTING + +//! # Documentation: Derive Tutorial +//! +//! 1. [Quick Start](#quick-start) +//! 2. [Configuring the Parser](#configuring-the-parser) +//! 3. [Adding Arguments](#adding-arguments) +//! 1. [Positionals](#positionals) +//! 2. [Options](#options) +//! 3. [Flags](#flags) +//! 4. [Subcommands](#subcommands) +//! 5. [Defaults](#defaults) +//! 4. Validation +//! 1. [Enumerated values](#enumerated-values) +//! 2. [Validated values](#validated-values) +//! 3. [Argument Relations](#argument-relations) +//! 4. [Custom Validation](#custom-validation) +//! 5. [Testing](#testing) +//! +//! See also +//! - [FAQ: When should I use the builder vs derive APIs?][crate::_faq#when-should-i-use-the-builder-vs-derive-apis] +//! - The [cookbook][crate::_cookbook] for more application-focused examples +//! +//! ## Quick Start +//! +//! You can create an application declaratively with a `struct` and some +//! attributes. **This requires enabling the [`derive` feature flag][crate::_features].** +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/01_quick.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/tutorial_derive/01_quick.md")] +//! +//! ## Configuring the Parser +//! +//! You use derive [`Parser`][crate::Parser] to start building a parser. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/02_apps.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/tutorial_derive/02_apps.md")] +//! +//! You can use `#[command(author, version, about)]` attribute defaults to fill these fields in from your `Cargo.toml` file. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/02_crate.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/02_crate.md")] +//! +//! You can use attributes to change the application level behavior of clap. Any [`Command`][crate::Command] builder function can be used as an attribute. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/02_app_settings.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/02_app_settings.md")] +//! +//! ## Adding Arguments +//! +//! ### Positionals +//! +//! You can have users specify values by their position on the command-line: +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_03_positional.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/03_03_positional.md")] +//! +//! Note that the default [`ArgAction`][crate::ArgAction] is [`Set`][crate::ArgAction::Set]. To +//! accept multiple values, use [`Append`][crate::ArgAction::Append]: +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_03_positional_mult.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/03_03_positional_mult.md")] +//! +//! ### Options +//! +//! You can name your arguments with a flag: +//! - Order doesn't matter +//! - They can be optional +//! - Intent is clearer +//! +//! The `#[arg(short = 'n')]` and `#[arg(long = "name")]` attributes that define +//! the flags are [`Arg`][crate::Args] methods that are derived from the field name when no value +//! is specified (`#[arg(short)]` and `#[arg(long)]`). +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_02_option.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/03_02_option.md")] +//! +//! Note that the default [`ArgAction`][crate::ArgAction] is [`Set`][crate::ArgAction::Set]. To +//! accept multiple occurrences, use [`Append`][crate::ArgAction::Append]: +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_02_option_mult.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/03_02_option_mult.md")] +//! +//! ### Flags +//! +//! Flags can also be switches that can be on/off. This is enabled via the +//! `#[arg(action = ArgAction::SetTrue)]` attribute though this is implied when the field is a +//! `bool`. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_bool.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_bool.md")] +//! +//! Note that the default [`ArgAction`][crate::ArgAction] for a `bool` field is +//! [`SetTrue`][crate::ArgAction::SetTrue]. To accept multiple flags, use +//! [`Count`][crate::ArgAction::Count]: +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_count.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/03_01_flag_count.md")] +//! +//! ### Subcommands +//! +//! Subcommands are derived with `#[derive(Subcommand)]` and be added via `#[command(subcommand)]` attribute. Each +//! instance of a [Subcommand][crate::Subcommand] can have its own version, author(s), Args, and even its own +//! subcommands. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_04_subcommands.rs")] +//! ``` +//! We used a struct-variant to define the `add` subcommand. +//! Alternatively, you can use a struct for your subcommand's arguments: +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_04_subcommands_alt.rs")] +//! ``` +//! +#![doc = include_str!("../../examples/tutorial_derive/03_04_subcommands.md")] +//! +//! ### Defaults +//! +//! We've previously showed that arguments can be [`required`][crate::Arg::required] or optional. +//! When optional, you work with a `Option` and can `unwrap_or`. Alternatively, you can +//! set `#[arg(default_value_t)]`. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_05_default_values.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/03_05_default_values.md")] +//! +//! ## Validation +//! +//! An appropriate default parser/validator will be selected for the field's type. See +//! [`value_parser!`][crate::value_parser!] for more details. +//! +//! ### Enumerated values +//! +//! For example, if you have arguments of specific values you want to test for, you can derive +//! [`ValueEnum`][crate::ValueEnum]. +//! +//! This allows you specify the valid values for that argument. If the user does not use one of +//! those specific values, they will receive a graceful exit with error message informing them +//! of the mistake, and what the possible valid values are +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/04_01_enum.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/04_01_enum.md")] +//! +//! ### Validated values +//! +//! More generally, you can validate and parse into any data type. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/04_02_parse.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/04_02_parse.md")] +//! +//! A custom parser can be used to improve the error messages or provide additional validation: +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/04_02_validate.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/04_02_validate.md")] +//! +//! See [`Arg::value_parser`][crate::Arg::value_parser] for more details. +//! +//! ### Argument Relations +//! +//! You can declare dependencies or conflicts between [`Arg`][crate::Arg]s or even +//! [`ArgGroup`][crate::ArgGroup]s. +//! +//! [`ArgGroup`][crate::ArgGroup]s make it easier to declare relations instead of having to list +//! each individually, or when you want a rule to apply "any but not all" arguments. +//! +//! Perhaps the most common use of [`ArgGroup`][crate::ArgGroup]s is to require one and *only* one +//! argument to be present out of a given set. Imagine that you had multiple arguments, and you +//! want one of them to be required, but making all of them required isn't feasible because perhaps +//! they conflict with each other. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/04_03_relations.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/04_03_relations.md")] +//! +//! ### Custom Validation +//! +//! As a last resort, you can create custom errors with the basics of clap's formatting. +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/04_04_custom.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/04_04_custom.md")] +//! +//! ## Testing +//! +//! clap reports most development errors as `debug_assert!`s. Rather than checking every +//! subcommand, you should have a test that calls +//! [`Command::debug_assert`][crate::Command::debug_assert]: +//! ```rust,no_run +#![doc = include_str!("../../examples/tutorial_derive/05_01_assert.rs")] +//! ``` diff --git a/vendor/clap/src/_derive/mod.rs b/vendor/clap/src/_derive/mod.rs new file mode 100644 index 000000000..a92b7c87b --- /dev/null +++ b/vendor/clap/src/_derive/mod.rs @@ -0,0 +1,480 @@ +//! # Documentation: Derive Reference +//! +//! 1. [Overview](#overview) +//! 2. [Attributes](#attributes) +//! 1. [Terminology](#terminology) +//! 2. [Command Attributes](#command-attributes) +//! 2. [ArgGroup Attributes](#arggroup-attributes) +//! 3. [Arg Attributes](#arg-attributes) +//! 4. [ValueEnum Attributes](#valueenum-attributes) +//! 5. [Possible Value Attributes](#possible-value-attributes) +//! 3. [Arg Types](#arg-types) +//! 4. [Doc Comments](#doc-comments) +//! 5. [Mixing Builder and Derive APIs](#mixing-builder-and-derive-apis) +//! 6. [Tips](#tips) +//! +//! ## Overview +//! +//! To derive `clap` types, you need to enable the [`derive` feature flag][crate::_features]. +//! +//! Example: +//! ```rust +#![doc = include_str!("../../examples/demo.rs")] +//! ``` +//! +//! Let's start by breaking down the anatomy of the derive attributes: +//! ```rust +//! use clap::{Parser, Args, Subcommand, ValueEnum}; +//! +//! /// Doc comment +//! #[derive(Parser)] +//! #[command(CMD ATTRIBUTE)] +//! #[group(GROUP ATTRIBUTE)] +//! struct Cli { +//! /// Doc comment +//! #[arg(ARG ATTRIBUTE)] +//! field: UserType, +//! +//! #[arg(value_enum, ARG ATTRIBUTE...)] +//! field: EnumValues, +//! +//! #[command(flatten)] +//! delegate: Struct, +//! +//! #[command(subcommand)] +//! command: Command, +//! } +//! +//! /// Doc comment +//! #[derive(Args)] +//! #[command(PARENT CMD ATTRIBUTE)] +//! #[group(GROUP ATTRIBUTE)] +//! struct Struct { +//! /// Doc comment +//! #[command(ARG ATTRIBUTE)] +//! field: UserType, +//! } +//! +//! /// Doc comment +//! #[derive(Subcommand)] +//! #[command(PARENT CMD ATTRIBUTE)] +//! enum Command { +//! /// Doc comment +//! #[command(CMD ATTRIBUTE)] +//! Variant1(Struct), +//! +//! /// Doc comment +//! #[command(CMD ATTRIBUTE)] +//! Variant2 { +//! /// Doc comment +//! #[arg(ARG ATTRIBUTE)] +//! field: UserType, +//! } +//! } +//! +//! /// Doc comment +//! #[derive(ValueEnum)] +//! #[value(VALUE ENUM ATTRIBUTE)] +//! enum EnumValues { +//! /// Doc comment +//! #[value(POSSIBLE VALUE ATTRIBUTE)] +//! Variant1, +//! } +//! +//! fn main() { +//! let cli = Cli::parse(); +//! } +//! ``` +//! +//! Traits: +//! - [`Parser`][crate::Parser] parses arguments into a `struct` (arguments) or `enum` (subcommands). +//! - [`Args`][crate::Args] allows defining a set of re-usable arguments that get merged into their parent container. +//! - [`Subcommand`][crate::Subcommand] defines available subcommands. +//! - Subcommand arguments can be defined in a struct-variant or automatically flattened with a tuple-variant. +//! - [`ValueEnum`][crate::ValueEnum] allows parsing a value directly into an `enum`, erroring on unsupported values. +//! - The derive doesn't work on enums that contain non-unit variants, unless they are skipped +//! +//! *See also the [derive tutorial][crate::_derive::_tutorial] and [cookbook][crate::_cookbook]* +//! +//! ## Attributes +//! +//! ### Terminology +//! +//! **Raw attributes** are forwarded directly to the underlying [`clap` builder][crate::builder]. Any +//! [`Command`][crate::Command], [`Arg`][crate::Arg], or [`PossibleValue`][crate::builder::PossibleValue] method can be used as an attribute. +//! +//! Raw attributes come in two different syntaxes: +//! ```rust,ignore +//! #[arg( +//! global = true, // name = arg form, neat for one-arg methods +//! required_if_eq("out", "file") // name(arg1, arg2, ...) form. +//! )] +//! ``` +//! +//! - `method = arg` can only be used for methods which take only one argument. +//! - `method(arg1, arg2)` can be used with any method. +//! +//! As long as `method_name` is not one of the magical methods it will be +//! translated into a mere method call. +//! +//! **Magic attributes** have post-processing done to them, whether that is +//! - Providing of defaults +//! - Special behavior is triggered off of it +//! +//! Magic attributes are more constrained in the syntax they support, usually just +//! ` = ` though some use `()` instead. See the specific +//! magic attributes documentation for details. This allows users to access the +//! raw behavior of an attribute via `()` syntax. +//! +//! **NOTE:** Some attributes are inferred from [Arg Types](#arg-types) and [Doc +//! Comments](#doc-comments). Explicit attributes take precedence over inferred +//! attributes. +//! +//! ### Command Attributes +//! +//! These correspond to a [`Command`][crate::Command] which is used for both top-level parsers and +//! when defining subcommands. +//! +//! **Raw attributes:** Any [`Command` method][crate::Command] can also be used as an attribute, +//! see [Terminology](#terminology) for syntax. +//! - e.g. `#[command(arg_required_else_help(true))]` would translate to `cmd.arg_required_else_help(true)` +//! +//! **Magic attributes:** +//! - `name = `: [`Command::name`][crate::Command::name] +//! - When not present: [crate `name`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-name-field) (if on [`Parser`][crate::Parser] container), variant name (if on [`Subcommand`][crate::Subcommand] variant) +//! - `version [= ]`: [`Command::version`][crate::Command::version] +//! - When not present: no version set +//! - Without ``: defaults to [crate `version`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field) +//! - `author [= ]`: [`Command::author`][crate::Command::author] +//! - When not present: no author set +//! - Without ``: defaults to [crate `authors`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field) +//! - `about [= ]`: [`Command::about`][crate::Command::about] +//! - When not present: [Doc comment summary](#doc-comments) +//! - Without ``: [crate `description`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-description-field) ([`Parser`][crate::Parser] container) +//! - **TIP:** When a doc comment is also present, you most likely want to add +//! `#[arg(long_about = None)]` to clear the doc comment so only [`about`][crate::Command::about] +//! gets shown with both `-h` and `--help`. +//! - `long_about[ = ]`: [`Command::long_about`][crate::Command::long_about] +//! - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing +//! - When present without a value: [Doc comment](#doc-comments) +//! - `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to [`about`][crate::Command::about] / [`long_about`][crate::Command::long_about] +//! - `next_display_order`: [`Command::next_display_order`][crate::Command::next_display_order] +//! - `next_help_heading`: [`Command::next_help_heading`][crate::Command::next_help_heading] +//! - When `flatten`ing [`Args`][crate::Args], this is scoped to just the args in this struct and any struct `flatten`ed into it +//! - `rename_all = `: Override default field / variant name case conversion for [`Command::name`][crate::Command::name] / [`Arg::id`][crate::Arg::id] +//! - When not present: `"kebab-case"` +//! - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"` +//! - `rename_all_env = `: Override default field name case conversion for env variables for [`Arg::env`][crate::Arg::env] +//! - When not present: `"SCREAMING_SNAKE_CASE"` +//! - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"` +//! +//! And for [`Subcommand`][crate::Subcommand] variants: +//! - `skip`: Ignore this variant +//! - `flatten`: Delegates to the variant for more subcommands (must implement +//! [`Subcommand`][crate::Subcommand]) +//! - `subcommand`: Nest subcommands under the current set of subcommands (must implement +//! [`Subcommand`][crate::Subcommand]) +//! - `external_subcommand`: [`Command::allow_external_subcommand(true)`][crate::Command::allow_external_subcommands] +//! - Variant must be either `Variant(Vec)` or `Variant(Vec)` +//! +//! And for [`Args`][crate::Args] fields: +//! - `flatten`: Delegates to the field for more arguments (must implement [`Args`][crate::Args]) +//! - Only [`next_help_heading`][crate::Command::next_help_heading] can be used with `flatten`. See +//! [clap-rs/clap#3269](https://github.com/clap-rs/clap/issues/3269) for why +//! arg attributes are not generally supported. +//! - **Tip:** Though we do apply a flattened [`Args`][crate::Args]'s Parent Command Attributes, this +//! makes reuse harder. Generally prefer putting the cmd attributes on the +//! [`Parser`][crate::Parser] or on the flattened field. +//! - `subcommand`: Delegates definition of subcommands to the field (must implement +//! [`Subcommand`][crate::Subcommand]) +//! - When `Option`, the subcommand becomes optional +//! +//! ### ArgGroup Attributes +//! +//! These correspond to the [`ArgGroup`][crate::ArgGroup] which is implicitly created for each +//! `Args` derive. +//! +//! At the moment, only `#[group(skip)]` is supported +//! +//! ### Arg Attributes +//! +//! These correspond to a [`Arg`][crate::Arg]. +//! +//! **Raw attributes:** Any [`Arg` method][crate::Arg] can also be used as an attribute, see [Terminology](#terminology) for syntax. +//! - e.g. `#[arg(max_values(3))]` would translate to `arg.max_values(3)` +//! +//! **Magic attributes**: +//! - `id = `: [`Arg::id`][crate::Arg::id] +//! - When not present: case-converted field name is used +//! - `value_parser [= ]`: [`Arg::value_parser`][crate::Arg::value_parser] +//! - When not present: will auto-select an implementation based on the field type using +//! [`value_parser!`][crate::value_parser!] +//! - `action [= ]`: [`Arg::action`][crate::Arg::action] +//! - When not present: will auto-select an action based on the field type +//! - `help = `: [`Arg::help`][crate::Arg::help] +//! - When not present: [Doc comment summary](#doc-comments) +//! - `long_help[ = ]`: [`Arg::long_help`][crate::Arg::long_help] +//! - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing +//! - When present without a value: [Doc comment](#doc-comments) +//! - `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to [`help`][crate::Arg::help] / [`long_help`][crate::Arg::long_help] +//! - `short [= ]`: [`Arg::short`][crate::Arg::short] +//! - When not present: no short set +//! - Without ``: defaults to first character in the case-converted field name +//! - `long [= ]`: [`Arg::long`][crate::Arg::long] +//! - When not present: no long set +//! - Without ``: defaults to the case-converted field name +//! - `env [= ]`: [`Arg::env`][crate::Arg::env] (needs [`env` feature][crate::_features] enabled) +//! - When not present: no env set +//! - Without ``: defaults to the case-converted field name +//! - `from_global`: Read a [`Arg::global`][crate::Arg::global] argument (raw attribute), regardless of what subcommand you are in +//! - `value_enum`: Parse the value using the [`ValueEnum`][crate::ValueEnum] +//! - `skip [= ]`: Ignore this field, filling in with `` +//! - Without ``: fills the field with `Default::default()` +//! - `default_value = `: [`Arg::default_value`][crate::Arg::default_value] and [`Arg::required(false)`][crate::Arg::required] +//! - `default_value_t [= ]`: [`Arg::default_value`][crate::Arg::default_value] and [`Arg::required(false)`][crate::Arg::required] +//! - Requires `std::fmt::Display` that roundtrips correctly with the +//! [`Arg::value_parser`][crate::Arg::value_parser] or `#[arg(value_enum)]` +//! - Without ``, relies on `Default::default()` +//! - `default_values_t = `: [`Arg::default_values`][crate::Arg::default_values] and [`Arg::required(false)`][crate::Arg::required] +//! - Requires field arg to be of type `Vec` and `T` to implement `std::fmt::Display` or `#[arg(value_enum)]` +//! - `` must implement `IntoIterator` +//! - `default_value_os_t [= ]`: [`Arg::default_value_os`][crate::Arg::default_value_os] and [`Arg::required(false)`][crate::Arg::required] +//! - Requires `std::convert::Into` or `#[arg(value_enum)]` +//! - Without ``, relies on `Default::default()` +//! - `default_values_os_t = `: [`Arg::default_values_os`][crate::Arg::default_values_os] and [`Arg::required(false)`][crate::Arg::required] +//! - Requires field arg to be of type `Vec` and `T` to implement `std::convert::Into` or `#[arg(value_enum)]` +//! - `` must implement `IntoIterator` +//! +//! ### ValueEnum Attributes +//! +//! - `rename_all = `: Override default field / variant name case conversion for [`PossibleValue::new`][crate::builder::PossibleValue] +//! - When not present: `"kebab-case"` +//! - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"` +//! +//! ### Possible Value Attributes +//! +//! These correspond to a [`PossibleValue`][crate::builder::PossibleValue]. +//! +//! **Raw attributes:** Any [`PossibleValue` method][crate::builder::PossibleValue] can also be used as an attribute, see [Terminology](#terminology) for syntax. +//! - e.g. `#[value(alias("foo"))]` would translate to `pv.alias("foo")` +//! +//! **Magic attributes**: +//! - `name = `: [`PossibleValue::new`][crate::builder::PossibleValue::new] +//! - When not present: case-converted field name is used +//! - `help = `: [`PossibleValue::help`][crate::builder::PossibleValue::help] +//! - When not present: [Doc comment summary](#doc-comments) +//! - `skip`: Ignore this variant +//! +//! ## Arg Types +//! +//! `clap` assumes some intent based on the type used: +//! +//! | Type | Effect | Implies | +//! |---------------------|--------------------------------------|-------------------------------------------------------------| +//! | `()` | user-defined | `.action(ArgAction::Set).required(false)` | +//! | `bool` | flag | `.action(ArgAction::SetTrue)` | +//! | `Option` | optional argument | `.action(ArgAction::Set).required(false)` | +//! | `Option>` | optional value for optional argument | `.action(ArgAction::Set).required(false).num_args(0..=1)` | +//! | `T` | required argument | `.action(ArgAction::Set).required(!has_default)` | +//! | `Vec` | `0..` occurrences of argument | `.action(ArgAction::Append).required(false)` | +//! | `Option>` | `0..` occurrences of argument | `.action(ArgAction::Append).required(false)` | +//! +//! In addition, [`.value_parser(value_parser!(T))`][crate::value_parser!] is called for each +//! field. +//! +//! Notes: +//! - For custom type behavior, you can override the implied attributes/settings and/or set additional ones +//! - `Option>` will be `None` instead of `vec![]` if no arguments are provided. +//! - This gives the user some flexibility in designing their argument, like with `num_args(0..)` +//! +//! ## Doc Comments +//! +//! In clap, help messages for the whole binary can be specified +//! via [`Command::about`][crate::Command::about] and [`Command::long_about`][crate::Command::long_about] while help messages +//! for individual arguments can be specified via [`Arg::help`][crate::Arg::help] and [`Arg::long_help`][crate::Arg::long_help]. +//! +//! `long_*` variants are used when user calls the program with +//! `--help` and "short" variants are used with `-h` flag. +//! +//! ```rust +//! # use clap::Parser; +//! +//! #[derive(Parser)] +//! #[command(about = "I am a program and I work, just pass `-h`", long_about = None)] +//! struct Foo { +//! #[arg(short, help = "Pass `-h` and you'll see me!")] +//! bar: String, +//! } +//! ``` +//! +//! For convenience, doc comments can be used instead of raw methods +//! (this example works exactly like the one above): +//! +//! ```rust +//! # use clap::Parser; +//! +//! #[derive(Parser)] +//! /// I am a program and I work, just pass `-h` +//! struct Foo { +//! /// Pass `-h` and you'll see me! +//! bar: String, +//! } +//! ``` +//! +//! **NOTE:** Attributes have priority over doc comments! +//! +//! **Top level doc comments always generate `Command::about/long_about` calls!** +//! If you really want to use the `Command::about/long_about` methods (you likely don't), +//! use the `about` / `long_about` attributes to override the calls generated from +//! the doc comment. To clear `long_about`, you can use +//! `#[command(long_about = None)]`. +//! +//! ### Pre-processing +//! +//! ```rust +//! # use clap::Parser; +//! #[derive(Parser)] +//! /// Hi there, I'm Robo! +//! /// +//! /// I like beeping, stumbling, eating your electricity, +//! /// and making records of you singing in a shower. +//! /// Pay up, or I'll upload it to youtube! +//! struct Robo { +//! /// Call my brother SkyNet. +//! /// +//! /// I am artificial superintelligence. I won't rest +//! /// until I'll have destroyed humanity. Enjoy your +//! /// pathetic existence, you mere mortals. +//! #[arg(long, action)] +//! kill_all_humans: bool, +//! } +//! ``` +//! +//! A doc comment consists of three parts: +//! - Short summary +//! - A blank line (whitespace only) +//! - Detailed description, all the rest +//! +//! The summary corresponds with `Command::about` / `Arg::help`. When a blank line is +//! present, the whole doc comment will be passed to `Command::long_about` / +//! `Arg::long_help`. Or in other words, a doc may result in just a `Command::about` / +//! `Arg::help` or `Command::about` / `Arg::help` and `Command::long_about` / +//! `Arg::long_help` +//! +//! In addition, when `verbatim_doc_comment` is not present, `clap` applies some preprocessing, including: +//! +//! - Strip leading and trailing whitespace from every line, if present. +//! +//! - Strip leading and trailing blank lines, if present. +//! +//! - Interpret each group of non-empty lines as a word-wrapped paragraph. +//! +//! We replace newlines within paragraphs with spaces to allow the output +//! to be re-wrapped to the terminal width. +//! +//! - Strip any excess blank lines so that there is exactly one per paragraph break. +//! +//! - If the first paragraph ends in exactly one period, +//! remove the trailing period (i.e. strip trailing periods but not trailing ellipses). +//! +//! Sometimes you don't want this preprocessing to apply, for example the comment contains +//! some ASCII art or markdown tables, you would need to preserve LFs along with +//! blank lines and the leading/trailing whitespace. When you pass use the +//! `verbatim_doc_comment` magic attribute, you preserve +//! them. +//! +//! **Note:** Keep in mind that `verbatim_doc_comment` will *still* +//! - Remove one leading space from each line, even if this attribute is present, +//! to allow for a space between `///` and the content. +//! - Remove leading and trailing blank lines +//! +//! ## Mixing Builder and Derive APIs +//! +//! The builder and derive APIs do not live in isolation. They can work together, which is +//! especially helpful if some arguments can be specified at compile-time while others must be +//! specified at runtime. +//! +//! ### Using derived arguments in a builder application +//! +//! When using the derive API, you can `#[command(flatten)]` a struct deriving `Args` into a struct +//! deriving `Args` or `Parser`. This example shows how you can augment a `Command` instance +//! created using the builder API with `Args` created using the derive API. +//! +//! It uses the [`Args::augment_args`][crate::Args::augment_args] method to add the arguments to +//! the `Command` instance. +//! +//! Crates such as [clap-verbosity-flag](https://github.com/rust-cli/clap-verbosity-flag) provide +//! structs that implement `Args`. Without the technique shown in this example, it would not be +//! possible to use such crates with the builder API. +//! +//! For example: +//! ```rust +#![doc = include_str!("../../examples/derive_ref/augment_args.rs")] +//! ``` +//! +//! ### Using derived subcommands in a builder application +//! +//! When using the derive API, you can use `#[command(subcommand)]` inside the struct to add +//! subcommands. The type of the field is usually an enum that derived `Parser`. However, you can +//! also add the subcommands in that enum to a `Command` instance created with the builder API. +//! +//! It uses the [`Subcommand::augment_subcommands`][crate::Subcommand::augment_subcommands] method +//! to add the subcommands to the `Command` instance. +//! +//! For example: +//! ```rust +#![doc = include_str!("../../examples/derive_ref/augment_subcommands.rs")] +//! ``` +//! +//! ### Adding hand-implemented subcommands to a derived application +//! +//! When using the derive API, you can use `#[command(subcommand)]` inside the struct to add +//! subcommands. The type of the field is usually an enum that derived `Parser`. However, you can +//! also implement the `Subcommand` trait manually on this enum (or any other type) and it can +//! still be used inside the struct created with the derive API. The implementation of the +//! `Subcommand` trait will use the builder API to add the subcommands to the `Command` instance +//! created behind the scenes for you by the derive API. +//! +//! Notice how in the previous example we used +//! [`augment_subcommands`][crate::Subcommand::augment_subcommands] on an enum that derived +//! `Parser`, whereas now we implement +//! [`augment_subcommands`][crate::Subcommand::augment_subcommands] ourselves, but the derive API +//! calls it automatically since we used the `#[command(subcommand)]` attribute. +//! +//! For example: +//! ```rust +#![doc = include_str!("../../examples/derive_ref/hand_subcommand.rs")] +//! ``` +//! +//! ### Flattening hand-implemented args into a derived application +//! +//! When using the derive API, you can use `#[command(flatten)]` inside the struct to add arguments as +//! if they were added directly to the containing struct. The type of the field is usually an +//! struct that derived `Args`. However, you can also implement the `Args` trait manually on this +//! struct (or any other type) and it can still be used inside the struct created with the derive +//! API. The implementation of the `Args` trait will use the builder API to add the arguments to +//! the `Command` instance created behind the scenes for you by the derive API. +//! +//! Notice how in the previous example we used [`augment_args`][crate::Args::augment_args] on the +//! struct that derived `Parser`, whereas now we implement +//! [`augment_args`][crate::Args::augment_args] ourselves, but the derive API calls it +//! automatically since we used the `#[command(flatten)]` attribute. +//! +//! For example: +//! ```rust +#![doc = include_str!("../../examples/derive_ref/flatten_hand_args.rs")] +//! ``` +//! +//! ## Tips +//! +//! - To get access to a [`Command`][crate::Command] call +//! [`CommandFactory::command`][crate::CommandFactory::command] (implemented when deriving +//! [`Parser`][crate::Parser]) +//! - Proactively check for bad [`Command`][crate::Command] configurations by calling +//! [`Command::debug_assert`][crate::Command::debug_assert] in a test +//! ([example](../tutorial_derive/05_01_assert.rs)) +//! - Always remember to [document](#doc-comments) args and commands with `#![deny(missing_docs)]` + +pub mod _tutorial; +#[doc(inline)] +pub use crate::_cookbook; diff --git a/vendor/clap/src/_faq.rs b/vendor/clap/src/_faq.rs new file mode 100644 index 000000000..70e7ca5bc --- /dev/null +++ b/vendor/clap/src/_faq.rs @@ -0,0 +1,95 @@ +//! # Documentation: FAQ +//! +//! 1. [Comparisons](#comparisons) +//! 1. [How does `clap` compare to structopt?](#how-does-clap-compare-to-structopt) +//! 2. [What are some reasons to use `clap`? (The Pitch)](#what-are-some-reasons-to-use-clap-the-pitch) +//! 3. [What are some reasons *not* to use `clap`? (The Anti Pitch)](#what-are-some-reasons-not-to-use-clap-the-anti-pitch) +//! 4. [Reasons to use `clap`](#reasons-to-use-clap) +//! 2. [How many approaches are there to create a parser?](#how-many-approaches-are-there-to-create-a-parser) +//! 3. [When should I use the builder vs derive APIs?](#when-should-i-use-the-builder-vs-derive-apis) +//! 4. [Why is there a default subcommand of help?](#why-is-there-a-default-subcommand-of-help) +//! +//! ### Comparisons +//! +//! First, let me say that these comparisons are highly subjective, and not meant +//! in a critical or harsh manner. All the argument parsing libraries out there (to +//! include `clap`) have their own strengths and weaknesses. Sometimes it just +//! comes down to personal taste when all other factors are equal. When in doubt, +//! try them all and pick one that you enjoy :). There's plenty of room in the Rust +//! community for multiple implementations! +//! +//! For less detailed but more broad comparisons, see +//! [argparse-benchmarks](https://github.com/rust-cli/argparse-benchmarks-rs). +//! +//! #### How does `clap` compare to [structopt](https://github.com/TeXitoi/structopt)? +//! +//! Simple! `clap` *is* `structopt`. `structopt` started as a derive API built on +//! top of clap v2. With clap v3, we've forked structopt and integrated it +//! directly into clap. structopt is in +//! [maintenance mode](https://github.com/TeXitoi/structopt/issues/516#issuecomment-989566094) +//! with the release of `clap_derive`. +//! +//! The benefits of integrating `structopt` and `clap` are: +//! - Easier cross-linking in documentation +//! - [Documentation parity](../examples) +//! - Tighter design feedback loop, ensuring all new features are designed with +//! derives in mind and easier to change `clap` in response to `structopt` bugs. +//! - Clearer endorsement of `structopt` +//! +//! See also +//! - [`clap` v3 CHANGELOG](../CHANGELOG.md#300---2021-12-31) +//! - [`structopt` migration guide](../CHANGELOG.md#migrate-structopt) +//! +//! #### What are some reasons to use `clap`? (The Pitch) +//! +//! `clap` is as fast, and as lightweight as possible while still giving all the features you'd expect from a modern argument parser. In fact, for the amount and type of features `clap` offers it remains about as fast as `getopts`. If you use `clap`, when you just need some simple arguments parsed, you'll find it's a walk in the park. `clap` also makes it possible to represent extremely complex and advanced requirements without too much thought. `clap` aims to be intuitive, easy to use, and fully capable for wide variety use cases and needs. +//! +//! #### What are some reasons *not* to use `clap`? (The Anti Pitch) +//! +//! Depending on the style in which you choose to define the valid arguments, `clap` can be very verbose. `clap` also offers so many finetuning knobs and dials, that learning everything can seem overwhelming. I strive to keep the simple cases simple, but when turning all those custom dials it can get complex. `clap` is also opinionated about parsing. Even though so much can be tweaked and tuned with `clap` (and I'm adding more all the time), there are still certain features which `clap` implements in specific ways that may be contrary to some users' use-cases. +//! +//! #### Reasons to use `clap` +//! +//! * You want all the nice CLI features your users may expect, yet you don't want to implement them all yourself. You'd like to focus on your application, not argument parsing. +//! * In addition to the point above, you don't want to sacrifice performance to get all those nice features. +//! * You have complex requirements/conflicts between your various valid args. +//! * You want to use subcommands (although other libraries also support subcommands, they are not nearly as feature rich as those provided by `clap`). +//! * You want some sort of custom validation built into the argument parsing process, instead of as part of your application (which allows for earlier failures, better error messages, more cohesive experience, etc.). +//! +//! ### How many approaches are there to create a parser? +//! +//! The following APIs are supported: +//! - [Derive][crate::_derive::_tutorial] +//! - [Builder][crate::_tutorial] +//! +//! Previously, we supported: +//! - [YAML](https://github.com/clap-rs/clap/issues/3087) +//! - [docopt](http://docopt.org/)-inspired [usage parser](https://github.com/clap-rs/clap/issues/3086) +//! - [`clap_app!`](https://github.com/clap-rs/clap/issues/2835) +//! +//! There are also experiments with other APIs: +//! - [fncmd](https://github.com/yuhr/fncmd): function attribute +//! - [clap-serde](https://github.com/aobatact/clap-serde): create an `Command` from a deserializer +//! +//! ### When should I use the builder vs derive APIs? +//! +//! Our default answer is to use the [Derive API][crate::_derive::_tutorial]: +//! - Easier to read, write, and modify +//! - Easier to keep the argument declaration and reading of argument in sync +//! - Easier to reuse, e.g. [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag) +//! +//! The [Builder API][crate::_tutorial] is a lower-level API that someone might want to use for +//! - Faster compile times if you aren't already using other procedural macros +//! - More flexibility, e.g. you can look up an [arguments values][crate::ArgMatches::get_many], +//! their [ordering with other arguments][crate::ArgMatches::indices_of], and [what set +//! them][crate::ArgMatches::value_source]. The Derive API can only report values and not +//! indices of or other data. +//! +//! You can [interop between Derive and Builder APIs][crate::_derive#mixing-builder-and-derive-apis]. +//! +//! ### Why is there a default subcommand of help? +//! +//! There is only a default subcommand of `help` when other subcommands have been defined manually. So it's opt-in(ish), being that you only get a `help` subcommand if you're actually using subcommands. +//! +//! Also, if the user defined a `help` subcommand themselves, the auto-generated one wouldn't be added (meaning it's only generated if the user hasn't defined one themselves). +//! diff --git a/vendor/clap/src/_features.rs b/vendor/clap/src/_features.rs new file mode 100644 index 000000000..2f551e792 --- /dev/null +++ b/vendor/clap/src/_features.rs @@ -0,0 +1,29 @@ +//! ## Documentation: Feature Flags +//! +//! Available [compile-time feature flags](https://doc.rust-lang.org/cargo/reference/features.html#dependency-features) +//! +//! #### Default Features +//! +//! * **std**: _Not Currently Used._ Placeholder for supporting `no_std` environments in a backwards compatible manner. +//! * **color**: Turns on colored error messages. +//! * **help**: Auto-generate help output +//! * **usage**: Auto-generate usage +//! * **error-context**: Include contextual information for errors (which arg failed, etc) +//! * **suggestions**: Turns on the `Did you mean '--myoption'?` feature for when users make typos. +//! +//! #### Optional features +//! +//! * **deprecated**: Guided experience to prepare for next breaking release (at different stages of development, this may become default) +//! * **derive**: Enables the custom derive (i.e. `#[derive(Parser)]`). Without this you must use one of the other methods of creating a `clap` CLI listed above. +//! * **cargo**: Turns on macros that read values from [`CARGO_*` environment variables](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates). +//! * **env**: Turns on the usage of environment variables during parsing. +//! * **unicode**: Turns on support for unicode characters (including emoji) in arguments and help messages. +//! * **wrap_help**: Turns on the help text wrapping feature, based on the terminal size. +//! * **string**: Allow runtime generated strings (e.g. with [`Str`][crate::builder::Str]). +//! +//! #### Experimental features +//! +//! **Warning:** These may contain breaking changes between minor releases. +//! +//! * **unstable-replace**: Enable [`Command::replace`](https://github.com/clap-rs/clap/issues/2836) +//! * **unstable-v5**: Preview features which will be stable on the v5.0 release diff --git a/vendor/clap/src/_tutorial.rs b/vendor/clap/src/_tutorial.rs new file mode 100644 index 000000000..4605ec9a1 --- /dev/null +++ b/vendor/clap/src/_tutorial.rs @@ -0,0 +1,222 @@ +// Contributing +// +// New example code: +// - Please update the corresponding section in the derive tutorial +// - Building: They must be added to `Cargo.toml` with the appropriate `required-features`. +// - Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax +// +// See also the general CONTRIBUTING + +//! # Documentation: Builder Tutorial +//! +//! 1. [Quick Start](#quick-start) +//! 2. [Configuring the Parser](#configuring-the-parser) +//! 3. [Adding Arguments](#adding-arguments) +//! 1. [Positionals](#positionals) +//! 2. [Options](#options) +//! 3. [Flags](#flags) +//! 4. [Subcommands](#subcommands) +//! 5. [Defaults](#defaults) +//! 4. Validation +//! 1. [Enumerated values](#enumerated-values) +//! 2. [Validated values](#validated-values) +//! 3. [Argument Relations](#argument-relations) +//! 4. [Custom Validation](#custom-validation) +//! 5. [Testing](#testing) +//! +//! See also +//! - [FAQ: When should I use the builder vs derive APIs?][crate::_faq#when-should-i-use-the-builder-vs-derive-apis] +//! - The [cookbook][crate::_cookbook] for more application-focused examples +//! +//! ## Quick Start +//! +//! You can create an application with several arguments using usage strings. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/01_quick.rs")] +//! ``` +//! +#![doc = include_str!("../examples/tutorial_builder/01_quick.md")] +//! +//! ## Configuring the Parser +//! +//! You use [`Command`][crate::Command] to start building a parser. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/02_apps.rs")] +//! ``` +//! +#![doc = include_str!("../examples/tutorial_builder/02_apps.md")] +//! +//! You can use [`command!()`][crate::command!] to fill these fields in from your `Cargo.toml` +//! file. **This requires the [`cargo` feature flag][crate::_features].** +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/02_crate.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/02_crate.md")] +//! +//! You can use [`Command`][crate::Command] methods to change the application level behavior of +//! clap. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/02_app_settings.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/02_app_settings.md")] +//! +//! ## Adding Arguments +//! +//! ### Positionals +//! +//! You can have users specify values by their position on the command-line: +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_03_positional.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_03_positional.md")] +//! +//! Note that the default [`ArgAction`][crate::ArgAction] is [`Set`][crate::ArgAction::Set]. To +//! accept multiple values, use [`Append`][crate::ArgAction::Append]: +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_03_positional_mult.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_03_positional_mult.md")] +//! +//! ### Options +//! +//! You can name your arguments with a flag: +//! - Order doesn't matter +//! - They can be optional +//! - Intent is clearer +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_02_option.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_02_option.md")] +//! +//! Note that the default [`ArgAction`][crate::ArgAction] is [`Set`][crate::ArgAction::Set]. To +//! accept multiple occurrences, use [`Append`][crate::ArgAction::Append]: +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_02_option_mult.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_02_option_mult.md")] +//! +//! ### Flags +//! +//! Flags can also be switches that can be on/off: +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_01_flag_bool.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_01_flag_bool.md")] +//! +//! To accept multiple flags, use [`Count`][crate::ArgAction::Count]: +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_01_flag_count.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_01_flag_count.md")] +//! +//! ### Subcommands +//! +//! Subcommands are defined as [`Command`][crate::Command]s that get added via +//! [`Command::subcommand`][crate::Command::subcommand]. Each instance of a Subcommand can have its +//! own version, author(s), Args, and even its own subcommands. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_04_subcommands.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_04_subcommands.md")] +//! +//! ### Defaults +//! +//! We've previously showed that arguments can be [`required`][crate::Arg::required] or optional. +//! When optional, you work with a `Option` and can `unwrap_or`. Alternatively, you can set +//! [`Arg::default_value`][crate::Arg::default_value]. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/03_05_default_values.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/03_05_default_values.md")] +//! +//! ## Validation +//! +//! By default, arguments are assumed to be `String`s and only UTF-8 validation is performed. +//! +//! ### Enumerated values +//! +//! If you have arguments of specific values you want to test for, you can use the +//! [`PossibleValuesParser`][crate::builder::PossibleValuesParser] or [`Arg::value_parser(["val1", +//! ...])`][crate::Arg::value_parser] for short. +//! +//! This allows you specify the valid values for that argument. If the user does not use one of +//! those specific values, they will receive a graceful exit with error message informing them +//! of the mistake, and what the possible valid values are +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/04_01_possible.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/04_01_possible.md")] +//! +//! When enabling the [`derive` feature][crate::_features], you can use +//! [`ValueEnum`][crate::ValueEnum] to take care of the boiler plate for you, giving the same +//! results. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/04_01_enum.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/04_01_enum.md")] +//! +//! ### Validated values +//! +//! More generally, you can validate and parse into any data type. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/04_02_parse.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/04_02_parse.md")] +//! +//! A custom parser can be used to improve the error messages or provide additional validation: +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/04_02_validate.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/04_02_validate.md")] +//! +//! See [`Arg::value_parser`][crate::Arg::value_parser] for more details. +//! +//! ### Argument Relations +//! +//! You can declare dependencies or conflicts between [`Arg`][crate::Arg]s or even +//! [`ArgGroup`][crate::ArgGroup]s. +//! +//! [`ArgGroup`][crate::ArgGroup]s make it easier to declare relations instead of having to list +//! each individually, or when you want a rule to apply "any but not all" arguments. +//! +//! Perhaps the most common use of [`ArgGroup`][crate::ArgGroup]s is to require one and *only* one +//! argument to be present out of a given set. Imagine that you had multiple arguments, and you +//! want one of them to be required, but making all of them required isn't feasible because perhaps +//! they conflict with each other. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/04_03_relations.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/04_03_relations.md")] +//! +//! ### Custom Validation +//! +//! As a last resort, you can create custom errors with the basics of clap's formatting. +//! +//! ```rust +#![doc = include_str!("../examples/tutorial_builder/04_04_custom.rs")] +//! ``` +#![doc = include_str!("../examples/tutorial_builder/04_04_custom.md")] +//! +//! ## Testing +//! +//! clap reports most development errors as `debug_assert!`s. Rather than checking every +//! subcommand, you should have a test that calls +//! [`Command::debug_assert`][crate::Command::debug_assert]: +//! ```rust,no_run +#![doc = include_str!("../examples/tutorial_builder/05_01_assert.rs")] +//! ``` diff --git a/vendor/clap/src/bin/stdio-fixture.rs b/vendor/clap/src/bin/stdio-fixture.rs new file mode 100644 index 000000000..3a60d1338 --- /dev/null +++ b/vendor/clap/src/bin/stdio-fixture.rs @@ -0,0 +1,15 @@ +fn main() { + let cmd = clap::Command::new("stdio-fixture") + .version("1.0") + .long_version("1.0 - a2132c") + .arg_required_else_help(true) + .subcommand(clap::Command::new("more")) + .arg( + clap::Arg::new("verbose") + .long("verbose") + .help("log") + .action(clap::ArgAction::SetTrue) + .long_help("more log"), + ); + cmd.get_matches(); +} diff --git a/vendor/clap/src/builder/action.rs b/vendor/clap/src/builder/action.rs new file mode 100644 index 000000000..9739f8800 --- /dev/null +++ b/vendor/clap/src/builder/action.rs @@ -0,0 +1,344 @@ +/// Behavior of arguments when they are encountered while parsing +/// +/// # Examples +/// +#[cfg_attr(not(feature = "help"), doc = " ```ignore")] +#[cfg_attr(feature = "help", doc = " ```")] +/// # use clap::Command; +/// # use clap::Arg; +/// let cmd = Command::new("mycmd") +/// .arg( +/// Arg::new("special-help") +/// .short('?') +/// .action(clap::ArgAction::Help) +/// ); +/// +/// // Existing help still exists +/// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); +/// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); +/// +/// // New help available +/// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); +/// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); +/// ``` +#[derive(Clone, Debug)] +#[non_exhaustive] +#[allow(missing_copy_implementations)] // In the future, we may accept `Box` +pub enum ArgAction { + /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches] + /// + /// **NOTE:** If the argument has previously been seen, it will result in a + /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless + /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::Set) + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_many::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), + /// vec!["value"] + /// ); + /// ``` + Set, + /// When encountered, store the associated value(s) in [`ArgMatches`][crate::ArgMatches] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::Append) + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value1", "--flag", "value2"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_many::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), + /// vec!["value1", "value2"] + /// ); + /// ``` + Append, + /// When encountered, act as if `"true"` was encountered on the command-line + /// + /// If no [`default_value`][super::Arg::default_value] is set, it will be `false`. + /// + /// No value is allowed. To optionally accept a value, see + /// [`Arg::default_missing_value`][super::Arg::default_missing_value] + /// + /// **NOTE:** If the argument has previously been seen, it will result in a + /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless + /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::SetTrue) + /// ); + /// + /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_flag("flag"), + /// true + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_flag("flag"), + /// false + /// ); + /// ``` + /// + /// You can use [`TypedValueParser::map`][crate::builder::TypedValueParser::map] to have the + /// flag control an application-specific type: + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// # use clap::builder::TypedValueParser as _; + /// # use clap::builder::BoolishValueParser; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::SetTrue) + /// .value_parser( + /// BoolishValueParser::new() + /// .map(|b| -> usize { + /// if b { 10 } else { 5 } + /// }) + /// ) + /// ); + /// + /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_one::("flag").copied(), + /// Some(10) + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_one::("flag").copied(), + /// Some(5) + /// ); + /// ``` + SetTrue, + /// When encountered, act as if `"false"` was encountered on the command-line + /// + /// If no [`default_value`][super::Arg::default_value] is set, it will be `true`. + /// + /// No value is allowed. To optionally accept a value, see + /// [`Arg::default_missing_value`][super::Arg::default_missing_value] + /// + /// **NOTE:** If the argument has previously been seen, it will result in a + /// [`ArgumentConflict`][crate::error::ErrorKind::ArgumentConflict] unless + /// [`Command::args_override_self(true)`][crate::Command::args_override_self] is set. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::SetFalse) + /// ); + /// + /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_flag("flag"), + /// false + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_flag("flag"), + /// true + /// ); + /// ``` + SetFalse, + /// When encountered, increment a `u8` counter + /// + /// If no [`default_value`][super::Arg::default_value] is set, it will be `0`. + /// + /// No value is allowed. To optionally accept a value, see + /// [`Arg::default_missing_value`][super::Arg::default_missing_value] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::Count) + /// ); + /// + /// let matches = cmd.clone().try_get_matches_from(["mycmd", "--flag", "--flag"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_count("flag"), + /// 2 + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_count("flag"), + /// 0 + /// ); + /// ``` + Count, + /// When encountered, display [`Command::print_help`][super::Command::print_help] + /// + /// Depending on the flag, [`Command::print_long_help`][super::Command::print_long_help] may be shown + /// + /// # Examples + /// + #[cfg_attr(not(feature = "help"), doc = " ```ignore")] + #[cfg_attr(feature = "help", doc = " ```")] + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("special-help") + /// .short('?') + /// .action(clap::ArgAction::Help) + /// ); + /// + /// // Existing help still exists + /// let err = cmd.clone().try_get_matches_from(["mycmd", "-h"]).unwrap_err(); + /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); + /// + /// // New help available + /// let err = cmd.try_get_matches_from(["mycmd", "-?"]).unwrap_err(); + /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp); + /// ``` + Help, + /// When encountered, display [`Command::version`][super::Command::version] + /// + /// Depending on the flag, [`Command::long_version`][super::Command::long_version] may be shown + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .version("1.0.0") + /// .arg( + /// Arg::new("special-version") + /// .long("special-version") + /// .action(clap::ArgAction::Version) + /// ); + /// + /// // Existing help still exists + /// let err = cmd.clone().try_get_matches_from(["mycmd", "--version"]).unwrap_err(); + /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion); + /// + /// // New help available + /// let err = cmd.try_get_matches_from(["mycmd", "--special-version"]).unwrap_err(); + /// assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion); + /// ``` + Version, +} + +impl ArgAction { + /// Returns whether this action accepts values on the command-line + /// + /// [`default_values`][super::Arg::default_values] and [`env`][super::Arg::env] may still be + /// processed. + pub fn takes_values(&self) -> bool { + match self { + Self::Set => true, + Self::Append => true, + Self::SetTrue => false, + Self::SetFalse => false, + Self::Count => false, + Self::Help => false, + Self::Version => false, + } + } + + pub(crate) fn default_value(&self) -> Option<&'static std::ffi::OsStr> { + match self { + Self::Set => None, + Self::Append => None, + Self::SetTrue => Some(std::ffi::OsStr::new("false")), + Self::SetFalse => Some(std::ffi::OsStr::new("true")), + Self::Count => Some(std::ffi::OsStr::new("0")), + Self::Help => None, + Self::Version => None, + } + } + + pub(crate) fn default_missing_value(&self) -> Option<&'static std::ffi::OsStr> { + match self { + Self::Set => None, + Self::Append => None, + Self::SetTrue => Some(std::ffi::OsStr::new("true")), + Self::SetFalse => Some(std::ffi::OsStr::new("false")), + Self::Count => None, + Self::Help => None, + Self::Version => None, + } + } + + pub(crate) fn default_value_parser(&self) -> Option { + match self { + Self::Set => None, + Self::Append => None, + Self::SetTrue => Some(super::ValueParser::bool()), + Self::SetFalse => Some(super::ValueParser::bool()), + Self::Count => Some(crate::value_parser!(u8).into()), + Self::Help => None, + Self::Version => None, + } + } + + #[cfg(debug_assertions)] + pub(crate) fn value_type_id(&self) -> Option { + use crate::parser::AnyValueId; + + match self { + Self::Set => None, + Self::Append => None, + Self::SetTrue => None, + Self::SetFalse => None, + Self::Count => Some(AnyValueId::of::()), + Self::Help => None, + Self::Version => None, + } + } +} + +pub(crate) type CountType = u8; diff --git a/vendor/clap/src/builder/app_settings.rs b/vendor/clap/src/builder/app_settings.rs new file mode 100644 index 000000000..7a9ff8c69 --- /dev/null +++ b/vendor/clap/src/builder/app_settings.rs @@ -0,0 +1,172 @@ +// Std +use std::ops::BitOr; + +#[allow(unused)] +use crate::Arg; +#[allow(unused)] +use crate::Command; + +// Third party +use bitflags::bitflags; + +#[doc(hidden)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct AppFlags(Flags); + +impl Default for AppFlags { + fn default() -> Self { + AppFlags(Flags::COLOR_AUTO) + } +} + +/// Application level settings, which affect how [`Command`] operates +/// +/// **NOTE:** When these settings are used, they apply only to current command, and are *not* +/// propagated down or up through child or parent subcommands +/// +/// [`Command`]: crate::Command +#[derive(Debug, PartialEq, Copy, Clone)] +#[non_exhaustive] +pub(crate) enum AppSettings { + IgnoreErrors, + AllowHyphenValues, + AllowNegativeNumbers, + AllArgsOverrideSelf, + AllowMissingPositional, + TrailingVarArg, + DontDelimitTrailingValues, + InferLongArgs, + InferSubcommands, + SubcommandRequired, + AllowExternalSubcommands, + Multicall, + SubcommandsNegateReqs, + ArgsNegateSubcommands, + SubcommandPrecedenceOverArg, + ArgRequiredElseHelp, + NextLineHelp, + DisableColoredHelp, + DisableHelpFlag, + DisableHelpSubcommand, + DisableVersionFlag, + PropagateVersion, + Hidden, + HidePossibleValues, + HelpExpected, + NoBinaryName, + #[allow(dead_code)] + ColorAuto, + ColorAlways, + ColorNever, + Built, + BinNameBuilt, +} + +bitflags! { + struct Flags: u64 { + const SC_NEGATE_REQS = 1; + const SC_REQUIRED = 1 << 1; + const ARG_REQUIRED_ELSE_HELP = 1 << 2; + const PROPAGATE_VERSION = 1 << 3; + const DISABLE_VERSION_FOR_SC = 1 << 4; + const WAIT_ON_ERROR = 1 << 6; + const DISABLE_VERSION_FLAG = 1 << 10; + const HIDDEN = 1 << 11; + const TRAILING_VARARG = 1 << 12; + const NO_BIN_NAME = 1 << 13; + const ALLOW_UNK_SC = 1 << 14; + const LEADING_HYPHEN = 1 << 16; + const NO_POS_VALUES = 1 << 17; + const NEXT_LINE_HELP = 1 << 18; + const DISABLE_COLORED_HELP = 1 << 20; + const COLOR_ALWAYS = 1 << 21; + const COLOR_AUTO = 1 << 22; + const COLOR_NEVER = 1 << 23; + const DONT_DELIM_TRAIL = 1 << 24; + const ALLOW_NEG_NUMS = 1 << 25; + const DISABLE_HELP_SC = 1 << 27; + const ARGS_NEGATE_SCS = 1 << 29; + const PROPAGATE_VALS_DOWN = 1 << 30; + const ALLOW_MISSING_POS = 1 << 31; + const TRAILING_VALUES = 1 << 32; + const BUILT = 1 << 33; + const BIN_NAME_BUILT = 1 << 34; + const VALID_ARG_FOUND = 1 << 35; + const INFER_SUBCOMMANDS = 1 << 36; + const CONTAINS_LAST = 1 << 37; + const ARGS_OVERRIDE_SELF = 1 << 38; + const HELP_REQUIRED = 1 << 39; + const SUBCOMMAND_PRECEDENCE_OVER_ARG = 1 << 40; + const DISABLE_HELP_FLAG = 1 << 41; + const INFER_LONG_ARGS = 1 << 43; + const IGNORE_ERRORS = 1 << 44; + const MULTICALL = 1 << 45; + const EXPAND_HELP_SUBCOMMAND_TREES = 1 << 46; + const NO_OP = 0; + } +} + +impl_settings! { AppSettings, AppFlags, + ArgRequiredElseHelp + => Flags::ARG_REQUIRED_ELSE_HELP, + SubcommandPrecedenceOverArg + => Flags::SUBCOMMAND_PRECEDENCE_OVER_ARG, + ArgsNegateSubcommands + => Flags::ARGS_NEGATE_SCS, + AllowExternalSubcommands + => Flags::ALLOW_UNK_SC, + AllowHyphenValues + => Flags::LEADING_HYPHEN, + AllowNegativeNumbers + => Flags::ALLOW_NEG_NUMS, + AllowMissingPositional + => Flags::ALLOW_MISSING_POS, + ColorAlways + => Flags::COLOR_ALWAYS, + ColorAuto + => Flags::COLOR_AUTO, + ColorNever + => Flags::COLOR_NEVER, + DontDelimitTrailingValues + => Flags::DONT_DELIM_TRAIL, + DisableColoredHelp + => Flags::DISABLE_COLORED_HELP, + DisableHelpSubcommand + => Flags::DISABLE_HELP_SC, + DisableHelpFlag + => Flags::DISABLE_HELP_FLAG, + DisableVersionFlag + => Flags::DISABLE_VERSION_FLAG, + PropagateVersion + => Flags::PROPAGATE_VERSION, + HidePossibleValues + => Flags::NO_POS_VALUES, + HelpExpected + => Flags::HELP_REQUIRED, + Hidden + => Flags::HIDDEN, + Multicall + => Flags::MULTICALL, + NoBinaryName + => Flags::NO_BIN_NAME, + SubcommandsNegateReqs + => Flags::SC_NEGATE_REQS, + SubcommandRequired + => Flags::SC_REQUIRED, + TrailingVarArg + => Flags::TRAILING_VARARG, + NextLineHelp + => Flags::NEXT_LINE_HELP, + IgnoreErrors + => Flags::IGNORE_ERRORS, + Built + => Flags::BUILT, + BinNameBuilt + => Flags::BIN_NAME_BUILT, + InferSubcommands + => Flags::INFER_SUBCOMMANDS, + AllArgsOverrideSelf + => Flags::ARGS_OVERRIDE_SELF, + InferLongArgs + => Flags::INFER_LONG_ARGS +} diff --git a/vendor/clap/src/builder/arg.rs b/vendor/clap/src/builder/arg.rs new file mode 100644 index 000000000..ca2d6acbc --- /dev/null +++ b/vendor/clap/src/builder/arg.rs @@ -0,0 +1,4647 @@ +// Std +#[cfg(feature = "env")] +use std::env; +#[cfg(feature = "env")] +use std::ffi::OsString; +use std::{ + cmp::{Ord, Ordering}, + fmt::{self, Display, Formatter}, + str, +}; + +// Internal +use super::{ArgFlags, ArgSettings}; +use crate::builder::ArgPredicate; +use crate::builder::IntoResettable; +use crate::builder::OsStr; +use crate::builder::PossibleValue; +use crate::builder::Str; +use crate::builder::StyledStr; +use crate::builder::ValueRange; +use crate::ArgAction; +use crate::Id; +use crate::ValueHint; +use crate::INTERNAL_ERROR_MSG; + +/// The abstract representation of a command line argument. Used to set all the options and +/// relationships that define a valid argument for the program. +/// +/// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options +/// manually, or using a usage string which is far less verbose but has fewer options. You can also +/// use a combination of the two methods to achieve the best of both worlds. +/// +/// - [Basic API][crate::Arg#basic-api] +/// - [Value Handling][crate::Arg#value-handling] +/// - [Help][crate::Arg#help-1] +/// - [Advanced Argument Relations][crate::Arg#advanced-argument-relations] +/// - [Reflection][crate::Arg#reflection] +/// +/// # Examples +/// +/// ```rust +/// # use clap::{Arg, arg, ArgAction}; +/// // Using the traditional builder pattern and setting each option manually +/// let cfg = Arg::new("config") +/// .short('c') +/// .long("config") +/// .action(ArgAction::Set) +/// .value_name("FILE") +/// .help("Provides a config file to myprog"); +/// // Using a usage string (setting a similar argument to the one above) +/// let input = arg!(-i --input "Provides an input file to the program"); +/// ``` +#[derive(Default, Clone)] +pub struct Arg { + pub(crate) id: Id, + pub(crate) help: Option, + pub(crate) long_help: Option, + pub(crate) action: Option, + pub(crate) value_parser: Option, + pub(crate) blacklist: Vec, + pub(crate) settings: ArgFlags, + pub(crate) overrides: Vec, + pub(crate) groups: Vec, + pub(crate) requires: Vec<(ArgPredicate, Id)>, + pub(crate) r_ifs: Vec<(Id, OsStr)>, + pub(crate) r_ifs_all: Vec<(Id, OsStr)>, + pub(crate) r_unless: Vec, + pub(crate) r_unless_all: Vec, + pub(crate) short: Option, + pub(crate) long: Option, + pub(crate) aliases: Vec<(Str, bool)>, // (name, visible) + pub(crate) short_aliases: Vec<(char, bool)>, // (name, visible) + pub(crate) disp_ord: Option, + pub(crate) val_names: Vec, + pub(crate) num_vals: Option, + pub(crate) val_delim: Option, + pub(crate) default_vals: Vec, + pub(crate) default_vals_ifs: Vec<(Id, ArgPredicate, Option)>, + pub(crate) default_missing_vals: Vec, + #[cfg(feature = "env")] + pub(crate) env: Option<(OsStr, Option)>, + pub(crate) terminator: Option, + pub(crate) index: Option, + pub(crate) help_heading: Option>, + pub(crate) value_hint: Option, +} + +/// # Basic API +impl Arg { + /// Create a new [`Arg`] with a unique name. + /// + /// The name is used to check whether or not the argument was used at + /// runtime, get values, set relationships with other args, etc.. + /// + /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::action(ArgAction::Set)`]) + /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also + /// be displayed when the user prints the usage/help information of the program. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("config") + /// # ; + /// ``` + /// [`Arg::action(ArgAction::Set)`]: Arg::action() + pub fn new(id: impl Into) -> Self { + Arg::default().id(id) + } + + /// Set the identifier used for referencing this argument in the clap API. + /// + /// See [`Arg::new`] for more details. + #[must_use] + pub fn id(mut self, id: impl Into) -> Self { + self.id = id.into(); + self + } + + /// Sets the short version of the argument without the preceding `-`. + /// + /// By default `V` and `h` are used by the auto-generated `version` and `help` arguments, + /// respectively. You will need to disable the auto-generated flags + /// ([`disable_help_flag`][crate::Command::disable_help_flag], + /// [`disable_version_flag`][crate::Command::disable_version_flag]) and define your own. + /// + /// # Examples + /// + /// When calling `short`, use a single valid UTF-8 character which will allow using the + /// argument via a single hyphen (`-`) such as `-c`: + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("config") + /// .short('c') + /// .action(ArgAction::Set)) + /// .get_matches_from(vec![ + /// "prog", "-c", "file.toml" + /// ]); + /// + /// assert_eq!(m.get_one::("config").map(String::as_str), Some("file.toml")); + /// ``` + /// + /// To use `-h` for your own flag and still have help: + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .disable_help_flag(true) + /// .arg(Arg::new("host") + /// .short('h') + /// .long("host")) + /// .arg(Arg::new("help") + /// .long("help") + /// .global(true) + /// .action(ArgAction::Help)) + /// .get_matches_from(vec![ + /// "prog", "-h", "wikipedia.org" + /// ]); + /// + /// assert_eq!(m.get_one::("host").map(String::as_str), Some("wikipedia.org")); + /// ``` + #[inline] + #[must_use] + pub fn short(mut self, s: impl IntoResettable) -> Self { + if let Some(s) = s.into_resettable().into_option() { + debug_assert!(s != '-', "short option name cannot be `-`"); + self.short = Some(s); + } else { + self.short = None; + } + self + } + + /// Sets the long version of the argument without the preceding `--`. + /// + /// By default `version` and `help` are used by the auto-generated `version` and `help` + /// arguments, respectively. You may use the word `version` or `help` for the long form of your + /// own arguments, in which case `clap` simply will not assign those to the auto-generated + /// `version` or `help` arguments. + /// + /// **NOTE:** Any leading `-` characters will be stripped + /// + /// # Examples + /// + /// To set `long` use a word containing valid UTF-8. If you supply a double leading + /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however, + /// will *not* be stripped (i.e. `config-file` is allowed). + /// + /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config` + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .action(ArgAction::Set)) + /// .get_matches_from(vec![ + /// "prog", "--config", "file.toml" + /// ]); + /// + /// assert_eq!(m.get_one::("cfg").map(String::as_str), Some("file.toml")); + /// ``` + #[inline] + #[must_use] + pub fn long(mut self, l: impl IntoResettable) -> Self { + self.long = l.into_resettable().into_option(); + self + } + + /// Add an alias, which functions as a hidden long flag. + /// + /// This is more efficient, and easier than creating multiple hidden arguments as one only + /// needs to check for the existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .alias("alias") + /// .action(ArgAction::Set)) + /// .get_matches_from(vec![ + /// "prog", "--alias", "cool" + /// ]); + /// assert_eq!(m.get_one::("test").unwrap(), "cool"); + /// ``` + #[must_use] + pub fn alias(mut self, name: impl IntoResettable) -> Self { + if let Some(name) = name.into_resettable().into_option() { + self.aliases.push((name, false)); + } else { + self.aliases.clear(); + } + self + } + + /// Add an alias, which functions as a hidden short flag. + /// + /// This is more efficient, and easier than creating multiple hidden arguments as one only + /// needs to check for the existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .short('t') + /// .short_alias('e') + /// .action(ArgAction::Set)) + /// .get_matches_from(vec![ + /// "prog", "-e", "cool" + /// ]); + /// assert_eq!(m.get_one::("test").unwrap(), "cool"); + /// ``` + #[must_use] + pub fn short_alias(mut self, name: impl IntoResettable) -> Self { + if let Some(name) = name.into_resettable().into_option() { + debug_assert!(name != '-', "short alias name cannot be `-`"); + self.short_aliases.push((name, false)); + } else { + self.short_aliases.clear(); + } + self + } + + /// Add aliases, which function as hidden long flags. + /// + /// This is more efficient, and easier than creating multiple hidden subcommands as one only + /// needs to check for the existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .aliases(["do-stuff", "do-tests", "tests"]) + /// .action(ArgAction::SetTrue) + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec![ + /// "prog", "--do-tests" + /// ]); + /// assert_eq!(m.get_flag("test"), true); + /// ``` + #[must_use] + pub fn aliases(mut self, names: impl IntoIterator>) -> Self { + self.aliases + .extend(names.into_iter().map(|x| (x.into(), false))); + self + } + + /// Add aliases, which functions as a hidden short flag. + /// + /// This is more efficient, and easier than creating multiple hidden subcommands as one only + /// needs to check for the existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .short('t') + /// .short_aliases(['e', 's']) + /// .action(ArgAction::SetTrue) + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec![ + /// "prog", "-s" + /// ]); + /// assert_eq!(m.get_flag("test"), true); + /// ``` + #[must_use] + pub fn short_aliases(mut self, names: impl IntoIterator) -> Self { + for s in names { + debug_assert!(s != '-', "short alias name cannot be `-`"); + self.short_aliases.push((s, false)); + } + self + } + + /// Add an alias, which functions as a visible long flag. + /// + /// Like [`Arg::alias`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .visible_alias("something-awesome") + /// .long("test") + /// .action(ArgAction::Set)) + /// .get_matches_from(vec![ + /// "prog", "--something-awesome", "coffee" + /// ]); + /// assert_eq!(m.get_one::("test").unwrap(), "coffee"); + /// ``` + /// [`Command::alias`]: Arg::alias() + #[must_use] + pub fn visible_alias(mut self, name: impl IntoResettable) -> Self { + if let Some(name) = name.into_resettable().into_option() { + self.aliases.push((name, true)); + } else { + self.aliases.clear(); + } + self + } + + /// Add an alias, which functions as a visible short flag. + /// + /// Like [`Arg::short_alias`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .visible_short_alias('t') + /// .action(ArgAction::Set)) + /// .get_matches_from(vec![ + /// "prog", "-t", "coffee" + /// ]); + /// assert_eq!(m.get_one::("test").unwrap(), "coffee"); + /// ``` + #[must_use] + pub fn visible_short_alias(mut self, name: impl IntoResettable) -> Self { + if let Some(name) = name.into_resettable().into_option() { + debug_assert!(name != '-', "short alias name cannot be `-`"); + self.short_aliases.push((name, true)); + } else { + self.short_aliases.clear(); + } + self + } + + /// Add aliases, which function as visible long flags. + /// + /// Like [`Arg::aliases`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .action(ArgAction::SetTrue) + /// .visible_aliases(["something", "awesome", "cool"])) + /// .get_matches_from(vec![ + /// "prog", "--awesome" + /// ]); + /// assert_eq!(m.get_flag("test"), true); + /// ``` + /// [`Command::aliases`]: Arg::aliases() + #[must_use] + pub fn visible_aliases(mut self, names: impl IntoIterator>) -> Self { + self.aliases + .extend(names.into_iter().map(|n| (n.into(), true))); + self + } + + /// Add aliases, which function as visible short flags. + /// + /// Like [`Arg::short_aliases`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("test") + /// .long("test") + /// .action(ArgAction::SetTrue) + /// .visible_short_aliases(['t', 'e'])) + /// .get_matches_from(vec![ + /// "prog", "-t" + /// ]); + /// assert_eq!(m.get_flag("test"), true); + /// ``` + #[must_use] + pub fn visible_short_aliases(mut self, names: impl IntoIterator) -> Self { + for n in names { + debug_assert!(n != '-', "short alias name cannot be `-`"); + self.short_aliases.push((n, true)); + } + self + } + + /// Specifies the index of a positional argument **starting at** 1. + /// + /// **NOTE:** The index refers to position according to **other positional argument**. It does + /// not define position in the argument list as a whole. + /// + /// **NOTE:** You can optionally leave off the `index` method, and the index will be + /// assigned in order of evaluation. Utilizing the `index` method allows for setting + /// indexes out of order + /// + /// **NOTE:** This is only meant to be used for positional arguments and shouldn't to be used + /// with [`Arg::short`] or [`Arg::long`]. + /// + /// **NOTE:** When utilized with [`Arg::num_args(1..)`], only the **last** positional argument + /// may be defined as having a variable number of arguments (i.e. with the highest index) + /// + /// # Panics + /// + /// [`Command`] will [`panic!`] if indexes are skipped (such as defining `index(1)` and `index(3)` + /// but not `index(2)`, or a positional argument is defined as multiple and is not the highest + /// index + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("config") + /// .index(1) + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .index(1)) + /// .arg(Arg::new("debug") + /// .long("debug") + /// .action(ArgAction::SetTrue)) + /// .get_matches_from(vec![ + /// "prog", "--debug", "fast" + /// ]); + /// + /// assert!(m.contains_id("mode")); + /// assert_eq!(m.get_one::("mode").unwrap(), "fast"); // notice index(1) means "first positional" + /// // *not* first argument + /// ``` + /// [`Arg::short`]: Arg::short() + /// [`Arg::long`]: Arg::long() + /// [`Arg::num_args(true)`]: Arg::num_args() + /// [`Command`]: crate::Command + #[inline] + #[must_use] + pub fn index(mut self, idx: impl IntoResettable) -> Self { + self.index = idx.into_resettable().into_option(); + self + } + + /// This is a "VarArg" and everything that follows should be captured by it, as if the user had + /// used a `--`. + /// + /// **NOTE:** To start the trailing "VarArg" on unknown flags (and not just a positional + /// value), set [`allow_hyphen_values`][Arg::allow_hyphen_values]. Either way, users still + /// have the option to explicitly escape ambiguous arguments with `--`. + /// + /// **NOTE:** [`Arg::value_delimiter`] still applies if set. + /// + /// **NOTE:** Setting this requires [`Arg::num_args(..)`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let m = Command::new("myprog") + /// .arg(arg!( ... "commands to run").trailing_var_arg(true)) + /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]); + /// + /// let trail: Vec<_> = m.get_many::("cmd").unwrap().collect(); + /// assert_eq!(trail, ["arg1", "-r", "val1"]); + /// ``` + /// [`Arg::num_args(..)`]: crate::Arg::num_args() + pub fn trailing_var_arg(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::TrailingVarArg) + } else { + self.unset_setting(ArgSettings::TrailingVarArg) + } + } + + /// This arg is the last, or final, positional argument (i.e. has the highest + /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args -- + /// last_arg`). + /// + /// Even, if no other arguments are left to parse, if the user omits the `--` syntax + /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also + /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with + /// the `--` syntax is otherwise not possible. + /// + /// **NOTE:** This will change the usage string to look like `$ prog [OPTIONS] [-- ]` if + /// `ARG` is marked as `.last(true)`. + /// + /// **NOTE:** This setting will imply [`crate::Command::dont_collapse_args_in_usage`] because failing + /// to set this can make the usage string very confusing. + /// + /// **NOTE**: This setting only applies to positional arguments, and has no effect on OPTIONS + /// + /// **NOTE:** Setting this requires [taking values][Arg::num_args] + /// + /// **CAUTION:** Using this setting *and* having child subcommands is not + /// recommended with the exception of *also* using + /// [`crate::Command::args_conflicts_with_subcommands`] + /// (or [`crate::Command::subcommand_negates_reqs`] if the argument marked `Last` is also + /// marked [`Arg::required`]) + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Arg, ArgAction}; + /// Arg::new("args") + /// .action(ArgAction::Set) + /// .last(true) + /// # ; + /// ``` + /// + /// Setting `last` ensures the arg has the highest [index] of all positional args + /// and requires that the `--` syntax be used to access it early. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("first")) + /// .arg(Arg::new("second")) + /// .arg(Arg::new("third") + /// .action(ArgAction::Set) + /// .last(true)) + /// .try_get_matches_from(vec![ + /// "prog", "one", "--", "three" + /// ]); + /// + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// assert_eq!(m.get_one::("third").unwrap(), "three"); + /// assert_eq!(m.get_one::("second"), None); + /// ``` + /// + /// Even if the positional argument marked `Last` is the only argument left to parse, + /// failing to use the `--` syntax results in an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("first")) + /// .arg(Arg::new("second")) + /// .arg(Arg::new("third") + /// .action(ArgAction::Set) + /// .last(true)) + /// .try_get_matches_from(vec![ + /// "prog", "one", "two", "three" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + /// [index]: Arg::index() + /// [`UnknownArgument`]: crate::error::ErrorKind::UnknownArgument + #[inline] + #[must_use] + pub fn last(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Last) + } else { + self.unset_setting(ArgSettings::Last) + } + } + + /// Specifies that the argument must be present. + /// + /// Required by default means it is required, when no other conflicting rules or overrides have + /// been evaluated. Conflicting rules take precedence over being required. + /// + /// **Pro tip:** Flags (i.e. not positional, or arguments that take values) shouldn't be + /// required by default. This is because if a flag were to be required, it should simply be + /// implied. No additional information is required from user. Flags by their very nature are + /// simply boolean on/off switches. The only time a user *should* be required to use a flag + /// is if the operation is destructive in nature, and the user is essentially proving to you, + /// "Yes, I know what I'm doing." + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required(true) + /// # ; + /// ``` + /// + /// Setting required requires that the argument be used at runtime. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required(true) + /// .action(ArgAction::Set) + /// .long("config")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf", + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting required and then *not* supplying that argument at runtime is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required(true) + /// .action(ArgAction::Set) + /// .long("config")) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + #[inline] + #[must_use] + pub fn required(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Required) + } else { + self.unset_setting(ArgSettings::Required) + } + } + + /// Sets an argument that is required when this one is present + /// + /// i.e. when using this argument, the following argument *must* be present. + /// + /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .requires("input") + /// # ; + /// ``` + /// + /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the + /// defining argument is used. If the defining argument isn't used, the other argument isn't + /// required + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required + /// ``` + /// + /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .requires("input") + /// .long("config")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [override]: Arg::overrides_with() + #[must_use] + pub fn requires(mut self, arg_id: impl IntoResettable) -> Self { + if let Some(arg_id) = arg_id.into_resettable().into_option() { + self.requires.push((ArgPredicate::IsPresent, arg_id)); + } else { + self.requires.clear(); + } + self + } + + /// This argument must be passed alone; it conflicts with all other arguments. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .exclusive(true) + /// # ; + /// ``` + /// + /// Setting an exclusive argument and having any other arguments present at runtime + /// is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("exclusive") + /// .action(ArgAction::Set) + /// .exclusive(true) + /// .long("exclusive")) + /// .arg(Arg::new("debug") + /// .long("debug")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog", "--exclusive", "file.conf", "file.txt" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); + /// ``` + #[inline] + #[must_use] + pub fn exclusive(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Exclusive) + } else { + self.unset_setting(ArgSettings::Exclusive) + } + } + + /// Specifies that an argument can be matched to all child [`Subcommand`]s. + /// + /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however + /// their values once a user uses them will be propagated back up to parents. In effect, this + /// means one should *define* all global arguments at the top level, however it doesn't matter + /// where the user *uses* the global argument. + /// + /// # Examples + /// + /// Assume an application with two subcommands, and you'd like to define a + /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't + /// want to clutter the source with three duplicate [`Arg`] definitions. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("verb") + /// .long("verbose") + /// .short('v') + /// .action(ArgAction::SetTrue) + /// .global(true)) + /// .subcommand(Command::new("test")) + /// .subcommand(Command::new("do-stuff")) + /// .get_matches_from(vec![ + /// "prog", "do-stuff", "--verbose" + /// ]); + /// + /// assert_eq!(m.subcommand_name(), Some("do-stuff")); + /// let sub_m = m.subcommand_matches("do-stuff").unwrap(); + /// assert_eq!(sub_m.get_flag("verb"), true); + /// ``` + /// + /// [`Subcommand`]: crate::Subcommand + #[inline] + #[must_use] + pub fn global(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Global) + } else { + self.unset_setting(ArgSettings::Global) + } + } + + #[inline] + pub(crate) fn is_set(&self, s: ArgSettings) -> bool { + self.settings.is_set(s) + } + + #[inline] + #[must_use] + pub(crate) fn setting(mut self, setting: F) -> Self + where + F: Into, + { + self.settings.insert(setting.into()); + self + } + + #[inline] + #[must_use] + pub(crate) fn unset_setting(mut self, setting: F) -> Self + where + F: Into, + { + self.settings.remove(setting.into()); + self + } +} + +/// # Value Handling +impl Arg { + /// Specify how to react to an argument when parsing it. + /// + /// [ArgAction][crate::ArgAction] controls things like + /// - Overwriting previous values with new ones + /// - Appending new values to all previous ones + /// - Counting how many times a flag occurs + /// + /// The default action is `ArgAction::Set` + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// # use clap::Arg; + /// let cmd = Command::new("mycmd") + /// .arg( + /// Arg::new("flag") + /// .long("flag") + /// .action(clap::ArgAction::Append) + /// ); + /// + /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap(); + /// assert!(matches.contains_id("flag")); + /// assert_eq!( + /// matches.get_many::("flag").unwrap_or_default().map(|v| v.as_str()).collect::>(), + /// vec!["value"] + /// ); + /// ``` + #[inline] + #[must_use] + pub fn action(mut self, action: impl IntoResettable) -> Self { + self.action = action.into_resettable().into_option(); + self + } + + /// Specify the typed behavior of the argument. + /// + /// This allows parsing and validating a value before storing it into + /// [`ArgMatches`][crate::ArgMatches] as the given type. + /// + /// Possible value parsers include: + /// - [`value_parser!(T)`][crate::value_parser!] for auto-selecting a value parser for a given type + /// - Or [range expressions like `0..=1`][std::ops::RangeBounds] as a shorthand for [`RangedI64ValueParser`][crate::builder::RangedI64ValueParser] + /// - `Fn(&str) -> Result` + /// - `[&str]` and [`PossibleValuesParser`][crate::builder::PossibleValuesParser] for static enumerated values + /// - [`BoolishValueParser`][crate::builder::BoolishValueParser], and [`FalseyValueParser`][crate::builder::FalseyValueParser] for alternative `bool` implementations + /// - [`NonEmptyStringValueParser`][crate::builder::NonEmptyStringValueParser] for basic validation for strings + /// - or any other [`TypedValueParser`][crate::builder::TypedValueParser] implementation + /// + /// The default value is [`ValueParser::string`][crate::builder::ValueParser::string]. + /// + /// ```rust + /// # use clap::ArgAction; + /// let mut cmd = clap::Command::new("raw") + /// .arg( + /// clap::Arg::new("color") + /// .long("color") + /// .value_parser(["always", "auto", "never"]) + /// .default_value("auto") + /// ) + /// .arg( + /// clap::Arg::new("hostname") + /// .long("hostname") + /// .value_parser(clap::builder::NonEmptyStringValueParser::new()) + /// .action(ArgAction::Set) + /// .required(true) + /// ) + /// .arg( + /// clap::Arg::new("port") + /// .long("port") + /// .value_parser(clap::value_parser!(u16).range(3000..)) + /// .action(ArgAction::Set) + /// .required(true) + /// ); + /// + /// let m = cmd.try_get_matches_from_mut( + /// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"] + /// ).unwrap(); + /// + /// let color: &String = m.get_one("color") + /// .expect("default"); + /// assert_eq!(color, "auto"); + /// + /// let hostname: &String = m.get_one("hostname") + /// .expect("required"); + /// assert_eq!(hostname, "rust-lang.org"); + /// + /// let port: u16 = *m.get_one("port") + /// .expect("required"); + /// assert_eq!(port, 3001); + /// ``` + pub fn value_parser(mut self, parser: impl IntoResettable) -> Self { + self.value_parser = parser.into_resettable().into_option(); + self + } + + /// Specifies the number of arguments parsed per occurrence + /// + /// For example, if you had a `-f ` argument where you wanted exactly 3 'files' you would + /// set `.num_args(3)`, and this argument wouldn't be satisfied unless the user + /// provided 3 and only 3 values. + /// + /// Users may specify values for arguments in any of the following methods + /// + /// - Using a space such as `-o value` or `--option value` + /// - Using an equals and no space such as `-o=value` or `--option=value` + /// - Use a short and no space such as `-ovalue` + /// + /// **WARNING:** + /// + /// Setting a variable number of values (e.g. `1..=10`) for an argument without + /// other details can be dangerous in some circumstances. Because multiple values are + /// allowed, `--option val1 val2 val3` is perfectly valid. Be careful when designing a CLI + /// where **positional arguments** or **subcommands** are *also* expected as `clap` will continue + /// parsing *values* until one of the following happens: + /// + /// - It reaches the maximum number of values + /// - It reaches a specific number of values + /// - It finds another flag or option (i.e. something that starts with a `-`) + /// - It reaches the [`Arg::value_terminator`] if set + /// + /// Alternatively, + /// - Use a delimiter between values with [Arg::value_delimiter] + /// - Require a flag occurrence per value with [`ArgAction::Append`] + /// - Require positional arguments to appear after `--` with [`Arg::last`] + /// + /// # Examples + /// + /// Option: + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .num_args(1)) + /// .get_matches_from(vec![ + /// "prog", "--mode", "fast" + /// ]); + /// + /// assert_eq!(m.get_one::("mode").unwrap(), "fast"); + /// ``` + /// + /// Flag/option hybrid (see also [default_missing_value][Arg::default_missing_value]) + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let cmd = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .default_missing_value("slow") + /// .default_value("plaid") + /// .num_args(0..=1)); + /// + /// let m = cmd.clone() + /// .get_matches_from(vec![ + /// "prog", "--mode", "fast" + /// ]); + /// assert_eq!(m.get_one::("mode").unwrap(), "fast"); + /// + /// let m = cmd.clone() + /// .get_matches_from(vec![ + /// "prog", "--mode", + /// ]); + /// assert_eq!(m.get_one::("mode").unwrap(), "slow"); + /// + /// let m = cmd.clone() + /// .get_matches_from(vec![ + /// "prog", + /// ]); + /// assert_eq!(m.get_one::("mode").unwrap(), "plaid"); + /// ``` + /// + /// Tuples + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let cmd = Command::new("prog") + /// .arg(Arg::new("file") + /// .action(ArgAction::Set) + /// .num_args(2) + /// .short('F')); + /// + /// let m = cmd.clone() + /// .get_matches_from(vec![ + /// "prog", "-F", "in-file", "out-file" + /// ]); + /// assert_eq!( + /// m.get_many::("file").unwrap_or_default().map(|v| v.as_str()).collect::>(), + /// vec!["in-file", "out-file"] + /// ); + /// + /// let res = cmd.clone() + /// .try_get_matches_from(vec![ + /// "prog", "-F", "file1" + /// ]); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::WrongNumberOfValues); + /// ``` + /// + /// A common mistake is to define an option which allows multiple values and a positional + /// argument. + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let cmd = Command::new("prog") + /// .arg(Arg::new("file") + /// .action(ArgAction::Set) + /// .num_args(0..) + /// .short('F')) + /// .arg(Arg::new("word")); + /// + /// let m = cmd.clone().get_matches_from(vec![ + /// "prog", "-F", "file1", "file2", "file3", "word" + /// ]); + /// let files: Vec<_> = m.get_many::("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?! + /// assert!(!m.contains_id("word")); // but we clearly used word! + /// + /// // but this works + /// let m = cmd.clone().get_matches_from(vec![ + /// "prog", "word", "-F", "file1", "file2", "file3", + /// ]); + /// let files: Vec<_> = m.get_many::("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// assert_eq!(m.get_one::("word").unwrap(), "word"); + /// ``` + /// The problem is `clap` doesn't know when to stop parsing values for "file". + /// + /// A solution for the example above is to limit how many values with a maximum, or specific + /// number, or to say [`ArgAction::Append`] is ok, but multiple values are not. + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("file") + /// .action(ArgAction::Append) + /// .short('F')) + /// .arg(Arg::new("word")) + /// .get_matches_from(vec![ + /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word" + /// ]); + /// + /// let files: Vec<_> = m.get_many::("file").unwrap().collect(); + /// assert_eq!(files, ["file1", "file2", "file3"]); + /// assert_eq!(m.get_one::("word").unwrap(), "word"); + /// ``` + #[inline] + #[must_use] + pub fn num_args(mut self, qty: impl IntoResettable) -> Self { + self.num_vals = qty.into_resettable().into_option(); + self + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Arg::num_args`") + )] + pub fn number_of_values(self, qty: usize) -> Self { + self.num_args(qty) + } + + /// Placeholder for the argument's value in the help message / usage. + /// + /// This name is cosmetic only; the name is **not** used to access arguments. + /// This setting can be very helpful when describing the type of input the user should be + /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to + /// use all capital letters for the value name. + /// + /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("cfg") + /// .long("config") + /// .value_name("FILE") + /// # ; + /// ``` + /// + #[cfg_attr(not(feature = "help"), doc = " ```ignore")] + #[cfg_attr(feature = "help", doc = " ```")] + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("config") + /// .long("config") + /// .value_name("FILE") + /// .help("Some help text")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// Running the above program produces the following output + /// + /// ```text + /// valnames + /// + /// Usage: valnames [OPTIONS] + /// + /// Options: + /// --config Some help text + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + /// [positional]: Arg::index() + /// [`Arg::action(ArgAction::Set)`]: Arg::action() + #[inline] + #[must_use] + pub fn value_name(mut self, name: impl IntoResettable) -> Self { + if let Some(name) = name.into_resettable().into_option() { + self.value_names([name]) + } else { + self.val_names.clear(); + self + } + } + + /// Placeholders for the argument's values in the help message / usage. + /// + /// These names are cosmetic only, used for help and usage strings only. The names are **not** + /// used to access arguments. The values of the arguments are accessed in numeric order (i.e. + /// if you specify two names `one` and `two` `one` will be the first matched value, `two` will + /// be the second). + /// + /// This setting can be very helpful when describing the type of input the user should be + /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to + /// use all capital letters for the value name. + /// + /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or + /// multiple value names in order to not throw off the help text alignment of all options. + /// + /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`] and [`Arg::num_args(1..)`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("speed") + /// .short('s') + /// .value_names(["fast", "slow"]); + /// ``` + /// + #[cfg_attr(not(feature = "help"), doc = " ```ignore")] + #[cfg_attr(feature = "help", doc = " ```")] + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("io") + /// .long("io-files") + /// .value_names(["INFILE", "OUTFILE"])) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// Running the above program produces the following output + /// + /// ```text + /// valnames + /// + /// Usage: valnames [OPTIONS] + /// + /// Options: + /// -h, --help Print help information + /// --io-files Some help text + /// -V, --version Print version information + /// ``` + /// [`Arg::next_line_help(true)`]: Arg::next_line_help() + /// [`Arg::num_args`]: Arg::num_args() + /// [`Arg::action(ArgAction::Set)`]: Arg::action() + /// [`Arg::num_args(1..)`]: Arg::num_args() + #[must_use] + pub fn value_names(mut self, names: impl IntoIterator>) -> Self { + self.val_names = names.into_iter().map(|s| s.into()).collect(); + self + } + + /// Provide the shell a hint about how to complete this argument. + /// + /// See [`ValueHint`][crate::ValueHint] for more information. + /// + /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`]. + /// + /// For example, to take a username as argument: + /// + /// ``` + /// # use clap::{Arg, ValueHint}; + /// Arg::new("user") + /// .short('u') + /// .long("user") + /// .value_hint(ValueHint::Username); + /// ``` + /// + /// To take a full command line and its arguments (for example, when writing a command wrapper): + /// + /// ``` + /// # use clap::{Command, Arg, ValueHint, ArgAction}; + /// Command::new("prog") + /// .trailing_var_arg(true) + /// .arg( + /// Arg::new("command") + /// .action(ArgAction::Set) + /// .num_args(1..) + /// .value_hint(ValueHint::CommandWithArguments) + /// ); + /// ``` + #[must_use] + pub fn value_hint(mut self, value_hint: impl IntoResettable) -> Self { + self.value_hint = value_hint.into_resettable().into_option(); + self + } + + /// Match values against [`PossibleValuesParser`][crate::builder::PossibleValuesParser] without matching case. + /// + /// When other arguments are conditionally required based on the + /// value of a case-insensitive argument, the equality check done + /// by [`Arg::required_if_eq`], [`Arg::required_if_eq_any`], or + /// [`Arg::required_if_eq_all`] is case-insensitive. + /// + /// + /// **NOTE:** Setting this requires [taking values][Arg::num_args] + /// + /// **NOTE:** To do unicode case folding, enable the `unicode` feature flag. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("pv") + /// .arg(Arg::new("option") + /// .long("option") + /// .action(ArgAction::Set) + /// .ignore_case(true) + /// .value_parser(["test123"])) + /// .get_matches_from(vec![ + /// "pv", "--option", "TeSt123", + /// ]); + /// + /// assert!(m.get_one::("option").unwrap().eq_ignore_ascii_case("test123")); + /// ``` + /// + /// This setting also works when multiple values can be defined: + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("pv") + /// .arg(Arg::new("option") + /// .short('o') + /// .long("option") + /// .action(ArgAction::Set) + /// .ignore_case(true) + /// .num_args(1..) + /// .value_parser(["test123", "test321"])) + /// .get_matches_from(vec![ + /// "pv", "--option", "TeSt123", "teST123", "tESt321" + /// ]); + /// + /// let matched_vals = m.get_many::("option").unwrap().collect::>(); + /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]); + /// ``` + #[inline] + #[must_use] + pub fn ignore_case(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::IgnoreCase) + } else { + self.unset_setting(ArgSettings::IgnoreCase) + } + } + + /// Allows values which start with a leading hyphen (`-`) + /// + /// To limit values to just numbers, see + /// [`allow_negative_numbers`][Arg::allow_negative_numbers]. + /// + /// See also [`trailing_var_arg`][Arg::trailing_var_arg]. + /// + /// **NOTE:** Setting this requires [taking values][Arg::num_args] + /// + /// **WARNING:** Prior arguments with `allow_hyphen_values(true)` get precedence over known + /// flags but known flags get precedence over the next possible positional argument with + /// `allow_hyphen_values(true)`. When combined with [`Arg::num_args(..)`], + /// [`Arg::value_terminator`] is one way to ensure processing stops. + /// + /// **WARNING**: Take caution when using this setting combined with another argument using + /// [`Arg::num_args`], as this becomes ambiguous `$ prog --arg -- -- val`. All + /// three `--, --, val` will be values when the user may have thought the second `--` would + /// constitute the normal, "Only positional args follow" idiom. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("pat") + /// .action(ArgAction::Set) + /// .allow_hyphen_values(true) + /// .long("pattern")) + /// .get_matches_from(vec![ + /// "prog", "--pattern", "-file" + /// ]); + /// + /// assert_eq!(m.get_one::("pat").unwrap(), "-file"); + /// ``` + /// + /// Not setting `Arg::allow_hyphen_values(true)` and supplying a value which starts with a + /// hyphen is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("pat") + /// .action(ArgAction::Set) + /// .long("pattern")) + /// .try_get_matches_from(vec![ + /// "prog", "--pattern", "-file" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + /// [`Arg::num_args(1)`]: Arg::num_args() + #[inline] + #[must_use] + pub fn allow_hyphen_values(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::AllowHyphenValues) + } else { + self.unset_setting(ArgSettings::AllowHyphenValues) + } + } + + /// Allows negative numbers to pass as values. + /// + /// This is similar to [`Arg::allow_hyphen_values`] except that it only allows numbers, + /// all other undefined leading hyphens will fail to parse. + /// + /// **NOTE:** Setting this requires [taking values][Arg::num_args] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let res = Command::new("myprog") + /// .arg(Arg::new("num").allow_negative_numbers(true)) + /// .try_get_matches_from(vec![ + /// "myprog", "-20" + /// ]); + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// assert_eq!(m.get_one::("num").unwrap(), "-20"); + /// ``` + #[inline] + pub fn allow_negative_numbers(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::AllowNegativeNumbers) + } else { + self.unset_setting(ArgSettings::AllowNegativeNumbers) + } + } + + /// Requires that options use the `--option=val` syntax + /// + /// i.e. an equals between the option and associated value. + /// + /// **NOTE:** Setting this requires [taking values][Arg::num_args] + /// + /// # Examples + /// + /// Setting `require_equals` requires that the option have an equals sign between + /// it and the associated value. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .require_equals(true) + /// .long("config")) + /// .try_get_matches_from(vec![ + /// "prog", "--config=file.conf" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting `require_equals` and *not* supplying the equals will cause an + /// error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .require_equals(true) + /// .long("config")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals); + /// ``` + #[inline] + #[must_use] + pub fn require_equals(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::RequireEquals) + } else { + self.unset_setting(ArgSettings::RequireEquals) + } + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Arg::value_delimiter`") + )] + pub fn use_value_delimiter(mut self, yes: bool) -> Self { + if yes { + self.val_delim.get_or_insert(','); + } else { + self.val_delim = None; + } + self + } + + /// Allow grouping of multiple values via a delimiter. + /// + /// i.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`, + /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the + /// value delimiter for all arguments that accept values (options and positional arguments) + /// + /// **NOTE:** implicitly sets [`Arg::action(ArgAction::Set)`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("config") + /// .short('c') + /// .long("config") + /// .value_delimiter(',')) + /// .get_matches_from(vec![ + /// "prog", "--config=val1,val2,val3" + /// ]); + /// + /// assert_eq!(m.get_many::("config").unwrap().collect::>(), ["val1", "val2", "val3"]) + /// ``` + /// [`Arg::value_delimiter(',')`]: Arg::value_delimiter() + /// [`Arg::action(ArgAction::Set)`]: Arg::action() + #[inline] + #[must_use] + pub fn value_delimiter(mut self, d: impl IntoResettable) -> Self { + self.val_delim = d.into_resettable().into_option(); + self + } + + /// Sentinel to **stop** parsing multiple values of a given argument. + /// + /// By default when + /// one sets [`num_args(1..)`] on an argument, clap will continue parsing values for that + /// argument until it reaches another valid argument, or one of the other more specific settings + /// for multiple values is used (such as [`num_args`]). + /// + /// **NOTE:** This setting only applies to [options] and [positional arguments] + /// + /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one + /// of the values + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// Arg::new("vals") + /// .action(ArgAction::Set) + /// .num_args(1..) + /// .value_terminator(";") + /// # ; + /// ``` + /// + /// The following example uses two arguments, a sequence of commands, and the location in which + /// to perform them + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cmds") + /// .action(ArgAction::Set) + /// .num_args(1..) + /// .allow_hyphen_values(true) + /// .value_terminator(";")) + /// .arg(Arg::new("location")) + /// .get_matches_from(vec![ + /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap" + /// ]); + /// let cmds: Vec<_> = m.get_many::("cmds").unwrap().collect(); + /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]); + /// assert_eq!(m.get_one::("location").unwrap(), "/home/clap"); + /// ``` + /// [options]: Arg::action + /// [positional arguments]: Arg::index() + /// [`num_args(1..)`]: Arg::num_args() + /// [`num_args`]: Arg::num_args() + #[inline] + #[must_use] + pub fn value_terminator(mut self, term: impl IntoResettable) -> Self { + self.terminator = term.into_resettable().into_option(); + self + } + + /// Consume all following arguments. + /// + /// Do not be parse them individually, but rather pass them in entirety. + /// + /// It is worth noting that setting this requires all values to come after a `--` to indicate + /// they should all be captured. For example: + /// + /// ```text + /// --foo something -- -v -v -v -b -b -b --baz -q -u -x + /// ``` + /// + /// Will result in everything after `--` to be considered one raw argument. This behavior + /// may not be exactly what you are expecting and using [`crate::Command::trailing_var_arg`] + /// may be more appropriate. + /// + /// **NOTE:** Implicitly sets [`Arg::action(ArgAction::Set)`] [`Arg::num_args(1..)`], + /// [`Arg::allow_hyphen_values(true)`], and [`Arg::last(true)`] when set to `true`. + /// + /// [`Arg::action(ArgAction::Set)`]: Arg::action() + /// [`Arg::num_args(1..)`]: Arg::num_args() + /// [`Arg::allow_hyphen_values(true)`]: Arg::allow_hyphen_values() + /// [`Arg::last(true)`]: Arg::last() + #[inline] + #[must_use] + pub fn raw(mut self, yes: bool) -> Self { + if yes { + self.num_vals.get_or_insert_with(|| (1..).into()); + } + self.allow_hyphen_values(yes).last(yes) + } + + /// Value for the argument when not present. + /// + /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::contains_id`] will + /// still return `true`. If you wish to determine whether the argument was used at runtime or + /// not, consider [`ArgMatches::value_source`][crate::ArgMatches::value_source]. + /// + /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly + /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg + /// at runtime. `Arg::default_value_if` however only takes effect when the user has not provided + /// a value at runtime **and** these other conditions are met as well. If you have set + /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide this arg + /// at runtime, nor were the conditions met for `Arg::default_value_if`, the `Arg::default_value` + /// will be applied. + /// + /// **NOTE:** This implicitly sets [`Arg::action(ArgAction::Set)`]. + /// + /// # Examples + /// + /// First we use the default value without providing any value at runtime. + /// + /// ```rust + /// # use clap::{Command, Arg, parser::ValueSource}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .long("myopt") + /// .default_value("myval")) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.get_one::("opt").unwrap(), "myval"); + /// assert!(m.contains_id("opt")); + /// assert_eq!(m.value_source("opt"), Some(ValueSource::DefaultValue)); + /// ``` + /// + /// Next we provide a value at runtime to override the default. + /// + /// ```rust + /// # use clap::{Command, Arg, parser::ValueSource}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .long("myopt") + /// .default_value("myval")) + /// .get_matches_from(vec![ + /// "prog", "--myopt=non_default" + /// ]); + /// + /// assert_eq!(m.get_one::("opt").unwrap(), "non_default"); + /// assert!(m.contains_id("opt")); + /// assert_eq!(m.value_source("opt"), Some(ValueSource::CommandLine)); + /// ``` + /// [`Arg::action(ArgAction::Set)`]: Arg::action() + /// [`ArgMatches::contains_id`]: crate::ArgMatches::contains_id() + /// [`Arg::default_value_if`]: Arg::default_value_if() + #[inline] + #[must_use] + pub fn default_value(mut self, val: impl IntoResettable) -> Self { + if let Some(val) = val.into_resettable().into_option() { + self.default_values([val]) + } else { + self.default_vals.clear(); + self + } + } + + #[inline] + #[must_use] + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value`") + )] + pub fn default_value_os(self, val: impl Into) -> Self { + self.default_values([val]) + } + + /// Value for the argument when not present. + /// + /// See [`Arg::default_value`]. + /// + /// [`Arg::default_value`]: Arg::default_value() + #[inline] + #[must_use] + pub fn default_values(mut self, vals: impl IntoIterator>) -> Self { + self.default_vals = vals.into_iter().map(|s| s.into()).collect(); + self + } + + #[inline] + #[must_use] + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Arg::default_values`") + )] + pub fn default_values_os(self, vals: impl IntoIterator>) -> Self { + self.default_values(vals) + } + + /// Value for the argument when the flag is present but no value is specified. + /// + /// This configuration option is often used to give the user a shortcut and allow them to + /// efficiently specify an option argument without requiring an explicitly value. The `--color` + /// argument is a common example. By, supplying an default, such as `default_missing_value("always")`, + /// the user can quickly just add `--color` to the command line to produce the desired color output. + /// + /// **NOTE:** using this configuration option requires the use of the + /// [`.num_args(0..N)`][Arg::num_args] and the + /// [`.require_equals(true)`][Arg::require_equals] configuration option. These are required in + /// order to unambiguously determine what, if any, value was supplied for the argument. + /// + /// # Examples + /// + /// For POSIX style `--color`: + /// ```rust + /// # use clap::{Command, Arg, parser::ValueSource}; + /// fn cli() -> Command { + /// Command::new("prog") + /// .arg(Arg::new("color").long("color") + /// .value_name("WHEN") + /// .value_parser(["always", "auto", "never"]) + /// .default_value("auto") + /// .num_args(0..=1) + /// .require_equals(true) + /// .default_missing_value("always") + /// .help("Specify WHEN to colorize output.") + /// ) + /// } + /// + /// // first, we'll provide no arguments + /// let m = cli().get_matches_from(vec![ + /// "prog" + /// ]); + /// assert_eq!(m.get_one::("color").unwrap(), "auto"); + /// assert_eq!(m.value_source("color"), Some(ValueSource::DefaultValue)); + /// + /// // next, we'll provide a runtime value to override the default (as usually done). + /// let m = cli().get_matches_from(vec![ + /// "prog", "--color=never" + /// ]); + /// assert_eq!(m.get_one::("color").unwrap(), "never"); + /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine)); + /// + /// // finally, we will use the shortcut and only provide the argument without a value. + /// let m = cli().get_matches_from(vec![ + /// "prog", "--color" + /// ]); + /// assert_eq!(m.get_one::("color").unwrap(), "always"); + /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine)); + /// ``` + /// + /// For bool literals: + /// ```rust + /// # use clap::{Command, Arg, parser::ValueSource, value_parser}; + /// fn cli() -> Command { + /// Command::new("prog") + /// .arg(Arg::new("create").long("create") + /// .value_name("BOOL") + /// .value_parser(value_parser!(bool)) + /// .num_args(0..=1) + /// .require_equals(true) + /// .default_missing_value("true") + /// ) + /// } + /// + /// // first, we'll provide no arguments + /// let m = cli().get_matches_from(vec![ + /// "prog" + /// ]); + /// assert_eq!(m.get_one::("create").copied(), None); + /// + /// // next, we'll provide a runtime value to override the default (as usually done). + /// let m = cli().get_matches_from(vec![ + /// "prog", "--create=false" + /// ]); + /// assert_eq!(m.get_one::("create").copied(), Some(false)); + /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine)); + /// + /// // finally, we will use the shortcut and only provide the argument without a value. + /// let m = cli().get_matches_from(vec![ + /// "prog", "--create" + /// ]); + /// assert_eq!(m.get_one::("create").copied(), Some(true)); + /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine)); + /// ``` + /// + /// [`Arg::action(ArgAction::Set)`]: Arg::action() + /// [`Arg::default_value`]: Arg::default_value() + #[inline] + #[must_use] + pub fn default_missing_value(mut self, val: impl IntoResettable) -> Self { + if let Some(val) = val.into_resettable().into_option() { + self.default_missing_values_os([val]) + } else { + self.default_missing_vals.clear(); + self + } + } + + /// Value for the argument when the flag is present but no value is specified. + /// + /// See [`Arg::default_missing_value`]. + /// + /// [`Arg::default_missing_value`]: Arg::default_missing_value() + /// [`OsStr`]: std::ffi::OsStr + #[inline] + #[must_use] + pub fn default_missing_value_os(self, val: impl Into) -> Self { + self.default_missing_values_os([val]) + } + + /// Value for the argument when the flag is present but no value is specified. + /// + /// See [`Arg::default_missing_value`]. + /// + /// [`Arg::default_missing_value`]: Arg::default_missing_value() + #[inline] + #[must_use] + pub fn default_missing_values(self, vals: impl IntoIterator>) -> Self { + self.default_missing_values_os(vals) + } + + /// Value for the argument when the flag is present but no value is specified. + /// + /// See [`Arg::default_missing_values`]. + /// + /// [`Arg::default_missing_values`]: Arg::default_missing_values() + /// [`OsStr`]: std::ffi::OsStr + #[inline] + #[must_use] + pub fn default_missing_values_os( + mut self, + vals: impl IntoIterator>, + ) -> Self { + self.default_missing_vals = vals.into_iter().map(|s| s.into()).collect(); + self + } + + /// Read from `name` environment variable when argument is not present. + /// + /// If it is not present in the environment, then default + /// rules will apply. + /// + /// If user sets the argument in the environment: + /// - When [`Arg::action(ArgAction::Set)`] is not set, the flag is considered raised. + /// - When [`Arg::action(ArgAction::Set)`] is set, + /// [`ArgMatches::get_one`][crate::ArgMatches::get_one] will + /// return value of the environment variable. + /// + /// If user doesn't set the argument in the environment: + /// - When [`Arg::action(ArgAction::Set)`] is not set, the flag is considered off. + /// - When [`Arg::action(ArgAction::Set)`] is set, + /// [`ArgMatches::get_one`][crate::ArgMatches::get_one] will + /// return the default specified. + /// + /// # Examples + /// + /// In this example, we show the variable coming from the environment: + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg, ArgAction}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .env("MY_FLAG") + /// .action(ArgAction::Set)) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.get_one::("flag").unwrap(), "env"); + /// ``` + /// + /// In this example, because `prog` is a flag that accepts an optional, case-insensitive + /// boolean literal. + /// + /// Note that the value parser controls how flags are parsed. In this case we've selected + /// [`FalseyValueParser`][crate::builder::FalseyValueParser]. A `false` literal is `n`, `no`, + /// `f`, `false`, `off` or `0`. An absent environment variable will also be considered as + /// `false`. Anything else will considered as `true`. + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg, ArgAction}; + /// # use clap::builder::FalseyValueParser; + /// + /// env::set_var("TRUE_FLAG", "true"); + /// env::set_var("FALSE_FLAG", "0"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("true_flag") + /// .long("true_flag") + /// .action(ArgAction::SetTrue) + /// .value_parser(FalseyValueParser::new()) + /// .env("TRUE_FLAG")) + /// .arg(Arg::new("false_flag") + /// .long("false_flag") + /// .action(ArgAction::SetTrue) + /// .value_parser(FalseyValueParser::new()) + /// .env("FALSE_FLAG")) + /// .arg(Arg::new("absent_flag") + /// .long("absent_flag") + /// .action(ArgAction::SetTrue) + /// .value_parser(FalseyValueParser::new()) + /// .env("ABSENT_FLAG")) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(m.get_flag("true_flag")); + /// assert!(!m.get_flag("false_flag")); + /// assert!(!m.get_flag("absent_flag")); + /// ``` + /// + /// In this example, we show the variable coming from an option on the CLI: + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg, ArgAction}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .env("MY_FLAG") + /// .action(ArgAction::Set)) + /// .get_matches_from(vec![ + /// "prog", "--flag", "opt" + /// ]); + /// + /// assert_eq!(m.get_one::("flag").unwrap(), "opt"); + /// ``` + /// + /// In this example, we show the variable coming from the environment even with the + /// presence of a default: + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg, ArgAction}; + /// + /// env::set_var("MY_FLAG", "env"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .env("MY_FLAG") + /// .action(ArgAction::Set) + /// .default_value("default")) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.get_one::("flag").unwrap(), "env"); + /// ``` + /// + /// In this example, we show the use of multiple values in a single environment variable: + /// + /// ```rust + /// # use std::env; + /// # use clap::{Command, Arg, ArgAction}; + /// + /// env::set_var("MY_FLAG_MULTI", "env1,env2"); + /// + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .env("MY_FLAG_MULTI") + /// .action(ArgAction::Set) + /// .num_args(1..) + /// .value_delimiter(',')) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.get_many::("flag").unwrap().collect::>(), vec!["env1", "env2"]); + /// ``` + /// [`Arg::action(ArgAction::Set)`]: Arg::action() + /// [`Arg::value_delimiter(',')`]: Arg::value_delimiter() + #[cfg(feature = "env")] + #[inline] + #[must_use] + pub fn env(mut self, name: impl IntoResettable) -> Self { + if let Some(name) = name.into_resettable().into_option() { + let value = env::var_os(&name); + self.env = Some((name, value)); + } else { + self.env = None; + } + self + } + + #[cfg(feature = "env")] + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Arg::env`") + )] + pub fn env_os(self, name: impl Into) -> Self { + self.env(name) + } +} + +/// # Help +impl Arg { + /// Sets the description of the argument for short help (`-h`). + /// + /// Typically, this is a short (one line) description of the arg. + /// + /// If [`Arg::long_help`] is not specified, this message will be displayed for `--help`. + /// + /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise + /// + /// # Examples + /// + /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to + /// include a newline in the help text and have the following text be properly aligned with all + /// the other help text. + /// + /// Setting `help` displays a short message to the side of the argument when the user passes + /// `-h` or `--help` (by default). + /// + #[cfg_attr(not(feature = "help"), doc = " ```ignore")] + #[cfg_attr(feature = "help", doc = " ```")] + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```notrust + /// helptest + /// + /// Usage: helptest [OPTIONS] + /// + /// Options: + /// --config Some help text describing the --config arg + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + /// [`Arg::long_help`]: Arg::long_help() + #[inline] + #[must_use] + pub fn help(mut self, h: impl IntoResettable) -> Self { + self.help = h.into_resettable().into_option(); + self + } + + /// Sets the description of the argument for long help (`--help`). + /// + /// Typically this a more detailed (multi-line) message + /// that describes the arg. + /// + /// If [`Arg::help`] is not specified, this message will be displayed for `-h`. + /// + /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise + /// + /// # Examples + /// + /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to + /// include a newline in the help text and have the following text be properly aligned with all + /// the other help text. + /// + /// Setting `help` displays a short message to the side of the argument when the user passes + /// `-h` or `--help` (by default). + /// + #[cfg_attr(not(feature = "help"), doc = " ```ignore")] + #[cfg_attr(feature = "help", doc = " ```")] + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .long_help( + /// "The config file used by the myprog must be in JSON format + /// with only valid keys and may not contain other nonsense + /// that cannot be read by this program. Obviously I'm going on + /// and on, so I'll stop now.")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```text + /// prog + /// + /// Usage: prog [OPTIONS] + /// + /// Options: + /// --config + /// The config file used by the myprog must be in JSON format + /// with only valid keys and may not contain other nonsense + /// that cannot be read by this program. Obviously I'm going on + /// and on, so I'll stop now. + /// + /// -h, --help + /// Print help information + /// + /// -V, --version + /// Print version information + /// ``` + /// [`Arg::help`]: Arg::help() + #[inline] + #[must_use] + pub fn long_help(mut self, h: impl IntoResettable) -> Self { + self.long_help = h.into_resettable().into_option(); + self + } + + /// Allows custom ordering of args within the help message. + /// + /// Args with a lower value will be displayed first in the help message. This is helpful when + /// one would like to emphasise frequently used args, or prioritize those towards the top of + /// the list. Args with duplicate display orders will be displayed in alphabetical order. + /// + /// **NOTE:** The default is 999 for all arguments. + /// + /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in + /// [index] order. + /// + /// # Examples + /// + #[cfg_attr(not(feature = "help"), doc = " ```ignore")] + #[cfg_attr(feature = "help", doc = " ```")] + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("a") // Typically args are grouped alphabetically by name. + /// // Args without a display_order have a value of 999 and are + /// // displayed alphabetically with all other 999 valued args. + /// .long("long-option") + /// .short('o') + /// .action(ArgAction::Set) + /// .help("Some help and text")) + /// .arg(Arg::new("b") + /// .long("other-option") + /// .short('O') + /// .action(ArgAction::Set) + /// .display_order(1) // In order to force this arg to appear *first* + /// // all we have to do is give it a value lower than 999. + /// // Any other args with a value of 1 will be displayed + /// // alphabetically with this one...then 2 values, then 3, etc. + /// .help("I should be first!")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays the following help message + /// + /// ```text + /// cust-ord + /// + /// Usage: cust-ord [OPTIONS] + /// + /// Options: + /// -h, --help Print help information + /// -V, --version Print version information + /// -O, --other-option I should be first! + /// -o, --long-option Some help and text + /// ``` + /// [positional arguments]: Arg::index() + /// [index]: Arg::index() + #[inline] + #[must_use] + pub fn display_order(mut self, ord: impl IntoResettable) -> Self { + self.disp_ord = ord.into_resettable().into_option(); + self + } + + /// Override the [current] help section. + /// + /// [current]: crate::Command::next_help_heading + #[inline] + #[must_use] + pub fn help_heading(mut self, heading: impl IntoResettable) -> Self { + self.help_heading = Some(heading.into_resettable().into_option()); + self + } + + /// Render the [help][Arg::help] on the line after the argument. + /// + /// This can be helpful for arguments with very long or complex help messages. + /// This can also be helpful for arguments with very long flag names, or many/long value names. + /// + /// **NOTE:** To apply this setting to all arguments and subcommands, consider using + /// [`crate::Command::next_line_help`] + /// + /// # Examples + /// + #[cfg_attr(not(feature = "help"), doc = " ```ignore")] + #[cfg_attr(feature = "help", doc = " ```")] + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .long("long-option-flag") + /// .short('o') + /// .action(ArgAction::Set) + /// .next_line_help(true) + /// .value_names(["value1", "value2"]) + /// .help("Some really long help and complex\n\ + /// help that makes more sense to be\n\ + /// on a line after the option")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays the following help message + /// + /// ```text + /// nlh + /// + /// Usage: nlh [OPTIONS] + /// + /// Options: + /// -h, --help Print help information + /// -V, --version Print version information + /// -o, --long-option-flag + /// Some really long help and complex + /// help that makes more sense to be + /// on a line after the option + /// ``` + #[inline] + #[must_use] + pub fn next_line_help(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::NextLineHelp) + } else { + self.unset_setting(ArgSettings::NextLineHelp) + } + } + + /// Do not display the argument in help message. + /// + /// **NOTE:** This does **not** hide the argument from usage strings on error + /// + /// # Examples + /// + /// Setting `Hidden` will hide the argument when displaying help text + /// + #[cfg_attr(not(feature = "help"), doc = " ```ignore")] + #[cfg_attr(feature = "help", doc = " ```")] + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```text + /// helptest + /// + /// Usage: helptest [OPTIONS] + /// + /// Options: + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + #[inline] + #[must_use] + pub fn hide(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::Hidden) + } else { + self.unset_setting(ArgSettings::Hidden) + } + } + + /// Do not display the [possible values][crate::builder::ValueParser::possible_values] in the help message. + /// + /// This is useful for args with many values, or ones which are explained elsewhere in the + /// help text. + /// + /// **NOTE:** Setting this requires [taking values][Arg::num_args] + /// + /// To set this for all arguments, see + /// [`Command::hide_possible_values`][crate::Command::hide_possible_values]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .value_parser(["fast", "slow"]) + /// .action(ArgAction::Set) + /// .hide_possible_values(true)); + /// ``` + /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of + /// the help text would be omitted. + #[inline] + #[must_use] + pub fn hide_possible_values(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HidePossibleValues) + } else { + self.unset_setting(ArgSettings::HidePossibleValues) + } + } + + /// Do not display the default value of the argument in the help message. + /// + /// This is useful when default behavior of an arg is explained elsewhere in the help text. + /// + /// **NOTE:** Setting this requires [taking values][Arg::num_args] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("connect") + /// .arg(Arg::new("host") + /// .long("host") + /// .default_value("localhost") + /// .action(ArgAction::Set) + /// .hide_default_value(true)); + /// + /// ``` + /// + /// If we were to run the above program with `--help` the `[default: localhost]` portion of + /// the help text would be omitted. + #[inline] + #[must_use] + pub fn hide_default_value(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HideDefaultValue) + } else { + self.unset_setting(ArgSettings::HideDefaultValue) + } + } + + /// Do not display in help the environment variable name. + /// + /// This is useful when the variable option is explained elsewhere in the help text. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("mode") + /// .long("mode") + /// .env("MODE") + /// .action(ArgAction::Set) + /// .hide_env(true)); + /// ``` + /// + /// If we were to run the above program with `--help` the `[env: MODE]` portion of the help + /// text would be omitted. + #[cfg(feature = "env")] + #[inline] + #[must_use] + pub fn hide_env(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HideEnv) + } else { + self.unset_setting(ArgSettings::HideEnv) + } + } + + /// Do not display in help any values inside the associated ENV variables for the argument. + /// + /// This is useful when ENV vars contain sensitive values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("connect") + /// .arg(Arg::new("host") + /// .long("host") + /// .env("CONNECT") + /// .action(ArgAction::Set) + /// .hide_env_values(true)); + /// + /// ``` + /// + /// If we were to run the above program with `$ CONNECT=super_secret connect --help` the + /// `[default: CONNECT=super_secret]` portion of the help text would be omitted. + #[cfg(feature = "env")] + #[inline] + #[must_use] + pub fn hide_env_values(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HideEnvValues) + } else { + self.unset_setting(ArgSettings::HideEnvValues) + } + } + + /// Hides an argument from short help (`-h`). + /// + /// **NOTE:** This does **not** hide the argument from usage strings on error + /// + /// **NOTE:** Setting this option will cause next-line-help output style to be used + /// when long help (`--help`) is called. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Arg::new("debug") + /// .hide_short_help(true); + /// ``` + /// + /// Setting `hide_short_help(true)` will hide the argument when displaying short help text + /// + #[cfg_attr(not(feature = "help"), doc = " ```ignore")] + #[cfg_attr(feature = "help", doc = " ```")] + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide_short_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "-h" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```text + /// helptest + /// + /// Usage: helptest [OPTIONS] + /// + /// Options: + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + /// + /// However, when --help is called + /// + #[cfg_attr(not(feature = "help"), doc = " ```ignore")] + #[cfg_attr(feature = "help", doc = " ```")] + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide_short_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// Then the following would be displayed + /// + /// ```text + /// helptest + /// + /// Usage: helptest [OPTIONS] + /// + /// Options: + /// --config Some help text describing the --config arg + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + #[inline] + #[must_use] + pub fn hide_short_help(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HiddenShortHelp) + } else { + self.unset_setting(ArgSettings::HiddenShortHelp) + } + } + + /// Hides an argument from long help (`--help`). + /// + /// **NOTE:** This does **not** hide the argument from usage strings on error + /// + /// **NOTE:** Setting this option will cause next-line-help output style to be used + /// when long help (`--help`) is called. + /// + /// # Examples + /// + /// Setting `hide_long_help(true)` will hide the argument when displaying long help text + /// + #[cfg_attr(not(feature = "help"), doc = " ```ignore")] + #[cfg_attr(feature = "help", doc = " ```")] + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide_long_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "--help" + /// ]); + /// ``` + /// + /// The above example displays + /// + /// ```text + /// helptest + /// + /// Usage: helptest [OPTIONS] + /// + /// Options: + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + /// + /// However, when -h is called + /// + #[cfg_attr(not(feature = "help"), doc = " ```ignore")] + #[cfg_attr(feature = "help", doc = " ```")] + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .long("config") + /// .hide_long_help(true) + /// .help("Some help text describing the --config arg")) + /// .get_matches_from(vec![ + /// "prog", "-h" + /// ]); + /// ``` + /// + /// Then the following would be displayed + /// + /// ```text + /// helptest + /// + /// Usage: helptest [OPTIONS] + /// + /// OPTIONS: + /// --config Some help text describing the --config arg + /// -h, --help Print help information + /// -V, --version Print version information + /// ``` + #[inline] + #[must_use] + pub fn hide_long_help(self, yes: bool) -> Self { + if yes { + self.setting(ArgSettings::HiddenLongHelp) + } else { + self.unset_setting(ArgSettings::HiddenLongHelp) + } + } +} + +/// # Advanced Argument Relations +impl Arg { + /// The name of the [`ArgGroup`] the argument belongs to. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// Arg::new("debug") + /// .long("debug") + /// .action(ArgAction::SetTrue) + /// .group("mode") + /// # ; + /// ``` + /// + /// Multiple arguments can be a member of a single group and then the group checked as if it + /// was one of said arguments. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("debug") + /// .long("debug") + /// .action(ArgAction::SetTrue) + /// .group("mode")) + /// .arg(Arg::new("verbose") + /// .long("verbose") + /// .action(ArgAction::SetTrue) + /// .group("mode")) + /// .get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// assert!(m.contains_id("mode")); + /// ``` + /// + /// [`ArgGroup`]: crate::ArgGroup + #[must_use] + pub fn group(mut self, group_id: impl IntoResettable) -> Self { + if let Some(group_id) = group_id.into_resettable().into_option() { + self.groups.push(group_id); + } else { + self.groups.clear(); + } + self + } + + /// The names of [`ArgGroup`]'s the argument belongs to. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// Arg::new("debug") + /// .long("debug") + /// .action(ArgAction::SetTrue) + /// .groups(["mode", "verbosity"]) + /// # ; + /// ``` + /// + /// Arguments can be members of multiple groups and then the group checked as if it + /// was one of said arguments. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("debug") + /// .long("debug") + /// .action(ArgAction::SetTrue) + /// .groups(["mode", "verbosity"])) + /// .arg(Arg::new("verbose") + /// .long("verbose") + /// .action(ArgAction::SetTrue) + /// .groups(["mode", "verbosity"])) + /// .get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// assert!(m.contains_id("mode")); + /// assert!(m.contains_id("verbosity")); + /// ``` + /// + /// [`ArgGroup`]: crate::ArgGroup + #[must_use] + pub fn groups(mut self, group_ids: impl IntoIterator>) -> Self { + self.groups.extend(group_ids.into_iter().map(Into::into)); + self + } + + /// Specifies the value of the argument if `arg` has been used at runtime. + /// + /// If `default` is set to `None`, `default_value` will be removed. + /// + /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly + /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg + /// at runtime. This setting however only takes effect when the user has not provided a value at + /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value` + /// and `Arg::default_value_if`, and the user **did not** provide this arg at runtime, nor were + /// the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be applied. + /// + /// **NOTE:** This implicitly sets [`Arg::action(ArgAction::Set)`]. + /// + /// # Examples + /// + /// First we use the default value only if another arg is present at runtime. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// # use clap::builder::{ArgPredicate}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_if("flag", ArgPredicate::IsPresent, Some("default"))) + /// .get_matches_from(vec![ + /// "prog", "--flag" + /// ]); + /// + /// assert_eq!(m.get_one::("other").unwrap(), "default"); + /// ``` + /// + /// Next we run the same test, but without providing `--flag`. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_if("flag", "true", Some("default"))) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.get_one::("other"), None); + /// ``` + /// + /// Now lets only use the default value if `--opt` contains the value `special`. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .action(ArgAction::Set) + /// .long("opt")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_if("opt", "special", Some("default"))) + /// .get_matches_from(vec![ + /// "prog", "--opt", "special" + /// ]); + /// + /// assert_eq!(m.get_one::("other").unwrap(), "default"); + /// ``` + /// + /// We can run the same test and provide any value *other than* `special` and we won't get a + /// default value. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("opt") + /// .action(ArgAction::Set) + /// .long("opt")) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_if("opt", "special", Some("default"))) + /// .get_matches_from(vec![ + /// "prog", "--opt", "hahaha" + /// ]); + /// + /// assert_eq!(m.get_one::("other"), None); + /// ``` + /// + /// If we want to unset the default value for an Arg based on the presence or + /// value of some other Arg. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value("default") + /// .default_value_if("flag", "true", None)) + /// .get_matches_from(vec![ + /// "prog", "--flag" + /// ]); + /// + /// assert_eq!(m.get_one::("other"), None); + /// ``` + /// [`Arg::action(ArgAction::Set)`]: Arg::action() + /// [`Arg::default_value`]: Arg::default_value() + #[must_use] + pub fn default_value_if( + mut self, + arg_id: impl Into, + predicate: impl Into, + default: impl IntoResettable, + ) -> Self { + self.default_vals_ifs.push(( + arg_id.into(), + predicate.into(), + default.into_resettable().into_option(), + )); + self + } + + #[must_use] + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_if`") + )] + pub fn default_value_if_os( + self, + arg_id: impl Into, + predicate: impl Into, + default: impl IntoResettable, + ) -> Self { + self.default_value_if(arg_id, predicate, default) + } + + /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`]. + /// + /// The method takes a slice of tuples in the `(arg, predicate, default)` format. + /// + /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first + /// if multiple conditions are true, the first one found will be applied and the ultimate value. + /// + /// # Examples + /// + /// First we use the default value only if another arg is present at runtime. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("opt") + /// .long("opt") + /// .action(ArgAction::Set)) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_ifs([ + /// ("flag", "true", Some("default")), + /// ("opt", "channal", Some("chan")), + /// ])) + /// .get_matches_from(vec![ + /// "prog", "--opt", "channal" + /// ]); + /// + /// assert_eq!(m.get_one::("other").unwrap(), "chan"); + /// ``` + /// + /// Next we run the same test, but without providing `--flag`. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_ifs([ + /// ("flag", "true", Some("default")), + /// ("opt", "channal", Some("chan")), + /// ])) + /// .get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert_eq!(m.get_one::("other"), None); + /// ``` + /// + /// We can also see that these values are applied in order, and if more than one condition is + /// true, only the first evaluated "wins" + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// # use clap::builder::ArgPredicate; + /// let m = Command::new("prog") + /// .arg(Arg::new("flag") + /// .long("flag") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("opt") + /// .long("opt") + /// .action(ArgAction::Set)) + /// .arg(Arg::new("other") + /// .long("other") + /// .default_value_ifs([ + /// ("flag", ArgPredicate::IsPresent, Some("default")), + /// ("opt", ArgPredicate::Equals("channal".into()), Some("chan")), + /// ])) + /// .get_matches_from(vec![ + /// "prog", "--opt", "channal", "--flag" + /// ]); + /// + /// assert_eq!(m.get_one::("other").unwrap(), "default"); + /// ``` + /// [`Arg::action(ArgAction::Set)`]: Arg::action() + /// [`Arg::default_value_if`]: Arg::default_value_if() + #[must_use] + pub fn default_value_ifs( + mut self, + ifs: impl IntoIterator< + Item = ( + impl Into, + impl Into, + impl IntoResettable, + ), + >, + ) -> Self { + for (arg, predicate, default) in ifs { + self = self.default_value_if(arg, predicate, default); + } + self + } + + #[must_use] + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_ifs`") + )] + pub fn default_value_ifs_os( + self, + ifs: impl IntoIterator< + Item = ( + impl Into, + impl Into, + impl IntoResettable, + ), + >, + ) -> Self { + self.default_value_ifs(ifs) + } + + /// Set this arg as [required] as long as the specified argument is not present at runtime. + /// + /// **Pro Tip:** Using `Arg::required_unless_present` implies [`Arg::required`] and is therefore not + /// mandatory to also set. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_unless_present("debug") + /// # ; + /// ``` + /// + /// In the following example, the required argument is *not* provided, + /// but it's not an error because the `unless` arg has been supplied. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present("dbg") + /// .action(ArgAction::Set) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug") + /// .action(ArgAction::SetTrue)) + /// .try_get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting `Arg::required_unless_present(name)` and *not* supplying `name` or this arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present("dbg") + /// .action(ArgAction::Set) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug")) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required]: Arg::required() + #[must_use] + pub fn required_unless_present(mut self, arg_id: impl IntoResettable) -> Self { + if let Some(arg_id) = arg_id.into_resettable().into_option() { + self.r_unless.push(arg_id); + } else { + self.r_unless.clear(); + } + self + } + + /// Sets this arg as [required] unless *all* of the specified arguments are present at runtime. + /// + /// In other words, parsing will succeed only if user either + /// * supplies the `self` arg. + /// * supplies *all* of the `names` arguments. + /// + /// **NOTE:** If you wish for this argument to only be required unless *any of* these args are + /// present see [`Arg::required_unless_present_any`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_unless_present_all(["cfg", "dbg"]) + /// # ; + /// ``` + /// + /// In the following example, the required argument is *not* provided, but it's not an error + /// because *all* of the `names` args have been supplied. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present_all(["dbg", "infile"]) + /// .action(ArgAction::Set) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("infile") + /// .short('i') + /// .action(ArgAction::Set)) + /// .try_get_matches_from(vec![ + /// "prog", "--debug", "-i", "file" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting [`Arg::required_unless_present_all(names)`] and *not* supplying + /// either *all* of `unless` args or the `self` arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present_all(["dbg", "infile"]) + /// .action(ArgAction::Set) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("infile") + /// .short('i') + /// .action(ArgAction::Set)) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required]: Arg::required() + /// [`Arg::required_unless_present_any`]: Arg::required_unless_present_any() + /// [`Arg::required_unless_present_all(names)`]: Arg::required_unless_present_all() + #[must_use] + pub fn required_unless_present_all( + mut self, + names: impl IntoIterator>, + ) -> Self { + self.r_unless_all.extend(names.into_iter().map(Into::into)); + self + } + + /// Sets this arg as [required] unless *any* of the specified arguments are present at runtime. + /// + /// In other words, parsing will succeed only if user either + /// * supplies the `self` arg. + /// * supplies *one or more* of the `unless` arguments. + /// + /// **NOTE:** If you wish for this argument to be required unless *all of* these args are + /// present see [`Arg::required_unless_present_all`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_unless_present_any(["cfg", "dbg"]) + /// # ; + /// ``` + /// + /// Setting [`Arg::required_unless_present_any(names)`] requires that the argument be used at runtime + /// *unless* *at least one of* the args in `names` are present. In the following example, the + /// required argument is *not* provided, but it's not an error because one the `unless` args + /// have been supplied. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present_any(["dbg", "infile"]) + /// .action(ArgAction::Set) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("infile") + /// .short('i') + /// .action(ArgAction::Set)) + /// .try_get_matches_from(vec![ + /// "prog", "--debug" + /// ]); + /// + /// assert!(res.is_ok()); + /// ``` + /// + /// Setting [`Arg::required_unless_present_any(names)`] and *not* supplying *at least one of* `names` + /// or this arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_unless_present_any(["dbg", "infile"]) + /// .action(ArgAction::Set) + /// .long("config")) + /// .arg(Arg::new("dbg") + /// .long("debug") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("infile") + /// .short('i') + /// .action(ArgAction::Set)) + /// .try_get_matches_from(vec![ + /// "prog" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required]: Arg::required() + /// [`Arg::required_unless_present_any(names)`]: Arg::required_unless_present_any() + /// [`Arg::required_unless_present_all`]: Arg::required_unless_present_all() + #[must_use] + pub fn required_unless_present_any( + mut self, + names: impl IntoIterator>, + ) -> Self { + self.r_unless.extend(names.into_iter().map(Into::into)); + self + } + + /// This argument is [required] only if the specified `arg` is present at runtime and its value + /// equals `val`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_if_eq("other_arg", "value") + /// # ; + /// ``` + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .required_if_eq("other", "special") + /// .long("config")) + /// .arg(Arg::new("other") + /// .long("other") + /// .action(ArgAction::Set)) + /// .try_get_matches_from(vec![ + /// "prog", "--other", "not-special" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required + /// + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .required_if_eq("other", "special") + /// .long("config")) + /// .arg(Arg::new("other") + /// .long("other") + /// .action(ArgAction::Set)) + /// .try_get_matches_from(vec![ + /// "prog", "--other", "special" + /// ]); + /// + /// // We did use --other=special so "cfg" had become required but was missing. + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .required_if_eq("other", "special") + /// .long("config")) + /// .arg(Arg::new("other") + /// .long("other") + /// .action(ArgAction::Set)) + /// .try_get_matches_from(vec![ + /// "prog", "--other", "SPECIAL" + /// ]); + /// + /// // By default, the comparison is case-sensitive, so "cfg" wasn't required + /// assert!(res.is_ok()); + /// + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .required_if_eq("other", "special") + /// .long("config")) + /// .arg(Arg::new("other") + /// .long("other") + /// .ignore_case(true) + /// .action(ArgAction::Set)) + /// .try_get_matches_from(vec![ + /// "prog", "--other", "SPECIAL" + /// ]); + /// + /// // However, case-insensitive comparisons can be enabled. This typically occurs when using Arg::possible_values(). + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [required]: Arg::required() + #[must_use] + pub fn required_if_eq(mut self, arg_id: impl Into, val: impl Into) -> Self { + self.r_ifs.push((arg_id.into(), val.into())); + self + } + + /// Specify this argument is [required] based on multiple conditions. + /// + /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become + /// valid if one of the specified `arg`'s value equals its corresponding `val`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_if_eq_any([ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// # ; + /// ``` + /// + /// Setting `Arg::required_if_eq_any([(arg, val)])` makes this arg required if any of the `arg`s + /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is + /// anything other than `val`, this argument isn't required. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_if_eq_any([ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .action(ArgAction::Set) + /// .long("config")) + /// .arg(Arg::new("extra") + /// .action(ArgAction::Set) + /// .long("extra")) + /// .arg(Arg::new("option") + /// .action(ArgAction::Set) + /// .long("option")) + /// .try_get_matches_from(vec![ + /// "prog", "--option", "other" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required + /// ``` + /// + /// Setting `Arg::required_if_eq_any([(arg, val)])` and having any of the `arg`s used with its + /// value of `val` but *not* using this arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_if_eq_any([ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .action(ArgAction::Set) + /// .long("config")) + /// .arg(Arg::new("extra") + /// .action(ArgAction::Set) + /// .long("extra")) + /// .arg(Arg::new("option") + /// .action(ArgAction::Set) + /// .long("option")) + /// .try_get_matches_from(vec![ + /// "prog", "--option", "spec" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [required]: Arg::required() + #[must_use] + pub fn required_if_eq_any( + mut self, + ifs: impl IntoIterator, impl Into)>, + ) -> Self { + self.r_ifs + .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into()))); + self + } + + /// Specify this argument is [required] based on multiple conditions. + /// + /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become + /// valid if every one of the specified `arg`'s value equals its corresponding `val`. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .required_if_eq_all([ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// # ; + /// ``` + /// + /// Setting `Arg::required_if_eq_all([(arg, val)])` makes this arg required if all of the `arg`s + /// are used at runtime and every value is equal to its corresponding `val`. If the `arg`'s value is + /// anything other than `val`, this argument isn't required. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_if_eq_all([ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .action(ArgAction::Set) + /// .long("config")) + /// .arg(Arg::new("extra") + /// .action(ArgAction::Set) + /// .long("extra")) + /// .arg(Arg::new("option") + /// .action(ArgAction::Set) + /// .long("option")) + /// .try_get_matches_from(vec![ + /// "prog", "--option", "spec" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required + /// ``` + /// + /// Setting `Arg::required_if_eq_all([(arg, val)])` and having all of the `arg`s used with its + /// value of `val` but *not* using this arg is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .required_if_eq_all([ + /// ("extra", "val"), + /// ("option", "spec") + /// ]) + /// .action(ArgAction::Set) + /// .long("config")) + /// .arg(Arg::new("extra") + /// .action(ArgAction::Set) + /// .long("extra")) + /// .arg(Arg::new("option") + /// .action(ArgAction::Set) + /// .long("option")) + /// .try_get_matches_from(vec![ + /// "prog", "--extra", "val", "--option", "spec" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required]: Arg::required() + #[must_use] + pub fn required_if_eq_all( + mut self, + ifs: impl IntoIterator, impl Into)>, + ) -> Self { + self.r_ifs_all + .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into()))); + self + } + + /// Require another argument if this arg matches the [`ArgPredicate`] + /// + /// This method takes `value, another_arg` pair. At runtime, clap will check + /// if this arg (`self`) matches the [`ArgPredicate`]. + /// If it does, `another_arg` will be marked as required. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .requires_if("val", "arg") + /// # ; + /// ``` + /// + /// Setting `Arg::requires_if(val, arg)` requires that the `arg` be used at runtime if the + /// defining argument's value is equal to `val`. If the defining argument is anything other than + /// `val`, the other argument isn't required. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .requires_if("my.cfg", "other") + /// .long("config")) + /// .arg(Arg::new("other")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "some.cfg" + /// ]); + /// + /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required + /// ``` + /// + /// Setting `Arg::requires_if(val, arg)` and setting the value to `val` but *not* supplying + /// `arg` is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .requires_if("my.cfg", "input") + /// .long("config")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "my.cfg" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [override]: Arg::overrides_with() + #[must_use] + pub fn requires_if(mut self, val: impl Into, arg_id: impl Into) -> Self { + self.requires.push((val.into(), arg_id.into())); + self + } + + /// Allows multiple conditional requirements. + /// + /// The requirement will only become valid if this arg's value matches the + /// [`ArgPredicate`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .requires_ifs([ + /// ("val", "arg"), + /// ("other_val", "arg2"), + /// ]) + /// # ; + /// ``` + /// + /// Setting `Arg::requires_ifs(["val", "arg"])` requires that the `arg` be used at runtime if the + /// defining argument's value is equal to `val`. If the defining argument's value is anything other + /// than `val`, `arg` isn't required. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .requires_ifs([ + /// ("special.conf", "opt"), + /// ("other.conf", "other"), + /// ]) + /// .long("config")) + /// .arg(Arg::new("opt") + /// .long("option") + /// .action(ArgAction::Set)) + /// .arg(Arg::new("other")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "special.conf" + /// ]); + /// + /// assert!(res.is_err()); // We used --config=special.conf so --option is required + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// + /// Setting `Arg::requires_ifs` with [`ArgPredicate::IsPresent`] and *not* supplying all the + /// arguments is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction, builder::ArgPredicate}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .requires_ifs([ + /// (ArgPredicate::IsPresent, "input"), + /// (ArgPredicate::IsPresent, "output"), + /// ]) + /// .long("config")) + /// .arg(Arg::new("input")) + /// .arg(Arg::new("output")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf", "in.txt" + /// ]); + /// + /// assert!(res.is_err()); + /// // We didn't use output + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// + /// [`Arg::requires(name)`]: Arg::requires() + /// [Conflicting]: Arg::conflicts_with() + /// [override]: Arg::overrides_with() + #[must_use] + pub fn requires_ifs( + mut self, + ifs: impl IntoIterator, impl Into)>, + ) -> Self { + self.requires + .extend(ifs.into_iter().map(|(val, arg)| (val.into(), arg.into()))); + self + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Arg::requires_ifs`") + )] + pub fn requires_all(self, ids: impl IntoIterator>) -> Self { + self.requires_ifs(ids.into_iter().map(|id| (ArgPredicate::IsPresent, id))) + } + + /// This argument is mutually exclusive with the specified argument. + /// + /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules + /// only need to be set for one of the two arguments, they do not need to be set for each. + /// + /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments + /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not + /// need to also do B.conflicts_with(A)) + /// + /// **NOTE:** [`Arg::conflicts_with_all(names)`] allows specifying an argument which conflicts with more than one argument. + /// + /// **NOTE** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. + /// + /// **NOTE:** All arguments implicitly conflict with themselves. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .conflicts_with("debug") + /// # ; + /// ``` + /// + /// Setting conflicting argument, and having both arguments present at runtime is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .conflicts_with("debug") + /// .long("config")) + /// .arg(Arg::new("debug") + /// .long("debug") + /// .action(ArgAction::SetTrue)) + /// .try_get_matches_from(vec![ + /// "prog", "--debug", "--config", "file.conf" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); + /// ``` + /// + /// [`Arg::conflicts_with_all(names)`]: Arg::conflicts_with_all() + /// [`Arg::exclusive(true)`]: Arg::exclusive() + #[must_use] + pub fn conflicts_with(mut self, arg_id: impl IntoResettable) -> Self { + if let Some(arg_id) = arg_id.into_resettable().into_option() { + self.blacklist.push(arg_id); + } else { + self.blacklist.clear(); + } + self + } + + /// This argument is mutually exclusive with the specified arguments. + /// + /// See [`Arg::conflicts_with`]. + /// + /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules + /// only need to be set for one of the two arguments, they do not need to be set for each. + /// + /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments + /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need + /// need to also do B.conflicts_with(A)) + /// + /// **NOTE:** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// Arg::new("config") + /// .conflicts_with_all(["debug", "input"]) + /// # ; + /// ``` + /// + /// Setting conflicting argument, and having any of the arguments present at runtime with a + /// conflicting argument is an error. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind, ArgAction}; + /// let res = Command::new("prog") + /// .arg(Arg::new("cfg") + /// .action(ArgAction::Set) + /// .conflicts_with_all(["debug", "input"]) + /// .long("config")) + /// .arg(Arg::new("debug") + /// .long("debug")) + /// .arg(Arg::new("input")) + /// .try_get_matches_from(vec![ + /// "prog", "--config", "file.conf", "file.txt" + /// ]); + /// + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict); + /// ``` + /// [`Arg::conflicts_with`]: Arg::conflicts_with() + /// [`Arg::exclusive(true)`]: Arg::exclusive() + #[must_use] + pub fn conflicts_with_all(mut self, names: impl IntoIterator>) -> Self { + self.blacklist.extend(names.into_iter().map(Into::into)); + self + } + + /// Sets an overridable argument. + /// + /// i.e. this argument and the following argument + /// will override each other in POSIX style (whichever argument was specified at runtime + /// **last** "wins") + /// + /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any + /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed + /// + /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let m = Command::new("prog") + /// .arg(arg!(-f --flag "some flag") + /// .conflicts_with("debug")) + /// .arg(arg!(-d --debug "other flag")) + /// .arg(arg!(-c --color "third flag") + /// .overrides_with("flag")) + /// .get_matches_from(vec![ + /// "prog", "-f", "-d", "-c"]); + /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color + /// + /// assert!(m.get_flag("color")); + /// assert!(m.get_flag("debug")); // even though flag conflicts with debug, it's as if flag + /// // was never used because it was overridden with color + /// assert!(!m.get_flag("flag")); + /// ``` + #[must_use] + pub fn overrides_with(mut self, arg_id: impl IntoResettable) -> Self { + if let Some(arg_id) = arg_id.into_resettable().into_option() { + self.overrides.push(arg_id); + } else { + self.overrides.clear(); + } + self + } + + /// Sets multiple mutually overridable arguments by name. + /// + /// i.e. this argument and the following argument will override each other in POSIX style + /// (whichever argument was specified at runtime **last** "wins") + /// + /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any + /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed + /// + /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with_all`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let m = Command::new("prog") + /// .arg(arg!(-f --flag "some flag") + /// .conflicts_with("color")) + /// .arg(arg!(-d --debug "other flag")) + /// .arg(arg!(-c --color "third flag") + /// .overrides_with_all(["flag", "debug"])) + /// .get_matches_from(vec![ + /// "prog", "-f", "-d", "-c"]); + /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color + /// + /// assert!(m.get_flag("color")); // even though flag conflicts with color, it's as if flag + /// // and debug were never used because they were overridden + /// // with color + /// assert!(!m.get_flag("debug")); + /// assert!(!m.get_flag("flag")); + /// ``` + #[must_use] + pub fn overrides_with_all(mut self, names: impl IntoIterator>) -> Self { + self.overrides.extend(names.into_iter().map(Into::into)); + self + } +} + +/// # Reflection +impl Arg { + /// Get the name of the argument + #[inline] + pub fn get_id(&self) -> &Id { + &self.id + } + + /// Get the help specified for this argument, if any + #[inline] + pub fn get_help(&self) -> Option<&StyledStr> { + self.help.as_ref() + } + + /// Get the long help specified for this argument, if any + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// let arg = Arg::new("foo").long_help("long help"); + /// assert_eq!(Some("long help".to_owned()), arg.get_long_help().map(|s| s.to_string())); + /// ``` + /// + #[inline] + pub fn get_long_help(&self) -> Option<&StyledStr> { + self.long_help.as_ref() + } + + /// Get the help heading specified for this argument, if any + #[inline] + pub fn get_help_heading(&self) -> Option<&str> { + self.help_heading + .as_ref() + .map(|s| s.as_deref()) + .unwrap_or_default() + } + + /// Get the short option name for this argument, if any + #[inline] + pub fn get_short(&self) -> Option { + self.short + } + + /// Get visible short aliases for this argument, if any + #[inline] + pub fn get_visible_short_aliases(&self) -> Option> { + if self.short_aliases.is_empty() { + None + } else { + Some( + self.short_aliases + .iter() + .filter_map(|(c, v)| if *v { Some(c) } else { None }) + .copied() + .collect(), + ) + } + } + + /// Get *all* short aliases for this argument, if any, both visible and hidden. + #[inline] + pub fn get_all_short_aliases(&self) -> Option> { + if self.short_aliases.is_empty() { + None + } else { + Some(self.short_aliases.iter().map(|(s, _)| s).copied().collect()) + } + } + + /// Get the short option name and its visible aliases, if any + #[inline] + pub fn get_short_and_visible_aliases(&self) -> Option> { + let mut shorts = match self.short { + Some(short) => vec![short], + None => return None, + }; + if let Some(aliases) = self.get_visible_short_aliases() { + shorts.extend(aliases); + } + Some(shorts) + } + + /// Get the long option name for this argument, if any + #[inline] + pub fn get_long(&self) -> Option<&str> { + self.long.as_deref() + } + + /// Get visible aliases for this argument, if any + #[inline] + pub fn get_visible_aliases(&self) -> Option> { + if self.aliases.is_empty() { + None + } else { + Some( + self.aliases + .iter() + .filter_map(|(s, v)| if *v { Some(s.as_str()) } else { None }) + .collect(), + ) + } + } + + /// Get *all* aliases for this argument, if any, both visible and hidden. + #[inline] + pub fn get_all_aliases(&self) -> Option> { + if self.aliases.is_empty() { + None + } else { + Some(self.aliases.iter().map(|(s, _)| s.as_str()).collect()) + } + } + + /// Get the long option name and its visible aliases, if any + #[inline] + pub fn get_long_and_visible_aliases(&self) -> Option> { + let mut longs = match self.get_long() { + Some(long) => vec![long], + None => return None, + }; + if let Some(aliases) = self.get_visible_aliases() { + longs.extend(aliases); + } + Some(longs) + } + + /// Get the names of possible values for this argument. Only useful for user + /// facing applications, such as building help messages or man files + pub fn get_possible_values(&self) -> Vec { + if !self.is_takes_value_set() { + vec![] + } else { + self.get_value_parser() + .possible_values() + .map(|pvs| pvs.collect()) + .unwrap_or_default() + } + } + + /// Get the names of values for this argument. + #[inline] + pub fn get_value_names(&self) -> Option<&[Str]> { + if self.val_names.is_empty() { + None + } else { + Some(&self.val_names) + } + } + + /// Get the number of values for this argument. + #[inline] + pub fn get_num_args(&self) -> Option { + self.num_vals + } + + #[inline] + pub(crate) fn get_min_vals(&self) -> usize { + self.get_num_args().expect(INTERNAL_ERROR_MSG).min_values() + } + + /// Get the delimiter between multiple values + #[inline] + pub fn get_value_delimiter(&self) -> Option { + self.val_delim + } + + /// Get the value terminator for this argument. The value_terminator is a value + /// that terminates parsing of multi-valued arguments. + #[inline] + pub fn get_value_terminator(&self) -> Option<&Str> { + self.terminator.as_ref() + } + + /// Get the index of this argument, if any + #[inline] + pub fn get_index(&self) -> Option { + self.index + } + + /// Get the value hint of this argument + pub fn get_value_hint(&self) -> ValueHint { + self.value_hint.unwrap_or_else(|| { + if self.is_takes_value_set() { + let type_id = self.get_value_parser().type_id(); + if type_id == crate::parser::AnyValueId::of::() { + ValueHint::AnyPath + } else { + ValueHint::default() + } + } else { + ValueHint::default() + } + }) + } + + /// Get the environment variable name specified for this argument, if any + /// + /// # Examples + /// + /// ```rust + /// # use std::ffi::OsStr; + /// # use clap::Arg; + /// let arg = Arg::new("foo").env("ENVIRONMENT"); + /// assert_eq!(arg.get_env(), Some(OsStr::new("ENVIRONMENT"))); + /// ``` + #[cfg(feature = "env")] + pub fn get_env(&self) -> Option<&std::ffi::OsStr> { + self.env.as_ref().map(|x| x.0.as_os_str()) + } + + /// Get the default values specified for this argument, if any + /// + /// # Examples + /// + /// ```rust + /// # use clap::Arg; + /// let arg = Arg::new("foo").default_value("default value"); + /// assert_eq!(arg.get_default_values(), &["default value"]); + /// ``` + pub fn get_default_values(&self) -> &[OsStr] { + &self.default_vals + } + + /// Checks whether this argument is a positional or not. + /// + /// # Examples + /// + /// ``` + /// # use clap::Arg; + /// let arg = Arg::new("foo"); + /// assert_eq!(arg.is_positional(), true); + /// + /// let arg = Arg::new("foo").long("foo"); + /// assert_eq!(arg.is_positional(), false); + /// ``` + pub fn is_positional(&self) -> bool { + self.get_long().is_none() && self.get_short().is_none() + } + + /// Reports whether [`Arg::required`] is set + pub fn is_required_set(&self) -> bool { + self.is_set(ArgSettings::Required) + } + + pub(crate) fn is_multiple_values_set(&self) -> bool { + self.get_num_args().unwrap_or_default().is_multiple() + } + + pub(crate) fn is_takes_value_set(&self) -> bool { + self.get_action().takes_values() + } + + /// Report whether [`Arg::allow_hyphen_values`] is set + pub fn is_allow_hyphen_values_set(&self) -> bool { + self.is_set(ArgSettings::AllowHyphenValues) + } + + /// Report whether [`Arg::allow_negative_numbers`] is set + pub fn is_allow_negative_numbers_set(&self) -> bool { + self.is_set(ArgSettings::AllowNegativeNumbers) + } + + /// Behavior when parsing the argument + pub fn get_action(&self) -> &super::ArgAction { + const DEFAULT: super::ArgAction = super::ArgAction::Set; + self.action.as_ref().unwrap_or(&DEFAULT) + } + + /// Configured parser for argument values + /// + /// # Example + /// + /// ```rust + /// let cmd = clap::Command::new("raw") + /// .arg( + /// clap::Arg::new("port") + /// .value_parser(clap::value_parser!(usize)) + /// ); + /// let value_parser = cmd.get_arguments() + /// .find(|a| a.get_id() == "port").unwrap() + /// .get_value_parser(); + /// println!("{:?}", value_parser); + /// ``` + pub fn get_value_parser(&self) -> &super::ValueParser { + if let Some(value_parser) = self.value_parser.as_ref() { + value_parser + } else { + static DEFAULT: super::ValueParser = super::ValueParser::string(); + &DEFAULT + } + } + + /// Report whether [`Arg::global`] is set + pub fn is_global_set(&self) -> bool { + self.is_set(ArgSettings::Global) + } + + /// Report whether [`Arg::next_line_help`] is set + pub fn is_next_line_help_set(&self) -> bool { + self.is_set(ArgSettings::NextLineHelp) + } + + /// Report whether [`Arg::hide`] is set + pub fn is_hide_set(&self) -> bool { + self.is_set(ArgSettings::Hidden) + } + + /// Report whether [`Arg::hide_default_value`] is set + pub fn is_hide_default_value_set(&self) -> bool { + self.is_set(ArgSettings::HideDefaultValue) + } + + /// Report whether [`Arg::hide_possible_values`] is set + pub fn is_hide_possible_values_set(&self) -> bool { + self.is_set(ArgSettings::HidePossibleValues) + } + + /// Report whether [`Arg::hide_env`] is set + #[cfg(feature = "env")] + pub fn is_hide_env_set(&self) -> bool { + self.is_set(ArgSettings::HideEnv) + } + + /// Report whether [`Arg::hide_env_values`] is set + #[cfg(feature = "env")] + pub fn is_hide_env_values_set(&self) -> bool { + self.is_set(ArgSettings::HideEnvValues) + } + + /// Report whether [`Arg::hide_short_help`] is set + pub fn is_hide_short_help_set(&self) -> bool { + self.is_set(ArgSettings::HiddenShortHelp) + } + + /// Report whether [`Arg::hide_long_help`] is set + pub fn is_hide_long_help_set(&self) -> bool { + self.is_set(ArgSettings::HiddenLongHelp) + } + + /// Report whether [`Arg::require_equals`] is set + pub fn is_require_equals_set(&self) -> bool { + self.is_set(ArgSettings::RequireEquals) + } + + /// Reports whether [`Arg::exclusive`] is set + pub fn is_exclusive_set(&self) -> bool { + self.is_set(ArgSettings::Exclusive) + } + + /// Report whether [`Arg::trailing_var_arg`] is set + pub fn is_trailing_var_arg_set(&self) -> bool { + self.is_set(ArgSettings::TrailingVarArg) + } + + /// Reports whether [`Arg::last`] is set + pub fn is_last_set(&self) -> bool { + self.is_set(ArgSettings::Last) + } + + /// Reports whether [`Arg::ignore_case`] is set + pub fn is_ignore_case_set(&self) -> bool { + self.is_set(ArgSettings::IgnoreCase) + } +} + +/// # Internally used only +impl Arg { + pub(crate) fn _build(&mut self) { + if self.action.is_none() { + if self.num_vals == Some(ValueRange::EMPTY) { + let action = super::ArgAction::SetTrue; + self.action = Some(action); + } else { + let action = + if self.is_positional() && self.num_vals.unwrap_or_default().is_unbounded() { + // Allow collecting arguments interleaved with flags + // + // Bounded values are probably a group and the user should explicitly opt-in to + // Append + super::ArgAction::Append + } else { + super::ArgAction::Set + }; + self.action = Some(action); + } + } + if let Some(action) = self.action.as_ref() { + if let Some(default_value) = action.default_value() { + if self.default_vals.is_empty() { + self.default_vals = vec![default_value.into()]; + } + } + if let Some(default_value) = action.default_missing_value() { + if self.default_missing_vals.is_empty() { + self.default_missing_vals = vec![default_value.into()]; + } + } + } + + if self.value_parser.is_none() { + if let Some(default) = self.action.as_ref().and_then(|a| a.default_value_parser()) { + self.value_parser = Some(default); + } else { + self.value_parser = Some(super::ValueParser::string()); + } + } + + let val_names_len = self.val_names.len(); + if val_names_len > 1 { + self.num_vals.get_or_insert(val_names_len.into()); + } else { + let nargs = if self.get_action().takes_values() { + ValueRange::SINGLE + } else { + ValueRange::EMPTY + }; + self.num_vals.get_or_insert(nargs); + } + } + + // Used for positionals when printing + pub(crate) fn name_no_brackets(&self) -> String { + debug!("Arg::name_no_brackets:{}", self.get_id()); + let delim = " "; + if !self.val_names.is_empty() { + debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names); + + if self.val_names.len() > 1 { + self.val_names + .iter() + .map(|n| format!("<{}>", n)) + .collect::>() + .join(delim) + } else { + self.val_names + .first() + .expect(INTERNAL_ERROR_MSG) + .as_str() + .to_owned() + } + } else { + debug!("Arg::name_no_brackets: just name"); + self.get_id().as_str().to_owned() + } + } + + pub(crate) fn stylized(&self, required: Option) -> StyledStr { + let mut styled = StyledStr::new(); + // Write the name such --long or -l + if let Some(l) = self.get_long() { + styled.literal("--"); + styled.literal(l); + } else if let Some(s) = self.get_short() { + styled.literal("-"); + styled.literal(s); + } + styled.extend(self.stylize_arg_suffix(required).into_iter()); + styled + } + + pub(crate) fn stylize_arg_suffix(&self, required: Option) -> StyledStr { + let mut styled = StyledStr::new(); + + let mut need_closing_bracket = false; + if self.is_takes_value_set() && !self.is_positional() { + let is_optional_val = self.get_min_vals() == 0; + if self.is_require_equals_set() { + if is_optional_val { + need_closing_bracket = true; + styled.placeholder("[="); + } else { + styled.literal("="); + } + } else if is_optional_val { + need_closing_bracket = true; + styled.placeholder(" ["); + } else { + styled.placeholder(" "); + } + } + if self.is_takes_value_set() || self.is_positional() { + let required = required.unwrap_or_else(|| self.is_required_set()); + let arg_val = self.render_arg_val(required); + styled.placeholder(arg_val); + } else if matches!(*self.get_action(), ArgAction::Count) { + styled.placeholder("..."); + } + if need_closing_bracket { + styled.placeholder("]"); + } + + styled + } + + /// Write the values such as ` ` + fn render_arg_val(&self, required: bool) -> String { + let mut rendered = String::new(); + + let num_vals = self.get_num_args().unwrap_or_else(|| 1.into()); + + let mut val_names = if self.val_names.is_empty() { + vec![self.id.as_internal_str().to_owned()] + } else { + self.val_names.clone() + }; + if val_names.len() == 1 { + let min = num_vals.min_values().max(1); + let val_name = val_names.pop().unwrap(); + val_names = vec![val_name; min]; + } + + debug_assert!(self.is_takes_value_set()); + for (n, val_name) in val_names.iter().enumerate() { + let arg_name = if self.is_positional() && (num_vals.min_values() == 0 || !required) { + format!("[{}]", val_name) + } else { + format!("<{}>", val_name) + }; + + if n != 0 { + rendered.push(' '); + } + rendered.push_str(&arg_name); + } + + let mut extra_values = false; + extra_values |= val_names.len() < num_vals.max_values(); + if self.is_positional() && matches!(*self.get_action(), ArgAction::Append) { + extra_values = true; + } + if extra_values { + rendered.push_str("..."); + } + + rendered + } + + /// Either multiple values or occurrences + pub(crate) fn is_multiple(&self) -> bool { + self.is_multiple_values_set() || matches!(*self.get_action(), ArgAction::Append) + } + + #[cfg(feature = "help")] + pub(crate) fn get_display_order(&self) -> usize { + self.disp_ord.unwrap_or(999) + } +} + +impl From<&'_ Arg> for Arg { + fn from(a: &Arg) -> Self { + a.clone() + } +} + +impl PartialEq for Arg { + fn eq(&self, other: &Arg) -> bool { + self.get_id() == other.get_id() + } +} + +impl PartialOrd for Arg { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Arg { + fn cmp(&self, other: &Arg) -> Ordering { + self.get_id().cmp(other.get_id()) + } +} + +impl Eq for Arg {} + +impl Display for Arg { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + self.stylized(None).fmt(f) + } +} + +impl fmt::Debug for Arg { + fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { + let mut ds = f.debug_struct("Arg"); + + #[allow(unused_mut)] + let mut ds = ds + .field("id", &self.id) + .field("help", &self.help) + .field("long_help", &self.long_help) + .field("action", &self.action) + .field("value_parser", &self.value_parser) + .field("blacklist", &self.blacklist) + .field("settings", &self.settings) + .field("overrides", &self.overrides) + .field("groups", &self.groups) + .field("requires", &self.requires) + .field("r_ifs", &self.r_ifs) + .field("r_unless", &self.r_unless) + .field("short", &self.short) + .field("long", &self.long) + .field("aliases", &self.aliases) + .field("short_aliases", &self.short_aliases) + .field("disp_ord", &self.disp_ord) + .field("val_names", &self.val_names) + .field("num_vals", &self.num_vals) + .field("val_delim", &self.val_delim) + .field("default_vals", &self.default_vals) + .field("default_vals_ifs", &self.default_vals_ifs) + .field("terminator", &self.terminator) + .field("index", &self.index) + .field("help_heading", &self.help_heading) + .field("value_hint", &self.value_hint) + .field("default_missing_vals", &self.default_missing_vals); + + #[cfg(feature = "env")] + { + ds = ds.field("env", &self.env); + } + + ds.finish() + } +} + +// Flags +#[cfg(test)] +mod test { + use super::Arg; + use super::ArgAction; + + #[test] + fn flag_display_long() { + let mut f = Arg::new("flg").long("flag").action(ArgAction::SetTrue); + f._build(); + + assert_eq!(f.to_string(), "--flag"); + } + + #[test] + fn flag_display_short() { + let mut f2 = Arg::new("flg").short('f').action(ArgAction::SetTrue); + f2._build(); + + assert_eq!(f2.to_string(), "-f"); + } + + #[test] + fn flag_display_count() { + let mut f2 = Arg::new("flg").long("flag").action(ArgAction::Count); + f2._build(); + + assert_eq!(f2.to_string(), "--flag..."); + } + + #[test] + fn flag_display_single_alias() { + let mut f = Arg::new("flg") + .long("flag") + .visible_alias("als") + .action(ArgAction::SetTrue); + f._build(); + + assert_eq!(f.to_string(), "--flag") + } + + #[test] + fn flag_display_multiple_aliases() { + let mut f = Arg::new("flg").short('f').action(ArgAction::SetTrue); + f.aliases = vec![ + ("alias_not_visible".into(), false), + ("f2".into(), true), + ("f3".into(), true), + ("f4".into(), true), + ]; + f._build(); + + assert_eq!(f.to_string(), "-f"); + } + + #[test] + fn flag_display_single_short_alias() { + let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue); + f.short_aliases = vec![('b', true)]; + f._build(); + + assert_eq!(f.to_string(), "-a") + } + + #[test] + fn flag_display_multiple_short_aliases() { + let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue); + f.short_aliases = vec![('b', false), ('c', true), ('d', true), ('e', true)]; + f._build(); + + assert_eq!(f.to_string(), "-a"); + } + + // Options + + #[test] + fn option_display_multiple_occurrences() { + let mut o = Arg::new("opt").long("option").action(ArgAction::Append); + o._build(); + + assert_eq!(o.to_string(), "--option "); + } + + #[test] + fn option_display_multiple_values() { + let mut o = Arg::new("opt") + .long("option") + .action(ArgAction::Set) + .num_args(1..); + o._build(); + + assert_eq!(o.to_string(), "--option ..."); + } + + #[test] + fn option_display_zero_or_more_values() { + let mut o = Arg::new("opt") + .long("option") + .action(ArgAction::Set) + .num_args(0..); + o._build(); + + assert_eq!(o.to_string(), "--option [...]"); + } + + #[test] + fn option_display_one_or_more_values() { + let mut o = Arg::new("opt") + .long("option") + .action(ArgAction::Set) + .num_args(1..); + o._build(); + + assert_eq!(o.to_string(), "--option ..."); + } + + #[test] + fn option_display_zero_or_more_values_with_value_name() { + let mut o = Arg::new("opt") + .short('o') + .action(ArgAction::Set) + .num_args(0..) + .value_names(["file"]); + o._build(); + + assert_eq!(o.to_string(), "-o [...]"); + } + + #[test] + fn option_display_one_or_more_values_with_value_name() { + let mut o = Arg::new("opt") + .short('o') + .action(ArgAction::Set) + .num_args(1..) + .value_names(["file"]); + o._build(); + + assert_eq!(o.to_string(), "-o ..."); + } + + #[test] + fn option_display_optional_value() { + let mut o = Arg::new("opt") + .long("option") + .action(ArgAction::Set) + .num_args(0..=1); + o._build(); + + assert_eq!(o.to_string(), "--option []"); + } + + #[test] + fn option_display_value_names() { + let mut o = Arg::new("opt") + .short('o') + .action(ArgAction::Set) + .value_names(["file", "name"]); + o._build(); + + assert_eq!(o.to_string(), "-o "); + } + + #[test] + fn option_display3() { + let mut o = Arg::new("opt") + .short('o') + .num_args(1..) + .action(ArgAction::Set) + .value_names(["file", "name"]); + o._build(); + + assert_eq!(o.to_string(), "-o ..."); + } + + #[test] + fn option_display_single_alias() { + let mut o = Arg::new("opt") + .long("option") + .action(ArgAction::Set) + .visible_alias("als"); + o._build(); + + assert_eq!(o.to_string(), "--option "); + } + + #[test] + fn option_display_multiple_aliases() { + let mut o = Arg::new("opt") + .long("option") + .action(ArgAction::Set) + .visible_aliases(["als2", "als3", "als4"]) + .alias("als_not_visible"); + o._build(); + + assert_eq!(o.to_string(), "--option "); + } + + #[test] + fn option_display_single_short_alias() { + let mut o = Arg::new("opt") + .short('a') + .action(ArgAction::Set) + .visible_short_alias('b'); + o._build(); + + assert_eq!(o.to_string(), "-a "); + } + + #[test] + fn option_display_multiple_short_aliases() { + let mut o = Arg::new("opt") + .short('a') + .action(ArgAction::Set) + .visible_short_aliases(['b', 'c', 'd']) + .short_alias('e'); + o._build(); + + assert_eq!(o.to_string(), "-a "); + } + + // Positionals + + #[test] + fn positional_display_multiple_values() { + let mut p = Arg::new("pos").index(1).num_args(1..); + p._build(); + + assert_eq!(p.to_string(), "[pos]..."); + } + + #[test] + fn positional_display_multiple_values_required() { + let mut p = Arg::new("pos").index(1).num_args(1..).required(true); + p._build(); + + assert_eq!(p.to_string(), "..."); + } + + #[test] + fn positional_display_zero_or_more_values() { + let mut p = Arg::new("pos").index(1).num_args(0..); + p._build(); + + assert_eq!(p.to_string(), "[pos]..."); + } + + #[test] + fn positional_display_one_or_more_values() { + let mut p = Arg::new("pos").index(1).num_args(1..); + p._build(); + + assert_eq!(p.to_string(), "[pos]..."); + } + + #[test] + fn positional_display_one_or_more_values_required() { + let mut p = Arg::new("pos").index(1).num_args(1..).required(true); + p._build(); + + assert_eq!(p.to_string(), "..."); + } + + #[test] + fn positional_display_optional_value() { + let mut p = Arg::new("pos") + .index(1) + .num_args(0..=1) + .action(ArgAction::Set); + p._build(); + + assert_eq!(p.to_string(), "[pos]"); + } + + #[test] + fn positional_display_multiple_occurrences() { + let mut p = Arg::new("pos").index(1).action(ArgAction::Append); + p._build(); + + assert_eq!(p.to_string(), "[pos]..."); + } + + #[test] + fn positional_display_multiple_occurrences_required() { + let mut p = Arg::new("pos") + .index(1) + .action(ArgAction::Append) + .required(true); + p._build(); + + assert_eq!(p.to_string(), "..."); + } + + #[test] + fn positional_display_required() { + let mut p = Arg::new("pos").index(1).required(true); + p._build(); + + assert_eq!(p.to_string(), ""); + } + + #[test] + fn positional_display_val_names() { + let mut p = Arg::new("pos").index(1).value_names(["file1", "file2"]); + p._build(); + + assert_eq!(p.to_string(), "[file1] [file2]"); + } + + #[test] + fn positional_display_val_names_required() { + let mut p = Arg::new("pos") + .index(1) + .value_names(["file1", "file2"]) + .required(true); + p._build(); + + assert_eq!(p.to_string(), " "); + } + + #[test] + fn positional_display_val_names_req() { + let mut p = Arg::new("pos") + .index(1) + .required(true) + .value_names(["file1", "file2"]); + p._build(); + + assert_eq!(p.to_string(), " "); + } +} diff --git a/vendor/clap/src/builder/arg_group.rs b/vendor/clap/src/builder/arg_group.rs new file mode 100644 index 000000000..a6386a1c0 --- /dev/null +++ b/vendor/clap/src/builder/arg_group.rs @@ -0,0 +1,596 @@ +// Internal +use crate::builder::IntoResettable; +use crate::util::Id; + +/// Family of related [arguments]. +/// +/// By placing arguments in a logical group, you can create easier requirement and +/// exclusion rules instead of having to list each argument individually, or when you want a rule +/// to apply "any but not all" arguments. +/// +/// For instance, you can make an entire `ArgGroup` required. If [`ArgGroup::multiple(true)`] is +/// set, this means that at least one argument from that group must be present. If +/// [`ArgGroup::multiple(false)`] is set (the default), one and *only* one must be present. +/// +/// You can also do things such as name an entire `ArgGroup` as a [conflict] or [requirement] for +/// another argument, meaning any of the arguments that belong to that group will cause a failure +/// if present, or must be present respectively. +/// +/// Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be +/// present out of a given set. Imagine that you had multiple arguments, and you want one of them +/// to be required, but making all of them required isn't feasible because perhaps they conflict +/// with each other. For example, lets say that you were building an application where one could +/// set a given version number by supplying a string with an option argument, i.e. +/// `--set-ver v1.2.3`, you also wanted to support automatically using a previous version number +/// and simply incrementing one of the three numbers. So you create three flags `--major`, +/// `--minor`, and `--patch`. All of these arguments shouldn't be used at one time but you want to +/// specify that *at least one* of them is used. For this, you can create a group. +/// +/// Finally, you may use `ArgGroup`s to pull a value from a group of arguments when you don't care +/// exactly which argument was actually used at runtime. +/// +/// # Examples +/// +/// The following example demonstrates using an `ArgGroup` to ensure that one, and only one, of +/// the arguments from the specified group is present at runtime. +/// +/// ```rust +/// # use clap::{Command, arg, ArgGroup, error::ErrorKind}; +/// let result = Command::new("cmd") +/// .arg(arg!(--"set-ver" "set the version manually")) +/// .arg(arg!(--major "auto increase major")) +/// .arg(arg!(--minor "auto increase minor")) +/// .arg(arg!(--patch "auto increase patch")) +/// .group(ArgGroup::new("vers") +/// .args(["set-ver", "major", "minor", "patch"]) +/// .required(true)) +/// .try_get_matches_from(vec!["cmd", "--major", "--patch"]); +/// // Because we used two args in the group it's an error +/// assert!(result.is_err()); +/// let err = result.unwrap_err(); +/// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); +/// ``` +/// +/// This next example shows a passing parse of the same scenario +/// ```rust +/// # use clap::{Command, arg, ArgGroup, Id}; +/// let result = Command::new("cmd") +/// .arg(arg!(--"set-ver" "set the version manually")) +/// .arg(arg!(--major "auto increase major")) +/// .arg(arg!(--minor "auto increase minor")) +/// .arg(arg!(--patch "auto increase patch")) +/// .group(ArgGroup::new("vers") +/// .args(["set-ver", "major", "minor","patch"]) +/// .required(true)) +/// .try_get_matches_from(vec!["cmd", "--major"]); +/// assert!(result.is_ok()); +/// let matches = result.unwrap(); +/// // We may not know which of the args was used, so we can test for the group... +/// assert!(matches.contains_id("vers")); +/// // We can also ask the group which arg was used +/// assert_eq!(matches +/// .get_one::("vers") +/// .expect("`vers` is required") +/// .as_str(), +/// "major" +/// ); +/// // we could also alternatively check each arg individually (not shown here) +/// ``` +/// [`ArgGroup::multiple(true)`]: ArgGroup::multiple() +/// +/// [`ArgGroup::multiple(false)`]: ArgGroup::multiple() +/// [arguments]: crate::Arg +/// [conflict]: crate::Arg::conflicts_with() +/// [requirement]: crate::Arg::requires() +#[derive(Default, Clone, Debug, PartialEq, Eq)] +pub struct ArgGroup { + pub(crate) id: Id, + pub(crate) args: Vec, + pub(crate) required: bool, + pub(crate) requires: Vec, + pub(crate) conflicts: Vec, + pub(crate) multiple: bool, +} + +/// # Builder +impl ArgGroup { + /// Create a `ArgGroup` using a unique name. + /// + /// The name will be used to get values from the group or refer to the group inside of conflict + /// and requirement rules. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ArgGroup}; + /// ArgGroup::new("config") + /// # ; + /// ``` + pub fn new(id: impl Into) -> Self { + ArgGroup::default().id(id) + } + + /// Sets the group name. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, ArgGroup}; + /// ArgGroup::default().id("config") + /// # ; + /// ``` + #[must_use] + pub fn id(mut self, id: impl Into) -> Self { + self.id = id.into(); + self + } + + /// Adds an [argument] to this group by name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ArgAction}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("color") + /// .short('c') + /// .action(ArgAction::SetTrue)) + /// .group(ArgGroup::new("req_flags") + /// .arg("flag") + /// .arg("color")) + /// .get_matches_from(vec!["myprog", "-f"]); + /// // maybe we don't know which of the two flags was used... + /// assert!(m.contains_id("req_flags")); + /// // but we can also check individually if needed + /// assert!(m.contains_id("flag")); + /// ``` + /// [argument]: crate::Arg + #[must_use] + pub fn arg(mut self, arg_id: impl IntoResettable) -> Self { + if let Some(arg_id) = arg_id.into_resettable().into_option() { + self.args.push(arg_id); + } else { + self.args.clear(); + } + self + } + + /// Adds multiple [arguments] to this group by name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ArgAction}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("color") + /// .short('c') + /// .action(ArgAction::SetTrue)) + /// .group(ArgGroup::new("req_flags") + /// .args(["flag", "color"])) + /// .get_matches_from(vec!["myprog", "-f"]); + /// // maybe we don't know which of the two flags was used... + /// assert!(m.contains_id("req_flags")); + /// // but we can also check individually if needed + /// assert!(m.contains_id("flag")); + /// ``` + /// [arguments]: crate::Arg + #[must_use] + pub fn args(mut self, ns: impl IntoIterator>) -> Self { + for n in ns { + self = self.arg(n); + } + self + } + + /// Getters for all args. It will return a vector of `Id` + /// + /// # Example + /// + /// ```rust + /// # use clap::{ArgGroup}; + /// let args: Vec<&str> = vec!["a1".into(), "a4".into()]; + /// let grp = ArgGroup::new("program").args(&args); + /// + /// for (pos, arg) in grp.get_args().enumerate() { + /// assert_eq!(*arg, args[pos]); + /// } + /// ``` + pub fn get_args(&self) -> impl Iterator { + self.args.iter() + } + + /// Allows more than one of the [`Arg`]s in this group to be used. (Default: `false`) + /// + /// # Examples + /// + /// Notice in this example we use *both* the `-f` and `-c` flags which are both part of the + /// group + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, ArgAction}; + /// let m = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("color") + /// .short('c') + /// .action(ArgAction::SetTrue)) + /// .group(ArgGroup::new("req_flags") + /// .args(["flag", "color"]) + /// .multiple(true)) + /// .get_matches_from(vec!["myprog", "-f", "-c"]); + /// // maybe we don't know which of the two flags was used... + /// assert!(m.contains_id("req_flags")); + /// ``` + /// In this next example, we show the default behavior (i.e. `multiple(false)) which will throw + /// an error if more than one of the args in the group was used. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("color") + /// .short('c') + /// .action(ArgAction::SetTrue)) + /// .group(ArgGroup::new("req_flags") + /// .args(["flag", "color"])) + /// .try_get_matches_from(vec!["myprog", "-f", "-c"]); + /// // Because we used both args in the group it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); + /// ``` + /// + /// [`Arg`]: crate::Arg + #[inline] + #[must_use] + pub fn multiple(mut self, yes: bool) -> Self { + self.multiple = yes; + self + } + + /// Return true if the group allows more than one of the arguments + /// in this group to be used. (Default: `false`) + /// + /// # Example + /// + /// ```rust + /// # use clap::{ArgGroup}; + /// let mut group = ArgGroup::new("myprog") + /// .args(["f", "c"]) + /// .multiple(true); + /// + /// assert!(group.is_multiple()); + /// ``` + pub fn is_multiple(&mut self) -> bool { + self.multiple + } + + /// Require an argument from the group to be present when parsing. + /// + /// This is unless conflicting with another argument. A required group will be displayed in + /// the usage string of the application in the format ``. + /// + /// **NOTE:** This setting only applies to the current [`Command`] / [`Subcommand`]s, and not + /// globally. + /// + /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with + /// `ArgGroup::required(true)` states, "One and *only one* arg must be used from this group. + /// Use of more than one arg is an error." Vice setting `ArgGroup::multiple(true)` which + /// states, '*At least* one arg from this group must be used. Using multiple is OK." + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("color") + /// .short('c') + /// .action(ArgAction::SetTrue)) + /// .group(ArgGroup::new("req_flags") + /// .args(["flag", "color"]) + /// .required(true)) + /// .try_get_matches_from(vec!["myprog"]); + /// // Because we didn't use any of the args in the group, it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// + /// [`Subcommand`]: crate::Subcommand + /// [`ArgGroup::multiple`]: ArgGroup::multiple() + /// [`Command`]: crate::Command + #[inline] + #[must_use] + pub fn required(mut self, yes: bool) -> Self { + self.required = yes; + self + } + + /// Specify an argument or group that must be present when this group is. + /// + /// This is not to be confused with a [required group]. Requirement rules function just like + /// [argument requirement rules], you can name other arguments or groups that must be present + /// when any one of the arguments from this group is used. + /// + /// **NOTE:** The name provided may be an argument or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("color") + /// .short('c') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("debug") + /// .short('d') + /// .action(ArgAction::SetTrue)) + /// .group(ArgGroup::new("req_flags") + /// .args(["flag", "color"]) + /// .requires("debug")) + /// .try_get_matches_from(vec!["myprog", "-c"]); + /// // because we used an arg from the group, and the group requires "-d" to be used, it's an + /// // error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required group]: ArgGroup::required() + /// [argument requirement rules]: crate::Arg::requires() + #[must_use] + pub fn requires(mut self, id: impl IntoResettable) -> Self { + if let Some(id) = id.into_resettable().into_option() { + self.requires.push(id); + } else { + self.requires.clear(); + } + self + } + + /// Specify arguments or groups that must be present when this group is. + /// + /// This is not to be confused with a [required group]. Requirement rules function just like + /// [argument requirement rules], you can name other arguments or groups that must be present + /// when one of the arguments from this group is used. + /// + /// **NOTE:** The names provided may be an argument or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("color") + /// .short('c') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("debug") + /// .short('d') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("verb") + /// .short('v') + /// .action(ArgAction::SetTrue)) + /// .group(ArgGroup::new("req_flags") + /// .args(["flag", "color"]) + /// .requires_all(["debug", "verb"])) + /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); + /// // because we used an arg from the group, and the group requires "-d" and "-v" to be used, + /// // yet we only used "-d" it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument); + /// ``` + /// [required group]: ArgGroup::required() + /// [argument requirement rules]: crate::Arg::requires_ifs() + #[must_use] + pub fn requires_all(mut self, ns: impl IntoIterator>) -> Self { + for n in ns { + self = self.requires(n); + } + self + } + + /// Specify an argument or group that must **not** be present when this group is. + /// + /// Exclusion (aka conflict) rules function just like [argument exclusion rules], you can name + /// other arguments or groups that must *not* be present when one of the arguments from this + /// group are used. + /// + /// **NOTE:** The name provided may be an argument, or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("color") + /// .short('c') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("debug") + /// .short('d') + /// .action(ArgAction::SetTrue)) + /// .group(ArgGroup::new("req_flags") + /// .args(["flag", "color"]) + /// .conflicts_with("debug")) + /// .try_get_matches_from(vec!["myprog", "-c", "-d"]); + /// // because we used an arg from the group, and the group conflicts with "-d", it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); + /// ``` + /// [argument exclusion rules]: crate::Arg::conflicts_with() + #[must_use] + pub fn conflicts_with(mut self, id: impl IntoResettable) -> Self { + if let Some(id) = id.into_resettable().into_option() { + self.conflicts.push(id); + } else { + self.conflicts.clear(); + } + self + } + + /// Specify arguments or groups that must **not** be present when this group is. + /// + /// Exclusion rules function just like [argument exclusion rules], you can name other arguments + /// or groups that must *not* be present when one of the arguments from this group are used. + /// + /// **NOTE:** The names provided may be an argument, or group name + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgGroup, error::ErrorKind, ArgAction}; + /// let result = Command::new("myprog") + /// .arg(Arg::new("flag") + /// .short('f') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("color") + /// .short('c') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("debug") + /// .short('d') + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("verb") + /// .short('v') + /// .action(ArgAction::SetTrue)) + /// .group(ArgGroup::new("req_flags") + /// .args(["flag", "color"]) + /// .conflicts_with_all(["debug", "verb"])) + /// .try_get_matches_from(vec!["myprog", "-c", "-v"]); + /// // because we used an arg from the group, and the group conflicts with either "-v" or "-d" + /// // it's an error + /// assert!(result.is_err()); + /// let err = result.unwrap_err(); + /// assert_eq!(err.kind(), ErrorKind::ArgumentConflict); + /// ``` + /// + /// [argument exclusion rules]: crate::Arg::conflicts_with_all() + #[must_use] + pub fn conflicts_with_all(mut self, ns: impl IntoIterator>) -> Self { + for n in ns { + self = self.conflicts_with(n); + } + self + } +} + +/// # Reflection +impl ArgGroup { + /// Get the name of the group + #[inline] + pub fn get_id(&self) -> &Id { + &self.id + } + + /// Reports whether [`ArgGroup::required`] is set + #[inline] + pub fn is_required_set(&self) -> bool { + self.required + } +} + +impl From<&'_ ArgGroup> for ArgGroup { + fn from(g: &ArgGroup) -> Self { + g.clone() + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn groups() { + let g = ArgGroup::new("test") + .arg("a1") + .arg("a4") + .args(["a2", "a3"]) + .required(true) + .conflicts_with("c1") + .conflicts_with_all(["c2", "c3"]) + .conflicts_with("c4") + .requires("r1") + .requires_all(["r2", "r3"]) + .requires("r4"); + + let args: Vec = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; + let reqs: Vec = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; + let confs: Vec = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; + + assert_eq!(g.args, args); + assert_eq!(g.requires, reqs); + assert_eq!(g.conflicts, confs); + } + + #[test] + fn test_from() { + let g = ArgGroup::new("test") + .arg("a1") + .arg("a4") + .args(["a2", "a3"]) + .required(true) + .conflicts_with("c1") + .conflicts_with_all(["c2", "c3"]) + .conflicts_with("c4") + .requires("r1") + .requires_all(["r2", "r3"]) + .requires("r4"); + + let args: Vec = vec!["a1".into(), "a4".into(), "a2".into(), "a3".into()]; + let reqs: Vec = vec!["r1".into(), "r2".into(), "r3".into(), "r4".into()]; + let confs: Vec = vec!["c1".into(), "c2".into(), "c3".into(), "c4".into()]; + + let g2 = ArgGroup::from(&g); + assert_eq!(g2.args, args); + assert_eq!(g2.requires, reqs); + assert_eq!(g2.conflicts, confs); + } + + // This test will *fail to compile* if ArgGroup is not Send + Sync + #[test] + fn arg_group_send_sync() { + fn foo(_: T) {} + foo(ArgGroup::new("test")) + } + + #[test] + fn arg_group_expose_is_multiple_helper() { + let args: Vec = vec!["a1".into(), "a4".into()]; + + let mut grp_multiple = ArgGroup::new("test_multiple").args(&args).multiple(true); + assert!(grp_multiple.is_multiple()); + + let mut grp_not_multiple = ArgGroup::new("test_multiple").args(&args).multiple(false); + assert!(!grp_not_multiple.is_multiple()); + } + + #[test] + fn arg_group_expose_get_args_helper() { + let args: Vec = vec!["a1".into(), "a4".into()]; + let grp = ArgGroup::new("program").args(&args); + + for (pos, arg) in grp.get_args().enumerate() { + assert_eq!(*arg, args[pos]); + } + } +} diff --git a/vendor/clap/src/builder/arg_predicate.rs b/vendor/clap/src/builder/arg_predicate.rs new file mode 100644 index 000000000..bc79a11b7 --- /dev/null +++ b/vendor/clap/src/builder/arg_predicate.rs @@ -0,0 +1,19 @@ +use crate::builder::OsStr; + +/// Operations to perform on argument values +/// +/// These do not apply to [`ValueSource::DefaultValue`][crate::parser::ValueSource::DefaultValue] +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "unstable-v5", non_exhaustive)] +pub enum ArgPredicate { + /// Is the argument present? + IsPresent, + /// Does the argument match the specified value? + Equals(OsStr), +} + +impl> From for ArgPredicate { + fn from(other: S) -> Self { + Self::Equals(other.into()) + } +} diff --git a/vendor/clap/src/builder/arg_settings.rs b/vendor/clap/src/builder/arg_settings.rs new file mode 100644 index 000000000..0f63e4396 --- /dev/null +++ b/vendor/clap/src/builder/arg_settings.rs @@ -0,0 +1,145 @@ +// Std +use std::ops::BitOr; + +// Third party +use bitflags::bitflags; + +#[allow(unused)] +use crate::Arg; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ArgFlags(Flags); + +impl Default for ArgFlags { + fn default() -> Self { + Self::empty() + } +} + +/// Various settings that apply to arguments and may be set, unset, and checked via getter/setter +/// methods [`Arg::setting`], [`Arg::unset_setting`], and [`Arg::is_set`]. This is what the +/// [`Arg`] methods which accept a `bool` use internally. +/// +/// [`Arg`]: crate::Arg +/// [`Arg::setting`]: crate::Arg::setting() +/// [`Arg::unset_setting`]: crate::Arg::unset_setting() +/// [`Arg::is_set`]: crate::Arg::is_set() +#[derive(Debug, PartialEq, Copy, Clone)] +#[non_exhaustive] +pub(crate) enum ArgSettings { + Required, + Global, + Hidden, + NextLineHelp, + HidePossibleValues, + AllowHyphenValues, + AllowNegativeNumbers, + RequireEquals, + Last, + TrailingVarArg, + HideDefaultValue, + IgnoreCase, + #[cfg(feature = "env")] + HideEnv, + #[cfg(feature = "env")] + HideEnvValues, + HiddenShortHelp, + HiddenLongHelp, + Exclusive, +} + +bitflags! { + struct Flags: u32 { + const REQUIRED = 1; + const GLOBAL = 1 << 3; + const HIDDEN = 1 << 4; + const TRAILING_VARARG = 1 << 5; + const ALLOW_NEG_NUMS = 1 << 6; + const NEXT_LINE_HELP = 1 << 7; + const DELIM_NOT_SET = 1 << 10; + const HIDE_POS_VALS = 1 << 11; + const ALLOW_TAC_VALS = 1 << 12; + const REQUIRE_EQUALS = 1 << 13; + const LAST = 1 << 14; + const HIDE_DEFAULT_VAL = 1 << 15; + const CASE_INSENSITIVE = 1 << 16; + #[cfg(feature = "env")] + const HIDE_ENV_VALS = 1 << 17; + const HIDDEN_SHORT_H = 1 << 18; + const HIDDEN_LONG_H = 1 << 19; + #[cfg(feature = "env")] + const HIDE_ENV = 1 << 21; + const EXCLUSIVE = 1 << 23; + const NO_OP = 0; + } +} + +impl_settings! { ArgSettings, ArgFlags, + Required => Flags::REQUIRED, + Global => Flags::GLOBAL, + Hidden => Flags::HIDDEN, + NextLineHelp => Flags::NEXT_LINE_HELP, + HidePossibleValues => Flags::HIDE_POS_VALS, + AllowHyphenValues => Flags::ALLOW_TAC_VALS, + AllowNegativeNumbers => Flags::ALLOW_NEG_NUMS, + RequireEquals => Flags::REQUIRE_EQUALS, + Last => Flags::LAST, + TrailingVarArg => Flags::TRAILING_VARARG, + IgnoreCase => Flags::CASE_INSENSITIVE, + #[cfg(feature = "env")] + HideEnv => Flags::HIDE_ENV, + #[cfg(feature = "env")] + HideEnvValues => Flags::HIDE_ENV_VALS, + HideDefaultValue => Flags::HIDE_DEFAULT_VAL, + HiddenShortHelp => Flags::HIDDEN_SHORT_H, + HiddenLongHelp => Flags::HIDDEN_LONG_H, + Exclusive => Flags::EXCLUSIVE +} + +#[cfg(test)] +mod test { + use super::*; + use crate::Arg; + + #[test] + fn setting() { + let m = Arg::new("setting").setting(ArgSettings::Required); + assert!(m.is_required_set()); + } + + #[test] + fn unset_setting() { + let m = Arg::new("unset_setting").setting(ArgSettings::Required); + assert!(m.is_required_set()); + + let m = m.unset_setting(ArgSettings::Required); + assert!(!m.is_required_set(), "{:#?}", m); + } + + #[test] + fn setting_bitor() { + let m = Arg::new("setting_bitor") + .setting(ArgSettings::Required | ArgSettings::Hidden | ArgSettings::Last); + + assert!(m.is_required_set()); + assert!(m.is_hide_set()); + assert!(m.is_last_set()); + } + + #[test] + fn unset_setting_bitor() { + let m = Arg::new("unset_setting_bitor") + .setting(ArgSettings::Required) + .setting(ArgSettings::Hidden) + .setting(ArgSettings::Last); + + assert!(m.is_required_set()); + assert!(m.is_hide_set()); + assert!(m.is_last_set()); + + let m = m.unset_setting(ArgSettings::Required | ArgSettings::Hidden | ArgSettings::Last); + assert!(!m.is_required_set(), "{:#?}", m); + assert!(!m.is_hide_set(), "{:#?}", m); + assert!(!m.is_last_set(), "{:#?}", m); + } +} diff --git a/vendor/clap/src/builder/command.rs b/vendor/clap/src/builder/command.rs new file mode 100644 index 000000000..fc2c983e4 --- /dev/null +++ b/vendor/clap/src/builder/command.rs @@ -0,0 +1,4703 @@ +#![cfg_attr(not(feature = "usage"), allow(unused_mut))] + +// Std +use std::env; +use std::ffi::OsString; +use std::fmt; +use std::io; +use std::ops::Index; +use std::path::Path; + +// Internal +use crate::builder::app_settings::{AppFlags, AppSettings}; +use crate::builder::arg_settings::ArgSettings; +use crate::builder::ArgAction; +use crate::builder::IntoResettable; +use crate::builder::PossibleValue; +use crate::builder::Str; +use crate::builder::StyledStr; +use crate::builder::{Arg, ArgGroup, ArgPredicate}; +use crate::error::ErrorKind; +use crate::error::Result as ClapResult; +use crate::mkeymap::MKeyMap; +use crate::output::fmt::Stream; +use crate::output::{fmt::Colorizer, write_help, Usage}; +use crate::parser::{ArgMatcher, ArgMatches, Parser}; +use crate::util::ChildGraph; +use crate::util::FlatMap; +use crate::util::{color::ColorChoice, Id}; +use crate::{Error, INTERNAL_ERROR_MSG}; + +#[cfg(debug_assertions)] +use crate::builder::debug_asserts::assert_app; + +/// Build a command-line interface. +/// +/// This includes defining arguments, subcommands, parser behavior, and help output. +/// Once all configuration is complete, +/// the [`Command::get_matches`] family of methods starts the runtime-parsing +/// process. These methods then return information about the user supplied +/// arguments (or lack thereof). +/// +/// When deriving a [`Parser`][crate::Parser], you can use +/// [`CommandFactory::command`][crate::CommandFactory::command] to access the +/// `Command`. +/// +/// - [Basic API][crate::Command#basic-api] +/// - [Application-wide Settings][crate::Command#application-wide-settings] +/// - [Command-specific Settings][crate::Command#command-specific-settings] +/// - [Subcommand-specific Settings][crate::Command#subcommand-specific-settings] +/// - [Reflection][crate::Command#reflection] +/// +/// # Examples +/// +/// ```no_run +/// # use clap::{Command, Arg}; +/// let m = Command::new("My Program") +/// .author("Me, me@mail.com") +/// .version("1.0.2") +/// .about("Explains in brief what the program does") +/// .arg( +/// Arg::new("in_file") +/// ) +/// .after_help("Longer explanation to appear after the options when \ +/// displaying the help information from --help or -h") +/// .get_matches(); +/// +/// // Your program logic starts here... +/// ``` +/// [`Command::get_matches`]: Command::get_matches() +#[derive(Debug, Clone)] +pub struct Command { + name: Str, + long_flag: Option, + short_flag: Option, + display_name: Option, + bin_name: Option, + author: Option, + version: Option, + long_version: Option, + about: Option, + long_about: Option, + before_help: Option, + before_long_help: Option, + after_help: Option, + after_long_help: Option, + aliases: Vec<(Str, bool)>, // (name, visible) + short_flag_aliases: Vec<(char, bool)>, // (name, visible) + long_flag_aliases: Vec<(Str, bool)>, // (name, visible) + usage_str: Option, + usage_name: Option, + help_str: Option, + disp_ord: Option, + term_w: Option, + max_w: Option, + #[cfg(feature = "help")] + template: Option, + settings: AppFlags, + g_settings: AppFlags, + args: MKeyMap, + subcommands: Vec, + replacers: FlatMap>, + groups: Vec, + current_help_heading: Option, + current_disp_ord: Option, + subcommand_value_name: Option, + subcommand_heading: Option, + external_value_parser: Option, + long_help_exists: bool, +} + +/// # Basic API +impl Command { + /// Creates a new instance of an `Command`. + /// + /// It is common, but not required, to use binary name as the `name`. This + /// name will only be displayed to the user when they request to print + /// version or help and usage information. + /// + /// See also [`command!`](crate::command!) and [`crate_name!`](crate::crate_name!). + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("My Program") + /// # ; + /// ``` + pub fn new(name: impl Into) -> Self { + /// The actual implementation of `new`, non-generic to save code size. + /// + /// If we don't do this rustc will unnecessarily generate multiple versions + /// of this code. + fn new_inner(name: Str) -> Command { + Command { + name, + ..Default::default() + } + } + + new_inner(name.into()) + } + + /// Adds an [argument] to the list of valid possibilities. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, arg, Arg}; + /// Command::new("myprog") + /// // Adding a single "flag" argument with a short and help text, using Arg::new() + /// .arg( + /// Arg::new("debug") + /// .short('d') + /// .help("turns on debugging mode") + /// ) + /// // Adding a single "option" argument with a short, a long, and help text using the less + /// // verbose Arg::from() + /// .arg( + /// arg!(-c --config "Optionally sets a config file to use") + /// ) + /// # ; + /// ``` + /// [argument]: Arg + #[must_use] + pub fn arg(mut self, a: impl Into) -> Self { + let arg = a.into(); + self.arg_internal(arg); + self + } + + fn arg_internal(&mut self, mut arg: Arg) { + if let Some(current_disp_ord) = self.current_disp_ord.as_mut() { + if !arg.is_positional() { + let current = *current_disp_ord; + arg.disp_ord.get_or_insert(current); + *current_disp_ord = current + 1; + } + } + + arg.help_heading + .get_or_insert_with(|| self.current_help_heading.clone()); + self.args.push(arg); + } + + /// Adds multiple [arguments] to the list of valid possibilities. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, arg, Arg}; + /// Command::new("myprog") + /// .args([ + /// arg!("[debug] -d 'turns on debugging info'"), + /// Arg::new("input").help("the input file to use") + /// ]) + /// # ; + /// ``` + /// [arguments]: Arg + #[must_use] + pub fn args(mut self, args: impl IntoIterator>) -> Self { + for arg in args { + self = self.arg(arg); + } + self + } + + /// Allows one to mutate an [`Arg`] after it's been added to a [`Command`]. + /// + /// This can be useful for modifying the auto-generated help or version arguments. + /// + /// # Panics + /// + /// If the argument is undefined + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// + /// let mut cmd = Command::new("foo") + /// .arg(Arg::new("bar") + /// .short('b') + /// .action(ArgAction::SetTrue)) + /// .mut_arg("bar", |a| a.short('B')); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]); + /// + /// // Since we changed `bar`'s short to "B" this should err as there + /// // is no `-b` anymore, only `-B` + /// + /// assert!(res.is_err()); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]); + /// assert!(res.is_ok()); + /// ``` + #[must_use] + #[cfg_attr(debug_assertions, track_caller)] + pub fn mut_arg(mut self, arg_id: impl AsRef, f: F) -> Self + where + F: FnOnce(Arg) -> Arg, + { + let id = arg_id.as_ref(); + let a = self + .args + .remove_by_name(id) + .unwrap_or_else(|| panic!("Argument `{}` is undefined", id)); + + self.args.push(f(a)); + self + } + + /// Allows one to mutate a [`Command`] after it's been added as a subcommand. + /// + /// This can be useful for modifying auto-generated arguments of nested subcommands with + /// [`Command::mut_arg`]. + /// + /// # Panics + /// + /// If the subcommand is undefined + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// + /// let mut cmd = Command::new("foo") + /// .subcommand(Command::new("bar")) + /// .mut_subcommand("bar", |subcmd| subcmd.disable_help_flag(true)); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar", "--help"]); + /// + /// // Since we disabled the help flag on the "bar" subcommand, this should err. + /// + /// assert!(res.is_err()); + /// + /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar"]); + /// assert!(res.is_ok()); + /// ``` + #[must_use] + pub fn mut_subcommand(mut self, name: impl AsRef, f: F) -> Self + where + F: FnOnce(Self) -> Self, + { + let name = name.as_ref(); + let pos = self.subcommands.iter().position(|s| s.name == name); + + let subcmd = if let Some(idx) = pos { + self.subcommands.remove(idx) + } else { + panic!("Command `{}` is undefined", name) + }; + + self.subcommands.push(f(subcmd)); + self + } + + /// Adds an [`ArgGroup`] to the application. + /// + /// [`ArgGroup`]s are a family of related arguments. + /// By placing them in a logical group, you can build easier requirement and exclusion rules. + /// + /// Example use cases: + /// - Make an entire [`ArgGroup`] required, meaning that one (and *only* + /// one) argument from that group must be present at runtime. + /// - Name an [`ArgGroup`] as a conflict to another argument. + /// Meaning any of the arguments that belong to that group will cause a failure if present with + /// the conflicting argument. + /// - Ensure exclusion between arguments. + /// - Extract a value from a group instead of determining exactly which argument was used. + /// + /// # Examples + /// + /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one, + /// of the arguments from the specified group is present at runtime. + /// + /// ```no_run + /// # use clap::{Command, arg, ArgGroup}; + /// Command::new("cmd") + /// .arg(arg!("--set-ver [ver] 'set the version manually'")) + /// .arg(arg!("--major 'auto increase major'")) + /// .arg(arg!("--minor 'auto increase minor'")) + /// .arg(arg!("--patch 'auto increase patch'")) + /// .group(ArgGroup::new("vers") + /// .args(["set-ver", "major", "minor","patch"]) + /// .required(true)) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn group(mut self, group: impl Into) -> Self { + self.groups.push(group.into()); + self + } + + /// Adds multiple [`ArgGroup`]s to the [`Command`] at once. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, arg, ArgGroup}; + /// Command::new("cmd") + /// .arg(arg!("--set-ver [ver] 'set the version manually'")) + /// .arg(arg!("--major 'auto increase major'")) + /// .arg(arg!("--minor 'auto increase minor'")) + /// .arg(arg!("--patch 'auto increase patch'")) + /// .arg(arg!("-c [FILE] 'a config file'")) + /// .arg(arg!("-i [IFACE] 'an interface'")) + /// .groups([ + /// ArgGroup::new("vers") + /// .args(["set-ver", "major", "minor","patch"]) + /// .required(true), + /// ArgGroup::new("input") + /// .args(["c", "i"]) + /// ]) + /// # ; + /// ``` + #[must_use] + pub fn groups(mut self, groups: impl IntoIterator>) -> Self { + for g in groups.into_iter() { + self = self.group(g.into()); + } + self + } + + /// Adds a subcommand to the list of valid possibilities. + /// + /// Subcommands are effectively sub-[`Command`]s, because they can contain their own arguments, + /// subcommands, version, usage, etc. They also function just like [`Command`]s, in that they get + /// their own auto generated help, version, and usage. + /// + /// A subcommand's [`Command::name`] will be used for: + /// - The argument the user passes in + /// - Programmatically looking up the subcommand + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("config") + /// .about("Controls configuration features") + /// .arg(arg!(" 'Required configuration file to use'"))) + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn subcommand(self, subcmd: impl Into) -> Self { + let subcmd = subcmd.into(); + self.subcommand_internal(subcmd) + } + + fn subcommand_internal(mut self, mut subcmd: Self) -> Self { + if let Some(current_disp_ord) = self.current_disp_ord.as_mut() { + let current = *current_disp_ord; + subcmd.disp_ord.get_or_insert(current); + *current_disp_ord = current + 1; + } + self.subcommands.push(subcmd); + self + } + + /// Adds multiple subcommands to the list of valid possibilities. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, }; + /// # Command::new("myprog") + /// .subcommands( [ + /// Command::new("config").about("Controls configuration functionality") + /// .arg(Arg::new("config_file")), + /// Command::new("debug").about("Controls debug functionality")]) + /// # ; + /// ``` + /// [`IntoIterator`]: std::iter::IntoIterator + #[must_use] + pub fn subcommands(mut self, subcmds: impl IntoIterator>) -> Self { + for subcmd in subcmds { + self = self.subcommand(subcmd); + } + self + } + + /// Catch problems earlier in the development cycle. + /// + /// Most error states are handled as asserts under the assumption they are programming mistake + /// and not something to handle at runtime. Rather than relying on tests (manual or automated) + /// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those + /// asserts in a way convenient for running as a test. + /// + /// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive + /// testing of your CLI. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// fn cmd() -> Command { + /// Command::new("foo") + /// .arg( + /// Arg::new("bar").short('b').action(ArgAction::SetTrue) + /// ) + /// } + /// + /// #[test] + /// fn verify_app() { + /// cmd().debug_assert(); + /// } + /// + /// fn main() { + /// let m = cmd().get_matches_from(vec!["foo", "-b"]); + /// println!("{}", m.get_flag("bar")); + /// } + /// ``` + pub fn debug_assert(mut self) { + self.build(); + } + + /// Custom error message for post-parsing validation + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, error::ErrorKind}; + /// let mut cmd = Command::new("myprog"); + /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case"); + /// ``` + pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error { + Error::raw(kind, message).format(self) + } + + /// Parse [`env::args_os`], exiting on failure. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let matches = Command::new("myprog") + /// // Args and options go here... + /// .get_matches(); + /// ``` + /// [`env::args_os`]: std::env::args_os() + /// [`Command::try_get_matches_from_mut`]: Command::try_get_matches_from_mut() + #[inline] + pub fn get_matches(self) -> ArgMatches { + self.get_matches_from(env::args_os()) + } + + /// Parse [`env::args_os`], exiting on failure. + /// + /// Like [`Command::get_matches`] but doesn't consume the `Command`. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let mut cmd = Command::new("myprog") + /// // Args and options go here... + /// ; + /// let matches = cmd.get_matches_mut(); + /// ``` + /// [`env::args_os`]: std::env::args_os() + /// [`Command::get_matches`]: Command::get_matches() + pub fn get_matches_mut(&mut self) -> ArgMatches { + self.try_get_matches_from_mut(&mut env::args_os()) + .unwrap_or_else(|e| e.exit()) + } + + /// Parse [`env::args_os`], returning a [`clap::Result`] on failure. + /// + /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are + /// used. It will return a [`clap::Error`], where the [`kind`] is a + /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call + /// [`Error::exit`] or perform a [`std::process::exit`]. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let matches = Command::new("myprog") + /// // Args and options go here... + /// .try_get_matches() + /// .unwrap_or_else(|e| e.exit()); + /// ``` + /// [`env::args_os`]: std::env::args_os() + /// [`Error::exit`]: crate::Error::exit() + /// [`std::process::exit`]: std::process::exit() + /// [`clap::Result`]: Result + /// [`clap::Error`]: crate::Error + /// [`kind`]: crate::Error + /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp + /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion + #[inline] + pub fn try_get_matches(self) -> ClapResult { + // Start the parsing + self.try_get_matches_from(env::args_os()) + } + + /// Parse the specified arguments, exiting on failure. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`Command::no_binary_name`] is used. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let matches = Command::new("myprog") + /// // Args and options go here... + /// .get_matches_from(arg_vec); + /// ``` + /// [`Command::get_matches`]: Command::get_matches() + /// [`clap::Result`]: Result + /// [`Vec`]: std::vec::Vec + pub fn get_matches_from(mut self, itr: I) -> ArgMatches + where + I: IntoIterator, + T: Into + Clone, + { + self.try_get_matches_from_mut(itr).unwrap_or_else(|e| { + drop(self); + e.exit() + }) + } + + /// Parse the specified arguments, returning a [`clap::Result`] on failure. + /// + /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are + /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] + /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or + /// perform a [`std::process::exit`] yourself. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`Command::no_binary_name`] is used. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let matches = Command::new("myprog") + /// // Args and options go here... + /// .try_get_matches_from(arg_vec) + /// .unwrap_or_else(|e| e.exit()); + /// ``` + /// [`Command::get_matches_from`]: Command::get_matches_from() + /// [`Command::try_get_matches`]: Command::try_get_matches() + /// [`Error::exit`]: crate::Error::exit() + /// [`std::process::exit`]: std::process::exit() + /// [`clap::Error`]: crate::Error + /// [`Error::exit`]: crate::Error::exit() + /// [`kind`]: crate::Error + /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp + /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion + /// [`clap::Result`]: Result + pub fn try_get_matches_from(mut self, itr: I) -> ClapResult + where + I: IntoIterator, + T: Into + Clone, + { + self.try_get_matches_from_mut(itr) + } + + /// Parse the specified arguments, returning a [`clap::Result`] on failure. + /// + /// Like [`Command::try_get_matches_from`] but doesn't consume the `Command`. + /// + /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are + /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] + /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or + /// perform a [`std::process::exit`] yourself. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`Command::no_binary_name`] is used. + /// + /// # Panics + /// + /// If contradictory arguments or settings exist. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let mut cmd = Command::new("myprog"); + /// // Args and options go here... + /// let matches = cmd.try_get_matches_from_mut(arg_vec) + /// .unwrap_or_else(|e| e.exit()); + /// ``` + /// [`Command::try_get_matches_from`]: Command::try_get_matches_from() + /// [`clap::Result`]: Result + /// [`clap::Error`]: crate::Error + /// [`kind`]: crate::Error + pub fn try_get_matches_from_mut(&mut self, itr: I) -> ClapResult + where + I: IntoIterator, + T: Into + Clone, + { + let mut raw_args = clap_lex::RawArgs::new(itr.into_iter()); + let mut cursor = raw_args.cursor(); + + if self.settings.is_set(AppSettings::Multicall) { + if let Some(argv0) = raw_args.next_os(&mut cursor) { + let argv0 = Path::new(&argv0); + if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) { + // Stop borrowing command so we can get another mut ref to it. + let command = command.to_owned(); + debug!( + "Command::try_get_matches_from_mut: Parsed command {} from argv", + command + ); + + debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it"); + raw_args.insert(&cursor, [&command]); + debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name"); + self.name = "".into(); + self.bin_name = None; + return self._do_parse(&mut raw_args, cursor); + } + } + }; + + // Get the name of the program (argument 1 of env::args()) and determine the + // actual file + // that was used to execute the program. This is because a program called + // ./target/release/my_prog -a + // will have two arguments, './target/release/my_prog', '-a' but we don't want + // to display + // the full path when displaying help messages and such + if !self.settings.is_set(AppSettings::NoBinaryName) { + if let Some(name) = raw_args.next_os(&mut cursor) { + let p = Path::new(name); + + if let Some(f) = p.file_name() { + if let Some(s) = f.to_str() { + if self.bin_name.is_none() { + self.bin_name = Some(s.to_owned()); + } + } + } + } + } + + self._do_parse(&mut raw_args, cursor) + } + + /// Prints the short help message (`-h`) to [`io::stdout()`]. + /// + /// See also [`Command::print_long_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// let mut cmd = Command::new("myprog"); + /// cmd.print_help(); + /// ``` + /// [`io::stdout()`]: std::io::stdout() + pub fn print_help(&mut self) -> io::Result<()> { + self._build_self(false); + let color = self.color_help(); + + let mut styled = StyledStr::new(); + let usage = Usage::new(self); + write_help(&mut styled, self, &usage, false); + + let c = Colorizer::new(Stream::Stdout, color).with_content(styled); + c.print() + } + + /// Prints the long help message (`--help`) to [`io::stdout()`]. + /// + /// See also [`Command::print_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// let mut cmd = Command::new("myprog"); + /// cmd.print_long_help(); + /// ``` + /// [`io::stdout()`]: std::io::stdout() + /// [`BufWriter`]: std::io::BufWriter + /// [`-h` (short)]: Arg::help() + /// [`--help` (long)]: Arg::long_help() + pub fn print_long_help(&mut self) -> io::Result<()> { + self._build_self(false); + let color = self.color_help(); + + let mut styled = StyledStr::new(); + let usage = Usage::new(self); + write_help(&mut styled, self, &usage, true); + + let c = Colorizer::new(Stream::Stdout, color).with_content(styled); + c.print() + } + + /// Render the short help message (`-h`) to a [`StyledStr`] + /// + /// See also [`Command::render_long_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let mut cmd = Command::new("myprog"); + /// let mut out = io::stdout(); + /// let help = cmd.render_help(); + /// println!("{}", help); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-h` (short)]: Arg::help() + /// [`--help` (long)]: Arg::long_help() + pub fn render_help(&mut self) -> StyledStr { + self._build_self(false); + + let mut styled = StyledStr::new(); + let usage = Usage::new(self); + write_help(&mut styled, self, &usage, false); + styled + } + + /// Render the long help message (`--help`) to a [`StyledStr`]. + /// + /// See also [`Command::render_help`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let mut cmd = Command::new("myprog"); + /// let mut out = io::stdout(); + /// let help = cmd.render_long_help(); + /// println!("{}", help); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-h` (short)]: Arg::help() + /// [`--help` (long)]: Arg::long_help() + pub fn render_long_help(&mut self) -> StyledStr { + self._build_self(false); + + let mut styled = StyledStr::new(); + let usage = Usage::new(self); + write_help(&mut styled, self, &usage, true); + styled + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Command::render_help`") + )] + pub fn write_help(&mut self, w: &mut W) -> io::Result<()> { + self._build_self(false); + + let mut styled = StyledStr::new(); + let usage = Usage::new(self); + write_help(&mut styled, self, &usage, false); + ok!(write!(w, "{}", styled)); + w.flush() + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Command::render_long_help`") + )] + pub fn write_long_help(&mut self, w: &mut W) -> io::Result<()> { + self._build_self(false); + + let mut styled = StyledStr::new(); + let usage = Usage::new(self); + write_help(&mut styled, self, &usage, true); + ok!(write!(w, "{}", styled)); + w.flush() + } + + /// Version message rendered as if the user ran `-V`. + /// + /// See also [`Command::render_long_version`]. + /// + /// ### Coloring + /// + /// This function does not try to color the message nor it inserts any [ANSI escape codes]. + /// + /// ### Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let cmd = Command::new("myprog"); + /// println!("{}", cmd.render_version()); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-V` (short)]: Command::version() + /// [`--version` (long)]: Command::long_version() + /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code + pub fn render_version(&self) -> String { + self._render_version(false) + } + + /// Version message rendered as if the user ran `--version`. + /// + /// See also [`Command::render_version`]. + /// + /// ### Coloring + /// + /// This function does not try to color the message nor it inserts any [ANSI escape codes]. + /// + /// ### Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let cmd = Command::new("myprog"); + /// println!("{}", cmd.render_long_version()); + /// ``` + /// [`io::Write`]: std::io::Write + /// [`-V` (short)]: Command::version() + /// [`--version` (long)]: Command::long_version() + /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code + pub fn render_long_version(&self) -> String { + self._render_version(true) + } + + /// Usage statement + /// + /// ### Examples + /// + /// ```rust + /// # use clap::Command; + /// use std::io; + /// let mut cmd = Command::new("myprog"); + /// println!("{}", cmd.render_usage()); + /// ``` + pub fn render_usage(&mut self) -> StyledStr { + self.render_usage_().unwrap_or_default() + } + + pub(crate) fn render_usage_(&mut self) -> Option { + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing incase we run into a subcommand + self._build_self(false); + + Usage::new(self).create_usage_with_title(&[]) + } +} + +/// # Application-wide Settings +/// +/// These settings will apply to the top-level command and all subcommands, by default. Some +/// settings can be overridden in subcommands. +impl Command { + /// Specifies that the parser should not assume the first argument passed is the binary name. + /// + /// This is normally the case when using a "daemon" style mode. For shells / REPLs, see + /// [`Command::multicall`][Command::multicall]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let m = Command::new("myprog") + /// .no_binary_name(true) + /// .arg(arg!( ... "commands to run")) + /// .get_matches_from(vec!["command", "set"]); + /// + /// let cmds: Vec<_> = m.get_many::("cmd").unwrap().collect(); + /// assert_eq!(cmds, ["command", "set"]); + /// ``` + /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut() + #[inline] + pub fn no_binary_name(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::NoBinaryName) + } else { + self.unset_global_setting(AppSettings::NoBinaryName) + } + } + + /// Try not to fail on parse errors, like missing option values. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, arg}; + /// let cmd = Command::new("cmd") + /// .ignore_errors(true) + /// .arg(arg!(-c --config "Sets a custom config file")) + /// .arg(arg!(-x --stuff "Sets a custom stuff file")) + /// .arg(arg!(f: -f "Flag")); + /// + /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]); + /// + /// assert!(r.is_ok(), "unexpected error: {:?}", r); + /// let m = r.unwrap(); + /// assert_eq!(m.get_one::("config").unwrap(), "file"); + /// assert!(m.get_flag("f")); + /// assert_eq!(m.get_one::("stuff"), None); + /// ``` + #[inline] + pub fn ignore_errors(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::IgnoreErrors) + } else { + self.unset_global_setting(AppSettings::IgnoreErrors) + } + } + + /// Replace prior occurrences of arguments rather than error + /// + /// For any argument that would conflict with itself by default (e.g. + /// [`ArgAction::Set`][ArgAction::Set], it will now override itself. + /// + /// This is the equivalent to saying the `foo` arg using [`Arg::overrides_with("foo")`] for all + /// defined arguments. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// [`Arg::overrides_with("foo")`]: crate::Arg::overrides_with() + #[inline] + pub fn args_override_self(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::AllArgsOverrideSelf) + } else { + self.unset_global_setting(AppSettings::AllArgsOverrideSelf) + } + } + + /// Disables the automatic delimiting of values after `--` or when [`Command::trailing_var_arg`] + /// was used. + /// + /// **NOTE:** The same thing can be done manually by setting the final positional argument to + /// [`Arg::value_delimiter(None)`]. Using this setting is safer, because it's easier to locate + /// when making changes. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .dont_delimit_trailing_values(true) + /// .get_matches(); + /// ``` + /// + /// [`Arg::value_delimiter(None)`]: crate::Arg::value_delimiter() + #[inline] + pub fn dont_delimit_trailing_values(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DontDelimitTrailingValues) + } else { + self.unset_global_setting(AppSettings::DontDelimitTrailingValues) + } + } + + /// Sets when to color output. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// **NOTE:** Default behaviour is [`ColorChoice::Auto`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, ColorChoice}; + /// Command::new("myprog") + /// .color(ColorChoice::Never) + /// .get_matches(); + /// ``` + /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto + #[cfg(feature = "color")] + #[inline] + #[must_use] + pub fn color(self, color: ColorChoice) -> Self { + let cmd = self + .unset_global_setting(AppSettings::ColorAuto) + .unset_global_setting(AppSettings::ColorAlways) + .unset_global_setting(AppSettings::ColorNever); + match color { + ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto), + ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways), + ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever), + } + } + + /// Sets the terminal width at which to wrap help messages. + /// + /// Using `0` will ignore terminal widths and use source formatting. + /// + /// Defaults to current terminal width when `wrap_help` feature flag is enabled. If the flag + /// is disabled or it cannot be determined, the default is 100. + /// + /// **NOTE:** This setting applies globally and *not* on a per-command basis. + /// + /// **NOTE:** This requires the [`wrap_help` feature][crate::_features] + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .term_width(80) + /// # ; + /// ``` + #[inline] + #[must_use] + #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))] + pub fn term_width(mut self, width: usize) -> Self { + self.term_w = Some(width); + self + } + + /// Limit the line length for wrapping help when using the current terminal's width. + /// + /// This only applies when [`term_width`][Command::term_width] is unset so that the current + /// terminal's width will be used. See [`Command::term_width`] for more details. + /// + /// Using `0` will ignore terminal widths and use source formatting (default). + /// + /// **NOTE:** This setting applies globally and *not* on a per-command basis. + /// + /// **NOTE:** This requires the [`wrap_help` feature][crate::_features] + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .max_term_width(100) + /// # ; + /// ``` + #[inline] + #[must_use] + #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))] + pub fn max_term_width(mut self, w: usize) -> Self { + self.max_w = Some(w); + self + } + + /// Disables `-V` and `--version` flag. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, error::ErrorKind}; + /// let res = Command::new("myprog") + /// .disable_version_flag(true) + /// .try_get_matches_from(vec![ + /// "myprog", "-V" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + #[inline] + pub fn disable_version_flag(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DisableVersionFlag) + } else { + self.unset_global_setting(AppSettings::DisableVersionFlag) + } + } + + /// Specifies to use the version of the current command for all [`subcommands`]. + /// + /// Defaults to `false`; subcommands have independent version strings from their parents. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .version("v1.1") + /// .propagate_version(true) + /// .subcommand(Command::new("test")) + /// .get_matches(); + /// // running `$ myprog test --version` will display + /// // "myprog-test v1.1" + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + #[inline] + pub fn propagate_version(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::PropagateVersion) + } else { + self.unset_global_setting(AppSettings::PropagateVersion) + } + } + + /// Places the help string for all arguments and subcommands on the line after them. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .next_line_help(true) + /// .get_matches(); + /// ``` + #[inline] + pub fn next_line_help(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::NextLineHelp) + } else { + self.unset_global_setting(AppSettings::NextLineHelp) + } + } + + /// Disables `-h` and `--help` flag. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, error::ErrorKind}; + /// let res = Command::new("myprog") + /// .disable_help_flag(true) + /// .try_get_matches_from(vec![ + /// "myprog", "-h" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// ``` + #[inline] + pub fn disable_help_flag(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DisableHelpFlag) + } else { + self.unset_global_setting(AppSettings::DisableHelpFlag) + } + } + + /// Disables the `help` [`subcommand`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, error::ErrorKind}; + /// let res = Command::new("myprog") + /// .disable_help_subcommand(true) + /// // Normally, creating a subcommand causes a `help` subcommand to automatically + /// // be generated as well + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", "help" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidSubcommand); + /// ``` + /// + /// [`subcommand`]: crate::Command::subcommand() + #[inline] + pub fn disable_help_subcommand(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DisableHelpSubcommand) + } else { + self.unset_global_setting(AppSettings::DisableHelpSubcommand) + } + } + + /// Disables colorized help messages. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .disable_colored_help(true) + /// .get_matches(); + /// ``` + #[inline] + pub fn disable_colored_help(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::DisableColoredHelp) + } else { + self.unset_global_setting(AppSettings::DisableColoredHelp) + } + } + + /// Panic if help descriptions are omitted. + /// + /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at + /// compile-time with `#![deny(missing_docs)]` + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .help_expected(true) + /// .arg( + /// Arg::new("foo").help("It does foo stuff") + /// // As required via `help_expected`, a help message was supplied + /// ) + /// # .get_matches(); + /// ``` + /// + /// # Panics + /// + /// ```rust,no_run + /// # use clap::{Command, Arg}; + /// Command::new("myapp") + /// .help_expected(true) + /// .arg( + /// Arg::new("foo") + /// // Someone forgot to put .about("...") here + /// // Since the setting `help_expected` is activated, this will lead to + /// // a panic (if you are in debug mode) + /// ) + /// # .get_matches(); + ///``` + #[inline] + pub fn help_expected(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::HelpExpected) + } else { + self.unset_global_setting(AppSettings::HelpExpected) + } + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "This is now the default") + )] + pub fn dont_collapse_args_in_usage(self, _yes: bool) -> Self { + self + } + + /// Tells `clap` *not* to print possible values when displaying help information. + /// + /// This can be useful if there are many values, or they are explained elsewhere. + /// + /// To set this per argument, see + /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values]. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + #[inline] + pub fn hide_possible_values(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::HidePossibleValues) + } else { + self.unset_global_setting(AppSettings::HidePossibleValues) + } + } + + /// Allow partial matches of long arguments or their [aliases]. + /// + /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and + /// `--test`. + /// + /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match + /// `--te` to `--test` there could not also be another argument or alias `--temp` because both + /// start with `--te` + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// [aliases]: crate::Command::aliases() + #[inline] + pub fn infer_long_args(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::InferLongArgs) + } else { + self.unset_global_setting(AppSettings::InferLongArgs) + } + } + + /// Allow partial matches of [subcommand] names and their [aliases]. + /// + /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and + /// `test`. + /// + /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te` + /// to `test` there could not also be a subcommand or alias `temp` because both start with `te` + /// + /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when + /// designing CLIs which allow inferred subcommands and have potential positional/free + /// arguments whose values could start with the same characters as subcommands. If this is the + /// case, it's recommended to use settings such as [`Command::args_conflicts_with_subcommands`] in + /// conjunction with this setting. + /// + /// **NOTE:** This choice is propagated to all child subcommands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let m = Command::new("prog") + /// .infer_subcommands(true) + /// .subcommand(Command::new("test")) + /// .get_matches_from(vec![ + /// "prog", "te" + /// ]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// + /// [subcommand]: crate::Command::subcommand() + /// [positional/free arguments]: crate::Arg::index() + /// [aliases]: crate::Command::aliases() + #[inline] + pub fn infer_subcommands(self, yes: bool) -> Self { + if yes { + self.global_setting(AppSettings::InferSubcommands) + } else { + self.unset_global_setting(AppSettings::InferSubcommands) + } + } +} + +/// # Command-specific Settings +/// +/// These apply only to the current command and are not inherited by subcommands. +impl Command { + /// (Re)Sets the program's name. + /// + /// See [`Command::new`] for more details. + /// + /// # Examples + /// + /// ```ignore + /// let cmd = clap::command!() + /// .name("foo"); + /// + /// // continued logic goes here, such as `cmd.get_matches()` etc. + /// ``` + #[must_use] + pub fn name(mut self, name: impl Into) -> Self { + self.name = name.into(); + self + } + + /// Overrides the runtime-determined name of the binary for help and error messages. + /// + /// This should only be used when absolutely necessary, such as when the binary name for your + /// application is misleading, or perhaps *not* how the user should invoke your program. + /// + /// **Pro-tip:** When building things such as third party `cargo` + /// subcommands, this setting **should** be used! + /// + /// **NOTE:** This *does not* change or set the name of the binary file on + /// disk. It only changes what clap thinks the name is for the purposes of + /// error or help messages. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("My Program") + /// .bin_name("my_binary") + /// # ; + /// ``` + #[must_use] + pub fn bin_name(mut self, name: impl IntoResettable) -> Self { + self.bin_name = name.into_resettable().into_option(); + self + } + + /// Overrides the runtime-determined display name of the program for help and error messages. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("My Program") + /// .display_name("my_program") + /// # ; + /// ``` + #[must_use] + pub fn display_name(mut self, name: impl IntoResettable) -> Self { + self.display_name = name.into_resettable().into_option(); + self + } + + /// Sets the author(s) for the help message. + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to + /// automatically set your application's author(s) to the same thing as your + /// crate at compile time. + /// + /// **NOTE:** A custom [`help_template`][Command::help_template] is needed for author to show + /// up. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .author("Me, me@mymain.com") + /// # ; + /// ``` + #[must_use] + pub fn author(mut self, author: impl IntoResettable) -> Self { + self.author = author.into_resettable().into_option(); + self + } + + /// Sets the program's description for the short help (`-h`). + /// + /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`. + /// + /// **NOTE:** Only `Command::about` (short format) is used in completion + /// script generation in order to be concise. + /// + /// See also [`crate_description!`](crate::crate_description!). + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .about("Does really amazing things for great people") + /// # ; + /// ``` + #[must_use] + pub fn about(mut self, about: impl IntoResettable) -> Self { + self.about = about.into_resettable().into_option(); + self + } + + /// Sets the program's description for the long help (`--help`). + /// + /// If [`Command::about`] is not specified, this message will be displayed for `-h`. + /// + /// **NOTE:** Only [`Command::about`] (short format) is used in completion + /// script generation in order to be concise. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .long_about( + /// "Does really amazing things to great people. Now let's talk a little + /// more in depth about how this subcommand really works. It may take about + /// a few lines of text, but that's ok!") + /// # ; + /// ``` + /// [`Command::about`]: Command::about() + #[must_use] + pub fn long_about(mut self, long_about: impl IntoResettable) -> Self { + self.long_about = long_about.into_resettable().into_option(); + self + } + + /// Free-form help text for after auto-generated short help (`-h`). + /// + /// This is often used to describe how to use the arguments, caveats to be noted, or license + /// and contact information. + /// + /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .after_help("Does really amazing things for great people... but be careful with -R!") + /// # ; + /// ``` + /// + #[must_use] + pub fn after_help(mut self, help: impl IntoResettable) -> Self { + self.after_help = help.into_resettable().into_option(); + self + } + + /// Free-form help text for after auto-generated long help (`--help`). + /// + /// This is often used to describe how to use the arguments, caveats to be noted, or license + /// and contact information. + /// + /// If [`Command::after_help`] is not specified, this message will be displayed for `-h`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .after_long_help("Does really amazing things to great people... but be careful with -R, \ + /// like, for real, be careful with this!") + /// # ; + /// ``` + #[must_use] + pub fn after_long_help(mut self, help: impl IntoResettable) -> Self { + self.after_long_help = help.into_resettable().into_option(); + self + } + + /// Free-form help text for before auto-generated short help (`-h`). + /// + /// This is often used for header, copyright, or license information. + /// + /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .before_help("Some info I'd like to appear before the help info") + /// # ; + /// ``` + #[must_use] + pub fn before_help(mut self, help: impl IntoResettable) -> Self { + self.before_help = help.into_resettable().into_option(); + self + } + + /// Free-form help text for before auto-generated long help (`--help`). + /// + /// This is often used for header, copyright, or license information. + /// + /// If [`Command::before_help`] is not specified, this message will be displayed for `-h`. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .before_long_help("Some verbose and long info I'd like to appear before the help info") + /// # ; + /// ``` + #[must_use] + pub fn before_long_help(mut self, help: impl IntoResettable) -> Self { + self.before_long_help = help.into_resettable().into_option(); + self + } + + /// Sets the version for the short version (`-V`) and help messages. + /// + /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`. + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to + /// automatically set your application's version to the same thing as your + /// crate at compile time. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .version("v0.1.24") + /// # ; + /// ``` + #[must_use] + pub fn version(mut self, ver: impl IntoResettable) -> Self { + self.version = ver.into_resettable().into_option(); + self + } + + /// Sets the version for the long version (`--version`) and help messages. + /// + /// If [`Command::version`] is not specified, this message will be displayed for `-V`. + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to + /// automatically set your application's version to the same thing as your + /// crate at compile time. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .long_version( + /// "v0.1.24 + /// commit: abcdef89726d + /// revision: 123 + /// release: 2 + /// binary: myprog") + /// # ; + /// ``` + #[must_use] + pub fn long_version(mut self, ver: impl IntoResettable) -> Self { + self.long_version = ver.into_resettable().into_option(); + self + } + + /// Overrides the `clap` generated usage string for help and error messages. + /// + /// **NOTE:** Using this setting disables `clap`s "context-aware" usage + /// strings. After this setting is set, this will be *the only* usage string + /// displayed to the user! + /// + /// **NOTE:** Multiple usage lines may be present in the usage argument, but + /// some rules need to be followed to ensure the usage lines are formatted + /// correctly by the default help formatter: + /// + /// - Do not indent the first usage line. + /// - Indent all subsequent usage lines with seven spaces. + /// - The last line must not end with a newline. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .override_usage("myapp [-clDas] ") + /// # ; + /// ``` + /// + /// Or for multiple usage lines: + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .override_usage( + /// "myapp -X [-a] [-b] \n \ + /// myapp -Y [-c] \n \ + /// myapp -Z [-d|-e]" + /// ) + /// # ; + /// ``` + /// + /// [`ArgMatches::usage`]: ArgMatches::usage() + #[must_use] + pub fn override_usage(mut self, usage: impl IntoResettable) -> Self { + self.usage_str = usage.into_resettable().into_option(); + self + } + + /// Overrides the `clap` generated help message (both `-h` and `--help`). + /// + /// This should only be used when the auto-generated message does not suffice. + /// + /// **NOTE:** This **only** replaces the help message for the current + /// command, meaning if you are using subcommands, those help messages will + /// still be auto-generated unless you specify a [`Command::override_help`] for + /// them as well. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myapp") + /// .override_help("myapp v1.0\n\ + /// Does awesome things\n\ + /// (C) me@mail.com\n\n\ + /// + /// Usage: myapp \n\n\ + /// + /// Options:\n\ + /// -h, --help Display this message\n\ + /// -V, --version Display version info\n\ + /// -s Do something with stuff\n\ + /// -v Be verbose\n\n\ + /// + /// Commands:\n\ + /// help Print this message\n\ + /// work Do some work") + /// # ; + /// ``` + #[must_use] + pub fn override_help(mut self, help: impl IntoResettable) -> Self { + self.help_str = help.into_resettable().into_option(); + self + } + + /// Sets the help template to be used, overriding the default format. + /// + /// **NOTE:** The template system is by design very simple. Therefore, the + /// tags have to be written in the lowercase and without spacing. + /// + /// Tags are given inside curly brackets. + /// + /// Valid tags are: + /// + /// * `{name}` - Display name for the (sub-)command. + /// * `{bin}` - Binary name.(deprecated) + /// * `{version}` - Version number. + /// * `{author}` - Author information. + /// * `{author-with-newline}` - Author followed by `\n`. + /// * `{author-section}` - Author preceded and followed by `\n`. + /// * `{about}` - General description (from [`Command::about`] or + /// [`Command::long_about`]). + /// * `{about-with-newline}` - About followed by `\n`. + /// * `{about-section}` - About preceded and followed by '\n'. + /// * `{usage-heading}` - Automatically generated usage heading. + /// * `{usage}` - Automatically generated or given usage string. + /// * `{all-args}` - Help for all arguments (options, flags, positional + /// arguments, and subcommands) including titles. + /// * `{options}` - Help for options. + /// * `{positionals}` - Help for positional arguments. + /// * `{subcommands}` - Help for subcommands. + /// * `{tab}` - Standard tab sized used within clap + /// * `{after-help}` - Help from [`Command::after_help`] or [`Command::after_long_help`]. + /// * `{before-help}` - Help from [`Command::before_help`] or [`Command::before_long_help`]. + /// + /// # Examples + /// + /// For a very brief help: + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .version("1.0") + /// .help_template("{name} ({version}) - {usage}") + /// # ; + /// ``` + /// + /// For showing more application context: + /// + /// ```no_run + /// # use clap::Command; + /// Command::new("myprog") + /// .version("1.0") + /// .help_template("\ + /// {before-help}{name} {version} + /// {author-with-newline}{about-with-newline} + /// {usage-heading} {usage} + /// + /// {all-args}{after-help} + /// ") + /// # ; + /// ``` + /// [`Command::about`]: Command::about() + /// [`Command::long_about`]: Command::long_about() + /// [`Command::after_help`]: Command::after_help() + /// [`Command::after_long_help`]: Command::after_long_help() + /// [`Command::before_help`]: Command::before_help() + /// [`Command::before_long_help`]: Command::before_long_help() + #[must_use] + #[cfg(feature = "help")] + pub fn help_template(mut self, s: impl IntoResettable) -> Self { + self.template = s.into_resettable().into_option(); + self + } + + #[inline] + #[must_use] + pub(crate) fn setting(mut self, setting: F) -> Self + where + F: Into, + { + self.settings.insert(setting.into()); + self + } + + #[inline] + #[must_use] + pub(crate) fn unset_setting(mut self, setting: F) -> Self + where + F: Into, + { + self.settings.remove(setting.into()); + self + } + + #[inline] + #[must_use] + pub(crate) fn global_setting(mut self, setting: AppSettings) -> Self { + self.settings.set(setting); + self.g_settings.set(setting); + self + } + + #[inline] + #[must_use] + pub(crate) fn unset_global_setting(mut self, setting: AppSettings) -> Self { + self.settings.unset(setting); + self.g_settings.unset(setting); + self + } + + /// Set the default section heading for future args. + /// + /// This will be used for any arg that hasn't had [`Arg::help_heading`] called. + /// + /// This is useful if the default `Options` or `Arguments` headings are + /// not specific enough for one's use case. + /// + /// For subcommands, see [`Command::subcommand_help_heading`] + /// + /// [`Command::arg`]: Command::arg() + /// [`Arg::help_heading`]: crate::Arg::help_heading() + #[inline] + #[must_use] + pub fn next_help_heading(mut self, heading: impl IntoResettable) -> Self { + self.current_help_heading = heading.into_resettable().into_option(); + self + } + + /// Change the starting value for assigning future display orders for ags. + /// + /// This will be used for any arg that hasn't had [`Arg::display_order`] called. + #[inline] + #[must_use] + pub fn next_display_order(mut self, disp_ord: impl IntoResettable) -> Self { + self.current_disp_ord = disp_ord.into_resettable().into_option(); + self + } + + /// Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands. + /// + /// **Note:** This is gated behind [`unstable-replace`](https://github.com/clap-rs/clap/issues/2836) + /// + /// When this method is used, `name` is removed from the CLI, and `target` + /// is inserted in its place. Parsing continues as if the user typed + /// `target` instead of `name`. + /// + /// This can be used to create "shortcuts" for subcommands, or if a + /// particular argument has the semantic meaning of several other specific + /// arguments and values. + /// + /// # Examples + /// + /// We'll start with the "subcommand short" example. In this example, let's + /// assume we have a program with a subcommand `module` which can be invoked + /// via `cmd module`. Now let's also assume `module` also has a subcommand + /// called `install` which can be invoked `cmd module install`. If for some + /// reason users needed to be able to reach `cmd module install` via the + /// short-hand `cmd install`, we'd have several options. + /// + /// We *could* create another sibling subcommand to `module` called + /// `install`, but then we would need to manage another subcommand and manually + /// dispatch to `cmd module install` handling code. This is error prone and + /// tedious. + /// + /// We could instead use [`Command::replace`] so that, when the user types `cmd + /// install`, `clap` will replace `install` with `module install` which will + /// end up getting parsed as if the user typed the entire incantation. + /// + /// ```rust + /// # use clap::Command; + /// let m = Command::new("cmd") + /// .subcommand(Command::new("module") + /// .subcommand(Command::new("install"))) + /// .replace("install", &["module", "install"]) + /// .get_matches_from(vec!["cmd", "install"]); + /// + /// assert!(m.subcommand_matches("module").is_some()); + /// assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some()); + /// ``` + /// + /// Now let's show an argument example! + /// + /// Let's assume we have an application with two flags `--save-context` and + /// `--save-runtime`. But often users end up needing to do *both* at the + /// same time. We can add a third flag `--save-all` which semantically means + /// the same thing as `cmd --save-context --save-runtime`. To implement that, + /// we have several options. + /// + /// We could create this third argument and manually check if that argument + /// and in our own consumer code handle the fact that both `--save-context` + /// and `--save-runtime` *should* have been used. But again this is error + /// prone and tedious. If we had code relying on checking `--save-context` + /// and we forgot to update that code to *also* check `--save-all` it'd mean + /// an error! + /// + /// Luckily we can use [`Command::replace`] so that when the user types + /// `--save-all`, `clap` will replace that argument with `--save-context + /// --save-runtime`, and parsing will continue like normal. Now all our code + /// that was originally checking for things like `--save-context` doesn't + /// need to change! + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("cmd") + /// .arg(Arg::new("save-context") + /// .long("save-context") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("save-runtime") + /// .long("save-runtime") + /// .action(ArgAction::SetTrue)) + /// .replace("--save-all", &["--save-context", "--save-runtime"]) + /// .get_matches_from(vec!["cmd", "--save-all"]); + /// + /// assert!(m.get_flag("save-context")); + /// assert!(m.get_flag("save-runtime")); + /// ``` + /// + /// This can also be used with options, for example if our application with + /// `--save-*` above also had a `--format=TYPE` option. Let's say it + /// accepted `txt` or `json` values. However, when `--save-all` is used, + /// only `--format=json` is allowed, or valid. We could change the example + /// above to enforce this: + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let m = Command::new("cmd") + /// .arg(Arg::new("save-context") + /// .long("save-context") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("save-runtime") + /// .long("save-runtime") + /// .action(ArgAction::SetTrue)) + /// .arg(Arg::new("format") + /// .long("format") + /// .action(ArgAction::Set) + /// .value_parser(["txt", "json"])) + /// .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"]) + /// .get_matches_from(vec!["cmd", "--save-all"]); + /// + /// assert!(m.get_flag("save-context")); + /// assert!(m.get_flag("save-runtime")); + /// assert_eq!(m.get_one::("format").unwrap(), "json"); + /// ``` + /// + /// [`Command::replace`]: Command::replace() + #[inline] + #[cfg(feature = "unstable-replace")] + #[must_use] + pub fn replace( + mut self, + name: impl Into, + target: impl IntoIterator>, + ) -> Self { + self.replacers + .insert(name.into(), target.into_iter().map(Into::into).collect()); + self + } + + /// Exit gracefully if no arguments are present (e.g. `$ myprog`). + /// + /// **NOTE:** [`subcommands`] count as arguments + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command}; + /// Command::new("myprog") + /// .arg_required_else_help(true); + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + /// [`Arg::default_value`]: crate::Arg::default_value() + #[inline] + pub fn arg_required_else_help(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::ArgRequiredElseHelp) + } else { + self.unset_setting(AppSettings::ArgRequiredElseHelp) + } + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_hyphen_values`") + )] + pub fn allow_hyphen_values(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowHyphenValues) + } else { + self.unset_setting(AppSettings::AllowHyphenValues) + } + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_negative_numbers`") + )] + pub fn allow_negative_numbers(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowNegativeNumbers) + } else { + self.unset_setting(AppSettings::AllowNegativeNumbers) + } + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Arg::trailing_var_arg`") + )] + pub fn trailing_var_arg(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::TrailingVarArg) + } else { + self.unset_setting(AppSettings::TrailingVarArg) + } + } + + /// Allows one to implement two styles of CLIs where positionals can be used out of order. + /// + /// The first example is a CLI where the second to last positional argument is optional, but + /// the final positional argument is required. Such as `$ prog [optional] ` where one + /// of the two following usages is allowed: + /// + /// * `$ prog [optional] ` + /// * `$ prog ` + /// + /// This would otherwise not be allowed. This is useful when `[optional]` has a default value. + /// + /// **Note:** when using this style of "missing positionals" the final positional *must* be + /// [required] if `--` will not be used to skip to the final positional argument. + /// + /// **Note:** This style also only allows a single positional argument to be "skipped" without + /// the use of `--`. To skip more than one, see the second example. + /// + /// The second example is when one wants to skip multiple optional positional arguments, and use + /// of the `--` operator is OK (but not required if all arguments will be specified anyways). + /// + /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where + /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments). + /// + /// With this setting the following invocations are posisble: + /// + /// * `$ prog foo bar baz1 baz2 baz3` + /// * `$ prog foo -- baz1 baz2 baz3` + /// * `$ prog -- baz1 baz2 baz3` + /// + /// # Examples + /// + /// Style number one from above: + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_missing_positional(true) + /// .arg(Arg::new("arg1")) + /// .arg(Arg::new("arg2") + /// .required(true)) + /// .get_matches_from(vec![ + /// "prog", "other" + /// ]); + /// + /// assert_eq!(m.get_one::("arg1"), None); + /// assert_eq!(m.get_one::("arg2").unwrap(), "other"); + /// ``` + /// + /// Now the same example, but using a default value for the first optional positional argument + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_missing_positional(true) + /// .arg(Arg::new("arg1") + /// .default_value("something")) + /// .arg(Arg::new("arg2") + /// .required(true)) + /// .get_matches_from(vec![ + /// "prog", "other" + /// ]); + /// + /// assert_eq!(m.get_one::("arg1").unwrap(), "something"); + /// assert_eq!(m.get_one::("arg2").unwrap(), "other"); + /// ``` + /// + /// Style number two from above: + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_missing_positional(true) + /// .arg(Arg::new("foo")) + /// .arg(Arg::new("bar")) + /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..)) + /// .get_matches_from(vec![ + /// "prog", "foo", "bar", "baz1", "baz2", "baz3" + /// ]); + /// + /// assert_eq!(m.get_one::("foo").unwrap(), "foo"); + /// assert_eq!(m.get_one::("bar").unwrap(), "bar"); + /// assert_eq!(m.get_many::("baz").unwrap().collect::>(), &["baz1", "baz2", "baz3"]); + /// ``` + /// + /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator. + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_missing_positional(true) + /// .arg(Arg::new("foo")) + /// .arg(Arg::new("bar")) + /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..)) + /// .get_matches_from(vec![ + /// "prog", "--", "baz1", "baz2", "baz3" + /// ]); + /// + /// assert_eq!(m.get_one::("foo"), None); + /// assert_eq!(m.get_one::("bar"), None); + /// assert_eq!(m.get_many::("baz").unwrap().collect::>(), &["baz1", "baz2", "baz3"]); + /// ``` + /// + /// [required]: crate::Arg::required() + #[inline] + pub fn allow_missing_positional(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowMissingPositional) + } else { + self.unset_setting(AppSettings::AllowMissingPositional) + } + } +} + +/// # Subcommand-specific Settings +impl Command { + /// Sets the short version of the subcommand flag without the preceding `-`. + /// + /// Allows the subcommand to be used as if it were an [`Arg::short`]. + /// + /// # Examples + /// + /// ``` + /// # use clap::{Command, Arg, ArgAction}; + /// let matches = Command::new("pacman") + /// .subcommand( + /// Command::new("sync").short_flag('S').arg( + /// Arg::new("search") + /// .short('s') + /// .long("search") + /// .action(ArgAction::SetTrue) + /// .help("search remote repositories for matching strings"), + /// ), + /// ) + /// .get_matches_from(vec!["pacman", "-Ss"]); + /// + /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); + /// let sync_matches = matches.subcommand_matches("sync").unwrap(); + /// assert!(sync_matches.get_flag("search")); + /// ``` + /// [`Arg::short`]: Arg::short() + #[must_use] + pub fn short_flag(mut self, short: impl IntoResettable) -> Self { + self.short_flag = short.into_resettable().into_option(); + self + } + + /// Sets the long version of the subcommand flag without the preceding `--`. + /// + /// Allows the subcommand to be used as if it were an [`Arg::long`]. + /// + /// **NOTE:** Any leading `-` characters will be stripped. + /// + /// # Examples + /// + /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading + /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however, + /// will *not* be stripped (i.e. `sync-file` is allowed). + /// + /// ``` + /// # use clap::{Command, Arg, ArgAction}; + /// let matches = Command::new("pacman") + /// .subcommand( + /// Command::new("sync").long_flag("sync").arg( + /// Arg::new("search") + /// .short('s') + /// .long("search") + /// .action(ArgAction::SetTrue) + /// .help("search remote repositories for matching strings"), + /// ), + /// ) + /// .get_matches_from(vec!["pacman", "--sync", "--search"]); + /// + /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); + /// let sync_matches = matches.subcommand_matches("sync").unwrap(); + /// assert!(sync_matches.get_flag("search")); + /// ``` + /// + /// [`Arg::long`]: Arg::long() + #[must_use] + pub fn long_flag(mut self, long: impl Into) -> Self { + self.long_flag = Some(long.into()); + self + } + + /// Sets a hidden alias to this subcommand. + /// + /// This allows the subcommand to be accessed via *either* the original name, or this given + /// alias. This is more efficient and easier than creating multiple hidden subcommands as one + /// only needs to check for the existence of this command, and not all aliased variants. + /// + /// **NOTE:** Aliases defined with this method are *hidden* from the help + /// message. If you're looking for aliases that will be displayed in the help + /// message, see [`Command::visible_alias`]. + /// + /// **NOTE:** When using aliases and checking for the existence of a + /// particular subcommand within an [`ArgMatches`] struct, one only needs to + /// search for the original name and not all aliases. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test") + /// .alias("do-stuff")) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`Command::visible_alias`]: Command::visible_alias() + #[must_use] + pub fn alias(mut self, name: impl IntoResettable) -> Self { + if let Some(name) = name.into_resettable().into_option() { + self.aliases.push((name, false)); + } else { + self.aliases.clear(); + } + self + } + + /// Add an alias, which functions as "hidden" short flag subcommand + /// + /// This will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").short_flag('t') + /// .short_flag_alias('d')) + /// .get_matches_from(vec!["myprog", "-d"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + #[must_use] + pub fn short_flag_alias(mut self, name: impl IntoResettable) -> Self { + if let Some(name) = name.into_resettable().into_option() { + debug_assert!(name != '-', "short alias name cannot be `-`"); + self.short_flag_aliases.push((name, false)); + } else { + self.short_flag_aliases.clear(); + } + self + } + + /// Add an alias, which functions as a "hidden" long flag subcommand. + /// + /// This will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").long_flag("test") + /// .long_flag_alias("testing")) + /// .get_matches_from(vec!["myprog", "--testing"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + #[must_use] + pub fn long_flag_alias(mut self, name: impl IntoResettable) -> Self { + if let Some(name) = name.into_resettable().into_option() { + self.long_flag_aliases.push((name, false)); + } else { + self.long_flag_aliases.clear(); + } + self + } + + /// Sets multiple hidden aliases to this subcommand. + /// + /// This allows the subcommand to be accessed via *either* the original name or any of the + /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands + /// as one only needs to check for the existence of this command and not all aliased variants. + /// + /// **NOTE:** Aliases defined with this method are *hidden* from the help + /// message. If looking for aliases that will be displayed in the help + /// message, see [`Command::visible_aliases`]. + /// + /// **NOTE:** When using aliases and checking for the existence of a + /// particular subcommand within an [`ArgMatches`] struct, one only needs to + /// search for the original name and not all aliases. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test") + /// .aliases(["do-stuff", "do-tests", "tests"])) + /// .arg(Arg::new("input") + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec!["myprog", "do-tests"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`Command::visible_aliases`]: Command::visible_aliases() + #[must_use] + pub fn aliases(mut self, names: impl IntoIterator>) -> Self { + self.aliases + .extend(names.into_iter().map(|n| (n.into(), false))); + self + } + + /// Add aliases, which function as "hidden" short flag subcommands. + /// + /// These will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").short_flag('t') + /// .short_flag_aliases(['a', 'b', 'c'])) + /// .arg(Arg::new("input") + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec!["myprog", "-a"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + #[must_use] + pub fn short_flag_aliases(mut self, names: impl IntoIterator) -> Self { + for s in names { + debug_assert!(s != '-', "short alias name cannot be `-`"); + self.short_flag_aliases.push((s, false)); + } + self + } + + /// Add aliases, which function as "hidden" long flag subcommands. + /// + /// These will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").long_flag("test") + /// .long_flag_aliases(["testing", "testall", "test_all"])) + /// .arg(Arg::new("input") + /// .help("the file to add") + /// .required(false)) + /// .get_matches_from(vec!["myprog", "--testing"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + #[must_use] + pub fn long_flag_aliases(mut self, names: impl IntoIterator>) -> Self { + for s in names { + self = self.long_flag_alias(s) + } + self + } + + /// Sets a visible alias to this subcommand. + /// + /// This allows the subcommand to be accessed via *either* the + /// original name or the given alias. This is more efficient and easier + /// than creating hidden subcommands as one only needs to check for + /// the existence of this command and not all aliased variants. + /// + /// **NOTE:** The alias defined with this method is *visible* from the help + /// message and displayed as if it were just another regular subcommand. If + /// looking for an alias that will not be displayed in the help message, see + /// [`Command::alias`]. + /// + /// **NOTE:** When using aliases and checking for the existence of a + /// particular subcommand within an [`ArgMatches`] struct, one only needs to + /// search for the original name and not all aliases. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test") + /// .visible_alias("do-stuff")) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`Command::alias`]: Command::alias() + #[must_use] + pub fn visible_alias(mut self, name: impl IntoResettable) -> Self { + if let Some(name) = name.into_resettable().into_option() { + self.aliases.push((name, true)); + } else { + self.aliases.clear(); + } + self + } + + /// Add an alias, which functions as "visible" short flag subcommand + /// + /// This will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// See also [`Command::short_flag_alias`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").short_flag('t') + /// .visible_short_flag_alias('d')) + /// .get_matches_from(vec!["myprog", "-d"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`Command::short_flag_alias`]: Command::short_flag_alias() + #[must_use] + pub fn visible_short_flag_alias(mut self, name: impl IntoResettable) -> Self { + if let Some(name) = name.into_resettable().into_option() { + debug_assert!(name != '-', "short alias name cannot be `-`"); + self.short_flag_aliases.push((name, true)); + } else { + self.short_flag_aliases.clear(); + } + self + } + + /// Add an alias, which functions as a "visible" long flag subcommand. + /// + /// This will automatically dispatch as if this subcommand was used. This is more efficient, + /// and easier than creating multiple hidden subcommands as one only needs to check for the + /// existence of this command, and not all variants. + /// + /// See also [`Command::long_flag_alias`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").long_flag("test") + /// .visible_long_flag_alias("testing")) + /// .get_matches_from(vec!["myprog", "--testing"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`Command::long_flag_alias`]: Command::long_flag_alias() + #[must_use] + pub fn visible_long_flag_alias(mut self, name: impl IntoResettable) -> Self { + if let Some(name) = name.into_resettable().into_option() { + self.long_flag_aliases.push((name, true)); + } else { + self.long_flag_aliases.clear(); + } + self + } + + /// Sets multiple visible aliases to this subcommand. + /// + /// This allows the subcommand to be accessed via *either* the + /// original name or any of the given aliases. This is more efficient and easier + /// than creating multiple hidden subcommands as one only needs to check for + /// the existence of this command and not all aliased variants. + /// + /// **NOTE:** The alias defined with this method is *visible* from the help + /// message and displayed as if it were just another regular subcommand. If + /// looking for an alias that will not be displayed in the help message, see + /// [`Command::alias`]. + /// + /// **NOTE:** When using aliases, and checking for the existence of a + /// particular subcommand within an [`ArgMatches`] struct, one only needs to + /// search for the original name and not all aliases. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test") + /// .visible_aliases(["do-stuff", "tests"])) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`Command::alias`]: Command::alias() + #[must_use] + pub fn visible_aliases(mut self, names: impl IntoIterator>) -> Self { + self.aliases + .extend(names.into_iter().map(|n| (n.into(), true))); + self + } + + /// Add aliases, which function as *visible* short flag subcommands. + /// + /// See [`Command::short_flag_aliases`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").short_flag('b') + /// .visible_short_flag_aliases(['t'])) + /// .get_matches_from(vec!["myprog", "-t"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`Command::short_flag_aliases`]: Command::short_flag_aliases() + #[must_use] + pub fn visible_short_flag_aliases(mut self, names: impl IntoIterator) -> Self { + for s in names { + debug_assert!(s != '-', "short alias name cannot be `-`"); + self.short_flag_aliases.push((s, true)); + } + self + } + + /// Add aliases, which function as *visible* long flag subcommands. + /// + /// See [`Command::long_flag_aliases`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg, }; + /// let m = Command::new("myprog") + /// .subcommand(Command::new("test").long_flag("test") + /// .visible_long_flag_aliases(["testing", "testall", "test_all"])) + /// .get_matches_from(vec!["myprog", "--testing"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`Command::long_flag_aliases`]: Command::long_flag_aliases() + #[must_use] + pub fn visible_long_flag_aliases( + mut self, + names: impl IntoIterator>, + ) -> Self { + for s in names { + self = self.visible_long_flag_alias(s); + } + self + } + + /// Set the placement of this subcommand within the help. + /// + /// Subcommands with a lower value will be displayed first in the help message. Subcommands + /// with duplicate display orders will be displayed in alphabetical order. + /// + /// This is helpful when one would like to emphasize frequently used subcommands, or prioritize + /// those towards the top of the list. + /// + /// **NOTE:** The default is 999 for all subcommands. + /// + /// # Examples + /// + #[cfg_attr(not(feature = "help"), doc = " ```ignore")] + #[cfg_attr(feature = "help", doc = " ```")] + /// # use clap::{Command, }; + /// let m = Command::new("cust-ord") + /// .subcommand(Command::new("alpha") // typically subcommands are grouped + /// // alphabetically by name. Subcommands + /// // without a display_order have a value of + /// // 999 and are displayed alphabetically with + /// // all other 999 subcommands + /// .about("Some help and text")) + /// .subcommand(Command::new("beta") + /// .display_order(1) // In order to force this subcommand to appear *first* + /// // all we have to do is give it a value lower than 999. + /// // Any other subcommands with a value of 1 will be displayed + /// // alphabetically with this one...then 2 values, then 3, etc. + /// .about("I should be first!")) + /// .get_matches_from(vec![ + /// "cust-ord", "--help" + /// ]); + /// ``` + /// + /// The above example displays the following help message + /// + /// ```text + /// cust-ord + /// + /// Usage: cust-ord [OPTIONS] + /// + /// Commands: + /// beta I should be first! + /// alpha Some help and text + /// + /// Options: + /// -h, --help Print help + /// -V, --version Print version + /// ``` + #[inline] + #[must_use] + pub fn display_order(mut self, ord: impl IntoResettable) -> Self { + self.disp_ord = ord.into_resettable().into_option(); + self + } + + /// Specifies that this [`subcommand`] should be hidden from help messages + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand( + /// Command::new("test").hide(true) + /// ) + /// # ; + /// ``` + /// + /// [`subcommand`]: crate::Command::subcommand() + #[inline] + pub fn hide(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::Hidden) + } else { + self.unset_setting(AppSettings::Hidden) + } + } + + /// If no [`subcommand`] is present at runtime, error and exit gracefully. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, error::ErrorKind}; + /// let err = Command::new("myprog") + /// .subcommand_required(true) + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); + /// # ; + /// ``` + /// + /// [`subcommand`]: crate::Command::subcommand() + pub fn subcommand_required(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::SubcommandRequired) + } else { + self.unset_setting(AppSettings::SubcommandRequired) + } + } + + /// Assume unexpected positional arguments are a [`subcommand`]. + /// + /// Arguments will be stored in the `""` argument in the [`ArgMatches`] + /// + /// **NOTE:** Use this setting with caution, + /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand) + /// will **not** cause an error and instead be treated as a potential subcommand. + /// One should check for such cases manually and inform the user appropriately. + /// + /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with + /// `--`. + /// + /// # Examples + /// + /// ```rust + /// # use std::ffi::OsString; + /// # use clap::Command; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_external_subcommands(true) + /// .get_matches_from(vec![ + /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" + /// ]); + /// + /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty + /// // string argument name + /// match m.subcommand() { + /// Some((external, ext_m)) => { + /// let ext_args: Vec<_> = ext_m.get_many::("").unwrap().collect(); + /// assert_eq!(external, "subcmd"); + /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + /// }, + /// _ => {}, + /// } + /// ``` + /// + /// [`subcommand`]: crate::Command::subcommand() + /// [`ArgMatches`]: crate::ArgMatches + /// [`ErrorKind::UnknownArgument`]: crate::error::ErrorKind::UnknownArgument + pub fn allow_external_subcommands(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::AllowExternalSubcommands) + } else { + self.unset_setting(AppSettings::AllowExternalSubcommands) + } + } + + /// Specifies how to parse external subcommand arguments. + /// + /// The default parser is for `OsString`. This can be used to switch it to `String` or another + /// type. + /// + /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`] + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use std::ffi::OsString; + /// # use clap::Command; + /// # use clap::value_parser; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .allow_external_subcommands(true) + /// .get_matches_from(vec![ + /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" + /// ]); + /// + /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty + /// // string argument name + /// match m.subcommand() { + /// Some((external, ext_m)) => { + /// let ext_args: Vec<_> = ext_m.get_many::("").unwrap().collect(); + /// assert_eq!(external, "subcmd"); + /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + /// }, + /// _ => {}, + /// } + /// ``` + /// + /// ``` + /// # use clap::Command; + /// # use clap::value_parser; + /// // Assume there is an external subcommand named "subcmd" + /// let m = Command::new("myprog") + /// .external_subcommand_value_parser(value_parser!(String)) + /// .get_matches_from(vec![ + /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" + /// ]); + /// + /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty + /// // string argument name + /// match m.subcommand() { + /// Some((external, ext_m)) => { + /// let ext_args: Vec<_> = ext_m.get_many::("").unwrap().collect(); + /// assert_eq!(external, "subcmd"); + /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + /// }, + /// _ => {}, + /// } + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + pub fn external_subcommand_value_parser( + mut self, + parser: impl IntoResettable, + ) -> Self { + self.external_value_parser = parser.into_resettable().into_option(); + self + } + + /// Specifies that use of an argument prevents the use of [`subcommands`]. + /// + /// By default `clap` allows arguments between subcommands such + /// as ` [cmd_args] [subcmd_args] [subsubcmd_args]`. + /// + /// This setting disables that functionality and says that arguments can + /// only follow the *final* subcommand. For instance using this setting + /// makes only the following invocations possible: + /// + /// * ` [subsubcmd_args]` + /// * ` [subcmd_args]` + /// * ` [cmd_args]` + /// + /// # Examples + /// + /// ```rust + /// # use clap::Command; + /// Command::new("myprog") + /// .args_conflicts_with_subcommands(true); + /// ``` + /// + /// [`subcommands`]: crate::Command::subcommand() + pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::ArgsNegateSubcommands) + } else { + self.unset_setting(AppSettings::ArgsNegateSubcommands) + } + } + + /// Prevent subcommands from being consumed as an arguments value. + /// + /// By default, if an option taking multiple values is followed by a subcommand, the + /// subcommand will be parsed as another value. + /// + /// ```text + /// cmd --foo val1 val2 subcommand + /// --------- ---------- + /// values another value + /// ``` + /// + /// This setting instructs the parser to stop when encountering a subcommand instead of + /// greedily consuming arguments. + /// + /// ```text + /// cmd --foo val1 val2 subcommand + /// --------- ---------- + /// values subcommand + /// ``` + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Command, Arg, ArgAction}; + /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg( + /// Arg::new("arg") + /// .long("arg") + /// .num_args(1..) + /// .action(ArgAction::Set), + /// ); + /// + /// let matches = cmd + /// .clone() + /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) + /// .unwrap(); + /// assert_eq!( + /// matches.get_many::("arg").unwrap().collect::>(), + /// &["1", "2", "3", "sub"] + /// ); + /// assert!(matches.subcommand_matches("sub").is_none()); + /// + /// let matches = cmd + /// .subcommand_precedence_over_arg(true) + /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) + /// .unwrap(); + /// assert_eq!( + /// matches.get_many::("arg").unwrap().collect::>(), + /// &["1", "2", "3"] + /// ); + /// assert!(matches.subcommand_matches("sub").is_some()); + /// ``` + pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::SubcommandPrecedenceOverArg) + } else { + self.unset_setting(AppSettings::SubcommandPrecedenceOverArg) + } + } + + /// Allows [`subcommands`] to override all requirements of the parent command. + /// + /// For example, if you had a subcommand or top level application with a required argument + /// that is only required as long as there is no subcommand present, + /// using this setting would allow you to set those arguments to [`Arg::required(true)`] + /// and yet receive no error so long as the user uses a valid subcommand instead. + /// + /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements) + /// + /// # Examples + /// + /// This first example shows that it is an error to not use a required argument + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind}; + /// let err = Command::new("myprog") + /// .subcommand_negates_reqs(true) + /// .arg(Arg::new("opt").required(true)) + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog" + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); + /// # ; + /// ``` + /// + /// This next example shows that it is no longer error to not use a required argument if a + /// valid subcommand is used. + /// + /// ```rust + /// # use clap::{Command, Arg, error::ErrorKind}; + /// let noerr = Command::new("myprog") + /// .subcommand_negates_reqs(true) + /// .arg(Arg::new("opt").required(true)) + /// .subcommand(Command::new("test")) + /// .try_get_matches_from(vec![ + /// "myprog", "test" + /// ]); + /// assert!(noerr.is_ok()); + /// # ; + /// ``` + /// + /// [`Arg::required(true)`]: crate::Arg::required() + /// [`subcommands`]: crate::Command::subcommand() + pub fn subcommand_negates_reqs(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::SubcommandsNegateReqs) + } else { + self.unset_setting(AppSettings::SubcommandsNegateReqs) + } + } + + /// Multiple-personality program dispatched on the binary name (`argv[0]`) + /// + /// A "multicall" executable is a single executable + /// that contains a variety of applets, + /// and decides which applet to run based on the name of the file. + /// The executable can be called from different names by creating hard links + /// or symbolic links to it. + /// + /// This is desirable for: + /// - Easy distribution, a single binary that can install hardlinks to access the different + /// personalities. + /// - Minimal binary size by sharing common code (e.g. standard library, clap) + /// - Custom shells or REPLs where there isn't a single top-level command + /// + /// Setting `multicall` will cause + /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if + /// [`Command::no_binary_name`][Command::no_binary_name] was set. + /// - Help and errors to report subcommands as if they were the top-level command + /// + /// When the subcommand is not present, there are several strategies you may employ, depending + /// on your needs: + /// - Let the error percolate up normally + /// - Print a specialized error message using the + /// [`Error::context`][crate::Error::context] + /// - Print the [help][Command::write_help] but this might be ambiguous + /// - Disable `multicall` and re-parse it + /// - Disable `multicall` and re-parse it with a specific subcommand + /// + /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand + /// might report the same error. Enable + /// [`allow_external_subcommands`][Command::allow_external_subcommands] if you want to specifically + /// get the unrecognized binary name. + /// + /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret + /// the command name in incompatible ways. + /// + /// **NOTE:** The multicall command cannot have arguments. + /// + /// **NOTE:** Applets are slightly semantically different from subcommands, + /// so it's recommended to use [`Command::subcommand_help_heading`] and + /// [`Command::subcommand_value_name`] to change the descriptive text as above. + /// + /// # Examples + /// + /// `hostname` is an example of a multicall executable. + /// Both `hostname` and `dnsdomainname` are provided by the same executable + /// and which behaviour to use is based on the executable file name. + /// + /// This is desirable when the executable has a primary purpose + /// but there is related functionality that would be convenient to provide + /// and implement it to be in the same executable. + /// + /// The name of the cmd is essentially unused + /// and may be the same as the name of a subcommand. + /// + /// The names of the immediate subcommands of the Command + /// are matched against the basename of the first argument, + /// which is conventionally the path of the executable. + /// + /// This does not allow the subcommand to be passed as the first non-path argument. + /// + /// ```rust + /// # use clap::{Command, error::ErrorKind}; + /// let mut cmd = Command::new("hostname") + /// .multicall(true) + /// .subcommand(Command::new("hostname")) + /// .subcommand(Command::new("dnsdomainname")); + /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]); + /// assert!(m.is_err()); + /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument); + /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]); + /// assert_eq!(m.subcommand_name(), Some("dnsdomainname")); + /// ``` + /// + /// Busybox is another common example of a multicall executable + /// with a subcommmand for each applet that can be run directly, + /// e.g. with the `cat` applet being run by running `busybox cat`, + /// or with `cat` as a link to the `busybox` binary. + /// + /// This is desirable when the launcher program has additional options + /// or it is useful to run the applet without installing a symlink + /// e.g. to test the applet without installing it + /// or there may already be a command of that name installed. + /// + /// To make an applet usable as both a multicall link and a subcommand + /// the subcommands must be defined both in the top-level Command + /// and as subcommands of the "main" applet. + /// + /// ```rust + /// # use clap::Command; + /// fn applet_commands() -> [Command; 2] { + /// [Command::new("true"), Command::new("false")] + /// } + /// let mut cmd = Command::new("busybox") + /// .multicall(true) + /// .subcommand( + /// Command::new("busybox") + /// .subcommand_value_name("APPLET") + /// .subcommand_help_heading("APPLETS") + /// .subcommands(applet_commands()), + /// ) + /// .subcommands(applet_commands()); + /// // When called from the executable's canonical name + /// // its applets can be matched as subcommands. + /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap(); + /// assert_eq!(m.subcommand_name(), Some("busybox")); + /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true")); + /// // When called from a link named after an applet that applet is matched. + /// let m = cmd.get_matches_from(&["/usr/bin/true"]); + /// assert_eq!(m.subcommand_name(), Some("true")); + /// ``` + /// + /// [`no_binary_name`]: crate::Command::no_binary_name + /// [`Command::subcommand_value_name`]: crate::Command::subcommand_value_name + /// [`Command::subcommand_help_heading`]: crate::Command::subcommand_help_heading + #[inline] + pub fn multicall(self, yes: bool) -> Self { + if yes { + self.setting(AppSettings::Multicall) + } else { + self.unset_setting(AppSettings::Multicall) + } + } + + /// Sets the value name used for subcommands when printing usage and help. + /// + /// By default, this is "COMMAND". + /// + /// See also [`Command::subcommand_help_heading`] + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("sub1")) + /// .print_help() + /// # ; + /// ``` + /// + /// will produce + /// + /// ```text + /// myprog + /// + /// Usage: myprog [COMMAND] + /// + /// Commands: + /// help Print this message or the help of the given subcommand(s) + /// sub1 + /// + /// Options: + /// -h, --help Print help + /// -V, --version Print version + /// ``` + /// + /// but usage of `subcommand_value_name` + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("sub1")) + /// .subcommand_value_name("THING") + /// .print_help() + /// # ; + /// ``` + /// + /// will produce + /// + /// ```text + /// myprog + /// + /// Usage: myprog [THING] + /// + /// Commands: + /// help Print this message or the help of the given subcommand(s) + /// sub1 + /// + /// Options: + /// -h, --help Print help + /// -V, --version Print version + /// ``` + #[must_use] + pub fn subcommand_value_name(mut self, value_name: impl IntoResettable) -> Self { + self.subcommand_value_name = value_name.into_resettable().into_option(); + self + } + + /// Sets the help heading used for subcommands when printing usage and help. + /// + /// By default, this is "Commands". + /// + /// See also [`Command::subcommand_value_name`] + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("sub1")) + /// .print_help() + /// # ; + /// ``` + /// + /// will produce + /// + /// ```text + /// myprog + /// + /// Usage: myprog [COMMAND] + /// + /// Commands: + /// help Print this message or the help of the given subcommand(s) + /// sub1 + /// + /// Options: + /// -h, --help Print help + /// -V, --version Print version + /// ``` + /// + /// but usage of `subcommand_help_heading` + /// + /// ```no_run + /// # use clap::{Command, Arg}; + /// Command::new("myprog") + /// .subcommand(Command::new("sub1")) + /// .subcommand_help_heading("Things") + /// .print_help() + /// # ; + /// ``` + /// + /// will produce + /// + /// ```text + /// myprog + /// + /// Usage: myprog [COMMAND] + /// + /// Things: + /// help Print this message or the help of the given subcommand(s) + /// sub1 + /// + /// Options: + /// -h, --help Print help + /// -V, --version Print version + /// ``` + #[must_use] + pub fn subcommand_help_heading(mut self, heading: impl IntoResettable) -> Self { + self.subcommand_heading = heading.into_resettable().into_option(); + self + } +} + +/// # Reflection +impl Command { + #[inline] + #[cfg(feature = "usage")] + pub(crate) fn get_usage_name(&self) -> Option<&str> { + self.usage_name.as_deref() + } + + /// Get the name of the binary. + #[inline] + pub fn get_display_name(&self) -> Option<&str> { + self.display_name.as_deref() + } + + /// Get the name of the binary. + #[inline] + pub fn get_bin_name(&self) -> Option<&str> { + self.bin_name.as_deref() + } + + /// Set binary name. Uses `&mut self` instead of `self`. + pub fn set_bin_name(&mut self, name: impl Into) { + self.bin_name = Some(name.into()); + } + + /// Get the name of the cmd. + #[inline] + pub fn get_name(&self) -> &str { + self.name.as_str() + } + + #[inline] + #[cfg(debug_assertions)] + pub(crate) fn get_name_str(&self) -> &Str { + &self.name + } + + /// Get the version of the cmd. + #[inline] + pub fn get_version(&self) -> Option<&str> { + self.version.as_deref() + } + + /// Get the long version of the cmd. + #[inline] + pub fn get_long_version(&self) -> Option<&str> { + self.long_version.as_deref() + } + + /// Get the authors of the cmd. + #[inline] + pub fn get_author(&self) -> Option<&str> { + self.author.as_deref() + } + + /// Get the short flag of the subcommand. + #[inline] + pub fn get_short_flag(&self) -> Option { + self.short_flag + } + + /// Get the long flag of the subcommand. + #[inline] + pub fn get_long_flag(&self) -> Option<&str> { + self.long_flag.as_deref() + } + + /// Get the help message specified via [`Command::about`]. + /// + /// [`Command::about`]: Command::about() + #[inline] + pub fn get_about(&self) -> Option<&StyledStr> { + self.about.as_ref() + } + + /// Get the help message specified via [`Command::long_about`]. + /// + /// [`Command::long_about`]: Command::long_about() + #[inline] + pub fn get_long_about(&self) -> Option<&StyledStr> { + self.long_about.as_ref() + } + + /// Get the custom section heading specified via [`Command::next_help_heading`]. + /// + /// [`Command::help_heading`]: Command::help_heading() + #[inline] + pub fn get_next_help_heading(&self) -> Option<&str> { + self.current_help_heading.as_deref() + } + + /// Iterate through the *visible* aliases for this subcommand. + #[inline] + pub fn get_visible_aliases(&self) -> impl Iterator + '_ { + self.aliases + .iter() + .filter(|(_, vis)| *vis) + .map(|a| a.0.as_str()) + } + + /// Iterate through the *visible* short aliases for this subcommand. + #[inline] + pub fn get_visible_short_flag_aliases(&self) -> impl Iterator + '_ { + self.short_flag_aliases + .iter() + .filter(|(_, vis)| *vis) + .map(|a| a.0) + } + + /// Iterate through the *visible* long aliases for this subcommand. + #[inline] + pub fn get_visible_long_flag_aliases(&self) -> impl Iterator + '_ { + self.long_flag_aliases + .iter() + .filter(|(_, vis)| *vis) + .map(|a| a.0.as_str()) + } + + /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden. + #[inline] + pub fn get_all_aliases(&self) -> impl Iterator + '_ { + self.aliases.iter().map(|a| a.0.as_str()) + } + + /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden. + #[inline] + pub fn get_all_short_flag_aliases(&self) -> impl Iterator + '_ { + self.short_flag_aliases.iter().map(|a| a.0) + } + + /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden. + #[inline] + pub fn get_all_long_flag_aliases(&self) -> impl Iterator + '_ { + self.long_flag_aliases.iter().map(|a| a.0.as_str()) + } + + #[inline] + pub(crate) fn is_set(&self, s: AppSettings) -> bool { + self.settings.is_set(s) || self.g_settings.is_set(s) + } + + /// Should we color the output? + pub fn get_color(&self) -> ColorChoice { + debug!("Command::color: Color setting..."); + + if cfg!(feature = "color") { + if self.is_set(AppSettings::ColorNever) { + debug!("Never"); + ColorChoice::Never + } else if self.is_set(AppSettings::ColorAlways) { + debug!("Always"); + ColorChoice::Always + } else { + debug!("Auto"); + ColorChoice::Auto + } + } else { + ColorChoice::Never + } + } + + /// Iterate through the set of subcommands, getting a reference to each. + #[inline] + pub fn get_subcommands(&self) -> impl Iterator { + self.subcommands.iter() + } + + /// Iterate through the set of subcommands, getting a mutable reference to each. + #[inline] + pub fn get_subcommands_mut(&mut self) -> impl Iterator { + self.subcommands.iter_mut() + } + + /// Returns `true` if this `Command` has subcommands. + #[inline] + pub fn has_subcommands(&self) -> bool { + !self.subcommands.is_empty() + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_subcommand_help_heading(&self) -> Option<&str> { + self.subcommand_heading.as_deref() + } + + /// Returns the subcommand value name. + #[inline] + pub fn get_subcommand_value_name(&self) -> Option<&str> { + self.subcommand_value_name.as_deref() + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_before_help(&self) -> Option<&StyledStr> { + self.before_help.as_ref() + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_before_long_help(&self) -> Option<&StyledStr> { + self.before_long_help.as_ref() + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_after_help(&self) -> Option<&StyledStr> { + self.after_help.as_ref() + } + + /// Returns the help heading for listing subcommands. + #[inline] + pub fn get_after_long_help(&self) -> Option<&StyledStr> { + self.after_long_help.as_ref() + } + + /// Find subcommand such that its name or one of aliases equals `name`. + /// + /// This does not recurse through subcommands of subcommands. + #[inline] + pub fn find_subcommand(&self, name: impl AsRef) -> Option<&Command> { + let name = name.as_ref(); + self.get_subcommands().find(|s| s.aliases_to(name)) + } + + /// Find subcommand such that its name or one of aliases equals `name`, returning + /// a mutable reference to the subcommand. + /// + /// This does not recurse through subcommands of subcommands. + #[inline] + pub fn find_subcommand_mut( + &mut self, + name: impl AsRef, + ) -> Option<&mut Command> { + let name = name.as_ref(); + self.get_subcommands_mut().find(|s| s.aliases_to(name)) + } + + /// Iterate through the set of groups. + #[inline] + pub fn get_groups(&self) -> impl Iterator { + self.groups.iter() + } + + /// Iterate through the set of arguments. + #[inline] + pub fn get_arguments(&self) -> impl Iterator { + self.args.args() + } + + /// Iterate through the *positionals* arguments. + #[inline] + pub fn get_positionals(&self) -> impl Iterator { + self.get_arguments().filter(|a| a.is_positional()) + } + + /// Iterate through the *options*. + pub fn get_opts(&self) -> impl Iterator { + self.get_arguments() + .filter(|a| a.is_takes_value_set() && !a.is_positional()) + } + + /// Get a list of all arguments the given argument conflicts with. + /// + /// If the provided argument is declared as global, the conflicts will be determined + /// based on the propagation rules of global arguments. + /// + /// ### Panics + /// + /// If the given arg contains a conflict with an argument that is unknown to + /// this `Command`. + pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator + { + if arg.is_global_set() { + self.get_global_arg_conflicts_with(arg) + } else { + let mut result = Vec::new(); + for id in arg.blacklist.iter() { + if let Some(arg) = self.find(id) { + result.push(arg); + } else if let Some(group) = self.find_group(id) { + result.extend( + self.unroll_args_in_group(&group.id) + .iter() + .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)), + ); + } else { + panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd"); + } + } + result + } + } + + // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with. + // + // This behavior follows the propagation rules of global arguments. + // It is useful for finding conflicts for arguments declared as global. + // + // ### Panics + // + // If the given arg contains a conflict with an argument that is unknown to + // this `Command`. + fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator + { + arg.blacklist + .iter() + .map(|id| { + self.args + .args() + .chain( + self.get_subcommands_containing(arg) + .iter() + .flat_map(|x| x.args.args()), + ) + .find(|arg| arg.get_id() == id) + .expect( + "Command::get_arg_conflicts_with: \ + The passed arg conflicts with an arg unknown to the cmd", + ) + }) + .collect() + } + + // Get a list of subcommands which contain the provided Argument + // + // This command will only include subcommands in its list for which the subcommands + // parent also contains the Argument. + // + // This search follows the propagation rules of global arguments. + // It is useful to finding subcommands, that have inherited a global argument. + // + // **NOTE:** In this case only Sucommand_1 will be included + // Subcommand_1 (contains Arg) + // Subcommand_1.1 (doesn't contain Arg) + // Subcommand_1.1.1 (contains Arg) + // + fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> { + let mut vec = std::vec::Vec::new(); + for idx in 0..self.subcommands.len() { + if self.subcommands[idx] + .args + .args() + .any(|ar| ar.get_id() == arg.get_id()) + { + vec.push(&self.subcommands[idx]); + vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg)); + } + } + vec + } + + /// Report whether [`Command::no_binary_name`] is set + pub fn is_no_binary_name_set(&self) -> bool { + self.is_set(AppSettings::NoBinaryName) + } + + /// Report whether [`Command::ignore_errors`] is set + pub(crate) fn is_ignore_errors_set(&self) -> bool { + self.is_set(AppSettings::IgnoreErrors) + } + + /// Report whether [`Command::dont_delimit_trailing_values`] is set + pub fn is_dont_delimit_trailing_values_set(&self) -> bool { + self.is_set(AppSettings::DontDelimitTrailingValues) + } + + /// Report whether [`Command::disable_version_flag`] is set + pub fn is_disable_version_flag_set(&self) -> bool { + self.is_set(AppSettings::DisableVersionFlag) + || (self.version.is_none() && self.long_version.is_none()) + } + + /// Report whether [`Command::propagate_version`] is set + pub fn is_propagate_version_set(&self) -> bool { + self.is_set(AppSettings::PropagateVersion) + } + + /// Report whether [`Command::next_line_help`] is set + pub fn is_next_line_help_set(&self) -> bool { + self.is_set(AppSettings::NextLineHelp) + } + + /// Report whether [`Command::disable_help_flag`] is set + pub fn is_disable_help_flag_set(&self) -> bool { + self.is_set(AppSettings::DisableHelpFlag) + } + + /// Report whether [`Command::disable_help_subcommand`] is set + pub fn is_disable_help_subcommand_set(&self) -> bool { + self.is_set(AppSettings::DisableHelpSubcommand) + } + + /// Report whether [`Command::disable_colored_help`] is set + pub fn is_disable_colored_help_set(&self) -> bool { + self.is_set(AppSettings::DisableColoredHelp) + } + + /// Report whether [`Command::help_expected`] is set + #[cfg(debug_assertions)] + pub(crate) fn is_help_expected_set(&self) -> bool { + self.is_set(AppSettings::HelpExpected) + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "This is now the default") + )] + pub fn is_dont_collapse_args_in_usage_set(&self) -> bool { + true + } + + /// Report whether [`Command::infer_long_args`] is set + pub(crate) fn is_infer_long_args_set(&self) -> bool { + self.is_set(AppSettings::InferLongArgs) + } + + /// Report whether [`Command::infer_subcommands`] is set + pub(crate) fn is_infer_subcommands_set(&self) -> bool { + self.is_set(AppSettings::InferSubcommands) + } + + /// Report whether [`Command::arg_required_else_help`] is set + pub fn is_arg_required_else_help_set(&self) -> bool { + self.is_set(AppSettings::ArgRequiredElseHelp) + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "4.0.0", + note = "Replaced with `Arg::is_allow_hyphen_values_set`" + ) + )] + pub(crate) fn is_allow_hyphen_values_set(&self) -> bool { + self.is_set(AppSettings::AllowHyphenValues) + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated( + since = "4.0.0", + note = "Replaced with `Arg::is_allow_negative_numbers_set`" + ) + )] + pub fn is_allow_negative_numbers_set(&self) -> bool { + self.is_set(AppSettings::AllowNegativeNumbers) + } + + #[doc(hidden)] + #[cfg_attr( + feature = "deprecated", + deprecated(since = "4.0.0", note = "Replaced with `Arg::is_trailing_var_arg_set`") + )] + pub fn is_trailing_var_arg_set(&self) -> bool { + self.is_set(AppSettings::TrailingVarArg) + } + + /// Report whether [`Command::allow_missing_positional`] is set + pub fn is_allow_missing_positional_set(&self) -> bool { + self.is_set(AppSettings::AllowMissingPositional) + } + + /// Report whether [`Command::hide`] is set + pub fn is_hide_set(&self) -> bool { + self.is_set(AppSettings::Hidden) + } + + /// Report whether [`Command::subcommand_required`] is set + pub fn is_subcommand_required_set(&self) -> bool { + self.is_set(AppSettings::SubcommandRequired) + } + + /// Report whether [`Command::allow_external_subcommands`] is set + pub fn is_allow_external_subcommands_set(&self) -> bool { + self.is_set(AppSettings::AllowExternalSubcommands) + } + + /// Configured parser for values passed to an external subcommand + /// + /// # Example + /// + /// ```rust + /// let cmd = clap::Command::new("raw") + /// .external_subcommand_value_parser(clap::value_parser!(String)); + /// let value_parser = cmd.get_external_subcommand_value_parser(); + /// println!("{:?}", value_parser); + /// ``` + pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> { + if !self.is_allow_external_subcommands_set() { + None + } else { + static DEFAULT: super::ValueParser = super::ValueParser::os_string(); + Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT)) + } + } + + /// Report whether [`Command::args_conflicts_with_subcommands`] is set + pub fn is_args_conflicts_with_subcommands_set(&self) -> bool { + self.is_set(AppSettings::ArgsNegateSubcommands) + } + + #[doc(hidden)] + pub fn is_args_override_self(&self) -> bool { + self.is_set(AppSettings::AllArgsOverrideSelf) + } + + /// Report whether [`Command::subcommand_precedence_over_arg`] is set + pub fn is_subcommand_precedence_over_arg_set(&self) -> bool { + self.is_set(AppSettings::SubcommandPrecedenceOverArg) + } + + /// Report whether [`Command::subcommand_negates_reqs`] is set + pub fn is_subcommand_negates_reqs_set(&self) -> bool { + self.is_set(AppSettings::SubcommandsNegateReqs) + } + + /// Report whether [`Command::multicall`] is set + pub fn is_multicall_set(&self) -> bool { + self.is_set(AppSettings::Multicall) + } +} + +// Internally used only +impl Command { + pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> { + self.usage_str.as_ref() + } + + pub(crate) fn get_override_help(&self) -> Option<&StyledStr> { + self.help_str.as_ref() + } + + #[cfg(feature = "help")] + pub(crate) fn get_help_template(&self) -> Option<&StyledStr> { + self.template.as_ref() + } + + #[cfg(feature = "help")] + pub(crate) fn get_term_width(&self) -> Option { + self.term_w + } + + #[cfg(feature = "help")] + pub(crate) fn get_max_term_width(&self) -> Option { + self.max_w + } + + pub(crate) fn get_replacement(&self, key: &str) -> Option<&[Str]> { + self.replacers.get(key).map(|v| v.as_slice()) + } + + pub(crate) fn get_keymap(&self) -> &MKeyMap { + &self.args + } + + fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec) { + global_arg_vec.extend( + self.args + .args() + .filter(|a| a.is_global_set()) + .map(|ga| ga.id.clone()), + ); + if let Some((id, matches)) = matches.subcommand() { + if let Some(used_sub) = self.find_subcommand(id) { + used_sub.get_used_global_args(matches, global_arg_vec); + } + } + } + + fn _do_parse( + &mut self, + raw_args: &mut clap_lex::RawArgs, + args_cursor: clap_lex::ArgCursor, + ) -> ClapResult { + debug!("Command::_do_parse"); + + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing in case we run into a subcommand + self._build_self(false); + + let mut matcher = ArgMatcher::new(self); + + // do the real parsing + let mut parser = Parser::new(self); + if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) { + if self.is_set(AppSettings::IgnoreErrors) { + debug!("Command::_do_parse: ignoring error: {}", error); + } else { + return Err(error); + } + } + + let mut global_arg_vec = Default::default(); + self.get_used_global_args(&matcher, &mut global_arg_vec); + + matcher.propagate_globals(&global_arg_vec); + + Ok(matcher.into_inner()) + } + + /// Prepare for introspecting on all included [`Command`]s + /// + /// Call this on the top-level [`Command`] when done building and before reading state for + /// cases like completions, custom help output, etc. + pub fn build(&mut self) { + self._build_recursive(true); + self._build_bin_names_internal(); + } + + pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) { + self._build_self(expand_help_tree); + for subcmd in self.get_subcommands_mut() { + subcmd._build_recursive(expand_help_tree); + } + } + + pub(crate) fn _build_self(&mut self, expand_help_tree: bool) { + debug!("Command::_build: name={:?}", self.get_name()); + if !self.settings.is_set(AppSettings::Built) { + // Make sure all the globally set flags apply to us as well + self.settings = self.settings | self.g_settings; + + if self.is_multicall_set() { + self.settings.insert(AppSettings::SubcommandRequired.into()); + self.settings.insert(AppSettings::DisableHelpFlag.into()); + self.settings.insert(AppSettings::DisableVersionFlag.into()); + } + if !cfg!(feature = "help") && self.get_override_help().is_none() { + self.settings.insert(AppSettings::DisableHelpFlag.into()); + self.settings + .insert(AppSettings::DisableHelpSubcommand.into()); + } + if self.is_set(AppSettings::ArgsNegateSubcommands) { + self.settings + .insert(AppSettings::SubcommandsNegateReqs.into()); + } + if self.external_value_parser.is_some() { + self.settings + .insert(AppSettings::AllowExternalSubcommands.into()); + } + if !self.has_subcommands() { + self.settings + .insert(AppSettings::DisableHelpSubcommand.into()); + } + + self._propagate(); + self._check_help_and_version(expand_help_tree); + self._propagate_global_args(); + + let mut pos_counter = 1; + let hide_pv = self.is_set(AppSettings::HidePossibleValues); + for a in self.args.args_mut() { + // Fill in the groups + for g in &a.groups { + if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) { + ag.args.push(a.get_id().clone()); + } else { + let mut ag = ArgGroup::new(g); + ag.args.push(a.get_id().clone()); + self.groups.push(ag); + } + } + + // Figure out implied settings + a._build(); + if hide_pv && a.is_takes_value_set() { + a.settings.set(ArgSettings::HidePossibleValues); + } + if a.is_positional() && a.index.is_none() { + a.index = Some(pos_counter); + pos_counter += 1; + } + } + + self.args._build(); + + #[allow(deprecated)] + { + let highest_idx = self + .get_keymap() + .keys() + .filter_map(|x| { + if let crate::mkeymap::KeyType::Position(n) = x { + Some(*n) + } else { + None + } + }) + .max() + .unwrap_or(0); + let is_trailing_var_arg_set = self.is_trailing_var_arg_set(); + let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set(); + let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set(); + for arg in self.args.args_mut() { + if is_allow_hyphen_values_set && arg.is_takes_value_set() { + arg.settings.insert(ArgSettings::AllowHyphenValues.into()); + } + if is_allow_negative_numbers_set && arg.is_takes_value_set() { + arg.settings + .insert(ArgSettings::AllowNegativeNumbers.into()); + } + if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) { + arg.settings.insert(ArgSettings::TrailingVarArg.into()); + } + } + } + + #[cfg(debug_assertions)] + assert_app(self); + self.settings.set(AppSettings::Built); + } else { + debug!("Command::_build: already built"); + } + } + + pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> { + use std::fmt::Write; + + let mut mid_string = String::from(" "); + #[cfg(feature = "usage")] + if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set() + { + let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) + + for s in &reqs { + mid_string.push_str(&s.to_string()); + mid_string.push(' '); + } + } + let is_multicall_set = self.is_multicall_set(); + + let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name)); + + // Display subcommand name, short and long in usage + let mut sc_names = String::new(); + sc_names.push_str(sc.name.as_str()); + let mut flag_subcmd = false; + if let Some(l) = sc.get_long_flag() { + write!(sc_names, "|--{}", l).unwrap(); + flag_subcmd = true; + } + if let Some(s) = sc.get_short_flag() { + write!(sc_names, "|-{}", s).unwrap(); + flag_subcmd = true; + } + + if flag_subcmd { + sc_names = format!("{{{}}}", sc_names); + } + + let usage_name = self + .bin_name + .as_ref() + .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names)) + .unwrap_or(sc_names); + sc.usage_name = Some(usage_name); + + // bin_name should be parent's bin_name + [] + the sc's name separated by + // a space + let bin_name = format!( + "{}{}{}", + self.bin_name.as_deref().unwrap_or_default(), + if self.bin_name.is_some() { " " } else { "" }, + &*sc.name + ); + debug!( + "Command::_build_subcommand Setting bin_name of {} to {:?}", + sc.name, bin_name + ); + sc.bin_name = Some(bin_name); + + if sc.display_name.is_none() { + let self_display_name = if is_multicall_set { + self.display_name.as_deref().unwrap_or("") + } else { + self.display_name.as_deref().unwrap_or(&self.name) + }; + let display_name = format!( + "{}{}{}", + self_display_name, + if !self_display_name.is_empty() { + "-" + } else { + "" + }, + &*sc.name + ); + debug!( + "Command::_build_subcommand Setting display_name of {} to {:?}", + sc.name, display_name + ); + sc.display_name = Some(display_name); + } + + // Ensure all args are built and ready to parse + sc._build_self(false); + + Some(sc) + } + + fn _build_bin_names_internal(&mut self) { + debug!("Command::_build_bin_names"); + + if !self.is_set(AppSettings::BinNameBuilt) { + let mut mid_string = String::from(" "); + #[cfg(feature = "usage")] + if !self.is_subcommand_negates_reqs_set() + && !self.is_args_conflicts_with_subcommands_set() + { + let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) + + for s in &reqs { + mid_string.push_str(&s.to_string()); + mid_string.push(' '); + } + } + let is_multicall_set = self.is_multicall_set(); + + let self_bin_name = if is_multicall_set { + self.bin_name.as_deref().unwrap_or("") + } else { + self.bin_name.as_deref().unwrap_or(&self.name) + } + .to_owned(); + + for mut sc in &mut self.subcommands { + debug!("Command::_build_bin_names:iter: bin_name set..."); + + if sc.usage_name.is_none() { + use std::fmt::Write; + // Display subcommand name, short and long in usage + let mut sc_names = String::new(); + sc_names.push_str(sc.name.as_str()); + let mut flag_subcmd = false; + if let Some(l) = sc.get_long_flag() { + write!(sc_names, "|--{}", l).unwrap(); + flag_subcmd = true; + } + if let Some(s) = sc.get_short_flag() { + write!(sc_names, "|-{}", s).unwrap(); + flag_subcmd = true; + } + + if flag_subcmd { + sc_names = format!("{{{}}}", sc_names); + } + + let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names); + debug!( + "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}", + sc.name, usage_name + ); + sc.usage_name = Some(usage_name); + } else { + debug!( + "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})", + sc.name, sc.usage_name + ); + } + + if sc.bin_name.is_none() { + let bin_name = format!( + "{}{}{}", + self_bin_name, + if !self_bin_name.is_empty() { " " } else { "" }, + &*sc.name + ); + debug!( + "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}", + sc.name, bin_name + ); + sc.bin_name = Some(bin_name); + } else { + debug!( + "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})", + sc.name, sc.bin_name + ); + } + + if sc.display_name.is_none() { + let self_display_name = if is_multicall_set { + self.display_name.as_deref().unwrap_or("") + } else { + self.display_name.as_deref().unwrap_or(&self.name) + }; + let display_name = format!( + "{}{}{}", + self_display_name, + if !self_display_name.is_empty() { + "-" + } else { + "" + }, + &*sc.name + ); + debug!( + "Command::_build_bin_names:iter: Setting display_name of {} to {:?}", + sc.name, display_name + ); + sc.display_name = Some(display_name); + } else { + debug!( + "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})", + sc.name, sc.display_name + ); + } + + sc._build_bin_names_internal(); + } + self.set(AppSettings::BinNameBuilt); + } else { + debug!("Command::_build_bin_names: already built"); + } + } + + pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) { + if self.is_set(AppSettings::HelpExpected) || help_required_globally { + let args_missing_help: Vec = self + .args + .args() + .filter(|arg| arg.get_help().is_none() && arg.get_long_help().is_none()) + .map(|arg| arg.get_id().clone()) + .collect(); + + debug_assert!(args_missing_help.is_empty(), + "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}", + self.name, + args_missing_help.join(", ") + ); + } + + for sub_app in &self.subcommands { + sub_app._panic_on_missing_help(help_required_globally); + } + } + + #[cfg(debug_assertions)] + pub(crate) fn two_args_of(&self, condition: F) -> Option<(&Arg, &Arg)> + where + F: Fn(&Arg) -> bool, + { + two_elements_of(self.args.args().filter(|a: &&Arg| condition(a))) + } + + // just in case + #[allow(unused)] + fn two_groups_of(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)> + where + F: Fn(&ArgGroup) -> bool, + { + two_elements_of(self.groups.iter().filter(|a| condition(a))) + } + + /// Propagate global args + pub(crate) fn _propagate_global_args(&mut self) { + debug!("Command::_propagate_global_args:{}", self.name); + + let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set(); + + for sc in &mut self.subcommands { + if sc.get_name() == "help" && autogenerated_help_subcommand { + // Avoid propagating args to the autogenerated help subtrees used in completion. + // This prevents args from showing up during help completions like + // `myapp help subcmd `, which should only suggest subcommands and not args, + // while still allowing args to show up properly on the generated help message. + continue; + } + + for a in self.args.args().filter(|a| a.is_global_set()) { + if sc.find(&a.id).is_some() { + debug!( + "Command::_propagate skipping {:?} to {}, already exists", + a.id, + sc.get_name(), + ); + continue; + } + + debug!( + "Command::_propagate pushing {:?} to {}", + a.id, + sc.get_name(), + ); + sc.args.push(a.clone()); + } + } + } + + /// Propagate settings + pub(crate) fn _propagate(&mut self) { + debug!("Command::_propagate:{}", self.name); + let mut subcommands = std::mem::take(&mut self.subcommands); + for sc in &mut subcommands { + self._propagate_subcommand(sc); + } + self.subcommands = subcommands; + } + + fn _propagate_subcommand(&self, sc: &mut Self) { + // We have to create a new scope in order to tell rustc the borrow of `sc` is + // done and to recursively call this method + { + if self.settings.is_set(AppSettings::PropagateVersion) { + if let Some(version) = self.version.as_ref() { + sc.version.get_or_insert_with(|| version.clone()); + } + if let Some(long_version) = self.long_version.as_ref() { + sc.long_version.get_or_insert_with(|| long_version.clone()); + } + } + + sc.settings = sc.settings | self.g_settings; + sc.g_settings = sc.g_settings | self.g_settings; + sc.term_w = self.term_w; + sc.max_w = self.max_w; + } + } + + pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) { + debug!( + "Command::_check_help_and_version:{} expand_help_tree={}", + self.name, expand_help_tree + ); + + self.long_help_exists = self.long_help_exists_(); + + if !self.is_disable_help_flag_set() { + debug!("Command::_check_help_and_version: Building default --help"); + let mut arg = Arg::new(Id::HELP) + .short('h') + .long("help") + .action(ArgAction::Help); + if self.long_help_exists { + arg = arg + .help("Print help (see more with '--help')") + .long_help("Print help (see a summary with '-h')"); + } else { + arg = arg.help("Print help"); + } + // Avoiding `arg_internal` to not be sensitive to `next_help_heading` / + // `next_display_order` + self.args.push(arg); + } + if !self.is_disable_version_flag_set() { + debug!("Command::_check_help_and_version: Building default --version"); + let arg = Arg::new(Id::VERSION) + .short('V') + .long("version") + .action(ArgAction::Version) + .help("Print version"); + // Avoiding `arg_internal` to not be sensitive to `next_help_heading` / + // `next_display_order` + self.args.push(arg); + } + + if !self.is_set(AppSettings::DisableHelpSubcommand) { + debug!("Command::_check_help_and_version: Building help subcommand"); + let help_about = "Print this message or the help of the given subcommand(s)"; + + let mut help_subcmd = if expand_help_tree { + // Slow code path to recursively clone all other subcommand subtrees under help + let help_subcmd = Command::new("help") + .about(help_about) + .global_setting(AppSettings::DisableHelpSubcommand) + .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); + + let mut help_help_subcmd = Command::new("help").about(help_about); + help_help_subcmd.version = None; + help_help_subcmd.long_version = None; + help_help_subcmd = help_help_subcmd + .setting(AppSettings::DisableHelpFlag) + .setting(AppSettings::DisableVersionFlag); + + help_subcmd.subcommand(help_help_subcmd) + } else { + Command::new("help").about(help_about).arg( + Arg::new("subcommand") + .action(ArgAction::Append) + .num_args(..) + .value_name("COMMAND") + .help("Print help for the subcommand(s)"), + ) + }; + self._propagate_subcommand(&mut help_subcmd); + + // The parser acts like this is set, so let's set it so we don't falsely + // advertise it to the user + help_subcmd.version = None; + help_subcmd.long_version = None; + help_subcmd = help_subcmd + .setting(AppSettings::DisableHelpFlag) + .setting(AppSettings::DisableVersionFlag) + .unset_global_setting(AppSettings::PropagateVersion); + + self.subcommands.push(help_subcmd); + } + } + + fn _copy_subtree_for_help(&self) -> Command { + let mut cmd = Command::new(self.name.clone()) + .hide(self.is_hide_set()) + .global_setting(AppSettings::DisableHelpFlag) + .global_setting(AppSettings::DisableVersionFlag) + .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); + if self.get_about().is_some() { + cmd = cmd.about(self.get_about().unwrap().clone()); + } + cmd + } + + pub(crate) fn _render_version(&self, use_long: bool) -> String { + debug!("Command::_render_version"); + + let ver = if use_long { + self.long_version + .as_deref() + .or(self.version.as_deref()) + .unwrap_or_default() + } else { + self.version + .as_deref() + .or(self.long_version.as_deref()) + .unwrap_or_default() + }; + let display_name = self.get_display_name().unwrap_or_else(|| self.get_name()); + format!("{} {}\n", display_name, ver) + } + + pub(crate) fn format_group(&self, g: &Id) -> StyledStr { + let g_string = self + .unroll_args_in_group(g) + .iter() + .filter_map(|x| self.find(x)) + .map(|x| { + if x.is_positional() { + // Print val_name for positional arguments. e.g. + x.name_no_brackets() + } else { + // Print usage string for flags arguments, e.g. <--help> + x.to_string() + } + }) + .collect::>() + .join("|"); + let mut styled = StyledStr::new(); + styled.none("<"); + styled.none(g_string); + styled.none(">"); + styled + } +} + +/// A workaround: +/// +pub(crate) trait Captures<'a> {} +impl<'a, T> Captures<'a> for T {} + +// Internal Query Methods +impl Command { + /// Iterate through the *flags* & *options* arguments. + #[cfg(any(feature = "usage", feature = "help"))] + pub(crate) fn get_non_positionals(&self) -> impl Iterator { + self.get_arguments().filter(|a| !a.is_positional()) + } + + pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg> { + self.args.args().find(|a| a.get_id() == arg_id) + } + + #[inline] + pub(crate) fn contains_short(&self, s: char) -> bool { + debug_assert!( + self.is_set(AppSettings::Built), + "If Command::_build hasn't been called, manually search through Arg shorts" + ); + + self.args.contains(s) + } + + #[inline] + pub(crate) fn set(&mut self, s: AppSettings) { + self.settings.set(s) + } + + #[inline] + pub(crate) fn has_positionals(&self) -> bool { + self.get_positionals().next().is_some() + } + + #[cfg(any(feature = "usage", feature = "help"))] + pub(crate) fn has_visible_subcommands(&self) -> bool { + self.subcommands + .iter() + .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden)) + } + + /// Check if this subcommand can be referred to as `name`. In other words, + /// check if `name` is the name of this subcommand or is one of its aliases. + #[inline] + pub(crate) fn aliases_to(&self, name: impl AsRef) -> bool { + let name = name.as_ref(); + self.get_name() == name || self.get_all_aliases().any(|alias| alias == name) + } + + /// Check if this subcommand can be referred to as `name`. In other words, + /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases. + #[inline] + pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool { + Some(flag) == self.short_flag + || self.get_all_short_flag_aliases().any(|alias| flag == alias) + } + + /// Check if this subcommand can be referred to as `name`. In other words, + /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases. + #[inline] + pub(crate) fn long_flag_aliases_to(&self, flag: &str) -> bool { + match self.long_flag.as_ref() { + Some(long_flag) => { + long_flag == flag || self.get_all_long_flag_aliases().any(|alias| alias == flag) + } + None => self.get_all_long_flag_aliases().any(|alias| alias == flag), + } + } + + #[cfg(debug_assertions)] + pub(crate) fn id_exists(&self, id: &Id) -> bool { + self.args.args().any(|x| x.get_id() == id) || self.groups.iter().any(|x| x.id == *id) + } + + /// Iterate through the groups this arg is member of. + pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator + 'a { + debug!("Command::groups_for_arg: id={:?}", arg); + let arg = arg.clone(); + self.groups + .iter() + .filter(move |grp| grp.args.iter().any(|a| a == &arg)) + .map(|grp| grp.id.clone()) + } + + pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup> { + self.groups.iter().find(|g| g.id == *group_id) + } + + /// Iterate through all the names of all subcommands (not recursively), including aliases. + /// Used for suggestions. + pub(crate) fn all_subcommand_names(&self) -> impl Iterator + Captures { + self.get_subcommands().flat_map(|sc| { + let name = sc.get_name(); + let aliases = sc.get_all_aliases(); + std::iter::once(name).chain(aliases) + }) + } + + pub(crate) fn required_graph(&self) -> ChildGraph { + let mut reqs = ChildGraph::with_capacity(5); + for a in self.args.args().filter(|a| a.is_required_set()) { + reqs.insert(a.get_id().clone()); + } + for group in &self.groups { + if group.required { + let idx = reqs.insert(group.id.clone()); + for a in &group.requires { + reqs.insert_child(idx, a.clone()); + } + } + } + + reqs + } + + pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec { + debug!("Command::unroll_args_in_group: group={:?}", group); + let mut g_vec = vec![group]; + let mut args = vec![]; + + while let Some(g) = g_vec.pop() { + for n in self + .groups + .iter() + .find(|grp| grp.id == *g) + .expect(INTERNAL_ERROR_MSG) + .args + .iter() + { + debug!("Command::unroll_args_in_group:iter: entity={:?}", n); + if !args.contains(n) { + if self.find(n).is_some() { + debug!("Command::unroll_args_in_group:iter: this is an arg"); + args.push(n.clone()) + } else { + debug!("Command::unroll_args_in_group:iter: this is a group"); + g_vec.push(n); + } + } + } + } + + args + } + + pub(crate) fn unroll_arg_requires(&self, func: F, arg: &Id) -> Vec + where + F: Fn(&(ArgPredicate, Id)) -> Option, + { + let mut processed = vec![]; + let mut r_vec = vec![arg]; + let mut args = vec![]; + + while let Some(a) = r_vec.pop() { + if processed.contains(&a) { + continue; + } + + processed.push(a); + + if let Some(arg) = self.find(a) { + for r in arg.requires.iter().filter_map(&func) { + if let Some(req) = self.find(&r) { + if !req.requires.is_empty() { + r_vec.push(req.get_id()) + } + } + args.push(r); + } + } + } + + args + } + + /// Find a flag subcommand name by short flag or an alias + pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> { + self.get_subcommands() + .find(|sc| sc.short_flag_aliases_to(c)) + .map(|sc| sc.get_name()) + } + + /// Find a flag subcommand name by long flag or an alias + pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> { + self.get_subcommands() + .find(|sc| sc.long_flag_aliases_to(long)) + .map(|sc| sc.get_name()) + } + + #[cfg(feature = "help")] + pub(crate) fn get_display_order(&self) -> usize { + self.disp_ord.unwrap_or(999) + } + + pub(crate) fn write_help_err(&self, mut use_long: bool) -> StyledStr { + debug!( + "Command::write_help_err: {}, use_long={:?}", + self.get_display_name().unwrap_or_else(|| self.get_name()), + use_long && self.long_help_exists(), + ); + + use_long = use_long && self.long_help_exists(); + let usage = Usage::new(self); + + let mut styled = StyledStr::new(); + write_help(&mut styled, self, &usage, use_long); + + styled + } + + pub(crate) fn write_version_err(&self, use_long: bool) -> StyledStr { + let msg = self._render_version(use_long); + let mut styled = StyledStr::new(); + styled.none(msg); + styled + } + + pub(crate) fn long_help_exists(&self) -> bool { + debug!("Command::long_help_exists: {}", self.long_help_exists); + self.long_help_exists + } + + fn long_help_exists_(&self) -> bool { + debug!("Command::long_help_exists"); + // In this case, both must be checked. This allows the retention of + // original formatting, but also ensures that the actual -h or --help + // specified by the user is sent through. If hide_short_help is not included, + // then items specified with hidden_short_help will also be hidden. + let should_long = |v: &Arg| { + v.get_long_help().is_some() + || v.is_hide_long_help_set() + || v.is_hide_short_help_set() + || v.get_possible_values() + .iter() + .any(PossibleValue::should_show_help) + }; + + // Subcommands aren't checked because we prefer short help for them, deferring to + // `cmd subcmd --help` for more. + self.get_long_about().is_some() + || self.get_before_long_help().is_some() + || self.get_after_long_help().is_some() + || self.get_arguments().any(should_long) + } + + // Should we color the help? + pub(crate) fn color_help(&self) -> ColorChoice { + #[cfg(feature = "color")] + if self.is_disable_colored_help_set() { + return ColorChoice::Never; + } + + self.get_color() + } +} + +impl Default for Command { + fn default() -> Self { + Self { + name: Default::default(), + long_flag: Default::default(), + short_flag: Default::default(), + display_name: Default::default(), + bin_name: Default::default(), + author: Default::default(), + version: Default::default(), + long_version: Default::default(), + about: Default::default(), + long_about: Default::default(), + before_help: Default::default(), + before_long_help: Default::default(), + after_help: Default::default(), + after_long_help: Default::default(), + aliases: Default::default(), + short_flag_aliases: Default::default(), + long_flag_aliases: Default::default(), + usage_str: Default::default(), + usage_name: Default::default(), + help_str: Default::default(), + disp_ord: Default::default(), + term_w: Default::default(), + max_w: Default::default(), + #[cfg(feature = "help")] + template: Default::default(), + settings: Default::default(), + g_settings: Default::default(), + args: Default::default(), + subcommands: Default::default(), + replacers: Default::default(), + groups: Default::default(), + current_help_heading: Default::default(), + current_disp_ord: Some(0), + subcommand_value_name: Default::default(), + subcommand_heading: Default::default(), + external_value_parser: Default::default(), + long_help_exists: false, + } + } +} + +impl Index<&'_ Id> for Command { + type Output = Arg; + + fn index(&self, key: &Id) -> &Self::Output { + self.find(key).expect(INTERNAL_ERROR_MSG) + } +} + +impl From<&'_ Command> for Command { + fn from(cmd: &'_ Command) -> Self { + cmd.clone() + } +} + +impl fmt::Display for Command { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.name) + } +} + +fn two_elements_of(mut iter: I) -> Option<(T, T)> +where + I: Iterator, +{ + let first = iter.next(); + let second = iter.next(); + + match (first, second) { + (Some(first), Some(second)) => Some((first, second)), + _ => None, + } +} + +#[test] +fn check_auto_traits() { + static_assertions::assert_impl_all!(Command: Send, Sync, Unpin); +} diff --git a/vendor/clap/src/builder/debug_asserts.rs b/vendor/clap/src/builder/debug_asserts.rs new file mode 100644 index 000000000..bfebbb4c4 --- /dev/null +++ b/vendor/clap/src/builder/debug_asserts.rs @@ -0,0 +1,887 @@ +use std::cmp::Ordering; + +use clap_lex::RawOsStr; + +use crate::builder::OsStr; +use crate::builder::ValueRange; +use crate::mkeymap::KeyType; +use crate::util::FlatSet; +use crate::util::Id; +use crate::ArgAction; +use crate::INTERNAL_ERROR_MSG; +use crate::{Arg, Command, ValueHint}; + +pub(crate) fn assert_app(cmd: &Command) { + debug!("Command::_debug_asserts"); + + let mut short_flags = vec![]; + let mut long_flags = vec![]; + + // Invalid version flag settings + if cmd.get_version().is_none() && cmd.get_long_version().is_none() { + // PropagateVersion is meaningless if there is no version + assert!( + !cmd.is_propagate_version_set(), + "Command {}: No version information via Command::version or Command::long_version to propagate", + cmd.get_name(), + ); + + // Used `Command::mut_arg("version", ..) but did not provide any version information to display + let version_needed = cmd + .get_arguments() + .filter(|x| matches!(x.get_action(), ArgAction::Version)) + .map(|x| x.get_id()) + .collect::>(); + + assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version" + ,cmd.get_name() + ); + } + + for sc in cmd.get_subcommands() { + if let Some(s) = sc.get_short_flag().as_ref() { + short_flags.push(Flag::Command(format!("-{}", s), sc.get_name())); + } + + for short_alias in sc.get_all_short_flag_aliases() { + short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name())); + } + + if let Some(l) = sc.get_long_flag().as_ref() { + assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l); + long_flags.push(Flag::Command(format!("--{}", l), sc.get_name())); + } + + for long_alias in sc.get_all_long_flag_aliases() { + long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name())); + } + } + + for arg in cmd.get_arguments() { + assert_arg(arg); + + assert!( + !cmd.is_multicall_set(), + "Command {}: Arguments like {} cannot be set on a multicall command", + cmd.get_name(), + arg.get_id() + ); + + if let Some(s) = arg.get_short() { + short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str())); + } + + for (short_alias, _) in &arg.short_aliases { + short_flags.push(Flag::Arg( + format!("-{}", short_alias), + arg.get_id().as_str(), + )); + } + + if let Some(l) = arg.get_long() { + assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l); + long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str())); + } + + for (long_alias, _) in &arg.aliases { + long_flags.push(Flag::Arg( + format!("--{}", long_alias), + arg.get_id().as_str(), + )); + } + + // Name conflicts + if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) { + panic!( + "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}", + cmd.get_name(), + arg.get_id(), + duplicate_tip(cmd, first, second), + ); + } + + // Long conflicts + if let Some(l) = arg.get_long() { + if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) { + panic!( + "Command {}: Long option names must be unique for each argument, \ + but '--{}' is in use by both '{}' and '{}'{}", + cmd.get_name(), + l, + first.get_id(), + second.get_id(), + duplicate_tip(cmd, first, second) + ) + } + } + + // Short conflicts + if let Some(s) = arg.get_short() { + if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) { + panic!( + "Command {}: Short option names must be unique for each argument, \ + but '-{}' is in use by both '{}' and '{}'{}", + cmd.get_name(), + s, + first.get_id(), + second.get_id(), + duplicate_tip(cmd, first, second), + ) + } + } + + // Index conflicts + if let Some(idx) = arg.index { + if let Some((first, second)) = + cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx)) + { + panic!( + "Command {}: Argument '{}' has the same index as '{}' \ + and they are both positional arguments\n\n\t \ + Use `Arg::num_args(1..)` to allow one \ + positional argument to take multiple values", + cmd.get_name(), + first.get_id(), + second.get_id() + ) + } + } + + // requires, r_if, r_unless + for req in &arg.requires { + assert!( + cmd.id_exists(&req.1), + "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist", + cmd.get_name(), + req.1, + arg.get_id(), + ); + } + + for req in &arg.r_ifs { + assert!( + !arg.is_required_set(), + "Argument {}: `required` conflicts with `required_if_eq*`", + arg.get_id() + ); + assert!( + cmd.id_exists(&req.0), + "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist", + cmd.get_name(), + req.0, + arg.get_id() + ); + } + + for req in &arg.r_ifs_all { + assert!( + !arg.is_required_set(), + "Argument {}: `required` conflicts with `required_if_eq_all`", + arg.get_id() + ); + assert!( + cmd.id_exists(&req.0), + "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist", + cmd.get_name(), + req.0, + arg.get_id() + ); + } + + for req in &arg.r_unless { + assert!( + !arg.is_required_set(), + "Argument {}: `required` conflicts with `required_unless*`", + arg.get_id() + ); + assert!( + cmd.id_exists(req), + "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist", + cmd.get_name(), + req, + arg.get_id(), + ); + } + + for req in &arg.r_unless_all { + assert!( + !arg.is_required_set(), + "Argument {}: `required` conflicts with `required_unless*`", + arg.get_id() + ); + assert!( + cmd.id_exists(req), + "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist", + cmd.get_name(), + req, + arg.get_id(), + ); + } + + // blacklist + for req in &arg.blacklist { + assert!( + cmd.id_exists(req), + "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist", + cmd.get_name(), + req, + arg.get_id(), + ); + } + + // overrides + for req in &arg.overrides { + assert!( + cmd.id_exists(req), + "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist", + cmd.get_name(), + req, + arg.get_id(), + ); + } + + if arg.is_last_set() { + assert!( + arg.get_long().is_none(), + "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.", + cmd.get_name(), + arg.get_id() + ); + assert!( + arg.get_short().is_none(), + "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.", + cmd.get_name(), + arg.get_id() + ); + } + + assert!( + !(arg.is_required_set() && arg.is_global_set()), + "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required", + cmd.get_name(), + arg.get_id() + ); + + if arg.get_value_hint() == ValueHint::CommandWithArguments { + assert!( + arg.is_positional(), + "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.", + cmd.get_name(), + arg.get_id() + ); + + assert!( + arg.is_trailing_var_arg_set() || arg.is_last_set(), + "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.", + cmd.get_name(), + arg.get_id() + ); + } + } + + for group in cmd.get_groups() { + let derive_hint = if cfg!(feature = "derive") { + " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`" + } else { + "" + }; + + // Name conflicts + assert!( + cmd.get_groups().filter(|x| x.id == group.id).count() < 2, + "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}", + cmd.get_name(), + group.get_id(), + derive_hint + ); + + // Groups should not have naming conflicts with Args + assert!( + !cmd.get_arguments().any(|x| x.get_id() == group.get_id()), + "Command {}: Argument group name '{}' must not conflict with argument name{}", + cmd.get_name(), + group.get_id(), + derive_hint + ); + + for arg in &group.args { + // Args listed inside groups should exist + assert!( + cmd.get_arguments().any(|x| x.get_id() == arg), + "Command {}: Argument group '{}' contains non-existent argument '{}'", + cmd.get_name(), + group.get_id(), + arg + ); + } + } + + // Conflicts between flags and subcommands + + long_flags.sort_unstable(); + short_flags.sort_unstable(); + + detect_duplicate_flags(&long_flags, "long"); + detect_duplicate_flags(&short_flags, "short"); + + let mut subs = FlatSet::new(); + for sc in cmd.get_subcommands() { + assert!( + subs.insert(sc.get_name()), + "Command {}: command name `{}` is duplicated", + cmd.get_name(), + sc.get_name() + ); + for alias in sc.get_all_aliases() { + assert!( + subs.insert(alias), + "Command {}: command `{}` alias `{}` is duplicated", + cmd.get_name(), + sc.get_name(), + alias + ); + } + } + + _verify_positionals(cmd); + + #[cfg(feature = "help")] + if let Some(help_template) = cmd.get_help_template() { + assert!( + !help_template.to_string().contains("{flags}"), + "Command {}: {}", + cmd.get_name(), + "`{flags}` template variable was removed in clap3, they are now included in `{options}`", + ); + assert!( + !help_template.to_string().contains("{unified}"), + "Command {}: {}", + cmd.get_name(), + "`{unified}` template variable was removed in clap3, use `{options}` instead" + ); + #[cfg(feature = "unstable-v5")] + assert!( + !help_template.to_string().contains("{bin}"), + "Command {}: {}", + cmd.get_name(), + "`{bin}` template variable was removed in clap5, use `{name}` instead" + ) + } + + cmd._panic_on_missing_help(cmd.is_help_expected_set()); + assert_app_flags(cmd); +} + +fn duplicate_tip(cmd: &Command, first: &Arg, second: &Arg) -> &'static str { + if !cmd.is_disable_help_flag_set() + && (first.get_id() == Id::HELP || second.get_id() == Id::HELP) + { + " (call `cmd.disable_help_flag(true)` to remove the auto-generated `--help`)" + } else if !cmd.is_disable_version_flag_set() + && (first.get_id() == Id::VERSION || second.get_id() == Id::VERSION) + { + " (call `cmd.disable_version_flag(true)` to remove the auto-generated `--version`)" + } else { + "" + } +} + +#[derive(Eq)] +enum Flag<'a> { + Command(String, &'a str), + Arg(String, &'a str), +} + +impl PartialEq for Flag<'_> { + fn eq(&self, other: &Flag) -> bool { + self.cmp(other) == Ordering::Equal + } +} + +impl PartialOrd for Flag<'_> { + fn partial_cmp(&self, other: &Flag) -> Option { + use Flag::*; + + match (self, other) { + (Command(s1, _), Command(s2, _)) + | (Arg(s1, _), Arg(s2, _)) + | (Command(s1, _), Arg(s2, _)) + | (Arg(s1, _), Command(s2, _)) => { + if s1 == s2 { + Some(Ordering::Equal) + } else { + s1.partial_cmp(s2) + } + } + } + } +} + +impl Ord for Flag<'_> { + fn cmp(&self, other: &Self) -> Ordering { + self.partial_cmp(other).unwrap() + } +} + +fn detect_duplicate_flags(flags: &[Flag], short_or_long: &str) { + use Flag::*; + + for (one, two) in find_duplicates(flags) { + match (one, two) { + (Command(flag, one), Command(_, another)) if one != another => panic!( + "the '{}' {} flag is specified for both '{}' and '{}' subcommands", + flag, short_or_long, one, another + ), + + (Arg(flag, one), Arg(_, another)) if one != another => panic!( + "{} option names must be unique, but '{}' is in use by both '{}' and '{}'", + short_or_long, flag, one, another + ), + + (Arg(flag, arg), Command(_, sub)) | (Command(flag, sub), Arg(_, arg)) => panic!( + "the '{}' {} flag for the '{}' argument conflicts with the short flag \ + for '{}' subcommand", + flag, short_or_long, arg, sub + ), + + _ => {} + } + } +} + +/// Find duplicates in a sorted array. +/// +/// The algorithm is simple: the array is sorted, duplicates +/// must be placed next to each other, we can check only adjacent elements. +fn find_duplicates(slice: &[T]) -> impl Iterator { + slice.windows(2).filter_map(|w| { + if w[0] == w[1] { + Some((&w[0], &w[1])) + } else { + None + } + }) +} + +fn assert_app_flags(cmd: &Command) { + macro_rules! checker { + ($a:ident requires $($b:ident)|+) => { + if cmd.$a() { + let mut s = String::new(); + + $( + if !cmd.$b() { + use std::fmt::Write; + write!(&mut s, " AppSettings::{} is required when AppSettings::{} is set.\n", std::stringify!($b), std::stringify!($a)).unwrap(); + } + )+ + + if !s.is_empty() { + panic!("{}", s) + } + } + }; + ($a:ident conflicts $($b:ident)|+) => { + if cmd.$a() { + let mut s = String::new(); + + $( + if cmd.$b() { + use std::fmt::Write; + write!(&mut s, " AppSettings::{} conflicts with AppSettings::{}.\n", std::stringify!($b), std::stringify!($a)).unwrap(); + } + )+ + + if !s.is_empty() { + panic!("{}\n{}", cmd.get_name(), s) + } + } + }; + } + + checker!(is_multicall_set conflicts is_no_binary_name_set); +} + +#[cfg(debug_assertions)] +fn _verify_positionals(cmd: &Command) -> bool { + debug!("Command::_verify_positionals"); + // Because you must wait until all arguments have been supplied, this is the first chance + // to make assertions on positional argument indexes + // + // First we verify that the index highest supplied index, is equal to the number of + // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3 + // but no 2) + + let highest_idx = cmd + .get_keymap() + .keys() + .filter_map(|x| { + if let KeyType::Position(n) = x { + Some(*n) + } else { + None + } + }) + .max() + .unwrap_or(0); + + let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count(); + + assert!( + highest_idx == num_p, + "Found positional argument whose index is {} but there \ + are only {} positional arguments defined", + highest_idx, + num_p + ); + + for arg in cmd.get_arguments() { + if arg.index.unwrap_or(0) == highest_idx { + assert!( + !arg.is_trailing_var_arg_set() || !arg.is_last_set(), + "{}:{}: `Arg::trailing_var_arg` and `Arg::last` cannot be used together", + cmd.get_name(), + arg.get_id() + ); + + if arg.is_trailing_var_arg_set() { + assert!( + arg.is_multiple(), + "{}:{}: `Arg::trailing_var_arg` must accept multiple values", + cmd.get_name(), + arg.get_id() + ); + } + } else { + assert!( + !arg.is_trailing_var_arg_set(), + "{}:{}: `Arg::trailing_var_arg` can only apply to last positional", + cmd.get_name(), + arg.get_id() + ); + } + } + + // Next we verify that only the highest index has takes multiple arguments (if any) + let only_highest = |a: &Arg| a.is_multiple() && (a.get_index().unwrap_or(0) != highest_idx); + if cmd.get_positionals().any(only_highest) { + // First we make sure if there is a positional that allows multiple values + // the one before it (second to last) has one of these: + // * a value terminator + // * ArgSettings::Last + // * The last arg is Required + + // We can't pass the closure (it.next()) to the macro directly because each call to + // find() (iterator, not macro) gets called repeatedly. + let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)]; + let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)]; + + // Either the final positional is required + // Or the second to last has a terminator or .last(true) set + let ok = last.is_required_set() + || (second_to_last.terminator.is_some() || second_to_last.is_last_set()) + || last.is_last_set(); + assert!( + ok, + "When using a positional argument with `.num_args(1..)` that is *not the \ + last* positional argument, the last positional argument (i.e. the one \ + with the highest index) *must* have .required(true) or .last(true) set." + ); + + // We make sure if the second to last is Multiple the last is ArgSettings::Last + let ok = second_to_last.is_multiple() || last.is_last_set(); + assert!( + ok, + "Only the last positional argument, or second to last positional \ + argument may be set to `.num_args(1..)`" + ); + + // Next we check how many have both Multiple and not a specific number of values set + let count = cmd + .get_positionals() + .filter(|p| { + p.is_multiple_values_set() + && !p.get_num_args().expect(INTERNAL_ERROR_MSG).is_fixed() + }) + .count(); + let ok = count <= 1 + || (last.is_last_set() + && last.is_multiple() + && second_to_last.is_multiple() + && count == 2); + assert!( + ok, + "Only one positional argument with `.num_args(1..)` set is allowed per \ + command, unless the second one also has .last(true) set" + ); + } + + let mut found = false; + + if cmd.is_allow_missing_positional_set() { + // Check that if a required positional argument is found, all positions with a lower + // index are also required. + let mut foundx2 = false; + + for p in cmd.get_positionals() { + if foundx2 && !p.is_required_set() { + assert!( + p.is_required_set(), + "Found non-required positional argument with a lower \ + index than a required positional argument by two or more: {:?} \ + index {:?}", + p.get_id(), + p.get_index() + ); + } else if p.is_required_set() && !p.is_last_set() { + // Args that .last(true) don't count since they can be required and have + // positionals with a lower index that aren't required + // Imagine: prog [opt1] -- + // Both of these are valid invocations: + // $ prog r1 -- r2 + // $ prog r1 o1 -- r2 + if found { + foundx2 = true; + continue; + } + found = true; + continue; + } else { + found = false; + } + } + } else { + // Check that if a required positional argument is found, all positions with a lower + // index are also required + for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) { + if found { + assert!( + p.is_required_set(), + "Found non-required positional argument with a lower \ + index than a required positional argument: {:?} index {:?}", + p.get_id(), + p.get_index() + ); + } else if p.is_required_set() && !p.is_last_set() { + // Args that .last(true) don't count since they can be required and have + // positionals with a lower index that aren't required + // Imagine: prog [opt1] -- + // Both of these are valid invocations: + // $ prog r1 -- r2 + // $ prog r1 o1 -- r2 + found = true; + continue; + } + } + } + assert!( + cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2, + "Only one positional argument may have last(true) set. Found two." + ); + if cmd + .get_positionals() + .any(|p| p.is_last_set() && p.is_required_set()) + && cmd.has_subcommands() + && !cmd.is_subcommand_negates_reqs_set() + { + panic!( + "Having a required positional argument with .last(true) set *and* child \ + subcommands without setting SubcommandsNegateReqs isn't compatible." + ); + } + + true +} + +fn assert_arg(arg: &Arg) { + debug!("Arg::_debug_asserts:{}", arg.get_id()); + + // Self conflict + // TODO: this check should be recursive + assert!( + !arg.blacklist.iter().any(|x| x == arg.get_id()), + "Argument '{}' cannot conflict with itself", + arg.get_id(), + ); + + assert_eq!( + arg.get_action().takes_values(), + arg.is_takes_value_set(), + "Argument `{}`'s selected action {:?} contradicts `takes_value`", + arg.get_id(), + arg.get_action() + ); + if let Some(action_type_id) = arg.get_action().value_type_id() { + assert_eq!( + action_type_id, + arg.get_value_parser().type_id(), + "Argument `{}`'s selected action {:?} contradicts `value_parser` ({:?})", + arg.get_id(), + arg.get_action(), + arg.get_value_parser() + ); + } + + if arg.get_value_hint() != ValueHint::Unknown { + assert!( + arg.is_takes_value_set(), + "Argument '{}' has value hint but takes no value", + arg.get_id() + ); + + if arg.get_value_hint() == ValueHint::CommandWithArguments { + assert!( + arg.is_multiple_values_set(), + "Argument '{}' uses hint CommandWithArguments and must accept multiple values", + arg.get_id() + ) + } + } + + if arg.index.is_some() { + assert!( + arg.is_positional(), + "Argument '{}' is a positional argument and can't have short or long name versions", + arg.get_id() + ); + assert!( + arg.is_takes_value_set(), + "Argument '{}` is positional, it must take a value{}", + arg.get_id(), + if arg.get_id() == Id::HELP { + " (`mut_arg` no longer works with implicit `--help`)" + } else if arg.get_id() == Id::VERSION { + " (`mut_arg` no longer works with implicit `--version`)" + } else { + "" + } + ); + } + + let num_vals = arg.get_num_args().expect(INTERNAL_ERROR_MSG); + // This can be the cause of later asserts, so put this first + if num_vals != ValueRange::EMPTY { + // HACK: Don't check for flags to make the derive easier + let num_val_names = arg.get_value_names().unwrap_or(&[]).len(); + if num_vals.max_values() < num_val_names { + panic!( + "Argument {}: Too many value names ({}) compared to `num_args` ({})", + arg.get_id(), + num_val_names, + num_vals + ); + } + } + + assert_eq!( + num_vals.takes_values(), + arg.is_takes_value_set(), + "Argument {}: mismatch between `num_args` ({}) and `takes_value`", + arg.get_id(), + num_vals, + ); + assert_eq!( + num_vals.is_multiple(), + arg.is_multiple_values_set(), + "Argument {}: mismatch between `num_args` ({}) and `multiple_values`", + arg.get_id(), + num_vals, + ); + + if 1 < num_vals.min_values() { + assert!( + !arg.is_require_equals_set(), + "Argument {}: cannot accept more than 1 arg (num_args={}) with require_equals", + arg.get_id(), + num_vals + ); + } + + if num_vals == ValueRange::SINGLE { + assert!( + !arg.is_multiple_values_set(), + "Argument {}: mismatch between `num_args` and `multiple_values`", + arg.get_id() + ); + } + + assert_arg_flags(arg); + + assert_defaults(arg, "default_value", arg.default_vals.iter()); + assert_defaults( + arg, + "default_missing_value", + arg.default_missing_vals.iter(), + ); + assert_defaults( + arg, + "default_value_if", + arg.default_vals_ifs + .iter() + .filter_map(|(_, _, default)| default.as_ref()), + ); +} + +fn assert_arg_flags(arg: &Arg) { + macro_rules! checker { + ($a:ident requires $($b:ident)|+) => { + if arg.$a() { + let mut s = String::new(); + + $( + if !arg.$b() { + use std::fmt::Write; + write!(&mut s, " Arg::{} is required when Arg::{} is set.\n", std::stringify!($b), std::stringify!($a)).unwrap(); + } + )+ + + if !s.is_empty() { + panic!("Argument {:?}\n{}", arg.get_id(), s) + } + } + } + } + + checker!(is_hide_possible_values_set requires is_takes_value_set); + checker!(is_allow_hyphen_values_set requires is_takes_value_set); + checker!(is_allow_negative_numbers_set requires is_takes_value_set); + checker!(is_require_equals_set requires is_takes_value_set); + checker!(is_last_set requires is_takes_value_set); + checker!(is_hide_default_value_set requires is_takes_value_set); + checker!(is_multiple_values_set requires is_takes_value_set); + checker!(is_ignore_case_set requires is_takes_value_set); +} + +fn assert_defaults<'d>( + arg: &Arg, + field: &'static str, + defaults: impl IntoIterator, +) { + for default_os in defaults { + let value_parser = arg.get_value_parser(); + let assert_cmd = Command::new("assert"); + if let Some(delim) = arg.get_value_delimiter() { + let default_os = RawOsStr::new(default_os); + for part in default_os.split(delim) { + if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), &part.to_os_str()) + { + panic!( + "Argument `{}`'s {}={:?} failed validation: {}", + arg.get_id(), + field, + part.to_str_lossy(), + err + ); + } + } + } else if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), default_os) { + panic!( + "Argument `{}`'s {}={:?} failed validation: {}", + arg.get_id(), + field, + default_os, + err + ); + } + } +} diff --git a/vendor/clap/src/builder/mod.rs b/vendor/clap/src/builder/mod.rs new file mode 100644 index 000000000..098ad576e --- /dev/null +++ b/vendor/clap/src/builder/mod.rs @@ -0,0 +1,60 @@ +//! Define [`Command`] line [arguments][`Arg`] + +mod action; +mod app_settings; +mod arg; +mod arg_group; +mod arg_predicate; +mod arg_settings; +mod command; +mod os_str; +mod possible_value; +mod range; +mod resettable; +mod str; +mod styled_str; +mod value_hint; +mod value_parser; + +#[cfg(debug_assertions)] +mod debug_asserts; + +#[cfg(test)] +mod tests; + +pub use self::str::Str; +pub use action::ArgAction; +pub use arg::Arg; +pub use arg_group::ArgGroup; +pub use arg_predicate::ArgPredicate; +pub use command::Command; +pub use os_str::OsStr; +pub use possible_value::PossibleValue; +pub use range::ValueRange; +pub use resettable::IntoResettable; +pub use resettable::Resettable; +pub use styled_str::StyledStr; +pub use value_hint::ValueHint; +pub use value_parser::_AutoValueParser; +pub use value_parser::via_prelude; +pub use value_parser::BoolValueParser; +pub use value_parser::BoolishValueParser; +pub use value_parser::EnumValueParser; +pub use value_parser::FalseyValueParser; +pub use value_parser::MapValueParser; +pub use value_parser::NonEmptyStringValueParser; +pub use value_parser::OsStringValueParser; +pub use value_parser::PathBufValueParser; +pub use value_parser::PossibleValuesParser; +pub use value_parser::RangedI64ValueParser; +pub use value_parser::RangedU64ValueParser; +pub use value_parser::StringValueParser; +pub use value_parser::TypedValueParser; +pub use value_parser::ValueParser; +pub use value_parser::ValueParserFactory; +pub use value_parser::_AnonymousValueParser; + +#[allow(unused_imports)] +pub(crate) use self::str::Inner as StrInner; +pub(crate) use action::CountType; +pub(crate) use arg_settings::{ArgFlags, ArgSettings}; diff --git a/vendor/clap/src/builder/os_str.rs b/vendor/clap/src/builder/os_str.rs new file mode 100644 index 000000000..bb2370deb --- /dev/null +++ b/vendor/clap/src/builder/os_str.rs @@ -0,0 +1,336 @@ +use crate::builder::Str; + +/// A UTF-8-encoded fixed string +/// +/// **NOTE:** To support dynamic values (i.e. `OsString`), enable the [`string` +/// feature][crate::_features] +#[derive(Default, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] +pub struct OsStr { + name: Inner, +} + +impl OsStr { + #[cfg(feature = "string")] + pub(crate) fn from_string(name: std::ffi::OsString) -> Self { + Self { + name: Inner::from_string(name), + } + } + + #[cfg(feature = "string")] + pub(crate) fn from_ref(name: &std::ffi::OsStr) -> Self { + Self { + name: Inner::from_ref(name), + } + } + + pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self { + Self { + name: Inner::from_static_ref(name), + } + } + + /// Get the raw string as an `std::ffi::OsStr` + pub fn as_os_str(&self) -> &std::ffi::OsStr { + self.name.as_os_str() + } + + /// Get the raw string as an `OsString` + pub fn to_os_string(&self) -> std::ffi::OsString { + self.as_os_str().to_owned() + } +} + +impl From<&'_ OsStr> for OsStr { + fn from(id: &'_ OsStr) -> Self { + id.clone() + } +} + +#[cfg(feature = "string")] +impl From for OsStr { + fn from(id: Str) -> Self { + match id.into_inner() { + crate::builder::StrInner::Static(s) => Self::from_static_ref(std::ffi::OsStr::new(s)), + crate::builder::StrInner::Owned(s) => Self::from_ref(std::ffi::OsStr::new(s.as_ref())), + } + } +} + +#[cfg(not(feature = "string"))] +impl From for OsStr { + fn from(id: Str) -> Self { + Self::from_static_ref(std::ffi::OsStr::new(id.into_inner().0)) + } +} + +#[cfg(feature = "perf")] +impl From<&'_ Str> for OsStr { + fn from(id: &'_ Str) -> Self { + match id.clone().into_inner() { + crate::builder::StrInner::Static(s) => Self::from_static_ref(std::ffi::OsStr::new(s)), + crate::builder::StrInner::Owned(s) => Self::from_ref(std::ffi::OsStr::new(s.as_ref())), + } + } +} + +impl From<&'_ Str> for OsStr { + fn from(id: &'_ Str) -> Self { + id.clone().into() + } +} + +#[cfg(feature = "string")] +impl From for OsStr { + fn from(name: std::ffi::OsString) -> Self { + Self::from_string(name) + } +} + +#[cfg(feature = "string")] +impl From<&'_ std::ffi::OsString> for OsStr { + fn from(name: &'_ std::ffi::OsString) -> Self { + Self::from_ref(name.as_os_str()) + } +} + +#[cfg(feature = "string")] +impl From for OsStr { + fn from(name: std::string::String) -> Self { + Self::from_string(name.into()) + } +} + +#[cfg(feature = "string")] +impl From<&'_ std::string::String> for OsStr { + fn from(name: &'_ std::string::String) -> Self { + Self::from_ref(name.as_str().as_ref()) + } +} + +impl From<&'static std::ffi::OsStr> for OsStr { + fn from(name: &'static std::ffi::OsStr) -> Self { + Self::from_static_ref(name) + } +} + +impl From<&'_ &'static std::ffi::OsStr> for OsStr { + fn from(name: &'_ &'static std::ffi::OsStr) -> Self { + Self::from_static_ref(name) + } +} + +impl From<&'static str> for OsStr { + fn from(name: &'static str) -> Self { + Self::from_static_ref(name.as_ref()) + } +} + +impl From<&'_ &'static str> for OsStr { + fn from(name: &'_ &'static str) -> Self { + Self::from_static_ref((*name).as_ref()) + } +} + +impl From for std::ffi::OsString { + fn from(name: OsStr) -> Self { + name.name.into_os_string() + } +} + +impl From for std::path::PathBuf { + fn from(name: OsStr) -> Self { + std::ffi::OsString::from(name).into() + } +} + +impl std::fmt::Debug for OsStr { + #[inline] + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt(self.as_os_str(), f) + } +} + +impl std::ops::Deref for OsStr { + type Target = std::ffi::OsStr; + + #[inline] + fn deref(&self) -> &std::ffi::OsStr { + self.as_os_str() + } +} + +impl AsRef for OsStr { + #[inline] + fn as_ref(&self) -> &std::ffi::OsStr { + self.as_os_str() + } +} + +impl AsRef for OsStr { + #[inline] + fn as_ref(&self) -> &std::path::Path { + std::path::Path::new(self) + } +} + +impl std::borrow::Borrow for OsStr { + #[inline] + fn borrow(&self) -> &std::ffi::OsStr { + self.as_os_str() + } +} + +impl PartialEq for OsStr { + #[inline] + fn eq(&self, other: &str) -> bool { + PartialEq::eq(self.as_os_str(), other) + } +} +impl PartialEq for str { + #[inline] + fn eq(&self, other: &OsStr) -> bool { + PartialEq::eq(self, other.as_os_str()) + } +} + +impl PartialEq<&'_ str> for OsStr { + #[inline] + fn eq(&self, other: &&str) -> bool { + PartialEq::eq(self.as_os_str(), *other) + } +} +impl PartialEq for &'_ str { + #[inline] + fn eq(&self, other: &OsStr) -> bool { + PartialEq::eq(*self, other.as_os_str()) + } +} + +impl PartialEq<&'_ std::ffi::OsStr> for OsStr { + #[inline] + fn eq(&self, other: &&std::ffi::OsStr) -> bool { + PartialEq::eq(self.as_os_str(), *other) + } +} +impl PartialEq for &'_ std::ffi::OsStr { + #[inline] + fn eq(&self, other: &OsStr) -> bool { + PartialEq::eq(*self, other.as_os_str()) + } +} + +impl PartialEq for OsStr { + #[inline] + fn eq(&self, other: &std::string::String) -> bool { + PartialEq::eq(self.as_os_str(), other.as_str()) + } +} +impl PartialEq for std::string::String { + #[inline] + fn eq(&self, other: &OsStr) -> bool { + PartialEq::eq(self.as_str(), other.as_os_str()) + } +} + +impl PartialEq for OsStr { + #[inline] + fn eq(&self, other: &std::ffi::OsString) -> bool { + PartialEq::eq(self.as_os_str(), other.as_os_str()) + } +} +impl PartialEq for std::ffi::OsString { + #[inline] + fn eq(&self, other: &OsStr) -> bool { + PartialEq::eq(self.as_os_str(), other.as_os_str()) + } +} + +#[cfg(feature = "string")] +pub(crate) mod inner { + #[derive(Clone)] + pub(crate) enum Inner { + Static(&'static std::ffi::OsStr), + Owned(Box), + } + + impl Inner { + pub(crate) fn from_string(name: std::ffi::OsString) -> Self { + Self::Owned(name.into_boxed_os_str()) + } + + pub(crate) fn from_ref(name: &std::ffi::OsStr) -> Self { + Self::Owned(Box::from(name)) + } + + pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self { + Self::Static(name) + } + + pub(crate) fn as_os_str(&self) -> &std::ffi::OsStr { + match self { + Self::Static(s) => s, + Self::Owned(s) => s.as_ref(), + } + } + + pub(crate) fn into_os_string(self) -> std::ffi::OsString { + self.as_os_str().to_owned() + } + } +} + +#[cfg(not(feature = "string"))] +pub(crate) mod inner { + #[derive(Clone)] + pub(crate) struct Inner(&'static std::ffi::OsStr); + + impl Inner { + pub(crate) fn from_static_ref(name: &'static std::ffi::OsStr) -> Self { + Self(name) + } + + pub(crate) fn as_os_str(&self) -> &std::ffi::OsStr { + self.0 + } + + pub(crate) fn into_os_string(self) -> std::ffi::OsString { + self.as_os_str().to_owned() + } + } +} + +pub(crate) use inner::Inner; + +impl Default for Inner { + fn default() -> Self { + Self::from_static_ref(std::ffi::OsStr::new("")) + } +} + +impl PartialEq for Inner { + fn eq(&self, other: &Inner) -> bool { + self.as_os_str() == other.as_os_str() + } +} + +impl PartialOrd for Inner { + fn partial_cmp(&self, other: &Self) -> Option { + self.as_os_str().partial_cmp(other.as_os_str()) + } +} + +impl Ord for Inner { + fn cmp(&self, other: &Inner) -> std::cmp::Ordering { + self.as_os_str().cmp(other.as_os_str()) + } +} + +impl Eq for Inner {} + +impl std::hash::Hash for Inner { + #[inline] + fn hash(&self, state: &mut H) { + self.as_os_str().hash(state); + } +} diff --git a/vendor/clap/src/builder/possible_value.rs b/vendor/clap/src/builder/possible_value.rs new file mode 100644 index 000000000..7a313ad25 --- /dev/null +++ b/vendor/clap/src/builder/possible_value.rs @@ -0,0 +1,234 @@ +use crate::builder::IntoResettable; +use crate::builder::Str; +use crate::builder::StyledStr; +use crate::util::eq_ignore_case; + +/// A possible value of an argument. +/// +/// This is used for specifying [possible values] of [Args]. +/// +/// See also [`PossibleValuesParser`][crate::builder::PossibleValuesParser] +/// +/// **NOTE:** Most likely you can use strings, rather than `PossibleValue` as it is only required +/// to [hide] single values from help messages and shell completions or to attach [help] to +/// possible values. +/// +/// # Examples +/// +/// ```rust +/// # use clap::{Arg, builder::PossibleValue, ArgAction}; +/// let cfg = Arg::new("config") +/// .action(ArgAction::Set) +/// .value_name("FILE") +/// .value_parser([ +/// PossibleValue::new("fast"), +/// PossibleValue::new("slow").help("slower than fast"), +/// PossibleValue::new("secret speed").hide(true) +/// ]); +/// ``` +/// +/// [Args]: crate::Arg +/// [possible values]: crate::builder::ValueParser::possible_values +/// [hide]: PossibleValue::hide() +/// [help]: PossibleValue::help() +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct PossibleValue { + name: Str, + help: Option, + aliases: Vec, // (name, visible) + hide: bool, +} + +impl PossibleValue { + /// Create a [`PossibleValue`] with its name. + /// + /// The name will be used to decide whether this value was provided by the user to an argument. + /// + /// **NOTE:** In case it is not [hidden] it will also be shown in help messages for arguments + /// that use it as a [possible value] and have not hidden them through [`Arg::hide_possible_values(true)`]. + /// + /// # Examples + /// + /// ```rust + /// # use clap::builder::PossibleValue; + /// PossibleValue::new("fast") + /// # ; + /// ``` + /// [hidden]: PossibleValue::hide + /// [possible value]: crate::builder::PossibleValuesParser + /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() + pub fn new(name: impl Into) -> Self { + PossibleValue { + name: name.into(), + ..Default::default() + } + } + + /// Sets the help description of the value. + /// + /// This is typically displayed in completions (where supported) and should be a short, one-line + /// description. + /// + /// # Examples + /// + /// ```rust + /// # use clap::builder::PossibleValue; + /// PossibleValue::new("slow") + /// .help("not fast") + /// # ; + /// ``` + #[inline] + #[must_use] + pub fn help(mut self, help: impl IntoResettable) -> Self { + self.help = help.into_resettable().into_option(); + self + } + + /// Hides this value from help and shell completions. + /// + /// This is an alternative to hiding through [`Arg::hide_possible_values(true)`], if you only + /// want to hide some values. + /// + /// # Examples + /// + /// ```rust + /// # use clap::builder::PossibleValue; + /// PossibleValue::new("secret") + /// .hide(true) + /// # ; + /// ``` + /// [`Arg::hide_possible_values(true)`]: crate::Arg::hide_possible_values() + #[inline] + #[must_use] + pub fn hide(mut self, yes: bool) -> Self { + self.hide = yes; + self + } + + /// Sets a *hidden* alias for this argument value. + /// + /// # Examples + /// + /// ```rust + /// # use clap::builder::PossibleValue; + /// PossibleValue::new("slow") + /// .alias("not-fast") + /// # ; + /// ``` + #[must_use] + pub fn alias(mut self, name: impl IntoResettable) -> Self { + if let Some(name) = name.into_resettable().into_option() { + self.aliases.push(name); + } else { + self.aliases.clear(); + } + self + } + + /// Sets multiple *hidden* aliases for this argument value. + /// + /// # Examples + /// + /// ```rust + /// # use clap::builder::PossibleValue; + /// PossibleValue::new("slow") + /// .aliases(["not-fast", "snake-like"]) + /// # ; + /// ``` + #[must_use] + pub fn aliases(mut self, names: impl IntoIterator>) -> Self { + self.aliases.extend(names.into_iter().map(|a| a.into())); + self + } +} + +/// Reflection +impl PossibleValue { + /// Get the name of the argument value + #[inline] + pub fn get_name(&self) -> &str { + self.name.as_str() + } + + /// Get the help specified for this argument, if any + #[inline] + pub fn get_help(&self) -> Option<&StyledStr> { + self.help.as_ref() + } + + /// Get the help specified for this argument, if any and the argument + /// value is not hidden + #[inline] + #[cfg(feature = "help")] + pub(crate) fn get_visible_help(&self) -> Option<&StyledStr> { + if !self.hide { + self.get_help() + } else { + None + } + } + + /// Report if [`PossibleValue::hide`] is set + #[inline] + pub fn is_hide_set(&self) -> bool { + self.hide + } + + /// Report if PossibleValue is not hidden and has a help message + pub(crate) fn should_show_help(&self) -> bool { + !self.hide && self.help.is_some() + } + + /// Get the name if argument value is not hidden, `None` otherwise, + /// but wrapped in quotes if it contains whitespace + #[cfg(feature = "help")] + pub(crate) fn get_visible_quoted_name(&self) -> Option> { + if !self.hide { + Some(if self.name.contains(char::is_whitespace) { + format!("{:?}", self.name).into() + } else { + self.name.as_str().into() + }) + } else { + None + } + } + + /// Returns all valid values of the argument value. + /// + /// Namely the name and all aliases. + pub fn get_name_and_aliases(&self) -> impl Iterator + '_ { + std::iter::once(self.get_name()).chain(self.aliases.iter().map(|s| s.as_str())) + } + + /// Tests if the value is valid for this argument value + /// + /// The value is valid if it is either the name or one of the aliases. + /// + /// # Examples + /// + /// ```rust + /// # use clap::builder::PossibleValue; + /// let arg_value = PossibleValue::new("fast").alias("not-slow"); + /// + /// assert!(arg_value.matches("fast", false)); + /// assert!(arg_value.matches("not-slow", false)); + /// + /// assert!(arg_value.matches("FAST", true)); + /// assert!(!arg_value.matches("FAST", false)); + /// ``` + pub fn matches(&self, value: &str, ignore_case: bool) -> bool { + if ignore_case { + self.get_name_and_aliases() + .any(|name| eq_ignore_case(name, value)) + } else { + self.get_name_and_aliases().any(|name| name == value) + } + } +} + +impl> From for PossibleValue { + fn from(s: S) -> Self { + Self::new(s) + } +} diff --git a/vendor/clap/src/builder/range.rs b/vendor/clap/src/builder/range.rs new file mode 100644 index 000000000..3f077bd86 --- /dev/null +++ b/vendor/clap/src/builder/range.rs @@ -0,0 +1,283 @@ +/// Values per occurrence for an argument +#[derive(Copy, Clone, PartialEq, Eq, Hash)] +pub struct ValueRange { + start_inclusive: usize, + end_inclusive: usize, +} + +impl ValueRange { + /// Nor argument values, or a flag + pub const EMPTY: Self = Self { + start_inclusive: 0, + end_inclusive: 0, + }; + + /// A single argument value, the most common case for options + pub const SINGLE: Self = Self { + start_inclusive: 1, + end_inclusive: 1, + }; + + /// Create a range + /// + /// # Panics + /// + /// If the end is less than the start + /// + /// # Examples + /// + /// ``` + /// # use clap::builder::ValueRange; + /// let range = ValueRange::new(5); + /// let range = ValueRange::new(5..10); + /// let range = ValueRange::new(5..=10); + /// let range = ValueRange::new(5..); + /// let range = ValueRange::new(..10); + /// let range = ValueRange::new(..=10); + /// ``` + /// + /// While this will panic: + /// ```should_panic + /// # use clap::builder::ValueRange; + /// let range = ValueRange::new(10..5); // Panics! + /// ``` + pub fn new(range: impl Into) -> Self { + range.into() + } + + pub(crate) fn raw(start_inclusive: usize, end_inclusive: usize) -> Self { + debug_assert!(start_inclusive <= end_inclusive); + Self { + start_inclusive, + end_inclusive, + } + } + + /// Fewest number of values the argument accepts + pub fn min_values(&self) -> usize { + self.start_inclusive + } + + /// Most number of values the argument accepts + pub fn max_values(&self) -> usize { + self.end_inclusive + } + + /// Report whether the argument takes any values (ie is a flag) + /// + /// # Examples + /// + /// ``` + /// # use clap::builder::ValueRange; + /// let range = ValueRange::new(5); + /// assert!(range.takes_values()); + /// + /// let range = ValueRange::new(0); + /// assert!(!range.takes_values()); + /// ``` + pub fn takes_values(&self) -> bool { + self.end_inclusive != 0 + } + + pub(crate) fn is_unbounded(&self) -> bool { + self.end_inclusive == usize::MAX + } + + pub(crate) fn is_fixed(&self) -> bool { + self.start_inclusive == self.end_inclusive + } + + pub(crate) fn is_multiple(&self) -> bool { + self.start_inclusive != self.end_inclusive || 1 < self.start_inclusive + } + + pub(crate) fn num_values(&self) -> Option { + self.is_fixed().then_some(self.start_inclusive) + } + + pub(crate) fn accepts_more(&self, current: usize) -> bool { + current < self.end_inclusive + } +} + +impl std::ops::RangeBounds for ValueRange { + fn start_bound(&self) -> std::ops::Bound<&usize> { + std::ops::Bound::Included(&self.start_inclusive) + } + + fn end_bound(&self) -> std::ops::Bound<&usize> { + std::ops::Bound::Included(&self.end_inclusive) + } +} + +impl Default for ValueRange { + fn default() -> Self { + Self::SINGLE + } +} + +impl From for ValueRange { + fn from(fixed: usize) -> Self { + (fixed..=fixed).into() + } +} + +impl From> for ValueRange { + fn from(range: std::ops::Range) -> Self { + let start_inclusive = range.start; + let end_inclusive = range.end.saturating_sub(1); + Self::raw(start_inclusive, end_inclusive) + } +} + +impl From for ValueRange { + fn from(_: std::ops::RangeFull) -> Self { + let start_inclusive = 0; + let end_inclusive = usize::MAX; + Self::raw(start_inclusive, end_inclusive) + } +} + +impl From> for ValueRange { + fn from(range: std::ops::RangeFrom) -> Self { + let start_inclusive = range.start; + let end_inclusive = usize::MAX; + Self::raw(start_inclusive, end_inclusive) + } +} + +impl From> for ValueRange { + fn from(range: std::ops::RangeTo) -> Self { + let start_inclusive = 0; + let end_inclusive = range.end.saturating_sub(1); + Self::raw(start_inclusive, end_inclusive) + } +} + +impl From> for ValueRange { + fn from(range: std::ops::RangeInclusive) -> Self { + let start_inclusive = *range.start(); + let end_inclusive = *range.end(); + Self::raw(start_inclusive, end_inclusive) + } +} + +impl From> for ValueRange { + fn from(range: std::ops::RangeToInclusive) -> Self { + let start_inclusive = 0; + let end_inclusive = range.end; + Self::raw(start_inclusive, end_inclusive) + } +} + +impl std::fmt::Display for ValueRange { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + ok!(self.start_inclusive.fmt(f)); + if !self.is_fixed() { + ok!("..=".fmt(f)); + ok!(self.end_inclusive.fmt(f)); + } + Ok(()) + } +} + +impl std::fmt::Debug for ValueRange { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "{}", self) + } +} + +#[cfg(test)] +mod test { + use super::*; + + use std::ops::RangeBounds; + + #[test] + fn from_fixed() { + let range: ValueRange = 5.into(); + assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); + assert_eq!(range.end_bound(), std::ops::Bound::Included(&5)); + assert!(range.is_fixed()); + assert!(range.is_multiple()); + assert_eq!(range.num_values(), Some(5)); + assert!(range.takes_values()); + } + + #[test] + fn from_fixed_empty() { + let range: ValueRange = 0.into(); + assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); + assert_eq!(range.end_bound(), std::ops::Bound::Included(&0)); + assert!(range.is_fixed()); + assert!(!range.is_multiple()); + assert_eq!(range.num_values(), Some(0)); + assert!(!range.takes_values()); + } + + #[test] + fn from_range() { + let range: ValueRange = (5..10).into(); + assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); + assert_eq!(range.end_bound(), std::ops::Bound::Included(&9)); + assert!(!range.is_fixed()); + assert!(range.is_multiple()); + assert_eq!(range.num_values(), None); + assert!(range.takes_values()); + } + + #[test] + fn from_range_inclusive() { + let range: ValueRange = (5..=10).into(); + assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); + assert_eq!(range.end_bound(), std::ops::Bound::Included(&10)); + assert!(!range.is_fixed()); + assert!(range.is_multiple()); + assert_eq!(range.num_values(), None); + assert!(range.takes_values()); + } + + #[test] + fn from_range_full() { + let range: ValueRange = (..).into(); + assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); + assert_eq!(range.end_bound(), std::ops::Bound::Included(&usize::MAX)); + assert!(!range.is_fixed()); + assert!(range.is_multiple()); + assert_eq!(range.num_values(), None); + assert!(range.takes_values()); + } + + #[test] + fn from_range_from() { + let range: ValueRange = (5..).into(); + assert_eq!(range.start_bound(), std::ops::Bound::Included(&5)); + assert_eq!(range.end_bound(), std::ops::Bound::Included(&usize::MAX)); + assert!(!range.is_fixed()); + assert!(range.is_multiple()); + assert_eq!(range.num_values(), None); + assert!(range.takes_values()); + } + + #[test] + fn from_range_to() { + let range: ValueRange = (..10).into(); + assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); + assert_eq!(range.end_bound(), std::ops::Bound::Included(&9)); + assert!(!range.is_fixed()); + assert!(range.is_multiple()); + assert_eq!(range.num_values(), None); + assert!(range.takes_values()); + } + + #[test] + fn from_range_to_inclusive() { + let range: ValueRange = (..=10).into(); + assert_eq!(range.start_bound(), std::ops::Bound::Included(&0)); + assert_eq!(range.end_bound(), std::ops::Bound::Included(&10)); + assert!(!range.is_fixed()); + assert!(range.is_multiple()); + assert_eq!(range.num_values(), None); + assert!(range.takes_values()); + } +} diff --git a/vendor/clap/src/builder/resettable.rs b/vendor/clap/src/builder/resettable.rs new file mode 100644 index 000000000..e0b82b11b --- /dev/null +++ b/vendor/clap/src/builder/resettable.rs @@ -0,0 +1,211 @@ +// Unlike `impl Into>` or `Option>`, this isn't ambiguous for the `None` +// case. + +use crate::builder::ArgAction; +use crate::builder::OsStr; +use crate::builder::Str; +use crate::builder::StyledStr; +use crate::builder::ValueHint; +use crate::builder::ValueParser; +use crate::builder::ValueRange; + +/// Clearable builder value +/// +/// This allows a builder function to both accept any value that can [`Into::into`] `T` (like +/// `&str` into `OsStr`) as well as `None` to reset it to the default. This is needed to +/// workaround a limitation where you can't have a function argument that is `impl Into>` +/// where `T` is `impl Into` accept `None` as its type is ambiguous. +/// +/// # Example +/// +/// ```rust +/// # use clap::Command; +/// # use clap::Arg; +/// fn common() -> Command { +/// Command::new("cli") +/// .arg(Arg::new("input").short('i').long("input")) +/// } +/// let mut command = common(); +/// command.mut_arg("input", |arg| arg.short(None)); +/// ``` +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Resettable { + /// Overwrite builder value + Value(T), + /// Reset builder value + Reset, +} + +impl Resettable { + pub(crate) fn into_option(self) -> Option { + match self { + Self::Value(t) => Some(t), + Self::Reset => None, + } + } +} + +impl From for Resettable { + fn from(other: T) -> Self { + Self::Value(other) + } +} + +impl From> for Resettable { + fn from(other: Option) -> Self { + match other { + Some(inner) => Self::Value(inner), + None => Self::Reset, + } + } +} + +/// Convert to the intended resettable type +pub trait IntoResettable { + /// Convert to the intended resettable type + fn into_resettable(self) -> Resettable; +} + +impl IntoResettable for Option { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option<&'static str> { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s.into()), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option<&'static str> { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s.into()), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Option<&'static str> { + fn into_resettable(self) -> Resettable { + match self { + Some(s) => Resettable::Value(s.into()), + None => Resettable::Reset, + } + } +} + +impl IntoResettable for Resettable { + fn into_resettable(self) -> Resettable { + self + } +} + +impl IntoResettable for char { + fn into_resettable(self) -> Resettable { + Resettable::Value(self) + } +} + +impl IntoResettable for usize { + fn into_resettable(self) -> Resettable { + Resettable::Value(self) + } +} + +impl IntoResettable for ArgAction { + fn into_resettable(self) -> Resettable { + Resettable::Value(self) + } +} + +impl IntoResettable for ValueHint { + fn into_resettable(self) -> Resettable { + Resettable::Value(self) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} + +impl> IntoResettable for I { + fn into_resettable(self) -> Resettable { + Resettable::Value(self.into()) + } +} diff --git a/vendor/clap/src/builder/str.rs b/vendor/clap/src/builder/str.rs new file mode 100644 index 000000000..c6689d310 --- /dev/null +++ b/vendor/clap/src/builder/str.rs @@ -0,0 +1,307 @@ +/// A UTF-8-encoded fixed string +/// +/// **NOTE:** To support dynamic values (i.e. `String`), enable the [`string` +/// feature][crate::_features] +#[derive(Default, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] +pub struct Str { + name: Inner, +} + +impl Str { + #[cfg(feature = "string")] + pub(crate) fn from_string(name: std::string::String) -> Self { + Self { + name: Inner::from_string(name), + } + } + + #[cfg(feature = "string")] + pub(crate) fn from_ref(name: &str) -> Self { + Self { + name: Inner::from_ref(name), + } + } + + pub(crate) fn from_static_ref(name: &'static str) -> Self { + Self { + name: Inner::from_static_ref(name), + } + } + + pub(crate) fn into_inner(self) -> Inner { + self.name + } + + /// Get the raw string of the `Str` + pub fn as_str(&self) -> &str { + self.name.as_str() + } +} + +impl From<&'_ Str> for Str { + fn from(id: &'_ Str) -> Self { + id.clone() + } +} + +#[cfg(feature = "string")] +impl From for Str { + fn from(name: std::string::String) -> Self { + Self::from_string(name) + } +} + +#[cfg(feature = "string")] +impl From<&'_ std::string::String> for Str { + fn from(name: &'_ std::string::String) -> Self { + Self::from_ref(name.as_str()) + } +} + +impl From<&'static str> for Str { + fn from(name: &'static str) -> Self { + Self::from_static_ref(name) + } +} + +impl From<&'_ &'static str> for Str { + fn from(name: &'_ &'static str) -> Self { + Self::from_static_ref(name) + } +} + +impl From for String { + fn from(name: Str) -> Self { + name.name.into_string() + } +} + +impl From for Vec { + fn from(name: Str) -> Self { + String::from(name).into() + } +} + +impl From for std::ffi::OsString { + fn from(name: Str) -> Self { + String::from(name).into() + } +} + +impl From for std::path::PathBuf { + fn from(name: Str) -> Self { + String::from(name).into() + } +} + +impl std::fmt::Display for Str { + #[inline] + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Display::fmt(self.as_str(), f) + } +} + +impl std::fmt::Debug for Str { + #[inline] + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt(self.as_str(), f) + } +} + +impl std::ops::Deref for Str { + type Target = str; + + #[inline] + fn deref(&self) -> &str { + self.as_str() + } +} + +impl AsRef for Str { + #[inline] + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl AsRef<[u8]> for Str { + #[inline] + fn as_ref(&self) -> &[u8] { + self.as_bytes() + } +} + +impl AsRef for Str { + #[inline] + fn as_ref(&self) -> &std::ffi::OsStr { + (**self).as_ref() + } +} + +impl AsRef for Str { + #[inline] + fn as_ref(&self) -> &std::path::Path { + std::path::Path::new(self) + } +} + +impl std::borrow::Borrow for Str { + #[inline] + fn borrow(&self) -> &str { + self.as_str() + } +} + +impl PartialEq for Str { + #[inline] + fn eq(&self, other: &str) -> bool { + PartialEq::eq(self.as_str(), other) + } +} +impl PartialEq for str { + #[inline] + fn eq(&self, other: &Str) -> bool { + PartialEq::eq(self, other.as_str()) + } +} + +impl PartialEq<&'_ str> for Str { + #[inline] + fn eq(&self, other: &&str) -> bool { + PartialEq::eq(self.as_str(), *other) + } +} +impl PartialEq for &'_ str { + #[inline] + fn eq(&self, other: &Str) -> bool { + PartialEq::eq(*self, other.as_str()) + } +} + +impl PartialEq for Str { + #[inline] + fn eq(&self, other: &std::ffi::OsStr) -> bool { + PartialEq::eq(self.as_str(), other) + } +} +impl PartialEq for std::ffi::OsStr { + #[inline] + fn eq(&self, other: &Str) -> bool { + PartialEq::eq(self, other.as_str()) + } +} + +impl PartialEq<&'_ std::ffi::OsStr> for Str { + #[inline] + fn eq(&self, other: &&std::ffi::OsStr) -> bool { + PartialEq::eq(self.as_str(), *other) + } +} +impl PartialEq for &'_ std::ffi::OsStr { + #[inline] + fn eq(&self, other: &Str) -> bool { + PartialEq::eq(*self, other.as_str()) + } +} + +impl PartialEq for Str { + #[inline] + fn eq(&self, other: &std::string::String) -> bool { + PartialEq::eq(self.as_str(), other.as_str()) + } +} +impl PartialEq for std::string::String { + #[inline] + fn eq(&self, other: &Str) -> bool { + PartialEq::eq(self.as_str(), other.as_str()) + } +} + +#[cfg(feature = "string")] +pub(crate) mod inner { + #[derive(Clone)] + pub(crate) enum Inner { + Static(&'static str), + Owned(Box), + } + + impl Inner { + pub(crate) fn from_string(name: std::string::String) -> Self { + Self::Owned(name.into_boxed_str()) + } + + pub(crate) fn from_ref(name: &str) -> Self { + Self::Owned(Box::from(name)) + } + + pub(crate) fn from_static_ref(name: &'static str) -> Self { + Self::Static(name) + } + + pub(crate) fn as_str(&self) -> &str { + match self { + Self::Static(s) => s, + Self::Owned(s) => s.as_ref(), + } + } + + pub(crate) fn into_string(self) -> String { + self.as_str().to_owned() + } + } +} + +#[cfg(not(feature = "string"))] +pub(crate) mod inner { + #[derive(Clone)] + pub(crate) struct Inner(pub(crate) &'static str); + + impl Inner { + pub(crate) fn from_static_ref(name: &'static str) -> Self { + Self(name) + } + + pub(crate) fn as_str(&self) -> &str { + self.0 + } + + pub(crate) fn into_string(self) -> String { + self.as_str().to_owned() + } + } +} + +pub(crate) use inner::Inner; + +impl Default for Inner { + fn default() -> Self { + Self::from_static_ref("") + } +} + +impl PartialEq for Inner { + fn eq(&self, other: &Inner) -> bool { + self.as_str() == other.as_str() + } +} + +impl PartialOrd for Inner { + fn partial_cmp(&self, other: &Self) -> Option { + self.as_str().partial_cmp(other.as_str()) + } +} + +impl Ord for Inner { + fn cmp(&self, other: &Inner) -> std::cmp::Ordering { + self.as_str().cmp(other.as_str()) + } +} + +impl Eq for Inner {} + +impl std::hash::Hash for Inner { + #[inline] + fn hash(&self, state: &mut H) { + self.as_str().hash(state); + } +} diff --git a/vendor/clap/src/builder/styled_str.rs b/vendor/clap/src/builder/styled_str.rs new file mode 100644 index 000000000..d36329dee --- /dev/null +++ b/vendor/clap/src/builder/styled_str.rs @@ -0,0 +1,349 @@ +/// Terminal-styling container +/// +/// For now, this is the same as a [`Str`][crate::builder::Str]. This exists to reserve space in +/// the API for exposing terminal styling. +#[derive(Clone, Default, Debug, PartialEq, Eq)] +pub struct StyledStr { + #[cfg(feature = "color")] + pieces: Vec<(Option