A full featured, fast Command Line Argument Parser for Rust

Related tags

Command-line clapng
Overview

clap

Crates.io Crates.io License License Build Status Coverage Status Contributors

Command Line Argument Parser for Rust

It is a simple-to-use, efficient, and full-featured library for parsing command line arguments and subcommands when writing command line, console or terminal applications.

We are currently hard at work trying to release 3.0. We have a 3.0.0-beta.5 prerelease out but we do not give any guarantees that its API is stable. We do not have a changelog yet which will be written down after we are sure about the API stability. We recommend users to not update to the prerelease version yet and to wait for the official 3.0.

If you're looking for the readme & examples for clap v2.33 - find it on github, crates.io, docs.rs.

  1. About
  2. FAQ
  3. Features
  4. Quick Example
    1. Using Derive Macros
    2. Using Builder Pattern
    3. Using YAML
    4. Running it
  5. Try it!
    1. Pre-Built Test
    2. Build Your Own Binary
  6. Usage
    1. Optional Dependencies / Features
      1. Features enabled by default
      2. Opt-in features
      3. Experimental features
    2. More Information
  7. Sponsors
  8. Contributing
    1. Compatibility Policy
      1. Minimum Supported Version of Rust (MSRV)
      2. Breaking Changes
  9. License
  10. Related Crates

About

clap is used to parse and validate the string of command line arguments provided by a user at runtime. You provide the list of valid possibilities, and clap handles the rest. This means you focus on your applications functionality, and less on the parsing and validating of arguments.

clap provides many things 'for free' (with no configuration) including the traditional version and help switches (or flags) along with associated messages. If you are using subcommands, clap will also auto-generate a help subcommand and separate associated help messages.

Once clap parses the user provided string of arguments, it returns the matches along with any applicable values. If the user made an error or typo, clap informs them with a friendly message and exits gracefully (or returns a Result type and allows you to perform any clean up prior to exit). Because of this, you can make reasonable assumptions in your code about the validity of the arguments prior to your applications main execution.

FAQ

How does clap compare to structopt?

For a full FAQ, see this

Features

Below are a few of the features which clap supports, full descriptions and usage can be found in the documentation and examples directory

  • Generate a CLI simply by defining a struct!
  • Auto-generated Help, Version, and Usage information
    • Can optionally be fully, or partially overridden if you want a custom help, version, or usage statements
  • Auto-generated completion scripts (Bash, Zsh, Fish, Fig, Elvish and PowerShell)
    • Using clap_generate
    • Even works through many multiple levels of subcommands
    • Works with options which only accept certain values
    • Works with subcommand aliases
  • Flags / Switches (i.e. bool fields)
    • Both short and long versions supported (i.e. -f and --flag respectively)
    • Supports combining short versions (i.e. -fBgoZ is the same as -f -B -g -o -Z)
    • Supports multiple occurrences (i.e. -vvv or -v -v -v)
  • Positional Arguments (i.e. those which are based off an index from the program name)
    • Supports multiple values (i.e. myprog <file>... such as myprog file1.txt file2.txt being two values for the same "file" argument)
    • Supports Specific Value Sets (See below)
    • Can set value parameters (such as the minimum number of values, the maximum number of values, or the exact number of values)
    • Can set custom validations on values to extend the argument parsing capability to truly custom domains
  • Option Arguments (i.e. those that take values)
    • Both short and long versions supported (i.e. -o value, -ovalue, -o=value and --option value or --option=value respectively)
    • Supports multiple values (i.e. -o <val1> -o <val2> or -o <val1> <val2>)
    • Supports delimited values (i.e. -o=val1,val2,val3, can also change the delimiter)
    • Supports Specific Value Sets (See below)
    • Supports named values so that the usage/help info appears as -o <FILE> <INTERFACE> etc. for when you require specific multiple values
    • Can set value parameters (such as the minimum number of values, the maximum number of values, or the exact number of values)
    • Can set custom validations on values to extend the argument parsing capability to truly custom domains
  • Sub-Commands (i.e. git add <file> where add is a sub-command of git)
    • Support their own sub-arguments, and sub-sub-commands independent of the parent
    • Get their own auto-generated Help, Version, and Usage independent of parent
  • Support for building CLIs from YAML - This keeps your Rust source nice and tidy and makes supporting localized translation very simple!
  • Requirement Rules: Arguments can define the following types of requirement rules
    • Can be required by default
    • Can be required only if certain arguments are present
    • Can require other arguments to be present
    • Can be required only if certain values of other arguments are used
  • Confliction Rules: Arguments can optionally define the following types of exclusion rules
    • Can be disallowed when certain arguments are present
    • Can disallow use of other arguments when present
  • Groups: Arguments can be made part of a group
    • Fully compatible with other relational rules (requirements, conflicts, and overrides) which allows things like requiring the use of any arg in a group, or denying the use of an entire group conditionally
  • Specific Value Sets: Positional or Option Arguments can define a specific set of allowed values (i.e. imagine a --mode option which may only have one of two values fast or slow such as --mode fast or --mode slow)
  • Default Values
    • Also supports conditional default values (i.e. a default which only applies if specific arguments are used, or specific values of those arguments)
  • Automatic Version from Cargo.toml: clap is fully compatible with Rust's env!() macro for automatically setting the version of your application to the version in your Cargo.toml. See 09_auto_version example for how to do this (Thanks to jhelwig for pointing this out)
  • Typed Values: You can use several convenience macros provided by clap to get typed values (i.e. i32, u8, etc.) from positional or option arguments so long as the type you request implements std::str::FromStr See the 12_typed_values example. You can also use claps arg_enum! macro to create an enum with variants that automatically implement std::str::FromStr. See 13_enum_values example for details
  • Suggestions: Suggests corrections when the user enters a typo. For example, if you defined a --myoption argument, and the user mistakenly typed --moyption (notice y and o transposed), they would receive a Did you mean '--myoption'? error and exit gracefully. This also works for subcommands and flags. (Thanks to Byron for the implementation) (This feature can optionally be disabled, see 'Optional Dependencies / Features')
  • Colorized Errors (Non Windows OS only): Error message are printed in colored text (this feature can optionally be disabled, see 'Optional Dependencies / Features').
  • Global Arguments: Arguments can optionally be defined once, and be available to all child subcommands. These values will also be propagated up/down throughout all subcommands.
  • Custom Validations: You can define a function to use as a validator of argument values. Imagine defining a function to validate IP addresses, or fail parsing upon error. This means your application logic can be solely focused on using values.
  • POSIX Compatible Conflicts/Overrides - In POSIX args can be conflicting, but not fail parsing because whichever arg comes last "wins" so to speak. This allows things such as aliases (i.e. alias ls='ls -l' but then using ls -C in your terminal which ends up passing ls -l -C as the final arguments. Since -l and -C aren't compatible, this effectively runs ls -C in clap if you choose...clap also supports hard conflicts that fail parsing). (Thanks to Vinatorul!)
  • Supports the Unix -- meaning, only positional arguments follow

Quick Example

The following examples show a quick example of some of the very basic functionality of clap. For more advanced usage, such as requirements, conflicts, groups, multiple values and occurrences see the documentation, examples directory of this repository.

NOTE: All of these examples are functionally the same, but show different styles in which to use clap. These different styles are purely a matter of personal preference.

Add clap to your Cargo.toml

[dependencies]
clap = "3.0.0-beta.5"

Using Derive Macros

The first example shows the simplest way to use clap, by defining a struct. If you're familiar with the structopt crate you're in luck, it's the same! (In fact it's the exact same code running under the covers!)

// (Full example with detailed comments in examples/01d_quick_example.rs)
//
// This example demonstrates clap's full 'custom derive' style of creating arguments which is the
// simplest method of use, but sacrifices some flexibility.
use clap::{AppSettings, Parser};

/// This doc string acts as a help message when the user runs '--help'
/// as do all doc strings on fields
#[derive(Parser)]
#[clap(version = "1.0", author = "Kevin K. <[email protected]>")]
struct Opts {
    /// Sets a custom config file. Could have been an Option<T> with no default too
    #[clap(short, long, default_value = "default.conf")]
    config: String,
    /// Some input. Because this isn't an Option<T> it's required to be used
    input: String,
    /// A level of verbosity, and can be used multiple times
    #[clap(short, long, parse(from_occurrences))]
    verbose: i32,
    #[clap(subcommand)]
    subcmd: SubCommand,
}

#[derive(Parser)]
enum SubCommand {
    #[clap(version = "1.3", author = "Someone E. <[email protected]>")]
    Test(Test),
}

/// A subcommand for controlling testing
#[derive(Parser)]
struct Test {
    /// Print debug info
    #[clap(short)]
    debug: bool
}

fn main() {
    let opts: Opts = Opts::parse();

    // Gets a value for config if supplied by user, or defaults to "default.conf"
    println!("Value for config: {}", opts.config);
    println!("Using input file: {}", opts.input);

    // Vary the output based on how many times the user used the "verbose" flag
    // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v'
    match opts.verbose {
        0 => println!("No verbose info"),
        1 => println!("Some verbose info"),
        2 => println!("Tons of verbose info"),
        _ => println!("Don't be ridiculous"),
    }

    // You can handle information about subcommands by requesting their matches by name
    // (as below), requesting just the name used, or both at the same time
    match opts.subcmd {
        SubCommand::Test(t) => {
            if t.debug {
                println!("Printing debug info...");
            } else {
                println!("Printing normally...");
            }
        }
    }

    // more program logic goes here...
}

Using Builder Pattern

This second method shows a method using the 'Builder Pattern' which allows more advanced configuration options (not shown in this small example), or even dynamically generating arguments when desired. The downside is it's more verbose.

// (Full example with detailed comments in examples/01b_quick_example.rs)
//
// This example demonstrates clap's "builder pattern" method of creating arguments
// which the most flexible, but also most verbose.
use clap::{Arg, App};

fn main() {
    let matches = App::new("My Super Program")
        .version("1.0")
        .author("Kevin K. <[email protected]>")
        .about("Does awesome things")
        .arg(Arg::new("config")
            .short('c')
            .long("config")
            .value_name("FILE")
            .help("Sets a custom config file")
            .takes_value(true))
        .arg(Arg::new("INPUT")
            .help("Sets the input file to use")
            .required(true)
            .index(1))
        .arg(Arg::new("v")
            .short('v')
            .multiple_occurrences(true)
            .takes_value(true)
            .help("Sets the level of verbosity"))
        .subcommand(App::new("test")
            .about("controls testing features")
            .version("1.3")
            .author("Someone E. <[email protected]>")
            .arg(Arg::new("debug")
                .short('d')
                .help("print debug information verbosely")))
        .get_matches();

    // You can check the value provided by positional arguments, or option arguments
    if let Some(i) = matches.value_of("INPUT") {
        println!("Value for input: {}", i);
    }

    if let Some(c) = matches.value_of("config") {
        println!("Value for config: {}", c);
    }

    // You can see how many times a particular flag or argument occurred
    // Note, only flags can have multiple occurrences
    match matches.occurrences_of("v") {
        0 => println!("Verbose mode is off"),
        1 => println!("Verbose mode is kind of on"),
        2 => println!("Verbose mode is on"),
        _ => println!("Don't be crazy"),
    }

    // You can check for the existence of subcommands, and if found use their
    // matches just as you would the top level app
    if let Some(ref matches) = matches.subcommand_matches("test") {
        // "$ myapp test" was run
        if matches.is_present("debug") {
            // "$ myapp test -d" was run
            println!("Printing debug info...");
        } else {
            println!("Printing normally...");
        }
    }

    // Continued program logic goes here...
}

The next example shows a far less verbose method, but sacrifices some of the advanced configuration options (not shown in this small example). This method also takes a very minor runtime penalty.

// (Full example with detailed comments in examples/01a_quick_example.rs)
//
// This example demonstrates clap's "usage strings" method of creating arguments
// which is less verbose
use clap::App;

fn main() {
    let matches = App::new("myapp")
        .version("1.0")
        .author("Kevin K. <[email protected]>")
        .about("Does awesome things")
        .arg("-c, --config=[FILE] 'Sets a custom config file'")
        .arg("<INPUT>              'Sets the input file to use'")
        .arg("-v...                'Sets the level of verbosity'")
        .subcommand(App::new("test")
            .about("controls testing features")
            .version("1.3")
            .author("Someone E. <[email protected]>")
            .arg("-d, --debug 'Print debug information'"))
        .get_matches();

    // Same as previous example...
}

Using YAML

This third method shows how you can use a YAML file to build your CLI and keep your Rust source tidy or support multiple localized translations by having different YAML files for each localization.

First, create the cli.yaml file to hold your CLI options, but it could be called anything we like:

name: myapp
version: "1.0"
author: Kevin K. <[email protected]>
about: Does awesome things
args:
    - config:
        short: c
        long: config
        value_name: FILE
        help: Sets a custom config file
        takes_value: true
    - INPUT:
        help: Sets the input file to use
        required: true
        index: 1
    - verbose:
        short: v
        multiple_occurrences: true
        help: Sets the level of verbosity
subcommands:
    - test:
        about: controls testing features
        version: "1.3"
        author: Someone E. <[email protected]>
        args:
            - debug:
                short: d
                long: debug
                help: Print debug information

Since this feature requires additional dependencies that not everyone may want, it is not compiled in by default and we need to enable a feature flag in Cargo.toml:

Simply add the yaml feature flag to your Cargo.toml.

[dependencies]
clap = { version = "3.0.0-beta.5", features = ["yaml"] }

Finally we create our main.rs file just like we would have with the previous two examples:

// (Full example with detailed comments in examples/17_yaml.rs)
//
// This example demonstrates clap's building from YAML style of creating arguments which is far
// more clean, but takes a very small performance hit compared to the other two methods.
use clap::{App, load_yaml};

fn main() {
    // The YAML file is found relative to the current file, similar to how modules are found
    let yaml = load_yaml!("cli.yaml");
    let matches = App::from(yaml).get_matches();

    // Same as previous examples...
}

Running it

If you were to compile any of the above programs and run them with the flag --help or -h (or help subcommand, since we defined test as a subcommand) the following would be output (except the first example where the help message sort of explains the Rust code).

$ myprog --help
My Super Program 1.0
Kevin K. <[email protected]>
Does awesome things

ARGS:
    INPUT    The input file to use

USAGE:
    MyApp [OPTIONS] <INPUT> [SUBCOMMAND]

OPTIONS:
    -c, --config <FILE>    Sets a custom config file
    -h, --help             Print help information
    -v                     Sets the level of verbosity
    -V, --version          Print version information

SUBCOMMANDS:
    help    Print this message or the help of the given subcommand(s)
    test    Controls testing features

NOTE: You could also run myapp test --help or myapp help test to see the help message for the test subcommand.

Try it!

Pre-Built Test

To try out the pre-built examples, use the following steps:

  • Clone the repository $ git clone https://github.com/clap-rs/clap && cd clap/
  • Compile the example $ cargo build --example <EXAMPLE>
  • Run the help info $ ./target/debug/examples/<EXAMPLE> --help
  • Play with the arguments!
  • You can also do a onetime run via $ cargo run --example <EXAMPLE> -- [args to example]

Build Your Own Binary

To test out clap's default auto-generated help/version follow these steps:

  • Create a new cargo project $ cargo new fake --bin && cd fake
  • Write your program as described in the quick example section.
  • Build your program $ cargo build --release
  • Run with help or version $ ./target/release/fake --help or $ ./target/release/fake --version

Usage

For full usage, add clap as a dependency in your Cargo.toml to use from crates.io:

[dependencies]
clap = "3.0.0-beta.5"

Define a list of valid arguments for your program (see the documentation or examples directory of this repo)

Then run cargo build or cargo update && cargo build for your project.

Optional Dependencies / Features

Disabling optional features can decrease the binary size of clap and decrease the compile time. If binary size or compile times are extremely important to you, it is a good idea to disable the feautres that you are not using.

Features enabled by default

  • std: Not Currently Used. Placeholder for supporting no_std environments in a backwards compatible manner.
  • 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. (builds dependency clap_derive)
  • cargo: Turns on macros that read values from CARGO_* environment variables.
  • color: Turns on colored error messages. (builds dependency atty, termcolor)
  • env: Turns on the usage of environment variables during parsing.
  • suggestions: Turns on the Did you mean '--myoption'? feature for when users make typos. (builds dependency strsim)
  • unicode: Turns on support for unicode characters in arguments and help messages. (builds dependency textwrap, unicase)

To disable these, add this to your Cargo.toml:

[dependencies.clap]
version = "3.0.0-beta.5"
default-features = false
features = ["std"]

You can also selectively enable only the features you'd like to include, by adding:

[dependencies.clap]
version = "3.0.0-beta.5"
default-features = false

# Cherry-pick the features you'd like to use
features = ["std", "suggestions", "color"]

Opt-in features

  • regex: Enables regex validators. (builds dependency regex)
  • wrap_help: Turns on the help text wrapping feature, based on the terminal size. (builds dependency term-size)
  • yaml: Enables building CLIs from YAML documents. (builds dependency yaml-rust)

Experimental features

These features are opt-in. But be wary that they can contain breaking changes between minor releases.

More Information

You can find complete documentation on the docs.rs for this project.

You can also find usage examples in the examples directory of this repo.

Sponsors

Gold

Silver

Bronze

Backer

Contributing

Details on how to contribute can be found in the CONTRIBUTING.md file.

Compatibility Policy

Because clap takes SemVer and compatibility seriously, this is the official policy regarding breaking changes and minimum required versions of Rust.

clap will pin the minimum required version of Rust to the CI builds. Bumping the minimum version of Rust is considered a minor breaking change, meaning at a minimum the minor version of clap will be bumped.

In order to keep from being surprised of breaking changes, it is highly recommended to use the ~major.minor.patch style in your Cargo.toml only if you wish to target a version of Rust that is older than current stable minus two releases:

[dependencies]
clap = "~3.0.0-beta.5"

This will cause only the patch version to be updated upon a cargo update call, and therefore cannot break due to new features, or bumped minimum versions of Rust.

Minimum Supported Version of Rust (MSRV)

The following is a list of the minimum required version of Rust to compile clap by our MAJOR.MINOR version number:

clap MSRV
>=3.0 1.54.0
>=2.21 1.24.0
>=2.2 1.12.0
>=2.1 1.6.0
>=1.5 1.4.0
>=1.4 1.2.0
>=1.2 1.1.0
>=1.0 1.0.0

Breaking Changes

clap takes a similar policy to Rust and will bump the major version number upon breaking changes with only the following exceptions:

  • The breaking change is to fix a security concern
  • The breaking change is to be fixing a bug (i.e. relying on a bug as a feature)
  • The breaking change is a feature isn't used in the wild, or all users of said feature have given approval prior to the change

License

clap is distributed under the terms of both the MIT license and the Apache License (Version 2.0).

See the LICENSE-APACHE and LICENSE-MIT files in this repository for more information.

Related Crates

There are several excellent crates which can be used with clap, I recommend checking them all out! If you've got a crate that would be a good fit to be used with clap open an issue and let me know, I'd love to add it!

  • assert_cmd - This crate allows you test your CLIs in a very intuitive and functional way!
Comments
  • Reduce clap2->clap3 porting burden

    Reduce clap2->clap3 porting burden

    Issue by epage Thursday Jul 22, 2021 at 15:34 GMT Originally opened as https://github.com/clap-rs/clap/issues/2617


    Please complete the following tasks

    • [X] I have searched the discussions
    • [X] I have searched the existing issues

    Rust Version

    rustc 1.53.0 (53cb7b09b 2021-06-17)

    Clap Version

    3.0.0-beta.2

    Minimal reproducible code

    See https://github.com/rust-cli/argparse-benchmarks-rs/blob/main/examples/clap-app/app.rs

    Steps to reproduce the bug with the above code

    Port it to clap3

    Actual Behaviour

    Have to dig through the docs and changelog where the more that exists, the harder to find content

    We especially don't want noise from mechanical transitions to drown out behavior changes like #751 or removal of implied settings

    Expected Behaviour

    Deprecation warnings

    Additional Context

    Where its trivial, I'd propose we add functions back in

    • Forward to new impl
    • Have deprecation attribute
    • Doc comment is only brief enough to mention what should be used

    Examples:

    • Arg::multiple
    • Arg::with_name
    • Arg::help

    Debug Output

    No response

    opened by epage 18
  • docs: Re-work examples

    docs: Re-work examples

    This creates distinct tutorial examples from complex feature examples (more how-tos). Both sets are getting builder / derive versions (at least the critical ones).

    Fixes #42

    opened by epage 1
  • Ease 2-3 transition by asserting on utf8/os mismatch

    Ease 2-3 transition by asserting on utf8/os mismatch

    This will help make sure people creating a PathBuf will set AllowInvalidUtf8 on the arg.

    This will also make it so we can work towards https://github.com/clap-rs/clap/issues/2683 without breaking compatibility

    opened by epage 1
  • CI running without features actually runs with features

    CI running without features actually runs with features

    Because we use --workspace, cargo unifies the feature set when running:

    • Since clap_derive depends on the default feature set of clap, all of that gets pulled in.
    • The examples need cargo to run
    opened by epage 1
  • chore(deps): update os_str_bytes requirement from 5.0 to 6.0

    chore(deps): update os_str_bytes requirement from 5.0 to 6.0

    Updates the requirements on os_str_bytes to permit the latest version.

    Release notes

    Sourced from os_str_bytes's releases.

    6.0.0

    • Removed the crate name ("os_str_bytes") from the output of the Display implementation for EncodingError.
    • Removed the deprecated "deprecated-byte-patterns" feature.
    • Increased the minimum supported Rust toolchain version 1.52.0
    Commits

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    C-dependencies 
    opened by dependabot[bot] 0
  • docs: Re-order items in docs

    docs: Re-order items in docs

    This contains two types of re-ordering:

    • Internal, putting the focus of each file first.
    • Public, re-arranging items and grouping impl blocks to try to better organize the documentation and find related items.

    The main weakness of the docs work is in Args. Its just a mess. In particular, we should probably link the simple casesm like required to the advanced impl block.

    Fixes #55

    opened by epage 0
  • Add DisableColoredHelp setting to improve flexibility (clap-rs/clap#2956)

    Add DisableColoredHelp setting to improve flexibility (clap-rs/clap#2956)

    Until we have a modular help generator that can be configured and/or authored by the users themselves as part of #2914, we will provide the flexibility of turning off colored help messages but still wanting colored error messages.

    This flexibility was available before #2845 and @dbrgn immediately noticed it and requested it back to which I agree. This was also suggested by Josh in here

    opened by epage 0
  • fix(derive): Smooth out transition for structopt

    fix(derive): Smooth out transition for structopt

    Adding in a StructOpt derive with structopt attributes, with deprecation notices. Unofrtunately, not as many deprecation warnings as I would like. Apparently, you can't do them for a use of a derive? I also wanted to inject code that would trigger a deprecation notice for attributes but that would require enough of a refactor that I didn't consider it worth it. We are at least providing a transition window even if it means we'll have to remvoe it next major release without a deprecation warning.

    opened by epage 0
  • fix: Change `app_from_crate` default separator

    fix: Change `app_from_crate` default separator

    ":" isn't ideal, so let's make it at least ",".

    BREAKING CHANGE: Changed app_from_crate!() to use ", " separator for authors.

    opened by epage 0
  • tests: Consolidate clap tests

    tests: Consolidate clap tests

    This reduces the need for us to have clap as a dependency in clap_derive, preparing the way to fix #15.

    To keep tests/ organized, I have a test bin per API. This also has the benefit of reducing link times in CI at the cost of more compilation when a single test gets changed.

    opened by epage 0
  • docs: Prefer `global_setting`

    docs: Prefer `global_setting`

    I've been finding I've been setting AppSettings without it which is likely leading to bugs. This tries to raise the visibility by using it based on the setting being used and not whether the application needs it.

    opened by epage 0
  • chore(deps): update heck requirement from 0.3.0 to 0.4.0

    chore(deps): update heck requirement from 0.3.0 to 0.4.0

    Updates the requirements on heck to permit the latest version.

    Changelog

    Sourced from heck's changelog.

    0.4.0

    Breaking changes:

    • Make unicode support optional (off by default). Enable the unicode crate feature if you need unicode support.
    • Rename all traits from SomeCase to ToSomeCase, matching stds convention of beginning trait names with a verb (ToOwned, AsRef, …)
    • Rename ToMixedCase to ToLowerCamelCase
    • Rename ToCamelCase to ToUpperCamelCase
    • Add ToPascalCase as an alias to ToUpperCamelCase
    Commits

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    C-dependencies 
    opened by dependabot[bot] 0
  • Cannot enable crate features on Rust Playground because `[package.metadata.playground]` is absent in Cargo.toml

    Cannot enable crate features on Rust Playground because `[package.metadata.playground]` is absent in Cargo.toml

    Issue by shivanandvp Monday Dec 06, 2021 at 08:12 GMT Originally opened as https://github.com/clap-rs/clap/issues/3065


    Please complete the following tasks

    • [X] I have searched the discussions
    • [X] I have searched the existing issues

    Clap Version

    2.34.0

    Describe your use case

    Tried using a string YAML with clap on the Rust playground, but it does not run due to the yaml feature not being enabled. Here is an example code:

    use clap;
    use yaml_rust; // Needs the `yaml` feature
    
    fn yaml_literal() -> &'static str {
        return r#"
        args: 
        - json:
            about: Output in the JSON format for machine readability and scripting purposes.
            long: json
            global: true
        - plain:
            about: Output plain text of the output without extra information, for machine readability and scripting purposes.
            long: plain
            global: true
        - debug:
            about: Output debug messages.
            long: debug
            global: true
        "#;
    }
    
    fn main() {
        let yaml = yaml_rust::YamlLoader::load_from_str(yaml_literal())
            .unwrap()
            .get(0)
            .unwrap();
        let app = clap::App::from_yaml(yaml);
        println!("{}", app.render_usage());
    }
    

    Describe the solution you'd like

    Please add a list of features (including 'yaml') under [package.metadata.playground] section in your Cargo.toml file. Because it is currently not present, only the default features are enabled on the rust playground. That severely limits the use of clap, because there is no other way to enable crate features on the Rust Playground.

    Alternatives, if applicable

    None.

    Additional Context

    No response

    T: new feature 
    opened by epage 0
  • requires_ifs does not appear to work

    requires_ifs does not appear to work

    Issue by FrankC01 Saturday Dec 04, 2021 at 11:16 GMT Originally opened as https://github.com/clap-rs/clap/issues/3059


    Please complete the following tasks

    • [X] I have searched the discussions
    • [X] I have searched the existing issues

    Rust Version

    rustc 1.55.0 (c8dfcfe04 2021-09-06)

    Clap Version

    clap = "2.33.3"

    Minimal reproducible code

        #[test]
        fn test_output() {
            let res = App::new("prog")
                .arg(
                    Arg::with_name("output")
                        .long("output")
                        .short("o")
                        .takes_value(true)
                        .possible_values(&["csv", "excel", "stdout"])
                        .default_value("stdout")
                        .help("Direct output to file"),
                )
                .arg(
                    Arg::with_name("filename")
                        .long("filename")
                        .short("f")
                        .takes_value(true)
                        // .requires_if("excel", "output") 
                        // .requires_ifs(&[("output", "excel"), ("output", "csv")])
                        .requires_ifs(&[("excel", "output"), ("csv", "output")])
                        .help("Filename for '-o excel' or '-o csv' output"),
                )
                .get_matches_from_safe(vec!["prog", "-o", "excel"]);
            println!("{:?}", res);
            // assert!(res.is_err()); // We  used -o excel so -f <filename> is required
            // assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
        }
    

    Steps to reproduce the bug with the above code

    cargo test

    Actual Behaviour

    No error occurred

    Expected Behaviour

    Expected error as the -f <val> is required if -o excel or -o csv is present

    Additional Context

    No response

    Debug Output

    No response

    T: bug 
    opened by epage 5
  • Parse arguments before or after subcommands ambivalently

    Parse arguments before or after subcommands ambivalently

    Issue by 9999years Thursday Dec 02, 2021 at 21:14 GMT Originally opened as https://github.com/clap-rs/clap/issues/3056


    Please complete the following tasks

    • [X] I have searched the discussions
    • [X] I have searched the existing issues

    Clap Version

    2.34, but I don't think this is a feature in 3.0 either.

    Describe your use case

    I'd like to be able to pass args at any position before or after subcommands. This is a quality-of-live improvement for users of command-line tools.

    Consider the following App:

    use clap::{App, Arg, Subcommand};
    App::new("prog")
        .arg(Arg::with_name("a").short("a"))
        .subcommand(SubCommand::with_name("cmd").arg(Arg::with_name("b").short("b")))
    

    prog -a cmd -b will parse, but prog -a -b cmd and prog cmd -a -b will not. In my opinion, this makes the command-line interface more cumbersome:

    • In the shell, it's harder to work on a previous command by hitting ^P and adding options to the end -- you have to know what level the option can be set at and insert it at the correct place in the command line
    • Requiring arguments at a certain position doesn't enable a compelling use-case -- I don't like the idea of a CLI where prog -a cmd and prog cmd -a mean different things

    Describe the solution you'd like

    Adding a clap::AppSettings variant seems like the natural way to alter parsing behavior:

    App::new("prog")
        .setting(AppSettings::ArgsBeforeOrAfterSubcommands)
        // ...
    

    Alternatives, if applicable

    A more granular API could use an ArgSettings instead:

    App::new("prog")
        .arg(Arg::with_name("a").short("a").set(ArgSettings::BeforeOrAfterSubcommands))
    

    Additional Context

    I'm not familiar with clap's implementation, and it occurs to me that the parser might be structured such that it would be difficult or resource-intensive to alter the parser to recognize subcommand args before the subcommand token itself.

    The parser would have to know about and check all the subcommand-args before parsing, or otherwise determine which subcommand is going to be used -- which I think may be tricky, because determining if bar is a subcommand in prog --foo bar would require knowing if --foo takes a value or not.

    This change would also make certain patterns that are currently allowed ambiguous, such as having a top-level argument and a subcommand argument with the same name (and impossible to parse if, for example, one takes a value and the other doesn't).

    My immediate questions about this feature request are:

    • Would it be possible to add this to clap?
    • Would this feature be allowed in clap, in light of the above complications?
    • Should I work on a PR to implement this functionality?
    T: new feature 
    opened by epage 1
  • ArgMatches method to get the alias used (and long or short version)

    ArgMatches method to get the alias used (and long or short version)

    Issue by MarcelRobitaille Wednesday Nov 24, 2021 at 18:25 GMT Originally opened as https://github.com/clap-rs/clap/issues/3048


    Please complete the following tasks

    • [X] I have searched the discussions
    • [X] I have searched the existing issues

    Clap Version

    2.33.3

    Describe your use case

    I am trying to determine which variant of an option was used. For example, did the user type --number or just -n.

    Describe the solution you'd like

    I think ArgMatches should have a method similar to value_of that would return this.

    let matches = App::new("cli")
        .arg(
            Arg::with_name("number")
                .short("n")
                .long("number")
                .alias("limit")
                .takes_value(true),
        )
        .get_matches_from(vec!["cli", "--limit", "10"]);
    
    assert_eq!(matches.variant_of("number").unwrap(), "--limit");
    
    

    Alternatives, if applicable

    Here is my workaround.

    use std::env;
    
    let matches = App::new("cli")
        .arg(
            Arg::with_name("number")
                .short("n")
                .long("number")
                .alias("limit")
                .takes_value(true),
        )
        .get_matches();
    
    assert_eq!(
        env::args()
            .nth(matches.index_of("number").unwrap() - 1)
            .unwrap(),
        "--limit"
    );
    

    Additional Context

    I am trying to print more helpful error messages. For example, instead of Failed to parse argument "number" I could print Failed to parse argument "--limit".

    T: new feature 
    opened by epage 0
  • Infer trait bounds for generic derives

    Infer trait bounds for generic derives

    Issue by epage Tuesday Nov 16, 2021 at 15:07 GMT Originally opened as https://github.com/clap-rs/clap/issues/3032


    Building off of #2769 / #3023, we should allow inferring trait bounds.

    So instead of

    #[derive(Parser)]
    struct Opt<T: Args> {
        #[clap(flatten)]
        inner: T,
    }
    

    The user does

    #[derive(Parser)]
    struct Opt<T> {
        #[clap(flatten)]
        inner: T,
    }
    

    like they do with when deriving Copy, Clone, serde types, etc.

    See https://serde.rs/attr-bound.html for some inspiration on issues to deal with.

    T: enhancement C: derive macros 
    opened by epage 0
Owner
Ed Page
Ed Page
Docopt for Rust (command line argument parser).

THIS CRATE IS UNMAINTAINED This crate is unlikely to see significant future evolution. The primary reason to choose this crate for a new project is if

null 743 Jan 1, 2023
A simple, lightweight and extensible command line argument parser for rust codebases

A simple, lightweight and extensible command line argument parser for rust codebases. This crate aims to provide you with an easy-to-use and extensibl

Victor Ndaba 20 Nov 12, 2022
A minimal argument parser

Pieces An argument parser built with control in mind. Parsing The results you get are dependent on what order you parse in. If you want to say only pa

ibx34 3 Sep 30, 2021
argmax is a library that allows Rust applications to avoid Argument list too long errors (E2BIG) by providing a std::process::Command wrapper with a

argmax argmax is a library that allows Rust applications to avoid Argument list too long errors (E2BIG) by providing a std::process::Command wrapper w

David Peter 22 Nov 20, 2022
Rust derive-based argument parsing optimized for code size

Argh Argh is an opinionated Derive-based argument parser optimized for code size Derive-based argument parsing optimized for code size and conformance

Google 1.3k Dec 28, 2022
Argument parsing for the future 🚀

argi Argument parsing for the future ?? Features Macro-based approach, providing an intuitive way to layout a cli Rich auto-help generation, styling b

Owez 132 Oct 23, 2022
Small command-line tool to switch monitor inputs from command line

swmon Small command-line tool to switch monitor inputs from command line Installation git clone https://github.com/cr1901/swmon cargo install --path .

William D. Jones 5 Aug 20, 2022
Calc: A fully-featured minimalistic configurable calculator written in Rust

Calc Calc: A fully-featured minimalistic configurable rust calculator Install You can install the latest version from source git clone https://github.

Charlotte Thomas 4 Nov 15, 2023
Simple command line flag parser for rust.

easy_flag Simple command line flag parser for rust. use easy_flag::FlagSet; fn main() -> Result<(), String>{ let mut help = false; let mut my

BillyfBrain 3 Oct 20, 2021
A customizable MCTS planner with advanced featured tailored to multi-agent simulations and emergent narratives.

NPC engine Core:  Utils:  © 2020-2022 ETH Zurich and other contributors. See AUTHORS.txt for more details. A customizable Monte Carlo Tree Search (MCT

Game Technology Center, ETH Zurich 30 Jun 6, 2023
xcp is a (partial) clone of the Unix cp command. It is not intended as a full replacement

xcp is a (partial) clone of the Unix cp command. It is not intended as a full replacement, but as a companion utility with some more user-friendly feedback and some optimisations that make sense under certain tasks (see below).

Steve Smith 310 Jan 5, 2023
A language parser tool to build recursive descent top down parser.

lang-pt A language parser tool to generate recursive descent top down parser. Overview Parsers written for the languages like Javascript are often cus

Creative Forest 7 Jan 4, 2023
Command-line HTTP client for sending a POST request to specified URI on each stdin line.

line2httppost Simple tool to read lines from stdin and post each line as separate POST request to a specified URL (TCP connection is reused though). G

Vitaly Shukela 3 Jan 3, 2023
Pink is a command-line tool inspired by the Unix man command.

Pink is a command-line tool inspired by the Unix man command. It displays custom-formatted text pages in the terminal using a subset of HTML-like tags.

null 3 Nov 2, 2023
⚡️ Lightning-fast and minimal calendar command line. Written in Rust 🦀

⚡️ Lightning-fast and minimal calendar command line. It's similar to cal. Written in Rust ??

Arthur Henrique 36 Jan 1, 2023
Xsv - A fast CSV command line toolkit written in Rust.

xsv is a command line program for indexing, slicing, analyzing, splitting and joining CSV files. Commands should be simple, fast and composable: Simpl

Andrew Gallant 9.1k Dec 31, 2022
A blazing fast command line license generator for your open source projects written in Rust🚀

Overview This is a blazing fast ⚡ , command line license generator for your open source projects written in Rust. I know that GitHub

Shoubhit Dash 43 Dec 30, 2022
A blazingly fast command-line tool for converting Chinese punctuations to English punctuations

A blazingly fast command-line tool for converting Chinese punctuations to English punctuations

Hogan Lee 9 Dec 23, 2022