From d43f1dbf6f1f7865dccfece0e1605a12efb76670 Mon Sep 17 00:00:00 2001 From: Ed Page Date: Tue, 19 Jul 2022 13:29:31 -0500 Subject: [PATCH] docs: Move everything to docs.rs A couple of things happened when preparing to release 3.0 - We needed derive documentation - I had liked how serde handled theres - I had bad experiences finding things in structopt's documentation - The examples were broken and we needed tests - The examples seemed to follow a pattern of having tutorial content and cookbook content - We had been getting bug reports from people looking at master and thinking they were looking at what is currently released - We had gotten feedback to keep down the number of places that documentation was located From this, we went with a mix of docs.rs and github - We kept the number of content locations at 2 rather than 3 by not having an external site like serde - We rewrote the examples into explicit tutorials and cookbooks to align with the 4 styles of documentation - We could test our examples by running `console` code blocks with trycmd - Documentation was versioned and the README pointed to the last release This had downsides - The tutorials didn't have the code inlined - Users still had a hard time finding and navigating between the different forms of documentation - In practice, we were less likely to cross-link between the different types of documentation Moving to docs.rs would offer a lot of benefits, even if it is only designed for Rust-reference documentation and isn't good for Rust derive reference documentation, tutorials, cookbooks, etc. The big problem was keeping the examples tested to keep maintenance costs down. Maybe its just me but its easy to overlook - You can pull documentation from a file using `#[doc = "path"]` - Repeated doc attributes get concatenated rather than first or last writer winning Remember these when specifically thinking about Rust documentation made me realize that we could get everything into docs.rs. When doing this - Tutorial code got brought in as was one of the aims - We needed to split the lib documentation and the README to have all of the linking work. This allowed us to specialize them according to their rule (user vs contributor) - We needed to avoid users getting caught up in making a decision between Derive and Builder APIs so we put the focus on the derive API with links to the FAQ to help users decide when to use one or the other. - Improved cross-referencing between different parts of the documentation - Limited inline comments were added to example code - Introductory example code intentionally does not have teaching comments in it as its meant to give a flavor or sense of things and not meant to teach on its own. This is a first attempt. There will be a lot of room for further improvement. Current know downsides: - Content source is more split up for the tutorials This hopefully addresses #3189 --- README.md | 143 +--- docs/FAQ.md | 76 -- examples/README.md | 40 -- examples/cargo-example-derive.md | 2 - examples/cargo-example-derive.rs | 4 +- examples/cargo-example.md | 2 - examples/cargo-example.rs | 2 - examples/demo.md | 9 +- examples/demo.rs | 2 - examples/derive_ref/README.md | 440 ------------ examples/derive_ref/augment_args.rs | 4 +- examples/escaped-positional-derive.md | 4 +- examples/escaped-positional-derive.rs | 4 +- examples/escaped-positional.md | 4 +- examples/escaped-positional.rs | 4 +- examples/git-derive.md | 4 +- examples/git-derive.rs | 4 +- examples/git.md | 2 - examples/git.rs | 2 - examples/multicall-busybox.md | 6 +- examples/multicall-hostname.md | 6 +- examples/pacman.md | 2 - examples/tutorial_builder/01_quick.md | 37 + examples/tutorial_builder/01_quick.rs | 4 +- examples/tutorial_builder/02_app_settings.md | 19 + examples/tutorial_builder/02_app_settings.rs | 4 +- examples/tutorial_builder/02_apps.md | 19 + examples/tutorial_builder/02_crate.md | 18 + examples/tutorial_builder/02_crate.rs | 3 +- examples/tutorial_builder/03_01_flag_bool.md | 23 + examples/tutorial_builder/03_01_flag_bool.rs | 4 +- examples/tutorial_builder/03_01_flag_count.md | 23 + examples/tutorial_builder/03_01_flag_count.rs | 4 +- examples/tutorial_builder/03_02_option.md | 32 + examples/tutorial_builder/03_02_option.rs | 4 +- examples/tutorial_builder/03_03_positional.md | 22 + examples/tutorial_builder/03_03_positional.rs | 6 +- .../tutorial_builder/03_04_subcommands.md | 64 ++ .../tutorial_builder/03_04_subcommands.rs | 4 +- .../tutorial_builder/03_05_default_values.md | 22 + .../tutorial_builder/03_05_default_values.rs | 4 +- examples/tutorial_builder/04_01_enum.md | 29 + examples/tutorial_builder/04_01_enum.rs | 6 +- examples/tutorial_builder/04_01_possible.md | 29 + examples/tutorial_builder/04_01_possible.rs | 4 +- examples/tutorial_builder/04_02_parse.md | 31 + examples/tutorial_builder/04_02_parse.rs | 4 +- examples/tutorial_builder/04_02_validate.md | 31 + examples/tutorial_builder/04_02_validate.rs | 4 +- examples/tutorial_builder/04_03_relations.md | 58 ++ examples/tutorial_builder/04_03_relations.rs | 4 +- examples/tutorial_builder/04_04_custom.md | 57 ++ examples/tutorial_builder/04_04_custom.rs | 4 +- examples/tutorial_builder/05_01_assert.rs | 15 +- examples/tutorial_builder/README.md | 658 ------------------ examples/tutorial_derive/01_quick.md | 37 + examples/tutorial_derive/02_app_settings.md | 19 + examples/tutorial_derive/02_apps.md | 19 + examples/tutorial_derive/02_crate.md | 18 + examples/tutorial_derive/02_crate.rs | 2 +- examples/tutorial_derive/03_01_flag_bool.md | 23 + examples/tutorial_derive/03_01_flag_count.md | 23 + examples/tutorial_derive/03_02_option.md | 32 + examples/tutorial_derive/03_03_positional.md | 22 + examples/tutorial_derive/03_04_subcommands.md | 64 ++ .../tutorial_derive/03_05_default_values.md | 22 + examples/tutorial_derive/04_01_enum.md | 29 + examples/tutorial_derive/04_02_parse.md | 31 + examples/tutorial_derive/04_02_validate.md | 31 + examples/tutorial_derive/04_03_relations.md | 58 ++ examples/tutorial_derive/04_04_custom.md | 57 ++ examples/tutorial_derive/05_01_assert.rs | 2 +- examples/tutorial_derive/README.md | 639 ----------------- examples/typed-derive.md | 4 +- examples/typed-derive.rs | 4 +- src/_cookbook/cargo_example.rs | 7 + src/_cookbook/cargo_example_derive | 0 src/_cookbook/cargo_example_derive.rs | 7 + src/_cookbook/escaped_positional.rs | 7 + src/_cookbook/escaped_positional_derive.rs | 7 + src/_cookbook/git.rs | 7 + src/_cookbook/git_derive.rs | 7 + src/_cookbook/mod.rs | 55 ++ src/_cookbook/multicall_busybox.rs | 7 + src/_cookbook/multicall_hostname.rs | 7 + src/_cookbook/pacman.rs | 7 + src/_cookbook/repl.rs | 5 + src/_cookbook/typed_derive.rs | 7 + src/_derive/_tutorial.rs | 205 ++++++ src/_derive/mod.rs | 496 +++++++++++++ src/_faq.rs | 95 +++ src/_features.rs | 27 + src/_tutorial.rs | 204 ++++++ src/derive.rs | 24 +- src/lib.rs | 85 ++- 95 files changed, 2293 insertions(+), 2125 deletions(-) delete mode 100644 docs/FAQ.md delete mode 100644 examples/README.md delete mode 100644 examples/derive_ref/README.md create mode 100644 examples/tutorial_builder/01_quick.md create mode 100644 examples/tutorial_builder/02_app_settings.md create mode 100644 examples/tutorial_builder/02_apps.md create mode 100644 examples/tutorial_builder/02_crate.md create mode 100644 examples/tutorial_builder/03_01_flag_bool.md create mode 100644 examples/tutorial_builder/03_01_flag_count.md create mode 100644 examples/tutorial_builder/03_02_option.md create mode 100644 examples/tutorial_builder/03_03_positional.md create mode 100644 examples/tutorial_builder/03_04_subcommands.md create mode 100644 examples/tutorial_builder/03_05_default_values.md create mode 100644 examples/tutorial_builder/04_01_enum.md create mode 100644 examples/tutorial_builder/04_01_possible.md create mode 100644 examples/tutorial_builder/04_02_parse.md create mode 100644 examples/tutorial_builder/04_02_validate.md create mode 100644 examples/tutorial_builder/04_03_relations.md create mode 100644 examples/tutorial_builder/04_04_custom.md delete mode 100644 examples/tutorial_builder/README.md create mode 100644 examples/tutorial_derive/01_quick.md create mode 100644 examples/tutorial_derive/02_app_settings.md create mode 100644 examples/tutorial_derive/02_apps.md create mode 100644 examples/tutorial_derive/02_crate.md create mode 100644 examples/tutorial_derive/03_01_flag_bool.md create mode 100644 examples/tutorial_derive/03_01_flag_count.md create mode 100644 examples/tutorial_derive/03_02_option.md create mode 100644 examples/tutorial_derive/03_03_positional.md create mode 100644 examples/tutorial_derive/03_04_subcommands.md create mode 100644 examples/tutorial_derive/03_05_default_values.md create mode 100644 examples/tutorial_derive/04_01_enum.md create mode 100644 examples/tutorial_derive/04_02_parse.md create mode 100644 examples/tutorial_derive/04_02_validate.md create mode 100644 examples/tutorial_derive/04_03_relations.md create mode 100644 examples/tutorial_derive/04_04_custom.md delete mode 100644 examples/tutorial_derive/README.md create mode 100644 src/_cookbook/cargo_example.rs create mode 100644 src/_cookbook/cargo_example_derive create mode 100644 src/_cookbook/cargo_example_derive.rs create mode 100644 src/_cookbook/escaped_positional.rs create mode 100644 src/_cookbook/escaped_positional_derive.rs create mode 100644 src/_cookbook/git.rs create mode 100644 src/_cookbook/git_derive.rs create mode 100644 src/_cookbook/mod.rs create mode 100644 src/_cookbook/multicall_busybox.rs create mode 100644 src/_cookbook/multicall_hostname.rs create mode 100644 src/_cookbook/pacman.rs create mode 100644 src/_cookbook/repl.rs create mode 100644 src/_cookbook/typed_derive.rs create mode 100644 src/_derive/_tutorial.rs create mode 100644 src/_derive/mod.rs create mode 100644 src/_faq.rs create mode 100644 src/_features.rs create mode 100644 src/_tutorial.rs diff --git a/README.md b/README.md index 524a3a0a993..285efe86cb4 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,3 @@ - # clap > **Command Line Argument Parser for Rust** @@ -13,149 +12,13 @@ Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT). -1. [About](#about) -2. Tutorial: [Builder API](https://github.com/clap-rs/clap/blob/v3.2.12/examples/tutorial_builder/README.md), [Derive API](https://github.com/clap-rs/clap/blob/v3.2.12/examples/tutorial_derive/README.md) -3. [Examples](https://github.com/clap-rs/clap/blob/v3.2.12/examples/README.md) -4. [API Reference](https://docs.rs/clap) - - [Derive Reference](https://github.com/clap-rs/clap/blob/v3.2.12/examples/derive_ref/README.md) - - [Feature Flags](#feature-flags) -5. [CHANGELOG](https://github.com/clap-rs/clap/blob/v3.2.12/CHANGELOG.md) -6. [FAQ](https://github.com/clap-rs/clap/blob/v3.2.12/docs/FAQ.md) -7. [Questions & Discussions](https://github.com/clap-rs/clap/discussions) -8. [Contributing](https://github.com/clap-rs/clap/blob/v3.2.12/CONTRIBUTING.md) -8. [Sponsors](#sponsors) - ## About Create your command-line parser, with all of the bells and whistles, declaratively or procedurally. -### Example - -Add `clap` as a dependency with the `derive` feature enabled: -```console -cargo add clap -F derive -``` - -This allows using the -[Derive API](https://github.com/clap-rs/clap/blob/v3.2.12/examples/tutorial_derive/README.md) -which provides access to the [Builder API](https://github.com/clap-rs/clap/blob/v3.2.12/examples/tutorial_builder/README.md) as attributes on a `struct`: - - -```rust,no_run -use clap::Parser; - -/// Simple program to greet a person -#[derive(Parser, Debug)] -#[clap(author, version, about, long_about = None)] -struct Args { - /// Name of the person to greet - #[clap(short, long, value_parser)] - name: String, - - /// Number of times to greet - #[clap(short, long, value_parser, default_value_t = 1)] - count: u8, -} - -fn main() { - let args = Args::parse(); - - for _ in 0..args.count { - println!("Hello {}!", args.name) - } -} -``` - -```bash -$ demo --help -clap [..] -Simple program to greet a person - -USAGE: - demo[EXE] [OPTIONS] --name - -OPTIONS: - -c, --count Number of times to greet [default: 1] - -h, --help Print help information - -n, --name Name of the person to greet - -V, --version Print version information -``` -*(version number and `.exe` extension on windows replaced by placeholders)* - -### Aspirations - -- Out of the box, users get a polished CLI experience - - Including common argument behavior, help generation, suggested fixes for users, colored output, [shell completions](https://github.com/clap-rs/clap/tree/master/clap_complete), etc -- Flexible enough to port your existing CLI interface - - However, we won't necessarily streamline support for each use case -- Reasonable parse performance -- Resilient maintainership, including - - Willing to break compatibility rather than batching up breaking changes in large releases - - Leverage feature flags to keep to one active branch - - Being under [WG-CLI](https://github.com/rust-cli/team/) to increase the bus factor -- We follow semver and will wait about 6-9 months between major breaking changes -- We will support the last two minor Rust releases (MSRV, currently 1.56.1) - -While these aspirations can be at odds with fast build times and low binary -size, we will still strive to keep these reasonable for the flexibility you -get. Check out the -[argparse-benchmarks](https://github.com/rust-cli/argparse-benchmarks-rs) for -CLI parsers optimized for other use cases. - -### Selecting an API - -Why use the declarative [Derive API](https://github.com/clap-rs/clap/blob/v3.2.12/examples/tutorial_derive/README.md): -- Easier to read, write, and modify -- Easier to keep the argument declaration and reading of argument in sync -- Easier to reuse, e.g. [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag) - -Why use the procedural [Builder API](https://github.com/clap-rs/clap/blob/v3.2.12/examples/tutorial_builder/README.md): -- Faster compile times if you aren't already using other procedural macros -- More flexible, e.g. you can look up how many times an argument showed up, - what its values were, and what were the indexes of those values. The Derive - API can only report presence, number of occurrences, or values but no indices - or combinations of data. - -### Related Projects - -- [wild](https://crates.io/crates/wild) for supporting wildcards (`*`) on Windows like you do Linux -- [argfile](https://crates.io/crates/argfile) for loading additional arguments from a file (aka response files) -- [shadow-rs](https://crates.io/crates/shadow-rs) for generating `Command::long_version` -- [clap_lex](https://crates.io/crates/clap_lex) for a lighter-weight, battle-tested CLI parser -- [clap_mangen](https://crates.io/crates/clap_mangen) for generating man page source (roff) -- [clap_complete](https://crates.io/crates/clap_complete) for shell completion support -- [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag) -- [clap-cargo](https://crates.io/crates/clap-cargo) -- [concolor-clap](https://crates.io/crates/concolor-clap) -- [Command-line Apps for Rust](https://rust-cli.github.io/book/index.html) book -- [`trycmd`](https://crates.io/crates/trycmd): Snapshot testing - - Or for more control, [`assert_cmd`](https://crates.io/crates/assert_cmd) and [`assert_fs`](https://crates.io/crates/assert_fs) - -## Feature Flags - -### Default Features - -* **std**: _Not Currently Used._ Placeholder for supporting `no_std` environments in a backwards compatible manner. -* **color**: Turns on colored error messages. -* **suggestions**: Turns on the `Did you mean '--myoption'?` feature for when users make typos. - -#### Optional features - -* **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. -* **env**: Turns on the usage of environment variables during parsing. -* **regex**: Enables regex validators. -* **unicode**: Turns on support for unicode characters (including emoji) in arguments and help messages. -* **wrap_help**: Turns on the help text wrapping feature, based on the terminal size. - -#### Experimental features - -**Warning:** These may contain breaking changes between minor releases. - -* **unstable-replace**: Enable [`Command::replace`](https://github.com/clap-rs/clap/issues/2836) -* **unstable-grouped**: Enable [`ArgMatches::grouped_values_of`](https://github.com/clap-rs/clap/issues/2924) -* **unstable-v4**: Preview features which will be stable on the v4.0 release +For more details, see: +- [docs.rs](https://docs.rs/clap/latest/clap/) +- [examples](examples/) ## Sponsors diff --git a/docs/FAQ.md b/docs/FAQ.md deleted file mode 100644 index fe212eae49d..00000000000 --- a/docs/FAQ.md +++ /dev/null @@ -1,76 +0,0 @@ -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. [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 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 which 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 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](../examples/tutorial_derive/README.md) -- [Builder](../examples/tutorial_builder/README.md) - -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 - -### 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/examples/README.md b/examples/README.md deleted file mode 100644 index 2034ab80e3f..00000000000 --- a/examples/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# Examples - -- Basic demo: [derive](demo.md) -- Typed arguments: [derive](typed-derive.md) - - Topics: - - Custom `parse()` -- Custom cargo command: [builder](cargo-example.md), [derive](cargo-example-derive.md) - - Topics: - - Subcommands - - Cargo plugins -- git-like interface: [builder](git.md), [derive](git-derive.md) - - Topics: - - Subcommands - - External subcommands - - Optional subcommands - - Default subcommands -- pacman-like interface: [builder](pacman.md) - - Topics: - - Flag subcommands - - Conflicting arguments -- Escaped positionals with `--`: [builder](escaped-positional.md), [derive](escaped-positional-derive.md) -- Multi-call - - busybox: [builder](multicall-busybox.md) - - Topics: - - Subcommands - - hostname: [builder](multicall-hostname.md) - - Topics: - - Subcommands -- repl: [builder](repl.rs) - - Topics: - - Read-Eval-Print Loops / Custom command lines - -## Contributing - -New examples: -- Building: They must be added to [Cargo.toml](../Cargo.toml) with the appropriate `required-features`. -- Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax -- Link the `.md` file from here - -See also the general [CONTRIBUTING](../CONTRIBUTING.md). diff --git a/examples/cargo-example-derive.md b/examples/cargo-example-derive.md index 994c6d4d80c..2c7a11b8816 100644 --- a/examples/cargo-example-derive.md +++ b/examples/cargo-example-derive.md @@ -1,5 +1,3 @@ -*Jump to [source](cargo-example-derive.rs)* - For more on creating a custom subcommand, see [the cargo book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands). The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in diff --git a/examples/cargo-example-derive.rs b/examples/cargo-example-derive.rs index 6667a4a7df9..f0aad29c764 100644 --- a/examples/cargo-example-derive.rs +++ b/examples/cargo-example-derive.rs @@ -1,8 +1,6 @@ -// Note: this requires the `derive` feature - use clap::Parser; -#[derive(Parser)] +#[derive(Parser)] // requires `derive` feature #[clap(name = "cargo")] #[clap(bin_name = "cargo")] enum Cargo { diff --git a/examples/cargo-example.md b/examples/cargo-example.md index 9279cc49250..6fb6a3c4d96 100644 --- a/examples/cargo-example.md +++ b/examples/cargo-example.md @@ -1,5 +1,3 @@ -*Jump to [source](cargo-example.rs)* - For more on creating a custom subcommand, see [the cargo book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands). The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in diff --git a/examples/cargo-example.rs b/examples/cargo-example.rs index 45ae67c81d9..d9a909f4f0b 100644 --- a/examples/cargo-example.rs +++ b/examples/cargo-example.rs @@ -1,5 +1,3 @@ -// Note: this requires the `cargo` feature - fn main() { let cmd = clap::Command::new("cargo") .bin_name("cargo") diff --git a/examples/demo.md b/examples/demo.md index 9b0e7e260f1..93ee49c3725 100644 --- a/examples/demo.md +++ b/examples/demo.md @@ -1,8 +1,3 @@ -*Jump to [source](demo.rs)* - -**This requires enabling the `derive` feature flag.** - -Used to validate README.md's content ```console $ demo --help clap [..] @@ -17,4 +12,8 @@ OPTIONS: -n, --name Name of the person to greet -V, --version Print version information +$ demo --name Me +Hello Me! + ``` +*(version number and `.exe` extension on windows replaced by placeholders)* diff --git a/examples/demo.rs b/examples/demo.rs index 95748972444..a7cecfb0cc1 100644 --- a/examples/demo.rs +++ b/examples/demo.rs @@ -1,5 +1,3 @@ -// Note: this requires the `derive` feature - use clap::Parser; /// Simple program to greet a person diff --git a/examples/derive_ref/README.md b/examples/derive_ref/README.md deleted file mode 100644 index db5113d82b6..00000000000 --- a/examples/derive_ref/README.md +++ /dev/null @@ -1,440 +0,0 @@ -# Derive Reference - -1. [Overview](#overview) -2. [Attributes](#attributes) - 1. [Terminology](#terminology) - 2. [Command Attributes](#command-attributes) - 3. [Arg Attributes](#arg-attributes) - 4. [Arg Enum Attributes](#arg-enum-attributes) - 5. [Possible Value Attributes](#possible-value-attributes) -3. [Arg Types](#arg-types) -4. [Doc Comments](#doc-comments) -5. [Tips](#tips) -6. [Mixing Builder and Derive APIs](#mixing-builder-and-derive-apis) - -## Overview - -To derive `clap` types, you need to enable the `derive` feature flag. - -See [demo.rs](../demo.rs) and [demo.md](../demo.md) for a brief example. - -Let's start by breaking down the anatomy of the derive attributes: -```rust -use clap::{Parser, Args, Subcommand, ValueEnum}; - -/// Doc comment -#[derive(Parser)] -#[clap(APP ATTRIBUTE)] -struct Cli { - /// Doc comment - #[clap(ARG ATTRIBUTE)] - field: UserType, - - #[clap(value_enum, ARG ATTRIBUTE...)] - field: EnumValues, - - #[clap(flatten)] - delegate: Struct, - - #[clap(subcommand)] - command: Command, -} - -/// Doc comment -#[derive(Args)] -#[clap(PARENT APP ATTRIBUTE)] -struct Struct { - /// Doc comment - #[clap(ARG ATTRIBUTE)] - field: UserType, -} - -/// Doc comment -#[derive(Subcommand)] -#[clap(PARENT APP ATTRIBUTE)] -enum Command { - /// Doc comment - #[clap(APP ATTRIBUTE)] - Variant1(Struct), - - /// Doc comment - #[clap(APP ATTRIBUTE)] - Variant2 { - /// Doc comment - #[clap(ARG ATTRIBUTE)] - field: UserType, - } -} - -/// Doc comment -#[derive(ValueEnum)] -#[clap(ARG ENUM ATTRIBUTE)] -enum EnumValues { - /// Doc comment - #[clap(POSSIBLE VALUE ATTRIBUTE)] - Variant1, -} - -fn main() { - let cli = Cli::parse(); -} -``` - -- `Parser` parses arguments into a `struct` (arguments) or `enum` (subcommands). -- `Args` allows defining a set of re-usable arguments that get merged into their parent container. -- `Subcommand` defines available subcommands. - - Subcommand arguments can be defined in a struct-variant or automatically flattened with a tuple-variant. -- `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 [tutorial](../tutorial_derive/README.md) and [examples](../README.md). - -## Attributes - -### Terminology - -**Raw attributes** are forwarded directly to the underlying `clap` builder. Any -`Command`, `Arg`, or `PossibleValue` method can be used as an attribute. - -Raw attributes come in two different syntaxes: -```rust -#[clap( - global = true, // name = arg form, neat for one-arg methods - required_if_eq("out", "file") // name(arg1, arg2, ...) form. -)] -``` - -- `method = arg` can only be used for methods which take only one argument. -- `method(arg1, arg2)` can be used with any method. - -As long as `method_name` is not one of the magical methods - it will be -translated into a mere method call. - -**Magic attributes** have post-processing done to them, whether that is -- Providing of defaults -- Special behavior is triggered off of it - -Magic attributes are more constrained in the syntax they support, usually just -` = ` 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 `clap::Command` which is used for both top-level parsers and -when defining subcommands. - -**Raw attributes:** Any [`Command` method](https://docs.rs/clap/latest/clap/type.Command.html) can also be used as an attribute, see [Terminology](#terminology) for syntax. -- e.g. `#[clap(arg_required_else_help(true))]` would translate to `cmd.arg_required_else_help(true)` - -**Magic attributes:** -- `name = `: `clap::Command::name` - - When not present: [crate `name`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-name-field) (`Parser` container), variant name (`Subcommand` variant) -- `version [= ]`: `clap::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 [= ]`: `clap::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 [= ]`: `clap::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` container) - - **TIP:** When a doc comment is also present, you most likely want to add - `#[clap(long_about = None)]` to clear the doc comment so only `about` - gets shown with both `-h` and `--help`. -- `long_about = `: `clap::Command::long_about` - - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing -- `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to `about` / `long_about` -- `next_display_order`: `clap::Command::next_display_order` -- `next_help_heading`: `clap::Command::next_help_heading` - - When `flatten`ing `Args`, this is scoped to just the args in this struct and any struct `flatten`ed into it -- `rename_all = `: Override default field / variant name case conversion for `Command::name` / `Arg::name` - - When not present: `"kebab-case"` - - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"` -- `rename_all_env = `: Override default field name case conversion for env variables for `clap::Arg::env` - - When not present: `"SCREAMING_SNAKE_CASE"` - - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"` - -And for `Subcommand` variants: -- `skip`: Ignore this variant -- `flatten`: Delegates to the variant for more subcommands (must implement `Subcommand`) -- `subcommand`: Nest subcommands under the current set of subcommands (must implement `Subcommand`) -- `external_subcommand`: `clap::Command::allow_external_subcommand(true)` - - Variant must be either `Variant(Vec)` or `Variant(Vec)` - -### Arg Attributes - -These correspond to a `clap::Arg`. - -**Raw attributes:** Any [`Arg` method](https://docs.rs/clap/latest/clap/struct.Arg.html) can also be used as an attribute, see [Terminology](#terminology) for syntax. -- e.g. `#[clap(max_values(3))]` would translate to `arg.max_values(3)` - -**Magic attributes**: -- `name = `: `clap::Arg::new` - - When not present: case-converted field name is used -- `value_parser [= ]`: `clap::Arg::value_parser` - - When not present: will auto-select an implementation based on the field type - - To register a custom type's `ValueParser`, implement `ValueParserFactory` - - When present, implies `#[clap(action)]` -- `action [= ]`: `clap::Arg::action` - - When not present: will auto-select an action based on the field type - - When present, implies `#[clap(value_parser)]` -- `help = `: `clap::Arg::help` - - When not present: [Doc comment summary](#doc-comments) -- `long_help = `: `clap::Arg::long_help` - - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing -- `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to `help` / `long_help` -- `short [= ]`: `clap::Arg::short` - - When not present: no short set - - Without ``: defaults to first character in the case-converted field name -- `long [= ]`: `clap::Arg::long` - - When not present: no long set - - Without ``: defaults to the case-converted field name -- `env [= ]`: `clap::Arg::env` (needs `env` feature enabled) - - When not present: no env set - - Without ``: defaults to the case-converted field name -- `flatten`: Delegates to the field for more arguments (must implement `Args`) - - Only `help_heading` can be used with `flatten`. See - [clap-rs/clap#3269](https://github.com/clap-rs/clap/issues/3269) for why - arg attributes are not generally supported. - - **Tip:** Though we do apply a flattened `Args`'s Parent Command Attributes, this - makes reuse harder. Generally prefer putting the cmd attributes on the `Parser` - or on the flattened field. -- `subcommand`: Delegates definition of subcommands to the field (must implement `Subcommand`) - - When `Option`, the subcommand becomes optional -- `from_global`: Read a `clap::Arg::global` argument (raw attribute), regardless of what subcommand you are in -- `parse( [= ])`: `clap::Arg::validator` and `clap::ArgMatches::values_of_t` - - **Deprecated:** - - Use `value_parser(...)` for `from_str`, `try_from_str`, `from_os_str`, and `try_from_os_str` - - Use `action(ArgAction::Count` for `from_occurrences` - - Use `action(ArgAction::SetTrue` for `from_flag` - - Default: `try_from_str` - - Warning: for `Path` / `OsString`, be sure to use `try_from_os_str` - - See [Arg Types](#arg-types) for more details -- `value_enum`: Parse the value using the `ValueEnum` trait -- `skip [= ]`: Ignore this field, filling in with `` - - Without ``: fills the field with `Default::default()` -- `default_value = `: `clap::Arg::default_value` and `clap::Arg::required(false)` -- `default_value_t [= ]`: `clap::Arg::default_value` and `clap::Arg::required(false)` - - Requires `std::fmt::Display` or `#[clap(value_enum)]` - - Without ``, relies on `Default::default()` -- `default_value_os_t [= ]`: `clap::Arg::default_value_os` and `clap::Arg::required(false)` - - Requires `std::convert::Into` or `#[clap(value_enum)]` - - Without ``, relies on `Default::default()` - -### Arg Enum Attributes - -- `rename_all = `: Override default field / variant name case conversion for `PossibleValue::new` - - When not present: `"kebab-case"` - - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"` - -### Possible Value Attributes - -These correspond to a `clap::PossibleValue`. - -**Raw attributes:** Any [`PossibleValue` method](https://docs.rs/clap/latest/clap/struct.PossibleValue.html) can also be used as an attribute, see [Terminology](#terminology) for syntax. -- e.g. `#[clap(alias("foo"))]` would translate to `pv.alias("foo")` - -**Magic attributes**: -- `name = `: `clap::PossibleValue::new` - - When not present: case-converted field name is used -- `help = `: `clap::PossibleValue::help` - - When not present: [Doc comment summary](#doc-comments) - -## Arg Types - -`clap` assumes some intent based on the type used: - -| Type | Effect | Implies | -|---------------------|--------------------------------------|------------------------------------------------------------------| -| `bool` | flag | `#[clap(parse(from_flag))]` | -| `Option` | optional argument | `.takes_value(true).required(false)` | -| `Option>` | optional value for optional argument | `.takes_value(true).required(false).min_values(0).max_values(1)` | -| `T` | required argument | `.takes_value(true).required(!has_default)` | -| `Vec` | `0..` occurrences of argument | `.takes_value(true).required(false).multiple_occurrences(true)` | -| `Option>` | `0..` occurrences of argument | `.takes_value(true).required(false).multiple_occurrences(true)` | - -Notes: -- For custom type behavior, you can override the implied attributes/settings and/or set additional ones - - For example, see [custom-bool](./custom-bool.md) -- `Option>` will be `None` instead of `vec![]` if no arguments are provided. - - This gives the user some flexibility in designing their argument, like with `min_values(0)` - -You can then support your custom type with `#[clap(parse( [= ]))]`: - -| `` | Signature | Default `` | -|--------------------------|---------------------------------------|---------------------------------| -| `from_str` | `fn(&str) -> T` | `::std::convert::From::from` | -| `try_from_str` (default) | `fn(&str) -> Result` | `::std::str::FromStr::from_str` | -| `from_os_str` | `fn(&OsStr) -> T` | `::std::convert::From::from` | -| `try_from_os_str` | `fn(&OsStr) -> Result` | (no default function) | -| `from_occurrences` | `fn(u64) -> T` | `value as T` | -| `from_flag` | `fn(bool) -> T` | `::std::convert::From::from` | - -Notes: -- `from_os_str`: - - Implies `arg.takes_value(true).allow_invalid_utf8(true)` -- `try_from_os_str`: - - Implies `arg.takes_value(true).allow_invalid_utf8(true)` -- `from_occurrences`: - - Implies `arg.takes_value(false).multiple_occurrences(true)` - - Reads from `clap::ArgMatches::occurrences_of` rather than a `get_one` function - - Note: operations on values, like `default_value`, are unlikely to do what you want -- `from_flag` - - Implies `arg.takes_value(false)` - - Reads from `clap::ArgMatches::is_present` rather than a `get_one` function - - Note: operations on values, like `default_value`, are unlikely to do what you want - -**Warning:** -- To support non-UTF8 paths, you should use `#[clap(value_parser)]` otherwise - `clap` will parse it as a `String` which will fail on some paths. - -## Doc Comments - -In clap, help messages for the whole binary can be specified -via [`Command::about`] and [`Command::long_about`] while help messages -for individual arguments can be specified via [`Arg::help`] and [`Arg::long_help`]". - -`long_*` variants are used when user calls the program with -`--help` and "short" variants are used with `-h` flag. - -```rust -# use clap::Parser; - -#[derive(Parser)] -#[clap(about = "I am a program and I work, just pass `-h`", long_about = None)] -struct Foo { - #[clap(short, help = "Pass `-h` and you'll see me!")] - bar: String, -} -``` - -For convenience, doc comments can be used instead of raw methods -(this example works exactly like the one above): - -```rust -# use clap::Parser; - -#[derive(Parser)] -/// I am a program and I work, just pass `-h` -struct Foo { - /// Pass `-h` and you'll see me! - bar: String, -} -``` - -**NOTE:** Attributes have priority over doc comments! - -**Top level doc comments always generate `Command::about/long_about` calls!** -If you really want to use the `Command::about/long_about` methods (you likely don't), -use the `about` / `long_about` attributes to override the calls generated from -the doc comment. To clear `long_about`, you can use -`#[clap(long_about = None)]`. - -**TIP:** Set `#![deny(missing_docs)]` to catch missing `--help` documentation at compile time. - -### Pre-processing - -```rust -# use clap::Parser; -#[derive(Parser)] -/// Hi there, I'm Robo! -/// -/// I like beeping, stumbling, eating your electricity, -/// and making records of you singing in a shower. -/// Pay up, or I'll upload it to youtube! -struct Robo { - /// Call my brother SkyNet. - /// - /// I am artificial superintelligence. I won't rest - /// until I'll have destroyed humanity. Enjoy your - /// pathetic existence, you mere mortals. - #[clap(long, 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 - -## Tips - -- To get access to a `Command` call `CommandFactory::command` (implemented when deriving `Parser`) -- Proactively check for bad `Command` configurations by calling `Command::debug_assert` in a test ([example](../tutorial_derive/05_01_assert.rs)) - -## Mixing Builder and Derive APIs - -The builder and derive APIs do not live in isolation. They can work together, which is especially helpful if some arguments can be specified at compile-time while others must be specified at runtime. - -### Using derived arguments in a builder application - -*[Jump to source](augment_args.rs)* - -When using the derive API, you can `#[clap(flatten)]` a struct deriving `Args` into a struct deriving `Args` or `Parser`. This example shows how you can augment a `Command` instance created using the builder API with `Args` created using the derive API. - -It uses the `Args::augment_args` method to add the arguments to the `Command` instance. - -Crates such as [clap-verbosity-flag](https://github.com/rust-cli/clap-verbosity-flag) provide structs that implement `Args` or `Parser`. Without the technique shown in this example, it would not be possible to use such crates with the builder API. `augment_args` to the rescue! - -### Using derived subcommands in a builder application - -*[Jump to source](augment_subcommands.rs)* - -When using the derive API, you can use `#[clap(subcommand)]` inside the struct to add subcommands. The type of the field is usually an enum that derived `Parser`. However, you can also add the subcommands in that enum to a `Command` instance created with the builder API. - -It uses the `Subcommand::augment_subcommands` method to add the subcommands to the `Command` instance. - -### Adding hand-implemented subcommands to a derived application - -*[Jump to source](hand_subcommand.rs)* - -When using the derive API, you can use `#[clap(subcommand)]` inside the struct to add subcommands. The type of the field is usually an enum that derived `Parser`. However, you can also implement the `Subcommand` trait manually on this enum (or any other type) and it can still be used inside the struct created with the derive API. The implementation of the `Subcommand` trait will use the builder API to add the subcommands to the `Command` instance created behind the scenes for you by the derive API. - -Notice how in the previous example we used `augment_subcommands` on an enum that derived `Parser`, whereas now we implement `augment_subcommands` ourselves, but the derive API calls it automatically since we used the `#[clap(subcommand)]` attribute. - -### Flattening hand-implemented args into a derived application - -*[Jump to source](flatten_hand_args.rs)* - -When using the derive API, you can use `#[clap(flatten)]` inside the struct to add arguments as if they were added directly to the containing struct. The type of the field is usually an struct that derived `Args`. However, you can also implement the `Args` trait manually on this struct (or any other type) and it can still be used inside the struct created with the derive API. The implementation of the `Args` trait will use the builder API to add the arguments to the `Command` instance created behind the scenes for you by the derive API. - -Notice how in the example 1 we used `augment_args` on the struct that derived `Parser`, whereas now we implement `augment_args` ourselves, but the derive API calls it automatically since we used the `#[clap(flatten)]` attribute. diff --git a/examples/derive_ref/augment_args.rs b/examples/derive_ref/augment_args.rs index 390c72f4a08..8a07f6743c5 100644 --- a/examples/derive_ref/augment_args.rs +++ b/examples/derive_ref/augment_args.rs @@ -1,6 +1,6 @@ -use clap::{arg, Args as _, Command, FromArgMatches as _, Parser}; +use clap::{arg, Args, Command, FromArgMatches as _}; -#[derive(Parser, Debug)] +#[derive(Args, Debug)] struct DerivedArgs { #[clap(short, long, action)] derived: bool, diff --git a/examples/escaped-positional-derive.md b/examples/escaped-positional-derive.md index 3b5f8fe5652..fa39a2c039d 100644 --- a/examples/escaped-positional-derive.md +++ b/examples/escaped-positional-derive.md @@ -1,6 +1,4 @@ -*Jump to [source](escaped-positional-derive.rs)* - -**This requires enabling the `derive` feature flag.** +**This requires enabling the [`derive` feature flag][crate::_features].** You can use `--` to escape further arguments. diff --git a/examples/escaped-positional-derive.rs b/examples/escaped-positional-derive.rs index 54dbc853b3f..fd8fde4ed25 100644 --- a/examples/escaped-positional-derive.rs +++ b/examples/escaped-positional-derive.rs @@ -1,8 +1,6 @@ -// Note: this requires the `derive` feature - use clap::Parser; -#[derive(Parser)] +#[derive(Parser)] // requires `derive` feature #[clap(author, version, about, long_about = None)] struct Cli { #[clap(short = 'f', action)] diff --git a/examples/escaped-positional.md b/examples/escaped-positional.md index 1f71a87369d..987b2613952 100644 --- a/examples/escaped-positional.md +++ b/examples/escaped-positional.md @@ -1,6 +1,4 @@ -*Jump to [source](escaped-positional.rs)* - -**This requires enabling the `cargo` feature flag.** +**This requires enabling the [`cargo` feature flag][crate::_features].** You can use `--` to escape further arguments. diff --git a/examples/escaped-positional.rs b/examples/escaped-positional.rs index a0fff790bc7..02420010022 100644 --- a/examples/escaped-positional.rs +++ b/examples/escaped-positional.rs @@ -1,9 +1,7 @@ -// Note: this requires the `cargo` feature - use clap::{arg, command, value_parser, ArgAction}; fn main() { - let matches = command!() + let matches = command!() // requires `cargo` feature .arg(arg!(eff: -f).action(ArgAction::SetTrue)) .arg( arg!(pea: -p ) diff --git a/examples/git-derive.md b/examples/git-derive.md index dc27776f582..aa1ca6d9dfa 100644 --- a/examples/git-derive.md +++ b/examples/git-derive.md @@ -1,6 +1,4 @@ -*Jump to [source](git-derive.rs)* - -**This requires enabling the `derive` feature flag.** +**This requires enabling the [`derive` feature flag][crate::_features].** Git is an example of several common subcommand patterns. diff --git a/examples/git-derive.rs b/examples/git-derive.rs index ecbda3fe9d3..ac500ddad08 100644 --- a/examples/git-derive.rs +++ b/examples/git-derive.rs @@ -1,12 +1,10 @@ -// Note: this requires the `derive` feature - use std::ffi::OsString; use std::path::PathBuf; use clap::{Args, Parser, Subcommand}; /// A fictional versioning CLI -#[derive(Debug, Parser)] +#[derive(Debug, Parser)] // requires `derive` feature #[clap(name = "git")] #[clap(about = "A fictional versioning CLI", long_about = None)] struct Cli { diff --git a/examples/git.md b/examples/git.md index 2cdfe653b3c..9e413415a4b 100644 --- a/examples/git.md +++ b/examples/git.md @@ -1,5 +1,3 @@ -*Jump to [source](git.rs)* - Git is an example of several common subcommand patterns. Help: diff --git a/examples/git.rs b/examples/git.rs index 5536f1487ca..e56f427a6ed 100644 --- a/examples/git.rs +++ b/examples/git.rs @@ -1,5 +1,3 @@ -// Note: this requires the `cargo` feature - use std::ffi::OsString; use std::path::PathBuf; diff --git a/examples/multicall-busybox.md b/examples/multicall-busybox.md index a09418403f7..5ca2cad5b82 100644 --- a/examples/multicall-busybox.md +++ b/examples/multicall-busybox.md @@ -1,8 +1,4 @@ -*Jump to [source](multicall-busybox.rs)* - -Example of a busybox-style multicall program - -See the documentation for `clap::Command::multicall` for rationale. +See the documentation for [`Command::multicall`][crate::App::multicall] for rationale. This example omits every command except true and false, which are the most trivial to implement, diff --git a/examples/multicall-hostname.md b/examples/multicall-hostname.md index 9e17ca16cbc..d22b85fba6b 100644 --- a/examples/multicall-hostname.md +++ b/examples/multicall-hostname.md @@ -1,8 +1,4 @@ -*Jump to [source](multicall-hostname.rs)* - -Example of a `hostname-style` multicall program - -See the documentation for `clap::Command::multicall` for rationale. +See the documentation for [`Command::multicall`][crate::App::multicall] for rationale. This example omits the implementation of displaying address config diff --git a/examples/pacman.md b/examples/pacman.md index 7f6c5a7d339..b8ddd09d91f 100644 --- a/examples/pacman.md +++ b/examples/pacman.md @@ -1,5 +1,3 @@ -*Jump to [source](pacman.rs)* - [`pacman`](https://wiki.archlinux.org/index.php/pacman) defines subcommands via flags. Here, `-S` is a short flag subcommand: diff --git a/examples/tutorial_builder/01_quick.md b/examples/tutorial_builder/01_quick.md new file mode 100644 index 00000000000..4a9e3fca17a --- /dev/null +++ b/examples/tutorial_builder/01_quick.md @@ -0,0 +1,37 @@ +```console +$ 01_quick --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 01_quick[EXE] [OPTIONS] [name] [SUBCOMMAND] + +ARGS: + Optional name to operate on + +OPTIONS: + -c, --config Sets a custom config file + -d, --debug Turn debugging information on + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + help Print this message or the help of the given subcommand(s) + test does testing things + +``` + +By default, the program does nothing: +```console +$ 01_quick +Debug mode is off + +``` + +But you can mix and match the various features +```console +$ 01_quick -dd test +Debug mode is on +Not printing testing lists... + +``` diff --git a/examples/tutorial_builder/01_quick.rs b/examples/tutorial_builder/01_quick.rs index 61cc3432d4b..393d6aeae5c 100644 --- a/examples/tutorial_builder/01_quick.rs +++ b/examples/tutorial_builder/01_quick.rs @@ -1,11 +1,9 @@ -// Note: this requires the `cargo` feature - use std::path::PathBuf; use clap::{arg, command, value_parser, ArgAction, Command}; fn main() { - let matches = command!() + let matches = command!() // requires `cargo` feature .arg(arg!([name] "Optional name to operate on")) .arg( arg!( diff --git a/examples/tutorial_builder/02_app_settings.md b/examples/tutorial_builder/02_app_settings.md new file mode 100644 index 00000000000..247843bcfdc --- /dev/null +++ b/examples/tutorial_builder/02_app_settings.md @@ -0,0 +1,19 @@ +```console +$ 02_app_settings --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 02_app_settings[EXE] --two --one + +OPTIONS: + --two + --one + -h, --help Print help information + -V, --version Print version information + +$ 02_app_settings --one -1 --one -3 --two 10 +two: "10" +one: "-3" + +``` diff --git a/examples/tutorial_builder/02_app_settings.rs b/examples/tutorial_builder/02_app_settings.rs index 7bbedd3ebbc..5f374d7f01c 100644 --- a/examples/tutorial_builder/02_app_settings.rs +++ b/examples/tutorial_builder/02_app_settings.rs @@ -1,9 +1,7 @@ -// Note: this requires the `cargo` feature - use clap::{arg, command, AppSettings, ArgAction}; fn main() { - let matches = command!() + let matches = command!() // requires `cargo` feature .global_setting(AppSettings::DeriveDisplayOrder) .allow_negative_numbers(true) .arg(arg!(--two ).action(ArgAction::Set)) diff --git a/examples/tutorial_builder/02_apps.md b/examples/tutorial_builder/02_apps.md new file mode 100644 index 00000000000..8504b5f5220 --- /dev/null +++ b/examples/tutorial_builder/02_apps.md @@ -0,0 +1,19 @@ +```console +$ 02_apps --help +MyApp 1.0 +Kevin K. +Does awesome things + +USAGE: + 02_apps[EXE] --two --one + +OPTIONS: + -h, --help Print help information + --one + --two + -V, --version Print version information + +$ 02_apps --version +MyApp 1.0 + +``` diff --git a/examples/tutorial_builder/02_crate.md b/examples/tutorial_builder/02_crate.md new file mode 100644 index 00000000000..f76e0d608b5 --- /dev/null +++ b/examples/tutorial_builder/02_crate.md @@ -0,0 +1,18 @@ +```console +$ 02_crate --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 02_crate[EXE] --two --one + +OPTIONS: + -h, --help Print help information + --one + --two + -V, --version Print version information + +$ 02_crate --version +clap [..] + +``` diff --git a/examples/tutorial_builder/02_crate.rs b/examples/tutorial_builder/02_crate.rs index 16b7e7ee0d6..8a1722fd338 100644 --- a/examples/tutorial_builder/02_crate.rs +++ b/examples/tutorial_builder/02_crate.rs @@ -1,8 +1,7 @@ -// Note: this requires the `cargo` feature - use clap::{arg, command}; fn main() { + // requires `cargo` feature, reading name, version, author, and description from `Cargo.toml` let matches = command!() .arg(arg!(--two )) .arg(arg!(--one )) diff --git a/examples/tutorial_builder/03_01_flag_bool.md b/examples/tutorial_builder/03_01_flag_bool.md new file mode 100644 index 00000000000..b0ee2a12635 --- /dev/null +++ b/examples/tutorial_builder/03_01_flag_bool.md @@ -0,0 +1,23 @@ +```console +$ 03_01_flag_bool --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_01_flag_bool[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -v, --verbose + -V, --version Print version information + +$ 03_01_flag_bool +verbose: false + +$ 03_01_flag_bool --verbose +verbose: true + +$ 03_01_flag_bool --verbose --verbose +verbose: true + +``` diff --git a/examples/tutorial_builder/03_01_flag_bool.rs b/examples/tutorial_builder/03_01_flag_bool.rs index 41ecbb1d73f..5aa55be9516 100644 --- a/examples/tutorial_builder/03_01_flag_bool.rs +++ b/examples/tutorial_builder/03_01_flag_bool.rs @@ -1,9 +1,7 @@ -// Note: this requires the `cargo` feature - use clap::{command, Arg, ArgAction}; fn main() { - let matches = command!() + let matches = command!() // requires `cargo` feature .arg( Arg::new("verbose") .short('v') diff --git a/examples/tutorial_builder/03_01_flag_count.md b/examples/tutorial_builder/03_01_flag_count.md new file mode 100644 index 00000000000..ca4bcd6eb89 --- /dev/null +++ b/examples/tutorial_builder/03_01_flag_count.md @@ -0,0 +1,23 @@ +```console +$ 03_01_flag_count --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_01_flag_count[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -v, --verbose + -V, --version Print version information + +$ 03_01_flag_count +verbose: 0 + +$ 03_01_flag_count --verbose +verbose: 1 + +$ 03_01_flag_count --verbose --verbose +verbose: 2 + +``` diff --git a/examples/tutorial_builder/03_01_flag_count.rs b/examples/tutorial_builder/03_01_flag_count.rs index 764affbd87c..059a3f30256 100644 --- a/examples/tutorial_builder/03_01_flag_count.rs +++ b/examples/tutorial_builder/03_01_flag_count.rs @@ -1,9 +1,7 @@ -// Note: this requires the `cargo` feature - use clap::{arg, command, ArgAction}; fn main() { - let matches = command!() + let matches = command!() // requires `cargo` feature .arg(arg!(-v - -verbose).action(ArgAction::Count)) .get_matches(); diff --git a/examples/tutorial_builder/03_02_option.md b/examples/tutorial_builder/03_02_option.md new file mode 100644 index 00000000000..6198bcc7372 --- /dev/null +++ b/examples/tutorial_builder/03_02_option.md @@ -0,0 +1,32 @@ +```console +$ 03_02_option --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_02_option[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -n, --name + -V, --version Print version information + +$ 03_02_option +name: None + +$ 03_02_option --name bob +name: Some("bob") + +$ 03_02_option --name=bob +name: Some("bob") + +$ 03_02_option -n bob +name: Some("bob") + +$ 03_02_option -n=bob +name: Some("bob") + +$ 03_02_option -nbob +name: Some("bob") + +``` diff --git a/examples/tutorial_builder/03_02_option.rs b/examples/tutorial_builder/03_02_option.rs index 80e2b915901..188244566f8 100644 --- a/examples/tutorial_builder/03_02_option.rs +++ b/examples/tutorial_builder/03_02_option.rs @@ -1,9 +1,7 @@ -// Note: this requires the `cargo` feature - use clap::{arg, command}; fn main() { - let matches = command!() + let matches = command!() // requires `cargo` feature .arg(arg!(-n --name ).required(false)) .get_matches(); diff --git a/examples/tutorial_builder/03_03_positional.md b/examples/tutorial_builder/03_03_positional.md new file mode 100644 index 00000000000..a3d7b8cf347 --- /dev/null +++ b/examples/tutorial_builder/03_03_positional.md @@ -0,0 +1,22 @@ +```console +$ 03_03_positional --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_03_positional[EXE] [NAME] + +ARGS: + + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_03_positional +NAME: None + +$ 03_03_positional bob +NAME: Some("bob") + +``` diff --git a/examples/tutorial_builder/03_03_positional.rs b/examples/tutorial_builder/03_03_positional.rs index c6579409a71..0c3a5f037b6 100644 --- a/examples/tutorial_builder/03_03_positional.rs +++ b/examples/tutorial_builder/03_03_positional.rs @@ -1,9 +1,9 @@ -// Note: this requires the `cargo` feature - use clap::{arg, command}; fn main() { - let matches = command!().arg(arg!([NAME])).get_matches(); + let matches = command!() // requires `cargo` feature + .arg(arg!([NAME])) + .get_matches(); println!("NAME: {:?}", matches.get_one::("NAME")); } diff --git a/examples/tutorial_builder/03_04_subcommands.md b/examples/tutorial_builder/03_04_subcommands.md new file mode 100644 index 00000000000..8f9efa911bf --- /dev/null +++ b/examples/tutorial_builder/03_04_subcommands.md @@ -0,0 +1,64 @@ +```console +$ 03_04_subcommands help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_04_subcommands[EXE] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + add Adds files to myapp + help Print this message or the help of the given subcommand(s) + +$ 03_04_subcommands help add +03_04_subcommands[EXE]-add [..] +Adds files to myapp + +USAGE: + 03_04_subcommands[EXE] add [NAME] + +ARGS: + + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_04_subcommands add bob +'myapp add' was used, name is: Some("bob") + +``` + +Because we set [`Command::arg_required_else_help`][crate::Command::arg_required_else_help]: +```console +$ 03_04_subcommands +? failed +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_04_subcommands[EXE] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + add Adds files to myapp + help Print this message or the help of the given subcommand(s) + +``` + +Because we set [`Command::propagate_version`][crate::Command::propagate_version]: +```console +$ 03_04_subcommands --version +clap [..] + +$ 03_04_subcommands add --version +03_04_subcommands[EXE]-add [..] + +``` diff --git a/examples/tutorial_builder/03_04_subcommands.rs b/examples/tutorial_builder/03_04_subcommands.rs index 1dd1cbf0940..fbe23809e92 100644 --- a/examples/tutorial_builder/03_04_subcommands.rs +++ b/examples/tutorial_builder/03_04_subcommands.rs @@ -1,9 +1,7 @@ -// Note: this requires the `cargo` feature - use clap::{arg, command, Command}; fn main() { - let matches = command!() + let matches = command!() // requires `cargo` feature .propagate_version(true) .subcommand_required(true) .arg_required_else_help(true) diff --git a/examples/tutorial_builder/03_05_default_values.md b/examples/tutorial_builder/03_05_default_values.md new file mode 100644 index 00000000000..7b6c0307d34 --- /dev/null +++ b/examples/tutorial_builder/03_05_default_values.md @@ -0,0 +1,22 @@ +```console +$ 03_05_default_values --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_05_default_values[EXE] [NAME] + +ARGS: + [default: alice] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_05_default_values +NAME: "alice" + +$ 03_05_default_values bob +NAME: "bob" + +``` diff --git a/examples/tutorial_builder/03_05_default_values.rs b/examples/tutorial_builder/03_05_default_values.rs index c68e8797332..cb3e3831f0f 100644 --- a/examples/tutorial_builder/03_05_default_values.rs +++ b/examples/tutorial_builder/03_05_default_values.rs @@ -1,9 +1,7 @@ -// Note: this requires the `cargo` feature - use clap::{arg, command}; fn main() { - let matches = command!() + let matches = command!() // requires `cargo` feature .arg(arg!([NAME]).default_value("alice")) .get_matches(); diff --git a/examples/tutorial_builder/04_01_enum.md b/examples/tutorial_builder/04_01_enum.md new file mode 100644 index 00000000000..282b1e61344 --- /dev/null +++ b/examples/tutorial_builder/04_01_enum.md @@ -0,0 +1,29 @@ +```console +$ 04_01_enum --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_01_enum[EXE] + +ARGS: + What mode to run the program in [possible values: fast, slow] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_01_enum fast +Hare + +$ 04_01_enum slow +Tortoise + +$ 04_01_enum medium +? failed +error: "medium" isn't a valid value for '' + [possible values: fast, slow] + +For more information try --help + +``` diff --git a/examples/tutorial_builder/04_01_enum.rs b/examples/tutorial_builder/04_01_enum.rs index ad2177c2313..e76c9512e1e 100644 --- a/examples/tutorial_builder/04_01_enum.rs +++ b/examples/tutorial_builder/04_01_enum.rs @@ -1,15 +1,13 @@ -// Note: this requires the `cargo` feature - use clap::{arg, command, value_parser, ValueEnum}; -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] // requires `derive` feature enum Mode { Fast, Slow, } fn main() { - let matches = command!() + let matches = command!() // requires `cargo` feature .arg( arg!() .help("What mode to run the program in") diff --git a/examples/tutorial_builder/04_01_possible.md b/examples/tutorial_builder/04_01_possible.md new file mode 100644 index 00000000000..2909bfb17e0 --- /dev/null +++ b/examples/tutorial_builder/04_01_possible.md @@ -0,0 +1,29 @@ +```console +$ 04_01_possible --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_01_possible[EXE] + +ARGS: + What mode to run the program in [possible values: fast, slow] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_01_possible fast +Hare + +$ 04_01_possible slow +Tortoise + +$ 04_01_possible medium +? failed +error: "medium" isn't a valid value for '' + [possible values: fast, slow] + +For more information try --help + +``` diff --git a/examples/tutorial_builder/04_01_possible.rs b/examples/tutorial_builder/04_01_possible.rs index f7b0cfb3415..3da7aca74b6 100644 --- a/examples/tutorial_builder/04_01_possible.rs +++ b/examples/tutorial_builder/04_01_possible.rs @@ -1,9 +1,7 @@ -// Note: this requires the `cargo` feature - use clap::{arg, command}; fn main() { - let matches = command!() + let matches = command!() // requires `cargo` feature .arg( arg!() .help("What mode to run the program in") diff --git a/examples/tutorial_builder/04_02_parse.md b/examples/tutorial_builder/04_02_parse.md new file mode 100644 index 00000000000..605bf4b5920 --- /dev/null +++ b/examples/tutorial_builder/04_02_parse.md @@ -0,0 +1,31 @@ +```console +$ 04_02_parse --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_02_parse[EXE] + +ARGS: + Network port to use + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_02_parse 22 +PORT = 22 + +$ 04_02_parse foobar +? failed +error: Invalid value "foobar" for '': invalid digit found in string + +For more information try --help + +$ 04_02_parse_derive 0 +? failed +error: Invalid value "0" for '': 0 is not in 1..=65535 + +For more information try --help + +``` diff --git a/examples/tutorial_builder/04_02_parse.rs b/examples/tutorial_builder/04_02_parse.rs index c2f3cc53341..13f41a18e31 100644 --- a/examples/tutorial_builder/04_02_parse.rs +++ b/examples/tutorial_builder/04_02_parse.rs @@ -1,9 +1,7 @@ -// Note: this requires the `cargo` feature - use clap::{arg, command, value_parser}; fn main() { - let matches = command!() + let matches = command!() // requires `cargo` feature .arg( arg!() .help("Network port to use") diff --git a/examples/tutorial_builder/04_02_validate.md b/examples/tutorial_builder/04_02_validate.md new file mode 100644 index 00000000000..a317a8eb76c --- /dev/null +++ b/examples/tutorial_builder/04_02_validate.md @@ -0,0 +1,31 @@ +```console +$ 04_02_validate --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_02_validate[EXE] + +ARGS: + Network port to use + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_02_validate 22 +PORT = 22 + +$ 04_02_validate foobar +? failed +error: Invalid value "foobar" for '': `foobar` isn't a port number + +For more information try --help + +$ 04_02_validate 0 +? failed +error: Invalid value "0" for '': Port not in range 1-65535 + +For more information try --help + +``` diff --git a/examples/tutorial_builder/04_02_validate.rs b/examples/tutorial_builder/04_02_validate.rs index e60018a4615..ea2f32e679a 100644 --- a/examples/tutorial_builder/04_02_validate.rs +++ b/examples/tutorial_builder/04_02_validate.rs @@ -1,11 +1,9 @@ -// Note: this requires the `cargo` feature - use std::ops::RangeInclusive; use clap::{arg, command}; fn main() { - let matches = command!() + let matches = command!() // requires `cargo` feature .arg( arg!() .help("Network port to use") diff --git a/examples/tutorial_builder/04_03_relations.md b/examples/tutorial_builder/04_03_relations.md new file mode 100644 index 00000000000..3ea33636310 --- /dev/null +++ b/examples/tutorial_builder/04_03_relations.md @@ -0,0 +1,58 @@ +```console +$ 04_03_relations --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_03_relations[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] + +ARGS: + some regular input + +OPTIONS: + -c + -h, --help Print help information + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --set-ver set version manually + --spec-in some special input argument + -V, --version Print version information + +$ 04_03_relations +? failed +error: The following required arguments were not provided: + <--set-ver |--major|--minor|--patch> + +USAGE: + 04_03_relations[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] + +For more information try --help + +$ 04_03_relations --major +Version: 2.2.3 + +$ 04_03_relations --major --minor +? failed +error: The argument '--major' cannot be used with '--minor' + +USAGE: + 04_03_relations[EXE] <--set-ver |--major|--minor|--patch> + +For more information try --help + +$ 04_03_relations --major -c config.toml +? failed +error: The following required arguments were not provided: + > + +USAGE: + 04_03_relations[EXE] -c <--set-ver |--major|--minor|--patch> > + +For more information try --help + +$ 04_03_relations --major -c config.toml --spec-in input.txt +Version: 2.2.3 +Doing work using input input.txt and config config.toml + +``` diff --git a/examples/tutorial_builder/04_03_relations.rs b/examples/tutorial_builder/04_03_relations.rs index 605e5b48e80..37e097558f1 100644 --- a/examples/tutorial_builder/04_03_relations.rs +++ b/examples/tutorial_builder/04_03_relations.rs @@ -1,12 +1,10 @@ -// Note: this requires the `cargo` feature - use std::path::PathBuf; use clap::{arg, command, value_parser, ArgAction, ArgGroup}; fn main() { // Create application like normal - let matches = command!() + let matches = command!() // requires `cargo` feature // Add the version arguments .arg(arg!(--"set-ver" "set version manually").required(false)) .arg(arg!(--major "auto inc major").action(ArgAction::SetTrue)) diff --git a/examples/tutorial_builder/04_04_custom.md b/examples/tutorial_builder/04_04_custom.md new file mode 100644 index 00000000000..26a3df1ab6b --- /dev/null +++ b/examples/tutorial_builder/04_04_custom.md @@ -0,0 +1,57 @@ +```console +$ 04_04_custom --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +ARGS: + some regular input + +OPTIONS: + -c + -h, --help Print help information + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --set-ver set version manually + --spec-in some special input argument + -V, --version Print version information + +$ 04_04_custom +? failed +error: Can only modify one version field + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom --major +Version: 2.2.3 + +$ 04_04_custom --major --minor +? failed +error: Can only modify one version field + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom --major -c config.toml +? failed +Version: 2.2.3 +error: INPUT_FILE or --spec-in is required when using --config + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom --major -c config.toml --spec-in input.txt +Version: 2.2.3 +Doing work using input input.txt and config config.toml + +``` diff --git a/examples/tutorial_builder/04_04_custom.rs b/examples/tutorial_builder/04_04_custom.rs index 3dc080505e4..bd97f7ee275 100644 --- a/examples/tutorial_builder/04_04_custom.rs +++ b/examples/tutorial_builder/04_04_custom.rs @@ -1,12 +1,10 @@ -// Note: this requires the `cargo` feature - use std::path::PathBuf; use clap::{arg, command, value_parser, ArgAction, ErrorKind}; fn main() { // Create application like normal - let mut cmd = command!() + let mut cmd = command!() // requires `cargo` feature // Add the version arguments .arg(arg!(--"set-ver" "set version manually").required(false)) .arg(arg!(--major "auto inc major").action(ArgAction::SetTrue)) diff --git a/examples/tutorial_builder/05_01_assert.rs b/examples/tutorial_builder/05_01_assert.rs index d6f19ffe538..4b92542302e 100644 --- a/examples/tutorial_builder/05_01_assert.rs +++ b/examples/tutorial_builder/05_01_assert.rs @@ -1,5 +1,3 @@ -// Note: this requires the `cargo` feature - use clap::{arg, command, value_parser}; fn main() { @@ -13,14 +11,15 @@ fn main() { } fn cmd() -> clap::Command<'static> { - command!().arg( - arg!() - .help("Network port to use") - .value_parser(value_parser!(usize)), - ) + command!() // requires `cargo` feature + .arg( + arg!() + .help("Network port to use") + .value_parser(value_parser!(usize)), + ) } #[test] -fn verify_app() { +fn verify_cmd() { cmd().debug_assert(); } diff --git a/examples/tutorial_builder/README.md b/examples/tutorial_builder/README.md deleted file mode 100644 index 98f86cafdf1..00000000000 --- a/examples/tutorial_builder/README.md +++ /dev/null @@ -1,658 +0,0 @@ -# Tutorial - -*Jump to [derive tutorial](../tutorial_derive/README.md)* - -1. [Quick Start](#quick-start) -2. [Configuring the Parser](#configuring-the-parser) -3. [Adding Arguments](#adding-arguments) - 1. [Positionals](#positionals) - 2. [Options](#options) - 3. [Flags](#flags) - 4. [Subcommands](#subcommands) - 5. [Defaults](#defaults) -4. Validation - 1. [Enumerated values](#enumerated-values) - 2. [Validated values](#validated-values) - 3. [Argument Relations](#argument-relations) - 4. [Custom Validation](#custom-validation) -5. [Tips](#tips) -6. [Contributing](#contributing) - -## Quick Start - -You can create an application with several arguments using usage strings. - -[Example:](01_quick.rs) -```console -$ 01_quick --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 01_quick[EXE] [OPTIONS] [name] [SUBCOMMAND] - -ARGS: - Optional name to operate on - -OPTIONS: - -c, --config Sets a custom config file - -d, --debug Turn debugging information on - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - help Print this message or the help of the given subcommand(s) - test does testing things - -``` - -By default, the program does nothing: -```console -$ 01_quick -Debug mode is off - -``` - -But you can mix and match the various features -```console -$ 01_quick -dd test -Debug mode is on -Not printing testing lists... - -``` - -## Configuring the Parser - -You use the `Command` to start building a parser. - -[Example:](02_apps.rs) -```console -$ 02_apps --help -MyApp 1.0 -Kevin K. -Does awesome things - -USAGE: - 02_apps[EXE] --two --one - -OPTIONS: - -h, --help Print help information - --one - --two - -V, --version Print version information - -$ 02_apps --version -MyApp 1.0 - -``` - -You can use `command!()` to fill these fields in from your `Cargo.toml` -file. **This requires the `cargo` feature flag.** - -[Example:](02_crate.rs) -```console -$ 02_crate --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 02_crate[EXE] --two --one - -OPTIONS: - -h, --help Print help information - --one - --two - -V, --version Print version information - -$ 02_crate --version -clap [..] - -``` - -You can use `Command` methods to change the application level behavior of clap. - -[Example:](02_app_settings.rs) -```console -$ 02_app_settings --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 02_app_settings[EXE] --two --one - -OPTIONS: - --two - --one - -h, --help Print help information - -V, --version Print version information - -$ 02_app_settings --one -1 --one -3 --two 10 -two: "10" -one: "-3" - -``` - -## Adding Arguments - -### Positionals - -You can have users specify values by their position on the command-line: - -[Example:](03_03_positional.rs) -```console -$ 03_03_positional --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_03_positional[EXE] [NAME] - -ARGS: - - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 03_03_positional -NAME: None - -$ 03_03_positional bob -NAME: Some("bob") - -``` - -### Options - -You can name your arguments with a flag: -- Order doesn't matter -- They can be optional -- Intent is clearer - -[Example:](03_02_option.rs) -```console -$ 03_02_option --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_02_option[EXE] [OPTIONS] - -OPTIONS: - -h, --help Print help information - -n, --name - -V, --version Print version information - -$ 03_02_option -name: None - -$ 03_02_option --name bob -name: Some("bob") - -$ 03_02_option --name=bob -name: Some("bob") - -$ 03_02_option -n bob -name: Some("bob") - -$ 03_02_option -n=bob -name: Some("bob") - -$ 03_02_option -nbob -name: Some("bob") - -``` - -### Flags - -Flags can also be switches that can be on/off: - -[Example:](03_01_flag_bool.rs) -```console -$ 03_01_flag_bool --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_01_flag_bool[EXE] [OPTIONS] - -OPTIONS: - -h, --help Print help information - -v, --verbose - -V, --version Print version information - -$ 03_01_flag_bool -verbose: false - -$ 03_01_flag_bool --verbose -verbose: true - -$ 03_01_flag_bool --verbose --verbose -verbose: true - -``` - -Or counted. - -[Example:](03_01_flag_count.rs) -```console -$ 03_01_flag_count --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_01_flag_count[EXE] [OPTIONS] - -OPTIONS: - -h, --help Print help information - -v, --verbose - -V, --version Print version information - -$ 03_01_flag_count -verbose: 0 - -$ 03_01_flag_count --verbose -verbose: 1 - -$ 03_01_flag_count --verbose --verbose -verbose: 2 - -``` - -### Subcommands - -Subcommands are defined as `Command`s that get added via `Command::subcommand`. Each -instance of a Subcommand can have its own version, author(s), Args, and even its own -subcommands. - -[Example:](03_04_subcommands.rs) -```console -$ 03_04_subcommands help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_04_subcommands[EXE] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - add Adds files to myapp - help Print this message or the help of the given subcommand(s) - -$ 03_04_subcommands help add -03_04_subcommands[EXE]-add [..] -Adds files to myapp - -USAGE: - 03_04_subcommands[EXE] add [NAME] - -ARGS: - - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 03_04_subcommands add bob -'myapp add' was used, name is: Some("bob") - -``` - -Because we set `Command::arg_required_else_help`: -```console -$ 03_04_subcommands -? failed -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_04_subcommands[EXE] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - add Adds files to myapp - help Print this message or the help of the given subcommand(s) - -``` - -Because we set `Command::propagate_version`: -```console -$ 03_04_subcommands --version -clap [..] - -$ 03_04_subcommands add --version -03_04_subcommands[EXE]-add [..] - -``` - -### Defaults - -We've previously showed that arguments can be `required` or optional. When -optional, you work with a `Option` and can `unwrap_or`. Alternatively, you can -set `Arg::default_value`. - -[Example:](03_05_default_values.rs) -```console -$ 03_05_default_values --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_05_default_values[EXE] [NAME] - -ARGS: - [default: alice] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 03_05_default_values -NAME: "alice" - -$ 03_05_default_values bob -NAME: "bob" - -``` - -## Validation - -### Enumerated values - -If you have arguments of specific values you want to test for, you can use the -`PossibleValuesParser` or `Arg::value_parser(["val1", ...])` 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 - -[Example:](04_01_possible.rs) -```console -$ 04_01_possible --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_01_possible[EXE] - -ARGS: - What mode to run the program in [possible values: fast, slow] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_01_possible fast -Hare - -$ 04_01_possible slow -Tortoise - -$ 04_01_possible medium -? failed -error: "medium" isn't a valid value for '' - [possible values: fast, slow] - -For more information try --help - -``` - -When enabling the `derive` feature, you can use `ValueEnum` to take care of the boiler plate for you, giving the same results. - -[Example:](04_01_enum.rs) -```console -$ 04_01_enum --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_01_enum[EXE] - -ARGS: - What mode to run the program in [possible values: fast, slow] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_01_enum fast -Hare - -$ 04_01_enum slow -Tortoise - -$ 04_01_enum medium -? failed -error: "medium" isn't a valid value for '' - [possible values: fast, slow] - -For more information try --help - -``` - -### Validated values - -More generally, you can validate and parse into any data type. - -[Example:](04_02_parse.rs) -```console -$ 04_02_parse --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_02_parse[EXE] - -ARGS: - Network port to use - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_02_parse 22 -PORT = 22 - -$ 04_02_parse foobar -? failed -error: Invalid value "foobar" for '': invalid digit found in string - -For more information try --help - -$ 04_02_parse_derive 0 -? failed -error: Invalid value "0" for '': 0 is not in 1..=65535 - -For more information try --help - -``` - -A custom parser can be used to improve the error messages or provide additional validation: - -[Example:](04_02_validate.rs) -```console -$ 04_02_validate --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_02_validate[EXE] - -ARGS: - Network port to use - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_02_validate 22 -PORT = 22 - -$ 04_02_validate foobar -? failed -error: Invalid value "foobar" for '': `foobar` isn't a port number - -For more information try --help - -$ 04_02_validate 0 -? failed -error: Invalid value "0" for '': Port not in range 1-65535 - -For more information try --help - -``` - -### Argument Relations - -You can declare dependencies or conflicts between `Arg`s or even `ArgGroup`s. - -`ArgGroup`s make it easier to declare relations instead of having to list each -individually, or when you want a rule to apply "any but not all" arguments. - -Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be -present out of a given set. Imagine that you had multiple arguments, and you want one of them to -be required, but making all of them required isn't feasible because perhaps they conflict with -each other. - -[Example:](04_03_relations.rs) -```console -$ 04_03_relations --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_03_relations[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] - -ARGS: - some regular input - -OPTIONS: - -c - -h, --help Print help information - --major auto inc major - --minor auto inc minor - --patch auto inc patch - --set-ver set version manually - --spec-in some special input argument - -V, --version Print version information - -$ 04_03_relations -? failed -error: The following required arguments were not provided: - <--set-ver |--major|--minor|--patch> - -USAGE: - 04_03_relations[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] - -For more information try --help - -$ 04_03_relations --major -Version: 2.2.3 - -$ 04_03_relations --major --minor -? failed -error: The argument '--major' cannot be used with '--minor' - -USAGE: - 04_03_relations[EXE] <--set-ver |--major|--minor|--patch> - -For more information try --help - -$ 04_03_relations --major -c config.toml -? failed -error: The following required arguments were not provided: - > - -USAGE: - 04_03_relations[EXE] -c <--set-ver |--major|--minor|--patch> > - -For more information try --help - -$ 04_03_relations --major -c config.toml --spec-in input.txt -Version: 2.2.3 -Doing work using input input.txt and config config.toml - -``` - -### Custom Validation - -As a last resort, you can create custom errors with the basics of clap's formatting. - -[Example:](04_04_custom.rs) -```console -$ 04_04_custom --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] - -ARGS: - some regular input - -OPTIONS: - -c - -h, --help Print help information - --major auto inc major - --minor auto inc minor - --patch auto inc patch - --set-ver set version manually - --spec-in some special input argument - -V, --version Print version information - -$ 04_04_custom -? failed -error: Can only modify one version field - -USAGE: - 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] - -For more information try --help - -$ 04_04_custom --major -Version: 2.2.3 - -$ 04_04_custom --major --minor -? failed -error: Can only modify one version field - -USAGE: - 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] - -For more information try --help - -$ 04_04_custom --major -c config.toml -? failed -Version: 2.2.3 -error: INPUT_FILE or --spec-in is required when using --config - -USAGE: - 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] - -For more information try --help - -$ 04_04_custom --major -c config.toml --spec-in input.txt -Version: 2.2.3 -Doing work using input input.txt and config config.toml - -``` - -## Tips - -- For more complex demonstration of features, see our [examples](../README.md). -- Proactively check for bad `Command` configurations by calling `Command::debug_assert` in a test ([example](05_01_assert.rs)) - -## Contributing - -New example code: -- Please update the corresponding section in the [derive tutorial](../tutorial_derive/README.md) -- Building: They must be added to [Cargo.toml](../../Cargo.toml) with the appropriate `required-features`. -- Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax (generally they'll go in here). - -See also the general [CONTRIBUTING](../../CONTRIBUTING.md). diff --git a/examples/tutorial_derive/01_quick.md b/examples/tutorial_derive/01_quick.md new file mode 100644 index 00000000000..4a9e3fca17a --- /dev/null +++ b/examples/tutorial_derive/01_quick.md @@ -0,0 +1,37 @@ +```console +$ 01_quick --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 01_quick[EXE] [OPTIONS] [name] [SUBCOMMAND] + +ARGS: + Optional name to operate on + +OPTIONS: + -c, --config Sets a custom config file + -d, --debug Turn debugging information on + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + help Print this message or the help of the given subcommand(s) + test does testing things + +``` + +By default, the program does nothing: +```console +$ 01_quick +Debug mode is off + +``` + +But you can mix and match the various features +```console +$ 01_quick -dd test +Debug mode is on +Not printing testing lists... + +``` diff --git a/examples/tutorial_derive/02_app_settings.md b/examples/tutorial_derive/02_app_settings.md new file mode 100644 index 00000000000..247843bcfdc --- /dev/null +++ b/examples/tutorial_derive/02_app_settings.md @@ -0,0 +1,19 @@ +```console +$ 02_app_settings --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 02_app_settings[EXE] --two --one + +OPTIONS: + --two + --one + -h, --help Print help information + -V, --version Print version information + +$ 02_app_settings --one -1 --one -3 --two 10 +two: "10" +one: "-3" + +``` diff --git a/examples/tutorial_derive/02_apps.md b/examples/tutorial_derive/02_apps.md new file mode 100644 index 00000000000..8504b5f5220 --- /dev/null +++ b/examples/tutorial_derive/02_apps.md @@ -0,0 +1,19 @@ +```console +$ 02_apps --help +MyApp 1.0 +Kevin K. +Does awesome things + +USAGE: + 02_apps[EXE] --two --one + +OPTIONS: + -h, --help Print help information + --one + --two + -V, --version Print version information + +$ 02_apps --version +MyApp 1.0 + +``` diff --git a/examples/tutorial_derive/02_crate.md b/examples/tutorial_derive/02_crate.md new file mode 100644 index 00000000000..f76e0d608b5 --- /dev/null +++ b/examples/tutorial_derive/02_crate.md @@ -0,0 +1,18 @@ +```console +$ 02_crate --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 02_crate[EXE] --two --one + +OPTIONS: + -h, --help Print help information + --one + --two + -V, --version Print version information + +$ 02_crate --version +clap [..] + +``` diff --git a/examples/tutorial_derive/02_crate.rs b/examples/tutorial_derive/02_crate.rs index df16468d0bb..5576f998c15 100644 --- a/examples/tutorial_derive/02_crate.rs +++ b/examples/tutorial_derive/02_crate.rs @@ -1,7 +1,7 @@ use clap::Parser; #[derive(Parser)] -#[clap(author, version, about, long_about = None)] +#[clap(author, version, about, long_about = None)] // Read from `Cargo.toml` struct Cli { #[clap(long, value_parser)] two: String, diff --git a/examples/tutorial_derive/03_01_flag_bool.md b/examples/tutorial_derive/03_01_flag_bool.md new file mode 100644 index 00000000000..b0ee2a12635 --- /dev/null +++ b/examples/tutorial_derive/03_01_flag_bool.md @@ -0,0 +1,23 @@ +```console +$ 03_01_flag_bool --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_01_flag_bool[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -v, --verbose + -V, --version Print version information + +$ 03_01_flag_bool +verbose: false + +$ 03_01_flag_bool --verbose +verbose: true + +$ 03_01_flag_bool --verbose --verbose +verbose: true + +``` diff --git a/examples/tutorial_derive/03_01_flag_count.md b/examples/tutorial_derive/03_01_flag_count.md new file mode 100644 index 00000000000..ca4bcd6eb89 --- /dev/null +++ b/examples/tutorial_derive/03_01_flag_count.md @@ -0,0 +1,23 @@ +```console +$ 03_01_flag_count --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_01_flag_count[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -v, --verbose + -V, --version Print version information + +$ 03_01_flag_count +verbose: 0 + +$ 03_01_flag_count --verbose +verbose: 1 + +$ 03_01_flag_count --verbose --verbose +verbose: 2 + +``` diff --git a/examples/tutorial_derive/03_02_option.md b/examples/tutorial_derive/03_02_option.md new file mode 100644 index 00000000000..6198bcc7372 --- /dev/null +++ b/examples/tutorial_derive/03_02_option.md @@ -0,0 +1,32 @@ +```console +$ 03_02_option --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_02_option[EXE] [OPTIONS] + +OPTIONS: + -h, --help Print help information + -n, --name + -V, --version Print version information + +$ 03_02_option +name: None + +$ 03_02_option --name bob +name: Some("bob") + +$ 03_02_option --name=bob +name: Some("bob") + +$ 03_02_option -n bob +name: Some("bob") + +$ 03_02_option -n=bob +name: Some("bob") + +$ 03_02_option -nbob +name: Some("bob") + +``` diff --git a/examples/tutorial_derive/03_03_positional.md b/examples/tutorial_derive/03_03_positional.md new file mode 100644 index 00000000000..a3d7b8cf347 --- /dev/null +++ b/examples/tutorial_derive/03_03_positional.md @@ -0,0 +1,22 @@ +```console +$ 03_03_positional --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_03_positional[EXE] [NAME] + +ARGS: + + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_03_positional +NAME: None + +$ 03_03_positional bob +NAME: Some("bob") + +``` diff --git a/examples/tutorial_derive/03_04_subcommands.md b/examples/tutorial_derive/03_04_subcommands.md new file mode 100644 index 00000000000..8f3e7a8943c --- /dev/null +++ b/examples/tutorial_derive/03_04_subcommands.md @@ -0,0 +1,64 @@ +```console +$ 03_04_subcommands help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_04_subcommands[EXE] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + add Adds files to myapp + help Print this message or the help of the given subcommand(s) + +$ 03_04_subcommands help add +03_04_subcommands[EXE]-add [..] +Adds files to myapp + +USAGE: + 03_04_subcommands[EXE] add [NAME] + +ARGS: + + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_04_subcommands add bob +'myapp add' was used, name is: Some("bob") + +``` + +Because we used `command: Commands` instead of `command: Option`: +```console +$ 03_04_subcommands +? failed +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_04_subcommands[EXE] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + add Adds files to myapp + help Print this message or the help of the given subcommand(s) + +``` + +Because we added `#[clap(propagate_version = true)]`: +```console +$ 03_04_subcommands --version +clap [..] + +$ 03_04_subcommands add --version +03_04_subcommands[EXE]-add [..] + +``` diff --git a/examples/tutorial_derive/03_05_default_values.md b/examples/tutorial_derive/03_05_default_values.md new file mode 100644 index 00000000000..7b6c0307d34 --- /dev/null +++ b/examples/tutorial_derive/03_05_default_values.md @@ -0,0 +1,22 @@ +```console +$ 03_05_default_values --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 03_05_default_values[EXE] [NAME] + +ARGS: + [default: alice] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 03_05_default_values +NAME: "alice" + +$ 03_05_default_values bob +NAME: "bob" + +``` diff --git a/examples/tutorial_derive/04_01_enum.md b/examples/tutorial_derive/04_01_enum.md new file mode 100644 index 00000000000..282b1e61344 --- /dev/null +++ b/examples/tutorial_derive/04_01_enum.md @@ -0,0 +1,29 @@ +```console +$ 04_01_enum --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_01_enum[EXE] + +ARGS: + What mode to run the program in [possible values: fast, slow] + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_01_enum fast +Hare + +$ 04_01_enum slow +Tortoise + +$ 04_01_enum medium +? failed +error: "medium" isn't a valid value for '' + [possible values: fast, slow] + +For more information try --help + +``` diff --git a/examples/tutorial_derive/04_02_parse.md b/examples/tutorial_derive/04_02_parse.md new file mode 100644 index 00000000000..605bf4b5920 --- /dev/null +++ b/examples/tutorial_derive/04_02_parse.md @@ -0,0 +1,31 @@ +```console +$ 04_02_parse --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_02_parse[EXE] + +ARGS: + Network port to use + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_02_parse 22 +PORT = 22 + +$ 04_02_parse foobar +? failed +error: Invalid value "foobar" for '': invalid digit found in string + +For more information try --help + +$ 04_02_parse_derive 0 +? failed +error: Invalid value "0" for '': 0 is not in 1..=65535 + +For more information try --help + +``` diff --git a/examples/tutorial_derive/04_02_validate.md b/examples/tutorial_derive/04_02_validate.md new file mode 100644 index 00000000000..a317a8eb76c --- /dev/null +++ b/examples/tutorial_derive/04_02_validate.md @@ -0,0 +1,31 @@ +```console +$ 04_02_validate --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_02_validate[EXE] + +ARGS: + Network port to use + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +$ 04_02_validate 22 +PORT = 22 + +$ 04_02_validate foobar +? failed +error: Invalid value "foobar" for '': `foobar` isn't a port number + +For more information try --help + +$ 04_02_validate 0 +? failed +error: Invalid value "0" for '': Port not in range 1-65535 + +For more information try --help + +``` diff --git a/examples/tutorial_derive/04_03_relations.md b/examples/tutorial_derive/04_03_relations.md new file mode 100644 index 00000000000..3ea33636310 --- /dev/null +++ b/examples/tutorial_derive/04_03_relations.md @@ -0,0 +1,58 @@ +```console +$ 04_03_relations --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_03_relations[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] + +ARGS: + some regular input + +OPTIONS: + -c + -h, --help Print help information + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --set-ver set version manually + --spec-in some special input argument + -V, --version Print version information + +$ 04_03_relations +? failed +error: The following required arguments were not provided: + <--set-ver |--major|--minor|--patch> + +USAGE: + 04_03_relations[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] + +For more information try --help + +$ 04_03_relations --major +Version: 2.2.3 + +$ 04_03_relations --major --minor +? failed +error: The argument '--major' cannot be used with '--minor' + +USAGE: + 04_03_relations[EXE] <--set-ver |--major|--minor|--patch> + +For more information try --help + +$ 04_03_relations --major -c config.toml +? failed +error: The following required arguments were not provided: + > + +USAGE: + 04_03_relations[EXE] -c <--set-ver |--major|--minor|--patch> > + +For more information try --help + +$ 04_03_relations --major -c config.toml --spec-in input.txt +Version: 2.2.3 +Doing work using input input.txt and config config.toml + +``` diff --git a/examples/tutorial_derive/04_04_custom.md b/examples/tutorial_derive/04_04_custom.md new file mode 100644 index 00000000000..26a3df1ab6b --- /dev/null +++ b/examples/tutorial_derive/04_04_custom.md @@ -0,0 +1,57 @@ +```console +$ 04_04_custom --help +clap [..] +A simple to use, efficient, and full-featured Command Line Argument Parser + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +ARGS: + some regular input + +OPTIONS: + -c + -h, --help Print help information + --major auto inc major + --minor auto inc minor + --patch auto inc patch + --set-ver set version manually + --spec-in some special input argument + -V, --version Print version information + +$ 04_04_custom +? failed +error: Can only modify one version field + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom --major +Version: 2.2.3 + +$ 04_04_custom --major --minor +? failed +error: Can only modify one version field + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom --major -c config.toml +? failed +Version: 2.2.3 +error: INPUT_FILE or --spec-in is required when using --config + +USAGE: + 04_04_custom[EXE] [OPTIONS] [INPUT_FILE] + +For more information try --help + +$ 04_04_custom --major -c config.toml --spec-in input.txt +Version: 2.2.3 +Doing work using input input.txt and config config.toml + +``` diff --git a/examples/tutorial_derive/05_01_assert.rs b/examples/tutorial_derive/05_01_assert.rs index f5fa3f6c599..66dca727f3d 100644 --- a/examples/tutorial_derive/05_01_assert.rs +++ b/examples/tutorial_derive/05_01_assert.rs @@ -15,7 +15,7 @@ fn main() { } #[test] -fn verify_app() { +fn verify_cli() { use clap::CommandFactory; Cli::command().debug_assert() } diff --git a/examples/tutorial_derive/README.md b/examples/tutorial_derive/README.md deleted file mode 100644 index 8f47b2fc6e5..00000000000 --- a/examples/tutorial_derive/README.md +++ /dev/null @@ -1,639 +0,0 @@ -# Tutorial - -*Jump to [builder tutorial](../tutorial_builder/README.md)* - -1. [Quick Start](#quick-start) -2. [Configuring the Parser](#configuring-the-parser) -3. [Adding Arguments](#adding-arguments) - 1. [Positionals](#positionals) - 2. [Options](#options) - 3. [Flags](#flags) - 4. [Subcommands](#subcommands) - 5. [Defaults](#defaults) -4. Validation - 1. [Enumerated values](#enumerated-values) - 2. [Validated values](#validated-values) - 3. [Argument Relations](#argument-relations) - 4. [Custom Validation](#custom-validation) -5. [Tips](#tips) -6. [Contributing](#contributing) - -## Quick Start - -You can create an application declaratively with a `struct` and some -attributes. **This requires enabling the `derive` feature flag.** - -[Example:](01_quick.rs) -```console -$ 01_quick_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 01_quick_derive[EXE] [OPTIONS] [NAME] [SUBCOMMAND] - -ARGS: - Optional name to operate on - -OPTIONS: - -c, --config Sets a custom config file - -d, --debug Turn debugging information on - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - help Print this message or the help of the given subcommand(s) - test does testing things - -``` - -By default, the program does nothing: -```console -$ 01_quick_derive -Debug mode is off - -``` - -But you can mix and match the various features -```console -$ 01_quick_derive -dd test -Debug mode is on -Not printing testing lists... - -``` - -In addition to this tutorial, see the [derive reference](../derive_ref/README.md). - -## Configuring the Parser - -You use derive `Parser` to start building a parser. - -[Example:](02_apps.rs) -```console -$ 02_apps_derive --help -MyApp 1.0 -Kevin K. -Does awesome things - -USAGE: - 02_apps_derive[EXE] --two --one - -OPTIONS: - -h, --help Print help information - --one - --two - -V, --version Print version information - -$ 02_apps_derive --version -MyApp 1.0 - -``` - -You can use `#[clap(author, version, about)]` attribute defaults to fill these fields in from your `Cargo.toml` file. - -[Example:](02_crate.rs) -```console -$ 02_crate_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 02_crate_derive[EXE] --two --one - -OPTIONS: - -h, --help Print help information - --one - --two - -V, --version Print version information - -$ 02_crate_derive --version -clap [..] - -``` - -You can use attributes to change the application level behavior of clap. Any `Command` builder function can be used as an attribute. - -[Example:](02_app_settings.rs) -```console -$ 02_app_settings_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 02_app_settings_derive[EXE] --two --one - -OPTIONS: - --two - --one - -h, --help Print help information - -V, --version Print version information - -$ 02_app_settings_derive --one -1 --one -3 --two 10 -two: "10" -one: "-3" - -``` - -## Adding Arguments - -### Positionals - -You can have users specify values by their position on the command-line: - -[Example:](03_03_positional.rs) -```console -$ 03_03_positional_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_03_positional_derive[EXE] [NAME] - -ARGS: - - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 03_03_positional_derive -name: None - -$ 03_03_positional_derive bob -name: Some("bob") - -``` - -### Options - -You can name your arguments with a flag: -- Order doesn't matter -- They can be optional -- Intent is clearer - -The `#[clap(short = 'c')]` and `#[clap(long = "name")]` attributes that define -the flags are `Arg` methods that are derived from the field name when no value -is specified (`#[clap(short)]` and `#[clap(long)]`). - -[Example:](03_02_option.rs) -```console -$ 03_02_option_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_02_option_derive[EXE] [OPTIONS] - -OPTIONS: - -h, --help Print help information - -n, --name - -V, --version Print version information - -$ 03_02_option_derive -name: None - -$ 03_02_option_derive --name bob -name: Some("bob") - -$ 03_02_option_derive --name=bob -name: Some("bob") - -$ 03_02_option_derive -n bob -name: Some("bob") - -$ 03_02_option_derive -n=bob -name: Some("bob") - -$ 03_02_option_derive -nbob -name: Some("bob") - -``` - -### Flags - -Flags can also be switches that can be on/off. This is enabled via the -`#[clap(parse(from_flag)]` attribute though this is implied when the field is a -`bool`. - -[Example:](03_01_flag_bool.rs) -```console -$ 03_01_flag_bool_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_01_flag_bool_derive[EXE] [OPTIONS] - -OPTIONS: - -h, --help Print help information - -v, --verbose - -V, --version Print version information - -$ 03_01_flag_bool_derive -verbose: false - -$ 03_01_flag_bool_derive --verbose -verbose: true - -$ 03_01_flag_bool_derive --verbose --verbose -verbose: true - -``` - -Or counted with `#[clap(action = clap::ArgAction::Count)]`: - -[Example:](03_01_flag_count.rs) -```console -$ 03_01_flag_count_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_01_flag_count_derive[EXE] [OPTIONS] - -OPTIONS: - -h, --help Print help information - -v, --verbose - -V, --version Print version information - -$ 03_01_flag_count_derive -verbose: 0 - -$ 03_01_flag_count_derive --verbose -verbose: 1 - -$ 03_01_flag_count_derive --verbose --verbose -verbose: 2 - -``` - -### Subcommands - -Subcommands are derived with `#[derive(Subcommand)]` and be added via `#[clap(subcommand)]` attribute. Each -instance of a Subcommand can have its own version, author(s), Args, and even its own -subcommands. - -[Example:](03_04_subcommands.rs) -```console -$ 03_04_subcommands_derive help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_04_subcommands_derive[EXE] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - add Adds files to myapp - help Print this message or the help of the given subcommand(s) - -$ 03_04_subcommands_derive help add -03_04_subcommands_derive[EXE]-add [..] -Adds files to myapp - -USAGE: - 03_04_subcommands_derive[EXE] add [NAME] - -ARGS: - - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 03_04_subcommands_derive add bob -'myapp add' was used, name is: Some("bob") - -``` - -Above, we used a struct-variant to define the `add` subcommand. Alternatively, -you can -[use a struct for your subcommand's arguments](03_04_subcommands_alt.rs). - -Because we used `command: Commands` instead of `command: Option`: -```console -$ 03_04_subcommands_derive -? failed -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_04_subcommands_derive[EXE] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - add Adds files to myapp - help Print this message or the help of the given subcommand(s) - -``` - -Because we added `#[clap(propagate_version = true)]`: -```console -$ 03_04_subcommands_derive --version -clap [..] - -$ 03_04_subcommands_derive add --version -03_04_subcommands_derive[EXE]-add [..] - -``` - -### Defaults - -We've previously showed that arguments can be `required` or optional. When -optional, you work with an `Option` and can `unwrap_or`. Alternatively, you can -set `#[clap(default_value_t)]`. - -[Example:](03_05_default_values.rs) -```console -$ 03_05_default_values_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 03_05_default_values_derive[EXE] [NAME] - -ARGS: - [default: alice] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 03_05_default_values_derive -name: "alice" - -$ 03_05_default_values_derive bob -name: "bob" - -``` - -## Validation - -### Enumerated values - -If you have arguments of specific values you want to test for, you can derive -`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 - -[Example:](04_01_enum.rs) -```console -$ 04_01_enum_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_01_enum_derive[EXE] - -ARGS: - What mode to run the program in [possible values: fast, slow] - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_01_enum_derive fast -Hare - -$ 04_01_enum_derive slow -Tortoise - -$ 04_01_enum_derive medium -? failed -error: "medium" isn't a valid value for '' - [possible values: fast, slow] - -For more information try --help - -``` - -### Validated values - -More generally, you can validate and parse into any data type. - -[Example:](04_02_parse.rs) -```console -$ 04_02_parse_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_02_parse_derive[EXE] - -ARGS: - Network port to use - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_02_parse_derive 22 -PORT = 22 - -$ 04_02_parse_derive foobar -? failed -error: Invalid value "foobar" for '': invalid digit found in string - -For more information try --help - -$ 04_02_parse_derive 0 -? failed -error: Invalid value "0" for '': 0 is not in 1..=65535 - -For more information try --help - -``` - -A custom parser can be used to improve the error messages or provide additional validation: - -[Example:](04_02_validate.rs) -```console -$ 04_02_validate_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_02_validate_derive[EXE] - -ARGS: - Network port to use - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -$ 04_02_validate_derive 22 -PORT = 22 - -$ 04_02_validate_derive foobar -? failed -error: Invalid value "foobar" for '': `foobar` isn't a port number - -For more information try --help - -$ 04_02_validate_derive 0 -? failed -error: Invalid value "0" for '': Port not in range 1-65535 - -For more information try --help - -``` - -### Argument Relations - -You can declare dependencies or conflicts between `Arg`s or even `ArgGroup`s. - -`ArgGroup`s make it easier to declare relations instead of having to list each -individually, or when you want a rule to apply "any but not all" arguments. - -Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be -present out of a given set. Imagine that you had multiple arguments, and you want one of them to -be required, but making all of them required isn't feasible because perhaps they conflict with -each other. - -[Example:](04_03_relations.rs) -```console -$ 04_03_relations_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_03_relations_derive[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] - -ARGS: - some regular input - -OPTIONS: - -c - -h, --help Print help information - --major auto inc major - --minor auto inc minor - --patch auto inc patch - --set-ver set version manually - --spec-in some special input argument - -V, --version Print version information - -$ 04_03_relations_derive -? failed -error: The following required arguments were not provided: - <--set-ver |--major|--minor|--patch> - -USAGE: - 04_03_relations_derive[EXE] [OPTIONS] <--set-ver |--major|--minor|--patch> [INPUT_FILE] - -For more information try --help - -$ 04_03_relations_derive --major -Version: 2.2.3 - -$ 04_03_relations_derive --major --minor -? failed -error: The argument '--major' cannot be used with '--minor' - -USAGE: - 04_03_relations_derive[EXE] <--set-ver |--major|--minor|--patch> - -For more information try --help - -$ 04_03_relations_derive --major -c config.toml -? failed -error: The following required arguments were not provided: - > - -USAGE: - 04_03_relations_derive[EXE] -c <--set-ver |--major|--minor|--patch> > - -For more information try --help - -$ 04_03_relations_derive --major -c config.toml --spec-in input.txt -Version: 2.2.3 -Doing work using input input.txt and config config.toml - -``` - -### Custom Validation - -As a last resort, you can create custom errors with the basics of clap's formatting. - -[Example:](04_04_custom.rs) -```console -$ 04_04_custom_derive --help -clap [..] -A simple to use, efficient, and full-featured Command Line Argument Parser - -USAGE: - 04_04_custom_derive[EXE] [OPTIONS] [INPUT_FILE] - -ARGS: - some regular input - -OPTIONS: - -c - -h, --help Print help information - --major auto inc major - --minor auto inc minor - --patch auto inc patch - --set-ver set version manually - --spec-in some special input argument - -V, --version Print version information - -$ 04_04_custom_derive -? failed -error: Can only modify one version field - -USAGE: - clap [OPTIONS] [INPUT_FILE] - -For more information try --help - -$ 04_04_custom_derive --major -Version: 2.2.3 - -$ 04_04_custom_derive --major --minor -? failed -error: Can only modify one version field - -USAGE: - clap [OPTIONS] [INPUT_FILE] - -For more information try --help - -$ 04_04_custom_derive --major -c config.toml -? failed -Version: 2.2.3 -error: INPUT_FILE or --spec-in is required when using --config - -USAGE: - clap [OPTIONS] [INPUT_FILE] - -For more information try --help - -$ 04_04_custom_derive --major -c config.toml --spec-in input.txt -Version: 2.2.3 -Doing work using input input.txt and config config.toml - -``` - -## Tips - -- For more complex demonstration of features, see our [examples](../README.md). -- See the [derive reference](../derive_ref/README.md) to understand how to use - anything in the [builder API](https://docs.rs/clap/) in the derive API. -- Proactively check for bad `Command` configurations by calling `Command::debug_assert` in a test ([example](05_01_assert.rs)) - -## Contributing - -New example code: -- Please update the corresponding section in the [builder tutorial](../tutorial_builder/README.md) -- Building: They must be added to [Cargo.toml](../../Cargo.toml) with the appropriate `required-features`. -- Testing: Ensure there is a markdown file with [trycmd](https://docs.rs/trycmd) syntax (generally they'll go in here). - -See also the general [CONTRIBUTING](../../CONTRIBUTING.md). diff --git a/examples/typed-derive.md b/examples/typed-derive.md index 7c61f70d9a9..9c7615c63aa 100644 --- a/examples/typed-derive.md +++ b/examples/typed-derive.md @@ -1,6 +1,4 @@ -*Jump to [source](typed-derive.rs)* - -**This requires enabling the `derive` feature flag.** +**This requires enabling the [`derive` feature flag][crate::_features].** Help: ```console diff --git a/examples/typed-derive.rs b/examples/typed-derive.rs index 85c750f9c11..31084029d36 100644 --- a/examples/typed-derive.rs +++ b/examples/typed-derive.rs @@ -1,9 +1,7 @@ -// Note: this requires the `derive` feature - use clap::Parser; use std::error::Error; -#[derive(Parser, Debug)] +#[derive(Parser, Debug)] // requires `derive` feature struct Args { /// Implicitly using `std::str::FromStr` #[clap(short = 'O', value_parser)] diff --git a/src/_cookbook/cargo_example.rs b/src/_cookbook/cargo_example.rs new file mode 100644 index 00000000000..ec5d582db05 --- /dev/null +++ b/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/src/_cookbook/cargo_example_derive b/src/_cookbook/cargo_example_derive new file mode 100644 index 00000000000..e69de29bb2d diff --git a/src/_cookbook/cargo_example_derive.rs b/src/_cookbook/cargo_example_derive.rs new file mode 100644 index 00000000000..d49f956f9c0 --- /dev/null +++ b/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/src/_cookbook/escaped_positional.rs b/src/_cookbook/escaped_positional.rs new file mode 100644 index 00000000000..99a3f83f3b5 --- /dev/null +++ b/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/src/_cookbook/escaped_positional_derive.rs b/src/_cookbook/escaped_positional_derive.rs new file mode 100644 index 00000000000..e6f99ad1719 --- /dev/null +++ b/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/src/_cookbook/git.rs b/src/_cookbook/git.rs new file mode 100644 index 00000000000..03a926ca85b --- /dev/null +++ b/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/src/_cookbook/git_derive.rs b/src/_cookbook/git_derive.rs new file mode 100644 index 00000000000..d3119736de2 --- /dev/null +++ b/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/src/_cookbook/mod.rs b/src/_cookbook/mod.rs new file mode 100644 index 00000000000..1a78ed11bb7 --- /dev/null +++ b/src/_cookbook/mod.rs @@ -0,0 +1,55 @@ +// 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 +//! +//! git-like interface: [builder][git], [derive][git_derive] +//! - Topics: +//! - Subcommands +//! - External subcommands +//! - Optional subcommands +//! - Default subcommands +//! +//! 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 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/src/_cookbook/multicall_busybox.rs b/src/_cookbook/multicall_busybox.rs new file mode 100644 index 00000000000..e3384d682f5 --- /dev/null +++ b/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/src/_cookbook/multicall_hostname.rs b/src/_cookbook/multicall_hostname.rs new file mode 100644 index 00000000000..9777654dc13 --- /dev/null +++ b/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/src/_cookbook/pacman.rs b/src/_cookbook/pacman.rs new file mode 100644 index 00000000000..880c58158bc --- /dev/null +++ b/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/src/_cookbook/repl.rs b/src/_cookbook/repl.rs new file mode 100644 index 00000000000..549ec825908 --- /dev/null +++ b/src/_cookbook/repl.rs @@ -0,0 +1,5 @@ +//! # Example: Command REPL (Builder API) +//! +//! ```rust +#![doc = include_str!("../../examples/repl.rs")] +//! ``` diff --git a/src/_cookbook/typed_derive.rs b/src/_cookbook/typed_derive.rs new file mode 100644 index 00000000000..a5fd15ff84c --- /dev/null +++ b/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/src/_derive/_tutorial.rs b/src/_derive/_tutorial.rs new file mode 100644 index 00000000000..abd57cef83a --- /dev/null +++ b/src/_derive/_tutorial.rs @@ -0,0 +1,205 @@ +// 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 `#[clap(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")] +//! +//! ### Options +//! +//! You can name your arguments with a flag: +//! - Order doesn't matter +//! - They can be optional +//! - Intent is clearer +//! +//! The `#[clap(short = 'n')]` and `#[clap(long = "name")]` attributes that define +//! the flags are [`Arg`][crate::Args] methods that are derived from the field name when no value +//! is specified (`#[clap(short)]` and `#[clap(long)]`). +//! +//! ```rust +#![doc = include_str!("../../examples/tutorial_derive/03_02_option.rs")] +//! ``` +#![doc = include_str!("../../examples/tutorial_derive/03_02_option.md")] +//! +//! ### Flags +//! +//! Flags can also be switches that can be on/off. This is enabled via the +//! `#[clap(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")] +//! +//! Or counted with `#[clap(action = clap::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 `#[clap(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 `#[clap(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 +//! +//! ### Enumerated values +//! +//! 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")] +//! +//! ### 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::App::debug_assert]: +//! ```rust,no_run +#![doc = include_str!("../../examples/tutorial_derive/05_01_assert.rs")] +//! ``` diff --git a/src/_derive/mod.rs b/src/_derive/mod.rs new file mode 100644 index 00000000000..6a7a4023a20 --- /dev/null +++ b/src/_derive/mod.rs @@ -0,0 +1,496 @@ +//! # Documentation: Derive Reference +//! +//! 1. [Overview](#overview) +//! 2. [Attributes](#attributes) +//! 1. [Terminology](#terminology) +//! 2. [Command Attributes](#command-attributes) +//! 3. [Arg Attributes](#arg-attributes) +//! 4. [Arg Enum Attributes](#arg-enum-attributes) +//! 5. [Possible Value Attributes](#possible-value-attributes) +//! 3. [Arg Types](#arg-types) +//! 4. [Doc Comments](#doc-comments) +//! 5. [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)] +//! #[clap(APP ATTRIBUTE)] +//! struct Cli { +//! /// Doc comment +//! #[clap(ARG ATTRIBUTE)] +//! field: UserType, +//! +//! #[clap(value_enum, ARG ATTRIBUTE...)] +//! field: EnumValues, +//! +//! #[clap(flatten)] +//! delegate: Struct, +//! +//! #[clap(subcommand)] +//! command: Command, +//! } +//! +//! /// Doc comment +//! #[derive(Args)] +//! #[clap(PARENT APP ATTRIBUTE)] +//! struct Struct { +//! /// Doc comment +//! #[clap(ARG ATTRIBUTE)] +//! field: UserType, +//! } +//! +//! /// Doc comment +//! #[derive(Subcommand)] +//! #[clap(PARENT APP ATTRIBUTE)] +//! enum Command { +//! /// Doc comment +//! #[clap(APP ATTRIBUTE)] +//! Variant1(Struct), +//! +//! /// Doc comment +//! #[clap(APP ATTRIBUTE)] +//! Variant2 { +//! /// Doc comment +//! #[clap(ARG ATTRIBUTE)] +//! field: UserType, +//! } +//! } +//! +//! /// Doc comment +//! #[derive(ValueEnum)] +//! #[clap(VALUE ENUM ATTRIBUTE)] +//! enum EnumValues { +//! /// Doc comment +//! #[clap(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::PossibleValue] method can be used as an attribute. +//! +//! Raw attributes come in two different syntaxes: +//! ```rust,ignore +//! #[clap( +//! global = true, // name = arg form, neat for one-arg methods +//! required_if_eq("out", "file") // name(arg1, arg2, ...) form. +//! )] +//! ``` +//! +//! - `method = arg` can only be used for methods which take only one argument. +//! - `method(arg1, arg2)` can be used with any method. +//! +//! As long as `method_name` is not one of the magical methods it will be +//! translated into a mere method call. +//! +//! **Magic attributes** have post-processing done to them, whether that is +//! - Providing of defaults +//! - Special behavior is triggered off of it +//! +//! Magic attributes are more constrained in the syntax they support, usually just +//! ` = ` 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. `#[clap(arg_required_else_help(true))]` would translate to `cmd.arg_required_else_help(true)` +//! +//! **Magic attributes:** +//! - `name = `: [`Command::name`][crate::App::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::App::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::App::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::App::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 +//! `#[clap(long_about = None)]` to clear the doc comment so only [`about`][crate::App::about] +//! gets shown with both `-h` and `--help`. +//! - `long_about = `: [`Command::long_about`][crate::App::long_about] +//! - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing +//! - `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to [`about`][crate::App::about] / [`long_about`][crate::App::long_about] +//! - `next_display_order`: [`Command::next_display_order`][crate::App::next_display_order] +//! - `next_help_heading`: [`Command::next_help_heading`][crate::App::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::App::allow_external_subcommands] +//! - Variant must be either `Variant(Vec)` or `Variant(Vec)` +//! +//! ### 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. `#[clap(max_values(3))]` would translate to `arg.max_values(3)` +//! +//! **Magic attributes**: +//! - `name = `: [`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!] +//! - To register a custom type's [`ValueParser`][crate::builder::ValueParser], implement [`ValueParserFactory`][crate::builder::ValueParserFactory] +//! - When present, implies `#[clap(action)]` +//! - `action [= ]`: [`Arg::action`][crate::Arg::action] +//! - When not present: will auto-select an action based on the field type +//! - When present, implies `#[clap(value_parser)]` +//! - `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 +//! - `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 +//! - `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 +//! - `from_global`: Read a [`Arg::global`][crate::Arg::global] argument (raw attribute), regardless of what subcommand you are in +//! - `parse( [= ])`: [`Arg::validator`][crate::Arg::validator] and [`ArgMatches::values_of_t`][crate::ArgMatches::values_of_t] +//! - **Deprecated:** +//! - Use `value_parser(...)` for `from_str`, `try_from_str`, `from_os_str`, and `try_from_os_str` +//! - Use `action(ArgAction::Count` for `from_occurrences` +//! - Use `action(ArgAction::SetTrue` for `from_flag` +//! - Default: `try_from_str` +//! - Warning: for `Path` / `OsString`, be sure to use `try_from_os_str` +//! - See [Arg Types](#arg-types) for more details +//! - `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` or `#[clap(value_enum)]` +//! - Without ``, relies on `Default::default()` +//! - `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 `#[clap(value_enum)]` +//! - Without ``, relies on `Default::default()` +//! +//! ### Value Enum Attributes +//! +//! - `rename_all = `: Override default field / variant name case conversion for [`PossibleValue::new`][crate::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::PossibleValue]. +//! +//! **Raw attributes:** Any [`PossibleValue` method][crate::PossibleValue] can also be used as an attribute, see [Terminology](#terminology) for syntax. +//! - e.g. `#[clap(alias("foo"))]` would translate to `pv.alias("foo")` +//! +//! **Magic attributes**: +//! - `name = `: [`PossibleValue::new`][crate::PossibleValue::new] +//! - When not present: case-converted field name is used +//! - `help = `: [`PossibleValue::help`][crate::PossibleValue::help] +//! - When not present: [Doc comment summary](#doc-comments) +//! +//! ## Arg Types +//! +//! `clap` assumes some intent based on the type used: +//! +//! | Type | Effect | Implies | +//! |---------------------|--------------------------------------|------------------------------------------------------------------| +//! | `bool` | flag | `#[clap(parse(from_flag))]` | +//! | `Option` | optional argument | `.takes_value(true).required(false)` | +//! | `Option>` | optional value for optional argument | `.takes_value(true).required(false).min_values(0).max_values(1)` | +//! | `T` | required argument | `.takes_value(true).required(!has_default)` | +//! | `Vec` | `0..` occurrences of argument | `.takes_value(true).required(false).multiple_occurrences(true)` | +//! | `Option>` | `0..` occurrences of argument | `.takes_value(true).required(false).multiple_occurrences(true)` | +//! +//! Notes: +//! - For custom type behavior, you can override the implied attributes/settings and/or set additional ones +//! - For example, see [custom-bool](./custom-bool.md) +//! - `Option>` will be `None` instead of `vec![]` if no arguments are provided. +//! - This gives the user some flexibility in designing their argument, like with `min_values(0)` +//! +//! You can then support your custom type with `#[clap(parse( [= ]))]`: +//! +//! | `` | Signature | Default `` | +//! |--------------------------|---------------------------------------|---------------------------------| +//! | `from_str` | `fn(&str) -> T` | `::std::convert::From::from` | +//! | `try_from_str` (default) | `fn(&str) -> Result` | `::std::str::FromStr::from_str` | +//! | `from_os_str` | `fn(&OsStr) -> T` | `::std::convert::From::from` | +//! | `try_from_os_str` | `fn(&OsStr) -> Result` | (no default function) | +//! | `from_occurrences` | `fn(u64) -> T` | `value as T` | +//! | `from_flag` | `fn(bool) -> T` | `::std::convert::From::from` | +//! +//! Notes: +//! - `from_os_str`: +//! - Implies `arg.takes_value(true).allow_invalid_utf8(true)` +//! - `try_from_os_str`: +//! - Implies `arg.takes_value(true).allow_invalid_utf8(true)` +//! - `from_occurrences`: +//! - Implies `arg.takes_value(false).multiple_occurrences(true)` +//! - Reads from `clap::ArgMatches::occurrences_of` rather than a `get_one` function +//! - Note: operations on values, like `default_value`, are unlikely to do what you want +//! - `from_flag` +//! - Implies `arg.takes_value(false)` +//! - Reads from `clap::ArgMatches::is_present` rather than a `get_one` function +//! - Note: operations on values, like `default_value`, are unlikely to do what you want +//! +//! **Warning:** +//! - To support non-UTF8 paths, you should use `#[clap(value_parser)]` otherwise +//! `clap` will parse it as a `String` which will fail on some paths. +//! +//! ## Doc Comments +//! +//! In clap, help messages for the whole binary can be specified +//! via [`Command::about`][crate::App::about] and [`Command::long_about`][crate::App::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)] +//! #[clap(about = "I am a program and I work, just pass `-h`", long_about = None)] +//! struct Foo { +//! #[clap(short, help = "Pass `-h` and you'll see me!")] +//! bar: String, +//! } +//! ``` +//! +//! For convenience, doc comments can be used instead of raw methods +//! (this example works exactly like the one above): +//! +//! ```rust +//! # use clap::Parser; +//! +//! #[derive(Parser)] +//! /// I am a program and I work, just pass `-h` +//! struct Foo { +//! /// Pass `-h` and you'll see me! +//! bar: String, +//! } +//! ``` +//! +//! **NOTE:** Attributes have priority over doc comments! +//! +//! **Top level doc comments always generate `Command::about/long_about` calls!** +//! If you really want to use the `Command::about/long_about` methods (you likely don't), +//! use the `about` / `long_about` attributes to override the calls generated from +//! the doc comment. To clear `long_about`, you can use +//! `#[clap(long_about = None)]`. +//! +//! **TIP:** Set `#![deny(missing_docs)]` to catch missing `--help` documentation at compile time. +//! +//! ### Pre-processing +//! +//! ```rust +//! # use clap::Parser; +//! #[derive(Parser)] +//! /// Hi there, I'm Robo! +//! /// +//! /// I like beeping, stumbling, eating your electricity, +//! /// and making records of you singing in a shower. +//! /// Pay up, or I'll upload it to youtube! +//! struct Robo { +//! /// Call my brother SkyNet. +//! /// +//! /// I am artificial superintelligence. I won't rest +//! /// until I'll have destroyed humanity. Enjoy your +//! /// pathetic existence, you mere mortals. +//! #[clap(long, 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 `#[clap(flatten)]` a struct deriving `Args` into a struct +//! deriving `Args` or `Parser`. This example shows how you can augment a `Command` instance +//! created using the builder API with `Args` created using the derive API. +//! +//! It uses the [`Args::augment_args`][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 `#[clap(subcommand)]` inside the struct to add +//! subcommands. The type of the field is usually an enum that derived `Parser`. However, you can +//! also add the subcommands in that enum to a `Command` instance created with the builder API. +//! +//! It uses the [`Subcommand::augment_subcommands`][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 `#[clap(subcommand)]` inside the struct to add +//! subcommands. The type of the field is usually an enum that derived `Parser`. However, you can +//! also implement the `Subcommand` trait manually on this enum (or any other type) and it can +//! still be used inside the struct created with the derive API. The implementation of the +//! `Subcommand` trait will use the builder API to add the subcommands to the `Command` instance +//! created behind the scenes for you by the derive API. +//! +//! Notice how in the previous example we used +//! [`augment_subcommands`][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 `#[clap(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 `#[clap(flatten)]` inside the struct to add arguments as +//! if they were added directly to the containing struct. The type of the field is usually an +//! struct that derived `Args`. However, you can also implement the `Args` trait manually on this +//! struct (or any other type) and it can still be used inside the struct created with the derive +//! API. The implementation of the `Args` trait will use the builder API to add the arguments to +//! the `Command` instance created behind the scenes for you by the derive API. +//! +//! Notice how in the 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 `#[clap(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::App::debug_assert] in a test +//! ([example](../tutorial_derive/05_01_assert.rs)) + +pub mod _tutorial; +#[doc(inline)] +pub use crate::_cookbook; diff --git a/src/_faq.rs b/src/_faq.rs new file mode 100644 index 00000000000..661a7e73ded --- /dev/null +++ b/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 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 which 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 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/src/_features.rs b/src/_features.rs new file mode 100644 index 00000000000..923134c45e1 --- /dev/null +++ b/src/_features.rs @@ -0,0 +1,27 @@ +//! ## 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. +//! * **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. +//! * **regex**: Enables regex validators. +//! * **unicode**: Turns on support for unicode characters (including emoji) in arguments and help messages. +//! * **wrap_help**: Turns on the help text wrapping feature, based on the terminal size. +//! +//! #### Experimental features +//! +//! **Warning:** These may contain breaking changes between minor releases. +//! +//! * **unstable-replace**: Enable [`Command::replace`](https://github.com/clap-rs/clap/issues/2836) +//! * **unstable-grouped**: Enable [`ArgMatches::grouped_values_of`](https://github.com/clap-rs/clap/issues/2924) +//! * **unstable-v4**: Preview features which will be stable on the v4.0 release diff --git a/src/_tutorial.rs b/src/_tutorial.rs new file mode 100644 index 00000000000..9dbfc686458 --- /dev/null +++ b/src/_tutorial.rs @@ -0,0 +1,204 @@ +// 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")] +//! +//! ### 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")] +//! +//! ### 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")] +//! +//! Or counted. +//! +//! ```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 +//! +//! ### 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")] +//! +//! ### 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::App::debug_assert]: +//! ```rust,no_run +#![doc = include_str!("../examples/tutorial_builder/05_01_assert.rs")] +//! ``` diff --git a/src/derive.rs b/src/derive.rs index 46609ed160f..b6ac04df644 100644 --- a/src/derive.rs +++ b/src/derive.rs @@ -19,11 +19,9 @@ use std::ffi::OsString; /// /// See also [`Subcommand`] and [`Args`]. /// -/// See the -/// [derive reference](https://github.com/clap-rs/clap/blob/v3.2.12/examples/derive_ref/README.md) -/// for attributes and best practices. +/// See the [derive reference](crate::_derive) for attributes and best practices. /// -/// **NOTE:** Deriving requires the `derive` feature flag +/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] /// /// # Examples /// @@ -372,11 +370,9 @@ pub trait FromArgMatches: Sized { /// `Args`. /// - `Variant(ChildArgs)`: No attribute is used with enum variants that impl `Args`. /// -/// See the -/// [derive reference](https://github.com/clap-rs/clap/blob/v3.2.12/examples/derive_ref/README.md) -/// for attributes and best practices. +/// See the [derive reference](crate::_derive) for attributes and best practices. /// -/// **NOTE:** Deriving requires the `derive` feature flag +/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] /// /// # Example /// @@ -416,11 +412,9 @@ pub trait Args: FromArgMatches + Sized { /// - `#[clap(flatten)] Variant(SubCmd)`: Attribute can only be used with enum variants that impl /// `Subcommand`. /// -/// See the -/// [derive reference](https://github.com/clap-rs/clap/blob/v3.2.12/examples/derive_ref/README.md) -/// for attributes and best practices. +/// See the [derive reference](crate::_derive) for attributes and best practices. /// -/// **NOTE:** Deriving requires the `derive` feature flag +/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] /// /// # Example /// @@ -460,11 +454,9 @@ pub trait Subcommand: FromArgMatches + Sized { /// - Call [`Arg::possible_values`][crate::Arg::possible_values] /// - Allowing using the `#[clap(default_value_t)]` attribute without implementing `Display`. /// -/// See the -/// [derive reference](https://github.com/clap-rs/clap/blob/v3.2.12/examples/derive_ref/README.md) -/// for attributes and best practices. +/// See the [derive reference](crate::_derive) for attributes and best practices. /// -/// **NOTE:** Deriving requires the `derive` feature flag +/// **NOTE:** Deriving requires the [`derive` feature flag][crate::_features] /// /// # Example /// diff --git a/src/lib.rs b/src/lib.rs index 2146320b5f2..e10336a27ba 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,11 +3,79 @@ // (see LICENSE or ) All files in the project carrying such // notice may not be copied, modified, or distributed except according to those terms. +//! > **Command Line Argument Parser for Rust** +//! +//! Quick Links: +//! - Derive [tutorial][_derive::_tutorial] and [reference][_derive] +//! - Builder [tutorial][_tutorial] and [reference](index.html) +//! - [Cookbook][_cookbook] +//! - [FAQ][_faq] +//! - [Discussions](https://github.com/clap-rs/clap/discussions) +//! +//! ## Aspirations +//! +//! - Out of the box, users get a polished CLI experience +//! - Including common argument behavior, help generation, suggested fixes for users, colored output, [shell completions](https://github.com/clap-rs/clap/tree/master/clap_complete), etc +//! - Flexible enough to port your existing CLI interface +//! - However, we won't necessarily streamline support for each use case +//! - Reasonable parse performance +//! - Resilient maintainership, including +//! - Willing to break compatibility rather than batching up breaking changes in large releases +//! - Leverage feature flags to keep to one active branch +//! - Being under [WG-CLI](https://github.com/rust-cli/team/) to increase the bus factor +//! - We follow semver and will wait about 6-9 months between major breaking changes +//! - We will support the last two minor Rust releases (MSRV, currently 1.56.1) +//! +//! While these aspirations can be at odds with fast build times and low binary +//! size, we will still strive to keep these reasonable for the flexibility you +//! get. Check out the +//! [argparse-benchmarks](https://github.com/rust-cli/argparse-benchmarks-rs) for +//! CLI parsers optimized for other use cases. +//! +//! ## Example +//! +//! Run +//! ```console +//! $ cargo add clap -F derive +//! ``` +//! *(See also [feature flag reference][_features])* +//! +//! Then in `main.rs`: +#![cfg_attr(not(feature = "derive"), doc = " ```ignore")] +#![cfg_attr(feature = "derive", doc = " ```no_run")] +#![doc = include_str!("../examples/demo.rs")] +//! ``` +//! +//! Then try it out: +#![doc = include_str!("../examples/demo.md")] +//! +//! See also the derive [tutorial][_derive::_tutorial] and [reference][_derive] +//! +//! ### Related Projects +//! +//! Augment clap: +//! - [wild](https://crates.io/crates/wild) for supporting wildcards (`*`) on Windows like you do Linux +//! - [argfile](https://crates.io/crates/argfile) for loading additional arguments from a file (aka response files) +//! - [shadow-rs](https://crates.io/crates/shadow-rs) for generating `Command::long_version` +//! - [clap_mangen](https://crates.io/crates/clap_mangen) for generating man page source (roff) +//! - [clap_complete](https://crates.io/crates/clap_complete) for shell completion support +//! +//! CLI Helpers +//! - [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag) +//! - [clap-cargo](https://crates.io/crates/clap-cargo) +//! - [concolor-clap](https://crates.io/crates/concolor-clap) +//! +//! Testing +//! - [`trycmd`](https://crates.io/crates/trycmd): Bulk snapshot testing +//! - [`snapbox`](https://crates.io/crates/snapbox): Specialized snapshot testing +//! - [`assert_cmd`](https://crates.io/crates/assert_cmd) and [`assert_fs`](https://crates.io/crates/assert_fs): Customized testing +//! +//! Documentation: +//! - [Command-line Apps for Rust](https://rust-cli.github.io/book/index.html) book +//! + #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![doc(html_logo_url = "https://raw.githubusercontent.com/clap-rs/clap/master/assets/clap.png")] -#![cfg_attr(feature = "derive", doc = include_str!("../README.md"))] -//! For tutorials, examples, etc, see either or build with -//! `--features unstable-doc` #![warn( missing_docs, missing_debug_implementations, @@ -83,6 +151,17 @@ pub use Parser as StructOpt; )] pub use ValueEnum as ArgEnum; +#[cfg(feature = "unstable-doc")] +pub mod _cookbook; +#[cfg(feature = "unstable-doc")] +pub mod _derive; +#[cfg(feature = "unstable-doc")] +pub mod _faq; +#[cfg(feature = "unstable-doc")] +pub mod _features; +#[cfg(feature = "unstable-doc")] +pub mod _tutorial; + #[doc(hidden)] pub mod __macro_refs { #[cfg(any(feature = "derive", feature = "cargo"))]